个人开发学习
参考一、使用iText填充PDF模板(适用于表单式PDF)
依赖配置(pom.xml):
XML
代码示例:
Java
public void exportPdf(HttpServletResponse response) throws Exception {
String templatePath = "template.pdf"; // 模板路径
String outputFileName = "output.pdf";
// 设置响应头
response.setContentType("application/pdf");
response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(outputFileName, "UTF-8"));
PdfReader reader = new PdfReader(templatePath);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
PdfStamper stamper = new PdfStamper(reader, bos);
AcroFields form = stamper.getAcroFields();
// 设置中文字体(解决中文乱码)
BaseFont bf = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.EMBEDDED);
form.addSubstitutionFont(bf);
// 填充数据
form.setField("name", "张三");
form.setField("date", "2024-04-17");
stamper.setFormFlattening(true); // 锁定表单
stamper.close();
reader.close();
// 输出到浏览器
OutputStream out = response.getOutputStream();
bos.writeTo(out);
out.flush();
}
参考二、动态生成PDF内容(适用于自由排版)
代码示例:
Java
public void createPdf(HttpServletResponse response) throws Exception {
Document document = new Document(PageSize.A4);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
PdfWriter.getInstance(document, baos);
document.open();
// 设置中文字体
BaseFont bf = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.EMBEDDED);
Font font = new Font(bf, 12);
// 添加标题
Paragraph title = new Paragraph("动态生成的PDF", new Font(bf, 18, Font.BOLD));
title.setAlignment(Element.ALIGN_CENTER);
document.add(title);
// 添加表格
PdfPTable table = new PdfPTable(3);
table.addCell(new PdfPCell(new Phrase("姓名", font)));
table.addCell(new PdfPCell(new Phrase("年龄", font)));
table.addCell(new PdfPCell(new Phrase("职业", font)));
table.addCell("张三");
table.addCell("30");
table.addCell("工程师");
document.add(table);
document.close();
// 输出到浏览器
response.setContentType("application/pdf");
response.setHeader("Content-Disposition", "attachment; filename=dynamic.pdf");
baos.writeTo(response.getOutputStream());
}主要问题还是在于中文的学习
浙公网安备 33010602011771号