Created
June 14, 2024 11:01
-
-
Save lechien73/6cd9a121811ff381f42d4c78bb2f4982 to your computer and use it in GitHub Desktop.
Export to PDF from Google Sheets
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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