Koesh
Koesh

Reputation: 471

iText Android - Adding text to existing PDF

we have a PDF with some fields in order to collect some data, and I have to fill it programmatically with iText on Android by adding some text in those positions. I've been thinking about different ways to achieve this, with little success in each one.

Note: I'm using the Android version of iText (iTextG 5.5.4) and a Samsung Galaxy Note 10.1 2014 (Android 4.4) for most of my tests.

I'd like to know what's be the best way in performance to do this process, and any help about achieving it. I am really newbie with iText and any help would be really appreciated.

Thanks!

EDIT

At the end I used the third option: a PDF with editable fields that we fill, and then we use the "flattening" to create a non-editable PDF with all texts already there.

The code is as follows:

    pdfReader = new PdfReader(is);

    FileOutputStream fios = new FileOutputStream(outPdf);

    PdfStamper pdfStamper = new PdfStamper(pdfReader, fios);
    //Filling the PDF (It's totally necessary that the PDF has Form fields)
    fillPDF(pdfStamper);
    //Setting the PDF to uneditable format
    pdfStamper.setFormFlattening(true);

    pdfStamper.close();

and the method to fill the forms:

public static void fillPDF(PdfStamper stamper) throws IOException, DocumentException{
    //Getting the Form fields from the PDF
    AcroFields form = stamper.getAcroFields();
    Set<String> fields = form.getFields().keySet();
    for(String field : fields){
            form.setField("name", "Ernesto");
            form.setField("surname", "Lage");
        }
    }
}

The only thing about this approach is that you need to know the name of each field in order to fill it.

Upvotes: 6

Views: 2203

Answers (1)

GreyBeardedGeek
GreyBeardedGeek

Reputation: 30088

There is a process in iText known as 'flattening', which takes the form fields, and replaces them with the text that the fields contain.

I haven't used iText in a few years (and not at all on Android), but if you search the manual or online examples for 'flattening', you should find how to do it.

Upvotes: 4

Related Questions