-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathbackground_script.js
More file actions
53 lines (49 loc) · 2 KB
/
background_script.js
File metadata and controls
53 lines (49 loc) · 2 KB
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
browser.runtime.onMessage.addListener((message) => {
if (message.id === "msd-create") {
let doc = new PDFDocument({
autoFirstPage: false,
bufferPages: true,
size: [595, 842] // A4 @ 72 PPI
});
let stream = doc.pipe(blobStream());
let resCount = 0;
for(let i=0; i<message.urls.length; i++) {
const isPNG = /score_\d+.png/.test(message.urls[0]);
fetch(message.urls[i])
.then((res) => {
if (!res.ok) throw new Error(`HTTP error! Status: ${res.status}`);
return res.blob();
})
.then(async (res) => {
const data = isPNG ? await res.arrayBuffer() : await res.text();
while(i >= doc.bufferedPageRange().count) doc.addPage();
doc.switchToPage(i);
if(isPNG) doc.image(data, 0, 0, {fit: [595, 842]});
else SVGtoPDF(doc, data, 0, 0, {preserveAspectRatio: "16:9"});
resCount++;
if (resCount >= message.urls.length) {
doc.end();
stream.on("finish", () => {
browser.downloads.download({
filename: "score.pdf",
url: stream.toBlobURL("application/pdf"),
saveAs: true
})
.catch((error) => {
return browser.runtime.sendMessage({ // Send to browserAction
id: "msd-log",
content: `Wasn't able to save PDF.\nError: ${error.message}`
});
});
});
}
})
.catch((error) => {
return browser.runtime.sendMessage({ // Send to browserAction
id: "msd-log",
content: error.message
});
});
}
}
});