Java

How to configure Flying Saucer and OpenPDF to load CSS from java resources classpath?

This post is a follow-up of the previous one about How to convert HTML to PDF in Java ?

The latter is about how to use Flying Saucer and OpenPDF libraries to convert Html content to PDF. The sample in there was simply using resources by providing system path to necessary files. In the real world you can’t go like this. Resources like CSS should be located in the java resources classpath. Then we need to tell OpenPDF renderer how to resolve them. I’m going to enhance a bit the sample from previous post and add a little extension class which does the job.

All we need to do is to tell OpenPDF to look for resources not in the file system, but in java resources classpath. For this purpose we’ll extend ITextUserAgent class and override resolveAndOpenStream method by pointing resource lookup into the classpath. Here is the class:

import org.xhtmlrenderer.pdf.ITextOutputDevice;
import org.xhtmlrenderer.pdf.ITextUserAgent;

import java.io.InputStream;

public class CustomOpenPdfUserAgent extends ITextUserAgent {

    public CustomOpenPdfUserAgent(ITextOutputDevice outputDevice) {
        super(outputDevice);
    }

    @Override
    protected InputStream resolveAndOpenStream(String uri) {
        InputStream is = getClass()
                .getClassLoader().getResourceAsStream(uri);
        return is;
    }
}

Then we need to set this custom behavior to the PDF renderer. We’ll do it like this:

ITextRenderer renderer = new ITextRenderer();
renderer.getSharedContext()
        .setUserAgentCallback(new CustomOpenPdfUserAgent(renderer.getOutputDevice()));

After doing all this, further you need to point your CSS or other resources relatively to the resources classpath. For example if your CSS is located straight under resources folder, you’ll just point it in Html like href=”yourStyles.css”. Example Html:

<!DOCTYPE html>
<html lang="en" xml:lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>Flying saucer</title>
   <link href="source.css" rel="stylesheet" type="text/css"/>
</head>
<body>
<h1 class="textStyle">Hi!<br/>This is PDF rendered by Flying saucer and OpenPDF.</h1>
</body>
</html>

Sample maven project with all stuff mentioned in this post can be downloaded here.

About Danas Tarnauskas

2 thoughts on “How to configure Flying Saucer and OpenPDF to load CSS from java resources classpath?

Comments are closed.