Git Product home page Git Product logo

docx-templates's Introduction

Docx-templates Coverage Status npm version

Template-based docx report creation for both Node and the browser. (See the blog post).

Why?

  • Write documents naturally using Word, just adding some commands where needed for dynamic contents
  • Express your data needs (queries) in the template itself (QUERY command), in whatever query language you want (e.g. in GraphQL). This is similar to the Relay way™: in Relay, data requirements are declared alongside the React components that need the data
  • Execute JavaScript snippets (EXEC command, or ! for short)
  • Insert the result of JavaScript snippets in your document (INS, = or just nothing)
  • Embed images, hyperlinks and even HTML dynamically (IMAGE, LINK, HTML). Dynamic images can be great for on-the-fly QR codes, downloading photos straight to your reports, charts… even maps!
  • Add loops with FOR/END-FOR commands, with support for table rows, nested loops, and JavaScript processing of elements (filter, sort, etc)
  • Include contents conditionally, IF a certain JavaScript expression is truthy
  • Define custom aliases for some commands (ALIAS) — useful for writing table templates!
  • Run all JavaScript in a separate Node VM or a user-provided sandbox.
  • Include literal XML
  • Written in TypeScript, so ships with type definitions.
  • Plenty of examples in this repo (with Node, Webpack and Browserify)
  • Supports .docm templates in addition to regular .docx files.

Contributions are welcome!

Table of contents

Installation

$ npm install docx-templates

...or using yarn:

$ yarn add docx-templates

Node usage

Here is a simple example, with report data injected directly as an object:

import createReport from 'docx-templates';
import fs from 'fs';

const template = fs.readFileSync('myTemplate.docx');

const buffer = await createReport({
  template,
  data: {
    name: 'John',
    surname: 'Appleseed',
  },
});

fs.writeFileSync('report.docx', buffer)

You can also provide a sync or Promise-returning callback function (query resolver) instead of a data object:

const report = await createReport({
  template,
  data: query => graphqlServer.execute(query),
});

Your resolver callback will receive the query embedded in the template (in a QUERY command) as an argument.

Other options (with defaults):

const report = await createReport({
  // ...
  additionalJsContext: {
    // all of these will be available to JS snippets in your template commands (see below)
    foo: 'bar',
    qrCode: async url => {
      /* build QR and return image data */
    },
  },
  cmdDelimiter: '+++',
    /* default for backwards compatibility; but even better: ['{', '}'] */
  literalXmlDelimiter: '||',
  processLineBreaks: true,
  noSandbox: false,

  /**
   * Whether to fail on the first error encountered in the template. Defaults to true. Can be used to collect all errors in a template (e.g. misspelled commands) before failing.
   */
  failFast: true,

  /**
   * When set to `true`, this setting ensures createReport throws an error when the result of an INS, HTML, IMAGE, or LINK command turns out to be null or undefined,
   * as this usually indicates a mistake in the template or the invoking code (defaults to `false`).
   */
  rejectNullish: false,

  /**
   * MS Word usually autocorrects JS string literal quotes with unicode 'smart' quotes ('curly' quotes). E.g. 'aubergine' -> ‘aubergine’.
   * This causes an error when evaluating commands containing these smart quotes, as they are not valid JavaScript.
   * If you set fixSmartQuotes to 'true', these smart quotes will automatically get replaced with straight quotes (') before command evaluation.
   * Defaults to false.
   */
  fixSmartQuotes: false;

  /**
   * Maximum loop iterations allowed when walking through the template.
   * You can increase this to generate reports with large amount of FOR loop elements.
   * Tip: You can disable infinite loop protection by using the `Infinity` constant.
   * This may be useful if you implement a process timeout instead.
   * (Default: 1,000,000)
   */
  maximumWalkingDepth: 1_000_000;
});

Check out the Node examples folder.

Deno usage

You can use docx-templates in Deno! Just follow the Browser guide and import the polyfilled docx-templates bundle, for example from unpkg:

// @deno-types="https://unpkg.com/docx-templates/lib/bundled.d.ts"
import { createReport } from 'https://unpkg.com/docx-templates/lib/browser.js';

Note that you have to set noSandbox: true or bring your own sandbox with the runJs option.

Browser usage

You can use docx-templates in the browser (yay!). Just as when using docx-templates in Node, you need to provide the template contents as a Buffer-like object.

For example when the template is on your server you can get it with something like:

const template = await fetch('./template.docx').then(res => res.arrayBuffer())

Or if the user provides the template you can get a File object with:

<input type="file">

Then read this file in an ArrayBuffer, feed it to docx-templates, and download the result:

import createReport from 'docx-templates';

const onTemplateChosen = async () => {
  const template = await readFileIntoArrayBuffer(myFile);
  const report = await createReport({
    template,
    data: { name: 'John', surname: 'Appleseed' },
  });
  saveDataToFile(
    report,
    'report.docx',
    'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
  );
};

// Load the user-provided file into an ArrayBuffer
const readFileIntoArrayBuffer = fd =>
  new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.onerror = reject;
    reader.onload = () => {
      resolve(reader.result);
    };
    reader.readAsArrayBuffer(fd);
  });

You can find an example implementation of saveDataToFile() in the Webpack example.

Check out the examples using Webpack and using Browserify or you can use the browserified bundle directly as discussed below.

Polyfilled browser-ready bundle

As this library depends on the internal NodeJS modules vm, stream, util, and events, your build tools have to polyfill these modules when using the library in the browser. We provide a browser build which includes the required polyfills. Its file size is about 300K uncompressed or 85K / 70K with gzip / brotli compression).

You can import the library directly as a module using e.g. the unpkg.com CDN, like below, or you can host the /lib/browser.js bundle yourself.

import { createReport } from 'https://unpkg.com/docx-templates/lib/browser.js';

this is good for testing or prototyping but you should keep in mind that the browser.js is es2017 code which is supported by only 95% of users. If you have to support IE or old browser versions, you are better off compiling it to your target. Also see the support table for es2017 here.

Browser template compatibility caveat

Note that the JavaScript code in your .docx template will be run as-is by the browser. Transpilers like Babel can't see this code, and won't be able to polyfill it. This means that the JS code in your template needs to be compatible with the browsers you are targeting. In other words: don't use fancy modern syntax and functions in your template if you want older browsers, like IE11, to be able to render it.

Running within a Web Worker

Note that you need to disable the sandbox mode using the noSandbox: true option to be able to run createReport from within a web worker. This is because the default sandbox mode browser polyfills require access to the iframe API, which is not available from a web worker context. Make sure you are aware of the security implications of disabling the sandbox.

Writing templates

You can find several template examples in this repo:

  • SWAPI, a good example of what you can achieve embedding a template (GraphQL in this case) in your report, including a simple script for report generation. Uses the freak-ish online Star Wars GraphQL API.
  • Dynamic images: with examples of images that are dynamically downloaded or created. Check out the images-many-tiles example for a taste of this powerful feature.
  • Browser-based examples using Webpack and using Browserify.

Custom command delimiters

You can use different left/right command delimiters by passing an array to cmdDelimiter:

const report = await createReport({
  // ...
  cmdDelimiter: ['{', '}'],
})

This allows much cleaner-looking templates!

Then you can add commands and JS snippets in your template like this: {foo}, {project.name} {QUERY ...}, {FOR ...}.

When choosing a delimiter, take care not to introduce conflicts with JS syntax, especially if you are planning to use larger JS code snippets in your templates. For example, with ['{', '}'] you may run into conflicts as the brackets in your JS code may be mistaken for command delimiters. As an alternative, consider using multi-character delimiters, like {# and #} (see issue #102).

Supported commands

Currently supported commands are defined below.

Insert data with the INS command ( or using =, or nothing at all)

Inserts the result of a given JavaScript snippet as follows.

Using code like this:

 const report = await createReport({
    template,
    data: { name: 'John', surname: 'Appleseed' },
    cmdDelimiter: ['+++', '+++'],
  });

And a template like this:

+++name+++ +++surname+++

Will produce a result docx file that looks like this:

John Appleseed

Alternatively, you can use the more explicit INS (insert) command syntax.

+++INS name+++ +++INS surname+++

Note that the last evaluated expression is inserted into the document, so you can include more complex code if you wish:

+++INS
const a = Math.random();
const b = Math.round((a - 0.5) * 20);
`A number between -10 and 10: ${b}.`
+++

You can also use = as shorthand notation instead of INS:

+++= name+++ +++= surname+++

Even shorter (and with custom cmdDelimiter: ['{', '}']):

{name} {surname}

You can also access functions in the additionalJsContext parameter to createReport(), which may even return a Promise. The resolved value of the Promise will be inserted in the document.

Use JavaScript's ternary operator to implement an if-else structure:

+++= $details.year != null ? `(${$details.year})` : ''+++

QUERY

You can use GraphQL, SQL, whatever you want: the query will be passed unchanged to your data query resolver.

+++QUERY
query getData($projectId: Int!) {
  project(id: $projectId) {
    name
    details { year }
    people(sortedBy: "name") { name }
  }
}
+++

For the following sections (except where noted), we assume the following dataset:

const data = {
  project: {
    name: 'docx-templates',
    details: { year: '2016' },
    people: [{ name: 'John', since: 2015 }, { name: 'Robert', since: 2010 }],
  },
};

EXEC (!)

Executes a given JavaScript snippet, just like INS or =, but doesn't insert anything in the document. You can use EXEC, for example, to define functions or constants before using them elsewhere in your template.

+++EXEC
myFun = () => Math.random();
MY_CONSTANT = 3;
+++

+++! ANOTHER_CONSTANT = 5; +++

Usage elsewhere will then look like

+++= MY_CONSTANT +++
+++= ANOTHER_CONSTANT +++
+++= myFun() +++

A note on scoping:

When disabling sandbox mode (noSandbox: true), the scoping behaviour is slightly different. Disabling the sandbox will execute each EXEC snippet's code in a with(this){...} context, where this is the 'context' object. This 'context' object is re-used between the code snippets of your template. The critical difference outside of sandbox mode is that you are not declaring functions and variables in the global scope by default. The only way to assign to the global scope is to assign declarations as properties of the context object. This is simplified by the with(context){} wrapper: all global declarations are actually added as properties to this context object. Locally scoped declarations are not. _The above examples should work in both noSandbox: true and noSandbox: false.

This example declares the test function in the context object, making it callable from another snippet.

test = () => {};

While the below example only declares test in the local scope of the snippet, meaning it gets garbage collected after the snippet has executed.

function test() {};

IMAGE

Includes an image with the data resulting from evaluating a JavaScript snippet:

+++IMAGE qrCode(project.url)+++

In this case, we use a function from additionalJsContext object passed to createReport() that looks like this:

  additionalJsContext: {
    qrCode: url => {
      const dataUrl = createQrImage(url, { size: 500 });
      const data = dataUrl.slice('data:image/gif;base64,'.length);
      return { width: 6, height: 6, data, extension: '.gif' };
    },
  }

The JS snippet must return an image object or a Promise of an image object, containing:

  • width: desired width of the image on the page in cm. Note that the aspect ratio should match that of the input image to avoid stretching.
  • height desired height of the image on the page in cm.
  • data: either an ArrayBuffer or a base64 string with the image data
  • extension: one of '.png', '.gif', '.jpg', '.jpeg', '.svg'.
  • thumbnail [optional]: when injecting an SVG image, a fallback non-SVG (png/jpg/gif, etc.) image can be provided. This thumbnail is used when SVG images are not supported (e.g. older versions of Word) or when the document is previewed by e.g. Windows Explorer. See usage example below.
  • alt [optional]: optional alt text.
  • rotation [optional]: optional rotation in degrees, with positive angles moving clockwise.
  • caption [optional]: optional caption displayed below the image

In the .docx template:

+++IMAGE injectSvg()+++

Note that you can center the image by centering the IMAGE command in the template.

In the createReport call:

additionalJsContext: {
  injectSvg: () => {
      const svg_data = Buffer.from(`<svg  xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
                                  <rect x="10" y="10" height="100" width="100" style="stroke:#ff0000; fill: #0000ff"/>
                                </svg>`, 'utf-8');

      // Providing a thumbnail is technically optional, as newer versions of Word will just ignore it.
      const thumbnail = {
        data: fs.readFileSync('sample.png'),
        extension: '.png',
      };
      return { width: 6, height: 6, data: svg_data, extension: '.svg', thumbnail };                    
    }
  }

LINK

Includes a hyperlink with the data resulting from evaluating a JavaScript snippet:

+++LINK ({ url: project.url, label: project.name })+++

If the label is not specified, the URL is used as a label.

HTML

Takes the HTML resulting from evaluating a JavaScript snippet and converts it to Word contents.

Important: This uses altchunk, which is only supported in Microsoft Word, and not in e.g. LibreOffice or Google Docs.

+++HTML `
<meta charset="UTF-8">
<body>
  <h1>${$film.title}</h1>
  <h3>${$film.releaseDate.slice(0, 4)}</h3>
  <p>
    <strong style="color: red;">This paragraph should be red and strong</strong>
  </p>
</body>
`+++

FOR and END-FOR

Loop over a group of elements (resulting from the evaluation of a JavaScript expression):

+++FOR person IN project.people+++
+++INS $person.name+++ (since +++INS $person.since+++)
+++END-FOR person+++

Note that inside the loop, the variable relative to the current element being processed must be prefixed with $.

It is possible to get the current element index of the inner-most loop with the variable $idx, starting from 0. For example:

+++FOR company IN companies+++
Company (+++$idx+++): +++INS $company.name+++
Executives:
+++FOR executive IN $company.executives+++
-	+++$idx+++ +++$executive+++
+++END-FOR executive+++
+++END-FOR company+++

Since JavaScript expressions are supported, you can for example filter the loop domain:

+++FOR person IN project.people.filter(person => person.since > 2013)+++
...

FOR loops also work over table rows:

----------------------------------------------------------
| Name                         | Since                   |
----------------------------------------------------------
| +++FOR person IN             |                         |
| project.people+++            |                         |
----------------------------------------------------------
| +++INS $person.name+++       | +++INS $person.since+++ |
----------------------------------------------------------
| +++END-FOR person+++         |                         |
----------------------------------------------------------

And let you dynamically generate columns:

+-------------------------------+--------------------+------------------------+
| +++ FOR row IN rows+++        |                    |                        |
+===============================+====================+========================+
| +++ FOR column IN columns +++ | +++INS $row+++     | +++ END-FOR column +++ |
|                               |                    |                        |
|                               | Some cell content  |                        |
|                               |                    |                        |
|                               | +++INS $column+++  |                        |
+-------------------------------+--------------------+------------------------+
| +++ END-FOR row+++            |                    |                        |
+-------------------------------+--------------------+------------------------+

Finally, you can nest loops (this example assumes a different data set):

+++FOR company IN companies+++
+++INS $company.name+++
+++FOR person IN $company.people+++
* +++INS $person.firstName+++
+++FOR project IN $person.projects+++
    - +++INS $project.name+++
+++END-FOR project+++
+++END-FOR person+++

+++END-FOR company+++

IF and END-IF

Include contents conditionally (depending on the evaluation of a JavaScript expression):

+++IF person.name === 'Guillermo'+++
+++= person.fullName +++
+++END-IF+++

Similarly to the FOR command, it also works over table rows. You can also nest IF commands and mix & match IF and FOR commands. In fact, for the technically inclined: the IF command is implemented as a FOR command with 1 or 0 iterations, depending on the expression value.

ALIAS (and alias resolution with *)

Define a name for a complete command (especially useful for formatting tables):

+++ALIAS name INS $person.name+++
+++ALIAS since INS $person.since+++

----------------------------------------------------------
| Name                         | Since                   |
----------------------------------------------------------
| +++FOR person IN             |                         |
| project.people+++            |                         |
----------------------------------------------------------
| +++*name+++                  | +++*since+++            |
----------------------------------------------------------
| +++END-FOR person+++         |                         |
----------------------------------------------------------

Inserting literal XML

You can also directly insert Office Open XML markup into the document using the literalXmlDelimiter, which is by default set to ||.

E.g. if you have a template like this:

+++INS text+++
await createReport({
  template,
  data: { text: 'foo||<w:br/>||bar' },
}

See http://officeopenxml.com/anatomyofOOXML.php for a good reference of the internal XML structure of a docx file.

Error handling

By default, the Promise returned by createReport will reject with an error immediately when a problem is encountered in the template, such as a bad command (i.e. it 'fails fast'). In some cases, however, you may want to collect all errors that may exist in the template before failing. For example, this is useful when you are letting your users create templates interactively. You can disable fast-failing by providing the failFast: false parameter as shown below. This will make createReport reject with an array of errors instead of a single error so you can get a more complete picture of what is wrong with the template.

try {
  const report = await createReport({
    template,
    data: {
      name: 'John',
      surname: 'Appleseed',
    },
    failFast: false,
  });
} catch (errors) {
  if (Array.isArray(errors)) {
    // An array of errors likely caused by bad commands in the template.
    console.log(errors);
  } else {
    // Not an array of template errors, indicating something more serious.
    throw errors;
  }
}

Error types

The library exposes the following error types. See the errors.ts module for details.

NullishCommandResultError // thrown when rejectNullish is set to true and a command returns null or undefined
ObjectCommandResultError // thrown when the result of an `INS` command is an Object. This ensures you don't accidentally put `'[object Object]'` in your report.
CommandSyntaxError
InvalidCommandError
CommandExecutionError
ImageError
InternalError
TemplateParseError
IncompleteConditionalStatementError // thrown when an IF-statement has no corresponding END-IF command

Custom error handler

A custom error handler callback can be provided to handle any errors that may occur when executing commands from a template. The value returned by this callback will be inserted into the rendered document instead. The callback is provided with two arguments: the error that was caught and the raw code of the command.

  const report = await createReport({
    template,
    data: {
      name: 'John',
      surname: 'Appleseed',
    },
    errorHandler: (err, command_code) => {
      return 'command failed!';
    },
  });

Using a custom errorHandler in combination with rejectNullish = true allows users to intelligently replace the result of commands that returned null or undefined (make sure to check for NullishCommandResultError).

Inspecting templates

The listCommands function lets you list all the commands in a docx template using the same parser as createReport.

import { listCommands } from 'docx-templates';
const template_buffer = fs.readFileSync('template.docx');
const commands = await listCommands(template_buffer, ['{', '}']);

// `commands` will contain something like:
[
  { raw: 'INS some_variable', code: 'some_variable', type: 'INS' },
  { raw: 'IMAGE svgImgFile()', code: 'svgImgFile()', type: 'IMAGE' },
]

The getMetadata function lets you extract the metadata fields from a document, such as the number of pages or words. Note that this feature has a few limitations:

  • Not all fields may be available, depending on the document.
  • These metadata fields, including the number of pages, are only updated by MS Word (or LibreOffice) when saving the document. Docx-templates does not alter these metadata fields, so the number of pages may not reflect the actual size of your rendered document (see issue #240). Docx-templates can not reliably determine the number of pages in a document, as this requires a full-fledged docx renderer (e.g. MS Word).
    import { getMetadata } from 'docx-templates';
    const template = fs.readFileSync('template.docx');
    await getMetadata(template)
    // result:
      Object {
        "category": undefined,
        "characters": 24,
        "company": undefined,
        "created": "2015-08-16T18:55:00Z",
        "creator": "Someone Else",
        "description": undefined,
        "lastModifiedBy": "Grau Panea, Guillermo",
        "lastPrinted": undefined,
        "lines": 1,
        "modified": "2016-12-15T11:21:00Z",
        "pages": 1,
        "paragraphs": 1,
        "revision": "32",
        "subject": undefined,
        "template": "Normal.dotm",
        "title": undefined,
        "words": 4,
      }

Performance & security

Templates can contain arbitrary javascript code. Beware of code injection risks!

Obviously, this is less of an issue when running docx-templates in a browser environment.

Regardless of whether you are using sandboxing or not (noSandbox: true), be aware that allowing users to upload arbitrary templates to be executed on your server poses a significant security threat. Use at your own risk.

The library uses require('vm') as its default sandboxing environment. Note that this sandbox is explicitly not meant to be used as a security mechanism. You can provide your own sandboxing environment if you want, as shown in this example project.

Note that turning off the sandbox (noSandbox: true) is known to give significant performance improvements when working with large templates or datasets. However, before you do this, make sure you are aware of the security implications.

Similar projects

  • docxtemplater (believe it or not, I just discovered this very similarly-named project after brushing up my old CS code for docx-templates and publishing it for the first time!). It provides lots of goodies, but doesn't allow (AFAIK) embedding queries or JS snippets.

  • docx and similar ones - generate docx files from scratch, programmatically. Drawbacks of this approach: they typically do not support all Word features, and producing a complex document can be challenging.

License (MIT)

This Project is licensed under the MIT License. See LICENSE for more information.

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

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?

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 --

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

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

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?

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

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!

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.

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
+++

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})+++

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.

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?

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.

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 +++

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 ?

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.

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();

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.

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

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 ?

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.

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

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

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

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).

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?

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.

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+++

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.

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.

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.

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.

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;
+++

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.

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.

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'
    }
]

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

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?

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

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>"
}

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.