Welcome folks today in this blog post we will be using the pdfobject
library in browser to render pdf
documents in browser using javascript. All the full source code of the application is shown below.
Get Started
In order to get started you need to make an index.html
file and copy paste the following code
index.html
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
<!DOCTYPE html> <html> <head> <title>PDF Embed Example</title> <script src="https://cdnjs.cloudflare.com/ajax/libs/pdfobject/2.2.4/pdfobject.min.js"></script> </head> <body> <h1>PDF Embed Example</h1> <form> <input type="file" id="pdfFile" accept=".pdf"> <button type="button" onclick="embedPDF()">Embed PDF</button> </form> <div id="pdfContainer"></div> <script> function embedPDF() { const pdfFile = document.getElementById('pdfFile').files[0]; if (pdfFile) { const fileReader = new FileReader(); fileReader.onload = function() { PDFObject.embed(fileReader.result, "#pdfContainer"); } fileReader.readAsDataURL(pdfFile); } } </script> </body> </html> |
As you can see we have the div
container where we will be rendering the user
selected pdf file we have the input element where we allow the user to select the pdf document from the computer
and then inside the javascript we are reading the content of the pdf
file and then using the pdfobject
library we are using the embed()
method to render the pdf document.
Rendering PDF From URL
Similarly we can even pass the url
of the pdf document to the embed()
function as shown below
1 |
PDFObject.embed("https://www.africau.edu/images/default/sample.pdf", "#pdfContainer"); |