0
votes

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
Not sure about your issue. However, I would review your code as it calls functions that are deprecated 5 years ago (var body = doc.getActiveSection();).Casper
Your combined function fails to export data because you do not flush the data buffer for doc. This means Apps Script is free to run your code when it wants to, which means your code running via the Drive service doesn't have to wait for your code running via the Document service to finish writing.tehhowch
I see, it's working now, thank you very muchReighend

1 Answers

2
votes

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. :)