2019-12-01 23:30:38 +00:00
|
|
|
|
|
|
|
/// <reference lib="webworker" />
|
|
|
|
|
|
|
|
import PDFDocument from "pdfkit/lib/document"
|
2020-01-26 06:32:54 +00:00
|
|
|
import SVGtoPDF from "svg-to-pdfkit"
|
2019-12-01 23:30:38 +00:00
|
|
|
|
2020-01-26 06:32:54 +00:00
|
|
|
type ImgType = "svg" | "png"
|
|
|
|
|
|
|
|
const generatePDF = async (imgURLs: string[], imgType: ImgType, width: number, height: number): Promise<ArrayBuffer> => {
|
2019-12-01 23:30:38 +00:00
|
|
|
|
|
|
|
// @ts-ignore
|
|
|
|
const pdf = new (PDFDocument as typeof import("pdfkit"))({
|
|
|
|
// compress: true,
|
|
|
|
size: [width, height],
|
|
|
|
autoFirstPage: false,
|
|
|
|
margin: 0,
|
|
|
|
layout: "portrait",
|
|
|
|
})
|
|
|
|
|
2020-01-26 06:32:54 +00:00
|
|
|
if (imgType == "png") {
|
|
|
|
const imgDataUrlList: string[] = await Promise.all(imgURLs.map(fetchDataURL))
|
|
|
|
|
|
|
|
imgDataUrlList.forEach((data) => {
|
|
|
|
pdf.addPage()
|
|
|
|
pdf.image(data, {
|
|
|
|
width,
|
|
|
|
height,
|
|
|
|
})
|
2019-12-01 23:30:38 +00:00
|
|
|
})
|
2020-01-26 06:32:54 +00:00
|
|
|
} else { // imgType == "svg"
|
|
|
|
const svgList = await Promise.all(imgURLs.map(fetchText))
|
|
|
|
|
|
|
|
svgList.forEach((svg) => {
|
|
|
|
pdf.addPage()
|
|
|
|
SVGtoPDF(pdf, svg, 0, 0, {
|
|
|
|
preserveAspectRatio: "none",
|
|
|
|
})
|
|
|
|
})
|
|
|
|
}
|
2019-12-01 23:30:38 +00:00
|
|
|
|
|
|
|
// @ts-ignore
|
|
|
|
const buf: Uint8Array = await pdf.getBuffer()
|
|
|
|
|
|
|
|
return buf.buffer
|
|
|
|
}
|
|
|
|
|
|
|
|
const getDataURL = (blob: Blob): Promise<string> => {
|
|
|
|
return new Promise((resolve, reject) => {
|
|
|
|
const reader = new FileReader()
|
|
|
|
reader.onload = () => {
|
|
|
|
const result = reader.result
|
|
|
|
resolve(result as string)
|
|
|
|
}
|
|
|
|
reader.onerror = reject
|
|
|
|
reader.readAsDataURL(blob)
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
2020-01-26 06:32:54 +00:00
|
|
|
const fetchDataURL = async (imgUrl: string): Promise<string> => {
|
|
|
|
const r = await fetch(imgUrl)
|
|
|
|
const blob = await r.blob()
|
|
|
|
return getDataURL(blob)
|
|
|
|
}
|
|
|
|
|
|
|
|
const fetchText = async (imgUrl: string): Promise<string> => {
|
|
|
|
const r = await fetch(imgUrl)
|
|
|
|
return r.text()
|
|
|
|
}
|
|
|
|
|
|
|
|
export type PDFWorkerMessage = [string[], ImgType, number, number];
|
2019-12-01 23:30:38 +00:00
|
|
|
|
|
|
|
onmessage = async (e) => {
|
|
|
|
const [
|
2020-01-26 06:32:54 +00:00
|
|
|
imgURLs,
|
|
|
|
imgType,
|
2019-12-01 23:30:38 +00:00
|
|
|
width,
|
|
|
|
height,
|
|
|
|
] = e.data as PDFWorkerMessage
|
|
|
|
|
|
|
|
const pdfBuf = await generatePDF(
|
2020-01-26 06:32:54 +00:00
|
|
|
imgURLs,
|
|
|
|
imgType,
|
2019-12-01 23:30:38 +00:00
|
|
|
width,
|
|
|
|
height,
|
|
|
|
)
|
|
|
|
|
|
|
|
postMessage(pdfBuf, [pdfBuf])
|
|
|
|
}
|