I have this script to export three separate sheets as PDF's using Google Apps Script which works fine except for the fact that the PDF's are exported with the file name of export.pdf in each case. I would like to rename them to 'Yesterday', 'Last 7 Days' and 'Last 30 Days' respectively, can anyone help me to achieve this, please?
//Menu in Google Sheet
function onOpen() {
var ui = SpreadsheetApp.getUi();
ui.createMenu('Dashboard')
.addItem('Email Dashboard','emailDashboard')
.addToUi();
}
//Convert dashboard to PDF and email a copy to user
function emailDashboard() {
// get sheet id
var ss = SpreadsheetApp.getActiveSpreadsheet();
var id = ss.getId();
// setup sheets
var yesterdaySheet = ss.getSheetByName('Yesterday');
var last7DaysSheet = ss.getSheetByName('Last 7 Days');
var last30DaysSheet = ss.getSheetByName('Last 30 Days');
var settingsSheet = ss.getSheetByName('Settings');
var dashboardURL = ss.getUrl() + "?usp=sharing";
// Send the PDF of the spreadsheet to this email address
// get this from the settings sheet
var email = settingsSheet.getRange(8,2).getValue();
var cc_email = settingsSheet.getRange(9,2).getValue();
var bcc_email = settingsSheet.getRange(10,2).getValue();
// Subject of email message
var subject = "Dashboard PDF generated from " + ss.getName() + " - " + new Date().toLocaleString();
// Email Body
var body = `A pdf copy of your dashboard is attached.<br><br>
To access this Google Sheet,;
<a href="` + dashboardURL + `" >click here</a>`;
// Base URL
var url = "https://docs.google.com/spreadsheets/d/" + id + "/export?";
var url_ext = 'exportFormat=pdf&format=pdf&size=A4&portrait=false&fitw=true&gid=';
// Auth value
var token = ScriptApp.getOAuthToken();
var options = {
headers: { 'Authorization': 'Bearer ' + token }
}
// helps initialize first time using the script
var driveCall = DriveApp.getRootFolder();
// create the pdf
var responseYesterday = UrlFetchApp.fetch(url + url_ext + yesterdaySheet.getSheetId(), options);
var response7Days = UrlFetchApp.fetch(url + url_ext + last7DaysSheet.getSheetId(), options);
var response30Days = UrlFetchApp.fetch(url + url_ext + last30DaysSheet.getSheetId(), options);
// send the email with the PDF attachment
GmailApp.sendEmail(email, subject, body, {
cc: cc_email,
bcc: bcc_email,
htmlBody: body,
attachments:[responseYesterday,response7Days, response30Days]
});
}
Explanation:
Just add these three lines after the pdf creation part:
var blob_Y = responseYesterday.getBlob().setName('Yesterday' + '.pdf');
var blob_L7D = response7Days.getBlob().setName('Last 7 Days' + '.pdf');
var blob_L30D = response30Days.getBlob().setName('Last 30 Days' + '.pdf');
and then change this part:
GmailApp.sendEmail(email, subject, body, {
cc: cc_email,
bcc: bcc_email,
htmlBody: body,
attachments:[blob_Y, blob_L7D, blob_L30D ]
});
Solution:
//Menu in Google Sheet
function onOpen() {
var ui = SpreadsheetApp.getUi();
ui.createMenu('Dashboard')
.addItem('Email Dashboard','emailDashboard')
.addToUi();
}
//Convert dashboard to PDF and email a copy to user
function emailDashboard() {
// get sheet id
var ss = SpreadsheetApp.getActiveSpreadsheet();
var id = ss.getId();
// setup sheets
var yesterdaySheet = ss.getSheetByName('Yesterday');
var last7DaysSheet = ss.getSheetByName('Last 7 Days');
var last30DaysSheet = ss.getSheetByName('Last 30 Days');
var settingsSheet = ss.getSheetByName('Settings');
var dashboardURL = ss.getUrl() + "?usp=sharing";
// Send the PDF of the spreadsheet to this email address
// get this from the settings sheet
var email = settingsSheet.getRange(8,2).getValue();
var cc_email = settingsSheet.getRange(9,2).getValue();
var bcc_email = settingsSheet.getRange(10,2).getValue();
// Subject of email message
var subject = "Dashboard PDF generated from " + ss.getName() + " - " + new Date().toLocaleString();
// Email Body
var body = `A pdf copy of your dashboard is attached.<br><br>
To access this Google Sheet,;
<a href="` + dashboardURL + `" >click here</a>`;
// Base URL
var url = "https://docs.google.com/spreadsheets/d/" + id + "/export?";
var url_ext = 'exportFormat=pdf&format=pdf&size=A4&portrait=false&fitw=true&gid=';
// Auth value
var token = ScriptApp.getOAuthToken();
var options = {
headers: { 'Authorization': 'Bearer ' + token }
}
// helps initialize first time using the script
var driveCall = DriveApp.getRootFolder();
// create the pdf
var responseYesterday = UrlFetchApp.fetch(url + url_ext + yesterdaySheet.getSheetId(), options);
var response7Days = UrlFetchApp.fetch(url + url_ext + last7DaysSheet.getSheetId(), options);
var response30Days = UrlFetchApp.fetch(url + url_ext + last30DaysSheet.getSheetId(), options);
var blob_Y = responseYesterday.getBlob().setName('Yesterday' + '.pdf');
var blob_L7D = response7Days.getBlob().setName('Last 7 Days' + '.pdf');
var blob_L30D = response30Days.getBlob().setName('Last 30 Days' + '.pdf');
GmailApp.sendEmail(email, subject, body, {
cc: cc_email,
bcc: bcc_email,
htmlBody: body,
attachments:[blob_Y, blob_L7D, blob_L30D ]
});
}
Related
I'm trying to work out how to create a PDF document through Google Apps Script which is displayed in landscape orientation (A4 size). This is the code I'm using to create the PDF so far, which comes out in portrait orientation.
function pdfSheet() {
var d = new Date();
var cdate = d.getDate();
var cmonth = d.getMonth() + 1;
var cyear = d.getFullYear();
var current = [cdate + "-" + cmonth + "-" + cyear];
var imageBlob = UrlFetchApp.fetch("https://sites.google.com/site/mysite/smalllogo.png").getBlob();
var base64EncodedBytes = Utilities.base64Encode(imageBlob.getBytes());
var logo = "<img src='data:image/png;base64," + base64EncodedBytes + "' width='170'/>";
var html = "<table width='100%'><tr><td align='right'>" + logo + "<br><br><b>Date:</b> " + current + "</td></tr></table>"; //PDF content will carry on here.
var gmailLabels = "PDF";
var driveFolder = "My Gmail";
var folders = DriveApp.getFoldersByName(driveFolder);
var folder = folders.hasNext() ?
folders.next() : DriveApp.createFolder(driveFolder);
var subject = 'Test PDF';
var tempFile = DriveApp.createFile("temp.html", html, "text/html");
var page = folder.createFile(tempFile.getAs("application/pdf")).setName(subject + ".pdf")
tempFile.setTrashed(true);
var link = page.getUrl();
Logger.log(link);
}
I took most of this from another user and edited to have the current days date (in EST) in the email subject and the PDF name. Hope it helps!
// Simple function to send Daily Status Sheets
// Load a menu item called "Project Admin" with a submenu item called "Send Status"
// Running this, sends the currently open sheet, as a PDF attachment
function onOpen() {
var submenu = [{name:"Send Status", functionName:"exportSomeSheets"}];
SpreadsheetApp.getActiveSpreadsheet().addMenu('Project Admin', submenu);
}
function creatPDF() {
SpreadsheetApp.flush();
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getActiveSheet();
//Date set with format in EST (NYC) used in subject and PDF name
var period = Utilities.formatDate(new Date(), "GMT+5", "yyyy.MM.dd");
var url = ss.getUrl();
//remove the trailing 'edit' from the url
url = url.replace(/edit$/, '');
//additional parameters for exporting the sheet as a pdf
var url_ext = 'export?exportFormat=pdf&format=pdf' + //export as pdf
//below parameters are optional...
'&size=letter' + //paper size
'&portrait=false' + //orientation, false for landscape
'&fitw=true' + //fit to width, false for actual size
'&sheetnames=false&printtitle=false&pagenumbers=false' + //hide optional headers and footers
'&gridlines=false' + //hide gridlines
'&fzr=false' + //do not repeat row headers (frozen rows) on each page
'&gid=' + sheet.getSheetId(); //the sheet's Id
var token = ScriptApp.getOAuthToken();
var response = UrlFetchApp.fetch(url + url_ext, {
headers: {
'Authorization': 'Bearer ' + token
}
});
var blob = response.getBlob().setName(ss.getName() + " " + period + '.pdf');
//from here you should be able to use and manipulate the blob to send and email or create a file per usual.
var email = 'email#co-email.com';
var subject = "subject line " + period ;
var body = "Please find attached your Daily Report.";
//Place receipient email between the marks
MailApp.sendEmail( email, subject, body, {attachments:[blob]});
}
I have a script that exports a sheet to a pdf file when function is run. This works fine when I run it from the account in which the script was created but when a shared user runs it returns the following error: Exception: Cannot retrieve the next object: iterator has reached the end. Line 9
The code is as below, i'm not sure what actually is wrong with this so would be glad of help:
function CreatePDF() {
var sourceSpreadsheet = SpreadsheetApp.getActive();
var ui = SpreadsheetApp.getUi();
var sheetName = "Stock List";
var sourceSheet = sourceSpreadsheet.getSheetByName(sheetName);
var sh = sourceSpreadsheet.getSheetByName("Product List");
var driveFile = DriveApp.getFileById("xxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
var parentFolder = driveFile.getParents();
var folderName =parentFolder.next().getId();
var folder = DriveApp.getFolderById(folderName);
var numf = sourceSpreadsheet.getRangeByName("exportrange").getValue();
var anof = numf.split("/",2);
var pdfRange = sh.getRange("F1");
var pdfName = pdfRange.getValue();
// export url
var url = 'https://docs.google.com/spreadsheets/d/'+sourceSpreadsheet.getId()+'/export?exportFormat=pdf&format=pdf' // export as pdf / csv / xls / xlsx
+ '&size=A4'
+ '&portrait=true'
+ '&fitw=true'
+ '&top_margin=0.00'
+ '&bottom_margin=0.00'
+ '&left_margin=0.00'
+ '&right_margin=0.00'
+ '&sheetnames=false&printtitle=false'
+ '&pagenumbers=false&gridlines=false'
+ '&fzr=false'
+ '&gid='+sourceSheet.getSheetId();
var token = ScriptApp.getOAuthToken();
var response = UrlFetchApp.fetch(url, {
headers: {
'Authorization': 'Bearer ' + token
}
});
var theBlob = response.getBlob().setName(pdfName+'.pdf');
var files = folder.getFilesByName(pdfName);
while (files.hasNext())
{
files.next().setTrashed(true);
}
}
my google sheet will email a PDF copy of the sheet to a list of 4 emails ( in cells L5:L8 )
but it seems that the email in cell L8 never picked , logger shows it in the array ! .
see my code and help figuring the problem !? I'm suspecting something wrong in my FOREACH loop .
function onEdit2(e) {
var sheet = SpreadsheetApp.getActiveSheet();
var r = sheet.getRange('L11').getValue();
if (r == "Send") {
var ss = SpreadsheetApp.getActiveSpreadsheet()
var ssID = ss.getId();
var sheet = ss.getActiveSheet();
var sheetName = ss.getName();
var key = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet().getName();
var token = ScriptApp.getOAuthToken();
var setcolor= SpreadsheetApp.getActiveSheet().setTabColor("#0000A0");
var emails= sheet.getRange("L5:L8").getValues();
var subject = "Daily report ";
var body = "Please find the attached" +" "+ key ;
var url = "https://docs.google.com/spreadsheets/d/"+ssID+"/export?"
+ "format=xlsx" + "&gid="+sheetgId+ "&portrait=true" +
"&exportFormat=pdf";
var tempSheet = ss.insertSheet("tempSheet"); // Added
sheet.getRange("A1:J27").copyTo(tempSheet.getRange(1, 1)); // Added
SpreadsheetApp.flush(); // Added
var sheetgId = tempSheet.getSheetId(); // Added
var url = "https://docs.google.com/spreadsheets/d/"+ssID+"/export?" + "format=xlsx" + "&gid="+sheetgId+ "&portrait=true" + "&exportFormat=pdf";
var result = UrlFetchApp.fetch(url, {headers: {'Authorization': 'Bearer ' + token}});
var contents = result.getContent();
emails.forEach(function(email){
MailApp.sendEmail(email.toString(),sheetName ,body, {attachments: [{fileName: sheetName + ".pdf", content: contents, mimeType: "application//pdf"}]});
ss.deleteSheet(tempSheet); // Added
})
}
var sheets = SpreadsheetApp.getActiveSpreadsheet().getSheets();
for ( var i = 0 ; i<sheets.length ; i++) {
var sheet1 = sheets[i];
sheet1.getRangeList(['L3','L11']).clearContent();
}
}
this script sends a pdf copy to my email when I type Send in cell L6 , this code send the whole sheet and I need to send as only A1:J22 , any Ideas ?
function onEdit2(e) {
var sheet = SpreadsheetApp.getActiveSheet();
var r = sheet.getRange('L6').getValue();
if (r == "Send") {
var ss = SpreadsheetApp.getActiveSpreadsheet()
var ssID = ss.getId();
var sheetgId = ss.getActiveSheet().getSheetId();
var sheetName = ss.getName();
var token = ScriptApp.getOAuthToken();
var email = "EMAIL HERE";
var subject = "Daily report ";
var body = "Please find the attached Daily report";
var url = "https://docs.google.com/spreadsheets/d/"+ssID+"/export?"
+ "format=xlsx" + "&gid="+sheetgId+ "&portrait=true" +
"&exportFormat=pdf";
var result = UrlFetchApp.fetch(url, {
headers: {
'Authorization': 'Bearer ' + token
}
});
var contents = result.getContent();
MailApp.sendEmail(email,subject ,body, {
attachments: [{
fileName: sheetName + ".pdf",
content: contents,
mimeType: "application//pdf"
}]
})
}
}
You want to retrieve the cells of A1:J22 and want to create them to PDF data.
You want to achieve this using Google Apps Script.
If my understanding is correct, how about this answer? Please think of this as just one of several possible answers.
Modification points:
In this modification, create a temporal sheet and copy the values of the cells of A1:J22 to it. Then, the temporal sheet is converted to PDF file. And, the temporal sheet is deleted.
Modified script:
When your script is modified, please modify as follows.
function onEdit2(e) {
var sheet = SpreadsheetApp.getActiveSheet();
var r = sheet.getRange('L6').getValue();
if (r == "Send") {
var ss = SpreadsheetApp.getActiveSpreadsheet()
var ssID = ss.getId();
var sheet = ss.getActiveSheet(); // Added
// var sheetgId = ss.getActiveSheet().getSheetId(); // removed
var sheetName = ss.getName();
var token = ScriptApp.getOAuthToken();
var email = "EMAIL HERE";
var subject = "Daily report ";
var body = "Please find the attached Daily report";
var tempSheet = ss.insertSheet("tempSheet"); // Added
sheet.getRange("A1:J22").copyTo(tempSheet.getRange(1, 1)); // Added
SpreadsheetApp.flush(); // Added
var sheetgId = tempSheet.getSheetId(); // Added
var url = "https://docs.google.com/spreadsheets/d/"+ssID+"/export?" + "format=xlsx" + "&gid="+sheetgId+ "&portrait=true" + "&exportFormat=pdf";
var result = UrlFetchApp.fetch(url, {headers: {'Authorization': 'Bearer ' + token}});
var contents = result.getContent();
MailApp.sendEmail(email,subject ,body, {attachments: [{fileName: sheetName + ".pdf", content: contents, mimeType: "application//pdf"}]});
ss.deleteSheet(tempSheet); // Added
}
}
References:
insertSheet(sheetName)
copyTo(destination)
deleteSheet(sheet)
If I misunderstood your question and this was not the direction you want, I apologize.
I'm trying to make this script to work on google sheets app so it sends a pdf copy to my email when I type Send in cell L6
the code work perfect on computer but not on ipads , anyway to do this from app ?
function onEdit2(e) {
var sheet = SpreadsheetApp.getActiveSheet();
var r = sheet.getRange('L6').getValue();
if (r == "Send") {
var ss = SpreadsheetApp.getActiveSpreadsheet()
var ssID = ss.getId();
var sheetgId = ss.getActiveSheet().getSheetId();
var sheetName = ss.getName();
var token = ScriptApp.getOAuthToken();
var email = "EMAIL HERE";
var subject = "Daily report ";
var body = "Please find the attached Daily report";
var url = "https://docs.google.com/spreadsheets/d/"+ssID+"/export?"
+ "format=xlsx" + "&gid="+sheetgId+ "&portrait=true" +
"&exportFormat=pdf";
var result = UrlFetchApp.fetch(url, {
headers: {
'Authorization': 'Bearer ' + token
}
});
var contents = result.getContent();
MailApp.sendEmail(email,subject ,body, {
attachments: [{
fileName: sheetName + ".pdf",
content: contents,
mimeType: "application//pdf"
}]
})
}
}
The way it worked for me by " installed Trigger "
from the script editor : Edit - current project Triggers
I added new trigger that will run the code below based on " On edit " and voila it worked , from sheets app if I typed " Send " in Cell L6 it will send a PDF copy of the active sheet to the email listed in the code.
function onEdit2(e) {
var sheet = SpreadsheetApp.getActiveSheet();
var r = sheet.getRange('L6').getValue();
if (r == "Send") {
var ss = SpreadsheetApp.getActiveSpreadsheet()
var ssID = ss.getId();
var sheetgId = ss.getActiveSheet().getSheetId();
var sheetName = ss.getName();
var token = ScriptApp.getOAuthToken();
var email = "EMAIL HERE";
var subject = "Daily report ";
var body = "Please find the attached Daily report";
var url = "https://docs.google.com/spreadsheets/d/"+ssID+"/export?"
+ "format=xlsx" + "&gid="+sheetgId+ "&portrait=true" +
"&exportFormat=pdf";
var result = UrlFetchApp.fetch(url, {
headers: {
'Authorization': 'Bearer ' + token
}
});
var contents = result.getContent();
MailApp.sendEmail(email,subject ,body, {
attachments: [{
fileName: sheetName + ".pdf",
content: contents,
mimeType: "application//pdf"
}]
})
}
}
Create a Google Script in the very same Spreadsheet or in another one (Tools / Script editor), add the script you already have, grant the authorizations required, and trigger it with a simple form (Tools / Create a form) (trigger → Edit / Current project's triggers). The long URL to view the form can be easily opened by means of a URL shortener or something by the sort. Forms work in cell phones too and without need to sign in to your account. With this method you can even add a useless conditional password to run the script.
function createPDF(e) {
var input = e.values[1];
if (input == 'my_password'){
// your scripts to create and send the PDF goes here
}
}
It's a simplistic solution, but it works.