Search code examples
javascripthtmlms-wordblobdocx

Saving text in a Word Document using JavaScript


For a project I need to save some text into a word document. I do this using this function:

function saveText(text) {
            var data = new Blob([text], {type: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'});
            var textFile = window.URL.createObjectURL(data);
            if (document.getElementById('download') !== null) {
                document.body.removeChild(document.getElementById('download'));
            }
            var a = document.createElement("a");
            a.setAttribute("id", "download");
            a.setAttribute("href", textFile);
            a.setAttribute("download", "");
            a.textContent = "Click here to download the test for the students";
            document.body.appendChild(a);
        }

However, there is one problem. Whenever I try to open it it shows this error message:

The file is corrupt and cannot be opened.

(Sorry I couldn't embed the image; I don't have enough reputation yet)
So, I have a feeling that the problem is that I need to format my text differently because right now I am just calling the function like this: saveText("Test");. In an rtf file it does have lots of stuff at the start so I thought maybe word needs this as well. However, I have looked a lot 'round the internet and couldn't find a solution. Thanks for taking the time to read (and maybe answer) this :D


Solution

  • function saveText(text) {
            var data = new Blob([text], {type: 'application/msword'});
            var textFile = window.URL.createObjectURL(data);
            if (document.getElementById('download') !== null) {
                document.body.removeChild(document.getElementById('download'));
            }
            var a = document.createElement("a");
            a.setAttribute("id", "download");
            a.setAttribute("href", textFile);
            a.setAttribute("download", "");
            a.textContent = "Click here to download the test for the students";
            document.body.appendChild(a);
        }
    

    I simply changed application/vnd.openxmlformatsofficedocument.wordprocessingml.document to application/ms-word and everything worked :)