current position:Home>Docxtemplator + Vue + docxtemplator image module free realize the front-end Word Download Text and free image download

Docxtemplator + Vue + docxtemplator image module free realize the front-end Word Download Text and free image download

2022-04-29 04:28:18@huihui_ new

1. brief introduction

docxtemplate It is a slave. docx/pptx The template to generate docx/pptx Library of documents . It can replace... With data { Place holder }, It also supports loops and conditions . Templates can be edited by non programmers , For example, your client .
docxtemplate There are many functions supported , Syntax includes variable substitution 、 conditional 、 loop 、 List loop 、 Form cycle, etc , It also includes pictures 、html Wait for module conversion , For details, see :https://docxtemplater.com/demo/

To put it bluntly , The best part is word The template defines itself , The format can be word Generate , It's still great , Post an example :
word Definitions in the template :
 Insert picture description here
The effect after downloading :
 The effect after downloading , You can see that the defined variable is replaced with data
It can be noted that : Where placeholders are used {} The variables defined by the inclusion are replaced .

2. grammar

2.1. Replace

js Variable definition :

{
    title:' brief introduction '}

word Syntax in template file :

{
    title}

2.2. loop

js Variable definition :

{
    
	loop:[
   		{
     name: "Windows", price: 100},
   		{
     name: "Mac OSX", price: 200 },
   		{
     name: "Ubuntu", price: 0 }
  	],
	userGreeting: (scope) => {
    
         return "The product is" + scope.name + ", price:" + scope.price;
 	},
}

word Syntax in template file :

	 loop {
    #loop} 
		{
    name}, {
    price}
		//  Anonymous function slot usage 
		{
    userGreeting}
	{
    /loop}

2.3. Judge

js Variable definition :

	{
    
		hasKitty: true,
	 	kitty: "Minie",
		hasDog: false,
		dog: "wangwang",
	}

word Syntax in template file :

	{
    #hasKitty}
		Cat’s name: {
    kitty}
	{
    /hasKitty} 
	{
    #hasDog}
		Dog’s name: {
    dog}
	{
    /hasDog}

2.4. picture

js Variable definition :

{
    
	// File path 
	image: '/logo.png',
}

word Syntax in template file :

{
    %image}

2.5. Advanced usage

Need to install plug-ins :‘angular-expressions’ 、 ‘lodash’ ,
When the configuration is complete , Can be found in word Use judgment, advanced syntax, etc. in the template :

	{
    #users.length>1} There are multiple users {
    /}
	{
    #users[0] == 1} The first value is 1 {
    /}

Deep value Syntax :

	{
    user.age}--{
    user.num.say}

3. stay vue Use in

3.1 Common usage ( Text templates )

import Docxtemplater from 'docxtemplater'
import PizZip from 'pizzip'
import PizZipUtils from 'pizzip/utils/index.js'
import {
     saveAs } from 'file-saver'
function loadFile(url, callback) {
    
  PizZipUtils.getBinaryContent(url, callback)
}

methods: {
    
	renderImg() {
    
      loadFile('/word.docx',
      function(error, content) {
    
        if (error) {
    
          throw error
        }
        const zip = new PizZip(content)
		// options  It's an object   You can configure it yourself 
		const options = {
    
			paragraphLoop: true,
            linebreaks: true,
		}
       	const doc = new Docxtemplater(zip, options)
       	doc.render({
    
         	products: [
                {
     name: "Windows", price: 100 },
                {
     name: "Mac OSX", price: 200 },
                {
     name: "Ubuntu", price: 0 }
            ],
            userGreeting: (scope) => {
    
                return "The product is" + scope.name;
            },
          })
			const out = doc.getZip().generate({
    
            type: 'blob',
            mimeType: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
          })
          // Output the document using Data-URI
          saveAs(out, 'output1.docx')
	})
}

3.2 Add a free picture plugin

The picture download module provided by the official needs to be charged , Caring people have developed free plug-ins ’docxtemplater-image-module-free’, That must be used :

import ImageModule from 'docxtemplater-image-module-free'

methods: {
    
renderImg() {
    
	loadFile('/word.docx',
	  	function(error, content) {
    
		    if (error) {
    
		      throw error
		    }
		
		    const imageOpts = {
    
		      getImage: function(tagValue, tagName) {
    
		        return new Promise(function (resolve, reject) {
    
		          PizZipUtils.getBinaryContent(tagValue, function (error, content) {
    
		            if (error) {
    
		              return reject(error);
		            }
		            return resolve(content);
		          });
		        });
		      },
		      getSize : function (img, tagValue, tagName) {
    
		        // FOR FIXED SIZE IMAGE :
		        return [150, 150];
		      }
		    }
		
		    var imageModule = new ImageModule(imageOpts);
		
		    const zip = new PizZip(content)
		
		    const doc = new Docxtemplater().loadZip(zip).setOptions({
    
		      // delimiters: { start: "[[", end: "]]" },
		      paragraphLoop: true,
		      linebreaks: true,
		    }).attachModule(imageModule).compile()
		
		      doc.renderAsync({
    
		        image: '/logo.png',
		        title: ' brief introduction ',
		       	...
		      }).then(function () {
    
		        const out = doc.getZip().generate({
    
		            type: "blob",
		            mimeType: 'application/vnd.openxmlformatsofficedocument.wordprocessingml.document',
		        });
		        saveAs(out, "generated.docx");
		      });
	    })
	}
}

3.3 Add parsing Syntax

You can use more and more convenient word Template syntax , see 2.5 section

import expressions from 'angular-expressions'
import assign from 'lodash/assign'
expressions.filters.lower = function (input) {
    
    // This condition should be used to make sure that if your input is
    // undefined, your output will be undefined as well and will not
    // throw an error
    if (!input) return input;
    return input.toLowerCase();
}

function angularParser(tag) {
    
    tag = tag
        .replace(/^\.$/, "this")
        .replace(/('|')/g, "'")
        .replace(/("|")/g, '"');
    const expr = expressions.compile(tag);
    return {
    
        get: function (scope, context) {
    
            let obj = {
    };
            const scopeList = context.scopeList;
            const num = context.num;
            for (let i = 0, len = num + 1; i < len; i++) {
    
                obj = assign(obj, scopeList[i]);
            }
            return expr(scope, obj);
        },
    };
}

new Docxtemplater().loadZip(zip).setOptions({
    parse: angularParser})

stay vue The sample code used in has been put into github above , Address Links :wordDown, There are unclear little partners , Feel free to leave a comment .

copyright notice
author[@huihui_ new],Please bring the original link to reprint, thank you.
https://en.qdmana.com/2022/117/202204270551339090.html

Random recommended