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)?
var body = doc.getActiveSection();
). – Casperdoc
. 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