Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Google Doc to Docx using Google Script

Is it possible to convert a Google document to a Word docx file programmatically using Google Script ?

like image 234
Albertus Avatar asked Mar 26 '13 11:03

Albertus


2 Answers

This should work

function myFunction() {

  var token = ScriptApp.getOAuthToken();

  //Make sure to replace the correct file Id
  // Fetch the docx blob
  var blb = UrlFetchApp.fetch('https://docs.google.com/feeds/download/documents/export/Export?id=<ID_of_Google_Document>&exportFormat=docx', 
                              {
                                headers : {
                                  Authorization : 'Bearer '+token
                                }
                              }).getBlob();

  //Create file in Google Drive
  var file = DriveApp.createFile(blb).setName('<name_of_exported_file>.docx');

  //Put the file in a drive folder
  DriveApp.getFolderById('<FOLDER_ID>').addFile(file);

}
like image 61
Waqar Ahmad Avatar answered Oct 08 '22 11:10

Waqar Ahmad


Quoting from this item on the issue tracker...

You can convert a Google Document to docx today using the Drive Advanced Service:

https://developers.google.com/apps-script/advanced/drive

Here is a small example:

function convertToDocx(documentId) {
  var file = Drive.Files.get(documentId);
  var url = file.exportLinks['application/vnd.openxmlformats-officedocument.wordprocessingml.document'];
  var oauthToken = ScriptApp.getOAuthToken();
  var response = UrlFetchApp.fetch(url, {
    headers: {
      'Authorization': 'Bearer ' + oauthToken
    }
  });
  return response.getBlob();
}
like image 41
Daniel Avatar answered Oct 08 '22 12:10

Daniel