我正在尝试使用pdf.js放大和缩小pdf,这是渲染和重新渲染pdf的函数:
const renderPdfPage = async (pdf: any, pdfJS: any, pageNum: number) => {
if (!canvasRef || !canvasRef.current) return;
const docCavas = document.getElementById("the-canvas" + pageNum);
if (!docCavas) {
const el = window.document.createElement("canvas") as HTMLCanvasElement;
el.id = "the-canvas" + pageNum;
canvasRef.current.append(el);
}
if(pageNum > pdf.numPages){
return;
}
const page = await pdf.getPage(pageNum);
const viewport = page.getViewport({
scale: pdfScale
});
let canvas = document.getElementById('the-canvas' + pageNum) as HTMLCanvasElement;
const canvasContext = canvas.getContext('2d');
canvas.height = viewport.height;
canvas.width = viewport.width;
const renderContext = { canvasContext, viewport };
const renderTask = page.render(renderContext);
renderTask.promise.then(function () {
const textContent = page.getTextContent();
return textContent;
}).then(function (textContent: string) {
const textLayer = document.querySelector(`.${styles.textLayer}`) as HTMLDivElement;
if (!textLayer) return;
textLayer.style.left = canvas.offsetLeft + 'px';
textLayer.style.top = canvas.offsetTop + 'px';
textLayer.style.height = canvas.offsetHeight + 'px';
textLayer.style.width = canvas.offsetWidth + 'px';
textLayer.style.setProperty('--scale-factor', pdfScale.toString());
pdfJS.renderTextLayer({
textContentSource: textContent,
container: textLayer,
viewport: viewport,
textDivs: []
});
});
}
现在我面临一个问题,有时获取 pdf 页面会失败并显示如下错误:
api.js:2917 Uncaught (in promise) Error: Invalid page request.
at WorkerTransport.getPage (api.js:2917:29)
at PDFDocumentProxy.getPage (api.js:837:28)
at renderPdfPage (Previewer.tsx:55:32)
at getPage (Previewer.tsx:136:68)
错误是从这一行抛出的
const page = await pdf.getPage(pageNum);
,我重新检查了我的代码,但没有弄清楚为什么会发生这种情况。我错过了什么吗?我应该怎么做才能解决这个问题?这是缩放功能:
const handleZoomOut = async (pdfUrl: any) => {
if (!pdfUrl) {
return;
}
var zoomoutbutton = document.getElementById("zoomoutbutton") as HTMLButtonElement;
zoomoutbutton.onclick = function () {
if (pdfScale <= 0.25) {
return;
}
setPdfScale(pdfScale - 0.25);
displayPage(currentPdf, pageNum);
}
}
当我传递的
pageNum
值是字符串类型而不是整数类型时,我遇到了此错误。