google-apps-scriptcloudconvert

CloudConvert conversion API - PDF to PNG using Google Apps Script


I'm a Google Apps Script Developer and a beginner with API integrations. I'm attempting to convert a PDF file stored in Google Drive to PNG format and save it back to the same folder. For this purpose, I'm using CloudConvert API. Unfortunately, my code is not functioning correctly. I would greatly appreciate it if someone could review my code and provide me with the correct solution.

function convertPDFtoPNG(fileName) {
  var apiKey = "xyz";

  var file = folder.getFilesByName(fileName + ".pdf").next();
  var folderId = folder.getId();
  var fileUrl = file.getDownloadUrl();

  var requestBody = {
    "tasks": {
      "import-pdf-file": {
        "operation": "import/url",
        "url": fileUrl,
        "filename": file.getName()
      },
      "convert-pdf-file": {
        "operation": "convert",
        "input": "import-pdf-file",
        "input_format": "pdf",
        "output_format": "png"
      },
      "export-png-file": {
        "operation": "export/url",
        "input": "convert-pdf-file",
        "folder_id": folderId
      }
    },
    "tag": "convert-pdf-to-png"
  };

  var options = {
    method: 'post',
    headers: {
      'Authorization': 'Bearer ' + apiKey,
      'Content-Type': 'application/json'
    },
    payload: JSON.stringify(requestBody)
  };

  var response = UrlFetchApp.fetch('https://api.cloudconvert.com/v2/jobs', options);
  var job = JSON.parse(response.getContentText());
  var downloadUrl = job.url;
  var pngBlob = UrlFetchApp.fetch(downloadUrl).getBlob();
  var newFile = folder.createFile(pngBlob).setName(fileName + ".png");
}

Solution

  • Check if the file is shared correctly with "Anyone with the link can view" option. If it's not, the server won't be able to download it.

    If the file is a single-page PDF, this workaround could help without requiring an external API: the same code can be applied to any image format including HEIC and TIFF files. However, this is just a workaround that works for my use case and may not fit yours.

    function anyFileToPng() {
      //  FileID of the file you want to "convert"
    
      const fileId = "<<PDF-FILE-ID-GOES-HERE>>"
      // Use the Drive Advanced Service (you'll need to enable it thrue 'Services'...)
      const driveFileObj = Drive.Files.get(fileId);  
    
      /* Change the thumbnailUrl > I'm guessing the =s stands for "size". Change it to something like 2500 if you want a larger file. */
      const thumbnailURL = driveFileObj.thumbnailLink.replace(/=s.+/, "=s2500")  
    
    
      /* Take the filename and remove the extension part. */
      const fileName = driveFileObj.title;
      const newFileName = fileName.substring(0, fileName.lastIndexOf('.')) || fileName 
    
    
      // Fetch the "thumbnail-Image".
      const pngBlob = UrlFetchApp.fetch(thumbnailURL).getBlob();
      
      // Save the file in some folder...
      const destinationFolder = DriveApp.getFolderById("<<DESTINATION-FOLDER-ID-GOES-HERE>>")
      destinationFolder.createFile(pngBlob).setName(newFileName+'.png');
    }
    

    Please also check out this question. The accepted answer includes similar code to mine, but with support for PDFs with multiple pages... Convert a gdoc into image