musescore-downloader/src/pdf.ts

41 lines
1.3 KiB
TypeScript
Raw Normal View History

2020-05-18 22:44:45 +00:00
import { PDFWorkerHelper } from './worker-helper'
import { getFileUrl } from './file'
2020-11-24 17:35:14 +00:00
import FileSaver from 'file-saver'
2020-11-24 08:17:50 +00:00
import { ScoreInfo, SheetInfo } from './scoreinfo'
2020-05-18 22:44:45 +00:00
let pdfBlob: Blob
2020-09-27 15:45:51 +00:00
const _downloadPDF = async (imgURLs: string[], imgType: 'svg' | 'png', name = ''): Promise<void> => {
2020-05-18 22:44:45 +00:00
if (pdfBlob) {
2020-11-24 17:35:14 +00:00
return FileSaver.saveAs(pdfBlob, `${name}.pdf`)
2020-05-18 22:44:45 +00:00
}
const cachedImg = document.querySelector('img[src*=score_]') as HTMLImageElement
const { naturalWidth: width, naturalHeight: height } = cachedImg
const worker = new PDFWorkerHelper()
const pdfArrayBuffer = await worker.generatePDF(imgURLs, imgType, width, height)
worker.terminate()
pdfBlob = new Blob([pdfArrayBuffer])
2020-11-24 17:35:14 +00:00
FileSaver.saveAs(pdfBlob, `${name}.pdf`)
2020-05-18 22:44:45 +00:00
}
2020-11-24 08:17:50 +00:00
export const downloadPDF = async (scoreinfo: ScoreInfo, sheet: SheetInfo): Promise<void> => {
const imgType = sheet.imgType
const pageCount = sheet.pageCount
2020-05-18 22:44:45 +00:00
const rs = Array.from({ length: pageCount }).map((_, i) => {
if (i === 0) { // The url to the first page is static. We don't need to use API to obtain it.
2020-11-24 08:17:50 +00:00
return sheet.thumbnailUrl
} else { // obtain image urls using the API
2020-11-24 07:51:43 +00:00
return getFileUrl(scoreinfo.id, 'img', i)
}
2020-05-18 22:44:45 +00:00
})
const sheetImgURLs = await Promise.all(rs)
2020-05-18 22:44:45 +00:00
return _downloadPDF(sheetImgURLs, imgType, scoreinfo.fileName)
}