【问题标题】:Java HTML Rendering EngineJava HTML 渲染引擎
【发布时间】:2013-06-08 08:09:46
【问题描述】:

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

是否有可以将HTML 呈现为图像文件或字节数组的Java 库?我看到了Cobra,但它看起来很旧。

编辑: 将基本 HTML 设置为 JLabel 并使用 BufferedImage 应该可以,但我不确定 CSS 和 Style 的东西是否会得到正确处理。

示例样式

宽度:“240”,高度:“96”,背景:{类型:“solid”,颜色:“#ffffff”}

【问题讨论】:

  • 会解析 HTML 以找到适合您需要的图像吗?
  • @david99world 我必须创建一个类似于 html 在浏览器中呈现的样子的图像。 HTML 中没有图像。
  • “HTML 由文本和格式组成。” 举个例子。我最初希望简化(如果需要)HTML,并将其呈现为JLabelJEditorPane。顺便说一句 - “CSS 和样式的东西” 除非你的意思与我对“样式的东西”的理解完全不同,否则两者是一回事。
  • @AndrewThompson 添加了示例样式。
  • <styles> 我听说过的任何 HTML 规范中都不存在该元素。你是复制/粘贴它还是你只是随手编造?但我不只想要样式,显示一个完整的(valid)HTML,因为它可能会提供给渲染。

标签: java html image graphics rendering


【解决方案1】:

您好,我为此使用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");

【讨论】:

  • 让我看看这个。谢谢。
  • 谢谢。这个符合我的目的。它与 HTML 3.2 兼容,因此必须对我的模板进行一些修改。
  • 链接已失效。
【解决方案2】:

我的解决方案包括 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();
        }
    }
}

结果:

【讨论】:

  • +1 下面提到的工具基于 JEditorPane,但做了几行额外的编码,以确保在打印完成之前页面加载完成。
【解决方案3】:

试试flying saucer(又名xhtml 渲染器)。它支持许多 CSS 3 功能,可以渲染为图像和 PDF。它的图像渲染虽然是实验性的,但缺少诸如 DPI 设置之类的东西(假设 1 点 == 1 像素)。

【讨论】:

    【解决方案4】:

    您或许可以使用WebVector。它基于实际完成所有工作的CSSBox rendering engine。使用这个库从网页生成位图图像非常容易。或者您可以在 StackOverflow 上查看similar topic

    【讨论】:

      猜你喜欢
      • 2011-02-04
      • 2011-04-18
      • 2010-09-18
      • 2011-05-05
      • 1970-01-01
      • 1970-01-01
      • 2014-05-03
      • 2019-04-27
      • 1970-01-01
      相关资源
      最近更新 更多