google-apps-scriptpdfgoogle-drive-api

Count total number of pages in pdf file


Every week, I'll be receiving a set of pdf files from my clients.

They will paste the pdf files in the specific google drive folder. I need a total number of pages of the pdf file. I was trying to create a code in Apps script which will helps to update the pdf file name and the total number of pages in the particular Google sheet.

I found the code which was created for the google docs here and here.

But that doesn't work. I am looking for a Apps script which helps to check the particular drive folder and update the pdf file name and the total number of pages in the specific google sheet.

I have tried to below script.

function getNumberofPages() {
  var myFolder = DriveApp.getFoldersByName("Test").next();
  var files = myFolder.searchFiles('title contains ".PDF"');
  while (files.hasNext()) {
    var file = files.next();
    Logger.log(file.getName());
    Logger.log(file.length);
  }
}

But the length option is not working of pdf file....


Solution

  • function menuItem() {
    var folder = 
    DriveApp.getFoldersByName('Test').next();
    var contents = folder.searchFiles('title contains ".PDF"');
    var file;
    var name;
    var sheet = SpreadsheetApp.getActiveSheet();
    var count;
    
    sheet.clear();
    sheet.appendRow(["Name", "Number of pages"]);
    
    while(contents.hasNext()) {
    file = contents.next();
    name = file.getName();
    count = 
    file.getBlob().getDataAsString().split("/Contents").length - 1;
    
    data = [name, count]
    sheet.appendRow(data);
    }
    };
    
    
    function onOpen() {
    var ui = SpreadsheetApp.getUi();
    ui.createMenu('PDF Page Calculator')
              .addItem("PDF Page Calculator", 
    'menuItem')
    .addToUi();
    };