pom文件如下
<dependencies>
<dependency>
<groupId>com.itextpdf.tool</groupId>
<artifactId>xmlworker</artifactId>
<version>5.5.8</version>
</dependency>
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.28</version>
</dependency>
</dependencies>
java 代码如下
import com.itextpdf.text.Document;
import com.itextpdf.text.pdf.PdfWriter;
import com.itextpdf.tool.xml.XMLWorkerHelper;
import freemarker.cache.StringTemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import java.io.*;
import java.nio.charset.Charset;
public class PDFKit {
private String saveFilePath;
public static final String FILE_PATH ="e:/html/result.html";//文件指定存放的路径
/*
* 把模板读入到String中,然后根据String构造FreeMarker模板
*/
public void createHtmlFromString(Object data) {
BufferedInputStream in = null;
FileWriter out = null;
try {
//模板文件
File file = new File("E:\\html\\hello.ftl");
//构造输入流
in = new BufferedInputStream(new FileInputStream(file));
int len;
byte[] bytes = new byte[1024];
//模板内容
StringBuilder content = new StringBuilder();
while((len = in.read(bytes)) != -1) {
content.append(new String(bytes, 0, len, "utf-8"));
}
//构造Configuration
Configuration configuration = new Configuration();
//构造StringTemplateLoader
StringTemplateLoader loader = new StringTemplateLoader();
//添加String模板
loader.putTemplate("test", content.toString());
//把StringTemplateLoader添加到Configuration中
configuration.setTemplateLoader(loader);
//构造Model
//获取模板
Template template = configuration.getTemplate("test");
//生成html
File dirPath = new File(FILE_PATH);
if(!dirPath.getParentFile().exists()){
dirPath.getParentFile().mkdirs();
}
//构造输出路
out = new FileWriter(FILE_PATH);
//生成HTML
template.process(data, out);
} catch (TemplateException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if(null != in) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(null != out) {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
/**
* @description 导出pdf到文件
* @param fileName 输出PDF文件名
* @param data 模板所需要的数据
*
*/
public String exportToFile(String fileName,Object data){
try {
//根据模板生成html
createHtmlFromString( data);
File file=new File(saveFilePath);
if(!file.getParentFile().exists()){
file.getParentFile().mkdirs();
}
Document document =null;
try{
// step 1
document = new Document();
// step 2
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(file));
// step 3
document.open();
// step 4
XMLWorkerHelper.getInstance().parseXHtml(writer, document,
new FileInputStream(FILE_PATH), Charset.forName("UTF-8")
);
System.out.println("生成完成");
}catch(Exception ex){
ex.printStackTrace();
}finally{
document.close();
}
} catch (Exception e) {
e.printStackTrace();
}
return saveFilePath;
}
public String getSaveFilePath() {
return saveFilePath;
}
public void setSaveFilePath(String saveFilePath) {
this.saveFilePath = saveFilePath;
}
}
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.pdf.PdfWriter;
import com.itextpdf.tool.xml.XMLWorkerHelper;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Created by fgm on 2017/4/17.
* 360报告
*
*/
public class ReportKit360 {
public static final String HTML = "E:index.html";
public static final String DEST = "E:hello.pdf";
/**
* Creates a PDF with the words "Hello World"
* @param file
* @throws IOException
* @throws DocumentException
*/
public static void createPdf(String file) throws IOException, DocumentException {
// step 1
Document document = new Document();
// step 2
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(file));
// step 3
document.open();
// step 4
XMLWorkerHelper.getInstance().parseXHtml(writer, document,
new FileInputStream(HTML), Charset.forName("UTF-8"));
System.out.println("生成完成");
// step 5
document.close();
}
/**
* Creates a PDF with the words "Hello World"
* @param file
* @throws IOException
* @throws DocumentException
*/
public static void createPdf2() throws IOException, DocumentException {
ReportKit360 kit=new ReportKit360();
//数据
TemplateBO templateBO=new TemplateBO();
templateBO.setTemplateName("测试");
templateBO.setFreeMarkerUrl("http://www.zheng-hang.com/chm/freemarker2_3_24/ref_directive_if.html");
templateBO.setITEXTUrl("http://developers.itextpdf.com/examples-itext5");
templateBO.setJFreeChartUrl("http://www.yiibai.com/jfreechart/jfreechart_referenced_apis.html");
templateBO.setImageUrl("E:/31.jpg");
List<String> scores=new ArrayList<String>();
scores.add("94");
scores.add("95");
scores.add("98");
templateBO.setScores(scores);
List<Map<String,String>> userList=new ArrayList<Map<String,String>>();
Map<String,String> userMap1=new HashMap<String,String>();
userMap1.put("username", "张三");
userMap1.put("password", "123456");
userMap1.put("age", "12");
userMap1.put("address", "北京");
userList.add(userMap1);
Map<String,String> userMap2=new HashMap<String,String>();
userMap2.put("username", "张三");
userMap2.put("password", "123456");
userMap2.put("age", "12");
userMap2.put("address", "北京");
userList.add(userMap2);
templateBO.setUserList(userList);
String picUrl="E:/31.jpg";
templateBO.setPicUrl(picUrl);
System.out.println("picUrl:"+picUrl);
String path= kit.createPDF(templateBO,"hello.pdf");
System.out.println("打印:"+path);
}
public String createPDF(Object data, String fileName){
//pdf保存路径
try {
PDFKit kit=new PDFKit();
//设置输出路径
kit.setSaveFilePath("e:/hello.pdf");
String saveFilePath=kit.exportToFile(fileName,data);
return saveFilePath;
} catch (Exception e) {
System.out.println("竟然失败了,艹!");
e.printStackTrace();
return null;
}
}
public static void main(String[] args) throws IOException, DocumentException {
createPdf2();
}
}
import java.util.List;
import java.util.Map;
public class TemplateBO {
private String templateName;
private String freeMarkerUrl;
private String ITEXTUrl;
private String JFreeChartUrl;
private List<String> scores;
private List<Map<String,String>> userList;
public List<Map<String, String>> getUserList() {
return userList;
}
public void setUserList(List<Map<String, String>> userList) {
this.userList = userList;
}
private String imageUrl;
private String picUrl;
public String getTemplateName() {
return templateName;
}
public void setTemplateName(String templateName) {
this.templateName = templateName;
}
public String getFreeMarkerUrl() {
return freeMarkerUrl;
}
public void setFreeMarkerUrl(String freeMarkerUrl) {
this.freeMarkerUrl = freeMarkerUrl;
}
public String getITEXTUrl() {
return ITEXTUrl;
}
public void setITEXTUrl(String iTEXTUrl) {
ITEXTUrl = iTEXTUrl;
}
public String getJFreeChartUrl() {
return JFreeChartUrl;
}
public void setJFreeChartUrl(String jFreeChartUrl) {
JFreeChartUrl = jFreeChartUrl;
}
public List<String> getScores() {
return scores;
}
public void setScores(List<String> scores) {
this.scores = scores;
}
public String getImageUrl() {
return imageUrl;
}
public void setImageUrl(String imageUrl) {
this.imageUrl = imageUrl;
}
public String getPicUrl() {
return picUrl;
}
public void setPicUrl(String picUrl) {
this.picUrl = picUrl;
}
}
模板文件
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<meta http-equiv="Content-Style-Type" content="text/css"/>
<title></title>
<style type="text/css">
body {
font-family: pingfang sc light;
}
.center{
text-align: center;
width: 100%;
}
</style>
</head>
<body>
<!--第一页开始-->
<div class="page" >
<div class="center"><p>${templateName}</p></div>
<div><p>iText官网:${ITEXTUrl}</p></div>
<div><p>FreeMarker官网:${freeMarkerUrl}</p></div>
<div><p>JFreeChart教程:${JFreeChartUrl}</p></div>
<!--外部链接-->
<p>静态logo图</p>
<div>
<img src="${imageUrl}" alt="美团点评" width="512" height="359"/>
</div>
<!--动态生成的图片-->
<p>气温变化对比图</p>
<div>
<img src="${picUrl}" alt="我的图片" width="500" height="270"/>
</div>
</div>
<!--第一页结束-->
<!---分页标记-->
<span style="page-break-after:always;"></span>
<!--第二页开始-->
<div class="page">
<div>第二页开始了</div>
<div>列表值:</div>
<div>
<#list scores as item>
<div><p>${item}</p></div>
</#list>
</div>
</div>
<!--第二页结束-->
</body>
</html>