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

左心房为你撑大大i 提交于 2019-11-26 14:38:43

问题


I have a file input, and before "uploading" i need to calculate the number of pages of that .pdf in JAVASCRIPT (eg. JQuery...)


回答1:


In case you use pdf.js you may reference an example on github ('.../examples/node/getinfo.js') with following code that prints 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);
}



回答2:


and a pure 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 );
}



回答3:


As has been stated in the other answers, something like pdf.js is be what you are looking for. I've taken a look at the API and it does include a numPages() function to return the total number of pages. It also seems to count pages for me when viewing the demo page from Mozilla.

It depends if you are able to use modern browsers and experimental technology for your solution. pdf.js is very impressive, but it is still experimental according to the github page .

If you are able to count the pages on the server after uploading, then you should look at pdftools or similar.

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




回答4:


You could also use pdf-lib.

You will need to read the file from the input field and then make use of pdf-lib to get the number of pages. The code would be 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 input the variable which stores the reference to the DOM element of the file input.



来源:https://stackoverflow.com/questions/10253669/how-to-get-the-number-of-pages-of-a-pdf-uploaded-by-user

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!