如何将网站的 HTML 转换为图像? [英] How to convert HTML of a website to an image?
本文介绍了如何将网站的 HTML 转换为图像?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有人知道怎么做吗?我试过 JEditorPane 但它不起作用?还有其他想法吗?
Does anyone know how to do this? I've tried with JEditorPane but it does not work? Any other idea?
提前致谢.
这是我正在使用的代码:
This is the code I'm using:
import java.awt.Dimension;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import javax.imageio.ImageIO;
import javax.swing.JEditorPane;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
public class HtmlToImage
{
protected static File generateOutput() throws Exception
{
// Create a temporary output file for the PNG image.
File outputFile = new File("Reporte.png");
outputFile.deleteOnExit();
JEditorPane pane = new JEditorPane();
pane.setContentType("text/html");
pane.setPage("http://www.google.com");
final JFrame frame = new JFrame();
frame.pack();
// Time Delay for the correct loading of the file.
try
{
Thread.sleep(5000);
}
catch(NumberFormatException nfe)
{
}
frame.add(pane);
frame.pack();
Dimension prefSize = pane.getPreferredSize();
pane.setSize(prefSize);
BufferedImage img = new BufferedImage( prefSize.width, prefSize.height,
BufferedImage.TYPE_INT_RGB);
Graphics2D g = (Graphics2D) img.getGraphics();
SwingUtilities.paintComponent(g, pane, frame, 0, 0, prefSize.width, prefSize.height);
ImageIO.write(img, "png", outputFile);
return outputFile;
}
public static void main(String[] args)
{
try
{
generateOutput();
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
推荐答案
您需要渲染 HTML 并将结果输出为图片文件.目前,核心 Java 中没有成熟的 HTML 渲染器,因此您需要一个单独的库或应用程序,以 WebRenderer 为例.只需从 servlet 过滤器调用它并使用呈现结果覆盖响应.
You need to render the HTML and output the result as a picture file. Currently there is no full-fledged HTML renderer in core Java so you'll need a separate library or an application, WebRenderer for example. Simply invoke it from a servlet filter and override the response with rendering results.
编辑 WebRenderer 的开源替代方案是 Cobra
Edit Open source alternative to WebRenderer is Cobra
这篇关于如何将网站的 HTML 转换为图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文