How to export/convert Google Doc in PDF with Google Apps Script?

2.8k Views Asked by At

I'm trying to do 2 actions from Google Drive with Google Apps Scripts :

  1. Creating a file from a Google Doc template and insert data inside this file
  2. Doing an export of this Google Doc file to PDF file inside Google Drive (at the same)

Step 1 is working : the Google Docs file is correclty created with values updated inside it.

Step 2 : I have 2 questions/problems :

  1. The code I have found to generate PDF has been made to convert all Google Docs files to PDF files but from my side, I need just to export/convert the file which has been created (not all the files already located in the folder).
  2. Despite of point 1, the script is working and PDF is generated but when I open the PDF file, the values added inside it have been lost, I have only the tags present in the template.

Have you got some ideas?

Here is the code :

function replaceTags () {
 // Global vars
  var ui = DocumentApp.getUi ();
  var date = Utilities.formatDate(new Date(), "GMT", "dd-MM-yyyy");
  var folderOutId = 'xxxxxxxxxxxxxxxxxxxx';
  var tplMaintenanceId = 'xxxxxxxxxxxxxxxxxxxx';
  var fileOutName = 'my file name';
  var clientCompany = ui.prompt ('Company Name :');
  
  // Do a copy from template file to a new file inside a specific folder
  targetFolder = DriveApp.getFolderById (folderOutId);
  var documentId = DriveApp.getFileById (tplMaintenanceId). makeCopy (targetFolder). getId ();
      
  // Rename filed copied
  DriveApp.getFileById (documentId) .setName (fileOutName + ' - ' + clientCompany.getResponseText ());
      
  // Add document body inside variable
  var body = DocumentApp.openById (documentId) .getBody ();
    
  // Insert data inside Google Doc document
  body.replaceText ('##DATE##', date);
  body.replaceText ('##CLIENT_COMPANY##', clientCompany.getResponseText ());
  
  gdocToPDF(documentId);
}

function gdocToPDF(fileID) {
  var documentRootfolder = DriveApp.getFolderById("xxxxxxxxxxxxxxxxxxxx") // replace this with the ID of the folder that contains the documents you want to convert
  var pdfFolder = DriveApp.getFolderById("xxxxxxxxxxxxxxxxxxxx"); // replace this with the ID of the folder that the PDFs should be put in. 
  
  var docFile = DriveApp.getFileById(fileID)
  
  createPDF(docFile.getId(), pdfFolder.getId(), function (fileID, folderID) {
    if (fileID) createPDFfile(fileID, folderID);
  }
 )
}

function createPDF(fileID, folderID, callback) {
    var templateFile = DriveApp.getFileById(fileID);
    var templateName = templateFile.getName();
    
    var existingPDFs = DriveApp.getFolderById(folderID).getFiles();

    //in case no files exist
    if (!existingPDFs.hasNext()) {
        return callback(fileID, folderID);
    }

    for (; existingPDFs.hasNext();) {

        var existingPDFfile = existingPDFs.next();
        var existingPDFfileName = existingPDFfile.getName();
        if (existingPDFfileName == templateName + ".pdf") {
            Logger.log("PDF exists already. No PDF created")
            return callback();
        }
        if (!existingPDFs.hasNext()) {
            Logger.log("PDF is created")
            return callback(fileID, folderID)
        }
    }
}

function createPDFfile(fileID, folderID) {
    var templateFile = DriveApp.getFileById(fileID);
    var folder = DriveApp.getFolderById(folderID);
    var theBlob = templateFile.getBlob().getAs('application/pdf');
    var newPDFFile = folder.createFile(theBlob);

    var fileName = templateFile.getName().replace(".", ""); //otherwise filename will be shortened after full stop    
    newPDFFile.setName(fileName + ".pdf");
}
1

There are 1 best solutions below

18
On BEST ANSWER

I tried recreating your code and I converted a doc to pdf successfully.

What you can do to is to edit your gdocToPDF() function to accept only the document that you want to be converted to PDF. Please see below sample code(might not be exactly the way you want it):

Pass the document id used in replaceTags() function to gdocToPDF()

function replaceTags () {
 ....
 .... 
  DocumentApp.openById(documentId).saveAndClose()
  gdocToPDF(documentId);
}

Instead of fetching all the files in a drive folder, use this code instead to use the file with replaced tags only

function gdocToPDF(fileID) { 
  var documentRootfolder = DriveApp.getFolderById(folder-id) // replace this with the ID of the folder that contains the documents you want to convert
  var pdfFolder = DriveApp.getFolderById(folder-id); // replace this with the ID of the folder that the PDFs should be put in. 
  
  var docFile = DriveApp.getFileById(fileID)
  
  createPDF(docFile.getId(), pdfFolder.getId(), function (fileID, folderID) {
    if (fileID) createPDFfile(fileID, folderID);
  }
 )
}

This will make a doc to pdf conversion to the only document that you wanted to be converted.

Have a great day ahead!