Send Google Sheets Data as PDF in an Email

Here’s a step-by-step approach on how to create a Google Sheet and use Apps Script to send it as an email as a PDF attachment, including steps to create a graph in the spreadsheet:

Step 1: Setup Google Sheet to export

  1. Create a new Google Sheet by going to Google Drive and selecting “New” > “Google Sheets”.
  2. Rename the sheet to something descriptive like “Sales Data”.
  3. Add some sample data to the sheet, including column headings for “Date”, “Product”, “Sales”, and “Expenses”.
  4. Highlight the data that you want to include in the graph.
  5. Select “Insert” > “Chart” from the Google Sheets menu.
  6. Choose the type of chart that you want to create, such as a bar chart or line chart.
  7. Customize the chart as desired using the options in the Chart Editor.
  8. Once the chart is created, you can move it to a separate sheet or embed it in a dashboard if desired.

Step 2: Write Apps Script to export the Sheet

  1. Open the Apps Script editor by selecting “Tools” > “Script editor” from the Google Sheets menu.
  2. In the Apps Script editor, create a new script file by selecting “File” > “New” > “Script file”.
  3. Name the script file something descriptive like “SendSalesReport”.
  4. Copy and paste the following code into the script file:
function sendSalesReport() { var sheet = SpreadsheetApp.getActive().getSheetByName('Sales Data'); // Replace 'Sales Data' with the name of your sheet var url = sheet.getUrl(); var sheetId = sheet.getSheetId(); var pdf = UrlFetchApp.fetch('https://docs.google.com/spreadsheets/d/' + url.substring(url.indexOf('/d/')+3, url.indexOf('/edit')) + '/export?exportFormat=pdf&gid=' + sheetId, { headers: { Authorization: 'Bearer ' + ScriptApp.getOAuthToken() } }).getBlob(); // Send email with PDF attachment var email = Session.getActiveUser().getEmail(); var subject = 'Sales Report'; var message = 'Attached is the latest sales report.'; var attachments = [{fileName: 'sales_report.pdf', content: pdf}]; GmailApp.sendEmail(email, subject, message, {attachments: attachments}); }
  1. Save the script file.
  2. Test the sendSalesReport() function by selecting “Run” > “sendSalesReport” from the menu in the script editor.
  3. Grant the necessary permissions when prompted.
  4. Check your email to ensure the sales report was sent as a PDF attachment with the chart included.
  5. You can now set up a time-driven trigger to run the sendSalesReport() function regularly, such as weekly or monthly.

That’s it! You can now use this script to send a sales report with a chart included as a PDF attachment via email.