I’m working on a Google Apps Script project and need to export a Google Document as a PDF file. I want to do this programmatically without having to manually go through the Documents interface or use any browser tabs.
I’ve been trying to write a script that can handle this conversion automatically, but I’m running into some issues. The goal is to take the current document, convert it to PDF format, and save it to a specific folder in Google Drive.
Here’s what I’ve attempted so far:
function exportDocumentAsPDF() {
const currentDocId = DocumentApp.getActiveDocument().getId();
const targetFolder = DriveApp.getFolderById('1ABC123-sampleFolderID-xyz789')
const sourceFile = DriveApp.getFileById(currentDocId)
const pdfContent = sourceFile.getAs('application/pdf')
targetFolder.createFile(pdfContent);
}
Is there a way to make this work without requiring any manual tab switching or user interaction? Any suggestions would be helpful.
You’re on the right track - this should work without manual steps. I’ve used similar code in several automation projects. Try adding a filename to your createFile() call since leaving it blank sometimes causes issues: targetFolder.createFile(pdfContent.setName('YourDocumentName.pdf')). Make sure your script has the right permissions too. You might need to run it once manually to authorize Drive and Document access. The getAs(‘application/pdf’) method works reliably, but larger documents can take time to process. If you’re still having issues, add a small delay with Utilities.sleep(1000) before the conversion step.
I’ve done this exact thing for our team’s document workflows. Your approach works perfectly - no manual steps needed once it’s set up. Just wrap your conversion in a try-catch block because PDF generation sometimes fails with unsupported elements or huge files. I’d also throw in some console.log() statements to track what’s happening during batch runs. The whole thing runs server-side, so no tab switching or user clicks once you’ve got the permissions sorted. Just make sure your target folder lets the script write files.
your code’s solid but ur missing the filename. instead of just targetFolder.createFile(pdfContent), try targetFolder.createFile(pdfContent.setName(DocumentApp.getActiveDocument().getName() + '.pdf')) - grabs the original doc name automatically. perfect for batch processing multiple docs.