I'm trying to save all of the sheets on my spreadsheet to google drive as one PDF (ultimately I would like to have them email as well). I'm having trouble saving more than just one of the sheets. I've tried multiple way of doing it. The code below is the best way I've found so far. Again the problem is that it only saves the first page as a PDF, I cant figure out how to get around the delete redundant sheets. All the posts I have seen only want to save 1 page, I have over 24 pages that need to be saved as one PDF. Thanks in advance for your help!
function PDF() {
var sheetName = SpreadsheetApp.getActiveSpreadsheet();
var folderID = "*** Google Drive ID***"; // Folder id to save in a Drive folder.
var ss = SpreadsheetApp.openByUrl(
'https://docs.google.com/spreadsheets/d/***Spreadsheet ID***');
var pdfName = "MAR - " + ss.getRange("A1:A1").getValue(); //Need to set the values to another sheet
var sourceSpreadsheet = SpreadsheetApp.getActive();
var sourceSheet = sourceSpreadsheet.getSheetByName(sheetName);
var folder = DriveApp.getFolderById(folderID);
//Copy whole spreadsheet
var destSpreadsheet = SpreadsheetApp.open(DriveApp.getFileById(sourceSpreadsheet.getId()).makeCopy("tmp_convert_to_pdf", folder))
//delete redundant sheets
var sheets = destSpreadsheet.getSheets();
for (i = 0; i < sheets.length; i++) {
if (sheets[i].getSheetName() != sheetName){
destSpreadsheet.deleteSheet(sheets[i]);
}
}
var destSheet = destSpreadsheet.getSheets()[0];
//repace cell values with text (to avoid broken references)
var sourceRange = sourceSheet.getRange(1,1,sourceSheet.getMaxRows(),sourceSheet.getMaxColumns());
var sourcevalues = sourceRange.getValues();
var destRange = destSheet.getRange(1, 1, destSheet.getMaxRows(), destSheet.getMaxColumns());
destRange.setValues(sourcevalues);
//save to pdf
var theBlob = destSpreadsheet.getBlob().getAs('application/pdf').setName(pdfName);
var newFile = folder.createFile(theBlob);
//Delete the temporary sheet
DriveApp.getFileById(destSpreadsheet.getId()).setTrashed(true);
}
By using Drive API, you can convert from a spreadsheet to a PDF which has all sheets in the spreadsheet. In order to use this, so please enable Drive API on Google API Console as follows.
In the script editor, select Resources > Cloud Platform Project
At the bottom of the dialog, click the link for the Google API Console.
In the console, click into the filter box and type part of the name of the API "Drive API", then click the name once you see it.
On the next screen, click Enable API.
Close the Developers Console and return to the script editor. Click OK in the dialog.
I prepared a sample script for creating PDF file from spreadsheet. Please use this to your script.
Script :
var spreadsheetId = "#####";
var folderId = "#####";
var outputFilename = "#####";
var url = "https://www.googleapis.com/drive/v3/files/" + spreadsheetId + "/export?mimeType=application/pdf";
var options = {
method: "GET",
headers: {Authorization: "Bearer " + ScriptApp.getOAuthToken()},
muteHttpExceptions: true
};
var response = UrlFetchApp.fetch(url, options).getBlob();
DriveApp.getFolderById(folderId).createFile(response).setName(outputFilename);
About this script, although I confirmed this works fine, if it doesn't work at your environment, please tell me. And if I misunderstand your question, I'm sorry.
Added 1 :
function PDF() {
var sheetName = SpreadsheetApp.getActiveSpreadsheet();
var folderID = "*** Google Drive ID***"; // Folder id to save in a Drive folder.
var ss = SpreadsheetApp.openByUrl(
'https://docs.google.com/spreadsheets/d/***Spreadsheet ID***');
var pdfName = "MAR - " + ss.getRange("A1:A1").getValue(); //Need to set the values to another sheet
var sourceSpreadsheet = SpreadsheetApp.getActive();
var sourceSheet = sourceSpreadsheet.getSheetByName(sheetName);
var folder = DriveApp.getFolderById(folderID);
//Copy whole spreadsheet
var destSpreadsheet = SpreadsheetApp.open(DriveApp.getFileById(sourceSpreadsheet.getId()).makeCopy("tmp_convert_to_pdf", folder))
//delete redundant sheets
var sheets = destSpreadsheet.getSheets();
for (i = 0; i < sheets.length; i++) {
if (sheets[i].getSheetName() != sheetName){
destSpreadsheet.deleteSheet(sheets[i]);
}
}
var destSheet = destSpreadsheet.getSheets()[0];
//repace cell values with text (to avoid broken references)
var sourceRange = sourceSheet.getRange(1,1,sourceSheet.getMaxRows(),sourceSheet.getMaxColumns());
var sourcevalues = sourceRange.getValues();
var destRange = destSheet.getRange(1, 1, destSheet.getMaxRows(), destSheet.getMaxColumns());
destRange.setValues(sourcevalues);
//save to pdf
// var theBlob = destSpreadsheet.getBlob().getAs('application/pdf').setName(pdfName);
// var newFile = folder.createFile(theBlob);
// A sample script was added here.
var url = "https://www.googleapis.com/drive/v3/files/" + destSpreadsheet.getId() + "/export?mimeType=application/pdf";
var options = {
method: "GET",
headers: {Authorization: "Bearer " + ScriptApp.getOAuthToken()},
muteHttpExceptions: true
};
var response = UrlFetchApp.fetch(url, options).getBlob();
DriveApp.getFolderById(folderID).createFile(response).setName(pdfName);
//Delete the temporary sheet
DriveApp.getFileById(destSpreadsheet.getId()).setTrashed(true);
}
Added 2 :
function PDF() {
var folderID = "*** Google Drive ID***"; // Folder id to save in a Drive folder.
var ss = SpreadsheetApp.openByUrl(
'https://docs.google.com/spreadsheets/d/***Spreadsheet ID***');
var pdfName = "MAR - " + ss.getRange("A1:A1").getValue(); //Need to set the values to another sheet
var sourceSpreadsheet = SpreadsheetApp.getActive();
var folder = DriveApp.getFolderById(folderID);
// A sample script was added here.
var url = "https://www.googleapis.com/drive/v3/files/" + sourceSpreadsheet.getId() + "/export?mimeType=application/pdf";
var options = {
method: "GET",
headers: {Authorization: "Bearer " + ScriptApp.getOAuthToken()},
muteHttpExceptions: true
};
var response = UrlFetchApp.fetch(url, options).getBlob();
DriveApp.getFolderById(folderID).createFile(response).setName(pdfName);
}
Here is the function that creates PDF file from google sheet and function that moves new created file into the folder that id you give to the parameter of the function.
function downloadPDF(fileId, folderId) {
var file = Drive.Files.get(fileId);
var url = file.exportLinks[MimeType.PDF];
var options = {
headers: {
Authorization:"Bearer " + ScriptApp.getOAuthToken()
},
muteHttpExceptions : true
}
var response = UrlFetchApp.fetch(url, options);
var status = response.getResponseCode();
var result = response.getContentText();
if (status != 200) {
// Get additional error message info, depending on format
if (result.toUpperCase().indexOf("<HTML") !== -1) {
var message = strip_tags(result);
}
else if (result.indexOf('errors') != -1) {
message = JSON.parse(result).error.message;
}
throw new Error('Error (' + status + ") " + message );
}
var doc = response.getBlob();
var newFileid = DriveApp.createFile(doc).setName(file.title + '.pdf').getId();
let id = moveFileTo(newFileid, folderId);
return id;
}
function moveFileTo(sourceId, folderId){
let file = DriveApp.getFileById(sourceId)
let blob = file.getBlob();
let id = DriveApp.getFolderById(folderId).createFile(blob).getId();
file.setTrashed(true)
return id;
}
Related
While downloading the pdf blob in google drive with UrlFetchApp.fetch method is causing two type of errors:
</div></div>This file might be unavailable right now due to heavy traffic. Try again.</div> [Written in downloaded PDF]
Exception: Timeout
Code Snippet:
function downloadasPDF(optSSId, optSheetId)
{
var ss = (optSSId) ? SpreadsheetApp.openById(optSSId) : SpreadsheetApp.getActiveSpreadsheet();
var preURL=ss.getUrl() //ss is an spreadsheet reference
var url = preURL.replace(/edit.*/,'');
var folder = DriveApp.getFolderById(FolderID);
// Get array of all sheets in spreadsheet
var sheets = ss.getSheets();
for (var i=0; i<sheets.length; i++) {
//Sheet length is 100+
Utilities.sleep("5000")
var sheet = sheets[i];
// If provided a optSheetId, only save it.
if (optSheetId && optSheetId !== sheet.getSheetId()) continue;
//additional parameters for exporting the sheet as a pdf
var url_ext = 'export?exportFormat=pdf&format=pdf' //export as pdf
+ '&gid=' + sheet.getSheetId() //the sheet's Id
+ '&gridlines=false' // hide gridlines
var options = {
headers: {
'Authorization': 'Bearer ' + ScriptApp.getOAuthToken()
},
muteHttpExceptions: true,
}
var response = UrlFetchApp.fetch(url + url_ext, options);
var blob = response.getBlob().setName(spreadsheet.getName() + ' - ' + sheet.getName() + '.pdf');
folder.createFile(blob);
}
To counter above problem I am using:
Utilities.sleep(5000)
But still some files are causing error 1 mentioned above.
Question: Do we have any other better approach to handle two mentioned cases apart from sleep ?
Note: I am using G Suite Enterprise, Number of sheets to download are between 100-150 approx, 240 cells filled for each sheet & rest cells are empty.
Use a exponential back off function to sleep exponentially on failure. Failure can be checked with .getResponseCode():
var response = (function exponentialBackoff(i) {
Utilities.sleep(Math.pow(2, i) * 1000);
let data = UrlFetchApp.fetch(url + url_ext, options);
if (data.getResponseCode() !== 200) return exponentialBackoff(++i);
else return data;
})(1);
I would like to add different API request on a spreadsheet where i already add some google app script code from here in oder to retrieve all orders from a woocommerce external source, however now i want to add another API calling request which allows me to list all products on my woocommerce source. So i type a new function below, modify the endpoint to /wp-json/wc/v3/products according to woocommerce API rest documentation here Woocommerce API rest doc. Here is the code i add to the Github code :
// Custom code to v2 Woocommerce API
function start_syncv2() {
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(Products);
fetch_products(sheet)
}
function fetch_products(sheet) {
var ck = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(OrderDetails).getRange("B4").getValue();
var cs = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(OrderDetails).getRange("B5").getValue();
var website = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(OrderDetails).getRange("B3").getValue();
var surl = website + "/wp-json/wc/v3/sheet?consumer_key=" + ck + "&consumer_secret=" + cs + "&after=" + "&per_page=100";
var url = surl
Logger.log(url)
var options =
{
"method": "GET",
"Content-Type": "application/x-www-form-urlencoded;charset=UTF-8",
"muteHttpExceptions": true,
};
var result = UrlFetchApp.fetch(url, options);
Logger.log(result.getResponseCode())
if (result.getResponseCode() == 200) {
var params = JSON.parse(result.getContentText());
Logger.log(result.getContentText());
}
var doc = SpreadsheetApp.getActiveSpreadsheet();
var temp = SpreadsheetApp.getSheetByName(sheet);
var consumption = {};
var arrayLength = params.length;
Logger.log(arrayLength)
for (var i = 0; i < arrayLength; i++) {
Logger.log("dfsfsdfsf")
var a;
var container = [];
a = container.push(params[i]["id"]);
Logger.log(a)
a = container.push(params[i]["name"]);
a = container.push(params[i]["sku"]);
a = container.push(params[i]["price"]);
a = container.push(params[i]["tax_status"]);
a = container.push(params[i]["stock_status"]);
a = container.push(params[i]["categories"]["name"]);
a = container.push(params[i]["images"]);
a = container.push(params[i]["attributes"]["options"]);
a = container.push(params[i]["_links"]["self"]["href"]);
var doc = SpreadsheetApp.getActiveSpreadsheet();
var temp = doc.getSheetByName(sheet);
temp.appendRow(container);
}
}
I have issue using google sheets calling method describe here. As i want my new API call request, i think my main problem is to select the right sheet into the spreadsheet.
Here is a copy of my spreadsheet : Woocommerce-google sheets integration
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 ]
});
}
I created an invoice template in the spreadsheet and used the attached VBA code to create a report from it (essentially it stores certain cell values into another sheet as a tabular report).I would like to port this over to Google Spreadsheet and need help in converting the VBA to corresponding JavaScript. Can you help?
Thanks
Sub InvoiceReport()
Dim myFile As String, lastRow As Long
myFile = “C: \invoices\” & Sheets(“Sheet1”).Range(“B5”) & “_” & Sheets(“Sheet1”).Range(“F1”) & Format(Now(), “yyyy - mm - dd”) & “.pdf”
lastRow = Sheets(“Sheet2”).UsedRange.SpecialCells(xlCellTypeLastCell).Row + 1
‘ Transfer data to sheet2
Sheets(“Sheet2”).Cells(lastRow, 1) = Sheets(“Sheet1”).Range(“B5”)
Sheets(“Sheet2”).Cells(lastRow, 2) = Sheets(“Sheet1”).Range(“F1”)
Sheets(“Sheet2”).Cells(lastRow, 3) = Sheets(“sheet1”).Range(“I36”)
Sheets(“Sheet2”).Cells(lastRow, 4) = Now
Sheets(“Sheet2”).Hyperlinks.Add Anchor: = Sheets(“Sheet2”).Cells(lastRow, 5), Address: = myFile, TextToDisplay: = myFile‘ Create invoice in PDF format
Sheets(“sheet1”).ExportAsFixedFormat Type: = xlTypePDF, Filename: = myFile
Application.DisplayAlerts = False
‘ create invoice in XLSX format
ActiveWorkbook.SaveAs“ C: \invoices\” & Sheets(“Sheet1”).Range(“B5”) & “_” & Sheets(“Sheet1”).Range(“F1”) & “_” & Format(Now(), “yyyy - mm - dd”) & “.xlsx”, FileFormat: = 51‘ ActiveWorkbook.Close
Application.DisplayAlerts = True
End Sub
Figured this out, thankfully I've had to do this before.
This moves the data by getting the invoice information via a map that I made as an object so it's easily looped through. The tricky part was getting the PDF of the sheet.
I accomplished this by first scoping the function with Driveapp.getRootFolder() so I can get an oAuth token later. I utilized the URLFetchApp use the spreadsheets export functionality to retrieve a PDF blob. I then take this blob, name it, convert it to a file, and insert it into your drives root folder.
//Data mapping for the invoice itself
var invoiceDetailsMap = {
'Buyer Name': {
rowIndex: 4,
columnIndex: 1
},
'Invoice Number': {
rowIndex: 0,
columnIndex: 5
},
'Total Amount': {
rowIndex: 35,
columnIndex: 7
},
'Date & Time': {
rowIndex: 0,
columnIndex: 1
}
}
//Entry point for script
function EntryPoint() {
var spreadsheet = SpreadsheetApp.getActive()
var sheet = spreadsheet.getSheetByName('Sheet1');
var dataRange = sheet.getDataRange();
var valuesRange = dataRange.getValues();
var invoiceData = GetInvoiceDetails(valuesRange);
WriteInviceDetailsToSheet(invoiceData);
GetPDF(spreadsheet, invoiceData['File Name']);
}
//Writes the invoice details to the 2nd sheet
function WriteInviceDetailsToSheet(invoiceData){
var sheet = SpreadsheetApp.getActive().getSheetByName('Sheet2');
var dataRange = sheet.getDataRange();
var valuesRange = dataRange.getValues();
var columns = GetColumns(valuesRange, dataRange.getNumColumns(), 0);
var arrayToWrite = [[]];
for(var column in columns.columns){
if(typeof invoiceData[column] !== 'undefined'){
arrayToWrite[0].push(invoiceData[column]);
}
}
sheet.insertRowAfter(dataRange.getLastRow());
sheet.getRange(dataRange.getLastRow() + 1, 1, 1, arrayToWrite[0].length).setValues(arrayToWrite);
}
//Gets the invoice details absed on the mappings
function GetInvoiceDetails(valuesRange) {
var output = {};
for(var value in invoiceDetailsMap){
output[value] = valuesRange[invoiceDetailsMap[value].rowIndex][invoiceDetailsMap[value].columnIndex];
}
output['File Name'] = 'Invoice' + output['Invoice Number'] + '_' + FormatDate(output['Date & Time'], 'MM.dd.yyyy');
return output;
}
//Gets the PDF and inserts it into drive
function GetPDF(spreadsheet, fileName){
DriveApp.getRootFolder(); //Scoping
var urlParameters = 'export?exportFormat=pdf&format=pdf&size=letter&portrait=true&fitw=true&source=labnol&sheetnames=false&printtitle=false&pagenumbers=false&gridlines=false&fzr=false&gid=0';
var baseURL = spreadsheet.getUrl();
baseURL = baseURL.replace(/edit$/,'');
var response = UrlFetchApp.fetch(baseURL + urlParameters, {
headers: {'Authorization': 'Bearer ' + ScriptApp.getOAuthToken() }
});
var pdfBlob = response.getBlob().setName(fileName + '.pdf');
var file = DriveApp.createFile(pdfBlob);
DriveApp.addFile(file);
}
//Reformts a date
function FormatDate(date, format)
{
var temp = new Date(date);
var output = Utilities.formatDate(temp, "PST", format);
return output;
}
//Gets a columns object for the sheet for easy indexing
function GetColumns(valuesRange, columnCount, rowIndex)
{
var columns = {
columns: {},
length: 0
}
Logger.log("Populating columns...");
for(var i = 0; i < columnCount; i++)
{
if(valuesRange[0][i] !== ''){
columns.columns[valuesRange[0][i]] = {index: i ,value: valuesRange[0][i]};
columns.length++;
}
}
return columns;
}
i changed the coding so far that i'm now able to send a spread sheet to a email address. What i'm looking for now is the possibility to select a specific range like (A1:J23) and send only that range to my mail address. any ideas what i'm doing wrong here? Always getting the warning:
TypeError: Cannot find function getSheets in object Range. (line 8, file
function onOpen() {
var submenu = [{name:"einreichen", functionName:"sendEmailWithPdfAttach"}];
SpreadsheetApp.getActiveSpreadsheet().addMenu('E-mail senden', submenu);
}
var range = 'A1:J23'
var source = SpreadsheetApp.getActiveSpreadsheet().getRange(range);
var subject = source.getSheets()[0].getRange('B3').getValue();
var body = source.getSheets()[0].getRange('F3').getValue();
var sheetNum = 0; // first sheet(tab) is zero, second sheet is 1, etc..
function sendEmailWithPdfAttach() {
var source = SpreadsheetApp.getActiveSpreadsheet();
var thema = source.getSheets()[0].getRange('D3').getValue(); //
var mailTo = source.getSheets()[0].getRange('E3').getValue(); // 'D46' cell which consists an emailaddress.
var name = source.getSheets()[0].getRange('C3').getValue();
var sheets = source.getSheets();
sheets.forEach(function (s, i) {
if (i !== sheetNum) s.hideSheet();
});
var url = Drive.Files.get(source.getId())
.exportLinks['application/pdf'];
url = url + '&size=letter' + //paper size
'&portrait=false' + //orientation, false for landscape
'&fitw=true' + //fit to width, false for actual size
'&sheetnames=true&printtitle=false&pagenumbers=false' + //hide optional// was false
'&gridlines=false' + //false = hide gridlines
'&fzr=false'; //do not repeat row headers (frozen rows) on each page
var token = ScriptApp.getOAuthToken();
var response = UrlFetchApp.fetch(url, {
headers: {
'Authorization': 'Bearer ' + token
}
});
MailApp.sendEmail(mailTo, subject, body, {
attachments: [response.getBlob().setName(name)]
});
sheets.forEach(function (s) {
s.showSheet();
})
}
So thats the solution i was i able to find on the internet, with the help of Kelvin and try and error by myself. it works now on my behalf. Because it was so hard to find i wanted to post the final result for somebody who is looking for something like this.
function onOpen() {
var ui = SpreadsheetApp.getUi();
// Or DocumentApp or FormApp.
ui.createMenu('Custom Menu')
.addItem('Send summary', 'menuItem1')
.addSeparator()
.addItem('Send summary&Week', 'menuItem2')
.addToUi();
}
function menuItem1() {
var source = SpreadsheetApp.getActiveSpreadsheet();
var subject = source.getSheets()[9].getRange('G1').getValue(); //cell for subject in sheet
var body = source.getSheets()[9].getRange('F1').getValue();
var sheetNumSummary = 9; // first sheet(tab) is zero, second sheet is 1, etc..
var source = SpreadsheetApp.getActiveSpreadsheet();
var thema = source.getSheets()[9].getRange('f3').getValue(); //
var mailTo = ('youremailaddress#here.com'); //source.getSheets() [0].getRange('D1').getValue(); // 'D1' cell which consists an emailaddress.
var name = source.getSheets()[9].getRange('G1').getValue(); // Name of Attachement
var sheets = source.getSheets();
sheets.forEach(function (s, i) {
if (i !== sheetNumSummary) s.hideSheet();
});
var url = Drive.Files.get(source.getId())
.exportLinks['application/pdf'];
url = url + '&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
'&gridlines=false' + //false = hide gridlines
'&fzr=false'; //do not repeat row headers (frozen rows) on each page
var token = ScriptApp.getOAuthToken();
var response = UrlFetchApp.fetch(url, {
headers: {
'Authorization': 'Bearer ' + token
}
});
MailApp.sendEmail(mailTo, subject, body, {
attachments: [response.getBlob().setName(name)]
});
sheets.forEach(function (s) {
s.showSheet();
})
}
function menuItem2() {
var source = SpreadsheetApp.getActiveSpreadsheet();
var subject = source.getSheets()[9].getRange('G1').getValue();
var body = source.getSheets()[9].getRange('F1').getValue();
var sheetNumSummary = 9; // first sheet(tab) is zero, second sheet is 1, etc..
var source = SpreadsheetApp.getActiveSpreadsheet();
var thema = source.getSheets()[9].getRange('f3').getValue(); //
var mailTo = ('youremailaddress#here.com'); //source.getSheets() [0].getRange('D1').getValue(); // 'D1' cell which consists an emailaddress.
var name = source.getSheets()[9].getRange('G1').getValue(); // Name of Attachement
var sheets = source.getSheets();
sheets.forEach(function (s, i) {
if (i !== sheetNumSummary) s.hideSheet();
});
var url = Drive.Files.get(source.getId())
.exportLinks['application/pdf'];
url = url + '&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
'&gridlines=false' + //false = hide gridlines
'&fzr=false'; //do not repeat row headers (frozen rows) on each page
var token = ScriptApp.getOAuthToken();
var response = UrlFetchApp.fetch(url, {
headers: {
'Authorization': 'Bearer ' + token
}
});
MailApp.sendEmail(mailTo, subject, body, {
attachments: [response.getBlob().setName(name)]
});
sheets.forEach(function (s) {
s.showSheet();
})
/*}
function menuItem2() {
*/
var source = SpreadsheetApp.getActiveSpreadsheet();
var subject = source.getSheets()[10].getRange('G1').getValue();
var body = source.getSheets()[10].getRange('F1').getValue(); //bleibt leer, kein Text notwendig
var sheetNumWeek = 10; // first sheet(tab) is zero, second sheet is 1, etc..
var source = SpreadsheetApp.getActiveSpreadsheet();
var thema = source.getSheets()[10].getRange('C1').getValue(); //
var mailTo = ('admin6142.c087880#m.evernote.com, Dwight#ndmarin.com'); //source.getSheets()[0].getRange('D1').getValue(); // 'D1' cell which consists an emailaddress.
var name = source.getSheets()[10].getRange('G1').getValue(); // Name of Attachement
var sheets = source.getSheets();
sheets.forEach(function (s, i) {
if (i !== sheetNumWeek) s.hideSheet();
});
var url = Drive.Files.get(source.getId())
.exportLinks['application/pdf'];
url = url + '&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// was false
'&gridlines=false' + //false = hide gridlines
'&fzr=false'; //do not repeat row headers (frozen rows) on each page
var token = ScriptApp.getOAuthToken();
var response = UrlFetchApp.fetch(url, {
headers: {
'Authorization': 'Bearer ' + token
}
});
MailApp.sendEmail(mailTo, subject, body, {
attachments: [response.getBlob().setName(name)]
});
sheets.forEach(function (s) {
s.showSheet();
})
}
This is something that I used before from a script online, It should suit everything you asked for. Go to Tools, and go to script editor, paste this in, change the settings you need and save. Reload the sheet and you will see an extra option there.
//var ss = SpreadsheetApp.getActiveSpreadsheet();
//function onOpen() {
// var menu = [{name: "Email PDF", functionName: "emailSpreadsheetAsPDF"}];
// ss.addMenu("Email PDF", menu);
//};
/* Send Spreadsheet in an email as PDF, automatically */
function emailSpreadsheetAsPDF() {
// Send the PDF of the spreadsheet to this email address
var email = "kelvin#test.com
// Subject of email message
// The way it is formatted now is "Timesheet by (Get email of user who initiated the sending) and the time
var now = new Date();
var subject = "Time Sheet by " + Session.getActiveUser().getEmail() + " " + (new Date()).toString();
// Or use SpreadsheetApp.openByUrl("<<SPREADSHEET URL>>");
var ss = SpreadsheetApp.getActiveSpreadsheet();
//var body = Choose what you want as the body message
var body = "PDF generated by " + Session.getActiveUser().getEmail() + " from " + ss.getName() + " on " + (new Date()).toString();
var url = ss.getUrl();
url = url.replace(/edit$/,'');
/* Specify PDF export parameters
// From: https://code.google.com/p/google-apps-script-issues/issues/detail?id=3579
exportFormat = pdf / csv / xls / xlsx
gridlines = true / false
printtitle = true (1) / false (0)
size = legal / letter/ A4
fzr (repeat frozen rows) = true / false
portrait = true (1) / false (0)
fitw (fit to page width) = true (1) / false (0)
add gid if to export a particular sheet - 0, 1, 2,..
*/
var url_ext = 'export?exportFormat=pdf&format=pdf' // export as pdf
+ '&size=A4' // paper size
+ '&portrait=false' // orientation, false for landscape
+ '&fitw=true&source=kelvin' // fit to 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
+ '&fitw=true' // Fit to page width
+ '&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
var pdfBlob = 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(pdfBlob);
// 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, {attachments:[pdfBlob]});
}