How to Integrate Google Apps Script and PDF.co?

About Google Apps Script

Google Apps Script is a scripting platform designed for rapid application development for the fast and easy creation of business applications that integrate with G Suite products. Modern JavaScript is the scripting language being used to write codes. Apps Script includes built-in libraries for G Suite applications such as Drive, Calendar, Gmail, and more.

Read more about Google Apps Script at https://developers.google.com/apps-script

What is PDF.co?

PDF.co is the secure and scalable data extraction API service with a full set of PDF tools included.

Benefits:

  • Reduces spending by using a flexible AI system for data extraction from receipts, invoices, and other documents;
  • Documents and files such as tables, and PDF forms can be read automatically using the Document Parser which is customizable;
  • It possesses functionality that lets the user fill documents with PDF documents, fields to PDF forms, text, and images;
  • It is a potent, unique tool that allows you to combine, split, and delete PDF pages. It also lets you create PDFs from advanced HTML;
  • It is perfect for Enterprise clients as they can utilize review logs and API logs;
  • Offline or on-premise versions can be accessed by Premium users;

Security

  • All documents and files processed by PDF.co are encrypted at rest using AES 256-bit encryption;
  • PDF.co relies on TLS and SSL to transmit data and files (the same security protocols that are used by banks)
  • Runs on award-winning secure certified Amazon AWS infrastructure: https://pdf.co/security

Popular API Calls

Add Text And Images

Barcode Reader

Document Parser

Merge PDFs

Split PDFs

PDF Password and Security

PDF to Text

Integrating PDF.co with Google Apps Script

The following code snippet demonstrates Google Apps Script invoking PDF.co API.

Sample Code Snippet

 
  // Prepare Payload
  var data = {
    "async": false,
    "encrypt": false,
    "inline": true,
    "name": "result",
    "url": pdfUrl
  };

  // Prepare Request Options
  var options = {
    'method' : 'post',
    'contentType': 'application/json',
    'headers': {
      "x-api-key": pdfCoAPIKey
    },
    // Convert the JavaScript object to a JSON string.
    'payload' : JSON.stringify(data)
  };
  
  // Get Response
  // https://developers.google.com/apps-script/reference/url-fetch
  var pdfCoResponse = UrlFetchApp.fetch('https://api.pdf.co/v1/pdf/merge', options);

  var pdfCoRespContent = pdfCoResponse.getContentText();
  var pdfCoRespJson = JSON.parse(pdfCoRespContent);

We can break PDF.co API integration into three steps.

  • Prepare Payload
  • Prepare Request Options.
  • Invoke Request and consume the response

It’s worth observing the second step where we’re preparing options for request. Here, Request options contain API Key in the header as well payload attribute containing JSON string.

The full Source Code is as below.

 
/**
 * IMPORTANT: Add Service reference for "Drive". Go to Services > Locate "Drive (drive API)" > Add Reference of it 
 */

// Add Your PDF.co API Key here
const pdfCoAPIKey = 'PDFco_API_Key_Here';

// Get the active spreadsheet and the active sheet
ss = SpreadsheetApp.getActiveSpreadsheet();
ssid = ss.getId();

// Look in the same folder the sheet exists in. For example, if this template is in
// My Drive, it will return all of the files in My Drive.
var ssparents = DriveApp.getFileById(ssid).getParents();

// Store File-Ids/PermissionIds used for merging
let filePermissions = [];

/**
 * Note: Here, we're getting current folder where spreadsheet is residing.
 * But we can certainly pick any folder of our like by using Folder related functions.
 * For example:
  var allFolders = DriveApp.getFoldersByName("Folder_Containing_PDF_Files");
  while (allFolders.hasNext()) {
    var folder = allFolders.next();
    Logger.log(folder.getName());
  }
 */
// Loop through all the files and add the values to the spreadsheet.
var folder = ssparents.next();

/**
 * Add PDF.co Menus in Google Spreadsheet
 */
function onOpen() {
  var menuItems = [
    {name: 'Merge All Files From Current Folder', functionName: 'mergePDFDocumentsFromCurrentFolder'} 
  ];
  ss.addMenu('PDF.co', menuItems);
}

function mergePDFDocumentsFromCurrentFolder(){
  var allFilesLink = getPDFFilesFromCurFolder(pdfCoAPIKey);
  mergePDFDocuments(allFilesLink, pdfCoAPIKey);
}

/**
 * Get all PDF files from current folder
 */
function getPDFFilesFromCurFolder(pdfCoAPIKey) {
  var files = folder.getFiles();
  var allFileUrls = [];

  while (files.hasNext()) {
    var file = files.next();

    var fileName = file.getName();
    if(fileName.endsWith(".pdf")){
      // Create Pre-Signed URL from PDF.co
      var respPresignedUrl = getPDFcoPreSignedURL(fileName, pdfCoAPIKey)

      if(!respPresignedUrl.error){
        var fileData = file.getBlob();
        if(uploadFileToPresignedURL(respPresignedUrl.presignedUrl, fileData, pdfCoAPIKey)){
          // Add Url
          allFileUrls.push(respPresignedUrl.url);
        }
      }
    }
  }

  return allFileUrls.join(",");
}

/**
 * Merges PDF URLs using PDF.co and Save to drive
 */
function mergePDFDocuments(pdfUrl, pdfCoAPIKey) {

  // Get Cells for Input/Output
  let resultUrlCell =  ss.getRange("A4");
  
  // Prepare Payload
  var data = {
    "async": false,
    "encrypt": false,
    "inline": true,
    "name": "result",
    "url": pdfUrl
  };

  // Prepare Request Options
  var options = {
    'method' : 'post',
    'contentType': 'application/json',
    'headers': {
      "x-api-key": pdfCoAPIKey
    },
    // Convert the JavaScript object to a JSON string.
    'payload' : JSON.stringify(data)
  };
  
  // Get Response
  // https://developers.google.com/apps-script/reference/url-fetch
  var pdfCoResponse = UrlFetchApp.fetch('https://api.pdf.co/v1/pdf/merge', options);

  var pdfCoRespContent = pdfCoResponse.getContentText();
  var pdfCoRespJson = JSON.parse(pdfCoRespContent);

  // Display Result
  if(!pdfCoRespJson.error){
    // Upload file to Google Drive
    uploadFile(pdfCoRespJson.url);

    // Update Cell with result URL
    resultUrlCell.setValue(pdfCoRespJson.url);    
  }
  else{
    resultUrlCell.setValue(pdfCoRespJson.message);    
  }
}

/**
 * Gets PDF.co Presigned URL
 */
function getPDFcoPreSignedURL(fileName, pdfCoAPIKey){
  // Prepare Request Options
  var options = {
    'method' : 'GET',
    'contentType': 'application/json',
    'headers': {
      "x-api-key": pdfCoAPIKey
    }
  };

  var apiUrl = `https://api.pdf.co/v1/file/upload/get-presigned-url?name=${fileName}`;
  
  // Get Response
  // https://developers.google.com/apps-script/reference/url-fetch
  var pdfCoResponse = UrlFetchApp.fetch(apiUrl, options);

  var pdfCoRespContent = pdfCoResponse.getContentText();
  var pdfCoRespJson = JSON.parse(pdfCoRespContent);

  return pdfCoRespJson;
}

/**
 * Uploads File to PDF.co PreSigned URL
 */
function uploadFileToPresignedURL(presignedUrl, fileContent, pdfCoAPIKey){
  // Prepare Request Options
  var options = {
    'method' : 'PUT',
    'contentType': 'application/octet-stream',
    'headers': {
      "x-api-key": pdfCoAPIKey
    },
    // Convert the JavaScript object to a JSON string.
    'payload' : fileContent
  };
  
  // Get Response
  // https://developers.google.com/apps-script/reference/url-fetch
  var pdfCoResponse = UrlFetchApp.fetch(presignedUrl, options);

  if(pdfCoResponse.getResponseCode() === 200){
    return true;
  }
  else{
    return false;
  }
}

/**
 * Save file URL to specific location
 */
function uploadFile(fileUrl) {
  var fileContent = UrlFetchApp.fetch(fileUrl).getBlob();
  folder.createFile(fileContent);
}

If we quickly analyze the above source code, we’re doing the following.

  • Adding necessary references such as “Drive”, as well declaring constant for PDF.co API Key. We’re also getting references for the input Google Drive folder which contains input files.
  • In the Next Step, we’re iterating through all PDF files from a folder and uploading them to the PDF.co cloud. After the file is uploaded to PDF.co, we’re preparing an array of PDF.co cloud URLs.
  • Then we’re performing a merge using PDF.co URLs and saving result files to the output folder.

Please review the tutorial links for more in-depth articles.

Tutorials:

 

Video Guides:

In this video guide, you will learn how to merge PDF using Google Apps Script and PDF.co.