3

Im trying to write to an existing pdf using the java pdf stamper, but for some reason there is a certain checkbox in the pdf that the text appears to be drawn under.

Code for Reading pdf:

PdfReader reader = new PdfReader(Testing.getImagePath() + "form.pdf");
File dir = new File(Testing.getResourcePath() + id + "/");
String destination = Testing.getResourcePath() + id + "form" + id + ".pdf";
File exist = new File(destination);

dir.mkdirs();
PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(destination));
stamper.setFormFlattening(true);
PdfContentByte over;
over = stamper.getOverContent(1);

Code for Drawing text:

over.beginText();
over.setFontAndSize(bf, 11);
over.setTextMatrix(169, 322);
over.showText("X");
over.endText();
Jan
  • 13,738
  • 3
  • 30
  • 55
King
  • 59
  • 8

1 Answers1

1

First off:

Iterate over the FormFields in your PDF and find out the valid values to set:

        AcroFields form = stamper.getAcroFields();
        for(Entry<String, Item> field : form.getFields().entrySet()) {
            System.out.println(field.getKey() + ": " + field.getValue());
            String[] values = form.getAppearanceStates(field.getKey());
            StringJoiner sb = new StringJoiner(",");
            for (String value : values) {
                sb.add(value);
            }
            System.out.println("Possible Options: " + sb.toString());
        }

Now you should be able to select the checkbox by setting it's allowed value:

        form.setField("myCheckbox", "myYesValue");
Jan
  • 13,738
  • 3
  • 30
  • 55
  • 1
    Where did you get your AcroFields from? From the Stamper / the writer or from the reader (in which case they'd be read-only). Share the code in an edit to your question? – Jan May 26 '17 at 16:18
  • yeah I used different code to output the id's from the pdf, and was reading from the reader instead of the stamper. Got it to work, Thanks! – King May 26 '17 at 16:21