Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save documentprocessing/31601867eafa86bbbf269733a2fb7a3e to your computer and use it in GitHub Desktop.
Save documentprocessing/31601867eafa86bbbf269733a2fb7a3e to your computer and use it in GitHub Desktop.
Render or View PDF Document in Browser using PDF.js JavaScript Library. Check https://products.documentprocessing.com/viewer/javascript/pdf.js/ for more details.
// This example contains necessary HTML and JavaScript code to demonstrate the use of PDF.js library
// by rendering a PDF document in the browser
<html>
<head>
// Link to PDF.js library
<script src="../build/pdf.js"></script>
</head>
<body>
// Add canvas that will show PDF document
<canvas id="pdfCanvas"></canvas>
<script>
//Setting URL of the PDF document that you want to render
const url = 'groupdocs.pdf';
// Rendering the PDF on the canvas
pdfjsLib.getDocument(url).promise.then(pdf => {
// Loading the first page of the PDF
const pageNumber = 1;
return pdf.getPage(pageNumber);
}).then(page => {
// Setting the PDF zoom level to 100% by setting scale to 1
const viewport = page.getViewport({ scale: 1 });
// Prepare canvas using PDF page dimensions
const canvas = document.getElementById("pdfCanvas");
const context = canvas.getContext("2d");
canvas.height = viewport.height;
canvas.width = viewport.width;
// Render PDF page into canvas context
const renderContext = {
canvasContext: context,
viewport: viewport,
};
return page.render(renderContext);
});
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment