App script conversion of DOC to PDF ruins formatting

I believe your goal and your current situation as follows.

  • You want to convert Google Document files to the PDF files.
  • In your script, you can retrieve the Google Document files from the folder.

Modification points:

  • In the function of convert(file, rootFolder), when file of convert(file, rootFolder) is Google Document, blob of var blob = file.getBlob(); has already been the converted PDF format. But your script converts the PDF format to Google Document again and retrieve only the text data, and then, the text data is created as a PDF file. By this, the PDF file with only text data is created. I think that this is the reason of your issue.

In order to remove this issue and convert the Google Document to the PDF file, I would like to modify as follows.

Modified script:

In this modification, I modified convert.

function convert(file, rootFolder) {
  if (file.getMimeType() != MimeType.GOOGLE_DOCS) return;
  var blob = file.getBlob();
  var filename = file.getName();
  var name = filename.split('.')[0];  
  rootFolder.createFile(blob.setName(name + '.pdf'));
}

Note:

  • In this case, the Google Document is converted to the PDF format with file.getBlob(). But when you want to use the Drive API for this, you can also use the following script. Ref

    • From

        var blob = file.getBlob();
      
    • To

        var url = `https://www.googleapis.com/drive/v3/files/${file.getId()}/export?mimeType=${MimeType.PDF}`;
        var blob = UrlFetchApp.fetch(url, {headers: {authorization: `Bearer ${ScriptApp.getOAuthToken()}`}}).getBlob();
      

Reference:

  • getBlob()