Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filling existing pdf text fields using iText

Tags:

itext

I have a pdf document already created with some textfields.I can fill those text fields using Adobe reader and save those values with that file.

My problem is ,can i do that programmatically using iText?If it is possible ,please tell me where i can find some examples?

like image 951
Yasitha Bandara Avatar asked Dec 23 '22 12:12

Yasitha Bandara


1 Answers

That's explained in the iText 7 Jump-start tutorial, more specifically in chapter 4:

This form:

enter image description here

Can be filled out like this:

PdfDocument pdf =
    new PdfDocument(new PdfReader(src), new PdfWriter(dest));
PdfAcroForm form = PdfAcroForm.getAcroForm(pdf, true);
Map<String, PdfFormField> fields = form.getFormFields();
fields.get("name").setValue("James Bond");
fields.get("language").setValue("English");
fields.get("experience1").setValue("Off");
fields.get("experience2").setValue("Yes");
fields.get("experience3").setValue("Yes");
fields.get("shift").setValue("Any");
fields.get("info").setValue("I was 38 years old when I became an MI6 agent.");
// form.flattenFields();
pdf.close();

The result looks like this:

enter image description here

If you uncomment the line form.flattenFields(); then you get this:

enter image description here

When the form is flattened, the fields are removed, and only the content is left.

If by any chance the PDF is a dynamic XFA form, then you should provide an XML stream, and you should read the FAQ: How to fill out a pdf file programmatically? (Dynamic XFA)

As you seem to be new to iText, it is assumed that you'll use the latest version of iText (which is iText 7) as opposed to a version that is being phased out (iText 5) or obsolete (all versions prior to iText 2). However, if for any reason you choose to use iText 5, then your question is a duplicate of How to fill out a pdf file programatically? (in which case your question should be closed as a duplicate).

like image 130
Bruno Lowagie Avatar answered Dec 28 '22 07:12

Bruno Lowagie