pdfxtract 1.0.1 → 2.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli.js +250 -4
- package/package.json +2 -2
package/dist/cli.js
CHANGED
|
@@ -3,18 +3,264 @@ import { mkdir, readFile, readdir, stat, writeFile } from "node:fs/promises";
|
|
|
3
3
|
import { createRequire } from "node:module";
|
|
4
4
|
import { basename, dirname, extname, join, relative, resolve } from "node:path";
|
|
5
5
|
import { parseArgs } from "node:util";
|
|
6
|
-
import {
|
|
6
|
+
import { getDocumentProxy } from "unpdf";
|
|
7
7
|
|
|
8
|
+
//#region src/characters.ts
|
|
9
|
+
/**
|
|
10
|
+
* CJK Radicals Supplement (U+2E80–U+2EFF) mapped to the unified ideograph each one is drawn the same as, taken from Unicode 18.0 EquivalentUnifiedIdeograph.txt.
|
|
11
|
+
* NFKC leaves all but two of these alone, so they need a table. Kangxi Radicals (U+2F00–U+2FDF) need none: NFKC maps every one of them to the ideograph that file lists.
|
|
12
|
+
*/
|
|
13
|
+
const RADICALS_SUPPLEMENT = `
|
|
14
|
+
2E81:5382 2E82:4E5B 2E83:4E5A 2E84:4E59 2E85:4EBB 2E86:5182 2E87:20628
|
|
15
|
+
2E88:5200 2E89:5202 2E8A:535C 2E8B:353E 2E8C:5C0F 2E8D:5C0F 2E8E:5140
|
|
16
|
+
2E8F:5C23 2E90:5C22 2E91:21BC2 2E92:5DF3 2E93:5E7A 2E94:5F51 2E95:2B739
|
|
17
|
+
2E96:5FC4 2E97:5FC3 2E98:624C 2E99:6535 2E9B:65E1 2E9C:65E5 2E9D:6708
|
|
18
|
+
2E9E:6B7A 2E9F:6BCD 2EA0:6C11 2EA1:6C35 2EA2:6C3A 2EA3:706C 2EA4:722B
|
|
19
|
+
2EA5:722B 2EA6:4E2C 2EA7:725B 2EA8:72AD 2EA9:738B 2EAA:24D14 2EAB:76EE
|
|
20
|
+
2EAC:793A 2EAD:793B 2EAE:25AD7 2EAF:7CF9 2EB0:7E9F 2EB1:7F53 2EB2:7F52
|
|
21
|
+
2EB3:34C1 2EB4:5197 2EB5:2626B 2EB6:7F8A 2EB7:2634C 2EB8:2634B 2EB9:8002
|
|
22
|
+
2EBA:8080 2EBB:807F 2EBC:8089 2EBD:26951 2EBE:8279 2EBF:8279 2EC0:8279
|
|
23
|
+
2EC1:864E 2EC2:8864 2EC3:8980 2EC4:897F 2EC5:89C1 2EC6:89D2 2EC7:278B2
|
|
24
|
+
2EC8:8BA0 2EC9:8D1D 2ECA:27FB7 2ECB:8F66 2ECC:8FB6 2ECD:8FB6 2ECE:8FB6
|
|
25
|
+
2ECF:9091 2ED0:9485 2ED1:9577 2ED2:9578 2ED3:957F 2ED4:95E8 2ED5:28E0F
|
|
26
|
+
2ED6:961D 2ED7:96E8 2ED8:9752 2ED9:97E6 2EDA:9875 2EDB:98CE 2EDC:98DE
|
|
27
|
+
2EDD:98DF 2EDE:2967F 2EDF:98E0 2EE0:9963 2EE1:29810 2EE2:9A6C 2EE3:9AA8
|
|
28
|
+
2EE4:9B3C 2EE5:9C7C 2EE6:9E1F 2EE7:5364 2EE8:9EA6 2EE9:9EC4 2EEA:9EFE
|
|
29
|
+
2EEB:6589 2EEC:9F50 2EED:6B6F 2EEE:9F7F 2EEF:7ADC 2EF0:9F99 2EF1:9F9C
|
|
30
|
+
2EF2:4E80 2EF3:9F9F
|
|
31
|
+
`;
|
|
32
|
+
const SUPPLEMENT_EQUIVALENTS = new Map(RADICALS_SUPPLEMENT.trim().split(/\s+/).map((pair) => {
|
|
33
|
+
const [radical, ideograph] = pair.split(":").map((hex) => String.fromCodePoint(Number.parseInt(hex, 16)));
|
|
34
|
+
return [radical, ideograph];
|
|
35
|
+
}));
|
|
36
|
+
const RADICAL = /[⺀-]/gu;
|
|
37
|
+
const STRAY_CONTROL = /[\u0000-\u0008\u000E-\u001F\u007F]/g;
|
|
38
|
+
/**
|
|
39
|
+
* Fonts often share one glyph between a radical and the ideograph it looks like (macOS Hiragino does, so Chrome and Preview PDFs carry this), and the PDF's ToUnicode map may name the radical: "⽇" (U+2F47) where the page shows "日" (U+65E5).
|
|
40
|
+
* The two look alike, but searching for one never finds the other, so map each radical to its ideograph.
|
|
41
|
+
*/
|
|
42
|
+
function unifyRadicals(text) {
|
|
43
|
+
return text.replace(RADICAL, (radical) => SUPPLEMENT_EQUIVALENTS.get(radical) ?? radical.normalize("NFKC"));
|
|
44
|
+
}
|
|
45
|
+
/**
|
|
46
|
+
* Clean up characters PDF.js reports verbatim but that do not belong in plain text: CJK radicals standing in for ideographs, and control characters that some fonts map spacing glyphs to.
|
|
47
|
+
*/
|
|
48
|
+
function normalizeCharacters(text) {
|
|
49
|
+
return unifyRadicals(text.replace(STRAY_CONTROL, ""));
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
//#endregion
|
|
53
|
+
//#region src/reading-order.ts
|
|
54
|
+
/** Baselines closer than this many font sizes belong to the same line. */
|
|
55
|
+
const BASELINE_TOLERANCE = .3;
|
|
56
|
+
/**
|
|
57
|
+
* Runs whose horizontal extents come within this many font sizes of each
|
|
58
|
+
* other belong to the same line. It must stay below the narrowest gutter that
|
|
59
|
+
* separates columns, or columns sharing baselines would be merged.
|
|
60
|
+
*/
|
|
61
|
+
const ADJACENCY_TOLERANCE = .5;
|
|
62
|
+
/**
|
|
63
|
+
* How many of the most recently started lines a run may join. A run drawn out
|
|
64
|
+
* of order lands right after the line it belongs to, so a short look-back
|
|
65
|
+
* finds it while keeping pages made of thousands of scattered runs linear.
|
|
66
|
+
*/
|
|
67
|
+
const LOOK_BACK_LINES = 16;
|
|
68
|
+
/**
|
|
69
|
+
* A run moves ahead of an earlier one only if it ends left of where that one
|
|
70
|
+
* starts, give or take this many font sizes. Runs that overlap, such as a
|
|
71
|
+
* space kerned under the letter after it, keep the order they were drawn in.
|
|
72
|
+
*/
|
|
73
|
+
const CLEARANCE = .1;
|
|
74
|
+
/**
|
|
75
|
+
* A gap wider than this many font sizes reads as a space. Word spaces run
|
|
76
|
+
* about a quarter to a third; glyphs set solid, as in Japanese, leave none.
|
|
77
|
+
*/
|
|
78
|
+
const SPACE_GAP = .1;
|
|
79
|
+
function fontSize(run) {
|
|
80
|
+
return Math.hypot(run.transform[2], run.transform[3]);
|
|
81
|
+
}
|
|
82
|
+
function onSameBaseline(p, q) {
|
|
83
|
+
const scale = Math.max(fontSize(p), fontSize(q));
|
|
84
|
+
return Math.abs(p.transform[5] - q.transform[5]) <= BASELINE_TOLERANCE * scale;
|
|
85
|
+
}
|
|
86
|
+
/**
|
|
87
|
+
* PDF.js fills the gap between two runs with a space run, but the width it
|
|
88
|
+
* reports can overshoot the gap several times over (Chrome's Type 3 fonts do
|
|
89
|
+
* this), stretching the line across text in the next column. Measure each
|
|
90
|
+
* space run as the gap it fills instead: up to where the next run starts if
|
|
91
|
+
* that run continues the same baseline, and nothing otherwise.
|
|
92
|
+
*/
|
|
93
|
+
function measureSpaces(runs) {
|
|
94
|
+
const measured = [...runs];
|
|
95
|
+
let next;
|
|
96
|
+
for (let i = runs.length - 1; i >= 0; i--) {
|
|
97
|
+
const run = runs[i];
|
|
98
|
+
if (run.str === "") continue;
|
|
99
|
+
if (run.str.trim() !== "") {
|
|
100
|
+
next = run;
|
|
101
|
+
continue;
|
|
102
|
+
}
|
|
103
|
+
const gap = next && onSameBaseline(run, next) ? next.transform[4] - run.transform[4] : 0;
|
|
104
|
+
measured[i] = {
|
|
105
|
+
...run,
|
|
106
|
+
width: Math.max(0, gap)
|
|
107
|
+
};
|
|
108
|
+
}
|
|
109
|
+
return measured;
|
|
110
|
+
}
|
|
111
|
+
function startLine(lines, run, closed) {
|
|
112
|
+
const x = run.transform[4];
|
|
113
|
+
const line = {
|
|
114
|
+
baseline: run.transform[5],
|
|
115
|
+
size: fontSize(run),
|
|
116
|
+
left: x,
|
|
117
|
+
right: x + run.width,
|
|
118
|
+
runs: [{
|
|
119
|
+
x,
|
|
120
|
+
width: run.width,
|
|
121
|
+
str: run.str
|
|
122
|
+
}],
|
|
123
|
+
movable: run.dir === "ltr",
|
|
124
|
+
reordered: false,
|
|
125
|
+
closed,
|
|
126
|
+
eol: false
|
|
127
|
+
};
|
|
128
|
+
lines.push(line);
|
|
129
|
+
return line;
|
|
130
|
+
}
|
|
131
|
+
function findLine(lines, run) {
|
|
132
|
+
const [, , , , x, y] = run.transform;
|
|
133
|
+
const size = fontSize(run);
|
|
134
|
+
const oldest = Math.max(0, lines.length - LOOK_BACK_LINES);
|
|
135
|
+
for (let i = lines.length - 1; i >= oldest; i--) {
|
|
136
|
+
const line = lines[i];
|
|
137
|
+
if (line.closed) continue;
|
|
138
|
+
const scale = Math.max(size, line.size);
|
|
139
|
+
if (Math.abs(y - line.baseline) > BASELINE_TOLERANCE * scale) continue;
|
|
140
|
+
const reach = ADJACENCY_TOLERANCE * scale;
|
|
141
|
+
if (x > line.right + reach || x + run.width < line.left - reach) continue;
|
|
142
|
+
return line;
|
|
143
|
+
}
|
|
144
|
+
return void 0;
|
|
145
|
+
}
|
|
146
|
+
/** Put a run after every run it does not sit wholly to the left of. */
|
|
147
|
+
function insertRun(line, run) {
|
|
148
|
+
let at = line.runs.length;
|
|
149
|
+
if (line.movable) {
|
|
150
|
+
const clearance = CLEARANCE * line.size;
|
|
151
|
+
while (at > 0 && run.x + run.width <= line.runs[at - 1].x + clearance) at--;
|
|
152
|
+
}
|
|
153
|
+
if (at < line.runs.length) line.reordered = true;
|
|
154
|
+
line.runs.splice(at, 0, run);
|
|
155
|
+
}
|
|
156
|
+
function placeRun(lines, run) {
|
|
157
|
+
const [a, b, , , x] = run.transform;
|
|
158
|
+
const horizontal = a > 0 && Math.abs(b) <= Math.abs(a) * .001;
|
|
159
|
+
if (!horizontal || run.dir === "ttb") return startLine(lines, run, true);
|
|
160
|
+
const line = findLine(lines, run);
|
|
161
|
+
if (!line) return startLine(lines, run, false);
|
|
162
|
+
if (run.dir !== "ltr") line.movable = false;
|
|
163
|
+
line.size = Math.max(line.size, fontSize(run));
|
|
164
|
+
line.left = Math.min(line.left, x);
|
|
165
|
+
line.right = Math.max(line.right, x + run.width);
|
|
166
|
+
insertRun(line, {
|
|
167
|
+
x,
|
|
168
|
+
width: run.width,
|
|
169
|
+
str: run.str
|
|
170
|
+
});
|
|
171
|
+
return line;
|
|
172
|
+
}
|
|
173
|
+
function lineText(line) {
|
|
174
|
+
if (!line.reordered) return line.runs.map((run) => run.str).join("");
|
|
175
|
+
let text = "";
|
|
176
|
+
let end = Number.NEGATIVE_INFINITY;
|
|
177
|
+
for (const run of line.runs) {
|
|
178
|
+
if (run.str.trim() === "") continue;
|
|
179
|
+
if (text !== "" && run.x - end > SPACE_GAP * line.size) text += " ";
|
|
180
|
+
text += run.str;
|
|
181
|
+
end = Math.max(end, run.x + run.width);
|
|
182
|
+
}
|
|
183
|
+
return text;
|
|
184
|
+
}
|
|
185
|
+
/**
|
|
186
|
+
* Join a page's text runs in reading order.
|
|
187
|
+
*
|
|
188
|
+
* PDF.js reports runs in the order the content stream draws them, which is
|
|
189
|
+
* not always the order they are read: Chrome draws a line's emphasized words
|
|
190
|
+
* in a second pass, so "try nano now" comes out as "try now nano". Runs that
|
|
191
|
+
* sit on one baseline and touch horizontally are gathered into a line, and a
|
|
192
|
+
* run drawn later moves ahead of the runs it sits wholly to the left of.
|
|
193
|
+
* Lines keep the order they first appear in, so columns, tables and anything
|
|
194
|
+
* already in order come out as before.
|
|
195
|
+
*/
|
|
196
|
+
function orderPageText(runs) {
|
|
197
|
+
const lines = [];
|
|
198
|
+
let last;
|
|
199
|
+
for (const run of measureSpaces(runs)) {
|
|
200
|
+
if (run.str === "") {
|
|
201
|
+
if (run.hasEOL) (last ?? startLine(lines, run, true)).eol = true;
|
|
202
|
+
continue;
|
|
203
|
+
}
|
|
204
|
+
last = placeRun(lines, run);
|
|
205
|
+
if (run.hasEOL) last.eol = true;
|
|
206
|
+
}
|
|
207
|
+
return lines.map((line) => lineText(line) + (line.eol ? "\n" : "")).join("");
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
//#endregion
|
|
8
211
|
//#region src/converter.ts
|
|
9
212
|
const VERBOSITY_ERRORS = 0;
|
|
213
|
+
const LINE_BREAK_HYPHEN = /([A-Za-z]{2,})-\n([A-Za-z]{2,})/g;
|
|
214
|
+
const WORD_SEPARATOR = /[^A-Za-z'-]+/;
|
|
215
|
+
/**
|
|
216
|
+
* Words the document spells out without crossing a line break. Fragments left
|
|
217
|
+
* by hyphenation are dropped rather than flattened, so they cannot vouch for
|
|
218
|
+
* themselves when `dehyphenate` consults this set.
|
|
219
|
+
*/
|
|
220
|
+
function buildVocabulary(text) {
|
|
221
|
+
return new Set(text.replace(LINE_BREAK_HYPHEN, "\n").split(WORD_SEPARATOR).filter(Boolean).map((word) => word.toLowerCase()));
|
|
222
|
+
}
|
|
223
|
+
/**
|
|
224
|
+
* PDF.js reports every hyphen as U+002D, so one sitting before a line break is
|
|
225
|
+
* ambiguous: it may be typesetting hyphenation ("prob-\nlem") or part of a real
|
|
226
|
+
* compound ("machine-\nlearning"). Resolve each occurrence against the rest of
|
|
227
|
+
* the document, preferring whichever spelling is attested elsewhere. When
|
|
228
|
+
* neither is, keep the hyphen only if both halves stand alone as words.
|
|
229
|
+
*/
|
|
230
|
+
function dehyphenate(text) {
|
|
231
|
+
const vocabulary = buildVocabulary(text);
|
|
232
|
+
return text.replace(LINE_BREAK_HYPHEN, (_match, head, tail) => {
|
|
233
|
+
const joined = `${head}${tail}`;
|
|
234
|
+
const hyphenated = `${head}-${tail}`;
|
|
235
|
+
if (vocabulary.has(joined.toLowerCase())) return joined;
|
|
236
|
+
if (vocabulary.has(hyphenated.toLowerCase())) return hyphenated;
|
|
237
|
+
const halvesAreWords = vocabulary.has(head.toLowerCase()) && vocabulary.has(tail.toLowerCase());
|
|
238
|
+
return halvesAreWords ? hyphenated : joined;
|
|
239
|
+
});
|
|
240
|
+
}
|
|
241
|
+
async function extractPageText(pdf, pageNumber) {
|
|
242
|
+
const page = await pdf.getPage(pageNumber);
|
|
243
|
+
const { items } = await page.getTextContent();
|
|
244
|
+
return orderPageText(items.filter((item) => "str" in item).map((item) => ({
|
|
245
|
+
...item,
|
|
246
|
+
str: normalizeCharacters(item.str)
|
|
247
|
+
})));
|
|
248
|
+
}
|
|
249
|
+
/**
|
|
250
|
+
* Join pages the way unpdf's `extractText(..., { mergePages: true })` does:
|
|
251
|
+
* collapse whitespace but keep line breaks, with at most one blank line.
|
|
252
|
+
*/
|
|
253
|
+
function mergePages(pages) {
|
|
254
|
+
return pages.join("\n").replace(/[^\S\n]+/g, " ").replace(/ ?\n ?/g, "\n").replace(/\n{3,}/g, "\n\n");
|
|
255
|
+
}
|
|
10
256
|
async function convertPdf(pdfPath, txtPath) {
|
|
11
257
|
const buffer = await readFile(pdfPath);
|
|
12
258
|
const pdf = await getDocumentProxy(new Uint8Array(buffer), { verbosity: VERBOSITY_ERRORS });
|
|
13
259
|
try {
|
|
14
|
-
const {
|
|
15
|
-
await writeFile(txtPath,
|
|
260
|
+
const pages = await Promise.all(Array.from({ length: pdf.numPages }, (_, i) => extractPageText(pdf, i + 1)));
|
|
261
|
+
await writeFile(txtPath, dehyphenate(mergePages(pages)), "utf-8");
|
|
16
262
|
} finally {
|
|
17
|
-
pdf.destroy();
|
|
263
|
+
await pdf.loadingTask.destroy();
|
|
18
264
|
}
|
|
19
265
|
}
|
|
20
266
|
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "pdfxtract",
|
|
3
|
-
"version": "
|
|
3
|
+
"version": "2.0.1",
|
|
4
4
|
"description": "Recursively convert PDF files to TXT in a directory",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"bin": {
|
|
@@ -38,7 +38,7 @@
|
|
|
38
38
|
"url": "https://github.com/NaokiYazawa/pdfxtract/issues"
|
|
39
39
|
},
|
|
40
40
|
"dependencies": {
|
|
41
|
-
"unpdf": "^
|
|
41
|
+
"unpdf": "^1.8.1"
|
|
42
42
|
},
|
|
43
43
|
"devDependencies": {
|
|
44
44
|
"@biomejs/biome": "2.4.6",
|