Skip to content

Instantly share code, notes, and snippets.

@jsdbroughton
Last active April 28, 2022 18:42
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jsdbroughton/4967544 to your computer and use it in GitHub Desktop.
Save jsdbroughton/4967544 to your computer and use it in GitHub Desktop.
Function to convert a given Google Spreadsheet [Sheet] into a PDF.
/**
* Function to convert a given Google Spreadsheet [Sheet] into a PDF.
*
* @param {string} key This is the Id of the Sheet to be converted bothe the DocsList.getId() and the SpreadsheetApp.getId() versions work
* @param {string} name [Optional] Intended Filename. If omitted, uses the Sheet filename.
* @param {object} options Settings object for the crafting of the PDF. Defaults to A4, no gridline print etc. <pre>
* {
* format:Enum,
* size:Enum,
* headers: Bool,
* orientation: String,
* actualSize: Bool,
* locale: Enum,
* sheet: Int,
* showGridlines: Bool,
* showTitle: Bool,
* hideSheetName: Bool,
* pageNumberPosition: Enum
* }
* </pre>
* @return {object} Object including a File Object [PDF] and all the settings used to perform the conversion (for testing?)
*/
function spreadsheetToPDF (key, name, options) {
var scope = 'https://spreadsheets.google.com/feeds',
fetchArgs = googleOAuth_('spreadsheets', scope),
sizes = {Screen:1, Letter: 0, Legal:2, Folio:25, F4:32, LongBond:26, PhilippineLegal:31, Tabloid:29, Executive: 30, Ledger: 33, Statement:27, A0:3, A1:4, A2:5, A3:6, A4:7, A5:8, A6:9, A7:10, A8:11, A9:12, A10:13, B0:14, B1:15, B2:16, B3:17, B4:18, B5:19, ARCHE:20, ARCHD:21, ARCHC:22, ARCHB:23, ARCHA:24, ANSIB:28},
formats = {PDF:12, CSV:5, ODS:13, XLSX:4},
pageNumberLocations = ['LEFT','CENTER','RIGHT','NONE'],
sheet,
pdf,
url;
try {
sheet = SpreadsheetApp.openById(key);
} catch(err) {
Logger.log('Invalid Spreadsheet Id - Cannot parse as PDF');
return; // this could pass a fail object back, but calling script would need to handle it and not break.
}
name = name || sheet.getName();
options = options || {actualSize: false, format: 'PDF'};
pdf = {
fileId: key,
fileFormat: (options.format && formats.hasOwnProperty(options.format)) ? formats[options.format] : 12, // defaults PDF
pageSize: (sizes.hasOwnProperty(options.size)) ? sizes[options.size] : 7, // defaults A4
repeatHeaders: options.headers === true, // defaults repeat frozen rows = false
portrait: (options.orientation) ? (options.orientation === 'portrait') : true, // defaults portrait
fit: (options.actualSize === false), // defaults fit width = true
locale: 'en_GB', // defaults UK English
sheet: (options.sheet && 0 <= options.sheet < sheet.getSheets().length) ? options.sheet : false, // defaults false if no sheet specified or beyond sheet count
gridlines: (options.showGridlines === true), // defaults hide gridlines
showTitle: (options.showTitle === true), // defaults include file name
showSheetName: (options.hideSheetName === true), // defaults hide sheet name
pageNumber: (pageNumberLocations.indexOf(options.pageNumberPosition) > -1) ? options.pageNumberPosition : 'LEFT', // defaults number bottom left
// selection: false, // selection print is not implemented
getFile: false // defaults to
}
url = scope + "/download/spreadsheets/Export?";
url += "key=" + key;
url += "&fmcmd=" + pdf.fileFormat;
url += "&size=" + pdf.pageSize;
url += "&fzr=" + pdf.repeatHeaders;
url += "&portrait=" + pdf.portrait;
url += "&fitw=" + pdf.fit;
url += "&locale=" + pdf.locale;
url += (pdf.sheet) ? "&gid=" + pdf.sheet : '';
url += "&gridlines=" + pdf.gridlines;
url += "&printtitle=" + pdf.showTitle;
url += "&sheetnames=" + pdf.showSheetName;
url += "&pagenum=" + pdf.pageNumber;
url += "&attachment=" + pdf.getFile;
// url += "&r1=1&c1=1&r2=1&c2=1"; // if gid != undefined all 4 are required !!!these values are a mystery to me!!!
pdf.file = UrlFetchApp.fetch(url, fetchArgs).getBlob().setName(name);
return pdf;
}
//Google oAuth
function googleOAuth_(name,scope) {
var oAuthConfig = UrlFetchApp.addOAuthService(name);
oAuthConfig.setRequestTokenUrl("https://www.google.com/accounts/OAuthGetRequestToken?scope="+scope);
oAuthConfig.setAuthorizationUrl("https://www.google.com/accounts/OAuthAuthorizeToken");
oAuthConfig.setAccessTokenUrl("https://www.google.com/accounts/OAuthGetAccessToken");
oAuthConfig.setConsumerKey("anonymous");
oAuthConfig.setConsumerSecret("anonymous");
return {oAuthServiceName:name, oAuthUseToken:"always"};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment