Java HTML rendering engine

I have a small HTML template in which I have to create an image. HTML consists of text and formatting. The generated image is used by other services. This is similar to displaying product prices in retail stores.

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

EDIT: Installing basic HTML in JLabel and using BufferedImage should work, but I'm not sure if the CSS and style will be handled properly.

Sample Style

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

+4
source share
4 answers

Hello, I am using HTML2Image for this purpose.

It is pretty 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"); 
+2
source

My solution includes 3 steps:

  • Create a BufferedImage and Create it Graphics
  • Create a JEditorPane and call print(Graphics)
  • Output 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

+4
source

Perhaps you can use WebVector . It is based on the CSSBox rendering engine , which actually does all the work. Using this library is pretty easy to create a bitmap from a web page. Or you can take a look at a similar topic here at StackOverflow.

0
source

Try the flying saucer (aka xhtml renderer). It supports many CSS 3 features and can display images and PDFs. Its image rendering is experimental, although there are no such things as setting DPI (assumes 1 point == 1 pixel).

0
source

Source: https://habr.com/ru/post/1485766/


All Articles