Render embedded image in PDF using Flying-Saucer from html
Asked Answered
T

2

11

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

Tapdance answered 31/5, 2012 at 20:40 Comment(1)
There is a feature request to make data-url for images work directly in Flying Saucer: code.google.com/p/flying-saucer/issues/detail?id=202Tuckerbag
L
11

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!).

Lerner answered 31/5, 2012 at 21:26 Comment(0)
W
8

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.

Wuhsien answered 11/7, 2012 at 12:50 Comment(1)
Do you have a link for how protocol handlers are registered?Tapdance

© 2022 - 2024 — McMap. All rights reserved.