-
Notifications
You must be signed in to change notification settings - Fork 1.2k
Expand file tree
/
Copy pathhelpers.js
More file actions
198 lines (184 loc) · 5.35 KB
/
helpers.js
File metadata and controls
198 lines (184 loc) · 5.35 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
/**
* @import PDFDocument from '../../lib/document';
*/
/**
* @typedef {object} TextStream
* @property {string} text
* @property {string} font
* @property {number} fontSize
* @property {number} x
* @property {number} y
*
* @typedef {string | Buffer} PDFDataItem
* @typedef {Array<PDFDataItem>} PDFData
*
* @typedef {object} PDFDataObject
* @property {PDFDataItem[]} items
*/
/**
* @param {PDFDocument} doc
* @return {PDFData}
*/
function logData(doc) {
const loggedData = [];
const originalMethod = doc._write;
doc._write = function (data) {
loggedData.push(data);
originalMethod.call(this, data);
};
return loggedData;
}
function escapeRegExp(string) {
return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); // $& means the whole matched string
}
function joinTokens(...args) {
let a = args.map((i) => escapeRegExp(i));
let r = new RegExp('^' + a.join('\\s*') + '$');
return r;
}
/**
* @description
* Returns an array of objects from the PDF data. Object items are surrounded by /\d 0 obj/ and 'endobj'.
* @param {PDFData} data
* @return {Array<PDFDataObject>}
*/
function getObjects(data) {
const objects = [];
let currentObject = null;
for (const item of data) {
if (item instanceof Buffer) {
if (currentObject) {
currentObject.items.push(item);
}
} else if (typeof item === 'string') {
if (/^\d+\s0\sobj/.test(item)) {
currentObject = { items: [] };
objects.push(currentObject);
} else if (item === 'endobj') {
currentObject = null;
} else if (currentObject) {
currentObject.items.push(item);
}
}
}
return objects;
}
/**
* Parse all text objects (multiple TJ) in a decoded stream.
* @param {string} decodedStream
* @return {TextStream[]}
*/
function parseTextStreams(decodedStream) {
const tjRegex = /\[([^\]]+)\]\s+TJ/g;
const fontRegex = /\/([A-Za-z0-9]+)\s+(\d+(?:\.\d+)?)\s+Tf/g;
const tmRegex =
/([+-]?\d+(?:\.\d+)?)\s+([+-]?\d+(?:\.\d+)?)\s+([+-]?\d+(?:\.\d+)?)\s+([+-]?\d+(?:\.\d+)?)\s+([+-]?\d+(?:\.\d+)?)\s+([+-]?\d+(?:\.\d+)?)\s+Tm/g;
const cmRegex =
/([+-]?\d+(?:\.\d+)?)\s+([+-]?\d+(?:\.\d+)?)\s+([+-]?\d+(?:\.\d+)?)\s+([+-]?\d+(?:\.\d+)?)\s+([+-]?\d+(?:\.\d+)?)\s+([+-]?\d+(?:\.\d+)?)\s+cm/g;
/** @type {TextStream[]} */
const results = [];
let tjMatch;
while ((tjMatch = tjRegex.exec(decodedStream)) !== null) {
const tjIndex = tjMatch.index;
let fMatch;
let lastFontName;
let lastFontSize;
fontRegex.lastIndex = 0;
while (
(fMatch = fontRegex.exec(decodedStream)) !== null &&
fMatch.index < tjIndex
) {
lastFontName = fMatch[1];
lastFontSize = parseFloat(fMatch[2]);
}
if (!lastFontName || !lastFontSize) continue;
// Find the nearest preceding text matrix (Tm) and current transformation (cm)
let tmMatch;
let lastTm = undefined;
tmRegex.lastIndex = 0;
while (
(tmMatch = tmRegex.exec(decodedStream)) !== null &&
tmMatch.index < tjIndex
) {
lastTm = tmMatch;
}
// Default to origin if no Tm found
let tx = 0;
let ty = 0;
if (lastTm) {
tx = parseFloat(lastTm[5]);
ty = parseFloat(lastTm[6]);
}
// Find the nearest preceding cm (CTM)
let cmMatch;
let lastCm = undefined;
cmRegex.lastIndex = 0;
while (
(cmMatch = cmRegex.exec(decodedStream)) !== null &&
cmMatch.index < tjIndex
) {
lastCm = cmMatch;
}
// Apply transform: [a b c d e f] to point (tx, ty)
let x = tx;
let y = ty;
if (lastCm) {
const a = parseFloat(lastCm[1]);
const b = parseFloat(lastCm[2]);
const c = parseFloat(lastCm[3]);
const d = parseFloat(lastCm[4]);
const e = parseFloat(lastCm[5]);
const f = parseFloat(lastCm[6]);
x = a * tx + c * ty + e;
y = b * tx + d * ty + f;
}
const arrayContent = tjMatch[1];
let text = '';
const hexMatches = [...arrayContent.matchAll(/<([0-9a-fA-F]+)>/g)];
for (const m of hexMatches) {
const hex = m[1];
for (let i = 0; i < hex.length; i += 2) {
// this is a simplified version
// the correct way is to retrieve the encoding from /Resources /Font dictionary and decode using it
// https://stackoverflow.com/a/29468049/5724645
const code = parseInt(hex.substring(i, i + 2), 16);
let char = String.fromCharCode(code);
if (code === 0x0a) char = '\n';
else if (code === 0x0d) char = '\r';
else if (code === 0x85) char = '...';
text += char;
}
}
results.push({ text, font: lastFontName, fontSize: lastFontSize, x, y });
}
return results;
}
/**
* Collect all PDF output from a document into a single binary string.
* @param {PDFDocument} doc
* @return {string}
*/
function collectPdf(doc) {
const data = logData(doc);
doc.end();
return data.map((d) => d.toString('binary')).join('');
}
/**
* Return object ids that are referenced but never defined in a PDF string.
* An empty result means no dangling references.
* @param {string} pdf
* @return {string[]}
*/
function missingObjects(pdf) {
const defined = [...pdf.matchAll(/(\d+) 0 obj/g)].map((m) => m[1]);
const refs = [...new Set([...pdf.matchAll(/(\d+) 0 R/g)].map((m) => m[1]))];
return refs.filter((r) => !defined.includes(r));
}
export {
logData,
joinTokens,
parseTextStreams,
getObjects,
collectPdf,
missingObjects,
};