forked from modesty/pdf2json
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpdf.js
296 lines (239 loc) · 8.49 KB
/
pdf.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
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
284
285
286
287
288
289
290
291
292
293
294
295
296
var nodeUtil = require("util"),
nodeEvents = require("events"),
fs = require('fs'),
_ = require('underscore'),
DOMParser = require('./../node_modules/xmldom').DOMParser,
PDFCanvas = require('./pdfcanvas.js'),
PDFUnit = require('./pdfunit.js'),
PDFField = require('./pdffield.js');
var _pdfjsFiles = [
'core.js',
'util.js',
'api.js',
'metadata.js',
'canvas.js',
'obj.js',
'function.js',
'charsets.js',
'colorspace.js',
'crypto.js',
'evaluator.js',
'fonts.js',
'glyphlist.js',
'image.js',
'metrics.js',
'parser.js',
'pattern.js',
'stream.js',
'worker.js',
'jpg.js'
];
//////replacing HTML5 canvas with PDFCanvas (in-memory canvas)
function createScratchCanvas(width, height) { return new PDFCanvas({}, width, height); }
var PDFJS = {};
var globalScope = {};
var _basePath = __dirname + "/pdfjs/";
var _fileContent = '';
_.each(_pdfjsFiles, function(fielName, idx) {
_fileContent += fs.readFileSync(_basePath + fielName, 'utf8');
});
eval(_fileContent);
////////////////////////////////start of helper classes
var PDFPageParser = (function () {
'use strict';
// private static
var _nextId = 1;
var _name = 'PDFPageParser';
var RenderingStates = {
INITIAL: 0,
RUNNING: 1,
PAUSED: 2,
FINISHED: 3
};
var _addField = function(field) {
if (!PDFField.isFormElement(field))
return;
var oneField = new PDFField(field, this.viewport, this.Fields, this.Boxsets);
oneField.processField();
};
// constructor
var cls = function (pdfPage, id, scale) {
nodeEvents.EventEmitter.call(this);
// private
var _id = _nextId++;
// public (every instance will have their own copy of these methods, needs to be lightweight)
this.get_id = function() { return _id; };
this.get_name = function() { return _name + _id; };
// public, this instance copies
this.id = id;
this.pdfPage = pdfPage;
this.scale = scale || 1.0;
this.viewport = this.pdfPage.getViewport(this.scale, 0);
this.renderingState = RenderingStates.INITIAL;
//form elements other than radio buttons and check boxes
this.Fields = [];
//form elements: radio buttons and check boxes
this.Boxsets = [];
this.currentRadioGroup = [];
this.currentRadioGroupName = "";
//public properties
Object.defineProperty(this, 'width', {
get:function () {
return PDFUnit.toFormX(this.viewport.width);
},
enumerable:true
});
Object.defineProperty(this, 'height', {
get:function () {
return PDFUnit.toFormY(this.viewport.height);
},
enumerable:true
});
};
// inherit from event emitter
nodeUtil.inherits(cls, nodeEvents.EventEmitter);
cls.prototype.destroy = function() {
this.pdfPage.destroy();
};
cls.prototype.getPagePoint = function(x, y) {
return this.viewport.convertToPdfPoint(x, y);
};
cls.prototype.parsePage = function(callback) {
if (this.renderingState !== RenderingStates.INITIAL)
error('Must be in new state before drawing');
this.renderingState = RenderingStates.RUNNING;
var canvas = createScratchCanvas(1, 1);
var ctx = canvas.getContext('2d');
var self = this;
function pageViewDrawCallback(error) {
self.renderingState = RenderingStates.FINISHED;
if (error) {
nodeUtil._logN.call(self, 'An error occurred while rendering the page.' + error);
}
else {
nodeUtil._logN.call(self, 'page ' + (self.id + 1) + ' is rendered successfully.');
_.extend(self, ctx.canvas);
}
self.stats = self.pdfPage.stats;
callback();
}
var renderContext = {
canvasContext:ctx,
viewport:this.viewport
};
self.pdfPage.render(renderContext).then(
function pdfPageRenderCallback() {
self.pdfPage.getAnnotations().then(function(fields){
_.each(fields, _addField, self);
pageViewDrawCallback(null);
});
},
function pdfPageRenderError(error) {
pageViewDrawCallback(error);
}
);
};
return cls;
})();
////////////////////////////////Start of Node.js Module
var PDFJSClass = (function () {
'use strict';
// private static
var _nextId = 1;
var _name = 'PDFJSClass';
// constructor
var cls = function () {
nodeEvents.EventEmitter.call(this);
// private
var _id = _nextId++;
// public (every instance will have their own copy of these methods, needs to be lightweight)
this.get_id = function() { return _id; };
this.get_name = function() { return _name + _id; };
// public, this instance copies
this.pdfDocument = null;
this.formImage = null;
};
// inherit from event emitter
nodeUtil.inherits(cls, nodeEvents.EventEmitter);
cls.prototype.parsePDFData = function(arrayBuffer) {
var parameters = {password: '', data: arrayBuffer};
this.pdfDocument = null;
this.formImage = null;
var self = this;
PDFJS.getDocument(parameters).then(
function getDocumentCallback(pdfDocument) {
self.load(pdfDocument, 1);
},
function getDocumentError(message, exception) {
nodeUtil._logN.call(self, "An error occurred while parsing the PDF: " + message);
},
function getDocumentProgress(progressData) {
nodeUtil._logN.call(self, "Loading progress: " + progressData.loaded / progressData.total + "%");
}
);
};
cls.prototype.load = function(pdfDocument, scale) {
this.pdfDocument = pdfDocument;
var pages = this.pages = [];
this.pageWidth = 0;
var pagesCount = pdfDocument.numPages;
var pagePromises = [];
for (var i = 1; i <= pagesCount; i++)
pagePromises.push(pdfDocument.getPage(i));
var self = this;
var pagesPromise = PDFJS.Promise.all(pagePromises);
nodeUtil._logN.call(self, "PDF loaded. pagesCount = " + pagesCount);
pagesPromise.then(function(promisedPages) {
self.parsePage(promisedPages, 0, 1.5);
});
pdfDocument.getMetadata().then(function(data) {
var info = data.info, metadata = data.metadata;
self.documentInfo = info;
self.metadata = metadata;
var pdfTile = "";
if (metadata && metadata.has('dc:title')) {
pdfTile = metadata.get('dc:title');
}
else if (info && info['Title'])
pdfTile = info['Title'];
self.emit("pdfjs_parseDataReady", {Agency:pdfTile, Id: info});
});
};
cls.prototype.parsePage = function(promisedPages, id, scale) {
nodeUtil._logN.call(this, "start to parse page:" + (id+1));
var self = this;
var pdfPage = promisedPages[id];
var pageParser = new PDFPageParser(pdfPage, id, scale);
pageParser.parsePage(function() {
if (!self.pageWidth) //get PDF width
self.pageWidth = pageParser.width;
PDFField.checkRadioGroup(pageParser.Boxsets);
var page = {Height: pageParser.height,
HLines: pageParser.HLines,
VLines: pageParser.VLines,
Fills:pageParser.Fills,
Texts: pageParser.Texts,
Fields: pageParser.Fields,
Boxsets: pageParser.Boxsets
};
self.pages.push(page);
if (id == self.pdfDocument.numPages - 1) {
nodeUtil._logN.call(self, "complete parsing page:" + (id+1));
self.emit("pdfjs_parseDataReady", {Pages:self.pages, Width: self.pageWidth});
}
else {
process.nextTick(function(){
self.parsePage(promisedPages, ++id, scale);
});
}
});
};
cls.prototype.destroy = function() {
this.removeAllListeners();
this.pdfDocument = null;
this.formImage = null;
};
return cls;
})();
module.exports = PDFJSClass;
////////////////////////////////End of Node.js Module