广州网站制作有哪些,怎么样建立学校网站,廊坊建设部网站,桂林漓江景区1.PDF模板制作
准备原始模板 准备一个原始PDF模板#xff0c;可以编辑好Word#xff0c;预留出要填充的部分#xff0c;再转换成PDF格式。 设置表单域 用任意PDF编辑器打开PDF模板文件#xff0c;设置表单域#xff0c;下面以WPS为例#xff1a; 拖动文本域到需要填充的…1.PDF模板制作
准备原始模板 准备一个原始PDF模板可以编辑好Word预留出要填充的部分再转换成PDF格式。 设置表单域 用任意PDF编辑器打开PDF模板文件设置表单域下面以WPS为例 拖动文本域到需要填充的位置调整区域大小和位置然后双击设置文本域属性 此处我添加了3个文本域分别是NAME姓名、GENDER性别、IDNUMBER身份证号然后保存即可。 2.相关依赖
dependencygroupIdcom.itextpdf/groupIdartifactIditextpdf/artifactIdversion5.1.2/version
/dependency3.模板填充
package com.visy.utils;import com.itextpdf.text.pdf.AcroFields;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfStamper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;/*** author visy.wang* date 2024/11/7 18:29*/
public class PdfUtil {private final static Logger logger LoggerFactory.getLogger(PdfUtil.class);/*** PDF模板填充* param tmplUrl 模板地址可以是本地文件路径也可以是Url* param targetFile 目标PDF基于模板填充后的输出* param fieldMap 表单域表单域名称表单域填充值*/public static void templateFill(String tmplUrl, File targetFile, MapString, Object fieldMap){ByteArrayOutputStream bos null;FileOutputStream fos null;try {PdfReader reader new PdfReader(tmplUrl);PdfStamper ps new PdfStamper(reader, bos new ByteArrayOutputStream());AcroFields acroFields ps.getAcroFields();//解决中文BaseFont bfChinese BaseFont.createFont(STSong-Light, UniGB-UCS2-H, false);acroFields.addSubstitutionFont(bfChinese);//模板表单域赋值MapString, AcroFields.Item fields acroFields.getFields();for (Map.EntryString, AcroFields.Item field : fields.entrySet()) {String fieldName field.getKey();if(Objects.nonNull(fieldName) fieldMap.containsKey(fieldName)){Object fieldValue fieldMap.get(fieldName);acroFields.setField(fieldName, Objects.isNull(fieldValue) ? : fieldValue.toString());}}ps.setFreeTextFlattening(true);ps.setFormFlattening(true);ps.close();fos new FileOutputStream(targetFile);fos.write(bos.toByteArray());fos.flush();}catch (Exception e){logger.info(fillPdfTemplate error: {}, e.getMessage(), e);throw new RuntimeException(e.getMessage(), e);}finally {try{if(Objects.nonNull(fos)){fos.close();}if(Objects.nonNull(bos)){bos.close();}}catch(Exception e){logger.info(fillPdfTemplate close error: {}, e.getMessage(), e);}}}public static void main(String[] args) {String tmplUrl E:\\test\\pdf\\PDF测试模板.pdf;File targetFile new File(E:\\test\\pdf\\目标PDF.pdf);MapString,Object fieldMap new HashMap();fieldMap.put(NAME, 张三);fieldMap.put(GENDER, 男);fieldMap.put(IDNUMBER, 513126198803120435);//基于模板生成文件templateFill(tmplUrl, targetFile, fieldMap);System.out.println(生成完毕targetFile.getAbsolutePath());}
}4.控制台输出
生成完毕E:\test\pdf\目标PDF.pdf5.目标PDF