release 0.5€¦ · docx is a zipped format that contains some xml. if you want to build a simple...

37
docxtemplater Documentation Release 0.5.4 Edgar Hipp October 10, 2014

Upload: others

Post on 16-Jun-2020

0 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Release 0.5€¦ · Docx is a zipped format that contains some xml. If you want to build a simple replace {tag} If you want to build a simple replace {tag} by value system, it can

docxtemplater DocumentationRelease 054

Edgar Hipp

October 10 2014

Contents

1 Goals 311 Why you should use a library for this 3

2 Platform Support 5

3 Dependencies 7

4 Installation 941 Node 942 Browser 9

5 Syntax 1151 Synopsis 1152 Tag types 1153 Loop syntax 1154 Dash syntax 1255 Inverted Selections 12

6 Generate a document 1561 Loading a document 1562 Setting the tags 1563 Applying the tags 1664 Outputing the document 16

7 Configuration 1971 Image Replacing 1972 Angular Parser 1973 Intelligent LoopTagging 20

8 Command Line Interface (CLI) 2181 Configjson Syntax 21

9 Full Documentation per method 2391 Creating a new Docxgen Object 2392 Docxgen methods 24

10 Copyright 27

11 Demos 29

i

12 Indices and tables 31

ii

docxtemplater Documentation Release 054

Contents

Contents 1

docxtemplater Documentation Release 054

2 Contents

CHAPTER 1

Goals

Docxtemplater was born out of the idea that you should be able to generate Docx as easily as you generate Html withsomething like Mustache

They are a lots of solutions like docxjs docx4j that generate docx but you will have to write specific code tocreate a title an image

I think this is a waste when you can just write your template with plain old Microsoft Word

Docxtemplater is just there for that

11 Why you should use a library for this

Docx is a zipped format that contains some xml If you want to build a simple replace tagby value system it can already become complicated because the tag is internally separated intoltwtgtltwtgtltwtgttagltwtgtltwtgtltwtgt If you want to embed loops to iterate over an array it becomes areal hassle

3

docxtemplater Documentation Release 054

4 Chapter 1 Goals

CHAPTER 2

Platform Support

docxtemplater works with

bull Nodejs with 010 and 011

bull Chrome tested on version 26

bull Firefox 3+ (tested on version 21 but should work with 3+)

bull Safari not tested

Internet explorer is not supported -even IE10- (basically because xhr Requests canrsquot be made on binary files)

You can test if everything works fine on your browser by using the test runner httpjavascript-ninjafrdocxgenjstestSpecRunnerhtml

Firefox has an other implementation of the xml parser thatrsquos why all tests donrsquot pass now However all of thefunctionality works on Firefox too The output files are not exactly the same byte wise but the generated XML iscorrect

5

docxtemplater Documentation Release 054

6 Chapter 2 Platform Support

CHAPTER 3

Dependencies

1 docxgenjs uses [jszipjs](httpstukgithubiojszip) to zip and unzip the docx files

2 Optionally if you want to be able to name the output files you can use Downloadifyjs which is requiredto use method download Be informed that it uses flash this is why the method is not recommended Thismethod is howewer useful because a lot of browsers are limited for the download size with the Data-URImethod Update I will probably implement in the future a way to use the FileSaver API with [File-SaverJS](httpeligreycomdemosFileSaverjs)

3 Optionnaly if you want to replace images by images situated at a particular URL you can use QR codes Forexample If you store an image at httpwebsitecomimagepng you should encode the URL in QR-Code for-mat [Qr Code Sample](httpqrfreekaywacoml=1amps=8ampd=http3A2F2Fwebsitecom2FimagepngldquoQrcode Sample to httpwebsitecomimagepngrdquo) You can even use bracket tags in imageshttpwebsitecomimagepngcolor=color will take the Tags[color] variable to make a dynamic URL Forthis too work you will need [jsqrcode](httpgithubcomedi9999jsqrcode ldquojsqrcode repositoty forkedrdquo) andinclude the following files in this order (only for browser support node support already comes out of the box)

ltscript type=textjavascript src=gridjsgtltscriptgtltscript type=textjavascript src=versionjsgtltscriptgtltscript type=textjavascript src=detectorjsgtltscriptgtltscript type=textjavascript src=formatinfjsgtltscriptgtltscript type=textjavascript src=errorleveljsgtltscriptgtltscript type=textjavascript src=bitmatjsgtltscriptgtltscript type=textjavascript src=datablockjsgtltscriptgtltscript type=textjavascript src=bmparserjsgtltscriptgtltscript type=textjavascript src=datamaskjsgtltscriptgtltscript type=textjavascript src=rsdecoderjsgtltscriptgtltscript type=textjavascript src=gf256polyjsgtltscriptgtltscript type=textjavascript src=gf256jsgtltscriptgtltscript type=textjavascript src=decoderjsgtltscriptgtltscript type=textjavascript src=qrcodejsgtltscriptgtltscript type=textjavascript src=findpatjsgtltscriptgtltscript type=textjavascript src=alignpatjsgtltscriptgtltscript type=textjavascript src=databrjsgtltscriptgt

7

docxtemplater Documentation Release 054

8 Chapter 3 Dependencies

CHAPTER 4

Installation

41 Node

To install docxtemplater we recommend you to use npm

npm install docxtemplater

If you want to use the command line interface you should use the global flag eg

npm install docxtemplater -g

42 Browser

You will just have to include the docxgenjs or docxgenminjs file

9

docxtemplater Documentation Release 054

10 Chapter 4 Installation

CHAPTER 5

Syntax

The syntax is highly inspired by Mustache The template is created in Microsoft Word or any equivalent that saves todocx

51 Synopsis

A typical docxtemplater template

Hello name

Given the following hash

namersquoEdgarrsquo

Will produce

Hello Edgar

52 Tag types

Like Mustache it has the loopopening and loopclosing brackets

53 Loop syntax

The following template

productsname price C

products

Given the following hash

products

[nameWindowsprice100

11

docxtemplater Documentation Release 054

nameMac OSXprice200nameUbuntuprice0]

will result in

Windows 100 CMac OSX 200 CUbuntu 0C

The loop behaves in the following way

bull If the value is an array it will loop over all the elements of that array

bull If the value is a boolean it will loop once if the value is true keeping the same scope and not loop at all if thevalue is false

Note Because the loops work also with boolean values you can also use them for conditions

54 Dash syntax

It is quite difficult to know on which element you are going to loop By default when using the for loop docxgen willfind that by himself

If between the two tags tag______tag

bull they is the Xml Tag ltwtcgt -gt you are in a table and it will loop over ltwtrgt

bull else -gt it will loop over ltwtgt which is the default Text Tag

With the Dash syntax you pass as a first argument the tag you want to loop on

-wp loop inner loop

In this case this will loop over the first parent ltwpgt tag

55 Inverted Selections

An inverted section begins with a caret (hat) and ends with a slash That is ^person begins a ldquopersonrdquo invertedsection while person ends it

While sections can be used to render text one or more times based on the value of the key inverted sections may rendertext once based on the inverse value of the key That is they will be rendered if the key doesnrsquot exist is false or is anempty list

Template

repoltbgtnameltbgt

repo^repo

No repos (repo

Hash

12 Chapter 5 Syntax

docxtemplater Documentation Release 054

repo []

Output

No repos (

55 Inverted Selections 13

docxtemplater Documentation Release 054

14 Chapter 5 Syntax

CHAPTER 6

Generate a document

Herersquos a sample code to generate a document

DocxGen=require(rsquodocxtemplaterrsquo) Only for Node Usagenew DocxGen()loadFromFile(tagExampledocxasynctrue)success(function(doc)

docsetTags(first_nameHipp

last_nameEdgarphone0652455478descriptionNew Website

) set the templateVariablesdocapplyTags() apply them (replace all occurences of first_name by Hipp )docoutput() Output the document using Data-URI

)

The different steps are the following

61 Loading a document

A docx can be loaded by itrsquos base64 representation like this

doc=new DocxGen(base64Dataoptions)

However loading the base64Data is not that easy so I created a wrapper function to load a docx from a file via Ajax

Note The options parameter are explained in Configuration

doc=new DocxGen()loadFromFile(documentPathoptions)

The documentPath is the path to the document you want to load The options are the same as in the constructorfunction and Irsquove added the async parameter

bull If async is true the document is loaded asynchronously and returns a promise (eg you can write suc-cess(callback) to get when the document is loaded)

bull If async is false the document is loaded synchronously and returns the document

62 Setting the tags

The tags are the variables that are going to be replaced by their values To set them just use

15

docxtemplater Documentation Release 054

docsetTags(tags)

63 Applying the tags

Applying the tags means opening all files that contain text (eg footer header main document) and replace thevariables by their values

docapplyTags(tags)

Note If you specify an argument for the applyTags method the function setTags(tags) will be called before applyingthe tags

64 Outputing the document

They are several ways to output the document The most basic usage is to download the document

docoutput(options)

Depending on your environment if you donrsquot set any options this will

bull In the browser Download the document using DataURI

bull In Node Save the document with the given fileName (outputdocx by default)

Herersquos the different options parameters

nameTypestring[outputdocx]The name of the file that will be outputed (doesnt work in the browser because of dataUri download)

callbackTypefunctionFunction that is called without arguments when the output is done Is used only in Node (because in the browser the operation is synchronous)

downloadTypeboolean[true]If download is true file will be downloaded automatically with data URIreturns the output file

typeTypestring[base64]The type of zip to return The possible values are (same as in httpstukgithubiojszip generate)base64 (default) the result will be a string the binary in a base64 formstring the result will be a string in binary form 1 byte per charuint8array the result will be a Uint8Array containing the zip This requires a compatible browserarraybuffer the result will be a ArrayBuffer containing the zip This requires a compatible browserblob the result will be a Blob containing the zip This requires a compatible browsernodebuffer the result will be a nodejs Buffer containing the zip This requires nodejs

This function creates the docx file and downloads it on the userrsquos computer The name of the file is downloaddocxfor Chrome and some akward file names for Firefox VEeTHCfSdocxpartdocx and canrsquot be changed because it ishandled by the browser For more informations about how to solve this problem see the Filename Problems sectionon [httpstukgithubiojszip](httpstukgithubiojszip)

16 Chapter 6 Generate a document

docxtemplater Documentation Release 054

Note Note All browsers donrsquot support the download of big files withData URI so you should use the download method for files bigger than 100kBdataimagepngbase64iVBORw0KGgoAAAANSUhEUgAAABcAAAAXCAIAAABvSEP3AAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAACXSURBVDhPtY7BDYAwDAMZhCf7b8YMxeCoatOQJhWcKGxT2zlCyaWcz8Y+X7Bs1TFVJSwIHIYyFkQufWIRVX9cNJyW1QpEo4rixaEe7JuQagAUctb7ZFYFh5MVJPBe84CVBnB42YsZRgKjFDBVg3cI9WbRwXLktQJX8cNIiFhM1ZuTWk7PIYSBhkVcLzwIiCjCxhCjlAkBqYnqFoQQ2AAAAAElFTkSuQmCC

In Node to send the document to the client you can write the following code snippet

out=docoutput(downloadfalsetypestring)ressend(new Buffer(outbinary))

64 Outputing the document 17

docxtemplater Documentation Release 054

18 Chapter 6 Generate a document

CHAPTER 7

Configuration

Here are documented the special options that you can set when creating a new DocxGen to get some more superpower

It documents the options parameter when you do

new DocxGen(dataoptions)

71 Image Replacing

The name of this option qrCode (boolean)

To stay a templating engine I wanted that DocxTemplater doesnrsquot add an image from scratch but rather uses anexisting image that can be detected and DocxTemplater will just change the contents of that image without changingitrsquos style The size of the replaced images will stay the same

So I decided to use the qrCode format which is a format that lets you identify images by their content

The option for this is qrCode (true for on false for off default off)

Note If you donrsquot use that functionality you should disable it because it is quite slow (the image decoding)

Warning The qrCode functionality only works for PNG They is no support for other file formats yet

72 Angular Parser

The name of this option parser (function)

You can set the angular parser with the following code

With a custom parser you can parse the tags to for example add operators like lsquo+rsquo lsquo-lsquo or whatever the way you wantto parse expressions

To enable this you need to specify a custom parser You need to create a parser function

docxtemplater comes shipped with this parser

parser=function(expression)

return

19

docxtemplater Documentation Release 054

getfunction(scope) return scope[expression]

To use the angular-parser do the following

expressions= require(rsquoangular-expressionsrsquo)angularParser= function(tag)

return getexpressionscompile(tag)

new DocxGen(dataparserangularParser)

Note The require() works in the browser if you include vendorangular-parser-browserjs

73 Intelligent LoopTagging

The name of this option intelligentTagging (boolean)

When looping over an element docxtemplater needs to know over which element you want to loop By default it triesto do that intelligently (by looking what XML Tags are between the tags) However if you want to always use theltwtgt tag by default set this option to false

You can always specify over which element you want to loop with the dash loop syntax

20 Chapter 7 Configuration

CHAPTER 8

Command Line Interface (CLI)

This section is about the commandline interface of docxtemplater

The syntax is the following

docxtemplater configjson

The full configjson should be something like that

configdocxFileinputdocxconfigoutputFileoutputdocxconfigqrcodetrueconfigdebugtruefirst_nameJohnlast_nameSmithage62

81 Configjson Syntax

811 Config properties

These are the properties to configure docxtemplater

configdocxFileinputdocx The input file pathconfigoutputFileoutputdocx The output file pathconfigqrcodetrue whether the images should be scanned to replace them by qrcodes (slows down the cli a lot)configdebugtrue whether to show debug output or not

812 Data properties

To add data to your template just use keys that donrsquot start with ldquoconfigrdquo

first_nameJohnlast_nameSmithage62

21

docxtemplater Documentation Release 054

22 Chapter 8 Command Line Interface (CLI)

CHAPTER 9

Full Documentation per method

91 Creating a new Docxgen Object

new DocxGen()

This function returns a new DocxGen Object

new DocxGen(content[Tagsoptions])

contentType stringThe docx template you want to load as plain text

TagsType Object tag_nametag_replacement []Object containing for each tag_name the replacement for this tag For example if you want to replace firstName by David your Object will be firstNameDavid

options object

parserType functionA custom parser to use See angularjs like parsing

intelligentTaggingType boolean [false]If intelligent Tagging is not set to true when using recursive tags (tag and tag) the system will copy paste what is between the start tag and the endtag this could basically corrupt the files if recursive tags are used inside tablesIf intelligent Tagging is set to true and when using recursive tags inside tables the whole column will be copy pasted

qrCodeType boolean [false]If qrCode is set to true DocxGen will look at all the images to find a Qr-Code If the Qr-code matches to a URL this URL will be loaded by ajax (Be aware that the server you want to access needs to allow your request or it wonrsquot work httpstackoverflowcomquestions9310112why-am-i-seeing-an-origin-is-not-allowed-by-access-control-allow-origin-error )

Important the qrCode functionality only works for PNG I donrsquot think I will enable this for other fileformats in the near future

localImageCreatorType function(argcallback) [function that returns an arrow]The function has to be customized only if you want to use the qrCode options (qrCode=true) When the qrcode text starts with gen the image is not going to be loaded by url but DocxGen calls localImageCreator with arg=full Text decoded The callback needs to be called with the image Datacallback(result) in plaintxt format (if you want to create it from a Data-URI you can use JSZipBase64decode(data) to decode a Data-URI to plaintxt)

The default localImageCreator returns a red arrow no matter what the arguments are

localImageCreator= (argcallback) -gtresult=JSZipBase64decode(iVBORw0KGgoAAAANSUhEUgAAABcAAAAXCAIAAABvSEP3AAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAACXSURBVDhPtY7BDYAwDAMZhCf7b8YMxeCoatOQJhWcKGxT2zlCyaWcz8Y+X7Bs1TFVJSwIHIYyFkQufWIRVX9cNJyW1QpEo4rixaEe7JuQagAUctb7ZFYFh5MVJPBe84CVBnB42YsZRgKjFDBVg3cI9WbRwXLktQJX8cNIiFhM1ZuTWk7PIYSBhkVcLzwIiCjCxhCjlAkBqYnqFoQQ2AAAAAElFTkSuQmCC)

23

docxtemplater Documentation Release 054

[Default Image](dataimagepngbase64iVBORw0KGgoAAAANSUhEUgAAABcAAAAXCAIAAABvSEP3AAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAACXSURBVDhPtY7BDYAwDAMZhCf7b8YMxeCoatOQJhWcKGxT2zlCyaWcz8Y+X7Bs1TFVJSwIHIYyFkQufWIRVX9cNJyW1QpEo4rixaEe7JuQagAUctb7ZFYFh5MVJPBe84CVBnB42YsZRgKjFDBVg3cI9WbRwXLktQJX8cNIiFhM1ZuTWk7PIYSBhkVcLzwIiCjCxhCjlAkBqYnqFoQQ2AAAAAElFTkSuQmCC)

qrFinishedCallBackType function () [function that consolelog(ready)]

This function is called if you specify qrCode argument to true in this constructor and will be called when all qrCodes have been replaced (because the qrCode replacing functions are async)

92 Docxgen methods

load(content)

contentType stringThe docx template you want to load as plain text

loadFromFile(path)path

Type stringLoads a docx from a file path

setTags(Tags)

TagsType Object tag_nametag_replacementObject containing for each tag_name the replacement for this tag For example if you want to replace firstName by David your Object will be firstNameDavid

applyTags([Tags])Tags

Type Object tag_nametag_replacementsame as setTagsDefaultthisTags

This function replaces all template variables by their values

output([options])

options object[]

nameTypestring[outputdocx]The name of the file that will be outputed (doesnt work in the browser because of dataUri download)

callbackTypefunctionFunction that is called without arguments when the output is done Is used only in Node (because in the browser the operation is synchronous)

downloadTypeboolean[true]If download is true file will be downloaded automatically with data URIreturns the output file

typeTypestring[base64]The type of zip to return The possible values are (same as in httpstukgithubiojszip generate)base64 (default) the result will be a string the binary in a base64 formstring the result will be a string in binary form 1 byte per charuint8array the result will be a Uint8Array containing the zip This requires a compatible browser

24 Chapter 9 Full Documentation per method

docxtemplater Documentation Release 054

arraybuffer the result will be a ArrayBuffer containing the zip This requires a compatible browserblob the result will be a Blob containing the zip This requires a compatible browsernodebuffer the result will be a nodejs Buffer containing the zip This requires nodejs

This function creates the docx file and downloads it on the userrsquos computer The name of the file is downloaddocx for Chrome and some akward file names for Firefox VEeTHCfSdocxpartdocx and canrsquot be changed because it is handled by the browserFor more informations about how to solve this problem see the Filename Problems section on [httpstukgithubiojszip](httpstukgithubiojszip)

Note All browsers donrsquot support the download of big files with Data URI so you should use the lsquodownloadlsquo method for files bigger than 100kB dataimagepngbase64iVBORw0KGgoAAAANSUhEUgAAABcAAAAXCAIAAABvSEP3AAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAACXSURBVDhPtY7BDYAwDAMZhCf7b8YMxeCoatOQJhWcKGxT2zlCyaWcz8Y+X7Bs1TFVJSwIHIYyFkQufWIRVX9cNJyW1QpEo4rixaEe7JuQagAUctb7ZFYFh5MVJPBe84CVBnB42YsZRgKjFDBVg3cI9WbRwXLktQJX8cNIiFhM1ZuTWk7PIYSBhkVcLzwIiCjCxhCjlAkBqYnqFoQQ2AAAAAElFTkSuQmCC

download(swfpathimgpath[fileName])

swfpathTypestringPath to the swfobjectjs in downloadify

imgpathTypestringPath to the image of the download button

[fileName]TypestringDefaultdefaultdocxName of the file you would like the user to download

This requires to include Downloadifyjs that needs flash version 10 Have a look at the output function if you donrsquot want to depend on it This function has the advantage that it works regardless of the file size

getImageList()

this gets all images that have one of the following extension rsquogifrsquorsquojpegrsquorsquojpgrsquorsquoemfrsquorsquopngrsquoReturn format Array of Object[pathstringfilesZipFile Object]

You shouldrsquont call this method before calling applyTags() because applyTags can modify the images or their path when replacing images with other (particularly when qrCode is set to true which is not the default case) You can call this method after applyTags() without any problems

setImage(pathimgData)

pathTypeStringPath of the image given by getImageList()

imgDataTypeStringimgData in txtplain

This sets the image given by a path and an imgData in txtplainYou shouldrsquont call this method before calling applyTags() because applyTags can modify the images or their path when replacing images with other (particularly when qrCode is set to true which is not the default case) You can call this method after applyTags() without any problems

getFullText([path])

pathTypeStringDefaultworddocumentxmlThis argument determines from which document you want to get the text The main document is called worddocumentxml but they are other documents wordheader1xml wordfooter1xml

returnsTypeStringThe string containing all the text from the document

92 Docxgen methods 25

docxtemplater Documentation Release 054

This method gets only the text of a given document (not the formatting)

getTags()

This function returns the template variables contained in the opened document For example if the content of the documentxml is the following

namefirst_namephone

The function will return[

filenamedocumentxmlvars

nametruefirst_nametruephonetrue

]

If the content contains tagLoops

titlecustomernamephonecustomer

The function will return

[filenamedocumentxmlvars

titletruecustomer

nametruephonetrue

]

26 Chapter 9 Full Documentation per method

CHAPTER 10

Copyright

License

(The MIT license)

Copyright (c) 2013 Edgar Hipp

Permission is hereby granted free of charge to any person obtaining a copy of this software and associated documen-tation files (the ldquoSoftwarerdquo) to deal in the Software without restriction including without limitation the rights to usecopy modify merge publish distribute sublicense andor sell copies of the Software and to permit persons to whomthe Software is furnished to do so subject to the following conditions

The above copyright notice and this permission notice shall be included in all copies or substantial portions of theSoftware

THE SOFTWARE IS PROVIDED ldquoAS ISrdquo WITHOUT WARRANTY OF ANY KIND EXPRESS OR IMPLIEDINCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY FITNESS FOR A PAR-TICULAR PURPOSE AND NONINFRINGEMENT IN NO EVENT SHALL THE AUTHORS OR COPYRIGHTHOLDERS BE LIABLE FOR ANY CLAIM DAMAGES OR OTHER LIABILITY WHETHER IN AN ACTIONOF CONTRACT TORT OR OTHERWISE ARISING FROM OUT OF OR IN CONNECTION WITH THE SOFT-WARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE

27

docxtemplater Documentation Release 054

28 Chapter 10 Copyright

CHAPTER 11

Demos

Including

bull Replace Variables

bull Formating

bull Angular Parsing

bull Loops

bull Loops and tables

bull Lists

bull Replacing images

bull Naming the output

bull Using QrCodes

bull Replacing many images with QrCode

bull Raw Xml Insertion

29

docxtemplater Documentation Release 054

30 Chapter 11 Demos

CHAPTER 12

Indices and tables

bull genindex

bull modindex

bull search

31

docxtemplater Documentation Release 054

32 Chapter 12 Indices and tables

Index

CCommand Line Interface (CLI) 20Configuration 17Copyright 26

FFull_doc 21

GGenerate a Document 13Goals 1

IInstallation 7

Pplatform_support 3

SSyntax 9

33

  • Goals
    • Why you should use a library for this
      • Platform Support
      • Dependencies
      • Installation
        • Node
        • Browser
          • Syntax
            • Synopsis
            • Tag types
            • Loop syntax
            • Dash syntax
            • Inverted Selections
              • Generate a document
                • Loading a document
                • Setting the tags
                • Applying the tags
                • Outputing the document
                  • Configuration
                    • Image Replacing
                    • Angular Parser
                    • Intelligent LoopTagging
                      • Command Line Interface (CLI)
                        • Configjson Syntax
                          • Full Documentation per method
                            • Creating a new Docxgen Object
                            • Docxgen methods
                              • Copyright
                              • Demos
                              • Indices and tables
Page 2: Release 0.5€¦ · Docx is a zipped format that contains some xml. If you want to build a simple replace {tag} If you want to build a simple replace {tag} by value system, it can

Contents

1 Goals 311 Why you should use a library for this 3

2 Platform Support 5

3 Dependencies 7

4 Installation 941 Node 942 Browser 9

5 Syntax 1151 Synopsis 1152 Tag types 1153 Loop syntax 1154 Dash syntax 1255 Inverted Selections 12

6 Generate a document 1561 Loading a document 1562 Setting the tags 1563 Applying the tags 1664 Outputing the document 16

7 Configuration 1971 Image Replacing 1972 Angular Parser 1973 Intelligent LoopTagging 20

8 Command Line Interface (CLI) 2181 Configjson Syntax 21

9 Full Documentation per method 2391 Creating a new Docxgen Object 2392 Docxgen methods 24

10 Copyright 27

11 Demos 29

i

12 Indices and tables 31

ii

docxtemplater Documentation Release 054

Contents

Contents 1

docxtemplater Documentation Release 054

2 Contents

CHAPTER 1

Goals

Docxtemplater was born out of the idea that you should be able to generate Docx as easily as you generate Html withsomething like Mustache

They are a lots of solutions like docxjs docx4j that generate docx but you will have to write specific code tocreate a title an image

I think this is a waste when you can just write your template with plain old Microsoft Word

Docxtemplater is just there for that

11 Why you should use a library for this

Docx is a zipped format that contains some xml If you want to build a simple replace tagby value system it can already become complicated because the tag is internally separated intoltwtgtltwtgtltwtgttagltwtgtltwtgtltwtgt If you want to embed loops to iterate over an array it becomes areal hassle

3

docxtemplater Documentation Release 054

4 Chapter 1 Goals

CHAPTER 2

Platform Support

docxtemplater works with

bull Nodejs with 010 and 011

bull Chrome tested on version 26

bull Firefox 3+ (tested on version 21 but should work with 3+)

bull Safari not tested

Internet explorer is not supported -even IE10- (basically because xhr Requests canrsquot be made on binary files)

You can test if everything works fine on your browser by using the test runner httpjavascript-ninjafrdocxgenjstestSpecRunnerhtml

Firefox has an other implementation of the xml parser thatrsquos why all tests donrsquot pass now However all of thefunctionality works on Firefox too The output files are not exactly the same byte wise but the generated XML iscorrect

5

docxtemplater Documentation Release 054

6 Chapter 2 Platform Support

CHAPTER 3

Dependencies

1 docxgenjs uses [jszipjs](httpstukgithubiojszip) to zip and unzip the docx files

2 Optionally if you want to be able to name the output files you can use Downloadifyjs which is requiredto use method download Be informed that it uses flash this is why the method is not recommended Thismethod is howewer useful because a lot of browsers are limited for the download size with the Data-URImethod Update I will probably implement in the future a way to use the FileSaver API with [File-SaverJS](httpeligreycomdemosFileSaverjs)

3 Optionnaly if you want to replace images by images situated at a particular URL you can use QR codes Forexample If you store an image at httpwebsitecomimagepng you should encode the URL in QR-Code for-mat [Qr Code Sample](httpqrfreekaywacoml=1amps=8ampd=http3A2F2Fwebsitecom2FimagepngldquoQrcode Sample to httpwebsitecomimagepngrdquo) You can even use bracket tags in imageshttpwebsitecomimagepngcolor=color will take the Tags[color] variable to make a dynamic URL Forthis too work you will need [jsqrcode](httpgithubcomedi9999jsqrcode ldquojsqrcode repositoty forkedrdquo) andinclude the following files in this order (only for browser support node support already comes out of the box)

ltscript type=textjavascript src=gridjsgtltscriptgtltscript type=textjavascript src=versionjsgtltscriptgtltscript type=textjavascript src=detectorjsgtltscriptgtltscript type=textjavascript src=formatinfjsgtltscriptgtltscript type=textjavascript src=errorleveljsgtltscriptgtltscript type=textjavascript src=bitmatjsgtltscriptgtltscript type=textjavascript src=datablockjsgtltscriptgtltscript type=textjavascript src=bmparserjsgtltscriptgtltscript type=textjavascript src=datamaskjsgtltscriptgtltscript type=textjavascript src=rsdecoderjsgtltscriptgtltscript type=textjavascript src=gf256polyjsgtltscriptgtltscript type=textjavascript src=gf256jsgtltscriptgtltscript type=textjavascript src=decoderjsgtltscriptgtltscript type=textjavascript src=qrcodejsgtltscriptgtltscript type=textjavascript src=findpatjsgtltscriptgtltscript type=textjavascript src=alignpatjsgtltscriptgtltscript type=textjavascript src=databrjsgtltscriptgt

7

docxtemplater Documentation Release 054

8 Chapter 3 Dependencies

CHAPTER 4

Installation

41 Node

To install docxtemplater we recommend you to use npm

npm install docxtemplater

If you want to use the command line interface you should use the global flag eg

npm install docxtemplater -g

42 Browser

You will just have to include the docxgenjs or docxgenminjs file

9

docxtemplater Documentation Release 054

10 Chapter 4 Installation

CHAPTER 5

Syntax

The syntax is highly inspired by Mustache The template is created in Microsoft Word or any equivalent that saves todocx

51 Synopsis

A typical docxtemplater template

Hello name

Given the following hash

namersquoEdgarrsquo

Will produce

Hello Edgar

52 Tag types

Like Mustache it has the loopopening and loopclosing brackets

53 Loop syntax

The following template

productsname price C

products

Given the following hash

products

[nameWindowsprice100

11

docxtemplater Documentation Release 054

nameMac OSXprice200nameUbuntuprice0]

will result in

Windows 100 CMac OSX 200 CUbuntu 0C

The loop behaves in the following way

bull If the value is an array it will loop over all the elements of that array

bull If the value is a boolean it will loop once if the value is true keeping the same scope and not loop at all if thevalue is false

Note Because the loops work also with boolean values you can also use them for conditions

54 Dash syntax

It is quite difficult to know on which element you are going to loop By default when using the for loop docxgen willfind that by himself

If between the two tags tag______tag

bull they is the Xml Tag ltwtcgt -gt you are in a table and it will loop over ltwtrgt

bull else -gt it will loop over ltwtgt which is the default Text Tag

With the Dash syntax you pass as a first argument the tag you want to loop on

-wp loop inner loop

In this case this will loop over the first parent ltwpgt tag

55 Inverted Selections

An inverted section begins with a caret (hat) and ends with a slash That is ^person begins a ldquopersonrdquo invertedsection while person ends it

While sections can be used to render text one or more times based on the value of the key inverted sections may rendertext once based on the inverse value of the key That is they will be rendered if the key doesnrsquot exist is false or is anempty list

Template

repoltbgtnameltbgt

repo^repo

No repos (repo

Hash

12 Chapter 5 Syntax

docxtemplater Documentation Release 054

repo []

Output

No repos (

55 Inverted Selections 13

docxtemplater Documentation Release 054

14 Chapter 5 Syntax

CHAPTER 6

Generate a document

Herersquos a sample code to generate a document

DocxGen=require(rsquodocxtemplaterrsquo) Only for Node Usagenew DocxGen()loadFromFile(tagExampledocxasynctrue)success(function(doc)

docsetTags(first_nameHipp

last_nameEdgarphone0652455478descriptionNew Website

) set the templateVariablesdocapplyTags() apply them (replace all occurences of first_name by Hipp )docoutput() Output the document using Data-URI

)

The different steps are the following

61 Loading a document

A docx can be loaded by itrsquos base64 representation like this

doc=new DocxGen(base64Dataoptions)

However loading the base64Data is not that easy so I created a wrapper function to load a docx from a file via Ajax

Note The options parameter are explained in Configuration

doc=new DocxGen()loadFromFile(documentPathoptions)

The documentPath is the path to the document you want to load The options are the same as in the constructorfunction and Irsquove added the async parameter

bull If async is true the document is loaded asynchronously and returns a promise (eg you can write suc-cess(callback) to get when the document is loaded)

bull If async is false the document is loaded synchronously and returns the document

62 Setting the tags

The tags are the variables that are going to be replaced by their values To set them just use

15

docxtemplater Documentation Release 054

docsetTags(tags)

63 Applying the tags

Applying the tags means opening all files that contain text (eg footer header main document) and replace thevariables by their values

docapplyTags(tags)

Note If you specify an argument for the applyTags method the function setTags(tags) will be called before applyingthe tags

64 Outputing the document

They are several ways to output the document The most basic usage is to download the document

docoutput(options)

Depending on your environment if you donrsquot set any options this will

bull In the browser Download the document using DataURI

bull In Node Save the document with the given fileName (outputdocx by default)

Herersquos the different options parameters

nameTypestring[outputdocx]The name of the file that will be outputed (doesnt work in the browser because of dataUri download)

callbackTypefunctionFunction that is called without arguments when the output is done Is used only in Node (because in the browser the operation is synchronous)

downloadTypeboolean[true]If download is true file will be downloaded automatically with data URIreturns the output file

typeTypestring[base64]The type of zip to return The possible values are (same as in httpstukgithubiojszip generate)base64 (default) the result will be a string the binary in a base64 formstring the result will be a string in binary form 1 byte per charuint8array the result will be a Uint8Array containing the zip This requires a compatible browserarraybuffer the result will be a ArrayBuffer containing the zip This requires a compatible browserblob the result will be a Blob containing the zip This requires a compatible browsernodebuffer the result will be a nodejs Buffer containing the zip This requires nodejs

This function creates the docx file and downloads it on the userrsquos computer The name of the file is downloaddocxfor Chrome and some akward file names for Firefox VEeTHCfSdocxpartdocx and canrsquot be changed because it ishandled by the browser For more informations about how to solve this problem see the Filename Problems sectionon [httpstukgithubiojszip](httpstukgithubiojszip)

16 Chapter 6 Generate a document

docxtemplater Documentation Release 054

Note Note All browsers donrsquot support the download of big files withData URI so you should use the download method for files bigger than 100kBdataimagepngbase64iVBORw0KGgoAAAANSUhEUgAAABcAAAAXCAIAAABvSEP3AAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAACXSURBVDhPtY7BDYAwDAMZhCf7b8YMxeCoatOQJhWcKGxT2zlCyaWcz8Y+X7Bs1TFVJSwIHIYyFkQufWIRVX9cNJyW1QpEo4rixaEe7JuQagAUctb7ZFYFh5MVJPBe84CVBnB42YsZRgKjFDBVg3cI9WbRwXLktQJX8cNIiFhM1ZuTWk7PIYSBhkVcLzwIiCjCxhCjlAkBqYnqFoQQ2AAAAAElFTkSuQmCC

In Node to send the document to the client you can write the following code snippet

out=docoutput(downloadfalsetypestring)ressend(new Buffer(outbinary))

64 Outputing the document 17

docxtemplater Documentation Release 054

18 Chapter 6 Generate a document

CHAPTER 7

Configuration

Here are documented the special options that you can set when creating a new DocxGen to get some more superpower

It documents the options parameter when you do

new DocxGen(dataoptions)

71 Image Replacing

The name of this option qrCode (boolean)

To stay a templating engine I wanted that DocxTemplater doesnrsquot add an image from scratch but rather uses anexisting image that can be detected and DocxTemplater will just change the contents of that image without changingitrsquos style The size of the replaced images will stay the same

So I decided to use the qrCode format which is a format that lets you identify images by their content

The option for this is qrCode (true for on false for off default off)

Note If you donrsquot use that functionality you should disable it because it is quite slow (the image decoding)

Warning The qrCode functionality only works for PNG They is no support for other file formats yet

72 Angular Parser

The name of this option parser (function)

You can set the angular parser with the following code

With a custom parser you can parse the tags to for example add operators like lsquo+rsquo lsquo-lsquo or whatever the way you wantto parse expressions

To enable this you need to specify a custom parser You need to create a parser function

docxtemplater comes shipped with this parser

parser=function(expression)

return

19

docxtemplater Documentation Release 054

getfunction(scope) return scope[expression]

To use the angular-parser do the following

expressions= require(rsquoangular-expressionsrsquo)angularParser= function(tag)

return getexpressionscompile(tag)

new DocxGen(dataparserangularParser)

Note The require() works in the browser if you include vendorangular-parser-browserjs

73 Intelligent LoopTagging

The name of this option intelligentTagging (boolean)

When looping over an element docxtemplater needs to know over which element you want to loop By default it triesto do that intelligently (by looking what XML Tags are between the tags) However if you want to always use theltwtgt tag by default set this option to false

You can always specify over which element you want to loop with the dash loop syntax

20 Chapter 7 Configuration

CHAPTER 8

Command Line Interface (CLI)

This section is about the commandline interface of docxtemplater

The syntax is the following

docxtemplater configjson

The full configjson should be something like that

configdocxFileinputdocxconfigoutputFileoutputdocxconfigqrcodetrueconfigdebugtruefirst_nameJohnlast_nameSmithage62

81 Configjson Syntax

811 Config properties

These are the properties to configure docxtemplater

configdocxFileinputdocx The input file pathconfigoutputFileoutputdocx The output file pathconfigqrcodetrue whether the images should be scanned to replace them by qrcodes (slows down the cli a lot)configdebugtrue whether to show debug output or not

812 Data properties

To add data to your template just use keys that donrsquot start with ldquoconfigrdquo

first_nameJohnlast_nameSmithage62

21

docxtemplater Documentation Release 054

22 Chapter 8 Command Line Interface (CLI)

CHAPTER 9

Full Documentation per method

91 Creating a new Docxgen Object

new DocxGen()

This function returns a new DocxGen Object

new DocxGen(content[Tagsoptions])

contentType stringThe docx template you want to load as plain text

TagsType Object tag_nametag_replacement []Object containing for each tag_name the replacement for this tag For example if you want to replace firstName by David your Object will be firstNameDavid

options object

parserType functionA custom parser to use See angularjs like parsing

intelligentTaggingType boolean [false]If intelligent Tagging is not set to true when using recursive tags (tag and tag) the system will copy paste what is between the start tag and the endtag this could basically corrupt the files if recursive tags are used inside tablesIf intelligent Tagging is set to true and when using recursive tags inside tables the whole column will be copy pasted

qrCodeType boolean [false]If qrCode is set to true DocxGen will look at all the images to find a Qr-Code If the Qr-code matches to a URL this URL will be loaded by ajax (Be aware that the server you want to access needs to allow your request or it wonrsquot work httpstackoverflowcomquestions9310112why-am-i-seeing-an-origin-is-not-allowed-by-access-control-allow-origin-error )

Important the qrCode functionality only works for PNG I donrsquot think I will enable this for other fileformats in the near future

localImageCreatorType function(argcallback) [function that returns an arrow]The function has to be customized only if you want to use the qrCode options (qrCode=true) When the qrcode text starts with gen the image is not going to be loaded by url but DocxGen calls localImageCreator with arg=full Text decoded The callback needs to be called with the image Datacallback(result) in plaintxt format (if you want to create it from a Data-URI you can use JSZipBase64decode(data) to decode a Data-URI to plaintxt)

The default localImageCreator returns a red arrow no matter what the arguments are

localImageCreator= (argcallback) -gtresult=JSZipBase64decode(iVBORw0KGgoAAAANSUhEUgAAABcAAAAXCAIAAABvSEP3AAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAACXSURBVDhPtY7BDYAwDAMZhCf7b8YMxeCoatOQJhWcKGxT2zlCyaWcz8Y+X7Bs1TFVJSwIHIYyFkQufWIRVX9cNJyW1QpEo4rixaEe7JuQagAUctb7ZFYFh5MVJPBe84CVBnB42YsZRgKjFDBVg3cI9WbRwXLktQJX8cNIiFhM1ZuTWk7PIYSBhkVcLzwIiCjCxhCjlAkBqYnqFoQQ2AAAAAElFTkSuQmCC)

23

docxtemplater Documentation Release 054

[Default Image](dataimagepngbase64iVBORw0KGgoAAAANSUhEUgAAABcAAAAXCAIAAABvSEP3AAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAACXSURBVDhPtY7BDYAwDAMZhCf7b8YMxeCoatOQJhWcKGxT2zlCyaWcz8Y+X7Bs1TFVJSwIHIYyFkQufWIRVX9cNJyW1QpEo4rixaEe7JuQagAUctb7ZFYFh5MVJPBe84CVBnB42YsZRgKjFDBVg3cI9WbRwXLktQJX8cNIiFhM1ZuTWk7PIYSBhkVcLzwIiCjCxhCjlAkBqYnqFoQQ2AAAAAElFTkSuQmCC)

qrFinishedCallBackType function () [function that consolelog(ready)]

This function is called if you specify qrCode argument to true in this constructor and will be called when all qrCodes have been replaced (because the qrCode replacing functions are async)

92 Docxgen methods

load(content)

contentType stringThe docx template you want to load as plain text

loadFromFile(path)path

Type stringLoads a docx from a file path

setTags(Tags)

TagsType Object tag_nametag_replacementObject containing for each tag_name the replacement for this tag For example if you want to replace firstName by David your Object will be firstNameDavid

applyTags([Tags])Tags

Type Object tag_nametag_replacementsame as setTagsDefaultthisTags

This function replaces all template variables by their values

output([options])

options object[]

nameTypestring[outputdocx]The name of the file that will be outputed (doesnt work in the browser because of dataUri download)

callbackTypefunctionFunction that is called without arguments when the output is done Is used only in Node (because in the browser the operation is synchronous)

downloadTypeboolean[true]If download is true file will be downloaded automatically with data URIreturns the output file

typeTypestring[base64]The type of zip to return The possible values are (same as in httpstukgithubiojszip generate)base64 (default) the result will be a string the binary in a base64 formstring the result will be a string in binary form 1 byte per charuint8array the result will be a Uint8Array containing the zip This requires a compatible browser

24 Chapter 9 Full Documentation per method

docxtemplater Documentation Release 054

arraybuffer the result will be a ArrayBuffer containing the zip This requires a compatible browserblob the result will be a Blob containing the zip This requires a compatible browsernodebuffer the result will be a nodejs Buffer containing the zip This requires nodejs

This function creates the docx file and downloads it on the userrsquos computer The name of the file is downloaddocx for Chrome and some akward file names for Firefox VEeTHCfSdocxpartdocx and canrsquot be changed because it is handled by the browserFor more informations about how to solve this problem see the Filename Problems section on [httpstukgithubiojszip](httpstukgithubiojszip)

Note All browsers donrsquot support the download of big files with Data URI so you should use the lsquodownloadlsquo method for files bigger than 100kB dataimagepngbase64iVBORw0KGgoAAAANSUhEUgAAABcAAAAXCAIAAABvSEP3AAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAACXSURBVDhPtY7BDYAwDAMZhCf7b8YMxeCoatOQJhWcKGxT2zlCyaWcz8Y+X7Bs1TFVJSwIHIYyFkQufWIRVX9cNJyW1QpEo4rixaEe7JuQagAUctb7ZFYFh5MVJPBe84CVBnB42YsZRgKjFDBVg3cI9WbRwXLktQJX8cNIiFhM1ZuTWk7PIYSBhkVcLzwIiCjCxhCjlAkBqYnqFoQQ2AAAAAElFTkSuQmCC

download(swfpathimgpath[fileName])

swfpathTypestringPath to the swfobjectjs in downloadify

imgpathTypestringPath to the image of the download button

[fileName]TypestringDefaultdefaultdocxName of the file you would like the user to download

This requires to include Downloadifyjs that needs flash version 10 Have a look at the output function if you donrsquot want to depend on it This function has the advantage that it works regardless of the file size

getImageList()

this gets all images that have one of the following extension rsquogifrsquorsquojpegrsquorsquojpgrsquorsquoemfrsquorsquopngrsquoReturn format Array of Object[pathstringfilesZipFile Object]

You shouldrsquont call this method before calling applyTags() because applyTags can modify the images or their path when replacing images with other (particularly when qrCode is set to true which is not the default case) You can call this method after applyTags() without any problems

setImage(pathimgData)

pathTypeStringPath of the image given by getImageList()

imgDataTypeStringimgData in txtplain

This sets the image given by a path and an imgData in txtplainYou shouldrsquont call this method before calling applyTags() because applyTags can modify the images or their path when replacing images with other (particularly when qrCode is set to true which is not the default case) You can call this method after applyTags() without any problems

getFullText([path])

pathTypeStringDefaultworddocumentxmlThis argument determines from which document you want to get the text The main document is called worddocumentxml but they are other documents wordheader1xml wordfooter1xml

returnsTypeStringThe string containing all the text from the document

92 Docxgen methods 25

docxtemplater Documentation Release 054

This method gets only the text of a given document (not the formatting)

getTags()

This function returns the template variables contained in the opened document For example if the content of the documentxml is the following

namefirst_namephone

The function will return[

filenamedocumentxmlvars

nametruefirst_nametruephonetrue

]

If the content contains tagLoops

titlecustomernamephonecustomer

The function will return

[filenamedocumentxmlvars

titletruecustomer

nametruephonetrue

]

26 Chapter 9 Full Documentation per method

CHAPTER 10

Copyright

License

(The MIT license)

Copyright (c) 2013 Edgar Hipp

Permission is hereby granted free of charge to any person obtaining a copy of this software and associated documen-tation files (the ldquoSoftwarerdquo) to deal in the Software without restriction including without limitation the rights to usecopy modify merge publish distribute sublicense andor sell copies of the Software and to permit persons to whomthe Software is furnished to do so subject to the following conditions

The above copyright notice and this permission notice shall be included in all copies or substantial portions of theSoftware

THE SOFTWARE IS PROVIDED ldquoAS ISrdquo WITHOUT WARRANTY OF ANY KIND EXPRESS OR IMPLIEDINCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY FITNESS FOR A PAR-TICULAR PURPOSE AND NONINFRINGEMENT IN NO EVENT SHALL THE AUTHORS OR COPYRIGHTHOLDERS BE LIABLE FOR ANY CLAIM DAMAGES OR OTHER LIABILITY WHETHER IN AN ACTIONOF CONTRACT TORT OR OTHERWISE ARISING FROM OUT OF OR IN CONNECTION WITH THE SOFT-WARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE

27

docxtemplater Documentation Release 054

28 Chapter 10 Copyright

CHAPTER 11

Demos

Including

bull Replace Variables

bull Formating

bull Angular Parsing

bull Loops

bull Loops and tables

bull Lists

bull Replacing images

bull Naming the output

bull Using QrCodes

bull Replacing many images with QrCode

bull Raw Xml Insertion

29

docxtemplater Documentation Release 054

30 Chapter 11 Demos

CHAPTER 12

Indices and tables

bull genindex

bull modindex

bull search

31

docxtemplater Documentation Release 054

32 Chapter 12 Indices and tables

Index

CCommand Line Interface (CLI) 20Configuration 17Copyright 26

FFull_doc 21

GGenerate a Document 13Goals 1

IInstallation 7

Pplatform_support 3

SSyntax 9

33

  • Goals
    • Why you should use a library for this
      • Platform Support
      • Dependencies
      • Installation
        • Node
        • Browser
          • Syntax
            • Synopsis
            • Tag types
            • Loop syntax
            • Dash syntax
            • Inverted Selections
              • Generate a document
                • Loading a document
                • Setting the tags
                • Applying the tags
                • Outputing the document
                  • Configuration
                    • Image Replacing
                    • Angular Parser
                    • Intelligent LoopTagging
                      • Command Line Interface (CLI)
                        • Configjson Syntax
                          • Full Documentation per method
                            • Creating a new Docxgen Object
                            • Docxgen methods
                              • Copyright
                              • Demos
                              • Indices and tables
Page 3: Release 0.5€¦ · Docx is a zipped format that contains some xml. If you want to build a simple replace {tag} If you want to build a simple replace {tag} by value system, it can

12 Indices and tables 31

ii

docxtemplater Documentation Release 054

Contents

Contents 1

docxtemplater Documentation Release 054

2 Contents

CHAPTER 1

Goals

Docxtemplater was born out of the idea that you should be able to generate Docx as easily as you generate Html withsomething like Mustache

They are a lots of solutions like docxjs docx4j that generate docx but you will have to write specific code tocreate a title an image

I think this is a waste when you can just write your template with plain old Microsoft Word

Docxtemplater is just there for that

11 Why you should use a library for this

Docx is a zipped format that contains some xml If you want to build a simple replace tagby value system it can already become complicated because the tag is internally separated intoltwtgtltwtgtltwtgttagltwtgtltwtgtltwtgt If you want to embed loops to iterate over an array it becomes areal hassle

3

docxtemplater Documentation Release 054

4 Chapter 1 Goals

CHAPTER 2

Platform Support

docxtemplater works with

bull Nodejs with 010 and 011

bull Chrome tested on version 26

bull Firefox 3+ (tested on version 21 but should work with 3+)

bull Safari not tested

Internet explorer is not supported -even IE10- (basically because xhr Requests canrsquot be made on binary files)

You can test if everything works fine on your browser by using the test runner httpjavascript-ninjafrdocxgenjstestSpecRunnerhtml

Firefox has an other implementation of the xml parser thatrsquos why all tests donrsquot pass now However all of thefunctionality works on Firefox too The output files are not exactly the same byte wise but the generated XML iscorrect

5

docxtemplater Documentation Release 054

6 Chapter 2 Platform Support

CHAPTER 3

Dependencies

1 docxgenjs uses [jszipjs](httpstukgithubiojszip) to zip and unzip the docx files

2 Optionally if you want to be able to name the output files you can use Downloadifyjs which is requiredto use method download Be informed that it uses flash this is why the method is not recommended Thismethod is howewer useful because a lot of browsers are limited for the download size with the Data-URImethod Update I will probably implement in the future a way to use the FileSaver API with [File-SaverJS](httpeligreycomdemosFileSaverjs)

3 Optionnaly if you want to replace images by images situated at a particular URL you can use QR codes Forexample If you store an image at httpwebsitecomimagepng you should encode the URL in QR-Code for-mat [Qr Code Sample](httpqrfreekaywacoml=1amps=8ampd=http3A2F2Fwebsitecom2FimagepngldquoQrcode Sample to httpwebsitecomimagepngrdquo) You can even use bracket tags in imageshttpwebsitecomimagepngcolor=color will take the Tags[color] variable to make a dynamic URL Forthis too work you will need [jsqrcode](httpgithubcomedi9999jsqrcode ldquojsqrcode repositoty forkedrdquo) andinclude the following files in this order (only for browser support node support already comes out of the box)

ltscript type=textjavascript src=gridjsgtltscriptgtltscript type=textjavascript src=versionjsgtltscriptgtltscript type=textjavascript src=detectorjsgtltscriptgtltscript type=textjavascript src=formatinfjsgtltscriptgtltscript type=textjavascript src=errorleveljsgtltscriptgtltscript type=textjavascript src=bitmatjsgtltscriptgtltscript type=textjavascript src=datablockjsgtltscriptgtltscript type=textjavascript src=bmparserjsgtltscriptgtltscript type=textjavascript src=datamaskjsgtltscriptgtltscript type=textjavascript src=rsdecoderjsgtltscriptgtltscript type=textjavascript src=gf256polyjsgtltscriptgtltscript type=textjavascript src=gf256jsgtltscriptgtltscript type=textjavascript src=decoderjsgtltscriptgtltscript type=textjavascript src=qrcodejsgtltscriptgtltscript type=textjavascript src=findpatjsgtltscriptgtltscript type=textjavascript src=alignpatjsgtltscriptgtltscript type=textjavascript src=databrjsgtltscriptgt

7

docxtemplater Documentation Release 054

8 Chapter 3 Dependencies

CHAPTER 4

Installation

41 Node

To install docxtemplater we recommend you to use npm

npm install docxtemplater

If you want to use the command line interface you should use the global flag eg

npm install docxtemplater -g

42 Browser

You will just have to include the docxgenjs or docxgenminjs file

9

docxtemplater Documentation Release 054

10 Chapter 4 Installation

CHAPTER 5

Syntax

The syntax is highly inspired by Mustache The template is created in Microsoft Word or any equivalent that saves todocx

51 Synopsis

A typical docxtemplater template

Hello name

Given the following hash

namersquoEdgarrsquo

Will produce

Hello Edgar

52 Tag types

Like Mustache it has the loopopening and loopclosing brackets

53 Loop syntax

The following template

productsname price C

products

Given the following hash

products

[nameWindowsprice100

11

docxtemplater Documentation Release 054

nameMac OSXprice200nameUbuntuprice0]

will result in

Windows 100 CMac OSX 200 CUbuntu 0C

The loop behaves in the following way

bull If the value is an array it will loop over all the elements of that array

bull If the value is a boolean it will loop once if the value is true keeping the same scope and not loop at all if thevalue is false

Note Because the loops work also with boolean values you can also use them for conditions

54 Dash syntax

It is quite difficult to know on which element you are going to loop By default when using the for loop docxgen willfind that by himself

If between the two tags tag______tag

bull they is the Xml Tag ltwtcgt -gt you are in a table and it will loop over ltwtrgt

bull else -gt it will loop over ltwtgt which is the default Text Tag

With the Dash syntax you pass as a first argument the tag you want to loop on

-wp loop inner loop

In this case this will loop over the first parent ltwpgt tag

55 Inverted Selections

An inverted section begins with a caret (hat) and ends with a slash That is ^person begins a ldquopersonrdquo invertedsection while person ends it

While sections can be used to render text one or more times based on the value of the key inverted sections may rendertext once based on the inverse value of the key That is they will be rendered if the key doesnrsquot exist is false or is anempty list

Template

repoltbgtnameltbgt

repo^repo

No repos (repo

Hash

12 Chapter 5 Syntax

docxtemplater Documentation Release 054

repo []

Output

No repos (

55 Inverted Selections 13

docxtemplater Documentation Release 054

14 Chapter 5 Syntax

CHAPTER 6

Generate a document

Herersquos a sample code to generate a document

DocxGen=require(rsquodocxtemplaterrsquo) Only for Node Usagenew DocxGen()loadFromFile(tagExampledocxasynctrue)success(function(doc)

docsetTags(first_nameHipp

last_nameEdgarphone0652455478descriptionNew Website

) set the templateVariablesdocapplyTags() apply them (replace all occurences of first_name by Hipp )docoutput() Output the document using Data-URI

)

The different steps are the following

61 Loading a document

A docx can be loaded by itrsquos base64 representation like this

doc=new DocxGen(base64Dataoptions)

However loading the base64Data is not that easy so I created a wrapper function to load a docx from a file via Ajax

Note The options parameter are explained in Configuration

doc=new DocxGen()loadFromFile(documentPathoptions)

The documentPath is the path to the document you want to load The options are the same as in the constructorfunction and Irsquove added the async parameter

bull If async is true the document is loaded asynchronously and returns a promise (eg you can write suc-cess(callback) to get when the document is loaded)

bull If async is false the document is loaded synchronously and returns the document

62 Setting the tags

The tags are the variables that are going to be replaced by their values To set them just use

15

docxtemplater Documentation Release 054

docsetTags(tags)

63 Applying the tags

Applying the tags means opening all files that contain text (eg footer header main document) and replace thevariables by their values

docapplyTags(tags)

Note If you specify an argument for the applyTags method the function setTags(tags) will be called before applyingthe tags

64 Outputing the document

They are several ways to output the document The most basic usage is to download the document

docoutput(options)

Depending on your environment if you donrsquot set any options this will

bull In the browser Download the document using DataURI

bull In Node Save the document with the given fileName (outputdocx by default)

Herersquos the different options parameters

nameTypestring[outputdocx]The name of the file that will be outputed (doesnt work in the browser because of dataUri download)

callbackTypefunctionFunction that is called without arguments when the output is done Is used only in Node (because in the browser the operation is synchronous)

downloadTypeboolean[true]If download is true file will be downloaded automatically with data URIreturns the output file

typeTypestring[base64]The type of zip to return The possible values are (same as in httpstukgithubiojszip generate)base64 (default) the result will be a string the binary in a base64 formstring the result will be a string in binary form 1 byte per charuint8array the result will be a Uint8Array containing the zip This requires a compatible browserarraybuffer the result will be a ArrayBuffer containing the zip This requires a compatible browserblob the result will be a Blob containing the zip This requires a compatible browsernodebuffer the result will be a nodejs Buffer containing the zip This requires nodejs

This function creates the docx file and downloads it on the userrsquos computer The name of the file is downloaddocxfor Chrome and some akward file names for Firefox VEeTHCfSdocxpartdocx and canrsquot be changed because it ishandled by the browser For more informations about how to solve this problem see the Filename Problems sectionon [httpstukgithubiojszip](httpstukgithubiojszip)

16 Chapter 6 Generate a document

docxtemplater Documentation Release 054

Note Note All browsers donrsquot support the download of big files withData URI so you should use the download method for files bigger than 100kBdataimagepngbase64iVBORw0KGgoAAAANSUhEUgAAABcAAAAXCAIAAABvSEP3AAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAACXSURBVDhPtY7BDYAwDAMZhCf7b8YMxeCoatOQJhWcKGxT2zlCyaWcz8Y+X7Bs1TFVJSwIHIYyFkQufWIRVX9cNJyW1QpEo4rixaEe7JuQagAUctb7ZFYFh5MVJPBe84CVBnB42YsZRgKjFDBVg3cI9WbRwXLktQJX8cNIiFhM1ZuTWk7PIYSBhkVcLzwIiCjCxhCjlAkBqYnqFoQQ2AAAAAElFTkSuQmCC

In Node to send the document to the client you can write the following code snippet

out=docoutput(downloadfalsetypestring)ressend(new Buffer(outbinary))

64 Outputing the document 17

docxtemplater Documentation Release 054

18 Chapter 6 Generate a document

CHAPTER 7

Configuration

Here are documented the special options that you can set when creating a new DocxGen to get some more superpower

It documents the options parameter when you do

new DocxGen(dataoptions)

71 Image Replacing

The name of this option qrCode (boolean)

To stay a templating engine I wanted that DocxTemplater doesnrsquot add an image from scratch but rather uses anexisting image that can be detected and DocxTemplater will just change the contents of that image without changingitrsquos style The size of the replaced images will stay the same

So I decided to use the qrCode format which is a format that lets you identify images by their content

The option for this is qrCode (true for on false for off default off)

Note If you donrsquot use that functionality you should disable it because it is quite slow (the image decoding)

Warning The qrCode functionality only works for PNG They is no support for other file formats yet

72 Angular Parser

The name of this option parser (function)

You can set the angular parser with the following code

With a custom parser you can parse the tags to for example add operators like lsquo+rsquo lsquo-lsquo or whatever the way you wantto parse expressions

To enable this you need to specify a custom parser You need to create a parser function

docxtemplater comes shipped with this parser

parser=function(expression)

return

19

docxtemplater Documentation Release 054

getfunction(scope) return scope[expression]

To use the angular-parser do the following

expressions= require(rsquoangular-expressionsrsquo)angularParser= function(tag)

return getexpressionscompile(tag)

new DocxGen(dataparserangularParser)

Note The require() works in the browser if you include vendorangular-parser-browserjs

73 Intelligent LoopTagging

The name of this option intelligentTagging (boolean)

When looping over an element docxtemplater needs to know over which element you want to loop By default it triesto do that intelligently (by looking what XML Tags are between the tags) However if you want to always use theltwtgt tag by default set this option to false

You can always specify over which element you want to loop with the dash loop syntax

20 Chapter 7 Configuration

CHAPTER 8

Command Line Interface (CLI)

This section is about the commandline interface of docxtemplater

The syntax is the following

docxtemplater configjson

The full configjson should be something like that

configdocxFileinputdocxconfigoutputFileoutputdocxconfigqrcodetrueconfigdebugtruefirst_nameJohnlast_nameSmithage62

81 Configjson Syntax

811 Config properties

These are the properties to configure docxtemplater

configdocxFileinputdocx The input file pathconfigoutputFileoutputdocx The output file pathconfigqrcodetrue whether the images should be scanned to replace them by qrcodes (slows down the cli a lot)configdebugtrue whether to show debug output or not

812 Data properties

To add data to your template just use keys that donrsquot start with ldquoconfigrdquo

first_nameJohnlast_nameSmithage62

21

docxtemplater Documentation Release 054

22 Chapter 8 Command Line Interface (CLI)

CHAPTER 9

Full Documentation per method

91 Creating a new Docxgen Object

new DocxGen()

This function returns a new DocxGen Object

new DocxGen(content[Tagsoptions])

contentType stringThe docx template you want to load as plain text

TagsType Object tag_nametag_replacement []Object containing for each tag_name the replacement for this tag For example if you want to replace firstName by David your Object will be firstNameDavid

options object

parserType functionA custom parser to use See angularjs like parsing

intelligentTaggingType boolean [false]If intelligent Tagging is not set to true when using recursive tags (tag and tag) the system will copy paste what is between the start tag and the endtag this could basically corrupt the files if recursive tags are used inside tablesIf intelligent Tagging is set to true and when using recursive tags inside tables the whole column will be copy pasted

qrCodeType boolean [false]If qrCode is set to true DocxGen will look at all the images to find a Qr-Code If the Qr-code matches to a URL this URL will be loaded by ajax (Be aware that the server you want to access needs to allow your request or it wonrsquot work httpstackoverflowcomquestions9310112why-am-i-seeing-an-origin-is-not-allowed-by-access-control-allow-origin-error )

Important the qrCode functionality only works for PNG I donrsquot think I will enable this for other fileformats in the near future

localImageCreatorType function(argcallback) [function that returns an arrow]The function has to be customized only if you want to use the qrCode options (qrCode=true) When the qrcode text starts with gen the image is not going to be loaded by url but DocxGen calls localImageCreator with arg=full Text decoded The callback needs to be called with the image Datacallback(result) in plaintxt format (if you want to create it from a Data-URI you can use JSZipBase64decode(data) to decode a Data-URI to plaintxt)

The default localImageCreator returns a red arrow no matter what the arguments are

localImageCreator= (argcallback) -gtresult=JSZipBase64decode(iVBORw0KGgoAAAANSUhEUgAAABcAAAAXCAIAAABvSEP3AAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAACXSURBVDhPtY7BDYAwDAMZhCf7b8YMxeCoatOQJhWcKGxT2zlCyaWcz8Y+X7Bs1TFVJSwIHIYyFkQufWIRVX9cNJyW1QpEo4rixaEe7JuQagAUctb7ZFYFh5MVJPBe84CVBnB42YsZRgKjFDBVg3cI9WbRwXLktQJX8cNIiFhM1ZuTWk7PIYSBhkVcLzwIiCjCxhCjlAkBqYnqFoQQ2AAAAAElFTkSuQmCC)

23

docxtemplater Documentation Release 054

[Default Image](dataimagepngbase64iVBORw0KGgoAAAANSUhEUgAAABcAAAAXCAIAAABvSEP3AAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAACXSURBVDhPtY7BDYAwDAMZhCf7b8YMxeCoatOQJhWcKGxT2zlCyaWcz8Y+X7Bs1TFVJSwIHIYyFkQufWIRVX9cNJyW1QpEo4rixaEe7JuQagAUctb7ZFYFh5MVJPBe84CVBnB42YsZRgKjFDBVg3cI9WbRwXLktQJX8cNIiFhM1ZuTWk7PIYSBhkVcLzwIiCjCxhCjlAkBqYnqFoQQ2AAAAAElFTkSuQmCC)

qrFinishedCallBackType function () [function that consolelog(ready)]

This function is called if you specify qrCode argument to true in this constructor and will be called when all qrCodes have been replaced (because the qrCode replacing functions are async)

92 Docxgen methods

load(content)

contentType stringThe docx template you want to load as plain text

loadFromFile(path)path

Type stringLoads a docx from a file path

setTags(Tags)

TagsType Object tag_nametag_replacementObject containing for each tag_name the replacement for this tag For example if you want to replace firstName by David your Object will be firstNameDavid

applyTags([Tags])Tags

Type Object tag_nametag_replacementsame as setTagsDefaultthisTags

This function replaces all template variables by their values

output([options])

options object[]

nameTypestring[outputdocx]The name of the file that will be outputed (doesnt work in the browser because of dataUri download)

callbackTypefunctionFunction that is called without arguments when the output is done Is used only in Node (because in the browser the operation is synchronous)

downloadTypeboolean[true]If download is true file will be downloaded automatically with data URIreturns the output file

typeTypestring[base64]The type of zip to return The possible values are (same as in httpstukgithubiojszip generate)base64 (default) the result will be a string the binary in a base64 formstring the result will be a string in binary form 1 byte per charuint8array the result will be a Uint8Array containing the zip This requires a compatible browser

24 Chapter 9 Full Documentation per method

docxtemplater Documentation Release 054

arraybuffer the result will be a ArrayBuffer containing the zip This requires a compatible browserblob the result will be a Blob containing the zip This requires a compatible browsernodebuffer the result will be a nodejs Buffer containing the zip This requires nodejs

This function creates the docx file and downloads it on the userrsquos computer The name of the file is downloaddocx for Chrome and some akward file names for Firefox VEeTHCfSdocxpartdocx and canrsquot be changed because it is handled by the browserFor more informations about how to solve this problem see the Filename Problems section on [httpstukgithubiojszip](httpstukgithubiojszip)

Note All browsers donrsquot support the download of big files with Data URI so you should use the lsquodownloadlsquo method for files bigger than 100kB dataimagepngbase64iVBORw0KGgoAAAANSUhEUgAAABcAAAAXCAIAAABvSEP3AAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAACXSURBVDhPtY7BDYAwDAMZhCf7b8YMxeCoatOQJhWcKGxT2zlCyaWcz8Y+X7Bs1TFVJSwIHIYyFkQufWIRVX9cNJyW1QpEo4rixaEe7JuQagAUctb7ZFYFh5MVJPBe84CVBnB42YsZRgKjFDBVg3cI9WbRwXLktQJX8cNIiFhM1ZuTWk7PIYSBhkVcLzwIiCjCxhCjlAkBqYnqFoQQ2AAAAAElFTkSuQmCC

download(swfpathimgpath[fileName])

swfpathTypestringPath to the swfobjectjs in downloadify

imgpathTypestringPath to the image of the download button

[fileName]TypestringDefaultdefaultdocxName of the file you would like the user to download

This requires to include Downloadifyjs that needs flash version 10 Have a look at the output function if you donrsquot want to depend on it This function has the advantage that it works regardless of the file size

getImageList()

this gets all images that have one of the following extension rsquogifrsquorsquojpegrsquorsquojpgrsquorsquoemfrsquorsquopngrsquoReturn format Array of Object[pathstringfilesZipFile Object]

You shouldrsquont call this method before calling applyTags() because applyTags can modify the images or their path when replacing images with other (particularly when qrCode is set to true which is not the default case) You can call this method after applyTags() without any problems

setImage(pathimgData)

pathTypeStringPath of the image given by getImageList()

imgDataTypeStringimgData in txtplain

This sets the image given by a path and an imgData in txtplainYou shouldrsquont call this method before calling applyTags() because applyTags can modify the images or their path when replacing images with other (particularly when qrCode is set to true which is not the default case) You can call this method after applyTags() without any problems

getFullText([path])

pathTypeStringDefaultworddocumentxmlThis argument determines from which document you want to get the text The main document is called worddocumentxml but they are other documents wordheader1xml wordfooter1xml

returnsTypeStringThe string containing all the text from the document

92 Docxgen methods 25

docxtemplater Documentation Release 054

This method gets only the text of a given document (not the formatting)

getTags()

This function returns the template variables contained in the opened document For example if the content of the documentxml is the following

namefirst_namephone

The function will return[

filenamedocumentxmlvars

nametruefirst_nametruephonetrue

]

If the content contains tagLoops

titlecustomernamephonecustomer

The function will return

[filenamedocumentxmlvars

titletruecustomer

nametruephonetrue

]

26 Chapter 9 Full Documentation per method

CHAPTER 10

Copyright

License

(The MIT license)

Copyright (c) 2013 Edgar Hipp

Permission is hereby granted free of charge to any person obtaining a copy of this software and associated documen-tation files (the ldquoSoftwarerdquo) to deal in the Software without restriction including without limitation the rights to usecopy modify merge publish distribute sublicense andor sell copies of the Software and to permit persons to whomthe Software is furnished to do so subject to the following conditions

The above copyright notice and this permission notice shall be included in all copies or substantial portions of theSoftware

THE SOFTWARE IS PROVIDED ldquoAS ISrdquo WITHOUT WARRANTY OF ANY KIND EXPRESS OR IMPLIEDINCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY FITNESS FOR A PAR-TICULAR PURPOSE AND NONINFRINGEMENT IN NO EVENT SHALL THE AUTHORS OR COPYRIGHTHOLDERS BE LIABLE FOR ANY CLAIM DAMAGES OR OTHER LIABILITY WHETHER IN AN ACTIONOF CONTRACT TORT OR OTHERWISE ARISING FROM OUT OF OR IN CONNECTION WITH THE SOFT-WARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE

27

docxtemplater Documentation Release 054

28 Chapter 10 Copyright

CHAPTER 11

Demos

Including

bull Replace Variables

bull Formating

bull Angular Parsing

bull Loops

bull Loops and tables

bull Lists

bull Replacing images

bull Naming the output

bull Using QrCodes

bull Replacing many images with QrCode

bull Raw Xml Insertion

29

docxtemplater Documentation Release 054

30 Chapter 11 Demos

CHAPTER 12

Indices and tables

bull genindex

bull modindex

bull search

31

docxtemplater Documentation Release 054

32 Chapter 12 Indices and tables

Index

CCommand Line Interface (CLI) 20Configuration 17Copyright 26

FFull_doc 21

GGenerate a Document 13Goals 1

IInstallation 7

Pplatform_support 3

SSyntax 9

33

  • Goals
    • Why you should use a library for this
      • Platform Support
      • Dependencies
      • Installation
        • Node
        • Browser
          • Syntax
            • Synopsis
            • Tag types
            • Loop syntax
            • Dash syntax
            • Inverted Selections
              • Generate a document
                • Loading a document
                • Setting the tags
                • Applying the tags
                • Outputing the document
                  • Configuration
                    • Image Replacing
                    • Angular Parser
                    • Intelligent LoopTagging
                      • Command Line Interface (CLI)
                        • Configjson Syntax
                          • Full Documentation per method
                            • Creating a new Docxgen Object
                            • Docxgen methods
                              • Copyright
                              • Demos
                              • Indices and tables
Page 4: Release 0.5€¦ · Docx is a zipped format that contains some xml. If you want to build a simple replace {tag} If you want to build a simple replace {tag} by value system, it can

docxtemplater Documentation Release 054

Contents

Contents 1

docxtemplater Documentation Release 054

2 Contents

CHAPTER 1

Goals

Docxtemplater was born out of the idea that you should be able to generate Docx as easily as you generate Html withsomething like Mustache

They are a lots of solutions like docxjs docx4j that generate docx but you will have to write specific code tocreate a title an image

I think this is a waste when you can just write your template with plain old Microsoft Word

Docxtemplater is just there for that

11 Why you should use a library for this

Docx is a zipped format that contains some xml If you want to build a simple replace tagby value system it can already become complicated because the tag is internally separated intoltwtgtltwtgtltwtgttagltwtgtltwtgtltwtgt If you want to embed loops to iterate over an array it becomes areal hassle

3

docxtemplater Documentation Release 054

4 Chapter 1 Goals

CHAPTER 2

Platform Support

docxtemplater works with

bull Nodejs with 010 and 011

bull Chrome tested on version 26

bull Firefox 3+ (tested on version 21 but should work with 3+)

bull Safari not tested

Internet explorer is not supported -even IE10- (basically because xhr Requests canrsquot be made on binary files)

You can test if everything works fine on your browser by using the test runner httpjavascript-ninjafrdocxgenjstestSpecRunnerhtml

Firefox has an other implementation of the xml parser thatrsquos why all tests donrsquot pass now However all of thefunctionality works on Firefox too The output files are not exactly the same byte wise but the generated XML iscorrect

5

docxtemplater Documentation Release 054

6 Chapter 2 Platform Support

CHAPTER 3

Dependencies

1 docxgenjs uses [jszipjs](httpstukgithubiojszip) to zip and unzip the docx files

2 Optionally if you want to be able to name the output files you can use Downloadifyjs which is requiredto use method download Be informed that it uses flash this is why the method is not recommended Thismethod is howewer useful because a lot of browsers are limited for the download size with the Data-URImethod Update I will probably implement in the future a way to use the FileSaver API with [File-SaverJS](httpeligreycomdemosFileSaverjs)

3 Optionnaly if you want to replace images by images situated at a particular URL you can use QR codes Forexample If you store an image at httpwebsitecomimagepng you should encode the URL in QR-Code for-mat [Qr Code Sample](httpqrfreekaywacoml=1amps=8ampd=http3A2F2Fwebsitecom2FimagepngldquoQrcode Sample to httpwebsitecomimagepngrdquo) You can even use bracket tags in imageshttpwebsitecomimagepngcolor=color will take the Tags[color] variable to make a dynamic URL Forthis too work you will need [jsqrcode](httpgithubcomedi9999jsqrcode ldquojsqrcode repositoty forkedrdquo) andinclude the following files in this order (only for browser support node support already comes out of the box)

ltscript type=textjavascript src=gridjsgtltscriptgtltscript type=textjavascript src=versionjsgtltscriptgtltscript type=textjavascript src=detectorjsgtltscriptgtltscript type=textjavascript src=formatinfjsgtltscriptgtltscript type=textjavascript src=errorleveljsgtltscriptgtltscript type=textjavascript src=bitmatjsgtltscriptgtltscript type=textjavascript src=datablockjsgtltscriptgtltscript type=textjavascript src=bmparserjsgtltscriptgtltscript type=textjavascript src=datamaskjsgtltscriptgtltscript type=textjavascript src=rsdecoderjsgtltscriptgtltscript type=textjavascript src=gf256polyjsgtltscriptgtltscript type=textjavascript src=gf256jsgtltscriptgtltscript type=textjavascript src=decoderjsgtltscriptgtltscript type=textjavascript src=qrcodejsgtltscriptgtltscript type=textjavascript src=findpatjsgtltscriptgtltscript type=textjavascript src=alignpatjsgtltscriptgtltscript type=textjavascript src=databrjsgtltscriptgt

7

docxtemplater Documentation Release 054

8 Chapter 3 Dependencies

CHAPTER 4

Installation

41 Node

To install docxtemplater we recommend you to use npm

npm install docxtemplater

If you want to use the command line interface you should use the global flag eg

npm install docxtemplater -g

42 Browser

You will just have to include the docxgenjs or docxgenminjs file

9

docxtemplater Documentation Release 054

10 Chapter 4 Installation

CHAPTER 5

Syntax

The syntax is highly inspired by Mustache The template is created in Microsoft Word or any equivalent that saves todocx

51 Synopsis

A typical docxtemplater template

Hello name

Given the following hash

namersquoEdgarrsquo

Will produce

Hello Edgar

52 Tag types

Like Mustache it has the loopopening and loopclosing brackets

53 Loop syntax

The following template

productsname price C

products

Given the following hash

products

[nameWindowsprice100

11

docxtemplater Documentation Release 054

nameMac OSXprice200nameUbuntuprice0]

will result in

Windows 100 CMac OSX 200 CUbuntu 0C

The loop behaves in the following way

bull If the value is an array it will loop over all the elements of that array

bull If the value is a boolean it will loop once if the value is true keeping the same scope and not loop at all if thevalue is false

Note Because the loops work also with boolean values you can also use them for conditions

54 Dash syntax

It is quite difficult to know on which element you are going to loop By default when using the for loop docxgen willfind that by himself

If between the two tags tag______tag

bull they is the Xml Tag ltwtcgt -gt you are in a table and it will loop over ltwtrgt

bull else -gt it will loop over ltwtgt which is the default Text Tag

With the Dash syntax you pass as a first argument the tag you want to loop on

-wp loop inner loop

In this case this will loop over the first parent ltwpgt tag

55 Inverted Selections

An inverted section begins with a caret (hat) and ends with a slash That is ^person begins a ldquopersonrdquo invertedsection while person ends it

While sections can be used to render text one or more times based on the value of the key inverted sections may rendertext once based on the inverse value of the key That is they will be rendered if the key doesnrsquot exist is false or is anempty list

Template

repoltbgtnameltbgt

repo^repo

No repos (repo

Hash

12 Chapter 5 Syntax

docxtemplater Documentation Release 054

repo []

Output

No repos (

55 Inverted Selections 13

docxtemplater Documentation Release 054

14 Chapter 5 Syntax

CHAPTER 6

Generate a document

Herersquos a sample code to generate a document

DocxGen=require(rsquodocxtemplaterrsquo) Only for Node Usagenew DocxGen()loadFromFile(tagExampledocxasynctrue)success(function(doc)

docsetTags(first_nameHipp

last_nameEdgarphone0652455478descriptionNew Website

) set the templateVariablesdocapplyTags() apply them (replace all occurences of first_name by Hipp )docoutput() Output the document using Data-URI

)

The different steps are the following

61 Loading a document

A docx can be loaded by itrsquos base64 representation like this

doc=new DocxGen(base64Dataoptions)

However loading the base64Data is not that easy so I created a wrapper function to load a docx from a file via Ajax

Note The options parameter are explained in Configuration

doc=new DocxGen()loadFromFile(documentPathoptions)

The documentPath is the path to the document you want to load The options are the same as in the constructorfunction and Irsquove added the async parameter

bull If async is true the document is loaded asynchronously and returns a promise (eg you can write suc-cess(callback) to get when the document is loaded)

bull If async is false the document is loaded synchronously and returns the document

62 Setting the tags

The tags are the variables that are going to be replaced by their values To set them just use

15

docxtemplater Documentation Release 054

docsetTags(tags)

63 Applying the tags

Applying the tags means opening all files that contain text (eg footer header main document) and replace thevariables by their values

docapplyTags(tags)

Note If you specify an argument for the applyTags method the function setTags(tags) will be called before applyingthe tags

64 Outputing the document

They are several ways to output the document The most basic usage is to download the document

docoutput(options)

Depending on your environment if you donrsquot set any options this will

bull In the browser Download the document using DataURI

bull In Node Save the document with the given fileName (outputdocx by default)

Herersquos the different options parameters

nameTypestring[outputdocx]The name of the file that will be outputed (doesnt work in the browser because of dataUri download)

callbackTypefunctionFunction that is called without arguments when the output is done Is used only in Node (because in the browser the operation is synchronous)

downloadTypeboolean[true]If download is true file will be downloaded automatically with data URIreturns the output file

typeTypestring[base64]The type of zip to return The possible values are (same as in httpstukgithubiojszip generate)base64 (default) the result will be a string the binary in a base64 formstring the result will be a string in binary form 1 byte per charuint8array the result will be a Uint8Array containing the zip This requires a compatible browserarraybuffer the result will be a ArrayBuffer containing the zip This requires a compatible browserblob the result will be a Blob containing the zip This requires a compatible browsernodebuffer the result will be a nodejs Buffer containing the zip This requires nodejs

This function creates the docx file and downloads it on the userrsquos computer The name of the file is downloaddocxfor Chrome and some akward file names for Firefox VEeTHCfSdocxpartdocx and canrsquot be changed because it ishandled by the browser For more informations about how to solve this problem see the Filename Problems sectionon [httpstukgithubiojszip](httpstukgithubiojszip)

16 Chapter 6 Generate a document

docxtemplater Documentation Release 054

Note Note All browsers donrsquot support the download of big files withData URI so you should use the download method for files bigger than 100kBdataimagepngbase64iVBORw0KGgoAAAANSUhEUgAAABcAAAAXCAIAAABvSEP3AAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAACXSURBVDhPtY7BDYAwDAMZhCf7b8YMxeCoatOQJhWcKGxT2zlCyaWcz8Y+X7Bs1TFVJSwIHIYyFkQufWIRVX9cNJyW1QpEo4rixaEe7JuQagAUctb7ZFYFh5MVJPBe84CVBnB42YsZRgKjFDBVg3cI9WbRwXLktQJX8cNIiFhM1ZuTWk7PIYSBhkVcLzwIiCjCxhCjlAkBqYnqFoQQ2AAAAAElFTkSuQmCC

In Node to send the document to the client you can write the following code snippet

out=docoutput(downloadfalsetypestring)ressend(new Buffer(outbinary))

64 Outputing the document 17

docxtemplater Documentation Release 054

18 Chapter 6 Generate a document

CHAPTER 7

Configuration

Here are documented the special options that you can set when creating a new DocxGen to get some more superpower

It documents the options parameter when you do

new DocxGen(dataoptions)

71 Image Replacing

The name of this option qrCode (boolean)

To stay a templating engine I wanted that DocxTemplater doesnrsquot add an image from scratch but rather uses anexisting image that can be detected and DocxTemplater will just change the contents of that image without changingitrsquos style The size of the replaced images will stay the same

So I decided to use the qrCode format which is a format that lets you identify images by their content

The option for this is qrCode (true for on false for off default off)

Note If you donrsquot use that functionality you should disable it because it is quite slow (the image decoding)

Warning The qrCode functionality only works for PNG They is no support for other file formats yet

72 Angular Parser

The name of this option parser (function)

You can set the angular parser with the following code

With a custom parser you can parse the tags to for example add operators like lsquo+rsquo lsquo-lsquo or whatever the way you wantto parse expressions

To enable this you need to specify a custom parser You need to create a parser function

docxtemplater comes shipped with this parser

parser=function(expression)

return

19

docxtemplater Documentation Release 054

getfunction(scope) return scope[expression]

To use the angular-parser do the following

expressions= require(rsquoangular-expressionsrsquo)angularParser= function(tag)

return getexpressionscompile(tag)

new DocxGen(dataparserangularParser)

Note The require() works in the browser if you include vendorangular-parser-browserjs

73 Intelligent LoopTagging

The name of this option intelligentTagging (boolean)

When looping over an element docxtemplater needs to know over which element you want to loop By default it triesto do that intelligently (by looking what XML Tags are between the tags) However if you want to always use theltwtgt tag by default set this option to false

You can always specify over which element you want to loop with the dash loop syntax

20 Chapter 7 Configuration

CHAPTER 8

Command Line Interface (CLI)

This section is about the commandline interface of docxtemplater

The syntax is the following

docxtemplater configjson

The full configjson should be something like that

configdocxFileinputdocxconfigoutputFileoutputdocxconfigqrcodetrueconfigdebugtruefirst_nameJohnlast_nameSmithage62

81 Configjson Syntax

811 Config properties

These are the properties to configure docxtemplater

configdocxFileinputdocx The input file pathconfigoutputFileoutputdocx The output file pathconfigqrcodetrue whether the images should be scanned to replace them by qrcodes (slows down the cli a lot)configdebugtrue whether to show debug output or not

812 Data properties

To add data to your template just use keys that donrsquot start with ldquoconfigrdquo

first_nameJohnlast_nameSmithage62

21

docxtemplater Documentation Release 054

22 Chapter 8 Command Line Interface (CLI)

CHAPTER 9

Full Documentation per method

91 Creating a new Docxgen Object

new DocxGen()

This function returns a new DocxGen Object

new DocxGen(content[Tagsoptions])

contentType stringThe docx template you want to load as plain text

TagsType Object tag_nametag_replacement []Object containing for each tag_name the replacement for this tag For example if you want to replace firstName by David your Object will be firstNameDavid

options object

parserType functionA custom parser to use See angularjs like parsing

intelligentTaggingType boolean [false]If intelligent Tagging is not set to true when using recursive tags (tag and tag) the system will copy paste what is between the start tag and the endtag this could basically corrupt the files if recursive tags are used inside tablesIf intelligent Tagging is set to true and when using recursive tags inside tables the whole column will be copy pasted

qrCodeType boolean [false]If qrCode is set to true DocxGen will look at all the images to find a Qr-Code If the Qr-code matches to a URL this URL will be loaded by ajax (Be aware that the server you want to access needs to allow your request or it wonrsquot work httpstackoverflowcomquestions9310112why-am-i-seeing-an-origin-is-not-allowed-by-access-control-allow-origin-error )

Important the qrCode functionality only works for PNG I donrsquot think I will enable this for other fileformats in the near future

localImageCreatorType function(argcallback) [function that returns an arrow]The function has to be customized only if you want to use the qrCode options (qrCode=true) When the qrcode text starts with gen the image is not going to be loaded by url but DocxGen calls localImageCreator with arg=full Text decoded The callback needs to be called with the image Datacallback(result) in plaintxt format (if you want to create it from a Data-URI you can use JSZipBase64decode(data) to decode a Data-URI to plaintxt)

The default localImageCreator returns a red arrow no matter what the arguments are

localImageCreator= (argcallback) -gtresult=JSZipBase64decode(iVBORw0KGgoAAAANSUhEUgAAABcAAAAXCAIAAABvSEP3AAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAACXSURBVDhPtY7BDYAwDAMZhCf7b8YMxeCoatOQJhWcKGxT2zlCyaWcz8Y+X7Bs1TFVJSwIHIYyFkQufWIRVX9cNJyW1QpEo4rixaEe7JuQagAUctb7ZFYFh5MVJPBe84CVBnB42YsZRgKjFDBVg3cI9WbRwXLktQJX8cNIiFhM1ZuTWk7PIYSBhkVcLzwIiCjCxhCjlAkBqYnqFoQQ2AAAAAElFTkSuQmCC)

23

docxtemplater Documentation Release 054

[Default Image](dataimagepngbase64iVBORw0KGgoAAAANSUhEUgAAABcAAAAXCAIAAABvSEP3AAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAACXSURBVDhPtY7BDYAwDAMZhCf7b8YMxeCoatOQJhWcKGxT2zlCyaWcz8Y+X7Bs1TFVJSwIHIYyFkQufWIRVX9cNJyW1QpEo4rixaEe7JuQagAUctb7ZFYFh5MVJPBe84CVBnB42YsZRgKjFDBVg3cI9WbRwXLktQJX8cNIiFhM1ZuTWk7PIYSBhkVcLzwIiCjCxhCjlAkBqYnqFoQQ2AAAAAElFTkSuQmCC)

qrFinishedCallBackType function () [function that consolelog(ready)]

This function is called if you specify qrCode argument to true in this constructor and will be called when all qrCodes have been replaced (because the qrCode replacing functions are async)

92 Docxgen methods

load(content)

contentType stringThe docx template you want to load as plain text

loadFromFile(path)path

Type stringLoads a docx from a file path

setTags(Tags)

TagsType Object tag_nametag_replacementObject containing for each tag_name the replacement for this tag For example if you want to replace firstName by David your Object will be firstNameDavid

applyTags([Tags])Tags

Type Object tag_nametag_replacementsame as setTagsDefaultthisTags

This function replaces all template variables by their values

output([options])

options object[]

nameTypestring[outputdocx]The name of the file that will be outputed (doesnt work in the browser because of dataUri download)

callbackTypefunctionFunction that is called without arguments when the output is done Is used only in Node (because in the browser the operation is synchronous)

downloadTypeboolean[true]If download is true file will be downloaded automatically with data URIreturns the output file

typeTypestring[base64]The type of zip to return The possible values are (same as in httpstukgithubiojszip generate)base64 (default) the result will be a string the binary in a base64 formstring the result will be a string in binary form 1 byte per charuint8array the result will be a Uint8Array containing the zip This requires a compatible browser

24 Chapter 9 Full Documentation per method

docxtemplater Documentation Release 054

arraybuffer the result will be a ArrayBuffer containing the zip This requires a compatible browserblob the result will be a Blob containing the zip This requires a compatible browsernodebuffer the result will be a nodejs Buffer containing the zip This requires nodejs

This function creates the docx file and downloads it on the userrsquos computer The name of the file is downloaddocx for Chrome and some akward file names for Firefox VEeTHCfSdocxpartdocx and canrsquot be changed because it is handled by the browserFor more informations about how to solve this problem see the Filename Problems section on [httpstukgithubiojszip](httpstukgithubiojszip)

Note All browsers donrsquot support the download of big files with Data URI so you should use the lsquodownloadlsquo method for files bigger than 100kB dataimagepngbase64iVBORw0KGgoAAAANSUhEUgAAABcAAAAXCAIAAABvSEP3AAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAACXSURBVDhPtY7BDYAwDAMZhCf7b8YMxeCoatOQJhWcKGxT2zlCyaWcz8Y+X7Bs1TFVJSwIHIYyFkQufWIRVX9cNJyW1QpEo4rixaEe7JuQagAUctb7ZFYFh5MVJPBe84CVBnB42YsZRgKjFDBVg3cI9WbRwXLktQJX8cNIiFhM1ZuTWk7PIYSBhkVcLzwIiCjCxhCjlAkBqYnqFoQQ2AAAAAElFTkSuQmCC

download(swfpathimgpath[fileName])

swfpathTypestringPath to the swfobjectjs in downloadify

imgpathTypestringPath to the image of the download button

[fileName]TypestringDefaultdefaultdocxName of the file you would like the user to download

This requires to include Downloadifyjs that needs flash version 10 Have a look at the output function if you donrsquot want to depend on it This function has the advantage that it works regardless of the file size

getImageList()

this gets all images that have one of the following extension rsquogifrsquorsquojpegrsquorsquojpgrsquorsquoemfrsquorsquopngrsquoReturn format Array of Object[pathstringfilesZipFile Object]

You shouldrsquont call this method before calling applyTags() because applyTags can modify the images or their path when replacing images with other (particularly when qrCode is set to true which is not the default case) You can call this method after applyTags() without any problems

setImage(pathimgData)

pathTypeStringPath of the image given by getImageList()

imgDataTypeStringimgData in txtplain

This sets the image given by a path and an imgData in txtplainYou shouldrsquont call this method before calling applyTags() because applyTags can modify the images or their path when replacing images with other (particularly when qrCode is set to true which is not the default case) You can call this method after applyTags() without any problems

getFullText([path])

pathTypeStringDefaultworddocumentxmlThis argument determines from which document you want to get the text The main document is called worddocumentxml but they are other documents wordheader1xml wordfooter1xml

returnsTypeStringThe string containing all the text from the document

92 Docxgen methods 25

docxtemplater Documentation Release 054

This method gets only the text of a given document (not the formatting)

getTags()

This function returns the template variables contained in the opened document For example if the content of the documentxml is the following

namefirst_namephone

The function will return[

filenamedocumentxmlvars

nametruefirst_nametruephonetrue

]

If the content contains tagLoops

titlecustomernamephonecustomer

The function will return

[filenamedocumentxmlvars

titletruecustomer

nametruephonetrue

]

26 Chapter 9 Full Documentation per method

CHAPTER 10

Copyright

License

(The MIT license)

Copyright (c) 2013 Edgar Hipp

Permission is hereby granted free of charge to any person obtaining a copy of this software and associated documen-tation files (the ldquoSoftwarerdquo) to deal in the Software without restriction including without limitation the rights to usecopy modify merge publish distribute sublicense andor sell copies of the Software and to permit persons to whomthe Software is furnished to do so subject to the following conditions

The above copyright notice and this permission notice shall be included in all copies or substantial portions of theSoftware

THE SOFTWARE IS PROVIDED ldquoAS ISrdquo WITHOUT WARRANTY OF ANY KIND EXPRESS OR IMPLIEDINCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY FITNESS FOR A PAR-TICULAR PURPOSE AND NONINFRINGEMENT IN NO EVENT SHALL THE AUTHORS OR COPYRIGHTHOLDERS BE LIABLE FOR ANY CLAIM DAMAGES OR OTHER LIABILITY WHETHER IN AN ACTIONOF CONTRACT TORT OR OTHERWISE ARISING FROM OUT OF OR IN CONNECTION WITH THE SOFT-WARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE

27

docxtemplater Documentation Release 054

28 Chapter 10 Copyright

CHAPTER 11

Demos

Including

bull Replace Variables

bull Formating

bull Angular Parsing

bull Loops

bull Loops and tables

bull Lists

bull Replacing images

bull Naming the output

bull Using QrCodes

bull Replacing many images with QrCode

bull Raw Xml Insertion

29

docxtemplater Documentation Release 054

30 Chapter 11 Demos

CHAPTER 12

Indices and tables

bull genindex

bull modindex

bull search

31

docxtemplater Documentation Release 054

32 Chapter 12 Indices and tables

Index

CCommand Line Interface (CLI) 20Configuration 17Copyright 26

FFull_doc 21

GGenerate a Document 13Goals 1

IInstallation 7

Pplatform_support 3

SSyntax 9

33

  • Goals
    • Why you should use a library for this
      • Platform Support
      • Dependencies
      • Installation
        • Node
        • Browser
          • Syntax
            • Synopsis
            • Tag types
            • Loop syntax
            • Dash syntax
            • Inverted Selections
              • Generate a document
                • Loading a document
                • Setting the tags
                • Applying the tags
                • Outputing the document
                  • Configuration
                    • Image Replacing
                    • Angular Parser
                    • Intelligent LoopTagging
                      • Command Line Interface (CLI)
                        • Configjson Syntax
                          • Full Documentation per method
                            • Creating a new Docxgen Object
                            • Docxgen methods
                              • Copyright
                              • Demos
                              • Indices and tables
Page 5: Release 0.5€¦ · Docx is a zipped format that contains some xml. If you want to build a simple replace {tag} If you want to build a simple replace {tag} by value system, it can

docxtemplater Documentation Release 054

2 Contents

CHAPTER 1

Goals

Docxtemplater was born out of the idea that you should be able to generate Docx as easily as you generate Html withsomething like Mustache

They are a lots of solutions like docxjs docx4j that generate docx but you will have to write specific code tocreate a title an image

I think this is a waste when you can just write your template with plain old Microsoft Word

Docxtemplater is just there for that

11 Why you should use a library for this

Docx is a zipped format that contains some xml If you want to build a simple replace tagby value system it can already become complicated because the tag is internally separated intoltwtgtltwtgtltwtgttagltwtgtltwtgtltwtgt If you want to embed loops to iterate over an array it becomes areal hassle

3

docxtemplater Documentation Release 054

4 Chapter 1 Goals

CHAPTER 2

Platform Support

docxtemplater works with

bull Nodejs with 010 and 011

bull Chrome tested on version 26

bull Firefox 3+ (tested on version 21 but should work with 3+)

bull Safari not tested

Internet explorer is not supported -even IE10- (basically because xhr Requests canrsquot be made on binary files)

You can test if everything works fine on your browser by using the test runner httpjavascript-ninjafrdocxgenjstestSpecRunnerhtml

Firefox has an other implementation of the xml parser thatrsquos why all tests donrsquot pass now However all of thefunctionality works on Firefox too The output files are not exactly the same byte wise but the generated XML iscorrect

5

docxtemplater Documentation Release 054

6 Chapter 2 Platform Support

CHAPTER 3

Dependencies

1 docxgenjs uses [jszipjs](httpstukgithubiojszip) to zip and unzip the docx files

2 Optionally if you want to be able to name the output files you can use Downloadifyjs which is requiredto use method download Be informed that it uses flash this is why the method is not recommended Thismethod is howewer useful because a lot of browsers are limited for the download size with the Data-URImethod Update I will probably implement in the future a way to use the FileSaver API with [File-SaverJS](httpeligreycomdemosFileSaverjs)

3 Optionnaly if you want to replace images by images situated at a particular URL you can use QR codes Forexample If you store an image at httpwebsitecomimagepng you should encode the URL in QR-Code for-mat [Qr Code Sample](httpqrfreekaywacoml=1amps=8ampd=http3A2F2Fwebsitecom2FimagepngldquoQrcode Sample to httpwebsitecomimagepngrdquo) You can even use bracket tags in imageshttpwebsitecomimagepngcolor=color will take the Tags[color] variable to make a dynamic URL Forthis too work you will need [jsqrcode](httpgithubcomedi9999jsqrcode ldquojsqrcode repositoty forkedrdquo) andinclude the following files in this order (only for browser support node support already comes out of the box)

ltscript type=textjavascript src=gridjsgtltscriptgtltscript type=textjavascript src=versionjsgtltscriptgtltscript type=textjavascript src=detectorjsgtltscriptgtltscript type=textjavascript src=formatinfjsgtltscriptgtltscript type=textjavascript src=errorleveljsgtltscriptgtltscript type=textjavascript src=bitmatjsgtltscriptgtltscript type=textjavascript src=datablockjsgtltscriptgtltscript type=textjavascript src=bmparserjsgtltscriptgtltscript type=textjavascript src=datamaskjsgtltscriptgtltscript type=textjavascript src=rsdecoderjsgtltscriptgtltscript type=textjavascript src=gf256polyjsgtltscriptgtltscript type=textjavascript src=gf256jsgtltscriptgtltscript type=textjavascript src=decoderjsgtltscriptgtltscript type=textjavascript src=qrcodejsgtltscriptgtltscript type=textjavascript src=findpatjsgtltscriptgtltscript type=textjavascript src=alignpatjsgtltscriptgtltscript type=textjavascript src=databrjsgtltscriptgt

7

docxtemplater Documentation Release 054

8 Chapter 3 Dependencies

CHAPTER 4

Installation

41 Node

To install docxtemplater we recommend you to use npm

npm install docxtemplater

If you want to use the command line interface you should use the global flag eg

npm install docxtemplater -g

42 Browser

You will just have to include the docxgenjs or docxgenminjs file

9

docxtemplater Documentation Release 054

10 Chapter 4 Installation

CHAPTER 5

Syntax

The syntax is highly inspired by Mustache The template is created in Microsoft Word or any equivalent that saves todocx

51 Synopsis

A typical docxtemplater template

Hello name

Given the following hash

namersquoEdgarrsquo

Will produce

Hello Edgar

52 Tag types

Like Mustache it has the loopopening and loopclosing brackets

53 Loop syntax

The following template

productsname price C

products

Given the following hash

products

[nameWindowsprice100

11

docxtemplater Documentation Release 054

nameMac OSXprice200nameUbuntuprice0]

will result in

Windows 100 CMac OSX 200 CUbuntu 0C

The loop behaves in the following way

bull If the value is an array it will loop over all the elements of that array

bull If the value is a boolean it will loop once if the value is true keeping the same scope and not loop at all if thevalue is false

Note Because the loops work also with boolean values you can also use them for conditions

54 Dash syntax

It is quite difficult to know on which element you are going to loop By default when using the for loop docxgen willfind that by himself

If between the two tags tag______tag

bull they is the Xml Tag ltwtcgt -gt you are in a table and it will loop over ltwtrgt

bull else -gt it will loop over ltwtgt which is the default Text Tag

With the Dash syntax you pass as a first argument the tag you want to loop on

-wp loop inner loop

In this case this will loop over the first parent ltwpgt tag

55 Inverted Selections

An inverted section begins with a caret (hat) and ends with a slash That is ^person begins a ldquopersonrdquo invertedsection while person ends it

While sections can be used to render text one or more times based on the value of the key inverted sections may rendertext once based on the inverse value of the key That is they will be rendered if the key doesnrsquot exist is false or is anempty list

Template

repoltbgtnameltbgt

repo^repo

No repos (repo

Hash

12 Chapter 5 Syntax

docxtemplater Documentation Release 054

repo []

Output

No repos (

55 Inverted Selections 13

docxtemplater Documentation Release 054

14 Chapter 5 Syntax

CHAPTER 6

Generate a document

Herersquos a sample code to generate a document

DocxGen=require(rsquodocxtemplaterrsquo) Only for Node Usagenew DocxGen()loadFromFile(tagExampledocxasynctrue)success(function(doc)

docsetTags(first_nameHipp

last_nameEdgarphone0652455478descriptionNew Website

) set the templateVariablesdocapplyTags() apply them (replace all occurences of first_name by Hipp )docoutput() Output the document using Data-URI

)

The different steps are the following

61 Loading a document

A docx can be loaded by itrsquos base64 representation like this

doc=new DocxGen(base64Dataoptions)

However loading the base64Data is not that easy so I created a wrapper function to load a docx from a file via Ajax

Note The options parameter are explained in Configuration

doc=new DocxGen()loadFromFile(documentPathoptions)

The documentPath is the path to the document you want to load The options are the same as in the constructorfunction and Irsquove added the async parameter

bull If async is true the document is loaded asynchronously and returns a promise (eg you can write suc-cess(callback) to get when the document is loaded)

bull If async is false the document is loaded synchronously and returns the document

62 Setting the tags

The tags are the variables that are going to be replaced by their values To set them just use

15

docxtemplater Documentation Release 054

docsetTags(tags)

63 Applying the tags

Applying the tags means opening all files that contain text (eg footer header main document) and replace thevariables by their values

docapplyTags(tags)

Note If you specify an argument for the applyTags method the function setTags(tags) will be called before applyingthe tags

64 Outputing the document

They are several ways to output the document The most basic usage is to download the document

docoutput(options)

Depending on your environment if you donrsquot set any options this will

bull In the browser Download the document using DataURI

bull In Node Save the document with the given fileName (outputdocx by default)

Herersquos the different options parameters

nameTypestring[outputdocx]The name of the file that will be outputed (doesnt work in the browser because of dataUri download)

callbackTypefunctionFunction that is called without arguments when the output is done Is used only in Node (because in the browser the operation is synchronous)

downloadTypeboolean[true]If download is true file will be downloaded automatically with data URIreturns the output file

typeTypestring[base64]The type of zip to return The possible values are (same as in httpstukgithubiojszip generate)base64 (default) the result will be a string the binary in a base64 formstring the result will be a string in binary form 1 byte per charuint8array the result will be a Uint8Array containing the zip This requires a compatible browserarraybuffer the result will be a ArrayBuffer containing the zip This requires a compatible browserblob the result will be a Blob containing the zip This requires a compatible browsernodebuffer the result will be a nodejs Buffer containing the zip This requires nodejs

This function creates the docx file and downloads it on the userrsquos computer The name of the file is downloaddocxfor Chrome and some akward file names for Firefox VEeTHCfSdocxpartdocx and canrsquot be changed because it ishandled by the browser For more informations about how to solve this problem see the Filename Problems sectionon [httpstukgithubiojszip](httpstukgithubiojszip)

16 Chapter 6 Generate a document

docxtemplater Documentation Release 054

Note Note All browsers donrsquot support the download of big files withData URI so you should use the download method for files bigger than 100kBdataimagepngbase64iVBORw0KGgoAAAANSUhEUgAAABcAAAAXCAIAAABvSEP3AAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAACXSURBVDhPtY7BDYAwDAMZhCf7b8YMxeCoatOQJhWcKGxT2zlCyaWcz8Y+X7Bs1TFVJSwIHIYyFkQufWIRVX9cNJyW1QpEo4rixaEe7JuQagAUctb7ZFYFh5MVJPBe84CVBnB42YsZRgKjFDBVg3cI9WbRwXLktQJX8cNIiFhM1ZuTWk7PIYSBhkVcLzwIiCjCxhCjlAkBqYnqFoQQ2AAAAAElFTkSuQmCC

In Node to send the document to the client you can write the following code snippet

out=docoutput(downloadfalsetypestring)ressend(new Buffer(outbinary))

64 Outputing the document 17

docxtemplater Documentation Release 054

18 Chapter 6 Generate a document

CHAPTER 7

Configuration

Here are documented the special options that you can set when creating a new DocxGen to get some more superpower

It documents the options parameter when you do

new DocxGen(dataoptions)

71 Image Replacing

The name of this option qrCode (boolean)

To stay a templating engine I wanted that DocxTemplater doesnrsquot add an image from scratch but rather uses anexisting image that can be detected and DocxTemplater will just change the contents of that image without changingitrsquos style The size of the replaced images will stay the same

So I decided to use the qrCode format which is a format that lets you identify images by their content

The option for this is qrCode (true for on false for off default off)

Note If you donrsquot use that functionality you should disable it because it is quite slow (the image decoding)

Warning The qrCode functionality only works for PNG They is no support for other file formats yet

72 Angular Parser

The name of this option parser (function)

You can set the angular parser with the following code

With a custom parser you can parse the tags to for example add operators like lsquo+rsquo lsquo-lsquo or whatever the way you wantto parse expressions

To enable this you need to specify a custom parser You need to create a parser function

docxtemplater comes shipped with this parser

parser=function(expression)

return

19

docxtemplater Documentation Release 054

getfunction(scope) return scope[expression]

To use the angular-parser do the following

expressions= require(rsquoangular-expressionsrsquo)angularParser= function(tag)

return getexpressionscompile(tag)

new DocxGen(dataparserangularParser)

Note The require() works in the browser if you include vendorangular-parser-browserjs

73 Intelligent LoopTagging

The name of this option intelligentTagging (boolean)

When looping over an element docxtemplater needs to know over which element you want to loop By default it triesto do that intelligently (by looking what XML Tags are between the tags) However if you want to always use theltwtgt tag by default set this option to false

You can always specify over which element you want to loop with the dash loop syntax

20 Chapter 7 Configuration

CHAPTER 8

Command Line Interface (CLI)

This section is about the commandline interface of docxtemplater

The syntax is the following

docxtemplater configjson

The full configjson should be something like that

configdocxFileinputdocxconfigoutputFileoutputdocxconfigqrcodetrueconfigdebugtruefirst_nameJohnlast_nameSmithage62

81 Configjson Syntax

811 Config properties

These are the properties to configure docxtemplater

configdocxFileinputdocx The input file pathconfigoutputFileoutputdocx The output file pathconfigqrcodetrue whether the images should be scanned to replace them by qrcodes (slows down the cli a lot)configdebugtrue whether to show debug output or not

812 Data properties

To add data to your template just use keys that donrsquot start with ldquoconfigrdquo

first_nameJohnlast_nameSmithage62

21

docxtemplater Documentation Release 054

22 Chapter 8 Command Line Interface (CLI)

CHAPTER 9

Full Documentation per method

91 Creating a new Docxgen Object

new DocxGen()

This function returns a new DocxGen Object

new DocxGen(content[Tagsoptions])

contentType stringThe docx template you want to load as plain text

TagsType Object tag_nametag_replacement []Object containing for each tag_name the replacement for this tag For example if you want to replace firstName by David your Object will be firstNameDavid

options object

parserType functionA custom parser to use See angularjs like parsing

intelligentTaggingType boolean [false]If intelligent Tagging is not set to true when using recursive tags (tag and tag) the system will copy paste what is between the start tag and the endtag this could basically corrupt the files if recursive tags are used inside tablesIf intelligent Tagging is set to true and when using recursive tags inside tables the whole column will be copy pasted

qrCodeType boolean [false]If qrCode is set to true DocxGen will look at all the images to find a Qr-Code If the Qr-code matches to a URL this URL will be loaded by ajax (Be aware that the server you want to access needs to allow your request or it wonrsquot work httpstackoverflowcomquestions9310112why-am-i-seeing-an-origin-is-not-allowed-by-access-control-allow-origin-error )

Important the qrCode functionality only works for PNG I donrsquot think I will enable this for other fileformats in the near future

localImageCreatorType function(argcallback) [function that returns an arrow]The function has to be customized only if you want to use the qrCode options (qrCode=true) When the qrcode text starts with gen the image is not going to be loaded by url but DocxGen calls localImageCreator with arg=full Text decoded The callback needs to be called with the image Datacallback(result) in plaintxt format (if you want to create it from a Data-URI you can use JSZipBase64decode(data) to decode a Data-URI to plaintxt)

The default localImageCreator returns a red arrow no matter what the arguments are

localImageCreator= (argcallback) -gtresult=JSZipBase64decode(iVBORw0KGgoAAAANSUhEUgAAABcAAAAXCAIAAABvSEP3AAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAACXSURBVDhPtY7BDYAwDAMZhCf7b8YMxeCoatOQJhWcKGxT2zlCyaWcz8Y+X7Bs1TFVJSwIHIYyFkQufWIRVX9cNJyW1QpEo4rixaEe7JuQagAUctb7ZFYFh5MVJPBe84CVBnB42YsZRgKjFDBVg3cI9WbRwXLktQJX8cNIiFhM1ZuTWk7PIYSBhkVcLzwIiCjCxhCjlAkBqYnqFoQQ2AAAAAElFTkSuQmCC)

23

docxtemplater Documentation Release 054

[Default Image](dataimagepngbase64iVBORw0KGgoAAAANSUhEUgAAABcAAAAXCAIAAABvSEP3AAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAACXSURBVDhPtY7BDYAwDAMZhCf7b8YMxeCoatOQJhWcKGxT2zlCyaWcz8Y+X7Bs1TFVJSwIHIYyFkQufWIRVX9cNJyW1QpEo4rixaEe7JuQagAUctb7ZFYFh5MVJPBe84CVBnB42YsZRgKjFDBVg3cI9WbRwXLktQJX8cNIiFhM1ZuTWk7PIYSBhkVcLzwIiCjCxhCjlAkBqYnqFoQQ2AAAAAElFTkSuQmCC)

qrFinishedCallBackType function () [function that consolelog(ready)]

This function is called if you specify qrCode argument to true in this constructor and will be called when all qrCodes have been replaced (because the qrCode replacing functions are async)

92 Docxgen methods

load(content)

contentType stringThe docx template you want to load as plain text

loadFromFile(path)path

Type stringLoads a docx from a file path

setTags(Tags)

TagsType Object tag_nametag_replacementObject containing for each tag_name the replacement for this tag For example if you want to replace firstName by David your Object will be firstNameDavid

applyTags([Tags])Tags

Type Object tag_nametag_replacementsame as setTagsDefaultthisTags

This function replaces all template variables by their values

output([options])

options object[]

nameTypestring[outputdocx]The name of the file that will be outputed (doesnt work in the browser because of dataUri download)

callbackTypefunctionFunction that is called without arguments when the output is done Is used only in Node (because in the browser the operation is synchronous)

downloadTypeboolean[true]If download is true file will be downloaded automatically with data URIreturns the output file

typeTypestring[base64]The type of zip to return The possible values are (same as in httpstukgithubiojszip generate)base64 (default) the result will be a string the binary in a base64 formstring the result will be a string in binary form 1 byte per charuint8array the result will be a Uint8Array containing the zip This requires a compatible browser

24 Chapter 9 Full Documentation per method

docxtemplater Documentation Release 054

arraybuffer the result will be a ArrayBuffer containing the zip This requires a compatible browserblob the result will be a Blob containing the zip This requires a compatible browsernodebuffer the result will be a nodejs Buffer containing the zip This requires nodejs

This function creates the docx file and downloads it on the userrsquos computer The name of the file is downloaddocx for Chrome and some akward file names for Firefox VEeTHCfSdocxpartdocx and canrsquot be changed because it is handled by the browserFor more informations about how to solve this problem see the Filename Problems section on [httpstukgithubiojszip](httpstukgithubiojszip)

Note All browsers donrsquot support the download of big files with Data URI so you should use the lsquodownloadlsquo method for files bigger than 100kB dataimagepngbase64iVBORw0KGgoAAAANSUhEUgAAABcAAAAXCAIAAABvSEP3AAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAACXSURBVDhPtY7BDYAwDAMZhCf7b8YMxeCoatOQJhWcKGxT2zlCyaWcz8Y+X7Bs1TFVJSwIHIYyFkQufWIRVX9cNJyW1QpEo4rixaEe7JuQagAUctb7ZFYFh5MVJPBe84CVBnB42YsZRgKjFDBVg3cI9WbRwXLktQJX8cNIiFhM1ZuTWk7PIYSBhkVcLzwIiCjCxhCjlAkBqYnqFoQQ2AAAAAElFTkSuQmCC

download(swfpathimgpath[fileName])

swfpathTypestringPath to the swfobjectjs in downloadify

imgpathTypestringPath to the image of the download button

[fileName]TypestringDefaultdefaultdocxName of the file you would like the user to download

This requires to include Downloadifyjs that needs flash version 10 Have a look at the output function if you donrsquot want to depend on it This function has the advantage that it works regardless of the file size

getImageList()

this gets all images that have one of the following extension rsquogifrsquorsquojpegrsquorsquojpgrsquorsquoemfrsquorsquopngrsquoReturn format Array of Object[pathstringfilesZipFile Object]

You shouldrsquont call this method before calling applyTags() because applyTags can modify the images or their path when replacing images with other (particularly when qrCode is set to true which is not the default case) You can call this method after applyTags() without any problems

setImage(pathimgData)

pathTypeStringPath of the image given by getImageList()

imgDataTypeStringimgData in txtplain

This sets the image given by a path and an imgData in txtplainYou shouldrsquont call this method before calling applyTags() because applyTags can modify the images or their path when replacing images with other (particularly when qrCode is set to true which is not the default case) You can call this method after applyTags() without any problems

getFullText([path])

pathTypeStringDefaultworddocumentxmlThis argument determines from which document you want to get the text The main document is called worddocumentxml but they are other documents wordheader1xml wordfooter1xml

returnsTypeStringThe string containing all the text from the document

92 Docxgen methods 25

docxtemplater Documentation Release 054

This method gets only the text of a given document (not the formatting)

getTags()

This function returns the template variables contained in the opened document For example if the content of the documentxml is the following

namefirst_namephone

The function will return[

filenamedocumentxmlvars

nametruefirst_nametruephonetrue

]

If the content contains tagLoops

titlecustomernamephonecustomer

The function will return

[filenamedocumentxmlvars

titletruecustomer

nametruephonetrue

]

26 Chapter 9 Full Documentation per method

CHAPTER 10

Copyright

License

(The MIT license)

Copyright (c) 2013 Edgar Hipp

Permission is hereby granted free of charge to any person obtaining a copy of this software and associated documen-tation files (the ldquoSoftwarerdquo) to deal in the Software without restriction including without limitation the rights to usecopy modify merge publish distribute sublicense andor sell copies of the Software and to permit persons to whomthe Software is furnished to do so subject to the following conditions

The above copyright notice and this permission notice shall be included in all copies or substantial portions of theSoftware

THE SOFTWARE IS PROVIDED ldquoAS ISrdquo WITHOUT WARRANTY OF ANY KIND EXPRESS OR IMPLIEDINCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY FITNESS FOR A PAR-TICULAR PURPOSE AND NONINFRINGEMENT IN NO EVENT SHALL THE AUTHORS OR COPYRIGHTHOLDERS BE LIABLE FOR ANY CLAIM DAMAGES OR OTHER LIABILITY WHETHER IN AN ACTIONOF CONTRACT TORT OR OTHERWISE ARISING FROM OUT OF OR IN CONNECTION WITH THE SOFT-WARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE

27

docxtemplater Documentation Release 054

28 Chapter 10 Copyright

CHAPTER 11

Demos

Including

bull Replace Variables

bull Formating

bull Angular Parsing

bull Loops

bull Loops and tables

bull Lists

bull Replacing images

bull Naming the output

bull Using QrCodes

bull Replacing many images with QrCode

bull Raw Xml Insertion

29

docxtemplater Documentation Release 054

30 Chapter 11 Demos

CHAPTER 12

Indices and tables

bull genindex

bull modindex

bull search

31

docxtemplater Documentation Release 054

32 Chapter 12 Indices and tables

Index

CCommand Line Interface (CLI) 20Configuration 17Copyright 26

FFull_doc 21

GGenerate a Document 13Goals 1

IInstallation 7

Pplatform_support 3

SSyntax 9

33

  • Goals
    • Why you should use a library for this
      • Platform Support
      • Dependencies
      • Installation
        • Node
        • Browser
          • Syntax
            • Synopsis
            • Tag types
            • Loop syntax
            • Dash syntax
            • Inverted Selections
              • Generate a document
                • Loading a document
                • Setting the tags
                • Applying the tags
                • Outputing the document
                  • Configuration
                    • Image Replacing
                    • Angular Parser
                    • Intelligent LoopTagging
                      • Command Line Interface (CLI)
                        • Configjson Syntax
                          • Full Documentation per method
                            • Creating a new Docxgen Object
                            • Docxgen methods
                              • Copyright
                              • Demos
                              • Indices and tables
Page 6: Release 0.5€¦ · Docx is a zipped format that contains some xml. If you want to build a simple replace {tag} If you want to build a simple replace {tag} by value system, it can

CHAPTER 1

Goals

Docxtemplater was born out of the idea that you should be able to generate Docx as easily as you generate Html withsomething like Mustache

They are a lots of solutions like docxjs docx4j that generate docx but you will have to write specific code tocreate a title an image

I think this is a waste when you can just write your template with plain old Microsoft Word

Docxtemplater is just there for that

11 Why you should use a library for this

Docx is a zipped format that contains some xml If you want to build a simple replace tagby value system it can already become complicated because the tag is internally separated intoltwtgtltwtgtltwtgttagltwtgtltwtgtltwtgt If you want to embed loops to iterate over an array it becomes areal hassle

3

docxtemplater Documentation Release 054

4 Chapter 1 Goals

CHAPTER 2

Platform Support

docxtemplater works with

bull Nodejs with 010 and 011

bull Chrome tested on version 26

bull Firefox 3+ (tested on version 21 but should work with 3+)

bull Safari not tested

Internet explorer is not supported -even IE10- (basically because xhr Requests canrsquot be made on binary files)

You can test if everything works fine on your browser by using the test runner httpjavascript-ninjafrdocxgenjstestSpecRunnerhtml

Firefox has an other implementation of the xml parser thatrsquos why all tests donrsquot pass now However all of thefunctionality works on Firefox too The output files are not exactly the same byte wise but the generated XML iscorrect

5

docxtemplater Documentation Release 054

6 Chapter 2 Platform Support

CHAPTER 3

Dependencies

1 docxgenjs uses [jszipjs](httpstukgithubiojszip) to zip and unzip the docx files

2 Optionally if you want to be able to name the output files you can use Downloadifyjs which is requiredto use method download Be informed that it uses flash this is why the method is not recommended Thismethod is howewer useful because a lot of browsers are limited for the download size with the Data-URImethod Update I will probably implement in the future a way to use the FileSaver API with [File-SaverJS](httpeligreycomdemosFileSaverjs)

3 Optionnaly if you want to replace images by images situated at a particular URL you can use QR codes Forexample If you store an image at httpwebsitecomimagepng you should encode the URL in QR-Code for-mat [Qr Code Sample](httpqrfreekaywacoml=1amps=8ampd=http3A2F2Fwebsitecom2FimagepngldquoQrcode Sample to httpwebsitecomimagepngrdquo) You can even use bracket tags in imageshttpwebsitecomimagepngcolor=color will take the Tags[color] variable to make a dynamic URL Forthis too work you will need [jsqrcode](httpgithubcomedi9999jsqrcode ldquojsqrcode repositoty forkedrdquo) andinclude the following files in this order (only for browser support node support already comes out of the box)

ltscript type=textjavascript src=gridjsgtltscriptgtltscript type=textjavascript src=versionjsgtltscriptgtltscript type=textjavascript src=detectorjsgtltscriptgtltscript type=textjavascript src=formatinfjsgtltscriptgtltscript type=textjavascript src=errorleveljsgtltscriptgtltscript type=textjavascript src=bitmatjsgtltscriptgtltscript type=textjavascript src=datablockjsgtltscriptgtltscript type=textjavascript src=bmparserjsgtltscriptgtltscript type=textjavascript src=datamaskjsgtltscriptgtltscript type=textjavascript src=rsdecoderjsgtltscriptgtltscript type=textjavascript src=gf256polyjsgtltscriptgtltscript type=textjavascript src=gf256jsgtltscriptgtltscript type=textjavascript src=decoderjsgtltscriptgtltscript type=textjavascript src=qrcodejsgtltscriptgtltscript type=textjavascript src=findpatjsgtltscriptgtltscript type=textjavascript src=alignpatjsgtltscriptgtltscript type=textjavascript src=databrjsgtltscriptgt

7

docxtemplater Documentation Release 054

8 Chapter 3 Dependencies

CHAPTER 4

Installation

41 Node

To install docxtemplater we recommend you to use npm

npm install docxtemplater

If you want to use the command line interface you should use the global flag eg

npm install docxtemplater -g

42 Browser

You will just have to include the docxgenjs or docxgenminjs file

9

docxtemplater Documentation Release 054

10 Chapter 4 Installation

CHAPTER 5

Syntax

The syntax is highly inspired by Mustache The template is created in Microsoft Word or any equivalent that saves todocx

51 Synopsis

A typical docxtemplater template

Hello name

Given the following hash

namersquoEdgarrsquo

Will produce

Hello Edgar

52 Tag types

Like Mustache it has the loopopening and loopclosing brackets

53 Loop syntax

The following template

productsname price C

products

Given the following hash

products

[nameWindowsprice100

11

docxtemplater Documentation Release 054

nameMac OSXprice200nameUbuntuprice0]

will result in

Windows 100 CMac OSX 200 CUbuntu 0C

The loop behaves in the following way

bull If the value is an array it will loop over all the elements of that array

bull If the value is a boolean it will loop once if the value is true keeping the same scope and not loop at all if thevalue is false

Note Because the loops work also with boolean values you can also use them for conditions

54 Dash syntax

It is quite difficult to know on which element you are going to loop By default when using the for loop docxgen willfind that by himself

If between the two tags tag______tag

bull they is the Xml Tag ltwtcgt -gt you are in a table and it will loop over ltwtrgt

bull else -gt it will loop over ltwtgt which is the default Text Tag

With the Dash syntax you pass as a first argument the tag you want to loop on

-wp loop inner loop

In this case this will loop over the first parent ltwpgt tag

55 Inverted Selections

An inverted section begins with a caret (hat) and ends with a slash That is ^person begins a ldquopersonrdquo invertedsection while person ends it

While sections can be used to render text one or more times based on the value of the key inverted sections may rendertext once based on the inverse value of the key That is they will be rendered if the key doesnrsquot exist is false or is anempty list

Template

repoltbgtnameltbgt

repo^repo

No repos (repo

Hash

12 Chapter 5 Syntax

docxtemplater Documentation Release 054

repo []

Output

No repos (

55 Inverted Selections 13

docxtemplater Documentation Release 054

14 Chapter 5 Syntax

CHAPTER 6

Generate a document

Herersquos a sample code to generate a document

DocxGen=require(rsquodocxtemplaterrsquo) Only for Node Usagenew DocxGen()loadFromFile(tagExampledocxasynctrue)success(function(doc)

docsetTags(first_nameHipp

last_nameEdgarphone0652455478descriptionNew Website

) set the templateVariablesdocapplyTags() apply them (replace all occurences of first_name by Hipp )docoutput() Output the document using Data-URI

)

The different steps are the following

61 Loading a document

A docx can be loaded by itrsquos base64 representation like this

doc=new DocxGen(base64Dataoptions)

However loading the base64Data is not that easy so I created a wrapper function to load a docx from a file via Ajax

Note The options parameter are explained in Configuration

doc=new DocxGen()loadFromFile(documentPathoptions)

The documentPath is the path to the document you want to load The options are the same as in the constructorfunction and Irsquove added the async parameter

bull If async is true the document is loaded asynchronously and returns a promise (eg you can write suc-cess(callback) to get when the document is loaded)

bull If async is false the document is loaded synchronously and returns the document

62 Setting the tags

The tags are the variables that are going to be replaced by their values To set them just use

15

docxtemplater Documentation Release 054

docsetTags(tags)

63 Applying the tags

Applying the tags means opening all files that contain text (eg footer header main document) and replace thevariables by their values

docapplyTags(tags)

Note If you specify an argument for the applyTags method the function setTags(tags) will be called before applyingthe tags

64 Outputing the document

They are several ways to output the document The most basic usage is to download the document

docoutput(options)

Depending on your environment if you donrsquot set any options this will

bull In the browser Download the document using DataURI

bull In Node Save the document with the given fileName (outputdocx by default)

Herersquos the different options parameters

nameTypestring[outputdocx]The name of the file that will be outputed (doesnt work in the browser because of dataUri download)

callbackTypefunctionFunction that is called without arguments when the output is done Is used only in Node (because in the browser the operation is synchronous)

downloadTypeboolean[true]If download is true file will be downloaded automatically with data URIreturns the output file

typeTypestring[base64]The type of zip to return The possible values are (same as in httpstukgithubiojszip generate)base64 (default) the result will be a string the binary in a base64 formstring the result will be a string in binary form 1 byte per charuint8array the result will be a Uint8Array containing the zip This requires a compatible browserarraybuffer the result will be a ArrayBuffer containing the zip This requires a compatible browserblob the result will be a Blob containing the zip This requires a compatible browsernodebuffer the result will be a nodejs Buffer containing the zip This requires nodejs

This function creates the docx file and downloads it on the userrsquos computer The name of the file is downloaddocxfor Chrome and some akward file names for Firefox VEeTHCfSdocxpartdocx and canrsquot be changed because it ishandled by the browser For more informations about how to solve this problem see the Filename Problems sectionon [httpstukgithubiojszip](httpstukgithubiojszip)

16 Chapter 6 Generate a document

docxtemplater Documentation Release 054

Note Note All browsers donrsquot support the download of big files withData URI so you should use the download method for files bigger than 100kBdataimagepngbase64iVBORw0KGgoAAAANSUhEUgAAABcAAAAXCAIAAABvSEP3AAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAACXSURBVDhPtY7BDYAwDAMZhCf7b8YMxeCoatOQJhWcKGxT2zlCyaWcz8Y+X7Bs1TFVJSwIHIYyFkQufWIRVX9cNJyW1QpEo4rixaEe7JuQagAUctb7ZFYFh5MVJPBe84CVBnB42YsZRgKjFDBVg3cI9WbRwXLktQJX8cNIiFhM1ZuTWk7PIYSBhkVcLzwIiCjCxhCjlAkBqYnqFoQQ2AAAAAElFTkSuQmCC

In Node to send the document to the client you can write the following code snippet

out=docoutput(downloadfalsetypestring)ressend(new Buffer(outbinary))

64 Outputing the document 17

docxtemplater Documentation Release 054

18 Chapter 6 Generate a document

CHAPTER 7

Configuration

Here are documented the special options that you can set when creating a new DocxGen to get some more superpower

It documents the options parameter when you do

new DocxGen(dataoptions)

71 Image Replacing

The name of this option qrCode (boolean)

To stay a templating engine I wanted that DocxTemplater doesnrsquot add an image from scratch but rather uses anexisting image that can be detected and DocxTemplater will just change the contents of that image without changingitrsquos style The size of the replaced images will stay the same

So I decided to use the qrCode format which is a format that lets you identify images by their content

The option for this is qrCode (true for on false for off default off)

Note If you donrsquot use that functionality you should disable it because it is quite slow (the image decoding)

Warning The qrCode functionality only works for PNG They is no support for other file formats yet

72 Angular Parser

The name of this option parser (function)

You can set the angular parser with the following code

With a custom parser you can parse the tags to for example add operators like lsquo+rsquo lsquo-lsquo or whatever the way you wantto parse expressions

To enable this you need to specify a custom parser You need to create a parser function

docxtemplater comes shipped with this parser

parser=function(expression)

return

19

docxtemplater Documentation Release 054

getfunction(scope) return scope[expression]

To use the angular-parser do the following

expressions= require(rsquoangular-expressionsrsquo)angularParser= function(tag)

return getexpressionscompile(tag)

new DocxGen(dataparserangularParser)

Note The require() works in the browser if you include vendorangular-parser-browserjs

73 Intelligent LoopTagging

The name of this option intelligentTagging (boolean)

When looping over an element docxtemplater needs to know over which element you want to loop By default it triesto do that intelligently (by looking what XML Tags are between the tags) However if you want to always use theltwtgt tag by default set this option to false

You can always specify over which element you want to loop with the dash loop syntax

20 Chapter 7 Configuration

CHAPTER 8

Command Line Interface (CLI)

This section is about the commandline interface of docxtemplater

The syntax is the following

docxtemplater configjson

The full configjson should be something like that

configdocxFileinputdocxconfigoutputFileoutputdocxconfigqrcodetrueconfigdebugtruefirst_nameJohnlast_nameSmithage62

81 Configjson Syntax

811 Config properties

These are the properties to configure docxtemplater

configdocxFileinputdocx The input file pathconfigoutputFileoutputdocx The output file pathconfigqrcodetrue whether the images should be scanned to replace them by qrcodes (slows down the cli a lot)configdebugtrue whether to show debug output or not

812 Data properties

To add data to your template just use keys that donrsquot start with ldquoconfigrdquo

first_nameJohnlast_nameSmithage62

21

docxtemplater Documentation Release 054

22 Chapter 8 Command Line Interface (CLI)

CHAPTER 9

Full Documentation per method

91 Creating a new Docxgen Object

new DocxGen()

This function returns a new DocxGen Object

new DocxGen(content[Tagsoptions])

contentType stringThe docx template you want to load as plain text

TagsType Object tag_nametag_replacement []Object containing for each tag_name the replacement for this tag For example if you want to replace firstName by David your Object will be firstNameDavid

options object

parserType functionA custom parser to use See angularjs like parsing

intelligentTaggingType boolean [false]If intelligent Tagging is not set to true when using recursive tags (tag and tag) the system will copy paste what is between the start tag and the endtag this could basically corrupt the files if recursive tags are used inside tablesIf intelligent Tagging is set to true and when using recursive tags inside tables the whole column will be copy pasted

qrCodeType boolean [false]If qrCode is set to true DocxGen will look at all the images to find a Qr-Code If the Qr-code matches to a URL this URL will be loaded by ajax (Be aware that the server you want to access needs to allow your request or it wonrsquot work httpstackoverflowcomquestions9310112why-am-i-seeing-an-origin-is-not-allowed-by-access-control-allow-origin-error )

Important the qrCode functionality only works for PNG I donrsquot think I will enable this for other fileformats in the near future

localImageCreatorType function(argcallback) [function that returns an arrow]The function has to be customized only if you want to use the qrCode options (qrCode=true) When the qrcode text starts with gen the image is not going to be loaded by url but DocxGen calls localImageCreator with arg=full Text decoded The callback needs to be called with the image Datacallback(result) in plaintxt format (if you want to create it from a Data-URI you can use JSZipBase64decode(data) to decode a Data-URI to plaintxt)

The default localImageCreator returns a red arrow no matter what the arguments are

localImageCreator= (argcallback) -gtresult=JSZipBase64decode(iVBORw0KGgoAAAANSUhEUgAAABcAAAAXCAIAAABvSEP3AAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAACXSURBVDhPtY7BDYAwDAMZhCf7b8YMxeCoatOQJhWcKGxT2zlCyaWcz8Y+X7Bs1TFVJSwIHIYyFkQufWIRVX9cNJyW1QpEo4rixaEe7JuQagAUctb7ZFYFh5MVJPBe84CVBnB42YsZRgKjFDBVg3cI9WbRwXLktQJX8cNIiFhM1ZuTWk7PIYSBhkVcLzwIiCjCxhCjlAkBqYnqFoQQ2AAAAAElFTkSuQmCC)

23

docxtemplater Documentation Release 054

[Default Image](dataimagepngbase64iVBORw0KGgoAAAANSUhEUgAAABcAAAAXCAIAAABvSEP3AAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAACXSURBVDhPtY7BDYAwDAMZhCf7b8YMxeCoatOQJhWcKGxT2zlCyaWcz8Y+X7Bs1TFVJSwIHIYyFkQufWIRVX9cNJyW1QpEo4rixaEe7JuQagAUctb7ZFYFh5MVJPBe84CVBnB42YsZRgKjFDBVg3cI9WbRwXLktQJX8cNIiFhM1ZuTWk7PIYSBhkVcLzwIiCjCxhCjlAkBqYnqFoQQ2AAAAAElFTkSuQmCC)

qrFinishedCallBackType function () [function that consolelog(ready)]

This function is called if you specify qrCode argument to true in this constructor and will be called when all qrCodes have been replaced (because the qrCode replacing functions are async)

92 Docxgen methods

load(content)

contentType stringThe docx template you want to load as plain text

loadFromFile(path)path

Type stringLoads a docx from a file path

setTags(Tags)

TagsType Object tag_nametag_replacementObject containing for each tag_name the replacement for this tag For example if you want to replace firstName by David your Object will be firstNameDavid

applyTags([Tags])Tags

Type Object tag_nametag_replacementsame as setTagsDefaultthisTags

This function replaces all template variables by their values

output([options])

options object[]

nameTypestring[outputdocx]The name of the file that will be outputed (doesnt work in the browser because of dataUri download)

callbackTypefunctionFunction that is called without arguments when the output is done Is used only in Node (because in the browser the operation is synchronous)

downloadTypeboolean[true]If download is true file will be downloaded automatically with data URIreturns the output file

typeTypestring[base64]The type of zip to return The possible values are (same as in httpstukgithubiojszip generate)base64 (default) the result will be a string the binary in a base64 formstring the result will be a string in binary form 1 byte per charuint8array the result will be a Uint8Array containing the zip This requires a compatible browser

24 Chapter 9 Full Documentation per method

docxtemplater Documentation Release 054

arraybuffer the result will be a ArrayBuffer containing the zip This requires a compatible browserblob the result will be a Blob containing the zip This requires a compatible browsernodebuffer the result will be a nodejs Buffer containing the zip This requires nodejs

This function creates the docx file and downloads it on the userrsquos computer The name of the file is downloaddocx for Chrome and some akward file names for Firefox VEeTHCfSdocxpartdocx and canrsquot be changed because it is handled by the browserFor more informations about how to solve this problem see the Filename Problems section on [httpstukgithubiojszip](httpstukgithubiojszip)

Note All browsers donrsquot support the download of big files with Data URI so you should use the lsquodownloadlsquo method for files bigger than 100kB dataimagepngbase64iVBORw0KGgoAAAANSUhEUgAAABcAAAAXCAIAAABvSEP3AAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAACXSURBVDhPtY7BDYAwDAMZhCf7b8YMxeCoatOQJhWcKGxT2zlCyaWcz8Y+X7Bs1TFVJSwIHIYyFkQufWIRVX9cNJyW1QpEo4rixaEe7JuQagAUctb7ZFYFh5MVJPBe84CVBnB42YsZRgKjFDBVg3cI9WbRwXLktQJX8cNIiFhM1ZuTWk7PIYSBhkVcLzwIiCjCxhCjlAkBqYnqFoQQ2AAAAAElFTkSuQmCC

download(swfpathimgpath[fileName])

swfpathTypestringPath to the swfobjectjs in downloadify

imgpathTypestringPath to the image of the download button

[fileName]TypestringDefaultdefaultdocxName of the file you would like the user to download

This requires to include Downloadifyjs that needs flash version 10 Have a look at the output function if you donrsquot want to depend on it This function has the advantage that it works regardless of the file size

getImageList()

this gets all images that have one of the following extension rsquogifrsquorsquojpegrsquorsquojpgrsquorsquoemfrsquorsquopngrsquoReturn format Array of Object[pathstringfilesZipFile Object]

You shouldrsquont call this method before calling applyTags() because applyTags can modify the images or their path when replacing images with other (particularly when qrCode is set to true which is not the default case) You can call this method after applyTags() without any problems

setImage(pathimgData)

pathTypeStringPath of the image given by getImageList()

imgDataTypeStringimgData in txtplain

This sets the image given by a path and an imgData in txtplainYou shouldrsquont call this method before calling applyTags() because applyTags can modify the images or their path when replacing images with other (particularly when qrCode is set to true which is not the default case) You can call this method after applyTags() without any problems

getFullText([path])

pathTypeStringDefaultworddocumentxmlThis argument determines from which document you want to get the text The main document is called worddocumentxml but they are other documents wordheader1xml wordfooter1xml

returnsTypeStringThe string containing all the text from the document

92 Docxgen methods 25

docxtemplater Documentation Release 054

This method gets only the text of a given document (not the formatting)

getTags()

This function returns the template variables contained in the opened document For example if the content of the documentxml is the following

namefirst_namephone

The function will return[

filenamedocumentxmlvars

nametruefirst_nametruephonetrue

]

If the content contains tagLoops

titlecustomernamephonecustomer

The function will return

[filenamedocumentxmlvars

titletruecustomer

nametruephonetrue

]

26 Chapter 9 Full Documentation per method

CHAPTER 10

Copyright

License

(The MIT license)

Copyright (c) 2013 Edgar Hipp

Permission is hereby granted free of charge to any person obtaining a copy of this software and associated documen-tation files (the ldquoSoftwarerdquo) to deal in the Software without restriction including without limitation the rights to usecopy modify merge publish distribute sublicense andor sell copies of the Software and to permit persons to whomthe Software is furnished to do so subject to the following conditions

The above copyright notice and this permission notice shall be included in all copies or substantial portions of theSoftware

THE SOFTWARE IS PROVIDED ldquoAS ISrdquo WITHOUT WARRANTY OF ANY KIND EXPRESS OR IMPLIEDINCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY FITNESS FOR A PAR-TICULAR PURPOSE AND NONINFRINGEMENT IN NO EVENT SHALL THE AUTHORS OR COPYRIGHTHOLDERS BE LIABLE FOR ANY CLAIM DAMAGES OR OTHER LIABILITY WHETHER IN AN ACTIONOF CONTRACT TORT OR OTHERWISE ARISING FROM OUT OF OR IN CONNECTION WITH THE SOFT-WARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE

27

docxtemplater Documentation Release 054

28 Chapter 10 Copyright

CHAPTER 11

Demos

Including

bull Replace Variables

bull Formating

bull Angular Parsing

bull Loops

bull Loops and tables

bull Lists

bull Replacing images

bull Naming the output

bull Using QrCodes

bull Replacing many images with QrCode

bull Raw Xml Insertion

29

docxtemplater Documentation Release 054

30 Chapter 11 Demos

CHAPTER 12

Indices and tables

bull genindex

bull modindex

bull search

31

docxtemplater Documentation Release 054

32 Chapter 12 Indices and tables

Index

CCommand Line Interface (CLI) 20Configuration 17Copyright 26

FFull_doc 21

GGenerate a Document 13Goals 1

IInstallation 7

Pplatform_support 3

SSyntax 9

33

  • Goals
    • Why you should use a library for this
      • Platform Support
      • Dependencies
      • Installation
        • Node
        • Browser
          • Syntax
            • Synopsis
            • Tag types
            • Loop syntax
            • Dash syntax
            • Inverted Selections
              • Generate a document
                • Loading a document
                • Setting the tags
                • Applying the tags
                • Outputing the document
                  • Configuration
                    • Image Replacing
                    • Angular Parser
                    • Intelligent LoopTagging
                      • Command Line Interface (CLI)
                        • Configjson Syntax
                          • Full Documentation per method
                            • Creating a new Docxgen Object
                            • Docxgen methods
                              • Copyright
                              • Demos
                              • Indices and tables
Page 7: Release 0.5€¦ · Docx is a zipped format that contains some xml. If you want to build a simple replace {tag} If you want to build a simple replace {tag} by value system, it can

docxtemplater Documentation Release 054

4 Chapter 1 Goals

CHAPTER 2

Platform Support

docxtemplater works with

bull Nodejs with 010 and 011

bull Chrome tested on version 26

bull Firefox 3+ (tested on version 21 but should work with 3+)

bull Safari not tested

Internet explorer is not supported -even IE10- (basically because xhr Requests canrsquot be made on binary files)

You can test if everything works fine on your browser by using the test runner httpjavascript-ninjafrdocxgenjstestSpecRunnerhtml

Firefox has an other implementation of the xml parser thatrsquos why all tests donrsquot pass now However all of thefunctionality works on Firefox too The output files are not exactly the same byte wise but the generated XML iscorrect

5

docxtemplater Documentation Release 054

6 Chapter 2 Platform Support

CHAPTER 3

Dependencies

1 docxgenjs uses [jszipjs](httpstukgithubiojszip) to zip and unzip the docx files

2 Optionally if you want to be able to name the output files you can use Downloadifyjs which is requiredto use method download Be informed that it uses flash this is why the method is not recommended Thismethod is howewer useful because a lot of browsers are limited for the download size with the Data-URImethod Update I will probably implement in the future a way to use the FileSaver API with [File-SaverJS](httpeligreycomdemosFileSaverjs)

3 Optionnaly if you want to replace images by images situated at a particular URL you can use QR codes Forexample If you store an image at httpwebsitecomimagepng you should encode the URL in QR-Code for-mat [Qr Code Sample](httpqrfreekaywacoml=1amps=8ampd=http3A2F2Fwebsitecom2FimagepngldquoQrcode Sample to httpwebsitecomimagepngrdquo) You can even use bracket tags in imageshttpwebsitecomimagepngcolor=color will take the Tags[color] variable to make a dynamic URL Forthis too work you will need [jsqrcode](httpgithubcomedi9999jsqrcode ldquojsqrcode repositoty forkedrdquo) andinclude the following files in this order (only for browser support node support already comes out of the box)

ltscript type=textjavascript src=gridjsgtltscriptgtltscript type=textjavascript src=versionjsgtltscriptgtltscript type=textjavascript src=detectorjsgtltscriptgtltscript type=textjavascript src=formatinfjsgtltscriptgtltscript type=textjavascript src=errorleveljsgtltscriptgtltscript type=textjavascript src=bitmatjsgtltscriptgtltscript type=textjavascript src=datablockjsgtltscriptgtltscript type=textjavascript src=bmparserjsgtltscriptgtltscript type=textjavascript src=datamaskjsgtltscriptgtltscript type=textjavascript src=rsdecoderjsgtltscriptgtltscript type=textjavascript src=gf256polyjsgtltscriptgtltscript type=textjavascript src=gf256jsgtltscriptgtltscript type=textjavascript src=decoderjsgtltscriptgtltscript type=textjavascript src=qrcodejsgtltscriptgtltscript type=textjavascript src=findpatjsgtltscriptgtltscript type=textjavascript src=alignpatjsgtltscriptgtltscript type=textjavascript src=databrjsgtltscriptgt

7

docxtemplater Documentation Release 054

8 Chapter 3 Dependencies

CHAPTER 4

Installation

41 Node

To install docxtemplater we recommend you to use npm

npm install docxtemplater

If you want to use the command line interface you should use the global flag eg

npm install docxtemplater -g

42 Browser

You will just have to include the docxgenjs or docxgenminjs file

9

docxtemplater Documentation Release 054

10 Chapter 4 Installation

CHAPTER 5

Syntax

The syntax is highly inspired by Mustache The template is created in Microsoft Word or any equivalent that saves todocx

51 Synopsis

A typical docxtemplater template

Hello name

Given the following hash

namersquoEdgarrsquo

Will produce

Hello Edgar

52 Tag types

Like Mustache it has the loopopening and loopclosing brackets

53 Loop syntax

The following template

productsname price C

products

Given the following hash

products

[nameWindowsprice100

11

docxtemplater Documentation Release 054

nameMac OSXprice200nameUbuntuprice0]

will result in

Windows 100 CMac OSX 200 CUbuntu 0C

The loop behaves in the following way

bull If the value is an array it will loop over all the elements of that array

bull If the value is a boolean it will loop once if the value is true keeping the same scope and not loop at all if thevalue is false

Note Because the loops work also with boolean values you can also use them for conditions

54 Dash syntax

It is quite difficult to know on which element you are going to loop By default when using the for loop docxgen willfind that by himself

If between the two tags tag______tag

bull they is the Xml Tag ltwtcgt -gt you are in a table and it will loop over ltwtrgt

bull else -gt it will loop over ltwtgt which is the default Text Tag

With the Dash syntax you pass as a first argument the tag you want to loop on

-wp loop inner loop

In this case this will loop over the first parent ltwpgt tag

55 Inverted Selections

An inverted section begins with a caret (hat) and ends with a slash That is ^person begins a ldquopersonrdquo invertedsection while person ends it

While sections can be used to render text one or more times based on the value of the key inverted sections may rendertext once based on the inverse value of the key That is they will be rendered if the key doesnrsquot exist is false or is anempty list

Template

repoltbgtnameltbgt

repo^repo

No repos (repo

Hash

12 Chapter 5 Syntax

docxtemplater Documentation Release 054

repo []

Output

No repos (

55 Inverted Selections 13

docxtemplater Documentation Release 054

14 Chapter 5 Syntax

CHAPTER 6

Generate a document

Herersquos a sample code to generate a document

DocxGen=require(rsquodocxtemplaterrsquo) Only for Node Usagenew DocxGen()loadFromFile(tagExampledocxasynctrue)success(function(doc)

docsetTags(first_nameHipp

last_nameEdgarphone0652455478descriptionNew Website

) set the templateVariablesdocapplyTags() apply them (replace all occurences of first_name by Hipp )docoutput() Output the document using Data-URI

)

The different steps are the following

61 Loading a document

A docx can be loaded by itrsquos base64 representation like this

doc=new DocxGen(base64Dataoptions)

However loading the base64Data is not that easy so I created a wrapper function to load a docx from a file via Ajax

Note The options parameter are explained in Configuration

doc=new DocxGen()loadFromFile(documentPathoptions)

The documentPath is the path to the document you want to load The options are the same as in the constructorfunction and Irsquove added the async parameter

bull If async is true the document is loaded asynchronously and returns a promise (eg you can write suc-cess(callback) to get when the document is loaded)

bull If async is false the document is loaded synchronously and returns the document

62 Setting the tags

The tags are the variables that are going to be replaced by their values To set them just use

15

docxtemplater Documentation Release 054

docsetTags(tags)

63 Applying the tags

Applying the tags means opening all files that contain text (eg footer header main document) and replace thevariables by their values

docapplyTags(tags)

Note If you specify an argument for the applyTags method the function setTags(tags) will be called before applyingthe tags

64 Outputing the document

They are several ways to output the document The most basic usage is to download the document

docoutput(options)

Depending on your environment if you donrsquot set any options this will

bull In the browser Download the document using DataURI

bull In Node Save the document with the given fileName (outputdocx by default)

Herersquos the different options parameters

nameTypestring[outputdocx]The name of the file that will be outputed (doesnt work in the browser because of dataUri download)

callbackTypefunctionFunction that is called without arguments when the output is done Is used only in Node (because in the browser the operation is synchronous)

downloadTypeboolean[true]If download is true file will be downloaded automatically with data URIreturns the output file

typeTypestring[base64]The type of zip to return The possible values are (same as in httpstukgithubiojszip generate)base64 (default) the result will be a string the binary in a base64 formstring the result will be a string in binary form 1 byte per charuint8array the result will be a Uint8Array containing the zip This requires a compatible browserarraybuffer the result will be a ArrayBuffer containing the zip This requires a compatible browserblob the result will be a Blob containing the zip This requires a compatible browsernodebuffer the result will be a nodejs Buffer containing the zip This requires nodejs

This function creates the docx file and downloads it on the userrsquos computer The name of the file is downloaddocxfor Chrome and some akward file names for Firefox VEeTHCfSdocxpartdocx and canrsquot be changed because it ishandled by the browser For more informations about how to solve this problem see the Filename Problems sectionon [httpstukgithubiojszip](httpstukgithubiojszip)

16 Chapter 6 Generate a document

docxtemplater Documentation Release 054

Note Note All browsers donrsquot support the download of big files withData URI so you should use the download method for files bigger than 100kBdataimagepngbase64iVBORw0KGgoAAAANSUhEUgAAABcAAAAXCAIAAABvSEP3AAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAACXSURBVDhPtY7BDYAwDAMZhCf7b8YMxeCoatOQJhWcKGxT2zlCyaWcz8Y+X7Bs1TFVJSwIHIYyFkQufWIRVX9cNJyW1QpEo4rixaEe7JuQagAUctb7ZFYFh5MVJPBe84CVBnB42YsZRgKjFDBVg3cI9WbRwXLktQJX8cNIiFhM1ZuTWk7PIYSBhkVcLzwIiCjCxhCjlAkBqYnqFoQQ2AAAAAElFTkSuQmCC

In Node to send the document to the client you can write the following code snippet

out=docoutput(downloadfalsetypestring)ressend(new Buffer(outbinary))

64 Outputing the document 17

docxtemplater Documentation Release 054

18 Chapter 6 Generate a document

CHAPTER 7

Configuration

Here are documented the special options that you can set when creating a new DocxGen to get some more superpower

It documents the options parameter when you do

new DocxGen(dataoptions)

71 Image Replacing

The name of this option qrCode (boolean)

To stay a templating engine I wanted that DocxTemplater doesnrsquot add an image from scratch but rather uses anexisting image that can be detected and DocxTemplater will just change the contents of that image without changingitrsquos style The size of the replaced images will stay the same

So I decided to use the qrCode format which is a format that lets you identify images by their content

The option for this is qrCode (true for on false for off default off)

Note If you donrsquot use that functionality you should disable it because it is quite slow (the image decoding)

Warning The qrCode functionality only works for PNG They is no support for other file formats yet

72 Angular Parser

The name of this option parser (function)

You can set the angular parser with the following code

With a custom parser you can parse the tags to for example add operators like lsquo+rsquo lsquo-lsquo or whatever the way you wantto parse expressions

To enable this you need to specify a custom parser You need to create a parser function

docxtemplater comes shipped with this parser

parser=function(expression)

return

19

docxtemplater Documentation Release 054

getfunction(scope) return scope[expression]

To use the angular-parser do the following

expressions= require(rsquoangular-expressionsrsquo)angularParser= function(tag)

return getexpressionscompile(tag)

new DocxGen(dataparserangularParser)

Note The require() works in the browser if you include vendorangular-parser-browserjs

73 Intelligent LoopTagging

The name of this option intelligentTagging (boolean)

When looping over an element docxtemplater needs to know over which element you want to loop By default it triesto do that intelligently (by looking what XML Tags are between the tags) However if you want to always use theltwtgt tag by default set this option to false

You can always specify over which element you want to loop with the dash loop syntax

20 Chapter 7 Configuration

CHAPTER 8

Command Line Interface (CLI)

This section is about the commandline interface of docxtemplater

The syntax is the following

docxtemplater configjson

The full configjson should be something like that

configdocxFileinputdocxconfigoutputFileoutputdocxconfigqrcodetrueconfigdebugtruefirst_nameJohnlast_nameSmithage62

81 Configjson Syntax

811 Config properties

These are the properties to configure docxtemplater

configdocxFileinputdocx The input file pathconfigoutputFileoutputdocx The output file pathconfigqrcodetrue whether the images should be scanned to replace them by qrcodes (slows down the cli a lot)configdebugtrue whether to show debug output or not

812 Data properties

To add data to your template just use keys that donrsquot start with ldquoconfigrdquo

first_nameJohnlast_nameSmithage62

21

docxtemplater Documentation Release 054

22 Chapter 8 Command Line Interface (CLI)

CHAPTER 9

Full Documentation per method

91 Creating a new Docxgen Object

new DocxGen()

This function returns a new DocxGen Object

new DocxGen(content[Tagsoptions])

contentType stringThe docx template you want to load as plain text

TagsType Object tag_nametag_replacement []Object containing for each tag_name the replacement for this tag For example if you want to replace firstName by David your Object will be firstNameDavid

options object

parserType functionA custom parser to use See angularjs like parsing

intelligentTaggingType boolean [false]If intelligent Tagging is not set to true when using recursive tags (tag and tag) the system will copy paste what is between the start tag and the endtag this could basically corrupt the files if recursive tags are used inside tablesIf intelligent Tagging is set to true and when using recursive tags inside tables the whole column will be copy pasted

qrCodeType boolean [false]If qrCode is set to true DocxGen will look at all the images to find a Qr-Code If the Qr-code matches to a URL this URL will be loaded by ajax (Be aware that the server you want to access needs to allow your request or it wonrsquot work httpstackoverflowcomquestions9310112why-am-i-seeing-an-origin-is-not-allowed-by-access-control-allow-origin-error )

Important the qrCode functionality only works for PNG I donrsquot think I will enable this for other fileformats in the near future

localImageCreatorType function(argcallback) [function that returns an arrow]The function has to be customized only if you want to use the qrCode options (qrCode=true) When the qrcode text starts with gen the image is not going to be loaded by url but DocxGen calls localImageCreator with arg=full Text decoded The callback needs to be called with the image Datacallback(result) in plaintxt format (if you want to create it from a Data-URI you can use JSZipBase64decode(data) to decode a Data-URI to plaintxt)

The default localImageCreator returns a red arrow no matter what the arguments are

localImageCreator= (argcallback) -gtresult=JSZipBase64decode(iVBORw0KGgoAAAANSUhEUgAAABcAAAAXCAIAAABvSEP3AAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAACXSURBVDhPtY7BDYAwDAMZhCf7b8YMxeCoatOQJhWcKGxT2zlCyaWcz8Y+X7Bs1TFVJSwIHIYyFkQufWIRVX9cNJyW1QpEo4rixaEe7JuQagAUctb7ZFYFh5MVJPBe84CVBnB42YsZRgKjFDBVg3cI9WbRwXLktQJX8cNIiFhM1ZuTWk7PIYSBhkVcLzwIiCjCxhCjlAkBqYnqFoQQ2AAAAAElFTkSuQmCC)

23

docxtemplater Documentation Release 054

[Default Image](dataimagepngbase64iVBORw0KGgoAAAANSUhEUgAAABcAAAAXCAIAAABvSEP3AAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAACXSURBVDhPtY7BDYAwDAMZhCf7b8YMxeCoatOQJhWcKGxT2zlCyaWcz8Y+X7Bs1TFVJSwIHIYyFkQufWIRVX9cNJyW1QpEo4rixaEe7JuQagAUctb7ZFYFh5MVJPBe84CVBnB42YsZRgKjFDBVg3cI9WbRwXLktQJX8cNIiFhM1ZuTWk7PIYSBhkVcLzwIiCjCxhCjlAkBqYnqFoQQ2AAAAAElFTkSuQmCC)

qrFinishedCallBackType function () [function that consolelog(ready)]

This function is called if you specify qrCode argument to true in this constructor and will be called when all qrCodes have been replaced (because the qrCode replacing functions are async)

92 Docxgen methods

load(content)

contentType stringThe docx template you want to load as plain text

loadFromFile(path)path

Type stringLoads a docx from a file path

setTags(Tags)

TagsType Object tag_nametag_replacementObject containing for each tag_name the replacement for this tag For example if you want to replace firstName by David your Object will be firstNameDavid

applyTags([Tags])Tags

Type Object tag_nametag_replacementsame as setTagsDefaultthisTags

This function replaces all template variables by their values

output([options])

options object[]

nameTypestring[outputdocx]The name of the file that will be outputed (doesnt work in the browser because of dataUri download)

callbackTypefunctionFunction that is called without arguments when the output is done Is used only in Node (because in the browser the operation is synchronous)

downloadTypeboolean[true]If download is true file will be downloaded automatically with data URIreturns the output file

typeTypestring[base64]The type of zip to return The possible values are (same as in httpstukgithubiojszip generate)base64 (default) the result will be a string the binary in a base64 formstring the result will be a string in binary form 1 byte per charuint8array the result will be a Uint8Array containing the zip This requires a compatible browser

24 Chapter 9 Full Documentation per method

docxtemplater Documentation Release 054

arraybuffer the result will be a ArrayBuffer containing the zip This requires a compatible browserblob the result will be a Blob containing the zip This requires a compatible browsernodebuffer the result will be a nodejs Buffer containing the zip This requires nodejs

This function creates the docx file and downloads it on the userrsquos computer The name of the file is downloaddocx for Chrome and some akward file names for Firefox VEeTHCfSdocxpartdocx and canrsquot be changed because it is handled by the browserFor more informations about how to solve this problem see the Filename Problems section on [httpstukgithubiojszip](httpstukgithubiojszip)

Note All browsers donrsquot support the download of big files with Data URI so you should use the lsquodownloadlsquo method for files bigger than 100kB dataimagepngbase64iVBORw0KGgoAAAANSUhEUgAAABcAAAAXCAIAAABvSEP3AAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAACXSURBVDhPtY7BDYAwDAMZhCf7b8YMxeCoatOQJhWcKGxT2zlCyaWcz8Y+X7Bs1TFVJSwIHIYyFkQufWIRVX9cNJyW1QpEo4rixaEe7JuQagAUctb7ZFYFh5MVJPBe84CVBnB42YsZRgKjFDBVg3cI9WbRwXLktQJX8cNIiFhM1ZuTWk7PIYSBhkVcLzwIiCjCxhCjlAkBqYnqFoQQ2AAAAAElFTkSuQmCC

download(swfpathimgpath[fileName])

swfpathTypestringPath to the swfobjectjs in downloadify

imgpathTypestringPath to the image of the download button

[fileName]TypestringDefaultdefaultdocxName of the file you would like the user to download

This requires to include Downloadifyjs that needs flash version 10 Have a look at the output function if you donrsquot want to depend on it This function has the advantage that it works regardless of the file size

getImageList()

this gets all images that have one of the following extension rsquogifrsquorsquojpegrsquorsquojpgrsquorsquoemfrsquorsquopngrsquoReturn format Array of Object[pathstringfilesZipFile Object]

You shouldrsquont call this method before calling applyTags() because applyTags can modify the images or their path when replacing images with other (particularly when qrCode is set to true which is not the default case) You can call this method after applyTags() without any problems

setImage(pathimgData)

pathTypeStringPath of the image given by getImageList()

imgDataTypeStringimgData in txtplain

This sets the image given by a path and an imgData in txtplainYou shouldrsquont call this method before calling applyTags() because applyTags can modify the images or their path when replacing images with other (particularly when qrCode is set to true which is not the default case) You can call this method after applyTags() without any problems

getFullText([path])

pathTypeStringDefaultworddocumentxmlThis argument determines from which document you want to get the text The main document is called worddocumentxml but they are other documents wordheader1xml wordfooter1xml

returnsTypeStringThe string containing all the text from the document

92 Docxgen methods 25

docxtemplater Documentation Release 054

This method gets only the text of a given document (not the formatting)

getTags()

This function returns the template variables contained in the opened document For example if the content of the documentxml is the following

namefirst_namephone

The function will return[

filenamedocumentxmlvars

nametruefirst_nametruephonetrue

]

If the content contains tagLoops

titlecustomernamephonecustomer

The function will return

[filenamedocumentxmlvars

titletruecustomer

nametruephonetrue

]

26 Chapter 9 Full Documentation per method

CHAPTER 10

Copyright

License

(The MIT license)

Copyright (c) 2013 Edgar Hipp

Permission is hereby granted free of charge to any person obtaining a copy of this software and associated documen-tation files (the ldquoSoftwarerdquo) to deal in the Software without restriction including without limitation the rights to usecopy modify merge publish distribute sublicense andor sell copies of the Software and to permit persons to whomthe Software is furnished to do so subject to the following conditions

The above copyright notice and this permission notice shall be included in all copies or substantial portions of theSoftware

THE SOFTWARE IS PROVIDED ldquoAS ISrdquo WITHOUT WARRANTY OF ANY KIND EXPRESS OR IMPLIEDINCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY FITNESS FOR A PAR-TICULAR PURPOSE AND NONINFRINGEMENT IN NO EVENT SHALL THE AUTHORS OR COPYRIGHTHOLDERS BE LIABLE FOR ANY CLAIM DAMAGES OR OTHER LIABILITY WHETHER IN AN ACTIONOF CONTRACT TORT OR OTHERWISE ARISING FROM OUT OF OR IN CONNECTION WITH THE SOFT-WARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE

27

docxtemplater Documentation Release 054

28 Chapter 10 Copyright

CHAPTER 11

Demos

Including

bull Replace Variables

bull Formating

bull Angular Parsing

bull Loops

bull Loops and tables

bull Lists

bull Replacing images

bull Naming the output

bull Using QrCodes

bull Replacing many images with QrCode

bull Raw Xml Insertion

29

docxtemplater Documentation Release 054

30 Chapter 11 Demos

CHAPTER 12

Indices and tables

bull genindex

bull modindex

bull search

31

docxtemplater Documentation Release 054

32 Chapter 12 Indices and tables

Index

CCommand Line Interface (CLI) 20Configuration 17Copyright 26

FFull_doc 21

GGenerate a Document 13Goals 1

IInstallation 7

Pplatform_support 3

SSyntax 9

33

  • Goals
    • Why you should use a library for this
      • Platform Support
      • Dependencies
      • Installation
        • Node
        • Browser
          • Syntax
            • Synopsis
            • Tag types
            • Loop syntax
            • Dash syntax
            • Inverted Selections
              • Generate a document
                • Loading a document
                • Setting the tags
                • Applying the tags
                • Outputing the document
                  • Configuration
                    • Image Replacing
                    • Angular Parser
                    • Intelligent LoopTagging
                      • Command Line Interface (CLI)
                        • Configjson Syntax
                          • Full Documentation per method
                            • Creating a new Docxgen Object
                            • Docxgen methods
                              • Copyright
                              • Demos
                              • Indices and tables
Page 8: Release 0.5€¦ · Docx is a zipped format that contains some xml. If you want to build a simple replace {tag} If you want to build a simple replace {tag} by value system, it can

CHAPTER 2

Platform Support

docxtemplater works with

bull Nodejs with 010 and 011

bull Chrome tested on version 26

bull Firefox 3+ (tested on version 21 but should work with 3+)

bull Safari not tested

Internet explorer is not supported -even IE10- (basically because xhr Requests canrsquot be made on binary files)

You can test if everything works fine on your browser by using the test runner httpjavascript-ninjafrdocxgenjstestSpecRunnerhtml

Firefox has an other implementation of the xml parser thatrsquos why all tests donrsquot pass now However all of thefunctionality works on Firefox too The output files are not exactly the same byte wise but the generated XML iscorrect

5

docxtemplater Documentation Release 054

6 Chapter 2 Platform Support

CHAPTER 3

Dependencies

1 docxgenjs uses [jszipjs](httpstukgithubiojszip) to zip and unzip the docx files

2 Optionally if you want to be able to name the output files you can use Downloadifyjs which is requiredto use method download Be informed that it uses flash this is why the method is not recommended Thismethod is howewer useful because a lot of browsers are limited for the download size with the Data-URImethod Update I will probably implement in the future a way to use the FileSaver API with [File-SaverJS](httpeligreycomdemosFileSaverjs)

3 Optionnaly if you want to replace images by images situated at a particular URL you can use QR codes Forexample If you store an image at httpwebsitecomimagepng you should encode the URL in QR-Code for-mat [Qr Code Sample](httpqrfreekaywacoml=1amps=8ampd=http3A2F2Fwebsitecom2FimagepngldquoQrcode Sample to httpwebsitecomimagepngrdquo) You can even use bracket tags in imageshttpwebsitecomimagepngcolor=color will take the Tags[color] variable to make a dynamic URL Forthis too work you will need [jsqrcode](httpgithubcomedi9999jsqrcode ldquojsqrcode repositoty forkedrdquo) andinclude the following files in this order (only for browser support node support already comes out of the box)

ltscript type=textjavascript src=gridjsgtltscriptgtltscript type=textjavascript src=versionjsgtltscriptgtltscript type=textjavascript src=detectorjsgtltscriptgtltscript type=textjavascript src=formatinfjsgtltscriptgtltscript type=textjavascript src=errorleveljsgtltscriptgtltscript type=textjavascript src=bitmatjsgtltscriptgtltscript type=textjavascript src=datablockjsgtltscriptgtltscript type=textjavascript src=bmparserjsgtltscriptgtltscript type=textjavascript src=datamaskjsgtltscriptgtltscript type=textjavascript src=rsdecoderjsgtltscriptgtltscript type=textjavascript src=gf256polyjsgtltscriptgtltscript type=textjavascript src=gf256jsgtltscriptgtltscript type=textjavascript src=decoderjsgtltscriptgtltscript type=textjavascript src=qrcodejsgtltscriptgtltscript type=textjavascript src=findpatjsgtltscriptgtltscript type=textjavascript src=alignpatjsgtltscriptgtltscript type=textjavascript src=databrjsgtltscriptgt

7

docxtemplater Documentation Release 054

8 Chapter 3 Dependencies

CHAPTER 4

Installation

41 Node

To install docxtemplater we recommend you to use npm

npm install docxtemplater

If you want to use the command line interface you should use the global flag eg

npm install docxtemplater -g

42 Browser

You will just have to include the docxgenjs or docxgenminjs file

9

docxtemplater Documentation Release 054

10 Chapter 4 Installation

CHAPTER 5

Syntax

The syntax is highly inspired by Mustache The template is created in Microsoft Word or any equivalent that saves todocx

51 Synopsis

A typical docxtemplater template

Hello name

Given the following hash

namersquoEdgarrsquo

Will produce

Hello Edgar

52 Tag types

Like Mustache it has the loopopening and loopclosing brackets

53 Loop syntax

The following template

productsname price C

products

Given the following hash

products

[nameWindowsprice100

11

docxtemplater Documentation Release 054

nameMac OSXprice200nameUbuntuprice0]

will result in

Windows 100 CMac OSX 200 CUbuntu 0C

The loop behaves in the following way

bull If the value is an array it will loop over all the elements of that array

bull If the value is a boolean it will loop once if the value is true keeping the same scope and not loop at all if thevalue is false

Note Because the loops work also with boolean values you can also use them for conditions

54 Dash syntax

It is quite difficult to know on which element you are going to loop By default when using the for loop docxgen willfind that by himself

If between the two tags tag______tag

bull they is the Xml Tag ltwtcgt -gt you are in a table and it will loop over ltwtrgt

bull else -gt it will loop over ltwtgt which is the default Text Tag

With the Dash syntax you pass as a first argument the tag you want to loop on

-wp loop inner loop

In this case this will loop over the first parent ltwpgt tag

55 Inverted Selections

An inverted section begins with a caret (hat) and ends with a slash That is ^person begins a ldquopersonrdquo invertedsection while person ends it

While sections can be used to render text one or more times based on the value of the key inverted sections may rendertext once based on the inverse value of the key That is they will be rendered if the key doesnrsquot exist is false or is anempty list

Template

repoltbgtnameltbgt

repo^repo

No repos (repo

Hash

12 Chapter 5 Syntax

docxtemplater Documentation Release 054

repo []

Output

No repos (

55 Inverted Selections 13

docxtemplater Documentation Release 054

14 Chapter 5 Syntax

CHAPTER 6

Generate a document

Herersquos a sample code to generate a document

DocxGen=require(rsquodocxtemplaterrsquo) Only for Node Usagenew DocxGen()loadFromFile(tagExampledocxasynctrue)success(function(doc)

docsetTags(first_nameHipp

last_nameEdgarphone0652455478descriptionNew Website

) set the templateVariablesdocapplyTags() apply them (replace all occurences of first_name by Hipp )docoutput() Output the document using Data-URI

)

The different steps are the following

61 Loading a document

A docx can be loaded by itrsquos base64 representation like this

doc=new DocxGen(base64Dataoptions)

However loading the base64Data is not that easy so I created a wrapper function to load a docx from a file via Ajax

Note The options parameter are explained in Configuration

doc=new DocxGen()loadFromFile(documentPathoptions)

The documentPath is the path to the document you want to load The options are the same as in the constructorfunction and Irsquove added the async parameter

bull If async is true the document is loaded asynchronously and returns a promise (eg you can write suc-cess(callback) to get when the document is loaded)

bull If async is false the document is loaded synchronously and returns the document

62 Setting the tags

The tags are the variables that are going to be replaced by their values To set them just use

15

docxtemplater Documentation Release 054

docsetTags(tags)

63 Applying the tags

Applying the tags means opening all files that contain text (eg footer header main document) and replace thevariables by their values

docapplyTags(tags)

Note If you specify an argument for the applyTags method the function setTags(tags) will be called before applyingthe tags

64 Outputing the document

They are several ways to output the document The most basic usage is to download the document

docoutput(options)

Depending on your environment if you donrsquot set any options this will

bull In the browser Download the document using DataURI

bull In Node Save the document with the given fileName (outputdocx by default)

Herersquos the different options parameters

nameTypestring[outputdocx]The name of the file that will be outputed (doesnt work in the browser because of dataUri download)

callbackTypefunctionFunction that is called without arguments when the output is done Is used only in Node (because in the browser the operation is synchronous)

downloadTypeboolean[true]If download is true file will be downloaded automatically with data URIreturns the output file

typeTypestring[base64]The type of zip to return The possible values are (same as in httpstukgithubiojszip generate)base64 (default) the result will be a string the binary in a base64 formstring the result will be a string in binary form 1 byte per charuint8array the result will be a Uint8Array containing the zip This requires a compatible browserarraybuffer the result will be a ArrayBuffer containing the zip This requires a compatible browserblob the result will be a Blob containing the zip This requires a compatible browsernodebuffer the result will be a nodejs Buffer containing the zip This requires nodejs

This function creates the docx file and downloads it on the userrsquos computer The name of the file is downloaddocxfor Chrome and some akward file names for Firefox VEeTHCfSdocxpartdocx and canrsquot be changed because it ishandled by the browser For more informations about how to solve this problem see the Filename Problems sectionon [httpstukgithubiojszip](httpstukgithubiojszip)

16 Chapter 6 Generate a document

docxtemplater Documentation Release 054

Note Note All browsers donrsquot support the download of big files withData URI so you should use the download method for files bigger than 100kBdataimagepngbase64iVBORw0KGgoAAAANSUhEUgAAABcAAAAXCAIAAABvSEP3AAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAACXSURBVDhPtY7BDYAwDAMZhCf7b8YMxeCoatOQJhWcKGxT2zlCyaWcz8Y+X7Bs1TFVJSwIHIYyFkQufWIRVX9cNJyW1QpEo4rixaEe7JuQagAUctb7ZFYFh5MVJPBe84CVBnB42YsZRgKjFDBVg3cI9WbRwXLktQJX8cNIiFhM1ZuTWk7PIYSBhkVcLzwIiCjCxhCjlAkBqYnqFoQQ2AAAAAElFTkSuQmCC

In Node to send the document to the client you can write the following code snippet

out=docoutput(downloadfalsetypestring)ressend(new Buffer(outbinary))

64 Outputing the document 17

docxtemplater Documentation Release 054

18 Chapter 6 Generate a document

CHAPTER 7

Configuration

Here are documented the special options that you can set when creating a new DocxGen to get some more superpower

It documents the options parameter when you do

new DocxGen(dataoptions)

71 Image Replacing

The name of this option qrCode (boolean)

To stay a templating engine I wanted that DocxTemplater doesnrsquot add an image from scratch but rather uses anexisting image that can be detected and DocxTemplater will just change the contents of that image without changingitrsquos style The size of the replaced images will stay the same

So I decided to use the qrCode format which is a format that lets you identify images by their content

The option for this is qrCode (true for on false for off default off)

Note If you donrsquot use that functionality you should disable it because it is quite slow (the image decoding)

Warning The qrCode functionality only works for PNG They is no support for other file formats yet

72 Angular Parser

The name of this option parser (function)

You can set the angular parser with the following code

With a custom parser you can parse the tags to for example add operators like lsquo+rsquo lsquo-lsquo or whatever the way you wantto parse expressions

To enable this you need to specify a custom parser You need to create a parser function

docxtemplater comes shipped with this parser

parser=function(expression)

return

19

docxtemplater Documentation Release 054

getfunction(scope) return scope[expression]

To use the angular-parser do the following

expressions= require(rsquoangular-expressionsrsquo)angularParser= function(tag)

return getexpressionscompile(tag)

new DocxGen(dataparserangularParser)

Note The require() works in the browser if you include vendorangular-parser-browserjs

73 Intelligent LoopTagging

The name of this option intelligentTagging (boolean)

When looping over an element docxtemplater needs to know over which element you want to loop By default it triesto do that intelligently (by looking what XML Tags are between the tags) However if you want to always use theltwtgt tag by default set this option to false

You can always specify over which element you want to loop with the dash loop syntax

20 Chapter 7 Configuration

CHAPTER 8

Command Line Interface (CLI)

This section is about the commandline interface of docxtemplater

The syntax is the following

docxtemplater configjson

The full configjson should be something like that

configdocxFileinputdocxconfigoutputFileoutputdocxconfigqrcodetrueconfigdebugtruefirst_nameJohnlast_nameSmithage62

81 Configjson Syntax

811 Config properties

These are the properties to configure docxtemplater

configdocxFileinputdocx The input file pathconfigoutputFileoutputdocx The output file pathconfigqrcodetrue whether the images should be scanned to replace them by qrcodes (slows down the cli a lot)configdebugtrue whether to show debug output or not

812 Data properties

To add data to your template just use keys that donrsquot start with ldquoconfigrdquo

first_nameJohnlast_nameSmithage62

21

docxtemplater Documentation Release 054

22 Chapter 8 Command Line Interface (CLI)

CHAPTER 9

Full Documentation per method

91 Creating a new Docxgen Object

new DocxGen()

This function returns a new DocxGen Object

new DocxGen(content[Tagsoptions])

contentType stringThe docx template you want to load as plain text

TagsType Object tag_nametag_replacement []Object containing for each tag_name the replacement for this tag For example if you want to replace firstName by David your Object will be firstNameDavid

options object

parserType functionA custom parser to use See angularjs like parsing

intelligentTaggingType boolean [false]If intelligent Tagging is not set to true when using recursive tags (tag and tag) the system will copy paste what is between the start tag and the endtag this could basically corrupt the files if recursive tags are used inside tablesIf intelligent Tagging is set to true and when using recursive tags inside tables the whole column will be copy pasted

qrCodeType boolean [false]If qrCode is set to true DocxGen will look at all the images to find a Qr-Code If the Qr-code matches to a URL this URL will be loaded by ajax (Be aware that the server you want to access needs to allow your request or it wonrsquot work httpstackoverflowcomquestions9310112why-am-i-seeing-an-origin-is-not-allowed-by-access-control-allow-origin-error )

Important the qrCode functionality only works for PNG I donrsquot think I will enable this for other fileformats in the near future

localImageCreatorType function(argcallback) [function that returns an arrow]The function has to be customized only if you want to use the qrCode options (qrCode=true) When the qrcode text starts with gen the image is not going to be loaded by url but DocxGen calls localImageCreator with arg=full Text decoded The callback needs to be called with the image Datacallback(result) in plaintxt format (if you want to create it from a Data-URI you can use JSZipBase64decode(data) to decode a Data-URI to plaintxt)

The default localImageCreator returns a red arrow no matter what the arguments are

localImageCreator= (argcallback) -gtresult=JSZipBase64decode(iVBORw0KGgoAAAANSUhEUgAAABcAAAAXCAIAAABvSEP3AAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAACXSURBVDhPtY7BDYAwDAMZhCf7b8YMxeCoatOQJhWcKGxT2zlCyaWcz8Y+X7Bs1TFVJSwIHIYyFkQufWIRVX9cNJyW1QpEo4rixaEe7JuQagAUctb7ZFYFh5MVJPBe84CVBnB42YsZRgKjFDBVg3cI9WbRwXLktQJX8cNIiFhM1ZuTWk7PIYSBhkVcLzwIiCjCxhCjlAkBqYnqFoQQ2AAAAAElFTkSuQmCC)

23

docxtemplater Documentation Release 054

[Default Image](dataimagepngbase64iVBORw0KGgoAAAANSUhEUgAAABcAAAAXCAIAAABvSEP3AAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAACXSURBVDhPtY7BDYAwDAMZhCf7b8YMxeCoatOQJhWcKGxT2zlCyaWcz8Y+X7Bs1TFVJSwIHIYyFkQufWIRVX9cNJyW1QpEo4rixaEe7JuQagAUctb7ZFYFh5MVJPBe84CVBnB42YsZRgKjFDBVg3cI9WbRwXLktQJX8cNIiFhM1ZuTWk7PIYSBhkVcLzwIiCjCxhCjlAkBqYnqFoQQ2AAAAAElFTkSuQmCC)

qrFinishedCallBackType function () [function that consolelog(ready)]

This function is called if you specify qrCode argument to true in this constructor and will be called when all qrCodes have been replaced (because the qrCode replacing functions are async)

92 Docxgen methods

load(content)

contentType stringThe docx template you want to load as plain text

loadFromFile(path)path

Type stringLoads a docx from a file path

setTags(Tags)

TagsType Object tag_nametag_replacementObject containing for each tag_name the replacement for this tag For example if you want to replace firstName by David your Object will be firstNameDavid

applyTags([Tags])Tags

Type Object tag_nametag_replacementsame as setTagsDefaultthisTags

This function replaces all template variables by their values

output([options])

options object[]

nameTypestring[outputdocx]The name of the file that will be outputed (doesnt work in the browser because of dataUri download)

callbackTypefunctionFunction that is called without arguments when the output is done Is used only in Node (because in the browser the operation is synchronous)

downloadTypeboolean[true]If download is true file will be downloaded automatically with data URIreturns the output file

typeTypestring[base64]The type of zip to return The possible values are (same as in httpstukgithubiojszip generate)base64 (default) the result will be a string the binary in a base64 formstring the result will be a string in binary form 1 byte per charuint8array the result will be a Uint8Array containing the zip This requires a compatible browser

24 Chapter 9 Full Documentation per method

docxtemplater Documentation Release 054

arraybuffer the result will be a ArrayBuffer containing the zip This requires a compatible browserblob the result will be a Blob containing the zip This requires a compatible browsernodebuffer the result will be a nodejs Buffer containing the zip This requires nodejs

This function creates the docx file and downloads it on the userrsquos computer The name of the file is downloaddocx for Chrome and some akward file names for Firefox VEeTHCfSdocxpartdocx and canrsquot be changed because it is handled by the browserFor more informations about how to solve this problem see the Filename Problems section on [httpstukgithubiojszip](httpstukgithubiojszip)

Note All browsers donrsquot support the download of big files with Data URI so you should use the lsquodownloadlsquo method for files bigger than 100kB dataimagepngbase64iVBORw0KGgoAAAANSUhEUgAAABcAAAAXCAIAAABvSEP3AAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAACXSURBVDhPtY7BDYAwDAMZhCf7b8YMxeCoatOQJhWcKGxT2zlCyaWcz8Y+X7Bs1TFVJSwIHIYyFkQufWIRVX9cNJyW1QpEo4rixaEe7JuQagAUctb7ZFYFh5MVJPBe84CVBnB42YsZRgKjFDBVg3cI9WbRwXLktQJX8cNIiFhM1ZuTWk7PIYSBhkVcLzwIiCjCxhCjlAkBqYnqFoQQ2AAAAAElFTkSuQmCC

download(swfpathimgpath[fileName])

swfpathTypestringPath to the swfobjectjs in downloadify

imgpathTypestringPath to the image of the download button

[fileName]TypestringDefaultdefaultdocxName of the file you would like the user to download

This requires to include Downloadifyjs that needs flash version 10 Have a look at the output function if you donrsquot want to depend on it This function has the advantage that it works regardless of the file size

getImageList()

this gets all images that have one of the following extension rsquogifrsquorsquojpegrsquorsquojpgrsquorsquoemfrsquorsquopngrsquoReturn format Array of Object[pathstringfilesZipFile Object]

You shouldrsquont call this method before calling applyTags() because applyTags can modify the images or their path when replacing images with other (particularly when qrCode is set to true which is not the default case) You can call this method after applyTags() without any problems

setImage(pathimgData)

pathTypeStringPath of the image given by getImageList()

imgDataTypeStringimgData in txtplain

This sets the image given by a path and an imgData in txtplainYou shouldrsquont call this method before calling applyTags() because applyTags can modify the images or their path when replacing images with other (particularly when qrCode is set to true which is not the default case) You can call this method after applyTags() without any problems

getFullText([path])

pathTypeStringDefaultworddocumentxmlThis argument determines from which document you want to get the text The main document is called worddocumentxml but they are other documents wordheader1xml wordfooter1xml

returnsTypeStringThe string containing all the text from the document

92 Docxgen methods 25

docxtemplater Documentation Release 054

This method gets only the text of a given document (not the formatting)

getTags()

This function returns the template variables contained in the opened document For example if the content of the documentxml is the following

namefirst_namephone

The function will return[

filenamedocumentxmlvars

nametruefirst_nametruephonetrue

]

If the content contains tagLoops

titlecustomernamephonecustomer

The function will return

[filenamedocumentxmlvars

titletruecustomer

nametruephonetrue

]

26 Chapter 9 Full Documentation per method

CHAPTER 10

Copyright

License

(The MIT license)

Copyright (c) 2013 Edgar Hipp

Permission is hereby granted free of charge to any person obtaining a copy of this software and associated documen-tation files (the ldquoSoftwarerdquo) to deal in the Software without restriction including without limitation the rights to usecopy modify merge publish distribute sublicense andor sell copies of the Software and to permit persons to whomthe Software is furnished to do so subject to the following conditions

The above copyright notice and this permission notice shall be included in all copies or substantial portions of theSoftware

THE SOFTWARE IS PROVIDED ldquoAS ISrdquo WITHOUT WARRANTY OF ANY KIND EXPRESS OR IMPLIEDINCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY FITNESS FOR A PAR-TICULAR PURPOSE AND NONINFRINGEMENT IN NO EVENT SHALL THE AUTHORS OR COPYRIGHTHOLDERS BE LIABLE FOR ANY CLAIM DAMAGES OR OTHER LIABILITY WHETHER IN AN ACTIONOF CONTRACT TORT OR OTHERWISE ARISING FROM OUT OF OR IN CONNECTION WITH THE SOFT-WARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE

27

docxtemplater Documentation Release 054

28 Chapter 10 Copyright

CHAPTER 11

Demos

Including

bull Replace Variables

bull Formating

bull Angular Parsing

bull Loops

bull Loops and tables

bull Lists

bull Replacing images

bull Naming the output

bull Using QrCodes

bull Replacing many images with QrCode

bull Raw Xml Insertion

29

docxtemplater Documentation Release 054

30 Chapter 11 Demos

CHAPTER 12

Indices and tables

bull genindex

bull modindex

bull search

31

docxtemplater Documentation Release 054

32 Chapter 12 Indices and tables

Index

CCommand Line Interface (CLI) 20Configuration 17Copyright 26

FFull_doc 21

GGenerate a Document 13Goals 1

IInstallation 7

Pplatform_support 3

SSyntax 9

33

  • Goals
    • Why you should use a library for this
      • Platform Support
      • Dependencies
      • Installation
        • Node
        • Browser
          • Syntax
            • Synopsis
            • Tag types
            • Loop syntax
            • Dash syntax
            • Inverted Selections
              • Generate a document
                • Loading a document
                • Setting the tags
                • Applying the tags
                • Outputing the document
                  • Configuration
                    • Image Replacing
                    • Angular Parser
                    • Intelligent LoopTagging
                      • Command Line Interface (CLI)
                        • Configjson Syntax
                          • Full Documentation per method
                            • Creating a new Docxgen Object
                            • Docxgen methods
                              • Copyright
                              • Demos
                              • Indices and tables
Page 9: Release 0.5€¦ · Docx is a zipped format that contains some xml. If you want to build a simple replace {tag} If you want to build a simple replace {tag} by value system, it can

docxtemplater Documentation Release 054

6 Chapter 2 Platform Support

CHAPTER 3

Dependencies

1 docxgenjs uses [jszipjs](httpstukgithubiojszip) to zip and unzip the docx files

2 Optionally if you want to be able to name the output files you can use Downloadifyjs which is requiredto use method download Be informed that it uses flash this is why the method is not recommended Thismethod is howewer useful because a lot of browsers are limited for the download size with the Data-URImethod Update I will probably implement in the future a way to use the FileSaver API with [File-SaverJS](httpeligreycomdemosFileSaverjs)

3 Optionnaly if you want to replace images by images situated at a particular URL you can use QR codes Forexample If you store an image at httpwebsitecomimagepng you should encode the URL in QR-Code for-mat [Qr Code Sample](httpqrfreekaywacoml=1amps=8ampd=http3A2F2Fwebsitecom2FimagepngldquoQrcode Sample to httpwebsitecomimagepngrdquo) You can even use bracket tags in imageshttpwebsitecomimagepngcolor=color will take the Tags[color] variable to make a dynamic URL Forthis too work you will need [jsqrcode](httpgithubcomedi9999jsqrcode ldquojsqrcode repositoty forkedrdquo) andinclude the following files in this order (only for browser support node support already comes out of the box)

ltscript type=textjavascript src=gridjsgtltscriptgtltscript type=textjavascript src=versionjsgtltscriptgtltscript type=textjavascript src=detectorjsgtltscriptgtltscript type=textjavascript src=formatinfjsgtltscriptgtltscript type=textjavascript src=errorleveljsgtltscriptgtltscript type=textjavascript src=bitmatjsgtltscriptgtltscript type=textjavascript src=datablockjsgtltscriptgtltscript type=textjavascript src=bmparserjsgtltscriptgtltscript type=textjavascript src=datamaskjsgtltscriptgtltscript type=textjavascript src=rsdecoderjsgtltscriptgtltscript type=textjavascript src=gf256polyjsgtltscriptgtltscript type=textjavascript src=gf256jsgtltscriptgtltscript type=textjavascript src=decoderjsgtltscriptgtltscript type=textjavascript src=qrcodejsgtltscriptgtltscript type=textjavascript src=findpatjsgtltscriptgtltscript type=textjavascript src=alignpatjsgtltscriptgtltscript type=textjavascript src=databrjsgtltscriptgt

7

docxtemplater Documentation Release 054

8 Chapter 3 Dependencies

CHAPTER 4

Installation

41 Node

To install docxtemplater we recommend you to use npm

npm install docxtemplater

If you want to use the command line interface you should use the global flag eg

npm install docxtemplater -g

42 Browser

You will just have to include the docxgenjs or docxgenminjs file

9

docxtemplater Documentation Release 054

10 Chapter 4 Installation

CHAPTER 5

Syntax

The syntax is highly inspired by Mustache The template is created in Microsoft Word or any equivalent that saves todocx

51 Synopsis

A typical docxtemplater template

Hello name

Given the following hash

namersquoEdgarrsquo

Will produce

Hello Edgar

52 Tag types

Like Mustache it has the loopopening and loopclosing brackets

53 Loop syntax

The following template

productsname price C

products

Given the following hash

products

[nameWindowsprice100

11

docxtemplater Documentation Release 054

nameMac OSXprice200nameUbuntuprice0]

will result in

Windows 100 CMac OSX 200 CUbuntu 0C

The loop behaves in the following way

bull If the value is an array it will loop over all the elements of that array

bull If the value is a boolean it will loop once if the value is true keeping the same scope and not loop at all if thevalue is false

Note Because the loops work also with boolean values you can also use them for conditions

54 Dash syntax

It is quite difficult to know on which element you are going to loop By default when using the for loop docxgen willfind that by himself

If between the two tags tag______tag

bull they is the Xml Tag ltwtcgt -gt you are in a table and it will loop over ltwtrgt

bull else -gt it will loop over ltwtgt which is the default Text Tag

With the Dash syntax you pass as a first argument the tag you want to loop on

-wp loop inner loop

In this case this will loop over the first parent ltwpgt tag

55 Inverted Selections

An inverted section begins with a caret (hat) and ends with a slash That is ^person begins a ldquopersonrdquo invertedsection while person ends it

While sections can be used to render text one or more times based on the value of the key inverted sections may rendertext once based on the inverse value of the key That is they will be rendered if the key doesnrsquot exist is false or is anempty list

Template

repoltbgtnameltbgt

repo^repo

No repos (repo

Hash

12 Chapter 5 Syntax

docxtemplater Documentation Release 054

repo []

Output

No repos (

55 Inverted Selections 13

docxtemplater Documentation Release 054

14 Chapter 5 Syntax

CHAPTER 6

Generate a document

Herersquos a sample code to generate a document

DocxGen=require(rsquodocxtemplaterrsquo) Only for Node Usagenew DocxGen()loadFromFile(tagExampledocxasynctrue)success(function(doc)

docsetTags(first_nameHipp

last_nameEdgarphone0652455478descriptionNew Website

) set the templateVariablesdocapplyTags() apply them (replace all occurences of first_name by Hipp )docoutput() Output the document using Data-URI

)

The different steps are the following

61 Loading a document

A docx can be loaded by itrsquos base64 representation like this

doc=new DocxGen(base64Dataoptions)

However loading the base64Data is not that easy so I created a wrapper function to load a docx from a file via Ajax

Note The options parameter are explained in Configuration

doc=new DocxGen()loadFromFile(documentPathoptions)

The documentPath is the path to the document you want to load The options are the same as in the constructorfunction and Irsquove added the async parameter

bull If async is true the document is loaded asynchronously and returns a promise (eg you can write suc-cess(callback) to get when the document is loaded)

bull If async is false the document is loaded synchronously and returns the document

62 Setting the tags

The tags are the variables that are going to be replaced by their values To set them just use

15

docxtemplater Documentation Release 054

docsetTags(tags)

63 Applying the tags

Applying the tags means opening all files that contain text (eg footer header main document) and replace thevariables by their values

docapplyTags(tags)

Note If you specify an argument for the applyTags method the function setTags(tags) will be called before applyingthe tags

64 Outputing the document

They are several ways to output the document The most basic usage is to download the document

docoutput(options)

Depending on your environment if you donrsquot set any options this will

bull In the browser Download the document using DataURI

bull In Node Save the document with the given fileName (outputdocx by default)

Herersquos the different options parameters

nameTypestring[outputdocx]The name of the file that will be outputed (doesnt work in the browser because of dataUri download)

callbackTypefunctionFunction that is called without arguments when the output is done Is used only in Node (because in the browser the operation is synchronous)

downloadTypeboolean[true]If download is true file will be downloaded automatically with data URIreturns the output file

typeTypestring[base64]The type of zip to return The possible values are (same as in httpstukgithubiojszip generate)base64 (default) the result will be a string the binary in a base64 formstring the result will be a string in binary form 1 byte per charuint8array the result will be a Uint8Array containing the zip This requires a compatible browserarraybuffer the result will be a ArrayBuffer containing the zip This requires a compatible browserblob the result will be a Blob containing the zip This requires a compatible browsernodebuffer the result will be a nodejs Buffer containing the zip This requires nodejs

This function creates the docx file and downloads it on the userrsquos computer The name of the file is downloaddocxfor Chrome and some akward file names for Firefox VEeTHCfSdocxpartdocx and canrsquot be changed because it ishandled by the browser For more informations about how to solve this problem see the Filename Problems sectionon [httpstukgithubiojszip](httpstukgithubiojszip)

16 Chapter 6 Generate a document

docxtemplater Documentation Release 054

Note Note All browsers donrsquot support the download of big files withData URI so you should use the download method for files bigger than 100kBdataimagepngbase64iVBORw0KGgoAAAANSUhEUgAAABcAAAAXCAIAAABvSEP3AAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAACXSURBVDhPtY7BDYAwDAMZhCf7b8YMxeCoatOQJhWcKGxT2zlCyaWcz8Y+X7Bs1TFVJSwIHIYyFkQufWIRVX9cNJyW1QpEo4rixaEe7JuQagAUctb7ZFYFh5MVJPBe84CVBnB42YsZRgKjFDBVg3cI9WbRwXLktQJX8cNIiFhM1ZuTWk7PIYSBhkVcLzwIiCjCxhCjlAkBqYnqFoQQ2AAAAAElFTkSuQmCC

In Node to send the document to the client you can write the following code snippet

out=docoutput(downloadfalsetypestring)ressend(new Buffer(outbinary))

64 Outputing the document 17

docxtemplater Documentation Release 054

18 Chapter 6 Generate a document

CHAPTER 7

Configuration

Here are documented the special options that you can set when creating a new DocxGen to get some more superpower

It documents the options parameter when you do

new DocxGen(dataoptions)

71 Image Replacing

The name of this option qrCode (boolean)

To stay a templating engine I wanted that DocxTemplater doesnrsquot add an image from scratch but rather uses anexisting image that can be detected and DocxTemplater will just change the contents of that image without changingitrsquos style The size of the replaced images will stay the same

So I decided to use the qrCode format which is a format that lets you identify images by their content

The option for this is qrCode (true for on false for off default off)

Note If you donrsquot use that functionality you should disable it because it is quite slow (the image decoding)

Warning The qrCode functionality only works for PNG They is no support for other file formats yet

72 Angular Parser

The name of this option parser (function)

You can set the angular parser with the following code

With a custom parser you can parse the tags to for example add operators like lsquo+rsquo lsquo-lsquo or whatever the way you wantto parse expressions

To enable this you need to specify a custom parser You need to create a parser function

docxtemplater comes shipped with this parser

parser=function(expression)

return

19

docxtemplater Documentation Release 054

getfunction(scope) return scope[expression]

To use the angular-parser do the following

expressions= require(rsquoangular-expressionsrsquo)angularParser= function(tag)

return getexpressionscompile(tag)

new DocxGen(dataparserangularParser)

Note The require() works in the browser if you include vendorangular-parser-browserjs

73 Intelligent LoopTagging

The name of this option intelligentTagging (boolean)

When looping over an element docxtemplater needs to know over which element you want to loop By default it triesto do that intelligently (by looking what XML Tags are between the tags) However if you want to always use theltwtgt tag by default set this option to false

You can always specify over which element you want to loop with the dash loop syntax

20 Chapter 7 Configuration

CHAPTER 8

Command Line Interface (CLI)

This section is about the commandline interface of docxtemplater

The syntax is the following

docxtemplater configjson

The full configjson should be something like that

configdocxFileinputdocxconfigoutputFileoutputdocxconfigqrcodetrueconfigdebugtruefirst_nameJohnlast_nameSmithage62

81 Configjson Syntax

811 Config properties

These are the properties to configure docxtemplater

configdocxFileinputdocx The input file pathconfigoutputFileoutputdocx The output file pathconfigqrcodetrue whether the images should be scanned to replace them by qrcodes (slows down the cli a lot)configdebugtrue whether to show debug output or not

812 Data properties

To add data to your template just use keys that donrsquot start with ldquoconfigrdquo

first_nameJohnlast_nameSmithage62

21

docxtemplater Documentation Release 054

22 Chapter 8 Command Line Interface (CLI)

CHAPTER 9

Full Documentation per method

91 Creating a new Docxgen Object

new DocxGen()

This function returns a new DocxGen Object

new DocxGen(content[Tagsoptions])

contentType stringThe docx template you want to load as plain text

TagsType Object tag_nametag_replacement []Object containing for each tag_name the replacement for this tag For example if you want to replace firstName by David your Object will be firstNameDavid

options object

parserType functionA custom parser to use See angularjs like parsing

intelligentTaggingType boolean [false]If intelligent Tagging is not set to true when using recursive tags (tag and tag) the system will copy paste what is between the start tag and the endtag this could basically corrupt the files if recursive tags are used inside tablesIf intelligent Tagging is set to true and when using recursive tags inside tables the whole column will be copy pasted

qrCodeType boolean [false]If qrCode is set to true DocxGen will look at all the images to find a Qr-Code If the Qr-code matches to a URL this URL will be loaded by ajax (Be aware that the server you want to access needs to allow your request or it wonrsquot work httpstackoverflowcomquestions9310112why-am-i-seeing-an-origin-is-not-allowed-by-access-control-allow-origin-error )

Important the qrCode functionality only works for PNG I donrsquot think I will enable this for other fileformats in the near future

localImageCreatorType function(argcallback) [function that returns an arrow]The function has to be customized only if you want to use the qrCode options (qrCode=true) When the qrcode text starts with gen the image is not going to be loaded by url but DocxGen calls localImageCreator with arg=full Text decoded The callback needs to be called with the image Datacallback(result) in plaintxt format (if you want to create it from a Data-URI you can use JSZipBase64decode(data) to decode a Data-URI to plaintxt)

The default localImageCreator returns a red arrow no matter what the arguments are

localImageCreator= (argcallback) -gtresult=JSZipBase64decode(iVBORw0KGgoAAAANSUhEUgAAABcAAAAXCAIAAABvSEP3AAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAACXSURBVDhPtY7BDYAwDAMZhCf7b8YMxeCoatOQJhWcKGxT2zlCyaWcz8Y+X7Bs1TFVJSwIHIYyFkQufWIRVX9cNJyW1QpEo4rixaEe7JuQagAUctb7ZFYFh5MVJPBe84CVBnB42YsZRgKjFDBVg3cI9WbRwXLktQJX8cNIiFhM1ZuTWk7PIYSBhkVcLzwIiCjCxhCjlAkBqYnqFoQQ2AAAAAElFTkSuQmCC)

23

docxtemplater Documentation Release 054

[Default Image](dataimagepngbase64iVBORw0KGgoAAAANSUhEUgAAABcAAAAXCAIAAABvSEP3AAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAACXSURBVDhPtY7BDYAwDAMZhCf7b8YMxeCoatOQJhWcKGxT2zlCyaWcz8Y+X7Bs1TFVJSwIHIYyFkQufWIRVX9cNJyW1QpEo4rixaEe7JuQagAUctb7ZFYFh5MVJPBe84CVBnB42YsZRgKjFDBVg3cI9WbRwXLktQJX8cNIiFhM1ZuTWk7PIYSBhkVcLzwIiCjCxhCjlAkBqYnqFoQQ2AAAAAElFTkSuQmCC)

qrFinishedCallBackType function () [function that consolelog(ready)]

This function is called if you specify qrCode argument to true in this constructor and will be called when all qrCodes have been replaced (because the qrCode replacing functions are async)

92 Docxgen methods

load(content)

contentType stringThe docx template you want to load as plain text

loadFromFile(path)path

Type stringLoads a docx from a file path

setTags(Tags)

TagsType Object tag_nametag_replacementObject containing for each tag_name the replacement for this tag For example if you want to replace firstName by David your Object will be firstNameDavid

applyTags([Tags])Tags

Type Object tag_nametag_replacementsame as setTagsDefaultthisTags

This function replaces all template variables by their values

output([options])

options object[]

nameTypestring[outputdocx]The name of the file that will be outputed (doesnt work in the browser because of dataUri download)

callbackTypefunctionFunction that is called without arguments when the output is done Is used only in Node (because in the browser the operation is synchronous)

downloadTypeboolean[true]If download is true file will be downloaded automatically with data URIreturns the output file

typeTypestring[base64]The type of zip to return The possible values are (same as in httpstukgithubiojszip generate)base64 (default) the result will be a string the binary in a base64 formstring the result will be a string in binary form 1 byte per charuint8array the result will be a Uint8Array containing the zip This requires a compatible browser

24 Chapter 9 Full Documentation per method

docxtemplater Documentation Release 054

arraybuffer the result will be a ArrayBuffer containing the zip This requires a compatible browserblob the result will be a Blob containing the zip This requires a compatible browsernodebuffer the result will be a nodejs Buffer containing the zip This requires nodejs

This function creates the docx file and downloads it on the userrsquos computer The name of the file is downloaddocx for Chrome and some akward file names for Firefox VEeTHCfSdocxpartdocx and canrsquot be changed because it is handled by the browserFor more informations about how to solve this problem see the Filename Problems section on [httpstukgithubiojszip](httpstukgithubiojszip)

Note All browsers donrsquot support the download of big files with Data URI so you should use the lsquodownloadlsquo method for files bigger than 100kB dataimagepngbase64iVBORw0KGgoAAAANSUhEUgAAABcAAAAXCAIAAABvSEP3AAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAACXSURBVDhPtY7BDYAwDAMZhCf7b8YMxeCoatOQJhWcKGxT2zlCyaWcz8Y+X7Bs1TFVJSwIHIYyFkQufWIRVX9cNJyW1QpEo4rixaEe7JuQagAUctb7ZFYFh5MVJPBe84CVBnB42YsZRgKjFDBVg3cI9WbRwXLktQJX8cNIiFhM1ZuTWk7PIYSBhkVcLzwIiCjCxhCjlAkBqYnqFoQQ2AAAAAElFTkSuQmCC

download(swfpathimgpath[fileName])

swfpathTypestringPath to the swfobjectjs in downloadify

imgpathTypestringPath to the image of the download button

[fileName]TypestringDefaultdefaultdocxName of the file you would like the user to download

This requires to include Downloadifyjs that needs flash version 10 Have a look at the output function if you donrsquot want to depend on it This function has the advantage that it works regardless of the file size

getImageList()

this gets all images that have one of the following extension rsquogifrsquorsquojpegrsquorsquojpgrsquorsquoemfrsquorsquopngrsquoReturn format Array of Object[pathstringfilesZipFile Object]

You shouldrsquont call this method before calling applyTags() because applyTags can modify the images or their path when replacing images with other (particularly when qrCode is set to true which is not the default case) You can call this method after applyTags() without any problems

setImage(pathimgData)

pathTypeStringPath of the image given by getImageList()

imgDataTypeStringimgData in txtplain

This sets the image given by a path and an imgData in txtplainYou shouldrsquont call this method before calling applyTags() because applyTags can modify the images or their path when replacing images with other (particularly when qrCode is set to true which is not the default case) You can call this method after applyTags() without any problems

getFullText([path])

pathTypeStringDefaultworddocumentxmlThis argument determines from which document you want to get the text The main document is called worddocumentxml but they are other documents wordheader1xml wordfooter1xml

returnsTypeStringThe string containing all the text from the document

92 Docxgen methods 25

docxtemplater Documentation Release 054

This method gets only the text of a given document (not the formatting)

getTags()

This function returns the template variables contained in the opened document For example if the content of the documentxml is the following

namefirst_namephone

The function will return[

filenamedocumentxmlvars

nametruefirst_nametruephonetrue

]

If the content contains tagLoops

titlecustomernamephonecustomer

The function will return

[filenamedocumentxmlvars

titletruecustomer

nametruephonetrue

]

26 Chapter 9 Full Documentation per method

CHAPTER 10

Copyright

License

(The MIT license)

Copyright (c) 2013 Edgar Hipp

Permission is hereby granted free of charge to any person obtaining a copy of this software and associated documen-tation files (the ldquoSoftwarerdquo) to deal in the Software without restriction including without limitation the rights to usecopy modify merge publish distribute sublicense andor sell copies of the Software and to permit persons to whomthe Software is furnished to do so subject to the following conditions

The above copyright notice and this permission notice shall be included in all copies or substantial portions of theSoftware

THE SOFTWARE IS PROVIDED ldquoAS ISrdquo WITHOUT WARRANTY OF ANY KIND EXPRESS OR IMPLIEDINCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY FITNESS FOR A PAR-TICULAR PURPOSE AND NONINFRINGEMENT IN NO EVENT SHALL THE AUTHORS OR COPYRIGHTHOLDERS BE LIABLE FOR ANY CLAIM DAMAGES OR OTHER LIABILITY WHETHER IN AN ACTIONOF CONTRACT TORT OR OTHERWISE ARISING FROM OUT OF OR IN CONNECTION WITH THE SOFT-WARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE

27

docxtemplater Documentation Release 054

28 Chapter 10 Copyright

CHAPTER 11

Demos

Including

bull Replace Variables

bull Formating

bull Angular Parsing

bull Loops

bull Loops and tables

bull Lists

bull Replacing images

bull Naming the output

bull Using QrCodes

bull Replacing many images with QrCode

bull Raw Xml Insertion

29

docxtemplater Documentation Release 054

30 Chapter 11 Demos

CHAPTER 12

Indices and tables

bull genindex

bull modindex

bull search

31

docxtemplater Documentation Release 054

32 Chapter 12 Indices and tables

Index

CCommand Line Interface (CLI) 20Configuration 17Copyright 26

FFull_doc 21

GGenerate a Document 13Goals 1

IInstallation 7

Pplatform_support 3

SSyntax 9

33

  • Goals
    • Why you should use a library for this
      • Platform Support
      • Dependencies
      • Installation
        • Node
        • Browser
          • Syntax
            • Synopsis
            • Tag types
            • Loop syntax
            • Dash syntax
            • Inverted Selections
              • Generate a document
                • Loading a document
                • Setting the tags
                • Applying the tags
                • Outputing the document
                  • Configuration
                    • Image Replacing
                    • Angular Parser
                    • Intelligent LoopTagging
                      • Command Line Interface (CLI)
                        • Configjson Syntax
                          • Full Documentation per method
                            • Creating a new Docxgen Object
                            • Docxgen methods
                              • Copyright
                              • Demos
                              • Indices and tables
Page 10: Release 0.5€¦ · Docx is a zipped format that contains some xml. If you want to build a simple replace {tag} If you want to build a simple replace {tag} by value system, it can

CHAPTER 3

Dependencies

1 docxgenjs uses [jszipjs](httpstukgithubiojszip) to zip and unzip the docx files

2 Optionally if you want to be able to name the output files you can use Downloadifyjs which is requiredto use method download Be informed that it uses flash this is why the method is not recommended Thismethod is howewer useful because a lot of browsers are limited for the download size with the Data-URImethod Update I will probably implement in the future a way to use the FileSaver API with [File-SaverJS](httpeligreycomdemosFileSaverjs)

3 Optionnaly if you want to replace images by images situated at a particular URL you can use QR codes Forexample If you store an image at httpwebsitecomimagepng you should encode the URL in QR-Code for-mat [Qr Code Sample](httpqrfreekaywacoml=1amps=8ampd=http3A2F2Fwebsitecom2FimagepngldquoQrcode Sample to httpwebsitecomimagepngrdquo) You can even use bracket tags in imageshttpwebsitecomimagepngcolor=color will take the Tags[color] variable to make a dynamic URL Forthis too work you will need [jsqrcode](httpgithubcomedi9999jsqrcode ldquojsqrcode repositoty forkedrdquo) andinclude the following files in this order (only for browser support node support already comes out of the box)

ltscript type=textjavascript src=gridjsgtltscriptgtltscript type=textjavascript src=versionjsgtltscriptgtltscript type=textjavascript src=detectorjsgtltscriptgtltscript type=textjavascript src=formatinfjsgtltscriptgtltscript type=textjavascript src=errorleveljsgtltscriptgtltscript type=textjavascript src=bitmatjsgtltscriptgtltscript type=textjavascript src=datablockjsgtltscriptgtltscript type=textjavascript src=bmparserjsgtltscriptgtltscript type=textjavascript src=datamaskjsgtltscriptgtltscript type=textjavascript src=rsdecoderjsgtltscriptgtltscript type=textjavascript src=gf256polyjsgtltscriptgtltscript type=textjavascript src=gf256jsgtltscriptgtltscript type=textjavascript src=decoderjsgtltscriptgtltscript type=textjavascript src=qrcodejsgtltscriptgtltscript type=textjavascript src=findpatjsgtltscriptgtltscript type=textjavascript src=alignpatjsgtltscriptgtltscript type=textjavascript src=databrjsgtltscriptgt

7

docxtemplater Documentation Release 054

8 Chapter 3 Dependencies

CHAPTER 4

Installation

41 Node

To install docxtemplater we recommend you to use npm

npm install docxtemplater

If you want to use the command line interface you should use the global flag eg

npm install docxtemplater -g

42 Browser

You will just have to include the docxgenjs or docxgenminjs file

9

docxtemplater Documentation Release 054

10 Chapter 4 Installation

CHAPTER 5

Syntax

The syntax is highly inspired by Mustache The template is created in Microsoft Word or any equivalent that saves todocx

51 Synopsis

A typical docxtemplater template

Hello name

Given the following hash

namersquoEdgarrsquo

Will produce

Hello Edgar

52 Tag types

Like Mustache it has the loopopening and loopclosing brackets

53 Loop syntax

The following template

productsname price C

products

Given the following hash

products

[nameWindowsprice100

11

docxtemplater Documentation Release 054

nameMac OSXprice200nameUbuntuprice0]

will result in

Windows 100 CMac OSX 200 CUbuntu 0C

The loop behaves in the following way

bull If the value is an array it will loop over all the elements of that array

bull If the value is a boolean it will loop once if the value is true keeping the same scope and not loop at all if thevalue is false

Note Because the loops work also with boolean values you can also use them for conditions

54 Dash syntax

It is quite difficult to know on which element you are going to loop By default when using the for loop docxgen willfind that by himself

If between the two tags tag______tag

bull they is the Xml Tag ltwtcgt -gt you are in a table and it will loop over ltwtrgt

bull else -gt it will loop over ltwtgt which is the default Text Tag

With the Dash syntax you pass as a first argument the tag you want to loop on

-wp loop inner loop

In this case this will loop over the first parent ltwpgt tag

55 Inverted Selections

An inverted section begins with a caret (hat) and ends with a slash That is ^person begins a ldquopersonrdquo invertedsection while person ends it

While sections can be used to render text one or more times based on the value of the key inverted sections may rendertext once based on the inverse value of the key That is they will be rendered if the key doesnrsquot exist is false or is anempty list

Template

repoltbgtnameltbgt

repo^repo

No repos (repo

Hash

12 Chapter 5 Syntax

docxtemplater Documentation Release 054

repo []

Output

No repos (

55 Inverted Selections 13

docxtemplater Documentation Release 054

14 Chapter 5 Syntax

CHAPTER 6

Generate a document

Herersquos a sample code to generate a document

DocxGen=require(rsquodocxtemplaterrsquo) Only for Node Usagenew DocxGen()loadFromFile(tagExampledocxasynctrue)success(function(doc)

docsetTags(first_nameHipp

last_nameEdgarphone0652455478descriptionNew Website

) set the templateVariablesdocapplyTags() apply them (replace all occurences of first_name by Hipp )docoutput() Output the document using Data-URI

)

The different steps are the following

61 Loading a document

A docx can be loaded by itrsquos base64 representation like this

doc=new DocxGen(base64Dataoptions)

However loading the base64Data is not that easy so I created a wrapper function to load a docx from a file via Ajax

Note The options parameter are explained in Configuration

doc=new DocxGen()loadFromFile(documentPathoptions)

The documentPath is the path to the document you want to load The options are the same as in the constructorfunction and Irsquove added the async parameter

bull If async is true the document is loaded asynchronously and returns a promise (eg you can write suc-cess(callback) to get when the document is loaded)

bull If async is false the document is loaded synchronously and returns the document

62 Setting the tags

The tags are the variables that are going to be replaced by their values To set them just use

15

docxtemplater Documentation Release 054

docsetTags(tags)

63 Applying the tags

Applying the tags means opening all files that contain text (eg footer header main document) and replace thevariables by their values

docapplyTags(tags)

Note If you specify an argument for the applyTags method the function setTags(tags) will be called before applyingthe tags

64 Outputing the document

They are several ways to output the document The most basic usage is to download the document

docoutput(options)

Depending on your environment if you donrsquot set any options this will

bull In the browser Download the document using DataURI

bull In Node Save the document with the given fileName (outputdocx by default)

Herersquos the different options parameters

nameTypestring[outputdocx]The name of the file that will be outputed (doesnt work in the browser because of dataUri download)

callbackTypefunctionFunction that is called without arguments when the output is done Is used only in Node (because in the browser the operation is synchronous)

downloadTypeboolean[true]If download is true file will be downloaded automatically with data URIreturns the output file

typeTypestring[base64]The type of zip to return The possible values are (same as in httpstukgithubiojszip generate)base64 (default) the result will be a string the binary in a base64 formstring the result will be a string in binary form 1 byte per charuint8array the result will be a Uint8Array containing the zip This requires a compatible browserarraybuffer the result will be a ArrayBuffer containing the zip This requires a compatible browserblob the result will be a Blob containing the zip This requires a compatible browsernodebuffer the result will be a nodejs Buffer containing the zip This requires nodejs

This function creates the docx file and downloads it on the userrsquos computer The name of the file is downloaddocxfor Chrome and some akward file names for Firefox VEeTHCfSdocxpartdocx and canrsquot be changed because it ishandled by the browser For more informations about how to solve this problem see the Filename Problems sectionon [httpstukgithubiojszip](httpstukgithubiojszip)

16 Chapter 6 Generate a document

docxtemplater Documentation Release 054

Note Note All browsers donrsquot support the download of big files withData URI so you should use the download method for files bigger than 100kBdataimagepngbase64iVBORw0KGgoAAAANSUhEUgAAABcAAAAXCAIAAABvSEP3AAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAACXSURBVDhPtY7BDYAwDAMZhCf7b8YMxeCoatOQJhWcKGxT2zlCyaWcz8Y+X7Bs1TFVJSwIHIYyFkQufWIRVX9cNJyW1QpEo4rixaEe7JuQagAUctb7ZFYFh5MVJPBe84CVBnB42YsZRgKjFDBVg3cI9WbRwXLktQJX8cNIiFhM1ZuTWk7PIYSBhkVcLzwIiCjCxhCjlAkBqYnqFoQQ2AAAAAElFTkSuQmCC

In Node to send the document to the client you can write the following code snippet

out=docoutput(downloadfalsetypestring)ressend(new Buffer(outbinary))

64 Outputing the document 17

docxtemplater Documentation Release 054

18 Chapter 6 Generate a document

CHAPTER 7

Configuration

Here are documented the special options that you can set when creating a new DocxGen to get some more superpower

It documents the options parameter when you do

new DocxGen(dataoptions)

71 Image Replacing

The name of this option qrCode (boolean)

To stay a templating engine I wanted that DocxTemplater doesnrsquot add an image from scratch but rather uses anexisting image that can be detected and DocxTemplater will just change the contents of that image without changingitrsquos style The size of the replaced images will stay the same

So I decided to use the qrCode format which is a format that lets you identify images by their content

The option for this is qrCode (true for on false for off default off)

Note If you donrsquot use that functionality you should disable it because it is quite slow (the image decoding)

Warning The qrCode functionality only works for PNG They is no support for other file formats yet

72 Angular Parser

The name of this option parser (function)

You can set the angular parser with the following code

With a custom parser you can parse the tags to for example add operators like lsquo+rsquo lsquo-lsquo or whatever the way you wantto parse expressions

To enable this you need to specify a custom parser You need to create a parser function

docxtemplater comes shipped with this parser

parser=function(expression)

return

19

docxtemplater Documentation Release 054

getfunction(scope) return scope[expression]

To use the angular-parser do the following

expressions= require(rsquoangular-expressionsrsquo)angularParser= function(tag)

return getexpressionscompile(tag)

new DocxGen(dataparserangularParser)

Note The require() works in the browser if you include vendorangular-parser-browserjs

73 Intelligent LoopTagging

The name of this option intelligentTagging (boolean)

When looping over an element docxtemplater needs to know over which element you want to loop By default it triesto do that intelligently (by looking what XML Tags are between the tags) However if you want to always use theltwtgt tag by default set this option to false

You can always specify over which element you want to loop with the dash loop syntax

20 Chapter 7 Configuration

CHAPTER 8

Command Line Interface (CLI)

This section is about the commandline interface of docxtemplater

The syntax is the following

docxtemplater configjson

The full configjson should be something like that

configdocxFileinputdocxconfigoutputFileoutputdocxconfigqrcodetrueconfigdebugtruefirst_nameJohnlast_nameSmithage62

81 Configjson Syntax

811 Config properties

These are the properties to configure docxtemplater

configdocxFileinputdocx The input file pathconfigoutputFileoutputdocx The output file pathconfigqrcodetrue whether the images should be scanned to replace them by qrcodes (slows down the cli a lot)configdebugtrue whether to show debug output or not

812 Data properties

To add data to your template just use keys that donrsquot start with ldquoconfigrdquo

first_nameJohnlast_nameSmithage62

21

docxtemplater Documentation Release 054

22 Chapter 8 Command Line Interface (CLI)

CHAPTER 9

Full Documentation per method

91 Creating a new Docxgen Object

new DocxGen()

This function returns a new DocxGen Object

new DocxGen(content[Tagsoptions])

contentType stringThe docx template you want to load as plain text

TagsType Object tag_nametag_replacement []Object containing for each tag_name the replacement for this tag For example if you want to replace firstName by David your Object will be firstNameDavid

options object

parserType functionA custom parser to use See angularjs like parsing

intelligentTaggingType boolean [false]If intelligent Tagging is not set to true when using recursive tags (tag and tag) the system will copy paste what is between the start tag and the endtag this could basically corrupt the files if recursive tags are used inside tablesIf intelligent Tagging is set to true and when using recursive tags inside tables the whole column will be copy pasted

qrCodeType boolean [false]If qrCode is set to true DocxGen will look at all the images to find a Qr-Code If the Qr-code matches to a URL this URL will be loaded by ajax (Be aware that the server you want to access needs to allow your request or it wonrsquot work httpstackoverflowcomquestions9310112why-am-i-seeing-an-origin-is-not-allowed-by-access-control-allow-origin-error )

Important the qrCode functionality only works for PNG I donrsquot think I will enable this for other fileformats in the near future

localImageCreatorType function(argcallback) [function that returns an arrow]The function has to be customized only if you want to use the qrCode options (qrCode=true) When the qrcode text starts with gen the image is not going to be loaded by url but DocxGen calls localImageCreator with arg=full Text decoded The callback needs to be called with the image Datacallback(result) in plaintxt format (if you want to create it from a Data-URI you can use JSZipBase64decode(data) to decode a Data-URI to plaintxt)

The default localImageCreator returns a red arrow no matter what the arguments are

localImageCreator= (argcallback) -gtresult=JSZipBase64decode(iVBORw0KGgoAAAANSUhEUgAAABcAAAAXCAIAAABvSEP3AAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAACXSURBVDhPtY7BDYAwDAMZhCf7b8YMxeCoatOQJhWcKGxT2zlCyaWcz8Y+X7Bs1TFVJSwIHIYyFkQufWIRVX9cNJyW1QpEo4rixaEe7JuQagAUctb7ZFYFh5MVJPBe84CVBnB42YsZRgKjFDBVg3cI9WbRwXLktQJX8cNIiFhM1ZuTWk7PIYSBhkVcLzwIiCjCxhCjlAkBqYnqFoQQ2AAAAAElFTkSuQmCC)

23

docxtemplater Documentation Release 054

[Default Image](dataimagepngbase64iVBORw0KGgoAAAANSUhEUgAAABcAAAAXCAIAAABvSEP3AAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAACXSURBVDhPtY7BDYAwDAMZhCf7b8YMxeCoatOQJhWcKGxT2zlCyaWcz8Y+X7Bs1TFVJSwIHIYyFkQufWIRVX9cNJyW1QpEo4rixaEe7JuQagAUctb7ZFYFh5MVJPBe84CVBnB42YsZRgKjFDBVg3cI9WbRwXLktQJX8cNIiFhM1ZuTWk7PIYSBhkVcLzwIiCjCxhCjlAkBqYnqFoQQ2AAAAAElFTkSuQmCC)

qrFinishedCallBackType function () [function that consolelog(ready)]

This function is called if you specify qrCode argument to true in this constructor and will be called when all qrCodes have been replaced (because the qrCode replacing functions are async)

92 Docxgen methods

load(content)

contentType stringThe docx template you want to load as plain text

loadFromFile(path)path

Type stringLoads a docx from a file path

setTags(Tags)

TagsType Object tag_nametag_replacementObject containing for each tag_name the replacement for this tag For example if you want to replace firstName by David your Object will be firstNameDavid

applyTags([Tags])Tags

Type Object tag_nametag_replacementsame as setTagsDefaultthisTags

This function replaces all template variables by their values

output([options])

options object[]

nameTypestring[outputdocx]The name of the file that will be outputed (doesnt work in the browser because of dataUri download)

callbackTypefunctionFunction that is called without arguments when the output is done Is used only in Node (because in the browser the operation is synchronous)

downloadTypeboolean[true]If download is true file will be downloaded automatically with data URIreturns the output file

typeTypestring[base64]The type of zip to return The possible values are (same as in httpstukgithubiojszip generate)base64 (default) the result will be a string the binary in a base64 formstring the result will be a string in binary form 1 byte per charuint8array the result will be a Uint8Array containing the zip This requires a compatible browser

24 Chapter 9 Full Documentation per method

docxtemplater Documentation Release 054

arraybuffer the result will be a ArrayBuffer containing the zip This requires a compatible browserblob the result will be a Blob containing the zip This requires a compatible browsernodebuffer the result will be a nodejs Buffer containing the zip This requires nodejs

This function creates the docx file and downloads it on the userrsquos computer The name of the file is downloaddocx for Chrome and some akward file names for Firefox VEeTHCfSdocxpartdocx and canrsquot be changed because it is handled by the browserFor more informations about how to solve this problem see the Filename Problems section on [httpstukgithubiojszip](httpstukgithubiojszip)

Note All browsers donrsquot support the download of big files with Data URI so you should use the lsquodownloadlsquo method for files bigger than 100kB dataimagepngbase64iVBORw0KGgoAAAANSUhEUgAAABcAAAAXCAIAAABvSEP3AAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAACXSURBVDhPtY7BDYAwDAMZhCf7b8YMxeCoatOQJhWcKGxT2zlCyaWcz8Y+X7Bs1TFVJSwIHIYyFkQufWIRVX9cNJyW1QpEo4rixaEe7JuQagAUctb7ZFYFh5MVJPBe84CVBnB42YsZRgKjFDBVg3cI9WbRwXLktQJX8cNIiFhM1ZuTWk7PIYSBhkVcLzwIiCjCxhCjlAkBqYnqFoQQ2AAAAAElFTkSuQmCC

download(swfpathimgpath[fileName])

swfpathTypestringPath to the swfobjectjs in downloadify

imgpathTypestringPath to the image of the download button

[fileName]TypestringDefaultdefaultdocxName of the file you would like the user to download

This requires to include Downloadifyjs that needs flash version 10 Have a look at the output function if you donrsquot want to depend on it This function has the advantage that it works regardless of the file size

getImageList()

this gets all images that have one of the following extension rsquogifrsquorsquojpegrsquorsquojpgrsquorsquoemfrsquorsquopngrsquoReturn format Array of Object[pathstringfilesZipFile Object]

You shouldrsquont call this method before calling applyTags() because applyTags can modify the images or their path when replacing images with other (particularly when qrCode is set to true which is not the default case) You can call this method after applyTags() without any problems

setImage(pathimgData)

pathTypeStringPath of the image given by getImageList()

imgDataTypeStringimgData in txtplain

This sets the image given by a path and an imgData in txtplainYou shouldrsquont call this method before calling applyTags() because applyTags can modify the images or their path when replacing images with other (particularly when qrCode is set to true which is not the default case) You can call this method after applyTags() without any problems

getFullText([path])

pathTypeStringDefaultworddocumentxmlThis argument determines from which document you want to get the text The main document is called worddocumentxml but they are other documents wordheader1xml wordfooter1xml

returnsTypeStringThe string containing all the text from the document

92 Docxgen methods 25

docxtemplater Documentation Release 054

This method gets only the text of a given document (not the formatting)

getTags()

This function returns the template variables contained in the opened document For example if the content of the documentxml is the following

namefirst_namephone

The function will return[

filenamedocumentxmlvars

nametruefirst_nametruephonetrue

]

If the content contains tagLoops

titlecustomernamephonecustomer

The function will return

[filenamedocumentxmlvars

titletruecustomer

nametruephonetrue

]

26 Chapter 9 Full Documentation per method

CHAPTER 10

Copyright

License

(The MIT license)

Copyright (c) 2013 Edgar Hipp

Permission is hereby granted free of charge to any person obtaining a copy of this software and associated documen-tation files (the ldquoSoftwarerdquo) to deal in the Software without restriction including without limitation the rights to usecopy modify merge publish distribute sublicense andor sell copies of the Software and to permit persons to whomthe Software is furnished to do so subject to the following conditions

The above copyright notice and this permission notice shall be included in all copies or substantial portions of theSoftware

THE SOFTWARE IS PROVIDED ldquoAS ISrdquo WITHOUT WARRANTY OF ANY KIND EXPRESS OR IMPLIEDINCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY FITNESS FOR A PAR-TICULAR PURPOSE AND NONINFRINGEMENT IN NO EVENT SHALL THE AUTHORS OR COPYRIGHTHOLDERS BE LIABLE FOR ANY CLAIM DAMAGES OR OTHER LIABILITY WHETHER IN AN ACTIONOF CONTRACT TORT OR OTHERWISE ARISING FROM OUT OF OR IN CONNECTION WITH THE SOFT-WARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE

27

docxtemplater Documentation Release 054

28 Chapter 10 Copyright

CHAPTER 11

Demos

Including

bull Replace Variables

bull Formating

bull Angular Parsing

bull Loops

bull Loops and tables

bull Lists

bull Replacing images

bull Naming the output

bull Using QrCodes

bull Replacing many images with QrCode

bull Raw Xml Insertion

29

docxtemplater Documentation Release 054

30 Chapter 11 Demos

CHAPTER 12

Indices and tables

bull genindex

bull modindex

bull search

31

docxtemplater Documentation Release 054

32 Chapter 12 Indices and tables

Index

CCommand Line Interface (CLI) 20Configuration 17Copyright 26

FFull_doc 21

GGenerate a Document 13Goals 1

IInstallation 7

Pplatform_support 3

SSyntax 9

33

  • Goals
    • Why you should use a library for this
      • Platform Support
      • Dependencies
      • Installation
        • Node
        • Browser
          • Syntax
            • Synopsis
            • Tag types
            • Loop syntax
            • Dash syntax
            • Inverted Selections
              • Generate a document
                • Loading a document
                • Setting the tags
                • Applying the tags
                • Outputing the document
                  • Configuration
                    • Image Replacing
                    • Angular Parser
                    • Intelligent LoopTagging
                      • Command Line Interface (CLI)
                        • Configjson Syntax
                          • Full Documentation per method
                            • Creating a new Docxgen Object
                            • Docxgen methods
                              • Copyright
                              • Demos
                              • Indices and tables
Page 11: Release 0.5€¦ · Docx is a zipped format that contains some xml. If you want to build a simple replace {tag} If you want to build a simple replace {tag} by value system, it can

docxtemplater Documentation Release 054

8 Chapter 3 Dependencies

CHAPTER 4

Installation

41 Node

To install docxtemplater we recommend you to use npm

npm install docxtemplater

If you want to use the command line interface you should use the global flag eg

npm install docxtemplater -g

42 Browser

You will just have to include the docxgenjs or docxgenminjs file

9

docxtemplater Documentation Release 054

10 Chapter 4 Installation

CHAPTER 5

Syntax

The syntax is highly inspired by Mustache The template is created in Microsoft Word or any equivalent that saves todocx

51 Synopsis

A typical docxtemplater template

Hello name

Given the following hash

namersquoEdgarrsquo

Will produce

Hello Edgar

52 Tag types

Like Mustache it has the loopopening and loopclosing brackets

53 Loop syntax

The following template

productsname price C

products

Given the following hash

products

[nameWindowsprice100

11

docxtemplater Documentation Release 054

nameMac OSXprice200nameUbuntuprice0]

will result in

Windows 100 CMac OSX 200 CUbuntu 0C

The loop behaves in the following way

bull If the value is an array it will loop over all the elements of that array

bull If the value is a boolean it will loop once if the value is true keeping the same scope and not loop at all if thevalue is false

Note Because the loops work also with boolean values you can also use them for conditions

54 Dash syntax

It is quite difficult to know on which element you are going to loop By default when using the for loop docxgen willfind that by himself

If between the two tags tag______tag

bull they is the Xml Tag ltwtcgt -gt you are in a table and it will loop over ltwtrgt

bull else -gt it will loop over ltwtgt which is the default Text Tag

With the Dash syntax you pass as a first argument the tag you want to loop on

-wp loop inner loop

In this case this will loop over the first parent ltwpgt tag

55 Inverted Selections

An inverted section begins with a caret (hat) and ends with a slash That is ^person begins a ldquopersonrdquo invertedsection while person ends it

While sections can be used to render text one or more times based on the value of the key inverted sections may rendertext once based on the inverse value of the key That is they will be rendered if the key doesnrsquot exist is false or is anempty list

Template

repoltbgtnameltbgt

repo^repo

No repos (repo

Hash

12 Chapter 5 Syntax

docxtemplater Documentation Release 054

repo []

Output

No repos (

55 Inverted Selections 13

docxtemplater Documentation Release 054

14 Chapter 5 Syntax

CHAPTER 6

Generate a document

Herersquos a sample code to generate a document

DocxGen=require(rsquodocxtemplaterrsquo) Only for Node Usagenew DocxGen()loadFromFile(tagExampledocxasynctrue)success(function(doc)

docsetTags(first_nameHipp

last_nameEdgarphone0652455478descriptionNew Website

) set the templateVariablesdocapplyTags() apply them (replace all occurences of first_name by Hipp )docoutput() Output the document using Data-URI

)

The different steps are the following

61 Loading a document

A docx can be loaded by itrsquos base64 representation like this

doc=new DocxGen(base64Dataoptions)

However loading the base64Data is not that easy so I created a wrapper function to load a docx from a file via Ajax

Note The options parameter are explained in Configuration

doc=new DocxGen()loadFromFile(documentPathoptions)

The documentPath is the path to the document you want to load The options are the same as in the constructorfunction and Irsquove added the async parameter

bull If async is true the document is loaded asynchronously and returns a promise (eg you can write suc-cess(callback) to get when the document is loaded)

bull If async is false the document is loaded synchronously and returns the document

62 Setting the tags

The tags are the variables that are going to be replaced by their values To set them just use

15

docxtemplater Documentation Release 054

docsetTags(tags)

63 Applying the tags

Applying the tags means opening all files that contain text (eg footer header main document) and replace thevariables by their values

docapplyTags(tags)

Note If you specify an argument for the applyTags method the function setTags(tags) will be called before applyingthe tags

64 Outputing the document

They are several ways to output the document The most basic usage is to download the document

docoutput(options)

Depending on your environment if you donrsquot set any options this will

bull In the browser Download the document using DataURI

bull In Node Save the document with the given fileName (outputdocx by default)

Herersquos the different options parameters

nameTypestring[outputdocx]The name of the file that will be outputed (doesnt work in the browser because of dataUri download)

callbackTypefunctionFunction that is called without arguments when the output is done Is used only in Node (because in the browser the operation is synchronous)

downloadTypeboolean[true]If download is true file will be downloaded automatically with data URIreturns the output file

typeTypestring[base64]The type of zip to return The possible values are (same as in httpstukgithubiojszip generate)base64 (default) the result will be a string the binary in a base64 formstring the result will be a string in binary form 1 byte per charuint8array the result will be a Uint8Array containing the zip This requires a compatible browserarraybuffer the result will be a ArrayBuffer containing the zip This requires a compatible browserblob the result will be a Blob containing the zip This requires a compatible browsernodebuffer the result will be a nodejs Buffer containing the zip This requires nodejs

This function creates the docx file and downloads it on the userrsquos computer The name of the file is downloaddocxfor Chrome and some akward file names for Firefox VEeTHCfSdocxpartdocx and canrsquot be changed because it ishandled by the browser For more informations about how to solve this problem see the Filename Problems sectionon [httpstukgithubiojszip](httpstukgithubiojszip)

16 Chapter 6 Generate a document

docxtemplater Documentation Release 054

Note Note All browsers donrsquot support the download of big files withData URI so you should use the download method for files bigger than 100kBdataimagepngbase64iVBORw0KGgoAAAANSUhEUgAAABcAAAAXCAIAAABvSEP3AAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAACXSURBVDhPtY7BDYAwDAMZhCf7b8YMxeCoatOQJhWcKGxT2zlCyaWcz8Y+X7Bs1TFVJSwIHIYyFkQufWIRVX9cNJyW1QpEo4rixaEe7JuQagAUctb7ZFYFh5MVJPBe84CVBnB42YsZRgKjFDBVg3cI9WbRwXLktQJX8cNIiFhM1ZuTWk7PIYSBhkVcLzwIiCjCxhCjlAkBqYnqFoQQ2AAAAAElFTkSuQmCC

In Node to send the document to the client you can write the following code snippet

out=docoutput(downloadfalsetypestring)ressend(new Buffer(outbinary))

64 Outputing the document 17

docxtemplater Documentation Release 054

18 Chapter 6 Generate a document

CHAPTER 7

Configuration

Here are documented the special options that you can set when creating a new DocxGen to get some more superpower

It documents the options parameter when you do

new DocxGen(dataoptions)

71 Image Replacing

The name of this option qrCode (boolean)

To stay a templating engine I wanted that DocxTemplater doesnrsquot add an image from scratch but rather uses anexisting image that can be detected and DocxTemplater will just change the contents of that image without changingitrsquos style The size of the replaced images will stay the same

So I decided to use the qrCode format which is a format that lets you identify images by their content

The option for this is qrCode (true for on false for off default off)

Note If you donrsquot use that functionality you should disable it because it is quite slow (the image decoding)

Warning The qrCode functionality only works for PNG They is no support for other file formats yet

72 Angular Parser

The name of this option parser (function)

You can set the angular parser with the following code

With a custom parser you can parse the tags to for example add operators like lsquo+rsquo lsquo-lsquo or whatever the way you wantto parse expressions

To enable this you need to specify a custom parser You need to create a parser function

docxtemplater comes shipped with this parser

parser=function(expression)

return

19

docxtemplater Documentation Release 054

getfunction(scope) return scope[expression]

To use the angular-parser do the following

expressions= require(rsquoangular-expressionsrsquo)angularParser= function(tag)

return getexpressionscompile(tag)

new DocxGen(dataparserangularParser)

Note The require() works in the browser if you include vendorangular-parser-browserjs

73 Intelligent LoopTagging

The name of this option intelligentTagging (boolean)

When looping over an element docxtemplater needs to know over which element you want to loop By default it triesto do that intelligently (by looking what XML Tags are between the tags) However if you want to always use theltwtgt tag by default set this option to false

You can always specify over which element you want to loop with the dash loop syntax

20 Chapter 7 Configuration

CHAPTER 8

Command Line Interface (CLI)

This section is about the commandline interface of docxtemplater

The syntax is the following

docxtemplater configjson

The full configjson should be something like that

configdocxFileinputdocxconfigoutputFileoutputdocxconfigqrcodetrueconfigdebugtruefirst_nameJohnlast_nameSmithage62

81 Configjson Syntax

811 Config properties

These are the properties to configure docxtemplater

configdocxFileinputdocx The input file pathconfigoutputFileoutputdocx The output file pathconfigqrcodetrue whether the images should be scanned to replace them by qrcodes (slows down the cli a lot)configdebugtrue whether to show debug output or not

812 Data properties

To add data to your template just use keys that donrsquot start with ldquoconfigrdquo

first_nameJohnlast_nameSmithage62

21

docxtemplater Documentation Release 054

22 Chapter 8 Command Line Interface (CLI)

CHAPTER 9

Full Documentation per method

91 Creating a new Docxgen Object

new DocxGen()

This function returns a new DocxGen Object

new DocxGen(content[Tagsoptions])

contentType stringThe docx template you want to load as plain text

TagsType Object tag_nametag_replacement []Object containing for each tag_name the replacement for this tag For example if you want to replace firstName by David your Object will be firstNameDavid

options object

parserType functionA custom parser to use See angularjs like parsing

intelligentTaggingType boolean [false]If intelligent Tagging is not set to true when using recursive tags (tag and tag) the system will copy paste what is between the start tag and the endtag this could basically corrupt the files if recursive tags are used inside tablesIf intelligent Tagging is set to true and when using recursive tags inside tables the whole column will be copy pasted

qrCodeType boolean [false]If qrCode is set to true DocxGen will look at all the images to find a Qr-Code If the Qr-code matches to a URL this URL will be loaded by ajax (Be aware that the server you want to access needs to allow your request or it wonrsquot work httpstackoverflowcomquestions9310112why-am-i-seeing-an-origin-is-not-allowed-by-access-control-allow-origin-error )

Important the qrCode functionality only works for PNG I donrsquot think I will enable this for other fileformats in the near future

localImageCreatorType function(argcallback) [function that returns an arrow]The function has to be customized only if you want to use the qrCode options (qrCode=true) When the qrcode text starts with gen the image is not going to be loaded by url but DocxGen calls localImageCreator with arg=full Text decoded The callback needs to be called with the image Datacallback(result) in plaintxt format (if you want to create it from a Data-URI you can use JSZipBase64decode(data) to decode a Data-URI to plaintxt)

The default localImageCreator returns a red arrow no matter what the arguments are

localImageCreator= (argcallback) -gtresult=JSZipBase64decode(iVBORw0KGgoAAAANSUhEUgAAABcAAAAXCAIAAABvSEP3AAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAACXSURBVDhPtY7BDYAwDAMZhCf7b8YMxeCoatOQJhWcKGxT2zlCyaWcz8Y+X7Bs1TFVJSwIHIYyFkQufWIRVX9cNJyW1QpEo4rixaEe7JuQagAUctb7ZFYFh5MVJPBe84CVBnB42YsZRgKjFDBVg3cI9WbRwXLktQJX8cNIiFhM1ZuTWk7PIYSBhkVcLzwIiCjCxhCjlAkBqYnqFoQQ2AAAAAElFTkSuQmCC)

23

docxtemplater Documentation Release 054

[Default Image](dataimagepngbase64iVBORw0KGgoAAAANSUhEUgAAABcAAAAXCAIAAABvSEP3AAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAACXSURBVDhPtY7BDYAwDAMZhCf7b8YMxeCoatOQJhWcKGxT2zlCyaWcz8Y+X7Bs1TFVJSwIHIYyFkQufWIRVX9cNJyW1QpEo4rixaEe7JuQagAUctb7ZFYFh5MVJPBe84CVBnB42YsZRgKjFDBVg3cI9WbRwXLktQJX8cNIiFhM1ZuTWk7PIYSBhkVcLzwIiCjCxhCjlAkBqYnqFoQQ2AAAAAElFTkSuQmCC)

qrFinishedCallBackType function () [function that consolelog(ready)]

This function is called if you specify qrCode argument to true in this constructor and will be called when all qrCodes have been replaced (because the qrCode replacing functions are async)

92 Docxgen methods

load(content)

contentType stringThe docx template you want to load as plain text

loadFromFile(path)path

Type stringLoads a docx from a file path

setTags(Tags)

TagsType Object tag_nametag_replacementObject containing for each tag_name the replacement for this tag For example if you want to replace firstName by David your Object will be firstNameDavid

applyTags([Tags])Tags

Type Object tag_nametag_replacementsame as setTagsDefaultthisTags

This function replaces all template variables by their values

output([options])

options object[]

nameTypestring[outputdocx]The name of the file that will be outputed (doesnt work in the browser because of dataUri download)

callbackTypefunctionFunction that is called without arguments when the output is done Is used only in Node (because in the browser the operation is synchronous)

downloadTypeboolean[true]If download is true file will be downloaded automatically with data URIreturns the output file

typeTypestring[base64]The type of zip to return The possible values are (same as in httpstukgithubiojszip generate)base64 (default) the result will be a string the binary in a base64 formstring the result will be a string in binary form 1 byte per charuint8array the result will be a Uint8Array containing the zip This requires a compatible browser

24 Chapter 9 Full Documentation per method

docxtemplater Documentation Release 054

arraybuffer the result will be a ArrayBuffer containing the zip This requires a compatible browserblob the result will be a Blob containing the zip This requires a compatible browsernodebuffer the result will be a nodejs Buffer containing the zip This requires nodejs

This function creates the docx file and downloads it on the userrsquos computer The name of the file is downloaddocx for Chrome and some akward file names for Firefox VEeTHCfSdocxpartdocx and canrsquot be changed because it is handled by the browserFor more informations about how to solve this problem see the Filename Problems section on [httpstukgithubiojszip](httpstukgithubiojszip)

Note All browsers donrsquot support the download of big files with Data URI so you should use the lsquodownloadlsquo method for files bigger than 100kB dataimagepngbase64iVBORw0KGgoAAAANSUhEUgAAABcAAAAXCAIAAABvSEP3AAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAACXSURBVDhPtY7BDYAwDAMZhCf7b8YMxeCoatOQJhWcKGxT2zlCyaWcz8Y+X7Bs1TFVJSwIHIYyFkQufWIRVX9cNJyW1QpEo4rixaEe7JuQagAUctb7ZFYFh5MVJPBe84CVBnB42YsZRgKjFDBVg3cI9WbRwXLktQJX8cNIiFhM1ZuTWk7PIYSBhkVcLzwIiCjCxhCjlAkBqYnqFoQQ2AAAAAElFTkSuQmCC

download(swfpathimgpath[fileName])

swfpathTypestringPath to the swfobjectjs in downloadify

imgpathTypestringPath to the image of the download button

[fileName]TypestringDefaultdefaultdocxName of the file you would like the user to download

This requires to include Downloadifyjs that needs flash version 10 Have a look at the output function if you donrsquot want to depend on it This function has the advantage that it works regardless of the file size

getImageList()

this gets all images that have one of the following extension rsquogifrsquorsquojpegrsquorsquojpgrsquorsquoemfrsquorsquopngrsquoReturn format Array of Object[pathstringfilesZipFile Object]

You shouldrsquont call this method before calling applyTags() because applyTags can modify the images or their path when replacing images with other (particularly when qrCode is set to true which is not the default case) You can call this method after applyTags() without any problems

setImage(pathimgData)

pathTypeStringPath of the image given by getImageList()

imgDataTypeStringimgData in txtplain

This sets the image given by a path and an imgData in txtplainYou shouldrsquont call this method before calling applyTags() because applyTags can modify the images or their path when replacing images with other (particularly when qrCode is set to true which is not the default case) You can call this method after applyTags() without any problems

getFullText([path])

pathTypeStringDefaultworddocumentxmlThis argument determines from which document you want to get the text The main document is called worddocumentxml but they are other documents wordheader1xml wordfooter1xml

returnsTypeStringThe string containing all the text from the document

92 Docxgen methods 25

docxtemplater Documentation Release 054

This method gets only the text of a given document (not the formatting)

getTags()

This function returns the template variables contained in the opened document For example if the content of the documentxml is the following

namefirst_namephone

The function will return[

filenamedocumentxmlvars

nametruefirst_nametruephonetrue

]

If the content contains tagLoops

titlecustomernamephonecustomer

The function will return

[filenamedocumentxmlvars

titletruecustomer

nametruephonetrue

]

26 Chapter 9 Full Documentation per method

CHAPTER 10

Copyright

License

(The MIT license)

Copyright (c) 2013 Edgar Hipp

Permission is hereby granted free of charge to any person obtaining a copy of this software and associated documen-tation files (the ldquoSoftwarerdquo) to deal in the Software without restriction including without limitation the rights to usecopy modify merge publish distribute sublicense andor sell copies of the Software and to permit persons to whomthe Software is furnished to do so subject to the following conditions

The above copyright notice and this permission notice shall be included in all copies or substantial portions of theSoftware

THE SOFTWARE IS PROVIDED ldquoAS ISrdquo WITHOUT WARRANTY OF ANY KIND EXPRESS OR IMPLIEDINCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY FITNESS FOR A PAR-TICULAR PURPOSE AND NONINFRINGEMENT IN NO EVENT SHALL THE AUTHORS OR COPYRIGHTHOLDERS BE LIABLE FOR ANY CLAIM DAMAGES OR OTHER LIABILITY WHETHER IN AN ACTIONOF CONTRACT TORT OR OTHERWISE ARISING FROM OUT OF OR IN CONNECTION WITH THE SOFT-WARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE

27

docxtemplater Documentation Release 054

28 Chapter 10 Copyright

CHAPTER 11

Demos

Including

bull Replace Variables

bull Formating

bull Angular Parsing

bull Loops

bull Loops and tables

bull Lists

bull Replacing images

bull Naming the output

bull Using QrCodes

bull Replacing many images with QrCode

bull Raw Xml Insertion

29

docxtemplater Documentation Release 054

30 Chapter 11 Demos

CHAPTER 12

Indices and tables

bull genindex

bull modindex

bull search

31

docxtemplater Documentation Release 054

32 Chapter 12 Indices and tables

Index

CCommand Line Interface (CLI) 20Configuration 17Copyright 26

FFull_doc 21

GGenerate a Document 13Goals 1

IInstallation 7

Pplatform_support 3

SSyntax 9

33

  • Goals
    • Why you should use a library for this
      • Platform Support
      • Dependencies
      • Installation
        • Node
        • Browser
          • Syntax
            • Synopsis
            • Tag types
            • Loop syntax
            • Dash syntax
            • Inverted Selections
              • Generate a document
                • Loading a document
                • Setting the tags
                • Applying the tags
                • Outputing the document
                  • Configuration
                    • Image Replacing
                    • Angular Parser
                    • Intelligent LoopTagging
                      • Command Line Interface (CLI)
                        • Configjson Syntax
                          • Full Documentation per method
                            • Creating a new Docxgen Object
                            • Docxgen methods
                              • Copyright
                              • Demos
                              • Indices and tables
Page 12: Release 0.5€¦ · Docx is a zipped format that contains some xml. If you want to build a simple replace {tag} If you want to build a simple replace {tag} by value system, it can

CHAPTER 4

Installation

41 Node

To install docxtemplater we recommend you to use npm

npm install docxtemplater

If you want to use the command line interface you should use the global flag eg

npm install docxtemplater -g

42 Browser

You will just have to include the docxgenjs or docxgenminjs file

9

docxtemplater Documentation Release 054

10 Chapter 4 Installation

CHAPTER 5

Syntax

The syntax is highly inspired by Mustache The template is created in Microsoft Word or any equivalent that saves todocx

51 Synopsis

A typical docxtemplater template

Hello name

Given the following hash

namersquoEdgarrsquo

Will produce

Hello Edgar

52 Tag types

Like Mustache it has the loopopening and loopclosing brackets

53 Loop syntax

The following template

productsname price C

products

Given the following hash

products

[nameWindowsprice100

11

docxtemplater Documentation Release 054

nameMac OSXprice200nameUbuntuprice0]

will result in

Windows 100 CMac OSX 200 CUbuntu 0C

The loop behaves in the following way

bull If the value is an array it will loop over all the elements of that array

bull If the value is a boolean it will loop once if the value is true keeping the same scope and not loop at all if thevalue is false

Note Because the loops work also with boolean values you can also use them for conditions

54 Dash syntax

It is quite difficult to know on which element you are going to loop By default when using the for loop docxgen willfind that by himself

If between the two tags tag______tag

bull they is the Xml Tag ltwtcgt -gt you are in a table and it will loop over ltwtrgt

bull else -gt it will loop over ltwtgt which is the default Text Tag

With the Dash syntax you pass as a first argument the tag you want to loop on

-wp loop inner loop

In this case this will loop over the first parent ltwpgt tag

55 Inverted Selections

An inverted section begins with a caret (hat) and ends with a slash That is ^person begins a ldquopersonrdquo invertedsection while person ends it

While sections can be used to render text one or more times based on the value of the key inverted sections may rendertext once based on the inverse value of the key That is they will be rendered if the key doesnrsquot exist is false or is anempty list

Template

repoltbgtnameltbgt

repo^repo

No repos (repo

Hash

12 Chapter 5 Syntax

docxtemplater Documentation Release 054

repo []

Output

No repos (

55 Inverted Selections 13

docxtemplater Documentation Release 054

14 Chapter 5 Syntax

CHAPTER 6

Generate a document

Herersquos a sample code to generate a document

DocxGen=require(rsquodocxtemplaterrsquo) Only for Node Usagenew DocxGen()loadFromFile(tagExampledocxasynctrue)success(function(doc)

docsetTags(first_nameHipp

last_nameEdgarphone0652455478descriptionNew Website

) set the templateVariablesdocapplyTags() apply them (replace all occurences of first_name by Hipp )docoutput() Output the document using Data-URI

)

The different steps are the following

61 Loading a document

A docx can be loaded by itrsquos base64 representation like this

doc=new DocxGen(base64Dataoptions)

However loading the base64Data is not that easy so I created a wrapper function to load a docx from a file via Ajax

Note The options parameter are explained in Configuration

doc=new DocxGen()loadFromFile(documentPathoptions)

The documentPath is the path to the document you want to load The options are the same as in the constructorfunction and Irsquove added the async parameter

bull If async is true the document is loaded asynchronously and returns a promise (eg you can write suc-cess(callback) to get when the document is loaded)

bull If async is false the document is loaded synchronously and returns the document

62 Setting the tags

The tags are the variables that are going to be replaced by their values To set them just use

15

docxtemplater Documentation Release 054

docsetTags(tags)

63 Applying the tags

Applying the tags means opening all files that contain text (eg footer header main document) and replace thevariables by their values

docapplyTags(tags)

Note If you specify an argument for the applyTags method the function setTags(tags) will be called before applyingthe tags

64 Outputing the document

They are several ways to output the document The most basic usage is to download the document

docoutput(options)

Depending on your environment if you donrsquot set any options this will

bull In the browser Download the document using DataURI

bull In Node Save the document with the given fileName (outputdocx by default)

Herersquos the different options parameters

nameTypestring[outputdocx]The name of the file that will be outputed (doesnt work in the browser because of dataUri download)

callbackTypefunctionFunction that is called without arguments when the output is done Is used only in Node (because in the browser the operation is synchronous)

downloadTypeboolean[true]If download is true file will be downloaded automatically with data URIreturns the output file

typeTypestring[base64]The type of zip to return The possible values are (same as in httpstukgithubiojszip generate)base64 (default) the result will be a string the binary in a base64 formstring the result will be a string in binary form 1 byte per charuint8array the result will be a Uint8Array containing the zip This requires a compatible browserarraybuffer the result will be a ArrayBuffer containing the zip This requires a compatible browserblob the result will be a Blob containing the zip This requires a compatible browsernodebuffer the result will be a nodejs Buffer containing the zip This requires nodejs

This function creates the docx file and downloads it on the userrsquos computer The name of the file is downloaddocxfor Chrome and some akward file names for Firefox VEeTHCfSdocxpartdocx and canrsquot be changed because it ishandled by the browser For more informations about how to solve this problem see the Filename Problems sectionon [httpstukgithubiojszip](httpstukgithubiojszip)

16 Chapter 6 Generate a document

docxtemplater Documentation Release 054

Note Note All browsers donrsquot support the download of big files withData URI so you should use the download method for files bigger than 100kBdataimagepngbase64iVBORw0KGgoAAAANSUhEUgAAABcAAAAXCAIAAABvSEP3AAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAACXSURBVDhPtY7BDYAwDAMZhCf7b8YMxeCoatOQJhWcKGxT2zlCyaWcz8Y+X7Bs1TFVJSwIHIYyFkQufWIRVX9cNJyW1QpEo4rixaEe7JuQagAUctb7ZFYFh5MVJPBe84CVBnB42YsZRgKjFDBVg3cI9WbRwXLktQJX8cNIiFhM1ZuTWk7PIYSBhkVcLzwIiCjCxhCjlAkBqYnqFoQQ2AAAAAElFTkSuQmCC

In Node to send the document to the client you can write the following code snippet

out=docoutput(downloadfalsetypestring)ressend(new Buffer(outbinary))

64 Outputing the document 17

docxtemplater Documentation Release 054

18 Chapter 6 Generate a document

CHAPTER 7

Configuration

Here are documented the special options that you can set when creating a new DocxGen to get some more superpower

It documents the options parameter when you do

new DocxGen(dataoptions)

71 Image Replacing

The name of this option qrCode (boolean)

To stay a templating engine I wanted that DocxTemplater doesnrsquot add an image from scratch but rather uses anexisting image that can be detected and DocxTemplater will just change the contents of that image without changingitrsquos style The size of the replaced images will stay the same

So I decided to use the qrCode format which is a format that lets you identify images by their content

The option for this is qrCode (true for on false for off default off)

Note If you donrsquot use that functionality you should disable it because it is quite slow (the image decoding)

Warning The qrCode functionality only works for PNG They is no support for other file formats yet

72 Angular Parser

The name of this option parser (function)

You can set the angular parser with the following code

With a custom parser you can parse the tags to for example add operators like lsquo+rsquo lsquo-lsquo or whatever the way you wantto parse expressions

To enable this you need to specify a custom parser You need to create a parser function

docxtemplater comes shipped with this parser

parser=function(expression)

return

19

docxtemplater Documentation Release 054

getfunction(scope) return scope[expression]

To use the angular-parser do the following

expressions= require(rsquoangular-expressionsrsquo)angularParser= function(tag)

return getexpressionscompile(tag)

new DocxGen(dataparserangularParser)

Note The require() works in the browser if you include vendorangular-parser-browserjs

73 Intelligent LoopTagging

The name of this option intelligentTagging (boolean)

When looping over an element docxtemplater needs to know over which element you want to loop By default it triesto do that intelligently (by looking what XML Tags are between the tags) However if you want to always use theltwtgt tag by default set this option to false

You can always specify over which element you want to loop with the dash loop syntax

20 Chapter 7 Configuration

CHAPTER 8

Command Line Interface (CLI)

This section is about the commandline interface of docxtemplater

The syntax is the following

docxtemplater configjson

The full configjson should be something like that

configdocxFileinputdocxconfigoutputFileoutputdocxconfigqrcodetrueconfigdebugtruefirst_nameJohnlast_nameSmithage62

81 Configjson Syntax

811 Config properties

These are the properties to configure docxtemplater

configdocxFileinputdocx The input file pathconfigoutputFileoutputdocx The output file pathconfigqrcodetrue whether the images should be scanned to replace them by qrcodes (slows down the cli a lot)configdebugtrue whether to show debug output or not

812 Data properties

To add data to your template just use keys that donrsquot start with ldquoconfigrdquo

first_nameJohnlast_nameSmithage62

21

docxtemplater Documentation Release 054

22 Chapter 8 Command Line Interface (CLI)

CHAPTER 9

Full Documentation per method

91 Creating a new Docxgen Object

new DocxGen()

This function returns a new DocxGen Object

new DocxGen(content[Tagsoptions])

contentType stringThe docx template you want to load as plain text

TagsType Object tag_nametag_replacement []Object containing for each tag_name the replacement for this tag For example if you want to replace firstName by David your Object will be firstNameDavid

options object

parserType functionA custom parser to use See angularjs like parsing

intelligentTaggingType boolean [false]If intelligent Tagging is not set to true when using recursive tags (tag and tag) the system will copy paste what is between the start tag and the endtag this could basically corrupt the files if recursive tags are used inside tablesIf intelligent Tagging is set to true and when using recursive tags inside tables the whole column will be copy pasted

qrCodeType boolean [false]If qrCode is set to true DocxGen will look at all the images to find a Qr-Code If the Qr-code matches to a URL this URL will be loaded by ajax (Be aware that the server you want to access needs to allow your request or it wonrsquot work httpstackoverflowcomquestions9310112why-am-i-seeing-an-origin-is-not-allowed-by-access-control-allow-origin-error )

Important the qrCode functionality only works for PNG I donrsquot think I will enable this for other fileformats in the near future

localImageCreatorType function(argcallback) [function that returns an arrow]The function has to be customized only if you want to use the qrCode options (qrCode=true) When the qrcode text starts with gen the image is not going to be loaded by url but DocxGen calls localImageCreator with arg=full Text decoded The callback needs to be called with the image Datacallback(result) in plaintxt format (if you want to create it from a Data-URI you can use JSZipBase64decode(data) to decode a Data-URI to plaintxt)

The default localImageCreator returns a red arrow no matter what the arguments are

localImageCreator= (argcallback) -gtresult=JSZipBase64decode(iVBORw0KGgoAAAANSUhEUgAAABcAAAAXCAIAAABvSEP3AAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAACXSURBVDhPtY7BDYAwDAMZhCf7b8YMxeCoatOQJhWcKGxT2zlCyaWcz8Y+X7Bs1TFVJSwIHIYyFkQufWIRVX9cNJyW1QpEo4rixaEe7JuQagAUctb7ZFYFh5MVJPBe84CVBnB42YsZRgKjFDBVg3cI9WbRwXLktQJX8cNIiFhM1ZuTWk7PIYSBhkVcLzwIiCjCxhCjlAkBqYnqFoQQ2AAAAAElFTkSuQmCC)

23

docxtemplater Documentation Release 054

[Default Image](dataimagepngbase64iVBORw0KGgoAAAANSUhEUgAAABcAAAAXCAIAAABvSEP3AAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAACXSURBVDhPtY7BDYAwDAMZhCf7b8YMxeCoatOQJhWcKGxT2zlCyaWcz8Y+X7Bs1TFVJSwIHIYyFkQufWIRVX9cNJyW1QpEo4rixaEe7JuQagAUctb7ZFYFh5MVJPBe84CVBnB42YsZRgKjFDBVg3cI9WbRwXLktQJX8cNIiFhM1ZuTWk7PIYSBhkVcLzwIiCjCxhCjlAkBqYnqFoQQ2AAAAAElFTkSuQmCC)

qrFinishedCallBackType function () [function that consolelog(ready)]

This function is called if you specify qrCode argument to true in this constructor and will be called when all qrCodes have been replaced (because the qrCode replacing functions are async)

92 Docxgen methods

load(content)

contentType stringThe docx template you want to load as plain text

loadFromFile(path)path

Type stringLoads a docx from a file path

setTags(Tags)

TagsType Object tag_nametag_replacementObject containing for each tag_name the replacement for this tag For example if you want to replace firstName by David your Object will be firstNameDavid

applyTags([Tags])Tags

Type Object tag_nametag_replacementsame as setTagsDefaultthisTags

This function replaces all template variables by their values

output([options])

options object[]

nameTypestring[outputdocx]The name of the file that will be outputed (doesnt work in the browser because of dataUri download)

callbackTypefunctionFunction that is called without arguments when the output is done Is used only in Node (because in the browser the operation is synchronous)

downloadTypeboolean[true]If download is true file will be downloaded automatically with data URIreturns the output file

typeTypestring[base64]The type of zip to return The possible values are (same as in httpstukgithubiojszip generate)base64 (default) the result will be a string the binary in a base64 formstring the result will be a string in binary form 1 byte per charuint8array the result will be a Uint8Array containing the zip This requires a compatible browser

24 Chapter 9 Full Documentation per method

docxtemplater Documentation Release 054

arraybuffer the result will be a ArrayBuffer containing the zip This requires a compatible browserblob the result will be a Blob containing the zip This requires a compatible browsernodebuffer the result will be a nodejs Buffer containing the zip This requires nodejs

This function creates the docx file and downloads it on the userrsquos computer The name of the file is downloaddocx for Chrome and some akward file names for Firefox VEeTHCfSdocxpartdocx and canrsquot be changed because it is handled by the browserFor more informations about how to solve this problem see the Filename Problems section on [httpstukgithubiojszip](httpstukgithubiojszip)

Note All browsers donrsquot support the download of big files with Data URI so you should use the lsquodownloadlsquo method for files bigger than 100kB dataimagepngbase64iVBORw0KGgoAAAANSUhEUgAAABcAAAAXCAIAAABvSEP3AAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAACXSURBVDhPtY7BDYAwDAMZhCf7b8YMxeCoatOQJhWcKGxT2zlCyaWcz8Y+X7Bs1TFVJSwIHIYyFkQufWIRVX9cNJyW1QpEo4rixaEe7JuQagAUctb7ZFYFh5MVJPBe84CVBnB42YsZRgKjFDBVg3cI9WbRwXLktQJX8cNIiFhM1ZuTWk7PIYSBhkVcLzwIiCjCxhCjlAkBqYnqFoQQ2AAAAAElFTkSuQmCC

download(swfpathimgpath[fileName])

swfpathTypestringPath to the swfobjectjs in downloadify

imgpathTypestringPath to the image of the download button

[fileName]TypestringDefaultdefaultdocxName of the file you would like the user to download

This requires to include Downloadifyjs that needs flash version 10 Have a look at the output function if you donrsquot want to depend on it This function has the advantage that it works regardless of the file size

getImageList()

this gets all images that have one of the following extension rsquogifrsquorsquojpegrsquorsquojpgrsquorsquoemfrsquorsquopngrsquoReturn format Array of Object[pathstringfilesZipFile Object]

You shouldrsquont call this method before calling applyTags() because applyTags can modify the images or their path when replacing images with other (particularly when qrCode is set to true which is not the default case) You can call this method after applyTags() without any problems

setImage(pathimgData)

pathTypeStringPath of the image given by getImageList()

imgDataTypeStringimgData in txtplain

This sets the image given by a path and an imgData in txtplainYou shouldrsquont call this method before calling applyTags() because applyTags can modify the images or their path when replacing images with other (particularly when qrCode is set to true which is not the default case) You can call this method after applyTags() without any problems

getFullText([path])

pathTypeStringDefaultworddocumentxmlThis argument determines from which document you want to get the text The main document is called worddocumentxml but they are other documents wordheader1xml wordfooter1xml

returnsTypeStringThe string containing all the text from the document

92 Docxgen methods 25

docxtemplater Documentation Release 054

This method gets only the text of a given document (not the formatting)

getTags()

This function returns the template variables contained in the opened document For example if the content of the documentxml is the following

namefirst_namephone

The function will return[

filenamedocumentxmlvars

nametruefirst_nametruephonetrue

]

If the content contains tagLoops

titlecustomernamephonecustomer

The function will return

[filenamedocumentxmlvars

titletruecustomer

nametruephonetrue

]

26 Chapter 9 Full Documentation per method

CHAPTER 10

Copyright

License

(The MIT license)

Copyright (c) 2013 Edgar Hipp

Permission is hereby granted free of charge to any person obtaining a copy of this software and associated documen-tation files (the ldquoSoftwarerdquo) to deal in the Software without restriction including without limitation the rights to usecopy modify merge publish distribute sublicense andor sell copies of the Software and to permit persons to whomthe Software is furnished to do so subject to the following conditions

The above copyright notice and this permission notice shall be included in all copies or substantial portions of theSoftware

THE SOFTWARE IS PROVIDED ldquoAS ISrdquo WITHOUT WARRANTY OF ANY KIND EXPRESS OR IMPLIEDINCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY FITNESS FOR A PAR-TICULAR PURPOSE AND NONINFRINGEMENT IN NO EVENT SHALL THE AUTHORS OR COPYRIGHTHOLDERS BE LIABLE FOR ANY CLAIM DAMAGES OR OTHER LIABILITY WHETHER IN AN ACTIONOF CONTRACT TORT OR OTHERWISE ARISING FROM OUT OF OR IN CONNECTION WITH THE SOFT-WARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE

27

docxtemplater Documentation Release 054

28 Chapter 10 Copyright

CHAPTER 11

Demos

Including

bull Replace Variables

bull Formating

bull Angular Parsing

bull Loops

bull Loops and tables

bull Lists

bull Replacing images

bull Naming the output

bull Using QrCodes

bull Replacing many images with QrCode

bull Raw Xml Insertion

29

docxtemplater Documentation Release 054

30 Chapter 11 Demos

CHAPTER 12

Indices and tables

bull genindex

bull modindex

bull search

31

docxtemplater Documentation Release 054

32 Chapter 12 Indices and tables

Index

CCommand Line Interface (CLI) 20Configuration 17Copyright 26

FFull_doc 21

GGenerate a Document 13Goals 1

IInstallation 7

Pplatform_support 3

SSyntax 9

33

  • Goals
    • Why you should use a library for this
      • Platform Support
      • Dependencies
      • Installation
        • Node
        • Browser
          • Syntax
            • Synopsis
            • Tag types
            • Loop syntax
            • Dash syntax
            • Inverted Selections
              • Generate a document
                • Loading a document
                • Setting the tags
                • Applying the tags
                • Outputing the document
                  • Configuration
                    • Image Replacing
                    • Angular Parser
                    • Intelligent LoopTagging
                      • Command Line Interface (CLI)
                        • Configjson Syntax
                          • Full Documentation per method
                            • Creating a new Docxgen Object
                            • Docxgen methods
                              • Copyright
                              • Demos
                              • Indices and tables
Page 13: Release 0.5€¦ · Docx is a zipped format that contains some xml. If you want to build a simple replace {tag} If you want to build a simple replace {tag} by value system, it can

docxtemplater Documentation Release 054

10 Chapter 4 Installation

CHAPTER 5

Syntax

The syntax is highly inspired by Mustache The template is created in Microsoft Word or any equivalent that saves todocx

51 Synopsis

A typical docxtemplater template

Hello name

Given the following hash

namersquoEdgarrsquo

Will produce

Hello Edgar

52 Tag types

Like Mustache it has the loopopening and loopclosing brackets

53 Loop syntax

The following template

productsname price C

products

Given the following hash

products

[nameWindowsprice100

11

docxtemplater Documentation Release 054

nameMac OSXprice200nameUbuntuprice0]

will result in

Windows 100 CMac OSX 200 CUbuntu 0C

The loop behaves in the following way

bull If the value is an array it will loop over all the elements of that array

bull If the value is a boolean it will loop once if the value is true keeping the same scope and not loop at all if thevalue is false

Note Because the loops work also with boolean values you can also use them for conditions

54 Dash syntax

It is quite difficult to know on which element you are going to loop By default when using the for loop docxgen willfind that by himself

If between the two tags tag______tag

bull they is the Xml Tag ltwtcgt -gt you are in a table and it will loop over ltwtrgt

bull else -gt it will loop over ltwtgt which is the default Text Tag

With the Dash syntax you pass as a first argument the tag you want to loop on

-wp loop inner loop

In this case this will loop over the first parent ltwpgt tag

55 Inverted Selections

An inverted section begins with a caret (hat) and ends with a slash That is ^person begins a ldquopersonrdquo invertedsection while person ends it

While sections can be used to render text one or more times based on the value of the key inverted sections may rendertext once based on the inverse value of the key That is they will be rendered if the key doesnrsquot exist is false or is anempty list

Template

repoltbgtnameltbgt

repo^repo

No repos (repo

Hash

12 Chapter 5 Syntax

docxtemplater Documentation Release 054

repo []

Output

No repos (

55 Inverted Selections 13

docxtemplater Documentation Release 054

14 Chapter 5 Syntax

CHAPTER 6

Generate a document

Herersquos a sample code to generate a document

DocxGen=require(rsquodocxtemplaterrsquo) Only for Node Usagenew DocxGen()loadFromFile(tagExampledocxasynctrue)success(function(doc)

docsetTags(first_nameHipp

last_nameEdgarphone0652455478descriptionNew Website

) set the templateVariablesdocapplyTags() apply them (replace all occurences of first_name by Hipp )docoutput() Output the document using Data-URI

)

The different steps are the following

61 Loading a document

A docx can be loaded by itrsquos base64 representation like this

doc=new DocxGen(base64Dataoptions)

However loading the base64Data is not that easy so I created a wrapper function to load a docx from a file via Ajax

Note The options parameter are explained in Configuration

doc=new DocxGen()loadFromFile(documentPathoptions)

The documentPath is the path to the document you want to load The options are the same as in the constructorfunction and Irsquove added the async parameter

bull If async is true the document is loaded asynchronously and returns a promise (eg you can write suc-cess(callback) to get when the document is loaded)

bull If async is false the document is loaded synchronously and returns the document

62 Setting the tags

The tags are the variables that are going to be replaced by their values To set them just use

15

docxtemplater Documentation Release 054

docsetTags(tags)

63 Applying the tags

Applying the tags means opening all files that contain text (eg footer header main document) and replace thevariables by their values

docapplyTags(tags)

Note If you specify an argument for the applyTags method the function setTags(tags) will be called before applyingthe tags

64 Outputing the document

They are several ways to output the document The most basic usage is to download the document

docoutput(options)

Depending on your environment if you donrsquot set any options this will

bull In the browser Download the document using DataURI

bull In Node Save the document with the given fileName (outputdocx by default)

Herersquos the different options parameters

nameTypestring[outputdocx]The name of the file that will be outputed (doesnt work in the browser because of dataUri download)

callbackTypefunctionFunction that is called without arguments when the output is done Is used only in Node (because in the browser the operation is synchronous)

downloadTypeboolean[true]If download is true file will be downloaded automatically with data URIreturns the output file

typeTypestring[base64]The type of zip to return The possible values are (same as in httpstukgithubiojszip generate)base64 (default) the result will be a string the binary in a base64 formstring the result will be a string in binary form 1 byte per charuint8array the result will be a Uint8Array containing the zip This requires a compatible browserarraybuffer the result will be a ArrayBuffer containing the zip This requires a compatible browserblob the result will be a Blob containing the zip This requires a compatible browsernodebuffer the result will be a nodejs Buffer containing the zip This requires nodejs

This function creates the docx file and downloads it on the userrsquos computer The name of the file is downloaddocxfor Chrome and some akward file names for Firefox VEeTHCfSdocxpartdocx and canrsquot be changed because it ishandled by the browser For more informations about how to solve this problem see the Filename Problems sectionon [httpstukgithubiojszip](httpstukgithubiojszip)

16 Chapter 6 Generate a document

docxtemplater Documentation Release 054

Note Note All browsers donrsquot support the download of big files withData URI so you should use the download method for files bigger than 100kBdataimagepngbase64iVBORw0KGgoAAAANSUhEUgAAABcAAAAXCAIAAABvSEP3AAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAACXSURBVDhPtY7BDYAwDAMZhCf7b8YMxeCoatOQJhWcKGxT2zlCyaWcz8Y+X7Bs1TFVJSwIHIYyFkQufWIRVX9cNJyW1QpEo4rixaEe7JuQagAUctb7ZFYFh5MVJPBe84CVBnB42YsZRgKjFDBVg3cI9WbRwXLktQJX8cNIiFhM1ZuTWk7PIYSBhkVcLzwIiCjCxhCjlAkBqYnqFoQQ2AAAAAElFTkSuQmCC

In Node to send the document to the client you can write the following code snippet

out=docoutput(downloadfalsetypestring)ressend(new Buffer(outbinary))

64 Outputing the document 17

docxtemplater Documentation Release 054

18 Chapter 6 Generate a document

CHAPTER 7

Configuration

Here are documented the special options that you can set when creating a new DocxGen to get some more superpower

It documents the options parameter when you do

new DocxGen(dataoptions)

71 Image Replacing

The name of this option qrCode (boolean)

To stay a templating engine I wanted that DocxTemplater doesnrsquot add an image from scratch but rather uses anexisting image that can be detected and DocxTemplater will just change the contents of that image without changingitrsquos style The size of the replaced images will stay the same

So I decided to use the qrCode format which is a format that lets you identify images by their content

The option for this is qrCode (true for on false for off default off)

Note If you donrsquot use that functionality you should disable it because it is quite slow (the image decoding)

Warning The qrCode functionality only works for PNG They is no support for other file formats yet

72 Angular Parser

The name of this option parser (function)

You can set the angular parser with the following code

With a custom parser you can parse the tags to for example add operators like lsquo+rsquo lsquo-lsquo or whatever the way you wantto parse expressions

To enable this you need to specify a custom parser You need to create a parser function

docxtemplater comes shipped with this parser

parser=function(expression)

return

19

docxtemplater Documentation Release 054

getfunction(scope) return scope[expression]

To use the angular-parser do the following

expressions= require(rsquoangular-expressionsrsquo)angularParser= function(tag)

return getexpressionscompile(tag)

new DocxGen(dataparserangularParser)

Note The require() works in the browser if you include vendorangular-parser-browserjs

73 Intelligent LoopTagging

The name of this option intelligentTagging (boolean)

When looping over an element docxtemplater needs to know over which element you want to loop By default it triesto do that intelligently (by looking what XML Tags are between the tags) However if you want to always use theltwtgt tag by default set this option to false

You can always specify over which element you want to loop with the dash loop syntax

20 Chapter 7 Configuration

CHAPTER 8

Command Line Interface (CLI)

This section is about the commandline interface of docxtemplater

The syntax is the following

docxtemplater configjson

The full configjson should be something like that

configdocxFileinputdocxconfigoutputFileoutputdocxconfigqrcodetrueconfigdebugtruefirst_nameJohnlast_nameSmithage62

81 Configjson Syntax

811 Config properties

These are the properties to configure docxtemplater

configdocxFileinputdocx The input file pathconfigoutputFileoutputdocx The output file pathconfigqrcodetrue whether the images should be scanned to replace them by qrcodes (slows down the cli a lot)configdebugtrue whether to show debug output or not

812 Data properties

To add data to your template just use keys that donrsquot start with ldquoconfigrdquo

first_nameJohnlast_nameSmithage62

21

docxtemplater Documentation Release 054

22 Chapter 8 Command Line Interface (CLI)

CHAPTER 9

Full Documentation per method

91 Creating a new Docxgen Object

new DocxGen()

This function returns a new DocxGen Object

new DocxGen(content[Tagsoptions])

contentType stringThe docx template you want to load as plain text

TagsType Object tag_nametag_replacement []Object containing for each tag_name the replacement for this tag For example if you want to replace firstName by David your Object will be firstNameDavid

options object

parserType functionA custom parser to use See angularjs like parsing

intelligentTaggingType boolean [false]If intelligent Tagging is not set to true when using recursive tags (tag and tag) the system will copy paste what is between the start tag and the endtag this could basically corrupt the files if recursive tags are used inside tablesIf intelligent Tagging is set to true and when using recursive tags inside tables the whole column will be copy pasted

qrCodeType boolean [false]If qrCode is set to true DocxGen will look at all the images to find a Qr-Code If the Qr-code matches to a URL this URL will be loaded by ajax (Be aware that the server you want to access needs to allow your request or it wonrsquot work httpstackoverflowcomquestions9310112why-am-i-seeing-an-origin-is-not-allowed-by-access-control-allow-origin-error )

Important the qrCode functionality only works for PNG I donrsquot think I will enable this for other fileformats in the near future

localImageCreatorType function(argcallback) [function that returns an arrow]The function has to be customized only if you want to use the qrCode options (qrCode=true) When the qrcode text starts with gen the image is not going to be loaded by url but DocxGen calls localImageCreator with arg=full Text decoded The callback needs to be called with the image Datacallback(result) in plaintxt format (if you want to create it from a Data-URI you can use JSZipBase64decode(data) to decode a Data-URI to plaintxt)

The default localImageCreator returns a red arrow no matter what the arguments are

localImageCreator= (argcallback) -gtresult=JSZipBase64decode(iVBORw0KGgoAAAANSUhEUgAAABcAAAAXCAIAAABvSEP3AAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAACXSURBVDhPtY7BDYAwDAMZhCf7b8YMxeCoatOQJhWcKGxT2zlCyaWcz8Y+X7Bs1TFVJSwIHIYyFkQufWIRVX9cNJyW1QpEo4rixaEe7JuQagAUctb7ZFYFh5MVJPBe84CVBnB42YsZRgKjFDBVg3cI9WbRwXLktQJX8cNIiFhM1ZuTWk7PIYSBhkVcLzwIiCjCxhCjlAkBqYnqFoQQ2AAAAAElFTkSuQmCC)

23

docxtemplater Documentation Release 054

[Default Image](dataimagepngbase64iVBORw0KGgoAAAANSUhEUgAAABcAAAAXCAIAAABvSEP3AAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAACXSURBVDhPtY7BDYAwDAMZhCf7b8YMxeCoatOQJhWcKGxT2zlCyaWcz8Y+X7Bs1TFVJSwIHIYyFkQufWIRVX9cNJyW1QpEo4rixaEe7JuQagAUctb7ZFYFh5MVJPBe84CVBnB42YsZRgKjFDBVg3cI9WbRwXLktQJX8cNIiFhM1ZuTWk7PIYSBhkVcLzwIiCjCxhCjlAkBqYnqFoQQ2AAAAAElFTkSuQmCC)

qrFinishedCallBackType function () [function that consolelog(ready)]

This function is called if you specify qrCode argument to true in this constructor and will be called when all qrCodes have been replaced (because the qrCode replacing functions are async)

92 Docxgen methods

load(content)

contentType stringThe docx template you want to load as plain text

loadFromFile(path)path

Type stringLoads a docx from a file path

setTags(Tags)

TagsType Object tag_nametag_replacementObject containing for each tag_name the replacement for this tag For example if you want to replace firstName by David your Object will be firstNameDavid

applyTags([Tags])Tags

Type Object tag_nametag_replacementsame as setTagsDefaultthisTags

This function replaces all template variables by their values

output([options])

options object[]

nameTypestring[outputdocx]The name of the file that will be outputed (doesnt work in the browser because of dataUri download)

callbackTypefunctionFunction that is called without arguments when the output is done Is used only in Node (because in the browser the operation is synchronous)

downloadTypeboolean[true]If download is true file will be downloaded automatically with data URIreturns the output file

typeTypestring[base64]The type of zip to return The possible values are (same as in httpstukgithubiojszip generate)base64 (default) the result will be a string the binary in a base64 formstring the result will be a string in binary form 1 byte per charuint8array the result will be a Uint8Array containing the zip This requires a compatible browser

24 Chapter 9 Full Documentation per method

docxtemplater Documentation Release 054

arraybuffer the result will be a ArrayBuffer containing the zip This requires a compatible browserblob the result will be a Blob containing the zip This requires a compatible browsernodebuffer the result will be a nodejs Buffer containing the zip This requires nodejs

This function creates the docx file and downloads it on the userrsquos computer The name of the file is downloaddocx for Chrome and some akward file names for Firefox VEeTHCfSdocxpartdocx and canrsquot be changed because it is handled by the browserFor more informations about how to solve this problem see the Filename Problems section on [httpstukgithubiojszip](httpstukgithubiojszip)

Note All browsers donrsquot support the download of big files with Data URI so you should use the lsquodownloadlsquo method for files bigger than 100kB dataimagepngbase64iVBORw0KGgoAAAANSUhEUgAAABcAAAAXCAIAAABvSEP3AAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAACXSURBVDhPtY7BDYAwDAMZhCf7b8YMxeCoatOQJhWcKGxT2zlCyaWcz8Y+X7Bs1TFVJSwIHIYyFkQufWIRVX9cNJyW1QpEo4rixaEe7JuQagAUctb7ZFYFh5MVJPBe84CVBnB42YsZRgKjFDBVg3cI9WbRwXLktQJX8cNIiFhM1ZuTWk7PIYSBhkVcLzwIiCjCxhCjlAkBqYnqFoQQ2AAAAAElFTkSuQmCC

download(swfpathimgpath[fileName])

swfpathTypestringPath to the swfobjectjs in downloadify

imgpathTypestringPath to the image of the download button

[fileName]TypestringDefaultdefaultdocxName of the file you would like the user to download

This requires to include Downloadifyjs that needs flash version 10 Have a look at the output function if you donrsquot want to depend on it This function has the advantage that it works regardless of the file size

getImageList()

this gets all images that have one of the following extension rsquogifrsquorsquojpegrsquorsquojpgrsquorsquoemfrsquorsquopngrsquoReturn format Array of Object[pathstringfilesZipFile Object]

You shouldrsquont call this method before calling applyTags() because applyTags can modify the images or their path when replacing images with other (particularly when qrCode is set to true which is not the default case) You can call this method after applyTags() without any problems

setImage(pathimgData)

pathTypeStringPath of the image given by getImageList()

imgDataTypeStringimgData in txtplain

This sets the image given by a path and an imgData in txtplainYou shouldrsquont call this method before calling applyTags() because applyTags can modify the images or their path when replacing images with other (particularly when qrCode is set to true which is not the default case) You can call this method after applyTags() without any problems

getFullText([path])

pathTypeStringDefaultworddocumentxmlThis argument determines from which document you want to get the text The main document is called worddocumentxml but they are other documents wordheader1xml wordfooter1xml

returnsTypeStringThe string containing all the text from the document

92 Docxgen methods 25

docxtemplater Documentation Release 054

This method gets only the text of a given document (not the formatting)

getTags()

This function returns the template variables contained in the opened document For example if the content of the documentxml is the following

namefirst_namephone

The function will return[

filenamedocumentxmlvars

nametruefirst_nametruephonetrue

]

If the content contains tagLoops

titlecustomernamephonecustomer

The function will return

[filenamedocumentxmlvars

titletruecustomer

nametruephonetrue

]

26 Chapter 9 Full Documentation per method

CHAPTER 10

Copyright

License

(The MIT license)

Copyright (c) 2013 Edgar Hipp

Permission is hereby granted free of charge to any person obtaining a copy of this software and associated documen-tation files (the ldquoSoftwarerdquo) to deal in the Software without restriction including without limitation the rights to usecopy modify merge publish distribute sublicense andor sell copies of the Software and to permit persons to whomthe Software is furnished to do so subject to the following conditions

The above copyright notice and this permission notice shall be included in all copies or substantial portions of theSoftware

THE SOFTWARE IS PROVIDED ldquoAS ISrdquo WITHOUT WARRANTY OF ANY KIND EXPRESS OR IMPLIEDINCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY FITNESS FOR A PAR-TICULAR PURPOSE AND NONINFRINGEMENT IN NO EVENT SHALL THE AUTHORS OR COPYRIGHTHOLDERS BE LIABLE FOR ANY CLAIM DAMAGES OR OTHER LIABILITY WHETHER IN AN ACTIONOF CONTRACT TORT OR OTHERWISE ARISING FROM OUT OF OR IN CONNECTION WITH THE SOFT-WARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE

27

docxtemplater Documentation Release 054

28 Chapter 10 Copyright

CHAPTER 11

Demos

Including

bull Replace Variables

bull Formating

bull Angular Parsing

bull Loops

bull Loops and tables

bull Lists

bull Replacing images

bull Naming the output

bull Using QrCodes

bull Replacing many images with QrCode

bull Raw Xml Insertion

29

docxtemplater Documentation Release 054

30 Chapter 11 Demos

CHAPTER 12

Indices and tables

bull genindex

bull modindex

bull search

31

docxtemplater Documentation Release 054

32 Chapter 12 Indices and tables

Index

CCommand Line Interface (CLI) 20Configuration 17Copyright 26

FFull_doc 21

GGenerate a Document 13Goals 1

IInstallation 7

Pplatform_support 3

SSyntax 9

33

  • Goals
    • Why you should use a library for this
      • Platform Support
      • Dependencies
      • Installation
        • Node
        • Browser
          • Syntax
            • Synopsis
            • Tag types
            • Loop syntax
            • Dash syntax
            • Inverted Selections
              • Generate a document
                • Loading a document
                • Setting the tags
                • Applying the tags
                • Outputing the document
                  • Configuration
                    • Image Replacing
                    • Angular Parser
                    • Intelligent LoopTagging
                      • Command Line Interface (CLI)
                        • Configjson Syntax
                          • Full Documentation per method
                            • Creating a new Docxgen Object
                            • Docxgen methods
                              • Copyright
                              • Demos
                              • Indices and tables
Page 14: Release 0.5€¦ · Docx is a zipped format that contains some xml. If you want to build a simple replace {tag} If you want to build a simple replace {tag} by value system, it can

CHAPTER 5

Syntax

The syntax is highly inspired by Mustache The template is created in Microsoft Word or any equivalent that saves todocx

51 Synopsis

A typical docxtemplater template

Hello name

Given the following hash

namersquoEdgarrsquo

Will produce

Hello Edgar

52 Tag types

Like Mustache it has the loopopening and loopclosing brackets

53 Loop syntax

The following template

productsname price C

products

Given the following hash

products

[nameWindowsprice100

11

docxtemplater Documentation Release 054

nameMac OSXprice200nameUbuntuprice0]

will result in

Windows 100 CMac OSX 200 CUbuntu 0C

The loop behaves in the following way

bull If the value is an array it will loop over all the elements of that array

bull If the value is a boolean it will loop once if the value is true keeping the same scope and not loop at all if thevalue is false

Note Because the loops work also with boolean values you can also use them for conditions

54 Dash syntax

It is quite difficult to know on which element you are going to loop By default when using the for loop docxgen willfind that by himself

If between the two tags tag______tag

bull they is the Xml Tag ltwtcgt -gt you are in a table and it will loop over ltwtrgt

bull else -gt it will loop over ltwtgt which is the default Text Tag

With the Dash syntax you pass as a first argument the tag you want to loop on

-wp loop inner loop

In this case this will loop over the first parent ltwpgt tag

55 Inverted Selections

An inverted section begins with a caret (hat) and ends with a slash That is ^person begins a ldquopersonrdquo invertedsection while person ends it

While sections can be used to render text one or more times based on the value of the key inverted sections may rendertext once based on the inverse value of the key That is they will be rendered if the key doesnrsquot exist is false or is anempty list

Template

repoltbgtnameltbgt

repo^repo

No repos (repo

Hash

12 Chapter 5 Syntax

docxtemplater Documentation Release 054

repo []

Output

No repos (

55 Inverted Selections 13

docxtemplater Documentation Release 054

14 Chapter 5 Syntax

CHAPTER 6

Generate a document

Herersquos a sample code to generate a document

DocxGen=require(rsquodocxtemplaterrsquo) Only for Node Usagenew DocxGen()loadFromFile(tagExampledocxasynctrue)success(function(doc)

docsetTags(first_nameHipp

last_nameEdgarphone0652455478descriptionNew Website

) set the templateVariablesdocapplyTags() apply them (replace all occurences of first_name by Hipp )docoutput() Output the document using Data-URI

)

The different steps are the following

61 Loading a document

A docx can be loaded by itrsquos base64 representation like this

doc=new DocxGen(base64Dataoptions)

However loading the base64Data is not that easy so I created a wrapper function to load a docx from a file via Ajax

Note The options parameter are explained in Configuration

doc=new DocxGen()loadFromFile(documentPathoptions)

The documentPath is the path to the document you want to load The options are the same as in the constructorfunction and Irsquove added the async parameter

bull If async is true the document is loaded asynchronously and returns a promise (eg you can write suc-cess(callback) to get when the document is loaded)

bull If async is false the document is loaded synchronously and returns the document

62 Setting the tags

The tags are the variables that are going to be replaced by their values To set them just use

15

docxtemplater Documentation Release 054

docsetTags(tags)

63 Applying the tags

Applying the tags means opening all files that contain text (eg footer header main document) and replace thevariables by their values

docapplyTags(tags)

Note If you specify an argument for the applyTags method the function setTags(tags) will be called before applyingthe tags

64 Outputing the document

They are several ways to output the document The most basic usage is to download the document

docoutput(options)

Depending on your environment if you donrsquot set any options this will

bull In the browser Download the document using DataURI

bull In Node Save the document with the given fileName (outputdocx by default)

Herersquos the different options parameters

nameTypestring[outputdocx]The name of the file that will be outputed (doesnt work in the browser because of dataUri download)

callbackTypefunctionFunction that is called without arguments when the output is done Is used only in Node (because in the browser the operation is synchronous)

downloadTypeboolean[true]If download is true file will be downloaded automatically with data URIreturns the output file

typeTypestring[base64]The type of zip to return The possible values are (same as in httpstukgithubiojszip generate)base64 (default) the result will be a string the binary in a base64 formstring the result will be a string in binary form 1 byte per charuint8array the result will be a Uint8Array containing the zip This requires a compatible browserarraybuffer the result will be a ArrayBuffer containing the zip This requires a compatible browserblob the result will be a Blob containing the zip This requires a compatible browsernodebuffer the result will be a nodejs Buffer containing the zip This requires nodejs

This function creates the docx file and downloads it on the userrsquos computer The name of the file is downloaddocxfor Chrome and some akward file names for Firefox VEeTHCfSdocxpartdocx and canrsquot be changed because it ishandled by the browser For more informations about how to solve this problem see the Filename Problems sectionon [httpstukgithubiojszip](httpstukgithubiojszip)

16 Chapter 6 Generate a document

docxtemplater Documentation Release 054

Note Note All browsers donrsquot support the download of big files withData URI so you should use the download method for files bigger than 100kBdataimagepngbase64iVBORw0KGgoAAAANSUhEUgAAABcAAAAXCAIAAABvSEP3AAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAACXSURBVDhPtY7BDYAwDAMZhCf7b8YMxeCoatOQJhWcKGxT2zlCyaWcz8Y+X7Bs1TFVJSwIHIYyFkQufWIRVX9cNJyW1QpEo4rixaEe7JuQagAUctb7ZFYFh5MVJPBe84CVBnB42YsZRgKjFDBVg3cI9WbRwXLktQJX8cNIiFhM1ZuTWk7PIYSBhkVcLzwIiCjCxhCjlAkBqYnqFoQQ2AAAAAElFTkSuQmCC

In Node to send the document to the client you can write the following code snippet

out=docoutput(downloadfalsetypestring)ressend(new Buffer(outbinary))

64 Outputing the document 17

docxtemplater Documentation Release 054

18 Chapter 6 Generate a document

CHAPTER 7

Configuration

Here are documented the special options that you can set when creating a new DocxGen to get some more superpower

It documents the options parameter when you do

new DocxGen(dataoptions)

71 Image Replacing

The name of this option qrCode (boolean)

To stay a templating engine I wanted that DocxTemplater doesnrsquot add an image from scratch but rather uses anexisting image that can be detected and DocxTemplater will just change the contents of that image without changingitrsquos style The size of the replaced images will stay the same

So I decided to use the qrCode format which is a format that lets you identify images by their content

The option for this is qrCode (true for on false for off default off)

Note If you donrsquot use that functionality you should disable it because it is quite slow (the image decoding)

Warning The qrCode functionality only works for PNG They is no support for other file formats yet

72 Angular Parser

The name of this option parser (function)

You can set the angular parser with the following code

With a custom parser you can parse the tags to for example add operators like lsquo+rsquo lsquo-lsquo or whatever the way you wantto parse expressions

To enable this you need to specify a custom parser You need to create a parser function

docxtemplater comes shipped with this parser

parser=function(expression)

return

19

docxtemplater Documentation Release 054

getfunction(scope) return scope[expression]

To use the angular-parser do the following

expressions= require(rsquoangular-expressionsrsquo)angularParser= function(tag)

return getexpressionscompile(tag)

new DocxGen(dataparserangularParser)

Note The require() works in the browser if you include vendorangular-parser-browserjs

73 Intelligent LoopTagging

The name of this option intelligentTagging (boolean)

When looping over an element docxtemplater needs to know over which element you want to loop By default it triesto do that intelligently (by looking what XML Tags are between the tags) However if you want to always use theltwtgt tag by default set this option to false

You can always specify over which element you want to loop with the dash loop syntax

20 Chapter 7 Configuration

CHAPTER 8

Command Line Interface (CLI)

This section is about the commandline interface of docxtemplater

The syntax is the following

docxtemplater configjson

The full configjson should be something like that

configdocxFileinputdocxconfigoutputFileoutputdocxconfigqrcodetrueconfigdebugtruefirst_nameJohnlast_nameSmithage62

81 Configjson Syntax

811 Config properties

These are the properties to configure docxtemplater

configdocxFileinputdocx The input file pathconfigoutputFileoutputdocx The output file pathconfigqrcodetrue whether the images should be scanned to replace them by qrcodes (slows down the cli a lot)configdebugtrue whether to show debug output or not

812 Data properties

To add data to your template just use keys that donrsquot start with ldquoconfigrdquo

first_nameJohnlast_nameSmithage62

21

docxtemplater Documentation Release 054

22 Chapter 8 Command Line Interface (CLI)

CHAPTER 9

Full Documentation per method

91 Creating a new Docxgen Object

new DocxGen()

This function returns a new DocxGen Object

new DocxGen(content[Tagsoptions])

contentType stringThe docx template you want to load as plain text

TagsType Object tag_nametag_replacement []Object containing for each tag_name the replacement for this tag For example if you want to replace firstName by David your Object will be firstNameDavid

options object

parserType functionA custom parser to use See angularjs like parsing

intelligentTaggingType boolean [false]If intelligent Tagging is not set to true when using recursive tags (tag and tag) the system will copy paste what is between the start tag and the endtag this could basically corrupt the files if recursive tags are used inside tablesIf intelligent Tagging is set to true and when using recursive tags inside tables the whole column will be copy pasted

qrCodeType boolean [false]If qrCode is set to true DocxGen will look at all the images to find a Qr-Code If the Qr-code matches to a URL this URL will be loaded by ajax (Be aware that the server you want to access needs to allow your request or it wonrsquot work httpstackoverflowcomquestions9310112why-am-i-seeing-an-origin-is-not-allowed-by-access-control-allow-origin-error )

Important the qrCode functionality only works for PNG I donrsquot think I will enable this for other fileformats in the near future

localImageCreatorType function(argcallback) [function that returns an arrow]The function has to be customized only if you want to use the qrCode options (qrCode=true) When the qrcode text starts with gen the image is not going to be loaded by url but DocxGen calls localImageCreator with arg=full Text decoded The callback needs to be called with the image Datacallback(result) in plaintxt format (if you want to create it from a Data-URI you can use JSZipBase64decode(data) to decode a Data-URI to plaintxt)

The default localImageCreator returns a red arrow no matter what the arguments are

localImageCreator= (argcallback) -gtresult=JSZipBase64decode(iVBORw0KGgoAAAANSUhEUgAAABcAAAAXCAIAAABvSEP3AAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAACXSURBVDhPtY7BDYAwDAMZhCf7b8YMxeCoatOQJhWcKGxT2zlCyaWcz8Y+X7Bs1TFVJSwIHIYyFkQufWIRVX9cNJyW1QpEo4rixaEe7JuQagAUctb7ZFYFh5MVJPBe84CVBnB42YsZRgKjFDBVg3cI9WbRwXLktQJX8cNIiFhM1ZuTWk7PIYSBhkVcLzwIiCjCxhCjlAkBqYnqFoQQ2AAAAAElFTkSuQmCC)

23

docxtemplater Documentation Release 054

[Default Image](dataimagepngbase64iVBORw0KGgoAAAANSUhEUgAAABcAAAAXCAIAAABvSEP3AAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAACXSURBVDhPtY7BDYAwDAMZhCf7b8YMxeCoatOQJhWcKGxT2zlCyaWcz8Y+X7Bs1TFVJSwIHIYyFkQufWIRVX9cNJyW1QpEo4rixaEe7JuQagAUctb7ZFYFh5MVJPBe84CVBnB42YsZRgKjFDBVg3cI9WbRwXLktQJX8cNIiFhM1ZuTWk7PIYSBhkVcLzwIiCjCxhCjlAkBqYnqFoQQ2AAAAAElFTkSuQmCC)

qrFinishedCallBackType function () [function that consolelog(ready)]

This function is called if you specify qrCode argument to true in this constructor and will be called when all qrCodes have been replaced (because the qrCode replacing functions are async)

92 Docxgen methods

load(content)

contentType stringThe docx template you want to load as plain text

loadFromFile(path)path

Type stringLoads a docx from a file path

setTags(Tags)

TagsType Object tag_nametag_replacementObject containing for each tag_name the replacement for this tag For example if you want to replace firstName by David your Object will be firstNameDavid

applyTags([Tags])Tags

Type Object tag_nametag_replacementsame as setTagsDefaultthisTags

This function replaces all template variables by their values

output([options])

options object[]

nameTypestring[outputdocx]The name of the file that will be outputed (doesnt work in the browser because of dataUri download)

callbackTypefunctionFunction that is called without arguments when the output is done Is used only in Node (because in the browser the operation is synchronous)

downloadTypeboolean[true]If download is true file will be downloaded automatically with data URIreturns the output file

typeTypestring[base64]The type of zip to return The possible values are (same as in httpstukgithubiojszip generate)base64 (default) the result will be a string the binary in a base64 formstring the result will be a string in binary form 1 byte per charuint8array the result will be a Uint8Array containing the zip This requires a compatible browser

24 Chapter 9 Full Documentation per method

docxtemplater Documentation Release 054

arraybuffer the result will be a ArrayBuffer containing the zip This requires a compatible browserblob the result will be a Blob containing the zip This requires a compatible browsernodebuffer the result will be a nodejs Buffer containing the zip This requires nodejs

This function creates the docx file and downloads it on the userrsquos computer The name of the file is downloaddocx for Chrome and some akward file names for Firefox VEeTHCfSdocxpartdocx and canrsquot be changed because it is handled by the browserFor more informations about how to solve this problem see the Filename Problems section on [httpstukgithubiojszip](httpstukgithubiojszip)

Note All browsers donrsquot support the download of big files with Data URI so you should use the lsquodownloadlsquo method for files bigger than 100kB dataimagepngbase64iVBORw0KGgoAAAANSUhEUgAAABcAAAAXCAIAAABvSEP3AAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAACXSURBVDhPtY7BDYAwDAMZhCf7b8YMxeCoatOQJhWcKGxT2zlCyaWcz8Y+X7Bs1TFVJSwIHIYyFkQufWIRVX9cNJyW1QpEo4rixaEe7JuQagAUctb7ZFYFh5MVJPBe84CVBnB42YsZRgKjFDBVg3cI9WbRwXLktQJX8cNIiFhM1ZuTWk7PIYSBhkVcLzwIiCjCxhCjlAkBqYnqFoQQ2AAAAAElFTkSuQmCC

download(swfpathimgpath[fileName])

swfpathTypestringPath to the swfobjectjs in downloadify

imgpathTypestringPath to the image of the download button

[fileName]TypestringDefaultdefaultdocxName of the file you would like the user to download

This requires to include Downloadifyjs that needs flash version 10 Have a look at the output function if you donrsquot want to depend on it This function has the advantage that it works regardless of the file size

getImageList()

this gets all images that have one of the following extension rsquogifrsquorsquojpegrsquorsquojpgrsquorsquoemfrsquorsquopngrsquoReturn format Array of Object[pathstringfilesZipFile Object]

You shouldrsquont call this method before calling applyTags() because applyTags can modify the images or their path when replacing images with other (particularly when qrCode is set to true which is not the default case) You can call this method after applyTags() without any problems

setImage(pathimgData)

pathTypeStringPath of the image given by getImageList()

imgDataTypeStringimgData in txtplain

This sets the image given by a path and an imgData in txtplainYou shouldrsquont call this method before calling applyTags() because applyTags can modify the images or their path when replacing images with other (particularly when qrCode is set to true which is not the default case) You can call this method after applyTags() without any problems

getFullText([path])

pathTypeStringDefaultworddocumentxmlThis argument determines from which document you want to get the text The main document is called worddocumentxml but they are other documents wordheader1xml wordfooter1xml

returnsTypeStringThe string containing all the text from the document

92 Docxgen methods 25

docxtemplater Documentation Release 054

This method gets only the text of a given document (not the formatting)

getTags()

This function returns the template variables contained in the opened document For example if the content of the documentxml is the following

namefirst_namephone

The function will return[

filenamedocumentxmlvars

nametruefirst_nametruephonetrue

]

If the content contains tagLoops

titlecustomernamephonecustomer

The function will return

[filenamedocumentxmlvars

titletruecustomer

nametruephonetrue

]

26 Chapter 9 Full Documentation per method

CHAPTER 10

Copyright

License

(The MIT license)

Copyright (c) 2013 Edgar Hipp

Permission is hereby granted free of charge to any person obtaining a copy of this software and associated documen-tation files (the ldquoSoftwarerdquo) to deal in the Software without restriction including without limitation the rights to usecopy modify merge publish distribute sublicense andor sell copies of the Software and to permit persons to whomthe Software is furnished to do so subject to the following conditions

The above copyright notice and this permission notice shall be included in all copies or substantial portions of theSoftware

THE SOFTWARE IS PROVIDED ldquoAS ISrdquo WITHOUT WARRANTY OF ANY KIND EXPRESS OR IMPLIEDINCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY FITNESS FOR A PAR-TICULAR PURPOSE AND NONINFRINGEMENT IN NO EVENT SHALL THE AUTHORS OR COPYRIGHTHOLDERS BE LIABLE FOR ANY CLAIM DAMAGES OR OTHER LIABILITY WHETHER IN AN ACTIONOF CONTRACT TORT OR OTHERWISE ARISING FROM OUT OF OR IN CONNECTION WITH THE SOFT-WARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE

27

docxtemplater Documentation Release 054

28 Chapter 10 Copyright

CHAPTER 11

Demos

Including

bull Replace Variables

bull Formating

bull Angular Parsing

bull Loops

bull Loops and tables

bull Lists

bull Replacing images

bull Naming the output

bull Using QrCodes

bull Replacing many images with QrCode

bull Raw Xml Insertion

29

docxtemplater Documentation Release 054

30 Chapter 11 Demos

CHAPTER 12

Indices and tables

bull genindex

bull modindex

bull search

31

docxtemplater Documentation Release 054

32 Chapter 12 Indices and tables

Index

CCommand Line Interface (CLI) 20Configuration 17Copyright 26

FFull_doc 21

GGenerate a Document 13Goals 1

IInstallation 7

Pplatform_support 3

SSyntax 9

33

  • Goals
    • Why you should use a library for this
      • Platform Support
      • Dependencies
      • Installation
        • Node
        • Browser
          • Syntax
            • Synopsis
            • Tag types
            • Loop syntax
            • Dash syntax
            • Inverted Selections
              • Generate a document
                • Loading a document
                • Setting the tags
                • Applying the tags
                • Outputing the document
                  • Configuration
                    • Image Replacing
                    • Angular Parser
                    • Intelligent LoopTagging
                      • Command Line Interface (CLI)
                        • Configjson Syntax
                          • Full Documentation per method
                            • Creating a new Docxgen Object
                            • Docxgen methods
                              • Copyright
                              • Demos
                              • Indices and tables
Page 15: Release 0.5€¦ · Docx is a zipped format that contains some xml. If you want to build a simple replace {tag} If you want to build a simple replace {tag} by value system, it can

docxtemplater Documentation Release 054

nameMac OSXprice200nameUbuntuprice0]

will result in

Windows 100 CMac OSX 200 CUbuntu 0C

The loop behaves in the following way

bull If the value is an array it will loop over all the elements of that array

bull If the value is a boolean it will loop once if the value is true keeping the same scope and not loop at all if thevalue is false

Note Because the loops work also with boolean values you can also use them for conditions

54 Dash syntax

It is quite difficult to know on which element you are going to loop By default when using the for loop docxgen willfind that by himself

If between the two tags tag______tag

bull they is the Xml Tag ltwtcgt -gt you are in a table and it will loop over ltwtrgt

bull else -gt it will loop over ltwtgt which is the default Text Tag

With the Dash syntax you pass as a first argument the tag you want to loop on

-wp loop inner loop

In this case this will loop over the first parent ltwpgt tag

55 Inverted Selections

An inverted section begins with a caret (hat) and ends with a slash That is ^person begins a ldquopersonrdquo invertedsection while person ends it

While sections can be used to render text one or more times based on the value of the key inverted sections may rendertext once based on the inverse value of the key That is they will be rendered if the key doesnrsquot exist is false or is anempty list

Template

repoltbgtnameltbgt

repo^repo

No repos (repo

Hash

12 Chapter 5 Syntax

docxtemplater Documentation Release 054

repo []

Output

No repos (

55 Inverted Selections 13

docxtemplater Documentation Release 054

14 Chapter 5 Syntax

CHAPTER 6

Generate a document

Herersquos a sample code to generate a document

DocxGen=require(rsquodocxtemplaterrsquo) Only for Node Usagenew DocxGen()loadFromFile(tagExampledocxasynctrue)success(function(doc)

docsetTags(first_nameHipp

last_nameEdgarphone0652455478descriptionNew Website

) set the templateVariablesdocapplyTags() apply them (replace all occurences of first_name by Hipp )docoutput() Output the document using Data-URI

)

The different steps are the following

61 Loading a document

A docx can be loaded by itrsquos base64 representation like this

doc=new DocxGen(base64Dataoptions)

However loading the base64Data is not that easy so I created a wrapper function to load a docx from a file via Ajax

Note The options parameter are explained in Configuration

doc=new DocxGen()loadFromFile(documentPathoptions)

The documentPath is the path to the document you want to load The options are the same as in the constructorfunction and Irsquove added the async parameter

bull If async is true the document is loaded asynchronously and returns a promise (eg you can write suc-cess(callback) to get when the document is loaded)

bull If async is false the document is loaded synchronously and returns the document

62 Setting the tags

The tags are the variables that are going to be replaced by their values To set them just use

15

docxtemplater Documentation Release 054

docsetTags(tags)

63 Applying the tags

Applying the tags means opening all files that contain text (eg footer header main document) and replace thevariables by their values

docapplyTags(tags)

Note If you specify an argument for the applyTags method the function setTags(tags) will be called before applyingthe tags

64 Outputing the document

They are several ways to output the document The most basic usage is to download the document

docoutput(options)

Depending on your environment if you donrsquot set any options this will

bull In the browser Download the document using DataURI

bull In Node Save the document with the given fileName (outputdocx by default)

Herersquos the different options parameters

nameTypestring[outputdocx]The name of the file that will be outputed (doesnt work in the browser because of dataUri download)

callbackTypefunctionFunction that is called without arguments when the output is done Is used only in Node (because in the browser the operation is synchronous)

downloadTypeboolean[true]If download is true file will be downloaded automatically with data URIreturns the output file

typeTypestring[base64]The type of zip to return The possible values are (same as in httpstukgithubiojszip generate)base64 (default) the result will be a string the binary in a base64 formstring the result will be a string in binary form 1 byte per charuint8array the result will be a Uint8Array containing the zip This requires a compatible browserarraybuffer the result will be a ArrayBuffer containing the zip This requires a compatible browserblob the result will be a Blob containing the zip This requires a compatible browsernodebuffer the result will be a nodejs Buffer containing the zip This requires nodejs

This function creates the docx file and downloads it on the userrsquos computer The name of the file is downloaddocxfor Chrome and some akward file names for Firefox VEeTHCfSdocxpartdocx and canrsquot be changed because it ishandled by the browser For more informations about how to solve this problem see the Filename Problems sectionon [httpstukgithubiojszip](httpstukgithubiojszip)

16 Chapter 6 Generate a document

docxtemplater Documentation Release 054

Note Note All browsers donrsquot support the download of big files withData URI so you should use the download method for files bigger than 100kBdataimagepngbase64iVBORw0KGgoAAAANSUhEUgAAABcAAAAXCAIAAABvSEP3AAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAACXSURBVDhPtY7BDYAwDAMZhCf7b8YMxeCoatOQJhWcKGxT2zlCyaWcz8Y+X7Bs1TFVJSwIHIYyFkQufWIRVX9cNJyW1QpEo4rixaEe7JuQagAUctb7ZFYFh5MVJPBe84CVBnB42YsZRgKjFDBVg3cI9WbRwXLktQJX8cNIiFhM1ZuTWk7PIYSBhkVcLzwIiCjCxhCjlAkBqYnqFoQQ2AAAAAElFTkSuQmCC

In Node to send the document to the client you can write the following code snippet

out=docoutput(downloadfalsetypestring)ressend(new Buffer(outbinary))

64 Outputing the document 17

docxtemplater Documentation Release 054

18 Chapter 6 Generate a document

CHAPTER 7

Configuration

Here are documented the special options that you can set when creating a new DocxGen to get some more superpower

It documents the options parameter when you do

new DocxGen(dataoptions)

71 Image Replacing

The name of this option qrCode (boolean)

To stay a templating engine I wanted that DocxTemplater doesnrsquot add an image from scratch but rather uses anexisting image that can be detected and DocxTemplater will just change the contents of that image without changingitrsquos style The size of the replaced images will stay the same

So I decided to use the qrCode format which is a format that lets you identify images by their content

The option for this is qrCode (true for on false for off default off)

Note If you donrsquot use that functionality you should disable it because it is quite slow (the image decoding)

Warning The qrCode functionality only works for PNG They is no support for other file formats yet

72 Angular Parser

The name of this option parser (function)

You can set the angular parser with the following code

With a custom parser you can parse the tags to for example add operators like lsquo+rsquo lsquo-lsquo or whatever the way you wantto parse expressions

To enable this you need to specify a custom parser You need to create a parser function

docxtemplater comes shipped with this parser

parser=function(expression)

return

19

docxtemplater Documentation Release 054

getfunction(scope) return scope[expression]

To use the angular-parser do the following

expressions= require(rsquoangular-expressionsrsquo)angularParser= function(tag)

return getexpressionscompile(tag)

new DocxGen(dataparserangularParser)

Note The require() works in the browser if you include vendorangular-parser-browserjs

73 Intelligent LoopTagging

The name of this option intelligentTagging (boolean)

When looping over an element docxtemplater needs to know over which element you want to loop By default it triesto do that intelligently (by looking what XML Tags are between the tags) However if you want to always use theltwtgt tag by default set this option to false

You can always specify over which element you want to loop with the dash loop syntax

20 Chapter 7 Configuration

CHAPTER 8

Command Line Interface (CLI)

This section is about the commandline interface of docxtemplater

The syntax is the following

docxtemplater configjson

The full configjson should be something like that

configdocxFileinputdocxconfigoutputFileoutputdocxconfigqrcodetrueconfigdebugtruefirst_nameJohnlast_nameSmithage62

81 Configjson Syntax

811 Config properties

These are the properties to configure docxtemplater

configdocxFileinputdocx The input file pathconfigoutputFileoutputdocx The output file pathconfigqrcodetrue whether the images should be scanned to replace them by qrcodes (slows down the cli a lot)configdebugtrue whether to show debug output or not

812 Data properties

To add data to your template just use keys that donrsquot start with ldquoconfigrdquo

first_nameJohnlast_nameSmithage62

21

docxtemplater Documentation Release 054

22 Chapter 8 Command Line Interface (CLI)

CHAPTER 9

Full Documentation per method

91 Creating a new Docxgen Object

new DocxGen()

This function returns a new DocxGen Object

new DocxGen(content[Tagsoptions])

contentType stringThe docx template you want to load as plain text

TagsType Object tag_nametag_replacement []Object containing for each tag_name the replacement for this tag For example if you want to replace firstName by David your Object will be firstNameDavid

options object

parserType functionA custom parser to use See angularjs like parsing

intelligentTaggingType boolean [false]If intelligent Tagging is not set to true when using recursive tags (tag and tag) the system will copy paste what is between the start tag and the endtag this could basically corrupt the files if recursive tags are used inside tablesIf intelligent Tagging is set to true and when using recursive tags inside tables the whole column will be copy pasted

qrCodeType boolean [false]If qrCode is set to true DocxGen will look at all the images to find a Qr-Code If the Qr-code matches to a URL this URL will be loaded by ajax (Be aware that the server you want to access needs to allow your request or it wonrsquot work httpstackoverflowcomquestions9310112why-am-i-seeing-an-origin-is-not-allowed-by-access-control-allow-origin-error )

Important the qrCode functionality only works for PNG I donrsquot think I will enable this for other fileformats in the near future

localImageCreatorType function(argcallback) [function that returns an arrow]The function has to be customized only if you want to use the qrCode options (qrCode=true) When the qrcode text starts with gen the image is not going to be loaded by url but DocxGen calls localImageCreator with arg=full Text decoded The callback needs to be called with the image Datacallback(result) in plaintxt format (if you want to create it from a Data-URI you can use JSZipBase64decode(data) to decode a Data-URI to plaintxt)

The default localImageCreator returns a red arrow no matter what the arguments are

localImageCreator= (argcallback) -gtresult=JSZipBase64decode(iVBORw0KGgoAAAANSUhEUgAAABcAAAAXCAIAAABvSEP3AAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAACXSURBVDhPtY7BDYAwDAMZhCf7b8YMxeCoatOQJhWcKGxT2zlCyaWcz8Y+X7Bs1TFVJSwIHIYyFkQufWIRVX9cNJyW1QpEo4rixaEe7JuQagAUctb7ZFYFh5MVJPBe84CVBnB42YsZRgKjFDBVg3cI9WbRwXLktQJX8cNIiFhM1ZuTWk7PIYSBhkVcLzwIiCjCxhCjlAkBqYnqFoQQ2AAAAAElFTkSuQmCC)

23

docxtemplater Documentation Release 054

[Default Image](dataimagepngbase64iVBORw0KGgoAAAANSUhEUgAAABcAAAAXCAIAAABvSEP3AAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAACXSURBVDhPtY7BDYAwDAMZhCf7b8YMxeCoatOQJhWcKGxT2zlCyaWcz8Y+X7Bs1TFVJSwIHIYyFkQufWIRVX9cNJyW1QpEo4rixaEe7JuQagAUctb7ZFYFh5MVJPBe84CVBnB42YsZRgKjFDBVg3cI9WbRwXLktQJX8cNIiFhM1ZuTWk7PIYSBhkVcLzwIiCjCxhCjlAkBqYnqFoQQ2AAAAAElFTkSuQmCC)

qrFinishedCallBackType function () [function that consolelog(ready)]

This function is called if you specify qrCode argument to true in this constructor and will be called when all qrCodes have been replaced (because the qrCode replacing functions are async)

92 Docxgen methods

load(content)

contentType stringThe docx template you want to load as plain text

loadFromFile(path)path

Type stringLoads a docx from a file path

setTags(Tags)

TagsType Object tag_nametag_replacementObject containing for each tag_name the replacement for this tag For example if you want to replace firstName by David your Object will be firstNameDavid

applyTags([Tags])Tags

Type Object tag_nametag_replacementsame as setTagsDefaultthisTags

This function replaces all template variables by their values

output([options])

options object[]

nameTypestring[outputdocx]The name of the file that will be outputed (doesnt work in the browser because of dataUri download)

callbackTypefunctionFunction that is called without arguments when the output is done Is used only in Node (because in the browser the operation is synchronous)

downloadTypeboolean[true]If download is true file will be downloaded automatically with data URIreturns the output file

typeTypestring[base64]The type of zip to return The possible values are (same as in httpstukgithubiojszip generate)base64 (default) the result will be a string the binary in a base64 formstring the result will be a string in binary form 1 byte per charuint8array the result will be a Uint8Array containing the zip This requires a compatible browser

24 Chapter 9 Full Documentation per method

docxtemplater Documentation Release 054

arraybuffer the result will be a ArrayBuffer containing the zip This requires a compatible browserblob the result will be a Blob containing the zip This requires a compatible browsernodebuffer the result will be a nodejs Buffer containing the zip This requires nodejs

This function creates the docx file and downloads it on the userrsquos computer The name of the file is downloaddocx for Chrome and some akward file names for Firefox VEeTHCfSdocxpartdocx and canrsquot be changed because it is handled by the browserFor more informations about how to solve this problem see the Filename Problems section on [httpstukgithubiojszip](httpstukgithubiojszip)

Note All browsers donrsquot support the download of big files with Data URI so you should use the lsquodownloadlsquo method for files bigger than 100kB dataimagepngbase64iVBORw0KGgoAAAANSUhEUgAAABcAAAAXCAIAAABvSEP3AAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAACXSURBVDhPtY7BDYAwDAMZhCf7b8YMxeCoatOQJhWcKGxT2zlCyaWcz8Y+X7Bs1TFVJSwIHIYyFkQufWIRVX9cNJyW1QpEo4rixaEe7JuQagAUctb7ZFYFh5MVJPBe84CVBnB42YsZRgKjFDBVg3cI9WbRwXLktQJX8cNIiFhM1ZuTWk7PIYSBhkVcLzwIiCjCxhCjlAkBqYnqFoQQ2AAAAAElFTkSuQmCC

download(swfpathimgpath[fileName])

swfpathTypestringPath to the swfobjectjs in downloadify

imgpathTypestringPath to the image of the download button

[fileName]TypestringDefaultdefaultdocxName of the file you would like the user to download

This requires to include Downloadifyjs that needs flash version 10 Have a look at the output function if you donrsquot want to depend on it This function has the advantage that it works regardless of the file size

getImageList()

this gets all images that have one of the following extension rsquogifrsquorsquojpegrsquorsquojpgrsquorsquoemfrsquorsquopngrsquoReturn format Array of Object[pathstringfilesZipFile Object]

You shouldrsquont call this method before calling applyTags() because applyTags can modify the images or their path when replacing images with other (particularly when qrCode is set to true which is not the default case) You can call this method after applyTags() without any problems

setImage(pathimgData)

pathTypeStringPath of the image given by getImageList()

imgDataTypeStringimgData in txtplain

This sets the image given by a path and an imgData in txtplainYou shouldrsquont call this method before calling applyTags() because applyTags can modify the images or their path when replacing images with other (particularly when qrCode is set to true which is not the default case) You can call this method after applyTags() without any problems

getFullText([path])

pathTypeStringDefaultworddocumentxmlThis argument determines from which document you want to get the text The main document is called worddocumentxml but they are other documents wordheader1xml wordfooter1xml

returnsTypeStringThe string containing all the text from the document

92 Docxgen methods 25

docxtemplater Documentation Release 054

This method gets only the text of a given document (not the formatting)

getTags()

This function returns the template variables contained in the opened document For example if the content of the documentxml is the following

namefirst_namephone

The function will return[

filenamedocumentxmlvars

nametruefirst_nametruephonetrue

]

If the content contains tagLoops

titlecustomernamephonecustomer

The function will return

[filenamedocumentxmlvars

titletruecustomer

nametruephonetrue

]

26 Chapter 9 Full Documentation per method

CHAPTER 10

Copyright

License

(The MIT license)

Copyright (c) 2013 Edgar Hipp

Permission is hereby granted free of charge to any person obtaining a copy of this software and associated documen-tation files (the ldquoSoftwarerdquo) to deal in the Software without restriction including without limitation the rights to usecopy modify merge publish distribute sublicense andor sell copies of the Software and to permit persons to whomthe Software is furnished to do so subject to the following conditions

The above copyright notice and this permission notice shall be included in all copies or substantial portions of theSoftware

THE SOFTWARE IS PROVIDED ldquoAS ISrdquo WITHOUT WARRANTY OF ANY KIND EXPRESS OR IMPLIEDINCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY FITNESS FOR A PAR-TICULAR PURPOSE AND NONINFRINGEMENT IN NO EVENT SHALL THE AUTHORS OR COPYRIGHTHOLDERS BE LIABLE FOR ANY CLAIM DAMAGES OR OTHER LIABILITY WHETHER IN AN ACTIONOF CONTRACT TORT OR OTHERWISE ARISING FROM OUT OF OR IN CONNECTION WITH THE SOFT-WARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE

27

docxtemplater Documentation Release 054

28 Chapter 10 Copyright

CHAPTER 11

Demos

Including

bull Replace Variables

bull Formating

bull Angular Parsing

bull Loops

bull Loops and tables

bull Lists

bull Replacing images

bull Naming the output

bull Using QrCodes

bull Replacing many images with QrCode

bull Raw Xml Insertion

29

docxtemplater Documentation Release 054

30 Chapter 11 Demos

CHAPTER 12

Indices and tables

bull genindex

bull modindex

bull search

31

docxtemplater Documentation Release 054

32 Chapter 12 Indices and tables

Index

CCommand Line Interface (CLI) 20Configuration 17Copyright 26

FFull_doc 21

GGenerate a Document 13Goals 1

IInstallation 7

Pplatform_support 3

SSyntax 9

33

  • Goals
    • Why you should use a library for this
      • Platform Support
      • Dependencies
      • Installation
        • Node
        • Browser
          • Syntax
            • Synopsis
            • Tag types
            • Loop syntax
            • Dash syntax
            • Inverted Selections
              • Generate a document
                • Loading a document
                • Setting the tags
                • Applying the tags
                • Outputing the document
                  • Configuration
                    • Image Replacing
                    • Angular Parser
                    • Intelligent LoopTagging
                      • Command Line Interface (CLI)
                        • Configjson Syntax
                          • Full Documentation per method
                            • Creating a new Docxgen Object
                            • Docxgen methods
                              • Copyright
                              • Demos
                              • Indices and tables
Page 16: Release 0.5€¦ · Docx is a zipped format that contains some xml. If you want to build a simple replace {tag} If you want to build a simple replace {tag} by value system, it can

docxtemplater Documentation Release 054

repo []

Output

No repos (

55 Inverted Selections 13

docxtemplater Documentation Release 054

14 Chapter 5 Syntax

CHAPTER 6

Generate a document

Herersquos a sample code to generate a document

DocxGen=require(rsquodocxtemplaterrsquo) Only for Node Usagenew DocxGen()loadFromFile(tagExampledocxasynctrue)success(function(doc)

docsetTags(first_nameHipp

last_nameEdgarphone0652455478descriptionNew Website

) set the templateVariablesdocapplyTags() apply them (replace all occurences of first_name by Hipp )docoutput() Output the document using Data-URI

)

The different steps are the following

61 Loading a document

A docx can be loaded by itrsquos base64 representation like this

doc=new DocxGen(base64Dataoptions)

However loading the base64Data is not that easy so I created a wrapper function to load a docx from a file via Ajax

Note The options parameter are explained in Configuration

doc=new DocxGen()loadFromFile(documentPathoptions)

The documentPath is the path to the document you want to load The options are the same as in the constructorfunction and Irsquove added the async parameter

bull If async is true the document is loaded asynchronously and returns a promise (eg you can write suc-cess(callback) to get when the document is loaded)

bull If async is false the document is loaded synchronously and returns the document

62 Setting the tags

The tags are the variables that are going to be replaced by their values To set them just use

15

docxtemplater Documentation Release 054

docsetTags(tags)

63 Applying the tags

Applying the tags means opening all files that contain text (eg footer header main document) and replace thevariables by their values

docapplyTags(tags)

Note If you specify an argument for the applyTags method the function setTags(tags) will be called before applyingthe tags

64 Outputing the document

They are several ways to output the document The most basic usage is to download the document

docoutput(options)

Depending on your environment if you donrsquot set any options this will

bull In the browser Download the document using DataURI

bull In Node Save the document with the given fileName (outputdocx by default)

Herersquos the different options parameters

nameTypestring[outputdocx]The name of the file that will be outputed (doesnt work in the browser because of dataUri download)

callbackTypefunctionFunction that is called without arguments when the output is done Is used only in Node (because in the browser the operation is synchronous)

downloadTypeboolean[true]If download is true file will be downloaded automatically with data URIreturns the output file

typeTypestring[base64]The type of zip to return The possible values are (same as in httpstukgithubiojszip generate)base64 (default) the result will be a string the binary in a base64 formstring the result will be a string in binary form 1 byte per charuint8array the result will be a Uint8Array containing the zip This requires a compatible browserarraybuffer the result will be a ArrayBuffer containing the zip This requires a compatible browserblob the result will be a Blob containing the zip This requires a compatible browsernodebuffer the result will be a nodejs Buffer containing the zip This requires nodejs

This function creates the docx file and downloads it on the userrsquos computer The name of the file is downloaddocxfor Chrome and some akward file names for Firefox VEeTHCfSdocxpartdocx and canrsquot be changed because it ishandled by the browser For more informations about how to solve this problem see the Filename Problems sectionon [httpstukgithubiojszip](httpstukgithubiojszip)

16 Chapter 6 Generate a document

docxtemplater Documentation Release 054

Note Note All browsers donrsquot support the download of big files withData URI so you should use the download method for files bigger than 100kBdataimagepngbase64iVBORw0KGgoAAAANSUhEUgAAABcAAAAXCAIAAABvSEP3AAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAACXSURBVDhPtY7BDYAwDAMZhCf7b8YMxeCoatOQJhWcKGxT2zlCyaWcz8Y+X7Bs1TFVJSwIHIYyFkQufWIRVX9cNJyW1QpEo4rixaEe7JuQagAUctb7ZFYFh5MVJPBe84CVBnB42YsZRgKjFDBVg3cI9WbRwXLktQJX8cNIiFhM1ZuTWk7PIYSBhkVcLzwIiCjCxhCjlAkBqYnqFoQQ2AAAAAElFTkSuQmCC

In Node to send the document to the client you can write the following code snippet

out=docoutput(downloadfalsetypestring)ressend(new Buffer(outbinary))

64 Outputing the document 17

docxtemplater Documentation Release 054

18 Chapter 6 Generate a document

CHAPTER 7

Configuration

Here are documented the special options that you can set when creating a new DocxGen to get some more superpower

It documents the options parameter when you do

new DocxGen(dataoptions)

71 Image Replacing

The name of this option qrCode (boolean)

To stay a templating engine I wanted that DocxTemplater doesnrsquot add an image from scratch but rather uses anexisting image that can be detected and DocxTemplater will just change the contents of that image without changingitrsquos style The size of the replaced images will stay the same

So I decided to use the qrCode format which is a format that lets you identify images by their content

The option for this is qrCode (true for on false for off default off)

Note If you donrsquot use that functionality you should disable it because it is quite slow (the image decoding)

Warning The qrCode functionality only works for PNG They is no support for other file formats yet

72 Angular Parser

The name of this option parser (function)

You can set the angular parser with the following code

With a custom parser you can parse the tags to for example add operators like lsquo+rsquo lsquo-lsquo or whatever the way you wantto parse expressions

To enable this you need to specify a custom parser You need to create a parser function

docxtemplater comes shipped with this parser

parser=function(expression)

return

19

docxtemplater Documentation Release 054

getfunction(scope) return scope[expression]

To use the angular-parser do the following

expressions= require(rsquoangular-expressionsrsquo)angularParser= function(tag)

return getexpressionscompile(tag)

new DocxGen(dataparserangularParser)

Note The require() works in the browser if you include vendorangular-parser-browserjs

73 Intelligent LoopTagging

The name of this option intelligentTagging (boolean)

When looping over an element docxtemplater needs to know over which element you want to loop By default it triesto do that intelligently (by looking what XML Tags are between the tags) However if you want to always use theltwtgt tag by default set this option to false

You can always specify over which element you want to loop with the dash loop syntax

20 Chapter 7 Configuration

CHAPTER 8

Command Line Interface (CLI)

This section is about the commandline interface of docxtemplater

The syntax is the following

docxtemplater configjson

The full configjson should be something like that

configdocxFileinputdocxconfigoutputFileoutputdocxconfigqrcodetrueconfigdebugtruefirst_nameJohnlast_nameSmithage62

81 Configjson Syntax

811 Config properties

These are the properties to configure docxtemplater

configdocxFileinputdocx The input file pathconfigoutputFileoutputdocx The output file pathconfigqrcodetrue whether the images should be scanned to replace them by qrcodes (slows down the cli a lot)configdebugtrue whether to show debug output or not

812 Data properties

To add data to your template just use keys that donrsquot start with ldquoconfigrdquo

first_nameJohnlast_nameSmithage62

21

docxtemplater Documentation Release 054

22 Chapter 8 Command Line Interface (CLI)

CHAPTER 9

Full Documentation per method

91 Creating a new Docxgen Object

new DocxGen()

This function returns a new DocxGen Object

new DocxGen(content[Tagsoptions])

contentType stringThe docx template you want to load as plain text

TagsType Object tag_nametag_replacement []Object containing for each tag_name the replacement for this tag For example if you want to replace firstName by David your Object will be firstNameDavid

options object

parserType functionA custom parser to use See angularjs like parsing

intelligentTaggingType boolean [false]If intelligent Tagging is not set to true when using recursive tags (tag and tag) the system will copy paste what is between the start tag and the endtag this could basically corrupt the files if recursive tags are used inside tablesIf intelligent Tagging is set to true and when using recursive tags inside tables the whole column will be copy pasted

qrCodeType boolean [false]If qrCode is set to true DocxGen will look at all the images to find a Qr-Code If the Qr-code matches to a URL this URL will be loaded by ajax (Be aware that the server you want to access needs to allow your request or it wonrsquot work httpstackoverflowcomquestions9310112why-am-i-seeing-an-origin-is-not-allowed-by-access-control-allow-origin-error )

Important the qrCode functionality only works for PNG I donrsquot think I will enable this for other fileformats in the near future

localImageCreatorType function(argcallback) [function that returns an arrow]The function has to be customized only if you want to use the qrCode options (qrCode=true) When the qrcode text starts with gen the image is not going to be loaded by url but DocxGen calls localImageCreator with arg=full Text decoded The callback needs to be called with the image Datacallback(result) in plaintxt format (if you want to create it from a Data-URI you can use JSZipBase64decode(data) to decode a Data-URI to plaintxt)

The default localImageCreator returns a red arrow no matter what the arguments are

localImageCreator= (argcallback) -gtresult=JSZipBase64decode(iVBORw0KGgoAAAANSUhEUgAAABcAAAAXCAIAAABvSEP3AAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAACXSURBVDhPtY7BDYAwDAMZhCf7b8YMxeCoatOQJhWcKGxT2zlCyaWcz8Y+X7Bs1TFVJSwIHIYyFkQufWIRVX9cNJyW1QpEo4rixaEe7JuQagAUctb7ZFYFh5MVJPBe84CVBnB42YsZRgKjFDBVg3cI9WbRwXLktQJX8cNIiFhM1ZuTWk7PIYSBhkVcLzwIiCjCxhCjlAkBqYnqFoQQ2AAAAAElFTkSuQmCC)

23

docxtemplater Documentation Release 054

[Default Image](dataimagepngbase64iVBORw0KGgoAAAANSUhEUgAAABcAAAAXCAIAAABvSEP3AAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAACXSURBVDhPtY7BDYAwDAMZhCf7b8YMxeCoatOQJhWcKGxT2zlCyaWcz8Y+X7Bs1TFVJSwIHIYyFkQufWIRVX9cNJyW1QpEo4rixaEe7JuQagAUctb7ZFYFh5MVJPBe84CVBnB42YsZRgKjFDBVg3cI9WbRwXLktQJX8cNIiFhM1ZuTWk7PIYSBhkVcLzwIiCjCxhCjlAkBqYnqFoQQ2AAAAAElFTkSuQmCC)

qrFinishedCallBackType function () [function that consolelog(ready)]

This function is called if you specify qrCode argument to true in this constructor and will be called when all qrCodes have been replaced (because the qrCode replacing functions are async)

92 Docxgen methods

load(content)

contentType stringThe docx template you want to load as plain text

loadFromFile(path)path

Type stringLoads a docx from a file path

setTags(Tags)

TagsType Object tag_nametag_replacementObject containing for each tag_name the replacement for this tag For example if you want to replace firstName by David your Object will be firstNameDavid

applyTags([Tags])Tags

Type Object tag_nametag_replacementsame as setTagsDefaultthisTags

This function replaces all template variables by their values

output([options])

options object[]

nameTypestring[outputdocx]The name of the file that will be outputed (doesnt work in the browser because of dataUri download)

callbackTypefunctionFunction that is called without arguments when the output is done Is used only in Node (because in the browser the operation is synchronous)

downloadTypeboolean[true]If download is true file will be downloaded automatically with data URIreturns the output file

typeTypestring[base64]The type of zip to return The possible values are (same as in httpstukgithubiojszip generate)base64 (default) the result will be a string the binary in a base64 formstring the result will be a string in binary form 1 byte per charuint8array the result will be a Uint8Array containing the zip This requires a compatible browser

24 Chapter 9 Full Documentation per method

docxtemplater Documentation Release 054

arraybuffer the result will be a ArrayBuffer containing the zip This requires a compatible browserblob the result will be a Blob containing the zip This requires a compatible browsernodebuffer the result will be a nodejs Buffer containing the zip This requires nodejs

This function creates the docx file and downloads it on the userrsquos computer The name of the file is downloaddocx for Chrome and some akward file names for Firefox VEeTHCfSdocxpartdocx and canrsquot be changed because it is handled by the browserFor more informations about how to solve this problem see the Filename Problems section on [httpstukgithubiojszip](httpstukgithubiojszip)

Note All browsers donrsquot support the download of big files with Data URI so you should use the lsquodownloadlsquo method for files bigger than 100kB dataimagepngbase64iVBORw0KGgoAAAANSUhEUgAAABcAAAAXCAIAAABvSEP3AAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAACXSURBVDhPtY7BDYAwDAMZhCf7b8YMxeCoatOQJhWcKGxT2zlCyaWcz8Y+X7Bs1TFVJSwIHIYyFkQufWIRVX9cNJyW1QpEo4rixaEe7JuQagAUctb7ZFYFh5MVJPBe84CVBnB42YsZRgKjFDBVg3cI9WbRwXLktQJX8cNIiFhM1ZuTWk7PIYSBhkVcLzwIiCjCxhCjlAkBqYnqFoQQ2AAAAAElFTkSuQmCC

download(swfpathimgpath[fileName])

swfpathTypestringPath to the swfobjectjs in downloadify

imgpathTypestringPath to the image of the download button

[fileName]TypestringDefaultdefaultdocxName of the file you would like the user to download

This requires to include Downloadifyjs that needs flash version 10 Have a look at the output function if you donrsquot want to depend on it This function has the advantage that it works regardless of the file size

getImageList()

this gets all images that have one of the following extension rsquogifrsquorsquojpegrsquorsquojpgrsquorsquoemfrsquorsquopngrsquoReturn format Array of Object[pathstringfilesZipFile Object]

You shouldrsquont call this method before calling applyTags() because applyTags can modify the images or their path when replacing images with other (particularly when qrCode is set to true which is not the default case) You can call this method after applyTags() without any problems

setImage(pathimgData)

pathTypeStringPath of the image given by getImageList()

imgDataTypeStringimgData in txtplain

This sets the image given by a path and an imgData in txtplainYou shouldrsquont call this method before calling applyTags() because applyTags can modify the images or their path when replacing images with other (particularly when qrCode is set to true which is not the default case) You can call this method after applyTags() without any problems

getFullText([path])

pathTypeStringDefaultworddocumentxmlThis argument determines from which document you want to get the text The main document is called worddocumentxml but they are other documents wordheader1xml wordfooter1xml

returnsTypeStringThe string containing all the text from the document

92 Docxgen methods 25

docxtemplater Documentation Release 054

This method gets only the text of a given document (not the formatting)

getTags()

This function returns the template variables contained in the opened document For example if the content of the documentxml is the following

namefirst_namephone

The function will return[

filenamedocumentxmlvars

nametruefirst_nametruephonetrue

]

If the content contains tagLoops

titlecustomernamephonecustomer

The function will return

[filenamedocumentxmlvars

titletruecustomer

nametruephonetrue

]

26 Chapter 9 Full Documentation per method

CHAPTER 10

Copyright

License

(The MIT license)

Copyright (c) 2013 Edgar Hipp

Permission is hereby granted free of charge to any person obtaining a copy of this software and associated documen-tation files (the ldquoSoftwarerdquo) to deal in the Software without restriction including without limitation the rights to usecopy modify merge publish distribute sublicense andor sell copies of the Software and to permit persons to whomthe Software is furnished to do so subject to the following conditions

The above copyright notice and this permission notice shall be included in all copies or substantial portions of theSoftware

THE SOFTWARE IS PROVIDED ldquoAS ISrdquo WITHOUT WARRANTY OF ANY KIND EXPRESS OR IMPLIEDINCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY FITNESS FOR A PAR-TICULAR PURPOSE AND NONINFRINGEMENT IN NO EVENT SHALL THE AUTHORS OR COPYRIGHTHOLDERS BE LIABLE FOR ANY CLAIM DAMAGES OR OTHER LIABILITY WHETHER IN AN ACTIONOF CONTRACT TORT OR OTHERWISE ARISING FROM OUT OF OR IN CONNECTION WITH THE SOFT-WARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE

27

docxtemplater Documentation Release 054

28 Chapter 10 Copyright

CHAPTER 11

Demos

Including

bull Replace Variables

bull Formating

bull Angular Parsing

bull Loops

bull Loops and tables

bull Lists

bull Replacing images

bull Naming the output

bull Using QrCodes

bull Replacing many images with QrCode

bull Raw Xml Insertion

29

docxtemplater Documentation Release 054

30 Chapter 11 Demos

CHAPTER 12

Indices and tables

bull genindex

bull modindex

bull search

31

docxtemplater Documentation Release 054

32 Chapter 12 Indices and tables

Index

CCommand Line Interface (CLI) 20Configuration 17Copyright 26

FFull_doc 21

GGenerate a Document 13Goals 1

IInstallation 7

Pplatform_support 3

SSyntax 9

33

  • Goals
    • Why you should use a library for this
      • Platform Support
      • Dependencies
      • Installation
        • Node
        • Browser
          • Syntax
            • Synopsis
            • Tag types
            • Loop syntax
            • Dash syntax
            • Inverted Selections
              • Generate a document
                • Loading a document
                • Setting the tags
                • Applying the tags
                • Outputing the document
                  • Configuration
                    • Image Replacing
                    • Angular Parser
                    • Intelligent LoopTagging
                      • Command Line Interface (CLI)
                        • Configjson Syntax
                          • Full Documentation per method
                            • Creating a new Docxgen Object
                            • Docxgen methods
                              • Copyright
                              • Demos
                              • Indices and tables
Page 17: Release 0.5€¦ · Docx is a zipped format that contains some xml. If you want to build a simple replace {tag} If you want to build a simple replace {tag} by value system, it can

docxtemplater Documentation Release 054

14 Chapter 5 Syntax

CHAPTER 6

Generate a document

Herersquos a sample code to generate a document

DocxGen=require(rsquodocxtemplaterrsquo) Only for Node Usagenew DocxGen()loadFromFile(tagExampledocxasynctrue)success(function(doc)

docsetTags(first_nameHipp

last_nameEdgarphone0652455478descriptionNew Website

) set the templateVariablesdocapplyTags() apply them (replace all occurences of first_name by Hipp )docoutput() Output the document using Data-URI

)

The different steps are the following

61 Loading a document

A docx can be loaded by itrsquos base64 representation like this

doc=new DocxGen(base64Dataoptions)

However loading the base64Data is not that easy so I created a wrapper function to load a docx from a file via Ajax

Note The options parameter are explained in Configuration

doc=new DocxGen()loadFromFile(documentPathoptions)

The documentPath is the path to the document you want to load The options are the same as in the constructorfunction and Irsquove added the async parameter

bull If async is true the document is loaded asynchronously and returns a promise (eg you can write suc-cess(callback) to get when the document is loaded)

bull If async is false the document is loaded synchronously and returns the document

62 Setting the tags

The tags are the variables that are going to be replaced by their values To set them just use

15

docxtemplater Documentation Release 054

docsetTags(tags)

63 Applying the tags

Applying the tags means opening all files that contain text (eg footer header main document) and replace thevariables by their values

docapplyTags(tags)

Note If you specify an argument for the applyTags method the function setTags(tags) will be called before applyingthe tags

64 Outputing the document

They are several ways to output the document The most basic usage is to download the document

docoutput(options)

Depending on your environment if you donrsquot set any options this will

bull In the browser Download the document using DataURI

bull In Node Save the document with the given fileName (outputdocx by default)

Herersquos the different options parameters

nameTypestring[outputdocx]The name of the file that will be outputed (doesnt work in the browser because of dataUri download)

callbackTypefunctionFunction that is called without arguments when the output is done Is used only in Node (because in the browser the operation is synchronous)

downloadTypeboolean[true]If download is true file will be downloaded automatically with data URIreturns the output file

typeTypestring[base64]The type of zip to return The possible values are (same as in httpstukgithubiojszip generate)base64 (default) the result will be a string the binary in a base64 formstring the result will be a string in binary form 1 byte per charuint8array the result will be a Uint8Array containing the zip This requires a compatible browserarraybuffer the result will be a ArrayBuffer containing the zip This requires a compatible browserblob the result will be a Blob containing the zip This requires a compatible browsernodebuffer the result will be a nodejs Buffer containing the zip This requires nodejs

This function creates the docx file and downloads it on the userrsquos computer The name of the file is downloaddocxfor Chrome and some akward file names for Firefox VEeTHCfSdocxpartdocx and canrsquot be changed because it ishandled by the browser For more informations about how to solve this problem see the Filename Problems sectionon [httpstukgithubiojszip](httpstukgithubiojszip)

16 Chapter 6 Generate a document

docxtemplater Documentation Release 054

Note Note All browsers donrsquot support the download of big files withData URI so you should use the download method for files bigger than 100kBdataimagepngbase64iVBORw0KGgoAAAANSUhEUgAAABcAAAAXCAIAAABvSEP3AAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAACXSURBVDhPtY7BDYAwDAMZhCf7b8YMxeCoatOQJhWcKGxT2zlCyaWcz8Y+X7Bs1TFVJSwIHIYyFkQufWIRVX9cNJyW1QpEo4rixaEe7JuQagAUctb7ZFYFh5MVJPBe84CVBnB42YsZRgKjFDBVg3cI9WbRwXLktQJX8cNIiFhM1ZuTWk7PIYSBhkVcLzwIiCjCxhCjlAkBqYnqFoQQ2AAAAAElFTkSuQmCC

In Node to send the document to the client you can write the following code snippet

out=docoutput(downloadfalsetypestring)ressend(new Buffer(outbinary))

64 Outputing the document 17

docxtemplater Documentation Release 054

18 Chapter 6 Generate a document

CHAPTER 7

Configuration

Here are documented the special options that you can set when creating a new DocxGen to get some more superpower

It documents the options parameter when you do

new DocxGen(dataoptions)

71 Image Replacing

The name of this option qrCode (boolean)

To stay a templating engine I wanted that DocxTemplater doesnrsquot add an image from scratch but rather uses anexisting image that can be detected and DocxTemplater will just change the contents of that image without changingitrsquos style The size of the replaced images will stay the same

So I decided to use the qrCode format which is a format that lets you identify images by their content

The option for this is qrCode (true for on false for off default off)

Note If you donrsquot use that functionality you should disable it because it is quite slow (the image decoding)

Warning The qrCode functionality only works for PNG They is no support for other file formats yet

72 Angular Parser

The name of this option parser (function)

You can set the angular parser with the following code

With a custom parser you can parse the tags to for example add operators like lsquo+rsquo lsquo-lsquo or whatever the way you wantto parse expressions

To enable this you need to specify a custom parser You need to create a parser function

docxtemplater comes shipped with this parser

parser=function(expression)

return

19

docxtemplater Documentation Release 054

getfunction(scope) return scope[expression]

To use the angular-parser do the following

expressions= require(rsquoangular-expressionsrsquo)angularParser= function(tag)

return getexpressionscompile(tag)

new DocxGen(dataparserangularParser)

Note The require() works in the browser if you include vendorangular-parser-browserjs

73 Intelligent LoopTagging

The name of this option intelligentTagging (boolean)

When looping over an element docxtemplater needs to know over which element you want to loop By default it triesto do that intelligently (by looking what XML Tags are between the tags) However if you want to always use theltwtgt tag by default set this option to false

You can always specify over which element you want to loop with the dash loop syntax

20 Chapter 7 Configuration

CHAPTER 8

Command Line Interface (CLI)

This section is about the commandline interface of docxtemplater

The syntax is the following

docxtemplater configjson

The full configjson should be something like that

configdocxFileinputdocxconfigoutputFileoutputdocxconfigqrcodetrueconfigdebugtruefirst_nameJohnlast_nameSmithage62

81 Configjson Syntax

811 Config properties

These are the properties to configure docxtemplater

configdocxFileinputdocx The input file pathconfigoutputFileoutputdocx The output file pathconfigqrcodetrue whether the images should be scanned to replace them by qrcodes (slows down the cli a lot)configdebugtrue whether to show debug output or not

812 Data properties

To add data to your template just use keys that donrsquot start with ldquoconfigrdquo

first_nameJohnlast_nameSmithage62

21

docxtemplater Documentation Release 054

22 Chapter 8 Command Line Interface (CLI)

CHAPTER 9

Full Documentation per method

91 Creating a new Docxgen Object

new DocxGen()

This function returns a new DocxGen Object

new DocxGen(content[Tagsoptions])

contentType stringThe docx template you want to load as plain text

TagsType Object tag_nametag_replacement []Object containing for each tag_name the replacement for this tag For example if you want to replace firstName by David your Object will be firstNameDavid

options object

parserType functionA custom parser to use See angularjs like parsing

intelligentTaggingType boolean [false]If intelligent Tagging is not set to true when using recursive tags (tag and tag) the system will copy paste what is between the start tag and the endtag this could basically corrupt the files if recursive tags are used inside tablesIf intelligent Tagging is set to true and when using recursive tags inside tables the whole column will be copy pasted

qrCodeType boolean [false]If qrCode is set to true DocxGen will look at all the images to find a Qr-Code If the Qr-code matches to a URL this URL will be loaded by ajax (Be aware that the server you want to access needs to allow your request or it wonrsquot work httpstackoverflowcomquestions9310112why-am-i-seeing-an-origin-is-not-allowed-by-access-control-allow-origin-error )

Important the qrCode functionality only works for PNG I donrsquot think I will enable this for other fileformats in the near future

localImageCreatorType function(argcallback) [function that returns an arrow]The function has to be customized only if you want to use the qrCode options (qrCode=true) When the qrcode text starts with gen the image is not going to be loaded by url but DocxGen calls localImageCreator with arg=full Text decoded The callback needs to be called with the image Datacallback(result) in plaintxt format (if you want to create it from a Data-URI you can use JSZipBase64decode(data) to decode a Data-URI to plaintxt)

The default localImageCreator returns a red arrow no matter what the arguments are

localImageCreator= (argcallback) -gtresult=JSZipBase64decode(iVBORw0KGgoAAAANSUhEUgAAABcAAAAXCAIAAABvSEP3AAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAACXSURBVDhPtY7BDYAwDAMZhCf7b8YMxeCoatOQJhWcKGxT2zlCyaWcz8Y+X7Bs1TFVJSwIHIYyFkQufWIRVX9cNJyW1QpEo4rixaEe7JuQagAUctb7ZFYFh5MVJPBe84CVBnB42YsZRgKjFDBVg3cI9WbRwXLktQJX8cNIiFhM1ZuTWk7PIYSBhkVcLzwIiCjCxhCjlAkBqYnqFoQQ2AAAAAElFTkSuQmCC)

23

docxtemplater Documentation Release 054

[Default Image](dataimagepngbase64iVBORw0KGgoAAAANSUhEUgAAABcAAAAXCAIAAABvSEP3AAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAACXSURBVDhPtY7BDYAwDAMZhCf7b8YMxeCoatOQJhWcKGxT2zlCyaWcz8Y+X7Bs1TFVJSwIHIYyFkQufWIRVX9cNJyW1QpEo4rixaEe7JuQagAUctb7ZFYFh5MVJPBe84CVBnB42YsZRgKjFDBVg3cI9WbRwXLktQJX8cNIiFhM1ZuTWk7PIYSBhkVcLzwIiCjCxhCjlAkBqYnqFoQQ2AAAAAElFTkSuQmCC)

qrFinishedCallBackType function () [function that consolelog(ready)]

This function is called if you specify qrCode argument to true in this constructor and will be called when all qrCodes have been replaced (because the qrCode replacing functions are async)

92 Docxgen methods

load(content)

contentType stringThe docx template you want to load as plain text

loadFromFile(path)path

Type stringLoads a docx from a file path

setTags(Tags)

TagsType Object tag_nametag_replacementObject containing for each tag_name the replacement for this tag For example if you want to replace firstName by David your Object will be firstNameDavid

applyTags([Tags])Tags

Type Object tag_nametag_replacementsame as setTagsDefaultthisTags

This function replaces all template variables by their values

output([options])

options object[]

nameTypestring[outputdocx]The name of the file that will be outputed (doesnt work in the browser because of dataUri download)

callbackTypefunctionFunction that is called without arguments when the output is done Is used only in Node (because in the browser the operation is synchronous)

downloadTypeboolean[true]If download is true file will be downloaded automatically with data URIreturns the output file

typeTypestring[base64]The type of zip to return The possible values are (same as in httpstukgithubiojszip generate)base64 (default) the result will be a string the binary in a base64 formstring the result will be a string in binary form 1 byte per charuint8array the result will be a Uint8Array containing the zip This requires a compatible browser

24 Chapter 9 Full Documentation per method

docxtemplater Documentation Release 054

arraybuffer the result will be a ArrayBuffer containing the zip This requires a compatible browserblob the result will be a Blob containing the zip This requires a compatible browsernodebuffer the result will be a nodejs Buffer containing the zip This requires nodejs

This function creates the docx file and downloads it on the userrsquos computer The name of the file is downloaddocx for Chrome and some akward file names for Firefox VEeTHCfSdocxpartdocx and canrsquot be changed because it is handled by the browserFor more informations about how to solve this problem see the Filename Problems section on [httpstukgithubiojszip](httpstukgithubiojszip)

Note All browsers donrsquot support the download of big files with Data URI so you should use the lsquodownloadlsquo method for files bigger than 100kB dataimagepngbase64iVBORw0KGgoAAAANSUhEUgAAABcAAAAXCAIAAABvSEP3AAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAACXSURBVDhPtY7BDYAwDAMZhCf7b8YMxeCoatOQJhWcKGxT2zlCyaWcz8Y+X7Bs1TFVJSwIHIYyFkQufWIRVX9cNJyW1QpEo4rixaEe7JuQagAUctb7ZFYFh5MVJPBe84CVBnB42YsZRgKjFDBVg3cI9WbRwXLktQJX8cNIiFhM1ZuTWk7PIYSBhkVcLzwIiCjCxhCjlAkBqYnqFoQQ2AAAAAElFTkSuQmCC

download(swfpathimgpath[fileName])

swfpathTypestringPath to the swfobjectjs in downloadify

imgpathTypestringPath to the image of the download button

[fileName]TypestringDefaultdefaultdocxName of the file you would like the user to download

This requires to include Downloadifyjs that needs flash version 10 Have a look at the output function if you donrsquot want to depend on it This function has the advantage that it works regardless of the file size

getImageList()

this gets all images that have one of the following extension rsquogifrsquorsquojpegrsquorsquojpgrsquorsquoemfrsquorsquopngrsquoReturn format Array of Object[pathstringfilesZipFile Object]

You shouldrsquont call this method before calling applyTags() because applyTags can modify the images or their path when replacing images with other (particularly when qrCode is set to true which is not the default case) You can call this method after applyTags() without any problems

setImage(pathimgData)

pathTypeStringPath of the image given by getImageList()

imgDataTypeStringimgData in txtplain

This sets the image given by a path and an imgData in txtplainYou shouldrsquont call this method before calling applyTags() because applyTags can modify the images or their path when replacing images with other (particularly when qrCode is set to true which is not the default case) You can call this method after applyTags() without any problems

getFullText([path])

pathTypeStringDefaultworddocumentxmlThis argument determines from which document you want to get the text The main document is called worddocumentxml but they are other documents wordheader1xml wordfooter1xml

returnsTypeStringThe string containing all the text from the document

92 Docxgen methods 25

docxtemplater Documentation Release 054

This method gets only the text of a given document (not the formatting)

getTags()

This function returns the template variables contained in the opened document For example if the content of the documentxml is the following

namefirst_namephone

The function will return[

filenamedocumentxmlvars

nametruefirst_nametruephonetrue

]

If the content contains tagLoops

titlecustomernamephonecustomer

The function will return

[filenamedocumentxmlvars

titletruecustomer

nametruephonetrue

]

26 Chapter 9 Full Documentation per method

CHAPTER 10

Copyright

License

(The MIT license)

Copyright (c) 2013 Edgar Hipp

Permission is hereby granted free of charge to any person obtaining a copy of this software and associated documen-tation files (the ldquoSoftwarerdquo) to deal in the Software without restriction including without limitation the rights to usecopy modify merge publish distribute sublicense andor sell copies of the Software and to permit persons to whomthe Software is furnished to do so subject to the following conditions

The above copyright notice and this permission notice shall be included in all copies or substantial portions of theSoftware

THE SOFTWARE IS PROVIDED ldquoAS ISrdquo WITHOUT WARRANTY OF ANY KIND EXPRESS OR IMPLIEDINCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY FITNESS FOR A PAR-TICULAR PURPOSE AND NONINFRINGEMENT IN NO EVENT SHALL THE AUTHORS OR COPYRIGHTHOLDERS BE LIABLE FOR ANY CLAIM DAMAGES OR OTHER LIABILITY WHETHER IN AN ACTIONOF CONTRACT TORT OR OTHERWISE ARISING FROM OUT OF OR IN CONNECTION WITH THE SOFT-WARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE

27

docxtemplater Documentation Release 054

28 Chapter 10 Copyright

CHAPTER 11

Demos

Including

bull Replace Variables

bull Formating

bull Angular Parsing

bull Loops

bull Loops and tables

bull Lists

bull Replacing images

bull Naming the output

bull Using QrCodes

bull Replacing many images with QrCode

bull Raw Xml Insertion

29

docxtemplater Documentation Release 054

30 Chapter 11 Demos

CHAPTER 12

Indices and tables

bull genindex

bull modindex

bull search

31

docxtemplater Documentation Release 054

32 Chapter 12 Indices and tables

Index

CCommand Line Interface (CLI) 20Configuration 17Copyright 26

FFull_doc 21

GGenerate a Document 13Goals 1

IInstallation 7

Pplatform_support 3

SSyntax 9

33

  • Goals
    • Why you should use a library for this
      • Platform Support
      • Dependencies
      • Installation
        • Node
        • Browser
          • Syntax
            • Synopsis
            • Tag types
            • Loop syntax
            • Dash syntax
            • Inverted Selections
              • Generate a document
                • Loading a document
                • Setting the tags
                • Applying the tags
                • Outputing the document
                  • Configuration
                    • Image Replacing
                    • Angular Parser
                    • Intelligent LoopTagging
                      • Command Line Interface (CLI)
                        • Configjson Syntax
                          • Full Documentation per method
                            • Creating a new Docxgen Object
                            • Docxgen methods
                              • Copyright
                              • Demos
                              • Indices and tables
Page 18: Release 0.5€¦ · Docx is a zipped format that contains some xml. If you want to build a simple replace {tag} If you want to build a simple replace {tag} by value system, it can

CHAPTER 6

Generate a document

Herersquos a sample code to generate a document

DocxGen=require(rsquodocxtemplaterrsquo) Only for Node Usagenew DocxGen()loadFromFile(tagExampledocxasynctrue)success(function(doc)

docsetTags(first_nameHipp

last_nameEdgarphone0652455478descriptionNew Website

) set the templateVariablesdocapplyTags() apply them (replace all occurences of first_name by Hipp )docoutput() Output the document using Data-URI

)

The different steps are the following

61 Loading a document

A docx can be loaded by itrsquos base64 representation like this

doc=new DocxGen(base64Dataoptions)

However loading the base64Data is not that easy so I created a wrapper function to load a docx from a file via Ajax

Note The options parameter are explained in Configuration

doc=new DocxGen()loadFromFile(documentPathoptions)

The documentPath is the path to the document you want to load The options are the same as in the constructorfunction and Irsquove added the async parameter

bull If async is true the document is loaded asynchronously and returns a promise (eg you can write suc-cess(callback) to get when the document is loaded)

bull If async is false the document is loaded synchronously and returns the document

62 Setting the tags

The tags are the variables that are going to be replaced by their values To set them just use

15

docxtemplater Documentation Release 054

docsetTags(tags)

63 Applying the tags

Applying the tags means opening all files that contain text (eg footer header main document) and replace thevariables by their values

docapplyTags(tags)

Note If you specify an argument for the applyTags method the function setTags(tags) will be called before applyingthe tags

64 Outputing the document

They are several ways to output the document The most basic usage is to download the document

docoutput(options)

Depending on your environment if you donrsquot set any options this will

bull In the browser Download the document using DataURI

bull In Node Save the document with the given fileName (outputdocx by default)

Herersquos the different options parameters

nameTypestring[outputdocx]The name of the file that will be outputed (doesnt work in the browser because of dataUri download)

callbackTypefunctionFunction that is called without arguments when the output is done Is used only in Node (because in the browser the operation is synchronous)

downloadTypeboolean[true]If download is true file will be downloaded automatically with data URIreturns the output file

typeTypestring[base64]The type of zip to return The possible values are (same as in httpstukgithubiojszip generate)base64 (default) the result will be a string the binary in a base64 formstring the result will be a string in binary form 1 byte per charuint8array the result will be a Uint8Array containing the zip This requires a compatible browserarraybuffer the result will be a ArrayBuffer containing the zip This requires a compatible browserblob the result will be a Blob containing the zip This requires a compatible browsernodebuffer the result will be a nodejs Buffer containing the zip This requires nodejs

This function creates the docx file and downloads it on the userrsquos computer The name of the file is downloaddocxfor Chrome and some akward file names for Firefox VEeTHCfSdocxpartdocx and canrsquot be changed because it ishandled by the browser For more informations about how to solve this problem see the Filename Problems sectionon [httpstukgithubiojszip](httpstukgithubiojszip)

16 Chapter 6 Generate a document

docxtemplater Documentation Release 054

Note Note All browsers donrsquot support the download of big files withData URI so you should use the download method for files bigger than 100kBdataimagepngbase64iVBORw0KGgoAAAANSUhEUgAAABcAAAAXCAIAAABvSEP3AAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAACXSURBVDhPtY7BDYAwDAMZhCf7b8YMxeCoatOQJhWcKGxT2zlCyaWcz8Y+X7Bs1TFVJSwIHIYyFkQufWIRVX9cNJyW1QpEo4rixaEe7JuQagAUctb7ZFYFh5MVJPBe84CVBnB42YsZRgKjFDBVg3cI9WbRwXLktQJX8cNIiFhM1ZuTWk7PIYSBhkVcLzwIiCjCxhCjlAkBqYnqFoQQ2AAAAAElFTkSuQmCC

In Node to send the document to the client you can write the following code snippet

out=docoutput(downloadfalsetypestring)ressend(new Buffer(outbinary))

64 Outputing the document 17

docxtemplater Documentation Release 054

18 Chapter 6 Generate a document

CHAPTER 7

Configuration

Here are documented the special options that you can set when creating a new DocxGen to get some more superpower

It documents the options parameter when you do

new DocxGen(dataoptions)

71 Image Replacing

The name of this option qrCode (boolean)

To stay a templating engine I wanted that DocxTemplater doesnrsquot add an image from scratch but rather uses anexisting image that can be detected and DocxTemplater will just change the contents of that image without changingitrsquos style The size of the replaced images will stay the same

So I decided to use the qrCode format which is a format that lets you identify images by their content

The option for this is qrCode (true for on false for off default off)

Note If you donrsquot use that functionality you should disable it because it is quite slow (the image decoding)

Warning The qrCode functionality only works for PNG They is no support for other file formats yet

72 Angular Parser

The name of this option parser (function)

You can set the angular parser with the following code

With a custom parser you can parse the tags to for example add operators like lsquo+rsquo lsquo-lsquo or whatever the way you wantto parse expressions

To enable this you need to specify a custom parser You need to create a parser function

docxtemplater comes shipped with this parser

parser=function(expression)

return

19

docxtemplater Documentation Release 054

getfunction(scope) return scope[expression]

To use the angular-parser do the following

expressions= require(rsquoangular-expressionsrsquo)angularParser= function(tag)

return getexpressionscompile(tag)

new DocxGen(dataparserangularParser)

Note The require() works in the browser if you include vendorangular-parser-browserjs

73 Intelligent LoopTagging

The name of this option intelligentTagging (boolean)

When looping over an element docxtemplater needs to know over which element you want to loop By default it triesto do that intelligently (by looking what XML Tags are between the tags) However if you want to always use theltwtgt tag by default set this option to false

You can always specify over which element you want to loop with the dash loop syntax

20 Chapter 7 Configuration

CHAPTER 8

Command Line Interface (CLI)

This section is about the commandline interface of docxtemplater

The syntax is the following

docxtemplater configjson

The full configjson should be something like that

configdocxFileinputdocxconfigoutputFileoutputdocxconfigqrcodetrueconfigdebugtruefirst_nameJohnlast_nameSmithage62

81 Configjson Syntax

811 Config properties

These are the properties to configure docxtemplater

configdocxFileinputdocx The input file pathconfigoutputFileoutputdocx The output file pathconfigqrcodetrue whether the images should be scanned to replace them by qrcodes (slows down the cli a lot)configdebugtrue whether to show debug output or not

812 Data properties

To add data to your template just use keys that donrsquot start with ldquoconfigrdquo

first_nameJohnlast_nameSmithage62

21

docxtemplater Documentation Release 054

22 Chapter 8 Command Line Interface (CLI)

CHAPTER 9

Full Documentation per method

91 Creating a new Docxgen Object

new DocxGen()

This function returns a new DocxGen Object

new DocxGen(content[Tagsoptions])

contentType stringThe docx template you want to load as plain text

TagsType Object tag_nametag_replacement []Object containing for each tag_name the replacement for this tag For example if you want to replace firstName by David your Object will be firstNameDavid

options object

parserType functionA custom parser to use See angularjs like parsing

intelligentTaggingType boolean [false]If intelligent Tagging is not set to true when using recursive tags (tag and tag) the system will copy paste what is between the start tag and the endtag this could basically corrupt the files if recursive tags are used inside tablesIf intelligent Tagging is set to true and when using recursive tags inside tables the whole column will be copy pasted

qrCodeType boolean [false]If qrCode is set to true DocxGen will look at all the images to find a Qr-Code If the Qr-code matches to a URL this URL will be loaded by ajax (Be aware that the server you want to access needs to allow your request or it wonrsquot work httpstackoverflowcomquestions9310112why-am-i-seeing-an-origin-is-not-allowed-by-access-control-allow-origin-error )

Important the qrCode functionality only works for PNG I donrsquot think I will enable this for other fileformats in the near future

localImageCreatorType function(argcallback) [function that returns an arrow]The function has to be customized only if you want to use the qrCode options (qrCode=true) When the qrcode text starts with gen the image is not going to be loaded by url but DocxGen calls localImageCreator with arg=full Text decoded The callback needs to be called with the image Datacallback(result) in plaintxt format (if you want to create it from a Data-URI you can use JSZipBase64decode(data) to decode a Data-URI to plaintxt)

The default localImageCreator returns a red arrow no matter what the arguments are

localImageCreator= (argcallback) -gtresult=JSZipBase64decode(iVBORw0KGgoAAAANSUhEUgAAABcAAAAXCAIAAABvSEP3AAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAACXSURBVDhPtY7BDYAwDAMZhCf7b8YMxeCoatOQJhWcKGxT2zlCyaWcz8Y+X7Bs1TFVJSwIHIYyFkQufWIRVX9cNJyW1QpEo4rixaEe7JuQagAUctb7ZFYFh5MVJPBe84CVBnB42YsZRgKjFDBVg3cI9WbRwXLktQJX8cNIiFhM1ZuTWk7PIYSBhkVcLzwIiCjCxhCjlAkBqYnqFoQQ2AAAAAElFTkSuQmCC)

23

docxtemplater Documentation Release 054

[Default Image](dataimagepngbase64iVBORw0KGgoAAAANSUhEUgAAABcAAAAXCAIAAABvSEP3AAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAACXSURBVDhPtY7BDYAwDAMZhCf7b8YMxeCoatOQJhWcKGxT2zlCyaWcz8Y+X7Bs1TFVJSwIHIYyFkQufWIRVX9cNJyW1QpEo4rixaEe7JuQagAUctb7ZFYFh5MVJPBe84CVBnB42YsZRgKjFDBVg3cI9WbRwXLktQJX8cNIiFhM1ZuTWk7PIYSBhkVcLzwIiCjCxhCjlAkBqYnqFoQQ2AAAAAElFTkSuQmCC)

qrFinishedCallBackType function () [function that consolelog(ready)]

This function is called if you specify qrCode argument to true in this constructor and will be called when all qrCodes have been replaced (because the qrCode replacing functions are async)

92 Docxgen methods

load(content)

contentType stringThe docx template you want to load as plain text

loadFromFile(path)path

Type stringLoads a docx from a file path

setTags(Tags)

TagsType Object tag_nametag_replacementObject containing for each tag_name the replacement for this tag For example if you want to replace firstName by David your Object will be firstNameDavid

applyTags([Tags])Tags

Type Object tag_nametag_replacementsame as setTagsDefaultthisTags

This function replaces all template variables by their values

output([options])

options object[]

nameTypestring[outputdocx]The name of the file that will be outputed (doesnt work in the browser because of dataUri download)

callbackTypefunctionFunction that is called without arguments when the output is done Is used only in Node (because in the browser the operation is synchronous)

downloadTypeboolean[true]If download is true file will be downloaded automatically with data URIreturns the output file

typeTypestring[base64]The type of zip to return The possible values are (same as in httpstukgithubiojszip generate)base64 (default) the result will be a string the binary in a base64 formstring the result will be a string in binary form 1 byte per charuint8array the result will be a Uint8Array containing the zip This requires a compatible browser

24 Chapter 9 Full Documentation per method

docxtemplater Documentation Release 054

arraybuffer the result will be a ArrayBuffer containing the zip This requires a compatible browserblob the result will be a Blob containing the zip This requires a compatible browsernodebuffer the result will be a nodejs Buffer containing the zip This requires nodejs

This function creates the docx file and downloads it on the userrsquos computer The name of the file is downloaddocx for Chrome and some akward file names for Firefox VEeTHCfSdocxpartdocx and canrsquot be changed because it is handled by the browserFor more informations about how to solve this problem see the Filename Problems section on [httpstukgithubiojszip](httpstukgithubiojszip)

Note All browsers donrsquot support the download of big files with Data URI so you should use the lsquodownloadlsquo method for files bigger than 100kB dataimagepngbase64iVBORw0KGgoAAAANSUhEUgAAABcAAAAXCAIAAABvSEP3AAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAACXSURBVDhPtY7BDYAwDAMZhCf7b8YMxeCoatOQJhWcKGxT2zlCyaWcz8Y+X7Bs1TFVJSwIHIYyFkQufWIRVX9cNJyW1QpEo4rixaEe7JuQagAUctb7ZFYFh5MVJPBe84CVBnB42YsZRgKjFDBVg3cI9WbRwXLktQJX8cNIiFhM1ZuTWk7PIYSBhkVcLzwIiCjCxhCjlAkBqYnqFoQQ2AAAAAElFTkSuQmCC

download(swfpathimgpath[fileName])

swfpathTypestringPath to the swfobjectjs in downloadify

imgpathTypestringPath to the image of the download button

[fileName]TypestringDefaultdefaultdocxName of the file you would like the user to download

This requires to include Downloadifyjs that needs flash version 10 Have a look at the output function if you donrsquot want to depend on it This function has the advantage that it works regardless of the file size

getImageList()

this gets all images that have one of the following extension rsquogifrsquorsquojpegrsquorsquojpgrsquorsquoemfrsquorsquopngrsquoReturn format Array of Object[pathstringfilesZipFile Object]

You shouldrsquont call this method before calling applyTags() because applyTags can modify the images or their path when replacing images with other (particularly when qrCode is set to true which is not the default case) You can call this method after applyTags() without any problems

setImage(pathimgData)

pathTypeStringPath of the image given by getImageList()

imgDataTypeStringimgData in txtplain

This sets the image given by a path and an imgData in txtplainYou shouldrsquont call this method before calling applyTags() because applyTags can modify the images or their path when replacing images with other (particularly when qrCode is set to true which is not the default case) You can call this method after applyTags() without any problems

getFullText([path])

pathTypeStringDefaultworddocumentxmlThis argument determines from which document you want to get the text The main document is called worddocumentxml but they are other documents wordheader1xml wordfooter1xml

returnsTypeStringThe string containing all the text from the document

92 Docxgen methods 25

docxtemplater Documentation Release 054

This method gets only the text of a given document (not the formatting)

getTags()

This function returns the template variables contained in the opened document For example if the content of the documentxml is the following

namefirst_namephone

The function will return[

filenamedocumentxmlvars

nametruefirst_nametruephonetrue

]

If the content contains tagLoops

titlecustomernamephonecustomer

The function will return

[filenamedocumentxmlvars

titletruecustomer

nametruephonetrue

]

26 Chapter 9 Full Documentation per method

CHAPTER 10

Copyright

License

(The MIT license)

Copyright (c) 2013 Edgar Hipp

Permission is hereby granted free of charge to any person obtaining a copy of this software and associated documen-tation files (the ldquoSoftwarerdquo) to deal in the Software without restriction including without limitation the rights to usecopy modify merge publish distribute sublicense andor sell copies of the Software and to permit persons to whomthe Software is furnished to do so subject to the following conditions

The above copyright notice and this permission notice shall be included in all copies or substantial portions of theSoftware

THE SOFTWARE IS PROVIDED ldquoAS ISrdquo WITHOUT WARRANTY OF ANY KIND EXPRESS OR IMPLIEDINCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY FITNESS FOR A PAR-TICULAR PURPOSE AND NONINFRINGEMENT IN NO EVENT SHALL THE AUTHORS OR COPYRIGHTHOLDERS BE LIABLE FOR ANY CLAIM DAMAGES OR OTHER LIABILITY WHETHER IN AN ACTIONOF CONTRACT TORT OR OTHERWISE ARISING FROM OUT OF OR IN CONNECTION WITH THE SOFT-WARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE

27

docxtemplater Documentation Release 054

28 Chapter 10 Copyright

CHAPTER 11

Demos

Including

bull Replace Variables

bull Formating

bull Angular Parsing

bull Loops

bull Loops and tables

bull Lists

bull Replacing images

bull Naming the output

bull Using QrCodes

bull Replacing many images with QrCode

bull Raw Xml Insertion

29

docxtemplater Documentation Release 054

30 Chapter 11 Demos

CHAPTER 12

Indices and tables

bull genindex

bull modindex

bull search

31

docxtemplater Documentation Release 054

32 Chapter 12 Indices and tables

Index

CCommand Line Interface (CLI) 20Configuration 17Copyright 26

FFull_doc 21

GGenerate a Document 13Goals 1

IInstallation 7

Pplatform_support 3

SSyntax 9

33

  • Goals
    • Why you should use a library for this
      • Platform Support
      • Dependencies
      • Installation
        • Node
        • Browser
          • Syntax
            • Synopsis
            • Tag types
            • Loop syntax
            • Dash syntax
            • Inverted Selections
              • Generate a document
                • Loading a document
                • Setting the tags
                • Applying the tags
                • Outputing the document
                  • Configuration
                    • Image Replacing
                    • Angular Parser
                    • Intelligent LoopTagging
                      • Command Line Interface (CLI)
                        • Configjson Syntax
                          • Full Documentation per method
                            • Creating a new Docxgen Object
                            • Docxgen methods
                              • Copyright
                              • Demos
                              • Indices and tables
Page 19: Release 0.5€¦ · Docx is a zipped format that contains some xml. If you want to build a simple replace {tag} If you want to build a simple replace {tag} by value system, it can

docxtemplater Documentation Release 054

docsetTags(tags)

63 Applying the tags

Applying the tags means opening all files that contain text (eg footer header main document) and replace thevariables by their values

docapplyTags(tags)

Note If you specify an argument for the applyTags method the function setTags(tags) will be called before applyingthe tags

64 Outputing the document

They are several ways to output the document The most basic usage is to download the document

docoutput(options)

Depending on your environment if you donrsquot set any options this will

bull In the browser Download the document using DataURI

bull In Node Save the document with the given fileName (outputdocx by default)

Herersquos the different options parameters

nameTypestring[outputdocx]The name of the file that will be outputed (doesnt work in the browser because of dataUri download)

callbackTypefunctionFunction that is called without arguments when the output is done Is used only in Node (because in the browser the operation is synchronous)

downloadTypeboolean[true]If download is true file will be downloaded automatically with data URIreturns the output file

typeTypestring[base64]The type of zip to return The possible values are (same as in httpstukgithubiojszip generate)base64 (default) the result will be a string the binary in a base64 formstring the result will be a string in binary form 1 byte per charuint8array the result will be a Uint8Array containing the zip This requires a compatible browserarraybuffer the result will be a ArrayBuffer containing the zip This requires a compatible browserblob the result will be a Blob containing the zip This requires a compatible browsernodebuffer the result will be a nodejs Buffer containing the zip This requires nodejs

This function creates the docx file and downloads it on the userrsquos computer The name of the file is downloaddocxfor Chrome and some akward file names for Firefox VEeTHCfSdocxpartdocx and canrsquot be changed because it ishandled by the browser For more informations about how to solve this problem see the Filename Problems sectionon [httpstukgithubiojszip](httpstukgithubiojszip)

16 Chapter 6 Generate a document

docxtemplater Documentation Release 054

Note Note All browsers donrsquot support the download of big files withData URI so you should use the download method for files bigger than 100kBdataimagepngbase64iVBORw0KGgoAAAANSUhEUgAAABcAAAAXCAIAAABvSEP3AAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAACXSURBVDhPtY7BDYAwDAMZhCf7b8YMxeCoatOQJhWcKGxT2zlCyaWcz8Y+X7Bs1TFVJSwIHIYyFkQufWIRVX9cNJyW1QpEo4rixaEe7JuQagAUctb7ZFYFh5MVJPBe84CVBnB42YsZRgKjFDBVg3cI9WbRwXLktQJX8cNIiFhM1ZuTWk7PIYSBhkVcLzwIiCjCxhCjlAkBqYnqFoQQ2AAAAAElFTkSuQmCC

In Node to send the document to the client you can write the following code snippet

out=docoutput(downloadfalsetypestring)ressend(new Buffer(outbinary))

64 Outputing the document 17

docxtemplater Documentation Release 054

18 Chapter 6 Generate a document

CHAPTER 7

Configuration

Here are documented the special options that you can set when creating a new DocxGen to get some more superpower

It documents the options parameter when you do

new DocxGen(dataoptions)

71 Image Replacing

The name of this option qrCode (boolean)

To stay a templating engine I wanted that DocxTemplater doesnrsquot add an image from scratch but rather uses anexisting image that can be detected and DocxTemplater will just change the contents of that image without changingitrsquos style The size of the replaced images will stay the same

So I decided to use the qrCode format which is a format that lets you identify images by their content

The option for this is qrCode (true for on false for off default off)

Note If you donrsquot use that functionality you should disable it because it is quite slow (the image decoding)

Warning The qrCode functionality only works for PNG They is no support for other file formats yet

72 Angular Parser

The name of this option parser (function)

You can set the angular parser with the following code

With a custom parser you can parse the tags to for example add operators like lsquo+rsquo lsquo-lsquo or whatever the way you wantto parse expressions

To enable this you need to specify a custom parser You need to create a parser function

docxtemplater comes shipped with this parser

parser=function(expression)

return

19

docxtemplater Documentation Release 054

getfunction(scope) return scope[expression]

To use the angular-parser do the following

expressions= require(rsquoangular-expressionsrsquo)angularParser= function(tag)

return getexpressionscompile(tag)

new DocxGen(dataparserangularParser)

Note The require() works in the browser if you include vendorangular-parser-browserjs

73 Intelligent LoopTagging

The name of this option intelligentTagging (boolean)

When looping over an element docxtemplater needs to know over which element you want to loop By default it triesto do that intelligently (by looking what XML Tags are between the tags) However if you want to always use theltwtgt tag by default set this option to false

You can always specify over which element you want to loop with the dash loop syntax

20 Chapter 7 Configuration

CHAPTER 8

Command Line Interface (CLI)

This section is about the commandline interface of docxtemplater

The syntax is the following

docxtemplater configjson

The full configjson should be something like that

configdocxFileinputdocxconfigoutputFileoutputdocxconfigqrcodetrueconfigdebugtruefirst_nameJohnlast_nameSmithage62

81 Configjson Syntax

811 Config properties

These are the properties to configure docxtemplater

configdocxFileinputdocx The input file pathconfigoutputFileoutputdocx The output file pathconfigqrcodetrue whether the images should be scanned to replace them by qrcodes (slows down the cli a lot)configdebugtrue whether to show debug output or not

812 Data properties

To add data to your template just use keys that donrsquot start with ldquoconfigrdquo

first_nameJohnlast_nameSmithage62

21

docxtemplater Documentation Release 054

22 Chapter 8 Command Line Interface (CLI)

CHAPTER 9

Full Documentation per method

91 Creating a new Docxgen Object

new DocxGen()

This function returns a new DocxGen Object

new DocxGen(content[Tagsoptions])

contentType stringThe docx template you want to load as plain text

TagsType Object tag_nametag_replacement []Object containing for each tag_name the replacement for this tag For example if you want to replace firstName by David your Object will be firstNameDavid

options object

parserType functionA custom parser to use See angularjs like parsing

intelligentTaggingType boolean [false]If intelligent Tagging is not set to true when using recursive tags (tag and tag) the system will copy paste what is between the start tag and the endtag this could basically corrupt the files if recursive tags are used inside tablesIf intelligent Tagging is set to true and when using recursive tags inside tables the whole column will be copy pasted

qrCodeType boolean [false]If qrCode is set to true DocxGen will look at all the images to find a Qr-Code If the Qr-code matches to a URL this URL will be loaded by ajax (Be aware that the server you want to access needs to allow your request or it wonrsquot work httpstackoverflowcomquestions9310112why-am-i-seeing-an-origin-is-not-allowed-by-access-control-allow-origin-error )

Important the qrCode functionality only works for PNG I donrsquot think I will enable this for other fileformats in the near future

localImageCreatorType function(argcallback) [function that returns an arrow]The function has to be customized only if you want to use the qrCode options (qrCode=true) When the qrcode text starts with gen the image is not going to be loaded by url but DocxGen calls localImageCreator with arg=full Text decoded The callback needs to be called with the image Datacallback(result) in plaintxt format (if you want to create it from a Data-URI you can use JSZipBase64decode(data) to decode a Data-URI to plaintxt)

The default localImageCreator returns a red arrow no matter what the arguments are

localImageCreator= (argcallback) -gtresult=JSZipBase64decode(iVBORw0KGgoAAAANSUhEUgAAABcAAAAXCAIAAABvSEP3AAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAACXSURBVDhPtY7BDYAwDAMZhCf7b8YMxeCoatOQJhWcKGxT2zlCyaWcz8Y+X7Bs1TFVJSwIHIYyFkQufWIRVX9cNJyW1QpEo4rixaEe7JuQagAUctb7ZFYFh5MVJPBe84CVBnB42YsZRgKjFDBVg3cI9WbRwXLktQJX8cNIiFhM1ZuTWk7PIYSBhkVcLzwIiCjCxhCjlAkBqYnqFoQQ2AAAAAElFTkSuQmCC)

23

docxtemplater Documentation Release 054

[Default Image](dataimagepngbase64iVBORw0KGgoAAAANSUhEUgAAABcAAAAXCAIAAABvSEP3AAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAACXSURBVDhPtY7BDYAwDAMZhCf7b8YMxeCoatOQJhWcKGxT2zlCyaWcz8Y+X7Bs1TFVJSwIHIYyFkQufWIRVX9cNJyW1QpEo4rixaEe7JuQagAUctb7ZFYFh5MVJPBe84CVBnB42YsZRgKjFDBVg3cI9WbRwXLktQJX8cNIiFhM1ZuTWk7PIYSBhkVcLzwIiCjCxhCjlAkBqYnqFoQQ2AAAAAElFTkSuQmCC)

qrFinishedCallBackType function () [function that consolelog(ready)]

This function is called if you specify qrCode argument to true in this constructor and will be called when all qrCodes have been replaced (because the qrCode replacing functions are async)

92 Docxgen methods

load(content)

contentType stringThe docx template you want to load as plain text

loadFromFile(path)path

Type stringLoads a docx from a file path

setTags(Tags)

TagsType Object tag_nametag_replacementObject containing for each tag_name the replacement for this tag For example if you want to replace firstName by David your Object will be firstNameDavid

applyTags([Tags])Tags

Type Object tag_nametag_replacementsame as setTagsDefaultthisTags

This function replaces all template variables by their values

output([options])

options object[]

nameTypestring[outputdocx]The name of the file that will be outputed (doesnt work in the browser because of dataUri download)

callbackTypefunctionFunction that is called without arguments when the output is done Is used only in Node (because in the browser the operation is synchronous)

downloadTypeboolean[true]If download is true file will be downloaded automatically with data URIreturns the output file

typeTypestring[base64]The type of zip to return The possible values are (same as in httpstukgithubiojszip generate)base64 (default) the result will be a string the binary in a base64 formstring the result will be a string in binary form 1 byte per charuint8array the result will be a Uint8Array containing the zip This requires a compatible browser

24 Chapter 9 Full Documentation per method

docxtemplater Documentation Release 054

arraybuffer the result will be a ArrayBuffer containing the zip This requires a compatible browserblob the result will be a Blob containing the zip This requires a compatible browsernodebuffer the result will be a nodejs Buffer containing the zip This requires nodejs

This function creates the docx file and downloads it on the userrsquos computer The name of the file is downloaddocx for Chrome and some akward file names for Firefox VEeTHCfSdocxpartdocx and canrsquot be changed because it is handled by the browserFor more informations about how to solve this problem see the Filename Problems section on [httpstukgithubiojszip](httpstukgithubiojszip)

Note All browsers donrsquot support the download of big files with Data URI so you should use the lsquodownloadlsquo method for files bigger than 100kB dataimagepngbase64iVBORw0KGgoAAAANSUhEUgAAABcAAAAXCAIAAABvSEP3AAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAACXSURBVDhPtY7BDYAwDAMZhCf7b8YMxeCoatOQJhWcKGxT2zlCyaWcz8Y+X7Bs1TFVJSwIHIYyFkQufWIRVX9cNJyW1QpEo4rixaEe7JuQagAUctb7ZFYFh5MVJPBe84CVBnB42YsZRgKjFDBVg3cI9WbRwXLktQJX8cNIiFhM1ZuTWk7PIYSBhkVcLzwIiCjCxhCjlAkBqYnqFoQQ2AAAAAElFTkSuQmCC

download(swfpathimgpath[fileName])

swfpathTypestringPath to the swfobjectjs in downloadify

imgpathTypestringPath to the image of the download button

[fileName]TypestringDefaultdefaultdocxName of the file you would like the user to download

This requires to include Downloadifyjs that needs flash version 10 Have a look at the output function if you donrsquot want to depend on it This function has the advantage that it works regardless of the file size

getImageList()

this gets all images that have one of the following extension rsquogifrsquorsquojpegrsquorsquojpgrsquorsquoemfrsquorsquopngrsquoReturn format Array of Object[pathstringfilesZipFile Object]

You shouldrsquont call this method before calling applyTags() because applyTags can modify the images or their path when replacing images with other (particularly when qrCode is set to true which is not the default case) You can call this method after applyTags() without any problems

setImage(pathimgData)

pathTypeStringPath of the image given by getImageList()

imgDataTypeStringimgData in txtplain

This sets the image given by a path and an imgData in txtplainYou shouldrsquont call this method before calling applyTags() because applyTags can modify the images or their path when replacing images with other (particularly when qrCode is set to true which is not the default case) You can call this method after applyTags() without any problems

getFullText([path])

pathTypeStringDefaultworddocumentxmlThis argument determines from which document you want to get the text The main document is called worddocumentxml but they are other documents wordheader1xml wordfooter1xml

returnsTypeStringThe string containing all the text from the document

92 Docxgen methods 25

docxtemplater Documentation Release 054

This method gets only the text of a given document (not the formatting)

getTags()

This function returns the template variables contained in the opened document For example if the content of the documentxml is the following

namefirst_namephone

The function will return[

filenamedocumentxmlvars

nametruefirst_nametruephonetrue

]

If the content contains tagLoops

titlecustomernamephonecustomer

The function will return

[filenamedocumentxmlvars

titletruecustomer

nametruephonetrue

]

26 Chapter 9 Full Documentation per method

CHAPTER 10

Copyright

License

(The MIT license)

Copyright (c) 2013 Edgar Hipp

Permission is hereby granted free of charge to any person obtaining a copy of this software and associated documen-tation files (the ldquoSoftwarerdquo) to deal in the Software without restriction including without limitation the rights to usecopy modify merge publish distribute sublicense andor sell copies of the Software and to permit persons to whomthe Software is furnished to do so subject to the following conditions

The above copyright notice and this permission notice shall be included in all copies or substantial portions of theSoftware

THE SOFTWARE IS PROVIDED ldquoAS ISrdquo WITHOUT WARRANTY OF ANY KIND EXPRESS OR IMPLIEDINCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY FITNESS FOR A PAR-TICULAR PURPOSE AND NONINFRINGEMENT IN NO EVENT SHALL THE AUTHORS OR COPYRIGHTHOLDERS BE LIABLE FOR ANY CLAIM DAMAGES OR OTHER LIABILITY WHETHER IN AN ACTIONOF CONTRACT TORT OR OTHERWISE ARISING FROM OUT OF OR IN CONNECTION WITH THE SOFT-WARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE

27

docxtemplater Documentation Release 054

28 Chapter 10 Copyright

CHAPTER 11

Demos

Including

bull Replace Variables

bull Formating

bull Angular Parsing

bull Loops

bull Loops and tables

bull Lists

bull Replacing images

bull Naming the output

bull Using QrCodes

bull Replacing many images with QrCode

bull Raw Xml Insertion

29

docxtemplater Documentation Release 054

30 Chapter 11 Demos

CHAPTER 12

Indices and tables

bull genindex

bull modindex

bull search

31

docxtemplater Documentation Release 054

32 Chapter 12 Indices and tables

Index

CCommand Line Interface (CLI) 20Configuration 17Copyright 26

FFull_doc 21

GGenerate a Document 13Goals 1

IInstallation 7

Pplatform_support 3

SSyntax 9

33

  • Goals
    • Why you should use a library for this
      • Platform Support
      • Dependencies
      • Installation
        • Node
        • Browser
          • Syntax
            • Synopsis
            • Tag types
            • Loop syntax
            • Dash syntax
            • Inverted Selections
              • Generate a document
                • Loading a document
                • Setting the tags
                • Applying the tags
                • Outputing the document
                  • Configuration
                    • Image Replacing
                    • Angular Parser
                    • Intelligent LoopTagging
                      • Command Line Interface (CLI)
                        • Configjson Syntax
                          • Full Documentation per method
                            • Creating a new Docxgen Object
                            • Docxgen methods
                              • Copyright
                              • Demos
                              • Indices and tables
Page 20: Release 0.5€¦ · Docx is a zipped format that contains some xml. If you want to build a simple replace {tag} If you want to build a simple replace {tag} by value system, it can

docxtemplater Documentation Release 054

Note Note All browsers donrsquot support the download of big files withData URI so you should use the download method for files bigger than 100kBdataimagepngbase64iVBORw0KGgoAAAANSUhEUgAAABcAAAAXCAIAAABvSEP3AAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAACXSURBVDhPtY7BDYAwDAMZhCf7b8YMxeCoatOQJhWcKGxT2zlCyaWcz8Y+X7Bs1TFVJSwIHIYyFkQufWIRVX9cNJyW1QpEo4rixaEe7JuQagAUctb7ZFYFh5MVJPBe84CVBnB42YsZRgKjFDBVg3cI9WbRwXLktQJX8cNIiFhM1ZuTWk7PIYSBhkVcLzwIiCjCxhCjlAkBqYnqFoQQ2AAAAAElFTkSuQmCC

In Node to send the document to the client you can write the following code snippet

out=docoutput(downloadfalsetypestring)ressend(new Buffer(outbinary))

64 Outputing the document 17

docxtemplater Documentation Release 054

18 Chapter 6 Generate a document

CHAPTER 7

Configuration

Here are documented the special options that you can set when creating a new DocxGen to get some more superpower

It documents the options parameter when you do

new DocxGen(dataoptions)

71 Image Replacing

The name of this option qrCode (boolean)

To stay a templating engine I wanted that DocxTemplater doesnrsquot add an image from scratch but rather uses anexisting image that can be detected and DocxTemplater will just change the contents of that image without changingitrsquos style The size of the replaced images will stay the same

So I decided to use the qrCode format which is a format that lets you identify images by their content

The option for this is qrCode (true for on false for off default off)

Note If you donrsquot use that functionality you should disable it because it is quite slow (the image decoding)

Warning The qrCode functionality only works for PNG They is no support for other file formats yet

72 Angular Parser

The name of this option parser (function)

You can set the angular parser with the following code

With a custom parser you can parse the tags to for example add operators like lsquo+rsquo lsquo-lsquo or whatever the way you wantto parse expressions

To enable this you need to specify a custom parser You need to create a parser function

docxtemplater comes shipped with this parser

parser=function(expression)

return

19

docxtemplater Documentation Release 054

getfunction(scope) return scope[expression]

To use the angular-parser do the following

expressions= require(rsquoangular-expressionsrsquo)angularParser= function(tag)

return getexpressionscompile(tag)

new DocxGen(dataparserangularParser)

Note The require() works in the browser if you include vendorangular-parser-browserjs

73 Intelligent LoopTagging

The name of this option intelligentTagging (boolean)

When looping over an element docxtemplater needs to know over which element you want to loop By default it triesto do that intelligently (by looking what XML Tags are between the tags) However if you want to always use theltwtgt tag by default set this option to false

You can always specify over which element you want to loop with the dash loop syntax

20 Chapter 7 Configuration

CHAPTER 8

Command Line Interface (CLI)

This section is about the commandline interface of docxtemplater

The syntax is the following

docxtemplater configjson

The full configjson should be something like that

configdocxFileinputdocxconfigoutputFileoutputdocxconfigqrcodetrueconfigdebugtruefirst_nameJohnlast_nameSmithage62

81 Configjson Syntax

811 Config properties

These are the properties to configure docxtemplater

configdocxFileinputdocx The input file pathconfigoutputFileoutputdocx The output file pathconfigqrcodetrue whether the images should be scanned to replace them by qrcodes (slows down the cli a lot)configdebugtrue whether to show debug output or not

812 Data properties

To add data to your template just use keys that donrsquot start with ldquoconfigrdquo

first_nameJohnlast_nameSmithage62

21

docxtemplater Documentation Release 054

22 Chapter 8 Command Line Interface (CLI)

CHAPTER 9

Full Documentation per method

91 Creating a new Docxgen Object

new DocxGen()

This function returns a new DocxGen Object

new DocxGen(content[Tagsoptions])

contentType stringThe docx template you want to load as plain text

TagsType Object tag_nametag_replacement []Object containing for each tag_name the replacement for this tag For example if you want to replace firstName by David your Object will be firstNameDavid

options object

parserType functionA custom parser to use See angularjs like parsing

intelligentTaggingType boolean [false]If intelligent Tagging is not set to true when using recursive tags (tag and tag) the system will copy paste what is between the start tag and the endtag this could basically corrupt the files if recursive tags are used inside tablesIf intelligent Tagging is set to true and when using recursive tags inside tables the whole column will be copy pasted

qrCodeType boolean [false]If qrCode is set to true DocxGen will look at all the images to find a Qr-Code If the Qr-code matches to a URL this URL will be loaded by ajax (Be aware that the server you want to access needs to allow your request or it wonrsquot work httpstackoverflowcomquestions9310112why-am-i-seeing-an-origin-is-not-allowed-by-access-control-allow-origin-error )

Important the qrCode functionality only works for PNG I donrsquot think I will enable this for other fileformats in the near future

localImageCreatorType function(argcallback) [function that returns an arrow]The function has to be customized only if you want to use the qrCode options (qrCode=true) When the qrcode text starts with gen the image is not going to be loaded by url but DocxGen calls localImageCreator with arg=full Text decoded The callback needs to be called with the image Datacallback(result) in plaintxt format (if you want to create it from a Data-URI you can use JSZipBase64decode(data) to decode a Data-URI to plaintxt)

The default localImageCreator returns a red arrow no matter what the arguments are

localImageCreator= (argcallback) -gtresult=JSZipBase64decode(iVBORw0KGgoAAAANSUhEUgAAABcAAAAXCAIAAABvSEP3AAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAACXSURBVDhPtY7BDYAwDAMZhCf7b8YMxeCoatOQJhWcKGxT2zlCyaWcz8Y+X7Bs1TFVJSwIHIYyFkQufWIRVX9cNJyW1QpEo4rixaEe7JuQagAUctb7ZFYFh5MVJPBe84CVBnB42YsZRgKjFDBVg3cI9WbRwXLktQJX8cNIiFhM1ZuTWk7PIYSBhkVcLzwIiCjCxhCjlAkBqYnqFoQQ2AAAAAElFTkSuQmCC)

23

docxtemplater Documentation Release 054

[Default Image](dataimagepngbase64iVBORw0KGgoAAAANSUhEUgAAABcAAAAXCAIAAABvSEP3AAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAACXSURBVDhPtY7BDYAwDAMZhCf7b8YMxeCoatOQJhWcKGxT2zlCyaWcz8Y+X7Bs1TFVJSwIHIYyFkQufWIRVX9cNJyW1QpEo4rixaEe7JuQagAUctb7ZFYFh5MVJPBe84CVBnB42YsZRgKjFDBVg3cI9WbRwXLktQJX8cNIiFhM1ZuTWk7PIYSBhkVcLzwIiCjCxhCjlAkBqYnqFoQQ2AAAAAElFTkSuQmCC)

qrFinishedCallBackType function () [function that consolelog(ready)]

This function is called if you specify qrCode argument to true in this constructor and will be called when all qrCodes have been replaced (because the qrCode replacing functions are async)

92 Docxgen methods

load(content)

contentType stringThe docx template you want to load as plain text

loadFromFile(path)path

Type stringLoads a docx from a file path

setTags(Tags)

TagsType Object tag_nametag_replacementObject containing for each tag_name the replacement for this tag For example if you want to replace firstName by David your Object will be firstNameDavid

applyTags([Tags])Tags

Type Object tag_nametag_replacementsame as setTagsDefaultthisTags

This function replaces all template variables by their values

output([options])

options object[]

nameTypestring[outputdocx]The name of the file that will be outputed (doesnt work in the browser because of dataUri download)

callbackTypefunctionFunction that is called without arguments when the output is done Is used only in Node (because in the browser the operation is synchronous)

downloadTypeboolean[true]If download is true file will be downloaded automatically with data URIreturns the output file

typeTypestring[base64]The type of zip to return The possible values are (same as in httpstukgithubiojszip generate)base64 (default) the result will be a string the binary in a base64 formstring the result will be a string in binary form 1 byte per charuint8array the result will be a Uint8Array containing the zip This requires a compatible browser

24 Chapter 9 Full Documentation per method

docxtemplater Documentation Release 054

arraybuffer the result will be a ArrayBuffer containing the zip This requires a compatible browserblob the result will be a Blob containing the zip This requires a compatible browsernodebuffer the result will be a nodejs Buffer containing the zip This requires nodejs

This function creates the docx file and downloads it on the userrsquos computer The name of the file is downloaddocx for Chrome and some akward file names for Firefox VEeTHCfSdocxpartdocx and canrsquot be changed because it is handled by the browserFor more informations about how to solve this problem see the Filename Problems section on [httpstukgithubiojszip](httpstukgithubiojszip)

Note All browsers donrsquot support the download of big files with Data URI so you should use the lsquodownloadlsquo method for files bigger than 100kB dataimagepngbase64iVBORw0KGgoAAAANSUhEUgAAABcAAAAXCAIAAABvSEP3AAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAACXSURBVDhPtY7BDYAwDAMZhCf7b8YMxeCoatOQJhWcKGxT2zlCyaWcz8Y+X7Bs1TFVJSwIHIYyFkQufWIRVX9cNJyW1QpEo4rixaEe7JuQagAUctb7ZFYFh5MVJPBe84CVBnB42YsZRgKjFDBVg3cI9WbRwXLktQJX8cNIiFhM1ZuTWk7PIYSBhkVcLzwIiCjCxhCjlAkBqYnqFoQQ2AAAAAElFTkSuQmCC

download(swfpathimgpath[fileName])

swfpathTypestringPath to the swfobjectjs in downloadify

imgpathTypestringPath to the image of the download button

[fileName]TypestringDefaultdefaultdocxName of the file you would like the user to download

This requires to include Downloadifyjs that needs flash version 10 Have a look at the output function if you donrsquot want to depend on it This function has the advantage that it works regardless of the file size

getImageList()

this gets all images that have one of the following extension rsquogifrsquorsquojpegrsquorsquojpgrsquorsquoemfrsquorsquopngrsquoReturn format Array of Object[pathstringfilesZipFile Object]

You shouldrsquont call this method before calling applyTags() because applyTags can modify the images or their path when replacing images with other (particularly when qrCode is set to true which is not the default case) You can call this method after applyTags() without any problems

setImage(pathimgData)

pathTypeStringPath of the image given by getImageList()

imgDataTypeStringimgData in txtplain

This sets the image given by a path and an imgData in txtplainYou shouldrsquont call this method before calling applyTags() because applyTags can modify the images or their path when replacing images with other (particularly when qrCode is set to true which is not the default case) You can call this method after applyTags() without any problems

getFullText([path])

pathTypeStringDefaultworddocumentxmlThis argument determines from which document you want to get the text The main document is called worddocumentxml but they are other documents wordheader1xml wordfooter1xml

returnsTypeStringThe string containing all the text from the document

92 Docxgen methods 25

docxtemplater Documentation Release 054

This method gets only the text of a given document (not the formatting)

getTags()

This function returns the template variables contained in the opened document For example if the content of the documentxml is the following

namefirst_namephone

The function will return[

filenamedocumentxmlvars

nametruefirst_nametruephonetrue

]

If the content contains tagLoops

titlecustomernamephonecustomer

The function will return

[filenamedocumentxmlvars

titletruecustomer

nametruephonetrue

]

26 Chapter 9 Full Documentation per method

CHAPTER 10

Copyright

License

(The MIT license)

Copyright (c) 2013 Edgar Hipp

Permission is hereby granted free of charge to any person obtaining a copy of this software and associated documen-tation files (the ldquoSoftwarerdquo) to deal in the Software without restriction including without limitation the rights to usecopy modify merge publish distribute sublicense andor sell copies of the Software and to permit persons to whomthe Software is furnished to do so subject to the following conditions

The above copyright notice and this permission notice shall be included in all copies or substantial portions of theSoftware

THE SOFTWARE IS PROVIDED ldquoAS ISrdquo WITHOUT WARRANTY OF ANY KIND EXPRESS OR IMPLIEDINCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY FITNESS FOR A PAR-TICULAR PURPOSE AND NONINFRINGEMENT IN NO EVENT SHALL THE AUTHORS OR COPYRIGHTHOLDERS BE LIABLE FOR ANY CLAIM DAMAGES OR OTHER LIABILITY WHETHER IN AN ACTIONOF CONTRACT TORT OR OTHERWISE ARISING FROM OUT OF OR IN CONNECTION WITH THE SOFT-WARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE

27

docxtemplater Documentation Release 054

28 Chapter 10 Copyright

CHAPTER 11

Demos

Including

bull Replace Variables

bull Formating

bull Angular Parsing

bull Loops

bull Loops and tables

bull Lists

bull Replacing images

bull Naming the output

bull Using QrCodes

bull Replacing many images with QrCode

bull Raw Xml Insertion

29

docxtemplater Documentation Release 054

30 Chapter 11 Demos

CHAPTER 12

Indices and tables

bull genindex

bull modindex

bull search

31

docxtemplater Documentation Release 054

32 Chapter 12 Indices and tables

Index

CCommand Line Interface (CLI) 20Configuration 17Copyright 26

FFull_doc 21

GGenerate a Document 13Goals 1

IInstallation 7

Pplatform_support 3

SSyntax 9

33

  • Goals
    • Why you should use a library for this
      • Platform Support
      • Dependencies
      • Installation
        • Node
        • Browser
          • Syntax
            • Synopsis
            • Tag types
            • Loop syntax
            • Dash syntax
            • Inverted Selections
              • Generate a document
                • Loading a document
                • Setting the tags
                • Applying the tags
                • Outputing the document
                  • Configuration
                    • Image Replacing
                    • Angular Parser
                    • Intelligent LoopTagging
                      • Command Line Interface (CLI)
                        • Configjson Syntax
                          • Full Documentation per method
                            • Creating a new Docxgen Object
                            • Docxgen methods
                              • Copyright
                              • Demos
                              • Indices and tables
Page 21: Release 0.5€¦ · Docx is a zipped format that contains some xml. If you want to build a simple replace {tag} If you want to build a simple replace {tag} by value system, it can

docxtemplater Documentation Release 054

18 Chapter 6 Generate a document

CHAPTER 7

Configuration

Here are documented the special options that you can set when creating a new DocxGen to get some more superpower

It documents the options parameter when you do

new DocxGen(dataoptions)

71 Image Replacing

The name of this option qrCode (boolean)

To stay a templating engine I wanted that DocxTemplater doesnrsquot add an image from scratch but rather uses anexisting image that can be detected and DocxTemplater will just change the contents of that image without changingitrsquos style The size of the replaced images will stay the same

So I decided to use the qrCode format which is a format that lets you identify images by their content

The option for this is qrCode (true for on false for off default off)

Note If you donrsquot use that functionality you should disable it because it is quite slow (the image decoding)

Warning The qrCode functionality only works for PNG They is no support for other file formats yet

72 Angular Parser

The name of this option parser (function)

You can set the angular parser with the following code

With a custom parser you can parse the tags to for example add operators like lsquo+rsquo lsquo-lsquo or whatever the way you wantto parse expressions

To enable this you need to specify a custom parser You need to create a parser function

docxtemplater comes shipped with this parser

parser=function(expression)

return

19

docxtemplater Documentation Release 054

getfunction(scope) return scope[expression]

To use the angular-parser do the following

expressions= require(rsquoangular-expressionsrsquo)angularParser= function(tag)

return getexpressionscompile(tag)

new DocxGen(dataparserangularParser)

Note The require() works in the browser if you include vendorangular-parser-browserjs

73 Intelligent LoopTagging

The name of this option intelligentTagging (boolean)

When looping over an element docxtemplater needs to know over which element you want to loop By default it triesto do that intelligently (by looking what XML Tags are between the tags) However if you want to always use theltwtgt tag by default set this option to false

You can always specify over which element you want to loop with the dash loop syntax

20 Chapter 7 Configuration

CHAPTER 8

Command Line Interface (CLI)

This section is about the commandline interface of docxtemplater

The syntax is the following

docxtemplater configjson

The full configjson should be something like that

configdocxFileinputdocxconfigoutputFileoutputdocxconfigqrcodetrueconfigdebugtruefirst_nameJohnlast_nameSmithage62

81 Configjson Syntax

811 Config properties

These are the properties to configure docxtemplater

configdocxFileinputdocx The input file pathconfigoutputFileoutputdocx The output file pathconfigqrcodetrue whether the images should be scanned to replace them by qrcodes (slows down the cli a lot)configdebugtrue whether to show debug output or not

812 Data properties

To add data to your template just use keys that donrsquot start with ldquoconfigrdquo

first_nameJohnlast_nameSmithage62

21

docxtemplater Documentation Release 054

22 Chapter 8 Command Line Interface (CLI)

CHAPTER 9

Full Documentation per method

91 Creating a new Docxgen Object

new DocxGen()

This function returns a new DocxGen Object

new DocxGen(content[Tagsoptions])

contentType stringThe docx template you want to load as plain text

TagsType Object tag_nametag_replacement []Object containing for each tag_name the replacement for this tag For example if you want to replace firstName by David your Object will be firstNameDavid

options object

parserType functionA custom parser to use See angularjs like parsing

intelligentTaggingType boolean [false]If intelligent Tagging is not set to true when using recursive tags (tag and tag) the system will copy paste what is between the start tag and the endtag this could basically corrupt the files if recursive tags are used inside tablesIf intelligent Tagging is set to true and when using recursive tags inside tables the whole column will be copy pasted

qrCodeType boolean [false]If qrCode is set to true DocxGen will look at all the images to find a Qr-Code If the Qr-code matches to a URL this URL will be loaded by ajax (Be aware that the server you want to access needs to allow your request or it wonrsquot work httpstackoverflowcomquestions9310112why-am-i-seeing-an-origin-is-not-allowed-by-access-control-allow-origin-error )

Important the qrCode functionality only works for PNG I donrsquot think I will enable this for other fileformats in the near future

localImageCreatorType function(argcallback) [function that returns an arrow]The function has to be customized only if you want to use the qrCode options (qrCode=true) When the qrcode text starts with gen the image is not going to be loaded by url but DocxGen calls localImageCreator with arg=full Text decoded The callback needs to be called with the image Datacallback(result) in plaintxt format (if you want to create it from a Data-URI you can use JSZipBase64decode(data) to decode a Data-URI to plaintxt)

The default localImageCreator returns a red arrow no matter what the arguments are

localImageCreator= (argcallback) -gtresult=JSZipBase64decode(iVBORw0KGgoAAAANSUhEUgAAABcAAAAXCAIAAABvSEP3AAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAACXSURBVDhPtY7BDYAwDAMZhCf7b8YMxeCoatOQJhWcKGxT2zlCyaWcz8Y+X7Bs1TFVJSwIHIYyFkQufWIRVX9cNJyW1QpEo4rixaEe7JuQagAUctb7ZFYFh5MVJPBe84CVBnB42YsZRgKjFDBVg3cI9WbRwXLktQJX8cNIiFhM1ZuTWk7PIYSBhkVcLzwIiCjCxhCjlAkBqYnqFoQQ2AAAAAElFTkSuQmCC)

23

docxtemplater Documentation Release 054

[Default Image](dataimagepngbase64iVBORw0KGgoAAAANSUhEUgAAABcAAAAXCAIAAABvSEP3AAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAACXSURBVDhPtY7BDYAwDAMZhCf7b8YMxeCoatOQJhWcKGxT2zlCyaWcz8Y+X7Bs1TFVJSwIHIYyFkQufWIRVX9cNJyW1QpEo4rixaEe7JuQagAUctb7ZFYFh5MVJPBe84CVBnB42YsZRgKjFDBVg3cI9WbRwXLktQJX8cNIiFhM1ZuTWk7PIYSBhkVcLzwIiCjCxhCjlAkBqYnqFoQQ2AAAAAElFTkSuQmCC)

qrFinishedCallBackType function () [function that consolelog(ready)]

This function is called if you specify qrCode argument to true in this constructor and will be called when all qrCodes have been replaced (because the qrCode replacing functions are async)

92 Docxgen methods

load(content)

contentType stringThe docx template you want to load as plain text

loadFromFile(path)path

Type stringLoads a docx from a file path

setTags(Tags)

TagsType Object tag_nametag_replacementObject containing for each tag_name the replacement for this tag For example if you want to replace firstName by David your Object will be firstNameDavid

applyTags([Tags])Tags

Type Object tag_nametag_replacementsame as setTagsDefaultthisTags

This function replaces all template variables by their values

output([options])

options object[]

nameTypestring[outputdocx]The name of the file that will be outputed (doesnt work in the browser because of dataUri download)

callbackTypefunctionFunction that is called without arguments when the output is done Is used only in Node (because in the browser the operation is synchronous)

downloadTypeboolean[true]If download is true file will be downloaded automatically with data URIreturns the output file

typeTypestring[base64]The type of zip to return The possible values are (same as in httpstukgithubiojszip generate)base64 (default) the result will be a string the binary in a base64 formstring the result will be a string in binary form 1 byte per charuint8array the result will be a Uint8Array containing the zip This requires a compatible browser

24 Chapter 9 Full Documentation per method

docxtemplater Documentation Release 054

arraybuffer the result will be a ArrayBuffer containing the zip This requires a compatible browserblob the result will be a Blob containing the zip This requires a compatible browsernodebuffer the result will be a nodejs Buffer containing the zip This requires nodejs

This function creates the docx file and downloads it on the userrsquos computer The name of the file is downloaddocx for Chrome and some akward file names for Firefox VEeTHCfSdocxpartdocx and canrsquot be changed because it is handled by the browserFor more informations about how to solve this problem see the Filename Problems section on [httpstukgithubiojszip](httpstukgithubiojszip)

Note All browsers donrsquot support the download of big files with Data URI so you should use the lsquodownloadlsquo method for files bigger than 100kB dataimagepngbase64iVBORw0KGgoAAAANSUhEUgAAABcAAAAXCAIAAABvSEP3AAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAACXSURBVDhPtY7BDYAwDAMZhCf7b8YMxeCoatOQJhWcKGxT2zlCyaWcz8Y+X7Bs1TFVJSwIHIYyFkQufWIRVX9cNJyW1QpEo4rixaEe7JuQagAUctb7ZFYFh5MVJPBe84CVBnB42YsZRgKjFDBVg3cI9WbRwXLktQJX8cNIiFhM1ZuTWk7PIYSBhkVcLzwIiCjCxhCjlAkBqYnqFoQQ2AAAAAElFTkSuQmCC

download(swfpathimgpath[fileName])

swfpathTypestringPath to the swfobjectjs in downloadify

imgpathTypestringPath to the image of the download button

[fileName]TypestringDefaultdefaultdocxName of the file you would like the user to download

This requires to include Downloadifyjs that needs flash version 10 Have a look at the output function if you donrsquot want to depend on it This function has the advantage that it works regardless of the file size

getImageList()

this gets all images that have one of the following extension rsquogifrsquorsquojpegrsquorsquojpgrsquorsquoemfrsquorsquopngrsquoReturn format Array of Object[pathstringfilesZipFile Object]

You shouldrsquont call this method before calling applyTags() because applyTags can modify the images or their path when replacing images with other (particularly when qrCode is set to true which is not the default case) You can call this method after applyTags() without any problems

setImage(pathimgData)

pathTypeStringPath of the image given by getImageList()

imgDataTypeStringimgData in txtplain

This sets the image given by a path and an imgData in txtplainYou shouldrsquont call this method before calling applyTags() because applyTags can modify the images or their path when replacing images with other (particularly when qrCode is set to true which is not the default case) You can call this method after applyTags() without any problems

getFullText([path])

pathTypeStringDefaultworddocumentxmlThis argument determines from which document you want to get the text The main document is called worddocumentxml but they are other documents wordheader1xml wordfooter1xml

returnsTypeStringThe string containing all the text from the document

92 Docxgen methods 25

docxtemplater Documentation Release 054

This method gets only the text of a given document (not the formatting)

getTags()

This function returns the template variables contained in the opened document For example if the content of the documentxml is the following

namefirst_namephone

The function will return[

filenamedocumentxmlvars

nametruefirst_nametruephonetrue

]

If the content contains tagLoops

titlecustomernamephonecustomer

The function will return

[filenamedocumentxmlvars

titletruecustomer

nametruephonetrue

]

26 Chapter 9 Full Documentation per method

CHAPTER 10

Copyright

License

(The MIT license)

Copyright (c) 2013 Edgar Hipp

Permission is hereby granted free of charge to any person obtaining a copy of this software and associated documen-tation files (the ldquoSoftwarerdquo) to deal in the Software without restriction including without limitation the rights to usecopy modify merge publish distribute sublicense andor sell copies of the Software and to permit persons to whomthe Software is furnished to do so subject to the following conditions

The above copyright notice and this permission notice shall be included in all copies or substantial portions of theSoftware

THE SOFTWARE IS PROVIDED ldquoAS ISrdquo WITHOUT WARRANTY OF ANY KIND EXPRESS OR IMPLIEDINCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY FITNESS FOR A PAR-TICULAR PURPOSE AND NONINFRINGEMENT IN NO EVENT SHALL THE AUTHORS OR COPYRIGHTHOLDERS BE LIABLE FOR ANY CLAIM DAMAGES OR OTHER LIABILITY WHETHER IN AN ACTIONOF CONTRACT TORT OR OTHERWISE ARISING FROM OUT OF OR IN CONNECTION WITH THE SOFT-WARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE

27

docxtemplater Documentation Release 054

28 Chapter 10 Copyright

CHAPTER 11

Demos

Including

bull Replace Variables

bull Formating

bull Angular Parsing

bull Loops

bull Loops and tables

bull Lists

bull Replacing images

bull Naming the output

bull Using QrCodes

bull Replacing many images with QrCode

bull Raw Xml Insertion

29

docxtemplater Documentation Release 054

30 Chapter 11 Demos

CHAPTER 12

Indices and tables

bull genindex

bull modindex

bull search

31

docxtemplater Documentation Release 054

32 Chapter 12 Indices and tables

Index

CCommand Line Interface (CLI) 20Configuration 17Copyright 26

FFull_doc 21

GGenerate a Document 13Goals 1

IInstallation 7

Pplatform_support 3

SSyntax 9

33

  • Goals
    • Why you should use a library for this
      • Platform Support
      • Dependencies
      • Installation
        • Node
        • Browser
          • Syntax
            • Synopsis
            • Tag types
            • Loop syntax
            • Dash syntax
            • Inverted Selections
              • Generate a document
                • Loading a document
                • Setting the tags
                • Applying the tags
                • Outputing the document
                  • Configuration
                    • Image Replacing
                    • Angular Parser
                    • Intelligent LoopTagging
                      • Command Line Interface (CLI)
                        • Configjson Syntax
                          • Full Documentation per method
                            • Creating a new Docxgen Object
                            • Docxgen methods
                              • Copyright
                              • Demos
                              • Indices and tables
Page 22: Release 0.5€¦ · Docx is a zipped format that contains some xml. If you want to build a simple replace {tag} If you want to build a simple replace {tag} by value system, it can

CHAPTER 7

Configuration

Here are documented the special options that you can set when creating a new DocxGen to get some more superpower

It documents the options parameter when you do

new DocxGen(dataoptions)

71 Image Replacing

The name of this option qrCode (boolean)

To stay a templating engine I wanted that DocxTemplater doesnrsquot add an image from scratch but rather uses anexisting image that can be detected and DocxTemplater will just change the contents of that image without changingitrsquos style The size of the replaced images will stay the same

So I decided to use the qrCode format which is a format that lets you identify images by their content

The option for this is qrCode (true for on false for off default off)

Note If you donrsquot use that functionality you should disable it because it is quite slow (the image decoding)

Warning The qrCode functionality only works for PNG They is no support for other file formats yet

72 Angular Parser

The name of this option parser (function)

You can set the angular parser with the following code

With a custom parser you can parse the tags to for example add operators like lsquo+rsquo lsquo-lsquo or whatever the way you wantto parse expressions

To enable this you need to specify a custom parser You need to create a parser function

docxtemplater comes shipped with this parser

parser=function(expression)

return

19

docxtemplater Documentation Release 054

getfunction(scope) return scope[expression]

To use the angular-parser do the following

expressions= require(rsquoangular-expressionsrsquo)angularParser= function(tag)

return getexpressionscompile(tag)

new DocxGen(dataparserangularParser)

Note The require() works in the browser if you include vendorangular-parser-browserjs

73 Intelligent LoopTagging

The name of this option intelligentTagging (boolean)

When looping over an element docxtemplater needs to know over which element you want to loop By default it triesto do that intelligently (by looking what XML Tags are between the tags) However if you want to always use theltwtgt tag by default set this option to false

You can always specify over which element you want to loop with the dash loop syntax

20 Chapter 7 Configuration

CHAPTER 8

Command Line Interface (CLI)

This section is about the commandline interface of docxtemplater

The syntax is the following

docxtemplater configjson

The full configjson should be something like that

configdocxFileinputdocxconfigoutputFileoutputdocxconfigqrcodetrueconfigdebugtruefirst_nameJohnlast_nameSmithage62

81 Configjson Syntax

811 Config properties

These are the properties to configure docxtemplater

configdocxFileinputdocx The input file pathconfigoutputFileoutputdocx The output file pathconfigqrcodetrue whether the images should be scanned to replace them by qrcodes (slows down the cli a lot)configdebugtrue whether to show debug output or not

812 Data properties

To add data to your template just use keys that donrsquot start with ldquoconfigrdquo

first_nameJohnlast_nameSmithage62

21

docxtemplater Documentation Release 054

22 Chapter 8 Command Line Interface (CLI)

CHAPTER 9

Full Documentation per method

91 Creating a new Docxgen Object

new DocxGen()

This function returns a new DocxGen Object

new DocxGen(content[Tagsoptions])

contentType stringThe docx template you want to load as plain text

TagsType Object tag_nametag_replacement []Object containing for each tag_name the replacement for this tag For example if you want to replace firstName by David your Object will be firstNameDavid

options object

parserType functionA custom parser to use See angularjs like parsing

intelligentTaggingType boolean [false]If intelligent Tagging is not set to true when using recursive tags (tag and tag) the system will copy paste what is between the start tag and the endtag this could basically corrupt the files if recursive tags are used inside tablesIf intelligent Tagging is set to true and when using recursive tags inside tables the whole column will be copy pasted

qrCodeType boolean [false]If qrCode is set to true DocxGen will look at all the images to find a Qr-Code If the Qr-code matches to a URL this URL will be loaded by ajax (Be aware that the server you want to access needs to allow your request or it wonrsquot work httpstackoverflowcomquestions9310112why-am-i-seeing-an-origin-is-not-allowed-by-access-control-allow-origin-error )

Important the qrCode functionality only works for PNG I donrsquot think I will enable this for other fileformats in the near future

localImageCreatorType function(argcallback) [function that returns an arrow]The function has to be customized only if you want to use the qrCode options (qrCode=true) When the qrcode text starts with gen the image is not going to be loaded by url but DocxGen calls localImageCreator with arg=full Text decoded The callback needs to be called with the image Datacallback(result) in plaintxt format (if you want to create it from a Data-URI you can use JSZipBase64decode(data) to decode a Data-URI to plaintxt)

The default localImageCreator returns a red arrow no matter what the arguments are

localImageCreator= (argcallback) -gtresult=JSZipBase64decode(iVBORw0KGgoAAAANSUhEUgAAABcAAAAXCAIAAABvSEP3AAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAACXSURBVDhPtY7BDYAwDAMZhCf7b8YMxeCoatOQJhWcKGxT2zlCyaWcz8Y+X7Bs1TFVJSwIHIYyFkQufWIRVX9cNJyW1QpEo4rixaEe7JuQagAUctb7ZFYFh5MVJPBe84CVBnB42YsZRgKjFDBVg3cI9WbRwXLktQJX8cNIiFhM1ZuTWk7PIYSBhkVcLzwIiCjCxhCjlAkBqYnqFoQQ2AAAAAElFTkSuQmCC)

23

docxtemplater Documentation Release 054

[Default Image](dataimagepngbase64iVBORw0KGgoAAAANSUhEUgAAABcAAAAXCAIAAABvSEP3AAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAACXSURBVDhPtY7BDYAwDAMZhCf7b8YMxeCoatOQJhWcKGxT2zlCyaWcz8Y+X7Bs1TFVJSwIHIYyFkQufWIRVX9cNJyW1QpEo4rixaEe7JuQagAUctb7ZFYFh5MVJPBe84CVBnB42YsZRgKjFDBVg3cI9WbRwXLktQJX8cNIiFhM1ZuTWk7PIYSBhkVcLzwIiCjCxhCjlAkBqYnqFoQQ2AAAAAElFTkSuQmCC)

qrFinishedCallBackType function () [function that consolelog(ready)]

This function is called if you specify qrCode argument to true in this constructor and will be called when all qrCodes have been replaced (because the qrCode replacing functions are async)

92 Docxgen methods

load(content)

contentType stringThe docx template you want to load as plain text

loadFromFile(path)path

Type stringLoads a docx from a file path

setTags(Tags)

TagsType Object tag_nametag_replacementObject containing for each tag_name the replacement for this tag For example if you want to replace firstName by David your Object will be firstNameDavid

applyTags([Tags])Tags

Type Object tag_nametag_replacementsame as setTagsDefaultthisTags

This function replaces all template variables by their values

output([options])

options object[]

nameTypestring[outputdocx]The name of the file that will be outputed (doesnt work in the browser because of dataUri download)

callbackTypefunctionFunction that is called without arguments when the output is done Is used only in Node (because in the browser the operation is synchronous)

downloadTypeboolean[true]If download is true file will be downloaded automatically with data URIreturns the output file

typeTypestring[base64]The type of zip to return The possible values are (same as in httpstukgithubiojszip generate)base64 (default) the result will be a string the binary in a base64 formstring the result will be a string in binary form 1 byte per charuint8array the result will be a Uint8Array containing the zip This requires a compatible browser

24 Chapter 9 Full Documentation per method

docxtemplater Documentation Release 054

arraybuffer the result will be a ArrayBuffer containing the zip This requires a compatible browserblob the result will be a Blob containing the zip This requires a compatible browsernodebuffer the result will be a nodejs Buffer containing the zip This requires nodejs

This function creates the docx file and downloads it on the userrsquos computer The name of the file is downloaddocx for Chrome and some akward file names for Firefox VEeTHCfSdocxpartdocx and canrsquot be changed because it is handled by the browserFor more informations about how to solve this problem see the Filename Problems section on [httpstukgithubiojszip](httpstukgithubiojszip)

Note All browsers donrsquot support the download of big files with Data URI so you should use the lsquodownloadlsquo method for files bigger than 100kB dataimagepngbase64iVBORw0KGgoAAAANSUhEUgAAABcAAAAXCAIAAABvSEP3AAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAACXSURBVDhPtY7BDYAwDAMZhCf7b8YMxeCoatOQJhWcKGxT2zlCyaWcz8Y+X7Bs1TFVJSwIHIYyFkQufWIRVX9cNJyW1QpEo4rixaEe7JuQagAUctb7ZFYFh5MVJPBe84CVBnB42YsZRgKjFDBVg3cI9WbRwXLktQJX8cNIiFhM1ZuTWk7PIYSBhkVcLzwIiCjCxhCjlAkBqYnqFoQQ2AAAAAElFTkSuQmCC

download(swfpathimgpath[fileName])

swfpathTypestringPath to the swfobjectjs in downloadify

imgpathTypestringPath to the image of the download button

[fileName]TypestringDefaultdefaultdocxName of the file you would like the user to download

This requires to include Downloadifyjs that needs flash version 10 Have a look at the output function if you donrsquot want to depend on it This function has the advantage that it works regardless of the file size

getImageList()

this gets all images that have one of the following extension rsquogifrsquorsquojpegrsquorsquojpgrsquorsquoemfrsquorsquopngrsquoReturn format Array of Object[pathstringfilesZipFile Object]

You shouldrsquont call this method before calling applyTags() because applyTags can modify the images or their path when replacing images with other (particularly when qrCode is set to true which is not the default case) You can call this method after applyTags() without any problems

setImage(pathimgData)

pathTypeStringPath of the image given by getImageList()

imgDataTypeStringimgData in txtplain

This sets the image given by a path and an imgData in txtplainYou shouldrsquont call this method before calling applyTags() because applyTags can modify the images or their path when replacing images with other (particularly when qrCode is set to true which is not the default case) You can call this method after applyTags() without any problems

getFullText([path])

pathTypeStringDefaultworddocumentxmlThis argument determines from which document you want to get the text The main document is called worddocumentxml but they are other documents wordheader1xml wordfooter1xml

returnsTypeStringThe string containing all the text from the document

92 Docxgen methods 25

docxtemplater Documentation Release 054

This method gets only the text of a given document (not the formatting)

getTags()

This function returns the template variables contained in the opened document For example if the content of the documentxml is the following

namefirst_namephone

The function will return[

filenamedocumentxmlvars

nametruefirst_nametruephonetrue

]

If the content contains tagLoops

titlecustomernamephonecustomer

The function will return

[filenamedocumentxmlvars

titletruecustomer

nametruephonetrue

]

26 Chapter 9 Full Documentation per method

CHAPTER 10

Copyright

License

(The MIT license)

Copyright (c) 2013 Edgar Hipp

Permission is hereby granted free of charge to any person obtaining a copy of this software and associated documen-tation files (the ldquoSoftwarerdquo) to deal in the Software without restriction including without limitation the rights to usecopy modify merge publish distribute sublicense andor sell copies of the Software and to permit persons to whomthe Software is furnished to do so subject to the following conditions

The above copyright notice and this permission notice shall be included in all copies or substantial portions of theSoftware

THE SOFTWARE IS PROVIDED ldquoAS ISrdquo WITHOUT WARRANTY OF ANY KIND EXPRESS OR IMPLIEDINCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY FITNESS FOR A PAR-TICULAR PURPOSE AND NONINFRINGEMENT IN NO EVENT SHALL THE AUTHORS OR COPYRIGHTHOLDERS BE LIABLE FOR ANY CLAIM DAMAGES OR OTHER LIABILITY WHETHER IN AN ACTIONOF CONTRACT TORT OR OTHERWISE ARISING FROM OUT OF OR IN CONNECTION WITH THE SOFT-WARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE

27

docxtemplater Documentation Release 054

28 Chapter 10 Copyright

CHAPTER 11

Demos

Including

bull Replace Variables

bull Formating

bull Angular Parsing

bull Loops

bull Loops and tables

bull Lists

bull Replacing images

bull Naming the output

bull Using QrCodes

bull Replacing many images with QrCode

bull Raw Xml Insertion

29

docxtemplater Documentation Release 054

30 Chapter 11 Demos

CHAPTER 12

Indices and tables

bull genindex

bull modindex

bull search

31

docxtemplater Documentation Release 054

32 Chapter 12 Indices and tables

Index

CCommand Line Interface (CLI) 20Configuration 17Copyright 26

FFull_doc 21

GGenerate a Document 13Goals 1

IInstallation 7

Pplatform_support 3

SSyntax 9

33

  • Goals
    • Why you should use a library for this
      • Platform Support
      • Dependencies
      • Installation
        • Node
        • Browser
          • Syntax
            • Synopsis
            • Tag types
            • Loop syntax
            • Dash syntax
            • Inverted Selections
              • Generate a document
                • Loading a document
                • Setting the tags
                • Applying the tags
                • Outputing the document
                  • Configuration
                    • Image Replacing
                    • Angular Parser
                    • Intelligent LoopTagging
                      • Command Line Interface (CLI)
                        • Configjson Syntax
                          • Full Documentation per method
                            • Creating a new Docxgen Object
                            • Docxgen methods
                              • Copyright
                              • Demos
                              • Indices and tables
Page 23: Release 0.5€¦ · Docx is a zipped format that contains some xml. If you want to build a simple replace {tag} If you want to build a simple replace {tag} by value system, it can

docxtemplater Documentation Release 054

getfunction(scope) return scope[expression]

To use the angular-parser do the following

expressions= require(rsquoangular-expressionsrsquo)angularParser= function(tag)

return getexpressionscompile(tag)

new DocxGen(dataparserangularParser)

Note The require() works in the browser if you include vendorangular-parser-browserjs

73 Intelligent LoopTagging

The name of this option intelligentTagging (boolean)

When looping over an element docxtemplater needs to know over which element you want to loop By default it triesto do that intelligently (by looking what XML Tags are between the tags) However if you want to always use theltwtgt tag by default set this option to false

You can always specify over which element you want to loop with the dash loop syntax

20 Chapter 7 Configuration

CHAPTER 8

Command Line Interface (CLI)

This section is about the commandline interface of docxtemplater

The syntax is the following

docxtemplater configjson

The full configjson should be something like that

configdocxFileinputdocxconfigoutputFileoutputdocxconfigqrcodetrueconfigdebugtruefirst_nameJohnlast_nameSmithage62

81 Configjson Syntax

811 Config properties

These are the properties to configure docxtemplater

configdocxFileinputdocx The input file pathconfigoutputFileoutputdocx The output file pathconfigqrcodetrue whether the images should be scanned to replace them by qrcodes (slows down the cli a lot)configdebugtrue whether to show debug output or not

812 Data properties

To add data to your template just use keys that donrsquot start with ldquoconfigrdquo

first_nameJohnlast_nameSmithage62

21

docxtemplater Documentation Release 054

22 Chapter 8 Command Line Interface (CLI)

CHAPTER 9

Full Documentation per method

91 Creating a new Docxgen Object

new DocxGen()

This function returns a new DocxGen Object

new DocxGen(content[Tagsoptions])

contentType stringThe docx template you want to load as plain text

TagsType Object tag_nametag_replacement []Object containing for each tag_name the replacement for this tag For example if you want to replace firstName by David your Object will be firstNameDavid

options object

parserType functionA custom parser to use See angularjs like parsing

intelligentTaggingType boolean [false]If intelligent Tagging is not set to true when using recursive tags (tag and tag) the system will copy paste what is between the start tag and the endtag this could basically corrupt the files if recursive tags are used inside tablesIf intelligent Tagging is set to true and when using recursive tags inside tables the whole column will be copy pasted

qrCodeType boolean [false]If qrCode is set to true DocxGen will look at all the images to find a Qr-Code If the Qr-code matches to a URL this URL will be loaded by ajax (Be aware that the server you want to access needs to allow your request or it wonrsquot work httpstackoverflowcomquestions9310112why-am-i-seeing-an-origin-is-not-allowed-by-access-control-allow-origin-error )

Important the qrCode functionality only works for PNG I donrsquot think I will enable this for other fileformats in the near future

localImageCreatorType function(argcallback) [function that returns an arrow]The function has to be customized only if you want to use the qrCode options (qrCode=true) When the qrcode text starts with gen the image is not going to be loaded by url but DocxGen calls localImageCreator with arg=full Text decoded The callback needs to be called with the image Datacallback(result) in plaintxt format (if you want to create it from a Data-URI you can use JSZipBase64decode(data) to decode a Data-URI to plaintxt)

The default localImageCreator returns a red arrow no matter what the arguments are

localImageCreator= (argcallback) -gtresult=JSZipBase64decode(iVBORw0KGgoAAAANSUhEUgAAABcAAAAXCAIAAABvSEP3AAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAACXSURBVDhPtY7BDYAwDAMZhCf7b8YMxeCoatOQJhWcKGxT2zlCyaWcz8Y+X7Bs1TFVJSwIHIYyFkQufWIRVX9cNJyW1QpEo4rixaEe7JuQagAUctb7ZFYFh5MVJPBe84CVBnB42YsZRgKjFDBVg3cI9WbRwXLktQJX8cNIiFhM1ZuTWk7PIYSBhkVcLzwIiCjCxhCjlAkBqYnqFoQQ2AAAAAElFTkSuQmCC)

23

docxtemplater Documentation Release 054

[Default Image](dataimagepngbase64iVBORw0KGgoAAAANSUhEUgAAABcAAAAXCAIAAABvSEP3AAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAACXSURBVDhPtY7BDYAwDAMZhCf7b8YMxeCoatOQJhWcKGxT2zlCyaWcz8Y+X7Bs1TFVJSwIHIYyFkQufWIRVX9cNJyW1QpEo4rixaEe7JuQagAUctb7ZFYFh5MVJPBe84CVBnB42YsZRgKjFDBVg3cI9WbRwXLktQJX8cNIiFhM1ZuTWk7PIYSBhkVcLzwIiCjCxhCjlAkBqYnqFoQQ2AAAAAElFTkSuQmCC)

qrFinishedCallBackType function () [function that consolelog(ready)]

This function is called if you specify qrCode argument to true in this constructor and will be called when all qrCodes have been replaced (because the qrCode replacing functions are async)

92 Docxgen methods

load(content)

contentType stringThe docx template you want to load as plain text

loadFromFile(path)path

Type stringLoads a docx from a file path

setTags(Tags)

TagsType Object tag_nametag_replacementObject containing for each tag_name the replacement for this tag For example if you want to replace firstName by David your Object will be firstNameDavid

applyTags([Tags])Tags

Type Object tag_nametag_replacementsame as setTagsDefaultthisTags

This function replaces all template variables by their values

output([options])

options object[]

nameTypestring[outputdocx]The name of the file that will be outputed (doesnt work in the browser because of dataUri download)

callbackTypefunctionFunction that is called without arguments when the output is done Is used only in Node (because in the browser the operation is synchronous)

downloadTypeboolean[true]If download is true file will be downloaded automatically with data URIreturns the output file

typeTypestring[base64]The type of zip to return The possible values are (same as in httpstukgithubiojszip generate)base64 (default) the result will be a string the binary in a base64 formstring the result will be a string in binary form 1 byte per charuint8array the result will be a Uint8Array containing the zip This requires a compatible browser

24 Chapter 9 Full Documentation per method

docxtemplater Documentation Release 054

arraybuffer the result will be a ArrayBuffer containing the zip This requires a compatible browserblob the result will be a Blob containing the zip This requires a compatible browsernodebuffer the result will be a nodejs Buffer containing the zip This requires nodejs

This function creates the docx file and downloads it on the userrsquos computer The name of the file is downloaddocx for Chrome and some akward file names for Firefox VEeTHCfSdocxpartdocx and canrsquot be changed because it is handled by the browserFor more informations about how to solve this problem see the Filename Problems section on [httpstukgithubiojszip](httpstukgithubiojszip)

Note All browsers donrsquot support the download of big files with Data URI so you should use the lsquodownloadlsquo method for files bigger than 100kB dataimagepngbase64iVBORw0KGgoAAAANSUhEUgAAABcAAAAXCAIAAABvSEP3AAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAACXSURBVDhPtY7BDYAwDAMZhCf7b8YMxeCoatOQJhWcKGxT2zlCyaWcz8Y+X7Bs1TFVJSwIHIYyFkQufWIRVX9cNJyW1QpEo4rixaEe7JuQagAUctb7ZFYFh5MVJPBe84CVBnB42YsZRgKjFDBVg3cI9WbRwXLktQJX8cNIiFhM1ZuTWk7PIYSBhkVcLzwIiCjCxhCjlAkBqYnqFoQQ2AAAAAElFTkSuQmCC

download(swfpathimgpath[fileName])

swfpathTypestringPath to the swfobjectjs in downloadify

imgpathTypestringPath to the image of the download button

[fileName]TypestringDefaultdefaultdocxName of the file you would like the user to download

This requires to include Downloadifyjs that needs flash version 10 Have a look at the output function if you donrsquot want to depend on it This function has the advantage that it works regardless of the file size

getImageList()

this gets all images that have one of the following extension rsquogifrsquorsquojpegrsquorsquojpgrsquorsquoemfrsquorsquopngrsquoReturn format Array of Object[pathstringfilesZipFile Object]

You shouldrsquont call this method before calling applyTags() because applyTags can modify the images or their path when replacing images with other (particularly when qrCode is set to true which is not the default case) You can call this method after applyTags() without any problems

setImage(pathimgData)

pathTypeStringPath of the image given by getImageList()

imgDataTypeStringimgData in txtplain

This sets the image given by a path and an imgData in txtplainYou shouldrsquont call this method before calling applyTags() because applyTags can modify the images or their path when replacing images with other (particularly when qrCode is set to true which is not the default case) You can call this method after applyTags() without any problems

getFullText([path])

pathTypeStringDefaultworddocumentxmlThis argument determines from which document you want to get the text The main document is called worddocumentxml but they are other documents wordheader1xml wordfooter1xml

returnsTypeStringThe string containing all the text from the document

92 Docxgen methods 25

docxtemplater Documentation Release 054

This method gets only the text of a given document (not the formatting)

getTags()

This function returns the template variables contained in the opened document For example if the content of the documentxml is the following

namefirst_namephone

The function will return[

filenamedocumentxmlvars

nametruefirst_nametruephonetrue

]

If the content contains tagLoops

titlecustomernamephonecustomer

The function will return

[filenamedocumentxmlvars

titletruecustomer

nametruephonetrue

]

26 Chapter 9 Full Documentation per method

CHAPTER 10

Copyright

License

(The MIT license)

Copyright (c) 2013 Edgar Hipp

Permission is hereby granted free of charge to any person obtaining a copy of this software and associated documen-tation files (the ldquoSoftwarerdquo) to deal in the Software without restriction including without limitation the rights to usecopy modify merge publish distribute sublicense andor sell copies of the Software and to permit persons to whomthe Software is furnished to do so subject to the following conditions

The above copyright notice and this permission notice shall be included in all copies or substantial portions of theSoftware

THE SOFTWARE IS PROVIDED ldquoAS ISrdquo WITHOUT WARRANTY OF ANY KIND EXPRESS OR IMPLIEDINCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY FITNESS FOR A PAR-TICULAR PURPOSE AND NONINFRINGEMENT IN NO EVENT SHALL THE AUTHORS OR COPYRIGHTHOLDERS BE LIABLE FOR ANY CLAIM DAMAGES OR OTHER LIABILITY WHETHER IN AN ACTIONOF CONTRACT TORT OR OTHERWISE ARISING FROM OUT OF OR IN CONNECTION WITH THE SOFT-WARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE

27

docxtemplater Documentation Release 054

28 Chapter 10 Copyright

CHAPTER 11

Demos

Including

bull Replace Variables

bull Formating

bull Angular Parsing

bull Loops

bull Loops and tables

bull Lists

bull Replacing images

bull Naming the output

bull Using QrCodes

bull Replacing many images with QrCode

bull Raw Xml Insertion

29

docxtemplater Documentation Release 054

30 Chapter 11 Demos

CHAPTER 12

Indices and tables

bull genindex

bull modindex

bull search

31

docxtemplater Documentation Release 054

32 Chapter 12 Indices and tables

Index

CCommand Line Interface (CLI) 20Configuration 17Copyright 26

FFull_doc 21

GGenerate a Document 13Goals 1

IInstallation 7

Pplatform_support 3

SSyntax 9

33

  • Goals
    • Why you should use a library for this
      • Platform Support
      • Dependencies
      • Installation
        • Node
        • Browser
          • Syntax
            • Synopsis
            • Tag types
            • Loop syntax
            • Dash syntax
            • Inverted Selections
              • Generate a document
                • Loading a document
                • Setting the tags
                • Applying the tags
                • Outputing the document
                  • Configuration
                    • Image Replacing
                    • Angular Parser
                    • Intelligent LoopTagging
                      • Command Line Interface (CLI)
                        • Configjson Syntax
                          • Full Documentation per method
                            • Creating a new Docxgen Object
                            • Docxgen methods
                              • Copyright
                              • Demos
                              • Indices and tables
Page 24: Release 0.5€¦ · Docx is a zipped format that contains some xml. If you want to build a simple replace {tag} If you want to build a simple replace {tag} by value system, it can

CHAPTER 8

Command Line Interface (CLI)

This section is about the commandline interface of docxtemplater

The syntax is the following

docxtemplater configjson

The full configjson should be something like that

configdocxFileinputdocxconfigoutputFileoutputdocxconfigqrcodetrueconfigdebugtruefirst_nameJohnlast_nameSmithage62

81 Configjson Syntax

811 Config properties

These are the properties to configure docxtemplater

configdocxFileinputdocx The input file pathconfigoutputFileoutputdocx The output file pathconfigqrcodetrue whether the images should be scanned to replace them by qrcodes (slows down the cli a lot)configdebugtrue whether to show debug output or not

812 Data properties

To add data to your template just use keys that donrsquot start with ldquoconfigrdquo

first_nameJohnlast_nameSmithage62

21

docxtemplater Documentation Release 054

22 Chapter 8 Command Line Interface (CLI)

CHAPTER 9

Full Documentation per method

91 Creating a new Docxgen Object

new DocxGen()

This function returns a new DocxGen Object

new DocxGen(content[Tagsoptions])

contentType stringThe docx template you want to load as plain text

TagsType Object tag_nametag_replacement []Object containing for each tag_name the replacement for this tag For example if you want to replace firstName by David your Object will be firstNameDavid

options object

parserType functionA custom parser to use See angularjs like parsing

intelligentTaggingType boolean [false]If intelligent Tagging is not set to true when using recursive tags (tag and tag) the system will copy paste what is between the start tag and the endtag this could basically corrupt the files if recursive tags are used inside tablesIf intelligent Tagging is set to true and when using recursive tags inside tables the whole column will be copy pasted

qrCodeType boolean [false]If qrCode is set to true DocxGen will look at all the images to find a Qr-Code If the Qr-code matches to a URL this URL will be loaded by ajax (Be aware that the server you want to access needs to allow your request or it wonrsquot work httpstackoverflowcomquestions9310112why-am-i-seeing-an-origin-is-not-allowed-by-access-control-allow-origin-error )

Important the qrCode functionality only works for PNG I donrsquot think I will enable this for other fileformats in the near future

localImageCreatorType function(argcallback) [function that returns an arrow]The function has to be customized only if you want to use the qrCode options (qrCode=true) When the qrcode text starts with gen the image is not going to be loaded by url but DocxGen calls localImageCreator with arg=full Text decoded The callback needs to be called with the image Datacallback(result) in plaintxt format (if you want to create it from a Data-URI you can use JSZipBase64decode(data) to decode a Data-URI to plaintxt)

The default localImageCreator returns a red arrow no matter what the arguments are

localImageCreator= (argcallback) -gtresult=JSZipBase64decode(iVBORw0KGgoAAAANSUhEUgAAABcAAAAXCAIAAABvSEP3AAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAACXSURBVDhPtY7BDYAwDAMZhCf7b8YMxeCoatOQJhWcKGxT2zlCyaWcz8Y+X7Bs1TFVJSwIHIYyFkQufWIRVX9cNJyW1QpEo4rixaEe7JuQagAUctb7ZFYFh5MVJPBe84CVBnB42YsZRgKjFDBVg3cI9WbRwXLktQJX8cNIiFhM1ZuTWk7PIYSBhkVcLzwIiCjCxhCjlAkBqYnqFoQQ2AAAAAElFTkSuQmCC)

23

docxtemplater Documentation Release 054

[Default Image](dataimagepngbase64iVBORw0KGgoAAAANSUhEUgAAABcAAAAXCAIAAABvSEP3AAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAACXSURBVDhPtY7BDYAwDAMZhCf7b8YMxeCoatOQJhWcKGxT2zlCyaWcz8Y+X7Bs1TFVJSwIHIYyFkQufWIRVX9cNJyW1QpEo4rixaEe7JuQagAUctb7ZFYFh5MVJPBe84CVBnB42YsZRgKjFDBVg3cI9WbRwXLktQJX8cNIiFhM1ZuTWk7PIYSBhkVcLzwIiCjCxhCjlAkBqYnqFoQQ2AAAAAElFTkSuQmCC)

qrFinishedCallBackType function () [function that consolelog(ready)]

This function is called if you specify qrCode argument to true in this constructor and will be called when all qrCodes have been replaced (because the qrCode replacing functions are async)

92 Docxgen methods

load(content)

contentType stringThe docx template you want to load as plain text

loadFromFile(path)path

Type stringLoads a docx from a file path

setTags(Tags)

TagsType Object tag_nametag_replacementObject containing for each tag_name the replacement for this tag For example if you want to replace firstName by David your Object will be firstNameDavid

applyTags([Tags])Tags

Type Object tag_nametag_replacementsame as setTagsDefaultthisTags

This function replaces all template variables by their values

output([options])

options object[]

nameTypestring[outputdocx]The name of the file that will be outputed (doesnt work in the browser because of dataUri download)

callbackTypefunctionFunction that is called without arguments when the output is done Is used only in Node (because in the browser the operation is synchronous)

downloadTypeboolean[true]If download is true file will be downloaded automatically with data URIreturns the output file

typeTypestring[base64]The type of zip to return The possible values are (same as in httpstukgithubiojszip generate)base64 (default) the result will be a string the binary in a base64 formstring the result will be a string in binary form 1 byte per charuint8array the result will be a Uint8Array containing the zip This requires a compatible browser

24 Chapter 9 Full Documentation per method

docxtemplater Documentation Release 054

arraybuffer the result will be a ArrayBuffer containing the zip This requires a compatible browserblob the result will be a Blob containing the zip This requires a compatible browsernodebuffer the result will be a nodejs Buffer containing the zip This requires nodejs

This function creates the docx file and downloads it on the userrsquos computer The name of the file is downloaddocx for Chrome and some akward file names for Firefox VEeTHCfSdocxpartdocx and canrsquot be changed because it is handled by the browserFor more informations about how to solve this problem see the Filename Problems section on [httpstukgithubiojszip](httpstukgithubiojszip)

Note All browsers donrsquot support the download of big files with Data URI so you should use the lsquodownloadlsquo method for files bigger than 100kB dataimagepngbase64iVBORw0KGgoAAAANSUhEUgAAABcAAAAXCAIAAABvSEP3AAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAACXSURBVDhPtY7BDYAwDAMZhCf7b8YMxeCoatOQJhWcKGxT2zlCyaWcz8Y+X7Bs1TFVJSwIHIYyFkQufWIRVX9cNJyW1QpEo4rixaEe7JuQagAUctb7ZFYFh5MVJPBe84CVBnB42YsZRgKjFDBVg3cI9WbRwXLktQJX8cNIiFhM1ZuTWk7PIYSBhkVcLzwIiCjCxhCjlAkBqYnqFoQQ2AAAAAElFTkSuQmCC

download(swfpathimgpath[fileName])

swfpathTypestringPath to the swfobjectjs in downloadify

imgpathTypestringPath to the image of the download button

[fileName]TypestringDefaultdefaultdocxName of the file you would like the user to download

This requires to include Downloadifyjs that needs flash version 10 Have a look at the output function if you donrsquot want to depend on it This function has the advantage that it works regardless of the file size

getImageList()

this gets all images that have one of the following extension rsquogifrsquorsquojpegrsquorsquojpgrsquorsquoemfrsquorsquopngrsquoReturn format Array of Object[pathstringfilesZipFile Object]

You shouldrsquont call this method before calling applyTags() because applyTags can modify the images or their path when replacing images with other (particularly when qrCode is set to true which is not the default case) You can call this method after applyTags() without any problems

setImage(pathimgData)

pathTypeStringPath of the image given by getImageList()

imgDataTypeStringimgData in txtplain

This sets the image given by a path and an imgData in txtplainYou shouldrsquont call this method before calling applyTags() because applyTags can modify the images or their path when replacing images with other (particularly when qrCode is set to true which is not the default case) You can call this method after applyTags() without any problems

getFullText([path])

pathTypeStringDefaultworddocumentxmlThis argument determines from which document you want to get the text The main document is called worddocumentxml but they are other documents wordheader1xml wordfooter1xml

returnsTypeStringThe string containing all the text from the document

92 Docxgen methods 25

docxtemplater Documentation Release 054

This method gets only the text of a given document (not the formatting)

getTags()

This function returns the template variables contained in the opened document For example if the content of the documentxml is the following

namefirst_namephone

The function will return[

filenamedocumentxmlvars

nametruefirst_nametruephonetrue

]

If the content contains tagLoops

titlecustomernamephonecustomer

The function will return

[filenamedocumentxmlvars

titletruecustomer

nametruephonetrue

]

26 Chapter 9 Full Documentation per method

CHAPTER 10

Copyright

License

(The MIT license)

Copyright (c) 2013 Edgar Hipp

Permission is hereby granted free of charge to any person obtaining a copy of this software and associated documen-tation files (the ldquoSoftwarerdquo) to deal in the Software without restriction including without limitation the rights to usecopy modify merge publish distribute sublicense andor sell copies of the Software and to permit persons to whomthe Software is furnished to do so subject to the following conditions

The above copyright notice and this permission notice shall be included in all copies or substantial portions of theSoftware

THE SOFTWARE IS PROVIDED ldquoAS ISrdquo WITHOUT WARRANTY OF ANY KIND EXPRESS OR IMPLIEDINCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY FITNESS FOR A PAR-TICULAR PURPOSE AND NONINFRINGEMENT IN NO EVENT SHALL THE AUTHORS OR COPYRIGHTHOLDERS BE LIABLE FOR ANY CLAIM DAMAGES OR OTHER LIABILITY WHETHER IN AN ACTIONOF CONTRACT TORT OR OTHERWISE ARISING FROM OUT OF OR IN CONNECTION WITH THE SOFT-WARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE

27

docxtemplater Documentation Release 054

28 Chapter 10 Copyright

CHAPTER 11

Demos

Including

bull Replace Variables

bull Formating

bull Angular Parsing

bull Loops

bull Loops and tables

bull Lists

bull Replacing images

bull Naming the output

bull Using QrCodes

bull Replacing many images with QrCode

bull Raw Xml Insertion

29

docxtemplater Documentation Release 054

30 Chapter 11 Demos

CHAPTER 12

Indices and tables

bull genindex

bull modindex

bull search

31

docxtemplater Documentation Release 054

32 Chapter 12 Indices and tables

Index

CCommand Line Interface (CLI) 20Configuration 17Copyright 26

FFull_doc 21

GGenerate a Document 13Goals 1

IInstallation 7

Pplatform_support 3

SSyntax 9

33

  • Goals
    • Why you should use a library for this
      • Platform Support
      • Dependencies
      • Installation
        • Node
        • Browser
          • Syntax
            • Synopsis
            • Tag types
            • Loop syntax
            • Dash syntax
            • Inverted Selections
              • Generate a document
                • Loading a document
                • Setting the tags
                • Applying the tags
                • Outputing the document
                  • Configuration
                    • Image Replacing
                    • Angular Parser
                    • Intelligent LoopTagging
                      • Command Line Interface (CLI)
                        • Configjson Syntax
                          • Full Documentation per method
                            • Creating a new Docxgen Object
                            • Docxgen methods
                              • Copyright
                              • Demos
                              • Indices and tables
Page 25: Release 0.5€¦ · Docx is a zipped format that contains some xml. If you want to build a simple replace {tag} If you want to build a simple replace {tag} by value system, it can

docxtemplater Documentation Release 054

22 Chapter 8 Command Line Interface (CLI)

CHAPTER 9

Full Documentation per method

91 Creating a new Docxgen Object

new DocxGen()

This function returns a new DocxGen Object

new DocxGen(content[Tagsoptions])

contentType stringThe docx template you want to load as plain text

TagsType Object tag_nametag_replacement []Object containing for each tag_name the replacement for this tag For example if you want to replace firstName by David your Object will be firstNameDavid

options object

parserType functionA custom parser to use See angularjs like parsing

intelligentTaggingType boolean [false]If intelligent Tagging is not set to true when using recursive tags (tag and tag) the system will copy paste what is between the start tag and the endtag this could basically corrupt the files if recursive tags are used inside tablesIf intelligent Tagging is set to true and when using recursive tags inside tables the whole column will be copy pasted

qrCodeType boolean [false]If qrCode is set to true DocxGen will look at all the images to find a Qr-Code If the Qr-code matches to a URL this URL will be loaded by ajax (Be aware that the server you want to access needs to allow your request or it wonrsquot work httpstackoverflowcomquestions9310112why-am-i-seeing-an-origin-is-not-allowed-by-access-control-allow-origin-error )

Important the qrCode functionality only works for PNG I donrsquot think I will enable this for other fileformats in the near future

localImageCreatorType function(argcallback) [function that returns an arrow]The function has to be customized only if you want to use the qrCode options (qrCode=true) When the qrcode text starts with gen the image is not going to be loaded by url but DocxGen calls localImageCreator with arg=full Text decoded The callback needs to be called with the image Datacallback(result) in plaintxt format (if you want to create it from a Data-URI you can use JSZipBase64decode(data) to decode a Data-URI to plaintxt)

The default localImageCreator returns a red arrow no matter what the arguments are

localImageCreator= (argcallback) -gtresult=JSZipBase64decode(iVBORw0KGgoAAAANSUhEUgAAABcAAAAXCAIAAABvSEP3AAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAACXSURBVDhPtY7BDYAwDAMZhCf7b8YMxeCoatOQJhWcKGxT2zlCyaWcz8Y+X7Bs1TFVJSwIHIYyFkQufWIRVX9cNJyW1QpEo4rixaEe7JuQagAUctb7ZFYFh5MVJPBe84CVBnB42YsZRgKjFDBVg3cI9WbRwXLktQJX8cNIiFhM1ZuTWk7PIYSBhkVcLzwIiCjCxhCjlAkBqYnqFoQQ2AAAAAElFTkSuQmCC)

23

docxtemplater Documentation Release 054

[Default Image](dataimagepngbase64iVBORw0KGgoAAAANSUhEUgAAABcAAAAXCAIAAABvSEP3AAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAACXSURBVDhPtY7BDYAwDAMZhCf7b8YMxeCoatOQJhWcKGxT2zlCyaWcz8Y+X7Bs1TFVJSwIHIYyFkQufWIRVX9cNJyW1QpEo4rixaEe7JuQagAUctb7ZFYFh5MVJPBe84CVBnB42YsZRgKjFDBVg3cI9WbRwXLktQJX8cNIiFhM1ZuTWk7PIYSBhkVcLzwIiCjCxhCjlAkBqYnqFoQQ2AAAAAElFTkSuQmCC)

qrFinishedCallBackType function () [function that consolelog(ready)]

This function is called if you specify qrCode argument to true in this constructor and will be called when all qrCodes have been replaced (because the qrCode replacing functions are async)

92 Docxgen methods

load(content)

contentType stringThe docx template you want to load as plain text

loadFromFile(path)path

Type stringLoads a docx from a file path

setTags(Tags)

TagsType Object tag_nametag_replacementObject containing for each tag_name the replacement for this tag For example if you want to replace firstName by David your Object will be firstNameDavid

applyTags([Tags])Tags

Type Object tag_nametag_replacementsame as setTagsDefaultthisTags

This function replaces all template variables by their values

output([options])

options object[]

nameTypestring[outputdocx]The name of the file that will be outputed (doesnt work in the browser because of dataUri download)

callbackTypefunctionFunction that is called without arguments when the output is done Is used only in Node (because in the browser the operation is synchronous)

downloadTypeboolean[true]If download is true file will be downloaded automatically with data URIreturns the output file

typeTypestring[base64]The type of zip to return The possible values are (same as in httpstukgithubiojszip generate)base64 (default) the result will be a string the binary in a base64 formstring the result will be a string in binary form 1 byte per charuint8array the result will be a Uint8Array containing the zip This requires a compatible browser

24 Chapter 9 Full Documentation per method

docxtemplater Documentation Release 054

arraybuffer the result will be a ArrayBuffer containing the zip This requires a compatible browserblob the result will be a Blob containing the zip This requires a compatible browsernodebuffer the result will be a nodejs Buffer containing the zip This requires nodejs

This function creates the docx file and downloads it on the userrsquos computer The name of the file is downloaddocx for Chrome and some akward file names for Firefox VEeTHCfSdocxpartdocx and canrsquot be changed because it is handled by the browserFor more informations about how to solve this problem see the Filename Problems section on [httpstukgithubiojszip](httpstukgithubiojszip)

Note All browsers donrsquot support the download of big files with Data URI so you should use the lsquodownloadlsquo method for files bigger than 100kB dataimagepngbase64iVBORw0KGgoAAAANSUhEUgAAABcAAAAXCAIAAABvSEP3AAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAACXSURBVDhPtY7BDYAwDAMZhCf7b8YMxeCoatOQJhWcKGxT2zlCyaWcz8Y+X7Bs1TFVJSwIHIYyFkQufWIRVX9cNJyW1QpEo4rixaEe7JuQagAUctb7ZFYFh5MVJPBe84CVBnB42YsZRgKjFDBVg3cI9WbRwXLktQJX8cNIiFhM1ZuTWk7PIYSBhkVcLzwIiCjCxhCjlAkBqYnqFoQQ2AAAAAElFTkSuQmCC

download(swfpathimgpath[fileName])

swfpathTypestringPath to the swfobjectjs in downloadify

imgpathTypestringPath to the image of the download button

[fileName]TypestringDefaultdefaultdocxName of the file you would like the user to download

This requires to include Downloadifyjs that needs flash version 10 Have a look at the output function if you donrsquot want to depend on it This function has the advantage that it works regardless of the file size

getImageList()

this gets all images that have one of the following extension rsquogifrsquorsquojpegrsquorsquojpgrsquorsquoemfrsquorsquopngrsquoReturn format Array of Object[pathstringfilesZipFile Object]

You shouldrsquont call this method before calling applyTags() because applyTags can modify the images or their path when replacing images with other (particularly when qrCode is set to true which is not the default case) You can call this method after applyTags() without any problems

setImage(pathimgData)

pathTypeStringPath of the image given by getImageList()

imgDataTypeStringimgData in txtplain

This sets the image given by a path and an imgData in txtplainYou shouldrsquont call this method before calling applyTags() because applyTags can modify the images or their path when replacing images with other (particularly when qrCode is set to true which is not the default case) You can call this method after applyTags() without any problems

getFullText([path])

pathTypeStringDefaultworddocumentxmlThis argument determines from which document you want to get the text The main document is called worddocumentxml but they are other documents wordheader1xml wordfooter1xml

returnsTypeStringThe string containing all the text from the document

92 Docxgen methods 25

docxtemplater Documentation Release 054

This method gets only the text of a given document (not the formatting)

getTags()

This function returns the template variables contained in the opened document For example if the content of the documentxml is the following

namefirst_namephone

The function will return[

filenamedocumentxmlvars

nametruefirst_nametruephonetrue

]

If the content contains tagLoops

titlecustomernamephonecustomer

The function will return

[filenamedocumentxmlvars

titletruecustomer

nametruephonetrue

]

26 Chapter 9 Full Documentation per method

CHAPTER 10

Copyright

License

(The MIT license)

Copyright (c) 2013 Edgar Hipp

Permission is hereby granted free of charge to any person obtaining a copy of this software and associated documen-tation files (the ldquoSoftwarerdquo) to deal in the Software without restriction including without limitation the rights to usecopy modify merge publish distribute sublicense andor sell copies of the Software and to permit persons to whomthe Software is furnished to do so subject to the following conditions

The above copyright notice and this permission notice shall be included in all copies or substantial portions of theSoftware

THE SOFTWARE IS PROVIDED ldquoAS ISrdquo WITHOUT WARRANTY OF ANY KIND EXPRESS OR IMPLIEDINCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY FITNESS FOR A PAR-TICULAR PURPOSE AND NONINFRINGEMENT IN NO EVENT SHALL THE AUTHORS OR COPYRIGHTHOLDERS BE LIABLE FOR ANY CLAIM DAMAGES OR OTHER LIABILITY WHETHER IN AN ACTIONOF CONTRACT TORT OR OTHERWISE ARISING FROM OUT OF OR IN CONNECTION WITH THE SOFT-WARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE

27

docxtemplater Documentation Release 054

28 Chapter 10 Copyright

CHAPTER 11

Demos

Including

bull Replace Variables

bull Formating

bull Angular Parsing

bull Loops

bull Loops and tables

bull Lists

bull Replacing images

bull Naming the output

bull Using QrCodes

bull Replacing many images with QrCode

bull Raw Xml Insertion

29

docxtemplater Documentation Release 054

30 Chapter 11 Demos

CHAPTER 12

Indices and tables

bull genindex

bull modindex

bull search

31

docxtemplater Documentation Release 054

32 Chapter 12 Indices and tables

Index

CCommand Line Interface (CLI) 20Configuration 17Copyright 26

FFull_doc 21

GGenerate a Document 13Goals 1

IInstallation 7

Pplatform_support 3

SSyntax 9

33

  • Goals
    • Why you should use a library for this
      • Platform Support
      • Dependencies
      • Installation
        • Node
        • Browser
          • Syntax
            • Synopsis
            • Tag types
            • Loop syntax
            • Dash syntax
            • Inverted Selections
              • Generate a document
                • Loading a document
                • Setting the tags
                • Applying the tags
                • Outputing the document
                  • Configuration
                    • Image Replacing
                    • Angular Parser
                    • Intelligent LoopTagging
                      • Command Line Interface (CLI)
                        • Configjson Syntax
                          • Full Documentation per method
                            • Creating a new Docxgen Object
                            • Docxgen methods
                              • Copyright
                              • Demos
                              • Indices and tables
Page 26: Release 0.5€¦ · Docx is a zipped format that contains some xml. If you want to build a simple replace {tag} If you want to build a simple replace {tag} by value system, it can

CHAPTER 9

Full Documentation per method

91 Creating a new Docxgen Object

new DocxGen()

This function returns a new DocxGen Object

new DocxGen(content[Tagsoptions])

contentType stringThe docx template you want to load as plain text

TagsType Object tag_nametag_replacement []Object containing for each tag_name the replacement for this tag For example if you want to replace firstName by David your Object will be firstNameDavid

options object

parserType functionA custom parser to use See angularjs like parsing

intelligentTaggingType boolean [false]If intelligent Tagging is not set to true when using recursive tags (tag and tag) the system will copy paste what is between the start tag and the endtag this could basically corrupt the files if recursive tags are used inside tablesIf intelligent Tagging is set to true and when using recursive tags inside tables the whole column will be copy pasted

qrCodeType boolean [false]If qrCode is set to true DocxGen will look at all the images to find a Qr-Code If the Qr-code matches to a URL this URL will be loaded by ajax (Be aware that the server you want to access needs to allow your request or it wonrsquot work httpstackoverflowcomquestions9310112why-am-i-seeing-an-origin-is-not-allowed-by-access-control-allow-origin-error )

Important the qrCode functionality only works for PNG I donrsquot think I will enable this for other fileformats in the near future

localImageCreatorType function(argcallback) [function that returns an arrow]The function has to be customized only if you want to use the qrCode options (qrCode=true) When the qrcode text starts with gen the image is not going to be loaded by url but DocxGen calls localImageCreator with arg=full Text decoded The callback needs to be called with the image Datacallback(result) in plaintxt format (if you want to create it from a Data-URI you can use JSZipBase64decode(data) to decode a Data-URI to plaintxt)

The default localImageCreator returns a red arrow no matter what the arguments are

localImageCreator= (argcallback) -gtresult=JSZipBase64decode(iVBORw0KGgoAAAANSUhEUgAAABcAAAAXCAIAAABvSEP3AAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAACXSURBVDhPtY7BDYAwDAMZhCf7b8YMxeCoatOQJhWcKGxT2zlCyaWcz8Y+X7Bs1TFVJSwIHIYyFkQufWIRVX9cNJyW1QpEo4rixaEe7JuQagAUctb7ZFYFh5MVJPBe84CVBnB42YsZRgKjFDBVg3cI9WbRwXLktQJX8cNIiFhM1ZuTWk7PIYSBhkVcLzwIiCjCxhCjlAkBqYnqFoQQ2AAAAAElFTkSuQmCC)

23

docxtemplater Documentation Release 054

[Default Image](dataimagepngbase64iVBORw0KGgoAAAANSUhEUgAAABcAAAAXCAIAAABvSEP3AAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAACXSURBVDhPtY7BDYAwDAMZhCf7b8YMxeCoatOQJhWcKGxT2zlCyaWcz8Y+X7Bs1TFVJSwIHIYyFkQufWIRVX9cNJyW1QpEo4rixaEe7JuQagAUctb7ZFYFh5MVJPBe84CVBnB42YsZRgKjFDBVg3cI9WbRwXLktQJX8cNIiFhM1ZuTWk7PIYSBhkVcLzwIiCjCxhCjlAkBqYnqFoQQ2AAAAAElFTkSuQmCC)

qrFinishedCallBackType function () [function that consolelog(ready)]

This function is called if you specify qrCode argument to true in this constructor and will be called when all qrCodes have been replaced (because the qrCode replacing functions are async)

92 Docxgen methods

load(content)

contentType stringThe docx template you want to load as plain text

loadFromFile(path)path

Type stringLoads a docx from a file path

setTags(Tags)

TagsType Object tag_nametag_replacementObject containing for each tag_name the replacement for this tag For example if you want to replace firstName by David your Object will be firstNameDavid

applyTags([Tags])Tags

Type Object tag_nametag_replacementsame as setTagsDefaultthisTags

This function replaces all template variables by their values

output([options])

options object[]

nameTypestring[outputdocx]The name of the file that will be outputed (doesnt work in the browser because of dataUri download)

callbackTypefunctionFunction that is called without arguments when the output is done Is used only in Node (because in the browser the operation is synchronous)

downloadTypeboolean[true]If download is true file will be downloaded automatically with data URIreturns the output file

typeTypestring[base64]The type of zip to return The possible values are (same as in httpstukgithubiojszip generate)base64 (default) the result will be a string the binary in a base64 formstring the result will be a string in binary form 1 byte per charuint8array the result will be a Uint8Array containing the zip This requires a compatible browser

24 Chapter 9 Full Documentation per method

docxtemplater Documentation Release 054

arraybuffer the result will be a ArrayBuffer containing the zip This requires a compatible browserblob the result will be a Blob containing the zip This requires a compatible browsernodebuffer the result will be a nodejs Buffer containing the zip This requires nodejs

This function creates the docx file and downloads it on the userrsquos computer The name of the file is downloaddocx for Chrome and some akward file names for Firefox VEeTHCfSdocxpartdocx and canrsquot be changed because it is handled by the browserFor more informations about how to solve this problem see the Filename Problems section on [httpstukgithubiojszip](httpstukgithubiojszip)

Note All browsers donrsquot support the download of big files with Data URI so you should use the lsquodownloadlsquo method for files bigger than 100kB dataimagepngbase64iVBORw0KGgoAAAANSUhEUgAAABcAAAAXCAIAAABvSEP3AAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAACXSURBVDhPtY7BDYAwDAMZhCf7b8YMxeCoatOQJhWcKGxT2zlCyaWcz8Y+X7Bs1TFVJSwIHIYyFkQufWIRVX9cNJyW1QpEo4rixaEe7JuQagAUctb7ZFYFh5MVJPBe84CVBnB42YsZRgKjFDBVg3cI9WbRwXLktQJX8cNIiFhM1ZuTWk7PIYSBhkVcLzwIiCjCxhCjlAkBqYnqFoQQ2AAAAAElFTkSuQmCC

download(swfpathimgpath[fileName])

swfpathTypestringPath to the swfobjectjs in downloadify

imgpathTypestringPath to the image of the download button

[fileName]TypestringDefaultdefaultdocxName of the file you would like the user to download

This requires to include Downloadifyjs that needs flash version 10 Have a look at the output function if you donrsquot want to depend on it This function has the advantage that it works regardless of the file size

getImageList()

this gets all images that have one of the following extension rsquogifrsquorsquojpegrsquorsquojpgrsquorsquoemfrsquorsquopngrsquoReturn format Array of Object[pathstringfilesZipFile Object]

You shouldrsquont call this method before calling applyTags() because applyTags can modify the images or their path when replacing images with other (particularly when qrCode is set to true which is not the default case) You can call this method after applyTags() without any problems

setImage(pathimgData)

pathTypeStringPath of the image given by getImageList()

imgDataTypeStringimgData in txtplain

This sets the image given by a path and an imgData in txtplainYou shouldrsquont call this method before calling applyTags() because applyTags can modify the images or their path when replacing images with other (particularly when qrCode is set to true which is not the default case) You can call this method after applyTags() without any problems

getFullText([path])

pathTypeStringDefaultworddocumentxmlThis argument determines from which document you want to get the text The main document is called worddocumentxml but they are other documents wordheader1xml wordfooter1xml

returnsTypeStringThe string containing all the text from the document

92 Docxgen methods 25

docxtemplater Documentation Release 054

This method gets only the text of a given document (not the formatting)

getTags()

This function returns the template variables contained in the opened document For example if the content of the documentxml is the following

namefirst_namephone

The function will return[

filenamedocumentxmlvars

nametruefirst_nametruephonetrue

]

If the content contains tagLoops

titlecustomernamephonecustomer

The function will return

[filenamedocumentxmlvars

titletruecustomer

nametruephonetrue

]

26 Chapter 9 Full Documentation per method

CHAPTER 10

Copyright

License

(The MIT license)

Copyright (c) 2013 Edgar Hipp

Permission is hereby granted free of charge to any person obtaining a copy of this software and associated documen-tation files (the ldquoSoftwarerdquo) to deal in the Software without restriction including without limitation the rights to usecopy modify merge publish distribute sublicense andor sell copies of the Software and to permit persons to whomthe Software is furnished to do so subject to the following conditions

The above copyright notice and this permission notice shall be included in all copies or substantial portions of theSoftware

THE SOFTWARE IS PROVIDED ldquoAS ISrdquo WITHOUT WARRANTY OF ANY KIND EXPRESS OR IMPLIEDINCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY FITNESS FOR A PAR-TICULAR PURPOSE AND NONINFRINGEMENT IN NO EVENT SHALL THE AUTHORS OR COPYRIGHTHOLDERS BE LIABLE FOR ANY CLAIM DAMAGES OR OTHER LIABILITY WHETHER IN AN ACTIONOF CONTRACT TORT OR OTHERWISE ARISING FROM OUT OF OR IN CONNECTION WITH THE SOFT-WARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE

27

docxtemplater Documentation Release 054

28 Chapter 10 Copyright

CHAPTER 11

Demos

Including

bull Replace Variables

bull Formating

bull Angular Parsing

bull Loops

bull Loops and tables

bull Lists

bull Replacing images

bull Naming the output

bull Using QrCodes

bull Replacing many images with QrCode

bull Raw Xml Insertion

29

docxtemplater Documentation Release 054

30 Chapter 11 Demos

CHAPTER 12

Indices and tables

bull genindex

bull modindex

bull search

31

docxtemplater Documentation Release 054

32 Chapter 12 Indices and tables

Index

CCommand Line Interface (CLI) 20Configuration 17Copyright 26

FFull_doc 21

GGenerate a Document 13Goals 1

IInstallation 7

Pplatform_support 3

SSyntax 9

33

  • Goals
    • Why you should use a library for this
      • Platform Support
      • Dependencies
      • Installation
        • Node
        • Browser
          • Syntax
            • Synopsis
            • Tag types
            • Loop syntax
            • Dash syntax
            • Inverted Selections
              • Generate a document
                • Loading a document
                • Setting the tags
                • Applying the tags
                • Outputing the document
                  • Configuration
                    • Image Replacing
                    • Angular Parser
                    • Intelligent LoopTagging
                      • Command Line Interface (CLI)
                        • Configjson Syntax
                          • Full Documentation per method
                            • Creating a new Docxgen Object
                            • Docxgen methods
                              • Copyright
                              • Demos
                              • Indices and tables
Page 27: Release 0.5€¦ · Docx is a zipped format that contains some xml. If you want to build a simple replace {tag} If you want to build a simple replace {tag} by value system, it can

docxtemplater Documentation Release 054

[Default Image](dataimagepngbase64iVBORw0KGgoAAAANSUhEUgAAABcAAAAXCAIAAABvSEP3AAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAACXSURBVDhPtY7BDYAwDAMZhCf7b8YMxeCoatOQJhWcKGxT2zlCyaWcz8Y+X7Bs1TFVJSwIHIYyFkQufWIRVX9cNJyW1QpEo4rixaEe7JuQagAUctb7ZFYFh5MVJPBe84CVBnB42YsZRgKjFDBVg3cI9WbRwXLktQJX8cNIiFhM1ZuTWk7PIYSBhkVcLzwIiCjCxhCjlAkBqYnqFoQQ2AAAAAElFTkSuQmCC)

qrFinishedCallBackType function () [function that consolelog(ready)]

This function is called if you specify qrCode argument to true in this constructor and will be called when all qrCodes have been replaced (because the qrCode replacing functions are async)

92 Docxgen methods

load(content)

contentType stringThe docx template you want to load as plain text

loadFromFile(path)path

Type stringLoads a docx from a file path

setTags(Tags)

TagsType Object tag_nametag_replacementObject containing for each tag_name the replacement for this tag For example if you want to replace firstName by David your Object will be firstNameDavid

applyTags([Tags])Tags

Type Object tag_nametag_replacementsame as setTagsDefaultthisTags

This function replaces all template variables by their values

output([options])

options object[]

nameTypestring[outputdocx]The name of the file that will be outputed (doesnt work in the browser because of dataUri download)

callbackTypefunctionFunction that is called without arguments when the output is done Is used only in Node (because in the browser the operation is synchronous)

downloadTypeboolean[true]If download is true file will be downloaded automatically with data URIreturns the output file

typeTypestring[base64]The type of zip to return The possible values are (same as in httpstukgithubiojszip generate)base64 (default) the result will be a string the binary in a base64 formstring the result will be a string in binary form 1 byte per charuint8array the result will be a Uint8Array containing the zip This requires a compatible browser

24 Chapter 9 Full Documentation per method

docxtemplater Documentation Release 054

arraybuffer the result will be a ArrayBuffer containing the zip This requires a compatible browserblob the result will be a Blob containing the zip This requires a compatible browsernodebuffer the result will be a nodejs Buffer containing the zip This requires nodejs

This function creates the docx file and downloads it on the userrsquos computer The name of the file is downloaddocx for Chrome and some akward file names for Firefox VEeTHCfSdocxpartdocx and canrsquot be changed because it is handled by the browserFor more informations about how to solve this problem see the Filename Problems section on [httpstukgithubiojszip](httpstukgithubiojszip)

Note All browsers donrsquot support the download of big files with Data URI so you should use the lsquodownloadlsquo method for files bigger than 100kB dataimagepngbase64iVBORw0KGgoAAAANSUhEUgAAABcAAAAXCAIAAABvSEP3AAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAACXSURBVDhPtY7BDYAwDAMZhCf7b8YMxeCoatOQJhWcKGxT2zlCyaWcz8Y+X7Bs1TFVJSwIHIYyFkQufWIRVX9cNJyW1QpEo4rixaEe7JuQagAUctb7ZFYFh5MVJPBe84CVBnB42YsZRgKjFDBVg3cI9WbRwXLktQJX8cNIiFhM1ZuTWk7PIYSBhkVcLzwIiCjCxhCjlAkBqYnqFoQQ2AAAAAElFTkSuQmCC

download(swfpathimgpath[fileName])

swfpathTypestringPath to the swfobjectjs in downloadify

imgpathTypestringPath to the image of the download button

[fileName]TypestringDefaultdefaultdocxName of the file you would like the user to download

This requires to include Downloadifyjs that needs flash version 10 Have a look at the output function if you donrsquot want to depend on it This function has the advantage that it works regardless of the file size

getImageList()

this gets all images that have one of the following extension rsquogifrsquorsquojpegrsquorsquojpgrsquorsquoemfrsquorsquopngrsquoReturn format Array of Object[pathstringfilesZipFile Object]

You shouldrsquont call this method before calling applyTags() because applyTags can modify the images or their path when replacing images with other (particularly when qrCode is set to true which is not the default case) You can call this method after applyTags() without any problems

setImage(pathimgData)

pathTypeStringPath of the image given by getImageList()

imgDataTypeStringimgData in txtplain

This sets the image given by a path and an imgData in txtplainYou shouldrsquont call this method before calling applyTags() because applyTags can modify the images or their path when replacing images with other (particularly when qrCode is set to true which is not the default case) You can call this method after applyTags() without any problems

getFullText([path])

pathTypeStringDefaultworddocumentxmlThis argument determines from which document you want to get the text The main document is called worddocumentxml but they are other documents wordheader1xml wordfooter1xml

returnsTypeStringThe string containing all the text from the document

92 Docxgen methods 25

docxtemplater Documentation Release 054

This method gets only the text of a given document (not the formatting)

getTags()

This function returns the template variables contained in the opened document For example if the content of the documentxml is the following

namefirst_namephone

The function will return[

filenamedocumentxmlvars

nametruefirst_nametruephonetrue

]

If the content contains tagLoops

titlecustomernamephonecustomer

The function will return

[filenamedocumentxmlvars

titletruecustomer

nametruephonetrue

]

26 Chapter 9 Full Documentation per method

CHAPTER 10

Copyright

License

(The MIT license)

Copyright (c) 2013 Edgar Hipp

Permission is hereby granted free of charge to any person obtaining a copy of this software and associated documen-tation files (the ldquoSoftwarerdquo) to deal in the Software without restriction including without limitation the rights to usecopy modify merge publish distribute sublicense andor sell copies of the Software and to permit persons to whomthe Software is furnished to do so subject to the following conditions

The above copyright notice and this permission notice shall be included in all copies or substantial portions of theSoftware

THE SOFTWARE IS PROVIDED ldquoAS ISrdquo WITHOUT WARRANTY OF ANY KIND EXPRESS OR IMPLIEDINCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY FITNESS FOR A PAR-TICULAR PURPOSE AND NONINFRINGEMENT IN NO EVENT SHALL THE AUTHORS OR COPYRIGHTHOLDERS BE LIABLE FOR ANY CLAIM DAMAGES OR OTHER LIABILITY WHETHER IN AN ACTIONOF CONTRACT TORT OR OTHERWISE ARISING FROM OUT OF OR IN CONNECTION WITH THE SOFT-WARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE

27

docxtemplater Documentation Release 054

28 Chapter 10 Copyright

CHAPTER 11

Demos

Including

bull Replace Variables

bull Formating

bull Angular Parsing

bull Loops

bull Loops and tables

bull Lists

bull Replacing images

bull Naming the output

bull Using QrCodes

bull Replacing many images with QrCode

bull Raw Xml Insertion

29

docxtemplater Documentation Release 054

30 Chapter 11 Demos

CHAPTER 12

Indices and tables

bull genindex

bull modindex

bull search

31

docxtemplater Documentation Release 054

32 Chapter 12 Indices and tables

Index

CCommand Line Interface (CLI) 20Configuration 17Copyright 26

FFull_doc 21

GGenerate a Document 13Goals 1

IInstallation 7

Pplatform_support 3

SSyntax 9

33

  • Goals
    • Why you should use a library for this
      • Platform Support
      • Dependencies
      • Installation
        • Node
        • Browser
          • Syntax
            • Synopsis
            • Tag types
            • Loop syntax
            • Dash syntax
            • Inverted Selections
              • Generate a document
                • Loading a document
                • Setting the tags
                • Applying the tags
                • Outputing the document
                  • Configuration
                    • Image Replacing
                    • Angular Parser
                    • Intelligent LoopTagging
                      • Command Line Interface (CLI)
                        • Configjson Syntax
                          • Full Documentation per method
                            • Creating a new Docxgen Object
                            • Docxgen methods
                              • Copyright
                              • Demos
                              • Indices and tables
Page 28: Release 0.5€¦ · Docx is a zipped format that contains some xml. If you want to build a simple replace {tag} If you want to build a simple replace {tag} by value system, it can

docxtemplater Documentation Release 054

arraybuffer the result will be a ArrayBuffer containing the zip This requires a compatible browserblob the result will be a Blob containing the zip This requires a compatible browsernodebuffer the result will be a nodejs Buffer containing the zip This requires nodejs

This function creates the docx file and downloads it on the userrsquos computer The name of the file is downloaddocx for Chrome and some akward file names for Firefox VEeTHCfSdocxpartdocx and canrsquot be changed because it is handled by the browserFor more informations about how to solve this problem see the Filename Problems section on [httpstukgithubiojszip](httpstukgithubiojszip)

Note All browsers donrsquot support the download of big files with Data URI so you should use the lsquodownloadlsquo method for files bigger than 100kB dataimagepngbase64iVBORw0KGgoAAAANSUhEUgAAABcAAAAXCAIAAABvSEP3AAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAACXSURBVDhPtY7BDYAwDAMZhCf7b8YMxeCoatOQJhWcKGxT2zlCyaWcz8Y+X7Bs1TFVJSwIHIYyFkQufWIRVX9cNJyW1QpEo4rixaEe7JuQagAUctb7ZFYFh5MVJPBe84CVBnB42YsZRgKjFDBVg3cI9WbRwXLktQJX8cNIiFhM1ZuTWk7PIYSBhkVcLzwIiCjCxhCjlAkBqYnqFoQQ2AAAAAElFTkSuQmCC

download(swfpathimgpath[fileName])

swfpathTypestringPath to the swfobjectjs in downloadify

imgpathTypestringPath to the image of the download button

[fileName]TypestringDefaultdefaultdocxName of the file you would like the user to download

This requires to include Downloadifyjs that needs flash version 10 Have a look at the output function if you donrsquot want to depend on it This function has the advantage that it works regardless of the file size

getImageList()

this gets all images that have one of the following extension rsquogifrsquorsquojpegrsquorsquojpgrsquorsquoemfrsquorsquopngrsquoReturn format Array of Object[pathstringfilesZipFile Object]

You shouldrsquont call this method before calling applyTags() because applyTags can modify the images or their path when replacing images with other (particularly when qrCode is set to true which is not the default case) You can call this method after applyTags() without any problems

setImage(pathimgData)

pathTypeStringPath of the image given by getImageList()

imgDataTypeStringimgData in txtplain

This sets the image given by a path and an imgData in txtplainYou shouldrsquont call this method before calling applyTags() because applyTags can modify the images or their path when replacing images with other (particularly when qrCode is set to true which is not the default case) You can call this method after applyTags() without any problems

getFullText([path])

pathTypeStringDefaultworddocumentxmlThis argument determines from which document you want to get the text The main document is called worddocumentxml but they are other documents wordheader1xml wordfooter1xml

returnsTypeStringThe string containing all the text from the document

92 Docxgen methods 25

docxtemplater Documentation Release 054

This method gets only the text of a given document (not the formatting)

getTags()

This function returns the template variables contained in the opened document For example if the content of the documentxml is the following

namefirst_namephone

The function will return[

filenamedocumentxmlvars

nametruefirst_nametruephonetrue

]

If the content contains tagLoops

titlecustomernamephonecustomer

The function will return

[filenamedocumentxmlvars

titletruecustomer

nametruephonetrue

]

26 Chapter 9 Full Documentation per method

CHAPTER 10

Copyright

License

(The MIT license)

Copyright (c) 2013 Edgar Hipp

Permission is hereby granted free of charge to any person obtaining a copy of this software and associated documen-tation files (the ldquoSoftwarerdquo) to deal in the Software without restriction including without limitation the rights to usecopy modify merge publish distribute sublicense andor sell copies of the Software and to permit persons to whomthe Software is furnished to do so subject to the following conditions

The above copyright notice and this permission notice shall be included in all copies or substantial portions of theSoftware

THE SOFTWARE IS PROVIDED ldquoAS ISrdquo WITHOUT WARRANTY OF ANY KIND EXPRESS OR IMPLIEDINCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY FITNESS FOR A PAR-TICULAR PURPOSE AND NONINFRINGEMENT IN NO EVENT SHALL THE AUTHORS OR COPYRIGHTHOLDERS BE LIABLE FOR ANY CLAIM DAMAGES OR OTHER LIABILITY WHETHER IN AN ACTIONOF CONTRACT TORT OR OTHERWISE ARISING FROM OUT OF OR IN CONNECTION WITH THE SOFT-WARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE

27

docxtemplater Documentation Release 054

28 Chapter 10 Copyright

CHAPTER 11

Demos

Including

bull Replace Variables

bull Formating

bull Angular Parsing

bull Loops

bull Loops and tables

bull Lists

bull Replacing images

bull Naming the output

bull Using QrCodes

bull Replacing many images with QrCode

bull Raw Xml Insertion

29

docxtemplater Documentation Release 054

30 Chapter 11 Demos

CHAPTER 12

Indices and tables

bull genindex

bull modindex

bull search

31

docxtemplater Documentation Release 054

32 Chapter 12 Indices and tables

Index

CCommand Line Interface (CLI) 20Configuration 17Copyright 26

FFull_doc 21

GGenerate a Document 13Goals 1

IInstallation 7

Pplatform_support 3

SSyntax 9

33

  • Goals
    • Why you should use a library for this
      • Platform Support
      • Dependencies
      • Installation
        • Node
        • Browser
          • Syntax
            • Synopsis
            • Tag types
            • Loop syntax
            • Dash syntax
            • Inverted Selections
              • Generate a document
                • Loading a document
                • Setting the tags
                • Applying the tags
                • Outputing the document
                  • Configuration
                    • Image Replacing
                    • Angular Parser
                    • Intelligent LoopTagging
                      • Command Line Interface (CLI)
                        • Configjson Syntax
                          • Full Documentation per method
                            • Creating a new Docxgen Object
                            • Docxgen methods
                              • Copyright
                              • Demos
                              • Indices and tables
Page 29: Release 0.5€¦ · Docx is a zipped format that contains some xml. If you want to build a simple replace {tag} If you want to build a simple replace {tag} by value system, it can

docxtemplater Documentation Release 054

This method gets only the text of a given document (not the formatting)

getTags()

This function returns the template variables contained in the opened document For example if the content of the documentxml is the following

namefirst_namephone

The function will return[

filenamedocumentxmlvars

nametruefirst_nametruephonetrue

]

If the content contains tagLoops

titlecustomernamephonecustomer

The function will return

[filenamedocumentxmlvars

titletruecustomer

nametruephonetrue

]

26 Chapter 9 Full Documentation per method

CHAPTER 10

Copyright

License

(The MIT license)

Copyright (c) 2013 Edgar Hipp

Permission is hereby granted free of charge to any person obtaining a copy of this software and associated documen-tation files (the ldquoSoftwarerdquo) to deal in the Software without restriction including without limitation the rights to usecopy modify merge publish distribute sublicense andor sell copies of the Software and to permit persons to whomthe Software is furnished to do so subject to the following conditions

The above copyright notice and this permission notice shall be included in all copies or substantial portions of theSoftware

THE SOFTWARE IS PROVIDED ldquoAS ISrdquo WITHOUT WARRANTY OF ANY KIND EXPRESS OR IMPLIEDINCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY FITNESS FOR A PAR-TICULAR PURPOSE AND NONINFRINGEMENT IN NO EVENT SHALL THE AUTHORS OR COPYRIGHTHOLDERS BE LIABLE FOR ANY CLAIM DAMAGES OR OTHER LIABILITY WHETHER IN AN ACTIONOF CONTRACT TORT OR OTHERWISE ARISING FROM OUT OF OR IN CONNECTION WITH THE SOFT-WARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE

27

docxtemplater Documentation Release 054

28 Chapter 10 Copyright

CHAPTER 11

Demos

Including

bull Replace Variables

bull Formating

bull Angular Parsing

bull Loops

bull Loops and tables

bull Lists

bull Replacing images

bull Naming the output

bull Using QrCodes

bull Replacing many images with QrCode

bull Raw Xml Insertion

29

docxtemplater Documentation Release 054

30 Chapter 11 Demos

CHAPTER 12

Indices and tables

bull genindex

bull modindex

bull search

31

docxtemplater Documentation Release 054

32 Chapter 12 Indices and tables

Index

CCommand Line Interface (CLI) 20Configuration 17Copyright 26

FFull_doc 21

GGenerate a Document 13Goals 1

IInstallation 7

Pplatform_support 3

SSyntax 9

33

  • Goals
    • Why you should use a library for this
      • Platform Support
      • Dependencies
      • Installation
        • Node
        • Browser
          • Syntax
            • Synopsis
            • Tag types
            • Loop syntax
            • Dash syntax
            • Inverted Selections
              • Generate a document
                • Loading a document
                • Setting the tags
                • Applying the tags
                • Outputing the document
                  • Configuration
                    • Image Replacing
                    • Angular Parser
                    • Intelligent LoopTagging
                      • Command Line Interface (CLI)
                        • Configjson Syntax
                          • Full Documentation per method
                            • Creating a new Docxgen Object
                            • Docxgen methods
                              • Copyright
                              • Demos
                              • Indices and tables
Page 30: Release 0.5€¦ · Docx is a zipped format that contains some xml. If you want to build a simple replace {tag} If you want to build a simple replace {tag} by value system, it can

CHAPTER 10

Copyright

License

(The MIT license)

Copyright (c) 2013 Edgar Hipp

Permission is hereby granted free of charge to any person obtaining a copy of this software and associated documen-tation files (the ldquoSoftwarerdquo) to deal in the Software without restriction including without limitation the rights to usecopy modify merge publish distribute sublicense andor sell copies of the Software and to permit persons to whomthe Software is furnished to do so subject to the following conditions

The above copyright notice and this permission notice shall be included in all copies or substantial portions of theSoftware

THE SOFTWARE IS PROVIDED ldquoAS ISrdquo WITHOUT WARRANTY OF ANY KIND EXPRESS OR IMPLIEDINCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY FITNESS FOR A PAR-TICULAR PURPOSE AND NONINFRINGEMENT IN NO EVENT SHALL THE AUTHORS OR COPYRIGHTHOLDERS BE LIABLE FOR ANY CLAIM DAMAGES OR OTHER LIABILITY WHETHER IN AN ACTIONOF CONTRACT TORT OR OTHERWISE ARISING FROM OUT OF OR IN CONNECTION WITH THE SOFT-WARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE

27

docxtemplater Documentation Release 054

28 Chapter 10 Copyright

CHAPTER 11

Demos

Including

bull Replace Variables

bull Formating

bull Angular Parsing

bull Loops

bull Loops and tables

bull Lists

bull Replacing images

bull Naming the output

bull Using QrCodes

bull Replacing many images with QrCode

bull Raw Xml Insertion

29

docxtemplater Documentation Release 054

30 Chapter 11 Demos

CHAPTER 12

Indices and tables

bull genindex

bull modindex

bull search

31

docxtemplater Documentation Release 054

32 Chapter 12 Indices and tables

Index

CCommand Line Interface (CLI) 20Configuration 17Copyright 26

FFull_doc 21

GGenerate a Document 13Goals 1

IInstallation 7

Pplatform_support 3

SSyntax 9

33

  • Goals
    • Why you should use a library for this
      • Platform Support
      • Dependencies
      • Installation
        • Node
        • Browser
          • Syntax
            • Synopsis
            • Tag types
            • Loop syntax
            • Dash syntax
            • Inverted Selections
              • Generate a document
                • Loading a document
                • Setting the tags
                • Applying the tags
                • Outputing the document
                  • Configuration
                    • Image Replacing
                    • Angular Parser
                    • Intelligent LoopTagging
                      • Command Line Interface (CLI)
                        • Configjson Syntax
                          • Full Documentation per method
                            • Creating a new Docxgen Object
                            • Docxgen methods
                              • Copyright
                              • Demos
                              • Indices and tables
Page 31: Release 0.5€¦ · Docx is a zipped format that contains some xml. If you want to build a simple replace {tag} If you want to build a simple replace {tag} by value system, it can

docxtemplater Documentation Release 054

28 Chapter 10 Copyright

CHAPTER 11

Demos

Including

bull Replace Variables

bull Formating

bull Angular Parsing

bull Loops

bull Loops and tables

bull Lists

bull Replacing images

bull Naming the output

bull Using QrCodes

bull Replacing many images with QrCode

bull Raw Xml Insertion

29

docxtemplater Documentation Release 054

30 Chapter 11 Demos

CHAPTER 12

Indices and tables

bull genindex

bull modindex

bull search

31

docxtemplater Documentation Release 054

32 Chapter 12 Indices and tables

Index

CCommand Line Interface (CLI) 20Configuration 17Copyright 26

FFull_doc 21

GGenerate a Document 13Goals 1

IInstallation 7

Pplatform_support 3

SSyntax 9

33

  • Goals
    • Why you should use a library for this
      • Platform Support
      • Dependencies
      • Installation
        • Node
        • Browser
          • Syntax
            • Synopsis
            • Tag types
            • Loop syntax
            • Dash syntax
            • Inverted Selections
              • Generate a document
                • Loading a document
                • Setting the tags
                • Applying the tags
                • Outputing the document
                  • Configuration
                    • Image Replacing
                    • Angular Parser
                    • Intelligent LoopTagging
                      • Command Line Interface (CLI)
                        • Configjson Syntax
                          • Full Documentation per method
                            • Creating a new Docxgen Object
                            • Docxgen methods
                              • Copyright
                              • Demos
                              • Indices and tables
Page 32: Release 0.5€¦ · Docx is a zipped format that contains some xml. If you want to build a simple replace {tag} If you want to build a simple replace {tag} by value system, it can

CHAPTER 11

Demos

Including

bull Replace Variables

bull Formating

bull Angular Parsing

bull Loops

bull Loops and tables

bull Lists

bull Replacing images

bull Naming the output

bull Using QrCodes

bull Replacing many images with QrCode

bull Raw Xml Insertion

29

docxtemplater Documentation Release 054

30 Chapter 11 Demos

CHAPTER 12

Indices and tables

bull genindex

bull modindex

bull search

31

docxtemplater Documentation Release 054

32 Chapter 12 Indices and tables

Index

CCommand Line Interface (CLI) 20Configuration 17Copyright 26

FFull_doc 21

GGenerate a Document 13Goals 1

IInstallation 7

Pplatform_support 3

SSyntax 9

33

  • Goals
    • Why you should use a library for this
      • Platform Support
      • Dependencies
      • Installation
        • Node
        • Browser
          • Syntax
            • Synopsis
            • Tag types
            • Loop syntax
            • Dash syntax
            • Inverted Selections
              • Generate a document
                • Loading a document
                • Setting the tags
                • Applying the tags
                • Outputing the document
                  • Configuration
                    • Image Replacing
                    • Angular Parser
                    • Intelligent LoopTagging
                      • Command Line Interface (CLI)
                        • Configjson Syntax
                          • Full Documentation per method
                            • Creating a new Docxgen Object
                            • Docxgen methods
                              • Copyright
                              • Demos
                              • Indices and tables
Page 33: Release 0.5€¦ · Docx is a zipped format that contains some xml. If you want to build a simple replace {tag} If you want to build a simple replace {tag} by value system, it can

docxtemplater Documentation Release 054

30 Chapter 11 Demos

CHAPTER 12

Indices and tables

bull genindex

bull modindex

bull search

31

docxtemplater Documentation Release 054

32 Chapter 12 Indices and tables

Index

CCommand Line Interface (CLI) 20Configuration 17Copyright 26

FFull_doc 21

GGenerate a Document 13Goals 1

IInstallation 7

Pplatform_support 3

SSyntax 9

33

  • Goals
    • Why you should use a library for this
      • Platform Support
      • Dependencies
      • Installation
        • Node
        • Browser
          • Syntax
            • Synopsis
            • Tag types
            • Loop syntax
            • Dash syntax
            • Inverted Selections
              • Generate a document
                • Loading a document
                • Setting the tags
                • Applying the tags
                • Outputing the document
                  • Configuration
                    • Image Replacing
                    • Angular Parser
                    • Intelligent LoopTagging
                      • Command Line Interface (CLI)
                        • Configjson Syntax
                          • Full Documentation per method
                            • Creating a new Docxgen Object
                            • Docxgen methods
                              • Copyright
                              • Demos
                              • Indices and tables
Page 34: Release 0.5€¦ · Docx is a zipped format that contains some xml. If you want to build a simple replace {tag} If you want to build a simple replace {tag} by value system, it can

CHAPTER 12

Indices and tables

bull genindex

bull modindex

bull search

31

docxtemplater Documentation Release 054

32 Chapter 12 Indices and tables

Index

CCommand Line Interface (CLI) 20Configuration 17Copyright 26

FFull_doc 21

GGenerate a Document 13Goals 1

IInstallation 7

Pplatform_support 3

SSyntax 9

33

  • Goals
    • Why you should use a library for this
      • Platform Support
      • Dependencies
      • Installation
        • Node
        • Browser
          • Syntax
            • Synopsis
            • Tag types
            • Loop syntax
            • Dash syntax
            • Inverted Selections
              • Generate a document
                • Loading a document
                • Setting the tags
                • Applying the tags
                • Outputing the document
                  • Configuration
                    • Image Replacing
                    • Angular Parser
                    • Intelligent LoopTagging
                      • Command Line Interface (CLI)
                        • Configjson Syntax
                          • Full Documentation per method
                            • Creating a new Docxgen Object
                            • Docxgen methods
                              • Copyright
                              • Demos
                              • Indices and tables
Page 35: Release 0.5€¦ · Docx is a zipped format that contains some xml. If you want to build a simple replace {tag} If you want to build a simple replace {tag} by value system, it can

docxtemplater Documentation Release 054

32 Chapter 12 Indices and tables

Index

CCommand Line Interface (CLI) 20Configuration 17Copyright 26

FFull_doc 21

GGenerate a Document 13Goals 1

IInstallation 7

Pplatform_support 3

SSyntax 9

33

  • Goals
    • Why you should use a library for this
      • Platform Support
      • Dependencies
      • Installation
        • Node
        • Browser
          • Syntax
            • Synopsis
            • Tag types
            • Loop syntax
            • Dash syntax
            • Inverted Selections
              • Generate a document
                • Loading a document
                • Setting the tags
                • Applying the tags
                • Outputing the document
                  • Configuration
                    • Image Replacing
                    • Angular Parser
                    • Intelligent LoopTagging
                      • Command Line Interface (CLI)
                        • Configjson Syntax
                          • Full Documentation per method
                            • Creating a new Docxgen Object
                            • Docxgen methods
                              • Copyright
                              • Demos
                              • Indices and tables
Page 36: Release 0.5€¦ · Docx is a zipped format that contains some xml. If you want to build a simple replace {tag} If you want to build a simple replace {tag} by value system, it can

Index

CCommand Line Interface (CLI) 20Configuration 17Copyright 26

FFull_doc 21

GGenerate a Document 13Goals 1

IInstallation 7

Pplatform_support 3

SSyntax 9

33

  • Goals
    • Why you should use a library for this
      • Platform Support
      • Dependencies
      • Installation
        • Node
        • Browser
          • Syntax
            • Synopsis
            • Tag types
            • Loop syntax
            • Dash syntax
            • Inverted Selections
              • Generate a document
                • Loading a document
                • Setting the tags
                • Applying the tags
                • Outputing the document
                  • Configuration
                    • Image Replacing
                    • Angular Parser
                    • Intelligent LoopTagging
                      • Command Line Interface (CLI)
                        • Configjson Syntax
                          • Full Documentation per method
                            • Creating a new Docxgen Object
                            • Docxgen methods
                              • Copyright
                              • Demos
                              • Indices and tables