如何通过Google脚本获取Google文档中的页面数? [英] How to get the number of pages in Google Docs via Google script?

查看:24
本文介绍了如何通过Google脚本获取Google文档中的页面数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我应该怎么做才能通过Google脚本获取Google文档中的页面数量(转换为PDF时)?

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

我已经尝试过了,但是它返回0而不是页面数.

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; 

}

推荐答案

您的正则表达式期望PDF文件中的字符串如 Pages/Count 3 .使用 Logger.log(data)记录文件的内容表明没有这样的字符串.相反,我找到文件开头附近的页数:

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 >>

/N后面的数字是页数.这是提取它的函数:

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; 
}

这篇关于如何通过Google脚本获取Google文档中的页面数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆