Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java HTML Rendering Engine

I have a small HTML template using which i have to create an image. The HTML consists of text and formatting. The generated image is used by other services. It is similar to product price display in retail shops.

Is there a Java library that can render HTML to an image file or byte array ? I saw Cobra but it seems old.

EDIT: Setting basic HTML to JLabel and using BufferedImage should work, but i'm not sure if the CSS and Style stuff will get properly handled.

Sample Style

<styles> width: "240", height: "96", background: { type: "solid", color: "#ffffff" } </styles>

like image 929
basiljames Avatar asked Jun 12 '13 09:06

basiljames


3 Answers

Hello I use HTML2Image for this purpose.

It's quite simple:

HtmlImageGenerator imageGenerator = new HtmlImageGenerator();
imageGenerator.loadHtml("<b>Hello World!</b> Please goto <a title=\"Goto Google\" href=\"http://www.google.com\">Google</a>.");
imageGenerator.saveAsImage("hello-world.png");
imageGenerator.saveAsHtmlWithMap("hello-world.html", "hello-world.png");
like image 199
Ricardo Simmus Avatar answered Oct 15 '22 17:10

Ricardo Simmus


My solution involves 3 steps:

  1. Create a BufferedImage and create the its Graphics
  2. Create an JEditorPane and invoke print(Graphics)
  3. Output the BufferedImage via ImageIO

Code:

import java.awt.Graphics;
import java.awt.GraphicsEnvironment;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.swing.JEditorPane;

public class Test {

    public static void main(String[] args) {
        String html = "<h1>Hello, world.</h1>Etc. Etc.";
        int width = 200, height = 100;
        // Create a `BufferedImage` and create the its `Graphics`
        BufferedImage image = GraphicsEnvironment.getLocalGraphicsEnvironment()
                .getDefaultScreenDevice().getDefaultConfiguration()
                .createCompatibleImage(width, height);
        Graphics graphics = image.createGraphics();
        // Create an `JEditorPane` and invoke `print(Graphics)`
        JEditorPane jep = new JEditorPane("text/html", html);
        jep.setSize(width, height);
        jep.print(graphics);
        // Output the `BufferedImage` via `ImageIO`
        try {
            ImageIO.write(image, "png", new File("Image.png"));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Result:

result

like image 45
johnchen902 Avatar answered Oct 15 '22 16:10

johnchen902


Try flying saucer (a.k.a. xhtml renderer). It it supports many CSS 3 features and can render to images and PDF. Its image rendering is experimental though and missing things such as DPI setting (assumes 1 point == 1 pixel).

like image 45
rustyx Avatar answered Oct 15 '22 16:10

rustyx