I’ve actually tackled this issue before in a project. You’re on the right track with your code, but here’s a tweak that should work:
function convertToPDF() {
const fileId = 'YOUR_FILE_ID_HERE';
const file = DriveApp.getFileById(fileId);
const pdfBlob = file.getAs(MimeType.PDF);
const pdfFile = DriveApp.createFile(pdfBlob);
// Optional: Move to a specific folder
const targetFolderId = 'YOUR_FOLDER_ID_HERE';
DriveApp.getFolderById(targetFolderId).addFile(pdfFile);
DriveApp.getRootFolder().removeFile(pdfFile);
}
This approach bypasses the Documents service entirely, working directly with Drive. Just replace the placeholder IDs with your actual file and folder IDs. It’s been reliable for me in automating PDF conversions across multiple docs.
I’ve used a similar approach in my work, and it’s quite effective. One thing to keep in mind is that while this method works well for basic documents, it might not perfectly preserve complex formatting or embedded elements. If you’re dealing with a large number of files, you might want to add some error handling and logging to your script. Something like:
function convertToPDF() {
try {
// Your conversion code here
Logger.log('Conversion successful for file: ' + fileId);
} catch (error) {
Logger.log('Error converting file ' + fileId + ': ' + error.toString());
}
}
This way, you can track which files converted successfully and which ones encountered issues. It’s been a lifesaver for me when batch processing documents.