Itext7填充PDF表单中文无法显示,‘凉’不显示问题
- 添加依赖
<!-- pdf处理依赖包 -->
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itext7-core</artifactId>
<version>7.0.3</version>
<type>pom</type>
</dependency>
- 下载中文字库msyh.ttc(直接在百度搜索msyh.ttc进行下载解压,可以放在工程下)
- 代码
/**
*静态方法填充pdf表单
* src 模板路径
* dest 生成后新的pdf路径
* font
* data 表单填充的数据
*/
public static void createPDF(String src, String dest, String font, Map<String, Object> data) throws IOException {
// 创建pdf文件
PdfDocument pdf = new PdfDocument(new PdfReader(src), new PdfWriter(dest));
// 创建中文字体,使用自定义中文库(font: msyh.ttc所在路径,我放在resources下,
// 可以通过:String font = this.getClass().getClassLoader().getResource("/").getPath() + "msyh.ttc";获取所在路径)
PdfFont f2 = PdfFontFactory.createFont(font + ",0", PdfEncodings.IDENTITY_H, true);
// 获取pdf模板中的表单信息
PdfAcroForm form = PdfAcroForm.getAcroForm(pdf, true);
// 设置表单填充值
Map<String, PdfFormField> fields = form.getFormFields();
for (String key : data.keySet()) {
fields.get(key).setValue(data.get(key).toString()).setFont(f2);
}
// 设置表单不可编辑
form.flattenFields();
// 关闭编辑
pdf.close();
}
附:生成pdf表单可以使用 Adobe Acrobat 9 Pro
参考:链接