Styling HTML to PDF with iText 2.1.7

Posted by in Software, Tutorial

There are various solutions for producing PDFs from a HTML file, some with excellent results (e.g. ones based on the chrome renderer). Unfortunately, they usually mean adding more dependencies to an existing system. To keep things in check, we’ve chosen to use iText to generate PDFs.

Following the previous post, we need to enhance the generated PDF with some styles. Now, the older versions of iText can’t use CSS directly, so we’ll need to produce the styles by hand.

iText has a StyleSheet object which can load tag styles via loadTagStyle() and class styles via loadStyle().

A code to style the table generated is:

This will produce an output like (file here):

While it doesn’t look that much better, you can see the stuff that works and the stuff that doesn’t (e.g. the red border at cell level).

Note: As the renderer is not a standard HTML renderer, the styles supported are a subset of the CSS and you’ll need to fiddle with the code to make them behave

HTH,


A little experiment: If you find this post and ad below useful, please check the ad out :-)