google script email spreadsheet as pdf code example
Example: google script email spreadsheet as pdf
function sendSheetToPdfwithA1MailAdress(){
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sh = ss.getSheets()[0];
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'
+ (sheetId ? ('&gid=' + sheetId) : ('&id=' + spreadsheetId))
+ '&size=A4'
+ '&portrait=true'
+ '&fitw=true'
+ '&sheetnames=true&printtitle=false&pagenumbers=true'
+ '&gridlines=false'
+ '&fzr=false';
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);
}
}