12

I've tried so many different ways, but I can't get the check box to be checked! Here's what I've tried:

var reader = new iTextSharp.text.pdf.PdfReader(originalFormLocation);
using (var stamper = new iTextSharp.text.pdf.PdfStamper(reader,ms)) {
    var formFields = stamper.AcroFields;
    formFields.SetField("IsNo", "1");
    formFields.SetField("IsNo", "true");
    formFields.SetField("IsNo", "On");
}

None of them work. Any ideas?

Bruno Lowagie
  • 75,994
  • 9
  • 109
  • 165
user948060
  • 953
  • 3
  • 12
  • 25

1 Answers1

17

You shouldn't "guess" for the possible values. You need to use a value that is stored in the PDF. Try the CheckBoxValues example to find these possible values:

public String getCheckboxValue(String src, String name) throws IOException {
    PdfReader reader = new PdfReader(SRC);
    AcroFields fields = reader.getAcroFields();
    // CP_1 is the name of a check box field
    String[] values = fields.getAppearanceStates("IsNo");
    StringBuffer sb = new StringBuffer();
    for (String value : values) {
        sb.append(value);
        sb.append('\n');
    }
    return sb.toString();
}

Or take a look at the PDF using RUPS. Go to the widget annotation and look for the normal (/N) appearance (AP) states. In my example they are /Off and /Yes:

screen shot

Amedee Van Gasse
  • 7,280
  • 5
  • 55
  • 101
Bruno Lowagie
  • 75,994
  • 9
  • 109
  • 165
  • What is precise meaning of that AP array? The 1st value is always to be used for "uncheck" state and 2nd for "check"? Currently I rely on that presumption and it works okay even for odd PDFs, but I'd like to be sure... – Pavel Vlasov Apr 22 '16 at 17:32
  • The `Off` value should always reflect the *off state*. The order doesn't matter. So you shouldn't count on the 1st state to be the "uncheck" state. – Bruno Lowagie Apr 22 '16 at 17:35
  • Hi @BrunoLowagie, please either update the link or remove them. I have come across a lot of 404s while going through ItextPdf questions. Thanks – Danyal Sandeelo Apr 16 '19 at 07:15
  • 1
    @DanyalSandeelo Bruno no longer works at iText Software. If you encounter such broken links, please send an email to iText, or talk to the chatbot on the iText website, and we'll try to fix it. – Amedee Van Gasse May 06 '20 at 09:36
  • Can't find the iText 5 code example, but the closest I could locate is an iText 7 code example that not only reads the values, but also shows you how to change them. I'll edit the post. – Amedee Van Gasse May 08 '20 at 08:40