Reputation: 38985
I am using this code to render the fisrt page of pdf to a image using pdfjs "pdfjs-dist": "^3.9.179"
:
const initPdf = async (pdfUrl: string) => {
setPdfUrl(pdfUrl);
const pdfJS = await import('pdfjs-dist/build/pdf');
pdfJS.GlobalWorkerOptions.workerSrc = window.location.origin + '/pdf.worker.min.js';
const pdf = await pdfJS.getDocument(pdfUrl).promise;
const page = await pdf.getPage(1);
const viewport = page.getViewport({ scale: 1.5 });
const canvas: any = canvasRef.current;
if (!canvas) return;
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(".textLayer") as HTMLDivElement;
textLayer.style.left = canvas.offsetLeft + 'px';
textLayer.style.top = canvas.offsetTop + 'px';
textLayer.style.height = canvas.offsetHeight + 'px';
textLayer.style.width = canvas.offsetWidth + 'px';
pdfJS.renderTextLayer({
textContent: textContent,
container: textLayer,
viewport: viewport,
textDivs: []
});
});
}
but I found the generate image did not show in the cavas, Am I missing something? I am sure the pdf contains the chinese words. what should I do to make the cavas render chinese normally? This is the html that shows the rendered pdf:
<div className={styles.cavasLayer}>
<canvas id="the-cavas" ref={canvasRef} />
<div className={styles.textLayer}></div>
</div>
I have tried to add the cMap like this:
pdfJS.cMapUrl= 'https://cdn.jsdelivr.net/npm/[email protected]/cmaps/'
seems did not work. shows error like this:
index-e5fb9cea.js:201 Uncaught (in promise) TypeError: Cannot add property cMapUrl, object is not extensible
at m (index-e5fb9cea.js:201:22598)
Upvotes: 0
Views: 406
Reputation: 38985
Finally I found add this configuration fixed this issue:
const pdf = await pdfJS.getDocument({
url: pdfUrl,
cMapUrl: 'https://cdn.jsdelivr.net/npm/[email protected]/cmaps/',
cMapPacked: true,
}).promise;
Upvotes: 0