-
Notifications
You must be signed in to change notification settings - Fork 290
Expand file tree
/
Copy pathpdf-annotations.ts
More file actions
1099 lines (995 loc) · 32.7 KB
/
pdf-annotations.ts
File metadata and controls
1099 lines (995 loc) · 32.7 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
/**
* PDF Annotation Helpers
*
* Pure functions for annotation persistence (diff-based model),
* color conversion, and PDF annotation dict creation using pdf-lib.
*
* The diff-based model stores only changes relative to the PDF's
* native annotations: additions, removals, and modifications.
* This keeps localStorage small and preserves round-trip fidelity.
*/
import {
PDFDocument,
PDFDict,
PDFName,
PDFArray,
PDFNumber,
PDFString,
PDFHexString,
StandardFonts,
PDFTextField,
PDFCheckBox,
PDFDropdown,
PDFRadioGroup,
} from "pdf-lib";
// =============================================================================
// Types
// =============================================================================
export interface Rect {
x: number;
y: number;
width: number;
height: number;
}
export interface AnnotationBase {
id: string;
page: number;
}
export interface HighlightAnnotation extends AnnotationBase {
type: "highlight";
rects: Rect[];
color?: string;
content?: string;
}
export interface UnderlineAnnotation extends AnnotationBase {
type: "underline";
rects: Rect[];
color?: string;
}
export interface StrikethroughAnnotation extends AnnotationBase {
type: "strikethrough";
rects: Rect[];
color?: string;
}
export interface NoteAnnotation extends AnnotationBase {
type: "note";
x: number;
y: number;
content: string;
color?: string;
}
export interface RectangleAnnotation extends AnnotationBase {
type: "rectangle";
x: number;
y: number;
width: number;
height: number;
color?: string;
fillColor?: string;
rotation?: number;
}
export interface CircleAnnotation extends AnnotationBase {
type: "circle";
x: number;
y: number;
width: number;
height: number;
color?: string;
fillColor?: string;
}
export interface LineAnnotation extends AnnotationBase {
type: "line";
x1: number;
y1: number;
x2: number;
y2: number;
color?: string;
}
export interface FreetextAnnotation extends AnnotationBase {
type: "freetext";
x: number;
y: number;
content: string;
fontSize?: number;
color?: string;
}
export interface StampAnnotation extends AnnotationBase {
type: "stamp";
x: number;
y: number;
label: string;
color?: string;
rotation?: number;
}
export interface ImageAnnotation extends AnnotationBase {
type: "image";
x: number;
y: number;
width: number;
height: number;
imageData?: string;
imageUrl?: string;
mimeType?: string;
rotation?: number;
aspect?: "preserve" | "ignore";
}
export type PdfAnnotationDef =
| HighlightAnnotation
| UnderlineAnnotation
| StrikethroughAnnotation
| NoteAnnotation
| RectangleAnnotation
| CircleAnnotation
| LineAnnotation
| FreetextAnnotation
| StampAnnotation
| ImageAnnotation;
// =============================================================================
// Coordinate Conversion (model ↔ internal PDF coords)
// =============================================================================
/**
* Convert annotation coordinates from model space (top-left origin, Y↓)
* to internal PDF space (bottom-left origin, Y↑).
*
* Call this when receiving coordinates from the model via add/update_annotations.
*/
export function convertFromModelCoords(
def: PdfAnnotationDef,
pageHeight: number,
): PdfAnnotationDef {
switch (def.type) {
case "highlight":
case "underline":
case "strikethrough":
return {
...def,
rects: def.rects.map((r) => ({
...r,
y: pageHeight - r.y - r.height,
})),
};
case "note":
case "freetext":
case "stamp":
return { ...def, y: pageHeight - def.y };
case "rectangle":
case "circle":
case "image":
return { ...def, y: pageHeight - def.y - def.height };
case "line":
return {
...def,
y1: pageHeight - def.y1,
y2: pageHeight - def.y2,
};
}
}
/**
* Convert annotation coordinates from internal PDF space (bottom-left origin, Y↑)
* to model space (top-left origin, Y↓).
*
* Call this when presenting coordinates to the model (e.g. in context strings).
*/
export function convertToModelCoords(
def: PdfAnnotationDef,
pageHeight: number,
): PdfAnnotationDef {
// The conversion is its own inverse (same formula flips both ways)
return convertFromModelCoords(def, pageHeight);
}
// =============================================================================
// Diff-Based Persistence Model
// =============================================================================
/**
* Represents changes relative to the PDF's native annotations.
* Only this diff is stored in localStorage, keeping it small.
*/
export interface AnnotationDiff {
/** Annotations created by the user (not in the original PDF) */
added: PdfAnnotationDef[];
/** PDF annotation ref strings that the user deleted */
removed: string[];
/** Form field values the user filled in */
formFields: Record<string, string | boolean>;
}
/** Create an empty diff */
export function emptyDiff(): AnnotationDiff {
return { added: [], removed: [], formFields: {} };
}
/** Check if a diff has any changes */
export function isDiffEmpty(diff: AnnotationDiff): boolean {
return (
diff.added.length === 0 &&
diff.removed.length === 0 &&
Object.keys(diff.formFields).length === 0
);
}
/** Serialize diff to JSON string for localStorage */
export function serializeDiff(diff: AnnotationDiff): string {
return JSON.stringify(diff);
}
/** Deserialize diff from JSON string. Returns empty diff on error. */
export function deserializeDiff(json: string): AnnotationDiff {
try {
const parsed = JSON.parse(json);
return {
added: Array.isArray(parsed.added) ? parsed.added : [],
removed: Array.isArray(parsed.removed) ? parsed.removed : [],
formFields:
parsed.formFields && typeof parsed.formFields === "object"
? parsed.formFields
: {},
};
} catch {
return emptyDiff();
}
}
/**
* Merge PDF-native annotations with user diff to produce the final annotation set.
*
* @param pdfAnnotations - Annotations imported from the PDF file
* @param diff - User's local changes (additions, removals)
* @returns Merged annotation list
*/
export function mergeAnnotations(
pdfAnnotations: PdfAnnotationDef[],
diff: AnnotationDiff,
): PdfAnnotationDef[] {
const removedSet = new Set(diff.removed);
// Start with PDF annotations, filtering out removed ones
const merged = pdfAnnotations.filter((a) => !removedSet.has(a.id));
// Add user-created annotations
// If an added annotation has the same ID as a PDF annotation, the added one wins
const addedIds = new Set(diff.added.map((a) => a.id));
const result = merged.filter((a) => !addedIds.has(a.id));
result.push(...diff.added);
return result;
}
/**
* Compute a diff given the PDF-native annotations and the current full set.
*
* @param pdfAnnotations - Original annotations from the PDF
* @param currentAnnotations - Current full annotation set (after user edits)
* @param formFields - Current form field values
* @returns The diff to persist
*/
export function computeDiff(
pdfAnnotations: PdfAnnotationDef[],
currentAnnotations: PdfAnnotationDef[],
formFields: Map<string, string | boolean>,
baselineFormFields?: Map<string, string | boolean>,
): AnnotationDiff {
const pdfIds = new Set(pdfAnnotations.map((a) => a.id));
const currentIds = new Set(currentAnnotations.map((a) => a.id));
// Added: in current but not in PDF
const added = currentAnnotations.filter((a) => !pdfIds.has(a.id));
// Removed: in PDF but not in current
const removed = pdfAnnotations
.filter((a) => !currentIds.has(a.id))
.map((a) => a.id);
// Form fields: only values that differ from what's already in the PDF.
// Without a baseline, every filled field is a user edit (back-compat).
const formFieldsObj: Record<string, string | boolean> = {};
for (const [k, v] of formFields) {
if (baselineFormFields?.get(k) === v) continue;
formFieldsObj[k] = v;
}
// Fields present in baseline but cleared in current are also a change
if (baselineFormFields) {
for (const [k, v] of baselineFormFields) {
if (!formFields.has(k) && v !== "" && v !== false) {
formFieldsObj[k] = formFields.get(k) ?? "";
}
}
}
return { added, removed, formFields: formFieldsObj };
}
// =============================================================================
// Color Conversion
// =============================================================================
/**
* Parse a CSS color string to normalized RGB values (0-1 range).
* Supports hex (#rgb, #rrggbb, #rrggbbaa) and rgb()/rgba() notation.
*/
export function cssColorToRgb(
color: string,
): { r: number; g: number; b: number } | null {
// Parse hex colors
const hex = color.match(/^#([0-9a-f]{3,8})$/i);
if (hex) {
let h = hex[1];
if (h.length === 3) h = h[0] + h[0] + h[1] + h[1] + h[2] + h[2];
return {
r: parseInt(h.slice(0, 2), 16) / 255,
g: parseInt(h.slice(2, 4), 16) / 255,
b: parseInt(h.slice(4, 6), 16) / 255,
};
}
// Parse rgb/rgba
const rgbMatch = color.match(/rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)/);
if (rgbMatch) {
return {
r: parseInt(rgbMatch[1]) / 255,
g: parseInt(rgbMatch[2]) / 255,
b: parseInt(rgbMatch[3]) / 255,
};
}
return null;
}
/** Default colors for each annotation type */
export function defaultColor(type: PdfAnnotationDef["type"]): string {
switch (type) {
case "highlight":
return "#ffff00";
case "underline":
case "strikethrough":
return "#ff0000";
case "note":
return "#f5a623";
case "rectangle":
case "circle":
return "#0066cc";
case "line":
return "#333333";
case "freetext":
return "#333333";
case "stamp":
return "#cc0000";
case "image":
return "#00000000";
}
}
// =============================================================================
// PDF Annotation Dict Creation (pdf-lib low-level API)
// =============================================================================
/**
* Create a PDF color array [r, g, b] from a CSS color string.
* Falls back to the default color for the annotation type.
*/
function makePdfColor(
context: PDFDocument["context"],
cssColor: string | undefined,
annotType: PdfAnnotationDef["type"],
): PDFArray {
const rgb = cssColorToRgb(cssColor || defaultColor(annotType));
const { r, g, b } = rgb || { r: 0, g: 0, b: 0 };
const arr = PDFArray.withContext(context);
arr.push(PDFNumber.of(r));
arr.push(PDFNumber.of(g));
arr.push(PDFNumber.of(b));
return arr;
}
/** Create a PDF /Rect array [x1, y1, x2, y2] */
function makePdfRect(
context: PDFDocument["context"],
x: number,
y: number,
width: number,
height: number,
): PDFArray {
const arr = PDFArray.withContext(context);
arr.push(PDFNumber.of(x));
arr.push(PDFNumber.of(y));
arr.push(PDFNumber.of(x + width));
arr.push(PDFNumber.of(y + height));
return arr;
}
/**
* Create /QuadPoints array for markup annotations (Highlight, Underline, StrikeOut).
* Each rect → 8 numbers: x1,y1 (top-left), x2,y2 (top-right), x3,y3 (bottom-left), x4,y4 (bottom-right)
* PDF spec order: top-left, top-right, bottom-left, bottom-right
*/
function makeQuadPoints(
context: PDFDocument["context"],
rects: Rect[],
): PDFArray {
const arr = PDFArray.withContext(context);
for (const r of rects) {
const x1 = r.x;
const y1 = r.y;
const x2 = r.x + r.width;
const y2 = r.y + r.height;
// QuadPoints order: top-left, top-right, bottom-left, bottom-right
arr.push(PDFNumber.of(x1));
arr.push(PDFNumber.of(y2)); // top-left
arr.push(PDFNumber.of(x2));
arr.push(PDFNumber.of(y2)); // top-right
arr.push(PDFNumber.of(x1));
arr.push(PDFNumber.of(y1)); // bottom-left
arr.push(PDFNumber.of(x2));
arr.push(PDFNumber.of(y1)); // bottom-right
}
return arr;
}
/** Compute bounding box of an array of rects */
function boundingBox(rects: Rect[]): {
x: number;
y: number;
w: number;
h: number;
} {
if (rects.length === 0) return { x: 0, y: 0, w: 0, h: 0 };
let minX = Infinity,
minY = Infinity,
maxX = -Infinity,
maxY = -Infinity;
for (const r of rects) {
minX = Math.min(minX, r.x);
minY = Math.min(minY, r.y);
maxX = Math.max(maxX, r.x + r.width);
maxY = Math.max(maxY, r.y + r.height);
}
return { x: minX, y: minY, w: maxX - minX, h: maxY - minY };
}
/**
* Detect image MIME type from magic bytes.
*/
function detectImageMimeType(bytes: Uint8Array): "image/png" | "image/jpeg" {
// PNG magic: 0x89 0x50 0x4E 0x47
if (
bytes[0] === 0x89 &&
bytes[1] === 0x50 &&
bytes[2] === 0x4e &&
bytes[3] === 0x47
) {
return "image/png";
}
// JPEG magic: 0xFF 0xD8
return "image/jpeg";
}
/**
* Add proper PDF annotation objects to a pdf-lib PDFDocument.
* Creates /Type /Annot dictionaries with correct /Subtype for each annotation type.
* These are real PDF annotations, editable in Acrobat/Preview.
*/
export async function addAnnotationDicts(
pdfDoc: PDFDocument,
annotations: PdfAnnotationDef[],
): Promise<void> {
const context = pdfDoc.context;
const pages = pdfDoc.getPages();
for (const def of annotations) {
const pageIdx = def.page - 1;
if (pageIdx < 0 || pageIdx >= pages.length) continue;
const page = pages[pageIdx];
const dict = PDFDict.withContext(context);
dict.set(PDFName.of("Type"), PDFName.of("Annot"));
// Set /F (flags) = 4 (Print) so annotations print
dict.set(PDFName.of("F"), PDFNumber.of(4));
const color = makePdfColor(
context,
"color" in def ? def.color : undefined,
def.type,
);
switch (def.type) {
case "highlight":
case "underline":
case "strikethrough": {
const subtypeMap = {
highlight: "Highlight",
underline: "Underline",
strikethrough: "StrikeOut",
};
dict.set(PDFName.of("Subtype"), PDFName.of(subtypeMap[def.type]));
const bb = boundingBox(def.rects);
dict.set(
PDFName.of("Rect"),
makePdfRect(context, bb.x, bb.y, bb.w, bb.h),
);
dict.set(PDFName.of("QuadPoints"), makeQuadPoints(context, def.rects));
dict.set(PDFName.of("C"), color);
if (def.type === "highlight" && "content" in def && def.content) {
dict.set(PDFName.of("Contents"), PDFHexString.fromText(def.content));
}
break;
}
case "note": {
dict.set(PDFName.of("Subtype"), PDFName.of("Text"));
// Note icon is 24x24 points
dict.set(
PDFName.of("Rect"),
makePdfRect(context, def.x, def.y - 24, 24, 24),
);
dict.set(PDFName.of("Contents"), PDFHexString.fromText(def.content));
dict.set(PDFName.of("C"), color);
dict.set(PDFName.of("Name"), PDFName.of("Note"));
// Open = false (collapsed by default)
dict.set(PDFName.of("Open"), context.obj(false));
break;
}
case "rectangle":
case "circle": {
dict.set(
PDFName.of("Subtype"),
PDFName.of(def.type === "rectangle" ? "Square" : "Circle"),
);
dict.set(
PDFName.of("Rect"),
makePdfRect(context, def.x, def.y, def.width, def.height),
);
dict.set(PDFName.of("C"), color);
// Border style
const bs = PDFDict.withContext(context);
bs.set(PDFName.of("Type"), PDFName.of("Border"));
bs.set(PDFName.of("W"), PDFNumber.of(2));
bs.set(PDFName.of("S"), PDFName.of("S")); // Solid
dict.set(PDFName.of("BS"), bs);
if (def.fillColor) {
const fc = cssColorToRgb(def.fillColor);
if (fc) {
const icArr = PDFArray.withContext(context);
icArr.push(PDFNumber.of(fc.r));
icArr.push(PDFNumber.of(fc.g));
icArr.push(PDFNumber.of(fc.b));
dict.set(PDFName.of("IC"), icArr);
}
}
break;
}
case "line": {
dict.set(PDFName.of("Subtype"), PDFName.of("Line"));
// Rect is bounding box of the line
const lx = Math.min(def.x1, def.x2);
const ly = Math.min(def.y1, def.y2);
const lw = Math.abs(def.x2 - def.x1);
const lh = Math.abs(def.y2 - def.y1);
dict.set(
PDFName.of("Rect"),
makePdfRect(context, lx, ly, lw || 1, lh || 1),
);
// Line endpoints
const lineArr = PDFArray.withContext(context);
lineArr.push(PDFNumber.of(def.x1));
lineArr.push(PDFNumber.of(def.y1));
lineArr.push(PDFNumber.of(def.x2));
lineArr.push(PDFNumber.of(def.y2));
dict.set(PDFName.of("L"), lineArr);
dict.set(PDFName.of("C"), color);
break;
}
case "freetext": {
dict.set(PDFName.of("Subtype"), PDFName.of("FreeText"));
const fontSize = def.fontSize || 12;
// Estimate text dimensions
const textWidth = def.content.length * fontSize * 0.6;
const textHeight = fontSize * 1.4;
dict.set(
PDFName.of("Rect"),
makePdfRect(
context,
def.x,
def.y - textHeight,
textWidth,
textHeight,
),
);
dict.set(PDFName.of("Contents"), PDFHexString.fromText(def.content));
// Default appearance string (DA) — required for FreeText
const rgb = cssColorToRgb(def.color || defaultColor("freetext"));
const { r, g, b } = rgb || { r: 0, g: 0, b: 0 };
dict.set(
PDFName.of("DA"),
PDFString.of(`${r} ${g} ${b} rg /Helv ${fontSize} Tf`),
);
break;
}
case "stamp": {
dict.set(PDFName.of("Subtype"), PDFName.of("Stamp"));
const fontSize = 24;
// Match CSS padding: 4px top/bottom, 12px left/right
const padX = 12;
const padY = 4;
dict.set(PDFName.of("C"), color);
// Use a non-standard /Name so viewers like Preview.app don't
// substitute their own built-in stamp graphic
dict.set(PDFName.of("Name"), PDFName.of("#custom"));
dict.set(PDFName.of("Contents"), PDFHexString.fromText(def.label));
// Create a simple appearance stream so the stamp text is visible
const font = await pdfDoc.embedFont(StandardFonts.HelveticaBold);
const actualTextWidth = font.widthOfTextAtSize(def.label, fontSize);
const apRectW = actualTextWidth + padX * 2;
const apRectH = fontSize + padY * 2;
// Set rect to match appearance stream dimensions
dict.set(
PDFName.of("Rect"),
makePdfRect(context, def.x, def.y - apRectH, apRectW, apRectH),
);
// Build appearance stream content matching the CSS rendering:
// - 3pt border stroke
// - 0.6 opacity
// - text baseline positioned to visually center in the box
const rgb = cssColorToRgb(def.color || defaultColor("stamp"));
const { r, g, b } = rgb || { r: 0.8, g: 0, b: 0 };
// Font descent ≈ 20% of font size for Helvetica
const descent = fontSize * 0.2;
const textBaselineY = padY + descent;
const streamContent = [
`/GS0 gs`, // match CSS opacity: 0.6
`${r} ${g} ${b} RG`, // stroke color
`${r} ${g} ${b} rg`, // fill color
`3 w`, // line width (matches CSS border: 3px)
`1.5 1.5 ${apRectW - 3} ${apRectH - 3} re S`, // border rect inset by half line width
`BT`,
`/F1 ${fontSize} Tf`,
`${padX} ${textBaselineY} Td`,
`(${def.label.replace(/[()\\]/g, "\\$&")}) Tj`,
`ET`,
].join("\n");
// Compute rotation matrix if specified
let rotationMatrix: number[] | undefined;
if (def.rotation) {
const rad = (def.rotation * Math.PI) / 180;
const cos = Math.cos(rad);
const sin = Math.sin(rad);
// Rotation matrix around the center of the bounding box
const cx = apRectW / 2;
const cy = apRectH / 2;
// Translate to origin, rotate, translate back: [cos sin -sin cos tx ty]
const tx = cx - cos * cx + sin * cy;
const ty = cy - sin * cx - cos * cy;
rotationMatrix = [cos, sin, -sin, cos, tx, ty];
}
// Create ExtGState for opacity (ca = fill opacity, CA = stroke opacity)
const gsDict = PDFDict.withContext(context);
gsDict.set(PDFName.of("Type"), PDFName.of("ExtGState"));
gsDict.set(PDFName.of("ca"), PDFNumber.of(0.6));
gsDict.set(PDFName.of("CA"), PDFNumber.of(0.6));
const gsRef = context.register(gsDict);
// Build Resources dict with Font and ExtGState
const stampResDict = PDFDict.withContext(context);
const fontResDict = PDFDict.withContext(context);
fontResDict.set(PDFName.of("F1"), font.ref);
stampResDict.set(PDFName.of("Font"), fontResDict);
const gsResDict = PDFDict.withContext(context);
gsResDict.set(PDFName.of("GS0"), gsRef);
stampResDict.set(PDFName.of("ExtGState"), gsResDict);
// Create the appearance stream
const apStream = context.flateStream(streamContent, {
Type: "XObject",
Subtype: "Form",
BBox: [0, 0, apRectW, apRectH],
...(rotationMatrix ? { Matrix: rotationMatrix } : {}),
});
// Attach Resources to the stream dict
const apStreamDict = (apStream as any).dict || apStream;
apStreamDict.set(PDFName.of("Resources"), stampResDict);
const apRef = context.register(apStream);
// Create AP dictionary
const apDict = PDFDict.withContext(context);
apDict.set(PDFName.of("N"), apRef);
dict.set(PDFName.of("AP"), apDict);
break;
}
case "image": {
dict.set(PDFName.of("Subtype"), PDFName.of("Stamp"));
dict.set(
PDFName.of("Rect"),
makePdfRect(context, def.x, def.y, def.width, def.height),
);
dict.set(PDFName.of("Name"), PDFName.of("Image"));
if (def.imageData) {
// Detect mime type from magic bytes or use provided mimeType
const imgBytes = base64ToUint8Array(def.imageData);
const mime = def.mimeType || detectImageMimeType(imgBytes);
const embeddedImage =
mime === "image/jpeg"
? await pdfDoc.embedJpg(imgBytes)
: await pdfDoc.embedPng(imgBytes);
const imgW = def.width;
const imgH = def.height;
// Build appearance stream that draws the image
const streamContent = `q ${imgW} 0 0 ${imgH} 0 0 cm /Img Do Q`;
// Compute rotation matrix if specified
let rotationMatrix: number[] | undefined;
if (def.rotation) {
const rad = (def.rotation * Math.PI) / 180;
const cos = Math.cos(rad);
const sin = Math.sin(rad);
const cx = imgW / 2;
const cy = imgH / 2;
const tx = cx - cos * cx + sin * cy;
const ty = cy - sin * cx - cos * cy;
rotationMatrix = [cos, sin, -sin, cos, tx, ty];
}
// Create Resources dict with XObject containing the image
const xObjDict = PDFDict.withContext(context);
xObjDict.set(PDFName.of("Img"), embeddedImage.ref);
const resDict = PDFDict.withContext(context);
resDict.set(PDFName.of("XObject"), xObjDict);
const apStream = context.flateStream(streamContent, {
Type: "XObject",
Subtype: "Form",
BBox: [0, 0, imgW, imgH],
...(rotationMatrix ? { Matrix: rotationMatrix } : {}),
});
// Attach Resources to the stream dict
const apStreamDict = (apStream as any).dict || apStream;
apStreamDict.set(PDFName.of("Resources"), resDict);
const apRef = context.register(apStream);
const apDict = PDFDict.withContext(context);
apDict.set(PDFName.of("N"), apRef);
dict.set(PDFName.of("AP"), apDict);
}
break;
}
}
// Register the annotation dict and add to page
const annotRef = context.register(dict);
page.node.addAnnot(annotRef);
}
}
/**
* Build annotated PDF bytes from the original document.
* Applies user annotations and form fills, returns Uint8Array of the new PDF.
*/
export async function buildAnnotatedPdfBytes(
pdfBytes: Uint8Array,
annotations: PdfAnnotationDef[],
formFields: Map<string, string | boolean>,
): Promise<Uint8Array> {
const pdfDoc = await PDFDocument.load(pdfBytes, { ignoreEncryption: true });
// Add proper PDF annotation objects
await addAnnotationDicts(pdfDoc, annotations);
// Apply form fills. Dispatch on actual field type — getTextField(name) throws
// for dropdowns/radios, so the old try/catch silently dropped those on save.
if (formFields.size > 0) {
try {
const form = pdfDoc.getForm();
for (const [name, value] of formFields) {
const field = form.getFieldMaybe(name);
if (!field) continue;
if (field instanceof PDFCheckBox) {
if (value) field.check();
else field.uncheck();
} else if (field instanceof PDFRadioGroup) {
// The viewer stores pdf.js's buttonValue, which for PDFs with an
// /Opt array is a numeric index ("0","1","2") rather than the
// option label pdf-lib's select() expects. Try the label first,
// then fall back to indexing into getOptions().
const opts = field.getOptions();
const s = String(value);
if (opts.includes(s)) {
field.select(s);
} else {
const idx = Number(s);
if (Number.isInteger(idx) && idx >= 0 && idx < opts.length) {
field.select(opts[idx]);
}
// else: value is neither label nor index — leave unset
}
} else if (field instanceof PDFDropdown) {
// select() auto-enables edit mode for values outside getOptions(),
// so this works for both enumerated and free-text combos.
field.select(String(value));
} else if (field instanceof PDFTextField) {
field.setText(String(value));
}
// PDFButton, PDFOptionList, PDFSignature: no fill_form support yet
}
} catch {
// pdfDoc.getForm() throws if the PDF has no AcroForm
}
}
return pdfDoc.save();
}
// =============================================================================
// PDF.js Annotation Import
// =============================================================================
/**
* PDF.js annotation type constants (from AnnotationType enum).
* We only import types we support.
*/
const PDFJS_TYPE_MAP: Record<number, PdfAnnotationDef["type"]> = {
1: "note", // TEXT
3: "freetext", // FREETEXT
4: "line", // LINE
5: "rectangle", // SQUARE
6: "circle", // CIRCLE
9: "highlight", // HIGHLIGHT
10: "underline", // UNDERLINE
12: "strikethrough", // STRIKEOUT
13: "stamp", // STAMP
};
/**
* Convert a PDF.js annotation color array [r, g, b] (0-255) to CSS hex string.
*/
function pdfjsColorToHex(
color: Uint8ClampedArray | number[] | null | undefined,
): string | undefined {
if (!color || color.length < 3) return undefined;
const r = Math.round(color[0]);
const g = Math.round(color[1]);
const b = Math.round(color[2]);
const hex = ((r << 16) | (g << 8) | b).toString(16).padStart(6, "0");
return `#${hex}`;
}
/**
* Convert a PDF.js annotation rect [x1, y1, x2, y2] to our Rect format.
*/
function pdfjsRectToRect(rect: number[]): Rect {
return {
x: Math.min(rect[0], rect[2]),
y: Math.min(rect[1], rect[3]),
width: Math.abs(rect[2] - rect[0]),
height: Math.abs(rect[3] - rect[1]),
};
}
/**
* Build a stable annotation ID from pdf.js annotation data.
* Uses the annotation's ref (PDF object reference) if available,
* otherwise falls back to page + index.
*/
function makeAnnotationId(
// eslint-disable-next-line @typescript-eslint/no-explicit-any
ann: any,
pageNum: number,
index: number,
): string {
if (ann.ref) {
return `pdf-${ann.ref.num}-${ann.ref.gen}`;
}
if (ann.id) {
return `pdf-${ann.id}`;
}
return `pdf-${pageNum}-${index}`;
}
/**
* Convert a single PDF.js annotation object to our PdfAnnotationDef format.
* Returns null for unsupported annotation types.
*/
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export function importPdfjsAnnotation(
ann: any,
pageNum: number,
index: number,
): PdfAnnotationDef | null {
const ourType = PDFJS_TYPE_MAP[ann.annotationType];
if (!ourType) return null;
// Skip form widgets (they're handled separately by AnnotationLayer)
if (ann.annotationType === 20) return null;
const id = makeAnnotationId(ann, pageNum, index);
const color = pdfjsColorToHex(ann.color);
switch (ourType) {
case "highlight":
case "underline":
case "strikethrough": {
// pdf.js emits quadPoints as a FLAT Float32Array [x1,y1,...,x4,y4, …]
// (8 numbers per quad), NOT as nested arrays. Iterating it yields
// numbers, so the old `for (const qp of …) if (qp.length>=8)` never
// matched and every quad-based annotation was dropped (#506).
const rects: Rect[] = [];
const qp = ann.quadPoints as ArrayLike<number> | undefined;
if (qp && qp.length >= 8) {
for (let i = 0; i + 8 <= qp.length; i += 8) {
const xs = [qp[i], qp[i + 2], qp[i + 4], qp[i + 6]];
const ys = [qp[i + 1], qp[i + 3], qp[i + 5], qp[i + 7]];
const minX = Math.min(...xs);
const minY = Math.min(...ys);
rects.push({
x: minX,
y: minY,
width: Math.max(...xs) - minX,
height: Math.max(...ys) - minY,
});
}
}
if (rects.length === 0 && ann.rect) {
rects.push(pdfjsRectToRect(ann.rect));
}
if (rects.length === 0) return null;
const base = { id, page: pageNum, rects, color };
if (ourType === "highlight") {
return {
...base,
type: "highlight",
content: ann.contentsObj?.str || ann.contents || undefined,
};
}
return { ...base, type: ourType } as PdfAnnotationDef;
}
case "note": {
if (!ann.rect) return null;
const rect = pdfjsRectToRect(ann.rect);
return {
type: "note",
id,
page: pageNum,
x: rect.x,
y: rect.y + rect.height, // PDF.js rect y is bottom; note uses top point
content: ann.contentsObj?.str || ann.contents || "",
color,
};
}