-
Notifications
You must be signed in to change notification settings - Fork 48
Expand file tree
/
Copy pathform-integration.test.ts
More file actions
1412 lines (1114 loc) · 48.3 KB
/
form-integration.test.ts
File metadata and controls
1412 lines (1114 loc) · 48.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* Integration tests for form field fonts, appearance generation, and incremental saves.
*
* These tests verify the complete workflow of modifying form fields with custom fonts
* and saving them (both full and incremental). Output files are saved to test-output/
* for manual inspection.
*/
import { PDF } from "#src/api/pdf";
import { DropdownField } from "#src/document/forms/fields/choice-fields";
import { loadFixture, saveTestOutput } from "#src/test-utils";
import { describe, expect, it } from "vitest";
// ─────────────────────────────────────────────────────────────────────────────
// Embedded Font Integration Tests
// ─────────────────────────────────────────────────────────────────────────────
describe("Form Integration: Embedded Fonts", () => {
it("fills text fields with embedded TTF font and saves", async () => {
const pdfBytes = await loadFixture("forms", "sample_form.pdf");
const fontBytes = await loadFixture("fonts", "ttf/LiberationSans-Regular.ttf");
const pdf = await PDF.load(pdfBytes);
const form = pdf.getForm();
expect(form).not.toBeNull();
// Embed font
const font = pdf.embedFont(fontBytes);
// Set font on form-level default
const acroForm = form!.acroForm();
acroForm.setDefaultFont(font);
acroForm.setDefaultFontSize(10);
// Fill some fields
const textFields = form!.getTextFields();
for (const field of textFields.slice(0, 3)) {
if (!field.isReadOnly()) {
field.setValue("Test Value");
}
}
// Update appearances
form!.updateAppearances();
// Save (full save)
const savedBytes = await pdf.save();
const outputPath = await saveTestOutput("forms/embedded-font-full-save.pdf", savedBytes);
console.log(` -> Output: ${outputPath}`);
expect(savedBytes.length).toBeGreaterThan(0);
// Verify by reloading
const pdf2 = await PDF.load(savedBytes);
const form2 = pdf2.getForm();
const reloadedFields = form2!.getTextFields();
const filledField = reloadedFields.find(f => f.getValue() === "Test Value");
expect(filledField).toBeDefined();
});
it("fills fields with embedded OTF font and saves", async () => {
const pdfBytes = await loadFixture("forms", "fancy_fields.pdf");
const fontBytes = await loadFixture("fonts", "otf/FoglihtenNo07.otf");
const pdf = await PDF.load(pdfBytes);
const form = pdf.getForm();
expect(form).not.toBeNull();
// Embed OTF font
const font = pdf.embedFont(fontBytes);
// Get first text field and set font
const nameField = form!.getTextField("First Name 🚀");
if (nameField) {
nameField.setFont(font);
nameField.setFontSize(14);
nameField.setValue("John Doe");
}
form!.updateAppearances();
const savedBytes = await pdf.save();
const outputPath = await saveTestOutput("forms/embedded-otf-font.pdf", savedBytes);
console.log(` -> Output: ${outputPath}`);
expect(savedBytes.length).toBeGreaterThan(0);
});
it("uses different fonts for different fields", async () => {
const pdfBytes = await loadFixture("forms", "sample_form.pdf");
const sansBytes = await loadFixture("fonts", "ttf/LiberationSans-Regular.ttf");
const italicBytes = await loadFixture("fonts", "ttf/JosefinSans-Italic.ttf");
const pdf = await PDF.load(pdfBytes);
const form = pdf.getForm();
expect(form).not.toBeNull();
// Embed two different fonts
const sansFont = pdf.embedFont(sansBytes);
const italicFont = pdf.embedFont(italicBytes);
const textFields = form!.getTextFields();
let count = 0;
for (const field of textFields) {
if (field.isReadOnly()) {
continue;
}
// Alternate between fonts
if (count % 2 === 0) {
field.setFont(sansFont);
field.setValue("Sans Regular");
} else {
field.setFont(italicFont);
field.setValue("Italic Style");
}
count++;
if (count >= 6) {
break;
}
}
form!.updateAppearances();
const savedBytes = await pdf.save();
const outputPath = await saveTestOutput("forms/multiple-fonts.pdf", savedBytes);
console.log(` -> Output: ${outputPath}`);
expect(savedBytes.length).toBeGreaterThan(0);
});
});
// ─────────────────────────────────────────────────────────────────────────────
// Existing Font Tests
// ─────────────────────────────────────────────────────────────────────────────
describe("Form Integration: Existing Fonts", () => {
it("uses existing PDF fonts (Helvetica) for form fields", async () => {
const pdfBytes = await loadFixture("forms", "sample_form.pdf");
const pdf = await PDF.load(pdfBytes);
const form = pdf.getForm();
expect(form).not.toBeNull();
const acroForm = form!.acroForm();
// Get existing font from form resources
const helv = acroForm.getExistingFont("/Helv");
if (helv) {
acroForm.setDefaultFont(helv);
acroForm.setDefaultFontSize(12);
}
// Fill all text fields
for (const field of form!.getTextFields()) {
if (!field.isReadOnly()) {
field.setValue("Helvetica Text");
}
}
form!.updateAppearances();
const savedBytes = await pdf.save();
const outputPath = await saveTestOutput("forms/existing-font-helv.pdf", savedBytes);
console.log(` -> Output: ${outputPath}`);
expect(savedBytes.length).toBeGreaterThan(0);
});
it("lists available fonts from form default resources", async () => {
const pdfBytes = await loadFixture("forms", "sample_form.pdf");
const pdf = await PDF.load(pdfBytes);
const form = pdf.getForm();
expect(form).not.toBeNull();
const acroForm = form!.acroForm();
const fonts = acroForm.getAvailableFonts();
console.log(` Available fonts: ${fonts.join(", ")}`);
expect(fonts.length).toBeGreaterThan(0);
});
});
// ─────────────────────────────────────────────────────────────────────────────
// Text Color Tests
// ─────────────────────────────────────────────────────────────────────────────
describe("Form Integration: Text Colors", () => {
it("applies custom text colors to fields", async () => {
const pdfBytes = await loadFixture("forms", "sample_form.pdf");
const pdf = await PDF.load(pdfBytes);
const form = pdf.getForm();
expect(form).not.toBeNull();
const textFields = form!.getTextFields();
const colors = [
{ r: 1, g: 0, b: 0 }, // Red
{ r: 0, g: 0.5, b: 0 }, // Dark green
{ r: 0, g: 0, b: 1 }, // Blue
];
let colorIndex = 0;
for (const field of textFields.slice(0, 6)) {
if (field.isReadOnly()) {
continue;
}
const color = colors[colorIndex % colors.length];
field.setTextColor(color.r, color.g, color.b);
field.setValue(`Color ${colorIndex + 1}`);
colorIndex++;
}
form!.updateAppearances();
const savedBytes = await pdf.save();
const outputPath = await saveTestOutput("forms/text-colors.pdf", savedBytes);
console.log(` -> Output: ${outputPath}`);
expect(savedBytes.length).toBeGreaterThan(0);
});
});
// ─────────────────────────────────────────────────────────────────────────────
// All Field Types Tests
// ─────────────────────────────────────────────────────────────────────────────
describe("Form Integration: All Field Types", () => {
it("updates appearances for all field types", async () => {
const pdfBytes = await loadFixture("forms", "fancy_fields.pdf");
const pdf = await PDF.load(pdfBytes);
const form = pdf.getForm();
expect(form).not.toBeNull();
// Fill different field types
const textFields = form!.getTextFields();
for (const field of textFields) {
if (!field.isReadOnly()) {
field.setValue("Filled Text");
}
}
const checkboxes = form!.getCheckboxes();
for (const cb of checkboxes) {
try {
cb.check();
} catch {
// Some checkboxes may have different on values, skip them
}
}
const radios = form!.getRadioGroups();
for (const radio of radios) {
const options = radio.getOptions();
if (options.length > 0) {
radio.setValue(options[0]);
}
}
const dropdowns = form!.getDropdowns();
for (const dd of dropdowns) {
const options = dd.getOptions();
if (options.length > 0) {
dd.setValue(options[0].value);
} else if (dd.isEditable) {
dd.setValue("Custom Entry");
}
}
const listboxes = form!.getListBoxes();
for (const lb of listboxes) {
const options = lb.getOptions();
if (options.length > 0) {
lb.setValue([options[0].value]);
}
}
form!.updateAppearances();
const savedBytes = await pdf.save();
const outputPath = await saveTestOutput("forms/all-field-types.pdf", savedBytes);
console.log(` -> Output: ${outputPath}`);
expect(savedBytes.length).toBeGreaterThan(0);
// Verify round-trip
const pdf2 = await PDF.load(savedBytes);
const form2 = pdf2.getForm();
expect(form2!.getFields().length).toBe(form!.getFields().length);
});
});
// ─────────────────────────────────────────────────────────────────────────────
// Incremental Save Tests
// ─────────────────────────────────────────────────────────────────────────────
describe("Form Integration: Incremental Saves", () => {
it("saves form changes incrementally", async () => {
const pdfBytes = await loadFixture("forms", "sample_form.pdf");
const pdf = await PDF.load(pdfBytes);
// Check if incremental save is possible
const blocker = pdf.canSaveIncrementally();
console.log(` Incremental save blocker: ${blocker ?? "none"}`);
const form = pdf.getForm();
expect(form).not.toBeNull();
// Make a simple change
const stateField = form!.getTextField("STATE");
expect(stateField).toBeDefined();
stateField!.setValue("CA");
form!.updateAppearances();
// Save incrementally
const savedBytes = await pdf.save({ incremental: true });
const outputPath = await saveTestOutput("forms/incremental-save.pdf", savedBytes);
console.log(` -> Output: ${outputPath}`);
console.log(` Original size: ${pdfBytes.length}, Saved size: ${savedBytes.length}`);
// Incremental save should be larger than original (appends data)
if (blocker === null) {
expect(savedBytes.length).toBeGreaterThan(pdfBytes.length);
}
// Verify the change persisted
const pdf2 = await PDF.load(savedBytes);
const form2 = pdf2.getForm();
const field2 = form2!.getTextField("STATE");
expect(field2!.getValue()).toBe("CA");
});
it("performs multiple incremental saves", async () => {
const pdfBytes = await loadFixture("forms", "sample_form.pdf");
let pdf = await PDF.load(pdfBytes);
let currentBytes: Uint8Array = new Uint8Array(pdfBytes);
const blocker = pdf.canSaveIncrementally();
if (blocker !== null) {
console.log(` Skipping: incremental save blocked by ${blocker}`);
return;
}
// First incremental save
let form = pdf.getForm();
const field1 = form!.getTextField("STATE");
field1!.setValue("NY");
form!.updateAppearances();
currentBytes = await pdf.save({ incremental: true });
const size1 = currentBytes.length;
await saveTestOutput("forms/multi-incremental-1.pdf", currentBytes);
// Second incremental save (reload from previous)
pdf = await PDF.load(currentBytes);
form = pdf.getForm();
const field2 = form!.getTextField("ZIP");
if (field2 && !field2.isReadOnly()) {
field2.setValue("10001");
form!.updateAppearances();
currentBytes = await pdf.save({ incremental: true });
const size2 = currentBytes.length;
await saveTestOutput("forms/multi-incremental-2.pdf", currentBytes);
console.log(` Sizes: original=${pdfBytes.length}, after1=${size1}, after2=${size2}`);
expect(size2).toBeGreaterThan(size1);
}
// Verify both changes persisted
const finalPdf = await PDF.load(currentBytes);
const finalForm = finalPdf.getForm();
expect(finalForm!.getTextField("STATE")!.getValue()).toBe("NY");
});
it("incremental save with checkbox changes", async () => {
const pdfBytes = await loadFixture("forms", "sample_form.pdf");
const pdf = await PDF.load(pdfBytes);
const form = pdf.getForm();
expect(form).not.toBeNull();
// Toggle some checkboxes
const checkboxes = form!.getCheckboxes();
for (const cb of checkboxes) {
if (cb.isChecked()) {
cb.uncheck();
} else {
cb.check();
}
}
form!.updateAppearances();
const savedBytes = await pdf.save({ incremental: true });
const outputPath = await saveTestOutput("forms/incremental-checkboxes.pdf", savedBytes);
console.log(` -> Output: ${outputPath}`);
// Verify
const pdf2 = await PDF.load(savedBytes);
const form2 = pdf2.getForm();
const cbs2 = form2!.getCheckboxes();
// States should be toggled from original
for (let i = 0; i < Math.min(checkboxes.length, cbs2.length); i++) {
// We toggled all, so states should differ from a fresh load
// (Note: This is a weak test since we don't know original states)
expect(typeof cbs2[i].isChecked()).toBe("boolean");
}
});
it("incremental save with embedded font", async () => {
const pdfBytes = await loadFixture("forms", "sample_form.pdf");
const fontBytes = await loadFixture("fonts", "ttf/LiberationSans-Regular.ttf");
const pdf = await PDF.load(pdfBytes);
const form = pdf.getForm();
expect(form).not.toBeNull();
// Embed font and use it
const font = pdf.embedFont(fontBytes);
const acroForm = form!.acroForm();
acroForm.setDefaultFont(font);
// Fill a field
const stateField = form!.getTextField("STATE");
stateField!.setValue("TX");
form!.updateAppearances();
// Try incremental save with embedded font
const savedBytes = await pdf.save({ incremental: true });
const outputPath = await saveTestOutput("forms/incremental-embedded-font.pdf", savedBytes);
console.log(` -> Output: ${outputPath}`);
console.log(` Original: ${pdfBytes.length}, Saved: ${savedBytes.length}`);
// Verify
const pdf2 = await PDF.load(savedBytes);
const form2 = pdf2.getForm();
expect(form2!.getTextField("STATE")!.getValue()).toBe("TX");
});
});
// ─────────────────────────────────────────────────────────────────────────────
// Flatten Tests with Output
// ─────────────────────────────────────────────────────────────────────────────
describe("Form Integration: Flatten with Output", () => {
it("flattens form with embedded font and saves", async () => {
const pdfBytes = await loadFixture("forms", "sample_form.pdf");
const fontBytes = await loadFixture("fonts", "ttf/LiberationSans-Regular.ttf");
const pdf = await PDF.load(pdfBytes);
const form = pdf.getForm();
expect(form).not.toBeNull();
// Embed font
const font = pdf.embedFont(fontBytes);
// Fill fields with embedded font
const acroForm = form!.acroForm();
acroForm.setDefaultFont(font);
acroForm.setDefaultFontSize(11);
for (const field of form!.getTextFields()) {
if (!field.isReadOnly()) {
field.setValue("Flattened Value");
}
}
// Check all checkboxes
for (const cb of form!.getCheckboxes()) {
cb.check();
}
// Flatten
form!.flatten();
const savedBytes = await pdf.save();
const outputPath = await saveTestOutput("forms/flatten-embedded-font.pdf", savedBytes);
console.log(` -> Output: ${outputPath}`);
// Verify form is gone
const pdf2 = await PDF.load(savedBytes);
const form2 = pdf2.getForm();
if (form2) {
expect(form2.getFields().length).toBe(0);
}
});
it("flattens form with font options", async () => {
// Use sample_form.pdf which has known good structure
const pdfBytes = await loadFixture("forms", "sample_form.pdf");
const fontBytes = await loadFixture("fonts", "ttf/LiberationSans-Regular.ttf");
const pdf = await PDF.load(pdfBytes);
const form = pdf.getForm();
if (!form || form.getFields().length === 0) {
console.log(" Skipping: form has no fields");
return;
}
// Embed font
const font = pdf.embedFont(fontBytes);
// Fill some fields
for (const field of form.getTextFields()) {
if (!field.isReadOnly()) {
field.setValue("Font Option Test");
}
}
// Flatten with font options
form.flatten({ font, fontSize: 12 });
const savedBytes = await pdf.save();
const outputPath = await saveTestOutput("forms/flatten-font-options.pdf", savedBytes);
console.log(` -> Output: ${outputPath}`);
expect(savedBytes.length).toBeGreaterThan(0);
});
it("flattens fancy_fields form with all field types", async () => {
const pdfBytes = await loadFixture("forms", "fancy_fields.pdf");
const pdf = await PDF.load(pdfBytes);
const form = pdf.getForm();
expect(form).not.toBeNull();
// Fill various field types
for (const field of form!.getTextFields()) {
if (!field.isReadOnly()) {
field.setValue("Flattened");
}
}
for (const cb of form!.getCheckboxes()) {
try {
cb.check();
} catch {
// Some checkboxes may have different on values, skip them
}
}
for (const radio of form!.getRadioGroups()) {
const options = radio.getOptions();
if (options.length > 1) {
radio.setValue(options[1]); // Select second option
}
}
for (const dd of form!.getDropdowns()) {
const options = dd.getOptions();
if (options.length > 0) {
dd.setValue(options[0].value);
}
}
form!.flatten();
const savedBytes = await pdf.save();
const outputPath = await saveTestOutput("forms/flatten-fancy-fields.pdf", savedBytes);
console.log(` -> Output: ${outputPath}`);
expect(savedBytes.length).toBeGreaterThan(0);
// Verify flattening
const pdf2 = await PDF.load(savedBytes);
const form2 = pdf2.getForm();
if (form2) {
expect(form2.getFields().length).toBe(0);
}
});
});
// ─────────────────────────────────────────────────────────────────────────────
// Round-trip Integrity Tests
// ─────────────────────────────────────────────────────────────────────────────
describe("Form Integration: Round-trip Integrity", () => {
it("preserves all field values through save/load cycle", async () => {
const pdfBytes = await loadFixture("forms", "sample_form.pdf");
const pdf = await PDF.load(pdfBytes);
const form = pdf.getForm();
expect(form).not.toBeNull();
// Record original values and set new ones
const originalValues = new Map<string, string>();
const newValues = new Map<string, string>();
for (const field of form!.getTextFields()) {
originalValues.set(field.name, field.getValue());
if (!field.isReadOnly()) {
const newValue = `New_${field.name.slice(0, 5)}`;
field.setValue(newValue);
// Record what was actually set (getValue returns the truncated value if applicable)
newValues.set(field.name, field.getValue());
}
}
form!.updateAppearances();
// Save and reload
const savedBytes = await pdf.save();
await saveTestOutput("forms/round-trip-values.pdf", savedBytes);
const pdf2 = await PDF.load(savedBytes);
const form2 = pdf2.getForm();
// Verify new values persisted
for (const [name, expectedValue] of newValues) {
const field = form2!.getTextField(name);
if (field) {
expect(field.getValue()).toBe(expectedValue);
}
}
});
it("preserves checkbox states through multiple saves", async () => {
const pdfBytes = await loadFixture("forms", "sample_form.pdf");
let currentBytes: Uint8Array = new Uint8Array(pdfBytes);
// First cycle: check all
let pdf = await PDF.load(currentBytes);
let form = pdf.getForm();
for (const cb of form!.getCheckboxes()) {
cb.check();
}
form!.updateAppearances();
currentBytes = await pdf.save();
await saveTestOutput("forms/checkbox-round-trip-1.pdf", currentBytes);
// Verify all checked
pdf = await PDF.load(currentBytes);
form = pdf.getForm();
for (const cb of form!.getCheckboxes()) {
expect(cb.isChecked()).toBe(true);
}
// Second cycle: uncheck all
for (const cb of form!.getCheckboxes()) {
cb.uncheck();
}
form!.updateAppearances();
currentBytes = await pdf.save();
await saveTestOutput("forms/checkbox-round-trip-2.pdf", currentBytes);
// Verify all unchecked
pdf = await PDF.load(currentBytes);
form = pdf.getForm();
for (const cb of form!.getCheckboxes()) {
expect(cb.isChecked()).toBe(false);
}
});
it("embedded font survives round-trip", async () => {
const pdfBytes = await loadFixture("forms", "sample_form.pdf");
const fontBytes = await loadFixture("fonts", "ttf/LiberationSans-Regular.ttf");
const pdf = await PDF.load(pdfBytes);
const form = pdf.getForm();
// Embed font and use it
const font = pdf.embedFont(fontBytes);
const acroForm = form!.acroForm();
acroForm.setDefaultFont(font);
const stateField = form!.getTextField("STATE");
stateField!.setValue("FL");
form!.updateAppearances();
// First save
const bytes1 = await pdf.save();
await saveTestOutput("forms/font-round-trip-1.pdf", bytes1);
// Reload and modify again
const pdf2 = await PDF.load(bytes1);
const form2 = pdf2.getForm();
const stateField2 = form2!.getTextField("STATE");
expect(stateField2!.getValue()).toBe("FL");
stateField2!.setValue("GA");
form2!.updateAppearances();
const bytes2 = await pdf2.save();
await saveTestOutput("forms/font-round-trip-2.pdf", bytes2);
// Final verification
const pdf3 = await PDF.load(bytes2);
const form3 = pdf3.getForm();
expect(form3!.getTextField("STATE")!.getValue()).toBe("GA");
});
});
// ─────────────────────────────────────────────────────────────────────────────
// Unicode and Special Characters
// ─────────────────────────────────────────────────────────────────────────────
describe("Form Integration: Unicode Text", () => {
it("handles unicode text with embedded font", async () => {
const pdfBytes = await loadFixture("forms", "fancy_fields.pdf");
const fontBytes = await loadFixture("fonts", "ttf/LiberationSans-Regular.ttf");
const pdf = await PDF.load(pdfBytes);
const form = pdf.getForm();
expect(form).not.toBeNull();
// Embed font that supports more glyphs
const font = pdf.embedFont(fontBytes);
// Find a text field and set unicode value
const textFields = form!.getTextFields();
if (textFields.length > 0) {
const field = textFields[0];
field.setFont(font);
field.setValue("Hello Wörld Café");
form!.updateAppearances();
const savedBytes = await pdf.save();
const outputPath = await saveTestOutput("forms/unicode-text.pdf", savedBytes);
console.log(` -> Output: ${outputPath}`);
// Verify value preserved
const pdf2 = await PDF.load(savedBytes);
const form2 = pdf2.getForm();
const field2 = form2!.getTextField(field.name);
expect(field2!.getValue()).toBe("Hello Wörld Café");
}
});
it("handles CJK text with appropriate font", async () => {
const pdfBytes = await loadFixture("forms", "fancy_fields.pdf");
const pdf = await PDF.load(pdfBytes);
const form = pdf.getForm();
expect(form).not.toBeNull();
// Note: The font may not have CJK glyphs, but the value should still be stored
const textFields = form!.getTextFields();
if (textFields.length > 0) {
const field = textFields[0];
field.setValue("こんにちは世界");
const savedBytes = await pdf.save();
const outputPath = await saveTestOutput("forms/cjk-text-value.pdf", savedBytes);
console.log(` -> Output: ${outputPath}`);
// Value should be preserved even if appearance may have fallback glyphs
const pdf2 = await PDF.load(savedBytes);
const form2 = pdf2.getForm();
const field2 = form2!.getTextField(field.name);
expect(field2!.getValue()).toBe("こんにちは世界");
}
});
});
// ─────────────────────────────────────────────────────────────────────────────
// Edge Cases and Error Handling
// ─────────────────────────────────────────────────────────────────────────────
describe("Form Integration: Edge Cases", () => {
it("handles empty form gracefully", async () => {
const pdfBytes = await loadFixture("basic", "document.pdf");
const pdf = await PDF.load(pdfBytes);
const form = pdf.getForm();
// Document without form - should be null or have no fields
if (form) {
expect(form.getFields().length).toBe(0);
} else {
expect(form).toBeNull();
}
});
it("handles form with read-only fields", async () => {
const pdfBytes = await loadFixture("forms", "sample_form.pdf");
const pdf = await PDF.load(pdfBytes);
const form = pdf.getForm();
expect(form).not.toBeNull();
// Count read-only fields
const readOnlyFields = form!.getFields().filter(f => f.isReadOnly());
console.log(` Read-only fields: ${readOnlyFields.length}`);
// Attempt to fill - should skip read-only
const result = form!.fill({
STATE: "CA",
CITY: "Los Angeles",
});
console.log(` Filled: ${result.filled.join(", ")}, Skipped: ${result.skipped.join(", ")}`);
form!.updateAppearances();
const savedBytes = await pdf.save();
await saveTestOutput("forms/with-readonly.pdf", savedBytes);
expect(savedBytes.length).toBeGreaterThan(0);
});
it("handles comb fields correctly", async () => {
const pdfBytes = await loadFixture("forms", "with_combed_fields.pdf");
const pdf = await PDF.load(pdfBytes);
const form = pdf.getForm();
if (!form) {
console.log(" Skipping: no form found");
return;
}
// Find comb fields (fields with maxLength and comb flag)
const textFields = form.getTextFields();
const combFields = textFields.filter(f => f.isComb);
console.log(` Comb fields found: ${combFields.length}`);
for (const field of combFields) {
if (field.isReadOnly()) {
continue;
}
const maxLen = field.maxLength ?? 10;
field.setValue("A".repeat(Math.min(maxLen, 5)));
}
form.updateAppearances();
const savedBytes = await pdf.save();
const outputPath = await saveTestOutput("forms/comb-fields.pdf", savedBytes);
console.log(` -> Output: ${outputPath}`);
expect(savedBytes.length).toBeGreaterThan(0);
});
it("reuses valid registered existing fonts for appearance generation", async () => {
const pdfBytes = await loadFixture("forms", "with_combed_fields.pdf");
const pdf = await PDF.load(pdfBytes);
const form = pdf.getForm();
expect(form).not.toBeNull();
const targetField = form!
.getTextFields()
.find(field => field.alternateName === "6. Certification. Name.");
expect(targetField).toBeDefined();
targetField!.setValue("Jane Doe");
form!.updateAppearances();
const savedBytes = await pdf.save();
const pdf2 = await PDF.load(savedBytes);
const field2 = pdf2
.getForm()!
.getTextFields()
.find(field => field.alternateName === "6. Certification. Name.");
expect(field2).toBeDefined();
expect(field2!.getValue()).toBe("Jane Doe");
const appearance = field2!.getWidgets()[0].getNormalAppearance();
expect(appearance).not.toBeNull();
const streamContent = new TextDecoder().decode(appearance!.getDecodedData());
expect(streamContent).toContain("/HeBo");
expect(streamContent).not.toContain("/Helv");
expect(streamContent).toContain("(Jane Doe) Tj");
});
it("skips unusable field fonts and reuses a later registered font", async () => {
const pdfBytes = await loadFixture("forms", "pdfjs/bug1669099.pdf");
const pdf = await PDF.load(pdfBytes);
const form = pdf.getForm();
expect(form).not.toBeNull();
const targetField = form!.getTextField("_e");
expect(targetField).not.toBeNull();
targetField!.setValue("Visible text");
form!.updateAppearances();
const savedBytes = await pdf.save();
const pdf2 = await PDF.load(savedBytes);
const field2 = pdf2.getForm()!.getTextField("_e");
expect(field2).not.toBeNull();
expect(field2!.getValue()).toBe("Visible text");
const appearance = field2!.getWidgets()[0].getNormalAppearance();
expect(appearance).not.toBeNull();
const streamContent = new TextDecoder().decode(appearance!.getDecodedData());
// Original /DA uses an unusable anonymous font name ("/"). We should
// skip it and reuse the later registered OpenSans font instead.
expect(streamContent).toContain("/Fo2");
expect(streamContent).not.toContain("/Helv");
expect(streamContent).not.toContain("\n/ 12.00000 Tf");
expect(streamContent).toContain("Visible text");
});
it("reuses existing fonts for choice field appearances", async () => {
const pdfBytes = await loadFixture("forms", "pdfjs/annotation-choice-widget.pdf");
const pdf = await PDF.load(pdfBytes);
const form = pdf.getForm();
expect(form).not.toBeNull();
const dropdown = form!
.acroForm()
.getFields()
.find(field => field.type === "dropdown" && field.alternateName === "Combo box");
expect(dropdown).toBeInstanceOf(DropdownField);
const comboBox = dropdown as DropdownField;
comboBox.setValue("Amet");
form!.updateAppearances();
const savedBytes = await pdf.save();
const pdf2 = await PDF.load(savedBytes);
const dropdown2 = pdf2
.getForm()!
.acroForm()
.getFields()
.find(field => field.type === "dropdown" && field.alternateName === "Combo box");
expect(dropdown2).toBeInstanceOf(DropdownField);
const appearance = (dropdown2 as DropdownField).getWidgets()[0].getNormalAppearance();
expect(appearance).not.toBeNull();
const streamContent = new TextDecoder().decode(appearance!.getDecodedData());
expect(streamContent).toContain("/MyriadPro-Regular");
expect(streamContent).not.toContain("/Helv");
expect(streamContent).toContain("(Amet) Tj");
});
it("reuses valid Type0 fonts for button captions", async () => {
const pdfBytes = await loadFixture("forms", "pdfjs/issue15053.pdf");
const pdf = await PDF.load(pdfBytes);
const form = pdf.getForm();
expect(form).not.toBeNull();
const buttonField = form!
.acroForm()
.getFields()
.find(field => field.type === "button" && field.name === "Button2");
expect(buttonField).toBeDefined();
buttonField!.setFont(form!.acroForm().getExistingFont("/KozMinPr6N-Regular")!);
buttonField!.needsAppearanceUpdate = true;
form!.updateAppearances();
const savedBytes = await pdf.save();
const pdf2 = await PDF.load(savedBytes);
const buttonField2 = pdf2
.getForm()!
.acroForm()
.getFields()
.find(field => field.type === "button" && field.name === "Button2");
expect(buttonField2).toBeDefined();
const appearance = buttonField2!.getWidgets()[0].getNormalAppearance();
expect(appearance).not.toBeNull();
const streamContent = new TextDecoder().decode(appearance!.getDecodedData());
expect(streamContent).toContain("/KozMinPr6N-Regular");
expect(streamContent).not.toContain("/Helv");
expect(streamContent).toContain("<0042007500740074006F006E0031> Tj");
});
it("handles multiline text fields", async () => {
const pdfBytes = await loadFixture("forms", "sample_form.pdf");
const pdf = await PDF.load(pdfBytes);
const form = pdf.getForm();
expect(form).not.toBeNull();
const textFields = form!.getTextFields();
const multilineFields = textFields.filter(f => f.isMultiline);
console.log(` Multiline fields: ${multilineFields.length}`);
for (const field of multilineFields) {