對比了網上常用的好幾種網頁轉圖片的開源插件,最后效果還不如使用原生的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);
}
}