2011년 3월 10일 목요일

Html page to image file

import java.awt.Color;
import java.awt.Container;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Insets;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.net.URL;

import javax.imageio.ImageIO;
import javax.swing.JEditorPane;
import javax.swing.SwingUtilities;
import javax.swing.text.Document;
import javax.swing.text.html.HTMLDocument;
import javax.swing.text.html.HTMLEditorKit;

import com.lowagie.text.FontFactory;
import com.lowagie.text.pdf.BaseFont;

public abstract class WebImage
{
static class Kit extends HTMLEditorKit
{
public Document createDefaultDocument() {
HTMLDocument doc = (HTMLDocument) super.createDefaultDocument();
doc.setTokenThreshold(Integer.MAX_VALUE);
doc.setAsynchronousLoadPriority(-1);

return doc;
}
}

public static BufferedImage create(String src, int width, int height) {

BufferedImage image = null;
JEditorPane pane = new JEditorPane();
Kit kit = new Kit();
pane.setEditorKit(kit);
pane.setEditable(false);
pane.setMargin(new Insets(0,20,0,20));
pane.setContentType("text/html; charset=UTF-8");
//pane.setFont(new Font("serif",Font.BOLD,20));

try {

System.out.println("-------------"+pane.getFont().getFamily());
System.out.println("-------------"+pane.getFont().getFontName());

pane.setPage(new URL(src));

System.out.println("-----------------------");
System.out.println(pane.getText());
System.out.println("-----------------------");

image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics g = image.createGraphics();
Container c = new Container();
SwingUtilities.paintComponent(g, pane, c, 0, 0, width, height);
g.dispose();
} catch (Exception e) {
System.out.println(e);
}

return image;
}

public static void main ( String [] args ) {


// TODO Auto-generated method stub
//Call the Web page and convert to Image
BufferedImage ire;
String url="file:///C:\\temp\\test.html";
String path="c:\\temp\\tmp.jpg";
ire = WebImage.create(url, 800, 800);
//You can convert the BufferedImage to
//any format that you wish, jpg I thought was the best format
try{
ImageIO.write(ire, "PNG", new File(path));
System.out.println("complete");
}catch(IOException e){
e.printStackTrace();
}catch(NullPointerException e){
e.printStackTrace();
}catch(IllegalArgumentException e){
e.printStackTrace();
}
}



}

댓글 없음:

댓글 쓰기