Convert Image to PDF to Google Script

The Google Script will fetch an image file, convert it to PDF and sends it as an image attachment using the Gmail service. The image file can be on your Google Drive or it can be on web (specify the image URL as the filename).

Also see: How to Convert Files

function convertImageToPDF(filename) {
  var image;

  // Is it a local file or web URL?
  if (filename.match(/^https?:\/\//i)) {
    image = UrlFetchApp.fetch(filename);
  } else {
    image = DriveApp.getFilesByName(filename).next();
  }

  // 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(filename + '.pdf');

  MailApp.sendEmail('ctrlq@labnol.org', 'Image to PDF', '', {
    attachments: blob.getAs(MimeType.PDF),
  });
}

Amit Agarwal is a web geek, solo entrepreneur and loves making things on the Internet. Google recently awarded him the Google Developer Expert and Google Cloud Champion title for his work on Google Workspace and Google Apps Script.

Awards & Recognition

Google Developer Expert

Google Developer Expert

Google awarded us the Developer Expert title recogizing our work in Workspace

ProductHunt Golden Kitty

ProductHunt Golden Kitty

Our Gmail tool won the Lifehack of the Year award at ProductHunt Golden Kitty Awards

Microsoft MVP Alumni

Microsoft MVP Alumni

Microsoft awarded us the Most Valuable Professional title for 5 years in a row

Google Cloud Champion

Google Cloud Champion

Google awarded us the Champion Innovator award for technical expertise

Want to stay up to date?
Sign up for our email newsletter.

We will never send any spam emails. Promise 🫶🏻