Docx-file created client-side in a web browser can not be opened after downloading (as Blob)

Viewed 18

I am trying to write a web application, which takes an input from the user in the browser, generates a docx-file and makes it available to the user to download. To generate the docx-file I use the js-library docx. I create a Blob with the document as input and provide an Object-Url for the download link. When clicking the link the docx is downloaded as expected. Nevertheless, Word can't open the file (without specific error message). When creating the file in node and downloading it via fs, the file can be opened by word. I reproduced the error with the reduced code down below.

JS:

const docx = require ("docx");
var content = "";

function updateContent(){//get user-input
    content = document.getElementById("inp").value;
}

function generateDocx(){
    updateContent();
    const doc = new docx.Document({
        sections: [
            {   
                properties: {},
                children: [
                    new docx.Paragraph({
                        children: [
                            new docx.TextRun({
                                text: `Input: ${content}`,
                            }),
                        ],
                    }),
                ],
            },
        ],
    });
    const blob = new Blob([doc], { type:"application/vnd.openxmlformats-officedocument.wordprocessingml.document" })
    const link = document.getElementById("downloadLink");
    link.href = URL.createObjectURL(blob);
}

document.getElementById('generateButton').addEventListener('click', generateDocx, true);

Note, that I had to browserify for require() to work in the browser, but i only showed the pre-bundling code above...

HTML:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>ErrorDemo</title>
    <script src="bundle.js" defer></script>
</head>
<body>
    <input type="text" id="inp" placeholder="Enter Input here!">
    <button id="generateButton">Generate Document</button>
    <a id="downloadLink">Download Document!</a>
</body>
</html>

I have tried to create the Blob via the class docx.Packer (.toBlob), which did not resolve the error. I suspect that the document created by new docx.Document() is not the right input for Blob, because it isn't an array or something related to that? If anyone has encountered/solved this before or has expertise in this area, i'd be forever grateful for a hint in the right direction :P.

0 Answers
Related