DavidF
DavidF

Reputation: 1345

How do I find the page number/number of pages in a document?

I want to create a new document based on a template and need to know when my insertion or append results in a new page in the final printed output is there any property/attribute eg number of pages that can be used for this?

Upvotes: 5

Views: 2959

Answers (3)

Wicket
Wicket

Reputation: 38160

As the accepted answer states, still, as of August 2, 2024, there is no built-in way in Documents Service nor the Advanced Docs Service / Google Documents API to get to the page count of a Google Docs file.

Workaround

Disclaimer: A previous answer, created ten years ago, suggested this, but the code no longer works.

Convert the document to PDF, get the converted file content as a string and parse the number of pages from there.

Below is an example.

function getNumPages() {
  const doc = DocumentApp.getActiveDocument();
  const blob = doc.getAs("application/pdf");
  const data = blob.getDataAsString();
  const n = data.split("/Contents").length - 1;
  Logger.log(n);
}

The idea of using String.prototype.split("/Contents").length - 1 was taken from Tainake's answer to Count total number of pages in pdf file. Tainake's answer was created in 2019.

This way might stop working at any time without notice because it wasn't publicly disclosed how the Google Docs files are converted to PDF. On the same answer, Tainake mentions other workarounds that rely on external libraries.

IMO, this workaround is good enough for most projects with a short life expectancy.

Related

Upvotes: 0

ColdCold
ColdCold

Reputation: 4337

One way to get total number of pages:

function countPages() {
   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; 
}

Upvotes: -1

Henrique G. Abreu
Henrique G. Abreu

Reputation: 17752

I've search this a lot in the past and I don't think there's any property or any other way to know page info.

The solution I use is to insert page breaks on my template or via the script, using my own knowledge of how my template works, i.e. how much space it takes as I iterate, etc. And then I know which page I am by counting the page breaks.

Anyway, you could an enhancement request on the issue tracker.

Upvotes: 3

Related Questions