-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
70 lines (60 loc) · 2.61 KB
/
index.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
window.addEventListener('load', async () => {
const downloadButton = document.getElementById('downloadButton');
downloadButton.addEventListener('click', () => go(document.getElementById('urlInput').value));
downloadButton.click();
const fileInput = document.getElementById('fileInput');
fileInput.addEventListener('change', () => {
const [file] = fileInput.files;
if (file) {
const fileReader = new FileReader();
fileReader.readAsArrayBuffer(file);
fileReader.addEventListener('load', () => go(fileReader.result));
}
});
});
async function go(source) {
[...window.document.getElementsByTagName('div')].forEach(div => div.remove());
const document = await pdfjsLib.getDocument(source).promise;
const page = await document.getPage(1);
const viewport = page.getViewport({ scale: 1 });
const canvas = window.document.getElementById('pageCanvas');
canvas.width = viewport.width;
canvas.height = viewport.height;
const context = canvas.getContext('2d');
const imageLayer = {
// Note that this method does not accept any arguments
beginLayout: () => { },
// Note that this method does not accept any arguments
endLayout: () => { },
appendImage: ({ imgData, objId, left, top, width, height }) => {
if (!imgData) {
// TODO: Fallback: commonObjs
const img = page.objs.get(objId);
const canvas = window.document.createElement('canvas');
canvas.width = img.naturalWidth;
canvas.height = img.naturalHeight;
const context = canvas.getContext('2d');
context.drawImage(img, 0, 0);
imgData = context.getImageData(0, 0, img.naturalWidth, img.naturalHeight);
// TODO: Verify this is always the case for images which come like this
top -= height;
}
box(left, top, width, height, `${imgData.data.length} B ${~~width}px × ${~~height}px (natively ${imgData.width}px × ${imgData.height}px) image at ${~~left}px × ${~~top}px`);
},
};
page.render({ canvasContext: context, viewport, imageLayer });
const { items } = await page.getTextContent();
for (const item of items) {
box(item.transform[4], viewport.height - item.transform[5] - item.height, item.width, item.height, item.str);
}
}
function box(x, y, width, height, title) {
const boxDiv = window.document.createElement('div');
boxDiv.textContent = title;
boxDiv.title = title;
boxDiv.style.left = x + 'px';
boxDiv.style.top = y + 'px';
boxDiv.style.width = width + 'px';
boxDiv.style.height = height + 'px';
window.document.body.append(boxDiv);
}