This is the third day of my participation in the November Gwen Challenge. Check out the details: the last Gwen Challenge 2021

First, basic knowledge

To implement front-end pure JS export of Word documents, we need to use docxTemplater, jszip-utils, file-saver three components, next a brief introduction to the three components.

1, docxtemplater

introduce

Docxtemplater is a mail merge tool that is used programmatically to handle conditions, loops, and can be extended to tables, HTML, images, and more.

Reference links: docxtemplater. Readthedocs. IO/en/latest/I…

Use the API
  • New window.docxtemplater: Creates a docxTemplater instance object and returns a new DocxTemplater object
  • Note: You must pass a zip instance to this method from the 2.x version of jszip
  • SetData (Tags): Sets the value of a template variable
  • Render () : This function replaces all template variables with their values
  • GetZip () : This function returns the ZIP representing the Docxtemplater object

2, jszip – utils

introduce

Jszip-utils is a cross-browser utility library used with jszip.

Use the API
  • GetBinaryContent () : Reads and gets the binary content of the template file

3, jszip

introduce

Jszip is a JavaScript library for creating, reading, and editing.zip files, and the API is simple to use. Reference: stuk.github. IO /jszip/

Use the API
  • New JSZip() : Creates an instance of JSZip
  • Generate () : This function generates a ZIP file (not a real file, but an in-memory representation)

4, FileSaver

introduce

FileSaver. Js is a solution for saving files on the client side, which is ideal for applications that need to generate files or store sensitive information that should not be sent to an external server. Refer to the link: www.cnblogs.com/yunser/p/76… www.npmjs.com/package/fil…

Use the API
  • SaveAs (blob, “1.docx”) : Saves the target file object as a file of the target type and names it

Two, operation steps

1, install,

The next step is to install the above component tools using the following installation command

/ / docxtemplater installation
cnpm install docxtemplater pizzip  --save

/ / install jszip - utils
cnpm install jszip-utils --save 

/ / install jszip
cnpm install jszip --save

/ / FileSaver installation
cnpm install file-saver --save

// No CNPM can use NPM
Copy the code

2, the introduction of

Introduce the above tools into the components you need

import docxtemplater from 'docxtemplater';
import PizZip from 'pizzip';
import JSZipUtils from 'jszip-utils';
import {saveAs} from 'file-saver';
Copy the code

Create a template file

We need to create a template file and define the format and content beforehand. Docxtemplater before introduced to by tags to fill in the form of data, rules can reference docxtemplater. Readthedocs. IO/en/latest/I…

Iii. Display of all codes of components

<template>
    <div class="word-box" @click="exportWordDocx">The export of word</div>
</template>

<script>
import Docxtemplater from 'docxtemplater';
import JSZip from 'jszip';
import JSZipUtils from 'jszip-utils';
import { saveAs } from 'file-saver';

export default {
    name: 'Docx'.props: {
        / / file name
        fileName: {
            type: String.default: ' '
        },
        // word template name
        fileTemplete: {
            type: String.default: ' '
        },
        / / word data
        wordData: {
            type: Object.default: () = >{}}},methods: {
        // Click export Word
        exportWordDocx() {
            // Read and get the binary contents of the template file
            JSZipUtils.getBinaryContent('./static/file/' + this.fileTemplete + '.docx'.(error, content) = > {
                // Throw an exception
                if (error) {
                    throw error;
                }
                // Create an instance of JSZip with the contents of the template
                let zip = new JSZip(content);
                // Create and load the docxTemplater instance object
                let doc = new Docxtemplater();
                doc.loadZip(zip);
                // Set the value of the template variabledoc.setData({ ... this.wordData });try {
                    // Replace all template variables with their values
                    doc.render();
                } catch (error) {
                    // Throw an exception
                    let e = {
                        message: error.message,
                        name: error.name,
                        stack: error.stack,
                        properties: error.properties
                    };
                    console.log(JSON.stringify({ error: e }));
                    throw error;
                }
                // Generate a zip file representing the docxTemplater object (not a real file, but an in-memory representation)
                let out = doc.getZip().generate({
                    type: 'blob'.mimeType: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
                });
                // Save the target file object as a file of the target type and name it
                saveAs(out, this.fileName + '.docx'); }); }}}</script>
Copy the code

The above is according to the word template export word document code, record, review the new!