Home > Blockchain >  CloudConvert conversion API - PDF to PNG using Google Apps Script
CloudConvert conversion API - PDF to PNG using Google Apps Script

Time:02-04

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");
}

CodePudding user response:

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

CodePudding user response:

I found this code in reply to this question and it works perfectly.

async function convertPDFToPNG_(blob) {
  // Convert PDF to PNG images.
  const cdnjs = "https://cdn.jsdelivr.net/npm/pdf-lib/dist/pdf-lib.min.js";
  eval(UrlFetchApp.fetch(cdnjs).getContentText()); // Load pdf-lib
  const setTimeout = function (f, t) { // Overwrite setTimeout with Google Apps Script.
    Utilities.sleep(t);
    return f();
  }
  const data = new Uint8Array(blob.getBytes());
  const pdfData = await PDFLib.PDFDocument.load(data);
  const pageLength = pdfData.getPageCount();
  console.log(`Total pages: ${pageLength}`);
  const obj = { imageBlobs: [], fileIds: [] };
  for (let i = 0; i < pageLength; i  ) {
    console.log(`Processing page: ${i   1}`);
    const pdfDoc = await PDFLib.PDFDocument.create();
    const [page] = await pdfDoc.copyPages(pdfData, [i]);
    pdfDoc.addPage(page);
    const bytes = await pdfDoc.save();
    const blob = Utilities.newBlob([...new Int8Array(bytes)], MimeType.PDF, `sample${i   1}.pdf`);
    const id = DriveApp.createFile(blob).getId();
    Utilities.sleep(3000); // This is used for preparing the thumbnail of the created file.
    const link = Drive.Files.get(id, { fields: "thumbnailLink" }).thumbnailLink;
    if (!link) {
      throw new Error("In this case, please increase the value of 3000 in Utilities.sleep(3000), and test it again.");
    }
    const imageBlob = UrlFetchApp.fetch(link.replace(/\=s\d*/, "=s1000")).getBlob().setName(`page${i   1}.png`);
    obj.imageBlobs.push(imageBlob);
    obj.fileIds.push(id);
  }
  obj.fileIds.forEach(id => DriveApp.getFileById(id).setTrashed(true));
  return obj.imageBlobs;
}

// Please run this function.
async function myFunction() {
  const SOURCE_TEMPLATE = "1HvqYidpUpihzo_HDAQ3zE5ScMVsHG9NNlwPkN80GHK0";
  const TARGET_FOLDER = "1Eue-3tJpE8sBML0qo6Z25G0D_uuXZjHZ";

  // Use a method for converting all pages in a PDF file to PNG images.
  const blob = DriveApp.getFileById(SOURCE_TEMPLATE).getBlob();
  const imageBlobs = await convertPDFToPNG_(blob);

  // As a sample, create PNG images as PNG files.
  const folder = DriveApp.getFolderById(TARGET_FOLDER);
  imageBlobs.forEach(b => folder.createFile(b));
}

  • Related