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