Reputation: 47
Here is my code to create a google doc paste some information in (eventually from a spreadsheet), convert it to a pdf and email it to myself.
Unfortunately, while the document in drive has the 'This document was created by Google Apps Script.' comment in it, The pdf in the email does not. It has the right title but the content of the page is lost. I have tried several examples on stack overflow and have not got one so far to work.
var ss = SpreadsheetApp.getActive();
function onOpen(){
var ui = SpreadsheetApp.getUi();
ui.createMenu('TEST MENU') //creates main menu tab
.addItem('pdf', 'pdf')
.addToUi();
}
function pdf() {
// Create a new Google Doc named 'Hello, world!'
var doc = DocumentApp.create('Hello, world!');
// Access the body of the document, then add a paragraph.
doc.getBody().appendParagraph('This document was created by Google Apps Script.');
var pdfContent = doc.getAs('application/pdf');
var draftMail = GmailApp.createDraft('[email protected]',
'Email title', 'Pls see attached',
{
attachments: [pdfContent.getAs(MimeType.PDF)],
name: 'Converted doc content'
});
// Now send the mail
draftMail.send();
}
Upvotes: 2
Views: 1475
Reputation: 4635
You're not saving and closing the doc before converting it to pdf, maybe that's why your changed is not flushed out.
Try something like this:
var ss = SpreadsheetApp.getActive();
function onOpen() {
var ui = SpreadsheetApp.getUi();
ui.createMenu('TEST MENU') //creates main menu tab
.addItem('pdf', 'pdf')
.addToUi();
}
function pdf() {
var doc = DocumentApp.create('Hello, world!');
doc.getBody().appendParagraph('This document was created by Google Apps Script.');
doc.saveAndClose()
var pdfContent = doc.getAs('application/pdf');
var draftMail = GmailApp.createDraft('[email protected]',
'Email title', 'Pls see attached', {
attachments: [pdfContent.getAs(MimeType.PDF)],
name: 'Converted doc content'
});
draftMail.send();
}
Reference : https://developers.google.com/apps-script/reference/document/document#saveandclose
Upvotes: 7