How to Create a PDF from HTML

Several years ago (circa 2013), I cloned the iText project and added the ability to generate PDF documents from a simple HTML document. The PDF library is called freepdf and is available on SourceForge. The library is based on iText 2.1.7, which was the last release of iText prior to the AGPL license switch.

Here's a simple example of how to generate a PDF using an HTML document.

import com.lowagie.text.Document;
import com.lowagie.text.PageSize;
import com.lowagie.text.html.HtmlParser;
import com.lowagie.text.pdf.PdfWriter;

public byte[] toPDF(String html) throws Exception {

    java.io.ByteArrayOutputStream out = new java.io.ByteArrayOutputStream();

    float _2cm = 56.6929134f;
    Document pdf = new Document(PageSize.LETTER, _2cm, _2cm, _2cm, _2cm);

    PdfWriter pdfWriter = PdfWriter.getInstance(pdf, out);
    pdfWriter.setViewerPreferences(PdfWriter.PageModeUseOutlines); //|PdfWriter.PrintScalingNone

    pdf.open();



    HtmlParser parser = new HtmlParser(pdf, true);
    parser.parse(new java.io.StringReader(html));

    pdf.close();
    return out.toByteArray();
}