###偶然有一个HTML转换为图片的需求,因此在网上搜遍了找到以下实现方式。
#1. html2image
<!-- lang: java -->
String htmlTxt = "<h1>开源中国社区</h1><h3>Header 3</h3><blockquote><p>This is a blockquote.</p><p>This is the second paragraph in the blockquote.</p><h2>This is an H2 in a blockquote</h2></blockquote>";
HtmlImageGenerator imageGenerator = new HtmlImageGenerator();
imageGenerator.loadHtml(htmlTxt);
imageGenerator.saveAsImage("html.png");
#2. Cobra
<!-- lang: java -->
JFrame window = new JFrame();
HtmlPanel panel = new HtmlPanel();
window.getContentPane().add(panel);
window.setSize(600, 400);
window.setVisible(true);
new SimpleHtmlRendererContext(panel, new SimpleUserAgentContext()).navigate("http://www.hefeipet.com/client/chongwuzhishi/shenghuozatan/2012/0220/95.html");
BufferedImage image = new BufferedImage(panel.getWidth(),
panel.getHeight(), BufferedImage.TYPE_INT_ARGB);
SwingUtilities.paintComponent(image.createGraphics(), panel, new JPanel(), 0, 0, image.getWidth(), image.getHeight());
ImageIO.write((RenderedImage) image, "png", new File("html.png"));