itext导出pdf代码并处理中文乱码(2)
作者:互联网
package com.itext.ipdf;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.pdf.AcroFields;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfStamper;
public class ReportPDF {
public static void main(String[] args) throws IOException {
makePdf();
}
public static void makePdf() throws IOException{
PdfReader readeTemplate = null;
FileOutputStream out = null;
try {
//1.读取template.pdf
readeTemplate = new PdfReader("template.pdf");
out = new FileOutputStream("ok.pdf");
PdfStamper ps = new PdfStamper(readeTemplate, out);//模板转换成新文件
AcroFields templateFileds = ps.getAcroFields();//获取Adobe Acrobat DC填充的字段
//2.处理中文乱码
//STZHONGS.TTF华文仿宋字体 可以到C:\Windows\Fonts文件下找
String fonurl = ReportPDF.class.getClassLoader().getResource("STZHONGS.TTF").getPath();
fonurl = fonurl.replaceAll("%20", " ");
BaseFont bfChinese = BaseFont.createFont(fonurl, BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
templateFileds.addSubstitutionFont(bfChinese);
//3.向Adobe Acrobat DC填充的字段赋值
templateFileds.setField("producer", "zzl");
templateFileds.setField("productionTime", new SimpleDateFormat("yyyy-MM-dd").format(new Date()));
templateFileds.setField("name", "内存条");
templateFileds.setField("size", "8G");
templateFileds.setField("color", "黑色");
templateFileds.setField("amount", "1");
ps.setFormFlattening(true);
ps.close();
} catch (IOException e) {
e.printStackTrace();
} catch (DocumentException e) {
e.printStackTrace();
}finally{
if(out != null){
out.close();
}
if(readeTemplate != null){
readeTemplate.close();
}
}
}
}
标签:text,乱码,itext,com,templateFileds,pdf,import,setField 来源: https://www.cnblogs.com/zzlcome/p/11059677.html