iText Add values to placeholders in PDF cover page dynamically

大城市里の小女人 提交于 2019-12-01 06:21:14

First you need to create a form that will act as a template for all your license document. Section 5.3.5 of Chapter 6 of "iText in Action" (a chapter that can be downloaded for free) explains how to create such a form using OpenOffice, but there are many alternative ways to do this. I created such a form using Adobe Acrobat: CertificateOfExcellence.pdf

I highlighted the fields so that you can see where I've added them. There are four:

  • course: the name of the course in 14pt Helvetica, with centered alignment
  • name: the name of the student in Helvetica, left alignment
  • date: the date of the course in Helvetica, left alignment
  • description of the course: the name of the student in Helvetica, left alignment with the multi-line flag on.

Now I can easily fill out the form (see 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();
}

The resulting PDF looks like this: certificate.pdf

As you can see, the code is very simple. All of this is very well documented for those who take the time to read the documentation. Maybe you can also take a look at the section entitled Interactive forms on the official web site.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!