I've searched all over for some lines of code that would accomplish what I want, but I'm too unfamiliar with how google apps script works. I've only ever coded in Microsoft excel and although I'm not completely lost, I'm still pretty lost.
I am looking for code that would select a range, then "Download as.." the selection to PDF, fit width, portrait, no grid. Ideally this PDF could be sent to a specific folder on my desktop, but I don't know if the apps script supports that.
I've found the methods needed (I think) to establish the width, portrait, no grid. All the other searches I've done convert the entire sheet to a PDF and email it which isn't what I want to do and I couldn't find what parts of those sample codes to delete because it looks like PDFs are recognized as web addresses. Any help would be greatly appreciated.
It is possible to export a range from your Google Sheet without hiding sheet tabs, rows and columns, or creating a temporary new spreadsheet.
function exportRangeToPDf(range) {
var blob,exportUrl,options,pdfFile,response,sheetTabNameToGet,sheetTabId,ss,ssID,url_base;
range = range ? range : "C4:D4";//Set the default to whatever you want
sheetTabNameToGet = "Sheet1";//Replace the name with the sheet tab name for your situation
ss = SpreadsheetApp.getActiveSpreadsheet();//This assumes that the Apps Script project is bound to a G-Sheet
ssID = ss.getId();
sh = ss.getSheetByName(sheetTabNameToGet);
sheetTabId = sh.getSheetId();
url_base = ss.getUrl().replace(/edit$/,'');
//Logger.log('url_base: ' + url_base)
exportUrl = url_base + 'export?exportFormat=pdf&format=pdf' +
'&gid=' + sheetTabId + '&id=' + ssID +
'&range=' + range +
//'&range=NamedRange +
'&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
//Logger.log('exportUrl: ' + exportUrl)
options = {
headers: {
'Authorization': 'Bearer ' + ScriptApp.getOAuthToken(),
}
}
options.muteHttpExceptions = true;//Make sure this is always set
response = UrlFetchApp.fetch(exportUrl, options);
//Logger.log(response.getResponseCode())
if (response.getResponseCode() !== 200) {
console.log("Error exporting Sheet to PDF! Response Code: " + response.getResponseCode());
return;
}
blob = response.getBlob();
blob.setName('AAA_test.pdf')
pdfFile = DriveApp.createFile(blob);//Create the PDF file
//Logger.log('pdfFile ID: ' +pdfFile.getId())
}
There are various strategies that have been used to export part of a Google Sheet to a PDF.
I would use the method of building a download URL with the range included in the download URL.