java填充pdf表单
maven
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>forms</artifactId>
<version>7.1.11</version>
</dependency>
示例代码:
public class AwardGenerateServiceImpl implements IAwardGenerateService {
private static final String FONT_PATH = "/files/SimSun.ttf";
public static void doGenerateS1(AwardPdfSampleForm sampleForm,
String sampleName,
HttpServletResponse response) {
InputStream pdfIs = null;
InputStream fontIs = null;
PdfDocument pdf = null;
try {
pdfIs = new ClassPathResource("/files/" + sampleName).getInputStream();
fontIs = new ClassPathResource(FONT_PATH).getInputStream();
ServletOutputStream out = response.getOutputStream();
pdf = new PdfDocument(new PdfReader(pdfIs), new PdfWriter(out));
PdfAcroForm form = PdfAcroForm.getAcroForm(pdf, false);
PdfFont font = PdfFontFactory.createFont(StreamUtil.copyToByteArray(fontIs), PdfEncodings.IDENTITY_H);
form.getField("certNo").setValue(sampleForm.getCertNo(), font, 14f).setReadOnly(true);
form.getField("realName").setValue(sampleForm.getRealName(), font, 14f).setReadOnly(true);
form.getField("productName").setValue(sampleForm.getProductName(), font, 14f).setReadOnly(true);
form.getField("contestName").setValue(sampleForm.getContestName(), font, 14f).setReadOnly(true);
form.getField("category").setValue(sampleForm.getCategory(), font, 14f).setReadOnly(true);
form.getField("group").setValue(sampleForm.getGroup(), font, 14f).setReadOnly(true);
form.getField("award").setValue(sampleForm.getAward(), font, 14f).setReadOnly(true);
form.getField("teacherName").setValue(sampleForm.getTeacherName(), font, 14f).setReadOnly(true);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (pdfIs != null) {
pdfIs.close();
}
if (fontIs != null) {
fontIs.close();
}
if (pdf != null) {
pdf.close();
}
} catch (IOException e) {
log.error("err", e);
}
}
}
}
资源文件
其中 s1.pdf 是sampleName,SimSun.ttf 是宋体
额外说明:由于pdf 为二进制文件,需要配置 maven 不进行过滤,否则打包后会损坏。
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<plugin>
<artifactId>maven-resources-plugin</artifactId>
<configuration>
<nonFilteredFileExtensions>
<nonFilteredFileExtension>pdf</nonFilteredFileExtension>
<nonFilteredFileExtension>ttf</nonFilteredFileExtension>
</nonFilteredFileExtensions>
</configuration>
</plugin>
</plugins>
</build>
2233
以上是 java填充pdf表单 的全部内容, 来源链接: utcz.com/z/518312.html