create pdf viewer by javascript
- User
create pdf viewer by javascript
- Assistant
To create a PDF viewer using JavaScript, you can make use of the PDF.js library. Here's an example that demonstrates how to integrate PDF.js into your web page:
- Include the required JavaScript files in your HTML file:
<!DOCTYPE html> <html> <head> <title>PDF Viewer</title> <script src="https://mozilla.github.io/pdf.js/build/pdf.js"></script> </head> <body> <div> <canvas id="pdfCanvas"></canvas> <!-- element to render the PDF --> </div> <script> // Function to load and render the PDF function renderPdf(url, canvasId) { const canvas = document.getElementById(canvasId); const context = canvas.getContext('2d'); // Asynchronously load the PDF pdfjsLib.getDocument(url).promise.then(function (pdfDoc) { // Fetch and render the first page pdfDoc.getPage(1).then(function (page) { const viewport = page.getViewport({ scale: 1 }); canvas.width = viewport.width; canvas.height = viewport.height; const renderContext = { canvasContext: context, viewport: viewport, }; page.render(renderContext); }); }); } // Render the PDF when the page loads window.onload = function () { const pdfUrl = 'sample.pdf'; // Replace with your PDF file URL const canvasId = 'pdfCanvas'; renderPdf(pdfUrl, canvasId); }; </script> </body> </html>