I am trying to create a web page with an embedded PDF. My code works but it doesn’t show breaks between the document’s pages or a margin (in the same way that Chrome does when used as a PDF viewer). My problem is that I am too unfamiliar with handling PDFs in JS to find the documentation I need. I have tried googling for pdfjslib and pdf.min.js but the hits all refer to “PDF.js” which I am not using – I think!
Here is my code:
<script src="https://cdnjs.cloudflare.com/ajax/libs/pdf.js/2.12.313/pdf.min.js"></script>
<script>
// Set worker path to worker bundle of pdf.js
pdfjsLib.GlobalWorkerOptions.workerSrc = 'https://cdnjs.cloudflare.com/ajax/libs/pdf.js/2.12.313/pdf.worker.min.js';
</script>
<script>
// PDF.js initialization
const container = document.getElementById('pdfRenderer');
const renderPage = (pageNumber, pdf) => {
pdf.getPage(pageNumber).then(page => {
const canvas = document.createElement('canvas');
const context = canvas.getContext('2d');
// Set the scale for rendering
const viewport = page.getViewport({ scale: 1 });
// Set canvas dimensions to PDF page dimensions
canvas.height = viewport.height;
canvas.width = viewport.width;
// Render the PDF page into the canvas context
page.render({
canvasContext: context,
viewport: viewport
});
container.appendChild(canvas);
// Render next page if available
if (pageNumber < pdf.numPages) {
renderPage(pageNumber + 1, pdf);
}
});
};
pdfjsLib.getDocument('Fergus-pdf-small.pdf').promise.then(pdf => {
renderPage(1, pdf);
});
</script>
Any pointers/suggestions greatfully received.