This repository has been archived by the owner on Jun 9, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 53
/
Copy pathindex.js
74 lines (68 loc) · 2.28 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
71
72
73
74
const wasm_pdf = import('./pkg');
const createPDF = (jsDocument) => {
wasm_pdf.then(pdf => {
const imagePaths = parseJsDoc(jsDocument.contents);
fetchImagePaths(imagePaths).then((imgData) => {
// add base64 encoded bytes to document
jsDocument.image_data = {};
// add image widths and heights
jsDocument.image_widths = {};
jsDocument.image_heights = {};
imgData.map(d => {
jsDocument.image_data[d.path] = d.data;
jsDocument.image_widths[d.path] = d.width;
jsDocument.image_heights[d.path] = d.height;
});
pdf.run(jsDocument);
});
//pdf.print_document(jsDocument);
}).catch(console.error)
};
window.createPDF = createPDF;
// convert list of image paths
const fetchImagePaths = paths => Promise.all(paths.map(p => imageBytes(p)));
// convert single image path
const imageBytes = (url) => {
return new Promise(resolve => {
let img = new Image();
img.onload = () => {
let canvas = document.createElement("canvas");
canvas.width = img.width;
canvas.height = img.height;
let ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0);
let dataURL = canvas.toDataURL("image/jpeg", 0.8);
resolve({
path: url,
data: stripDataURI(dataURL),
width: img.width,
height: img.height
});
};
img.onerror = () => resolve({
path,
status: 'error'
});
img.src = url;
});
};
const BASE64_MARKER = ';base64,';
const stripDataURI = (dataURI) => {
const base64Index = dataURI.indexOf(BASE64_MARKER) + BASE64_MARKER.length;
return dataURI.substring(base64Index);
};
const parseJsDoc = (obj) => {
let results = [];
for (let k in obj) {
if (obj[k] && typeof obj[k] === 'object') {
results = results.concat(parseJsDoc(obj[k]));
} else {
if (k === "obj_type" && obj[k].toLowerCase() === "image") {
if (obj["params"] && obj["params"]["src"]) {
results.push(obj.params.src);
}
}
}
}
return results;
}