1

I use Google Script to create a Google Docs file and want to get the page number of this document as soon as I have finished creating the content of the document. I used the following code at the end of my program:

var data = doc.getAs("application/pdf").getDataAsString();
    var pages = data.match(/\/Contents/g).length;
    Logger.log(pages);

No matter how many pages the newly created document has, the result I get is always pages = 1.0. Actually I used the existing code, so I don't understand it well. I really need help. Thank you.

  • Although I'm not sure about your whole script and whether I could correctly understand your actual situation, I proposed a modification point. Could you please confirm it? If I misunderstood your actual situation and that was not the solution to your situation, I apologize. – Tanaike Nov 26 '22 at 05:17

1 Answers1

0

From your following situation,

No matter how many pages the newly created document has, the result I get is always pages = 1.0.

Although I'm not sure about your whole script and whether I could correctly understand your actual situation, I guessed that saveAndClose() might be the direct solution to your issue. So, how about the following modification?

Modified script:

doc.saveAndClose(); // <--- Added
// doc = DocumentApp.getActiveDocument(); // or DocumentApp.openById("###")

var data = doc.getAs("application/pdf").getDataAsString();
var pages = data.match(/\/Contents/g).length;
Logger.log(pages);
  • If your script uses doc after your showng script, please use doc = DocumentApp.getActiveDocument(); // or DocumentApp.openById("###").

Reference:

Tanaike
  • 181,128
  • 11
  • 97
  • 165
  • I ran a test, of course it was perfect. Thank you very much @tanaike. Also I have more knowledge about `saveAndClose()`. – Lê Phong Nguyễn Nov 26 '22 at 08:46
  • @Lê Phong Nguyễn Thank you for replying. I'm glad your issue was resolved. – Tanaike Nov 26 '22 at 11:15
  • Somehow when I copy this code to another Google account, it gives an error: `Exception: Document is closed, its contents cannot be updated.`. @tanaike, Can you help me explain why? – Lê Phong Nguyễn Nov 30 '22 at 07:20
  • @Lê Phong Nguyễn About your new question of `Somehow when I copy this code to another Google account, it gives an error: Exception: Document is closed, its contents cannot be updated.. @tanaike, Can you help me explain why?`, I would like to support you. So, can you post it as a new question? In that time, please include more information. If you can cooperate to resolve your new question, I'm glad. Can you cooperate to do it? – Tanaike Nov 30 '22 at 12:16