0

How can I get the active document file data in doc/docx format? I can get the content in the PDF format without any issue. I have tried below apps script code, but it didn't return the base64 string in doc/docx format.

var doc = DocumentApp.getActiveDocument();

function doPostRequest(){
  
  var newblob = doc.getBlob();  
  newblob.setContentType("application/msword");
  newblob.setName("sample.doc");
  
  var dataObj = {
    date : new Date(),
    subject : "sample file data",
    comment : "this is a test comment",
    attachment : newblob
  }; 

  var options = {
    method : 'POST',
    payload: dataObj
  };
  
  var response = UrlFetchApp.fetch('https://postman-echo.com/post', options);
  console.log(response.getContentText());
  return response.getContentText();
}

Output

enter image description here

Although it says "sample.doc", when I copy-pasted and generated a file from the base64 string (using C#) it opened as a PDF file.

enter image description here

How to convert the file data into doc/docx format and save the file data as a doc/docx file?

stackflow
  • 2,112
  • 6
  • 32
  • 45
  • Isn't it called "sample.doc" because you call `newblob.setName("sample.doc");` ? I imagine `newblob.setName("sample.flyingspaghettimonster");` would return a file with the name "sample.flyingspaghettimonster". – ProgrammingLlama Sep 02 '20 at 06:18
  • I'm not familiar with the API, but [.setContentType](https://developers.google.com/apps-script/reference/base/blob.html#setContentType(String)) states: _"Sets the content type of the bytes in this blob."_, but doesn't mention anything about conversion. – ProgrammingLlama Sep 02 '20 at 06:20
  • 2
    When the blob is directly retrieved from Google Document using `getBlob()`, the mimeType is automatically changed to `application/pdf`. It seems that this is the current specification. So in this case, it is required to export the Google Document as the DOCX format. About this, these threads might be useful. https://stackoverflow.com/q/15636543 https://stackoverflow.com/q/46822740 – Tanaike Sep 02 '20 at 06:20
  • 2
    There's [`.getAs`](https://developers.google.com/apps-script/reference/base/blob.html#getAs(String)) which states: _"Return the data inside this object as a blob converted to the specified content type."_ but also says _"For most blobs, 'application/pdf' is the only valid option."_ so I'm not sure if that would work in your case. – ProgrammingLlama Sep 02 '20 at 06:21
  • I have tried - getAs("docx mime type") and Utilities.neBlob(blob.getBytes(), "docx mime type"); functions as well. After generating all of the files came to be just PDF. So currently is it not possible to convert to docx? – stackflow Sep 04 '20 at 02:56
  • Did you take a look at the questions linked above? It is possible. If those don't satisfy you, ask a new question explaining how you implemented those solutions and why they didn't satisfy you. – TheMaster Sep 04 '20 at 02:58

0 Answers0