js
function printPDF(){
window.open(adminPath+"/officer/cxsxwh/printPDF?&personnelUuid="+personnelUuid+param);
window.location.href=adminPath+"/officer/cxsxwh/printPDF?&personnelUuid="+personnelUuid+param;
}
maven
com.itextpdf.tool
xmlworker
5.5.1
com.itextpdf
itext-asian
5.2.0
org.xhtmlrenderer
flying-saucer-pdf-itext5
9.0.3
org.freemarker
freemarker
${freemarker.version}
Java
User类
package com.lenote.modules.officer.cxsxwh.entity;
public class User {
private String name;
private int age;
private int sex;
private String picUrl;
/**
* Constructor with all fields
*
* @param name
* @param age
* @param sex
*/
public User(String name, int age, int sex,String picUrl) {
super();
this.name = name;
this.age = age;
this.sex = sex;
this.picUrl= picUrl;
}
/// getter and setter ///
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public int getSex() {
return sex;
}
public void setSex(int sex) {
this.sex = sex;
}
public String getPicUrl() {
return picUrl;
}
public void setPicUrl(String picUrl) {
this.picUrl = picUrl;
}
}
@RequestMapping(value = "/printPDF")
public void printPDF(HttpServletRequest request, HttpServletResponse response) throws Exception
{
OutputStream os = null;
String htmlStr;
Map params = new HashMap();
Map data = new HashMap();
try {
Map variables = new HashMap();
List userList = new ArrayList();
User tom = new User("张三",19,1,"xxxx.jpg");
User amy = new User("李四",28,0,"xxxx.jpg");
User leo = new User("王五",23,1,"xxxx.jpg");
userList.add(tom);
userList.add(amy);
userList.add(leo);
variables.put("title", "用户");
variables.put("userList", userList);
//通过freemaker模板生成html
htmlStr = HtmlGenerator.generate("simple.ftl", variables,request);
String appPath = request.getSession().getServletContext().getRealPath(File.separator);
ITextRenderer renderer = new ITextRenderer();
String failPath = "file:" + File.separator + appPath;
renderer.setDocumentFromString(htmlStr);
//设置图片的相对路径
renderer.getSharedContext().setBaseURL("file:/C:/Users/hasee/Desktop/pic/");
// 解决中文支持问题
ITextFontResolver fontResolver = renderer.getFontResolver();
fontResolver.addFont("c://windows//fonts//simsun.ttc", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
//生成pdf文件
///response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode("测试", "UTF-8") + new Date().getTime() + ".pdf");
response.setContentType("application/pdf");
os = response.getOutputStream();
renderer.layout();
renderer.createPDF(os, true);
os.flush();
} catch (Exception e) {
e.printStackTrace();
}finally {
if (null != os) {
try {
os.close();
} catch (IOException e) {
throw new Exception(e);
}
}
}
}
HtmlGenerator类
import java.io.BufferedWriter;
import java.io.File;
import java.io.StringWriter;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import com.lenote.modules.pdfsimple.freemarker.FreemarkerConfiguration;
import freemarker.template.Configuration;
import freemarker.template.Template;
public class HtmlGenerator {
/**
* Generate html string.
*
* @param template the name of freemarker teamlate.
* @param variables the data of teamlate.
* @return htmlStr
* @throws Exception
*/
public static String generate(String template, Map variables,HttpServletRequest request) throws Exception{
String basePath = request.getSession().getServletContext().getRealPath("/");
Configuration config = FreemarkerConfiguration.getConfiguation();
//获取ftl文件所在目录
config.setDirectoryForTemplateLoading(new File(basePath + "/WEB-INF/ftl"));
config.setDefaultEncoding("UTF-8");
Template tp = config.getTemplate(template);
StringWriter stringWriter = new StringWriter();
BufferedWriter writer = new BufferedWriter(stringWriter);
tp.setEncoding("UTF-8");
tp.process(variables, writer);
String htmlStr = stringWriter.toString();
writer.flush();
writer.close();
return htmlStr;
}
}
${title}
${title}
Name
Age
Sex
图片
<#list userList as user>
<#if user.sex = 1>
${user.name}
${user.age}
<#if user.sex = 1>
male
<#else>
female
#if>
#if>
#list>
这段设置中文字体,如果不加输出中文的地方会变为空
参考:http://mazhiyuan.iteye.com/blog/849032
http://blog.51cto.com/12218186/1865716
https://www.cnblogs.com/youzhibing/p/7692366.html