Search code examples
javarenderingflying-saucer

How to create a Java2DRenderer from a XHTML String?


I am using Flying Saucer to create images from XHTML strings. After reading a couple of examples, I found I can do this using a class called Java2DRenderer. It has constructors that accept Files, URIs, and DOM documents. Therefore, I decided to use DOM documents because they can be created from String. By other hand, all constructors that accept such type require two other parameters: width and height.

For example:

    // Creates DOM document from String
    Document doc = DocumentBuilderFactory.newInstance()
        .parse(new ByteArrayInputStream(xhtmlString.getBytes()));

    //See constructor parameters: DOM document, width and height
    Java2DRenderer imageRenderer = new Java2DRenderer(doc, 
        1024, 768);

    imageRenderer.setBufferedImageType(BufferedImage.TYPE_INT_RGB);

    BufferedImage image = imageRenderer.getImage();

Unfortunately, sometimes a xhtmlString is too big and the XHTML content does not fit in an image 768 height. When this happens, a truncated image is generated. I have no way to predict it, and hardcoding a higher value will make most image (the small ones) to inflate.

As one of the Java2DRenderer's constructor accepts a java.io.File and just ask us to provide width (height is determined by the API), I think I have to options:

  1. Save XHTML strings to files
  2. Create in memory Files from XHTML strings

Neither seems to be good options. The first one is going do add extra IO overhead, but the second would be acceptable (if possible). I thought I could create in memory files using an Apache VFS FileObject (it supports RAM file systems), but it seems not to be compatible with the Java IO File class. I cannot pass org.apache.commons.vfs2.FileObject to a constructor that accepts a java.io.File.

What other options could you suggest me to solve my problem?


Solution

  • Loking at the source code of Java2DRenderer, the constructor public Java2DRenderer(File file, int width) initialises the height to -1.

    So you should call:

    Java2DRenderer imageRenderer = new Java2DRenderer(doc, 1024, -1);