-
-
Notifications
You must be signed in to change notification settings - Fork 251
Expand file tree
/
Copy pathhelper.ts
More file actions
283 lines (251 loc) · 7.65 KB
/
helper.ts
File metadata and controls
283 lines (251 loc) · 7.65 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
import { Matrix, Rotation, Rect, Size, PdfObjectSpec } from '@embedpdf/models';
import { PdfiumRuntimeMethods, PdfiumModule } from '@embedpdf/pdfium';
/**
* Read string from WASM heap
* @param wasmModule - pdfium wasm module instance
* @param readChars - function to read chars
* @param parseChars - function to parse chars
* @param defaultLength - default length of chars that needs to read
* @returns string from the heap
*
* @public
*/
export function readString(
wasmModule: PdfiumRuntimeMethods & PdfiumModule,
readChars: (buffer: number, bufferLength: number) => number,
parseChars: (buffer: number) => string,
defaultLength: number = 100,
): string {
let buffer = wasmModule.wasmExports.malloc(defaultLength);
for (let i = 0; i < defaultLength; i++) {
wasmModule.HEAP8[buffer + i] = 0;
}
const actualLength = readChars(buffer, defaultLength);
let str: string;
if (actualLength > defaultLength) {
wasmModule.wasmExports.free(buffer);
buffer = wasmModule.wasmExports.malloc(actualLength);
for (let i = 0; i < actualLength; i++) {
wasmModule.HEAP8[buffer + i] = 0;
}
readChars(buffer, actualLength);
str = parseChars(buffer);
} else {
str = parseChars(buffer);
}
wasmModule.wasmExports.free(buffer);
return str;
}
/**
* Read arraybyffer from WASM heap
* @param wasmModule - pdfium wasm module instance
* @param readChars - function to read chars
* @returns arraybuffer from the heap
*
* @public
*/
export function readArrayBuffer(
wasmModule: PdfiumRuntimeMethods & PdfiumModule,
readChars: (buffer: number, bufferLength: number) => number,
): ArrayBuffer {
const bufferSize = readChars(0, 0);
const bufferPtr = wasmModule.wasmExports.malloc(bufferSize);
readChars(bufferPtr, bufferSize);
const arrayBuffer = new ArrayBuffer(bufferSize);
const view = new DataView(arrayBuffer);
for (let i = 0; i < bufferSize; i++) {
view.setInt8(i, wasmModule.getValue(bufferPtr + i, 'i8'));
}
wasmModule.wasmExports.free(bufferPtr);
return arrayBuffer;
}
const RESERVED_INFO_KEYS = new Set([
'Title',
'Author',
'Subject',
'Keywords',
'Producer',
'Creator',
'CreationDate',
'ModDate',
'Trapped',
]);
export function isValidCustomKey(key: string): boolean {
// PDF Name object rules are looser than strings here, but keep it sane:
// - non-empty ASCII, no embedded NULs, avoid leading slash
if (!key || key.length > 127) return false;
if (RESERVED_INFO_KEYS.has(key)) return false;
if (key[0] === '/') return false;
// Keep ASCII-ish to avoid surprises; relax if you need.
for (let i = 0; i < key.length; i++) {
const c = key.charCodeAt(i);
if (c < 0x20 || c > 0x7e) return false;
}
return true;
}
const PDF_NAME_DELIMITERS = new Set(['(', ')', '<', '>', '[', ']', '{', '}', '/', '%', '#']);
const REGENERATING_ANNOTATION_KEYS = new Set([
'DA',
'DS',
'BS',
'BE',
'C',
'IC',
'LE',
'CL',
'Vertices',
'L',
'RD',
'IT',
]);
export function isValidPdfDictKey(key: string): boolean {
if (!key || key.length > 127) return false;
if (key[0] === '/') return false;
for (let i = 0; i < key.length; i++) {
const c = key.charCodeAt(i);
if (c < 0x21 || c > 0x7e) return false;
}
return true;
}
function formatPdfNumber(value: number): string {
if (!Number.isFinite(value)) {
throw new Error(`Invalid PDF number: ${value}`);
}
if (Object.is(value, -0)) {
return '0';
}
if (Number.isInteger(value)) {
return String(value);
}
let out = value.toString();
if (/e/i.test(out)) {
out = value.toFixed(12);
}
out = out.replace(/(?:\.0+|(?:(\.[0-9]*?)0+))$/, '$1');
if (out.endsWith('.')) {
out = out.slice(0, -1);
}
return out;
}
function encodePdfUtf16Hex(value: string): string {
let hex = 'FEFF';
for (let i = 0; i < value.length; i++) {
const codeUnit = value.charCodeAt(i);
hex += codeUnit.toString(16).toUpperCase().padStart(4, '0');
}
return `<${hex}>`;
}
function escapePdfName(name: string): string {
if (!name) {
throw new Error('PDF names must not be empty');
}
let out = '';
for (let i = 0; i < name.length; i++) {
const ch = name[i]!;
const code = name.charCodeAt(i);
const isRegular = code >= 0x21 && code <= 0x7e && !PDF_NAME_DELIMITERS.has(ch);
if (isRegular) {
out += ch;
continue;
}
if (code > 0xff) {
throw new Error(`PDF names must be ASCII/byte-oriented in v1: ${name}`);
}
out += `#${code.toString(16).toUpperCase().padStart(2, '0')}`;
}
return out;
}
function serializePdfObjectSpecInternal(value: PdfObjectSpec, nestedInDict: boolean): string | null {
switch (value.type) {
case 'null':
return nestedInDict ? null : 'null';
case 'boolean':
return value.value ? 'true' : 'false';
case 'number':
return formatPdfNumber(value.value);
case 'string':
return encodePdfUtf16Hex(value.value);
case 'name':
return `/${escapePdfName(value.value)}`;
case 'array': {
const items = value.value.map((item) => serializePdfObjectSpecInternal(item, false) ?? 'null');
return `[${items.join(' ')}]`;
}
case 'dict': {
const entries: string[] = [];
for (const [key, child] of Object.entries(value.value)) {
if (!isValidPdfDictKey(key)) {
throw new Error(`Invalid PDF dictionary key: ${key}`);
}
const serialized = serializePdfObjectSpecInternal(child, true);
if (serialized === null) {
continue;
}
entries.push(`/${escapePdfName(key)} ${serialized}`);
}
return entries.length > 0 ? `<< ${entries.join(' ')} >>` : '<< >>';
}
}
}
export function serializePdfObjectSpec(value: PdfObjectSpec): string {
return serializePdfObjectSpecInternal(value, false) ?? 'null';
}
export function shouldRegenerateAnnotationAppearanceForKey(key: string): boolean {
return REGENERATING_ANNOTATION_KEYS.has(key);
}
interface FormDrawParams {
startX: number;
startY: number;
formsWidth: number;
formsHeight: number;
scaleX: number;
scaleY: number;
}
export function computeFormDrawParams(
matrix: Matrix,
rect: Rect,
pageSize: Size,
rotation: Rotation,
): FormDrawParams {
const rectLeft = rect.origin.x;
const rectBottom = rect.origin.y;
const rectRight = rectLeft + rect.size.width;
const rectTop = rectBottom + rect.size.height;
const pageWidth = pageSize.width;
const pageHeight = pageSize.height;
// Extract the per-axis scale that the render matrix applies.
const scaleX = Math.hypot(matrix.a, matrix.b);
const scaleY = Math.hypot(matrix.c, matrix.d);
const swap = (rotation & 1) === 1;
const formsWidth = swap
? Math.max(1, Math.round(pageHeight * scaleX))
: Math.max(1, Math.round(pageWidth * scaleX));
const formsHeight = swap
? Math.max(1, Math.round(pageWidth * scaleY))
: Math.max(1, Math.round(pageHeight * scaleY));
let startX: number;
let startY: number;
switch (rotation) {
case Rotation.Degree0:
startX = -Math.round(rectLeft * scaleX);
startY = -Math.round(rectBottom * scaleY);
break;
case Rotation.Degree90:
startX = Math.round((rectTop - pageHeight) * scaleX);
startY = -Math.round(rectLeft * scaleY);
break;
case Rotation.Degree180:
startX = Math.round((rectRight - pageWidth) * scaleX);
startY = Math.round((rectTop - pageHeight) * scaleY);
break;
case Rotation.Degree270:
startX = -Math.round(rectBottom * scaleX);
startY = Math.round((rectRight - pageWidth) * scaleY);
break;
default:
startX = -Math.round(rectLeft * scaleX);
startY = -Math.round(rectBottom * scaleY);
break;
}
return { startX, startY, formsWidth, formsHeight, scaleX, scaleY };
}