I am tried to use pdf.js
to preview pdf in google chrome browsers, the pdf.js
dependencies version is "pdfjs-dist": "^3.9.179"
. This is my demo typescript code in react web app to implement the pdf preview:
const initPdf = async () => {
const pdfJS = await import('pdfjs-dist/build/pdf');
pdfJS.GlobalWorkerOptions.workerSrc =
window.location.origin + '/pdf.worker.min.js';
const pdf = await pdfJS.getDocument('lshort-zh-cn.pdf').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 };
page.render(renderContext);
}
this demo code works fine, but I fount the preview pdf could not select and copy the content, is it possible to enable the select and copy? I have tried like this but the text layer was seperate with the cavas:
const initPdf = async () => {
const pdfJS = await import('pdfjs-dist/build/pdf');
pdfJS.GlobalWorkerOptions.workerSrc =
window.location.origin + '/pdf.worker.min.js';
const pdf = await pdfJS.getDocument('lshort-zh-cn.pdf').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) {
var textLayer = document.querySelector(`.${styles.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: []
});
});
}
import the pdf viewer css like this:
import "pdfjs-dist/web/pdf_viewer.css";
I followed the guide from here: pdf.js with text selection. The UI look like this:
this is part of the css look like:
<div className={styles.previewBody}>
<div className={styles.cavasLayer}>
<canvas ref={canvasRef} style={{ height: '100vh' }} />
</div>
{/*https://stackoverflow.com/questions/33063213/pdf-js-with-text-selection*/}
<div className={styles.textLayer}>
</div>
</div