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>
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");
My solution involves 3 steps:
BufferedImage
and create the its Graphics
JEditorPane
and invoke print(Graphics)
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:
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With