Generate a Word document in JavaScript with Docx.js?

Peter picture Peter · Apr 9, 2013 · Viewed 73.4k times · Source

I am trying to use docx.js to generate a Word document but I can't seem to get it to work.

I copied the raw code into the Google Chrome console after amending line 247 to fix a "'textAlign' undefined error"

if (inNode.style && inNode.style.textAlign){..}

Which makes the function convertContent available. The result of which is an Object e.g.

JSON.stringify( convertContent($('<p>Word!</p>)[0]) )

Results in -

"{"string":
      "<w:body>
            <w:p>
                <w:r>
                    <w:t xml:space=\"preserve\">Word!</w:t>
                </w:r>
            </w:p>
       </w:body>"
 ,"charSpaceCount":5
 ,"charCount":5,
 "pCount":1}"

I copied

<w:body>
    <w:p>
        <w:r>
            <w:t xml:space="preserve">Word!</w:t>
        </w:r>
    </w:p>
</w:body>

into Notepad++ and saved it as a file with an extension of 'docx' but when I open it in MS Word but it says 'cannot be opened because there is a problem with the contents'.

Am I missing some attribute or XML tags or something?

Answer

edi9999 picture edi9999 · Jul 24, 2013

You can generate a Docx Document from a template using docxtemplater (library I have created).

It can replace tags by their values (like a template engine), and also replace images in a paid version.

Here is a demo of the templating engine: https://docxtemplater.com/demo/