Code Monkey home page Code Monkey logo

templaterexamples's Introduction

Document generation from templates

Templater is a reporting library which can be easily integrated into third party apps as advanced document generation engine. It works by binding provided data with specified template. Main goal is to provide customization options outside of development, so that reports/invoices/quotes and various other type of documents can be made to look as customers needs them.

Library has a minimal interface for providing data and various extension points for exposing specialized features not available in the library. This way same code is reused across all document generation, instead of having document being generated by writing special code just for that document.

These examples show various usages of the library.

Additional documentation is available from the official website.

How Templater works

Templater works by analyzing provided docx/xlsx/pptx/csv/xml document for tags. Tags are snippets of text written in either [[tag]], {{tag}} or a <<tag>> format. Tags can have metadata which can be used for various customization purposes, such as formatting, verbalization and others.

Tags placed in a resizable part of the document can be duplicated by Templater when paired with a collection input. Major difference from other templating solution is that repeating of a collection is implicit from tag definition instead of explicit by using for loop constructs. An example of this is a row in a table, list, page, sheet or the entire document.

Templater uses documents prepared in Microsoft Office (or some other editor), which allows for beautiful documents, without the need for writing code. This works great in most cases, although Templater must infer intention for the behavior from the structure of the document/tags.

Templater has minimal API for interaction:

  • high level process method
  • low level replace, resize and clone

and a builder API for customization.

Usage of Templater mostly consists from passing existing model to high level API.

Template Result

Data types

Most data types are processed by Templater with conversion to string. In Excel some types are converted into native Excel formats, such as numbers and dates.

Collections are usually processed by duplicating context which encapsulates all tags matching that collection.

Templater will use reflection to analyze classes, but it can work also on dynamic data types such as dictionary/map.

Templater has special behavior for several data types, such as:

and several others (DateTime, multiline strings, ...).

Resizing

Low level resize(tags, count) API is used for duplicating part of the document. It can work for simple cases, such as single row in a table, but can be used for more complex ones:

  • multiple rows - tags can span multiple rows, which will cause multi-row copying
  • nested elements - tags can span multiple tables/lists which can be used for cloning complex document layouts
  • formula rewriting - as formulas are moved around and copied, their expressions will be adjusted accordingly
  • row/column styles - if possible styles will be maintained during horizontal or vertical resizing (horizontal resizing requires horizontal-resize metadata)
  • pushdown/pushright - elements bellow/right of tags area will be moved according to builtin rules
  • merge cells/named ranges/tables - influence push rules by extending the affected region
  • XML binding - custom XML will be changed/updated when bound in Word
  • streaming - streaming over collections is also supported

Examples

This repository contains various examples covering some of the features:

Extensibility

Templater has several extensibility points. Various plugins are embedded into library, while others can be registered during library initialization.

Examples:

FAQ

Q: How can I inject text with special color/bolding instead of plain (or pre-formatted) text into Templater?
A: You need to use XML to inject rich text into document (and format it appropriately to the target document format).

Q: Can I convert docx/xlsx/pptx to PDF?
A: Templater does not support converting documents to PDF. If MS Office can't be used to do PDF conversion there are various 3rd party libraries such as Aspose or Spire for PDF conversion. For low budget solutions headless LibreOffice can be used. Almost all non MS solutions have some pixel perfect issues :(. To ease the usage of LibreOffice there is a Dockerfile which will prepare the environment for easy PDF conversion. Templater does support digital signatures and can sign documents as an alternative to PDF in some cases

Q: Is this just a fancy mail-merge library?
A: Not at all. Templater can create really complex documents, but you might need to have a good knowledge of Word/Excel/PowerPoint to create such complex documents.

Q: How does Templater compare to Microsoft OOXML SDK?
A: OOXML SDK is a low level abstraction over Office document formats, while Templater is a high level abstraction over populating documents with data. Templater goal is to avoid writing code for creating reports, but instead bind provided data with an existing template.

templaterexamples's People

Contributors

melezov avatar nutrija avatar sergook avatar templater-zzz avatar zapov 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

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

templaterexamples's Issues

Data inconsistencies

Hello,
i'm very interested to put this library into our inhouse management software, but before we decide to go ahead and buy a license we'd like to get some basic tests working.

this is the word template:
image

and this is the result:
image

  • there are a total of 7 data rows in the data model (see counter in the table header) but only 5 show up in the resulting table. the remaining two have no "findings" in their linked list. but why is the entire table row gone because of this?
  • for data row chk-135 and chk-132, for some reason the ".Count" function produces zero, while there is clearly a value in their linked list (FND-102 and FND-95)
  • i added a manually calculated field to make the error more visible

here's the simplified data model:

    public class ReportingRootObject
    {
        public Reporting_PlaceholderData Data;
        public List<Reporting_ScopeContainerChecks> checksInScope { get; set; }
    }
    public class Reporting_ScopeContainerChecks
    {
        public string scopeName;
        public List<Reporting_CheckInScope> scopeData { get; set; }
    }
    public class Reporting_CheckInScope
    {
        public string group;
        public string category;
        public string id;
        public string title;
        public string reasoning;
        public List<string> referenceUrls;
        public List<string> referenceUrlsMitre;
        public int rating;
        public int findingsCount;
        public List<Reporting_CheckTask> checkTasks { get; set; }
        public List<Reporting_Finding> findings { get; set; }
        public List<Reporting_Measure> measures { get; set; }
    }

and here's the debugger, to prove the data model is correct:
image

edit:
just remembered, this project is on .net 5 rc2. is this supported?

Problem with removing empty tables

daily_data_example.txt

Hello,
I want the table to be deleted from document when there is no data inside.
Normally, when there are no records, Templater generates table with header only.
I want Templater to remove header also, I was trying to achieve this in a few ways.
In user manual I found section "Removing a table". I putted collapse and hide metadata into header like it's described in user manual, but it gave no result. Then, I was trying to implement method similar to CollapseNonEmpty in wordtables example. After many tries I'm getting a lot of weird results. I don't exactly understand how Templater process data and what is current "context" when it's processing. I don't want to write all my observations and conjectures, but I've putted many breakpoints and spent many hours to understand Templater logic, but unfortunately I can't figure it enough modify this to my purposes.

I attach template and example data (in JSON for clearness) to show data structure.

Please, could you provide me solution or help to make solution for this problem? I don't have any other ideas. For now Templater is still almost like black box for me and I need help from creators.
Thanks a lot.
daily_demo.docx

CORS

The TemplateServer doesn't support CORS. I added following lines in Startup.cs

        public void ConfigureServices(IServiceCollection services)
        {
            services.AddCors(options =>
             {
                 options.AddDefaultPolicy(
                     policy =>
                     {
                         policy
                         .WithOrigins("http://localhost:3000", "http://localhost:3001")
                         .AllowAnyHeader()
                         .AllowAnyMethod();
                     });
             });
            services.AddMvc(options => options.EnableEndpointRouting = false);
        }

        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            app.UseCors();
            app.UseMvc();
        }

It works well on Windows, but it dosn't works as expected in Docker container.
Then I tried to run modified TemplateServer in Docker container with the following Dockerfile:

FROM mcr.microsoft.com/dotnet/sdk AS build

# copy csproj and restore as distinct layers
WORKDIR /source
COPY TemplaterServer.sln .
COPY Advanced/TemplaterServer/*.csproj ./Advanced/TemplaterServer/
RUN dotnet restore

# copy everything else and build app

COPY Advanced/TemplaterServer/. ./Advanced/TemplaterServer/
WORKDIR /source/Advanced/TemplaterServer
#RUN dotnet publish -c release -o /app --no-restore
RUN dotnet publish -c release -o /app

# final stage/image

FROM mcr.microsoft.com/dotnet/aspnet
WORKDIR /app
COPY --from=build /app ./
COPY dotnet-install.sh ./
RUN apt update && apt upgrade
RUN yes | apt install curl
RUN yes | apt install libc6-dev
RUN yes | apt install libgdiplus
RUN ./dotnet-install.sh --architecture x64 --install-dir /usr/share/dotnet/ --runtime aspnetcore --version 3.1.0
ENTRYPOINT ["dotnet", "TemplaterServer.dll"]
docker build --pull -t templateserver .
docker run --rm -it -p 8000:80 templateserver

It runs successfully, but CORS doesn't work. Also there is issues in the interface of the web-page. It doesn't switch between json examples and doesn't process the templates.

What might be the reason of that?
Is the way to add CORS support in java version of the TemplateServer?

Include HTML in templater

I developed a custom convert to allow an html from an external data source to be converted within the docx document managed by templater. Within my HTML are images encoded in Base64 format. The procedure is abuonly successful if the HTML contains no images. What can I use to include html in a templater tag? Thank you.

Default tag not repeating with template using :page

Hello.
We have a data structure like this one:

{
  [ MyCompany: {
      [ Name: string,
        Address: string
       ]},
    Fiscal: List({
      [ Number: int,
       TotalValue: decimal,
       Item: List({
               [ Code: string,
                 Value: decimal
                ]})
      ]})
]}

If creating a model where there is multiple Fiscal and just one MyCompany the tags inside MyCompany doesn't repeat in the rest of the report.

Attached are the example, result and desired result.
Example

Result generated

Result desired

"Trial" text even after purchasing the license

I purchased the Templater Solo Developer v7.x license, but the trial text is still present in some places in the generated docx document. I correctly integrated the templater.lic file received with the invoice. How can I fix this? Thank you very much.

Stacked bar does not render

I am development a new report that contains Stacked bar, the issue which I am facing is the bar does not render automatically unless do Edit Data, the stacked bar contains 3 columns (list of project(name), start date(date), finish date(date), and calculated duration.

Json file is attached.
any assistance!
Json.txt

Low level API replacement across fixed and resized tags

Using the low level API, how can you tell if a tag is on a fixed part of the page or the first (template) part of a resizable collection?

I understand that on the resized parts themselves you can check the metadata for _ci:r:_ci:r:#-# codes, however it is not clear how you distinguish between zero, one or more fixed tags and the first (template) tag of a resized set.

Thanks, Paul

Word template that uses the same data in a chart and across multiple pages

Hi,

Is it possible to supply Templater with a single collection of data, e.g.:

[{"type": "something"
"collection": [{"data": "data" ...} ...]
"count": 2}
{"type": "something else"
"collection": [{"other data": "other data" ...} ...]
"count": 4}
...
]

Then have this data shown in a pie chart on the first page, using the "type" and "count" and then a page for each, showing the "type" as a header and the "collection" in a table?

Originally I was hoping that we could get away without the "count" and use Excel to count the records in the collection, but Excel wouldn't allow that (is that possible?)

Ideally I don't want to change the data structure unless it's not possible to achieve via the template. I have attached a test docx and json (renamed .txt as GitHub won't allow json uploads), please note the attribute names are slightly different, I changed them above to make the intention clearer.

test.docx
test.txt

Regards,

Paul

Section feature

Hi,
Im trying to use section feature but the output generated is always showing the two tables template. Im using as the example located at Intermediate/WordTables.
Please could you help me giving me any clue respecting that.

template: 1 Solicitud_template.docx
output: 1 Solicitudx.docx

Cheers.

Documentation or example: how to specify default format for dates, numbers, etc?

Hello!
We are currently testing Templater, and I'm trying to find how to specify default formats of dates and numbers, so I don't need to write this:
[[Statement.Date]:format(dd.MM.yyyy)]
for every DateTime field in template.

I want to write this:
[[Statement.Date]:format ()]
and somehow be able to specify default format once for all template. Is this possible?

Thanks.

Date issue in charts

Hello..
I have a report that has a Stacked Bar depending on dates and values. When I pass data as list of object to the ms word report. the Stacked Bar chart does not render correctly until I open the word file and open edit data, then the chart appear correctly.

Details:
Watch video: https://www.loom.com/share/eedcfcccd3e940d8850ef73a7f89f7a2

Source Report:
Initative Report.docx

C# data model:

        List<Program> Programs = new List<Program>();
                Programs = _NajmServices.GetAllPrograms();
                var rep = new
                {
                    p = Programs.Select(s => new
                    {
                        name = !string.IsNullOrEmpty(s.NameEnglish) ? s.NameEnglish : s.NameArabic,
                        sdate = s.InitiativeStartDate.Date,//.ToString("M/d/yyyy"),
                        fdate = s.InitiativeFinishDate.Date,//.ToString("M/d/yyyy"),
                        dura = (s.InitiativeFinishDate - s.InitiativeStartDate).TotalDays,

                    }).ToList(),
                };

How do I resize a table/list with an IFormatter plugin?

Hi,

I am trying to take a JSON document, like:

{"departments" [{"id" "2",
                 "name" "Sales",
                 "_subs" {"id" "1",
                          "name" "Acme"}}
               {"id" "3",
                "name" "Support",
                "_subs" {"id" "1",
                         "name" "Acme"}}]}

And process it through an IFormatter plugin, with a tag like [[departments]:department]

The plugin takes the collection and returns a new collection where the value has been re-written as

["Acme/Sales" "Acme/Support"]

This works correctly, however, when I place the tag in a table or a list, instead of putting each department in a new row or a new bullet point, it displays it as above in a single cell/point.

Does the data have to be returned from the plugin with a specific type to correctly resize the table/list?

I'm using Clojure but can provide a code sample of my plugin if it will help.

Many thanks,

Paul

Collapase table row if data is null or empty

Hi,

I'm facing a problem. I need to collapse a table's row when the data of this row is null or empty.

I tried to search for this information but i didn't find it.

I saw that you can collapse a block when the value is null but Is it possible to achieve this with a row in a table ?

Thank you for your help.
Christophe

How License works?

Hello,

I have bought the license for 1 developer and I would like to know if the license should be applied exclusively on the server where the business api has been deployed. How does the license really work?
Could you give me an indication of how the team we are working on can work with the bookstore?

I will appreciate your kind response.

Numbering in section

I have this template, when it is rendered, the highlighted section: [[SolutionSystems.Groups.GroupDescription]] despite having neither numbering nor bullet when processed by template is created numbering 1.2.1. How can this be prevented?
immagine

page plugin generating more pages than necessary

Hello, I am having a problem while using the plugin :page

Given the following json model and word document for the template it generates far more pages than necessary and many are without content or printing directly the page

JsonModel
Template Example
Result

Not sure if there is a better way of making the model print one page per instance of the tag [OrdemProducao.Operacao.InsumoBaixado.MovimentacaoDeBaixa.EstoqueOrigem.Item.Descricao]

Thank you.

Image maxSize

Image MaxSize is not working on Excel document. How can we maintain Aspect ratio?

Excel Tabs

I'm looking for an example where I can remove an existing Excel worksheet (tab). Basically, I would like it to work like "collapseif" works in Word. That I could hide a tab should a value passed in be equal to a certain value.

Process method taking too long for large jsons.

Hello,

I have a complex docx template that runs against a 5,4mb Json data and the "process" method takes more than 2 minutes to generate this report, time that does not match with my application requirements. I'm attaching a zip with the Json (I ran the lib with a Map<String, Object>, converted to this Json and then removed sensitive data from it)
I'm using templater version 5.2.0 and java 16.

Is there any way to try to improve this performance?

ActivityTemplate.docx
templater_data.zip

Create a code example on how to register new tags

I'm looking at the user manual and it's not entirely clear to me how to register a new set of tags ("«" "»").
Adding a code example of how to do it would help a lot of people in the future, I reckon.

running TemplaterServer in docker container

Hello!

I created and run docker container on windows 10 (WSL2) as suggested:

docker build -t templater .
docker run -p 7777:7777 --tmpfs /mnt/ramdisk -it templater -tmp=/mnt/ramdisk -log=INFO
PS D:\sergook\TemplaterExamples-master\Advanced\TemplaterServer> docker run -p 7777:7777 --tmpfs /mnt/ramdisk -it templater -tmp=/mnt/ramdisk -log=INFO
Running without examples since resource path is not found...
java.lang.reflect.InvocationTargetException
        at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
        at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
        at java.base/jdk.internal.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
        at java.base/java.lang.reflect.Constructor.newInstance(Constructor.java:490)
        at hr.ngs.templater.server.TemplaterServer.main(TemplaterServer.java:781)
Caused by: java.lang.RuntimeException: Unable to find LibreOffice on the system. Please explicitly specify it via: -libreoffice=/user/home/office/libreoffice
        at hr.ngs.templater.server.LibreOffice.<init>(LibreOffice.java:50)
        ... 5 more
Jul 20, 2022 2:15:33 PM hr.ngs.templater.server.TemplaterServer <init>
WARNING: No template files found
Jul 20, 2022 2:15:33 PM hr.ngs.templater.server.TemplaterServer <init>
WARNING: No template files found
Server started on port 7777, press Enter to stop ...

But the page on localhost:7777 isn't working. It shows: "This page isn’t working. localhost didn’t send any data.
ERR_EMPTY_RESPONSE"

However http://localhost:7777/ works when running the following command in PowerShell:

PS D:\sergook\TemplaterServer> ls

Mode                 LastWriteTime         Length Name
----                 -------------         ------ ----
d-----        20.07.2022     15:08                resources
-a----        20.07.2022     10:55        1793382 templater-server.jar
-a----        11.07.2022     23:36             29 templater.lic

PS D:\sergook\TemplaterServer> java -jar templater-server.jar
Example arguments:
    -port=8080
    -timeout=10
    -tmp=/mnt/ramdisk
    -log=INFO
    -plugins=/templater/jars
    -files=/templater/files
    -disable-exit
    -pdf=LibreOffice,Spire,Aspose
    -libreoffice=/user/home/office/libreoffice
java.lang.reflect.InvocationTargetException
        at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
        at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
        at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
        at java.lang.reflect.Constructor.newInstance(Unknown Source)
        at hr.ngs.templater.server.TemplaterServer.main(TemplaterServer.java:781)
Caused by: java.lang.RuntimeException: Unable to find LibreOffice on the system. Please explicitly specify it via: -libreoffice=/user/home/office/libreoffice
        at hr.ngs.templater.server.LibreOffice.<init>(LibreOffice.java:50)
        ... 5 more
Server started on port 7777, press Enter to stop ...

I also eliminated all warning messages during image start:

  1. Slightly modified Dockerfile:
FROM ubuntu:20.04
ARG DEBIAN_FRONTEND=noninteractive
ENV TZ=Europe/Zagreb
RUN apt update && apt install openjdk-11-jre-headless libreoffice-common libreoffice-java-common libreoffice-writer libreoffice-calc wget -yq
RUN wget -q https://github.com/ngs-doo/TemplaterExamples/releases/download/v7.1.0/templater-server.jar
COPY templater.lic .
COPY ./resources ./resources
EXPOSE 7777
ENTRYPOINT ["java", "-jar", "templater-server.jar"]
  1. Used the following command to run container:
PS D:\sergook\TemplaterExamples-master\Advanced\TemplaterServer> docker run -p 7777:7777 --tmpfs /mnt/ramdisk -it templater -tmp=/mnt/ramdisk -log=INFO -libreoffice=/usr/lib/libreoffice
Server started on port 7777, press Enter to stop ...

But still the page isn't working.
Is any idea how to solve the problem?
Thanks!

How to initialize new list?

I've attached 2 files - template and output. What is the right way to force numbers in each block to start with 1? I've set it in template, but despite this setting we're still getting continuous numeration through all the blocks. Version we're using is 3.2.1
template.docx
output.docx

Alternate nesting syntax

Hi,

I'm currently reviewing Templater for inclusion in a Clojure project I am developing. For the most part it works really well out-the-box. However, Clojure's attribute naming is different to Java's and our users will be expecting to use the Clojure syntax not Java's. For example, a Clojure attribute, could be "some.dotted/attribute" or "some.more.dotted/attribute".  It is the dots in the namespace that is going to cause the confusion as they are also what it used to descend into nested values in Templater.

While, your system still functions as expected with the Clojure attribute names, it is confusing to the Document designer, i.e. "[[some.nested/collection.some.nested/value]]" it is unclear what is attribute and what is delimiting descending into the nested collection. It should be noted that attributes like "some.nested/value.attr" are also perfectly valid in Clojure, however as a convention dots aren't used after the slash.

So, is it possible to change the dot used to delimit descending into a nested value to another character, e.g. a colon ":"?

Many thanks,

Paul

Line break (\n) issue in pptx templates

Input:

  • pptx template document with tag {{tag}}
  • data to replace the tag with value "text before line break \n text after line break"

Expected output:

  • pptx doc with 2 lines:
    text before line break
    text after line break

Real output:

  • pptx doc has only the first line:
    text before line break

Looking into pptx doc internals it's seen that the second line is rendered improperly and nested into the first one

<a:r>
<a:rPr lang="en-US" sz="1600" b="0" strike="noStrike" spc="-1" dirty="0">
<a:solidFill>
<a:srgbClr val="000000"/>
</a:solidFill>
<a:latin typeface="Fira Sans"/>
<a:ea typeface="Arial"/>
</a:rPr>
<a:t>text before line break</a:t>
<a:br/>
<a:r>
<a:rPr lang="en-US" sz="1600" b="0" strike="noStrike" spc="-1" dirty="0">
<a:solidFill>
<a:srgbClr val="000000"/>
</a:solidFill>
<a:latin typeface="Fira Sans"/>
<a:ea typeface="Arial"/>
</a:rPr>
<a:t>text after line break</a:t>
</a:r>
</a:r>

Is it possible to use multiple tables with same column names in DataSet?

I have this code:

var ds = new DataSet();

var dt1 = new DataTable("Table1");
dt1.Columns.Add("Column1");
dt1.Columns.Add("Column2");

var dt1row = dt1.NewRow();
dt1row["Column1"] = 100;
dt1row["Column2"] = 200;
dt1.Rows.Add(dt1row);

var dt2 = new DataTable("Table2");
dt2.Columns.Add("Column1");
dt2.Columns.Add("Column2");

var dt2row = dt2.NewRow();
dt2row["Column1"] = 400;
dt2row["Column2"] = 500;
dt2.Rows.Add(dt2row);

ds.Tables.Add(dt1);
ds.Tables.Add(dt2);

using var inputFileStream = new FileStream("template.docx", FileMode.Open);
using var outputFileStream = new FileStream("result.docx", FileMode.Create);
using var templateDocument = Configuration.Builder.Build().Open(inputFileStream, outputFileStream, "docx");

templateDocument.Process(ds);

My template:

[[Column1]] [[Column2]]

And in the result docx file I always get 100 and 200 values from the first table. I want to be able to choose a specific table while export, like that:

[[Table1.Column1]] [[Table2.Column1]]

How can I achieve that?

Text box (Shape) colors

Hi,,
Is there away to control on shape fill and border color using c#?
for example: text box background color.

replacing image in word document

Hello,

I try to update an image on a word document based on the "Existing images" chapter of the TemplaterDocumentation
image

When processing the document with below code and Base64Image plugin the image is not replaced.

image

Any help would be very appreciated,
Thanks
Numa

Docx file used:
GreAGre.docx

How to define context/scope for nested collection in a right way?

I've faced with a strange problem, kind of nested collections mixing between items of the parent collection.

Template
Result
JSON data

JSON:

{
  "onSigners": [
    {
      "seaman": {
        "rankName": "Master",
        "plannedVesselName": "ACHILLEAS",
        "joinDate": "2017-09-05T00:00:00Z",
        "firstName": "VALENTYN",
        "birthDate": "1958-01-01T00:00:00Z",
        "nationalityName": null,
        "birthPlace": "MOLDOVA"
      },
      "documents": { }
    },
    {
      "seaman": {
        "rankName": "3rd Officer",
        "plannedVesselName": "ACHILLEAS",
        "joinDate": "2017-09-05T00:00:00Z",
        "firstName": "OLEKSANDR",
        "birthDate": "1988-01-01T00:00:00Z",
        "nationalityName": "Ukrainian",
        "birthPlace": "UKRAINE"
      },
      "documents": {
        "0002": {
          "abbreviation": "0002",
          "name": "SEAMAN'S BOOK",
          "issueDate": "2007-08-15T00:00:00Z",
          "validDate": "2017-04-10T00:00:00Z"
        },
        "0001": {
          "abbreviation": "0001",
          "name": "INTERNATIONAL PASSPORT",
          "issueDate": "2007-07-17T00:00:00Z",
          "validDate": "2017-07-17T00:00:00Z",
          
        }
      }
    }
  ],
  "offSigners": [
    {
      "seaman": {
        "rankName": "Master",
        "plannedVesselName": "ACHILLEAS",
        "joinDate": "2017-09-05T00:00:00Z",
        "firstName": "VALENTYN",
        "mediumName": "",
        "birthDate": "1958-01-01T00:00:00Z",
        "nationalityName": null,
        "birthPlace": "MOLDOVA"
      },
      "documents": {
        
      }
    }
  ]
}

documents property is a IDictionary type (C#)
As you can see the first item of the onSigners collection doesn't has any documents
screen

Finally I've tried wrap it in tables but it changed nothing.

I would appreciate any suggestions
Thanks

Collection per page rendering issue

Templater gives an unexpected result for the following docx template
Page per entry test: {{collection.name}} {{collection.value}} {{collection.values.id}}
and json input
{ "collection": [ { "name" : "one", "value": "value one", "values": [{"id": "value one nested array1"}, {"id": "value one nested array2"}] },{ "name" : "two", "value": "value two", "values": [{"id": "value two nested array1"}, {"id": "value two nested array2"}] },{ "name" : "three", "value": "value three", "values": [{"id": "value three nested array1"}, {"id": "value three nested array2"}] },{ "name" : "four", "value": "value four", "values": [{"id": "value four nested array1"}] } ] }
Expectation for the output file is to get a page per each collection.values.id in a parent context that is totally 7 pages. The real output has 10 pages and context is mixed. For instance, 'value one nested array2' is output in a context of item 'two'.
TBDGS-46.zip

How to hide some text before or after tag when hiding tag?

Hello.

Consider this template part:

"Template content before tag
Some text, some text before tag1 [[SomeObject.SomeProp1]:hide] some text after tag1 [[SomeObject.SomeProp2]] some text after tag2
Template content after tag"

How can I achieve this: when [[SomeObject.SomeProp]:hide] tag is hidden I want result to look like:
"Template content before tag
Some text, value of SomeObject.SomeProp2 some text after tag2
Template content after tag"

In other words - how to mark some part of template as belonging to tag so it will be hidden or visible according to tag visibility?

I've found this sample: https://github.com/ngs-doo/TemplaterExamples/tree/master/Intermediate/CollapseRegion but there are whole rows removed on collapse of corresponding tag.

Thanks.

Horizontal resize not working

I have this CSV template where I want a horizontal resize for 3 columns (Line number, Stock item, Qty) by order lines
image

The horizontal resize is not working and the result shows all order lines in separate rows instead of columns.
image

CSV template: InvoiceTest.csv
Test data: InvoiceJson.txt
Result: Result.csv

Also,
Is it possible to have a horizontal resize for a group of columns?
Instead of having all Line Number columns together, then the Stock Item columns, then Quantity columns.
image
I would like to have a set of columns for each order line.
image

Problem with list numeration (similar to #11)

Hello, thanks for response to #11. It worked fine, but for some reason same solution doesn't work with attached template. I have tried multilevel list and separate tables, but every time I get similar output with continuous numeration (attached example). Could you please explain in a bit more details how lists are being handled by templater, so I wouldn't bother you anymore with same question?

template.docx
output.docx

Where complete reference on built-in formatters, processors, etc could be found?

I've read User's manual and found no section describing full lis of built-in formatters,processors, etc. with description of their arguments and so on. Then I found README.txt file but it seems not complete and lacking of details. For example in Collapse example template I can see functions collapseIf and collapseNonEmpty, which are not described anywhere in manual or readme file.

Excel Report, Diagram is not moving down if above is a list of values

Hi,

i have a problem with a diagram. The diagram is placed under a list with some columns (so place diagram at the right side of list is not possible) and some rows. When i generate the report with the templater library it adds the rows but the diagram is not moving down so it is placed over the rows.
Also the data area of the diagram is not moving down. The data area is a second list under the first list.
Here is my ReportTemplate i am using:
DelayTimeTemplate.xlsx

Do i am something wrong or, missing some setting or anything?

Leave Tag Unprocessed if Value is Null

I am processing reports, which must be "complete". Complete means, that all tags must be replaced with a valid value. I achieve this by reading the remaining tags raising an exception if the template still contains tags after processing.

During testing, I have noticed that Templater replaces (collapses) tags with empty String, if the property in the input object exists, but has value null.

I failed to find examples or documentation on how to change this default behavior. I want to configure Templater such that, if a property has value null (which means "missing value" in my context), it does not process the tag. I still want to use [[thisTagMayBeNull]:empty(Value Missing)] in places, where I expect null values. But I want the default to leave the tag alone, if there's no value.

Can you provide (or point me to) a Java example or the relevant documentation on how to achieve this?
Thank you very much.

MissingPropertyExample explanation

Hi,

I am trying to implement onUnprocessed but I do not understand the example code.

ITemplateDocument doc = Configuration.builder().onUnprocessed((prefix, templater, tags, value) -> { ... }).build().open(templateStream, "docx", fos);

It looks like you are simply creating an in-line function in onUnprocessed, however when I try and reproduce that in Clojure I get a NullPointerException.

Is there anything special about that Java syntax?

Also, is this where I would clear missing markers, e.g.

ITemplateDocument doc = Configuration.builder().onUnprocessed((prefix, templater, tags, value) -> { for (String t : tags) { templater.replace(t, ""); } }).build().open(templateStream, "docx", fos);

So any marker not in the processed data would get replaced with an empty string?

Many thanks,

Paul

Image replacer (using Alt Text) appears to not work correctly when image is copied inside document

Just ran into a situation where i believe the existing image replacement is replacing all images with the last image in the document despite them having different tags and images.

Repro:

  1. Create data supporting two images [[Image1]], [[Image2]]
  2. Add an image to template from any image source.
  3. Update image alt text to match the first image [[Image1]]
  4. Copy the image in the template
  5. Update the alt text to the second image [[Image2]]
  6. Process

Result:
Both images are [[Image2]]

Expected:
First image [[Image1]] second image [[Image2]].

Example Repo:
TemplaterPictureBox.zip

I think it's the copying of the image in the template that is causing the issue - however i think this will be a common use case when designing templates.

Cheers

Zip doesn't have [Content_Types].xml

How can I fix this issue? I had used a docx file converted from doc via WPS Writer.

java.io.FileNotFoundException: Zip doesn't have [Content_Types].xml

at hr.ngs.templater.cc.<init>(Unknown Source)
at hr.ngs.templater.rn.<init>(Unknown Source)
at hr.ngs.templater.uy.<init>(Unknown Source)
at hr.ngs.templater.ab.<init>(Unknown Source)
at hr.ngs.templater.ap.a(Unknown Source)
at hr.ngs.templater.al.<init>(Unknown Source)
at hr.ngs.templater.a.open(Unknown Source)

Certain conditional formatting causes NullReferenceException

Hi

When I use Revenj.NET version v1.4.1 and Templater v2.5 and also v2.7.5 to create an xlsx file it threw a NullReferenceException exception.

report ABC {
    //...
	templater CreateSpreadsheet 'File.xlsx';
  }
Locator.Resolve<IDocumentReport<ABC>>().Create(abc);

I have simplified my spreadsheet template and delete all the content and it seems a conditional formatting rules causes the problem.

The attached ERROR.xlsx throws the exception and WORKS.xlsx works 😊

ERROR.xlsx

WORKS.xlsx

See the next page for the only difference between the two files.

Please advise.

Thank you.

error

works

System.AggregateException occurred
  HResult=0x80131500
  Message=One or more errors occurred.
  Source=mscorlib
  StackTrace:
   at System.Threading.Tasks.Task.ThrowIfExceptional(Boolean includeTaskCanceledExceptions)

Inner Exception 1:
WebException: Object reference not set to an instance of an object.System.ArgumentException: Object reference not set to an instance of an object. ---> Revenj.Common.FrameworkException: Error while executing service: Object reference not set to an instance of an object.. Sent data:

$c82fead7-9a9c-495e-b864-957478084660 ---> System.NullReferenceException: Object reference not set to an instance of an object.
   at s.a()
   at ag.h()
   at bg.a()
   at bg.b()
   at g.a()
   at ae.Dispose()
   at Revenj.DomainPatterns.DocumentReport.GenerateDocument(Object[] data)
   at RatingSystem.Service.OpenModelVersion.Execute(String modelVersionURI) in Y:\Main.cs:line 115
   at Revenj.Plugins.Server.Commands.ExecuteService.ExecuteServiceCommand`2.Execute[TInput,TOutput](ISerialization`1 input, ISerialization`1 output, IServiceProvider locator, Type serviceType, TInput data)
   --- End of inner exception stack trace ---
   --- End of inner exception stack trace ---
   at Revenj.Plugins.Server.Commands.ExecuteService.ExecuteServiceCommand`2.Execute[TInput,TOutput](ISerialization`1 input, ISerialization`1 output, IServiceProvider locator, Type serviceType, TInput data)
   at Revenj.Plugins.Server.Commands.ExecuteService.Execute[TInput,TOutput](IServiceProvider locator, ISerialization`1 input, ISerialization`1 output, IPrincipal principal, TInput data)
Revenj.Common.FrameworkException: Error while executing service: Object reference not set to an instance of an object.. Sent data:

$c82fead7-9a9c-495e-b864-957478084660 ---> System.NullReferenceException: Object reference not set to an instance of an object.
   at s.a()
   at ag.h()
   at bg.a()
   at bg.b()
   at g.a()
   at ae.Dispose()
   at Revenj.DomainPatterns.DocumentReport.GenerateDocument(Object[] data)
   at RatingSystem.Service.OpenModelVersion.Execute(String modelVersionURI) in Y:\Main.cs:line 115
   at Revenj.Plugins.Server.Commands.ExecuteService.ExecuteServiceCommand`2.Execute[TInput,TOutput](ISerialization`1 input, ISerialization`1 output, IServiceProvider locator, Type serviceType, TInput data)
   --- End of inner exception stack trace ---
System.NullReferenceException: Object reference not set to an instance of an object.
   at s.a()
   at ag.h()
   at bg.a()
   at bg.b()
   at g.a()
   at ae.Dispose()
   at Revenj.DomainPatterns.DocumentReport.GenerateDocument(Object[] data)
   at RatingSystem.Service.OpenModelVersion.Execute(String modelVersionURI) in Y:\Main.cs:line 115
   at Revenj.Plugins.Server.Commands.ExecuteService.ExecuteServiceCommand`2.Execute[TInput,TOutput](ISerialization`1 input, ISerialization`1 output, IServiceProvider locator, Type serviceType, TInput data)

Example argument: 
Revenj.Plugins.Server.Commands.ExecuteService+Argument`1[System.Object]

Duplicate section

Hi, I have a problem with the Templater process duplicating a section for me as in the screenshot I attached. Headings 1,2,3,4,5,6,7 are all level 1 however sections 2 and 4 are duplicated. How can this problem be resolved?

Thank you

image

This is the initial template that generates the document:

image

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.