Converting a google doc to a pdf results in blank pdf, google scripts

孤者浪人 提交于 2020-12-12 03:47:44

问题


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('will@exampleEmail.co.uk',
                                   'Email title', 'Pls see attached', 
                                   {
                                     attachments: [pdfContent.getAs(MimeType.PDF)],
                                     name: 'Converted doc content'
                                   });
// Now send the mail
draftMail.send();
}

回答1:


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('will@exampleEmail.co.uk',
        '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



来源:https://stackoverflow.com/questions/52112528/converting-a-google-doc-to-a-pdf-results-in-blank-pdf-google-scripts

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!