Google Sheet Script (Email to PDF) suddenly sending corrupt PDFs - pdf

I have a Google Sheet Script that sends the page to an email as a PDF which has been working perfectly until yesterday. Suddenly it started sending corrupted PDF's that can not be opened.
The Script runs just fine, if just can not open up the PDF file as it says "Can Not Display - Invalid format".
Any ideas on why it may have stopped working?
function sendSheetToPdfwithA1MailAdress(){ // this is the function to call
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sh = ss.getSheets()[0]; // it will send sheet 0 which is the first sheet in the spreadsheet.
// if you change the number, change it also in the parameters below
var shName = sh.getName()
// This function uses a cell in the spreadsheet that names the file that is being saved as getfilename(). using this function will pull from a certain Cell (G4 in this case)
function getFilename() {
var spreadsheet = SpreadsheetApp.getActive();
var sheet = spreadsheet.getSheetByName('N1944E'); // Edit the sheet name as necessary
var cell = sheet.getRange('C8'); //Cell to pull file name from.
var filename = cell.getValue();
return filename;
}
sendSpreadsheetToPdf(0, shName, sh.getRange('C6').getValue(),"Air Attack Daily Fire Sheet " + getFilename() );
}
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(),
" "+subject+" (" + pdfName +")",
"html content only",
mailOptions);
}
}

I had the exact same issue, but I just figured it out. The problem is here:
var url_base = ss.getUrl().replace(/edit$/,'') + "export?";
getUrl() appears to be returning a different version of the url than it was before. It now appends the following on the url: "ouid=###########&urlBuilderDomain=YOURDOMAIN" check it out yourself by using the logger.
That is causing an issue with the pdf export. So I built my own url address by replacing that line with the following:
var url_base = "https://docs.google.com/spreadsheets/d/" + ss.getId() + "/" + "export?";
It now seems to be working! Here's the full code that generates my blob:
function generatePDF(pdfName, sheet, portrait){
var token = ScriptApp.getOAuthToken();
var params = {
headers: {
'Authorization': 'Bearer ' + token,
},
'muteHttpExceptions' : true
};
var sheetId = sheet.getSheetId();
var ss = sheet.getParent();
// var url_base = ss.getUrl().replace(/edit$/,'') + "export?";
var url_base = "https://docs.google.com/spreadsheets/d/" + ss.getId() + "/" + "export?";
var url_ext = 'exportFormat=pdf' //export as pdf
+ '&format=pdf' //export as pdf
+ '&gid=' + sheetId
+ '&size=letter' // paper size
+ '&portrait=' + portrait // orientation, false for landscape
+ '&fitw=true' // fit to width, false for actual size
+ '&sheetnames=false' //optional headers and footers
+ '&printtitle=false' //optional headers and footers
+ '&pagenumbers=true' //page numbers
+ '&gridlines=true' // gridlines
+ '&fzr=true' // repeat row headers (frozen rows) on each page
var response = UrlFetchApp.fetch(url_base + url_ext, params);
var blob = response.getBlob().setName(pdfName + ".pdf");
return blob;
}

Try this:
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 = "docs.google.com/spreadsheets/d" + spreadsheetId + "/export?";
var url_ext = '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(),
},
'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,
subject+" (" + pdfName +")",
"html content only",
mailOptions);
MailApp.sendEmail(
Session.getActiveUser().getEmail(),
" "+subject+" (" + pdfName +")",
"html content only",
mailOptions);
}
}

Can you try this instead of your current blob declaration :
var blob = response.getBlob().getAs('application/pdf').setName(pdfName + ' .pdf');
References:
Class Blob

Related

setName when exporting a PDF from Google Sheets with Google Apps Script

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 ]
});
}

Google APP Script suddenly exporting PDF as text/html

I am having a strange problem and am hoping someone can guide. We have been using the following script for a long time with no issue, converts sheet into PDF and stores it into the drive. Now for some reason the file being created is a text/html file in PDF format. I am not sure why this is happening now nothing else has changed on our side.
function convertSpreadsheetToPdf(email, spreadsheetId, sheetName, pdfName)
{
var spreadsheet = spreadsheetId ? SpreadsheetApp.openById(spreadsheetId) :
SpreadsheetApp.getActiveSpreadsheet();
spreadsheetId = spreadsheetId ? spreadsheetId : spreadsheet.getId()
var sheetId = sheetName ? spreadsheet.getSheetByName(sheetName).getSheetId() : null;
var pdfName = pdfName ? pdfName : spreadsheet.getName();
var parents = DriveApp.getFileById(spreadsheetId).getParents();
var folder = parents.hasNext() ? parents.next() : DriveApp.getRootFolder();
var url_base = spreadsheet.getUrl().replace(/edit$/,'');
var url_ext = 'export?exportFormat=pdf&format=pdf' //export as pdf
// Print either the entire Spreadsheet or the specified sheet if optSheetId is provided
+ (sheetId ? ('&gid=' + sheetId) : ('&id=' + spreadsheetId))
// following parameters are optional...
+ '&size=letter' // paper size
+ '&portrait=true' // 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
var options = {
headers: {'Authorization': 'Bearer ' + ScriptApp.getOAuthToken(),}
var response = UrlFetchApp.fetch(url_base + url_ext, options);
var blob = response.getBlob().setName(pdfName + '.pdf');
folder.createFile(blob);
}

Change document orientation when exporting to PDF

I have this script that emails the content of a speadsheet to all the collaborators on a regular basis.
function myFunction() {
var document = SpreadsheetApp.openById("123documentid456");
var editors = document.getEditors();
for(var i = 0; i < editors.length; i++){
MailApp.sendEmail(editors[i].getEmail(), "Subject", "Some message", {
attachments : [document.getAs(MimeType.PDF)]
});
}
}
It creates a PDF and emails it. The thing is the content does not display nicely as the PDF's orientation is portrait. Is there any way to make it export to landscape?
From here, this code could help
*************************************************
function savePDFs() {
SpreadsheetApp.flush();
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getActiveSheet();
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, true for portrait
'&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(sheet.getName() + '.pdf');
//from here you should be able to use and manipulate the blob to send and email or create a file per usual.
//In this example, I save the pdf to drive
DocsList.createFile(blob);
//OR DriveApp.createFile(blob);
}
*************************************************
Notice this bit: '&portrait=false' + //orientation, false for landscape, true for portrait

google sheet to pdf mailto

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]});
}

Creating PDF in Landscape (Google Apps Script)

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]});
}