convert google docs to PDF using Apps Script

Viewed 1859

I need help with the next problem,

I have multiple Google Docs files and I need to convert them a PDF files using Google Apps Script.

I used this code to perform the conversion:

function convertFiles() {
  var fileId = "FILE_IDS";
  var folderId = "FOLDER_ID";

  var file = DriveApp.getFileById(fileId);

  var blobPDF = file.getAs("application/pdf");

  var resource = {
    title: "TEST PDF",
    parents: [{
      "id": folderId
    }],
  };

  Drive.Files.insert(resource, blobPDF);
}

However, if the Google document is extensive, the following error occurs

We're sorry, no servers are currently available. Please wait a bit and try again.

Another possible solution I found is to convert the Google document into a .docx file.

Here is the used code

function convertToDocx() {
  var fileId = "DOCUMENT_ID";
  var folderId = "FOLDER_ID";

  var file = Drive.Files.get(fileId);
  var url = 'https://docs.google.com/feeds/download/documents/export/Export?id=' + fileId + '&exportFormat=docx';
  var options = {
    headers: {
      Authorization: "Bearer " + ScriptApp.getOAuthToken()
    },
    muteHttpExceptions: true
  }
  var response = UrlFetchApp.fetch(url, options);
  var blob = response.getBlob();

  var resource = {
    title: "TEST PDF 1",
    parents: [{
      "id": folderId
    }],
  };

  Drive.Files.insert(resource, blob);
}

But the same problem happens with extensive documents

Timeout: https://docs.google.com/feeds/download/documents/export/Export?id=DOCUMENT_ID&exportFormat=docx

I appreciate any help and information that allows you to convert the Google document to a .pdf or .docx file

0 Answers
Related