I need to find out how many pages are in my Google Document when it gets exported as a PDF using Google Apps Script.
I wrote some code to try this but it keeps giving me 0 as the result instead of showing the actual page count. Here’s what I tried:
function countDocumentPages() {
var pdfBlob = DocumentApp.getActiveDocument().getAs("application/pdf");
var blobData = pdfBlob.getDataAsString();
var pattern = /Pages\/Count (\d+)/g;
var result;
var totalPages = 0;
while(result = pattern.exec(blobData)) {
Logger.log("FOUND = " + result[1]);
var pageNumber = parseInt(result[1]);
if (pageNumber > totalPages) {
totalPages = pageNumber;
}
}
Logger.log("total pages = " + totalPages);
return totalPages;
}
The function runs without errors but always returns 0. Is there a better way to get the page count from a Google Doc using Apps Script?