Here is a Google Apps Script to convert a Google Doc to a PDF and save it to your Google Drive. The script accepts the document’s ID, converts it to a PDF, and saves the file in a specified folder.
Script
function convertDocToPdf() {
const docId = "YOUR_DOCUMENT_ID"; // Replace with your Google Doc ID
const folderId = "YOUR_FOLDER_ID"; // Replace with the target folder ID
try {
// Fetch the Google Doc file
const docFile = DriveApp.getFileById(docId);
// Convert the file to a Blob in PDF format
const pdfBlob = docFile.getBlob().setContentType("application/pdf");
// Get the target folder
const folder = DriveApp.getFolderById(folderId);
// Save the PDF to the target folder
const pdfFile = folder.createFile(pdfBlob).setName(docFile.getName() + ".pdf");
Logger.log("PDF created and saved: " + pdfFile.getUrl());
SpreadsheetApp.getUi().alert("PDF created successfully and saved to the folder.");
} catch (e) {
Logger.log("Error: " + e.message);
SpreadsheetApp.getUi().alert("Error: Unable to convert the document to a PDF. " + e.message);
}
}
How It Works:
- Retrieve the Google Doc:
- The script uses the document ID to fetch the Google Doc.
- Convert to PDF:
- The document is converted into a Blob in PDF format.
- Save to Target Folder:
- The script creates a new file in the specified Google Drive folder, naming it the same as the original document with a
.pdf
extension.
- The script creates a new file in the specified Google Drive folder, naming it the same as the original document with a
Setup Instructions:
- Replace
YOUR_DOCUMENT_ID
with the ID of the Google Doc you want to convert.- You can find the ID in the document’s URL:bashCopy code
https://docs.google.com/document/d/DOCUMENT_ID/edit
- You can find the ID in the document’s URL:bashCopy code
- Replace
YOUR_FOLDER_ID
with the ID of the folder where you want to save the PDF.- You can find the ID in the folder’s URL:rubyCopy code
https://drive.google.com/drive/folders/FOLDER_ID
- You can find the ID in the folder’s URL:rubyCopy code
- Save and run the script.
Output:
- A PDF file with the same name as the original Google Doc is created and saved in the specified folder.
- The script logs the URL of the newly created PDF file and displays a success message.
Example Use Case:
- Automate document conversion to PDF for reports, invoices, or contracts and store them in an organized Drive folder.