如果合并和导出功能是从同一Apps脚本功能运行的,则导出的PDF为空白 [英] Exported PDF is blank if merge and export functions are run from the same Apps Script function

查看:65
本文介绍了如果合并和导出功能是从同一Apps脚本功能运行的,则导出的PDF为空白的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有将多个Google文档组合到一个文件中的代码,以及将文档另存为PDF的代码:

I have code that combines several Google Docs into one file, and code to save a Doc as PDF:

function createPDF(docId) {
  var docFile = DriveApp.getFileById(docId);
  var blob = docFile.getAs('application/pdf');
  var file = DriveApp.createFile(blob);
  file.setName('test.pdf');
}

function mergeDocuments(doc, docIDs){
  var body = doc.getActiveSection();
  for (var i = 0; i < docIDs.length; ++i ) {
    var otherBody = DocumentApp.openById(docIDs[i]).getActiveSection();
    var totalElements = otherBody.getNumChildren();
    for( var j = 0; j < totalElements; ++j ) {
      var element = otherBody.getChild(j).copy();
      var type = element.getType();
      if( type == DocumentApp.ElementType.PARAGRAPH )
        body.appendParagraph(element);
      else if( type == DocumentApp.ElementType.TABLE )
        body.appendTable(element);
      else if( type == DocumentApp.ElementType.LIST_ITEM )
        body.appendListItem(element);
      else
        throw new Error("Unknown element type: "+type);
    }
  }
}

mergeDocument()函数可以很好地用于合并文档,而createPDF()函数也可以很好地工作-如果我一一使用它们.如果将它们组合成一个呼叫,则导出的PDF始终为空白.

The mergeDocument() function works just fine to combine documents, and the createPDF() function also works fine - if I use them one-by-one. If I combine them into a single call, then the exported PDF is always blank.

function mergeAndCreatePDF() {
  var doc = DocumentApp.create('test.doc');
  var docIDs = ['docid0', 'docid1'];

  mergeDocuments(doc, docIDs);
  Logger.log(doc.getId())

  var docFile = DriveApp.getFileById('' + doc.getId());
  var blob = docFile.getAs('application/pdf');
  var file = DriveApp.createFile(blob);
  file.setName('test.pdf');
} 

我如何结合这两种方法,以便可以在一个罐中将它们用于Apps脚本(而不是先运行一个,然后再运行另一个)?

How can I combine the two methods so they can be used in a single can to Apps Script (rather than needing to run one, and then run the other)?

推荐答案

我认为发生这种情况是因为您没有保存和关闭文档.

I think that happening because you're not saving and closing the docs.

https://developers.google.com/apps-script/reference/document/document#saveandclose

并尝试在mergeDocuments函数末尾关闭文档.

And try closing your doc at the end of the mergeDocuments function.

tehhowch也用评论解释了这一点,他也得到了一些赞誉. :)

tehhowch have explained this in comment also, some credit goes to him too. :)

这篇关于如果合并和导出功能是从同一Apps脚本功能运行的,则导出的PDF为空白的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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