import { getDocument, GlobalWorkerOptions } from 'pdfjs-dist/legacy/build/pdf';
// 使用 CDN 避免本地 worker 问题
GlobalWorkerOptions.workerSrc = `//cdnjs.cloudflare.com/ajax/libs/pdf.js/3.11.174/pdf.worker.min.js`;

export const pdfToImage = async (pdfUrl) => {
    const loadingTask = getDocument(pdfUrl);
    const pdf = await loadingTask.promise;

    let pages = [];
    for (let num = 1; num <= pdf.numPages; num++) {
        const page = await pdf.getPage(num);
        const viewport = page.getViewport({ scale: 1 });
        const canvas = document.createElement('canvas');
        const context = canvas.getContext('2d');
        canvas.height = viewport.height;
        canvas.width = viewport.width;

        const renderContext = {
            canvasContext: context,
            viewport: viewport
        };
        await page.render(renderContext).promise;
        pages.push(canvas.toDataURL('image/png'));
    }
    return pages;
}