必备: 1.Adobe Acrobat pro软件(其它pdf编辑器也行,我最初用的迅捷pdf编辑器) 2.itext的jar包
制作模板: 1.用word把文档编辑好,若用的word2007,直接可以另存为pdf文件,暂定名为test.pdf。(网上也可以直接word转pdf:http://app.xunjiepdf.com/word2pdf) 2.用Adobe Acrobat pro打开test.pdf,点击 ‘准备表单’,再点击 ‘选择文件’,进行编辑
制作文本域,并设置属性,字体等。
制作好模板demo.pdf好,开始写代码。
// 利用模板生成pdf
public static void fillTemplate() {
// 模板路径
String templatePath = "D/demo.pdf";
// 生成的新文件路径
String newPDFPath = "D/new.pdf";
PdfReader reader;
FileOutputStream out;
ByteArrayOutputStream bos;
PdfStamper stamper;
try {
out = new FileOutputStream(newPDFPath);// 输出流
reader = new PdfReader(templatePath);// 读取pdf模板
bos = new ByteArrayOutputStream();
stamper = new PdfStamper(reader, bos);
AcroFields form = stamper.getAcroFields();
BaseFont baseFont = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
form.addSubstitutionFont(baseFont);
String[] str = { "qewqe", "3242", "中国" };
int i = 0;
Iterator<String> it = form.getFields().keySet().iterator();
while (it.hasNext()) {
String name = it.next().toString();
System.out.println(name);
form.setField(name, str[i++]);
}
);
// 设为true不可再编辑
stamper.setFormFlattening(true);
stamper.close();
Document doc = new Document();
PdfCopy copy = new PdfCopy(doc, out);
doc.open();
PdfImportedPage importPage = copy.getImportedPage(new PdfReader(bos.toByteArray()), 1);
copy.addPage(importPage);
doc.close();
} catch (IOException e) {
System.out.println(e);
} catch (DocumentException e) {
System.out.println(e);
}
}
其中遇到文本域内为中文不显示,添加 BaseFont baseFont = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);