This repository has been archived by the owner on Oct 22, 2023. It is now read-only.
forked from OferElfassi/pdf2jsonForElectron
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpdfparser.js
185 lines (152 loc) · 5.5 KB
/
pdfparser.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
import fs from "fs";
import { readFile } from "fs/promises";
import { EventEmitter } from "events";
import PDFJS from "./lib/pdf.js";
import { ParserStream } from "./lib/parserstream.js";
import { kColors, kFontFaces, kFontStyles } from "./lib/pdfconst.js";
export default class PDFParser extends EventEmitter {
// inherit from event emitter
//public static
static get colorDict() {
return kColors;
}
static get fontFaceDict() {
return kFontFaces;
}
static get fontStyleDict() {
return kFontStyles;
}
//private static
static #maxBinBufferCount = 10;
static #binBuffer = {};
//private
#password = "";
#context = null; // service context object, only used in Web Service project; null in command line
#pdfFilePath = null; //current PDF file to load and parse, null means loading/parsing not started
#pdfFileMTime = null; // last time the current pdf was modified, used to recognize changes and ignore cache
#data = null; //if file read success, data is PDF content; if failed, data is "err" object
#PDFJS = null; //will be initialized in constructor
#processFieldInfoXML = false; //disable additional _fieldInfo.xml parsing and merging (do NOT set to true)
// constructor
constructor(context, needRawText, password) {
//call constructor for super class
super();
// private
// service context object, only used in Web Service project; null in command line
this.#context = context;
this.#pdfFilePath = null; //current PDF file to load and parse, null means loading/parsing not started
this.#pdfFileMTime = null; // last time the current pdf was modified, used to recognize changes and ignore cache
this.#data = null; //if file read success, data is PDF content; if failed, data is "err" object
this.#processFieldInfoXML = false; //disable additional _fieldInfo.xml parsing and merging (do NOT set to true)
this.#PDFJS = new PDFJS(needRawText);
this.#password = password;
}
//private methods, needs to invoked by [funcName].call(this, ...)
#onPDFJSParseDataReady(data) {
if (!data) {
//v1.1.2: data===null means end of parsed data
this.emit("pdfParser_dataReady", this.#data);
} else {
this.#data = { ...this.#data, ...data };
}
}
#onPDFJSParserDataError(err) {
this.#data = null;
this.emit("pdfParser_dataError", { parserError: err });
// this.emit("error", err);
}
#startParsingPDF(buffer) {
this.#data = {};
this.#PDFJS.on("pdfjs_parseDataReady", (data) =>
this.#onPDFJSParseDataReady(data)
);
this.#PDFJS.on("pdfjs_parseDataError", (err) =>
this.#onPDFJSParserDataError(err)
);
//v1.3.0 the following Readable Stream-like events are replacement for the top two custom events
this.#PDFJS.on("readable", (meta) => this.emit("readable", meta));
this.#PDFJS.on("data", (data) => this.emit("data", data));
this.#PDFJS.on("error", (err) => this.#onPDFJSParserDataError(err));
this.#PDFJS.parsePDFData(
buffer || PDFParser.#binBuffer[this.binBufferKey],
this.#password
);
}
#processBinaryCache() {
if (this.binBufferKey in PDFParser.#binBuffer) {
this.#startParsingPDF();
return true;
}
const allKeys = Object.keys(PDFParser.#binBuffer);
if (allKeys.length > PDFParser.#maxBinBufferCount) {
const idx = this.id % PDFParser.#maxBinBufferCount;
const key = allKeys[idx];
PDFParser.#binBuffer[key] = null;
delete PDFParser.#binBuffer[key];
}
return false;
}
//public getter
get data() {
return this.#data;
}
get binBufferKey() {
return this.#pdfFilePath + this.#pdfFileMTime;
}
//public APIs
createParserStream() {
return new ParserStream(this, { objectMode: true, bufferSize: 64 * 1024 });
}
async loadPDF(pdfFilePath, verbosity) {
this.#pdfFilePath = pdfFilePath;
try {
this.#pdfFileMTime = fs.statSync(pdfFilePath).mtimeMs;
if (this.#processFieldInfoXML) {
this.#PDFJS.tryLoadFieldInfoXML(pdfFilePath);
}
if (this.#processBinaryCache()) return;
PDFParser.#binBuffer[this.binBufferKey] = await readFile(pdfFilePath);
this.#startParsingPDF();
} catch (err) {
console.error(`Load Failed: ${pdfFilePath} - ${err}`);
this.emit("pdfParser_dataError", err);
}
}
// Introduce a way to directly process buffers without the need to write it to a temporary file
parseBuffer(pdfBuffer) {
this.#startParsingPDF(pdfBuffer);
}
getRawTextContent() {
return this.#PDFJS.getRawTextContent();
}
getRawTextContentStream() {
return ParserStream.createContentStream(this.getRawTextContent());
}
getAllFieldsTypes() {
return this.#PDFJS.getAllFieldsTypes();
}
getAllFieldsTypesStream() {
return ParserStream.createContentStream(this.getAllFieldsTypes());
}
getMergedTextBlocksIfNeeded() {
return this.#PDFJS.getMergedTextBlocksIfNeeded();
}
getMergedTextBlocksStream() {
return ParserStream.createContentStream(this.getMergedTextBlocksIfNeeded());
}
destroy() {
// invoked with stream transform process
super.removeAllListeners();
//context object will be set in Web Service project, but not in command line utility
if (this.#context) {
this.#context.destroy();
this.#context = null;
}
this.#pdfFilePath = null;
this.#pdfFileMTime = null;
this.#data = null;
this.#processFieldInfoXML = false; //disable additional _fieldInfo.xml parsing and merging (do NOT set to true)
this.#PDFJS.destroy();
this.#PDFJS = null;
}
}