您的位置:首页 > 其它

Freemarker+Flying sauser +Itext 利用ftl模板生成PDF打印预览

2017-11-23 11:13 459 查看
js

function printPDF(){
window.open(adminPath+"/officer/cxsxwh/printPDF?&personnelUuid="+personnelUuid+param);
////window.location.href=adminPath+"/officer/cxsxwh/printPDF?&personnelUuid="+personnelUuid+param;
}
maven

<dependency>
<groupId>com.itextpdf.tool</groupId>
<artifactId>xmlworker</artifactId>
<version>5.5.1</version>
</dependency>

<!-- 支持中文 -->
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itext-asian</artifactId>
<version>5.2.0</version>
</dependency>
<!-- 支持css样式渲染 -->
<dependency>
<groupId>org.xhtmlrenderer</groupId>
<artifactId>flying-saucer-pdf-itext5</artifactId>
<version>9.0.3</version>
</dependency>
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>${freemarker.version}</version>
</dependency>

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<String, Object> params = new HashMap<String, Object>();
Map data = new HashMap();
try {
Map<String,Object> variables = new HashMap<String,Object>();

List<User> userList = new ArrayList<User>();

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
4000
);

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<String,Object> 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;
}
}


simple.ftl
<html>
<head>
<title>${title}</title>
<style>
table {
width:100%;border:green dotted ;border-width:2 0 0 2
}
td {
border:green dotted;border-width:0 2 2 0
}
@page {
size: 8.5in 11in;
@bottom-center {
content: "page " counter(page) " of " counter(pages);
}
}
body {
font-family: SimSun;
font-size:14px;
font-style:italic;
font-weight:500;
}

.heiti
{
font-family: simsun-bold;
}
</style>
</head>
<body>
<div>
<div align="center">
<h1>${title}</h1>
</div>
<table>
<tr>
<td><b>Name</b></td>
<td><b>Age</b></td>
<td><b>Sex</b></td>
<td><b>图片</b></td>
</tr>
<#list userList as user>
<#if user.sex = 1>
<tr>
<td>${user.name}</td>
<td>${user.age}</td>
<td>
<#if user.sex = 1>
male
<#else>
female
</#if>
</td>
<td><img src="${user.picUrl}" width="24" height="24" /></td>
</tr>
</#if>
</#list>
</table>
</div>
</body>
</html>

     body {  

       font-family: SimSun;        

       font-size:14px;       

       font-style:italic;   

       font-weight:500;  

    }  

  

    .heiti  

    {  

      font-family: simsun-bold;     

    } 
这段设置中文字体,如果不加输出中文的地方会变为空

参考:http://mazhiyuan.iteye.com/blog/849032

           http://blog.51cto.com/12218186/1865716

           https://www.cnblogs.com/youzhibing/p/7692366.html

           
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: