duck
duck

Reputation: 149

Attach google spreadsheet as pdf to email

I would like to create a PDF of a specific sheet (not necessarily the active one) and send it as an email attachment. I've borrowed and tried several code snippets, but none work correctly. I've searched and analyzed all the forums I can find, but I can't figure out the issue. I'm a novice programmer, so I like it simple. This snippet is intuitive to me, but it gives the following error: "We're sorry, no servers are currently available. Please wait a bit and try again." Debugger says that both pdf and attach are undefined.

var pdf = SpreadsheetApp.getActive().getAs('application/pdf').getBytes();
var attach = {fileName:'test.pdf',content:pdf, mimeType:'application/pdf'};
MailApp.sendEmail(recipients, subject, body, {attachments:[attach]});

Three things:

  1. can you help me get the pdf/attachment function working properly?
  2. can you help me modify it for a specific sheet (say, Sheet1)?
  3. is it possible to make a pdf out a range on a sheet rather than the whole sheet?

Thanks!

Upvotes: 1

Views: 3995

Answers (2)

Mogsdad
Mogsdad

Reputation: 45710

You're trying to apply methods of one Class to another that does not implement it. (e.g. getAs() isn't a Spreadsheet method.) When you're writing your script, pay attention to the autocomplete feature, which would have helped to avoid this error. See this previous answer for more details about that.

Answers:

  1. See Google Apps Script to Email Active Spreadsheet, which demonstrates how to generate a PDF from a sheet.

  2. To isolate a single sheet, see ajb1970's answer to the same question. The idea here is to copy the sheet you're interested in into a new, temporary, spreadsheet - and then make your PDF from that.

  3. To do this with a range, repeat step 2, but with the range you're interested in.

Upvotes: 2

Zig Mandel
Zig Mandel

Reputation: 19835

Use getBlob not getBytes. Also you cant specify a specific sheet. Instead copy that sheet into a new spreadsheet, convert that one to pdf and later delete it.

Upvotes: 0

Related Questions