Exported PDF is blank if merge and export functions are run from the same Apps Script function

回眸只為那壹抹淺笑 提交于 2019-12-17 17:16:26

问题


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

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

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


回答1:


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

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

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

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



来源:https://stackoverflow.com/questions/50213702/exported-pdf-is-blank-if-merge-and-export-functions-are-run-from-the-same-apps-s

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!