Fer Tovar
Fer Tovar

Reputation: 31

Issue with images in spreadsheet and App Script

I have an issue with apps script when I insert the image in spreadsheet and then convert it to pdf. The image doesn't appear in the document pdf.

My code is:

here insert the image

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

here convert the spreadsheet in pdf

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

here attach to email to send

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

MailApp.sendEmail([email protected], "title", "message" {attachments:[attach]});

I can't fix, the pdf send without image, could you help me? regards

Upvotes: 0

Views: 739

Answers (1)

ReyAnthonyRenacia
ReyAnthonyRenacia

Reputation: 17613

Here's how to 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 
}

Here's how to convert Image to PDF and attach in your email courtesy of Amit Agarwal. When you run this code, a message will be sent to your mail with the pdf attached.

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("[email protected]", "Image to PDF", "", {
    attachments:blob.getAs(MimeType.PDF)
  });

}

Upvotes: 1

Related Questions