0

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

1
  • This question has been solved. I see no reason to mark this question down. Please explain why so I can improve the question, or the answer Commented Oct 28, 2018 at 11:03

1 Answer 1

2
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 :)

Sign up to request clarification or add additional context in comments.

1 Comment

I will check this correct tomorrow when it is possible to

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.