Skip to content

HTML to PDF with iText 2.1.7

July 7th, 2017 - SoftwareTutorial(1 min)

Sometimes you need to use an older version of a product die to e.g. licensing changes. It’s my case with iText. While the new version looks fantastic, their changes (and removal of e.g. RTF output) are deal breakers for the feature set we need to maintain. Therefore, 2.1.7 is the most recent version we can use. Heh.

In maven, this would be:

    <dependency>
        <groupId>com.lowagie</groupId>
        <artifactId>itext</artifactId>
        <version>2.1.7</version>
    </dependency>

The string resulted from the previous article can be printed out fairly easily.

First, we create a document and a writer:

// THE PDF
// Doc's begin
final Document document = new Document();
File file = new File("/some/path/out.pdf");
DocWriter docWriter = PdfWriter.getInstance(document, new FileOutputStream(file));

document.open();

We write the document:

HTMLWorker worker = new HTMLWorker(document);
worker.parse(new StringReader(output));

And then we close the document and writer:

document.close();
docWriter.close();

It’s easy and the result is here. You can see it’s very basic!

Note The API can throw a DocumentException which we need to catch.

HTH,

Share on
Reddit
Linked in
Whatsapp

A little experiment: