6

What should I do to get amount of pages in Google Docs (when converted to PDF) via Google script?

I have tried this, but it returns 0 instead of the number of pages.

function getNumPages() 
{
  var blob = DocumentApp.getActiveDocument().getAs("application/pdf");
   var data = blob.getDataAsString();
   var re = /Pages\/Count (\d+)/g;
   var match;
   var pages = 0;

   while(match = re.exec(data)) {
      Logger.log("MATCH = " + match[1]);

      var value = parseInt(match[1]);

      if (value > pages) {
         pages = value;
      }
   }

   Logger.log("pages = " + pages);

   return pages; 

}
Kyryl Nevedrov
  • 107
  • 2
  • 9

2 Answers2

6

Your regular expression expects a string like Pages/Count 3 in the PDF file. Logging the contents of the file with Logger.log(data) shows there isn't such a string. Instead, I find the number of pages near the beginning of the file:

<< /Linearized 1 /L 18937 /H [ 687 137 ] /O 10 /E 17395 /N 3 /T 18641 >>

The number following /N is the number of pages. Here is a function extracting it:

function getNumPages() {
  var blob = DocumentApp.getActiveDocument().getAs("application/pdf");
  var data = blob.getDataAsString();
  var pages = parseInt(data.match(/ \/N (\d+) /)[1], 10);
  Logger.log("pages = " + pages);
  return pages; 
}
-1
function getNumPages(docId) {
    var pages = 0;
    var blob = DocumentApp.openById(docId).getAs("application/pdf");
    var data = blob.getDataAsString();
    try {
        var matched = data.match(/\/Type[\s]*\/Page[^s]/g);
        pages = matched.length; 
    } catch(err) {
        // NOOP
    }
    return pages; 
}