Welcome folks today in this blog post we will be using the pdf.js
library to count the number of pages
inside pdf
document 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 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 |
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>PDF.js Example to Count Number of Pages inside PDF Document</title> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css"> </head> <body> <div class="container"> <h1 class="text-center">Count Pages inside PDF Document</h1> <div class="form-group container"> <input type="file" accept=".pdf" required id="files" class="form-control"> </div> <br><br> <h1 class="text-primary container" id="result"></h1> </div> </body> <script src="https://cdnjs.cloudflare.com/ajax/libs/pdf.js/2.12.313/pdf.min.js"></script> <script> let inputElement = document.getElementById('files') inputElement.onchange = function(event) { var file = event.target.files[0]; //Step 2: Read the file using file reader var fileReader = new FileReader(); fileReader.onload = function() { //Step 4:turn array buffer into typed array var typedarray = new Uint8Array(this.result); //Step 5:pdfjs should be able to read this const loadingTask = pdfjsLib.getDocument(typedarray); loadingTask.promise.then(pdf => { document.getElementById('result').innerHTML = "The number of Pages inside pdf document is " + pdf.numPages // The document is loaded here... }); }; //Step 3:Read the file as ArrayBuffer fileReader.readAsArrayBuffer(file); } </script> </html> |
As you can see in the above html code we have the input
field where we allow the user to select pdf
documents and then we have written the javascript
code to parse the pdf
document which is selected and then we are using the getDocument()
method to count the number of pages inside the pdf document and then we are displaying it on the browser.