从Google应用程序脚本中的字符串创建PDF

从Google应用程序脚本中的字符串创建PDF,pdf,google-apps-script,Pdf,Google Apps Script,我确信这也是我没有得到的东西,因为我没有得到一个普遍的概念。我正试图在Google Drive中创建一个PDF文件,它来自于我之前构建的字符串 var oPdfCreator = { hFolderHandle: DocsList.getFolderById('0B1rbQnVtcj5CNWNmekFWMG9DZzA'), hPdfHandle: "", mToastFeedback: function () { SpreadsheetApp.getActi

我确信这也是我没有得到的东西,因为我没有得到一个普遍的概念。我正试图在Google Drive中创建一个PDF文件,它来自于我之前构建的字符串

var oPdfCreator = {
    hFolderHandle: DocsList.getFolderById('0B1rbQnVtcj5CNWNmekFWMG9DZzA'),
    hPdfHandle: "",

    mToastFeedback: function () {
      SpreadsheetApp.getActiveSpreadsheet().toast('Finished');
    }
};

oPdfCreator.hPdfHandle = oPdfCreator.hFolderHandle.createFile('test.pdf',   Utilities.newBlob(oInvoice.sInvoiceBody).getBytes(), 'application/pdf');
这不起作用,PDF格式不正确,我忍不住开始怀疑我是否没有理解这个概念

再次感谢你的回答


好的,答案让我走上了正确的轨道。这真的非常接近我想要做的,我希望能够直接创建一个带有pdf内容的blob,但我意识到这更容易阅读。我们都同意可读代码更好

var oPdfCreator = {
  hFolderHandle: DocsList.getFolderById('0B1rbQnVtcj5CNWNmekFWMG9DZzA'),
  hTempHtmlHandle: "",
  hPdfHandle: "",

  mToastFeedback: function () {
      SpreadsheetApp.getActiveSpreadsheet().toast('Finished');
  }
};
oPdfCreator.hTempHtmlHandle = oPdfCreator.hFolderHandle.createFile('test.html',  oInvoice.sInvoiceBody, 'text/html');
oPdfCreator.hPdfHandle = oPdfCreator.hFolderHandle.createFile(oPdfCreator.hTempHtmlHandle.getAs('application/pdf')).rename('test.pdf');
DocsList.getFileById(oPdfCreator.hTempHtmlHandle.getId()).setTrashed(true);

function fProcessRequest () {
  oInvoice.mProcessInvoice();
  oPdfCreator.mToastFeedback();
}

我尝试了两种方法来获得您想要的结果,一种不起作用,另一种成功了,但我不确定它是否适用于您的特定用例

试试看,告诉我们发生了什么。在这两个函数中,我创建了一个临时文件,在转换成功时动态删除该文件

第一个函数仅使用DriveApp并尝试创建中间纯文本文件,但最终转换失败:

function test1() {
  var pdfContent = 'test pdf content\n\nThis is a normal text in a pdf file';
  var intermediate = DriveApp.createFile('tempFile',pdfContent,MimeType.PLAIN_TEXT);
  var blob = intermediate.getAs(MimeType.PDF);
  Logger.log(blob.getContentType());
  var pdfFile = DriveApp.createFile(blob);
  DriveApp.getFileById(intermediate.getId()).setTrashed(true);
}
第二个函数假定文件内容为“纯文本”,并使用DocumnentApp创建中间文件。。。这种转换(再次使用DriveApp)有效,我得到了一个有效的pdf文件

function test2() {
  var pdfContent = 'test pdf content\n\nThis is a normal text in a pdf file';
  var intermediate = DocumentApp.create('otherTest');
  intermediate.getBody().editAsText().appendText(pdfContent);
  intermediate.saveAndClose();
  var id = intermediate.getId();
  var blob = DriveApp.getFileById(id).getAs(MimeType.PDF);
  Logger.log(blob.getContentType());
  var pdfFile = DriveApp.createFile(blob);
  DriveApp.getFileById(id).setTrashed(true);
}

要添加更多信息,我无法创建blob,这是使用createFile方法创建PDF所必需的。Apps脚本在“视图”菜单下有一个执行记录。在代码运行后,您是否查看过该选项?它是否显示错误?与其从oPdfCreator对象内部调用函数,不如逐行编写代码以简化调试?PS,你知道为什么我不能使用对象中定义的变量及其方法吗?你的意思是不使用中间驱动器文件吗?不,这与文件完全无关。例如,当我在javascript对象中定义变量时,例如:var oPdfCreator={hFolderHandle:”,mFunction:function(){obPdfCreator.hFolderHandle.createFile(blob);}这给了我一个错误,它告诉我在hFolder中找不到createFile方法。抱歉,无法在这方面帮助您…可能是一篇新文章?