🟪 Two "online" methods for converting an image to a pdf

If you, for whatever reason, need to set an image as a pdf, here are two methods you could use. For both examples you will need the ever-giving Base64 extension by @Juan_Antonio. The examples are worked up using an Android 10 emulator under API30 :

With Google Apps Script
This returns an A4 page with the image on it

  1. Create and Publish a google apps script web app with the following code:
function doPost(e) {
//convert Image To PDF

  //get base64 encoded image and filename from parameters
  var imgBase64 = e.parameter.imgBase64;
  var filename = e.parameter.filename;
  // make html
  var html = '<img src="data:image/png;base64,'+imgBase64+'" />';
  // create a blob, convert to PDF, get new filename
  var blob = Utilities.newBlob(html, MimeType.HTML).setName(filename + ".pdf");
  blob = blob.getAs(MimeType.PDF);
  var file = DriveApp.getRootFolder().createFile(blob);
  var pdfName = blob.getName();
  //convert file to base64 for download
  var b64String = Utilities.base64Encode(file.getBlob().getBytes());
  //delete pdf file (send to bin for 30 days before being deleted)
  file.setTrashed(true);

return ContentService.createTextOutput(JSON.stringify([b64String,pdfName]));
}
  1. Create an AI2 app project and setup your blocks like this: (note the blocks were setup using companion and a png image file from assets)

With Imagemagick on a php server
This returns a pdf the size of the image

  1. You will need a php server with imagemagick installed and a suitable php file:
<?php

header('Content-Type: image/png');

  $data = file_get_contents('php://input');
  $filename = $_GET['filename'];
  $command =  $_GET['command'];

  if (file_put_contents($filename,$data)) {
    if (filesize($filename) != 0) {
      
      passthru( $command );
    } 
  } 

if (!unlink($filename)) {
  }
else {
  }

?>
  1. You will need to ensure that your imagemagick policy.xml is set to work with pdf by setting this line in the /etc/ImageMagick-n/policy.xml file
<policy domain="coder" rights="read | write" pattern="PDF" />
  1. Create an AI2 project and setup you blocks like this: (again running in companion using a png image file from assets)

I leave you to work out a method to access the pdf file from the ASD and to display it! :wink:

3 Likes