-
-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathpdf.js
187 lines (154 loc) · 5.75 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
global.window = {document: {createElementNS: () => {return {}} }};
global.navigator = {};
global.btoa = () => {};
const jsPDF = require('jspdf');
const path = require('path');
const utils = require('./utils');
const exec = require('child_process').exec;
const fs = require('fs');
const hummus = require('hummus');
const _ = require('highland');
const HummusRecipe = require('hummus-recipe');
// Simple pass-through to pdftohtml so we can keep track of where the images went...
function convertPDF(inputFile, outputDir) {
console.log(`Writing all images in ${inputFile} to ${outputDir}`);
return new Promise((resolve, reject) => {
const inputPath = path.parse(inputFile);
const outputFile = path.join(inputPath.dir, outputDir, inputPath.name);
console.warn('Only looking at first 10 pages for demo, CHANGE THIS BEFORE PRODUCTION.');
exec(`mkdir -p "${path.dirname(outputFile)}" && pdftohtml -zoom 4 -c -l 10 -xml "${inputFile}" "${outputFile}"`, async (error, stdout, stderr) => {
if (error || stderr) reject([error, stderr]);
else {
outputDir = path.dirname(outputFile);
let extractedFiles = await utils.readdirAsync(outputDir);
extractedFiles = extractedFiles.map(file => path.join(outputDir, file));
let pdfMetadata = extractedFiles.filter(file => path.extname(file) == '.xml')[0];
let pdfImages = extractedFiles.filter(file => path.extname(file) == '.png');
resolve({
outputDir: outputDir,
pdfMetadata: pdfMetadata,
pdfImages: pdfImages
});
}
});
})
}
function readPDF(inputFile){
let pdfReader = hummus.createReader(inputFile);
return pdfReader;
}
function translateCoords(coords, page, pdfPage) {
// the pdftohtml output is from top to bottom, we want bottom to top
// also need to rescale the pdftohtml output from the page values and convert it to the new dimensions;
let top = coords.top;
let left = coords.left;
let newCoords = {
top: (top/page.height) * pdfPage.height,
left: (left/page.width) * pdfPage.width,
height: (coords.height/page.height) * pdfPage.height,
width: (coords.width/page.width) * pdfPage.width
}
return newCoords;
}
function setFonts(doc, page, pageMetadata) {
let scale = pageMetadata.width/page.width;
scale = 0.8;
console.log(pageMetadata.height, page.height, page.fontspec);
utils.hasToBeArray(page.fontspec)
.forEach(font => {
font.size = font.size * scale;
doc.fontSpec.set(font.id, font)
});
return doc
}
function parseGCV(doc, page) {
// Script that will parse the GCV output and create a text format similar to page.text so that we can add it to the pdf.
let pageMetadata = doc.pageInfo(page.number);
return _(page.image)
.map(image => image.ocr)
.flatMap(image => _(utils.readFileAsync(image, 'utf-8')))
.map(JSON.parse)
.pluck('fullTextAnnotation')
.flatten()
.pluck('pages')
.flatten()
.doto(pg => {
page.height = pg.height;
page.width = pg.width;
})
.pluck('blocks')
.flatten()
.pluck('paragraphs')
.flatten()
.pluck('words')
.flatten()
.pluck('symbols')
.flatten()
.map(d => {
let height = Math.max(...d.boundingBox.vertices.map(d => d.y)) - Math.min(...d.boundingBox.vertices.map(d => d.y));
let width = Math.max(...d.boundingBox.vertices.map(d => d.x)) - Math.min(...d.boundingBox.vertices.map(d => d.x));
console.log(JSON.stringify(d.boundingBox), d.text);
let coords = { top: Math.max(...d.boundingBox.vertices.map(d => d.y)), left: Math.max(...d.boundingBox.vertices.map(d => d.x)), height: height, width: width };
let newCoords = coords//translateCoords(coords, page, pageMetadata);
//newCoords.boundingBox = boundingBox: JSON.stringify(d.boundingBox)
newCoords['@text'] = d.text
return newCoords
})
.collect()
.toPromise(Promise)
.then(texts => {
page.text = texts
return page
});
//.zip(imageStream)
//.each(console.log)
}
function enrichPage(doc, page, fonts) {
page.number = parseInt(page.number);
let pageMetadata = doc.pageInfo(page.number);
let pdfPage = doc.editPage(page.number)
if(page.fontspec) doc = setFonts(doc, page, pageMetadata);
_(utils.hasToBeArray(page.text))
.map(text => {
let textCoords = translateCoords(text, page, pageMetadata);
let font;
if(typeof text.font == 'object') font = doc.fontSpec.get(text.font);
else font = {
family: "Times",
color: "#000000",
size: 3
}
font.textBox = {
width: text.width,
height: text.height,
lineHeight: text.height,
lineWidth: text.width
}
pdfPage.text(text['@text'], textCoords.left, textCoords.top, font)
})
.done(() => {
pdfPage.endPage();
})
return doc;
}
function initializePDF(inputFile) {
const inputPDF = new HummusRecipe(inputFile, 'output.pdf');
inputPDF.fontSpec = new Map();
//console.log(`${inputPDF.getModifiedFileParser().getPagesCount()} pages found.`);
return inputPDF;
}
function writePDF(doc) {
// Takes the GCV output and adds a text layer into the PDF.
fs.writeFileSync('document.pdf', doc.output());
delete global.window;
delete global.navigator;
delete global.btoa;
}
module.exports = {
convertPDF: convertPDF,
initializePDF: initializePDF,
enrichPage: enrichPage,
writePdf: writePDF,
readPDF: readPDF,
parseGCV: parseGCV
}