Java HTML 渲染引擎

8
我有一个小的HTML模板,使用它我必须创建一张图片。HTML包含文本和格式设置。生成的图片被其他服务使用。类似于零售店中的产品价格显示。
是否有一个Java库可以将HTML呈现为图像文件或字节数组?我看到了Cobra,但它似乎已经过时了。
编辑: 将基本的HTML设置为JLabel并使用BufferedImage应该可以工作,但我不确定CSS和样式等内容是否会得到正确处理。
样式示例

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


解析 HTML 查找图片是否符合您的需求? - David
@david99world 我需要创建一张类似于在浏览器中呈现的HTML的图片。HTML中没有图片。 - basiljames
"HTML由文本和格式组成。" 举个例子,我最初会尝试简化HTML,并在JLabelJEditorPane中呈现它。顺便说一句,"CSS和Style stuff"除非你的"Style stuff"意思完全不同于我理解的"样式",否则这两者是相同的。 - Andrew Thompson
@AndrewThompson 添加了一个样式示例。 - basiljames
<styles> 这个元素在我所听说的任何 HTML 规范中都不存在。你是复制/粘贴它还是随意编造的?但我不仅想要样式,还要展示一个完整(有效)的 HTML,以供渲染。 - Andrew Thompson
我刚刚意识到即使超出了styles/style,那也不是有效的CSS。请确保在适当的验证服务中验证 - Andrew Thompson
4个回答

7
我的解决方案包括3个步骤:
  1. 创建一个BufferedImage并创建其Graphics
  2. 创建一个JEditorPane并调用print(Graphics)
  3. 通过ImageIO输出BufferedImage
代码:
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();
        }
    }
}

结果:

结果


下面提到的工具基于JEditorPane,但进行了几行额外的编码以确保页面加载完成后再执行打印操作。 - basiljames

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");

让我看看这个。谢谢。 - basiljames
谢谢。这个符合我的需求。它与HTML 3.2兼容,所以我不得不对我的模板进行一些修改。 - basiljames
链接已失效。 - null

1

尝试使用飞碟(又名xhtml渲染器)。它支持许多CSS 3功能,并可以呈现为图像和PDF。虽然其图像渲染是实验性的,但缺少一些东西,例如DPI设置(假定1点== 1像素)。


0

你可以尝试使用WebVector。它基于CSSBox渲染引擎,实际上完成了所有的工作。使用这个库从网页生成位图图像非常容易。或者你也可以在StackOverflow上看一下类似的话题


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接