百度了一圈,文章全都是搬运的同一篇,还TM不能用,逆天!!!
上传组件用的 Ant Design Pro
- 正确的导入(cdn在国外,不建议使用)
import { pdfjs } from 'react-pdf';
pdfjs.GlobalWorkerOptions.workerSrc = new URL(
'pdfjs-dist/build/pdf.worker.min.js',
import.meta.url,
).toString();
- 使用canvas截图
<ProFormUploadButton
name="upload"
accept=".pdf"
onChange={async (args) => {
const file = args.file.originFileObj;
if (!file || !args.event) {
return;
}
const buff = await file.arrayBuffer(); // Uint8Array
const pdfDoc = await pdfjs.getDocument(buff).promise;
for (let pageNum = 1; pageNum <= pdfDoc._pdfInfo.numPages; pageNum++) {
const scale = 1.0;
const page = await pdfDoc.getPage(pageNum);
const viewport = page.getViewport({ scale });
const canvas = document.createElement('canvas');
const context = canvas.getContext('2d');
canvas.width = viewport.width;
canvas.height = viewport.height;
const renderContext = {
canvasContext: context!,
viewport: viewport,
};
await page.render(renderContext).promise;
const imageDataUrl = canvas.toDataURL('image/png');
//balabala
}
}}
/>;