I've created a simple Google Apps script to convert all Google Documents in a folder in my Drive into PDFs and save them to the same folder, which works:
function convertDocsToPDF() {
var folderId = "asdf";
var folder = DriveApp.getFolderById("folderId");
var invoices = folder.getFiles();
while (invoices.hasNext()) {
var invoice = invoices.next();
var id = invoice.getId();
var file = DriveApp.getFileById(id);
var PDFblob = file.getAs(MimeType.PDF);
var PDF = DriveApp.createFile(PDFblob);
PDF.moveTo(file.getParents().next());
}
}
I wrote this to test out the conversion, but want to integrate it into a longer script. The longer script creates the invoices from a template by replacing ##TextToReplace##
styled fields with data I pull from spreadsheets.
When I try to integrate the convertDocsToPDF()
functionality, the PDFs all look like the template, not the invoice. When I look at the invoice document when the script is done, it looks correct with all the fields replaced with the correct data, but the PDF just looks like a copy of the template.
Is there a lag between when my script edits the invoice and when it is saved in my Drive such that the PDF conversion is seeing the invoice before the replaced text?
This delay may be very small, but a script will be faster.
Document.saveAndClose()
as suggested by @Aaron Dunigan AtLee.Utilities.sleep()
at strategic places in your script.