iText pdf library
Website search

How to add external CSS while generating PDF?

Currently i am using following code to generate PDF in a JSP file:


response.setHeader("Content-Disposition", "attachment;filename=reports.pdf");
Document document = new Document();
PdfWriter writer = null;
writer = PdfWriter.getInstance(document, response.getOutputStream());;
ByteArrayInputStream bis
    = new ByteArrayInputStream(htmlSource.toString().getBytes());
XMLWorkerHelper.getInstance().parseXHtml(writer, document, bis);
With this code, I'm able to generate PDF, but I would like to add a CSS file while generating PDF.

Posted on StackOverflow on Jul 16, 2014 by Yella Goud

Please take a look at the ParseHtmlTable1 example. In this example, we have HTML stored in a StringBuilder object and some CSS stored in a String. In my example, I convert the sb object and the CSS object to an InputStream. If you have files with the HTML and the CSS, you could easily use a FileInputStream.

Once you have an InputStream for the HTML and the CSS, you can use this code:

// CSS
CSSResolver cssResolver = new StyleAttrCSSResolver();
CssFile cssFile = XMLWorkerHelper.getCSS(new ByteArrayInputStream(CSS.getBytes()));
HtmlPipelineContext htmlContext = new HtmlPipelineContext(null);
// Pipelines
PdfWriterPipeline pdf = new PdfWriterPipeline(document, writer);
HtmlPipeline html = new HtmlPipeline(htmlContext, pdf);
CssResolverPipeline css = new CssResolverPipeline(cssResolver, html);
// XML Worker
XMLWorker worker = new XMLWorker(css, true);
XMLParser p = new XMLParser(worker);
p.parse(new ByteArrayInputStream(sb.toString().getBytes()));

Or, if you don't like all that code:

ByteArrayInputStream bis =
    new ByteArrayInputStream(htmlSource.toString().getBytes());
ByteArrayInputStream cis =
    new ByteArrayInputStream(cssSource.toString().getBytes());
XMLWorkerHelper.getInstance().parseXHtml(writer, document, bis, cis);

Ready to use iText?

Try our iText 7 Library and add-ons FREE for 30 days. Test your proof of concept, and see if our solution is right for you.

Get my FREE trial

Still have questions? 

We're happy to answer your questions. Reach out to us and we'll get back to you shortly.

Contact us
Stay updated

Join 11,000+ subscribers and become an iText PDF expert by staying up to date with our new products, updates, tips, technical solutions and happenings.

Subscribe Now