Java HTML呈现引擎

bas*_*mes 7 html java graphics rendering image

我有一个小的HTML模板,我必须使用它创建一个图像.HTML由文本和格式组成.生成的图像由其他服务使用.它类似于零售商店的产品价格显示.

是否有可以渲染HTML到图像文件或字节数组的Java库?我看过眼镜蛇,但看起来很旧.

编辑:设置基本的HTML到JLabel和使用BufferedImage应该工作,但我不确定CSS和样式的东西是否会得到妥善处理.

样品风格

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

小智 5

您好,我使用HTML2Image来实现此目的。

这很简单:

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");
Run Code Online (Sandbox Code Playgroud)


joh*_*902 5

我的解决方案包括3个步骤

  1. 创建BufferedImage并创建它Graphics
  2. 创建JEditorPane并调用print(Graphics)
  3. 输出BufferedImage通道ImageIO

码:

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();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

结果:

结果