1. 程式人生 > >Java 實現HTML 頁面轉成image 圖片

Java 實現HTML 頁面轉成image 圖片

前言

在java 中把HTML轉化成圖檔,思路基本上是現在 AWT or Swing 的Panel上顯示網頁,在把Panel輸出為 image 檔案。

java 本身的API有提供相關的結果,但是直接產生的效果不是很好,所以有出現一些 library.

Java Core API

public class HtmlToImage {

	protected static void generateOutput() throws Exception {
		
		//load the webpage into the editor
		//JEditorPane ed = new JEditorPane(new URL("http://www.google.com"));
		JEditorPane ed = new JEditorPane(new URL("http://www.hefeipet.com/client/chongwuzhishi/shenghuozatan/2012/0220/95.html"));
		ed.setSize(200,200);

		//create a new image
		BufferedImage image = new BufferedImage(ed.getWidth(), ed.getHeight(),
		                                        BufferedImage.TYPE_INT_ARGB);

		//paint the editor onto the image
		SwingUtilities.paintComponent(image.createGraphics(), 
		                              ed, 
		                              new JPanel(), 
		                              0, 0, image.getWidth(), image.getHeight());
		//save the image to file
		ImageIO.write((RenderedImage)image, "png", new File("html.png"));
	}
	public static void main(String[] args) {
		try {
			generateOutput();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}


java-html2image


下載地址:

開源, 使用上很簡潔。API Doc 和source code 都有。

import gui.ava.html.image.generator.HtmlImageGenerator;

public class Html2ImageTest {
	
	public static void main(String[] args) {
		HtmlImageGenerator imageGenerator = new HtmlImageGenerator();
//		imageGenerator
//				.loadHtml("<b>Hello World!</b> Please goto <a title=\"Goto Google\" href=\"http://www.google.com\">Google</a>.");
		//imageGenerator.loadUrl("http://mtkplmap2:7001/esdm_web"); 
		imageGenerator.loadUrl("http://www.hefeipet.com/client/chongwuzhishi/shenghuozatan/2012/0220/95.html"); 
		imageGenerator.saveAsImage("hello-world.png");
		imageGenerator.saveAsHtmlWithMap("hello-world.html", "hello-world.png");
	}

}

Cobra

免費,開源
public class CobraTest {
	public static void main(String[] args) throws Exception {
		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);

		// paint the editor onto the image
		SwingUtilities.paintComponent(image.createGraphics(), panel,
				new JPanel(), 0, 0, image.getWidth(), image.getHeight());
		// save the image to file
		ImageIO.write((RenderedImage) image, "png", new File("html.png"));
	}
}


WebRenderer

收費的。

下載包裡有包含很多例子, 效果類似在swing 中使用browser的功能

總結

不管是哪一種,多於樣式複雜的頁面,

產生的效果都不盡如人意。。。