freemarker+itext生成PDF文件
由模板生成PDF的具体流程如下:
1.1 使用freemarker生成Html文件
具体生成过程之前已做介绍,详细参考《学习开发代码生成器(一)--使用FreeMarker开发代码生成器》
1.1.1 maven依赖
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.23</version>
</dependency>
1.1.2 FreeMarkerUtils工具类
package com.pdf.demo.util;
import freemarker.template.Configuration;
import freemarker.template.DefaultObjectWrapper;
import freemarker.template.Template;
import java.io.*;
import java.util.Map;
public class FreeMarkerUtils {
private static Template getTemplate(String template_path, String templateFileName) {
Configuration configuration = new Configuration();
Template template = null;
try {
configuration.setDirectoryForTemplateLoading(new File(template_path));
configuration.setObjectWrapper(new DefaultObjectWrapper());
configuration.setDefaultEncoding("UTF-8"); //设置编码格式
//模板文件
template = configuration.getTemplate(templateFileName + ".ftl");
} catch (IOException e) {
e.printStackTrace();
}
return template;
}
public static void genteratorFile(Map<String, String> input, String template_path, String templateFileName, String savePath, String fileName) {
Template template = getTemplate(template_path, templateFileName);
File filePath = new File(savePath);
if (!filePath.exists()) {
filePath.mkdirs();
}
String filename = savePath + "\\" + fileName;
File file = new File(filename);
if (!file.exists()) {
file.delete();
}
Writer writer = null;
try {
writer = new OutputStreamWriter(new FileOutputStream(filename), "UTF-8");
template.process(input, writer);
} catch (Exception e) {
e.printStackTrace();
}
}
}
1.2 使用itext生成pdf文件
1.2.1 maven依赖
<dependency>
<groupId>org.xhtmlrenderer</groupId>
<artifactId>flying-saucer-pdf-itext5</artifactId>
<version>9.1.6</version>
</dependency>
1.2.1 HtmlToPdfUtil工具类
package com.pdf.demo.util;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.pdf.BaseFont;
import org.xhtmlrenderer.pdf.ITextRenderer;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
/**
* @author Anna.
* @date 2020/9/2
*/
public class HtmlToPdfUtil {
public static void pdfHandler(String htmFilePath, String pdfFilePath,String fontResourcePath) throws DocumentException, IOException {
File htmFile = new File(htmFilePath);
File pdfFile = new File(pdfFilePath);
String url = htmFile.toURI().toURL().toString();
OutputStream os = new FileOutputStream(pdfFile);
ITextRenderer renderer = new ITextRenderer();
renderer.setDocument(url);
org.xhtmlrenderer.pdf.ITextFontResolver fontResolver = renderer.getFontResolver();
try {
fontResolver.addFont(Test.class.getClassLoader().getResource(fontResourcePath).getPath(), BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
} catch (com.itextpdf.text.DocumentException e) {
e.printStackTrace();
}
renderer.layout();
try {
renderer.createPDF(os);
} catch (com.itextpdf.text.DocumentException e) {
e.printStackTrace();
}
os.close();
}
}
1.3 Hello.ftl模板
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8"/>
<title></title>
<style type="text/css">
@page{size: 2in 2in;}
body{
font-family: STSong;
}
</style>
</head>
<body>
Hello ${name} !
</body>
</html>
注意:(1)html必须为标准html文档,<!DOCTYPE html>必须带,必须指定编码格式,否则浏览器显示会乱码
(2)@page{size: 2in 2in;},指定pdf文件大小,转PDF时才会有效,且不需在标准html文档中,否则会不生效。具体参数值,可参考size - CSS: Cascading Style Sheets | MDN
(3)指定字体必须与设置HtmlToPdfUtil工具类设置中文字体一致,否则将导致中文无法显示
(4) 使用@page{margin:0;}设置边距详细见:@page - CSS(层叠样式表) | MDN
1.4 Test测试类
package com.pdf.demo.util;
import com.itextpdf.text.BaseColor;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Font;
import com.itextpdf.text.pdf.BaseFont;
import org.xhtmlrenderer.pdf.ITextRenderer;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;
/**
* @author Anna.
* @date 2020/9/2
*/
public class Test {
public static void main(String[] args) {
Map input = new HashMap();
input.put("name", "ni hao 啊 asda1231 中国 adad");
FreeMarkerUtils.genteratorFile(input,"D:\\WordkSpaces\\JavaWorkSpaces\\IdeaWorkSpaces\\TestWorkSpaces\\pdfdemo\\src\\main\\resources\\templates\\","Hello","D:\\WordkSpaces\\JavaWorkSpaces\\IdeaWorkSpaces\\TestWorkSpaces\\pdfdemo\\src\\main\\resources\\templates\\","test.html");
try {
HtmlToPdfUtil.pdfHandler("D:\\WordkSpaces\\JavaWorkSpaces\\IdeaWorkSpaces\\TestWorkSpaces\\pdfdemo\\src\\main\\resources\\templates\\test.html","D:\\WordkSpaces\\JavaWorkSpaces\\IdeaWorkSpaces\\TestWorkSpaces\\pdfdemo\\src\\main\\resources\\templates\\test.pdf","font/STSONG.TTF");
} catch (DocumentException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
1.4 效果
1.5 附件
测试demo
链接:https://pan.baidu.com/s/1QKjiswT54PTfuoR6PsWndg
提取码:4tms