Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
google apps script to email a spreadsheet as a pdf invoice
/** Returns a PDF object based on the contents of the 'invoicing' sheet */
function invoiceToPDF(invDetails)
{
var spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
ssID = spreadsheet.getId();
var sheet = spreadsheet.getSheetByName(INVOICES_SHEETNAME);
var gid = sheet.getSheetId();
// &gid=x at the end of above url if you only want a particular sheet
var url2 = "http://spreadsheets.google.com/feeds/download/spreadsheets/Export?key=" + ssID +
"&gid=" + gid +
"&fmcmd=12&size=7&fzr=true&portrait=true&fitw=true&locale=en&gridlines=false&printtitle=false&sheetnames=false&pagenum=UNDEFINED&attachment=true";
// AUTH TOKEN required to access the UrlFetchApp call below. You can receive it
// from https://appscripts.appspot.com/getAuthToken
var AUTH_TOKEN = "your_token_goes_here";
var auth = "AuthSub token=\"" + AUTH_TOKEN + "\"";
var res = UrlFetchApp.fetch(url2, {headers: {Authorization: auth}}).getBlob();
return res;
}
/**
* Creates an invoice in the Invoices drive folder
*/
function createInvoiceAsGDriveDocsFile(pdfBlob)
{
var details = getInvoiceDetails();
filename = "Invoice_xyz";
var spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
// get or create the base folder
var theFolder = getInvoicesBaseFolder();
// Create the invoice file based on the filename
try
{
var matchingFileList = theFolder.find(filename);
// guard against duplicates
if (matchingFileList == undefined || matchingFileList.length == 0)
{
pdfBlob.setName(filename);
var f = theFolder.createFile(pdfBlob);
// check file created ok
if (f != undefined)
{
f.setDescription("TBD some blurb from the invoice perhaps");
spreadsheet.toast("Created invoice " + f.getName() + " " + f.getSize() + " bytes" + " in " + theFolder.getName());
}
else
{
Browser.msgBox("ERROR: creating document: " + filename);
}
}
else
{
Browser.msgBox("ERROR: New invoice not created. " + filename + " already exists. " + filename);
}
}
catch (fileCreateError)
{
Browser.msgBox("ERROR: couldn't create invoice pdf " + filename);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment