Render embedded image in PDF using Flying-Saucer from html

15.9k views Asked by At

I have an xhtml document that I'm turning into a PDF using flyingsaucer. The xhtml has several tags that have a base64 encoded images inline. The source of the xhtml is dynamic so the structure of where the image tags are can vary. This is a sample of what the tag looks like:

<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAagAAAEuCAYAAADbW4YFAAAgAElEQVR4Aex9CYBdRZ ...

When I look at the html in a browser, the image appears correctly, however, the img element doesn't get rendered in the final PDF. Here is how I'm rendering it out to create the PDF.

ITextRenderer renderer = new ITextRenderer();
renderer.setDocument(builder.parse(source), "");
renderer.layout();
renderer.createPDF(response.getOutputStream(),true);

Can anyone let me know what approach I should take to accomplish this? I saw this posting, however, I'm using inline images so I can't see how I can accomplish this using Edd's solution.

Thanks in advance

2

There are 2 answers

0
Malcolm Smith On BEST ANSWER

Yes, you can use the approach given here: Render image from servlet in flyingsaucer generated pdf

Where Edd has:

        InputStream input = null;
        try {
            input = ...;
            byte[] bytes = IOUtils.toByteArray(input);
            Image image = Image.getInstance(bytes);

In Edd's case the image is coming from a remote source (he skips over that bit with input = ...;). In your case you just want to read it from your Base64 encoded data (the text after the base64,. First use a Base64 decoder to get the binary data, into a byte[] or Stream, you can then use Java ImageIO to create the image from your bytes and follow Edd's approach to get the image into the PDF. Kudos to Edd here (upvote for sure!).

1
Kukeltje On

Flying-Saucer supports the data: protocol natively. All you have to do is register a protocol handler:

-Djava.protocol.handler.pkgs=org.xhtmlrenderer.protocols

No need for servlets whatsoverver.