forked from vanielf/pdf-lib
-
Notifications
You must be signed in to change notification settings - Fork 66
Expand file tree
/
Copy pathtest20.ts
More file actions
191 lines (183 loc) · 6.84 KB
/
test20.ts
File metadata and controls
191 lines (183 loc) · 6.84 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
import { Assets } from '../index.ts';
// @deno-types="../dummy.d.ts"
import {
PDFArray,
PDFDocument,
PDFHexString,
PDFInvalidObject,
PDFName,
PDFNumber,
PDFString,
rgb,
StandardFonts,
} from '../../../dist/pdf-lib.esm.js';
/**
* This test modifies the pdf adding a page and a placeholder for an electronic signature.
* It also deletes the first page of the PDF.
* The file should have an incremental update at the end, and the start of the file be exactly the original file.
*/
export default async (assets: Assets) => {
const pdfDoc = await PDFDocument.load(assets.pdfs.simple, {
forIncrementalUpdate: true,
});
// add a page (small one), with the visual representation of the digital signature, as a
// square box with text centered in it.
const page = pdfDoc.addPage([500, 200]);
// remove a page from de PDF
pdfDoc.removePage(0);
// embed fonts for the visual representation of the signature
const font = pdfDoc.embedStandardFont(StandardFonts.Helvetica);
const fontBold = pdfDoc.embedStandardFont(StandardFonts.HelveticaBoldOblique);
// couple of warning lines, about the signature and the visual representation
const signatureWarning =
'-- This is not the real signature of the document, just a a visual representation --';
const useLibreOffice =
'-- If your PDF viewer does not shows digital signatures, you can use "LibreOffice Draw" --';
const fontSize = 14;
const warningFontSize = 10;
// text in the visual representation maximun width
const textWidth = Math.max(
font.widthOfTextAtSize('Electronic Signature Test #20', fontSize),
fontBold.widthOfTextAtSize(useLibreOffice, warningFontSize),
);
// text line in the visual representation maximun height
const textHeight =
Math.max(
font.heightAtSize(fontSize),
fontBold.heightAtSize(warningFontSize),
) + 2;
// X position where the visual representation square starts
const startXpos = Math.trunc((page.getWidth() - textWidth) / 2);
// total vertical size of the visual representation
const visualRepHeight = textHeight * 4 + 20;
// rectangle containing the text
page.drawRectangle({
x: startXpos - 10,
y: page.getHeight() - visualRepHeight - 50,
width: textWidth + 20,
height: visualRepHeight,
borderWidth: 2,
borderColor: rgb(0.45, 0.45, 0.45),
});
let lineWidth = font.widthOfTextAtSize(
'Electronic Signature Test #20',
fontSize,
);
// vertial position where the text line will be outputted
let currentYPos = page.getHeight() - textHeight - 60;
// line #1
page.drawText('Electronic Signature Test #20', {
x: startXpos + Math.round((textWidth - lineWidth) / 2),
y: currentYPos,
size: fontSize,
font,
});
// timestamp of the signature, line #2
const signatureTimestamp = new Date().toISOString();
lineWidth = font.widthOfTextAtSize(signatureTimestamp, fontSize);
currentYPos -= textHeight;
page.drawText(signatureTimestamp, {
x: startXpos + Math.round((textWidth - lineWidth) / 2),
y: currentYPos,
size: fontSize,
font,
});
// first warning, line #3
lineWidth = fontBold.widthOfTextAtSize(signatureWarning, warningFontSize);
currentYPos -= textHeight;
page.drawText(signatureWarning, {
x: startXpos + Math.round((textWidth - lineWidth) / 2),
y: currentYPos,
size: warningFontSize,
font: fontBold,
});
// second warning, line #4
lineWidth = fontBold.widthOfTextAtSize(useLibreOffice, warningFontSize);
currentYPos -= textHeight;
page.drawText(useLibreOffice, {
x: startXpos + Math.round((textWidth - lineWidth) / 2),
y: currentYPos,
size: warningFontSize,
font: fontBold,
});
// Add an AcroForm or update the existing one
const acroForm = pdfDoc.catalog.getOrCreateAcroForm();
// Create a placeholder where the the last 3 parameters of the
// actual range will be replaced when signing is done.
const byteRange = PDFArray.withContext(pdfDoc.context);
byteRange.push(PDFNumber.of(0));
byteRange.push(PDFName.of('*********'));
byteRange.push(PDFName.of('*********'));
byteRange.push(PDFName.of('*********'));
// Fill the contents of the placeholder with 00s.
const placeholder = PDFHexString.of(String.fromCharCode(0).repeat(8096));
// Create a signature dictionary to be referenced in the signature widget.
const appBuild = { App: { Name: 'Test #20' } };
const signatureDict = pdfDoc.context.obj({
Type: 'Sig',
Filter: 'Adobe.PPKLite',
SubFilter: 'adbe.pkcs7.detached',
ByteRange: byteRange,
Contents: placeholder,
Reason: PDFString.of('Test #20'),
M: PDFString.fromDate(new Date()),
ContactInfo: PDFString.of('dabdala@adnsistemas.com.ar'),
Name: PDFString.of('David Abdala'),
Location: PDFString.of('Mendoza, Argentina'),
Prop_Build: {
Filter: { Name: 'Adobe.PPKLite' },
...appBuild,
},
});
// Register signatureDict as a PDFInvalidObject to prevent PDFLib from serializing it
// in an object stream.
const signatureBuffer = new Uint8Array(signatureDict.sizeInBytes());
signatureDict.copyBytesInto(signatureBuffer, 0);
const signatureObj = PDFInvalidObject.of(signatureBuffer);
const signatureDictRef = pdfDoc.context.register(signatureObj);
// Create the signature widget
const widgetRect = [0, 0, 0, 0];
const rect = PDFArray.withContext(pdfDoc.context);
widgetRect.forEach((c) => rect.push(PDFNumber.of(c)));
const apStream = pdfDoc.context.formXObject([], {
BBox: widgetRect,
Resources: {}, // Necessary to avoid Acrobat bug (see https://stackoverflow.com/a/73011571)
});
const widgetDict = pdfDoc.context.obj({
Type: 'Annot',
Subtype: 'Widget',
FT: 'Sig',
Rect: rect,
V: signatureDictRef,
T: PDFString.of('TestSig'),
TU: PDFString.of('Electronic Signature Test #20'),
F: 2,
P: page.ref,
AP: { N: pdfDoc.context.register(apStream) }, // Required for PDF/A compliance
});
const widgetDictRef = pdfDoc.context.register(widgetDict);
// Annotate the widget on the given page
let annotations = page.node.lookupMaybe(PDFName.of('Annots'), PDFArray);
if (typeof annotations === 'undefined') {
annotations = pdfDoc.context.obj([]);
}
annotations.push(widgetDictRef);
page.node.set(PDFName.of('Annots'), annotations);
let sigFlags: PDFNumber;
if (acroForm.dict.has(PDFName.of('SigFlags'))) {
// Already has some flags, will merge
sigFlags = acroForm.dict.get(PDFName.of('SigFlags')) as PDFNumber;
} else {
// Create blank flags
sigFlags = PDFNumber.of(0);
}
const updatedFlags = PDFNumber.of(sigFlags!.asNumber() | 1 | 2);
acroForm.dict.set(PDFName.of('SigFlags'), updatedFlags);
let fields = acroForm.dict.get(PDFName.of('Fields'));
if (!(fields instanceof PDFArray)) {
fields = pdfDoc.context.obj([]);
acroForm.dict.set(PDFName.of('Fields'), fields);
}
(fields as PDFArray).push(widgetDictRef);
return await pdfDoc.save({ useObjectStreams: false });
};