Search code examples
itextacrofields

Add a text field to a PDF form with default value using iText


We have a PDF form with existing fields, and we are trying to add new fields to the form, with default values, without success. Basically we are doing as follows:

        PdfReader reader = new PdfReader(new FileInputStream(new File("C:\\Temp\\577979.pdf")));
        PdfStamper stamper = new PdfStamper(reader, (new FileOutputStream(new File("C:\\Temp\\577979-out.pdf"))));
        AcroFields form = stamper.getAcroFields();

        // Let's add value to an existing field
        form.setField("idCustomer", "My customer!!!");

        // Let's add a new field
        TextField idDocTrackTypeField = new TextField(stamper.getWriter(), new Rectangle(150, 740, 180, 790), "idDocTrackType");
        PdfFormField field1 = idDocTrackTypeField.getTextField();

        // First attempt to set the value (before adding it)
        field1.setValueAsString("idDocTrackTypeValue1");

        // Let's add it
        stamper.addAnnotation(field1, 1);

        // Second attempt to set the value (after adding it)
        field1.setValueAsString("idDocTrackTypeValue2");

        // Third attempt to set the value
        form.setField("idDocTrackType", "idDocTrackTypeValue3")

The field idCustomer is updated with the new value, but the new field idDocTrackType has no content. What am I doing wrong?


Solution

  • Please add an extra line to set the text:

    TextField idDocTrackTypeField = new TextField(stamper.getWriter(),
        new Rectangle(150, 740, 180, 790), "idDocTrackType");
    idDocTrackTypeField.setText("default text");
    PdfFormField field1 = idDocTrackTypeField.getTextField();