dolanmiu / docx

Easily generate and modify .docx files with JS/TS with a nice declarative API. Works for Node and on the Browser.
https://docx.js.org/
MIT License
4.24k stars 479 forks source link

Use patchDocument on client side #2687

Closed joseph-ar closed 4 months ago

joseph-ar commented 4 months ago

I'm trying to fill a word template with data from JSON, and found this amazing library (Docx js), it's documentation says that works on server side and client side, until the most examples shows implementations in sever side... the function i'm trying to implement is "patchDocument", what takes an template file and fills it with some data but I'm getting the following message "Uncaught ReferenceError: patchDocument is not defined" like the library isn't included until is included... but when I try to generate a word document works fine.

It seems like the library wasn't included correctly

I've tried to include the library in the following ways:

1.- From CDN: <script src="https://cdn.jsdelivr.net/npm/docx@8.5/build/index.umd.min.js"></script>

2.-Installing it via npm and importing it via web-pack

require('./bootstrap');
import * as docx from "docx";
window.docx = docx;

With this two ways i tried to generate a word document and it works!! But when tried to call the patchDocument (https://docx.js.org/#/usage/patcher?id=usage) method shows that is undefined...

This is the code I'm trying to run:


        $.ajax({
            type: $(form).attr('method'),
            url: $(form).attr('action'),
            data: $(form).serialize(),
            dataType: "json",
            success: function (response, xhr) {
                console.log(response);
                patchDocument(atob(response.download), {
                    patches: {
                        my_patch: {
                            type: PatchType.PARAGRAPH,
                            children: [new TextRun("Sir. "), new TextRun("John Doe"), new TextRun("(The Conqueror)")],
                        },
                    },
                });
                processAlert.close();
            },
            error: function(xhr){
                console.log(xhr);
                processAlert.update({
                    title: 'Error!',
                    text: xhr.responseText,
                    icon: 'error'
                });
                processAlert.hideLoading();
            }
        });

Where response.download is the base64 string of the document, and my question is How is the correct way to include this library in a project to work on client side?

I understood that my question could be so basic, but I'm a little confused