Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate a Word document in JavaScript with Docx.js?

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?

like image 953
Peter Avatar asked Apr 09 '13 10:04

Peter


People also ask

Can docx contain macro?

docx file can hold macros. Any file can use macros that are stored in the normal.


1 Answers

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/

like image 125
edi9999 Avatar answered Nov 07 '22 19:11

edi9999