Search code examples
javaxhtmlpdf-generationflying-saucer

Relative paths in Flying Saucer XHTML?


I am using Flying Saucer to render some PDF documents from strings to XHTML. My code is something like:

iTextRenderer.setDocument(documentGenerator.generate(xhtmlDocumentAsString));
iTextRenderer.layout();
iTextRenderer.createPDF(outputStream);

What I'm trying to understand is, when using this method, where are relative paths in the XHTML resolved from? For example, for images or stylesheets. I am able to use this method to successfully generate a text-based document, but I need to understand how to reference my images and CSS.


Solution

  • The setDocument() method takes two parameters: document and url. The url parameter indicates the base url used to prepend to relative paths that appear in the xhtml, such as in img tags.

    Suppose you have:

    <img src="images/img1.jpg">
    

    Now suppose the folder "images" is located at:

    C:/physical/route/to/app/images/
    

    You may use setDocument() as:

    renderer.setDocument(xhtmlDoc, "file:///C:/physical/route/to/app/");
    

    Notice the trailing slash, it won't work without it.

    This is the way it worked for me. I assume you could use other types of urls such as "http://...".