-
-
Notifications
You must be signed in to change notification settings - Fork 172
/
pdflibAddPlaceholder.js
211 lines (199 loc) · 7.78 KB
/
pdflibAddPlaceholder.js
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
import PDFKitReferenceMock from './pdfkitReferenceMock'
import { DEFAULT_BYTE_RANGE_PLACEHOLDER, DEFAULT_SIGNATURE_LENGTH } from './const'
import {
PDFDocument,
StandardFonts,
PDFWriter,
PDFDict,
PDFName,
PDFArray,
PDFString,
PDFNumber,
PDFHexString,
PDFContentStream,
PDFContext,
drawText,
drawRectangle,
drawOptions,
degrees,
rgb
} from 'pdf-lib'
const pdflibAddPlaceholder = async ({
pdfBuffer,
infoSignature,
signatureLength = DEFAULT_SIGNATURE_LENGTH,
byteRangePlaceholder = DEFAULT_BYTE_RANGE_PLACEHOLDER,
}) => {
let pdfDoc
try {
pdfBuffer = pdfBuffer.toString('base64')
pdfDoc = await PDFDocument.load(pdfBuffer)
} catch (err) {
if (err.message.includes('encrypted')) {
throw new SignPdfError('Problem loading PDF, PDF encrypted', SignPdfError.TYPE_PARSE)
} else {
throw err
}
}
const date = new Date()
const arrayByteRange = PDFArray.withContext(pdfDoc.context)
arrayByteRange.push(PDFNumber.of(0))
arrayByteRange.push(PDFName.of(byteRangePlaceholder))
arrayByteRange.push(PDFName.of(byteRangePlaceholder))
arrayByteRange.push(PDFName.of(byteRangePlaceholder))
const signatureDictMap = new Map()
signatureDictMap.set(PDFName.Type, PDFName.of('Sig'))
signatureDictMap.set(PDFName.of('Filter'), PDFName.of('Adobe.PPKLite'))
signatureDictMap.set(PDFName.of('SubFilter'), PDFName.of('adbe.pkcs7.detached'))
signatureDictMap.set(PDFName.of('ByteRange'), arrayByteRange)
signatureDictMap.set(
PDFName.of('Contents'),
PDFHexString.of('0'.repeat(signatureLength))
)
signatureDictMap.set(PDFName.of('Reason'), PDFString.of(infoSignature.reason))
signatureDictMap.set(PDFName.of('M'), PDFString.fromDate(date))
signatureDictMap.set(
PDFName.of('ContactInfo'),
PDFString.of(infoSignature.contactInfo || '')
)
signatureDictMap.set(PDFName.of('Name'), PDFString.of(infoSignature.name || ''))
signatureDictMap.set(PDFName.of('Location'), PDFString.of(infoSignature.location || ''))
const signatureDict = PDFDict.fromMapWithContext(signatureDictMap, pdfDoc.context)
// Check if pdf already contains acroform field
const acroFormPosition = pdfBuffer.lastIndexOf('/Type /AcroForm')
const isAcroFormExists = acroFormPosition !== -1
let fieldIds = []
let acroFormId
if (isAcroFormExists) {
const pdfSlice = pdfBuffer.slice(acroFormPosition - 12)
const acroForm = pdfSlice.slice(0, pdfSlice.indexOf('endobj')).toString()
const acroFormFirsRow = acroForm.split('\n')[0]
acroFormId = parseInt(acroFormFirsRow.split(' ')[0])
const acroFormFields = acroForm.slice(acroForm.indexOf('/Fields [') + 9, acroForm.indexOf(']'))
fieldIds = acroFormFields
.split(' ')
.filter((element, index) => index % 3 === 0)
.map(fieldId => new PDFKitReferenceMock(fieldId))
}
const signatureName = 'Signature'
const info = (infoSignature.name || 'Signed') + '\n' + date.toISOString()
if (!infoSignature.positionBBox || !infoSignature.positionBBox.left ||
!infoSignature.positionBBox.bottom || !infoSignature.positionBBox.right ||
!infoSignature.positionBBox.top ) {
infoSignature.positionBBox = {
left: 0,
bottom: 0,
right: 200,
top: 50
}
}
const sigAppearanceStreamMapDict = new Map()
// const FontHelvetica = pdfDoc.embedStandardFont(StandardFonts.Helvetica)
// const resourcesMap = new Map()
// const fontMap = new Map()
// fontMap.set(PDFName.of('Helvetica'), FontHelvetica)
// resourcesMap.set(PDFName.Font, PDFDict.fromMapWithContext(fontMap, pdfDoc.context))
// sigAppearanceStreamMapDict.set(
// PDFName.of('Resources'),
// PDFDict.fromMapWithContext(resourcesMap, pdfDoc.context)
// )
sigAppearanceStreamMapDict.set(PDFName.Type, PDFName.XObject)
sigAppearanceStreamMapDict.set(PDFName.of('Subtype'), PDFName.of('Form'))
// Define a content stream that defines how the signature field should appear
// on the PDF. - Table 95 of the PDF specification.
const sigAppearanceStream = PDFContentStream.of(
PDFDict.fromMapWithContext(sigAppearanceStreamMapDict, pdfDoc.context),
drawRectangle({
x: PDFNumber.of(infoSignature.positionBBox.left),
y: PDFNumber.of(infoSignature.positionBBox.bottom),
width: PDFNumber.of(infoSignature.positionBBox.right),
height: PDFNumber.of(infoSignature.positionBBox.top),
color: rgb(0.95, 0.95, 0.95),
borderWidth: 3,
borderColor: rgb(0, 0, 0),
rotate: degrees(0),
xSkew: degrees(0),
ySkew: degrees(0)
})
)
drawText(info, {
x: PDFNumber.of(10),
y: PDFNumber.of(15),
font: 'Helvetica',
size: PDFNumber.of(15),
color: rgb(0.5, 0.5, 0.5),
rotate: degrees(0),
xSkew: degrees(0),
ySkew: degrees(0)
}).forEach(x => { sigAppearanceStream.push(x) })
drawRectangle({
x: PDFNumber.of(4),
y: PDFNumber.of(4),
width: PDFNumber.of(192),
height: PDFNumber.of(2),
color: rgb(0.5, 0.5, 0.5),
rotate: degrees(0),
borderWidth: 0,
borderColor: rgb(0, 0, 0),
xSkew: degrees(0),
ySkew: degrees(0)
}).forEach(x => { sigAppearanceStream.push(x) })
const sigAppearanceStreamRef = pdfDoc.context.register(sigAppearanceStream)
// Define the signature widget annotation - Table 164
const widgetDictMap = new Map()
const APMap = new Map()
const arrayRect = PDFArray.withContext(pdfDoc.context)
arrayRect.push(PDFNumber.of(50))
arrayRect.push(PDFNumber.of(50))
arrayRect.push(PDFNumber.of(300))
arrayRect.push(PDFNumber.of(100))
APMap.set(PDFName.of('N'), sigAppearanceStreamRef)
widgetDictMap.set(PDFName.Type, PDFName.of('Annot'))
widgetDictMap.set(PDFName.of('Subtype'), PDFName.of('Widget'))
widgetDictMap.set(PDFName.of('FT'), PDFName.of('Sig'))
widgetDictMap.set(PDFName.of('Rect'), arrayRect)
widgetDictMap.set(PDFName.of('V'), signatureDict)
widgetDictMap.set(PDFName.of('T'), PDFString.of(signatureName + (fieldIds.length + 1)))
widgetDictMap.set(PDFName.of('F'), PDFNumber.of(4))
widgetDictMap.set(PDFName.of('P'), pdfDoc.catalog.Pages().Kids().get(0))
widgetDictMap.set(PDFName.of('AP'), PDFDict.fromMapWithContext(APMap, pdfDoc.context))
const widgetDict = PDFDict.fromMapWithContext(widgetDictMap, pdfDoc.context)
const widgetDictRef = pdfDoc.context.register(widgetDict)
// Add our signature widget to the first page
// by parameter it should also be sent which pages you want to sign - ojo
const pages = pdfDoc.getPages()
const arrayAnnots = PDFArray.withContext(pdfDoc.context)
arrayAnnots.push(widgetDictRef)
pages[0].node.set(PDFName.Annots, arrayAnnots)
// Create an AcroForm object containing our signature widget
const formDictMap = new Map()
const arrayFields = PDFArray.withContext(pdfDoc.context)
arrayFields.push(widgetDictRef)
formDictMap.set(PDFName.of('SigFlags'), PDFNumber.of(3))
formDictMap.set(PDFName.of('Fields'), arrayFields)
const formDict = PDFDict.fromMapWithContext(formDictMap, pdfDoc.context)
pdfDoc.catalog.set(PDFName.of('AcroForm'), formDict)
let pdfDocBytes = await PDFWriter.forContext(pdfDoc.context).serializeToBuffer()
// Delete spaces in ByteRange
pdfDocBytes = Buffer.from(pdfDocBytes)
const byteRangePlaceholderContent = [
0,
`/${byteRangePlaceholder}`,
`/${byteRangePlaceholder}`,
`/${byteRangePlaceholder}`
]
const byteRangeString = `/ByteRange [ ${byteRangePlaceholderContent.join(' ')} ]`
let actualByteRange = `/ByteRange [${byteRangePlaceholderContent.join(' ')}]`
actualByteRange += ' '
const byteRangePos = pdfDocBytes.indexOf(byteRangeString)
if (byteRangePos !== -1) {
const byteRangeEnd = byteRangePos + byteRangeString.length
pdfDocBytes = Buffer.concat([
pdfDocBytes.slice(0, byteRangePos),
Buffer.from(actualByteRange),
pdfDocBytes.slice(byteRangeEnd),
])
}
return Buffer.from(pdfDocBytes)
}
export default pdflibAddPlaceholder