最近在做签章的项目,需要将FTL模板文件转换成PDF文件。整体思路是:首先将FTL文件转换成HTML文件,然后再将HTML文件转成PDf文件。下面是代码部分。
import java.io.BufferedWriter;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.xhtmlrenderer.pdf.ITextFontResolver;
import org.xhtmlrenderer.pdf.ITextRenderer;
import com.credithc.base.microservice.scs.test.Contract;
import com.itextpdf.text.pdf.BaseFont;
import freemarker.template.Configuration;
import freemarker.template.Template;
/**
* @Description:
* @author : hujingbo
* @date : 2017-11-3
*/
public class PdfUtils {
/**
* @Title: FTL2PDF
* @Description: 将FTL文件转换成PDF的工具类
* @param
* @return void
* @throws
*/
public static void FTL2PDF(String srcPath, String destPath , Map<String,Object> map) {
try {
// 将生成的内容写入html文件中
Configuration conf = new Configuration(Configuration.VERSION_2_3_23);
conf.setDirectoryForTemplateLoading(new File(srcPath));
conf.setEncoding(Locale.getDefault(), "UTF-8");
conf.setDateFormat("yyyy-MM-dd HH:mm:ss");
Template template = conf.getTemplate("123.ftl");
StringWriter stringWriter = new StringWriter();
BufferedWriter writer = new BufferedWriter(stringWriter);
template.process(map, writer);
String htmlStr = stringWriter.toString();
System.out.println("转换html成功!");
// 将生成的内容写入html转换成pdf
DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document doc = builder.parse(new ByteArrayInputStream(htmlStr.getBytes("UTF-8")));
ITextRenderer renderer = new ITextRenderer();
// 解决中文支持问题
ITextFontResolver fontResolver = renderer.getFontResolver();
// 设置pdf中文字体为宋体
if (isOsWindow()) {
fontResolver.addFont("C:/Windows/Fonts/SimSun.ttf",BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
} else {
fontResolver.addFont("/usr/share/fonts/ttc/SimSun.ttf",BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
}
renderer.setDocument(doc, null);
renderer.layout();
OutputStream out = new FileOutputStream(new File(destPath));
renderer.createPDF(out);
System.out.println("转换pdf成功!");
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* @Title: isOsWindow
* @Description: 获取系统类型
* @param
* @return boolean
* @throws
*/
private static boolean isOsWindow() {
String osName = System.getProperties().getProperty("os.name");
if(osName.toLowerCase().indexOf("win")!=-1){
return true;
}
return false;
}
public static void main(String[] args) {
String srcPath = "D:/test/bbb/";
String destPath = "D:/test/bbb/456.pdf";
Map<String, Object> map = new HashMap<String, Object>();
map.put("number", "1565615178");
map.put("years", "2017");
map.put("month", "11");
map.put("day", "05");
FTL2PDF(srcPath, destPath, map);
}
}
链接: https://pan.baidu.com/s/1dEURl1v 密码: sa55