aboutsummaryrefslogtreecommitdiff
path: root/src/worker-helper.ts
blob: 84cf2d6bf42d7230b970ca1744c73c5d623cb984 (plain) (blame)
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
import { PDFWorkerMessage } from "./worker";
import { PDFWorker } from "../dist/cache/worker";

const scriptUrlFromFunction = (fn: () => any): string => {
    const blob = new Blob(["(" + fn.toString() + ")()"], {
        type: "application/javascript",
    });
    return window.URL.createObjectURL(blob);
};

// Node.js fix
if (typeof Worker === "undefined") {
    globalThis.Worker = class {} as any; // noop shim
}

export class PDFWorkerHelper extends Worker {
    constructor() {
        const url = scriptUrlFromFunction(PDFWorker);
        super(url);
    }

    generatePDF(
        imgURLs: string[],
        imgType: "svg" | "png",
        width: number,
        height: number
    ): Promise<ArrayBuffer> {
        const msg: PDFWorkerMessage = [imgURLs, imgType, width, height];
        this.postMessage(msg);
        return new Promise((resolve) => {
            this.addEventListener("message", (e) => {
                resolve(e.data);
            });
        });
    }
}