Emailing Google Sheet as PDF - email

I have this script that emails me a PDF of the Google Spreadsheet. I only want it to email me the first 'Tab' and if possible as a single PDF vice a zip file.
Wondered if anyone could help. Also one of the 'Tabs' are hidden, so I don't know if that has an impact. He is a link to the sample sheet.
The code is shown below:
/* Send Spreadsheet in an email as PDF, automatically */
function emailSpreadsheetAsPDF() {
// Send the PDF of the spreadsheet to this email address
var email = "xxxxx#gmail.com";
// Get the currently active spreadsheet URL (link)
// Or use SpreadsheetApp.openByUrl("<<SPREADSHEET URL>>");
var ss = SpreadsheetApp.getActiveSpreadsheet();
// Subject of email message
var subject = "Sample Sheet " + ss.getName();
// Email Body can be HTML too with your logo image - see ctrlq.org/html-mail
var body = "Install the <a href='http://www.labnol.org/email-sheet'>Email Spreadsheet add-on</a> for one-click conversion.";
// Base URL
var url = "https://docs.google.com/spreadsheets/d/SS_ID/export?".replace("SS_ID", ss.getId());
/* Specify PDF export parameters
From: https://code.google.com/p/google-apps-script-issues/issues/detail?id=3579
*/
var url_ext = 'exportFormat=pdf&format=pdf' // export as pdf / csv / xls / xlsx
+ '&size=letter' // paper size legal / letter / A4
+ '&portrait=false' // orientation, false for landscape
+ '&fitw=true&source=labnol' // fit to page width, false for actual size
+ '&sheetnames=false&printtitle=false' // hide optional headers and footers
+ '&pagenumbers=false&gridlines=false' // hide page numbers and gridlines
+ '&fzr=false' // do not repeat row headers (frozen rows) on each page
+ '&gid='; // the sheet's Id
var token = ScriptApp.getOAuthToken();
var sheets = ss.getSheets();
//make an empty array to hold your fetched blobs
var blobs = [];
for (var i=0; i<sheets.length; i++) {
// Convert individual worksheets to PDF
var response = UrlFetchApp.fetch(url + url_ext + sheets[i].getSheetId(), {
headers: {
'Authorization': 'Bearer ' + token
}
});
//convert the response to a blob and store in our array
blobs[i] = response.getBlob().setName(sheets[i].getName() + '.pdf');
}
//create new blob that is a zip file containing our blob array
var zipBlob = Utilities.zip(blobs).setName(ss.getName() + '.zip');
//optional: save the file to the root folder of Google Drive
DriveApp.createFile(zipBlob);
// Define the scope
Logger.log("Storage Space used: " + DriveApp.getStorageUsed());
// If allowed to send emails, send the email with the PDF attachment
if (MailApp.getRemainingDailyQuota() > 0)
GmailApp.sendEmail(email, subject, body, {
htmlBody: body,
attachments:[zipBlob]
});
}
//**************************************************************************
// Revised Code
//**************************************************************************
/* Send Spreadsheet in an email as PDF, automatically */
function emailSpreadsheetAsPDF() {
// Send the PDF of the spreadsheet to this email address
var email = "xxxxx#gmail.com";
// Get the currently active spreadsheet URL (link)
// Or use SpreadsheetApp.openByUrl("<<SPREADSHEET URL>>");
var ss = SpreadsheetApp.getActiveSpreadsheet();
// Subject of email message
var subject = "PDF generated from spreadsheet " + ss.getName();
// Email Body can be HTML too with your logo image - see ctrlq.org/html-mail
var body = "Install the <a href='http://www.labnol.org/email-sheet'>Email Spreadsheet add-on</a> for one-click conversion.";
// Base URL
var url = "https://docs.google.com/spreadsheets/d/SS_ID/export?".replace("SS_ID", ss.getId());
/* Specify PDF export parameters
From: https://code.google.com/p/google-apps-script-issues/issues/detail?id=3579
*/
var url_ext = 'exportFormat=pdf&format=pdf' // export as pdf / csv / xls / xlsx
+ '&size=letter' // paper size legal / letter / A4
+ '&portrait=false' // orientation, false for landscape
+ '&fitw=true&source=labnol' // fit to page width, false for actual size
+ '&sheetnames=false&printtitle=false' // hide optional headers and footers
+ '&pagenumbers=false&gridlines=false' // hide page numbers and gridlines
+ '&fzr=false' // do not repeat row headers (frozen rows) on each page
+ '&gid='; // the sheet's Id
var token = ScriptApp.getOAuthToken();
var sheets = ss.getSheets();
//make an empty array to hold your fetched blobs
var blobs = [];
//for (var i=0; i<sheets.length; i++) {
for (var i=0; i<1; i++) {
// Convert individual worksheets to PDF
var response = UrlFetchApp.fetch(url + url_ext + sheets[i].getSheetId(), {
headers: {
'Authorization': 'Bearer ' + token
}
});
//convert the response to a blob and store in our array
// blobs[i] = response.getBlob().setName(sheets[i].getName() + '.pdf');
}
//create new blob that is a zip file containing our blob array
// var zipBlob = Utilities.zip(blobs).setName(ss.getName() + '.zip');
//optional: save the file to the root folder of Google Drive
//DriveApp.createFile(zipBlob);
// Define the scope
Logger.log("Storage Space used: " + DriveApp.getStorageUsed());
// If allowed to send emails, send the email with the PDF attachment
if (MailApp.getRemainingDailyQuota() > 0)
GmailApp.sendEmail(email, subject, body, {
htmlBody: body,
//attachments:[zipBlob]
});
}
Kind Regards
Al

In your code, you are getting both sheets as blobs and zipping them??
The easiest fix it is to change for (var i=0; i<sheets.length; i++) { to for (var i=0; i<1; i++) { so it only gets the first tab and zips it.
UPDATE Based on comments.
function emailSpreadsheetAsPDF() {
var email = ""; // Enter the required email address here
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName("**********"); // Enter the name of the sheet here
var subject = "PDF generated from spreadsheet " + ss.getName();
var body = "\n Attached is a PDF copy of the sheet " + sheet.getName() + " in the " + ss.getName() + " spreadsheet.";
// Base URL
var url = "https://docs.google.com/spreadsheets/d/SS_ID/export?".replace("SS_ID", ss.getId());
/* Specify PDF export parameters
From: https://code.google.com/p/google-apps-script-issues/issues/detail?id=3579
*/
var url_ext = 'exportFormat=pdf&format=pdf' // export as pdf / csv / xls / xlsx
+ '&size=letter' // paper size legal / letter / A4
+ '&portrait=false' // orientation, false for landscape
+ '&fitw=true&source=labnol' // fit to page width, false for actual size
+ '&sheetnames=false&printtitle=false' // hide optional headers and footers
+ '&pagenumbers=false&gridlines=false' // hide page numbers and gridlines
+ '&fzr=false' // do not repeat row headers (frozen rows) on each page
+ '&gid='; // the sheet's Id
var token = ScriptApp.getOAuthToken();
var response = UrlFetchApp.fetch(url + url_ext + sheet.getSheetId(), {
headers : {
'Authorization' : 'Bearer ' + token
}
}).getBlob().setName(sheet.getName() + ".pdf");
// Uncomment the line below to save the PDF to the root of your drive.
// var newFile = DriveApp.createFile(response).setName(sheet.getName() + ".pdf")
if (MailApp.getRemainingDailyQuota() > 0)
GmailApp.sendEmail(email, subject, body, {
htmlBody : body,
attachments : [response]
});
}

Related

How To Send Multiple Attachments From Google Form Uploaded Files And PDF Caputured Range From Spreadsheet OnSubmit?

What I'm trying to do is onSubmit script in google sheets from a submitted google forms include the uploaded PDFs from google form submittion and area of spreadsheet with some of the conolidated data
I dont know how to combine the url lists from the google form submission where a single cell may contain multile URLs to upload PDF or none at all
function myFunction() {
DocumentApp.getActiveDocument();
DriveApp.getFiles();
const ss = SpreadsheetApp.openByUrl("https://docs.google.com/spreadsheets/d/1ELQ-SvRwWRmqDae1xz_-062oIs5RrzsQzYs7zFrCdxk/edit");
var ss_formUrl = SpreadsheetApp.getActiveSpreadsheet().getFormUrl;
var ss_dynamic = SpreadsheetApp.getActiveSheet().getSheetId();
var ccemail = 'bruno.brottes#gmail.com';
var email = ss.getSheetByName("DATA").getRange("E1").getValue().toString();
var company = ss.getSheetByName("DATA").getRange("B1").getValue().toString();
var attachments1 = ss.getSheetByName("DATA").getRange("J1").getValue().toString();
//MIMETYPE:PDF
//drive.google.com/open?id=1IpuzbJO3LnSV80iAr6OZ-jSrn5ht7uYT
var attachments2 = ss.getSheetByName("DATA").getRange("P1").getValue().toString();
//MIMETYPE:PDF
//drive.google.com/open?id=1IpuzbJO3LnSV80iAr6OZ-jSrn5ht7uYT
var attachments3 = ss.getSheetByName("DATA").getRange("V1").getValue().toString();
//MIMETYPE:PDF
//drive.google.com/open?id=1lSnyBdfPFWvxVRedZo_SgK6HTLoTfFuA,
//drive.google.com/open?id=19g8oKib4sSvEVHDAO4IGd1hhJsJ-jY_A,
//drive.google.com/open?id=1WxOJCD0STFLOQ4Lw0Mw4ZOAQ3OVUx9-k
var attachments4 = ss.getSheetByName("DATA").getRange("AQ1").getValue().toString();
//MINETYPE:PDF
//drive.google.com/open?id=116ijk7n_CdmKWS6Z_aN0IlKJ1vNoeY7I
var attachments5 = ss.getSheetByName('DATA').getRange('AS1').getValue().toString();
//MINITYPE:ZIP
var combinedAttachments = ['attachments1','attachments2','attachments3','attachments4','attachments5'];
var combinedAll = ss_dynamic.getRange(combinedAttachments);
var combinedAll = combinedAttachments1.concat(combinedAttachments2).concat(combinedAttachments3).concat(combinedAttachments4);
for (var i = 0; i < combinedAll.length; i++)
{
var files = DriveApp.createFile(combinedAll[i]);
attachments.push(files);
}
if(files){
var files = files.split(', ');
}
const subject = 'Year-End.' + procedure + ".company" + ".pdf";
const body = "See Attached";
const url = 'https://docs.google.com/spreadsheets/d/1ELQ-SvRwWRmqDae1xz_-062oIs5RrzsQzYs7zFrCdxk/export?';
const exportOptions =
'exportFormat=pdf&format=pdf' + // export as pdf
'&size=letter' + // paper size letter / You can use A4 or legal
'&portrait=true' + // orientation portal, use false for landscape
'&fitw=true' + // fit to page width false, to get the actual size
'&fith=true' +
'&top_margin=0.25' + //All four margins must be set!
'&bottom_margin=0.25' + //All four margins must be set!
'&left_margin=0.25' + //All four margins must be set!
'&right_margin=0.25' + //All four margins must be set!
'&sheetnames=false&printtitle=false' + // hide optional headers and footers
'&pagenumbers=false&gridlines=false' + // hide page numbers and gridlines
'&fzr=false' + // do not repeat row headers (frozen rows) on each page
'&gid=2051090571' + // the sheet's Id. Change it to your sheet ID.
// Here is the part for selecting range to export to PDF
'&ir=false' + //seems to be always false
'&ic=false' + //same as ic
'&r1=0' + //Start Row number - 1, so row 1 would be 0 , row 15 wold be 14
'&c1=0' + //Start Column number - 1, so column 1 would be 0, column 8 would be 7
'&r2=37' + //End Row number
'&c2=10'; //End Column number
var params = {method:"GET",headers:{"authorization":"Bearer "+ ScriptApp.getOAuthToken()}};
var response = UrlFetchApp.fetch(url+exportOptions, params).getBlob();
GmailApp.sendEmail(email, subject, body, {
htmlBody: body,
cc: ccemail,
attachments: [{
fileName: "Corporate Year-End Checklist." + company + ".pdf",
content: response.getBytes(),
mimeType: "application/pdf"
},
files
]
});
}

Send PDF Attachment of Active Sheet with Email Cell Reference in Same Active Sheet

I am trying to send the active sheet and only the active sheet as a pdf attachment to an email located in cell C1 or (1,3)
The current script executes but I receive no email.
function sendSheetToPdf(){
}
var ss = SpreadsheetApp.getActiveSpreadsheet();
var ssId = SpreadsheetApp.getActiveSpreadsheet().getId();
var sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
var sheetName = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet().getName();
var email = sheet.getRange(1,3).getValue();
// Base URL
var url = "mysheetsurl", ss.getId());
/* Specify PDF export parameters
From: https://code.google.com/p/google-apps-script-issues/issues/detail?id=3579
*/
var url_ext = 'exportFormat=pdf&format=pdf' // export as pdf / csv / xls / xlsx
+ '&size=A4' // paper size legal / letter / A4
+ '&portrait=true' // orientation, false for landscape
+ '&fitw=true&source=labnol' // fit to page width, false for actual size
+ '&sheetnames=false&printtitle=false' // hide optional headers and footers
+ '&pagenumbers=false&gridlines=false' // hide page numbers and gridlines
+ '&fzr=false' // do not repeat row headers (frozen rows) on each page
+ '&gid='; // the sheet's Id
var token = ScriptApp.getOAuthToken();
var response = UrlFetchApp.fetch(url + url_ext + sheet.getSheetId(), {
headers : {
'Authorization' : 'Bearer ' + token
}
}).getBlob().setName(sheet.getName() + ".pdf");
sheet_as_pdf_blob_document=response;
// Email Business
var recipient = email;
var subject="Test"
var body="TEST.";
var nameOfSender="Test";
// Here we send the email
function sendReport() {
var message = {
to: recipient,
subject: subject,
body: body,
name: nameOfSender,
attachments: [sheet_as_pdf_blob_document]
}
MailApp.sendEmail(message);
}
I've written scripts that sent emails before successfully but never without designating the sheet name and email address. This time I wanted to create a dynamic way to send emails based on the active sheet. Thanks in advance!
Issues in your current code:
Your function structure is not correct. Your code should show you failed execution logs upon running this in your editor.
Here is what it looks like:
function sendSheetToPdf(){
}
// process the sheet data and get pdf blob
function sendReport() {
//send email
}
Your base url is incorrect. Based on your reference material Specify PDF export parameters, your base url should be like this:
var url = "https://docs.google.com/spreadsheets/d/" + doc.getId() + "/export?
Sample Working Code:
function sendSheetToPdf(){
var ss = SpreadsheetApp.getActiveSpreadsheet();
var ssId = SpreadsheetApp.getActiveSpreadsheet().getId();
var sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
var sheetName = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet().getName();
var email = sheet.getRange(1,3).getValue();
// Base URL
var url = "https://docs.google.com/spreadsheets/d/"+ ss.getId()+"/export?";
/* Specify PDF export parameters
From: https://code.google.com/p/google-apps-script-issues/issues/detail?id=3579
*/
var url_ext = 'exportFormat=pdf&format=pdf' // export as pdf / csv / xls / xlsx
+ '&size=A4' // paper size legal / letter / A4
+ '&portrait=true' // orientation, false for landscape
+ '&fitw=true&source=labnol' // fit to page width, false for actual size
+ '&sheetnames=false&printtitle=false' // hide optional headers and footers
+ '&pagenumbers=false&gridlines=false' // hide page numbers and gridlines
+ '&fzr=false' // do not repeat row headers (frozen rows) on each page
+ '&gid='; // the sheet's Id
var token = ScriptApp.getOAuthToken();
var response = UrlFetchApp.fetch(url + url_ext + sheet.getSheetId(), {
headers : {
'Authorization' : 'Bearer ' + token
}
}).getBlob().setName(sheet.getName() + ".pdf");
var sheet_as_pdf_blob_document=response;
// Email Business
var recipient = email;
var subject="Test"
var body="TEST.";
var nameOfSender="Test";
// Here we send the email
var message = {
to: recipient,
subject: subject,
body: body,
name: nameOfSender,
attachments: [sheet_as_pdf_blob_document]
}
MailApp.sendEmail(message);
}
I just fixed your base url, move sendReport() content inside sendSheetToPdf() because the variables needed to send the email were declared inside sendSheetToPdf().
Output:

Google Sheets - Create PDF and Send Email (Different PDFs to Different Emails)

I have a Google Sheet that updates information based on an Athlete Name that is in a specific cell (A24 in the "Dashboard" worksheet). Once the athlete name changes (e.g., A24 changes to a different athlete name), the information on the "Dashboard" worksheet changes to reflect the data for that athlete.
I have a list of athlete names (athleteList) and athlete emails (emails). Essentially, I want the script to do the following in a loop:
Update athlete name to athlete[i] in athlete list
Create PDF of the "Dashboard" worksheet (which is now updated to be athlete[i])
Send email of that PDF to athlete[i] (e.g., using their email, which is email[i]).
I'm new to Google Apps Script so I hope this makes sense... I'm very close. The emailing works fine with the code below, but the PDFs being created are not the right ones for the people receiving the emails. Any assistance would be appreciated. Thank you!
Link to editable sheet (different URL and GID than code): https://docs.google.com/spreadsheets/d/1Amkc1tDgLgaNxKCos95vsZEaxdyd67Xcdtfc4NEQT60/edit?usp=sharing
APPS SCRIPT CODE CODE:
//Google Sheets URL Edit (Athletes Sheet Name)
//Google Sheets URL Edit (Dashboard Sheet Name)
//Google Sheets URL Export (Dashboard Sheet Name)
var ss = SpreadsheetApp.openByUrl("https://docs.google.com/spreadsheets/d/1z15EwpuITPnmqPAIwHdxyV6DFDGMLBWKCxpDCQrGtBw/edit/");
var ssAthletes = SpreadsheetApp.openByUrl("https://docs.google.com/spreadsheets/d/1z15EwpuITPnmqPAIwHdxyV6DFDGMLBWKCxpDCQrGtBw/edit/").getSheetByName("Athletes");
var ssDashboard = SpreadsheetApp.openByUrl("https://docs.google.com/spreadsheets/d/1z15EwpuITPnmqPAIwHdxyV6DFDGMLBWKCxpDCQrGtBw/edit/").getSheetByName("Dashboard");
var ssDashboardExport = SpreadsheetApp.openByUrl("https://docs.google.com/spreadsheets/d/1z15EwpuITPnmqPAIwHdxyV6DFDGMLBWKCxpDCQrGtBw/export?/").getSheetByName("Dashboard");
var lastRow = ssAthletes.getLastRow()-1; //Define last Row
var athleteList = ssAthletes.getRange(2,1,lastRow).getValues(); //get list of Athletes (Starting at row 2, column 1)
var athleteEmails = ssAthletes.getRange(2,2,lastRow).getValues();
//THIS FUNCTION EMAILS as PDF
function emailSpreadsheetAsPDF() {
DocumentApp.getActiveDocument();
DriveApp.getFiles();
// This is the link to my spreadsheet with the Form responses and the Invoice Template sheets
// Add the link to your spreadsheet here
// or you can just replace the text in the link between "d/" and "/edit"
// In my case is the text: 17I8-QDce0Nug7amrZeYTB3IYbGCGxvUj-XMt8uUUyvI
// const ss = SpreadsheetApp.openByUrl("https://docs.google.com/spreadsheets/d/1z15EwpuITPnmqPAIwHdxyV6DFDGMLBWKCxpDCQrGtBw/edit");
// We are going to get the email address from the cell "E2" from the "Lists" sheet
// Change the reference of the cell or the name of the sheet if it is different
const value = ss.getSheetByName("Lists").getRange("E2").getValue();
const email = value.toString();
for (var i = 0; i < athleteList.length; ++i) {
athleteName = athleteList[i];
}
// Subject of the email message
const subject = 'Your Report';
// Email Text. You can add HTML code here - see ctrlq.org/html-mail
const body = "Hey " + athleteName + "! Great work today. Here is your report for " + Date();
// Again, the URL to your spreadsheet but now with "/export" at the end
// Change it to the link of your spreadsheet, but leave the "/export"
const url = 'https://docs.google.com/spreadsheets/d/1z15EwpuITPnmqPAIwHdxyV6DFDGMLBWKCxpDCQrGtBw/export?';
const exportOptions =
'exportFormat=pdf&format=pdf' + // export as pdf
'&size=letter' + // paper size letter / You can use A4 or legal
'&portrait=true' + // orientation portal, use false for landscape
'&fitw=true' + // fit to page width false, to get the actual size
'&sheetnames=false&printtitle=false' + // hide optional headers and footers
'&pagenumbers=false&gridlines=false' + // hide page numbers and gridlines
'&fzr=false' + // do not repeat row headers (frozen rows) on each page
'&gid=680445839'; // the sheet's Id. Change it to your sheet ID.
// You can find the sheet ID in the link bar.
// Select the sheet that you want to print and check the link,
// the gid number of the sheet is on the end of your link.
var params = {method:"GET",headers:{"authorization":"Bearer "+ ScriptApp.getOAuthToken()}};
// Generate the PDF file
var response = UrlFetchApp.fetch(url+exportOptions, params).getBlob();
// Send the PDF file as an attachement
GmailApp.sendEmail(email, subject, body, {
htmlBody: body,
attachments: [{
fileName: "Dashboard" + Date() + ".pdf",
content: response.getBytes(),
mimeType: "application/pdf"
}]
})}
//THIS FUNCTION EMAILS MULTIPLE PEOPLE as PDF -- WORK IN PROGRESS!!!
function emailSpreadsheetAsPDFMulti() {
DocumentApp.getActiveDocument();
DriveApp.getFiles();
// This is the link to my spreadsheet with the Form responses and the Invoice Template sheets
// Add the link to your spreadsheet here
// or you can just replace the text in the link between "d/" and "/edit"
// In my case is the text: 17I8-QDce0Nug7amrZeYTB3IYbGCGxvUj-XMt8uUUyvI
// const ss = SpreadsheetApp.openByUrl("https://docs.google.com/spreadsheets/d/1z15EwpuITPnmqPAIwHdxyV6DFDGMLBWKCxpDCQrGtBw/edit");
// We are going to get the email address from the cell "E2" from the "Lists" sheet
// Change the reference of the cell or the name of the sheet if it is different
const emails = ss.getSheetByName("Athletes").getRange(2,2,lastRow).getValues();
const emailsString = emails.toString();
// for (var i = 0; i < athleteList.length; ++i) {
// athleteName = athleteList[i];
// }
for (var i = 0; i < emails.length; ++i) {
athleteEmail = emails[i];
athleteName = athleteList[i];
}
// Again, the URL to your spreadsheet but now with "/export" at the end
// Change it to the link of your spreadsheet, but leave the "/export"
const url = 'https://docs.google.com/spreadsheets/d/1z15EwpuITPnmqPAIwHdxyV6DFDGMLBWKCxpDCQrGtBw/export?';
const exportOptions =
'exportFormat=pdf&format=pdf' + // export as pdf
'&size=letter' + // paper size letter / You can use A4 or legal
'&portrait=true' + // orientation portal, use false for landscape
'&fitw=true' + // fit to page width false, to get the actual size
'&sheetnames=false&printtitle=false' + // hide optional headers and footers
'&pagenumbers=false&gridlines=false' + // hide page numbers and gridlines
'&fzr=false' + // do not repeat row headers (frozen rows) on each page
'&gid=680445839'; // the sheet's Id. Change it to your sheet ID.
// You can find the sheet ID in the link bar.
// Select the sheet that you want to print and check the link,
// the gid number of the sheet is on the end of your link.
// Cycle through athletes
for (var i = 0; i < athleteList.length; i++) {
var output = [];
ssDashboard.getRange('A24').setValue(athleteList[i][0]);
output.push([athleteList[i][0]]);
Utilities.sleep(10000);
// Generate the PDF file
var params = {method:"GET",headers:{"authorization":"Bearer "+ ScriptApp.getOAuthToken()}};
var response = UrlFetchApp.fetch(url+exportOptions, params).getBlob();
// Subject of the email message
const subject = 'Report'
var athletename = athleteList[i][0];
// Email Text. You can add HTML code here - see ctrlq.org/html-mail
const body = "Hey " + athletename + "! Great work today. Here is your report for " + Date();
console.log(output);
console.log(response);
console.log(body);
console.log(athletename);
console.log(emails[i]);
// Send the PDF file as an attachement
GmailApp.sendEmail(emails[i], subject, body, {
htmlBody: body,
attachments: [{
fileName: "Dashboard" + Date() + ".pdf",
content: response.getBytes(),
mimeType: "application/pdf"
}]
})}}'''
I think you almost got it. This is how I would do it.
Please don't forget to update the Id of the spreadsheet
function updateInfo(){
// I get the emails from the Athletes sheet, hope is ok, otherwise you can point in to another range
var athleteSheet = SpreadsheetApp.getActive().getSheetByName("Athletes");
var athleteList = athleteSheet.getRange("A2:B"+athleteSheet.getLastRow()).getValues();
for (i=0;i<athleteList.length;i++){
var name = athleteList[i][0];
var email = athleteList[i][1];
SpreadsheetApp.getActive().getSheetByName("Dashboard").getRange("A24").setValue(name);
SpreadsheetApp.flush(); // this is important for the changes in the spreadsheet to take place
sendInfo(name, email); // then I send the emails
}
}
Now I used a very similar function to yours and send the files
function sendInfo(name, email){
// change the id (this is the id of my file, a copy of yours)
var ss = SpreadsheetApp.openById('1uftGO8ACoQTE8LtjURjIG2g5G-x3B-taIobVxzvJA2E');
var sheet = ss.getSheetByName("Dashboard");
var ssId = ss.getId();
// export url
var url = 'https://docs.google.com/spreadsheets/d/'+ ssId +'/export?'
+ 'exportFormat=pdf&format=pdf'
+ '&size=letter' // paper size legal / letter / A4
+ '&portrait=true' // orientation, false for landscape
+ '&fitw=true' // fit to page width, false for actual size
+ '&sheetnames=false&printtitle=false' // hide optional headers and footers
+ '&pagenumbers=false&gridlines=false' // hide page numbers and gridlines
+ '&fzr=false' // do not repeat row headers (frozen rows) on each page
+ '&gid='+sheet.getSheetId(); // the sheet's Id
var headers = {
'Authorization': 'Bearer ' + ScriptApp.getOAuthToken()
}
// request export url
var response = UrlFetchApp.fetch(url, { headers: headers });
var blob = response.getBlob();
const subject = 'Your Report';
const body = "Sent via Generate Dashboard Report from Google Form and print/email it";
GmailApp.sendEmail(email, subject, body, {
htmlBody: body,
attachments: [{
fileName: "Dashboard.pdf",
content: blob.getBytes(),
mimeType: "application/pdf"
}]
});
DriveApp.createFile(blob.setName(name+".pdf"))
}
By the way, nice work you have done with those spreadsheets.

Google sheets apps script, how to format a pdf saved to google drive?

im using this script in order to save the curren tab as a pdf to specific folder
function SaveAsPDF() {
SpreadsheetApp.flush();
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sourceSpreadsheet = SpreadsheetApp.getActive(); // Get active spreadsheet.
var sheetName = sourceSpreadsheet.getActiveSheet().getName();
var pdfName = sheetName + ".pdf"; // Set the output filename as SheetName.
folder = DriveApp.getFolderById('ID');
var theBlob = createblobpdf(sheetName, pdfName);
var existing = folder.getFilesByName(pdfName); //returns file iterator;
var hasFile = existing.hasNext(); //check if iterator isn't empty;
if (hasFile) {
var duplicate = existing.next(); //access file;
//delete file;
var durl = 'https://www.googleapis.com/drive/v3/files/' + duplicate.getId();
var token = ScriptApp.getOAuthToken();
var dres = UrlFetchApp.fetch(durl, {
method: 'delete',
muteHttpExceptions: true,
headers: { 'Authorization': 'Bearer ' + token }
});
if (dres.getResponseCode() >= 400) {
//handle errors;
}
}
var newFile = folder.createFile(theBlob);
sourceSpreadsheet.toast("Saved ", "Success");
}
function createblobpdf(sheetName, pdfName) {
var sourceSpreadsheet = SpreadsheetApp.getActive();
var sourceSheet = sourceSpreadsheet.getSheetByName(sheetName);
var url = 'https://docs.google.com/spreadsheets/d/' + sourceSpreadsheet.getId()
+ '/export'
+ '?format=pdf'
+ '&size=letter' // paper size legal / letter / A4
+ '&portrait=true' // orientation, false for landscape
+ '&scale=4' // 1= Normal 100% / 2= Fit to width / 3= Fit to height / 4= Fit to Page
+ '&fitw=true' // fit to width, false for actual size
+ '&top_margin=1.00' // All four margins must be set!
+ '&bottom_margin=0.00' // All four margins must be set!
+ '&left_margin=2.00' // All four margins must be set!
+ '&right_margin=0.00' // All four margins must be set!
+ '&sheetnames=true&printtitle=false' // hide optional headers and footers
+ '&pagenum=RIGHT&gridlines=false' // hide page numbers and gridlines
+ '&fzr=false' // do not repeat row headers (frozen rows) on each page
+ '&horizontal_alignment=CENTER' //LEFT/CENTER/RIGHT
+ '&vertical_alignment=TOP' //TOP/MIDDLE/BOTTOM
+ '&gid=' + sourceSheet.getSheetId(); // the sheet's Id
var token = ScriptApp.getOAuthToken();
// request export url
var response = UrlFetchApp.fetch(url, {
headers: {
'Authorization': 'Bearer ' + token
}
});
var theBlob = response.getBlob().setName(pdfName);
return theBlob;
};
my problem is that im not being able to format the pdf, I have been trying different ways but its like not responding to my changes (size, scale, margins fzr=false, etc) am I doing something wrong ?
the main thing I need is to fit to height in a letter size
any help please ?
Your code for formatting the pdf works correctly
The error must be elsewhere.
Mind that you have a loop that checks either the the file already exists before creating a new one. Most liekly you are not creating a new file because of the already existing file.
Try the following code:
function SaveAsPDF() {
SpreadsheetApp.flush();
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sourceSpreadsheet = SpreadsheetApp.getActive(); // Get active spreadsheet.
var sheetName = sourceSpreadsheet.getActiveSheet().getName();
var pdfName = "thisFileisNew.pdf"; // Set the output filename as SheetName.
// folder = DriveApp.getFolderById('ID');
var theBlob = createblobpdf(sheetName, pdfName);
var newFile = DriveApp.createFile(theBlob);
sourceSpreadsheet.toast("Saved ", "Success");
}
function createblobpdf(sheetName, pdfName) {
var sourceSpreadsheet = SpreadsheetApp.getActive();
var sourceSheet = sourceSpreadsheet.getSheetByName(sheetName);
var url = 'https://docs.google.com/spreadsheets/d/' + sourceSpreadsheet.getId()
+ '/export'
+ '?format=pdf'
+ '&size=A4' // paper size legal / letter / A4
+ '&portrait=false' // orientation, false for landscape
+ '&scale=4' // 1= Normal 100% / 2= Fit to width / 3= Fit to height / 4= Fit to Page
+ '&fitw=true' // fit to width, false for actual size
+ '&top_margin=1.00' // All four margins must be set!
+ '&bottom_margin=0.00' // All four margins must be set!
+ '&left_margin=2.00' // All four margins must be set!
+ '&right_margin=0.00' // All four margins must be set!
+ '&sheetnames=true&printtitle=false' // hide optional headers and footers
+ '&pagenum=RIGHT&gridlines=false' // hide page numbers and gridlines
+ '&fzr=false' // do not repeat row headers (frozen rows) on each page
+ '&horizontal_alignment=CENTER' //LEFT/CENTER/RIGHT
+ '&vertical_alignment=TOP' //TOP/MIDDLE/BOTTOM
+ '&gid=' + sourceSheet.getSheetId(); // the sheet's Id
var token = ScriptApp.getOAuthToken();
// request export url
var response = UrlFetchApp.fetch(url, {
headers: {
'Authorization': 'Bearer ' + token
}
});
var theBlob = response.getBlob().setName(pdfName);
return theBlob;
};
It will create in the root directory of your Drive a file called thisFileisNew.pdf - I set the format to landscape, so you see the change in the formatting easier.

Send active sheet as PDF to email listed in cell

I'm trying to use the script below to send the first sheets in a Google Sheets document to an email as PDF. The email to send to, is listed in cell A1.
However, this script send the entire spreadsheet as an PDF and not just the first sheet. I have been trying to use some of the other scripts from Stack Overflow, but this is the only one that actually sends an email.
/* Email Google Spreadsheet as PDF */
function emailGoogleSpreadsheetAsPDF() {
// Send the PDF of the spreadsheet to this email address
var email = "amit#labnol.org";
// Get the currently active spreadsheet URL (link)
var ss = SpreadsheetApp.getActiveSpreadsheet();
// Subject of email message
var subject = "PDF generated from spreadsheet " + ss.getName();
// Email Body can be HTML too
var body = "Install the <a href='http://www.labnol.org/email-sheet'>Email Spreadsheet add-on</a> for one-click conversion.";
var blob = DriveApp.getFileById(ss.getId()).getAs("application/pdf");
blob.setName(ss.getName() + ".pdf");
// If allowed to send emails, send the email with the PDF attachment
if (MailApp.getRemainingDailyQuota() > 0)
GmailApp.sendEmail(email, subject, body, {
htmlBody: body,
attachments:[blob]
});
}
below is a working version with a few useful parameters you may want to use.
UPDATED CODE
function sendSheetToPdfwithA1MailAdress(){ // this is the function to call
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sh = ss.getSheets()[0]; // it will send sheet 0 wich is the first sheet in the spreadsheet.
// if you change the number, change it also in the parameters below
var shName = sh.getName()
sendSpreadsheetToPdf(0, shName, sh.getRange('A1').getValue(),"test email with the adress in cell A1 ", "This is it !");
}
function sendSpreadsheetToPdf(sheetNumber, pdfName, email,subject, htmlbody) {
var spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
var spreadsheetId = spreadsheet.getId()
var sheetId = sheetNumber ? spreadsheet.getSheets()[sheetNumber].getSheetId() : null;
var url_base = spreadsheet.getUrl().replace(/edit$/,'');
var url_ext = 'export?exportFormat=pdf&format=pdf' //export as pdf
+ (sheetId ? ('&gid=' + sheetId) : ('&id=' + spreadsheetId))
// following parameters are optional...
+ '&size=A4' // paper size
+ '&portrait=true' // orientation, false for landscape
+ '&fitw=true' // fit to width, false for actual size
+ '&sheetnames=true&printtitle=false&pagenumbers=true' //hide optional headers and footers
+ '&gridlines=false' // hide gridlines
+ '&fzr=false'; // do not repeat row headers (frozen rows) on each page
var options = {
headers: {
'Authorization': 'Bearer ' + ScriptApp.getOAuthToken(),
}
}
var response = UrlFetchApp.fetch(url_base + url_ext, options);
var blob = response.getBlob().setName(pdfName + '.pdf');
if (email) {
var mailOptions = {
attachments:blob, htmlBody:htmlbody
}
MailApp.sendEmail(
email,
subject+" (" + pdfName +")",
"html content only",
mailOptions);
MailApp.sendEmail(
Session.getActiveUser().getEmail(),
"FRWD "+subject+" (" + pdfName +")",
"html content only",
mailOptions);
}
}
Excellent answer already accepted. I had a question about emailing just to a range and took the opportunity to add a few improvements from Serge's excellent answer above.
Mail range not whole sheet - apps script
/*
shNum = 0 for whole workbook or '0', or 0,1,2,etc for specific tab/sheet
shRng = A1 address for desired range, eg 'E1:L25', ignored if not a single sheet shNum
pdfName = text on top of pdf
*/
function mailPdf(shNum,shRng,pdfName,email,subject,htmlbody) {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var ssId = ss.getId();
var shId = shNum ? ss.getSheets()[shNum].getSheetId() : null;
var url_base = ss.getUrl().replace(/edit$/,'');
var url_ext = 'export?exportFormat=pdf&format=pdf' //export as pdf
+ (shId ? ('&gid=' + shId) : ('&id=' + ssId))
+ (shRng ? ('&range=E1:L25') : null)
+ '&format=pdf' //export format
+ '&size=letter' //A3/A4/A5/B4/B5/letter/tabloid/legal/statement/executive/folio
//+ '&portrait=false' //true= Potrait / false= Landscape
//+ '&scale=1' //1= Normal 100% / 2= Fit to width / 3= Fit to height / 4= Fit to Page
//+ '&top_margin=0.00' //All four margins must be set!
//+ '&bottom_margin=0.00' //All four margins must be set!
//+ '&left_margin=0.00' //All four margins must be set!
//+ '&right_margin=0.00' //All four margins must be set!
+ '&gridlines=false' //true/false
//+ '&printnotes=false' //true/false
//+ '&pageorder=2' //1= Down, then over / 2= Over, then down
//+ '&horizontal_alignment=CENTER' //LEFT/CENTER/RIGHT
+ '&vertical_alignment=TOP' //TOP/MIDDLE/BOTTOM
//+ '&printtitle=false' //true/false
//+ '&sheetnames=false' //true/false
//+ '&fzr=false' //true/false frozen rows
//+ '&fzc=false' //true/false frozen cols
//+ '&attachment=false' //true/false
var options = {
headers: {
'Authorization': 'Bearer ' + ScriptApp.getOAuthToken(),
'muteHttpExceptions': true
}
}
var response = UrlFetchApp.fetch(url_base + url_ext, options);
var blob = response.getBlob().setName(pdfName + '.pdf');
if (email) {
var mailOptions = {
attachments:blob, htmlBody:htmlbody
}
MailApp.sendEmail(
// email + "," + Session.getActiveUser().getEmail() // use this to email self and others
email, // use this to only email users requested
subject+' (' + pdfName +')',
'html content only',
mailOptions);
}
}
Here I found an extremely simple way to send the spreadsheet by email as pdf
https://spreadsheet.dev/automatically-email-google-sheet-as-pdf-attachment
Problem: it is sending the whole document and I only want to send a particular sheet, the active one.
So I modified the original code from this
//===============
function sendReport() {
var message = {
to: "spreadsheetdevdemo#gmail.com",
subject: "Monthly sales report",
body: "Hi team,\n\nPlease find the monthly report attached.\n\nThank you,\nBob",
name: "Bob",
attachments: [SpreadsheetApp.getActiveSpreadsheet().getAs(MimeType.PDF).setName("Monthly sales report")]
}
MailApp.sendEmail(message);
}
//===============
To this
Note: I took some code from Google spreadsheet script export active sheet only to PDF
//===============
// Define your variables here
var recipient="your#email.com";
var subject=SpreadsheetApp.getActiveSpreadsheet().getName();
var body="Hello,\n\nPlease find attached the document.\n\nThank you,\nYOURNAME";
var nameOfSender="YOURNAME";
// End of the stuff you need to edit
// Below, the sheet is converted to pdf in a blob object and that object
// is sent by email with the email-parameters above.
// Other stuff
var ss = SpreadsheetApp.getActiveSpreadsheet();
//var ssId = SpreadsheetApp.getActiveSpreadsheet().getId();
var sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
//var sheetName = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet().getName();
//var sheetId = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet().getSheetId();
// Base URL
var url = "https://docs.google.com/spreadsheets/d/SS_ID/export?".replace("SS_ID", ss.getId());
/* Specify PDF export parameters
From: https://code.google.com/p/google-apps-script-issues/issues/detail?id=3579
*/
var url_ext = 'exportFormat=pdf&format=pdf' // export as pdf / csv / xls / xlsx
+ '&size=A4' // paper size legal / letter / A4
+ '&portrait=true' // orientation, false for landscape
+ '&fitw=true&source=labnol' // fit to page width, false for actual size
+ '&sheetnames=false&printtitle=false' // hide optional headers and footers
+ '&pagenumbers=false&gridlines=false' // hide page numbers and gridlines
+ '&fzr=false' // do not repeat row headers (frozen rows) on each page
+ '&gid='; // the sheet's Id
var token = ScriptApp.getOAuthToken();
var response = UrlFetchApp.fetch(url + url_ext + sheet.getSheetId(), {
headers : {
'Authorization' : 'Bearer ' + token
}
}).getBlob().setName(sheet.getName() + ".pdf");
sheet_as_pdf_blob_document=response;
// Here we send the email
function sendReport() {
var message = {
to: recipient,
subject: subject,
body: body,
name: nameOfSender,
attachments: [sheet_as_pdf_blob_document]
}
MailApp.sendEmail(message);
}
//===============