简体   繁体   中英

How to get the number of pages in PDF file?

This is the input field for the document to be uploaded

<ion-item>
<ion-input name='File' required type="file" (change)="getNoOfPages($event)"></ion-input>
</ion-item>

This is the function am calling after the file is selected, am using the string split method to find the type because 'type' does not always holds the file type info, can I use any js library to find the number of pages in uploaded document (pdf in this case) or do I have to use anything in specific to make it work on android? and how?

getNoOfPages(event: any) {
const fileInfo = event.target.files[0];
const type =  fileInfo.name.split('.')[1];
console.log('document uploaded ', fileInfo);
switch (type) {
  case 'docx':

    break;
  case 'pdf':
     console.log('this is a pdf file');
     break;
 }
}

You could use a pure javascript (typescript syntax) solution:

const reader = new FileReader();
const fileInfo = event.target.files[0];
if (fileInfo) {
     reader.readAsBinaryString(event.target.files[0]);
     reader.onloadend = () => {
         const count = reader.result.match(/\/Type[\s]*\/Page[^s]/g).length;
         console.log('Number of Pages:', count);
     }
}

I tested it on many pdf docs and it works.

-Best regards.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM