Ravindra Ranwala Ravindra Ranwala - 2 years ago 133
Java Question

iText Add values to placeholders in PDF cover page dynamically

I have the following cover page. I need to add values for Licensee, date and fill in the box with another text given. How can this be done using iText. Any help is appreciated.enter image description here

Answer Source

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

enter image description here

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");
        "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.");

The resulting PDF looks like this: certificate.pdf

enter image description here

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download