动态生成PDF内容信息填充
需求背景: 需要动态生成 pdf 内容 供用户下载
使用技术:itextpdf
引入maven 依赖 itextpdf 包
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itextpdf</artifactId>
<version>5.5.3</version>
</dependency>
导入pdf 原始文件 进行pdf 模板文件制作
在线制作模板链接: pdfescape
第一步: 文件流读取模板PDF,获取 PdfStamper 对象
// 读取pdf模板
PdfReader reader = new PdfReader(templatePath);
// 输出流
FileOutputStream out = new FileOutputStream(outputPath);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
PdfStamper stamper = new PdfStamper(reader, bos);
第二步:设置替换字体,得到字段迭代器,遍历输出表单域名与值
AcroFields form = stamper.getAcroFields();
ArrayList<BaseFont> fontList = new ArrayList<BaseFont>();
// 设置替换字体
form.setSubstitutionFonts(fontList);
// 得到字段迭代器
Iterator<String> it = form.getFields().keySet().iterator();
// 遍历输出表单域名与值
while (it.hasNext()) {
String name = it.next().toString();
if (name.equals("order_no")) {
form.setField(name, orderNo);
} else if (name.equals("delivery_order_no")) {
form.setField(name, deliveryNo);
}
}
第三步:在PDF模板文件中绘制条形码
Barcode39 barcode39 = new Barcode39();
// 条形码字号
barcode39.setSize(15);
// 条形码高度
barcode39.setBarHeight(25);
// 条形码与数字间距
barcode39.setBaseline(15);
// 条形码值
barcode39.setCode(deliveryNo);
barcode39.setStartStopText(true);
barcode39.setExtended(true);
// 绘制条形码在第一页
PdfContentByte cb = stamper.getOverContent(1);
// 生成条形码图片
Image image128 = barcode39.createImageWithBarcode(cb, null, null);
// 条形码位置
image128.setAbsolutePosition(100,432);
// 加入条形码
cb.addImage(image128);
直接输出条形码
//-----------------绘制条形码开始------------------------//
PdfContentByte cb = stamper.getOverContent(1);
Barcode128 code128 = new Barcode128();
code128.setCode(code);
code128.setCodeType(Barcode128.CODE128);
Image code128Image = code128.createImageWithBarcode(cb, null, null);
code128Image.setAbsolutePosition(130,280);
code128Image.scalePercent(525);
cb.addImage(code128Image);
输出文件流
stamper.setFormFlattening(true);// 设置为fasle,生成PDF将不能编辑
stamper.close();//关闭PdfStamper
Document doc = new Document();//实例化Document对象
PdfCopy copy = new PdfCopy(doc, out);
doc.open();//打开文档
PdfImportedPage importPage = copy.getImportedPage(new PdfReader(bos.toByteArray()), 1);
copy.addPage(importPage);
doc.close();