Link Search Menu Expand Document

Merge PDF from Google Drive and Save back - GoogleAppScript

PDF Merge sample in GoogleAppScript demonstrating ‘Merge PDF from Google Drive and Save back’
 * Initial Declaration and References
// 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();

// Loop through all the files and add the values to the spreadsheet.
var folder =;

 * Add Menus in Google Spreadsheet
function onOpen() {
  var menuItems = [
    {name: 'Get All PDF From Current Folder', functionName: 'getPDFFilesFromCurFolder'},
    {name: 'Merge PDF URLs Listed In Cell', functionName: 'mergePDFDocuments'} 
  ss.addMenu('', menuItems);

 * Get all PDF files from current folder
function getPDFFilesFromCurFolder() {
  var files = folder.getFiles();
  var pdfUrlCell = ss.getRange("A4"); 

  var allFileUrls = [];

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

    var fileName = file.getName();
      // Make File Pulblic accessible with URL so that it can be accessible with external API
      var resource = {role: "reader", type: "anyone"};
      Drive.Permissions.insert(resource, file.getId());

      // Add Url


 * Function which merges documents using
function mergePDFDocuments() {

  // Get API Key Cell
  let pdfCoAPIKeyCell = ss.getRange("B1");

  // Get Cells for Input/Output
  let pdfUrlCell = ss.getRange("A4"); 
  let resultUrlCell =  ss.getRange("B4");

  let pdfCoAPIKey = pdfCoAPIKeyCell.getValue();
  let pdfUrl = pdfUrlCell.getValue();
  // 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
  var pdfCoResponse = UrlFetchApp.fetch('', options);

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

  // Display Result
    // Upload file to Google Drive

    // Update Cell with result URL

 * Save file URL to specific location
function uploadFile(fileUrl) {
  var fileContent = UrlFetchApp.fetch(fileUrl).getBlob();
} Web API: the Web API with a set of tools for documents manipulation, data conversion, data extraction, splitting and merging of documents. Includes image recognition, built-in OCR, barcode generation and barcode decoders to decode bar codes from scans, pictures and pdf.

Get your API key here!

Download Source Code (.zip)

return to the previous page explore PDF Merge endpoint