To use this script, follow these steps:
- Open a Google Sheet that you want to generate a PDF file from.
- Go to the “Tools” menu and select “Script editor.”
- Copy and paste the code I provided into the script editor.
- Replace the FOLDER_ID placeholder in the code with the ID of the folder where you want to save the PDF file.
- Save the script and close the script editor.
- Go back to your Google Sheet and run the script by selecting the function name (generatePdf) from the “Run” menu.
When you run the script, it will generate a PDF file from the active sheet and save it to the specified folder in Google Drive. The file name will be “My Spreadsheet.pdf” by default, but you can change this in the code if needed. The script will then display a message with the URL of the PDF file.
The code to paste in Google Sheets
function generatePdf() {
// Get the active sheet
var sheet = SpreadsheetApp.getActiveSheet();
// Get the data range
var range = sheet.getDataRange();
// Get the blob of the PDF file
var pdfBlob = sheet.getAs("application/pdf");
// Save the PDF file to Drive
var fileName = "My Spreadsheet.pdf";
var folder = DriveApp.getFolderById("FOLDER_ID"); // Replace FOLDER_ID with the ID of the folder where you want to save the file
var file = folder.createFile(pdfBlob);
file.setName(fileName);
// Display a message with the URL of the PDF file
var message = "PDF file generated: " + file.getUrl();
Browser.msgBox(message);
}