javacheckboxitextpdfstamper

Java PDF Stamper writing below checkbox (text being covered by checkbox)


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();

Solution

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