简体   繁体   English

如何通过谷歌脚本获取谷歌文档中的页数?

[英]How to get the number of pages in Google Docs via Google script?

What should I do to get amount of pages in Google Docs (when converted to PDF) via Google script?我应该怎么做才能通过 Google 脚本获取 Google Docs 中的页面数量(转换为 PDF 时)?

I have tried this, but it returns 0 instead of the number of pages.我试过这个,但它返回 0 而不是页数。

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; 

}

Your regular expression expects a string like Pages/Count 3 in the PDF file. 您的正则表达式需要PDF文件中的Pages/Count 3等字符串。 Logging the contents of the file with Logger.log(data) shows there isn't such a string. 使用Logger.log(data)记录文件的内容显示没有这样的字符串。 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. 后面的数字/ N是页数。 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; 
}
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; 
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM