itext模板生成PDF
pom.xml引入依赖
<!--itext生成PDF-->
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itextpdf</artifactId>
<version>5.5.13.3</version>
</dependency>
<!--输出中文-->
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itext-asian</artifactId>
<version>5.2.0</version>
</dependency>
生成PDF的util类
/**
* 模板
*/
final static String template = "templates/applying_for_volunteer_service_form_itext.pdf";
final static String fonts_ttf = "fonts/seguisym.ttf";
public static void generatePdf(OutputStream os, Message message, List<String> pickVolunteers, Map<String, List<DictData>> allVolunteers, List<DictData> dictData) throws IOException, DocumentException {
InputStream templateInputStream = new ClassPathResource(template).getInputStream();
PdfReader pdfReader = new PdfReader(templateInputStream);
PdfStamper stamper = new PdfStamper(pdfReader, os);
AcroFields acroFields = stamper.getAcroFields();
acroFields.setSubstitutionFonts(Stream.of(
BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED)
).collect(Collectors.toCollection(ArrayList::new)));
BaseFont base = BaseFont.createFont(fonts_ttf, BaseFont.IDENTITY_H, false);
acroFields.addSubstitutionFont(base);
//填充模板中的占位符(属性名在制作模板时指定)
acroFields.setField("name",message.getName());
acroFields.setField("date",message.getDate());
acroFields.setField("phone",message.getPhone());
acroFields.setField("email",message.getEmail());
acroFields.setField("school",message.getSchool());
acroFields.setField("reason", message.getReason());
acroFields.setField("speciality",message.getSpeciality());
acroFields.setField("volunteerType",message.getVolunteerType());
// 配置申请类型
String volunteerTypes = buildVolunteerTypes(message.getVolunteerType(),dictData);
acroFields.setField("volunteerTypes", volunteerTypes);
// 配置志愿服务
buildAllVolunteers(acroFields,allVolunteers,pickVolunteers);
stamper.setFormFlattening(true);
stamper.close();
}
资源
使用到的字体
fonts/seguisym.ttf
使用到的模板
template/applying_for_volunteer_service_form_itext.pdf
源码地址
效果图
遇到的问题
制作PDF模板
工具:Adobe Acrobat Pro DC
复选框
/**
* 复选框选中
*/
public final static String CHECK_BOX = "☑";
/**
* 复选框未选中
*/
public final static String UN_CHECK_BOX = "☐";
标签:Java,String,acroFields,itext5,static,PDF,message,setField,模板
From: https://www.cnblogs.com/xi-ke-xi/p/17460571.html