Search code examples
jspdf

Unchecked CheckBox in jsPDF AcroForms


The examples of jsPDF AcroForm fields in the jsPDF documentation show how to create a CheckBox field but that field is always checked initially. How do you create a CheckBox that initializes to unchecked?


Solution

  • After digging around in the PDF spec (ISO 32000-1:2008) I found in section 12.7.4.2.3 that the checked and unchecked appearances correspond to entries in the field's appearance dictionary. I downloaded this PDF generated by jsPDF:

    var doc = new jsPDF();
    doc.text('CheckBox:', 10, 125);
    var checkBox = new CheckBox();
    checkBox.fieldName = "CheckBox1";
    checkBox.Rect = [50, 120, 30, 10];
    checkBox.value = 'Yes'
    doc.addField(checkBox);
    

    I opened the PDF in a text editor and found my field definition:

    <<
    /F 4
    /Rect [141.73 473.39 226.77 501.73]
    /FT /Btn
    /T (CheckBox1)
    /DA (/F13 0 Tf 0.000 g)
    /V /Yes
    /Type /Annot
    /Subtype /Widget
    /Q 1
    /MK <<
    /CA (3)
    >>
    /AS /On
    /AP <<
    /N <</On 7 0 R >>/D <</On 8 0 R /Off 9 0 R >>>>
    >>
    

    The /N there is the dictionary and the AS value is whether the CheckBox is checked or not. So this means you can control the appearance with:

    checkBox.appearanceState = 'Off' //unchecked
    checkBox.appearanceState = 'On' //checked