diff --git a/src/worker.ts b/src/worker.ts index 449164e..179a5b8 100644 --- a/src/worker.ts +++ b/src/worker.ts @@ -6,7 +6,9 @@ import SVGtoPDF from 'svg-to-pdfkit' type ImgType = 'svg' | 'png' -const getDataURL = (blob: Blob): Promise => { +type DataResultType = 'dataUrl' | 'text' + +const readData = (blob: Blob, type: DataResultType): Promise => { return new Promise((resolve, reject) => { const reader = new FileReader() reader.onload = (): void => { @@ -14,19 +16,18 @@ const getDataURL = (blob: Blob): Promise => { resolve(result as string) } reader.onerror = reject - reader.readAsDataURL(blob) + if (type === 'dataUrl') { + reader.readAsDataURL(blob) + } else { + reader.readAsText(blob) + } }) } -const fetchDataURL = async (imgUrl: string): Promise => { +const fetchData = async (imgUrl: string, type: DataResultType): Promise => { const r = await fetch(imgUrl) const blob = await r.blob() - return getDataURL(blob) -} - -const fetchText = async (imgUrl: string): Promise => { - const r = await fetch(imgUrl) - return r.text() + return readData(blob, type) } const generatePDF = async (imgURLs: string[], imgType: ImgType, width: number, height: number): Promise => { @@ -40,7 +41,7 @@ const generatePDF = async (imgURLs: string[], imgType: ImgType, width: number, h }) if (imgType === 'png') { - const imgDataUrlList: string[] = await Promise.all(imgURLs.map(fetchDataURL)) + const imgDataUrlList: string[] = await Promise.all(imgURLs.map(url => fetchData(url, 'dataUrl'))) imgDataUrlList.forEach((data) => { pdf.addPage() @@ -50,7 +51,7 @@ const generatePDF = async (imgURLs: string[], imgType: ImgType, width: number, h }) }) } else { // imgType == "svg" - const svgList = await Promise.all(imgURLs.map(fetchText)) + const svgList = await Promise.all(imgURLs.map(url => fetchData(url, 'text'))) svgList.forEach((svg) => { pdf.addPage()