2
votes

I'm trying to convert an existing .DOCX file on my Google Drive. It works up until the new (PDF) file should be created, then I get this error message: "Conversion from application/vnd.openxmlformats-officedocument.wordprocessingml.document to application/pdf failed".

The relevant DOCX file should not be corrupted as it can be opened by Google Document and manually convertred to PDF from there.

I have enabled Drive API (both in Drive and in API Console)

Anyone else seen this problem?

Code:

 function convertPDF(fileid) {
     var docId = fileid;
     var f=DriveApp.getFileById(docId);
     var n=f.getName();
     var docFolder = f.getParents().next().getId();

     var docblob = f.getAs('application/pdf');
     n=n.replace(".docx",".pdf");
     docblob.setName(n);
     var bn=docblob.getName();
     var t=docblob.getContentType();
     Logger.log(bn+"-->"+t);  // <-- works 

     var file = DriveApp.createFile(docblob); // <<- error msg here

     var fileId = file.getId();
     moveFileId(fileId, docFolder);
     return (fileId);
}
1

1 Answers

3
votes

At Google, it cannot be directly converted from docx to pdf. But, after it converted docx to Google document, it can convert to pdf. In order to convert docx to Google document, you can use Drive API using Advanced Google services. For this, please enabling Drive API of Advanced Google services as follows.

  1. In the script editor, select Resources > Advanced Google services
  2. In the dialog that appears, click the on/off switch for Drive API v2.
  3. Click OK button.

The detail information of Advanced Google services is here.

I think that enabling Drive API at API console has already been done, because you have already used DriveApp on your script. Google automatically enables Drive API on API console when DriveApp is used in the script.

The modified script using Drive API is as follows.

Modified script :

function convertPDF(docx_id) {
  var docx = DriveApp.getFileById(docx_id);
  var docFolder = docx.getParents().next().getId();
  var n = docx.getName();
  var res = Drive.Files.insert({ // Here, Drive API of Advanced Google services is used.
    "mimeType": "application/vnd.google-apps.document",
    "title": n
  }, docx.getBlob());
  var f = DriveApp.getFileById(res.id).getBlob();

  var docblob = f.getAs('application/pdf');
  n=n.replace(".docx",".pdf");
  docblob.setName(n);
  var bn=docblob.getName();
  var t=docblob.getContentType();
  Logger.log(bn+"-->"+t);
  var file = DriveApp.createFile(docblob);
  var fileId = file.getId();
  Logger.log(fileId)
  moveFileId(fileId, docFolder);
  return (fileId);
}

I don't know about moveFileId(). So if an error occurs at this line, please check the function.

Note :

In this case, Google document is created as a temporally file for converting to PDF. The filename is the same to the docx file. So if it is not required for you, please delete it.