Chris
Chris

Reputation: 2046

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?

Upvotes: 0

Views: 4146

Answers (3)

akrinah
akrinah

Reputation: 159

Dedicated to all developers from the future.

AcroFormCheckBox is defined in the official repository on line 2348. Correct values for the value and appearanceState property are either On or Off.

The provided solution lead to inconsitent visualization of the checkbox in respect to the internal value and thus to errors on the PDF importing side.

Correct solution:

var doc = new jsPDF();
var checkBox = new CheckBox();
checkBox.fieldName = "CheckBox1";
checkBox.Rect = [50, 120, 30, 10];
checkBox.value = 'Off'; // or On
checkBox.appearanceState = 'Off'; // or On
doc.addField(checkBox);

Upvotes: 0

Alex
Alex

Reputation: 21

Here are two very simple variants that I have made use of:

var doc = new jsPDF('p', 'mm', 'a4');

function checkbox(x, y, length, width) {
doc.rect(x, y, length, width);
doc.line(x, y, x + length, y + width);
doc.line(x, y + length, x + width, y);
}

doc.text(10, 28, 'Checked')
checkbox(10, 30, 2, 2);
checkbox(20, 30, 4, 4);
checkbox(35, 30, 8, 8);
checkbox(55, 30, 12, 12);

doc.text(10, 48, 'Unchecked')
doc.rect(10, 50, 2, 2);
doc.rect(20, 50, 4, 4);
doc.rect(35, 50, 8, 8);
doc.rect(55, 50, 12, 12);

Result: What the checkbox looks like.

Upvotes: -1

Chris
Chris

Reputation: 2046

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

Upvotes: 4

Related Questions