电子表格和App脚本中的图像问题

时间:2016-09-06 20:33:53

标签: google-apps-script google-sheets

当我在电子表格中插入图片然后将其转换为pdf时,我遇到了应用脚本的问题。该图像未出现在文档pdf中。

我的代码是:

这里插入图片

libro=SpreadsheetApp.openById('XXXXXXXXXXXXXXXXX');
hojaX=Libro.getSheetByName('Test');
hojax.insertImage("http://test.com/imagen.jpg", 3, 71, 0, 0); 

此处将电子表格转换为pdf

var file = DriveApp.getFileById('XXXXXXXXXXXXXXXXX').getAs('application/pdf').getBytes();

此处附有要发送的电子邮件

var attach = {fileName:'name.pdf',content:file, mimeType:'application/pdf'};  

MailApp.sendEmail(test@test.com, "title", "message" {attachments:[attach]});

我无法解决,没有图片的pdf发送,你能帮帮我吗? 问候

1 个答案:

答案 0 :(得分:0)

以下是insert an image in App Script的方法。

function myFunction() {
  var SPREADSHEET_URL = 'https://docs.google.com/spreadsheets/d/abcdefghiklmnopqrstopwxyz/edit#gid=0';
   var SHEET_NAME = 'Sheet1';

  var ss = SpreadsheetApp.openByUrl(SPREADSHEET_URL);
  var sheet = ss.getSheetByName(SHEET_NAME);

  var response = UrlFetchApp.fetch(
      'http://i.imgur.com/PnJTXjN.png'); //url of the image
  var binaryData = response.getContent();

  var blob = Utilities.newBlob(binaryData, 'image/png', 'MyImageName');
  sheet.insertImage(blob, 1, 1); //this puts the image in A1 of the cell 
}

以下是如何将图片转换为PDF并附加到Amit Agarwal提供的电子邮件中。当您运行此代码时,将在附带pdf的邮件中发送一条消息。

function convertImageToPDF() {

 var image = UrlFetchApp.fetch('http://i.imgur.com/DS6bVac.png');

  // grab its bytes and base64-encode them.
  var base64 = Utilities.base64Encode(image.getBlob().getBytes());
  var html = '<img src="data:image/png;base64,'+base64+'" />';

  // create a blob, convert to PDF
  var blob = Utilities.newBlob(html, MimeType.HTML).setName('myImage' + ".pdf");

  //save to Google Drive
   var file = {
    title: 'myImage.pdf',
    mimeType: 'application/pdf'
  };
   file = Drive.Files.insert(file,blob.getAs(MimeType.PDF));
  Logger.log('ID: %s, File size (bytes): %s', file.id, file.fileSize);

  //send to email as attached file
  MailApp.sendEmail("youremail@gmail.com", "Image to PDF", "", {
    attachments:blob.getAs(MimeType.PDF)
  });

}