iText动态地为PDF封面页中的占位符添加值

时间:2016-04-09 22:16:26

标签: java pdf pdf-generation itext

我有以下封面。我需要为被许可方日期添加值,并在框中填写另一个文字。如何使用iText完成此操作。任何帮助表示赞赏。enter image description here

1 个答案:

答案 0 :(得分:6)

首先,您需要创建一个表单,作为所有许可证文档的模板。 Chapter 6 of "iText in Action"的第5.3.5节(可以免费下载的章节)解释了如何使用OpenOffice创建这样的表单,但是有很多替代方法可以做到这一点。我使用Adobe Acrobat创建了这样一个表单:CertificateOfExcellence.pdf

enter image description here

我突出显示了这些字段,以便您可以看到我添加它们的位置。有四个:

  • 当然: 14pt Helvetica的课程名称,中心对齐
  • 姓名: Helvetica的学生姓名,左对齐
  • 日期: Helvetica课程的日期,左对齐
  • 课程说明: Helvetica学生的姓名,左边是多行标志。

现在我可以轻松填写​​表格(参见FillForm):

public void manipulatePdf(String src, String dest) throws DocumentException, IOException {
    PdfReader reader = new PdfReader(src);
    PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(dest));
    AcroFields form = stamper.getAcroFields();
    form.setField("course", "Copying and Pasting from StackOverflow");
    form.setField("name", "Some dude on StackOverflow");
    form.setField("date", "April 10, 2016");
    form.setField("description",
        "In this course, people consistently ignore the existing documentation completely. "
        + "They are encouraged to do no effort whatsoever, but instead post their questions "
        + "on StackOverflow. It would be a mistake to refer to people completing this course "
        + "as developers. A better designation for them would be copy/paste artist. "
        + "Only in very rare cases do these people know what they are actually doing. "
        + "Not a single student has ever learned anything substantial during this course.");
    stamper.setFormFlattening(true);
    stamper.close();
}

生成的PDF如下所示:certificate.pdf

enter image description here

如您所见,代码非常简单。对于那些花时间阅读文档的人来说,所有这些都有很好的文档记录。也许您还可以查看Interactive forms上标题为official web site的部分。