Styling HTML to PDF with iText 2.1.7
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
A code to style the table generated is:
StyleSheet css = new StyleSheet();
css.loadTagStyle(HtmlTags.ROW, HtmlTags.BORDERCOLOR, "red");
css.loadTagStyle(HtmlTags.ROW, HtmlTags.BORDERWIDTH, "1");
css.loadTagStyle(HtmlTags.CELL, "style", "border: 1px solid #0000ff");
css.loadTagStyle(HtmlTags.CELL, HtmlTags.BACKGROUNDCOLOR, "#f0f0f0");
css.loadTagStyle(HtmlTags.CELL, "color", "#00ccff");
css.loadTagStyle(HtmlTags.BODY, "size", "12pt");
css.loadTagStyle(HtmlTags.BODY, "face", "Times");
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
A little experiment: If you find this post and ad below useful, please check the ad out :-)