Aris Kon.
Aris Kon.

Reputation: 61

Converting a GDoc to docx through GAS produces corrupted document

I use the snippet below to convert a Google Doc to PDF and docx format and save it to GDrive. PDF is fine, but docx has problems in Office Word 2013, and doesn't open at all showing this message. LibreOffice 6 can open the file, but only in LibreDraw as read-only, not LibreWriter, and text is in text boxes & borders are plain images, not objects.

If I convert it manually in menu from
File > Download As.. > Microsoft Word(.docx),
the document works fine. I have hundreds of files, and doing it manually is not a solution.

function saveToDrive(_name){
  //Get document blob for converting
  var blob = DocumentApp.openById('string_id').getBlob();
  //Save as PDF
  var pdf = {
    title: _name + '.pdf',
    mimeType: MimeType.PDF,
    parents:[{id:'google_drive_folder'}]
  };
  Drive.Files.insert(pdf, blob);
  //Save as docx
  var docx = {
    title: _name + '.docx',
    mimeType: MimeType.MICROSOFT_WORD,
    parents:[{id:'google_drive_folder'}]
  };
  Drive.Files.insert(docx, blob);  
}

I did use string mime type as well, with same result. What am I missing?

Upvotes: 1

Views: 341

Answers (1)

TheMaster
TheMaster

Reputation: 50761

Issue:

  • getBlob() by default converts it into PDF. So, When inserting it into Drive as docx, you're trying to convert from pdf to docx.

Possible Solutions:

  • Use direct conversion from gdoc using Drive API Files:export
  • Directly fetch the export link using UrlFetchApp

Sample Script:

function docToDocx(id) {
  var format = 'docx',
    exportLink =
      'https://docs.google.com/document/d/' + id + '/export?format=' + format,
    blob = UrlFetchApp.fetch(exportLink, {
      headers: {
        Authorization: 'Bearer ' + ScriptApp.getOAuthToken(),
      },
    });
  DriveApp.createFile(blob);
}

References:

Upvotes: 1

Related Questions