Skip to content

Instantly share code, notes, and snippets.

@lechien73
Created June 14, 2024 11:01
Show Gist options
  • Save lechien73/6cd9a121811ff381f42d4c78bb2f4982 to your computer and use it in GitHub Desktop.
Save lechien73/6cd9a121811ff381f42d4c78bb2f4982 to your computer and use it in GitHub Desktop.
Export to PDF from Google Sheets
function exportToPdf() {
var blob,exportUrl,name,options,pdfFile,response,sheetTabId,ss,ssID,url_base;
ss = SpreadsheetApp.getActiveSpreadsheet();
ssID = ss.getId();
sh = ss.getSheetByName(ss.getActiveSheet().getName());
range = "A1:F" + sh.getMaxRows();
sheetTabId = sh.getSheetId();
url_base = ss.getUrl().replace(/edit$/,'');
name = sh.getRange("J4").getValue() + "_" + sh.getRange("K4").getValue();
name += " Cohort Schedule";
exportUrl = url_base + 'export?exportFormat=pdf&format=pdf' +
'&gid=' + sheetTabId + '&id=' + ssID +
'&range=' + range +
'&size=A4' +
'&portrait=true' +
'&fitw=true' +
'&sheetnames=false&printtitle=false&pagenumbers=false' +
'&gridlines=false' +
'&fzr=false'; // do not repeat row headers (frozen rows) on each page
options = {
headers: {
'Authorization': 'Bearer ' + ScriptApp.getOAuthToken(),
}
}
options.muteHttpExceptions = true;
response = UrlFetchApp.fetch(exportUrl, options);
if (response.getResponseCode() !== 200) {
console.log("Error exporting Sheet to PDF! Response Code: " + response.getResponseCode());
return;
}
blob = response.getBlob();
blob.setName(name + ".pdf")
pdfFile = DriveApp.createFile(blob);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment