How to get the number of .PDF pages loaded by user?

I have an input for the file, and before "loading" I need to calculate the number of pages of this .pdf in JAVASCRIPT (for example, jQuery ...)

+10
source share
5 answers

You may be able to do something using pdf.js , but this will require some experimentation.

0
source

If you use pdf.js, you can refer to the example on github ('... / examples / node / getinfo.js') with the following code, which prints the number of pages in a PDF file.

const pdfjsLib = require('pdfjs-dist'); ... pdfjsLib.getDocument(pdfPath).then(function (doc) { var numPages = doc.numPages; console.log('# Document Loaded'); console.log('Number of Pages: ' + numPages); } 
+32
source

and a clean JavaScript solution:

 var input = document.getElementById("files"); var reader = new FileReader(); reader.readAsBinaryString(input.files[0]); reader.onloadend = function(){ var count = reader.result.match(/\/Type[\s]*\/Page[^s]/g).length; console.log('Number of Pages:',count ); } 
+6
source

As stated in other answers, something like pdf.js is what you are looking for. I took a look at the API and included the numPages () function to return the total number of pages. He also seems to be counting pages for me when viewing a demo page from Mozilla.

It depends on whether you can use modern browsers and experimental technologies for your solution. pdf.js is very impressive, but it is still experimental on the github page .

If you can count the pages on the server after loading, you should look at pdftools or similar.

Something like pdftools --countpages is what you are looking for

+2
source

You can also use pdf-lib .

You will need to read the file from the input field and then use pdf-lib to get the number of pages. The code will look like this:

 import { PDFDocument } from 'pdf-lib'; ... const readFile = (file) => { return new Promise((resolve, reject) => { const reader = new FileReader(); reader.onload = () => resolve(reader.result); reader.onerror = error => reject(error); reader.readAsArrayBuffer(file); }); } const async getNumPages = (file) => { const arrayBuffer = await readFile(file); const pdf = await PDFDocument.load(arrayBuffer); return pdf.getPages(); } 

And then just get the number of pages of the attached file with:

 const numPages = await getNumPages(input.files[0]); 

being an input variable that stores a reference to the DOM element of the input file.

0
source

All Articles