I don't know what happened, nothing error but the await is not pass.
<template>
<input id="file" type="file" accept=".pdf" @change="onpdf"/>
<canvas id="pdfViewer"></canvas>
</template>
I import this in my project to render my pdf file to canvas.
import * as pdfjsLib from "pdfjs-dist";
import "pdfjs-dist/web/pdf_viewer.css";
pdfjsLib.GlobalWorkerOptions.workerSrc =
"https://cdn.jsdelivr.net/npm/[email protected]/build/pdf.min.js";
Here is my method:
onpdf(e: any) {
const file = e.target.files[0];
if (file.type !== "application/pdf") {
return;
}
const canvas = this.$refs.pdfViewer as HTMLCanvasElement;
const fileReader = new FileReader();
fileReader.onload = async function () {
const pdfData = new Uint8Array(this.result as any);
const loadingTask = pdfjsLib.getDocument({ data: pdfData });
console.log(loadingTask); // the console show PDFDocumentLoadingTask
const pdf = await loadingTask.promise; // I stuck in here nothing happen and no error!?
console.log("PDF loaded"); // The console have nothing.
const pageNumber = 1;
const page = await pdf.getPage(pageNumber);
console.log("Page loaded");
const scale = 0.5;
const viewport = page.getViewport({ scale });
const context = canvas.getContext("2d")!;
canvas.height = viewport.height;
canvas.width = viewport.width;
const renderContext = {
canvasContext: context,
viewport,
};
const renderTask = page.render(renderContext);
await renderTask.promise;
console.log("Page rendered");
};
fileReader.readAsArrayBuffer(file);
}
Is there anyway to solves this or I have to find another way to render this pdf file.
CodePudding user response:
I tried to run the same code as you (only on the logical part of the await promise) and I had no problem. Maybe you can try the following solution:
const loadingTask = pdfjsLib.getDocument({ data: pdfData });
loadingTask.promise.then(function(pdf) {
console.log('PDF loaded');
...
}
CodePudding user response:
Try to change const
pdf = await loadingTask.promise;
into
pdf = await loadingTask.promise();
You are not calling promise method in my opinion