Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Render embedded image in PDF using Flying-Saucer from html

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

like image 489
It Grunt Avatar asked May 31 '12 20:05

It Grunt


2 Answers

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

like image 114
Malcolm Smith Avatar answered Sep 28 '22 16:09

Malcolm Smith


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.

like image 20
Kukeltje Avatar answered Sep 28 '22 16:09

Kukeltje