gpt4 book ai didi

java - 如何将网站的 HTML 转换为图像?

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:27:17 25 4
gpt4 key购买 nike

有人知道怎么做吗?我试过使用 JEditorPane 但它不起作用?还有其他想法吗?

提前致谢。

这是我正在使用的代码:

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 过滤器调用它并用呈现结果覆盖响应。

编辑 WebRenderer 的开源替代品是 Cobra

关于java - 如何将网站的 HTML 转换为图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3960881/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com