Question

I have a solution that inserts strings into an XHTML document and prints the results as Reports. My employer has asked if we could pull images off their SQL database (stored as byte arrays) to insert into the Reports.

I am using FlyingSaucer as the XHTML interpreter and I've been using Java DOM to modify pre-stored reports that I have stored in the Report Generator's package.

The only solution I can think of at the moment is to construct the images, save them as a file, link the file in an img tag (or background-image) in a constructed report, print the report and then delete the file. This seems really sloppy and I imagine it will be very time consuming.

I can't help but feel there must be a more elegant solution. Any suggestions for inserting a byte array into html?

Was it helpful?

Solution

  1. Read the image and convert it into it's Base64-encoded form:

    InputStream image = getClass().getClassLoader().getResourceAsStream("image.png");
    String encodedImage = BaseEncoding.base64().encode(ByteStreams.toByteArray(image));
    

    I've used BaseEncoding and ByteStreams from Google Guava.

  2. Change src attribute of img element within your Document object.

    Document doc = ...; // get Document from XHTMLPanel.getDocument() or create
                        // new one using DocumentBuilderFactory 
    
    doc.getElementById("myImage").getAttributes().getNamedItem("src").setNodeValue("data:image/png;base64," + encodedImage);
    
  3. Unfortunatley FlyingSaucer does not support DataURIs out-of-the-box so you'll have to create your own ReplacedElementFactory. Read Using Data URLs for embedding images in Flying Saucer generated PDFs article - it contains a complete solution.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top