quarta-feira, 8 de maio de 2013

Converter HTML em PDF com iText


/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package teste.pdf;

import com.lowagie.text.Document;
import com.lowagie.text.DocumentException;
import com.lowagie.text.PageSize;
import com.lowagie.text.html.simpleparser.HTMLWorker;
import com.lowagie.text.pdf.PdfWriter;
import java.io.BufferedReader;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.OutputStream;
import java.io.StringReader;

/**
 *
 * @author smart
 */
public class ConverterHtmlEmPdf {

    public static OutputStream convertHTMLtoPDF(BufferedReader html, OutputStream pdf) throws IOException, DocumentException {
        String htmlContent = "";
        try {
            StringBuilder sb = new StringBuilder();
            String line = html.readLine();
            while (line != null) {
                sb.append(line);
                sb.append("\n");
                line = html.readLine();
            }
            htmlContent = sb.toString();
        } finally {
            html.close();
        }
        Document doc = new Document(PageSize.A4);
        PdfWriter.getInstance(doc, pdf);
        doc.open();
        HTMLWorker hw = new HTMLWorker(doc);
        hw.parse(new StringReader(htmlContent));
        doc.close();
        return pdf;
    }

    public static void main(String[] args) throws IOException, DocumentException {
//        String File_To_Convert = "/tmp/teste2.html";
        String File_To_Convert = "/tmp/modelo3.html";

        BufferedReader br = new BufferedReader(new FileReader(File_To_Convert));

        String HTML_TO_PDF = "/tmp/MODELOTESTE.pdf";
        OutputStream os = new FileOutputStream(HTML_TO_PDF);

        convertHTMLtoPDF(br, os);
    }
}

Nenhum comentário:

Postar um comentário