对比了网上常用的好几种网页转图片的开源插件,最后效果还不如使用原生的java直接写来得好,上代码,很简单,中间需要考虑网页加载延迟的问题,所以需要加上thread.sleep,休眠一下等待网页加载完成了,再对html进行图片话,不然的话可能网页没加载出来,就已经被转成图片了,那就会出现白板或者部分不显示的问题,仅做记录,上代码
import javax.imageio.ImageIO;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import java.awt.image.BufferedImage;
import java.awt.image.RenderedImage;
import java.io.File;
import java.net.URL;
/**
* @Author 90
*/
public class HtmlToImage {
/**
* HTML链接转为图片
* @param htmlUrl 网页链接
* @param imagePath 生成的图片路径
* @param width 图片宽度
* @param height 图片高度
* @throws Exception
*/
public static void conversion(String htmlUrl, String imagePath, int width, int height) throws Exception {
JEditorPane ed = new JEditorPane(new URL(htmlUrl));
Thread.sleep(10000);
EmptyBorder eb = new EmptyBorder(0, 30, 0, 30);
ed.setBorder(eb);
ed.setSize(width, height);
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_BYTE_GRAY);
SwingUtilities.paintComponent(image.createGraphics(), ed, new JPanel(), 0, 0, width, height);
ImageIO.write((RenderedImage) image, "png", new File(imagePath));
}
public final static void main(String[] args) throws Exception {
HtmlToImage.conversion("http://www.google.com", "google.png", 1500, 5000);
}
}