记录笔记---------------------------------------------
Java html 转 图片
1、通过freemarker 转 html
2、html转图片
freemarker模板:test.flt
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>sdsd</title>
</head>
<body>
<table width="300" border="1" cellspacing="0">
<tr>
<td colspan="3">姓名:${username}</td>
</tr>
<tr>
<td>一班</td>
<td>2012-5-10</td>
<td>标题1</td>
</tr>
</table>
</body>
</html>
代码如下:
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import javafx.embed.swing.JFXPanel;
import javax.imageio.ImageIO;
import javax.swing.*;
import javax.swing.border.Border;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.HashMap;
import java.util.Map;
public class FreeMakerUtils {
public static void main(String[] args) throws IOException {
freeMakerToHtml("C:\\Users\\lili\\Desktop\\IO","test.flt","C:\\Users\\lili\\Desktop\\IO\\ooo.html");
String html = getHtmlContent("C:\\Users\\lili\\Desktop\\IO\\ooo.html");
htmlToImage(html);
}
public static void freeMakerToHtml(String templatePath, String templateName, String outPath){
//1创建freeMarker配置实例
Configuration configuration = new Configuration();
Writer out = null;
try {
//获取模版路径
configuration.setDirectoryForTemplateLoading(new File((templatePath)));
//加载模版文件
Template template = configuration.getTemplate(templateName);
//创建数据模型
Map dataMap = new HashMap();
dataMap.put("username","你哈");
// 生成数据
File docFile = new File(outPath);
out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(docFile)));
//输出文件
template.process(dataMap,out);
System.out.println("freemaker生成html成功!");
} catch (IOException e) {
e.printStackTrace();
} catch (TemplateException e) {
e.printStackTrace();
}
}
/**
* 获取html的内容
* @param filePath
* @return
*/
public static String getHtmlContent(String filePath){
File file = new File(filePath);
String html = "";
try {
FileInputStream in = new FileInputStream(file);
Reader reader = new InputStreamReader(in);
BufferedReader htmlReader = new BufferedReader(reader);
String line;
while ((line = htmlReader.readLine()) != null) {
html = html + line + "\n";
}
htmlReader.close();
reader.close();
in.close();
return html;
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return html;
}
/**
* html转图片
* @param html
* @throws IOException
*/
public static void htmlToImage(String html) throws IOException {
JEditorPane ed = new JEditorPane();
ed.setSize(700,800);
ed.setBackground(Color.white);
ed.setEditable(false);
ed.setContentType("text/html");
ed.setText(html);
BufferedImage image = new BufferedImage(ed.getWidth(), ed.getHeight(),
BufferedImage.TYPE_INT_RGB);
Graphics g = image.getGraphics();
ed.paint(g);
g.dispose();
ImageIO.write(image,"jpg",new File("C:\\Users\\lili\\Desktop\\IO\\ooo.jpg"));
}
}