How to Display PDF Files as Images in Web Pages with JavaScript❓
In this tutorial, we will show you how to display PDF files as images in web pages using JavaScript. This is a useful technique for previewing PDF files on your web pages without having to download them.
Embedding PDFs directly into web pages offers a seamless user experience, eliminating the need for external downloads. JavaScript, paired with the powerful PDF.js library, enables you to achieve this with ease.
The desired result will be like this:

Solution:
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Hion Coding Show PDF</title>
<link href="https://cdnjs.cloudflare.com/ajax/libs/pdf.js/2.6.347/pdf_viewer.min.css" rel="stylesheet"
type="text/css"/>
</head>
<body>
<div id="app">
<h1>Show PDF below</h1>
<div id="pdf_container"></div>
</div>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/pdf.js/2.6.347/pdf.min.js"></script>
<script>
var pdfUrl = "hion_test_pdf.pdf";
var pdfjsLib = window['pdfjs-dist/build/pdf'];
pdfjsLib.GlobalWorkerOptions.workerSrc = 'https://cdnjs.cloudflare.com/ajax/libs/pdf.js/2.6.347/pdf.worker.min.js';
var pdfDoc = null;
var scale = 0.6;
var resolution = 1;
function LoadPdfFromUrl(url) {
pdfjsLib.getDocument(url).promise.then(function (pdfDoc_) {
pdfDoc = pdfDoc_;
var pdf_container = document.getElementById("pdf_container");
pdf_container.style.display = "block";
for (var i = 1; i <= pdfDoc.numPages; i++) {
RenderPage(pdf_container, i);
}
});
};
function RenderPage(pdf_container, num) {
pdfDoc.getPage(num).then(function (page) {
var canvas = document.createElement('canvas');
canvas.id = 'pdf-' + num;
ctx = canvas.getContext('2d');
pdf_container.appendChild(canvas);
var viewport = page.getViewport({scale: scale});
canvas.height = resolution * viewport.height;
canvas.width = resolution * viewport.width;
var renderContext = {
canvasContext: ctx,
viewport: viewport,
transform: [resolution, 0, 0, resolution, 0, 0]
};
page.render(renderContext);
});
};
LoadPdfFromUrl(pdfUrl)
</script>
</body>
</html>
I was tired of finding a show pdf solution for my small project and this was exactly what I wanted.
Hope this code will help you solve your problem.