Code Monkey home page Code Monkey logo

docx-templates's People

Contributors

abs avatar betaweb avatar brandondr avatar brockfanning avatar brummelte avatar davidjb avatar dependabot[bot] avatar dseiler-itg avatar emilong avatar guigrpa avatar jjhbw avatar johannordin avatar jonathanlsignot avatar jwasnoggin avatar khaled-iva-docs avatar lwallent avatar mathe42 avatar nheisterkamp avatar paulovieira avatar petervelosy avatar roxus avatar skfrost19 avatar speedpro avatar suchirad avatar szazo avatar vdechef avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

docx-templates's Issues

Error when using file from Office365

Whenever i download a template created by the online Office 365
I get the bottom error

  • I use Node.js and this library on Ubuntu 16.04
(node:2170) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'async' of null
    at zipGetText (/home/itamar/Documents/export doc/node_modules/docx-templates/lib/zip.js:24:28)
    at _callee2$ (/home/itamar/Documents/export doc/node_modules/docx-templates/lib/mainBrowser.js:84:40)
    at tryCatch (/home/itamar/Documents/export doc/node_modules/regenerator-runtime/runtime.js:65:40)
    at Generator.invoke [as _invoke] (/home/itamar/Documents/export doc/node_modules/regenerator-runtime/runtime.js:303:22)
    at Generator.prototype.(anonymous function) [as next] (/home/itamar/Documents/export doc/node_modules/regenerator-runtime/runtime.js:117:21)
    at step (/home/itamar/Documents/export doc/node_modules/babel-runtime/helpers/asyncToGenerator.js:17:30)
    at /home/itamar/Documents/export doc/node_modules/babel-runtime/helpers/asyncToGenerator.js:28:13
    at <anonymous>
(node:2170) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:2170) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

IMAGE command doesn't support .svg files

Hi!
I have noticed that trying to insert an svg file in the word document with the command +++IMAGE insertSvg()+++ always ends with the document broken and an image that cannot be displayed

image

Is there any plan to support SVG files? or maybe I'm missing something?
I'm using the same function to load a .png file and everything goes well.

LINK style troubles

I'm getting some problems, when creating hyperlink by +++LINK method. The link is creating and works well, when I click it, but it doesn't have "hyperlink" style and is not colored in "hyperlink" color. When I try to create it with +++HTML method, it's creating well, with proper style, but html method creates not a text fragment, but a paragraph. What am I doing wrong?

The template code is simple, as in the docs: +++LINK ({url:$item.url, label:$item.name})+++

Error Cannot read property 'split' of undefined

When I use docx-templates version 2.9.0-rc.1 on my project, which uses meteor 1.7.0.5, I got the error:

Uncaught TypeError: Cannot read property 'split' of undefined

If I comment out and do not use docx-templates, the project run normally.

Use non Integer values on image sizes

First of all, thank you for this awesome library! It is helping me a lot in a printing module (browser usage).

That module prints bills/licenses and I'm facing some issues when trying to put images of specific sizes inside one of that documents.

As docx-templates use an HTMLImageElement, just non negative integers can be used as values for width and height attributes. This matter limits a lot the posibilites of place an image within the document.

Does anyone know any way to deal with it? Does someone comes up with how decimal values could be used setting the sizes of an image?

Thanks in advance

Insert Images

Hey we love this project, but we are looking for a way to insert images. Which in our case the images are unique barcodes for each .docx we create. Is this something that would be doable? Willing to help out.

Allow passing zip compression parameters as options.

Hey, first and foremost... I really appreciate this code.

I am going to be pushing my files over an api, and attaching them in a database. Adding a small amount of compression is extremely helpful for file size. By adding the compression options on jszip, the size difference is immense. Could that be easily added to the docx-templates options for pass through?

zip.js line 30

 _jszip2.default.prototype.toFile = function toFile() {
  // compression and compressionOptions added
   return this.generateAsync({ type: 'uint8array',  compression: "DEFLATE", compressionOptions : 
  {level:1} });
 };

As another size idea, I pulled the white space out of the document.xml, which generally saves a good amount of space as well. I understand why you'd want the whitespace in development. But perhaps again a way to extend with an option..... or my quick and dirty current code.

mainBrowser.js line 172

      case 43:
        DEBUG && log.debug('Writing report...');
     // LINE ADDED            
        reportXml = reportXml.replace(/\s+/g, ' ').trim();
        zip.setText(templatePath + '/document.xml', reportXml);

With these two additives my test file went from a 67kb template generating a 1301kb file. To a 67kb template generating a 87kb file.

Add support for rich text formatting

I would like to use something like Quill to display rich text input for users. Then I would like to export the result of the formatted input to a docx file.

It is possible to insert html snippets in a docx file with Altchunk. I did some tests manually, and by modifying Content_Types.xml, document.xml, and document.xml.res, I am able to display a html file wherever I want in the document.

By adding support for a +++HTML+++ tag, it would provide a way to add formatting to docx-templates, without having to support the code needed for parsing and converting the formatting stuff.

What do you think ? I can work on a PR for this.

Replacing template images - Header/Footer

Hi,

I am using the IMAGE command in the body of my document but it does not work when trying to insert an image into the "Header" of my template so I am still using the following for inserting a logo into the header of my document.

replaceImages: {
      'image1.png': getImageData(logo),
    },

I notice that this is now deprecated as of v2.4.0 and may be removed in future releases. Removal could cause issues unless the IMAGE command is working in the header/footer before it is it is removed.

Many Thanks

Iain

No way to add paragraphs in literal xml

Greetings! Loving your project. However, the literal XML functionality is not very useful in its current shape. Reason being is that you cannot add a table, new paragraphs and a lot of other XML content, because the parent paragraph is not being removed after the XML content is injected, which results in invalid XML. Any plans to change that in the future?

Bug:

Thank you so much for your cool project. When I install this (test with Master and version 2.9.0) I get the following bugs.

"@angular/core": "~7.1.0",
dyn-124-19:app schoeni$ npm start

> [email protected] start /Users/xxxxxxx/Projects/project_taskheld/taskheld
> ng serve

** Angular Live Development Server is listening on localhost:4200, open your browser on http://localhost:4200/ **
                                                                                          
Date: 2019-01-26T07:50:35.915Z
Hash: 2c784a2867112d0741d9
Time: 14475ms
chunk {main} main.js, main.js.map (main) 70.1 kB [initial] [rendered]
chunk {polyfills} polyfills.js, polyfills.js.map (polyfills) 223 kB [initial] [rendered]
chunk {runtime} runtime.js, runtime.js.map (runtime) 6.08 kB [entry] [rendered]
chunk {styles} styles.js, styles.js.map (styles) 348 kB [initial] [rendered]
chunk {vendor} vendor.js, vendor.js.map (vendor) 9.58 MB [initial] [rendered]

WARNING in ./node_modules/vm2/lib/main.js 146:26-33
Critical dependency: require function is used in a way in which dependencies cannot be statically extracted

WARNING in ./node_modules/vm2/lib/main.js 254:3-10
Critical dependency: require function is used in a way in which dependencies cannot be statically extracted

WARNING in ./node_modules/vm2/lib/main.js 298:26-33
Critical dependency: require function is used in a way in which dependencies cannot be statically extracted

WARNING in ./node_modules/vm2/lib/main.js
Module not found: Error: Can't resolve 'coffee-script' in '/Users/schoeni/Projects/project_taskheld/taskheld/node_modules/vm2/lib'

WARNING in ./node_modules/docx-templates/node_modules/sax/lib/sax.js
Module not found: Error: Can't resolve 'stream' in '/Users/schoeni/Projects/project_taskheld/taskheld/node_modules/docx-templates/node_modules/sax/lib'

ERROR in ./node_modules/graceful-fs/polyfills.js
Module not found: Error: Can't resolve 'constants' in '/Users/schoeni/Projects/project_taskheld/taskheld/node_modules/graceful-fs'
ERROR in ./node_modules/fs-extra/lib/empty/index.js
Module not found: Error: Can't resolve 'fs' in '/Users/schoeni/Projects/project_taskheld/taskheld/node_modules/fs-extra/lib/empty'
ERROR in ./node_modules/graceful-fs/graceful-fs.js
Module not found: Error: Can't resolve 'fs' in '/Users/schoeni/Projects/project_taskheld/taskheld/node_modules/graceful-fs'
ERROR in ./node_modules/jsonfile/index.js
Module not found: Error: Can't resolve 'fs' in '/Users/schoeni/Projects/project_taskheld/taskheld/node_modules/jsonfile'
ERROR in ./node_modules/vm2/lib/main.js
Module not found: Error: Can't resolve 'fs' in '/Users/schoeni/Projects/project_taskheld/taskheld/node_modules/vm2/lib'
ERROR in ./node_modules/fs-extra/lib/util/utimes.js
Module not found: Error: Can't resolve 'os' in '/Users/schoeni/Projects/project_taskheld/taskheld/node_modules/fs-extra/lib/util'
ERROR in ./node_modules/docx-templates/lib/processTemplate.js
Module not found: Error: Can't resolve 'path' in '/Users/schoeni/Projects/project_taskheld/taskheld/node_modules/docx-templates/lib'
ERROR in ./node_modules/fs-extra/lib/copy/copy.js
Module not found: Error: Can't resolve 'path' in '/Users/schoeni/Projects/project_taskheld/taskheld/node_modules/fs-extra/lib/copy'
ERROR in ./node_modules/fs-extra/lib/copy/ncp.js
Module not found: Error: Can't resolve 'path' in '/Users/schoeni/Projects/project_taskheld/taskheld/node_modules/fs-extra/lib/copy'
ERROR in ./node_modules/fs-extra/lib/copy-sync/copy-sync.js
Module not found: Error: Can't resolve 'path' in '/Users/schoeni/Projects/project_taskheld/taskheld/node_modules/fs-extra/lib/copy-sync'
[3[39m1mERROR in ./node_modules/fs-extra/lib/empty/index.js
Module not found: Error: Can't resolve 'path' in '/Users/schoeni/Projects/project_taskheld/taskheld/node_modules/fs-extra/lib/empty'
ERROR in ./node_modules/fs-extra/lib/ensure/symlink.js
Module not found: Error: Can't resolve 'path' in '/Users/schoeni/Projects/project_taskheld/taskheld/node_modules/fs-extra/lib/ensure'
ERROR in ./node_modules/fs-extra/lib/ensure/symlink-paths.js
Module not found: Error: Can't resolve 'path' in '/Users/schoeni/Projects/project_taskheld/taskheld/node_modules/fs-extra/lib/ensure'
ERROR in ./node_modules/fs-extra/lib/ensure/link.js
Module not found: Error: Can't resolve 'path' in '/Users/schoeni/Projects/project_taskheld/taskheld/node_modules/fs-extra/lib/ensure'
ERROR in ./node_modules/fs-extra/lib/ensure/file.js
Module not found: Error: Can't resolve 'path' in '/Users/schoeni/Projects/project_taskheld/taskheld/node_modules/fs-extra/lib/ensure'
ERROR in ./node_modules/fs-extra/lib/json/output-json-sync.js
Module not found: Error: Can't resolve 'path' in '/Users/schoeni/Projects/project_taskheld/taskheld/node_modules/fs-extra/lib/json'
ERROR in ./node_modules/fs-extra/lib/json/output-json.js
Module not found: Error: Can't resolve 'path' in '/Users/schoeni/Projects/project_taskheld/taskheld/node_modules/fs-extra/lib/json'
ERROR in ./node_modules/fs-extra/lib/mkdirs/win32.js
Module not found: Error: Can't resolve 'path' in '/Users/schoeni/Projects/project_taskheld/taskheld/node_modules/fs-extra/lib/mkdirs'
ERROR in ./node_modules/fs-extra/lib/mkdirs/mkdirs-sync.js
Module not found: Error: Can't resolve 'path' in '/Users/schoeni/Projects/project_taskheld/taskheld/node_modules/fs-extra/lib/mkdirs'
ERROR in ./node_modules/fs-extra/lib/mkdirs/mkdirs.js
Module not found: Error: Can't resolve 'path' in '/Users/schoeni/Projects/project_taskheld/taskheld/node_modules/fs-extra/lib/mkdirs'
ERROR in ./node_modules/fs-extra/lib/move/index.js
Module not found: Error: Can't resolve 'path' in '/Users/schoeni/Projects/project_taskheld/taskheld/node_modules/fs-extra/lib/move'
ERROR in ./node_modules/fs-extra/lib/move-sync/index.js
Module not found: Error: Can't resolve 'path' in '/Users/schoeni/Projects/project_taskheld/taskheld/node_modules/fs-extra/lib/move-sync'
ERROR in ./node_modules/fs-extra/lib/output/index.js
Module not found: Error: Can't resolve 'path' in '/Users/schoeni/Projects/project_taskheld/taskheld/node_modules/fs-extra/lib/output'
ERROR in ./node_modules/fs-extra/lib/remove/rimraf.js
Module not found: Error: Can't resolve 'path' in '/Users/schoeni/Projects/project_taskheld/taskheld/node_modules/fs-extra/lib/remove'
ERROR in ./node_modules/fs-extra/lib/util/utimes.js
Module not found: Error: Can't resolve 'path' in '/Users/schoeni/Projects/project_taskheld/taskheld/node_modules/fs-extra/lib/util'
ERROR in ./node_modules/vm2/lib/main.js
Module not found: Error: Can't resolve 'path' in '/Users/schoeni/Projects/project_taskheld/taskheld/node_modules/vm2/lib'
ERROR in ./node_modules/docx-templates/lib/debug.js
Module not found: Error: Can't resolve 'storyboard' in '/Users/schoeni/Projects/project_taskheld/taskheld/node_modules/docx-templates/lib'
ERROR in ./node_modules/docx-templates/lib/debug.js
Module not found: Error: Can't resolve 'storyboard-listener-console' in '/Users/schoeni/Projects/project_taskheld/taskheld/node_modules/docx-templates/lib'
ERROR in ./node_modules/graceful-fs/legacy-streams.js
Module not found: Error: Can't resolve 'stream' in '/Users/schoeni/Projects/project_taskheld/taskheld/node_modules/graceful-fs'
ERROR in ./node_modules/jszip/lib/readable-stream-browser.js
Module not found: Error: Can't resolve 'stream' in '/Users/schoeni/Projects/project_taskheld/taskheld/node_modules/jszip/lib'
ERROR in ./node_modules/docx-templates/lib/jsSandbox.js
Module not found: Error: Can't resolve 'vm' in '/Users/schoeni/Projects/project_taskheld/taskheld/node_modules/docx-templates/lib'
ERROR in ./node_modules/vm2/lib/main.js
Module not found: Error: Can't resolve 'vm' in '/Users/schoeni/Projects/project_taskheld/taskheld/node_modules/vm2/lib'
β„Ή ο½’wdmο½£: Failed to compile.

Text Watermarks

Hi,

Is there any way to add a Text watermark? I have tried adding the literal XML for the watermark and I get an error in document.xml which I think is due to the watermark being located in one of the header.xml files.

<v:shape id="PowerPlusWaterMarkObject200378111" stroked="f" fillcolor="silver" o:allowincell="f" style="position:absolute;margin-left:0;margin-top:0;width:397.65pt;height:238.6pt;rotation:315;z-index:-251657216;mso-position-horizontal:center;mso-position-horizontal-relative:margin;mso-position-vertical:center;mso-position-vertical-relative:margin" type="#_x0000_t136" o:spid="_x0000_s2049">

<v:fill opacity=".5"/>

<v:textpath style="font-family:"Calibri";font-size:1pt" string="DRAFT"/>

<w10:wrap anchory="margin" anchorx="margin"/>

</v:shape>

Also if I set a watermark manually in Word in my template the generated document errors on opening.

Any help would be greatly appeciated.

Thanks

Autodetecting current width and height of image

Thanks for the great work guys! You library makes our developer lives so much easier.
I'd like to request for support for autodetecting height and width for images (or this might already be supported and im just not aware of).
I'm trying to load images of different sizes. There's currently no way for me to know the image sizes ahead. I'd like the images to just render on the document without specifying a size... OR better yet provide a size (x or y) constraint so they dont go over a specific size (proportionately). TIA!

Header/Footer images messing up the page itself

When using a Header with images and adding images in the page itself -> the first image in the page layout will be identical to the header image.

When using a Footer with images and adding images in the page itself -> all the images in the page are replaced with the footer images.

Feature request - support for different formatting in same tag

Hi,

It would be really helpful to be able to add highlighting and/or describe different formatting options within the same template tag. What i mean is pretty much the HTML equivalent of <span> and <h1>, <h2>.

Example:
I put this in the template document:
{{Introduction}}

and this as data:

'introduction': [
   '<h1>Introduction</h1>',
   '<h2>Purpose</h2>'
   '<p>This is the <span class='highlight'>purpose</span> of this document</p>'
]

or maybe this:

'introduction': [
   { 'content': 'Introduction',
     'styling': 'h1'   
   },
   { 'content': 'Purpose',
     'styling': 'h2'
    },
   { 'content': This is the __purpose__ of this document',
     'styling': 'p',
     'span': 'highlight'
    }
]

EXEC and strings

Hey again,

maybe I do something wrong but I do not get an example running with exec and text values.
Here a litte example:

+++EXEC
a = { b : β€œ5”, c : β€œ4”};
fail = (val) => val === false ? a.b : a.c;
+++

Properly handling missing variable substitutions

It there a proper and/or "suggested" way to handle situations where there are templating definitions in a .docx file but no corresponding data to fulfill it being passed in via a JSON object?

Basically, we're getting "error: Error: Error executing command:" & "xblankx is not defined" because our json does not contain the correct data in the INS statement. I assume we could just wrap everything up in an IF statement but if so, how can we properly check to see if a JSON object !== undefined

Example

+++ IF outerJSONobj !== undefined && outerJSONobj.subattribute !== undefined +++
+++INS ${outerJSONobj.subattribute}+++
+++ END-IF +++

Make docx-template work from browser

I just discovered docx-templates, and it does exactly what I need. But now I would like to use it on frontend side.
Would it be feasible to have it work from browser ? I guess that the 2 main differences would be to read/write the file (eg. providing a buffer instead of path for input/output), and the VM part.
If you think this is technically possible, I am willing to work on it.

format the text from code

HI there, in what way could you format the text from code? (for example, bold) and is there a possibility of creating tables from code?

Node 8

I'm trying to use this in node 8 and although it doesn't generate any errors, it creates corrupt documents which cannot be opened.

Is there a minimum version required?

Image alignment

First of all: Thanks for this really awesome package! It saves my life in so many ways...

It would be nice to align images with text wrapping. Is this currently supported?

Using ++HTML+++ overrides +++IMAGE+++ relationships in document.xml.rels

I'm trying to create a report from template which contains a +++HTML [...]+++ command as well as a +++IMAGE [...] +++ command. Both commands work correct on their own but the HTML command seems to remove all relationship entries in the document.xml.rels file for any image. The image itself can be found in the created report in the word/media directory.

Minimal template file to reproduce the issue: template.docx
Created report using the above template file: report.docx
Code to create the report:

const report = await createReport({
   template: this.base64ToArrayBuffer(fileData),
   additionalJsContext: {
      sigImage: async (dataUrl) => {
          const resp = await fetch(dataUrl);
          const buffer = resp.arrayBuffer
              ? await resp.arrayBuffer()
              : await resp.buffer();
           return { width: 6, height: 2, data: buffer, extension: '.png' };
       },
   },
   data: () => {
      return {
         data
      }
   }
});

Data to create the report:

{
    signatur: "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAABQgA[...]"
    targets: "<ul><li>Test</li><li>Test</li><li>Test</li></ul>"
}

Insert Page break

Can a page break somehow be inserted inside a FOR and END-FOR.

In case one is iterating over something and wish to start a new page for each item

Adding a page break from code:
<w:br w:type="page"/>

Is inserted as the literal XML :-)

Can a page break be achieved in the current version? Or is it a missing feature?

How do I generate the library after doing fork?

I just created a fork but at the moment of wanting to implement it in the folder of node_modules using npm link it does not run because it does not find the library, checking the project I see that is missing / lib. What do I have to do to generate it?
Greetings.

IMAGE doesn't support .bmp files

Hi!
Related to this issue #33 the IMAGE command doesn't support .bmp files either.

It successfully loads the image, but when you open the .docx file, word prompts the "what to repair?" window.

HTML injection doesn't work in google docs

If I use HTML rule the text is missing when I open it with google docs.
You can try to recreate by simple making docx file that contents

+++HTML `<body><span>Simplest html</span></body>`+++

If you'll open it in google docs you won't see any text.

I don't really have any clue.

Error whit lib babel-polyfill

Exception has occurred: Error
Error: Cannot find module 'babel-polyfill'
include-all attempted to require(c:\Users\jonat\Documents\signot\backend\api\services\word.js), but an error occurred::
Details:Error: Cannot find module 'babel-polyfill'
at Function.Module._resolveFilename (module.js:469:15)
at Function.Module._load (module.js:417:25)
at Module.require (module.js:497:17)
at require (internal/module.js:20:19)
at Object. (c:\Users\jonat\Documents\signot\backend\node_modules\docx-templates\lib\main.js:7:1)
at Module._compile (module.js:570:32)
at Object.Module._extensions..js (module.js:579:10)
at Module.load (module.js:487:32)
at tryModuleLoad (module.js:446:12)
at Function.Module._load (module.js:438:3)
at Module.require (module.js:497:17)
at require (internal/module.js:20:19)
at Object. (c:\Users\jonat\Documents\signot\backend\node_modules\docx-templates\lib\index.js:3:37)
at Module._compile (module.js:570:32)
at Object.Module._extensions..js (module.js:579:10)
at Module.load (module.js:487:32)
at tryModuleLoad (module.js:446:12)
at Function.Module._load (module.js:438:3)
at Module.require (module.js:497:17)
at require (internal/module.js:20:19)
at Object. (c:\Users\jonat\Documents\signot\backend\api\services\word.js:8:22)
at Module._compile (module.js:570:32)

I hab to add "babel-polyfill": "6.23.0", in package.json

browser: Can't read the data of 'the loaded zip file'

This is the code i get the error.
I am using reactjs a for front-end
Thanks

    var url = "http://localhost:3001/test.docx";
      var req = new XMLHttpRequest();
      req.open("GET", url, true);
      req.responseType = "arraybuffer";
      req.onload = function (e) {
        let returnedValue = req.response
        createReport({
          returnedValue,
          data: { 
            data: "data"
          },
        }).then(
          function(report)
          {
            saveDataToFile(
              report,
              'report.docx',
              'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
            );
          }.bind(this)
        )
        
      }.bind(this)

      req.send();

Feature request: template as Buffer, output as Buffer

It wold be nice if template support node Buffer and also output as node Buffer

something like this

let template = fs.readFileSync('./template.docx')
let report = await createReport({
    template,
    data: {id: 1},
    nodeBuffer: true, // or something else
  })
console.log('Is buffer?', report instanceof Buffer)

I try to make PR, but my laptop is Windows, some build tools are not working

vm2 breaks browser support

Docx-templates for Browser has been broken since the addition of vm2 (you can verify this easily : just try to run browser examples). The author of vm2 is aware that the library is not compatible with Browsers, and won't fix this.

I think we should find a way to import vm2 only for Node usage. Maybe using node-browser-resolve ?

Latest Angular (7) support

Hi!

I am getting errors when I use this package with Angular 7, because it does not support 'require' as the older versions did, e..g. for require('path') etc. Do you think you would be able to make it more Angular 7 friendly?

Kind regards

Index of FOR loop

Is there a way to get the index of the FOR loop? I was hoping to use it with a conditional so that it does not export content on the first time (index 0) but does for all remaining.

Error executing command: ... Cannot read property β€˜then’ of null

The template looks like this:

First: +++= user.name+++
Middle: +++= user.middle+++
Last: +++= user.last+++

Sometimes the user.middle is JavaScript null value.

const user = {
  first: "John",
  middle: null,
  last: "Smith"
}

It would be great if the module wouldn't throw in this case.

Error executing command: INS user.middle Cannot read property β€˜then’ of null

I very much like how Vue.js is behaving. It prints undefined and null values as empty strings.

I'm happy to supply a PR if this idea seems ok to the maintainer(s).

Support for begin delimiter and end delimiter?

Hello, docx-templates is really powerful. It would be really really great if begin delimiter and end delimiter are support. Something like add cmdDelimiterBegin and cmdDelimiterEnd in createReport kwargs and treat empty string command as INS:

  const report = await createReport({
    cmdDelimiterBegin: '{',
    cmdDelimiterEnd: '}',
    literalXmlDelimiter: '||',
    processLineBreaks: true,
    noSandbox: false,
    data: {foo:'hello', bar:'world'},})

and then in the docx template, write like this:

{foo}
{bar}

which is equivalent to :

{=foo}
{=bar}

which is equivalent to (current version):

+++=foo+++
+++=bar+++

Feature request: insert image

It would be nice if it can insert image in loop
something like this

+++FOR staff in staffs+++
+++IMG $staff.photo+++
+++IMG barcode($staff.code)+++
+++IMG signature($staff.code)+++
+++END-FOR+++
createReport({
  template: 'templates/myTemplate.docx',
  output: 'reports/myReport.docx',
  data: {
    staffs: [
      {code: '123456', name: 'John', surname: 'Appleseed', photo: '/path/to/photo.jpg'},
    ],
  },
  fn: {
    barcode(code) {
      return Buffer(code).toString('base64') // base64 image of barcode
    },
    async signature(code) {
      const img = await axios.get('/path/to/signature/' + code, {responseType: 'arrayBuffer'}))
      return img.toString('base64')
    },
  },
});

Or any suggestions to implement this.

Update Table of Contents (TOC) after injecting dynamic content

Is it possible to update the MS Word based TOC after a merge has taken place? As you can imagine, we're injecting a lot of content which changes the page references in the TOC and we'd like to update it in the generated/merged document instead of forcing/instructing the end recipient that they must open it and do the normal MS TOC right-click "Update Entire Table"

image

Multi-line Queries

Great work Guillermo! Just a couple of minor annoyances with multi-line queries.

Line breaks in a query don't retain white-space when sent to the query function, causing a syntax error in the database query engine.
E.g.

+++QUERY SELECT id
FROM records
USE KEY "myRecord::1234"
+++

becomes

SELECT idFROM recordsUSE KEY "myRecord::1234"

Expected behavior would be to either retain a newline character, or to replace with a single space.

The easy work-around is to add some explicit white-space at the beginning of each line, but I keep forgetting to do this after pasting a query.

I've also noticed that you must start the query on the same line as the QUERY tag, or it doesn't work.
e.g. this works

+++QUERY SELECT id
    FROM records
+++

this does not (it just resolves to null)

+++QUERY
   SELECT id
   FROM records
+++

for-loop multiple pages

When I use FOR-LOOP between multiple pages, docx was renderred but with error.

page1
FOR-LOOP
content on page 1
-- page break --
page2
content on page2
END-FOR
-- page-break --

Generate columns for a table in a FOR loop

I cannot figure out how to generate columns in a FOR loop.
Using docx-templates I can generate rows for a table, using :

My table
+++FOR elem IN elements+++
+++= $elem.number +++ : +++= $elem.text +++
+++END-FOR elem+++

The output is something like:

My table
1 : element 1
2 : element 2
3 : element 3

But I cannot figure out how to generate columns, to obtain something like :

My table
1 : element 1 2 : element 2 3 : element 3

I tried :

My table
+++FOR elem IN elements+++ +++= $elem.number +++ : +++= $elem.text +++ +++END-FOR elem

but this generates empty cells and I get something like :

My table
1 : element 1 2 : element 2 3 : element 3

v2.9.0-rc.0 cannot generate from different templates

Hi,

Since the new release I run into an issue that prevent the library from generating reports from different templates.

I'm creating service that will generate docx reports. The process is running and listening to a port. It can generate reports from different templates. Since the new release it takes only the first template from the first report to generate the other reports.

It must be a cache issue that always takes the first template used to every other report generation.

Great job on the library by the way, I really enjoy it.

Best regards,
David

Sandboxing when used in browser

As vm2 module is not available for browsers, and Node VM module is way too slow in browsers, I was wondering if Web Workers could be a solution to isolate the docx generation process ?
As webworkers provide access to Ajax and File APIs, it may proves a good alternative.

I am currently calling createReport() inside a dedicated worker, by feeding it a File object and a JSON object as input data. Everything works smooth, and I don't have access to window/localStorage/cookies from within the template.

Do you have any ideas or remarks regarding the use of webworker as a kind of security sandbox ?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    πŸ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. πŸ“ŠπŸ“ˆπŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❀️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.