我有一个小的HTML模板,我必须使用它来创建一个图像。HTML由文本和格式组成。生成的映像被其他服务使用。它类似于零售商店的产品价格展示。
是否有一个可以将HTML呈现给图像文件或字节数组的Java库?我看到眼镜蛇了,但它看起来很老。
编辑:将基本的HTML设置为JLabel并使用BufferedImage应该有效,但我不确定CSS和样式的内容是否会得到正确的处理。
样本样式
宽度:"240",高度:"96",背景:{ type:“固态”,颜色:"#ffffff“}
发布于 2013-06-12 09:17:35
你好,我使用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");发布于 2013-06-12 09:27:28
我的解决方案包括三个步骤:
BufferedImage并创建其GraphicsJEditorPane并调用print(Graphics)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();
}
}
}结果:

发布于 2013-12-09 09:52:59
试试飞碟 (a.k.a.( xhtml渲染器)它支持许多CSS 3功能,并可以渲染到图像和PDF。但是,它的图像呈现是实验性的,缺少诸如DPI设置(假设为1点== 1像素)的东西。
https://stackoverflow.com/questions/17061682
复制相似问题