First push
This commit is contained in:
parent
682db991b8
commit
268f0cb2e6
1058
CHANGELOG.md
Normal file
1058
CHANGELOG.md
Normal file
File diff suppressed because it is too large
Load Diff
651
LICENSE.md
Normal file
651
LICENSE.md
Normal file
@ -0,0 +1,651 @@
|
||||
docxtemplater is dual licensed. You may use it under the MIT license *or* the GPLv3
|
||||
license.
|
||||
|
||||
The MIT License
|
||||
===============
|
||||
|
||||
Copyright (c) Edgar HIPP
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
|
||||
|
||||
GPL version 3
|
||||
=============
|
||||
|
||||
GNU GENERAL PUBLIC LICENSE
|
||||
Version 3, 29 June 2007
|
||||
|
||||
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
|
||||
Everyone is permitted to copy and distribute verbatim copies
|
||||
of this license document, but changing it is not allowed.
|
||||
|
||||
Preamble
|
||||
|
||||
The GNU General Public License is a free, copyleft license for
|
||||
software and other kinds of works.
|
||||
|
||||
The licenses for most software and other practical works are designed
|
||||
to take away your freedom to share and change the works. By contrast,
|
||||
the GNU General Public License is intended to guarantee your freedom to
|
||||
share and change all versions of a program--to make sure it remains free
|
||||
software for all its users. We, the Free Software Foundation, use the
|
||||
GNU General Public License for most of our software; it applies also to
|
||||
any other work released this way by its authors. You can apply it to
|
||||
your programs, too.
|
||||
|
||||
When we speak of free software, we are referring to freedom, not
|
||||
price. Our General Public Licenses are designed to make sure that you
|
||||
have the freedom to distribute copies of free software (and charge for
|
||||
them if you wish), that you receive source code or can get it if you
|
||||
want it, that you can change the software or use pieces of it in new
|
||||
free programs, and that you know you can do these things.
|
||||
|
||||
To protect your rights, we need to prevent others from denying you
|
||||
these rights or asking you to surrender the rights. Therefore, you have
|
||||
certain responsibilities if you distribute copies of the software, or if
|
||||
you modify it: responsibilities to respect the freedom of others.
|
||||
|
||||
For example, if you distribute copies of such a program, whether
|
||||
gratis or for a fee, you must pass on to the recipients the same
|
||||
freedoms that you received. You must make sure that they, too, receive
|
||||
or can get the source code. And you must show them these terms so they
|
||||
know their rights.
|
||||
|
||||
Developers that use the GNU GPL protect your rights with two steps:
|
||||
(1) assert copyright on the software, and (2) offer you this License
|
||||
giving you legal permission to copy, distribute and/or modify it.
|
||||
|
||||
For the developers' and authors' protection, the GPL clearly explains
|
||||
that there is no warranty for this free software. For both users' and
|
||||
authors' sake, the GPL requires that modified versions be marked as
|
||||
changed, so that their problems will not be attributed erroneously to
|
||||
authors of previous versions.
|
||||
|
||||
Some devices are designed to deny users access to install or run
|
||||
modified versions of the software inside them, although the manufacturer
|
||||
can do so. This is fundamentally incompatible with the aim of
|
||||
protecting users' freedom to change the software. The systematic
|
||||
pattern of such abuse occurs in the area of products for individuals to
|
||||
use, which is precisely where it is most unacceptable. Therefore, we
|
||||
have designed this version of the GPL to prohibit the practice for those
|
||||
products. If such problems arise substantially in other domains, we
|
||||
stand ready to extend this provision to those domains in future versions
|
||||
of the GPL, as needed to protect the freedom of users.
|
||||
|
||||
Finally, every program is threatened constantly by software patents.
|
||||
States should not allow patents to restrict development and use of
|
||||
software on general-purpose computers, but in those that do, we wish to
|
||||
avoid the special danger that patents applied to a free program could
|
||||
make it effectively proprietary. To prevent this, the GPL assures that
|
||||
patents cannot be used to render the program non-free.
|
||||
|
||||
The precise terms and conditions for copying, distribution and
|
||||
modification follow.
|
||||
|
||||
TERMS AND CONDITIONS
|
||||
|
||||
0. Definitions.
|
||||
|
||||
"This License" refers to version 3 of the GNU General Public License.
|
||||
|
||||
"Copyright" also means copyright-like laws that apply to other kinds of
|
||||
works, such as semiconductor masks.
|
||||
|
||||
"The Program" refers to any copyrightable work licensed under this
|
||||
License. Each licensee is addressed as "you". "Licensees" and
|
||||
"recipients" may be individuals or organizations.
|
||||
|
||||
To "modify" a work means to copy from or adapt all or part of the work
|
||||
in a fashion requiring copyright permission, other than the making of an
|
||||
exact copy. The resulting work is called a "modified version" of the
|
||||
earlier work or a work "based on" the earlier work.
|
||||
|
||||
A "covered work" means either the unmodified Program or a work based
|
||||
on the Program.
|
||||
|
||||
To "propagate" a work means to do anything with it that, without
|
||||
permission, would make you directly or secondarily liable for
|
||||
infringement under applicable copyright law, except executing it on a
|
||||
computer or modifying a private copy. Propagation includes copying,
|
||||
distribution (with or without modification), making available to the
|
||||
public, and in some countries other activities as well.
|
||||
|
||||
To "convey" a work means any kind of propagation that enables other
|
||||
parties to make or receive copies. Mere interaction with a user through
|
||||
a computer network, with no transfer of a copy, is not conveying.
|
||||
|
||||
An interactive user interface displays "Appropriate Legal Notices"
|
||||
to the extent that it includes a convenient and prominently visible
|
||||
feature that (1) displays an appropriate copyright notice, and (2)
|
||||
tells the user that there is no warranty for the work (except to the
|
||||
extent that warranties are provided), that licensees may convey the
|
||||
work under this License, and how to view a copy of this License. If
|
||||
the interface presents a list of user commands or options, such as a
|
||||
menu, a prominent item in the list meets this criterion.
|
||||
|
||||
1. Source Code.
|
||||
|
||||
The "source code" for a work means the preferred form of the work
|
||||
for making modifications to it. "Object code" means any non-source
|
||||
form of a work.
|
||||
|
||||
A "Standard Interface" means an interface that either is an official
|
||||
standard defined by a recognized standards body, or, in the case of
|
||||
interfaces specified for a particular programming language, one that
|
||||
is widely used among developers working in that language.
|
||||
|
||||
The "System Libraries" of an executable work include anything, other
|
||||
than the work as a whole, that (a) is included in the normal form of
|
||||
packaging a Major Component, but which is not part of that Major
|
||||
Component, and (b) serves only to enable use of the work with that
|
||||
Major Component, or to implement a Standard Interface for which an
|
||||
implementation is available to the public in source code form. A
|
||||
"Major Component", in this context, means a major essential component
|
||||
(kernel, window system, and so on) of the specific operating system
|
||||
(if any) on which the executable work runs, or a compiler used to
|
||||
produce the work, or an object code interpreter used to run it.
|
||||
|
||||
The "Corresponding Source" for a work in object code form means all
|
||||
the source code needed to generate, install, and (for an executable
|
||||
work) run the object code and to modify the work, including scripts to
|
||||
control those activities. However, it does not include the work's
|
||||
System Libraries, or general-purpose tools or generally available free
|
||||
programs which are used unmodified in performing those activities but
|
||||
which are not part of the work. For example, Corresponding Source
|
||||
includes interface definition files associated with source files for
|
||||
the work, and the source code for shared libraries and dynamically
|
||||
linked subprograms that the work is specifically designed to require,
|
||||
such as by intimate data communication or control flow between those
|
||||
subprograms and other parts of the work.
|
||||
|
||||
The Corresponding Source need not include anything that users
|
||||
can regenerate automatically from other parts of the Corresponding
|
||||
Source.
|
||||
|
||||
The Corresponding Source for a work in source code form is that
|
||||
same work.
|
||||
|
||||
2. Basic Permissions.
|
||||
|
||||
All rights granted under this License are granted for the term of
|
||||
copyright on the Program, and are irrevocable provided the stated
|
||||
conditions are met. This License explicitly affirms your unlimited
|
||||
permission to run the unmodified Program. The output from running a
|
||||
covered work is covered by this License only if the output, given its
|
||||
content, constitutes a covered work. This License acknowledges your
|
||||
rights of fair use or other equivalent, as provided by copyright law.
|
||||
|
||||
You may make, run and propagate covered works that you do not
|
||||
convey, without conditions so long as your license otherwise remains
|
||||
in force. You may convey covered works to others for the sole purpose
|
||||
of having them make modifications exclusively for you, or provide you
|
||||
with facilities for running those works, provided that you comply with
|
||||
the terms of this License in conveying all material for which you do
|
||||
not control copyright. Those thus making or running the covered works
|
||||
for you must do so exclusively on your behalf, under your direction
|
||||
and control, on terms that prohibit them from making any copies of
|
||||
your copyrighted material outside their relationship with you.
|
||||
|
||||
Conveying under any other circumstances is permitted solely under
|
||||
the conditions stated below. Sublicensing is not allowed; section 10
|
||||
makes it unnecessary.
|
||||
|
||||
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
||||
|
||||
No covered work shall be deemed part of an effective technological
|
||||
measure under any applicable law fulfilling obligations under article
|
||||
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
||||
similar laws prohibiting or restricting circumvention of such
|
||||
measures.
|
||||
|
||||
When you convey a covered work, you waive any legal power to forbid
|
||||
circumvention of technological measures to the extent such circumvention
|
||||
is effected by exercising rights under this License with respect to
|
||||
the covered work, and you disclaim any intention to limit operation or
|
||||
modification of the work as a means of enforcing, against the work's
|
||||
users, your or third parties' legal rights to forbid circumvention of
|
||||
technological measures.
|
||||
|
||||
4. Conveying Verbatim Copies.
|
||||
|
||||
You may convey verbatim copies of the Program's source code as you
|
||||
receive it, in any medium, provided that you conspicuously and
|
||||
appropriately publish on each copy an appropriate copyright notice;
|
||||
keep intact all notices stating that this License and any
|
||||
non-permissive terms added in accord with section 7 apply to the code;
|
||||
keep intact all notices of the absence of any warranty; and give all
|
||||
recipients a copy of this License along with the Program.
|
||||
|
||||
You may charge any price or no price for each copy that you convey,
|
||||
and you may offer support or warranty protection for a fee.
|
||||
|
||||
5. Conveying Modified Source Versions.
|
||||
|
||||
You may convey a work based on the Program, or the modifications to
|
||||
produce it from the Program, in the form of source code under the
|
||||
terms of section 4, provided that you also meet all of these conditions:
|
||||
|
||||
a) The work must carry prominent notices stating that you modified
|
||||
it, and giving a relevant date.
|
||||
|
||||
b) The work must carry prominent notices stating that it is
|
||||
released under this License and any conditions added under section
|
||||
7. This requirement modifies the requirement in section 4 to
|
||||
"keep intact all notices".
|
||||
|
||||
c) You must license the entire work, as a whole, under this
|
||||
License to anyone who comes into possession of a copy. This
|
||||
License will therefore apply, along with any applicable section 7
|
||||
additional terms, to the whole of the work, and all its parts,
|
||||
regardless of how they are packaged. This License gives no
|
||||
permission to license the work in any other way, but it does not
|
||||
invalidate such permission if you have separately received it.
|
||||
|
||||
d) If the work has interactive user interfaces, each must display
|
||||
Appropriate Legal Notices; however, if the Program has interactive
|
||||
interfaces that do not display Appropriate Legal Notices, your
|
||||
work need not make them do so.
|
||||
|
||||
A compilation of a covered work with other separate and independent
|
||||
works, which are not by their nature extensions of the covered work,
|
||||
and which are not combined with it such as to form a larger program,
|
||||
in or on a volume of a storage or distribution medium, is called an
|
||||
"aggregate" if the compilation and its resulting copyright are not
|
||||
used to limit the access or legal rights of the compilation's users
|
||||
beyond what the individual works permit. Inclusion of a covered work
|
||||
in an aggregate does not cause this License to apply to the other
|
||||
parts of the aggregate.
|
||||
|
||||
6. Conveying Non-Source Forms.
|
||||
|
||||
You may convey a covered work in object code form under the terms
|
||||
of sections 4 and 5, provided that you also convey the
|
||||
machine-readable Corresponding Source under the terms of this License,
|
||||
in one of these ways:
|
||||
|
||||
a) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by the
|
||||
Corresponding Source fixed on a durable physical medium
|
||||
customarily used for software interchange.
|
||||
|
||||
b) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by a
|
||||
written offer, valid for at least three years and valid for as
|
||||
long as you offer spare parts or customer support for that product
|
||||
model, to give anyone who possesses the object code either (1) a
|
||||
copy of the Corresponding Source for all the software in the
|
||||
product that is covered by this License, on a durable physical
|
||||
medium customarily used for software interchange, for a price no
|
||||
more than your reasonable cost of physically performing this
|
||||
conveying of source, or (2) access to copy the
|
||||
Corresponding Source from a network server at no charge.
|
||||
|
||||
c) Convey individual copies of the object code with a copy of the
|
||||
written offer to provide the Corresponding Source. This
|
||||
alternative is allowed only occasionally and noncommercially, and
|
||||
only if you received the object code with such an offer, in accord
|
||||
with subsection 6b.
|
||||
|
||||
d) Convey the object code by offering access from a designated
|
||||
place (gratis or for a charge), and offer equivalent access to the
|
||||
Corresponding Source in the same way through the same place at no
|
||||
further charge. You need not require recipients to copy the
|
||||
Corresponding Source along with the object code. If the place to
|
||||
copy the object code is a network server, the Corresponding Source
|
||||
may be on a different server (operated by you or a third party)
|
||||
that supports equivalent copying facilities, provided you maintain
|
||||
clear directions next to the object code saying where to find the
|
||||
Corresponding Source. Regardless of what server hosts the
|
||||
Corresponding Source, you remain obligated to ensure that it is
|
||||
available for as long as needed to satisfy these requirements.
|
||||
|
||||
e) Convey the object code using peer-to-peer transmission, provided
|
||||
you inform other peers where the object code and Corresponding
|
||||
Source of the work are being offered to the general public at no
|
||||
charge under subsection 6d.
|
||||
|
||||
A separable portion of the object code, whose source code is excluded
|
||||
from the Corresponding Source as a System Library, need not be
|
||||
included in conveying the object code work.
|
||||
|
||||
A "User Product" is either (1) a "consumer product", which means any
|
||||
tangible personal property which is normally used for personal, family,
|
||||
or household purposes, or (2) anything designed or sold for incorporation
|
||||
into a dwelling. In determining whether a product is a consumer product,
|
||||
doubtful cases shall be resolved in favor of coverage. For a particular
|
||||
product received by a particular user, "normally used" refers to a
|
||||
typical or common use of that class of product, regardless of the status
|
||||
of the particular user or of the way in which the particular user
|
||||
actually uses, or expects or is expected to use, the product. A product
|
||||
is a consumer product regardless of whether the product has substantial
|
||||
commercial, industrial or non-consumer uses, unless such uses represent
|
||||
the only significant mode of use of the product.
|
||||
|
||||
"Installation Information" for a User Product means any methods,
|
||||
procedures, authorization keys, or other information required to install
|
||||
and execute modified versions of a covered work in that User Product from
|
||||
a modified version of its Corresponding Source. The information must
|
||||
suffice to ensure that the continued functioning of the modified object
|
||||
code is in no case prevented or interfered with solely because
|
||||
modification has been made.
|
||||
|
||||
If you convey an object code work under this section in, or with, or
|
||||
specifically for use in, a User Product, and the conveying occurs as
|
||||
part of a transaction in which the right of possession and use of the
|
||||
User Product is transferred to the recipient in perpetuity or for a
|
||||
fixed term (regardless of how the transaction is characterized), the
|
||||
Corresponding Source conveyed under this section must be accompanied
|
||||
by the Installation Information. But this requirement does not apply
|
||||
if neither you nor any third party retains the ability to install
|
||||
modified object code on the User Product (for example, the work has
|
||||
been installed in ROM).
|
||||
|
||||
The requirement to provide Installation Information does not include a
|
||||
requirement to continue to provide support service, warranty, or updates
|
||||
for a work that has been modified or installed by the recipient, or for
|
||||
the User Product in which it has been modified or installed. Access to a
|
||||
network may be denied when the modification itself materially and
|
||||
adversely affects the operation of the network or violates the rules and
|
||||
protocols for communication across the network.
|
||||
|
||||
Corresponding Source conveyed, and Installation Information provided,
|
||||
in accord with this section must be in a format that is publicly
|
||||
documented (and with an implementation available to the public in
|
||||
source code form), and must require no special password or key for
|
||||
unpacking, reading or copying.
|
||||
|
||||
7. Additional Terms.
|
||||
|
||||
"Additional permissions" are terms that supplement the terms of this
|
||||
License by making exceptions from one or more of its conditions.
|
||||
Additional permissions that are applicable to the entire Program shall
|
||||
be treated as though they were included in this License, to the extent
|
||||
that they are valid under applicable law. If additional permissions
|
||||
apply only to part of the Program, that part may be used separately
|
||||
under those permissions, but the entire Program remains governed by
|
||||
this License without regard to the additional permissions.
|
||||
|
||||
When you convey a copy of a covered work, you may at your option
|
||||
remove any additional permissions from that copy, or from any part of
|
||||
it. (Additional permissions may be written to require their own
|
||||
removal in certain cases when you modify the work.) You may place
|
||||
additional permissions on material, added by you to a covered work,
|
||||
for which you have or can give appropriate copyright permission.
|
||||
|
||||
Notwithstanding any other provision of this License, for material you
|
||||
add to a covered work, you may (if authorized by the copyright holders of
|
||||
that material) supplement the terms of this License with terms:
|
||||
|
||||
a) Disclaiming warranty or limiting liability differently from the
|
||||
terms of sections 15 and 16 of this License; or
|
||||
|
||||
b) Requiring preservation of specified reasonable legal notices or
|
||||
author attributions in that material or in the Appropriate Legal
|
||||
Notices displayed by works containing it; or
|
||||
|
||||
c) Prohibiting misrepresentation of the origin of that material, or
|
||||
requiring that modified versions of such material be marked in
|
||||
reasonable ways as different from the original version; or
|
||||
|
||||
d) Limiting the use for publicity purposes of names of licensors or
|
||||
authors of the material; or
|
||||
|
||||
e) Declining to grant rights under trademark law for use of some
|
||||
trade names, trademarks, or service marks; or
|
||||
|
||||
f) Requiring indemnification of licensors and authors of that
|
||||
material by anyone who conveys the material (or modified versions of
|
||||
it) with contractual assumptions of liability to the recipient, for
|
||||
any liability that these contractual assumptions directly impose on
|
||||
those licensors and authors.
|
||||
|
||||
All other non-permissive additional terms are considered "further
|
||||
restrictions" within the meaning of section 10. If the Program as you
|
||||
received it, or any part of it, contains a notice stating that it is
|
||||
governed by this License along with a term that is a further
|
||||
restriction, you may remove that term. If a license document contains
|
||||
a further restriction but permits relicensing or conveying under this
|
||||
License, you may add to a covered work material governed by the terms
|
||||
of that license document, provided that the further restriction does
|
||||
not survive such relicensing or conveying.
|
||||
|
||||
If you add terms to a covered work in accord with this section, you
|
||||
must place, in the relevant source files, a statement of the
|
||||
additional terms that apply to those files, or a notice indicating
|
||||
where to find the applicable terms.
|
||||
|
||||
Additional terms, permissive or non-permissive, may be stated in the
|
||||
form of a separately written license, or stated as exceptions;
|
||||
the above requirements apply either way.
|
||||
|
||||
8. Termination.
|
||||
|
||||
You may not propagate or modify a covered work except as expressly
|
||||
provided under this License. Any attempt otherwise to propagate or
|
||||
modify it is void, and will automatically terminate your rights under
|
||||
this License (including any patent licenses granted under the third
|
||||
paragraph of section 11).
|
||||
|
||||
However, if you cease all violation of this License, then your
|
||||
license from a particular copyright holder is reinstated (a)
|
||||
provisionally, unless and until the copyright holder explicitly and
|
||||
finally terminates your license, and (b) permanently, if the copyright
|
||||
holder fails to notify you of the violation by some reasonable means
|
||||
prior to 60 days after the cessation.
|
||||
|
||||
Moreover, your license from a particular copyright holder is
|
||||
reinstated permanently if the copyright holder notifies you of the
|
||||
violation by some reasonable means, this is the first time you have
|
||||
received notice of violation of this License (for any work) from that
|
||||
copyright holder, and you cure the violation prior to 30 days after
|
||||
your receipt of the notice.
|
||||
|
||||
Termination of your rights under this section does not terminate the
|
||||
licenses of parties who have received copies or rights from you under
|
||||
this License. If your rights have been terminated and not permanently
|
||||
reinstated, you do not qualify to receive new licenses for the same
|
||||
material under section 10.
|
||||
|
||||
9. Acceptance Not Required for Having Copies.
|
||||
|
||||
You are not required to accept this License in order to receive or
|
||||
run a copy of the Program. Ancillary propagation of a covered work
|
||||
occurring solely as a consequence of using peer-to-peer transmission
|
||||
to receive a copy likewise does not require acceptance. However,
|
||||
nothing other than this License grants you permission to propagate or
|
||||
modify any covered work. These actions infringe copyright if you do
|
||||
not accept this License. Therefore, by modifying or propagating a
|
||||
covered work, you indicate your acceptance of this License to do so.
|
||||
|
||||
10. Automatic Licensing of Downstream Recipients.
|
||||
|
||||
Each time you convey a covered work, the recipient automatically
|
||||
receives a license from the original licensors, to run, modify and
|
||||
propagate that work, subject to this License. You are not responsible
|
||||
for enforcing compliance by third parties with this License.
|
||||
|
||||
An "entity transaction" is a transaction transferring control of an
|
||||
organization, or substantially all assets of one, or subdividing an
|
||||
organization, or merging organizations. If propagation of a covered
|
||||
work results from an entity transaction, each party to that
|
||||
transaction who receives a copy of the work also receives whatever
|
||||
licenses to the work the party's predecessor in interest had or could
|
||||
give under the previous paragraph, plus a right to possession of the
|
||||
Corresponding Source of the work from the predecessor in interest, if
|
||||
the predecessor has it or can get it with reasonable efforts.
|
||||
|
||||
You may not impose any further restrictions on the exercise of the
|
||||
rights granted or affirmed under this License. For example, you may
|
||||
not impose a license fee, royalty, or other charge for exercise of
|
||||
rights granted under this License, and you may not initiate litigation
|
||||
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
||||
any patent claim is infringed by making, using, selling, offering for
|
||||
sale, or importing the Program or any portion of it.
|
||||
|
||||
11. Patents.
|
||||
|
||||
A "contributor" is a copyright holder who authorizes use under this
|
||||
License of the Program or a work on which the Program is based. The
|
||||
work thus licensed is called the contributor's "contributor version".
|
||||
|
||||
A contributor's "essential patent claims" are all patent claims
|
||||
owned or controlled by the contributor, whether already acquired or
|
||||
hereafter acquired, that would be infringed by some manner, permitted
|
||||
by this License, of making, using, or selling its contributor version,
|
||||
but do not include claims that would be infringed only as a
|
||||
consequence of further modification of the contributor version. For
|
||||
purposes of this definition, "control" includes the right to grant
|
||||
patent sublicenses in a manner consistent with the requirements of
|
||||
this License.
|
||||
|
||||
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
||||
patent license under the contributor's essential patent claims, to
|
||||
make, use, sell, offer for sale, import and otherwise run, modify and
|
||||
propagate the contents of its contributor version.
|
||||
|
||||
In the following three paragraphs, a "patent license" is any express
|
||||
agreement or commitment, however denominated, not to enforce a patent
|
||||
(such as an express permission to practice a patent or covenant not to
|
||||
sue for patent infringement). To "grant" such a patent license to a
|
||||
party means to make such an agreement or commitment not to enforce a
|
||||
patent against the party.
|
||||
|
||||
If you convey a covered work, knowingly relying on a patent license,
|
||||
and the Corresponding Source of the work is not available for anyone
|
||||
to copy, free of charge and under the terms of this License, through a
|
||||
publicly available network server or other readily accessible means,
|
||||
then you must either (1) cause the Corresponding Source to be so
|
||||
available, or (2) arrange to deprive yourself of the benefit of the
|
||||
patent license for this particular work, or (3) arrange, in a manner
|
||||
consistent with the requirements of this License, to extend the patent
|
||||
license to downstream recipients. "Knowingly relying" means you have
|
||||
actual knowledge that, but for the patent license, your conveying the
|
||||
covered work in a country, or your recipient's use of the covered work
|
||||
in a country, would infringe one or more identifiable patents in that
|
||||
country that you have reason to believe are valid.
|
||||
|
||||
If, pursuant to or in connection with a single transaction or
|
||||
arrangement, you convey, or propagate by procuring conveyance of, a
|
||||
covered work, and grant a patent license to some of the parties
|
||||
receiving the covered work authorizing them to use, propagate, modify
|
||||
or convey a specific copy of the covered work, then the patent license
|
||||
you grant is automatically extended to all recipients of the covered
|
||||
work and works based on it.
|
||||
|
||||
A patent license is "discriminatory" if it does not include within
|
||||
the scope of its coverage, prohibits the exercise of, or is
|
||||
conditioned on the non-exercise of one or more of the rights that are
|
||||
specifically granted under this License. You may not convey a covered
|
||||
work if you are a party to an arrangement with a third party that is
|
||||
in the business of distributing software, under which you make payment
|
||||
to the third party based on the extent of your activity of conveying
|
||||
the work, and under which the third party grants, to any of the
|
||||
parties who would receive the covered work from you, a discriminatory
|
||||
patent license (a) in connection with copies of the covered work
|
||||
conveyed by you (or copies made from those copies), or (b) primarily
|
||||
for and in connection with specific products or compilations that
|
||||
contain the covered work, unless you entered into that arrangement,
|
||||
or that patent license was granted, prior to 28 March 2007.
|
||||
|
||||
Nothing in this License shall be construed as excluding or limiting
|
||||
any implied license or other defenses to infringement that may
|
||||
otherwise be available to you under applicable patent law.
|
||||
|
||||
12. No Surrender of Others' Freedom.
|
||||
|
||||
If conditions are imposed on you (whether by court order, agreement or
|
||||
otherwise) that contradict the conditions of this License, they do not
|
||||
excuse you from the conditions of this License. If you cannot convey a
|
||||
covered work so as to satisfy simultaneously your obligations under this
|
||||
License and any other pertinent obligations, then as a consequence you may
|
||||
not convey it at all. For example, if you agree to terms that obligate you
|
||||
to collect a royalty for further conveying from those to whom you convey
|
||||
the Program, the only way you could satisfy both those terms and this
|
||||
License would be to refrain entirely from conveying the Program.
|
||||
|
||||
13. Use with the GNU Affero General Public License.
|
||||
|
||||
Notwithstanding any other provision of this License, you have
|
||||
permission to link or combine any covered work with a work licensed
|
||||
under version 3 of the GNU Affero General Public License into a single
|
||||
combined work, and to convey the resulting work. The terms of this
|
||||
License will continue to apply to the part which is the covered work,
|
||||
but the special requirements of the GNU Affero General Public License,
|
||||
section 13, concerning interaction through a network will apply to the
|
||||
combination as such.
|
||||
|
||||
14. Revised Versions of this License.
|
||||
|
||||
The Free Software Foundation may publish revised and/or new versions of
|
||||
the GNU General Public License from time to time. Such new versions will
|
||||
be similar in spirit to the present version, but may differ in detail to
|
||||
address new problems or concerns.
|
||||
|
||||
Each version is given a distinguishing version number. If the
|
||||
Program specifies that a certain numbered version of the GNU General
|
||||
Public License "or any later version" applies to it, you have the
|
||||
option of following the terms and conditions either of that numbered
|
||||
version or of any later version published by the Free Software
|
||||
Foundation. If the Program does not specify a version number of the
|
||||
GNU General Public License, you may choose any version ever published
|
||||
by the Free Software Foundation.
|
||||
|
||||
If the Program specifies that a proxy can decide which future
|
||||
versions of the GNU General Public License can be used, that proxy's
|
||||
public statement of acceptance of a version permanently authorizes you
|
||||
to choose that version for the Program.
|
||||
|
||||
Later license versions may give you additional or different
|
||||
permissions. However, no additional obligations are imposed on any
|
||||
author or copyright holder as a result of your choosing to follow a
|
||||
later version.
|
||||
|
||||
15. Disclaimer of Warranty.
|
||||
|
||||
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
||||
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
||||
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
||||
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
||||
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
|
||||
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
||||
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||
|
||||
16. Limitation of Liability.
|
||||
|
||||
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
||||
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
||||
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
|
||||
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
|
||||
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
|
||||
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
|
||||
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
|
||||
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
||||
SUCH DAMAGES.
|
||||
|
||||
17. Interpretation of Sections 15 and 16.
|
||||
|
||||
If the disclaimer of warranty and limitation of liability provided
|
||||
above cannot be given local legal effect according to their terms,
|
||||
reviewing courts shall apply local law that most closely approximates
|
||||
an absolute waiver of all civil liability in connection with the
|
||||
Program, unless a warranty or assumption of liability accompanies a
|
||||
copy of the Program in return for a fee.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
69
README.md
69
README.md
@ -0,0 +1,69 @@
|
||||
# docxtemplater
|
||||
|
||||
[](https://travis-ci.org/open-xml-templating/docxtemplater) [](https://www.npmjs.org/package/docxtemplater) [](https://www.npmjs.org/package/docxtemplater) [](https://cdnjs.com/libraries/docxtemplater) [](https://raw.githubusercontent.com/open-xml-templating/docxtemplater-build/master/build/docxtemplater-latest.min.js) [](https://raw.githubusercontent.com/open-xml-templating/docxtemplater-build/master/build/docxtemplater-latest.min.js)
|
||||
|
||||
[](https://saucelabs.com/u/jsninja)
|
||||
|
||||
[](https://docxtemplater.com/)
|
||||
|
||||
**docxtemplater** is a library to generate docx/pptx documents from a docx/pptx template. It can replace {placeholders} with data and also supports loops and conditions. The templates can be edited by non-programmers, for example your clients.
|
||||
|
||||
## Features
|
||||
|
||||
[Demo Site](https://docxtemplater.com/demo)
|
||||
|
||||
- <a href="https://docxtemplater.com/demo#simple">Replace a {placeholder} by a value</a>
|
||||
- <a href="https://docxtemplater.com/demo#loops">Use loops: {#users} {name} {/users} </a>
|
||||
- <a href="https://docxtemplater.com/demo#loop-table">Use loops in tables to generate columns</a>
|
||||
- <a href="https://docxtemplater.com/demo#conditions">Use conditions (if users.length>3) with angular Parsing</a>
|
||||
- <a href="https://docxtemplater.com/demo#xml-insertion">Insert custom XML {@rawXml} (for formatted text for example)</a>
|
||||
|
||||
## Quickstart
|
||||
|
||||
- [Installation in node](https://docxtemplater.readthedocs.io/en/latest/installation.html#node)
|
||||
- [Installation in the browser](https://docxtemplater.readthedocs.io/en/latest/installation.html#browser)
|
||||
- [Generate a document in node](https://docxtemplater.readthedocs.io/en/latest/generate.html#node)
|
||||
- [Generate a document in the browser](https://docxtemplater.readthedocs.io/en/latest/generate.html#browser)
|
||||
|
||||
## Documentation
|
||||
|
||||
The full documentation of the latest version can be found on [read the docs](http://docxtemplater.readthedocs.io/en/latest/).
|
||||
|
||||
See [CHANGELOG.md](CHANGELOG.md) for information about how to migrate from older versions.
|
||||
|
||||
## Similar libraries
|
||||
|
||||
There are a few similar libraries that work with docx, here’s a list of those I know a bit about:
|
||||
|
||||
- [docx4j](https://www.docx4java.org/trac/docx4j) : JAVA, this is probably the biggest docx library out there. There is no built in templating engine, but you can generate your docx yourself programmatically.
|
||||
- [docx.js](https://github.com/stephen-hardy/DOCX.js) : Javascript in the browser, you can create (not modify) your docx from scratch, but only do very simple things such as adding non formatted text. Documentation is missing.
|
||||
- [redocx](https://github.com/nitin42/redocx) : Create Docx document from scratch, using JSX syntax, last commit on December 2018.
|
||||
- [officegen](https://github.com/Ziv-Barber/officegen) : works only server side for the moment.
|
||||
|
||||
## Modules
|
||||
|
||||
Functionality can be added with modules. Here is the list of existing modules:
|
||||
|
||||
PRO Modules developped by docxtemplater core team :
|
||||
|
||||
- [Image module](https://docxtemplater.com/modules/image/) to add a given image with the syntax: `{%image}`.
|
||||
- [Html Module](https://docxtemplater.com/modules/html/) to insert formatted text in a docx document.
|
||||
- [Html-Pptx Module](https://docxtemplater.com/modules/html-pptx/) to insert formatted text in a pptx document.
|
||||
- [Slides Module](https://docxtemplater.com/modules/slides/) to create multiple slides dynamically.
|
||||
- [Subtemplate Module](https://docxtemplater.com/modules/subtemplate) to include an external docx file inside a given docx file.
|
||||
- [Subsection Module](https://docxtemplater.com/modules/subsection) to include subsections (headers/footers) from an other document.
|
||||
- [Subtemplate-pptx Module](https://docxtemplater.com/modules/pptx-sub/) to include an external pptx file inside a given pptx file.
|
||||
- [Word-Run Module](https://docxtemplater.com/modules/word-run) to include raw runs (<w:r>) inside the document. This makes it possible to include styled text without having to remove the enclosing paragraph like in the {@rawXml} tag.
|
||||
- [QrCode Module](https://docxtemplater.com/modules/qrcode) to replace an image, keeping any existing properties.
|
||||
- [Error Location Module](https://docxtemplater.com/modules/error-location) to show the errors in the template with comments inside the template.
|
||||
- [Table Module](https://docxtemplater.com/modules/table) to create tables from two dimensional data.
|
||||
- [Meta Module](https://docxtemplater.com/modules/meta) to make a document readonly, add a text watermark or update the margins.
|
||||
- [Styling Module](https://docxtemplater.com/modules/styling) restyle a paragraph, a cell or a table depending on some data.
|
||||
- [XLSX Module](https://docxtemplater.com/modules/xlsx) to be able to do templating on Excel files (xlsx extension), also with loops and conditions.
|
||||
- [Footnotes Module](https://docxtemplater.com/modules/footnotes) to be able to add footnotes to a document.
|
||||
- [Paragraph Placeholder Module](https://docxtemplater.com/modules/paragraph-placeholder) to simplify conditions that should show or hide a given paragraph.
|
||||
|
||||
User-contributed modules :
|
||||
|
||||
- [Chart Module](https://github.com/prog666/docxtemplater-chart-module) using the syntax: `{$chart}` , user contributed (compatible with v2 only)
|
||||
- [Hyperlink module](https://github.com/sujith3g/docxtemplater-link-module) using the syntax: `{^link}`, (compatible with v2 only)
|
||||
0
browser/.gitkeep
Normal file
0
browser/.gitkeep
Normal file
18
check-casing.bash
Executable file
18
check-casing.bash
Executable file
@ -0,0 +1,18 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
|
||||
tgrep() {
|
||||
grep "$@" || true
|
||||
}
|
||||
|
||||
( git status --short|cut -d\ -f2- && git ls-files ) |
|
||||
sort -u |
|
||||
( xargs -d '\n' -- stat -c%n 2>/dev/null ||: ) > trackedfiles.log
|
||||
|
||||
count="$(grep -vE '(Makefile)' <trackedfiles.log | tgrep -v '^docs/' | tgrep -v '\.md$' | tgrep '[A-Z_]' | tee /dev/stderr | wc -l)"
|
||||
if [ "$count" = "0" ]
|
||||
then
|
||||
exit 0
|
||||
fi
|
||||
echo "$count files have incorrect casing"
|
||||
exit 1
|
||||
177
docs/Makefile
Normal file
177
docs/Makefile
Normal file
@ -0,0 +1,177 @@
|
||||
# Makefile for Sphinx documentation
|
||||
#
|
||||
|
||||
# You can set these variables from the command line.
|
||||
SPHINXOPTS =
|
||||
SPHINXBUILD = sphinx-build
|
||||
PAPER =
|
||||
BUILDDIR = build
|
||||
|
||||
# User-friendly check for sphinx-build
|
||||
ifeq ($(shell which $(SPHINXBUILD) >/dev/null 2>&1; echo $$?), 1)
|
||||
$(error The '$(SPHINXBUILD)' command was not found. Make sure you have Sphinx installed, then set the SPHINXBUILD environment variable to point to the full path of the '$(SPHINXBUILD)' executable. Alternatively you can add the directory with the executable to your PATH. If you don't have Sphinx installed, grab it from http://sphinx-doc.org/)
|
||||
endif
|
||||
|
||||
# Internal variables.
|
||||
PAPEROPT_a4 = -D latex_paper_size=a4
|
||||
PAPEROPT_letter = -D latex_paper_size=letter
|
||||
ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) source
|
||||
# the i18n builder cannot share the environment and doctrees with the others
|
||||
I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) source
|
||||
|
||||
.PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest gettext
|
||||
|
||||
help:
|
||||
@echo "Please use \`make <target>' where <target> is one of"
|
||||
@echo " html to make standalone HTML files"
|
||||
@echo " dirhtml to make HTML files named index.html in directories"
|
||||
@echo " singlehtml to make a single large HTML file"
|
||||
@echo " pickle to make pickle files"
|
||||
@echo " json to make JSON files"
|
||||
@echo " htmlhelp to make HTML files and a HTML help project"
|
||||
@echo " qthelp to make HTML files and a qthelp project"
|
||||
@echo " devhelp to make HTML files and a Devhelp project"
|
||||
@echo " epub to make an epub"
|
||||
@echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter"
|
||||
@echo " latexpdf to make LaTeX files and run them through pdflatex"
|
||||
@echo " latexpdfja to make LaTeX files and run them through platex/dvipdfmx"
|
||||
@echo " text to make text files"
|
||||
@echo " man to make manual pages"
|
||||
@echo " texinfo to make Texinfo files"
|
||||
@echo " info to make Texinfo files and run them through makeinfo"
|
||||
@echo " gettext to make PO message catalogs"
|
||||
@echo " changes to make an overview of all changed/added/deprecated items"
|
||||
@echo " xml to make Docutils-native XML files"
|
||||
@echo " pseudoxml to make pseudoxml-XML files for display purposes"
|
||||
@echo " linkcheck to check all external links for integrity"
|
||||
@echo " doctest to run all doctests embedded in the documentation (if enabled)"
|
||||
|
||||
clean:
|
||||
rm -rf $(BUILDDIR)/*
|
||||
|
||||
html:
|
||||
$(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html
|
||||
@echo
|
||||
@echo "Build finished. The HTML pages are in $(BUILDDIR)/html."
|
||||
|
||||
dirhtml:
|
||||
$(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml
|
||||
@echo
|
||||
@echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml."
|
||||
|
||||
singlehtml:
|
||||
$(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml
|
||||
@echo
|
||||
@echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml."
|
||||
|
||||
pickle:
|
||||
$(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle
|
||||
@echo
|
||||
@echo "Build finished; now you can process the pickle files."
|
||||
|
||||
json:
|
||||
$(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json
|
||||
@echo
|
||||
@echo "Build finished; now you can process the JSON files."
|
||||
|
||||
htmlhelp:
|
||||
$(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp
|
||||
@echo
|
||||
@echo "Build finished; now you can run HTML Help Workshop with the" \
|
||||
".hhp project file in $(BUILDDIR)/htmlhelp."
|
||||
|
||||
qthelp:
|
||||
$(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp
|
||||
@echo
|
||||
@echo "Build finished; now you can run "qcollectiongenerator" with the" \
|
||||
".qhcp project file in $(BUILDDIR)/qthelp, like this:"
|
||||
@echo "# qcollectiongenerator $(BUILDDIR)/qthelp/docxtemplater.qhcp"
|
||||
@echo "To view the help file:"
|
||||
@echo "# assistant -collectionFile $(BUILDDIR)/qthelp/docxtemplater.qhc"
|
||||
|
||||
devhelp:
|
||||
$(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp
|
||||
@echo
|
||||
@echo "Build finished."
|
||||
@echo "To view the help file:"
|
||||
@echo "# mkdir -p $$HOME/.local/share/devhelp/docxtemplater"
|
||||
@echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/docxtemplater"
|
||||
@echo "# devhelp"
|
||||
|
||||
epub:
|
||||
$(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub
|
||||
@echo
|
||||
@echo "Build finished. The epub file is in $(BUILDDIR)/epub."
|
||||
|
||||
latex:
|
||||
$(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
|
||||
@echo
|
||||
@echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex."
|
||||
@echo "Run \`make' in that directory to run these through (pdf)latex" \
|
||||
"(use \`make latexpdf' here to do that automatically)."
|
||||
|
||||
latexpdf:
|
||||
$(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
|
||||
@echo "Running LaTeX files through pdflatex..."
|
||||
$(MAKE) -C $(BUILDDIR)/latex all-pdf
|
||||
@echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex."
|
||||
|
||||
latexpdfja:
|
||||
$(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
|
||||
@echo "Running LaTeX files through platex and dvipdfmx..."
|
||||
$(MAKE) -C $(BUILDDIR)/latex all-pdf-ja
|
||||
@echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex."
|
||||
|
||||
text:
|
||||
$(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text
|
||||
@echo
|
||||
@echo "Build finished. The text files are in $(BUILDDIR)/text."
|
||||
|
||||
man:
|
||||
$(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man
|
||||
@echo
|
||||
@echo "Build finished. The manual pages are in $(BUILDDIR)/man."
|
||||
|
||||
texinfo:
|
||||
$(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo
|
||||
@echo
|
||||
@echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo."
|
||||
@echo "Run \`make' in that directory to run these through makeinfo" \
|
||||
"(use \`make info' here to do that automatically)."
|
||||
|
||||
info:
|
||||
$(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo
|
||||
@echo "Running Texinfo files through makeinfo..."
|
||||
make -C $(BUILDDIR)/texinfo info
|
||||
@echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo."
|
||||
|
||||
gettext:
|
||||
$(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale
|
||||
@echo
|
||||
@echo "Build finished. The message catalogs are in $(BUILDDIR)/locale."
|
||||
|
||||
changes:
|
||||
$(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes
|
||||
@echo
|
||||
@echo "The overview file is in $(BUILDDIR)/changes."
|
||||
|
||||
linkcheck:
|
||||
$(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck
|
||||
@echo
|
||||
@echo "Link check complete; look for any errors in the above output " \
|
||||
"or in $(BUILDDIR)/linkcheck/output.txt."
|
||||
|
||||
doctest:
|
||||
$(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest
|
||||
@echo "Testing of doctests in the sources finished, look at the " \
|
||||
"results in $(BUILDDIR)/doctest/output.txt."
|
||||
|
||||
xml:
|
||||
$(SPHINXBUILD) -b xml $(ALLSPHINXOPTS) $(BUILDDIR)/xml
|
||||
@echo
|
||||
@echo "Build finished. The XML files are in $(BUILDDIR)/xml."
|
||||
|
||||
pseudoxml:
|
||||
$(SPHINXBUILD) -b pseudoxml $(ALLSPHINXOPTS) $(BUILDDIR)/pseudoxml
|
||||
@echo
|
||||
@echo "Build finished. The pseudo-XML files are in $(BUILDDIR)/pseudoxml."
|
||||
242
docs/make.bat
Normal file
242
docs/make.bat
Normal file
@ -0,0 +1,242 @@
|
||||
@ECHO OFF
|
||||
|
||||
REM Command file for Sphinx documentation
|
||||
|
||||
if "%SPHINXBUILD%" == "" (
|
||||
set SPHINXBUILD=sphinx-build
|
||||
)
|
||||
set BUILDDIR=build
|
||||
set ALLSPHINXOPTS=-d %BUILDDIR%/doctrees %SPHINXOPTS% source
|
||||
set I18NSPHINXOPTS=%SPHINXOPTS% source
|
||||
if NOT "%PAPER%" == "" (
|
||||
set ALLSPHINXOPTS=-D latex_paper_size=%PAPER% %ALLSPHINXOPTS%
|
||||
set I18NSPHINXOPTS=-D latex_paper_size=%PAPER% %I18NSPHINXOPTS%
|
||||
)
|
||||
|
||||
if "%1" == "" goto help
|
||||
|
||||
if "%1" == "help" (
|
||||
:help
|
||||
echo.Please use `make ^<target^>` where ^<target^> is one of
|
||||
echo. html to make standalone HTML files
|
||||
echo. dirhtml to make HTML files named index.html in directories
|
||||
echo. singlehtml to make a single large HTML file
|
||||
echo. pickle to make pickle files
|
||||
echo. json to make JSON files
|
||||
echo. htmlhelp to make HTML files and a HTML help project
|
||||
echo. qthelp to make HTML files and a qthelp project
|
||||
echo. devhelp to make HTML files and a Devhelp project
|
||||
echo. epub to make an epub
|
||||
echo. latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter
|
||||
echo. text to make text files
|
||||
echo. man to make manual pages
|
||||
echo. texinfo to make Texinfo files
|
||||
echo. gettext to make PO message catalogs
|
||||
echo. changes to make an overview over all changed/added/deprecated items
|
||||
echo. xml to make Docutils-native XML files
|
||||
echo. pseudoxml to make pseudoxml-XML files for display purposes
|
||||
echo. linkcheck to check all external links for integrity
|
||||
echo. doctest to run all doctests embedded in the documentation if enabled
|
||||
goto end
|
||||
)
|
||||
|
||||
if "%1" == "clean" (
|
||||
for /d %%i in (%BUILDDIR%\*) do rmdir /q /s %%i
|
||||
del /q /s %BUILDDIR%\*
|
||||
goto end
|
||||
)
|
||||
|
||||
|
||||
%SPHINXBUILD% 2> nul
|
||||
if errorlevel 9009 (
|
||||
echo.
|
||||
echo.The 'sphinx-build' command was not found. Make sure you have Sphinx
|
||||
echo.installed, then set the SPHINXBUILD environment variable to point
|
||||
echo.to the full path of the 'sphinx-build' executable. Alternatively you
|
||||
echo.may add the Sphinx directory to PATH.
|
||||
echo.
|
||||
echo.If you don't have Sphinx installed, grab it from
|
||||
echo.http://sphinx-doc.org/
|
||||
exit /b 1
|
||||
)
|
||||
|
||||
if "%1" == "html" (
|
||||
%SPHINXBUILD% -b html %ALLSPHINXOPTS% %BUILDDIR%/html
|
||||
if errorlevel 1 exit /b 1
|
||||
echo.
|
||||
echo.Build finished. The HTML pages are in %BUILDDIR%/html.
|
||||
goto end
|
||||
)
|
||||
|
||||
if "%1" == "dirhtml" (
|
||||
%SPHINXBUILD% -b dirhtml %ALLSPHINXOPTS% %BUILDDIR%/dirhtml
|
||||
if errorlevel 1 exit /b 1
|
||||
echo.
|
||||
echo.Build finished. The HTML pages are in %BUILDDIR%/dirhtml.
|
||||
goto end
|
||||
)
|
||||
|
||||
if "%1" == "singlehtml" (
|
||||
%SPHINXBUILD% -b singlehtml %ALLSPHINXOPTS% %BUILDDIR%/singlehtml
|
||||
if errorlevel 1 exit /b 1
|
||||
echo.
|
||||
echo.Build finished. The HTML pages are in %BUILDDIR%/singlehtml.
|
||||
goto end
|
||||
)
|
||||
|
||||
if "%1" == "pickle" (
|
||||
%SPHINXBUILD% -b pickle %ALLSPHINXOPTS% %BUILDDIR%/pickle
|
||||
if errorlevel 1 exit /b 1
|
||||
echo.
|
||||
echo.Build finished; now you can process the pickle files.
|
||||
goto end
|
||||
)
|
||||
|
||||
if "%1" == "json" (
|
||||
%SPHINXBUILD% -b json %ALLSPHINXOPTS% %BUILDDIR%/json
|
||||
if errorlevel 1 exit /b 1
|
||||
echo.
|
||||
echo.Build finished; now you can process the JSON files.
|
||||
goto end
|
||||
)
|
||||
|
||||
if "%1" == "htmlhelp" (
|
||||
%SPHINXBUILD% -b htmlhelp %ALLSPHINXOPTS% %BUILDDIR%/htmlhelp
|
||||
if errorlevel 1 exit /b 1
|
||||
echo.
|
||||
echo.Build finished; now you can run HTML Help Workshop with the ^
|
||||
.hhp project file in %BUILDDIR%/htmlhelp.
|
||||
goto end
|
||||
)
|
||||
|
||||
if "%1" == "qthelp" (
|
||||
%SPHINXBUILD% -b qthelp %ALLSPHINXOPTS% %BUILDDIR%/qthelp
|
||||
if errorlevel 1 exit /b 1
|
||||
echo.
|
||||
echo.Build finished; now you can run "qcollectiongenerator" with the ^
|
||||
.qhcp project file in %BUILDDIR%/qthelp, like this:
|
||||
echo.^> qcollectiongenerator %BUILDDIR%\qthelp\docxtemplater.qhcp
|
||||
echo.To view the help file:
|
||||
echo.^> assistant -collectionFile %BUILDDIR%\qthelp\docxtemplater.ghc
|
||||
goto end
|
||||
)
|
||||
|
||||
if "%1" == "devhelp" (
|
||||
%SPHINXBUILD% -b devhelp %ALLSPHINXOPTS% %BUILDDIR%/devhelp
|
||||
if errorlevel 1 exit /b 1
|
||||
echo.
|
||||
echo.Build finished.
|
||||
goto end
|
||||
)
|
||||
|
||||
if "%1" == "epub" (
|
||||
%SPHINXBUILD% -b epub %ALLSPHINXOPTS% %BUILDDIR%/epub
|
||||
if errorlevel 1 exit /b 1
|
||||
echo.
|
||||
echo.Build finished. The epub file is in %BUILDDIR%/epub.
|
||||
goto end
|
||||
)
|
||||
|
||||
if "%1" == "latex" (
|
||||
%SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex
|
||||
if errorlevel 1 exit /b 1
|
||||
echo.
|
||||
echo.Build finished; the LaTeX files are in %BUILDDIR%/latex.
|
||||
goto end
|
||||
)
|
||||
|
||||
if "%1" == "latexpdf" (
|
||||
%SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex
|
||||
cd %BUILDDIR%/latex
|
||||
make all-pdf
|
||||
cd %BUILDDIR%/..
|
||||
echo.
|
||||
echo.Build finished; the PDF files are in %BUILDDIR%/latex.
|
||||
goto end
|
||||
)
|
||||
|
||||
if "%1" == "latexpdfja" (
|
||||
%SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex
|
||||
cd %BUILDDIR%/latex
|
||||
make all-pdf-ja
|
||||
cd %BUILDDIR%/..
|
||||
echo.
|
||||
echo.Build finished; the PDF files are in %BUILDDIR%/latex.
|
||||
goto end
|
||||
)
|
||||
|
||||
if "%1" == "text" (
|
||||
%SPHINXBUILD% -b text %ALLSPHINXOPTS% %BUILDDIR%/text
|
||||
if errorlevel 1 exit /b 1
|
||||
echo.
|
||||
echo.Build finished. The text files are in %BUILDDIR%/text.
|
||||
goto end
|
||||
)
|
||||
|
||||
if "%1" == "man" (
|
||||
%SPHINXBUILD% -b man %ALLSPHINXOPTS% %BUILDDIR%/man
|
||||
if errorlevel 1 exit /b 1
|
||||
echo.
|
||||
echo.Build finished. The manual pages are in %BUILDDIR%/man.
|
||||
goto end
|
||||
)
|
||||
|
||||
if "%1" == "texinfo" (
|
||||
%SPHINXBUILD% -b texinfo %ALLSPHINXOPTS% %BUILDDIR%/texinfo
|
||||
if errorlevel 1 exit /b 1
|
||||
echo.
|
||||
echo.Build finished. The Texinfo files are in %BUILDDIR%/texinfo.
|
||||
goto end
|
||||
)
|
||||
|
||||
if "%1" == "gettext" (
|
||||
%SPHINXBUILD% -b gettext %I18NSPHINXOPTS% %BUILDDIR%/locale
|
||||
if errorlevel 1 exit /b 1
|
||||
echo.
|
||||
echo.Build finished. The message catalogs are in %BUILDDIR%/locale.
|
||||
goto end
|
||||
)
|
||||
|
||||
if "%1" == "changes" (
|
||||
%SPHINXBUILD% -b changes %ALLSPHINXOPTS% %BUILDDIR%/changes
|
||||
if errorlevel 1 exit /b 1
|
||||
echo.
|
||||
echo.The overview file is in %BUILDDIR%/changes.
|
||||
goto end
|
||||
)
|
||||
|
||||
if "%1" == "linkcheck" (
|
||||
%SPHINXBUILD% -b linkcheck %ALLSPHINXOPTS% %BUILDDIR%/linkcheck
|
||||
if errorlevel 1 exit /b 1
|
||||
echo.
|
||||
echo.Link check complete; look for any errors in the above output ^
|
||||
or in %BUILDDIR%/linkcheck/output.txt.
|
||||
goto end
|
||||
)
|
||||
|
||||
if "%1" == "doctest" (
|
||||
%SPHINXBUILD% -b doctest %ALLSPHINXOPTS% %BUILDDIR%/doctest
|
||||
if errorlevel 1 exit /b 1
|
||||
echo.
|
||||
echo.Testing of doctests in the sources finished, look at the ^
|
||||
results in %BUILDDIR%/doctest/output.txt.
|
||||
goto end
|
||||
)
|
||||
|
||||
if "%1" == "xml" (
|
||||
%SPHINXBUILD% -b xml %ALLSPHINXOPTS% %BUILDDIR%/xml
|
||||
if errorlevel 1 exit /b 1
|
||||
echo.
|
||||
echo.Build finished. The XML files are in %BUILDDIR%/xml.
|
||||
goto end
|
||||
)
|
||||
|
||||
if "%1" == "pseudoxml" (
|
||||
%SPHINXBUILD% -b pseudoxml %ALLSPHINXOPTS% %BUILDDIR%/pseudoxml
|
||||
if errorlevel 1 exit /b 1
|
||||
echo.
|
||||
echo.Build finished. The pseudo-XML files are in %BUILDDIR%/pseudoxml.
|
||||
goto end
|
||||
)
|
||||
|
||||
:end
|
||||
345
docs/source/angular_parse.rst
Normal file
345
docs/source/angular_parse.rst
Normal file
@ -0,0 +1,345 @@
|
||||
.. _angular_parse:
|
||||
|
||||
.. index::
|
||||
single: Angular parser
|
||||
|
||||
Angular parser
|
||||
==============
|
||||
|
||||
Introduction
|
||||
------------
|
||||
|
||||
The angular-parser makes creating complex templates easier.
|
||||
You can for example now use :
|
||||
|
||||
.. code-block:: text
|
||||
|
||||
{user.name}
|
||||
|
||||
To access the nested name property in the following data :
|
||||
|
||||
.. code-block:: javascript
|
||||
|
||||
{
|
||||
user: {
|
||||
name: 'John'
|
||||
}
|
||||
}
|
||||
|
||||
You can also use `+`, `-`, `*`, `/`, `>`, `<` operators.
|
||||
|
||||
Setup
|
||||
-----
|
||||
|
||||
Here's a code sample for how to use the angularParser :
|
||||
|
||||
.. code-block:: javascript
|
||||
|
||||
// Please make sure to use angular-expressions 1.0.1 or later
|
||||
// More detail at https://github.com/open-xml-templating/docxtemplater/issues/488
|
||||
var expressions = require('angular-expressions');
|
||||
var assign = require("lodash/assign");
|
||||
// define your filter functions here, for example, to be able to write {clientname | lower}
|
||||
expressions.filters.lower = function(input) {
|
||||
// This condition should be used to make sure that if your input is
|
||||
// undefined, your output will be undefined as well and will not
|
||||
// throw an error
|
||||
if(!input) return input;
|
||||
return input.toLowerCase();
|
||||
}
|
||||
function angularParser(tag) {
|
||||
if (tag === '.') {
|
||||
return {
|
||||
get: function(s){ return s;}
|
||||
};
|
||||
}
|
||||
const expr = expressions.compile(
|
||||
tag.replace(/(’|‘)/g, "'").replace(/(“|”)/g, '"')
|
||||
);
|
||||
return {
|
||||
get: function(scope, context) {
|
||||
let obj = {};
|
||||
const scopeList = context.scopeList;
|
||||
const num = context.num;
|
||||
for (let i = 0, len = num + 1; i < len; i++) {
|
||||
obj = assign(obj, scopeList[i]);
|
||||
}
|
||||
return expr(scope, obj);
|
||||
}
|
||||
};
|
||||
}
|
||||
new Docxtemplater(zip, {parser:angularParser});
|
||||
|
||||
.. note::
|
||||
|
||||
The require() will not work in a browser, you have to use a module bundler like `webpack`_ or `browserify`_. Alternatively, you can download an outdated version at https://raw.githubusercontent.com/open-xml-templating/docxtemplater/6c8c76210d555fd0f6b3dbc927522a3805f17469/vendor/angular-parse-browser.js
|
||||
|
||||
.. _`webpack`: https://webpack.github.io/
|
||||
.. _`browserify`: http://browserify.org/
|
||||
|
||||
Conditions
|
||||
----------
|
||||
|
||||
With the angularParser option set, you can also use conditions :
|
||||
|
||||
.. code-block:: text
|
||||
|
||||
{#users.length>1}
|
||||
There are multiple users
|
||||
{/}
|
||||
|
||||
{#userName == "John"}
|
||||
Hello John, welcome back
|
||||
{/}
|
||||
|
||||
The first conditional will render the section only if there are 2 users or more.
|
||||
|
||||
The second conditional will render the section only if the userName is the string "John".
|
||||
|
||||
It also handles the boolean operators AND ``&&``, OR ``||``, ``+``, ``-``, the ternary operator ``a ? b : c``, operator precendence with parenthesis ``(a && b) || c``, and many other javascript features.
|
||||
|
||||
For example, it is possible to write the following template :
|
||||
|
||||
|
||||
.. code-block:: text
|
||||
|
||||
{#generalCondition}
|
||||
{#cond1 || cond2}
|
||||
Paragraph 1
|
||||
{/}
|
||||
{#cond2 && cond3}
|
||||
Paragraph 2
|
||||
{/}
|
||||
{#cond4 ? users : usersWithAdminRights}
|
||||
Paragraph 3
|
||||
{/}
|
||||
There are {users.length} users.
|
||||
{/generalCondition}
|
||||
|
||||
Filters
|
||||
-------
|
||||
|
||||
With filters, it is possible to write the following template to have the resulting string be uppercased:
|
||||
|
||||
.. code-block:: text
|
||||
|
||||
{user.name | upper}
|
||||
|
||||
.. code-block:: javascript
|
||||
|
||||
var expressions = require('angular-expressions');
|
||||
expressions.filters.upper = function(input) {
|
||||
// This condition should be used to make sure that if your input is
|
||||
// undefined, your output will be undefined as well and will not
|
||||
// throw an error
|
||||
if(!input) return input;
|
||||
return input.toUpperCase();
|
||||
}
|
||||
|
||||
More complex filters are possible, for example, if you would like to list the names of all active users. If your data is the following :
|
||||
|
||||
.. code-block:: json
|
||||
|
||||
{
|
||||
"users": [
|
||||
{
|
||||
"name": "John",
|
||||
"age": 15,
|
||||
},
|
||||
{
|
||||
"name": "Mary",
|
||||
"age": 26,
|
||||
}
|
||||
],
|
||||
}
|
||||
|
||||
You could show the list of users that are older than 18, by writing the following code :
|
||||
|
||||
.. code-block:: javascript
|
||||
|
||||
var expressions = require('angular-expressions');
|
||||
expressions.filters.olderThan = function(users, minAge) {
|
||||
// This condition should be used to make sure that if your input is
|
||||
// undefined, your output will be undefined as well and will not
|
||||
// throw an error
|
||||
if(!users) return users;
|
||||
return users.filter(function(user) {
|
||||
return user.age >= minAge;
|
||||
});
|
||||
}
|
||||
|
||||
And in your template,
|
||||
|
||||
.. code-block:: text
|
||||
|
||||
The allowed users are :
|
||||
|
||||
{#users | olderThan:15}
|
||||
{name} - {age} years old
|
||||
{/}
|
||||
|
||||
There are some interesting use cases for filters
|
||||
|
||||
Data aggregation
|
||||
~~~~~~~~~~~~~~~~
|
||||
|
||||
If your data is the following :
|
||||
|
||||
.. code-block:: json
|
||||
|
||||
{
|
||||
"items": [
|
||||
{
|
||||
"name": "Acme Computer",
|
||||
"price": 1000,
|
||||
},
|
||||
{
|
||||
"name": "Mouse & Keyboard",
|
||||
"price": 150,
|
||||
}
|
||||
],
|
||||
}
|
||||
|
||||
And you would like to show the total price, you can write in your template :
|
||||
|
||||
.. code-block:: text
|
||||
|
||||
{#items}
|
||||
{name} for a price of {price} €
|
||||
{/}
|
||||
Total Price of your purchase : {items | sumby:'price'}€
|
||||
|
||||
The `sumby` is a filter that you can write like this :
|
||||
|
||||
.. code-block:: javascript
|
||||
|
||||
expressions.filters.sumby = function(input, field) {
|
||||
// In our example field is the string "price"
|
||||
// This condition should be used to make sure that if your input is
|
||||
// undefined, your output will be undefined as well and will not
|
||||
// throw an error
|
||||
if(!input) return input;
|
||||
return input.reduce(function(sum, object) {
|
||||
return sum + object[field];
|
||||
}, 0);
|
||||
}
|
||||
|
||||
Data formatting
|
||||
~~~~~~~~~~~~~~~
|
||||
|
||||
This example is to format numbers in the format : "150.00" (2 digits of precision)
|
||||
If your data is the following :
|
||||
|
||||
.. code-block:: json
|
||||
|
||||
{
|
||||
"items": [
|
||||
{
|
||||
"name": "Acme Computer",
|
||||
"price": 1000,
|
||||
},
|
||||
{
|
||||
"name": "Mouse & Keyboard",
|
||||
"price": 150,
|
||||
}
|
||||
],
|
||||
}
|
||||
|
||||
And you would like to show the price with two digits of precision, you can write in your template :
|
||||
|
||||
.. code-block:: text
|
||||
|
||||
{#items}
|
||||
{name} for a price of {price | toFixed:2} €
|
||||
{/}
|
||||
|
||||
The `toFixed` is an angular filter that you can write like this :
|
||||
|
||||
.. code-block:: javascript
|
||||
|
||||
expressions.filters.toFixed = function(input, precision) {
|
||||
// In our example precision is the integer 2
|
||||
// This condition should be used to make sure that if your input is
|
||||
// undefined, your output will be undefined as well and will not
|
||||
// throw an error
|
||||
if(!input) return input;
|
||||
return input.toFixed(precision);
|
||||
}
|
||||
|
||||
|
||||
Assignments
|
||||
-----------
|
||||
|
||||
With the angular expression option, it is possible to assign a value to a variable directly from your template.
|
||||
|
||||
For example, in your template, write :
|
||||
|
||||
.. code-block:: text
|
||||
|
||||
{full_name = first_name + last_name}
|
||||
|
||||
The problem with this expression is that it will return the value of full_name.
|
||||
There are two ways to fix this issue, either, if you still would like to keep this as the default behavior, add `; ''` after your expression, for example
|
||||
|
||||
.. code-block:: text
|
||||
|
||||
{full_name = first_name + last_name; ''}
|
||||
|
||||
This will first execute the expression, and then execute the second statement which is an empty string, and return it.
|
||||
|
||||
An other approach is to automatically silence the return values of expression containing variable assignments.
|
||||
|
||||
You can do so by using the following parser option :
|
||||
|
||||
.. code-block:: javascript
|
||||
|
||||
var expressions = require("angular-expressions");
|
||||
var assign = require("lodash/assign");
|
||||
|
||||
function angularParser(tag) {
|
||||
if (tag === ".") {
|
||||
return {
|
||||
get(s) {
|
||||
return s;
|
||||
},
|
||||
};
|
||||
}
|
||||
const expr = expressions.compile(
|
||||
tag.replace(/(’|‘)/g, "'").replace(/(“|”)/g, '"')
|
||||
);
|
||||
// isAngularAssignment will be true if your tag contains a `=`, for example
|
||||
// when you write the following in your template :
|
||||
// {full_name = first_name + last_name}
|
||||
// In that case, it makes sense to return an empty string so
|
||||
// that the tag does not write something to the generated document.
|
||||
const isAngularAssignment =
|
||||
expr.ast.body[0] &&
|
||||
expr.ast.body[0].expression.type === "AssignmentExpression";
|
||||
|
||||
return {
|
||||
get(scope, context) {
|
||||
let obj = {};
|
||||
const scopeList = context.scopeList;
|
||||
const num = context.num;
|
||||
for (let i = 0, len = num + 1; i < len; i++) {
|
||||
obj = assign(obj, scopeList[i]);
|
||||
}
|
||||
const result = expr(scope, obj);
|
||||
if (isAngularAssignment) {
|
||||
return "";
|
||||
}
|
||||
return result;
|
||||
},
|
||||
};
|
||||
}
|
||||
new Docxtemplater(zip, {parser:angularParser});
|
||||
|
||||
Note that if you use a standard tag, like `{full_name = first_name + last_name}` and if you put no other content on that paragraph, the line will still be there but it will be an empty line. If you wish to remove the line, you could use a rawXML tag which will remove the paragraph, like this :
|
||||
|
||||
.. code-block:: text
|
||||
|
||||
{@full_name = first_name + last_name}
|
||||
{@vat = price * 0.2}
|
||||
{@total_price = price + vat}
|
||||
|
||||
This way, all these assignment lines will be dropped.
|
||||
87
docs/source/api.rst
Normal file
87
docs/source/api.rst
Normal file
@ -0,0 +1,87 @@
|
||||
.. _api:
|
||||
|
||||
.. index::
|
||||
single: API
|
||||
|
||||
API
|
||||
===
|
||||
|
||||
Constructor
|
||||
-----------
|
||||
|
||||
.. code-block:: text
|
||||
|
||||
new Docxtemplater()
|
||||
|
||||
This function returns a new Docxtemplater instance
|
||||
|
||||
.. code-block:: text
|
||||
|
||||
new Docxtemplater(zip[, options])
|
||||
|
||||
This constructor is preferred over the constructor without any arguments. The constructor without arguments will be removed in docxtemplater version 4.
|
||||
When calling the constructor with a zip file as the first argument, the document will be compiled during instantiation, meaning that this will throw an error if some tag is misplaced in your document.
|
||||
The options parameter allows you to attach some modules, and they will be attached before compilation.
|
||||
|
||||
zip:
|
||||
a zip instance to that method, coming from pizzip or jszip version 2.
|
||||
|
||||
options: (default {modules:[]})
|
||||
You can use this object to configure docxtemplater. It is possible to configure in the following ways:
|
||||
|
||||
* You can pass options to change custom parser, custom delimiters, etc.
|
||||
* You can pass the list of modules that you would like to attach.
|
||||
|
||||
For example :
|
||||
const options = {
|
||||
modules: [ new ImageModule(imageOpts) ],
|
||||
delimiters: {
|
||||
start: "<",
|
||||
end: ">",
|
||||
},
|
||||
}
|
||||
const doc = new Docxtemplater(zip, options);
|
||||
|
||||
This function returns a new Docxtemplater instance
|
||||
|
||||
|
||||
Methods
|
||||
-------
|
||||
|
||||
.. code-block:: text
|
||||
|
||||
setData(Tags)
|
||||
|
||||
Tags:
|
||||
Type: Object {tag_name:tag_replacement}
|
||||
Object containing for each tag_name, the replacement for this tag. For example, if you want to replace firstName by David, your Object should be: {"firstName":"David"}
|
||||
|
||||
render()
|
||||
|
||||
This function replaces all template variables by their values
|
||||
|
||||
getZip()
|
||||
|
||||
This will return you the zip that represents the docx. You can then call `.generate` on this to generate a buffer, string , ... (see https://github.com/open-xml-templating/pizzip/blob/master/documentation/api_pizzip/generate.md)
|
||||
|
||||
compile()
|
||||
|
||||
This function is **deprecated** and you should instead use the new constructor with two arguments.
|
||||
This function parses the template to prepare for the rendering. If your template has some issues in the syntax (for example if your tag is never closed like in : `Hello {user`), this function will throw an error with extra properties describing the error. This function is called for you in render() if you didn't call it yourself. This function should be called before doing resolveData() if you have some async data.
|
||||
|
||||
loadZip(zip)
|
||||
|
||||
This function is **deprecated** and you should instead use the new constructor with two arguments.
|
||||
You have to pass a zip instance to that method, coming from pizzip or jszip version 2
|
||||
|
||||
setOptions()
|
||||
|
||||
This function is **deprecated** and you should instead use the new constructor with two arguments.
|
||||
This function is used to configure the docxtemplater instance by changing parser, delimiters, etc. (See https://docxtemplater.readthedocs.io/en/latest/configuration.html).
|
||||
|
||||
attachModule(module)
|
||||
|
||||
This function is **deprecated** and you should instead use the new constructor with two arguments.
|
||||
This will attach a module to the docxtemplater instance, which is usually used to add new generation features (possibility to include images, HTML, ...). Pro modules can be bought on https://docxtemplater.com/
|
||||
|
||||
This method can be called multiple times, for example : `doc.loadZip(zip).attachModule(imageModule).attachModule(htmlModule)`
|
||||
59
docs/source/async.rst
Normal file
59
docs/source/async.rst
Normal file
@ -0,0 +1,59 @@
|
||||
.. index::
|
||||
single: Async
|
||||
|
||||
.. _async:
|
||||
|
||||
Asynchronous Data Resolving
|
||||
===========================
|
||||
|
||||
You can have promises in your data. Note that the only step running asynchronously is the resolving of your data. The compilation (parsing of your template to parse position of each tags), and the rendering (using the compiled version + the resolved data) will still be fully synchronous
|
||||
|
||||
.. code-block:: javascript
|
||||
|
||||
// The error object contains additional information when logged with JSON.stringify (it contains a properties object containing all suberrors).
|
||||
function replaceErrors(key, value) {
|
||||
if (value instanceof Error) {
|
||||
return Object.getOwnPropertyNames(value).reduce(function(error, key) {
|
||||
error[key] = value[key];
|
||||
return error;
|
||||
}, {});
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
function errorHandler(error) {
|
||||
console.log(JSON.stringify({error: error}, replaceErrors));
|
||||
|
||||
if (error.properties && error.properties.errors instanceof Array) {
|
||||
const errorMessages = error.properties.errors.map(function (error) {
|
||||
return error.properties.explanation;
|
||||
}).join("\n");
|
||||
console.log('errorMessages', errorMessages);
|
||||
// errorMessages is a humanly readable message looking like this :
|
||||
// 'The tag beginning with "foobar" is unopened'
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
|
||||
var doc;
|
||||
try {
|
||||
// Compile your document
|
||||
doc = new Docxtemplater(zip, options);
|
||||
}
|
||||
catch (error) {
|
||||
// Catch compilation errors (errors caused by the compilation of the template : misplaced tags)
|
||||
errorHandler(error);
|
||||
}
|
||||
|
||||
doc.resolveData({user: new Promise(resolve) { setTimeout(()=> resolve('John'), 1000)}})
|
||||
.then(function() {
|
||||
try {
|
||||
doc.render();
|
||||
}
|
||||
catch (error) {
|
||||
errorHandler(err);
|
||||
}
|
||||
var buf = doc.getZip()
|
||||
.generate({type: 'nodebuffer'});
|
||||
fs.writeFileSync(path.resolve(__dirname, 'output.docx'), buf);
|
||||
});
|
||||
19
docs/source/cli.rst
Normal file
19
docs/source/cli.rst
Normal file
@ -0,0 +1,19 @@
|
||||
.. _cli:
|
||||
|
||||
.. index::
|
||||
single: Command Line Interface (CLI)
|
||||
|
||||
Command Line Interface (CLI)
|
||||
============================
|
||||
|
||||
This section is about the commandline interface of docxtemplater.
|
||||
|
||||
To install the cli, please use this command :
|
||||
|
||||
npm install -g docxtemplater-cli
|
||||
|
||||
https://github.com/open-xml-templating/docxtemplater-cli
|
||||
|
||||
The syntax is the following:
|
||||
|
||||
docxtemplater input.docx data.json output.docx
|
||||
261
docs/source/conf.py
Normal file
261
docs/source/conf.py
Normal file
@ -0,0 +1,261 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
#
|
||||
# docxtemplater documentation build configuration file, created by
|
||||
# sphinx-quickstart on Thu May 8 11:17:49 2014.
|
||||
#
|
||||
# This file is execfile()d with the current directory set to its
|
||||
# containing dir.
|
||||
#
|
||||
# Note that not all possible configuration values are present in this
|
||||
# autogenerated file.
|
||||
#
|
||||
# All configuration values have a default; values that are commented out
|
||||
# serve to show the default.
|
||||
|
||||
import sys
|
||||
import os
|
||||
|
||||
# If extensions (or modules to document with autodoc) are in another directory,
|
||||
# add these directories to sys.path here. If the directory is relative to the
|
||||
# documentation root, use os.path.abspath to make it absolute, like shown here.
|
||||
#sys.path.insert(0, os.path.abspath('.'))
|
||||
|
||||
# -- General configuration ------------------------------------------------
|
||||
|
||||
# If your documentation needs a minimal Sphinx version, state it here.
|
||||
#needs_sphinx = '1.0'
|
||||
|
||||
# Add any Sphinx extension module names here, as strings. They can be
|
||||
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
|
||||
# ones.
|
||||
extensions = [
|
||||
'sphinx.ext.autodoc',
|
||||
]
|
||||
|
||||
# Add any paths that contain templates here, relative to this directory.
|
||||
templates_path = ['_templates']
|
||||
|
||||
# The suffix of source filenames.
|
||||
source_suffix = '.rst'
|
||||
|
||||
# The encoding of source files.
|
||||
#source_encoding = 'utf-8-sig'
|
||||
|
||||
# The master toctree document.
|
||||
master_doc = 'index'
|
||||
|
||||
# General information about the project.
|
||||
project = u'docxtemplater'
|
||||
copyright = u'Edgar Hipp'
|
||||
|
||||
# The version info for the project you're documenting, acts as replacement for
|
||||
# |version| and |release|, also used in various other places throughout the
|
||||
# built documents.
|
||||
#
|
||||
|
||||
# The language for content autogenerated by Sphinx. Refer to documentation
|
||||
# for a list of supported languages.
|
||||
#language = None
|
||||
|
||||
# There are two options for replacing |today|: either, you set today to some
|
||||
# non-false value, then it is used:
|
||||
#today = ''
|
||||
# Else, today_fmt is used as the format for a strftime call.
|
||||
#today_fmt = '%B %d, %Y'
|
||||
|
||||
# List of patterns, relative to source directory, that match files and
|
||||
# directories to ignore when looking for source files.
|
||||
exclude_patterns = []
|
||||
|
||||
# The reST default role (used for this markup: `text`) to use for all
|
||||
# documents.
|
||||
#default_role = None
|
||||
|
||||
# If true, '()' will be appended to :func: etc. cross-reference text.
|
||||
#add_function_parentheses = True
|
||||
|
||||
# If true, the current module name will be prepended to all description
|
||||
# unit titles (such as .. function::).
|
||||
#add_module_names = True
|
||||
|
||||
# If true, sectionauthor and moduleauthor directives will be shown in the
|
||||
# output. They are ignored by default.
|
||||
#show_authors = False
|
||||
|
||||
# The name of the Pygments (syntax highlighting) style to use.
|
||||
pygments_style = 'sphinx'
|
||||
|
||||
# A list of ignored prefixes for module index sorting.
|
||||
#modindex_common_prefix = []
|
||||
|
||||
# If true, keep warnings as "system message" paragraphs in the built documents.
|
||||
#keep_warnings = False
|
||||
|
||||
|
||||
# -- Options for HTML output ----------------------------------------------
|
||||
|
||||
# The theme to use for HTML and HTML Help pages. See the documentation for
|
||||
# a list of builtin themes.
|
||||
|
||||
on_rtd = os.environ.get('READTHEDOCS', None) == 'True'
|
||||
|
||||
if not on_rtd: # only import and set the theme if we're building docs locally
|
||||
import sphinx_rtd_theme
|
||||
html_theme = "sphinx_rtd_theme"
|
||||
html_theme_path = [sphinx_rtd_theme.get_html_theme_path()]
|
||||
|
||||
# Theme options are theme-specific and customize the look and feel of a theme
|
||||
# further. For a list of options available for each theme, see the
|
||||
# documentation.
|
||||
#html_theme_options = {}
|
||||
|
||||
# Add any paths that contain custom themes here, relative to this directory.
|
||||
|
||||
# The name for this set of Sphinx documents. If None, it defaults to
|
||||
# "<project> v<release> documentation".
|
||||
#html_title = None
|
||||
|
||||
# A shorter title for the navigation bar. Default is the same as html_title.
|
||||
#html_short_title = None
|
||||
|
||||
# The name of an image file (relative to this directory) to place at the top
|
||||
# of the sidebar.
|
||||
#html_logo = None
|
||||
|
||||
# The name of an image file (within the static path) to use as favicon of the
|
||||
# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
|
||||
# pixels large.
|
||||
#html_favicon = None
|
||||
|
||||
# Add any paths that contain custom static files (such as style sheets) here,
|
||||
# relative to this directory. They are copied after the builtin static files,
|
||||
# so a file named "default.css" will overwrite the builtin "default.css".
|
||||
# html_static_path = ['_static']
|
||||
|
||||
# Add any extra paths that contain custom files (such as robots.txt or
|
||||
# .htaccess) here, relative to this directory. These files are copied
|
||||
# directly to the root of the documentation.
|
||||
#html_extra_path = []
|
||||
|
||||
# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
|
||||
# using the given strftime format.
|
||||
#html_last_updated_fmt = '%b %d, %Y'
|
||||
|
||||
# If true, SmartyPants will be used to convert quotes and dashes to
|
||||
# typographically correct entities.
|
||||
#html_use_smartypants = True
|
||||
|
||||
# Custom sidebar templates, maps document names to template names.
|
||||
#html_sidebars = {}
|
||||
|
||||
# Additional templates that should be rendered to pages, maps page names to
|
||||
# template names.
|
||||
#html_additional_pages = {}
|
||||
|
||||
# If false, no module index is generated.
|
||||
#html_domain_indices = True
|
||||
|
||||
# If false, no index is generated.
|
||||
#html_use_index = True
|
||||
|
||||
# If true, the index is split into individual pages for each letter.
|
||||
#html_split_index = False
|
||||
|
||||
# If true, links to the reST sources are added to the pages.
|
||||
#html_show_sourcelink = True
|
||||
|
||||
# If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
|
||||
#html_show_sphinx = True
|
||||
|
||||
# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
|
||||
#html_show_copyright = True
|
||||
|
||||
# If true, an OpenSearch description file will be output, and all pages will
|
||||
# contain a <link> tag referring to it. The value of this option must be the
|
||||
# base URL from which the finished HTML is served.
|
||||
#html_use_opensearch = ''
|
||||
|
||||
# This is the file name suffix for HTML files (e.g. ".xhtml").
|
||||
#html_file_suffix = None
|
||||
|
||||
# Output file base name for HTML help builder.
|
||||
htmlhelp_basename = 'docxtemplaterdoc'
|
||||
|
||||
|
||||
# -- Options for LaTeX output ---------------------------------------------
|
||||
|
||||
latex_elements = {
|
||||
# The paper size ('letterpaper' or 'a4paper').
|
||||
#'papersize': 'letterpaper',
|
||||
|
||||
# The font size ('10pt', '11pt' or '12pt').
|
||||
#'pointsize': '10pt',
|
||||
|
||||
# Additional stuff for the LaTeX preamble.
|
||||
#'preamble': '',
|
||||
}
|
||||
|
||||
# Grouping the document tree into LaTeX files. List of tuples
|
||||
# (source start file, target name, title,
|
||||
# author, documentclass [howto, manual, or own class]).
|
||||
latex_documents = [
|
||||
('index', 'docxtemplater.tex', u'docxtemplater Documentation',
|
||||
u'Edgar Hipp', 'manual'),
|
||||
]
|
||||
|
||||
# The name of an image file (relative to this directory) to place at the top of
|
||||
# the title page.
|
||||
#latex_logo = None
|
||||
|
||||
# For "manual" documents, if this is true, then toplevel headings are parts,
|
||||
# not chapters.
|
||||
#latex_use_parts = False
|
||||
|
||||
# If true, show page references after internal links.
|
||||
#latex_show_pagerefs = False
|
||||
|
||||
# If true, show URL addresses after external links.
|
||||
#latex_show_urls = False
|
||||
|
||||
# Documents to append as an appendix to all manuals.
|
||||
#latex_appendices = []
|
||||
|
||||
# If false, no module index is generated.
|
||||
#latex_domain_indices = True
|
||||
|
||||
|
||||
# -- Options for manual page output ---------------------------------------
|
||||
|
||||
# One entry per manual page. List of tuples
|
||||
# (source start file, name, description, authors, manual section).
|
||||
man_pages = [
|
||||
('index', 'docxtemplater', u'docxtemplater Documentation',
|
||||
[u'Edgar Hipp'], 1)
|
||||
]
|
||||
|
||||
# If true, show URL addresses after external links.
|
||||
#man_show_urls = False
|
||||
|
||||
|
||||
# -- Options for Texinfo output -------------------------------------------
|
||||
|
||||
# Grouping the document tree into Texinfo files. List of tuples
|
||||
# (source start file, target name, title, author,
|
||||
# dir menu entry, description, category)
|
||||
texinfo_documents = [
|
||||
('index', 'docxtemplater', u'docxtemplater Documentation',
|
||||
u'Edgar Hipp', 'docxtemplater', 'Generate docx documents from docx templates',
|
||||
'Miscellaneous'),
|
||||
]
|
||||
|
||||
# Documents to append as an appendix to all manuals.
|
||||
#texinfo_appendices = []
|
||||
|
||||
# If false, no module index is generated.
|
||||
#texinfo_domain_indices = True
|
||||
|
||||
# How to display URL addresses: 'footnote', 'no', or 'inline'.
|
||||
#texinfo_show_urls = 'footnote'
|
||||
|
||||
# If true, do not generate a @detailmenu in the "Top" node's menu.
|
||||
#texinfo_no_detailmenu = False
|
||||
415
docs/source/configuration.rst
Normal file
415
docs/source/configuration.rst
Normal file
@ -0,0 +1,415 @@
|
||||
.. index::
|
||||
single: Configuration
|
||||
|
||||
.. _configuration:
|
||||
|
||||
Configuration
|
||||
=============
|
||||
|
||||
You can configure docxtemplater with an options object by using the ``v4 constructor`` with two arguments.
|
||||
|
||||
.. code-block:: javascript
|
||||
|
||||
var doc = new Docxtemplater(zip, options);
|
||||
|
||||
Custom Parser
|
||||
--------------
|
||||
|
||||
The name of this option is `parser` (function).
|
||||
|
||||
With a custom parser you can parse the tags to for example add operators
|
||||
like '+', '-', or even create a Domain Specific Language to specify your tag values.
|
||||
|
||||
To enable this, you need to specify a custom parser.
|
||||
|
||||
Introduction
|
||||
~~~~~~~~~~~~
|
||||
|
||||
To understand this option better, it is good to understand how docxtemplater manages the scope.
|
||||
|
||||
Whenever docxtemplater needs to render any tag, for example `{name}`, docxtemplater will delegate the retrieval of the value to the scopemanager.
|
||||
|
||||
The scopemanager does the following :
|
||||
|
||||
* it compiles the tag, by calling `parser('name')` where 'name' is the string representing what is inside the docxtemplater tag. For loop tags, if the tag is `{#condition}`, the passed string is only `condition` (it does not contain the #).
|
||||
|
||||
The compilation of that tag should return an object containing a function at the `get` property.
|
||||
|
||||
* whenever the tag needs to be rendered, docxtemplater calls `parser('name').get({name: 'John'})`, if `{name: 'John'}` is the current scope.
|
||||
|
||||
When inside a loop, for example : `{#users}{name}{/users}`, there are several "scopes" in which it is possible to evaluate the `{name}` property. The "deepest" scope is always evaluated first, so if the data is : `{users: [{name: "John"}], name: "Mary"}`, the parser calls the function `parser('name').get({name:"John"})`. Now if the returned value from the `.get` method is `null` or `undefined`, docxtemplater will call the same parser one level up, until it reaches the end of the scope.
|
||||
|
||||
If the root scope also returns `null` or `undefined` for the `.get` call, then the value from the nullGetter is used.
|
||||
|
||||
As a second argument to the `parser()` call, you receive more meta data about the tag of the document (and you could check if it is a loop tag for example).
|
||||
|
||||
As a second argument to the `get()` call, you receive more meta data about the scope, including the full scopeList.
|
||||
|
||||
Lets take an example, If your template is :
|
||||
|
||||
.. code-block:: text
|
||||
|
||||
Hello {user}
|
||||
|
||||
And we call `doc.setData({user: "John"})`
|
||||
|
||||
Default Parser
|
||||
~~~~~~~~~~~~~~
|
||||
|
||||
docxtemplater uses by default the following parser :
|
||||
|
||||
.. code-block:: javascript
|
||||
|
||||
const options = {
|
||||
parser: function(tag) {
|
||||
// tag is "user"
|
||||
return {
|
||||
'get': function(scope) {
|
||||
// scope will be {user: "John"}
|
||||
if (tag === '.') {
|
||||
return scope;
|
||||
}
|
||||
else {
|
||||
// Here we return the property "user" of the object {user: "John"}
|
||||
return scope[tag];
|
||||
}
|
||||
}
|
||||
};
|
||||
},
|
||||
};
|
||||
const doc = new Docxtemplater(zip, options);
|
||||
|
||||
Angular Parser
|
||||
~~~~~~~~~~~~~~
|
||||
|
||||
A very useful parser is the angular-expressions parser, which has implemented useful features.
|
||||
|
||||
See `angular parser`_ for comprehensive documentation
|
||||
|
||||
.. _`angular parser`: angular_parse.html
|
||||
|
||||
Deep Dive on the parser
|
||||
~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
The parser function is given two arguments,
|
||||
|
||||
For the template
|
||||
|
||||
.. code-block:: text
|
||||
|
||||
Hello {#users}{.}{/}
|
||||
|
||||
Using following data :
|
||||
|
||||
.. code-block:: javascript
|
||||
|
||||
{users: ['Mary', 'John']}
|
||||
|
||||
And with this parser
|
||||
|
||||
.. code-block:: javascript
|
||||
|
||||
function parser(scope, context) [
|
||||
console.log(scope);
|
||||
console.log(context);
|
||||
}
|
||||
|
||||
|
||||
For the tag `.` in the first iteration, the arguments will be :
|
||||
|
||||
.. code-block:: javascript
|
||||
|
||||
scope = { "name": "Jane" }
|
||||
context = {
|
||||
"num": 1, // This corresponds to the level of the nesting, the {#users} tag is level 0, the {.} is level 1
|
||||
"scopeList": [
|
||||
{
|
||||
"users": [
|
||||
{
|
||||
"name": "Jane"
|
||||
},
|
||||
{
|
||||
"name": "Mary"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "Jane"
|
||||
}
|
||||
],
|
||||
"scopePath": [
|
||||
"users"
|
||||
],
|
||||
"scopePathItem": [
|
||||
0
|
||||
]
|
||||
// Together, scopePath and scopePathItem describe where we are in the data, in this case, we are in the tag users[0] (the first user)
|
||||
}
|
||||
|
||||
|
||||
Simple Parser example for [lower] and [upper]
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
Here is an example parser that allows you to lowercase or uppercase the data if writing your tag as : `{user[lower]}` or `{user[upper]}` :
|
||||
|
||||
.. code-block:: javascript
|
||||
|
||||
options = {
|
||||
parser: function(tag) {
|
||||
// tag is "foo[lower]"
|
||||
let changeCase = false;
|
||||
if(tag.endsWith("[lower]") {
|
||||
changeCase = "lower";
|
||||
}
|
||||
if(tag.endsWith("[upper]") {
|
||||
changeCase = "upper";
|
||||
}
|
||||
return {
|
||||
'get': function(scope) {
|
||||
let result = null;
|
||||
// scope will be {user: "John"}
|
||||
if (tag === '.') {
|
||||
result = scope;
|
||||
}
|
||||
else {
|
||||
// Here we use the property "user" of the object {user: "John"}
|
||||
result = scope[tag];
|
||||
}
|
||||
|
||||
if (typeof result === "string") {
|
||||
if(changeCase === "upper") {
|
||||
return result.toUpperCase();
|
||||
}
|
||||
else if(changeCase === "lower") {
|
||||
return result.toLowerCase();
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
};
|
||||
},
|
||||
};
|
||||
new Docxtemplater(zip, options);
|
||||
|
||||
Simple Parser example for {$index} and {$isLast} inside loops
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
As an other example, it is possible to use the `{$index}` tag inside a loop by using following parser :
|
||||
|
||||
.. code-block:: javascript
|
||||
|
||||
function parser(tag) {
|
||||
return {
|
||||
get(scope, context) {
|
||||
if (tag === "$index") {
|
||||
const indexes = context.scopePathItem;
|
||||
return indexes[indexes.length - 1];
|
||||
}
|
||||
if (tag === "$isLast") {
|
||||
const totalLength =
|
||||
context.scopePathLength[context.scopePathLength.length - 1];
|
||||
const index =
|
||||
context.scopePathItem[context.scopePathItem.length - 1];
|
||||
return index === totalLength - 1;
|
||||
}
|
||||
if (tag === "$isFirst") {
|
||||
const index =
|
||||
context.scopePathItem[context.scopePathItem.length - 1];
|
||||
return index === 0;
|
||||
}
|
||||
return scope[tag];
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
Parser example to avoid using the parent scope if a value is null on the main scope
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
|
||||
When using following template:
|
||||
|
||||
.. code-block:: text
|
||||
|
||||
{#products}
|
||||
{name}, {price} €
|
||||
{/products}
|
||||
|
||||
With following data :
|
||||
|
||||
.. code-block:: javascript
|
||||
|
||||
doc.setData({
|
||||
name: 'Santa Katerina',
|
||||
products: [
|
||||
{
|
||||
price: '$3.99'
|
||||
}
|
||||
]
|
||||
});
|
||||
|
||||
The {name} tag will use the "root scope", since it is not present in the products array.
|
||||
|
||||
If you explicitly don't want this behavior because you want the nullGetter to handle the tag in this case, you could use the following parser :
|
||||
|
||||
.. code-block:: javascript
|
||||
|
||||
parser(tag) {
|
||||
return {
|
||||
get(scope, context) {
|
||||
if (context.num < context.scopePath.length) {
|
||||
return null;
|
||||
}
|
||||
// You can customize your parser here instead of scope[tag] of course
|
||||
return scope[tag];
|
||||
},
|
||||
};
|
||||
},
|
||||
|
||||
The context.num value contains the scope level for this particular evalutation.
|
||||
|
||||
When evaluating the {name} tag in the example above, there are two evaluations:
|
||||
|
||||
.. code-block:: javascript
|
||||
|
||||
// For the first evaluation, when evaluating in the {#users} scope
|
||||
context.num = 1;
|
||||
context.scopePath = ["users"];
|
||||
// This evaluation returns null because the
|
||||
// first product doesn't have a name property
|
||||
|
||||
// For the second evaluation, when evaluating in the root scope
|
||||
context.num = 0;
|
||||
context.scopePath = ["users"];
|
||||
// This evaluation returns null because of the extra added condition
|
||||
|
||||
Note that you could even make this behavior dependent on a given prefix, for
|
||||
example, if you want to by default, use the mechanism of scope traversal, but
|
||||
for some tags, allow only to evaluate on the deepest scope, you could add the
|
||||
following condition :
|
||||
|
||||
.. code-block:: javascript
|
||||
|
||||
parser(tag) {
|
||||
return {
|
||||
get(scope, context) {
|
||||
const onlyDeepestScope = tag[0] === '!';
|
||||
if (onlyDeepestScope) {
|
||||
if (context.num < context.scopePath.length) {
|
||||
return null;
|
||||
}
|
||||
else {
|
||||
// Transform "!name" into "name"
|
||||
tag = tag.substr(1);
|
||||
}
|
||||
}
|
||||
// You can customize your parser here instead of scope[tag] of course
|
||||
return scope[tag];
|
||||
},
|
||||
};
|
||||
},
|
||||
|
||||
Custom delimiters
|
||||
-----------------
|
||||
|
||||
You can set up your custom delimiters:
|
||||
|
||||
.. code-block:: javascript
|
||||
|
||||
new Docxtemplater(zip, {delimiters:{start:'[[',end:']]'}});
|
||||
|
||||
|
||||
paragraphLoop
|
||||
-------------
|
||||
|
||||
The paragraphLoop option has been added in version 3.2.0.
|
||||
|
||||
It is recommended to turn that option on, since it makes the rendering a little bit easier to reason about. Since it breaks backwards-compatibility, it is turned off by default.
|
||||
|
||||
.. code-block:: javascript
|
||||
|
||||
new Docxtemplater(zip, {paragraphLoop:true});
|
||||
|
||||
It allows to loop around paragraphs without having additional spacing.
|
||||
|
||||
When you write the following template
|
||||
|
||||
.. code-block:: text
|
||||
|
||||
The users list is :
|
||||
{#users}
|
||||
{name}
|
||||
{/users}
|
||||
End of users list
|
||||
|
||||
Most users of the library would expect to have no spaces between the different
|
||||
names.
|
||||
|
||||
The output without the option is as follows :
|
||||
|
||||
.. code-block:: text
|
||||
|
||||
The users list is :
|
||||
|
||||
John
|
||||
|
||||
Jane
|
||||
|
||||
Mary
|
||||
|
||||
End of users list
|
||||
|
||||
|
||||
With the paragraphLoop option turned on, the output becomes :
|
||||
|
||||
|
||||
.. code-block:: text
|
||||
|
||||
The users list is :
|
||||
John
|
||||
Jane
|
||||
Mary
|
||||
End of users list
|
||||
|
||||
The rule is quite simple :
|
||||
|
||||
If the opening loop ({#users}) and the closing loop ({/users}) are both on
|
||||
separate paragraphs (and there is no other content on those paragraphs), treat
|
||||
the loop as a paragraph loop (eg create one new paragraph for each loop) where
|
||||
you remove the first and last paragraphs (the ones containing the loop open and
|
||||
loop close tags).
|
||||
|
||||
nullGetter
|
||||
----------
|
||||
|
||||
You can customize the value that is shown whenever the parser (documented
|
||||
above) returns 'null' or undefined. By default the nullGetter is the following
|
||||
function
|
||||
|
||||
.. code-block:: javascript
|
||||
|
||||
nullGetter(part, scopeManager) {
|
||||
if (!part.module) {
|
||||
return "undefined";
|
||||
}
|
||||
if (part.module === "rawxml") {
|
||||
return "";
|
||||
}
|
||||
return "";
|
||||
},
|
||||
|
||||
This means that the default value for simple tags is to show "undefined".
|
||||
The default for rawTags ({@rawTag}) is to drop the paragraph completely (you could enter any xml here).
|
||||
|
||||
The scopeManager variable contains some meta information about the tag, for example, if the template is : {#users}{name}{/users} and the tag `{name}` is undefined, `scopeManager.scopePath === ["users", "name"]`
|
||||
|
||||
linebreaks
|
||||
----------
|
||||
|
||||
You can enable linebreaks, if your data contains newlines, those will be shown as linebreaks in the document
|
||||
|
||||
.. code-block:: javascript
|
||||
|
||||
const doc = new Docxtemplater(zip, {linebreaks:true});
|
||||
doc.setData({text: "My text,\nmultiline"});
|
||||
doc.render();
|
||||
|
||||
241
docs/source/errors.rst
Normal file
241
docs/source/errors.rst
Normal file
@ -0,0 +1,241 @@
|
||||
.. _cli:
|
||||
|
||||
.. index::
|
||||
single: Errors
|
||||
|
||||
Error handling
|
||||
==============
|
||||
|
||||
This section is about how to handle Docxtemplater errors.
|
||||
|
||||
To be able to see these errors, you need to catch them properly.
|
||||
|
||||
.. code-block:: javascript
|
||||
|
||||
try {
|
||||
// render the document (replace all occurences of {first_name} by John, {last_name} by Doe, ...)
|
||||
doc.render()
|
||||
}
|
||||
catch (error) {
|
||||
// The error thrown here contains additional information when logged with JSON.stringify (it contains a properties object containing all suberrors).
|
||||
function replaceErrors(key, value) {
|
||||
if (value instanceof Error) {
|
||||
return Object.getOwnPropertyNames(value).reduce(function(error, key) {
|
||||
error[key] = value[key];
|
||||
return error;
|
||||
}, {});
|
||||
}
|
||||
return value;
|
||||
}
|
||||
console.log(JSON.stringify({error: error}, replaceErrors));
|
||||
|
||||
if (error.properties && error.properties.errors instanceof Array) {
|
||||
const errorMessages = error.properties.errors.map(function (error) {
|
||||
return error.properties.explanation;
|
||||
}).join("\n");
|
||||
console.log('errorMessages', errorMessages);
|
||||
// errorMessages is a humanly readable message looking like this :
|
||||
// 'The tag beginning with "foobar" is unopened'
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
|
||||
Error Schema
|
||||
------------
|
||||
|
||||
All errors thrown by docxtemplater have the following schema:
|
||||
|
||||
.. code-block:: text
|
||||
|
||||
{
|
||||
name: One of [GenericError, TemplateError, ScopeParserError, InternalError, MultiError],
|
||||
message: The message of that error,
|
||||
properties : {
|
||||
explanation: An error that is user friendly (in english), explaining what failed exactly. This error could be shown as is to end users
|
||||
id: An identifier of the error that is unique for that type of Error
|
||||
... : The other properties are specific to each type of error.
|
||||
}
|
||||
}
|
||||
|
||||
Error example
|
||||
-------------
|
||||
|
||||
If the content of your template is `{user {name}`, docxtemplater will throw the following error :
|
||||
|
||||
.. code-block:: javascript
|
||||
|
||||
try {
|
||||
doc.render()
|
||||
}
|
||||
catch (e) {
|
||||
// All these expressions are true
|
||||
e.name === "TemplateError"
|
||||
e.message === "Unclosed tag"
|
||||
e.properties.explanation === "The tag beginning with '{user ' is unclosed"
|
||||
e.properties.id === "unclosed_tag"
|
||||
e.properties.context === "{user {"
|
||||
e.properties.xtag === "user "
|
||||
}
|
||||
|
||||
|
||||
List of all Error Identifiers
|
||||
-----------------------------
|
||||
|
||||
All errors can be identified with their id (`e.properties.id`).
|
||||
|
||||
The ids are :
|
||||
|
||||
**multi_error**: This error means that multiple errors where found in the template (1 or more). See below for handling these errors.
|
||||
|
||||
**unopened_tag**: This error happens if a tag is closed but not opened. For example with the following template :
|
||||
|
||||
.. code-block:: text
|
||||
|
||||
Hello name} !
|
||||
|
||||
**unclosed_tag**: This error happens if a tag is opened but not closed. For example with the following template :
|
||||
|
||||
.. code-block:: text
|
||||
|
||||
Hello {name !
|
||||
|
||||
**no_xml_tag_found_at_left** and **no_xml_tag_found_at_right**: This error happens if a rawXMLTag doesn't find a `<w:p>` element
|
||||
|
||||
.. code-block:: text
|
||||
|
||||
<w:p><w:t>{@raw}</w:t>
|
||||
// Note that the `</w:p>` tag is missing.
|
||||
|
||||
**utf8_decode** is an internal error, please report it if you see it
|
||||
|
||||
**xmltemplater_content_must_be_string** is an internal error that happens if you try to template something that is not a string (a number for example)
|
||||
|
||||
**raw_xml_tag_should_be_only_text_in_paragraph** happens when a rawXMLTag {@raw} is not the only text in the paragraph. For example, writing ` {@raw}` (Note the spaces) is not acceptable because the {@raw} tag replaces the full paragraph. We prefer to throw an Error now rather than have "strange behavior" because the spaces "disappeared".
|
||||
|
||||
To correct this error, you have to add manually the text that you want in your raw tag. (Or you can use the https://docxtemplater.com/modules/word-run/ which adds a tag that can replace rawXML inside a tag).
|
||||
|
||||
Writing
|
||||
|
||||
.. code-block:: text
|
||||
|
||||
{@my_first_tag}{my_second_tag}
|
||||
|
||||
Or even
|
||||
|
||||
.. code-block:: text
|
||||
|
||||
Hello {@my_first_tag}
|
||||
|
||||
Is misusing docxtemplater.
|
||||
|
||||
The `@` at the beginning means "replace the xml of **the current paragraph** with scope.my_first_tag" so that means that everything else in that Paragraph will be removed.
|
||||
|
||||
**unclosed_loop** and **unopened_loop** happen when a loop is closed but never opened : for example
|
||||
|
||||
.. code-block:: text
|
||||
|
||||
{#users}{name}
|
||||
|
||||
or
|
||||
|
||||
.. code-block:: text
|
||||
|
||||
{name}{/users}
|
||||
|
||||
**closing_tag_does_not_match_opening_tag** happens when a loop is closed but doesn't match the opening tag
|
||||
|
||||
.. code-block:: text
|
||||
|
||||
{#users}{name}{/people}
|
||||
|
||||
**scopeparser_compilation_failed** happens when your parser throws an error during compilation. The parser is the second argument of the constructor ``new Docxtemplater(zip, {parser: function parser(tag) {}});``
|
||||
|
||||
For example, if your template is :
|
||||
|
||||
.. code-block:: text
|
||||
|
||||
{name++}
|
||||
|
||||
and you use the angularParser, you will have this error. The error happens when you call parser('name++'); The underlying error can be read in `e.properties.rootError`
|
||||
|
||||
|
||||
**unimplemented_tag_type** happens when a tag type is not implemented. It should normally not happen, unless you changed docxtemplater code.
|
||||
|
||||
**malformed_xml** happens when a xml file of the document cannot be parsed correctly.
|
||||
|
||||
**loop_position_invalid** happens when a loop would produce invalid XML.
|
||||
|
||||
For example, if you write :
|
||||
|
||||
.. code-block:: text
|
||||
|
||||
======================
|
||||
| header1 | header2 |
|
||||
----------------------
|
||||
| {#users} | content |
|
||||
======================
|
||||
|
||||
{/users}
|
||||
|
||||
this is not allowed since a loop that starts in a table should also end in that table.
|
||||
|
||||
Cannot attach a module that was already attached
|
||||
------------------------------------------------
|
||||
|
||||
You might get this error :
|
||||
|
||||
`Cannot attach a module that was already attached : "ImageModule". Maybe you are instantiating the module at the root level, and using it for multiple instances of Docxtemplater`
|
||||
|
||||
In previous versions the error was `Cannot attach a module that was already attached`
|
||||
|
||||
This happens if you are reusing the same module instance twice.
|
||||
|
||||
It usually means that you are calling `new ImageModule()` just once, but you
|
||||
should call it for each instance of docxtemplater.
|
||||
|
||||
The following code will throw the error when calling "generate" twice:
|
||||
|
||||
.. code-block:: javascript
|
||||
|
||||
var Docxtemplater = require("docxtemplater");
|
||||
var ImageModule = require("docxtemplater-image-module");
|
||||
var imageModule = new ImageModule(opts);
|
||||
|
||||
function generate(content) {
|
||||
var zip = new PizZip(content);
|
||||
var doc = new Docxtemplater(zip, {modules: [imageModule]});
|
||||
doc.setData(data);
|
||||
doc.render()
|
||||
}
|
||||
|
||||
You should always reconstruct an imageModule for each Docxtemplater instance.
|
||||
|
||||
The following code will no more throw the error :
|
||||
|
||||
.. code-block:: javascript
|
||||
|
||||
var Docxtemplater = require("docxtemplater");
|
||||
var ImageModule = require("docxtemplater-image-module");
|
||||
|
||||
function generate(content) {
|
||||
var zip = new PizZip(content);
|
||||
var imageModule = new ImageModule(opts);
|
||||
var doc = new Docxtemplater(zip, {modules: [imageModule] });
|
||||
doc.setData(data);
|
||||
doc.render()
|
||||
}
|
||||
|
||||
|
||||
Handling multiple errors
|
||||
------------------------
|
||||
|
||||
docxtemplater now has the ability to detect multiple errors in your template.
|
||||
If it detects multiple errors, it will throw an error that has the id **multi_error**
|
||||
|
||||
You can then have the following to view all errors :
|
||||
|
||||
.. code-block:: javascript
|
||||
|
||||
e.properties.errors.forEach(function(err) {
|
||||
console.log(err);
|
||||
});
|
||||
816
docs/source/faq.rst
Normal file
816
docs/source/faq.rst
Normal file
@ -0,0 +1,816 @@
|
||||
.. index::
|
||||
single: FAQ
|
||||
|
||||
.. _faq:
|
||||
|
||||
Frequently asked questions
|
||||
==========================
|
||||
|
||||
Inserting new lines
|
||||
-------------------
|
||||
|
||||
.. code-block:: javascript
|
||||
|
||||
const doc = new Docxtemplater(zip, {linebreaks: true});
|
||||
|
||||
then in your data, if a string contains a newline, it will be translated to a linebreak in the document.
|
||||
|
||||
Insert HTML formatted text
|
||||
--------------------------
|
||||
|
||||
It is possible to insert HTML formatted text using the `HTML pro module`_
|
||||
|
||||
.. _`HTML pro module`: https://docxtemplater.com/modules/html/
|
||||
|
||||
|
||||
Generate smaller docx using compression
|
||||
---------------------------------------
|
||||
|
||||
The size of the docx output can be big, in the case where you generate the zip the following way:
|
||||
|
||||
.. code-block:: javascript
|
||||
|
||||
doc.getZip().generate({ type: "nodebuffer"})
|
||||
|
||||
This is because the zip will not be compressed in that case. To force the compression (which could be slow because it is running in JS for files bigger than 10 MB)
|
||||
|
||||
.. code-block:: javascript
|
||||
|
||||
var zip = doc.getZip().generate({
|
||||
type: "nodebuffer",
|
||||
compression: "DEFLATE"
|
||||
});
|
||||
|
||||
Writing if else
|
||||
---------------
|
||||
|
||||
To write if/else, see the documentation on `sections`_ for if and `inverted sections`_ for else.
|
||||
|
||||
.. _`inverted sections`: tag_types.html#inverted-sections
|
||||
.. _`sections`: tag_types.html#sections
|
||||
|
||||
Using boolean operators (AND, OR) and comparison operators (`<`, `>`)
|
||||
---------------------------------------------------------------------
|
||||
|
||||
You can also have conditions with comparison operators (`<` and `>`), or boolean operators (`&&` and `||`) using `angular parser conditions`_.
|
||||
|
||||
.. _`angular parser conditions`: angular_parse.html#conditions
|
||||
|
||||
|
||||
Conditional Formatting
|
||||
----------------------
|
||||
|
||||
With the `PRO styling module`_ it is possible to have a table cell be styled depending on a given condition (for example).
|
||||
|
||||
.. _`PRO styling module`: https://docxtemplater.com/modules/styling/.
|
||||
|
||||
Using data filters
|
||||
------------------
|
||||
|
||||
You might want to be able to show data a bit differently for each template. For this, you can use the angular parser and the filters functionality.
|
||||
|
||||
For example, if a user wants to put something in uppercase, you could write in your template :
|
||||
|
||||
|
||||
.. code-block:: text
|
||||
|
||||
{ user.name | uppercase }
|
||||
|
||||
See `angular parser`_ for comprehensive documentation
|
||||
|
||||
.. _`angular parser`: angular_parse.html
|
||||
|
||||
Keep placeholders that don't have data
|
||||
--------------------------------------
|
||||
|
||||
It is possible to define which value to show when a tag resolves to
|
||||
undefined or null (for example when no data is present for that value).
|
||||
|
||||
For example, with the following template
|
||||
|
||||
.. code-block:: text
|
||||
|
||||
Hello {name}, your hobby is {hobby}.
|
||||
|
||||
.. code-block:: json
|
||||
|
||||
{
|
||||
"hobby": "football",
|
||||
}
|
||||
|
||||
The default behavior is to return "undefined" for empty values.
|
||||
|
||||
.. code-block:: text
|
||||
|
||||
Hello undefined, your hobby is football.
|
||||
|
||||
You can customize this to either return another string, or return the name of the tag itself, so that it will show :
|
||||
|
||||
.. code-block:: text
|
||||
|
||||
Hello {name}, your hobby is football.
|
||||
|
||||
It is possible to customize the value that will be shown for {name} by using the nullGetter option. In the following case, it will return "{name}", hence it will keep the placeholder {name} if the value does not exist.
|
||||
|
||||
.. code-block:: javascript
|
||||
|
||||
function nullGetter(part, scopeManager) {
|
||||
// part.module can be "loop", "rawxml", or empty, (or any other module name that you use)
|
||||
if (!part.module) {
|
||||
// part.value contains the content of the tag, eg "name" in our example
|
||||
return '{' + part.value + '}';
|
||||
}
|
||||
if (part.module === "rawxml") {
|
||||
return "";
|
||||
}
|
||||
return "";
|
||||
}
|
||||
const doc = new Docxtemplater(zip, {nullGetter: nullGetter});
|
||||
|
||||
Performance
|
||||
-----------
|
||||
|
||||
Docxtemplater is quite fast, for a pretty complex 50 page document, it can generate 250 output of those documents in 44 seconds, which is about 180ms per document.
|
||||
|
||||
There is also an interesting blog article https://javascript-ninja.fr/ at https://javascript-ninja.fr/optimizing-speed-in-node-js/ that explains how I optimized loops in docxtemplater.
|
||||
|
||||
Support for IE9 and lower
|
||||
-------------------------
|
||||
|
||||
docxtemplater should work on almost all browsers as of version 1 : IE7 + . Safari, Chrome, Opera, Firefox.
|
||||
|
||||
The only 'problem' is to load the binary file into the browser. This is not in docxtemplater's scope, but here is the recommended code to load the zip from the browser:
|
||||
|
||||
https://github.com/open-xml-templating/pizzip/blob/master/documentation/howto/read_zip.md
|
||||
|
||||
The following code should load the binary content on all browsers:
|
||||
|
||||
.. code-block:: javascript
|
||||
|
||||
PizZipUtils.getBinaryContent('path/to/content.zip', function(err, data) {
|
||||
if(err) {
|
||||
throw err; // or handle err
|
||||
}
|
||||
|
||||
var zip = new PizZip(data);
|
||||
});
|
||||
|
||||
Get list of placeholders
|
||||
-------------------------
|
||||
|
||||
To be able to construct a form dynamically or to validate the document
|
||||
beforehand, it can be useful to get access to all placeholders defined in a
|
||||
given template. Before rendering a document, docxtemplater parses the Word
|
||||
document into a compiled form. In this compiled form, the document is stored
|
||||
in an `AST`_ which contains all the necessary information to get the list of
|
||||
the variables and list them in a JSON object.
|
||||
|
||||
With the simple inspection module, it is possible to get this compiled form and
|
||||
show the list of tags.
|
||||
suite :
|
||||
|
||||
.. _`AST`: https://en.wikipedia.org/wiki/Abstract_syntax_tree
|
||||
|
||||
.. code-block:: javascript
|
||||
|
||||
var InspectModule = require("docxtemplater/js/inspect-module");
|
||||
var iModule = InspectModule();
|
||||
const doc = new Docxtemplater(zip, { modules: [iModule] });
|
||||
doc.render();
|
||||
var tags = iModule.getAllTags();
|
||||
console.log(tags);
|
||||
|
||||
With the following template :
|
||||
|
||||
.. code-block:: text
|
||||
|
||||
{company}
|
||||
|
||||
{#users}
|
||||
{name}
|
||||
{age}
|
||||
{/users}
|
||||
|
||||
It will log this object :
|
||||
|
||||
.. code-block:: json
|
||||
|
||||
{
|
||||
"company": {},
|
||||
"users": {
|
||||
"name": {},
|
||||
"age": {},
|
||||
},
|
||||
}
|
||||
|
||||
You can also get a more detailled tree by using :
|
||||
|
||||
.. code-block:: javascript
|
||||
|
||||
console.log(iModule.fullInspected["word/document.xml"]);
|
||||
|
||||
The code of the inspect-module is very simple, and can be found here : https://github.com/open-xml-templating/docxtemplater/blob/master/es6/inspect-module.js
|
||||
|
||||
Convert to PDF
|
||||
--------------
|
||||
|
||||
It is not possible to convert docx to PDF with docxtemplater, because docxtemplater is a templating engine and doesn't know how to render a given document. There are many
|
||||
tools to do this conversion.
|
||||
|
||||
The first one is to use `libreoffice headless`, which permits you to generate a
|
||||
PDF from a docx document :
|
||||
|
||||
You just have to run :
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
libreoffice --headless --convert-to pdf --outdir . input.docx
|
||||
|
||||
This will convert the input.docx file into input.pdf file.
|
||||
|
||||
The rendering is not 100% perfect, since it uses libreoffice and not microsoft
|
||||
word. If you just want to render some preview of a docx, I think this is a
|
||||
possible choice. You can do it from within your application by executing a
|
||||
process, it is not the most beautiful solution but it works.
|
||||
|
||||
If you want something that does the rendering better, I think you should use
|
||||
some specialized software. `PDFtron`_ is one of them, I haven't used it myself,
|
||||
but I know that some of the users of docxtemplater use it. (I'm not affiliated to PDFtron in any way).
|
||||
|
||||
.. _`PDFtron`: https://www.pdftron.com/pdfnet/addons.html
|
||||
|
||||
Pptx support
|
||||
------------
|
||||
|
||||
Docxtemplater handles pptx files without any special configuration (since version 3.0.4).
|
||||
|
||||
It does so by looking at the content of the "[Content_Types].xml" file and by looking at some docx/pptx specific content types.
|
||||
|
||||
My document is corrupted, what should I do ?
|
||||
--------------------------------------------
|
||||
|
||||
If you are inserting multiple images inside a loop, it is possible that word cannot handle the docPr attributes correctly. You can try to add the following code in your constructor.
|
||||
|
||||
.. code-block:: javascript
|
||||
|
||||
const myModule = {
|
||||
set(options) {
|
||||
if (options.Lexer) {
|
||||
this.Lexer = options.Lexer;
|
||||
}
|
||||
if (options.zip) {
|
||||
this.zip = options.zip;
|
||||
}
|
||||
},
|
||||
on(event) {
|
||||
if (event !== "syncing-zip") {
|
||||
return;
|
||||
}
|
||||
const zip = this.zip;
|
||||
const Lexer = this.Lexer;
|
||||
let prId = 1;
|
||||
function setSingleAttribute(partValue, attr, attrValue) {
|
||||
const regex = new RegExp(`(<.* ${attr}=")([^"]+)(".*)$`);
|
||||
if (regex.test(partValue)) {
|
||||
return partValue.replace(regex, `$1${attrValue}$3`);
|
||||
}
|
||||
let end = partValue.lastIndexOf("/>");
|
||||
if (end === -1) {
|
||||
end = partValue.lastIndexOf(">");
|
||||
}
|
||||
return (
|
||||
partValue.substr(0, end) +
|
||||
` ${attr}="${attrValue}"` +
|
||||
partValue.substr(end)
|
||||
);
|
||||
}
|
||||
zip.file(/\.xml$/).forEach(function(f) {
|
||||
let text = f.asText();
|
||||
const xmllexed = Lexer.xmlparse(text, {
|
||||
text: [],
|
||||
other: ["wp:docPr"],
|
||||
});
|
||||
if (xmllexed.length > 1) {
|
||||
text = xmllexed.reduce(function(fullText, part) {
|
||||
if (part.tag === "wp:docPr") {
|
||||
return fullText + setSingleAttribute(part.value, "id", prId++);
|
||||
}
|
||||
return fullText + part.value;
|
||||
}, "");
|
||||
}
|
||||
zip.file(f.name, text);
|
||||
});
|
||||
}
|
||||
});
|
||||
const doc = new Docxtemplater(zip, { modules: [myModule]});
|
||||
|
||||
Attaching modules for extra functionality
|
||||
-----------------------------------------
|
||||
|
||||
If you have created or have access to docxtemplater PRO modules, you can attach them with the following code :
|
||||
|
||||
|
||||
.. code-block:: javascript
|
||||
|
||||
const doc = new Docxtemplater(zip, {modules: [...]});
|
||||
doc.setData(data);
|
||||
|
||||
Ternaries are not working well with angular-parser
|
||||
--------------------------------------------------
|
||||
|
||||
There is a common issue which is to use ternary on scopes that are not the current scope, which makes the ternary appear as if it always showed the second option.
|
||||
|
||||
For example, with following data :
|
||||
|
||||
.. code-block:: javascript
|
||||
|
||||
doc.setData({
|
||||
user: {
|
||||
gender: 'F',
|
||||
name: "Mary",
|
||||
hobbies: [{
|
||||
name: 'play football',
|
||||
},{
|
||||
name: 'read books',
|
||||
}]
|
||||
}
|
||||
})
|
||||
|
||||
And by using the following template :
|
||||
|
||||
.. code-block:: text
|
||||
|
||||
{#user}
|
||||
{name} is a kind person.
|
||||
|
||||
{#hobbies}
|
||||
- {gender == 'F' : 'She' : 'He'} likes to {name}
|
||||
{/hobbies}
|
||||
{/}
|
||||
|
||||
This will print :
|
||||
|
||||
|
||||
.. code-block:: text
|
||||
|
||||
Mary is a kind person.
|
||||
|
||||
- He likes to play football
|
||||
- He likes to read books
|
||||
|
||||
Note that the pronoun "He" is used instead of "She".
|
||||
|
||||
The reason for this behavior is that the {gender == 'F' : "She" : "He"} expression is evaluating in the scope of hobby, where gender does not even exist. Since the condtion `gender == 'F'` is false (since gender is undefined), the return value is "He". However, in the scope of the hobby, we do not know the gender so the return value should be null.
|
||||
|
||||
We can instead write a custom filter that will return "She" if the input is "F", "He" if the input is "M", and null if the input is anything else.
|
||||
|
||||
The code would look like this :
|
||||
|
||||
.. code-block:: javascript
|
||||
|
||||
expressions.filters.pronoun = function(input) {
|
||||
if(input === "F") {
|
||||
return "She";
|
||||
}
|
||||
if(input === "M") {
|
||||
return "He";
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
And use the following in your template :
|
||||
|
||||
.. code-block:: text
|
||||
|
||||
{#user}
|
||||
{name} is a kind person.
|
||||
|
||||
{#hobbies}
|
||||
- {gender | pronoun} likes to {name}
|
||||
{/hobbies}
|
||||
{/}
|
||||
|
||||
|
||||
Multi scope expressions do not work with the angularParser
|
||||
----------------------------------------------------------
|
||||
|
||||
If you would like to have multi-scope expressions with the angularparser, for example :
|
||||
|
||||
You would like to do : `{#users}{ date - age }{/users}`, where date is in the "global scope", and age in the subscope `users`, as in the following data :
|
||||
|
||||
.. code-block:: json
|
||||
|
||||
{
|
||||
"date": 2019,
|
||||
"users": [
|
||||
{
|
||||
"name": "John",
|
||||
"age": 44
|
||||
},
|
||||
{
|
||||
"name": "Mary",
|
||||
"age": 22
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
You can make use of a feature of the angularParser and the fact that docxtemplater gives you access to the whole scopeList.
|
||||
|
||||
.. code-block:: javascript
|
||||
|
||||
// Please make sure to use angular-expressions 1.0.1 or later
|
||||
// More detail at https://github.com/open-xml-templating/docxtemplater/issues/488
|
||||
var expressions = require("angular-expressions");
|
||||
var assign = require("lodash/assign");
|
||||
function angularParser(tag) {
|
||||
if (tag === ".") {
|
||||
return {
|
||||
get(s) {
|
||||
return s;
|
||||
},
|
||||
};
|
||||
}
|
||||
const expr = expressions.compile(
|
||||
tag.replace(/(’|‘)/g, "'").replace(/(“|”)/g, '"')
|
||||
);
|
||||
return {
|
||||
get(scope, context) {
|
||||
let obj = {};
|
||||
const scopeList = context.scopeList;
|
||||
const num = context.num;
|
||||
for (let i = 0, len = num + 1; i < len; i++) {
|
||||
obj = assign(obj, scopeList[i]);
|
||||
}
|
||||
return expr(scope, obj);
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
const doc = new Docxtemplater(zip, {parser: angularParser});
|
||||
|
||||
.. _cors:
|
||||
|
||||
Access to XMLHttpRequest at file.docx from origin 'null' has been blocked by CORS policy
|
||||
----------------------------------------------------------------------------------------
|
||||
|
||||
This happens if you use the HTML sample script but are not using a webserver.
|
||||
|
||||
If your browser window shows a URL starting with `file://`, then you are not using a webserver, but the filesystem itself.
|
||||
|
||||
For security reasons, the browsers don't let you load files from the local file system.
|
||||
|
||||
To do this, you have to setup a small web server.
|
||||
|
||||
The simplest way of starting a webserver is to run following command :
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
npx http-server
|
||||
# if you don't have npx, you can also do :
|
||||
# npm install -g http-server && http-server .
|
||||
|
||||
On your production server, you should probably use a more robust webserver such as nginx, or any webserver that you are currently using for static files.
|
||||
|
||||
Docxtemplater in an angular project
|
||||
-----------------------------------
|
||||
|
||||
There is an `online angular demo`_ available on stackblitz.
|
||||
|
||||
.. _`online angular demo`: https://stackblitz.com/edit/angular-docxtemplater-example?file=src%2Fapp%2Fproduct-list%2Fproduct-list.component.ts
|
||||
|
||||
If you are using an angular version that supports the `import` keyword, you can use the following code :
|
||||
|
||||
.. code-block:: javascript
|
||||
|
||||
import { Component } from "@angular/core";
|
||||
import Docxtemplater from "docxtemplater";
|
||||
import PizZip from "pizzip";
|
||||
import PizZipUtils from "pizzip/utils/index.js";
|
||||
import { saveAs } from "file-saver";
|
||||
|
||||
function loadFile(url, callback) {
|
||||
PizZipUtils.getBinaryContent(url, callback);
|
||||
}
|
||||
|
||||
@Component({
|
||||
selector: "app-product-list",
|
||||
templateUrl: "./product-list.component.html",
|
||||
styleUrls: ["./product-list.component.css"]
|
||||
})
|
||||
export class ProductListComponent {
|
||||
generate() {
|
||||
loadFile("https://docxtemplater.com/tag-example.docx", function(
|
||||
error,
|
||||
content
|
||||
) {
|
||||
if (error) {
|
||||
throw error;
|
||||
}
|
||||
var zip = new PizZip(content);
|
||||
var doc = new Docxtemplater(zip);
|
||||
doc.setData({
|
||||
first_name: "John",
|
||||
last_name: "Doe",
|
||||
phone: "0652455478",
|
||||
description: "New Website"
|
||||
});
|
||||
try {
|
||||
// render the document (replace all occurences of {first_name} by John, {last_name} by Doe, ...)
|
||||
doc.render();
|
||||
} catch (error) {
|
||||
// The error thrown here contains additional information when logged with JSON.stringify (it contains a properties object containing all suberrors).
|
||||
function replaceErrors(key, value) {
|
||||
if (value instanceof Error) {
|
||||
return Object.getOwnPropertyNames(value).reduce(function(
|
||||
error,
|
||||
key
|
||||
) {
|
||||
error[key] = value[key];
|
||||
return error;
|
||||
},
|
||||
{});
|
||||
}
|
||||
return value;
|
||||
}
|
||||
console.log(JSON.stringify({ error: error }, replaceErrors));
|
||||
|
||||
if (error.properties && error.properties.errors instanceof Array) {
|
||||
const errorMessages = error.properties.errors
|
||||
.map(function(error) {
|
||||
return error.properties.explanation;
|
||||
})
|
||||
.join("\n");
|
||||
console.log("errorMessages", errorMessages);
|
||||
// errorMessages is a humanly readable message looking like this :
|
||||
// 'The tag beginning with "foobar" is unopened'
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
var out = doc.getZip().generate({
|
||||
type: "blob",
|
||||
mimeType:
|
||||
"application/vnd.openxmlformats-officedocument.wordprocessingml.document"
|
||||
}); //Output the document using Data-URI
|
||||
saveAs(out, "output.docx");
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
Docxtemplater in a vuejs project
|
||||
--------------------------------
|
||||
|
||||
There is an `online vuejs demo`_ available on stackblitz.
|
||||
|
||||
.. _`online vuejs demo`: https://stackblitz.com/edit/vuejs-docxtemplater-example?file=button.component.js
|
||||
|
||||
If you are using vuejs 2.0 version that supports the `import` keyword, you can use the following code :
|
||||
|
||||
.. code-block:: javascript
|
||||
|
||||
import Docxtemplater from "docxtemplater";
|
||||
import PizZip from "pizzip";
|
||||
import PizZipUtils from "pizzip/utils/index.js";
|
||||
import { saveAs } from "file-saver";
|
||||
|
||||
function loadFile(url, callback) {
|
||||
PizZipUtils.getBinaryContent(url, callback);
|
||||
}
|
||||
|
||||
export default {
|
||||
methods: {
|
||||
renderDoc() {
|
||||
loadFile("https://docxtemplater.com/tag-example.docx", function(
|
||||
error,
|
||||
content
|
||||
) {
|
||||
if (error) {
|
||||
throw error;
|
||||
}
|
||||
var zip = new PizZip(content);
|
||||
var doc = new Docxtemplater(zip);
|
||||
doc.setData({
|
||||
first_name: "John",
|
||||
last_name: "Doe",
|
||||
phone: "0652455478",
|
||||
description: "New Website"
|
||||
});
|
||||
try {
|
||||
// render the document (replace all occurences of {first_name} by John, {last_name} by Doe, ...)
|
||||
doc.render();
|
||||
} catch (error) {
|
||||
// The error thrown here contains additional information when logged with JSON.stringify (it contains a properties object containing all suberrors).
|
||||
function replaceErrors(key, value) {
|
||||
if (value instanceof Error) {
|
||||
return Object.getOwnPropertyNames(value).reduce(function(
|
||||
error,
|
||||
key
|
||||
) {
|
||||
error[key] = value[key];
|
||||
return error;
|
||||
},
|
||||
{});
|
||||
}
|
||||
return value;
|
||||
}
|
||||
console.log(JSON.stringify({ error: error }, replaceErrors));
|
||||
|
||||
if (error.properties && error.properties.errors instanceof Array) {
|
||||
const errorMessages = error.properties.errors
|
||||
.map(function(error) {
|
||||
return error.properties.explanation;
|
||||
})
|
||||
.join("\n");
|
||||
console.log("errorMessages", errorMessages);
|
||||
// errorMessages is a humanly readable message looking like this :
|
||||
// 'The tag beginning with "foobar" is unopened'
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
var out = doc.getZip().generate({
|
||||
type: "blob",
|
||||
mimeType:
|
||||
"application/vnd.openxmlformats-officedocument.wordprocessingml.document"
|
||||
}); //Output the document using Data-URI
|
||||
saveAs(out, "output.docx");
|
||||
});
|
||||
}
|
||||
},
|
||||
|
||||
template: `
|
||||
<button @click="renderDoc">
|
||||
Render docx template
|
||||
</button>
|
||||
`
|
||||
};
|
||||
|
||||
Getting access to page number / total number of pages or regenerate Table of Contents
|
||||
-------------------------------------------------------------------------------------
|
||||
|
||||
Sometimes, you would like to know what are the total number of pages in the
|
||||
document, or what is the page number at the current tag position.
|
||||
|
||||
This is something that will never be achievable with docxtemplater, because
|
||||
docxtemplater is only a templating engine : it does know how to parse the docx
|
||||
format. However, it has no idea on how the docx is rendered at the end : the
|
||||
width, height of each paragraph determines the number of pages in a document.
|
||||
|
||||
Since docxtemplater does not know how to render a docx document, (which
|
||||
determines the page numbers), this is why it is impossible to regenerate the
|
||||
page numbers within docxtemplater.
|
||||
|
||||
Also, even across different "official" rendering engines, the page numbers may vary. Depending on whether you open a document with Office Online, Word 2013 or Word 2016 or the Mac versions of Word, you can have some slight differences that will, at the end, influence the number of pages or the position of some elements within a page.
|
||||
|
||||
The amount of work to write a good rendering engine would be very huge (a few years at least for a team of 5-10 people).
|
||||
|
||||
Special character keys with angular parser throws error
|
||||
-------------------------------------------------------
|
||||
|
||||
The error that you could see is this, when using the tag `{être}`.
|
||||
|
||||
.. code-block:: text
|
||||
|
||||
Error: [$parse:lexerr] Lexer Error: Unexpected next character at columns 0-0 [ê] in expression [être].
|
||||
|
||||
This is because angular-expressions does not allow non-ascii characters.
|
||||
You will need angular-expressions version 1.1.0 which adds the
|
||||
`isIdentifierStart` and `isIdentifierContinue` properties.
|
||||
|
||||
You can fix this issue by adding the characters that you would like to support, for example :
|
||||
|
||||
.. code-block:: javascript
|
||||
|
||||
function validChars(ch) {
|
||||
return (
|
||||
(ch >= "a" && ch <= "z") ||
|
||||
(ch >= "A" && ch <= "Z") ||
|
||||
ch === "_" ||
|
||||
ch === "$" ||
|
||||
"ÀÈÌÒÙàèìòùÁÉÍÓÚáéíóúÂÊÎÔÛâêîôûÃÑÕãñõÄËÏÖÜŸäëïöüÿß".indexOf(ch) !== -1
|
||||
);
|
||||
}
|
||||
function angularParser(tag) {
|
||||
if (tag === '.') {
|
||||
return {
|
||||
get: function(s){ return s;}
|
||||
};
|
||||
}
|
||||
const expr = expressions.compile(
|
||||
tag.replace(/(’|‘)/g, "'").replace(/(“|”)/g, '"'),
|
||||
{
|
||||
isIdentifierStart: validChars,
|
||||
isIdentifierContinue: validChars
|
||||
}
|
||||
);
|
||||
return {
|
||||
get: function(scope, context) {
|
||||
let obj = {};
|
||||
const scopeList = context.scopeList;
|
||||
const num = context.num;
|
||||
for (let i = 0, len = num + 1; i < len; i++) {
|
||||
obj = assign(obj, scopeList[i]);
|
||||
}
|
||||
return expr(scope, obj);
|
||||
}
|
||||
};
|
||||
}
|
||||
new Docxtemplater(zip, {parser:angularParser});
|
||||
|
||||
|
||||
Remove proofstate tag
|
||||
---------------------
|
||||
|
||||
The proofstate tag in a document marks the document as spell-checked when last saved.
|
||||
After rendering a document with docxtemplater, some spelling errors might have been introduced by the addition of text.
|
||||
The proofstate tag is by default, not removed.
|
||||
|
||||
To remove it, one could do the following, starting with docxtemplater 3.17.2
|
||||
|
||||
.. code-block:: javascript
|
||||
|
||||
const proofstateModule = require("docxtemplater/js/proof-state-module.js");
|
||||
doc = new Docxtemplater(zip, {modules: [proofstateModule] });
|
||||
|
||||
Adding page break except for last item in loop
|
||||
----------------------------------------------
|
||||
|
||||
It is possible, in a condition, to have some specific behavior for the last item in the loop using a custom parser. You can read more `about how custom parsers work here <configuration.html#custom-parser>`__.
|
||||
|
||||
It will allow you to add a page break at the end of each loop, except for the last item in the loop.
|
||||
|
||||
The template will look like this :
|
||||
|
||||
.. code-block:: text
|
||||
|
||||
{#users}
|
||||
The user {name} is aged {age}
|
||||
{description}
|
||||
Some other content
|
||||
{@$pageBreakExceptLast}
|
||||
{/}
|
||||
|
||||
And each user block will be followed by a pagebreak, except the last user.
|
||||
|
||||
.. code-block:: javascript
|
||||
|
||||
function angularParser(tag) {
|
||||
if (tag === '.') {
|
||||
return {
|
||||
get: function(s){ return s;}
|
||||
};
|
||||
}
|
||||
const expr = expressions.compile(
|
||||
tag.replace(/(’|‘)/g, "'").replace(/(“|”)/g, '"')
|
||||
);
|
||||
return {
|
||||
get: function(scope, context) {
|
||||
let obj = {};
|
||||
const scopeList = context.scopeList;
|
||||
const num = context.num;
|
||||
for (let i = 0, len = num + 1; i < len; i++) {
|
||||
obj = assign(obj, scopeList[i]);
|
||||
}
|
||||
return expr(scope, obj);
|
||||
}
|
||||
};
|
||||
}
|
||||
function parser(tag) {
|
||||
// We write an exception to handle the tag "$pageBreakExceptLast"
|
||||
if (tag === "$pageBreakExceptLast") {
|
||||
return {
|
||||
get(scope, context) {
|
||||
const totalLength = context.scopePathLength[context.scopePathLength.length - 1];
|
||||
const index = context.scopePathItem[context.scopePathItem.length - 1];
|
||||
const isLast = index === totalLength - 1;
|
||||
if (!isLast) {
|
||||
return '<w:p><w:r><w:br w:type="page"/></w:r></w:p>';
|
||||
}
|
||||
else {
|
||||
return '';
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// We use the angularParser as the default fallback
|
||||
// If you don't wish to use the angularParser,
|
||||
// you can use the default parser as documented here :
|
||||
// https://docxtemplater.readthedocs.io/en/latest/configuration.html#default-parser
|
||||
return angularParser(tag);
|
||||
}
|
||||
const doc = new Docxtemplater(zip, {parser: parser});
|
||||
doc.render();
|
||||
|
||||
Encrypting files
|
||||
----------------
|
||||
|
||||
Docxtemplater itself does not handle the Encryption of the docx files.
|
||||
|
||||
There seem to be two solutions for this :
|
||||
|
||||
* Use a Python tool that does exactly this, it is available here : https://github.com/nolze/msoffcrypto-tool
|
||||
|
||||
* The xlsx-populate library also implements the Encryption/Decryption (algorithms are inspired by msoffcrypto-tool), however, the code probably needs to be a bit changed to work with docxtemplater : https://github.com/dtjohnson/xlsx-populate/blob/7480a02575c9140c0e7995623ea192c88c1886d3/lib/Encryptor.js#L236
|
||||
|
||||
Assignment expression in template
|
||||
---------------------------------
|
||||
|
||||
By using the angular expressions options, it is possible to add assignment expressions (for example `{full_name = first_name + last_name}` in your template. See `following part of the doc <angular_parse.html#assignments>`__.
|
||||
199
docs/source/generate.rst
Normal file
199
docs/source/generate.rst
Normal file
@ -0,0 +1,199 @@
|
||||
.. _generate:
|
||||
|
||||
.. index::
|
||||
single: Generate a Document
|
||||
|
||||
Generate a document
|
||||
===================
|
||||
|
||||
.. _`Installation`: installation.html
|
||||
|
||||
Node
|
||||
----
|
||||
|
||||
.. code-block:: javascript
|
||||
|
||||
var PizZip = require('pizzip');
|
||||
var Docxtemplater = require('docxtemplater');
|
||||
|
||||
var fs = require('fs');
|
||||
var path = require('path');
|
||||
|
||||
// The error object contains additional information when logged with JSON.stringify (it contains a properties object containing all suberrors).
|
||||
function replaceErrors(key, value) {
|
||||
if (value instanceof Error) {
|
||||
return Object.getOwnPropertyNames(value).reduce(function(error, key) {
|
||||
error[key] = value[key];
|
||||
return error;
|
||||
}, {});
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
function errorHandler(error) {
|
||||
console.log(JSON.stringify({error: error}, replaceErrors));
|
||||
|
||||
if (error.properties && error.properties.errors instanceof Array) {
|
||||
const errorMessages = error.properties.errors.map(function (error) {
|
||||
return error.properties.explanation;
|
||||
}).join("\n");
|
||||
console.log('errorMessages', errorMessages);
|
||||
// errorMessages is a humanly readable message looking like this :
|
||||
// 'The tag beginning with "foobar" is unopened'
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
|
||||
//Load the docx file as a binary
|
||||
var content = fs
|
||||
.readFileSync(path.resolve(__dirname, 'input.docx'), 'binary');
|
||||
|
||||
var zip = new PizZip(content);
|
||||
var doc;
|
||||
try {
|
||||
doc = new Docxtemplater(zip);
|
||||
} catch(error) {
|
||||
// Catch compilation errors (errors caused by the compilation of the template : misplaced tags)
|
||||
errorHandler(error);
|
||||
}
|
||||
|
||||
//set the templateVariables
|
||||
doc.setData({
|
||||
first_name: 'John',
|
||||
last_name: 'Doe',
|
||||
phone: '0652455478',
|
||||
description: 'New Website'
|
||||
});
|
||||
|
||||
try {
|
||||
// render the document (replace all occurences of {first_name} by John, {last_name} by Doe, ...)
|
||||
doc.render()
|
||||
}
|
||||
catch (error) {
|
||||
// Catch rendering errors (errors relating to the rendering of the template : angularParser throws an error)
|
||||
errorHandler(error);
|
||||
}
|
||||
|
||||
var buf = doc.getZip()
|
||||
.generate({type: 'nodebuffer'});
|
||||
|
||||
// buf is a nodejs buffer, you can either write it to a file or do anything else with it.
|
||||
fs.writeFileSync(path.resolve(__dirname, 'output.docx'), buf);
|
||||
|
||||
You can download `input.docx`_ and put it in the same folder than your JS file.
|
||||
|
||||
.. _`input.docx`: https://github.com/open-xml-templating/docxtemplater/raw/master/examples/tag-example.docx
|
||||
|
||||
Browser
|
||||
-------
|
||||
|
||||
.. code-block:: html
|
||||
|
||||
<html>
|
||||
<body>
|
||||
<button onclick="generate()">Generate document</button>
|
||||
</body>
|
||||
<script src="https://cdnjs.cloudflare.com/ajax/libs/docxtemplater/3.19.6/docxtemplater.js"></script>
|
||||
<script src="https://unpkg.com/pizzip@3.0.6/dist/pizzip.js"></script>
|
||||
<script src="https://cdnjs.cloudflare.com/ajax/libs/FileSaver.js/1.3.8/FileSaver.js"></script>
|
||||
<script src="https://unpkg.com/pizzip@3.0.6/dist/pizzip-utils.js"></script>
|
||||
<!--
|
||||
Mandatory in IE 6, 7, 8 and 9.
|
||||
-->
|
||||
<!--[if IE]>
|
||||
<script type="text/javascript" src="https://unpkg.com/pizzip@3.0.6/dist/pizzip-utils-ie.js"></script>
|
||||
<![endif]-->
|
||||
<script>
|
||||
function loadFile(url,callback){
|
||||
PizZipUtils.getBinaryContent(url,callback);
|
||||
}
|
||||
function generate() {
|
||||
loadFile("https://docxtemplater.com/tag-example.docx",function(error,content){
|
||||
if (error) { throw error };
|
||||
|
||||
// The error object contains additional information when logged with JSON.stringify (it contains a properties object containing all suberrors).
|
||||
function replaceErrors(key, value) {
|
||||
if (value instanceof Error) {
|
||||
return Object.getOwnPropertyNames(value).reduce(function(error, key) {
|
||||
error[key] = value[key];
|
||||
return error;
|
||||
}, {});
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
function errorHandler(error) {
|
||||
console.log(JSON.stringify({error: error}, replaceErrors));
|
||||
|
||||
if (error.properties && error.properties.errors instanceof Array) {
|
||||
const errorMessages = error.properties.errors.map(function (error) {
|
||||
return error.properties.explanation;
|
||||
}).join("\n");
|
||||
console.log('errorMessages', errorMessages);
|
||||
// errorMessages is a humanly readable message looking like this :
|
||||
// 'The tag beginning with "foobar" is unopened'
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
|
||||
var zip = new PizZip(content);
|
||||
var doc;
|
||||
try {
|
||||
doc=new window.docxtemplater(zip);
|
||||
} catch(error) {
|
||||
// Catch compilation errors (errors caused by the compilation of the template : misplaced tags)
|
||||
errorHandler(error);
|
||||
}
|
||||
|
||||
doc.setData({
|
||||
first_name: 'John',
|
||||
last_name: 'Doe',
|
||||
phone: '0652455478',
|
||||
description: 'New Website'
|
||||
});
|
||||
try {
|
||||
// render the document (replace all occurences of {first_name} by John, {last_name} by Doe, ...)
|
||||
doc.render();
|
||||
}
|
||||
catch (error) {
|
||||
// Catch rendering errors (errors relating to the rendering of the template : angularParser throws an error)
|
||||
errorHandler(error);
|
||||
}
|
||||
|
||||
var out=doc.getZip().generate({
|
||||
type:"blob",
|
||||
mimeType: "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
|
||||
}) //Output the document using Data-URI
|
||||
saveAs(out,"output.docx")
|
||||
})
|
||||
}
|
||||
</script>
|
||||
</html>
|
||||
|
||||
Please note that if you want to load a docx from your filesystem, you will need a webserver or you will be blocked by CORS policy.
|
||||
|
||||
:ref:`cors`
|
||||
|
||||
It is also possible to read the docx from an `<input type="file" id="doc">`, by using the following :
|
||||
|
||||
.. code-block:: javascript
|
||||
|
||||
var docs = document.getElementById('doc');
|
||||
function generate() {
|
||||
var reader = new FileReader();
|
||||
if (docs.files.length === 0) {
|
||||
alert("No files selected")
|
||||
}
|
||||
reader.readAsBinaryString(docs.files.item(0));
|
||||
|
||||
reader.onerror = function (evt) {
|
||||
console.log("error reading file", evt);
|
||||
alert("error reading file" + evt)
|
||||
}
|
||||
reader.onload = function (evt) {
|
||||
const content = evt.target.result;
|
||||
var zip = new PizZip(content);
|
||||
// Same code as in the main HTML example.
|
||||
}
|
||||
}
|
||||
|
||||
42
docs/source/goals.rst
Normal file
42
docs/source/goals.rst
Normal file
@ -0,0 +1,42 @@
|
||||
.. _goals:
|
||||
|
||||
.. index::
|
||||
single: Goals
|
||||
|
||||
What is docxtemplater ?
|
||||
=======================
|
||||
|
||||
docxtemplater is a mail merging tool that is used programmatically and handles conditions, loops, and can be extended to insert anything (tables, html, images).
|
||||
|
||||
docxtemplater uses JSON (Javascript objects) as data input, so it can also be used easily from other languages. It handles docx but also pptx templates.
|
||||
|
||||
It works in the same way as a templating engine.
|
||||
|
||||
|
||||
Many solutions like `docx.js`_, `docx4j`_, `python-docx`_ can generate docx, but they require you to write specific code to create a title, an image, ...
|
||||
|
||||
In contrast, docxtemplater is based on the concepts of tags, and each type of tag exposes a feature to the user writing the template.
|
||||
|
||||
.. _docx.js: https://github.com/MrRio/DOCX.js/
|
||||
.. _docx4j: https://www.docx4java.org/trac/docx4j
|
||||
.. _python-docx: https://python-docx.readthedocs.io/en/latest/
|
||||
|
||||
Why you shouldn't write a similar library from scratch
|
||||
------------------------------------------------------
|
||||
|
||||
Docx is a zipped format that contains some xml.
|
||||
If you want to build a simple replace {tag} by value system, it could easily be challenging, because the {tag} is internally separated into :
|
||||
|
||||
.. code-block:: text
|
||||
|
||||
<w:t>{</w:t>
|
||||
<w:t>tag</w:t>
|
||||
<w:t>}</w:t>
|
||||
|
||||
The fact that the tags can be splitted into multiple xml tags makes the code challenging to write. I had to rewrite most of the parsing engine between version 2 and version 3 of docxtemplater to make the code more straighforward : See the migration here :https://github.com/open-xml-templating/docxtemplater/commit/59af93bd281932da4586175bb2428d28298d1e65.
|
||||
|
||||
If you want to have loops to iterate over an array, it will become even more complicated.
|
||||
|
||||
docxtemplater provides a very simple API that gives you abstraction to deal with loops, conditions, and other features.
|
||||
|
||||
If you need additional features, you can either build your own module, or use one of the free or paid modules that you can find at https://docxtemplater.com/
|
||||
50
docs/source/index.rst
Normal file
50
docs/source/index.rst
Normal file
@ -0,0 +1,50 @@
|
||||
Docxtemplater
|
||||
=============
|
||||
|
||||
.. toctree::
|
||||
:maxdepth: 1
|
||||
|
||||
|
||||
goals
|
||||
installation
|
||||
generate
|
||||
tag_types
|
||||
configuration
|
||||
angular_parse
|
||||
async
|
||||
platform_support
|
||||
errors
|
||||
cli
|
||||
api
|
||||
faq
|
||||
testing
|
||||
|
||||
|
||||
`Online Demos`_
|
||||
---------------
|
||||
|
||||
Including:
|
||||
|
||||
|
||||
- `Replace Variables`_
|
||||
- `Conditions`_
|
||||
- `Loops`_
|
||||
- `Loops and tables`_
|
||||
- `Lists`_
|
||||
- `Raw Xml Insertion`_
|
||||
- `HTML`_
|
||||
- `Image`_
|
||||
- `Slides`_
|
||||
- `Subtemplate`_
|
||||
|
||||
.. _`Online Demos`: https://docxtemplater.com/demo
|
||||
.. _Replace Variables: https://docxtemplater.com/demo#simple
|
||||
.. _Conditions: https://docxtemplater.com/demo#conditions
|
||||
.. _Loops: https://docxtemplater.com/demo#loops
|
||||
.. _Loops and tables: https://docxtemplater.com/demo#loop-table
|
||||
.. _Lists: https://docxtemplater.com/demo#loop-list
|
||||
.. _Raw Xml Insertion: https://docxtemplater.com/demo#xml-insertion
|
||||
.. _HTML: https://docxtemplater.com/demo#html
|
||||
.. _Image: https://docxtemplater.com/demo#image
|
||||
.. _Slides: https://docxtemplater.com/demo#slides
|
||||
.. _Subtemplate: https://docxtemplater.com/demo#subtemplate
|
||||
83
docs/source/installation.rst
Normal file
83
docs/source/installation.rst
Normal file
@ -0,0 +1,83 @@
|
||||
.. _installation:
|
||||
|
||||
.. index::
|
||||
single: Installation
|
||||
|
||||
Installation
|
||||
============
|
||||
|
||||
|
||||
Node
|
||||
----
|
||||
|
||||
npm is the easiest way to install docxtemplater
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
npm install docxtemplater pizzip
|
||||
|
||||
Browser
|
||||
-------
|
||||
|
||||
You can find ``.js`` and ``.min.js`` files for docxtemplater on `this repository <https://github.com/open-xml-templating/docxtemplater-build/tree/master/build>`__
|
||||
|
||||
You will also need Pizzip, which you can `download here <https://unpkg.com/pizzip@3.0.6/dist/pizzip.js>`__
|
||||
|
||||
Build it yourself
|
||||
-----------------
|
||||
|
||||
If you want to build docxtemplater for the browser yourself, here is how you should do :
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
git clone https://github.com/open-xml-templating/docxtemplater.git
|
||||
cd docxtemplater
|
||||
npm install
|
||||
npm test
|
||||
npm run compile
|
||||
./node_modules/.bin/browserify -r "./js/docxtemplater.js" -s docxtemplater > "browser/docxtemplater.js"
|
||||
./node_modules/.bin/uglifyjs "browser/docxtemplater.js" > "browser/docxtemplater.min.js" --verbose --ascii-only
|
||||
|
||||
Docxtemplater will be exported to window.docxtemplater for easy usage.
|
||||
|
||||
The generated files of docxtemplater will be in /browser (minified and non minified).
|
||||
|
||||
Minifying the build
|
||||
-------------------
|
||||
|
||||
On Browsers that have `window.XMLSerializer` and `window.DOMParser` (all browsers normally have it), you can use that as a replacement for the xmldom dependency.
|
||||
|
||||
As an example, if you use webpack, you can do the following in your webpack.config.js :
|
||||
|
||||
.. code-block:: javascript
|
||||
|
||||
module.exports = {
|
||||
// ...
|
||||
// ...
|
||||
resolve: {
|
||||
alias: {
|
||||
xmldom: path.resolve("./node_modules/docxtemplater/es6/browser-versions/xmldom.js"),
|
||||
},
|
||||
},
|
||||
// ...
|
||||
// ...
|
||||
}
|
||||
|
||||
Bower
|
||||
-----
|
||||
|
||||
You can use bower to install docxtemplater
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
bower install --save docxtemplater
|
||||
|
||||
When using bower, you can include the following script tag in your HTML :
|
||||
|
||||
.. code-block:: html
|
||||
|
||||
<script src="bower_components/docxtemplater/build/docxtemplater-latest.min.js"></script>
|
||||
|
||||
This tag will expose docxtemplater in `window.docxtemplater`.
|
||||
|
||||
|
||||
28
docs/source/platform_support.rst
Normal file
28
docs/source/platform_support.rst
Normal file
@ -0,0 +1,28 @@
|
||||
.. _platform_support:
|
||||
|
||||
.. index::
|
||||
single: platform_support
|
||||
|
||||
Platform Support
|
||||
================
|
||||
|
||||
docxtemplater works on most modern platforms, and also some older ones. Here is a list of what is tested regularly :
|
||||
|
||||
- Node.js versions 6, 7, 8, 9, 10, 11, 12 and all future versions (older versions will also work, but support has ended)
|
||||
- Chrome version 58,71,73
|
||||
- Firefox 55,60,66
|
||||
- Safari 11,12
|
||||
- IE10, IE11, Edge 16-18
|
||||
- Android 4.2+
|
||||
- iPads and iPhones v8.1, 10.3
|
||||
|
||||
You can test if everything works fine on your browser by using the test runner: http://javascript-ninja.fr/docxtemplater/v3/test/mocha.html
|
||||
|
||||
Dependencies
|
||||
------------
|
||||
|
||||
1. `PizZip`_ to zip and unzip the docx files
|
||||
2. `xmldom`_ to parse the files as xml
|
||||
|
||||
.. _`PizZip`: https://github.com/open-xml-templating/pizzip
|
||||
.. _`xmldom`: https://github.com/jindw/xmldom
|
||||
304
docs/source/tag_types.rst
Normal file
304
docs/source/tag_types.rst
Normal file
@ -0,0 +1,304 @@
|
||||
.. _syntax:
|
||||
|
||||
.. index::
|
||||
single: Types of tags
|
||||
|
||||
Types of tags
|
||||
=============
|
||||
|
||||
The syntax is inspired by Mustache_. The template is created in Microsoft Word or other software that can save a docx.
|
||||
|
||||
.. _Mustache: https://mustache.github.io/
|
||||
|
||||
Introduction
|
||||
------------
|
||||
|
||||
With this template (input.docx):
|
||||
|
||||
.. code-block:: text
|
||||
|
||||
Hello {name} !
|
||||
|
||||
And given the following data (data.json):
|
||||
|
||||
.. code-block:: javascript
|
||||
|
||||
{
|
||||
name:'John'
|
||||
}
|
||||
|
||||
docxtemplater will produce (output.docx):
|
||||
|
||||
.. code-block:: text
|
||||
|
||||
Hello John !
|
||||
|
||||
Conditions
|
||||
----------
|
||||
|
||||
Conditions start with a pound and end with a slash. That is `{#hasKitty}` starts a condition and `{/hasKitty}` ends it.
|
||||
|
||||
.. code-block:: text
|
||||
|
||||
{#hasKitty}Cat’s name: {kitty}{/hasKitty}
|
||||
{#hasDog}Dog’s name: {dog}{/hasDog}
|
||||
|
||||
and this data:
|
||||
|
||||
.. code-block:: javascript
|
||||
|
||||
{
|
||||
"first_name":"Jane",
|
||||
"hasKitty": true,
|
||||
"kitty": "Minie"
|
||||
"hasDog": false,
|
||||
"dog" :null
|
||||
}
|
||||
|
||||
renders the following:
|
||||
|
||||
.. code-block:: text
|
||||
|
||||
Cat’s name: Minie
|
||||
|
||||
For a more detailled explanation about Conditions, have a look at `Sections`_
|
||||
|
||||
You can also have "else" blocks with `Inverted Sections`_
|
||||
|
||||
Loops
|
||||
-----
|
||||
|
||||
In docxtemplater, conditions and loops use the same syntax called Sections
|
||||
|
||||
The following template:
|
||||
|
||||
.. code-block:: text
|
||||
|
||||
{#products}
|
||||
{name}, {price} €
|
||||
{/products}
|
||||
|
||||
Given the following data:
|
||||
|
||||
.. code-block:: javascript
|
||||
|
||||
{
|
||||
"products": [
|
||||
{ name :"Windows", price: 100},
|
||||
{ name :"Mac OSX", price: 200},
|
||||
{ name :"Ubuntu", price: 0}
|
||||
]
|
||||
}
|
||||
|
||||
will result in :
|
||||
|
||||
.. code-block:: text
|
||||
|
||||
Windows, 100 €
|
||||
Mac OSX, 200 €
|
||||
Ubuntu, 0€
|
||||
|
||||
To loop over an array containing primitive data (ex: string):
|
||||
|
||||
.. code-block:: javascript
|
||||
|
||||
{
|
||||
"products": [
|
||||
"Windows",
|
||||
"Mac OSX",
|
||||
"Ubuntu"
|
||||
]
|
||||
}
|
||||
|
||||
.. code-block:: text
|
||||
|
||||
{#products} {.} {/products}
|
||||
|
||||
Will result in :
|
||||
|
||||
.. code-block:: text
|
||||
|
||||
Windows Mac OSX Ubuntu
|
||||
|
||||
Sections
|
||||
--------
|
||||
|
||||
A section begins with a pound and ends with a slash. That is {#person} begins a "person" section while {/person} ends it.
|
||||
|
||||
The section behaves in the following way:
|
||||
|
||||
+----------------------+---------------------------+------------------+
|
||||
| Type of the value | the section is shown | scope |
|
||||
+======================+===========================+==================+
|
||||
| falsy or empty array | never | |
|
||||
+----------------------+---------------------------+------------------+
|
||||
| non empty array | for each element of array | element of array |
|
||||
+----------------------+---------------------------+------------------+
|
||||
| object | once | the object |
|
||||
+----------------------+---------------------------+------------------+
|
||||
| other truthy value | once | unchanged |
|
||||
+----------------------+---------------------------+------------------+
|
||||
|
||||
This table shows for each type of value, what is the condition for the section to be changed and what is the scope of that section.
|
||||
|
||||
If the value is of type **boolean**, the section is shown **once if the value is true**, and the scope of the section is **unchanged**.
|
||||
|
||||
If we have the section
|
||||
|
||||
.. code-block:: text
|
||||
|
||||
{#hasProduct}
|
||||
{price} €
|
||||
{/hasProduct}
|
||||
|
||||
Given the following data:
|
||||
|
||||
.. code-block:: javascript
|
||||
|
||||
{
|
||||
"hasProduct": true,
|
||||
"price" : 10
|
||||
}
|
||||
|
||||
Since hasProduct is a boolean, the section is shown once if `hasProduct` is `true`.
|
||||
Since the scope is unchanged, the subsection `{price} €` will render as `10 €`
|
||||
|
||||
|
||||
Inverted Sections
|
||||
-----------------
|
||||
|
||||
An inverted section begins with a caret (hat) and ends with a slash. That is {^person} begins a "person" inverted section while {/person} ends it.
|
||||
|
||||
While sections can be used to render text one or more times based on the value of the key, inverted sections may render text once based on the inverse value of the key. That is, they will be rendered if the key doesn't exist, is false, or is an empty list. The scope of an inverted section is unchanged.
|
||||
|
||||
Template:
|
||||
|
||||
.. code-block:: text
|
||||
|
||||
{#repo}
|
||||
<b>{name}</b>
|
||||
{/repo}
|
||||
{^repo}
|
||||
No repos :(
|
||||
{/repo}
|
||||
|
||||
Data:
|
||||
|
||||
.. code-block:: javascript
|
||||
|
||||
{
|
||||
"repo": []
|
||||
}
|
||||
|
||||
Output:
|
||||
|
||||
.. code-block:: javascript
|
||||
|
||||
No repos :(
|
||||
|
||||
Sections and newlines
|
||||
---------------------
|
||||
|
||||
New lines are kept inside sections, so the template :
|
||||
|
||||
.. code-block:: text
|
||||
|
||||
{#repo}
|
||||
<b>{name}</b>
|
||||
{/repo}
|
||||
{^repo}
|
||||
No repos :(
|
||||
{/repo}
|
||||
|
||||
Data:
|
||||
|
||||
.. code-block:: javascript
|
||||
|
||||
{
|
||||
"repo": [{name: "John"}]
|
||||
"repo": [{name: "Jane"}]
|
||||
}
|
||||
|
||||
Will actually render
|
||||
|
||||
.. code-block:: text
|
||||
|
||||
NL
|
||||
<b>John</b>
|
||||
NL
|
||||
NL
|
||||
<b>Jane</b>
|
||||
NL
|
||||
|
||||
(where NL represents an emptyline)
|
||||
|
||||
The way to make this work as expected is to not put unnecessary new lines after the start of the section and before the end of the section.
|
||||
|
||||
For our example , that would be :
|
||||
|
||||
.. code-block:: text
|
||||
|
||||
{#repo} <b>{name}</b>
|
||||
{/repo} {^repo} No repos :( {/repo}
|
||||
|
||||
Raw XML syntax
|
||||
--------------
|
||||
|
||||
It is possible to insert raw (unescaped) XML, for example to render a complex table, an equation, ...
|
||||
|
||||
With the ``rawXML`` syntax the whole current paragraph (``w:p``) is replaced by the XML passed in the value.
|
||||
|
||||
.. code-block:: text
|
||||
|
||||
{@rawXml}
|
||||
|
||||
with this data:
|
||||
|
||||
.. code-block:: javascript
|
||||
|
||||
{rawXml:'<w:p><w:pPr><w:rPr><w:color w:val="FF0000"/></w:rPr></w:pPr><w:r><w:rPr><w:color w:val="FF0000"/></w:rPr><w:t>My custom</w:t></w:r><w:r><w:rPr><w:color w:val="00FF00"/></w:rPr><w:t>XML</w:t></w:r></w:p>'}
|
||||
|
||||
This will loop over the first parent <w:p> tag
|
||||
|
||||
If you want to insert HTML styled input, you can also use the docxtemplater html module : https://docxtemplater.com/modules/html/
|
||||
|
||||
Set Delimiter
|
||||
-------------
|
||||
|
||||
Set Delimiter tags start and end with an equal sign and change the tag delimiters from { and } to custom strings.
|
||||
|
||||
Consider the following contrived example:
|
||||
|
||||
.. code-block:: text
|
||||
|
||||
* {default_tags}
|
||||
{=<% %>=}
|
||||
* <% erb_style_tags %>
|
||||
<%={ }=%>
|
||||
* { default_tags_again }
|
||||
|
||||
Here we have a list with three items. The first item uses the default tag style, the second uses erb style as defined by the Set Delimiter tag, and the third returns to the default style after yet another Set Delimiter declaration.
|
||||
|
||||
Custom delimiters may not contain whitespace or the equals sign.
|
||||
|
||||
It is also possible to `change the delimiters by using docxtemplater options object`_.
|
||||
|
||||
.. _`change the delimiters by using docxtemplater options object`: configuration.html#custom-delimiters
|
||||
|
||||
Dash syntax
|
||||
-----------
|
||||
|
||||
When using sections, docxtemplater will try to find on what element to loop over by itself:
|
||||
|
||||
If between the two tags {#tag}______{/tag}
|
||||
|
||||
* there is a tag ``<w:tc>`` , that means that your loop is inside a table, and it will loop over ``<w:tr>`` (table row).
|
||||
* by default, it will loop over ``<w:t>``, which is the default Text Tag
|
||||
|
||||
With the Dash syntax you can specify the tag you want to loop on:
|
||||
For example, if you want to loop on paragraphs (``w:p``), so that each of the loop creates a new paragraph, you can write :
|
||||
|
||||
.. code-block:: text
|
||||
|
||||
{-w:p loop} {inner} {/loop}
|
||||
|
||||
135
docs/source/testing.rst
Normal file
135
docs/source/testing.rst
Normal file
@ -0,0 +1,135 @@
|
||||
.. index::
|
||||
single: Testing
|
||||
|
||||
.. _testing:
|
||||
|
||||
Testing
|
||||
=======
|
||||
|
||||
This page documents how docxtemplater is tested.
|
||||
|
||||
First, there are multiple types of tests done in docxtemplater
|
||||
|
||||
* **Integration tests**, that are tests where we take a real .docx document, some JSON data, render the document and then verify that it the same as the expected document (this can be seen as snapshot testing)
|
||||
* **Regression tests**, that are tests where we take real or fake docx to ensure that bugfixes that have been found can't occur in the future
|
||||
* **Unit tests**, that help understand the internals of docxtemplater, and allows to verify that the internal data structures of the parsed template are correct
|
||||
* **Speed tests**, that help to optimize the speed of docxtemplater
|
||||
|
||||
Integration
|
||||
-----------
|
||||
|
||||
The integration tests are in es6/tests/integration.js
|
||||
|
||||
|
||||
.. code-block:: javascript
|
||||
|
||||
it("should work with table pptx", function () {
|
||||
const doc = createDoc("table-example.pptx");
|
||||
doc.setData({users: [{msg: "hello", name: "mary"}, {msg: "hello", name: "john"}]}).render();
|
||||
shouldBeSame({doc, expectedName: "expected-table-example.pptx"});
|
||||
});
|
||||
|
||||
All of the test documents are in the folder `examples/`
|
||||
|
||||
* We first load a document from table-example.pptx
|
||||
* We then set data and render the document.
|
||||
* We then verify that the document is the same as "expected-table-example.pptx"
|
||||
|
||||
shouldBeSame will, for each XML file that is inside the zip document, pretty print it, and then compare them. That way, we have a more beautiful diff and spacing differences do not matter in the output document.
|
||||
|
||||
Regression tests
|
||||
----------------
|
||||
|
||||
There are many regression tests, eg tests that are there to ensure that bugs that occured once will not appear again in the future.
|
||||
|
||||
A good example of such a test is
|
||||
|
||||
Docxtemplater https://github.com/open-xml-templating/docxtemplater/issues/14
|
||||
|
||||
Docxtemplater was not able to render text that was written in russian (because of an issue with encoding).
|
||||
|
||||
.. code-block:: javascript
|
||||
|
||||
it("should insert russian characters", function () {
|
||||
const russian = "Пупкина"
|
||||
const doc = createDoc("tag-example.docx");
|
||||
const zip = new PizZip(doc.loadedContent);
|
||||
const d = new Docxtemplater(zip);
|
||||
d.setData({last_name: russian});
|
||||
d.render();
|
||||
const outputText = d.getFullText();
|
||||
expect(outputText.substr(0, 7)).to.be.equal(russian);
|
||||
});
|
||||
|
||||
This test ensures that the output of the document is correct.
|
||||
|
||||
Every time we correct a bug, we should also add a regression test to make sure that bug cannot appear in the future.
|
||||
|
||||
Unit tests
|
||||
-----------
|
||||
|
||||
The input/output for the unit tests can be found in es6/tests/fixtures.js :
|
||||
|
||||
For example
|
||||
|
||||
|
||||
.. code-block:: javascript
|
||||
|
||||
simple: {
|
||||
it: "should handle {user} with tag",
|
||||
content: "<w:t>Hi {user}</w:t>",
|
||||
scope: {
|
||||
user: "Foo",
|
||||
},
|
||||
result: '<w:t xml:space="preserve">Hi Foo</w:t>',
|
||||
lexed: [
|
||||
{type: "tag", position: "start", value: "<w:t>", text: true},
|
||||
{type: "content", value: "Hi ", position: "insidetag"},
|
||||
{type: "delimiter", position: "start"},
|
||||
{type: "content", value: "user", position: "insidetag"},
|
||||
{type: "delimiter", position: "end"},
|
||||
{type: "tag", value: "</w:t>", text: true, position: "end"},
|
||||
],
|
||||
parsed: [
|
||||
{type: "tag", position: "start", value: "<w:t>", text: true},
|
||||
{type: "content", value: "Hi ", position: "insidetag"},
|
||||
{type: "placeholder", value: "user"},
|
||||
{type: "tag", value: "</w:t>", text: true, position: "end"},
|
||||
],
|
||||
postparsed: [
|
||||
{type: "tag", position: "start", value: '<w:t xml:space="preserve">', text: true},
|
||||
{type: "content", value: "Hi ", position: "insidetag"},
|
||||
{type: "placeholder", value: "user"},
|
||||
{type: "tag", value: "</w:t>", text: true, position: "end"},
|
||||
],
|
||||
},
|
||||
|
||||
|
||||
There you can see what the different steps of docxtemplater are, lex, parse, postparse.
|
||||
|
||||
|
||||
Speed tests
|
||||
-----------
|
||||
|
||||
To ensure that there is no regression on the speed of docxtemplater, we test the performance by generating multiple documents and we expect that the time to generate these documents should be less than for example 100ms.
|
||||
|
||||
These tests can be found in es6/tests/speed.js
|
||||
|
||||
For example for this test:
|
||||
|
||||
.. code-block:: javascript
|
||||
|
||||
it("should be fast for loop tags", function () {
|
||||
const content = "<w:t>{#users}{name}{/users}</w:t>";
|
||||
const users = [];
|
||||
for (let i = 1; i <= 1000; i++) {
|
||||
users.push({name: "foo"});
|
||||
}
|
||||
const time = new Date();
|
||||
createXmlTemplaterDocx(content, {tags: {users}}).render();
|
||||
const duration = new Date() - time;
|
||||
expect(duration).to.be.below(60);
|
||||
});
|
||||
|
||||
Here we verify that rendering a loop of 1000 items takes less than 60ms.
|
||||
This happens to also be a regression test, because they was a problem when generating documents with loops (the loops became very slow for more than 500 items), and we now ensure that such a regression cannot occur in the future.
|
||||
1
es6/browser-versions/fs.js
Normal file
1
es6/browser-versions/fs.js
Normal file
@ -0,0 +1 @@
|
||||
module.exports = {};
|
||||
5
es6/browser-versions/xmldom.js
Normal file
5
es6/browser-versions/xmldom.js
Normal file
@ -0,0 +1,5 @@
|
||||
module.exports = {
|
||||
XMLSerializer: window.XMLSerializer,
|
||||
DOMParser: window.DOMParser,
|
||||
XMLDocument: window.XMLDocument,
|
||||
};
|
||||
28
es6/collect-content-types.js
Normal file
28
es6/collect-content-types.js
Normal file
@ -0,0 +1,28 @@
|
||||
const ctXML = "[Content_Types].xml";
|
||||
function collectContentTypes(overrides, defaults, zip) {
|
||||
const partNames = {};
|
||||
for (let i = 0, len = overrides.length; i < len; i++) {
|
||||
const override = overrides[i];
|
||||
const contentType = override.getAttribute("ContentType");
|
||||
const partName = override.getAttribute("PartName").substr(1);
|
||||
partNames[partName] = contentType;
|
||||
}
|
||||
for (let i = 0, len = defaults.length; i < len; i++) {
|
||||
const def = defaults[i];
|
||||
const contentType = def.getAttribute("ContentType");
|
||||
const extension = def.getAttribute("Extension");
|
||||
// eslint-disable-next-line no-loop-func
|
||||
zip.file(/./).map(({ name }) => {
|
||||
if (
|
||||
name.slice(name.length - extension.length - 1) === ".xml" &&
|
||||
!partNames[name] &&
|
||||
name !== ctXML
|
||||
) {
|
||||
partNames[name] = contentType;
|
||||
}
|
||||
});
|
||||
}
|
||||
return partNames;
|
||||
}
|
||||
|
||||
module.exports = collectContentTypes;
|
||||
29
es6/debugger-module.js
Normal file
29
es6/debugger-module.js
Normal file
@ -0,0 +1,29 @@
|
||||
/* eslint-disable no-console */
|
||||
module.exports = class DebuggerModule {
|
||||
constructor() {}
|
||||
optionsTransformer(options, docxtemplater) {
|
||||
console.log(JSON.stringify({ options }));
|
||||
console.log(
|
||||
JSON.stringify({ files: Object.keys(docxtemplater.getZip().files) })
|
||||
);
|
||||
return options;
|
||||
}
|
||||
parse() {
|
||||
console.log(JSON.stringify({ msg: "parse" }));
|
||||
return null;
|
||||
}
|
||||
postparse(parsed) {
|
||||
console.log(JSON.stringify({ msg: "postparse" }));
|
||||
return {
|
||||
errors: [],
|
||||
parsed,
|
||||
};
|
||||
}
|
||||
render() {
|
||||
console.log(JSON.stringify({ msg: "render" }));
|
||||
return null;
|
||||
}
|
||||
postrender() {
|
||||
console.log(JSON.stringify({ msg: "postrender" }));
|
||||
}
|
||||
};
|
||||
471
es6/doc-utils.js
Normal file
471
es6/doc-utils.js
Normal file
@ -0,0 +1,471 @@
|
||||
"use strict";
|
||||
|
||||
const { DOMParser, XMLSerializer } = require("xmldom");
|
||||
const { throwXmlTagNotFound } = require("./errors");
|
||||
const { last, first } = require("./utils");
|
||||
|
||||
function parser(tag) {
|
||||
return {
|
||||
get(scope) {
|
||||
if (tag === ".") {
|
||||
return scope;
|
||||
}
|
||||
return scope[tag];
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function getNearestLeftIndex(parsed, elements, index) {
|
||||
for (let i = index; i >= 0; i--) {
|
||||
const part = parsed[i];
|
||||
for (let j = 0, len = elements.length; j < len; j++) {
|
||||
const element = elements[j];
|
||||
if (isStarting(part.value, element)) {
|
||||
return j;
|
||||
}
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function getNearestRightIndex(parsed, elements, index) {
|
||||
for (let i = index, l = parsed.length; i < l; i++) {
|
||||
const part = parsed[i];
|
||||
for (let j = 0, len = elements.length; j < len; j++) {
|
||||
const element = elements[j];
|
||||
if (isEnding(part.value, element)) {
|
||||
return j;
|
||||
}
|
||||
}
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
function getNearestLeft(parsed, elements, index) {
|
||||
const found = getNearestLeftIndex(parsed, elements, index);
|
||||
if (found !== -1) {
|
||||
return elements[found];
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function getNearestRight(parsed, elements, index) {
|
||||
const found = getNearestRightIndex(parsed, elements, index);
|
||||
if (found !== -1) {
|
||||
return elements[found];
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function buildNearestCache(postparsed, tags) {
|
||||
return postparsed.reduce(function (cached, part, i) {
|
||||
if (part.type === "tag" && tags.indexOf(part.tag) !== -1) {
|
||||
cached.push({ i, part });
|
||||
}
|
||||
return cached;
|
||||
}, []);
|
||||
}
|
||||
|
||||
function getNearestLeftIndexWithCache(index, cache) {
|
||||
if (cache.length === 0) {
|
||||
return -1;
|
||||
}
|
||||
for (let i = 0, len = cache.length; i < len; i++) {
|
||||
const current = cache[i];
|
||||
const next = cache[i + 1];
|
||||
if (
|
||||
current.i < index &&
|
||||
(!next || index < next.i) &&
|
||||
current.part.position === "start"
|
||||
) {
|
||||
return i;
|
||||
}
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
function getNearestLeftWithCache(index, cache) {
|
||||
const found = getNearestLeftIndexWithCache(index, cache);
|
||||
if (found !== -1) {
|
||||
return cache[found].part.tag;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function getNearestRightIndexWithCache(index, cache) {
|
||||
if (cache.length === 0) {
|
||||
return -1;
|
||||
}
|
||||
for (let i = 0, len = cache.length; i < len; i++) {
|
||||
const current = cache[i];
|
||||
const last = cache[i - 1];
|
||||
if (
|
||||
index < current.i &&
|
||||
(!last || last.i < index) &&
|
||||
current.part.position === "end"
|
||||
) {
|
||||
return i;
|
||||
}
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
function getNearestRightWithCache(index, cache) {
|
||||
const found = getNearestRightIndexWithCache(index, cache);
|
||||
if (found !== -1) {
|
||||
return cache[found].part.tag;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function endsWith(str, suffix) {
|
||||
return str.indexOf(suffix, str.length - suffix.length) !== -1;
|
||||
}
|
||||
function startsWith(str, prefix) {
|
||||
return str.substring(0, prefix.length) === prefix;
|
||||
}
|
||||
|
||||
function unique(arr) {
|
||||
const hash = {},
|
||||
result = [];
|
||||
for (let i = 0, l = arr.length; i < l; ++i) {
|
||||
if (!hash.hasOwnProperty(arr[i])) {
|
||||
hash[arr[i]] = true;
|
||||
result.push(arr[i]);
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
function chunkBy(parsed, f) {
|
||||
return parsed
|
||||
.reduce(
|
||||
function (chunks, p) {
|
||||
const currentChunk = last(chunks);
|
||||
const res = f(p);
|
||||
if (currentChunk.length === 0) {
|
||||
currentChunk.push(p);
|
||||
return chunks;
|
||||
}
|
||||
if (res === "start") {
|
||||
chunks.push([p]);
|
||||
} else if (res === "end") {
|
||||
currentChunk.push(p);
|
||||
chunks.push([]);
|
||||
} else {
|
||||
currentChunk.push(p);
|
||||
}
|
||||
return chunks;
|
||||
},
|
||||
[[]]
|
||||
)
|
||||
.filter(function (p) {
|
||||
return p.length > 0;
|
||||
});
|
||||
}
|
||||
|
||||
const defaults = {
|
||||
paragraphLoop: false,
|
||||
nullGetter(part) {
|
||||
if (!part.module) {
|
||||
return "undefined";
|
||||
}
|
||||
if (part.module === "rawxml") {
|
||||
return "";
|
||||
}
|
||||
return "";
|
||||
},
|
||||
xmlFileNames: [],
|
||||
parser,
|
||||
linebreaks: false,
|
||||
fileTypeConfig: null,
|
||||
delimiters: {
|
||||
start: "{",
|
||||
end: "}",
|
||||
},
|
||||
};
|
||||
|
||||
function mergeObjects() {
|
||||
const resObj = {};
|
||||
let obj, keys;
|
||||
for (let i = 0; i < arguments.length; i += 1) {
|
||||
obj = arguments[i];
|
||||
keys = Object.keys(obj);
|
||||
for (let j = 0; j < keys.length; j += 1) {
|
||||
resObj[keys[j]] = obj[keys[j]];
|
||||
}
|
||||
}
|
||||
return resObj;
|
||||
}
|
||||
|
||||
function xml2str(xmlNode) {
|
||||
const a = new XMLSerializer();
|
||||
return a.serializeToString(xmlNode).replace(/xmlns(:[a-z0-9]+)?="" ?/g, "");
|
||||
}
|
||||
|
||||
function str2xml(str) {
|
||||
if (str.charCodeAt(0) === 65279) {
|
||||
// BOM sequence
|
||||
str = str.substr(1);
|
||||
}
|
||||
const parser = new DOMParser();
|
||||
return parser.parseFromString(str, "text/xml");
|
||||
}
|
||||
|
||||
const charMap = [
|
||||
["&", "&"],
|
||||
["<", "<"],
|
||||
[">", ">"],
|
||||
['"', """],
|
||||
["'", "'"],
|
||||
];
|
||||
|
||||
function escapeRegExp(str) {
|
||||
// to be able to use a string as a regex
|
||||
return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
||||
}
|
||||
|
||||
const charMapRegexes = charMap.map(function ([endChar, startChar]) {
|
||||
return {
|
||||
rstart: new RegExp(escapeRegExp(startChar), "g"),
|
||||
rend: new RegExp(escapeRegExp(endChar), "g"),
|
||||
start: startChar,
|
||||
end: endChar,
|
||||
};
|
||||
});
|
||||
|
||||
function wordToUtf8(string) {
|
||||
let r;
|
||||
for (let i = charMapRegexes.length - 1; i >= 0; i--) {
|
||||
r = charMapRegexes[i];
|
||||
string = string.replace(r.rstart, r.end);
|
||||
}
|
||||
return string;
|
||||
}
|
||||
|
||||
function utf8ToWord(string) {
|
||||
if (typeof string !== "string") {
|
||||
string = string.toString();
|
||||
}
|
||||
let r;
|
||||
for (let i = 0, l = charMapRegexes.length; i < l; i++) {
|
||||
r = charMapRegexes[i];
|
||||
string = string.replace(r.rend, r.start);
|
||||
}
|
||||
return string;
|
||||
}
|
||||
|
||||
// This function is written with for loops for performance
|
||||
function concatArrays(arrays) {
|
||||
const result = [];
|
||||
for (let i = 0; i < arrays.length; i++) {
|
||||
const array = arrays[i];
|
||||
for (let j = 0, len = array.length; j < len; j++) {
|
||||
result.push(array[j]);
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
const spaceRegexp = new RegExp(String.fromCharCode(160), "g");
|
||||
function convertSpaces(s) {
|
||||
return s.replace(spaceRegexp, " ");
|
||||
}
|
||||
function pregMatchAll(regex, content) {
|
||||
/* regex is a string, content is the content. It returns an array of all matches with their offset, for example:
|
||||
regex=la
|
||||
content=lolalolilala
|
||||
returns: [{array: {0: 'la'},offset: 2},{array: {0: 'la'},offset: 8},{array: {0: 'la'} ,offset: 10}]
|
||||
*/
|
||||
const matchArray = [];
|
||||
let match;
|
||||
while ((match = regex.exec(content)) != null) {
|
||||
matchArray.push({ array: match, offset: match.index });
|
||||
}
|
||||
return matchArray;
|
||||
}
|
||||
|
||||
function isEnding(value, element) {
|
||||
return value === "</" + element + ">";
|
||||
}
|
||||
|
||||
function isStarting(value, element) {
|
||||
return (
|
||||
value.indexOf("<" + element) === 0 &&
|
||||
[">", " "].indexOf(value[element.length + 1]) !== -1
|
||||
);
|
||||
}
|
||||
|
||||
function getRight(parsed, element, index) {
|
||||
const val = getRightOrNull(parsed, element, index);
|
||||
if (val !== null) {
|
||||
return val;
|
||||
}
|
||||
throwXmlTagNotFound({ position: "right", element, parsed, index });
|
||||
}
|
||||
|
||||
function getRightOrNull(parsed, elements, index) {
|
||||
if (typeof elements === "string") {
|
||||
elements = [elements];
|
||||
}
|
||||
let level = 1;
|
||||
for (let i = index, l = parsed.length; i < l; i++) {
|
||||
const part = parsed[i];
|
||||
for (let j = 0, len = elements.length; j < len; j++) {
|
||||
const element = elements[j];
|
||||
if (isEnding(part.value, element)) {
|
||||
level--;
|
||||
}
|
||||
if (isStarting(part.value, element)) {
|
||||
level++;
|
||||
}
|
||||
if (level === 0) {
|
||||
return i;
|
||||
}
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function getLeft(parsed, element, index) {
|
||||
const val = getLeftOrNull(parsed, element, index);
|
||||
if (val !== null) {
|
||||
return val;
|
||||
}
|
||||
throwXmlTagNotFound({ position: "left", element, parsed, index });
|
||||
}
|
||||
|
||||
function getLeftOrNull(parsed, elements, index) {
|
||||
if (typeof elements === "string") {
|
||||
elements = [elements];
|
||||
}
|
||||
let level = 1;
|
||||
for (let i = index; i >= 0; i--) {
|
||||
const part = parsed[i];
|
||||
for (let j = 0, len = elements.length; j < len; j++) {
|
||||
const element = elements[j];
|
||||
if (isStarting(part.value, element)) {
|
||||
level--;
|
||||
}
|
||||
if (isEnding(part.value, element)) {
|
||||
level++;
|
||||
}
|
||||
if (level === 0) {
|
||||
return i;
|
||||
}
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function isTagStart(tagType, { type, tag, position }) {
|
||||
return type === "tag" && tag === tagType && position === "start";
|
||||
}
|
||||
function isTagEnd(tagType, { type, tag, position }) {
|
||||
return type === "tag" && tag === tagType && position === "end";
|
||||
}
|
||||
function isParagraphStart(options) {
|
||||
return isTagStart("w:p", options) || isTagStart("a:p", options);
|
||||
}
|
||||
function isParagraphEnd(options) {
|
||||
return isTagEnd("w:p", options) || isTagEnd("a:p", options);
|
||||
}
|
||||
function isTextStart(part) {
|
||||
return part.type === "tag" && part.position === "start" && part.text;
|
||||
}
|
||||
function isTextEnd(part) {
|
||||
return part.type === "tag" && part.position === "end" && part.text;
|
||||
}
|
||||
|
||||
function isContent(p) {
|
||||
return (
|
||||
p.type === "placeholder" ||
|
||||
(p.type === "content" && p.position === "insidetag")
|
||||
);
|
||||
}
|
||||
|
||||
const corruptCharacters = /[\x00-\x08\x0B\x0C\x0E-\x1F]/;
|
||||
// 00 NUL '\0' (null character)
|
||||
// 01 SOH (start of heading)
|
||||
// 02 STX (start of text)
|
||||
// 03 ETX (end of text)
|
||||
// 04 EOT (end of transmission)
|
||||
// 05 ENQ (enquiry)
|
||||
// 06 ACK (acknowledge)
|
||||
// 07 BEL '\a' (bell)
|
||||
// 08 BS '\b' (backspace)
|
||||
// 0B VT '\v' (vertical tab)
|
||||
// 0C FF '\f' (form feed)
|
||||
// 0E SO (shift out)
|
||||
// 0F SI (shift in)
|
||||
// 10 DLE (data link escape)
|
||||
// 11 DC1 (device control 1)
|
||||
// 12 DC2 (device control 2)
|
||||
// 13 DC3 (device control 3)
|
||||
// 14 DC4 (device control 4)
|
||||
// 15 NAK (negative ack.)
|
||||
// 16 SYN (synchronous idle)
|
||||
// 17 ETB (end of trans. blk)
|
||||
// 18 CAN (cancel)
|
||||
// 19 EM (end of medium)
|
||||
// 1A SUB (substitute)
|
||||
// 1B ESC (escape)
|
||||
// 1C FS (file separator)
|
||||
// 1D GS (group separator)
|
||||
// 1E RS (record separator)
|
||||
// 1F US (unit separator)
|
||||
function hasCorruptCharacters(string) {
|
||||
return corruptCharacters.test(string);
|
||||
}
|
||||
|
||||
function invertMap(map) {
|
||||
return Object.keys(map).reduce(function (invertedMap, key) {
|
||||
const value = map[key];
|
||||
invertedMap[value] = invertedMap[value] || [];
|
||||
invertedMap[value].push(key);
|
||||
return invertedMap;
|
||||
}, {});
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
endsWith,
|
||||
startsWith,
|
||||
getNearestLeft,
|
||||
getNearestRight,
|
||||
getNearestLeftWithCache,
|
||||
getNearestRightWithCache,
|
||||
getNearestLeftIndex,
|
||||
getNearestRightIndex,
|
||||
getNearestLeftIndexWithCache,
|
||||
getNearestRightIndexWithCache,
|
||||
buildNearestCache,
|
||||
isContent,
|
||||
isParagraphStart,
|
||||
isParagraphEnd,
|
||||
isTagStart,
|
||||
isTagEnd,
|
||||
isTextStart,
|
||||
isTextEnd,
|
||||
unique,
|
||||
chunkBy,
|
||||
last,
|
||||
first,
|
||||
mergeObjects,
|
||||
xml2str,
|
||||
str2xml,
|
||||
getRightOrNull,
|
||||
getRight,
|
||||
getLeftOrNull,
|
||||
getLeft,
|
||||
pregMatchAll,
|
||||
convertSpaces,
|
||||
escapeRegExp,
|
||||
charMapRegexes,
|
||||
hasCorruptCharacters,
|
||||
defaults,
|
||||
wordToUtf8,
|
||||
utf8ToWord,
|
||||
concatArrays,
|
||||
invertMap,
|
||||
charMap,
|
||||
};
|
||||
113
es6/docxtemplater.d.ts
vendored
Normal file
113
es6/docxtemplater.d.ts
vendored
Normal file
@ -0,0 +1,113 @@
|
||||
// Type definitions for Docxtemplater 3
|
||||
// Project: https://github.com/open-xml-templating/docxtemplater/
|
||||
// Definitions by: edi9999 <https://github.com/edi9999>
|
||||
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
|
||||
// TypeScript Version: 3.9
|
||||
|
||||
export namespace DXT {
|
||||
type integer = number;
|
||||
|
||||
interface SimplePart {
|
||||
type: string
|
||||
value: string
|
||||
module?: string
|
||||
[x: string]: any
|
||||
}
|
||||
|
||||
interface Part {
|
||||
type: string
|
||||
value: string
|
||||
module: string
|
||||
raw: string
|
||||
offset: integer
|
||||
lIndex: integer
|
||||
num: integer
|
||||
inverted?: boolean
|
||||
endLIndex?: integer
|
||||
expanded?: Part[]
|
||||
subparsed?: Part[]
|
||||
}
|
||||
|
||||
interface Rendered {
|
||||
value: string
|
||||
errors: any[]
|
||||
}
|
||||
|
||||
type Error = any
|
||||
|
||||
interface Module {
|
||||
set?(options:any): void
|
||||
parse?(placeHolderContent: string): SimplePart | null
|
||||
render?(part: Part): Rendered | null
|
||||
getTraits?(traitName: string, parsed: any): any
|
||||
getFileType?(opts: any): string
|
||||
nullGetter?(part: Part, scopeManager: any) : any
|
||||
optionsTransformer?(options: Options): Options
|
||||
postrender?(parts: string[], options: any) : string[]
|
||||
errorsTransformer?(errors: Error[]) :Error[]
|
||||
getRenderedMap?(map: any): any
|
||||
preparse?(parsed: any, options: any): any
|
||||
postparse?(postparsed: Part[], modules: Module[], options: any): Part[]
|
||||
on?(event :string) :void
|
||||
resolve?(part :Part, options: any): null | Promise<any>
|
||||
[x: string]: any
|
||||
}
|
||||
|
||||
interface ParserContext {
|
||||
meta: {
|
||||
part: Part
|
||||
}
|
||||
scopeList: any[]
|
||||
scopePath: string[]
|
||||
scopePathItem: integer[]
|
||||
scopePathLength: integer[]
|
||||
num: integer
|
||||
}
|
||||
|
||||
interface Parser{
|
||||
get(scope: any, context: ParserContext): any
|
||||
}
|
||||
|
||||
interface ConstructorOptions {
|
||||
modules? : Module[]
|
||||
delimiters? : { start: string, end: string }
|
||||
paragraphLoop? : boolean
|
||||
parser?(tag: string) : Parser
|
||||
linebreaks?: boolean
|
||||
nullGetter?(part: Part) : any
|
||||
}
|
||||
|
||||
interface Options {
|
||||
delimiters? : { start: string, end: string }
|
||||
paragraphLoop? : boolean
|
||||
parser?(tag: string) : Parser
|
||||
linebreaks?: boolean
|
||||
nullGetter?(part: Part) : any
|
||||
}
|
||||
}
|
||||
|
||||
declare class Docxtemplater {
|
||||
/**
|
||||
* Create Docxtemplater instance (and compile it on the fly)
|
||||
*
|
||||
* @param zip Serialized zip archive
|
||||
* @param options modules and other other options
|
||||
*/
|
||||
constructor (zip: any, options?: DXT.ConstructorOptions);
|
||||
/**
|
||||
* Create Docxtemplater instance, without options
|
||||
*/
|
||||
constructor ();
|
||||
|
||||
setData(data: any): this
|
||||
resolveData(data: any): Promise<any>
|
||||
render() : this
|
||||
getZip() : any
|
||||
|
||||
loadZip(zip: any): this
|
||||
setOptions(options: DXT.Options): this
|
||||
attachModule(module: DXT.Module): this
|
||||
compile(): this
|
||||
}
|
||||
|
||||
export default Docxtemplater;
|
||||
423
es6/docxtemplater.js
Normal file
423
es6/docxtemplater.js
Normal file
@ -0,0 +1,423 @@
|
||||
"use strict";
|
||||
|
||||
const DocUtils = require("./doc-utils");
|
||||
DocUtils.traits = require("./traits");
|
||||
DocUtils.moduleWrapper = require("./module-wrapper");
|
||||
const {
|
||||
throwMultiError,
|
||||
throwResolveBeforeCompile,
|
||||
throwRenderInvalidTemplate,
|
||||
} = require("./errors");
|
||||
|
||||
const collectContentTypes = require("./collect-content-types");
|
||||
const ctXML = "[Content_Types].xml";
|
||||
const commonModule = require("./modules/common");
|
||||
|
||||
const Lexer = require("./lexer");
|
||||
const {
|
||||
defaults,
|
||||
str2xml,
|
||||
xml2str,
|
||||
moduleWrapper,
|
||||
utf8ToWord,
|
||||
concatArrays,
|
||||
unique,
|
||||
} = DocUtils;
|
||||
const {
|
||||
XTInternalError,
|
||||
throwFileTypeNotIdentified,
|
||||
throwFileTypeNotHandled,
|
||||
throwApiVersionError,
|
||||
} = require("./errors");
|
||||
|
||||
const currentModuleApiVersion = [3, 24, 0];
|
||||
|
||||
const Docxtemplater = class Docxtemplater {
|
||||
constructor(zip, { modules = [], ...options } = {}) {
|
||||
if (!Array.isArray(modules)) {
|
||||
throw new Error(
|
||||
"The modules argument of docxtemplater's constructor must be an array"
|
||||
);
|
||||
}
|
||||
this.compiled = {};
|
||||
this.modules = [commonModule()];
|
||||
this.setOptions(options);
|
||||
modules.forEach((module) => {
|
||||
this.attachModule(module);
|
||||
});
|
||||
if (zip) {
|
||||
if (!zip.files || typeof zip.file !== "function") {
|
||||
throw new Error(
|
||||
"The first argument of docxtemplater's constructor must be a valid zip file (jszip v2 or pizzip v3)"
|
||||
);
|
||||
}
|
||||
this.loadZip(zip);
|
||||
// remove the unsupported modules
|
||||
this.modules = this.modules.filter((module) => {
|
||||
if (module.supportedFileTypes) {
|
||||
if (!Array.isArray(module.supportedFileTypes)) {
|
||||
throw new Error(
|
||||
"The supportedFileTypes field of the module must be an array"
|
||||
);
|
||||
}
|
||||
const isSupportedModule =
|
||||
module.supportedFileTypes.indexOf(this.fileType) !== -1;
|
||||
if (!isSupportedModule) {
|
||||
module.on("detached");
|
||||
}
|
||||
return isSupportedModule;
|
||||
}
|
||||
return true;
|
||||
});
|
||||
this.compile();
|
||||
this.v4Constructor = true;
|
||||
}
|
||||
}
|
||||
getModuleApiVersion() {
|
||||
return currentModuleApiVersion.join(".");
|
||||
}
|
||||
verifyApiVersion(neededVersion) {
|
||||
neededVersion = neededVersion.split(".").map(function (i) {
|
||||
return parseInt(i, 10);
|
||||
});
|
||||
if (neededVersion.length !== 3) {
|
||||
throwApiVersionError("neededVersion is not a valid version", {
|
||||
neededVersion,
|
||||
explanation: "the neededVersion must be an array of length 3",
|
||||
});
|
||||
}
|
||||
if (neededVersion[0] !== currentModuleApiVersion[0]) {
|
||||
throwApiVersionError(
|
||||
"The major api version do not match, you probably have to update docxtemplater with npm install --save docxtemplater",
|
||||
{
|
||||
neededVersion,
|
||||
currentModuleApiVersion,
|
||||
explanation: `moduleAPIVersionMismatch : needed=${neededVersion.join(
|
||||
"."
|
||||
)}, current=${currentModuleApiVersion.join(".")}`,
|
||||
}
|
||||
);
|
||||
}
|
||||
if (neededVersion[1] > currentModuleApiVersion[1]) {
|
||||
throwApiVersionError(
|
||||
"The minor api version is not uptodate, you probably have to update docxtemplater with npm install --save docxtemplater",
|
||||
{
|
||||
neededVersion,
|
||||
currentModuleApiVersion,
|
||||
explanation: `moduleAPIVersionMismatch : needed=${neededVersion.join(
|
||||
"."
|
||||
)}, current=${currentModuleApiVersion.join(".")}`,
|
||||
}
|
||||
);
|
||||
}
|
||||
if (
|
||||
neededVersion[1] === currentModuleApiVersion[1] &&
|
||||
neededVersion[2] > currentModuleApiVersion[2]
|
||||
) {
|
||||
throwApiVersionError(
|
||||
"The patch api version is not uptodate, you probably have to update docxtemplater with npm install --save docxtemplater",
|
||||
{
|
||||
neededVersion,
|
||||
currentModuleApiVersion,
|
||||
explanation: `moduleAPIVersionMismatch : needed=${neededVersion.join(
|
||||
"."
|
||||
)}, current=${currentModuleApiVersion.join(".")}`,
|
||||
}
|
||||
);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
setModules(obj) {
|
||||
this.modules.forEach((module) => {
|
||||
module.set(obj);
|
||||
});
|
||||
}
|
||||
sendEvent(eventName) {
|
||||
this.modules.forEach((module) => {
|
||||
module.on(eventName);
|
||||
});
|
||||
}
|
||||
attachModule(module, options = {}) {
|
||||
if (this.v4Constructor) {
|
||||
throw new Error(
|
||||
"attachModule() should not be called manually when using the v4 constructor"
|
||||
);
|
||||
}
|
||||
if (module.requiredAPIVersion) {
|
||||
this.verifyApiVersion(module.requiredAPIVersion);
|
||||
}
|
||||
if (module.attached === true) {
|
||||
throw new Error(
|
||||
`Cannot attach a module that was already attached : "${module.name}". Maybe you are instantiating the module at the root level, and using it for multiple instances of Docxtemplater`
|
||||
);
|
||||
}
|
||||
module.attached = true;
|
||||
const { prefix } = options;
|
||||
if (prefix) {
|
||||
module.prefix = prefix;
|
||||
}
|
||||
const wrappedModule = moduleWrapper(module);
|
||||
this.modules.push(wrappedModule);
|
||||
wrappedModule.on("attached");
|
||||
return this;
|
||||
}
|
||||
setOptions(options) {
|
||||
if (this.v4Constructor) {
|
||||
throw new Error(
|
||||
"setOptions() should not be called manually when using the v4 constructor"
|
||||
);
|
||||
}
|
||||
if (!options) {
|
||||
throw new Error(
|
||||
"setOptions should be called with an object as first parameter"
|
||||
);
|
||||
}
|
||||
if (options.delimiters) {
|
||||
options.delimiters.start = utf8ToWord(options.delimiters.start);
|
||||
options.delimiters.end = utf8ToWord(options.delimiters.end);
|
||||
}
|
||||
this.options = {};
|
||||
Object.keys(defaults).forEach((key) => {
|
||||
const defaultValue = defaults[key];
|
||||
this.options[key] = options[key] != null ? options[key] : defaultValue;
|
||||
this[key] = this.options[key];
|
||||
});
|
||||
if (this.zip) {
|
||||
this.updateFileTypeConfig();
|
||||
}
|
||||
return this;
|
||||
}
|
||||
loadZip(zip) {
|
||||
if (zip.loadAsync) {
|
||||
throw new XTInternalError(
|
||||
"Docxtemplater doesn't handle JSZip version >=3, please use pizzip"
|
||||
);
|
||||
}
|
||||
this.zip = zip;
|
||||
this.updateFileTypeConfig();
|
||||
|
||||
this.modules = concatArrays([
|
||||
this.fileTypeConfig.baseModules.map(function (moduleFunction) {
|
||||
return moduleFunction();
|
||||
}),
|
||||
this.modules,
|
||||
]);
|
||||
return this;
|
||||
}
|
||||
compileFile(fileName) {
|
||||
this.compiled[fileName].parse();
|
||||
}
|
||||
precompileFile(fileName) {
|
||||
const currentFile = this.createTemplateClass(fileName);
|
||||
currentFile.preparse();
|
||||
this.compiled[fileName] = currentFile;
|
||||
}
|
||||
resolveData(data) {
|
||||
let errors = [];
|
||||
if (!Object.keys(this.compiled).length) {
|
||||
throwResolveBeforeCompile();
|
||||
}
|
||||
return Promise.resolve(data)
|
||||
.then((data) => {
|
||||
return Promise.all(
|
||||
Object.keys(this.compiled).map((from) => {
|
||||
const currentFile = this.compiled[from];
|
||||
return currentFile.resolveTags(data).catch(function (errs) {
|
||||
errors = errors.concat(errs);
|
||||
});
|
||||
})
|
||||
);
|
||||
})
|
||||
.then((resolved) => {
|
||||
if (errors.length !== 0) {
|
||||
throwMultiError(errors);
|
||||
}
|
||||
return concatArrays(resolved);
|
||||
});
|
||||
}
|
||||
compile() {
|
||||
if (Object.keys(this.compiled).length) {
|
||||
return this;
|
||||
}
|
||||
this.options = this.modules.reduce((options, module) => {
|
||||
return module.optionsTransformer(options, this);
|
||||
}, this.options);
|
||||
this.options.xmlFileNames = unique(this.options.xmlFileNames);
|
||||
this.xmlDocuments = this.options.xmlFileNames.reduce(
|
||||
(xmlDocuments, fileName) => {
|
||||
const content = this.zip.files[fileName].asText();
|
||||
xmlDocuments[fileName] = str2xml(content);
|
||||
return xmlDocuments;
|
||||
},
|
||||
{}
|
||||
);
|
||||
this.setModules({
|
||||
zip: this.zip,
|
||||
xmlDocuments: this.xmlDocuments,
|
||||
});
|
||||
this.getTemplatedFiles();
|
||||
this.setModules({ compiled: this.compiled });
|
||||
// Loop inside all templatedFiles (ie xml files with content).
|
||||
// Sometimes they don't exist (footer.xml for example)
|
||||
this.templatedFiles.forEach((fileName) => {
|
||||
if (this.zip.files[fileName] != null) {
|
||||
this.precompileFile(fileName);
|
||||
}
|
||||
});
|
||||
this.templatedFiles.forEach((fileName) => {
|
||||
if (this.zip.files[fileName] != null) {
|
||||
this.compileFile(fileName);
|
||||
}
|
||||
});
|
||||
verifyErrors(this);
|
||||
return this;
|
||||
}
|
||||
updateFileTypeConfig() {
|
||||
let fileType;
|
||||
if (this.zip.files.mimetype) {
|
||||
fileType = "odt";
|
||||
}
|
||||
const contentTypes = this.zip.files[ctXML];
|
||||
this.targets = [];
|
||||
const contentTypeXml = contentTypes ? str2xml(contentTypes.asText()) : null;
|
||||
const overrides = contentTypeXml
|
||||
? contentTypeXml.getElementsByTagName("Override")
|
||||
: null;
|
||||
const defaults = contentTypeXml
|
||||
? contentTypeXml.getElementsByTagName("Default")
|
||||
: null;
|
||||
if (contentTypeXml) {
|
||||
this.filesContentTypes = collectContentTypes(
|
||||
overrides,
|
||||
defaults,
|
||||
this.zip
|
||||
);
|
||||
this.invertedContentTypes = DocUtils.invertMap(this.filesContentTypes);
|
||||
this.setModules({
|
||||
contentTypes: this.contentTypes,
|
||||
invertedContentTypes: this.invertedContentTypes,
|
||||
});
|
||||
}
|
||||
this.modules.forEach((module) => {
|
||||
fileType =
|
||||
module.getFileType({
|
||||
zip: this.zip,
|
||||
contentTypes,
|
||||
contentTypeXml,
|
||||
overrides,
|
||||
defaults,
|
||||
doc: this,
|
||||
}) || fileType;
|
||||
});
|
||||
if (fileType === "odt") {
|
||||
throwFileTypeNotHandled(fileType);
|
||||
}
|
||||
if (!fileType) {
|
||||
throwFileTypeNotIdentified();
|
||||
}
|
||||
|
||||
this.fileType = fileType;
|
||||
|
||||
this.fileTypeConfig =
|
||||
this.options.fileTypeConfig ||
|
||||
this.fileTypeConfig ||
|
||||
Docxtemplater.FileTypeConfig[this.fileType];
|
||||
return this;
|
||||
}
|
||||
render() {
|
||||
this.compile();
|
||||
if (this.errors.length > 0) {
|
||||
throwRenderInvalidTemplate();
|
||||
}
|
||||
this.setModules({
|
||||
data: this.data,
|
||||
Lexer,
|
||||
});
|
||||
this.mapper = this.modules.reduce(function (value, module) {
|
||||
return module.getRenderedMap(value);
|
||||
}, {});
|
||||
|
||||
this.fileTypeConfig.tagsXmlLexedArray = unique(
|
||||
this.fileTypeConfig.tagsXmlLexedArray
|
||||
);
|
||||
this.fileTypeConfig.tagsXmlTextArray = unique(
|
||||
this.fileTypeConfig.tagsXmlTextArray
|
||||
);
|
||||
|
||||
Object.keys(this.mapper).forEach((to) => {
|
||||
const { from, data } = this.mapper[to];
|
||||
const currentFile = this.compiled[from];
|
||||
currentFile.setTags(data);
|
||||
currentFile.render(to);
|
||||
this.zip.file(to, currentFile.content, { createFolders: true });
|
||||
});
|
||||
|
||||
verifyErrors(this);
|
||||
this.sendEvent("syncing-zip");
|
||||
this.syncZip();
|
||||
return this;
|
||||
}
|
||||
syncZip() {
|
||||
Object.keys(this.xmlDocuments).forEach((fileName) => {
|
||||
this.zip.remove(fileName);
|
||||
const content = xml2str(this.xmlDocuments[fileName]);
|
||||
return this.zip.file(fileName, content, { createFolders: true });
|
||||
});
|
||||
}
|
||||
setData(data) {
|
||||
this.data = data;
|
||||
return this;
|
||||
}
|
||||
getZip() {
|
||||
return this.zip;
|
||||
}
|
||||
createTemplateClass(path) {
|
||||
const content = this.zip.files[path].asText();
|
||||
return this.createTemplateClassFromContent(content, path);
|
||||
}
|
||||
createTemplateClassFromContent(content, filePath) {
|
||||
const xmltOptions = {
|
||||
filePath,
|
||||
contentType: this.filesContentTypes[filePath],
|
||||
};
|
||||
Object.keys(defaults)
|
||||
.concat(["filesContentTypes", "fileTypeConfig", "modules"])
|
||||
.forEach((key) => {
|
||||
xmltOptions[key] = this[key];
|
||||
});
|
||||
return new Docxtemplater.XmlTemplater(content, xmltOptions);
|
||||
}
|
||||
getFullText(path) {
|
||||
return this.createTemplateClass(
|
||||
path || this.fileTypeConfig.textPath(this)
|
||||
).getFullText();
|
||||
}
|
||||
getTemplatedFiles() {
|
||||
this.templatedFiles = this.fileTypeConfig.getTemplatedFiles(this.zip);
|
||||
this.targets.forEach((target) => {
|
||||
this.templatedFiles.push(target);
|
||||
});
|
||||
return this.templatedFiles;
|
||||
}
|
||||
};
|
||||
|
||||
function verifyErrors(doc) {
|
||||
const compiled = doc.compiled;
|
||||
let allErrors = [];
|
||||
Object.keys(compiled).forEach((name) => {
|
||||
const templatePart = compiled[name];
|
||||
allErrors = concatArrays([allErrors, templatePart.allErrors]);
|
||||
});
|
||||
doc.errors = allErrors;
|
||||
|
||||
if (allErrors.length !== 0) {
|
||||
throwMultiError(allErrors);
|
||||
}
|
||||
}
|
||||
|
||||
Docxtemplater.DocUtils = DocUtils;
|
||||
Docxtemplater.Errors = require("./errors");
|
||||
Docxtemplater.XmlTemplater = require("./xml-templater");
|
||||
Docxtemplater.FileTypeConfig = require("./file-type-config");
|
||||
Docxtemplater.XmlMatcher = require("./xml-matcher");
|
||||
module.exports = Docxtemplater;
|
||||
77
es6/docxtemplater.test-d.ts
Normal file
77
es6/docxtemplater.test-d.ts
Normal file
@ -0,0 +1,77 @@
|
||||
import Docxtemplater, {DXT} from "./docxtemplater";
|
||||
const PizZip: any = require('pizzip');
|
||||
import {expectType, expectError} from 'tsd';
|
||||
const doc1 = new Docxtemplater({}, {delimiters: { start: '[[', end: ']]'},
|
||||
nullGetter: function(part) {
|
||||
expectError(part.foobar);
|
||||
if (part.module === "rawxml") {
|
||||
return "";
|
||||
}
|
||||
if (part.type === "placeholder" && part.value === "foobar") {
|
||||
return "{Foobar}"
|
||||
}
|
||||
return "Hello";
|
||||
},
|
||||
});
|
||||
doc1.setData({foo: "bar"});
|
||||
doc1.attachModule({
|
||||
set: function() {
|
||||
|
||||
},
|
||||
parse: function(placeHolderContent) {
|
||||
if (placeHolderContent.indexOf(":hello") === 0) {
|
||||
return {
|
||||
type: "placeholder",
|
||||
module: "mycustomModule",
|
||||
value: placeHolderContent.substr(7),
|
||||
isEmpty: "foobar",
|
||||
}
|
||||
}
|
||||
return null;
|
||||
},
|
||||
getFoobar: function() {
|
||||
|
||||
}
|
||||
});
|
||||
doc1.render()
|
||||
|
||||
expectError(doc1.foobar())
|
||||
expectError(new Docxtemplater(1,2))
|
||||
expectError(new Docxtemplater({}, {delimiters: { start: 1, end: ']]'}}))
|
||||
expectError(new Docxtemplater({}, {delimiters: { start: '[['}}))
|
||||
|
||||
const doc2 = new Docxtemplater();
|
||||
doc2.loadZip(new PizZip("hello"));
|
||||
|
||||
// Error because parser should return a {get: fn} object
|
||||
expectError(doc2.setOptions({
|
||||
parser: function(tag) {
|
||||
return 10;
|
||||
}
|
||||
}));
|
||||
|
||||
doc2.setOptions({
|
||||
parser: function(tag) {
|
||||
expectType<string>(tag)
|
||||
return {
|
||||
get: function(scope, context) {
|
||||
const first = context.scopeList[0]
|
||||
expectType<DXT.integer>(context.num)
|
||||
expectError(context.foobar);
|
||||
if (context.meta.part.value === tag) {
|
||||
return scope[context.meta.part.value];
|
||||
}
|
||||
expectError(context.meta.part.other);
|
||||
return scope[tag];
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
const doc3 = new Docxtemplater();
|
||||
doc3.loadZip(new PizZip("hello"));
|
||||
doc3.compile();
|
||||
doc3.resolveData({a: "b"}).then(function() {
|
||||
doc3.render();
|
||||
});
|
||||
|
||||
27
es6/error-logger.js
Normal file
27
es6/error-logger.js
Normal file
@ -0,0 +1,27 @@
|
||||
// The error thrown here contains additional information when logged with JSON.stringify (it contains a properties object containing all suberrors).
|
||||
function replaceErrors(key, value) {
|
||||
if (value instanceof Error) {
|
||||
return Object.getOwnPropertyNames(value).reduce(function (error, key) {
|
||||
error[key] = value[key];
|
||||
return error;
|
||||
}, {});
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
function logger(error) {
|
||||
// eslint-disable-next-line no-console
|
||||
console.log(JSON.stringify({ error }, replaceErrors));
|
||||
if (error.properties && error.properties.errors instanceof Array) {
|
||||
const errorMessages = error.properties.errors
|
||||
.map(function (error) {
|
||||
return error.properties.explanation;
|
||||
})
|
||||
.join("\n");
|
||||
// eslint-disable-next-line no-console
|
||||
console.log("errorMessages", errorMessages);
|
||||
// errorMessages is a humanly readable message looking like this :
|
||||
// 'The tag beginning with "foobar" is unopened'
|
||||
}
|
||||
}
|
||||
module.exports = logger;
|
||||
394
es6/errors.js
Normal file
394
es6/errors.js
Normal file
@ -0,0 +1,394 @@
|
||||
"use strict";
|
||||
const { last, first } = require("./utils");
|
||||
|
||||
function XTError(message) {
|
||||
this.name = "GenericError";
|
||||
this.message = message;
|
||||
this.stack = new Error(message).stack;
|
||||
}
|
||||
XTError.prototype = Error.prototype;
|
||||
|
||||
function XTTemplateError(message) {
|
||||
this.name = "TemplateError";
|
||||
this.message = message;
|
||||
this.stack = new Error(message).stack;
|
||||
}
|
||||
XTTemplateError.prototype = new XTError();
|
||||
|
||||
function XTRenderingError(message) {
|
||||
this.name = "RenderingError";
|
||||
this.message = message;
|
||||
this.stack = new Error(message).stack;
|
||||
}
|
||||
XTRenderingError.prototype = new XTError();
|
||||
|
||||
function XTScopeParserError(message) {
|
||||
this.name = "ScopeParserError";
|
||||
this.message = message;
|
||||
this.stack = new Error(message).stack;
|
||||
}
|
||||
XTScopeParserError.prototype = new XTError();
|
||||
|
||||
function XTInternalError(message) {
|
||||
this.name = "InternalError";
|
||||
this.properties = { explanation: "InternalError" };
|
||||
this.message = message;
|
||||
this.stack = new Error(message).stack;
|
||||
}
|
||||
XTInternalError.prototype = new XTError();
|
||||
|
||||
function XTAPIVersionError(message) {
|
||||
this.name = "APIVersionError";
|
||||
this.properties = { explanation: "APIVersionError" };
|
||||
this.message = message;
|
||||
this.stack = new Error(message).stack;
|
||||
}
|
||||
XTAPIVersionError.prototype = new XTError();
|
||||
|
||||
function throwApiVersionError(msg, properties) {
|
||||
const err = new XTAPIVersionError(msg);
|
||||
err.properties = {
|
||||
id: "api_version_error",
|
||||
...properties,
|
||||
};
|
||||
throw err;
|
||||
}
|
||||
|
||||
function throwMultiError(errors) {
|
||||
const err = new XTTemplateError("Multi error");
|
||||
err.properties = {
|
||||
errors,
|
||||
id: "multi_error",
|
||||
explanation: "The template has multiple errors",
|
||||
};
|
||||
throw err;
|
||||
}
|
||||
|
||||
function getUnopenedTagException(options) {
|
||||
const err = new XTTemplateError("Unopened tag");
|
||||
err.properties = {
|
||||
xtag: last(options.xtag.split(" ")),
|
||||
id: "unopened_tag",
|
||||
context: options.xtag,
|
||||
offset: options.offset,
|
||||
lIndex: options.lIndex,
|
||||
explanation: `The tag beginning with "${options.xtag.substr(
|
||||
0,
|
||||
10
|
||||
)}" is unopened`,
|
||||
};
|
||||
return err;
|
||||
}
|
||||
|
||||
function getDuplicateOpenTagException(options) {
|
||||
const err = new XTTemplateError("Duplicate open tag, expected one open tag");
|
||||
err.properties = {
|
||||
xtag: first(options.xtag.split(" ")),
|
||||
id: "duplicate_open_tag",
|
||||
context: options.xtag,
|
||||
offset: options.offset,
|
||||
lIndex: options.lIndex,
|
||||
explanation: `The tag beginning with "${options.xtag.substr(
|
||||
0,
|
||||
10
|
||||
)}" has duplicate open tags`,
|
||||
};
|
||||
return err;
|
||||
}
|
||||
|
||||
function getDuplicateCloseTagException(options) {
|
||||
const err = new XTTemplateError(
|
||||
"Duplicate close tag, expected one close tag"
|
||||
);
|
||||
err.properties = {
|
||||
xtag: first(options.xtag.split(" ")),
|
||||
id: "duplicate_close_tag",
|
||||
context: options.xtag,
|
||||
offset: options.offset,
|
||||
lIndex: options.lIndex,
|
||||
explanation: `The tag ending with "${options.xtag.substr(
|
||||
0,
|
||||
10
|
||||
)}" has duplicate close tags`,
|
||||
};
|
||||
return err;
|
||||
}
|
||||
|
||||
function getUnclosedTagException(options) {
|
||||
const err = new XTTemplateError("Unclosed tag");
|
||||
err.properties = {
|
||||
xtag: first(options.xtag.split(" ")).substr(1),
|
||||
id: "unclosed_tag",
|
||||
context: options.xtag,
|
||||
offset: options.offset,
|
||||
lIndex: options.lIndex,
|
||||
explanation: `The tag beginning with "${options.xtag.substr(
|
||||
0,
|
||||
10
|
||||
)}" is unclosed`,
|
||||
};
|
||||
return err;
|
||||
}
|
||||
|
||||
function throwXmlTagNotFound(options) {
|
||||
const err = new XTTemplateError(
|
||||
`No tag "${options.element}" was found at the ${options.position}`
|
||||
);
|
||||
const part = options.parsed[options.index];
|
||||
err.properties = {
|
||||
id: `no_xml_tag_found_at_${options.position}`,
|
||||
explanation: `No tag "${options.element}" was found at the ${options.position}`,
|
||||
offset: part.offset,
|
||||
part,
|
||||
parsed: options.parsed,
|
||||
index: options.index,
|
||||
element: options.element,
|
||||
};
|
||||
throw err;
|
||||
}
|
||||
|
||||
function getCorruptCharactersException({ tag, value, offset }) {
|
||||
const err = new XTRenderingError("There are some XML corrupt characters");
|
||||
err.properties = {
|
||||
id: "invalid_xml_characters",
|
||||
xtag: tag,
|
||||
value,
|
||||
offset,
|
||||
explanation: "There are some corrupt characters for the field ${tag}",
|
||||
};
|
||||
return err;
|
||||
}
|
||||
|
||||
function throwContentMustBeString(type) {
|
||||
const err = new XTInternalError("Content must be a string");
|
||||
err.properties.id = "xmltemplater_content_must_be_string";
|
||||
err.properties.type = type;
|
||||
throw err;
|
||||
}
|
||||
|
||||
function throwExpandNotFound(options) {
|
||||
const {
|
||||
part: { value, offset },
|
||||
id = "raw_tag_outerxml_invalid",
|
||||
message = "Raw tag not in paragraph",
|
||||
} = options;
|
||||
const { part } = options;
|
||||
let {
|
||||
explanation = `The tag "${value}" is not inside a paragraph`,
|
||||
} = options;
|
||||
if (typeof explanation === "function") {
|
||||
explanation = explanation(part);
|
||||
}
|
||||
const err = new XTTemplateError(message);
|
||||
err.properties = {
|
||||
id,
|
||||
explanation,
|
||||
rootError: options.rootError,
|
||||
xtag: value,
|
||||
offset,
|
||||
postparsed: options.postparsed,
|
||||
expandTo: options.expandTo,
|
||||
index: options.index,
|
||||
};
|
||||
throw err;
|
||||
}
|
||||
|
||||
function throwRawTagShouldBeOnlyTextInParagraph(options) {
|
||||
const err = new XTTemplateError(
|
||||
"Raw tag should be the only text in paragraph"
|
||||
);
|
||||
const tag = options.part.value;
|
||||
err.properties = {
|
||||
id: "raw_xml_tag_should_be_only_text_in_paragraph",
|
||||
explanation: `The raw tag "${tag}" should be the only text in this paragraph. This means that this tag should not be surrounded by any text or spaces.`,
|
||||
xtag: tag,
|
||||
offset: options.part.offset,
|
||||
paragraphParts: options.paragraphParts,
|
||||
};
|
||||
throw err;
|
||||
}
|
||||
|
||||
function getUnmatchedLoopException(options) {
|
||||
const { location } = options;
|
||||
const t = location === "start" ? "unclosed" : "unopened";
|
||||
const T = location === "start" ? "Unclosed" : "Unopened";
|
||||
|
||||
const err = new XTTemplateError(`${T} loop`);
|
||||
const tag = options.part.value;
|
||||
err.properties = {
|
||||
id: `${t}_loop`,
|
||||
explanation: `The loop with tag "${tag}" is ${t}`,
|
||||
xtag: tag,
|
||||
offset: options.part.offset,
|
||||
};
|
||||
return err;
|
||||
}
|
||||
|
||||
function getClosingTagNotMatchOpeningTag({ tags }) {
|
||||
const err = new XTTemplateError("Closing tag does not match opening tag");
|
||||
err.properties = {
|
||||
id: "closing_tag_does_not_match_opening_tag",
|
||||
explanation: `The tag "${tags[0].value}" is closed by the tag "${tags[1].value}"`,
|
||||
openingtag: first(tags).value,
|
||||
offset: [first(tags).offset, last(tags).offset],
|
||||
closingtag: last(tags).value,
|
||||
};
|
||||
return err;
|
||||
}
|
||||
|
||||
function getScopeCompilationError({ tag, rootError, offset }) {
|
||||
const err = new XTScopeParserError("Scope parser compilation failed");
|
||||
err.properties = {
|
||||
id: "scopeparser_compilation_failed",
|
||||
offset,
|
||||
tag,
|
||||
explanation: `The scope parser for the tag "${tag}" failed to compile`,
|
||||
rootError,
|
||||
};
|
||||
return err;
|
||||
}
|
||||
|
||||
function getScopeParserExecutionError({ tag, scope, error, offset }) {
|
||||
const err = new XTScopeParserError("Scope parser execution failed");
|
||||
err.properties = {
|
||||
id: "scopeparser_execution_failed",
|
||||
explanation: `The scope parser for the tag ${tag} failed to execute`,
|
||||
scope,
|
||||
offset,
|
||||
tag,
|
||||
rootError: error,
|
||||
};
|
||||
return err;
|
||||
}
|
||||
|
||||
function getLoopPositionProducesInvalidXMLError({ tag, offset }) {
|
||||
const err = new XTTemplateError(
|
||||
`The position of the loop tags "${tag}" would produce invalid XML`
|
||||
);
|
||||
err.properties = {
|
||||
tag,
|
||||
id: "loop_position_invalid",
|
||||
explanation: `The tags "${tag}" are misplaced in the document, for example one of them is in a table and the other one outside the table`,
|
||||
offset,
|
||||
};
|
||||
return err;
|
||||
}
|
||||
|
||||
function throwUnimplementedTagType(part, index) {
|
||||
let errorMsg = `Unimplemented tag type "${part.type}"`;
|
||||
if (part.module) {
|
||||
errorMsg += ` "${part.module}"`;
|
||||
}
|
||||
const err = new XTTemplateError(errorMsg);
|
||||
err.properties = {
|
||||
part,
|
||||
index,
|
||||
id: "unimplemented_tag_type",
|
||||
};
|
||||
throw err;
|
||||
}
|
||||
|
||||
function throwMalformedXml(part) {
|
||||
const err = new XTInternalError("Malformed xml");
|
||||
err.properties = {
|
||||
part,
|
||||
id: "malformed_xml",
|
||||
};
|
||||
throw err;
|
||||
}
|
||||
|
||||
function throwLocationInvalid(part) {
|
||||
throw new XTInternalError(
|
||||
`Location should be one of "start" or "end" (given : ${part.location})`
|
||||
);
|
||||
}
|
||||
|
||||
function throwResolveBeforeCompile() {
|
||||
const err = new XTInternalError(
|
||||
"You must run `.compile()` before running `.resolveData()`"
|
||||
);
|
||||
err.properties = {
|
||||
id: "resolve_before_compile",
|
||||
};
|
||||
throw err;
|
||||
}
|
||||
|
||||
function throwRenderInvalidTemplate() {
|
||||
const err = new XTInternalError(
|
||||
"You should not call .render on a document that had compilation errors"
|
||||
);
|
||||
err.properties = {
|
||||
id: "render_on_invalid_template",
|
||||
};
|
||||
throw err;
|
||||
}
|
||||
|
||||
function throwFileTypeNotIdentified() {
|
||||
const err = new XTInternalError(
|
||||
"The filetype for this file could not be identified, is this file corrupted ?"
|
||||
);
|
||||
err.properties = {
|
||||
id: "filetype_not_identified",
|
||||
};
|
||||
throw err;
|
||||
}
|
||||
|
||||
function throwXmlInvalid(content, offset) {
|
||||
const err = new XTTemplateError("An XML file has invalid xml");
|
||||
err.properties = {
|
||||
id: "file_has_invalid_xml",
|
||||
content,
|
||||
offset,
|
||||
explanation: "The docx contains invalid XML, it is most likely corrupt",
|
||||
};
|
||||
throw err;
|
||||
}
|
||||
|
||||
function throwFileTypeNotHandled(fileType) {
|
||||
const err = new XTInternalError(
|
||||
`The filetype "${fileType}" is not handled by docxtemplater`
|
||||
);
|
||||
err.properties = {
|
||||
id: "filetype_not_handled",
|
||||
explanation: `The file you are trying to generate is of type "${fileType}", but only docx and pptx formats are handled`,
|
||||
fileType,
|
||||
};
|
||||
throw err;
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
XTError,
|
||||
XTTemplateError,
|
||||
XTInternalError,
|
||||
XTScopeParserError,
|
||||
XTAPIVersionError,
|
||||
// Remove this alias in v4
|
||||
RenderingError: XTRenderingError,
|
||||
XTRenderingError,
|
||||
|
||||
getClosingTagNotMatchOpeningTag,
|
||||
getLoopPositionProducesInvalidXMLError,
|
||||
getScopeCompilationError,
|
||||
getScopeParserExecutionError,
|
||||
getUnclosedTagException,
|
||||
getUnopenedTagException,
|
||||
getUnmatchedLoopException,
|
||||
getDuplicateCloseTagException,
|
||||
getDuplicateOpenTagException,
|
||||
getCorruptCharactersException,
|
||||
|
||||
throwApiVersionError,
|
||||
throwContentMustBeString,
|
||||
throwFileTypeNotHandled,
|
||||
throwFileTypeNotIdentified,
|
||||
throwLocationInvalid,
|
||||
throwMalformedXml,
|
||||
throwMultiError,
|
||||
throwExpandNotFound,
|
||||
throwRawTagShouldBeOnlyTextInParagraph,
|
||||
throwUnimplementedTagType,
|
||||
throwXmlTagNotFound,
|
||||
throwXmlInvalid,
|
||||
throwResolveBeforeCompile,
|
||||
throwRenderInvalidTemplate,
|
||||
};
|
||||
135
es6/file-type-config.js
Normal file
135
es6/file-type-config.js
Normal file
@ -0,0 +1,135 @@
|
||||
"use strict";
|
||||
|
||||
const loopModule = require("./modules/loop");
|
||||
const spacePreserveModule = require("./modules/space-preserve");
|
||||
const rawXmlModule = require("./modules/rawxml");
|
||||
const expandPairTrait = require("./modules/expand-pair-trait");
|
||||
const render = require("./modules/render");
|
||||
|
||||
const PptXFileTypeConfig = {
|
||||
getTemplatedFiles(zip) {
|
||||
const slideTemplates = zip
|
||||
.file(/ppt\/(slideMasters)\/(slideMaster)\d+\.xml/)
|
||||
.map(function (file) {
|
||||
return file.name;
|
||||
});
|
||||
return slideTemplates.concat([
|
||||
"ppt/presentation.xml",
|
||||
"docProps/app.xml",
|
||||
"docProps/core.xml",
|
||||
]);
|
||||
},
|
||||
textPath() {
|
||||
return "ppt/slides/slide1.xml";
|
||||
},
|
||||
tagsXmlTextArray: [
|
||||
"Company",
|
||||
"HyperlinkBase",
|
||||
"Manager",
|
||||
"cp:category",
|
||||
"cp:keywords",
|
||||
"dc:creator",
|
||||
"dc:description",
|
||||
"dc:subject",
|
||||
"dc:title",
|
||||
|
||||
"a:t",
|
||||
"m:t",
|
||||
"vt:lpstr",
|
||||
],
|
||||
tagsXmlLexedArray: [
|
||||
"p:sp",
|
||||
"a:tc",
|
||||
"a:tr",
|
||||
"a:table",
|
||||
"a:p",
|
||||
"a:r",
|
||||
"a:rPr",
|
||||
"p:txBody",
|
||||
"a:txBody",
|
||||
],
|
||||
expandTags: [{ contains: "a:tc", expand: "a:tr" }],
|
||||
onParagraphLoop: [{ contains: "a:p", expand: "a:p", onlyTextInTag: true }],
|
||||
tagRawXml: "p:sp",
|
||||
tagTextXml: "a:t",
|
||||
baseModules: [loopModule, expandPairTrait, rawXmlModule, render],
|
||||
tagShouldContain: [
|
||||
{ tag: "p:txBody", shouldContain: ["a:p"], value: "<a:p></a:p>" },
|
||||
{ tag: "a:txBody", shouldContain: ["a:p"], value: "<a:p></a:p>" },
|
||||
],
|
||||
};
|
||||
|
||||
const DocXFileTypeConfig = {
|
||||
getTemplatedFiles(zip) {
|
||||
const baseTags = [
|
||||
"docProps/core.xml",
|
||||
"docProps/app.xml",
|
||||
"word/settings.xml",
|
||||
];
|
||||
const headerFooters = zip
|
||||
.file(/word\/(header|footer)\d+\.xml/)
|
||||
.map(function (file) {
|
||||
return file.name;
|
||||
});
|
||||
return headerFooters.concat(baseTags);
|
||||
},
|
||||
textPath(doc) {
|
||||
return doc.targets[0];
|
||||
},
|
||||
tagsXmlTextArray: [
|
||||
"Company",
|
||||
"HyperlinkBase",
|
||||
"Manager",
|
||||
"cp:category",
|
||||
"cp:keywords",
|
||||
"dc:creator",
|
||||
"dc:description",
|
||||
"dc:subject",
|
||||
"dc:title",
|
||||
|
||||
"w:t",
|
||||
"m:t",
|
||||
"vt:lpstr",
|
||||
],
|
||||
tagsXmlLexedArray: [
|
||||
"w:proofState",
|
||||
"w:tc",
|
||||
"w:tr",
|
||||
"w:table",
|
||||
"w:p",
|
||||
"w:r",
|
||||
"w:br",
|
||||
"w:rPr",
|
||||
"w:pPr",
|
||||
"w:spacing",
|
||||
"w:sdtContent",
|
||||
|
||||
"w:sectPr",
|
||||
"w:headerReference",
|
||||
"w:footerReference",
|
||||
],
|
||||
expandTags: [{ contains: "w:tc", expand: "w:tr" }],
|
||||
onParagraphLoop: [{ contains: "w:p", expand: "w:p", onlyTextInTag: true }],
|
||||
tagRawXml: "w:p",
|
||||
tagTextXml: "w:t",
|
||||
baseModules: [
|
||||
loopModule,
|
||||
spacePreserveModule,
|
||||
expandPairTrait,
|
||||
rawXmlModule,
|
||||
render,
|
||||
],
|
||||
tagShouldContain: [
|
||||
{ tag: "w:tc", shouldContain: ["w:p"], value: "<w:p></w:p>" },
|
||||
{
|
||||
tag: "w:sdtContent",
|
||||
shouldContain: ["w:p", "w:r"],
|
||||
value: "<w:p></w:p>",
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
module.exports = {
|
||||
docx: DocXFileTypeConfig,
|
||||
pptx: PptXFileTypeConfig,
|
||||
};
|
||||
109
es6/inspect-module.js
Normal file
109
es6/inspect-module.js
Normal file
@ -0,0 +1,109 @@
|
||||
const { merge, cloneDeep } = require("lodash");
|
||||
|
||||
function isPlaceholder(part) {
|
||||
return part.type === "placeholder";
|
||||
}
|
||||
|
||||
function getTags(postParsed) {
|
||||
return postParsed.filter(isPlaceholder).reduce(function (tags, part) {
|
||||
tags[part.value] = tags[part.value] || {};
|
||||
if (part.subparsed) {
|
||||
tags[part.value] = merge(tags[part.value], getTags(part.subparsed));
|
||||
}
|
||||
return tags;
|
||||
}, {});
|
||||
}
|
||||
|
||||
function getStructuredTags(postParsed) {
|
||||
return postParsed.filter(isPlaceholder).map(function (part) {
|
||||
if (part.subparsed) {
|
||||
part.subparsed = getStructuredTags(part.subparsed);
|
||||
}
|
||||
return part;
|
||||
}, {});
|
||||
}
|
||||
|
||||
class InspectModule {
|
||||
constructor() {
|
||||
this.inspect = {};
|
||||
this.fullInspected = {};
|
||||
this.filePath = null;
|
||||
this.nullValues = [];
|
||||
}
|
||||
optionsTransformer(options, docxtemplater) {
|
||||
this.fileTypeConfig = docxtemplater.fileTypeConfig;
|
||||
this.zip = docxtemplater.zip;
|
||||
this.targets = docxtemplater.targets;
|
||||
this.templatedFiles = docxtemplater.getTemplatedFiles();
|
||||
this.fileType = docxtemplater.fileType;
|
||||
return options;
|
||||
}
|
||||
on(eventName) {
|
||||
if (eventName === "attached") {
|
||||
this.attached = false;
|
||||
this.inspect = {};
|
||||
this.fullInspected = {};
|
||||
this.filePath = null;
|
||||
this.nullValues = [];
|
||||
}
|
||||
}
|
||||
// eslint-disable-next-line complexity
|
||||
set(obj) {
|
||||
if (obj.data) {
|
||||
this.inspect.tags = obj.data;
|
||||
}
|
||||
if (obj.inspect) {
|
||||
if (obj.inspect.filePath) {
|
||||
this.filePath = obj.inspect.filePath;
|
||||
this.inspect = this.fullInspected[this.filePath] || {};
|
||||
} else if (obj.inspect.content) {
|
||||
this.inspect.content = obj.inspect.content;
|
||||
} else if (obj.inspect.postparsed) {
|
||||
this.inspect.postparsed = cloneDeep(obj.inspect.postparsed);
|
||||
} else if (obj.inspect.parsed) {
|
||||
this.inspect.parsed = cloneDeep(obj.inspect.parsed);
|
||||
} else if (obj.inspect.lexed) {
|
||||
this.inspect.lexed = cloneDeep(obj.inspect.lexed);
|
||||
} else if (obj.inspect.xmllexed) {
|
||||
this.inspect.xmllexed = cloneDeep(obj.inspect.xmllexed);
|
||||
} else if (obj.inspect.resolved) {
|
||||
this.inspect.resolved = obj.inspect.resolved;
|
||||
}
|
||||
this.fullInspected[this.filePath] = this.inspect;
|
||||
}
|
||||
}
|
||||
nullGetter(part, scopeManager, xt) {
|
||||
const inspected = this.fullInspected[xt.filePath];
|
||||
inspected.nullValues = inspected.nullValues || { summary: [], detail: [] };
|
||||
inspected.nullValues.detail.push({ part, scopeManager });
|
||||
inspected.nullValues.summary.push(
|
||||
scopeManager.scopePath.concat(part.value)
|
||||
);
|
||||
}
|
||||
getTags(file) {
|
||||
file = file || this.fileTypeConfig.textPath(this);
|
||||
return getTags(cloneDeep(this.fullInspected[file].postparsed));
|
||||
}
|
||||
getAllTags() {
|
||||
return Object.keys(this.fullInspected).reduce((result, file) => {
|
||||
return merge(result, this.getTags(file));
|
||||
}, {});
|
||||
}
|
||||
getStructuredTags(file) {
|
||||
file = file || this.fileTypeConfig.textPath(this);
|
||||
return getStructuredTags(cloneDeep(this.fullInspected[file].postparsed));
|
||||
}
|
||||
getAllStructuredTags() {
|
||||
return Object.keys(this.fullInspected).reduce((result, file) => {
|
||||
return result.concat(this.getStructuredTags(file));
|
||||
}, []);
|
||||
}
|
||||
getFileType() {
|
||||
return this.fileType;
|
||||
}
|
||||
getTemplatedFiles() {
|
||||
return this.templatedFiles;
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = () => new InspectModule();
|
||||
45
es6/join-uncorrupt.js
Normal file
45
es6/join-uncorrupt.js
Normal file
@ -0,0 +1,45 @@
|
||||
function joinUncorrupt(parts, contains) {
|
||||
// Before doing this "uncorruption" method here, this was done with the `part.emptyValue` trick, however, there were some corruptions that were not handled, for example with a template like this :
|
||||
//
|
||||
// ------------------------------------------------
|
||||
// | {-w:p falsy}My para{/falsy} | |
|
||||
// | {-w:p falsy}My para{/falsy} | |
|
||||
// ------------------------------------------------
|
||||
let collecting = "";
|
||||
let currentlyCollecting = -1;
|
||||
return parts.reduce(function (full, part) {
|
||||
for (let i = 0, len = contains.length; i < len; i++) {
|
||||
const { tag, shouldContain, value } = contains[i];
|
||||
const startTagRegex = new RegExp(`^(<(${tag})[^>]*>)$`, "g");
|
||||
if (currentlyCollecting === i) {
|
||||
if (part === `</${tag}>`) {
|
||||
currentlyCollecting = -1;
|
||||
return full + collecting + value + part;
|
||||
}
|
||||
collecting += part;
|
||||
for (let j = 0, len2 = shouldContain.length; j < len2; j++) {
|
||||
const sc = shouldContain[j];
|
||||
if (
|
||||
part.indexOf(`<${sc} `) !== -1 ||
|
||||
part.indexOf(`<${sc}>`) !== -1
|
||||
) {
|
||||
currentlyCollecting = -1;
|
||||
return full + collecting;
|
||||
}
|
||||
}
|
||||
return full;
|
||||
}
|
||||
if (currentlyCollecting === -1 && startTagRegex.test(part)) {
|
||||
if (part[part.length - 2] === "/") {
|
||||
return full;
|
||||
}
|
||||
currentlyCollecting = i;
|
||||
collecting = part;
|
||||
return full;
|
||||
}
|
||||
}
|
||||
return full + part;
|
||||
}, "");
|
||||
}
|
||||
|
||||
module.exports = joinUncorrupt;
|
||||
433
es6/lexer.js
Normal file
433
es6/lexer.js
Normal file
@ -0,0 +1,433 @@
|
||||
const {
|
||||
getUnclosedTagException,
|
||||
getUnopenedTagException,
|
||||
getDuplicateOpenTagException,
|
||||
getDuplicateCloseTagException,
|
||||
throwMalformedXml,
|
||||
throwXmlInvalid,
|
||||
} = require("./errors");
|
||||
const { concatArrays, isTextStart, isTextEnd } = require("./doc-utils");
|
||||
|
||||
const NONE = -2;
|
||||
const EQUAL = 0;
|
||||
const START = -1;
|
||||
const END = 1;
|
||||
|
||||
function inRange(range, match) {
|
||||
return range[0] <= match.offset && match.offset < range[1];
|
||||
}
|
||||
|
||||
function updateInTextTag(part, inTextTag) {
|
||||
if (isTextStart(part)) {
|
||||
if (inTextTag) {
|
||||
throwMalformedXml(part);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
if (isTextEnd(part)) {
|
||||
if (!inTextTag) {
|
||||
throwMalformedXml(part);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
return inTextTag;
|
||||
}
|
||||
|
||||
function getTag(tag) {
|
||||
let position = "";
|
||||
let start = 1;
|
||||
let end = tag.indexOf(" ");
|
||||
if (tag[tag.length - 2] === "/") {
|
||||
position = "selfclosing";
|
||||
if (end === -1) {
|
||||
end = tag.length - 2;
|
||||
}
|
||||
} else if (tag[1] === "/") {
|
||||
start = 2;
|
||||
position = "end";
|
||||
if (end === -1) {
|
||||
end = tag.length - 1;
|
||||
}
|
||||
} else {
|
||||
position = "start";
|
||||
if (end === -1) {
|
||||
end = tag.length - 1;
|
||||
}
|
||||
}
|
||||
return {
|
||||
tag: tag.slice(start, end),
|
||||
position,
|
||||
};
|
||||
}
|
||||
|
||||
function tagMatcher(content, textMatchArray, othersMatchArray) {
|
||||
let cursor = 0;
|
||||
const contentLength = content.length;
|
||||
const allMatches = concatArrays([
|
||||
textMatchArray.map(function (tag) {
|
||||
return { tag, text: true };
|
||||
}),
|
||||
othersMatchArray.map(function (tag) {
|
||||
return { tag, text: false };
|
||||
}),
|
||||
]).reduce(function (allMatches, t) {
|
||||
allMatches[t.tag] = t.text;
|
||||
return allMatches;
|
||||
}, {});
|
||||
const totalMatches = [];
|
||||
|
||||
while (cursor < contentLength) {
|
||||
cursor = content.indexOf("<", cursor);
|
||||
if (cursor === -1) {
|
||||
break;
|
||||
}
|
||||
const offset = cursor;
|
||||
const nextOpening = content.indexOf("<", cursor + 1);
|
||||
cursor = content.indexOf(">", cursor);
|
||||
if (cursor === -1 || (nextOpening !== -1 && cursor > nextOpening)) {
|
||||
throwXmlInvalid(content, offset);
|
||||
}
|
||||
const tagText = content.slice(offset, cursor + 1);
|
||||
const { tag, position } = getTag(tagText);
|
||||
const text = allMatches[tag];
|
||||
if (text == null) {
|
||||
continue;
|
||||
}
|
||||
totalMatches.push({
|
||||
type: "tag",
|
||||
position,
|
||||
text,
|
||||
offset,
|
||||
value: tagText,
|
||||
tag,
|
||||
});
|
||||
}
|
||||
|
||||
return totalMatches;
|
||||
}
|
||||
|
||||
function getDelimiterErrors(delimiterMatches, fullText, ranges) {
|
||||
if (delimiterMatches.length === 0) {
|
||||
return [];
|
||||
}
|
||||
const errors = [];
|
||||
let inDelimiter = false;
|
||||
let lastDelimiterMatch = { offset: 0 };
|
||||
let xtag;
|
||||
let rangeIndex = 0;
|
||||
delimiterMatches.forEach(function (delimiterMatch) {
|
||||
while (ranges[rangeIndex + 1]) {
|
||||
if (ranges[rangeIndex + 1].offset > delimiterMatch.offset) {
|
||||
break;
|
||||
}
|
||||
rangeIndex++;
|
||||
}
|
||||
xtag = fullText.substr(
|
||||
lastDelimiterMatch.offset,
|
||||
delimiterMatch.offset - lastDelimiterMatch.offset
|
||||
);
|
||||
if (
|
||||
(delimiterMatch.position === "start" && inDelimiter) ||
|
||||
(delimiterMatch.position === "end" && !inDelimiter)
|
||||
) {
|
||||
if (delimiterMatch.position === "start") {
|
||||
if (
|
||||
lastDelimiterMatch.offset + lastDelimiterMatch.length ===
|
||||
delimiterMatch.offset
|
||||
) {
|
||||
xtag = fullText.substr(
|
||||
lastDelimiterMatch.offset,
|
||||
delimiterMatch.offset -
|
||||
lastDelimiterMatch.offset +
|
||||
lastDelimiterMatch.length +
|
||||
4
|
||||
);
|
||||
errors.push(
|
||||
getDuplicateOpenTagException({
|
||||
xtag,
|
||||
offset: lastDelimiterMatch.offset,
|
||||
})
|
||||
);
|
||||
} else {
|
||||
errors.push(
|
||||
getUnclosedTagException({ xtag, offset: lastDelimiterMatch.offset })
|
||||
);
|
||||
}
|
||||
delimiterMatch.error = true;
|
||||
} else {
|
||||
if (
|
||||
lastDelimiterMatch.offset + lastDelimiterMatch.length ===
|
||||
delimiterMatch.offset
|
||||
) {
|
||||
xtag = fullText.substr(
|
||||
lastDelimiterMatch.offset - 4,
|
||||
delimiterMatch.offset -
|
||||
lastDelimiterMatch.offset +
|
||||
4 +
|
||||
lastDelimiterMatch.length
|
||||
);
|
||||
errors.push(
|
||||
getDuplicateCloseTagException({
|
||||
xtag,
|
||||
offset: lastDelimiterMatch.offset,
|
||||
})
|
||||
);
|
||||
} else {
|
||||
errors.push(
|
||||
getUnopenedTagException({ xtag, offset: delimiterMatch.offset })
|
||||
);
|
||||
}
|
||||
delimiterMatch.error = true;
|
||||
}
|
||||
} else {
|
||||
inDelimiter = !inDelimiter;
|
||||
}
|
||||
lastDelimiterMatch = delimiterMatch;
|
||||
});
|
||||
const delimiterMatch = { offset: fullText.length };
|
||||
xtag = fullText.substr(
|
||||
lastDelimiterMatch.offset,
|
||||
delimiterMatch.offset - lastDelimiterMatch.offset
|
||||
);
|
||||
if (inDelimiter) {
|
||||
errors.push(
|
||||
getUnclosedTagException({ xtag, offset: lastDelimiterMatch.offset })
|
||||
);
|
||||
delimiterMatch.error = true;
|
||||
}
|
||||
return errors;
|
||||
}
|
||||
|
||||
function compareOffsets(startOffset, endOffset) {
|
||||
if (startOffset === -1 && endOffset === -1) {
|
||||
return NONE;
|
||||
}
|
||||
if (startOffset === endOffset) {
|
||||
return EQUAL;
|
||||
}
|
||||
if (startOffset === -1 || endOffset === -1) {
|
||||
return endOffset < startOffset ? START : END;
|
||||
}
|
||||
return startOffset < endOffset ? START : END;
|
||||
}
|
||||
|
||||
function splitDelimiters(inside) {
|
||||
const newDelimiters = inside.split(" ");
|
||||
if (newDelimiters.length !== 2) {
|
||||
throw new Error("New Delimiters cannot be parsed");
|
||||
}
|
||||
const [start, end] = newDelimiters;
|
||||
if (start.length === 0 || end.length === 0) {
|
||||
throw new Error("New Delimiters cannot be parsed");
|
||||
}
|
||||
return [start, end];
|
||||
}
|
||||
|
||||
function getAllIndexes(fullText, delimiters) {
|
||||
const indexes = [];
|
||||
let { start, end } = delimiters;
|
||||
let offset = -1;
|
||||
let insideTag = false;
|
||||
while (true) {
|
||||
const startOffset = fullText.indexOf(start, offset + 1);
|
||||
const endOffset = fullText.indexOf(end, offset + 1);
|
||||
let position = null;
|
||||
let len;
|
||||
let compareResult = compareOffsets(startOffset, endOffset);
|
||||
if (compareResult === NONE) {
|
||||
return indexes;
|
||||
}
|
||||
if (compareResult === EQUAL) {
|
||||
if (!insideTag) {
|
||||
compareResult = START;
|
||||
} else {
|
||||
compareResult = END;
|
||||
}
|
||||
}
|
||||
if (compareResult === END) {
|
||||
insideTag = false;
|
||||
offset = endOffset;
|
||||
position = "end";
|
||||
len = end.length;
|
||||
}
|
||||
if (compareResult === START) {
|
||||
insideTag = true;
|
||||
offset = startOffset;
|
||||
position = "start";
|
||||
len = start.length;
|
||||
}
|
||||
if (position === "start" && fullText[offset + start.length] === "=") {
|
||||
indexes.push({
|
||||
offset: startOffset,
|
||||
position: "start",
|
||||
length: start.length,
|
||||
changedelimiter: true,
|
||||
});
|
||||
const nextEqual = fullText.indexOf("=", offset + start.length + 1);
|
||||
const endOffset = fullText.indexOf(end, nextEqual + 1);
|
||||
|
||||
indexes.push({
|
||||
offset: endOffset,
|
||||
position: "end",
|
||||
length: end.length,
|
||||
changedelimiter: true,
|
||||
});
|
||||
const insideTag = fullText.substr(
|
||||
offset + start.length + 1,
|
||||
nextEqual - offset - start.length - 1
|
||||
);
|
||||
[start, end] = splitDelimiters(insideTag);
|
||||
offset = endOffset;
|
||||
continue;
|
||||
}
|
||||
indexes.push({ offset, position, length: len });
|
||||
}
|
||||
}
|
||||
|
||||
function parseDelimiters(innerContentParts, delimiters) {
|
||||
const full = innerContentParts.map((p) => p.value).join("");
|
||||
const delimiterMatches = getAllIndexes(full, delimiters);
|
||||
|
||||
let offset = 0;
|
||||
const ranges = innerContentParts.map(function (part) {
|
||||
offset += part.value.length;
|
||||
return { offset: offset - part.value.length, lIndex: part.lIndex };
|
||||
});
|
||||
|
||||
const errors = getDelimiterErrors(delimiterMatches, full, ranges);
|
||||
let cutNext = 0;
|
||||
let delimiterIndex = 0;
|
||||
|
||||
const parsed = ranges.map(function (p, i) {
|
||||
const { offset } = p;
|
||||
const range = [offset, offset + innerContentParts[i].value.length];
|
||||
const partContent = innerContentParts[i].value;
|
||||
const delimitersInOffset = [];
|
||||
while (
|
||||
delimiterIndex < delimiterMatches.length &&
|
||||
inRange(range, delimiterMatches[delimiterIndex])
|
||||
) {
|
||||
delimitersInOffset.push(delimiterMatches[delimiterIndex]);
|
||||
delimiterIndex++;
|
||||
}
|
||||
const parts = [];
|
||||
let cursor = 0;
|
||||
if (cutNext > 0) {
|
||||
cursor = cutNext;
|
||||
cutNext = 0;
|
||||
}
|
||||
let insideDelimiterChange;
|
||||
delimitersInOffset.forEach(function (delimiterInOffset) {
|
||||
const value = partContent.substr(
|
||||
cursor,
|
||||
delimiterInOffset.offset - offset - cursor
|
||||
);
|
||||
if (value.length > 0) {
|
||||
if (insideDelimiterChange) {
|
||||
if (delimiterInOffset.changedelimiter) {
|
||||
cursor =
|
||||
delimiterInOffset.offset - offset + delimiterInOffset.length;
|
||||
insideDelimiterChange = delimiterInOffset.position === "start";
|
||||
}
|
||||
return;
|
||||
}
|
||||
parts.push({ type: "content", value, offset: cursor + offset });
|
||||
cursor += value.length;
|
||||
}
|
||||
const delimiterPart = {
|
||||
type: "delimiter",
|
||||
position: delimiterInOffset.position,
|
||||
offset: cursor + offset,
|
||||
};
|
||||
if (delimiterInOffset.error) {
|
||||
delimiterPart.error = delimiterInOffset.error;
|
||||
}
|
||||
if (delimiterInOffset.changedelimiter) {
|
||||
insideDelimiterChange = delimiterInOffset.position === "start";
|
||||
cursor = delimiterInOffset.offset - offset + delimiterInOffset.length;
|
||||
return;
|
||||
}
|
||||
parts.push(delimiterPart);
|
||||
cursor = delimiterInOffset.offset - offset + delimiterInOffset.length;
|
||||
});
|
||||
cutNext = cursor - partContent.length;
|
||||
const value = partContent.substr(cursor);
|
||||
if (value.length > 0) {
|
||||
parts.push({ type: "content", value, offset });
|
||||
}
|
||||
return parts;
|
||||
}, this);
|
||||
return { parsed, errors };
|
||||
}
|
||||
|
||||
function getContentParts(xmlparsed) {
|
||||
let inTextTag = false;
|
||||
const innerContentParts = [];
|
||||
xmlparsed.forEach(function (part) {
|
||||
inTextTag = updateInTextTag(part, inTextTag);
|
||||
if (inTextTag && part.type === "content") {
|
||||
innerContentParts.push(part);
|
||||
}
|
||||
});
|
||||
return innerContentParts;
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
parseDelimiters,
|
||||
parse(xmlparsed, delimiters) {
|
||||
let inTextTag = false;
|
||||
const { parsed: delimiterParsed, errors } = parseDelimiters(
|
||||
getContentParts(xmlparsed),
|
||||
delimiters
|
||||
);
|
||||
|
||||
let lexed = [];
|
||||
let index = 0;
|
||||
xmlparsed.forEach(function (part) {
|
||||
inTextTag = updateInTextTag(part, inTextTag);
|
||||
if (part.type === "content") {
|
||||
part.position = inTextTag ? "insidetag" : "outsidetag";
|
||||
}
|
||||
if (inTextTag && part.type === "content") {
|
||||
Array.prototype.push.apply(
|
||||
lexed,
|
||||
delimiterParsed[index].map(function (p) {
|
||||
if (p.type === "content") {
|
||||
p.position = "insidetag";
|
||||
}
|
||||
return p;
|
||||
})
|
||||
);
|
||||
index++;
|
||||
} else {
|
||||
lexed.push(part);
|
||||
}
|
||||
});
|
||||
lexed = lexed.map(function (p, i) {
|
||||
p.lIndex = i;
|
||||
return p;
|
||||
});
|
||||
return { errors, lexed };
|
||||
},
|
||||
xmlparse(content, xmltags) {
|
||||
const matches = tagMatcher(content, xmltags.text, xmltags.other);
|
||||
let cursor = 0;
|
||||
const parsed = matches.reduce(function (parsed, match) {
|
||||
const value = content.substr(cursor, match.offset - cursor);
|
||||
if (value.length > 0) {
|
||||
parsed.push({ type: "content", value });
|
||||
}
|
||||
cursor = match.offset + match.value.length;
|
||||
delete match.offset;
|
||||
if (match.value.length > 0) {
|
||||
parsed.push(match);
|
||||
}
|
||||
return parsed;
|
||||
}, []);
|
||||
const value = content.substr(cursor);
|
||||
if (value.length > 0) {
|
||||
parsed.push({ type: "content", value });
|
||||
}
|
||||
return parsed;
|
||||
},
|
||||
};
|
||||
44
es6/mergesort.js
Normal file
44
es6/mergesort.js
Normal file
@ -0,0 +1,44 @@
|
||||
function getMinFromArrays(arrays, state) {
|
||||
let minIndex = -1;
|
||||
for (let i = 0, l = arrays.length; i < l; i++) {
|
||||
if (state[i] >= arrays[i].length) {
|
||||
continue;
|
||||
}
|
||||
if (
|
||||
minIndex === -1 ||
|
||||
arrays[i][state[i]].offset < arrays[minIndex][state[minIndex]].offset
|
||||
) {
|
||||
minIndex = i;
|
||||
}
|
||||
}
|
||||
if (minIndex === -1) {
|
||||
throw new Error("minIndex negative");
|
||||
}
|
||||
return minIndex;
|
||||
}
|
||||
|
||||
module.exports = function (arrays) {
|
||||
const totalLength = arrays.reduce(function (sum, array) {
|
||||
return sum + array.length;
|
||||
}, 0);
|
||||
arrays = arrays.filter(function (array) {
|
||||
return array.length > 0;
|
||||
});
|
||||
|
||||
const resultArray = new Array(totalLength);
|
||||
|
||||
const state = arrays.map(function () {
|
||||
return 0;
|
||||
});
|
||||
|
||||
let i = 0;
|
||||
|
||||
while (i <= totalLength - 1) {
|
||||
const arrayIndex = getMinFromArrays(arrays, state);
|
||||
resultArray[i] = arrays[arrayIndex][state[arrayIndex]];
|
||||
state[arrayIndex]++;
|
||||
i++;
|
||||
}
|
||||
|
||||
return resultArray;
|
||||
};
|
||||
35
es6/module-wrapper.js
Normal file
35
es6/module-wrapper.js
Normal file
@ -0,0 +1,35 @@
|
||||
function emptyFun() {}
|
||||
function identity(i) {
|
||||
return i;
|
||||
}
|
||||
module.exports = function (module) {
|
||||
const defaults = {
|
||||
set: emptyFun,
|
||||
parse: emptyFun,
|
||||
render: emptyFun,
|
||||
getTraits: emptyFun,
|
||||
getFileType: emptyFun,
|
||||
nullGetter: emptyFun,
|
||||
optionsTransformer: identity,
|
||||
postrender: identity,
|
||||
errorsTransformer: identity,
|
||||
getRenderedMap: identity,
|
||||
preparse: identity,
|
||||
postparse: identity,
|
||||
on: emptyFun,
|
||||
resolve: emptyFun,
|
||||
};
|
||||
if (
|
||||
Object.keys(defaults).every(function (key) {
|
||||
return !module[key];
|
||||
})
|
||||
) {
|
||||
throw new Error(
|
||||
"This module cannot be wrapped, because it doesn't define any of the necessary functions"
|
||||
);
|
||||
}
|
||||
Object.keys(defaults).forEach(function (key) {
|
||||
module[key] = module[key] || defaults[key];
|
||||
});
|
||||
return module;
|
||||
};
|
||||
47
es6/modules/common.js
Normal file
47
es6/modules/common.js
Normal file
@ -0,0 +1,47 @@
|
||||
const wrapper = require("../module-wrapper");
|
||||
const { concatArrays } = require("../doc-utils");
|
||||
const docxContentType =
|
||||
"application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml";
|
||||
const docxmContentType =
|
||||
"application/vnd.ms-word.document.macroEnabled.main+xml";
|
||||
const pptxContentType =
|
||||
"application/vnd.openxmlformats-officedocument.presentationml.slide+xml";
|
||||
const dotxContentType =
|
||||
"application/vnd.openxmlformats-officedocument.wordprocessingml.template.main+xml";
|
||||
const dotmContentType =
|
||||
"application/vnd.ms-word.template.macroEnabledTemplate.main+xml";
|
||||
|
||||
const filetypes = {
|
||||
docx: [docxContentType, docxmContentType, dotxContentType, dotmContentType],
|
||||
pptx: [pptxContentType],
|
||||
};
|
||||
|
||||
class Common {
|
||||
constructor() {
|
||||
this.name = "Common";
|
||||
}
|
||||
set({ invertedContentTypes }) {
|
||||
if (invertedContentTypes) {
|
||||
this.invertedContentTypes = invertedContentTypes;
|
||||
}
|
||||
}
|
||||
getFileType({ doc }) {
|
||||
const invertedContentTypes = this.invertedContentTypes;
|
||||
if (!this.invertedContentTypes) {
|
||||
return;
|
||||
}
|
||||
const keys = Object.keys(filetypes);
|
||||
for (let i = 0, len = keys.length; i < len; i++) {
|
||||
const ftCandidate = keys[i];
|
||||
const contentTypes = filetypes[ftCandidate];
|
||||
for (let j = 0, len2 = contentTypes.length; j < len2; j++) {
|
||||
const ct = contentTypes[j];
|
||||
if (invertedContentTypes[ct]) {
|
||||
doc.targets = concatArrays([doc.targets, invertedContentTypes[ct]]);
|
||||
return ftCandidate;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
module.exports = () => wrapper(new Common());
|
||||
139
es6/modules/expand-pair-trait.js
Normal file
139
es6/modules/expand-pair-trait.js
Normal file
@ -0,0 +1,139 @@
|
||||
const traitName = "expandPair";
|
||||
const mergeSort = require("../mergesort");
|
||||
const { getLeft, getRight } = require("../doc-utils");
|
||||
|
||||
const wrapper = require("../module-wrapper");
|
||||
const { getExpandToDefault } = require("../traits");
|
||||
const {
|
||||
getUnmatchedLoopException,
|
||||
getClosingTagNotMatchOpeningTag,
|
||||
throwLocationInvalid,
|
||||
} = require("../errors");
|
||||
|
||||
function getOpenCountChange(part) {
|
||||
switch (part.location) {
|
||||
case "start":
|
||||
return 1;
|
||||
case "end":
|
||||
return -1;
|
||||
default:
|
||||
throwLocationInvalid(part);
|
||||
}
|
||||
}
|
||||
|
||||
function getPairs(traits) {
|
||||
const errors = [];
|
||||
let pairs = [];
|
||||
if (traits.length === 0) {
|
||||
return { pairs, errors };
|
||||
}
|
||||
let countOpen = 1;
|
||||
const [firstTrait] = traits;
|
||||
if (firstTrait.part.location === "start") {
|
||||
for (let i = 1; i < traits.length; i++) {
|
||||
const currentTrait = traits[i];
|
||||
countOpen += getOpenCountChange(currentTrait.part);
|
||||
if (countOpen === 0) {
|
||||
const outer = getPairs(traits.slice(i + 1));
|
||||
if (
|
||||
currentTrait.part.value !== firstTrait.part.value &&
|
||||
currentTrait.part.value !== ""
|
||||
) {
|
||||
errors.push(
|
||||
getClosingTagNotMatchOpeningTag({
|
||||
tags: [firstTrait.part, currentTrait.part],
|
||||
})
|
||||
);
|
||||
} else {
|
||||
pairs = [[firstTrait, currentTrait]];
|
||||
}
|
||||
return {
|
||||
pairs: pairs.concat(outer.pairs),
|
||||
errors: errors.concat(outer.errors),
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
const { part } = firstTrait;
|
||||
errors.push(getUnmatchedLoopException({ part, location: part.location }));
|
||||
const outer = getPairs(traits.slice(1));
|
||||
return { pairs: outer.pairs, errors: errors.concat(outer.errors) };
|
||||
}
|
||||
|
||||
const expandPairTrait = {
|
||||
name: "ExpandPairTrait",
|
||||
optionsTransformer(options, docxtemplater) {
|
||||
this.expandTags = docxtemplater.fileTypeConfig.expandTags.concat(
|
||||
docxtemplater.options.paragraphLoop
|
||||
? docxtemplater.fileTypeConfig.onParagraphLoop
|
||||
: []
|
||||
);
|
||||
return options;
|
||||
},
|
||||
postparse(postparsed, { getTraits, postparse }) {
|
||||
let traits = getTraits(traitName, postparsed);
|
||||
traits = traits.map(function (trait) {
|
||||
return trait || [];
|
||||
});
|
||||
traits = mergeSort(traits);
|
||||
const { pairs, errors } = getPairs(traits);
|
||||
const expandedPairs = pairs.map((pair) => {
|
||||
let { expandTo } = pair[0].part;
|
||||
if (expandTo === "auto") {
|
||||
const result = getExpandToDefault(postparsed, pair, this.expandTags);
|
||||
if (result.error) {
|
||||
errors.push(result.error);
|
||||
}
|
||||
expandTo = result.value;
|
||||
}
|
||||
if (!expandTo) {
|
||||
return [pair[0].offset, pair[1].offset];
|
||||
}
|
||||
let left, right;
|
||||
try {
|
||||
left = getLeft(postparsed, expandTo, pair[0].offset);
|
||||
} catch (e) {
|
||||
errors.push(e);
|
||||
}
|
||||
try {
|
||||
right = getRight(postparsed, expandTo, pair[1].offset);
|
||||
} catch (e) {
|
||||
errors.push(e);
|
||||
}
|
||||
return [left, right];
|
||||
});
|
||||
|
||||
let currentPairIndex = 0;
|
||||
let innerParts;
|
||||
|
||||
const newParsed = postparsed.reduce(function (newParsed, part, i) {
|
||||
const inPair =
|
||||
currentPairIndex < pairs.length &&
|
||||
expandedPairs[currentPairIndex][0] <= i;
|
||||
const pair = pairs[currentPairIndex];
|
||||
const expandedPair = expandedPairs[currentPairIndex];
|
||||
if (!inPair) {
|
||||
newParsed.push(part);
|
||||
return newParsed;
|
||||
}
|
||||
if (expandedPair[0] === i) {
|
||||
innerParts = [];
|
||||
}
|
||||
if (pair[0].offset !== i && pair[1].offset !== i) {
|
||||
innerParts.push(part);
|
||||
}
|
||||
if (expandedPair[1] === i) {
|
||||
const basePart = postparsed[pair[0].offset];
|
||||
basePart.subparsed = postparse(innerParts, { basePart });
|
||||
delete basePart.location;
|
||||
delete basePart.expandTo;
|
||||
newParsed.push(basePart);
|
||||
currentPairIndex++;
|
||||
}
|
||||
return newParsed;
|
||||
}, []);
|
||||
return { postparsed: newParsed, errors };
|
||||
},
|
||||
};
|
||||
|
||||
module.exports = () => wrapper(expandPairTrait);
|
||||
353
es6/modules/loop.js
Normal file
353
es6/modules/loop.js
Normal file
@ -0,0 +1,353 @@
|
||||
const {
|
||||
mergeObjects,
|
||||
chunkBy,
|
||||
last,
|
||||
isParagraphStart,
|
||||
isParagraphEnd,
|
||||
isContent,
|
||||
startsWith,
|
||||
} = require("../doc-utils");
|
||||
const wrapper = require("../module-wrapper");
|
||||
|
||||
const moduleName = "loop";
|
||||
|
||||
function hasContent(parts) {
|
||||
return parts.some(function (part) {
|
||||
return isContent(part);
|
||||
});
|
||||
}
|
||||
|
||||
function getFirstMeaningFulPart(parsed) {
|
||||
for (let i = 0, len = parsed.length; i < len; i++) {
|
||||
if (parsed[i].type !== "content") {
|
||||
return parsed[i];
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function isInsideParagraphLoop(part) {
|
||||
const firstMeaningfulPart = getFirstMeaningFulPart(part.subparsed);
|
||||
return firstMeaningfulPart != null && firstMeaningfulPart.tag !== "w:t";
|
||||
}
|
||||
|
||||
function getPageBreakIfApplies(part) {
|
||||
if (part.hasPageBreak) {
|
||||
if (isInsideParagraphLoop(part)) {
|
||||
return '<w:p><w:r><w:br w:type="page"/></w:r></w:p>';
|
||||
}
|
||||
}
|
||||
return "";
|
||||
}
|
||||
|
||||
function isEnclosedByParagraphs(parsed) {
|
||||
if (parsed.length === 0) {
|
||||
return false;
|
||||
}
|
||||
return isParagraphStart(parsed[0]) && isParagraphEnd(last(parsed));
|
||||
}
|
||||
|
||||
function getOffset(chunk) {
|
||||
return hasContent(chunk) ? 0 : chunk.length;
|
||||
}
|
||||
|
||||
function addPageBreakAtEnd(subRendered) {
|
||||
let found = false;
|
||||
let i = subRendered.parts.length - 1;
|
||||
for (let j = subRendered.parts.length - 1; i >= 0; i--) {
|
||||
const p = subRendered.parts[j];
|
||||
if (p === "</w:p>" && !found) {
|
||||
found = true;
|
||||
subRendered.parts.splice(j, 0, '<w:r><w:br w:type="page"/></w:r>');
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (!found) {
|
||||
subRendered.parts.push('<w:p><w:r><w:br w:type="page"/></w:r></w:p>');
|
||||
}
|
||||
}
|
||||
|
||||
function addPageBreakAtBeginning(subRendered) {
|
||||
subRendered.parts.unshift('<w:p><w:r><w:br w:type="page"/></w:r></w:p>');
|
||||
}
|
||||
|
||||
function dropHeaderFooterRefs(parts) {
|
||||
return parts.filter(function (text) {
|
||||
if (
|
||||
startsWith(text, "<w:headerReference") ||
|
||||
startsWith(text, "<w:footerReference")
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
});
|
||||
}
|
||||
|
||||
function hasPageBreak(chunk) {
|
||||
return chunk.some(function (part) {
|
||||
if (part.tag === "w:br" && part.value.indexOf('w:type="page"') !== -1) {
|
||||
return true;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function getSectPrHeaderFooterChangeCount(chunks) {
|
||||
let collectSectPr = false;
|
||||
let sectPrCount = 0;
|
||||
chunks.forEach(function (part) {
|
||||
if (part.tag === "w:sectPr" && part.position === "start") {
|
||||
collectSectPr = true;
|
||||
}
|
||||
if (collectSectPr) {
|
||||
if (
|
||||
part.tag === "w:headerReference" ||
|
||||
part.tag === "w:footerReference"
|
||||
) {
|
||||
sectPrCount++;
|
||||
collectSectPr = false;
|
||||
}
|
||||
}
|
||||
if (part.tag === "w:sectPr" && part.position === "end") {
|
||||
collectSectPr = false;
|
||||
}
|
||||
});
|
||||
return sectPrCount;
|
||||
}
|
||||
|
||||
class LoopModule {
|
||||
constructor() {
|
||||
this.name = "LoopModule";
|
||||
this.prefix = {
|
||||
start: "#",
|
||||
end: "/",
|
||||
dash: /^-([^\s]+)\s(.+)$/,
|
||||
inverted: "^",
|
||||
};
|
||||
}
|
||||
parse(placeHolderContent, { match, getValue, getValues }) {
|
||||
const module = moduleName;
|
||||
const type = "placeholder";
|
||||
const { start, inverted, dash, end } = this.prefix;
|
||||
if (match(start, placeHolderContent)) {
|
||||
return {
|
||||
type,
|
||||
value: getValue(start, placeHolderContent),
|
||||
expandTo: "auto",
|
||||
module,
|
||||
location: "start",
|
||||
inverted: false,
|
||||
};
|
||||
}
|
||||
if (match(inverted, placeHolderContent)) {
|
||||
return {
|
||||
type,
|
||||
value: getValue(inverted, placeHolderContent),
|
||||
expandTo: "auto",
|
||||
module,
|
||||
location: "start",
|
||||
inverted: true,
|
||||
};
|
||||
}
|
||||
if (match(end, placeHolderContent)) {
|
||||
return {
|
||||
type,
|
||||
value: getValue(end, placeHolderContent),
|
||||
module,
|
||||
location: "end",
|
||||
};
|
||||
}
|
||||
if (match(dash, placeHolderContent)) {
|
||||
const [, expandTo, value] = getValues(dash, placeHolderContent);
|
||||
return {
|
||||
type,
|
||||
value,
|
||||
expandTo,
|
||||
module,
|
||||
location: "start",
|
||||
inverted: false,
|
||||
};
|
||||
}
|
||||
return null;
|
||||
}
|
||||
getTraits(traitName, parsed) {
|
||||
if (traitName !== "expandPair") {
|
||||
return;
|
||||
}
|
||||
|
||||
return parsed.reduce(function (tags, part, offset) {
|
||||
if (
|
||||
part.type === "placeholder" &&
|
||||
part.module === moduleName &&
|
||||
part.subparsed == null
|
||||
) {
|
||||
tags.push({ part, offset });
|
||||
}
|
||||
return tags;
|
||||
}, []);
|
||||
}
|
||||
postparse(parsed, { basePart }) {
|
||||
if (basePart) {
|
||||
basePart.sectPrCount = getSectPrHeaderFooterChangeCount(parsed);
|
||||
}
|
||||
if (
|
||||
!basePart ||
|
||||
basePart.expandTo !== "auto" ||
|
||||
basePart.module !== moduleName ||
|
||||
!isEnclosedByParagraphs(parsed)
|
||||
) {
|
||||
return parsed;
|
||||
}
|
||||
|
||||
let level = 0;
|
||||
const chunks = chunkBy(parsed, function (p) {
|
||||
if (isParagraphStart(p)) {
|
||||
level++;
|
||||
if (level === 1) {
|
||||
return "start";
|
||||
}
|
||||
}
|
||||
if (isParagraphEnd(p)) {
|
||||
level--;
|
||||
if (level === 0) {
|
||||
return "end";
|
||||
}
|
||||
}
|
||||
return null;
|
||||
});
|
||||
if (chunks.length <= 2) {
|
||||
return parsed;
|
||||
}
|
||||
const firstChunk = chunks[0];
|
||||
const lastChunk = last(chunks);
|
||||
const firstOffset = getOffset(firstChunk);
|
||||
const lastOffset = getOffset(lastChunk);
|
||||
|
||||
basePart.hasPageBreak = hasPageBreak(lastChunk);
|
||||
basePart.hasPageBreakBeginning = hasPageBreak(firstChunk);
|
||||
|
||||
if (firstOffset === 0 || lastOffset === 0) {
|
||||
return parsed;
|
||||
}
|
||||
return parsed.slice(firstOffset, parsed.length - lastOffset);
|
||||
}
|
||||
render(part, options) {
|
||||
if (part.type !== "placeholder" || part.module !== moduleName) {
|
||||
return null;
|
||||
}
|
||||
let totalValue = [];
|
||||
let errors = [];
|
||||
function loopOver(scope, i, length) {
|
||||
const scopeManager = options.scopeManager.createSubScopeManager(
|
||||
scope,
|
||||
part.value,
|
||||
i,
|
||||
part,
|
||||
length
|
||||
);
|
||||
const subRendered = options.render(
|
||||
mergeObjects({}, options, {
|
||||
compiled: part.subparsed,
|
||||
tags: {},
|
||||
scopeManager,
|
||||
})
|
||||
);
|
||||
if (
|
||||
part.hasPageBreak &&
|
||||
i === length - 1 &&
|
||||
isInsideParagraphLoop(part)
|
||||
) {
|
||||
addPageBreakAtEnd(subRendered);
|
||||
}
|
||||
if (part.sectPrCount === 1) {
|
||||
if (
|
||||
i !== 0 ||
|
||||
scopeManager.scopePathItem.some(function (i) {
|
||||
return i !== 0;
|
||||
})
|
||||
) {
|
||||
subRendered.parts = dropHeaderFooterRefs(subRendered.parts);
|
||||
}
|
||||
}
|
||||
if (part.hasPageBreakBeginning && isInsideParagraphLoop(part)) {
|
||||
addPageBreakAtBeginning(subRendered);
|
||||
}
|
||||
totalValue = totalValue.concat(subRendered.parts);
|
||||
errors = errors.concat(subRendered.errors || []);
|
||||
}
|
||||
let result;
|
||||
try {
|
||||
result = options.scopeManager.loopOver(
|
||||
part.value,
|
||||
loopOver,
|
||||
part.inverted,
|
||||
{
|
||||
part,
|
||||
}
|
||||
);
|
||||
} catch (e) {
|
||||
errors.push(e);
|
||||
return { errors };
|
||||
}
|
||||
// if the loop is showing empty content
|
||||
if (result === false) {
|
||||
return {
|
||||
value: getPageBreakIfApplies(part) || "",
|
||||
errors,
|
||||
};
|
||||
}
|
||||
const contains = options.fileTypeConfig.tagShouldContain || [];
|
||||
|
||||
return { value: options.joinUncorrupt(totalValue, contains), errors };
|
||||
}
|
||||
resolve(part, options) {
|
||||
if (part.type !== "placeholder" || part.module !== moduleName) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const sm = options.scopeManager;
|
||||
const promisedValue = sm.getValueAsync(part.value, { part });
|
||||
const promises = [];
|
||||
function loopOver(scope, i, length) {
|
||||
const scopeManager = sm.createSubScopeManager(
|
||||
scope,
|
||||
part.value,
|
||||
i,
|
||||
part,
|
||||
length
|
||||
);
|
||||
promises.push(
|
||||
options.resolve({
|
||||
filePath: options.filePath,
|
||||
modules: options.modules,
|
||||
baseNullGetter: options.baseNullGetter,
|
||||
resolve: options.resolve,
|
||||
compiled: part.subparsed,
|
||||
tags: {},
|
||||
scopeManager,
|
||||
})
|
||||
);
|
||||
}
|
||||
const errorList = [];
|
||||
return promisedValue.then(function (value) {
|
||||
sm.loopOverValue(value, loopOver, part.inverted);
|
||||
return Promise.all(promises)
|
||||
.then(function (r) {
|
||||
return r.map(function ({ resolved, errors }) {
|
||||
if (errors.length > 0) {
|
||||
errorList.push(...errors);
|
||||
}
|
||||
return resolved;
|
||||
});
|
||||
})
|
||||
.then(function (value) {
|
||||
if (errorList.length > 0) {
|
||||
throw errorList;
|
||||
}
|
||||
return value;
|
||||
});
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = () => wrapper(new LoopModule());
|
||||
89
es6/modules/rawxml.js
Normal file
89
es6/modules/rawxml.js
Normal file
@ -0,0 +1,89 @@
|
||||
const traits = require("../traits");
|
||||
const { isContent } = require("../doc-utils");
|
||||
const { throwRawTagShouldBeOnlyTextInParagraph } = require("../errors");
|
||||
|
||||
const moduleName = "rawxml";
|
||||
const wrapper = require("../module-wrapper");
|
||||
|
||||
function getInner({ part, left, right, postparsed, index }) {
|
||||
const paragraphParts = postparsed.slice(left + 1, right);
|
||||
paragraphParts.forEach(function (p, i) {
|
||||
if (i === index - left - 1) {
|
||||
return;
|
||||
}
|
||||
if (isContent(p)) {
|
||||
throwRawTagShouldBeOnlyTextInParagraph({ paragraphParts, part });
|
||||
}
|
||||
});
|
||||
return part;
|
||||
}
|
||||
|
||||
class RawXmlModule {
|
||||
constructor() {
|
||||
this.name = "RawXmlModule";
|
||||
this.prefix = "@";
|
||||
}
|
||||
optionsTransformer(options, docxtemplater) {
|
||||
this.fileTypeConfig = docxtemplater.fileTypeConfig;
|
||||
return options;
|
||||
}
|
||||
parse(placeHolderContent, { match, getValue }) {
|
||||
const type = "placeholder";
|
||||
if (match(this.prefix, placeHolderContent)) {
|
||||
return {
|
||||
type,
|
||||
value: getValue(this.prefix, placeHolderContent),
|
||||
module: moduleName,
|
||||
};
|
||||
}
|
||||
return null;
|
||||
}
|
||||
postparse(postparsed) {
|
||||
return traits.expandToOne(postparsed, {
|
||||
moduleName,
|
||||
getInner,
|
||||
expandTo: this.fileTypeConfig.tagRawXml,
|
||||
error: {
|
||||
message: "Raw tag not in paragraph",
|
||||
id: "raw_tag_outerxml_invalid",
|
||||
explanation: (part) =>
|
||||
`The tag "${part.value}" is not inside a paragraph, putting raw tags inside an inline loop is disallowed.`,
|
||||
},
|
||||
});
|
||||
}
|
||||
render(part, options) {
|
||||
if (part.module !== moduleName) {
|
||||
return null;
|
||||
}
|
||||
let value;
|
||||
const errors = [];
|
||||
try {
|
||||
value = options.scopeManager.getValue(part.value, { part });
|
||||
if (value == null) {
|
||||
value = options.nullGetter(part);
|
||||
}
|
||||
} catch (e) {
|
||||
errors.push(e);
|
||||
return { errors };
|
||||
}
|
||||
if (!value) {
|
||||
return { value: "" };
|
||||
}
|
||||
return { value };
|
||||
}
|
||||
resolve(part, options) {
|
||||
if (part.type !== "placeholder" || part.module !== moduleName) {
|
||||
return null;
|
||||
}
|
||||
return options.scopeManager
|
||||
.getValueAsync(part.value, { part })
|
||||
.then(function (value) {
|
||||
if (value == null) {
|
||||
return options.nullGetter(part);
|
||||
}
|
||||
return value;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = () => wrapper(new RawXmlModule());
|
||||
123
es6/modules/render.js
Normal file
123
es6/modules/render.js
Normal file
@ -0,0 +1,123 @@
|
||||
const wrapper = require("../module-wrapper");
|
||||
const { getScopeCompilationError } = require("../errors");
|
||||
const { utf8ToWord, hasCorruptCharacters } = require("../doc-utils");
|
||||
const { getCorruptCharactersException } = require("../errors");
|
||||
|
||||
const ftprefix = {
|
||||
docx: "w",
|
||||
pptx: "a",
|
||||
};
|
||||
|
||||
class Render {
|
||||
constructor() {
|
||||
this.name = "Render";
|
||||
this.recordRun = false;
|
||||
this.recordedRun = [];
|
||||
}
|
||||
set(obj) {
|
||||
if (obj.compiled) {
|
||||
this.compiled = obj.compiled;
|
||||
}
|
||||
if (obj.data != null) {
|
||||
this.data = obj.data;
|
||||
}
|
||||
}
|
||||
getRenderedMap(mapper) {
|
||||
return Object.keys(this.compiled).reduce((mapper, from) => {
|
||||
mapper[from] = { from, data: this.data };
|
||||
return mapper;
|
||||
}, mapper);
|
||||
}
|
||||
optionsTransformer(options, docxtemplater) {
|
||||
this.parser = docxtemplater.parser;
|
||||
this.fileType = docxtemplater.fileType;
|
||||
return options;
|
||||
}
|
||||
postparse(postparsed, options) {
|
||||
const errors = [];
|
||||
postparsed.forEach((p) => {
|
||||
if (p.type === "placeholder") {
|
||||
const tag = p.value;
|
||||
try {
|
||||
options.cachedParsers[p.lIndex] = this.parser(tag, { tag: p });
|
||||
} catch (rootError) {
|
||||
errors.push(
|
||||
getScopeCompilationError({ tag, rootError, offset: p.offset })
|
||||
);
|
||||
}
|
||||
}
|
||||
});
|
||||
return { postparsed, errors };
|
||||
}
|
||||
recordRuns(part) {
|
||||
if (part.tag === `${ftprefix[this.fileType]}:r`) {
|
||||
this.recordRun = false;
|
||||
this.recordedRun = [];
|
||||
} else if (part.tag === `${ftprefix[this.fileType]}:rPr`) {
|
||||
if (part.position === "start") {
|
||||
this.recordRun = true;
|
||||
this.recordedRun = [part.value];
|
||||
}
|
||||
if (part.position === "end") {
|
||||
this.recordedRun.push(part.value);
|
||||
this.recordRun = false;
|
||||
}
|
||||
} else if (this.recordRun) {
|
||||
this.recordedRun.push(part.value);
|
||||
}
|
||||
}
|
||||
render(part, { scopeManager, linebreaks, nullGetter }) {
|
||||
if (linebreaks) {
|
||||
this.recordRuns(part);
|
||||
}
|
||||
if (part.type !== "placeholder" || part.module) {
|
||||
return;
|
||||
}
|
||||
let value;
|
||||
try {
|
||||
value = scopeManager.getValue(part.value, { part });
|
||||
} catch (e) {
|
||||
return { errors: [e] };
|
||||
}
|
||||
if (value == null) {
|
||||
value = nullGetter(part);
|
||||
}
|
||||
if (hasCorruptCharacters(value)) {
|
||||
return {
|
||||
errors: [
|
||||
getCorruptCharactersException({
|
||||
tag: part.value,
|
||||
value,
|
||||
offset: part.offset,
|
||||
}),
|
||||
],
|
||||
};
|
||||
}
|
||||
if (typeof value !== "string") {
|
||||
value = value.toString();
|
||||
}
|
||||
if (linebreaks) {
|
||||
return this.renderLineBreaks(value);
|
||||
}
|
||||
return { value: utf8ToWord(value) };
|
||||
}
|
||||
renderLineBreaks(value) {
|
||||
const p = ftprefix[this.fileType];
|
||||
const br = this.fileType === "docx" ? "<w:r><w:br/></w:r>" : "<a:br/>";
|
||||
const lines = value.split("\n");
|
||||
const runprops = this.recordedRun.join("");
|
||||
return {
|
||||
value: lines
|
||||
.map(function (line) {
|
||||
return utf8ToWord(line);
|
||||
})
|
||||
.join(
|
||||
`</${p}:t></${p}:r>${br}<${p}:r>${runprops}<${p}:t${
|
||||
this.fileType === "docx" ? ' xml:space="preserve"' : ""
|
||||
}>`
|
||||
),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = () => wrapper(new Render());
|
||||
104
es6/modules/space-preserve.js
Normal file
104
es6/modules/space-preserve.js
Normal file
@ -0,0 +1,104 @@
|
||||
const wrapper = require("../module-wrapper");
|
||||
const {
|
||||
isTextStart,
|
||||
isTextEnd,
|
||||
endsWith,
|
||||
startsWith,
|
||||
} = require("../doc-utils");
|
||||
const wTpreserve = '<w:t xml:space="preserve">';
|
||||
const wTpreservelen = wTpreserve.length;
|
||||
const wtEnd = "</w:t>";
|
||||
const wtEndlen = wtEnd.length;
|
||||
|
||||
function isWtStart(part) {
|
||||
return isTextStart(part) && part.tag === "w:t";
|
||||
}
|
||||
|
||||
function addXMLPreserve(chunk, index) {
|
||||
const tag = chunk[index].value;
|
||||
if (chunk[index + 1].value === "</w:t>") {
|
||||
return tag;
|
||||
}
|
||||
if (tag.indexOf('xml:space="preserve"') !== -1) {
|
||||
return tag;
|
||||
}
|
||||
return tag.substr(0, tag.length - 1) + ' xml:space="preserve">';
|
||||
}
|
||||
|
||||
function isInsideLoop(meta, chunk) {
|
||||
return meta && meta.basePart && chunk.length > 1;
|
||||
}
|
||||
|
||||
const spacePreserve = {
|
||||
name: "SpacePreserveModule",
|
||||
postparse(postparsed, meta) {
|
||||
let chunk = [],
|
||||
inTextTag = false,
|
||||
endLindex = 0,
|
||||
lastTextTag = 0;
|
||||
function isStartingPlaceHolder(part, chunk) {
|
||||
return (
|
||||
!endLindex &&
|
||||
part.type === "placeholder" &&
|
||||
(!part.module || part.module === "loop") &&
|
||||
chunk.length > 1
|
||||
);
|
||||
}
|
||||
const result = postparsed.reduce(function (postparsed, part) {
|
||||
if (isWtStart(part)) {
|
||||
inTextTag = true;
|
||||
lastTextTag = chunk.length;
|
||||
}
|
||||
if (!inTextTag) {
|
||||
postparsed.push(part);
|
||||
return postparsed;
|
||||
}
|
||||
chunk.push(part);
|
||||
if (isInsideLoop(meta, chunk)) {
|
||||
endLindex = meta.basePart.endLindex;
|
||||
chunk[0].value = addXMLPreserve(chunk, 0);
|
||||
}
|
||||
if (isStartingPlaceHolder(part, chunk)) {
|
||||
endLindex = part.endLindex;
|
||||
chunk[0].value = addXMLPreserve(chunk, 0);
|
||||
}
|
||||
if (isTextEnd(part) && part.lIndex > endLindex) {
|
||||
if (endLindex !== 0) {
|
||||
chunk[lastTextTag].value = addXMLPreserve(chunk, lastTextTag);
|
||||
}
|
||||
Array.prototype.push.apply(postparsed, chunk);
|
||||
chunk = [];
|
||||
inTextTag = false;
|
||||
endLindex = 0;
|
||||
lastTextTag = 0;
|
||||
}
|
||||
return postparsed;
|
||||
}, []);
|
||||
Array.prototype.push.apply(result, chunk);
|
||||
return result;
|
||||
},
|
||||
postrender(parts) {
|
||||
let lastNonEmpty = "";
|
||||
let lastNonEmptyIndex = 0;
|
||||
return parts.reduce(function (newParts, p, index) {
|
||||
if (p === "") {
|
||||
newParts.push(p);
|
||||
return newParts;
|
||||
}
|
||||
if (p.indexOf('<w:t xml:space="preserve"></w:t>') !== -1) {
|
||||
p = p.replace(/<w:t xml:space="preserve"><\/w:t>/g, "<w:t/>");
|
||||
}
|
||||
if (endsWith(lastNonEmpty, wTpreserve) && startsWith(p, wtEnd)) {
|
||||
newParts[lastNonEmptyIndex] =
|
||||
lastNonEmpty.substr(0, lastNonEmpty.length - wTpreservelen) +
|
||||
"<w:t/>";
|
||||
p = p.substr(wtEndlen);
|
||||
}
|
||||
lastNonEmpty = p;
|
||||
lastNonEmptyIndex = index;
|
||||
newParts.push(p);
|
||||
return newParts;
|
||||
}, []);
|
||||
},
|
||||
};
|
||||
module.exports = () => wrapper(spacePreserve);
|
||||
115
es6/parser.js
Normal file
115
es6/parser.js
Normal file
@ -0,0 +1,115 @@
|
||||
const { wordToUtf8, concatArrays } = require("./doc-utils");
|
||||
const { match, getValue, getValues } = require("./prefix-matcher");
|
||||
|
||||
function moduleParse(placeHolderContent, options) {
|
||||
const modules = options.modules;
|
||||
const startOffset = options.startOffset;
|
||||
const endLindex = options.lIndex;
|
||||
let moduleParsed;
|
||||
options.offset = startOffset;
|
||||
options.lIndex = endLindex;
|
||||
options.match = match;
|
||||
options.getValue = getValue;
|
||||
options.getValues = getValues;
|
||||
|
||||
for (let i = 0, l = modules.length; i < l; i++) {
|
||||
const module = modules[i];
|
||||
moduleParsed = module.parse(placeHolderContent, options);
|
||||
if (moduleParsed) {
|
||||
moduleParsed.offset = startOffset;
|
||||
moduleParsed.endLindex = endLindex;
|
||||
moduleParsed.lIndex = endLindex;
|
||||
moduleParsed.raw = placeHolderContent;
|
||||
return moduleParsed;
|
||||
}
|
||||
}
|
||||
return {
|
||||
type: "placeholder",
|
||||
value: placeHolderContent,
|
||||
offset: startOffset,
|
||||
endLindex,
|
||||
lIndex: endLindex,
|
||||
};
|
||||
}
|
||||
|
||||
const parser = {
|
||||
preparse(parsed, modules, options) {
|
||||
function preparse(parsed, options) {
|
||||
return modules.forEach(function (module) {
|
||||
module.preparse(parsed, options);
|
||||
});
|
||||
}
|
||||
return { preparsed: preparse(parsed, options) };
|
||||
},
|
||||
postparse(postparsed, modules, options) {
|
||||
function getTraits(traitName, postparsed) {
|
||||
return modules.map(function (module) {
|
||||
return module.getTraits(traitName, postparsed);
|
||||
});
|
||||
}
|
||||
let errors = [];
|
||||
function postparse(postparsed, options) {
|
||||
return modules.reduce(function (postparsed, module) {
|
||||
const r = module.postparse(postparsed, {
|
||||
...options,
|
||||
postparse: (parsed, opts) => {
|
||||
return postparse(parsed, { ...options, ...opts });
|
||||
},
|
||||
getTraits,
|
||||
});
|
||||
if (r == null) {
|
||||
return postparsed;
|
||||
}
|
||||
if (r.errors) {
|
||||
errors = concatArrays([errors, r.errors]);
|
||||
return r.postparsed;
|
||||
}
|
||||
return r;
|
||||
}, postparsed);
|
||||
}
|
||||
return { postparsed: postparse(postparsed, options), errors };
|
||||
},
|
||||
|
||||
parse(lexed, modules, options) {
|
||||
let inPlaceHolder = false;
|
||||
let placeHolderContent = "";
|
||||
let startOffset;
|
||||
let tailParts = [];
|
||||
return lexed.reduce(function lexedToParsed(parsed, token) {
|
||||
if (token.type === "delimiter") {
|
||||
inPlaceHolder = token.position === "start";
|
||||
if (token.position === "end") {
|
||||
placeHolderContent = wordToUtf8(placeHolderContent);
|
||||
options.parse = (placeHolderContent) =>
|
||||
moduleParse(placeHolderContent, {
|
||||
...options,
|
||||
...token,
|
||||
startOffset,
|
||||
modules,
|
||||
});
|
||||
parsed.push(options.parse(placeHolderContent));
|
||||
Array.prototype.push.apply(parsed, tailParts);
|
||||
tailParts = [];
|
||||
}
|
||||
if (token.position === "start") {
|
||||
tailParts = [];
|
||||
startOffset = token.offset;
|
||||
}
|
||||
placeHolderContent = "";
|
||||
return parsed;
|
||||
}
|
||||
if (!inPlaceHolder) {
|
||||
parsed.push(token);
|
||||
return parsed;
|
||||
}
|
||||
if (token.type !== "content" || token.position !== "insidetag") {
|
||||
tailParts.push(token);
|
||||
return parsed;
|
||||
}
|
||||
placeHolderContent += token.value;
|
||||
return parsed;
|
||||
}, []);
|
||||
},
|
||||
};
|
||||
|
||||
module.exports = parser;
|
||||
12
es6/postrender.js
Normal file
12
es6/postrender.js
Normal file
@ -0,0 +1,12 @@
|
||||
"use strict";
|
||||
|
||||
function postrender(parts, options) {
|
||||
for (let i = 0, l = options.modules.length; i < l; i++) {
|
||||
const module = options.modules[i];
|
||||
parts = module.postrender(parts, options);
|
||||
}
|
||||
const contains = options.fileTypeConfig.tagShouldContain || [];
|
||||
return options.joinUncorrupt(parts, contains);
|
||||
}
|
||||
|
||||
module.exports = postrender;
|
||||
28
es6/prefix-matcher.js
Normal file
28
es6/prefix-matcher.js
Normal file
@ -0,0 +1,28 @@
|
||||
function match(condition, placeHolderContent) {
|
||||
if (typeof condition === "string") {
|
||||
return placeHolderContent.substr(0, condition.length) === condition;
|
||||
}
|
||||
if (condition instanceof RegExp) {
|
||||
return condition.test(placeHolderContent);
|
||||
}
|
||||
}
|
||||
function getValue(condition, placeHolderContent) {
|
||||
if (typeof condition === "string") {
|
||||
return placeHolderContent.substr(condition.length);
|
||||
}
|
||||
if (condition instanceof RegExp) {
|
||||
return placeHolderContent.match(condition)[1];
|
||||
}
|
||||
}
|
||||
|
||||
function getValues(condition, placeHolderContent) {
|
||||
if (condition instanceof RegExp) {
|
||||
return placeHolderContent.match(condition);
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
match,
|
||||
getValue,
|
||||
getValues,
|
||||
};
|
||||
18
es6/proof-state-module.js
Normal file
18
es6/proof-state-module.js
Normal file
@ -0,0 +1,18 @@
|
||||
module.exports = {
|
||||
on(eventName) {
|
||||
if (eventName === "attached") {
|
||||
this.attached = false;
|
||||
}
|
||||
},
|
||||
postparse(postparsed, { filePath }) {
|
||||
if (filePath !== "word/settings.xml") {
|
||||
return null;
|
||||
}
|
||||
return postparsed.map(function (part) {
|
||||
if (part.type === "tag" && part.tag === "w:proofState") {
|
||||
return { type: "content", value: "" };
|
||||
}
|
||||
return part;
|
||||
});
|
||||
},
|
||||
};
|
||||
48
es6/render.js
Normal file
48
es6/render.js
Normal file
@ -0,0 +1,48 @@
|
||||
"use strict";
|
||||
|
||||
const { concatArrays } = require("./doc-utils");
|
||||
const { throwUnimplementedTagType } = require("./errors");
|
||||
|
||||
function moduleRender(part, options) {
|
||||
let moduleRendered;
|
||||
for (let i = 0, l = options.modules.length; i < l; i++) {
|
||||
const module = options.modules[i];
|
||||
moduleRendered = module.render(part, options);
|
||||
if (moduleRendered) {
|
||||
return moduleRendered;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
function render(options) {
|
||||
const baseNullGetter = options.baseNullGetter;
|
||||
const { compiled, scopeManager } = options;
|
||||
options.nullGetter = (part, sm) => {
|
||||
return baseNullGetter(part, sm || scopeManager);
|
||||
};
|
||||
if (!options.prefix) {
|
||||
options.prefix = "";
|
||||
}
|
||||
if (options.index) {
|
||||
options.prefix = options.prefix + options.index + "-";
|
||||
}
|
||||
let errors = [];
|
||||
const parts = compiled.map(function (part, i) {
|
||||
options.index = i;
|
||||
const moduleRendered = moduleRender(part, options);
|
||||
if (moduleRendered) {
|
||||
if (moduleRendered.errors) {
|
||||
errors = concatArrays([errors, moduleRendered.errors]);
|
||||
}
|
||||
return moduleRendered.value;
|
||||
}
|
||||
if (part.type === "content" || part.type === "tag") {
|
||||
return part.value;
|
||||
}
|
||||
throwUnimplementedTagType(part, i);
|
||||
});
|
||||
return { errors, parts };
|
||||
}
|
||||
|
||||
module.exports = render;
|
||||
69
es6/resolve.js
Normal file
69
es6/resolve.js
Normal file
@ -0,0 +1,69 @@
|
||||
"use strict";
|
||||
|
||||
function moduleResolve(part, options) {
|
||||
let moduleResolved;
|
||||
for (let i = 0, l = options.modules.length; i < l; i++) {
|
||||
const module = options.modules[i];
|
||||
moduleResolved = module.resolve(part, options);
|
||||
if (moduleResolved) {
|
||||
return moduleResolved;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
function resolve(options) {
|
||||
const resolved = [];
|
||||
const baseNullGetter = options.baseNullGetter;
|
||||
const { compiled, scopeManager } = options;
|
||||
options.nullGetter = (part, sm) => {
|
||||
return baseNullGetter(part, sm || scopeManager);
|
||||
};
|
||||
options.resolved = resolved;
|
||||
const errors = [];
|
||||
return Promise.all(
|
||||
compiled
|
||||
.filter(function (part) {
|
||||
return ["content", "tag"].indexOf(part.type) === -1;
|
||||
})
|
||||
.reduce(function (promises, part) {
|
||||
const moduleResolved = moduleResolve(part, options);
|
||||
let result;
|
||||
if (moduleResolved) {
|
||||
result = moduleResolved.then(function (value) {
|
||||
resolved.push({ tag: part.value, value, lIndex: part.lIndex });
|
||||
});
|
||||
} else if (part.type === "placeholder") {
|
||||
result = scopeManager
|
||||
.getValueAsync(part.value, { part })
|
||||
.then(function (value) {
|
||||
if (value == null) {
|
||||
value = options.nullGetter(part);
|
||||
}
|
||||
resolved.push({
|
||||
tag: part.value,
|
||||
value,
|
||||
lIndex: part.lIndex,
|
||||
});
|
||||
return value;
|
||||
});
|
||||
} else {
|
||||
return;
|
||||
}
|
||||
promises.push(
|
||||
result.catch(function (e) {
|
||||
if (e.length > 1) {
|
||||
errors.push(...e);
|
||||
} else {
|
||||
errors.push(e);
|
||||
}
|
||||
})
|
||||
);
|
||||
return promises;
|
||||
}, [])
|
||||
).then(function () {
|
||||
return { errors, resolved };
|
||||
});
|
||||
}
|
||||
|
||||
module.exports = resolve;
|
||||
208
es6/scope-manager.js
Normal file
208
es6/scope-manager.js
Normal file
@ -0,0 +1,208 @@
|
||||
"use strict";
|
||||
const { getScopeParserExecutionError } = require("./errors");
|
||||
const { last } = require("./utils");
|
||||
const { concatArrays } = require("./doc-utils");
|
||||
|
||||
function find(list, fn) {
|
||||
const length = list.length >>> 0;
|
||||
let value;
|
||||
|
||||
for (let i = 0; i < length; i++) {
|
||||
value = list[i];
|
||||
if (fn.call(this, value, i, list)) {
|
||||
return value;
|
||||
}
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function getValue(tag, meta, num) {
|
||||
const scope = this.scopeList[num];
|
||||
if (this.resolved) {
|
||||
let w = this.resolved;
|
||||
this.scopePath.forEach((p, index) => {
|
||||
const lIndex = this.scopeLindex[index];
|
||||
w = find(w, function (r) {
|
||||
return r.lIndex === lIndex;
|
||||
});
|
||||
w = w.value[this.scopePathItem[index]];
|
||||
});
|
||||
return [
|
||||
this.scopePath.length - 1,
|
||||
find(w, function (r) {
|
||||
return meta.part.lIndex === r.lIndex;
|
||||
}).value,
|
||||
];
|
||||
}
|
||||
// search in the scopes (in reverse order) and keep the first defined value
|
||||
let result;
|
||||
|
||||
let parser;
|
||||
if (!this.cachedParsers || !meta.part) {
|
||||
parser = this.parser(tag, {
|
||||
scopePath: this.scopePath,
|
||||
});
|
||||
} else if (this.cachedParsers[meta.part.lIndex]) {
|
||||
parser = this.cachedParsers[meta.part.lIndex];
|
||||
} else {
|
||||
parser = this.cachedParsers[meta.part.lIndex] = this.parser(tag, {
|
||||
scopePath: this.scopePath,
|
||||
});
|
||||
}
|
||||
try {
|
||||
result = parser.get(scope, this.getContext(meta, num));
|
||||
} catch (error) {
|
||||
throw getScopeParserExecutionError({
|
||||
tag,
|
||||
scope,
|
||||
error,
|
||||
offset: meta.part.offset,
|
||||
});
|
||||
}
|
||||
if (result == null && num > 0) {
|
||||
return getValue.call(this, tag, meta, num - 1);
|
||||
}
|
||||
return [num, result];
|
||||
}
|
||||
|
||||
function getValueAsync(tag, meta, num) {
|
||||
const scope = this.scopeList[num];
|
||||
// search in the scopes (in reverse order) and keep the first defined value
|
||||
let parser;
|
||||
if (!this.cachedParsers || !meta.part) {
|
||||
parser = this.parser(tag, {
|
||||
scopePath: this.scopePath,
|
||||
});
|
||||
} else if (this.cachedParsers[meta.part.lIndex]) {
|
||||
parser = this.cachedParsers[meta.part.lIndex];
|
||||
} else {
|
||||
parser = this.cachedParsers[meta.part.lIndex] = this.parser(tag, {
|
||||
scopePath: this.scopePath,
|
||||
});
|
||||
}
|
||||
|
||||
return Promise.resolve()
|
||||
.then(() => {
|
||||
return parser.get(scope, this.getContext(meta, num));
|
||||
})
|
||||
.catch(function (error) {
|
||||
throw getScopeParserExecutionError({
|
||||
tag,
|
||||
scope,
|
||||
error,
|
||||
offset: meta.part.offset,
|
||||
});
|
||||
})
|
||||
.then((result) => {
|
||||
if (result == null && num > 0) {
|
||||
return getValueAsync.call(this, tag, meta, num - 1);
|
||||
}
|
||||
return result;
|
||||
});
|
||||
}
|
||||
|
||||
// This class responsibility is to manage the scope
|
||||
const ScopeManager = class ScopeManager {
|
||||
constructor(options) {
|
||||
this.scopePath = options.scopePath;
|
||||
this.scopePathItem = options.scopePathItem;
|
||||
this.scopePathLength = options.scopePathLength;
|
||||
this.scopeList = options.scopeList;
|
||||
this.scopeLindex = options.scopeLindex;
|
||||
this.parser = options.parser;
|
||||
this.resolved = options.resolved;
|
||||
this.cachedParsers = options.cachedParsers;
|
||||
}
|
||||
loopOver(tag, functor, inverted, meta) {
|
||||
return this.loopOverValue(this.getValue(tag, meta), functor, inverted);
|
||||
}
|
||||
functorIfInverted(inverted, functor, value, i, length) {
|
||||
if (inverted) {
|
||||
functor(value, i, length);
|
||||
}
|
||||
return inverted;
|
||||
}
|
||||
isValueFalsy(value, type) {
|
||||
return (
|
||||
value == null ||
|
||||
!value ||
|
||||
(type === "[object Array]" && value.length === 0)
|
||||
);
|
||||
}
|
||||
loopOverValue(value, functor, inverted) {
|
||||
if (this.resolved) {
|
||||
inverted = false;
|
||||
}
|
||||
const type = Object.prototype.toString.call(value);
|
||||
if (this.isValueFalsy(value, type)) {
|
||||
return this.functorIfInverted(
|
||||
inverted,
|
||||
functor,
|
||||
last(this.scopeList),
|
||||
0,
|
||||
1
|
||||
);
|
||||
}
|
||||
if (type === "[object Array]") {
|
||||
for (let i = 0; i < value.length; i++) {
|
||||
this.functorIfInverted(!inverted, functor, value[i], i, value.length);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
if (type === "[object Object]") {
|
||||
return this.functorIfInverted(!inverted, functor, value, 0, 1);
|
||||
}
|
||||
return this.functorIfInverted(
|
||||
!inverted,
|
||||
functor,
|
||||
last(this.scopeList),
|
||||
0,
|
||||
1
|
||||
);
|
||||
}
|
||||
getValue(tag, meta) {
|
||||
const [num, result] = getValue.call(
|
||||
this,
|
||||
tag,
|
||||
meta,
|
||||
this.scopeList.length - 1
|
||||
);
|
||||
this.num = num;
|
||||
return result;
|
||||
}
|
||||
getValueAsync(tag, meta) {
|
||||
return getValueAsync.call(this, tag, meta, this.scopeList.length - 1);
|
||||
}
|
||||
getContext(meta, num) {
|
||||
return {
|
||||
num,
|
||||
meta,
|
||||
scopeList: this.scopeList,
|
||||
resolved: this.resolved,
|
||||
scopePath: this.scopePath,
|
||||
scopePathItem: this.scopePathItem,
|
||||
scopePathLength: this.scopePathLength,
|
||||
};
|
||||
}
|
||||
createSubScopeManager(scope, tag, i, part, length) {
|
||||
return new ScopeManager({
|
||||
resolved: this.resolved,
|
||||
parser: this.parser,
|
||||
cachedParsers: this.cachedParsers,
|
||||
scopeList: concatArrays([this.scopeList, [scope]]),
|
||||
scopePath: concatArrays([this.scopePath, [tag]]),
|
||||
scopePathItem: concatArrays([this.scopePathItem, [i]]),
|
||||
scopePathLength: concatArrays([this.scopePathLength, [length]]),
|
||||
scopeLindex: concatArrays([this.scopeLindex, [part.lIndex]]),
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
module.exports = function (options) {
|
||||
options.scopePath = [];
|
||||
options.scopePathItem = [];
|
||||
options.scopePathLength = [];
|
||||
options.scopeLindex = [];
|
||||
options.scopeList = [options.tags];
|
||||
return new ScopeManager(options);
|
||||
};
|
||||
41
es6/tests/angular-parser.js
vendored
Normal file
41
es6/tests/angular-parser.js
vendored
Normal file
@ -0,0 +1,41 @@
|
||||
const expressions = require("angular-expressions");
|
||||
const assign = require("lodash/assign");
|
||||
|
||||
function angularParser(tag) {
|
||||
if (tag === ".") {
|
||||
return {
|
||||
get(s) {
|
||||
return s;
|
||||
},
|
||||
};
|
||||
}
|
||||
const expr = expressions.compile(
|
||||
tag.replace(/(’|‘)/g, "'").replace(/(“|”)/g, '"')
|
||||
);
|
||||
// isAngularAssignment will be true if your tag contains a `=`, for example
|
||||
// when you write the following in your template :
|
||||
// {full_name = first_name + last_name}
|
||||
// In that case, it makes sense to return an empty string so
|
||||
// that the tag does not write something to the generated document.
|
||||
const isAngularAssignment =
|
||||
expr.ast.body[0] &&
|
||||
expr.ast.body[0].expression.type === "AssignmentExpression";
|
||||
|
||||
return {
|
||||
get(scope, context) {
|
||||
let obj = {};
|
||||
const scopeList = context.scopeList;
|
||||
const num = context.num;
|
||||
for (let i = 0, len = num + 1; i < len; i++) {
|
||||
obj = assign(obj, scopeList[i]);
|
||||
}
|
||||
const result = expr(scope, obj);
|
||||
if (isAngularAssignment) {
|
||||
return "";
|
||||
}
|
||||
return result;
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
module.exports = angularParser;
|
||||
52
es6/tests/assertion-module.js
Normal file
52
es6/tests/assertion-module.js
Normal file
@ -0,0 +1,52 @@
|
||||
function isArray(thing) {
|
||||
return thing instanceof Array;
|
||||
}
|
||||
function isObject(thing) {
|
||||
return thing instanceof Object && !isArray(thing);
|
||||
}
|
||||
function isString(thing) {
|
||||
return typeof thing === "string";
|
||||
}
|
||||
|
||||
class AssertionModule {
|
||||
preparse(parsed) {
|
||||
if (!isArray(parsed)) {
|
||||
throw new Error("Parsed should be an array");
|
||||
}
|
||||
}
|
||||
parse(placeholderContent) {
|
||||
if (!isString(placeholderContent)) {
|
||||
throw new Error("placeholderContent should be a string");
|
||||
}
|
||||
}
|
||||
postparse(parsed, { filePath, contentType }) {
|
||||
if (!isArray(parsed)) {
|
||||
throw new Error("Parsed should be an array");
|
||||
}
|
||||
if (!isString(filePath)) {
|
||||
throw new Error("filePath should be a string");
|
||||
}
|
||||
if (!isString(contentType)) {
|
||||
throw new Error("contentType should be a string");
|
||||
}
|
||||
}
|
||||
render(part, { filePath, contentType }) {
|
||||
if (!isObject(part)) {
|
||||
throw new Error("part should be an object");
|
||||
}
|
||||
if (!isString(filePath)) {
|
||||
throw new Error("filePath should be a string");
|
||||
}
|
||||
if (!isString(contentType)) {
|
||||
throw new Error("contentType should be a string");
|
||||
}
|
||||
}
|
||||
postrender(parts) {
|
||||
if (!isArray(parts)) {
|
||||
throw new Error("Parts should be an array");
|
||||
}
|
||||
return parts;
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = AssertionModule;
|
||||
1132
es6/tests/base.js
Normal file
1132
es6/tests/base.js
Normal file
File diff suppressed because one or more lines are too long
181
es6/tests/data-fixtures.js
Normal file
181
es6/tests/data-fixtures.js
Normal file
@ -0,0 +1,181 @@
|
||||
const expectedPrintedPostParsed = `
|
||||
(0)<?xml version="1.0" encoding="UTF-8" standalone="yes"?><w:document xmlns:wpc="http://schemas.microsoft.com/office/word/2010/wordprocessingCanvas" xmlns:cx="http://schemas.microsoft.com/office/drawing/2014/chartex" xmlns:cx1="http://schemas.microsoft.com/office/drawing/2015/9/8/chartex" xmlns:cx2="http://schemas.microsoft.com/office/drawing/2015/10/21/chartex" xmlns:cx3="http://schemas.microsoft.com/office/drawing/2016/5/9/chartex" xmlns:cx4="http://schemas.microsoft.com/office/drawing/2016/5/10/chartex" xmlns:cx5="http://schemas.microsoft.com/office/drawing/2016/5/11/chartex" xmlns:cx6="http://schemas.microsoft.com/office/drawing/2016/5/12/chartex" xmlns:cx7="http://schemas.microsoft.com/office/drawing/2016/5/13/chartex" xmlns:cx8="http://schemas.microsoft.com/office/drawing/2016/5/14/chartex" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:aink="http://schemas.microsoft.com/office/drawing/2016/ink" xmlns:am3d="http://schemas.microsoft.com/office/drawing/2017/model3d" xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" xmlns:m="http://schemas.openxmlformats.org/officeDocument/2006/math" xmlns:v="urn:schemas-microsoft-com:vml" xmlns:wp14="http://schemas.microsoft.com/office/word/2010/wordprocessingDrawing" xmlns:wp="http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing" xmlns:w10="urn:schemas-microsoft-com:office:word" xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main" xmlns:w14="http://schemas.microsoft.com/office/word/2010/wordml" xmlns:w15="http://schemas.microsoft.com/office/word/2012/wordml" xmlns:w16cid="http://schemas.microsoft.com/office/word/2016/wordml/cid" xmlns:w16se="http://schemas.microsoft.com/office/word/2015/wordml/symex" xmlns:wpg="http://schemas.microsoft.com/office/word/2010/wordprocessingGroup" xmlns:wpi="http://schemas.microsoft.com/office/word/2010/wordprocessingInk" xmlns:wne="http://schemas.microsoft.com/office/word/2006/wordml" xmlns:wps="http://schemas.microsoft.com/office/word/2010/wordprocessingShape" mc:Ignorable="w14 w15 w16se w16cid wp14"><w:body>
|
||||
***START LOOP OF hi
|
||||
(1) <w:p>
|
||||
(2) <w:r>
|
||||
(3) <w:t xml:space="preserve">
|
||||
(3) </w:t>
|
||||
(2) </w:r>
|
||||
(2) <w:p w14:paraId="736A2D9F" w14:textId="77777777" w:rsidR="008E1095" w:rsidRDefault="008E1095"/>
|
||||
(2) <w:sdt><w:sdtPr><w:alias w:val="SF:Table"/><w:id w:val="2039776175"/><w:placeholder><w:docPart w:val="CFCF8C7E6B33489A9DD50D7417AD410D"/></w:placeholder><w15:color w:val="008000"/><w15:appearance w15:val="hidden"/></w:sdtPr>
|
||||
(2) <w:sdtContent>
|
||||
(3) <w:p w14:paraId="4800949B" w14:textId="77777777" w:rsidR="00D3440B" w:rsidRDefault="00D3440B" w:rsidP="00D3440B"/>
|
||||
(3) <w:tbl><w:tblPr><w:tblStyle w:val="TableGrid"/><w:tblW w:w="0" w:type="auto"/><w:tblLook w:val="0660" w:firstRow="1" w:lastRow="1" w:firstColumn="0" w:lastColumn="0" w:noHBand="1" w:noVBand="1"/></w:tblPr><w:tblGrid><w:gridCol w:w="2909"/><w:gridCol w:w="2928"/><w:gridCol w:w="2793"/></w:tblGrid>
|
||||
(3) <w:tr w:rsidR="00D3440B" w14:paraId="5887C255" w14:textId="77777777" w:rsidTr="00F617CB">
|
||||
(4) <w:trPr><w:tblHeader/></w:trPr>
|
||||
(4) <w:tc>
|
||||
(5) <w:tcPr><w:tcW w:w="0" w:type="auto"/></w:tcPr>
|
||||
(5) <w:p w14:paraId="5951DD51" w14:textId="77777777" w:rsidR="00D3440B" w:rsidRDefault="00D3440B" w:rsidP="00F617CB">
|
||||
(6) <w:r>
|
||||
(7) <w:t xml:space="preserve">
|
||||
(8) name
|
||||
(7) </w:t>
|
||||
(6) </w:r>
|
||||
(5) </w:p>
|
||||
(4) </w:tc>
|
||||
(4) <w:tc>
|
||||
(5) <w:tcPr><w:tcW w:w="0" w:type="auto"/></w:tcPr>
|
||||
(5) <w:p w14:paraId="34A4528E" w14:textId="77777777" w:rsidR="00D3440B" w:rsidRDefault="00D3440B" w:rsidP="00F617CB">
|
||||
(6) <w:r>
|
||||
(7) <w:t xml:space="preserve">
|
||||
(8) phone
|
||||
(7) </w:t>
|
||||
(6) </w:r>
|
||||
(5) </w:p>
|
||||
(4) </w:tc>
|
||||
(4) <w:tc>
|
||||
(5) <w:tcPr><w:tcW w:w="0" w:type="auto"/></w:tcPr>
|
||||
(5) <w:p w14:paraId="1EFFDB2B" w14:textId="77777777" w:rsidR="00D3440B" w:rsidRDefault="00D3440B" w:rsidP="00F617CB">
|
||||
(6) <w:r>
|
||||
(7) <w:t xml:space="preserve">
|
||||
(8) website
|
||||
(7) </w:t>
|
||||
(6) </w:r>
|
||||
(5) </w:p>
|
||||
(4) </w:tc>
|
||||
(3) </w:tr>
|
||||
(3) <w:tr w:rsidR="00D3440B" w14:paraId="53971E16" w14:textId="77777777" w:rsidTr="00F617CB">
|
||||
(4) <w:sdt><w:sdtPr><w:alias w:val="SF:R"/><w:id w:val="1927457022"/><w15:color w:val="008000"/><w15:appearance w15:val="hidden"/></w:sdtPr>
|
||||
(4) <w:sdtContent>
|
||||
(5) <w:tc>
|
||||
(6) <w:tcPr><w:tcW w:w="0" w:type="auto"/></w:tcPr>
|
||||
(6) <w:p w14:paraId="6B371C2E" w14:textId="77777777" w:rsidR="00D3440B" w:rsidRDefault="00D3440B" w:rsidP="00F617CB">
|
||||
(7) <w:pPr>
|
||||
(8) <w:spacing w:line="360" w:lineRule="auto"/>
|
||||
(8) <w:jc w:val="both"/>
|
||||
(7) </w:pPr>
|
||||
(7) <w:r>
|
||||
(8) <w:t xml:space="preserve">
|
||||
=============================={foo}
|
||||
(8) </w:t>
|
||||
(7) </w:r>
|
||||
(6) </w:p>
|
||||
(5) </w:tc>
|
||||
(4) </w:sdtContent>
|
||||
(4) </w:sdt><w:sdt><w:sdtPr><w:alias w:val="SF:R"/><w:id w:val="1556285925"/><w15:color w:val="008000"/><w15:appearance w15:val="hidden"/></w:sdtPr>
|
||||
(4) <w:sdtContent>
|
||||
(5) <w:tc>
|
||||
(6) <w:tcPr><w:tcW w:w="0" w:type="auto"/></w:tcPr>
|
||||
(6) <w:p w14:paraId="3C4100BB" w14:textId="77777777" w:rsidR="00D3440B" w:rsidRDefault="00D3440B" w:rsidP="00F617CB">
|
||||
(7) <w:pPr>
|
||||
(8) <w:spacing w:line="360" w:lineRule="auto"/>
|
||||
(8) <w:jc w:val="both"/>
|
||||
(7) </w:pPr>
|
||||
(7) <w:r>
|
||||
(8) <w:t xml:space="preserve">
|
||||
=============================={bar}
|
||||
(8) </w:t>
|
||||
(7) </w:r>
|
||||
(6) </w:p>
|
||||
(5) </w:tc>
|
||||
(4) </w:sdtContent>
|
||||
(4) </w:sdt><w:sdt><w:sdtPr><w:alias w:val="SF:R"/><w:id w:val="-788971804"/><w15:color w:val="008000"/><w15:appearance w15:val="hidden"/></w:sdtPr>
|
||||
(4) <w:sdtContent>
|
||||
(5) <w:tc>
|
||||
(6) <w:tcPr><w:tcW w:w="0" w:type="auto"/></w:tcPr>
|
||||
(6) <w:p w14:paraId="24C5CEB1" w14:textId="77777777" w:rsidR="00D3440B" w:rsidRDefault="00D3440B" w:rsidP="00F617CB">
|
||||
(7) <w:pPr>
|
||||
(8) <w:spacing w:line="360" w:lineRule="auto"/>
|
||||
(8) <w:jc w:val="both"/>
|
||||
(7) </w:pPr>
|
||||
(7) <w:r>
|
||||
(8) <w:t xml:space="preserve">
|
||||
=============================={bar}
|
||||
(8) </w:t>
|
||||
(7) </w:r>
|
||||
(6) </w:p>
|
||||
(5) </w:tc>
|
||||
(4) </w:sdtContent>
|
||||
(4) </w:sdt>
|
||||
(3) </w:tr>
|
||||
(3) </w:tbl>
|
||||
(3) <w:p w14:paraId="676A1E43" w14:textId="77777777" w:rsidR="00D3440B" w:rsidRDefault="00D3440B" w:rsidP="00D3440B"/>
|
||||
(2) </w:sdtContent>
|
||||
(2) </w:sdt>
|
||||
(2) <w:p w14:paraId="22D858B2" w14:textId="69A6ACE6" w:rsidR="009843AE" w:rsidRDefault="00EB53B3"/>
|
||||
(1) </w:p>
|
||||
(1) <w:p>
|
||||
(2) <w:r>
|
||||
(3) <w:t xml:space="preserve">
|
||||
(3) </w:t>
|
||||
(2) </w:r>
|
||||
(1) </w:p>
|
||||
***END LOOP OF hi
|
||||
(0)</w:body></w:document>`;
|
||||
|
||||
const rawXMLValue = `<p:sp>
|
||||
<p:nvSpPr>
|
||||
<p:cNvPr id="37" name="CustomShape 2"/>
|
||||
<p:cNvSpPr/>
|
||||
<p:nvPr/>
|
||||
</p:nvSpPr>
|
||||
<p:spPr>
|
||||
<a:xfrm>
|
||||
<a:off x="504000" y="1769040"/>
|
||||
<a:ext cx="9071280" cy="4384080"/>
|
||||
</a:xfrm>
|
||||
<a:prstGeom prst="rect">
|
||||
<a:avLst/>
|
||||
</a:prstGeom>
|
||||
<a:noFill/>
|
||||
<a:ln>
|
||||
<a:noFill/>
|
||||
</a:ln>
|
||||
</p:spPr>
|
||||
<p:style>
|
||||
<a:lnRef idx="0"/>
|
||||
<a:fillRef idx="0"/>
|
||||
<a:effectRef idx="0"/>
|
||||
<a:fontRef idx="minor"/>
|
||||
</p:style>
|
||||
<p:txBody>
|
||||
<a:bodyPr lIns="0" rIns="0" tIns="0" bIns="0" anchor="ctr"/>
|
||||
<a:p>
|
||||
<a:pPr algn="ctr">
|
||||
<a:lnSpc>
|
||||
<a:spcPct val="100000"/>
|
||||
</a:lnSpc>
|
||||
</a:pPr>
|
||||
<a:r>
|
||||
<a:rPr b="0" lang="fr-FR" sz="3200" spc="-1" strike="noStrike">
|
||||
<a:solidFill>
|
||||
<a:srgbClr val="000000"/>
|
||||
</a:solidFill>
|
||||
<a:uFill>
|
||||
<a:solidFill>
|
||||
<a:srgbClr val="ffffff"/>
|
||||
</a:solidFill>
|
||||
</a:uFill>
|
||||
<a:latin typeface="Arial"/>
|
||||
</a:rPr>
|
||||
<a:t>Hello World</a:t>
|
||||
</a:r>
|
||||
<a:endParaRPr b="0" lang="fr-FR" sz="1800" spc="-1" strike="noStrike">
|
||||
<a:solidFill>
|
||||
<a:srgbClr val="000000"/>
|
||||
</a:solidFill>
|
||||
<a:uFill>
|
||||
<a:solidFill>
|
||||
<a:srgbClr val="ffffff"/>
|
||||
</a:solidFill>
|
||||
</a:uFill>
|
||||
<a:latin typeface="Arial"/>
|
||||
</a:endParaRPr>
|
||||
</a:p>
|
||||
</p:txBody>
|
||||
</p:sp>`;
|
||||
|
||||
module.exports = {
|
||||
expectedPrintedPostParsed,
|
||||
rawXMLValue,
|
||||
};
|
||||
23
es6/tests/doc-props.js
Normal file
23
es6/tests/doc-props.js
Normal file
@ -0,0 +1,23 @@
|
||||
const { createDoc, shouldBeSame, expect } = require("./utils");
|
||||
|
||||
describe("Docx docprops", function () {
|
||||
it("should change values with template data", function () {
|
||||
const tags = {
|
||||
first_name: "Hipp",
|
||||
last_name: "Edgar",
|
||||
phone: "0652455478",
|
||||
description: "New Website",
|
||||
};
|
||||
const doc = createDoc("tag-docprops.docx");
|
||||
doc.setData(tags);
|
||||
doc.render();
|
||||
expect(doc.getFullText()).to.be.equal("Edgar Hipp");
|
||||
expect(doc.getFullText("word/header1.xml")).to.be.equal(
|
||||
"Edgar Hipp0652455478New Website"
|
||||
);
|
||||
expect(doc.getFullText("word/footer1.xml")).to.be.equal(
|
||||
"EdgarHipp0652455478"
|
||||
);
|
||||
shouldBeSame({ doc, expectedName: "expected-tag-docprops.docx" });
|
||||
});
|
||||
});
|
||||
1521
es6/tests/errors.js
Normal file
1521
es6/tests/errors.js
Normal file
File diff suppressed because it is too large
Load Diff
1301
es6/tests/fixtures.js
Normal file
1301
es6/tests/fixtures.js
Normal file
File diff suppressed because it is too large
Load Diff
21
es6/tests/index.js
Normal file
21
es6/tests/index.js
Normal file
@ -0,0 +1,21 @@
|
||||
"use strict";
|
||||
|
||||
require("es6-promise").polyfill();
|
||||
const { setExamplesDirectory, setStartFunction, start } = require("./utils");
|
||||
const path = require("path");
|
||||
setExamplesDirectory(path.resolve(__dirname, "..", "..", "examples"));
|
||||
setStartFunction(startTest);
|
||||
|
||||
function startTest() {
|
||||
require("./base");
|
||||
require("./xml-templater");
|
||||
require("./xml-matcher");
|
||||
require("./errors");
|
||||
require("./speed");
|
||||
require("./lexer-parser-render");
|
||||
require("./integration");
|
||||
require("./doc-props");
|
||||
require("./modules");
|
||||
}
|
||||
|
||||
start();
|
||||
1273
es6/tests/integration.js
Normal file
1273
es6/tests/integration.js
Normal file
File diff suppressed because it is too large
Load Diff
137
es6/tests/lexer-parser-render.js
Normal file
137
es6/tests/lexer-parser-render.js
Normal file
@ -0,0 +1,137 @@
|
||||
const Lexer = require("../lexer.js");
|
||||
const { expect, makeDocx, cleanRecursive } = require("./utils");
|
||||
const fixtures = require("./fixtures");
|
||||
const docxconfig = require("../file-type-config").docx;
|
||||
const inspectModule = require("../inspect-module.js");
|
||||
const AssertionModule = require("./assertion-module.js");
|
||||
const tagsDocxConfig = {
|
||||
text: docxconfig.tagsXmlTextArray,
|
||||
other: docxconfig.tagsXmlLexedArray,
|
||||
};
|
||||
|
||||
describe("Algorithm", function () {
|
||||
Object.keys(fixtures).forEach(function (key) {
|
||||
const fixture = fixtures[key];
|
||||
(fixture.onlySync ? it.only : it)(fixture.it, function () {
|
||||
const doc = makeDocx(key, fixture.content);
|
||||
doc.setOptions(fixture.options);
|
||||
const iModule = inspectModule();
|
||||
doc.attachModule(iModule).attachModule(new AssertionModule());
|
||||
doc.setData(fixture.scope);
|
||||
doc.render();
|
||||
cleanRecursive(iModule.inspect.lexed);
|
||||
cleanRecursive(iModule.inspect.parsed);
|
||||
cleanRecursive(iModule.inspect.postparsed);
|
||||
if (fixture.result !== null) {
|
||||
expect(iModule.inspect.content).to.be.deep.equal(
|
||||
fixture.result,
|
||||
"Content incorrect"
|
||||
);
|
||||
}
|
||||
if (fixture.lexed !== null) {
|
||||
expect(iModule.inspect.lexed).to.be.deep.equal(
|
||||
fixture.lexed,
|
||||
"Lexed incorrect"
|
||||
);
|
||||
}
|
||||
if (fixture.parsed !== null) {
|
||||
expect(iModule.inspect.parsed).to.be.deep.equal(
|
||||
fixture.parsed,
|
||||
"Parsed incorrect"
|
||||
);
|
||||
}
|
||||
if (fixture.postparsed !== null) {
|
||||
expect(iModule.inspect.postparsed).to.be.deep.equal(
|
||||
fixture.postparsed,
|
||||
"Postparsed incorrect"
|
||||
);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
Object.keys(fixtures).forEach(function (key) {
|
||||
const fixture = fixtures[key];
|
||||
(fixture.only ? it.only : it)(`Async ${fixture.it}`, function () {
|
||||
const doc = makeDocx(key, fixture.content);
|
||||
doc.setOptions(fixture.options);
|
||||
const iModule = inspectModule();
|
||||
doc.attachModule(iModule);
|
||||
doc.compile();
|
||||
return doc.resolveData(fixture.scope).then(function () {
|
||||
doc.render();
|
||||
cleanRecursive(iModule.inspect.lexed);
|
||||
cleanRecursive(iModule.inspect.parsed);
|
||||
cleanRecursive(iModule.inspect.postparsed);
|
||||
if (fixture.result !== null) {
|
||||
expect(iModule.inspect.content).to.be.deep.equal(
|
||||
fixture.result,
|
||||
"Content incorrect"
|
||||
);
|
||||
}
|
||||
if (fixture.resolved) {
|
||||
expect(iModule.inspect.resolved).to.be.deep.equal(
|
||||
fixture.resolved,
|
||||
"Resolved incorrect"
|
||||
);
|
||||
}
|
||||
if (fixture.lexed !== null) {
|
||||
expect(iModule.inspect.lexed).to.be.deep.equal(
|
||||
fixture.lexed,
|
||||
"Lexed incorrect"
|
||||
);
|
||||
}
|
||||
if (fixture.parsed !== null) {
|
||||
expect(iModule.inspect.parsed).to.be.deep.equal(
|
||||
fixture.parsed,
|
||||
"Parsed incorrect"
|
||||
);
|
||||
}
|
||||
if (fixture.postparsed !== null) {
|
||||
expect(iModule.inspect.postparsed).to.be.deep.equal(
|
||||
fixture.postparsed,
|
||||
"Postparsed incorrect"
|
||||
);
|
||||
}
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
it("should xmlparse strange tags", function () {
|
||||
const xmllexed = Lexer.xmlparse(
|
||||
fixtures.strangetags.content,
|
||||
tagsDocxConfig
|
||||
);
|
||||
cleanRecursive(xmllexed);
|
||||
expect(xmllexed).to.be.deep.equal(fixtures.strangetags.xmllexed);
|
||||
});
|
||||
|
||||
it("should xmlparse selfclosing tag", function () {
|
||||
const xmllexed = Lexer.xmlparse("<w:rPr><w:noProof/></w:rPr>", {
|
||||
text: [],
|
||||
other: ["w:rPr", "w:noProof"],
|
||||
});
|
||||
expect(xmllexed).to.be.deep.equal([
|
||||
{
|
||||
type: "tag",
|
||||
position: "start",
|
||||
text: false,
|
||||
value: "<w:rPr>",
|
||||
tag: "w:rPr",
|
||||
},
|
||||
{
|
||||
type: "tag",
|
||||
position: "selfclosing",
|
||||
text: false,
|
||||
value: "<w:noProof/>",
|
||||
tag: "w:noProof",
|
||||
},
|
||||
{
|
||||
type: "tag",
|
||||
position: "end",
|
||||
text: false,
|
||||
value: "</w:rPr>",
|
||||
tag: "w:rPr",
|
||||
},
|
||||
]);
|
||||
});
|
||||
});
|
||||
348
es6/tests/modules.js
Normal file
348
es6/tests/modules.js
Normal file
@ -0,0 +1,348 @@
|
||||
const {
|
||||
expectToThrow,
|
||||
createDoc,
|
||||
shouldBeSame,
|
||||
isNode12,
|
||||
createDocV4,
|
||||
} = require("./utils");
|
||||
const Errors = require("../errors.js");
|
||||
const { expect } = require("chai");
|
||||
const { xml2str, traits } = require("../doc-utils");
|
||||
|
||||
describe("Verify apiversion", function () {
|
||||
it("should work with valid api version", function () {
|
||||
const module = {
|
||||
requiredAPIVersion: "3.23.0",
|
||||
render(part) {
|
||||
return part.value;
|
||||
},
|
||||
};
|
||||
const doc = createDoc("loop-valid.docx");
|
||||
doc.attachModule(module);
|
||||
});
|
||||
|
||||
it("should fail with invalid api version", function () {
|
||||
const module = {
|
||||
requiredAPIVersion: "3.92.0",
|
||||
render(part) {
|
||||
return part.value;
|
||||
},
|
||||
};
|
||||
const doc = createDoc("loop-valid.docx");
|
||||
|
||||
expectToThrow(() => doc.attachModule(module), Errors.XTAPIVersionError, {
|
||||
message:
|
||||
"The minor api version is not uptodate, you probably have to update docxtemplater with npm install --save docxtemplater",
|
||||
name: "APIVersionError",
|
||||
properties: {
|
||||
id: "api_version_error",
|
||||
currentModuleApiVersion: [3, 24, 0],
|
||||
neededVersion: [3, 92, 0],
|
||||
},
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("Module attachment", function () {
|
||||
it("should not allow to attach the same module twice", function () {
|
||||
const module = {
|
||||
name: "TestModule",
|
||||
requiredAPIVersion: "3.0.0",
|
||||
render(part) {
|
||||
return part.value;
|
||||
},
|
||||
};
|
||||
const doc1 = createDoc("loop-valid.docx");
|
||||
doc1.attachModule(module);
|
||||
const doc2 = createDoc("tag-example.docx");
|
||||
|
||||
let errMessage = null;
|
||||
try {
|
||||
doc2.attachModule(module);
|
||||
} catch (e) {
|
||||
errMessage = e.message;
|
||||
}
|
||||
expect(errMessage).to.equal(
|
||||
'Cannot attach a module that was already attached : "TestModule". Maybe you are instantiating the module at the root level, and using it for multiple instances of Docxtemplater'
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("Module xml parse", function () {
|
||||
it("should not mutate options (regression for issue #526)", function () {
|
||||
const module = {
|
||||
requiredAPIVersion: "3.0.0",
|
||||
optionsTransformer(options, docxtemplater) {
|
||||
const relsFiles = docxtemplater.zip
|
||||
.file(/document.xml.rels/)
|
||||
.map((file) => file.name);
|
||||
options.xmlFileNames = options.xmlFileNames.concat(relsFiles);
|
||||
return options;
|
||||
},
|
||||
};
|
||||
const doc = createDoc("tag-example.docx");
|
||||
const opts = {};
|
||||
doc.setOptions(opts);
|
||||
doc.attachModule(module);
|
||||
doc.compile();
|
||||
expect(opts).to.deep.equal({});
|
||||
});
|
||||
|
||||
it("should be possible to parse xml files", function () {
|
||||
let xmlDocuments;
|
||||
|
||||
const module = {
|
||||
requiredAPIVersion: "3.0.0",
|
||||
optionsTransformer(options, docxtemplater) {
|
||||
const relsFiles = docxtemplater.zip
|
||||
.file(/document.xml.rels/)
|
||||
.map((file) => file.name);
|
||||
options.xmlFileNames = options.xmlFileNames.concat(relsFiles);
|
||||
return options;
|
||||
},
|
||||
set(options) {
|
||||
if (options.xmlDocuments) {
|
||||
xmlDocuments = options.xmlDocuments;
|
||||
}
|
||||
},
|
||||
};
|
||||
|
||||
const doc = createDoc("tag-example.docx");
|
||||
doc.attachModule(module);
|
||||
doc.compile();
|
||||
|
||||
const xmlKeys = Object.keys(xmlDocuments);
|
||||
expect(xmlKeys).to.deep.equal(["word/_rels/document.xml.rels"]);
|
||||
const rels = xmlDocuments[
|
||||
"word/_rels/document.xml.rels"
|
||||
].getElementsByTagName("Relationship");
|
||||
expect(rels.length).to.equal(10);
|
||||
|
||||
const str = xml2str(xmlDocuments["word/_rels/document.xml.rels"]);
|
||||
if (isNode12()) {
|
||||
expect(str).to
|
||||
.equal(`<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\r
|
||||
<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId8" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/footer" Target="footer1.xml"/><Relationship Id="rId3" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/settings" Target="settings.xml"/><Relationship Id="rId7" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/header" Target="header1.xml"/><Relationship Id="rId2" Type="http://schemas.microsoft.com/office/2007/relationships/stylesWithEffects" Target="stylesWithEffects.xml"/><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles" Target="styles.xml"/><Relationship Id="rId6" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/endnotes" Target="endnotes.xml"/><Relationship Id="rId5" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/footnotes" Target="footnotes.xml"/><Relationship Id="rId10" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/theme" Target="theme/theme1.xml"/><Relationship Id="rId4" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/webSettings" Target="webSettings.xml"/><Relationship Id="rId9" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/fontTable" Target="fontTable.xml"/></Relationships>`);
|
||||
rels[5].setAttribute("Foobar", "Baz");
|
||||
doc.render();
|
||||
shouldBeSame({ doc, expectedName: "expected-module-change-rels.docx" });
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("Module unique tags xml", function () {
|
||||
it("should not cause an issue if tagsXmlLexedArray contains duplicates", function () {
|
||||
const module = {
|
||||
requiredAPIVersion: "3.0.0",
|
||||
optionsTransformer(options, docxtemplater) {
|
||||
docxtemplater.fileTypeConfig.tagsXmlLexedArray.push(
|
||||
"w:p",
|
||||
"w:r",
|
||||
"w:p"
|
||||
);
|
||||
return options;
|
||||
},
|
||||
};
|
||||
|
||||
const doc = createDoc("tag-example.docx");
|
||||
doc.attachModule(module);
|
||||
doc.setData({
|
||||
first_name: "Hipp",
|
||||
last_name: "Edgar",
|
||||
phone: "0652455478",
|
||||
description: "New Website",
|
||||
});
|
||||
doc.compile();
|
||||
doc.render();
|
||||
shouldBeSame({ doc, expectedName: "expected-tag-example.docx" });
|
||||
});
|
||||
});
|
||||
|
||||
describe("Module traits", function () {
|
||||
it("should not cause an issue if using traits.expandTo containing loop", function () {
|
||||
const moduleName = "comment-module";
|
||||
function getInner({ part, leftParts, rightParts, postparse }) {
|
||||
part.subparsed = postparse([].concat(leftParts).concat(rightParts), {
|
||||
basePart: part,
|
||||
});
|
||||
return part;
|
||||
}
|
||||
const module = {
|
||||
name: "Test module",
|
||||
requiredAPIVersion: "3.0.0",
|
||||
parse(placeHolderContent) {
|
||||
if (placeHolderContent[0] === "£") {
|
||||
const type = "placeholder";
|
||||
return {
|
||||
type,
|
||||
value: placeHolderContent.substr(1),
|
||||
module: moduleName,
|
||||
};
|
||||
}
|
||||
},
|
||||
postparse(parsed, { postparse }) {
|
||||
parsed = traits.expandToOne(parsed, {
|
||||
moduleName,
|
||||
getInner,
|
||||
expandTo: ["w:p"],
|
||||
postparse,
|
||||
});
|
||||
return parsed;
|
||||
},
|
||||
render(part) {
|
||||
if (part.module === moduleName) {
|
||||
return {
|
||||
value: "",
|
||||
};
|
||||
}
|
||||
},
|
||||
};
|
||||
|
||||
const doc = createDoc("comment-with-loop.docx");
|
||||
doc.attachModule(module);
|
||||
doc.setData({}).compile().render();
|
||||
shouldBeSame({ doc, expectedName: "expected-comment-example.docx" });
|
||||
});
|
||||
});
|
||||
|
||||
describe("Module errors", function () {
|
||||
it("should work", function () {
|
||||
const moduleName = "ErrorModule";
|
||||
const module = {
|
||||
name: "Error module",
|
||||
requiredAPIVersion: "3.0.0",
|
||||
parse(placeHolderContent) {
|
||||
const type = "placeholder";
|
||||
return {
|
||||
type,
|
||||
value: placeHolderContent,
|
||||
module: moduleName,
|
||||
};
|
||||
},
|
||||
render(part) {
|
||||
if (part.module === moduleName) {
|
||||
return {
|
||||
errors: [new Error(`foobar ${part.value}`)],
|
||||
};
|
||||
}
|
||||
},
|
||||
};
|
||||
|
||||
let error = null;
|
||||
const doc = createDoc("tag-example.docx");
|
||||
doc.attachModule(module);
|
||||
doc.setData({}).compile();
|
||||
try {
|
||||
doc.render();
|
||||
} catch (e) {
|
||||
error = e;
|
||||
}
|
||||
expect(error).to.be.an("object");
|
||||
expect(error.message).to.equal("Multi error");
|
||||
expect(error.properties.errors.length).to.equal(9);
|
||||
expect(error.properties.errors[0].message).to.equal("foobar last_name");
|
||||
expect(error.properties.errors[1].message).to.equal("foobar first_name");
|
||||
expect(error.properties.errors[2].message).to.equal("foobar phone");
|
||||
});
|
||||
});
|
||||
|
||||
describe("Module should pass options to module.parse, module.postparse, module.render, module.postrender", function () {
|
||||
it("should pass filePath and contentType options", function () {
|
||||
const doc = createDoc("tag-example.docx");
|
||||
const filePaths = [];
|
||||
let renderFP = "",
|
||||
renderCT = "",
|
||||
postrenderFP = "",
|
||||
postrenderCT = "",
|
||||
postparseFP = "",
|
||||
postparseCT = "";
|
||||
const ct = [];
|
||||
|
||||
const module = {
|
||||
name: "Test module",
|
||||
requiredAPIVersion: "3.0.0",
|
||||
parse(a, options) {
|
||||
filePaths.push(options.filePath);
|
||||
ct.push(options.contentType);
|
||||
},
|
||||
postparse(a, options) {
|
||||
postparseFP = options.filePath;
|
||||
postparseCT = options.contentType;
|
||||
return a;
|
||||
},
|
||||
render(a, options) {
|
||||
renderFP = options.filePath;
|
||||
renderCT = options.contentType;
|
||||
},
|
||||
postrender(a, options) {
|
||||
postrenderFP = options.filePath;
|
||||
postrenderCT = options.contentType;
|
||||
return a;
|
||||
},
|
||||
};
|
||||
doc.attachModule(module);
|
||||
doc.setData({}).compile();
|
||||
doc.render();
|
||||
expect(renderFP).to.equal("word/document.xml");
|
||||
expect(renderCT).to.equal(
|
||||
"application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml"
|
||||
);
|
||||
expect(postparseFP).to.equal("word/document.xml");
|
||||
expect(postparseCT).to.equal(
|
||||
"application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml"
|
||||
);
|
||||
expect(postrenderFP).to.equal("word/document.xml");
|
||||
expect(postrenderCT).to.equal(
|
||||
"application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml"
|
||||
);
|
||||
|
||||
expect(filePaths).to.deep.equal([
|
||||
// Header appears 4 times because there are 4 tags in the header
|
||||
"word/header1.xml",
|
||||
"word/header1.xml",
|
||||
"word/header1.xml",
|
||||
"word/header1.xml",
|
||||
// Footer appears 3 times because there are 3 tags in the header
|
||||
"word/footer1.xml",
|
||||
"word/footer1.xml",
|
||||
"word/footer1.xml",
|
||||
// Document appears 2 times because there are 2 tags in the header
|
||||
"word/document.xml",
|
||||
"word/document.xml",
|
||||
]);
|
||||
|
||||
expect(ct).to.deep.equal([
|
||||
"application/vnd.openxmlformats-officedocument.wordprocessingml.header+xml",
|
||||
"application/vnd.openxmlformats-officedocument.wordprocessingml.header+xml",
|
||||
"application/vnd.openxmlformats-officedocument.wordprocessingml.header+xml",
|
||||
"application/vnd.openxmlformats-officedocument.wordprocessingml.header+xml",
|
||||
"application/vnd.openxmlformats-officedocument.wordprocessingml.footer+xml",
|
||||
"application/vnd.openxmlformats-officedocument.wordprocessingml.footer+xml",
|
||||
"application/vnd.openxmlformats-officedocument.wordprocessingml.footer+xml",
|
||||
"application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml",
|
||||
"application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml",
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("Module detachment", function () {
|
||||
it("should detach the module when the module does not support the document filetype", function () {
|
||||
let isModuleCalled = false;
|
||||
let isDetachedCalled = false;
|
||||
const module = {
|
||||
optionsTransformer(options) {
|
||||
isModuleCalled = true;
|
||||
return options;
|
||||
},
|
||||
on(eventName) {
|
||||
if (eventName === "detached") {
|
||||
isDetachedCalled = true;
|
||||
}
|
||||
},
|
||||
supportedFileTypes: ["pptx"],
|
||||
};
|
||||
createDocV4("tag-example.docx", { modules: [module] });
|
||||
expect(isDetachedCalled).to.equal(true);
|
||||
expect(isModuleCalled).to.equal(false);
|
||||
});
|
||||
});
|
||||
48
es6/tests/printy.js
Normal file
48
es6/tests/printy.js
Normal file
@ -0,0 +1,48 @@
|
||||
const repeat = require("./string-repeat");
|
||||
|
||||
module.exports = function printy(parsed, indent = 0) {
|
||||
let indentWasNegative = false;
|
||||
const result = parsed
|
||||
.reduce(function (output, p) {
|
||||
const splitted = p.value.split(/(?:\n|\r|\t)(?: |\r|\t)*/g);
|
||||
const value = splitted.join("");
|
||||
if (value === "") {
|
||||
return output;
|
||||
}
|
||||
if (p.type === "tag" && p.position === "end") {
|
||||
indent--;
|
||||
}
|
||||
if (indent < 0) {
|
||||
indentWasNegative = true;
|
||||
}
|
||||
const i =
|
||||
indent < 0 ? `(${indent})` : `(${indent})` + repeat(" ", indent);
|
||||
if (p.subparsed) {
|
||||
indent++;
|
||||
const stars = i.replace(/./g, "*");
|
||||
output += `\n${stars}START LOOP OF ${value}`;
|
||||
output += printy(p.subparsed, indent);
|
||||
output += `\n${stars}END LOOP OF ${value}`;
|
||||
indent--;
|
||||
} else if (p.type === "placeholder") {
|
||||
output += `\n${i.replace(/./g, "=")}{${value}}`;
|
||||
} else {
|
||||
output += `\n${i}${value}`;
|
||||
}
|
||||
if (p.type === "tag" && p.position === "start") {
|
||||
indent++;
|
||||
}
|
||||
return output;
|
||||
}, "")
|
||||
.split("\n")
|
||||
.map(function (line) {
|
||||
return line.replace(/[\s\uFEFF\xA0]+$/g, "");
|
||||
})
|
||||
.join("\n");
|
||||
if (indentWasNegative) {
|
||||
const err = new Error("Indent negative");
|
||||
err.properties = { result };
|
||||
throw err;
|
||||
}
|
||||
return result;
|
||||
};
|
||||
1
es6/tests/raw-complex-docx.xml
Normal file
1
es6/tests/raw-complex-docx.xml
Normal file
File diff suppressed because one or more lines are too long
61
es6/tests/raw-pptx.xml
Normal file
61
es6/tests/raw-pptx.xml
Normal file
@ -0,0 +1,61 @@
|
||||
<p:sp>
|
||||
<p:nvSpPr>
|
||||
<p:cNvPr id="37" name="CustomShape 2" />
|
||||
<p:cNvSpPr />
|
||||
<p:nvPr />
|
||||
</p:nvSpPr>
|
||||
<p:spPr>
|
||||
<a:xfrm>
|
||||
<a:off x="504000" y="1769040" />
|
||||
<a:ext cx="9071280" cy="4384080" />
|
||||
</a:xfrm>
|
||||
<a:prstGeom prst="rect">
|
||||
<a:avLst />
|
||||
</a:prstGeom>
|
||||
<a:noFill />
|
||||
<a:ln>
|
||||
<a:noFill />
|
||||
</a:ln>
|
||||
</p:spPr>
|
||||
<p:style>
|
||||
<a:lnRef idx="0" />
|
||||
<a:fillRef idx="0" />
|
||||
<a:effectRef idx="0" />
|
||||
<a:fontRef idx="minor" />
|
||||
</p:style>
|
||||
<p:txBody>
|
||||
<a:bodyPr lIns="0" rIns="0" tIns="0" bIns="0" anchor="ctr" />
|
||||
<a:p>
|
||||
<a:pPr algn="ctr">
|
||||
<a:lnSpc>
|
||||
<a:spcPct val="100000" />
|
||||
</a:lnSpc>
|
||||
</a:pPr>
|
||||
<a:r>
|
||||
<a:rPr b="0" lang="fr-FR" sz="3200" spc="-1" strike="noStrike">
|
||||
<a:solidFill>
|
||||
<a:srgbClr val="000000" />
|
||||
</a:solidFill>
|
||||
<a:uFill>
|
||||
<a:solidFill>
|
||||
<a:srgbClr val="ffffff" />
|
||||
</a:solidFill>
|
||||
</a:uFill>
|
||||
<a:latin typeface="Arial" />
|
||||
</a:rPr>
|
||||
<a:t>Hello World</a:t>
|
||||
</a:r>
|
||||
<a:endParaRPr b="0" lang="fr-FR" sz="1800" spc="-1" strike="noStrike">
|
||||
<a:solidFill>
|
||||
<a:srgbClr val="000000" />
|
||||
</a:solidFill>
|
||||
<a:uFill>
|
||||
<a:solidFill>
|
||||
<a:srgbClr val="ffffff" />
|
||||
</a:solidFill>
|
||||
</a:uFill>
|
||||
<a:latin typeface="Arial" />
|
||||
</a:endParaRPr>
|
||||
</a:p>
|
||||
</p:txBody>
|
||||
</p:sp>;
|
||||
260
es6/tests/speed.js
Normal file
260
es6/tests/speed.js
Normal file
@ -0,0 +1,260 @@
|
||||
"use strict";
|
||||
|
||||
const {
|
||||
createDoc,
|
||||
expect,
|
||||
createXmlTemplaterDocxNoRender,
|
||||
browserMatches,
|
||||
} = require("./utils");
|
||||
|
||||
const { times } = require("lodash");
|
||||
const inspectModule = require("../inspect-module.js");
|
||||
|
||||
describe("Speed test", function () {
|
||||
it("should be fast for simple tags", function () {
|
||||
const content = "<w:t>tag {age}</w:t>";
|
||||
const docs = [];
|
||||
for (let i = 0; i < 100; i++) {
|
||||
docs.push(createXmlTemplaterDocxNoRender(content, { tags: { age: 12 } }));
|
||||
}
|
||||
const time = new Date();
|
||||
for (let i = 0; i < 100; i++) {
|
||||
docs[i].render();
|
||||
}
|
||||
const duration = new Date() - time;
|
||||
expect(duration).to.be.below(400);
|
||||
});
|
||||
it("should be fast for simple tags with huge content", function () {
|
||||
let content = "<w:t>tag {age}</w:t>";
|
||||
let i;
|
||||
const result = [];
|
||||
for (i = 1; i <= 10000; i++) {
|
||||
result.push("bla");
|
||||
}
|
||||
const prepost = result.join("");
|
||||
content = prepost + content + prepost;
|
||||
const docs = [];
|
||||
for (i = 0; i < 20; i++) {
|
||||
docs.push(createXmlTemplaterDocxNoRender(content, { tags: { age: 12 } }));
|
||||
}
|
||||
const time = new Date();
|
||||
for (i = 0; i < 20; i++) {
|
||||
docs[i].render();
|
||||
}
|
||||
const duration = new Date() - time;
|
||||
expect(duration).to.be.below(400);
|
||||
});
|
||||
it("should be fast for loop tags", function () {
|
||||
const content = "<w:t>{#users}{name}{/users}</w:t>";
|
||||
const users = [];
|
||||
for (let i = 1; i <= 1000; i++) {
|
||||
users.push({ name: "foo" });
|
||||
}
|
||||
const doc = createXmlTemplaterDocxNoRender(content, { tags: { users } });
|
||||
const time = new Date();
|
||||
doc.render();
|
||||
const duration = new Date() - time;
|
||||
let maxDuration = 100;
|
||||
if (
|
||||
browserMatches(/firefox (55|60|64|65)/) ||
|
||||
browserMatches(/MicrosoftEdge (16)/)
|
||||
) {
|
||||
maxDuration = 150;
|
||||
}
|
||||
expect(duration).to.be.below(maxDuration);
|
||||
});
|
||||
it("should be fast for nested loop tags", function () {
|
||||
const result = [];
|
||||
for (let i = 1; i <= 300; i++) {
|
||||
result.push(`
|
||||
<w:proofErr w:type="spellEnd"/>
|
||||
<w:r w:rsidRPr="0000000">
|
||||
<w:rPr>
|
||||
<w:rFonts w:asciiTheme="minorHAnsi" w:eastAsia="Times New Roman" w:hAnsiTheme="minorHAnsi" w:cs="Arial"/>
|
||||
<w:sz w:val="22"/>
|
||||
<w:szCs w:val="22"/>
|
||||
<w:lang w:eastAsia="es-ES"/>
|
||||
</w:rPr>
|
||||
<w:t xml:space="preserve">{#users} Names : {user}</w:t>
|
||||
<w:t xml:space="preserve">{/}</w:t>
|
||||
</w:r>
|
||||
`);
|
||||
}
|
||||
const prepost = result.join("");
|
||||
const content = `<w:p><w:r><w:t>{#foo}</w:t></w:r>${prepost}<w:r><w:t>{/}</w:t></w:r></w:p>`;
|
||||
const users = [{ name: "John" }, { name: "Mary" }];
|
||||
const doc = createXmlTemplaterDocxNoRender(content, { tags: { users } });
|
||||
const time = new Date();
|
||||
doc.render();
|
||||
const duration = new Date() - time;
|
||||
let maxDuration = 300;
|
||||
if (
|
||||
browserMatches(/MicrosoftEdge (16|17|18)/) ||
|
||||
browserMatches(/internet explorer (10|11)/) ||
|
||||
browserMatches(/iphone 10.3/)
|
||||
) {
|
||||
maxDuration = 500;
|
||||
}
|
||||
expect(duration).to.be.below(maxDuration);
|
||||
});
|
||||
/* eslint-disable-next-line no-process-env */
|
||||
if (!process.env.FAST) {
|
||||
it("should not exceed call stack size for big document with a few rawxml tags", function () {
|
||||
this.timeout(30000);
|
||||
const result = [];
|
||||
const normalContent = "<w:p><w:r><w:t>foo</w:t></w:r></w:p>";
|
||||
const rawContent = "<w:p><w:r><w:t>{@raw}</w:t></w:r></w:p>";
|
||||
|
||||
for (let i = 1; i <= 30000; i++) {
|
||||
if (i % 100 === 1) {
|
||||
result.push(rawContent);
|
||||
}
|
||||
result.push(normalContent);
|
||||
}
|
||||
const content = result.join("");
|
||||
const users = [];
|
||||
const doc = createXmlTemplaterDocxNoRender(content, { tags: { users } });
|
||||
let now = new Date();
|
||||
doc.compile();
|
||||
const compileDuration = new Date() - now;
|
||||
if (typeof window === "undefined") {
|
||||
// Skip this assertion in the browser
|
||||
expect(compileDuration).to.be.below(3000);
|
||||
}
|
||||
now = new Date();
|
||||
doc.render();
|
||||
const renderDuration = new Date() - now;
|
||||
expect(renderDuration).to.be.below(2000);
|
||||
});
|
||||
|
||||
it("should not exceed call stack size for big document with many rawxml tags", function () {
|
||||
this.timeout(30000);
|
||||
const result = [];
|
||||
const normalContent = "<w:p><w:r><w:t>foo</w:t></w:r></w:p>";
|
||||
const rawContent = "<w:p><w:r><w:t>{@raw}</w:t></w:r></w:p>";
|
||||
|
||||
for (let i = 1; i <= 50000; i++) {
|
||||
if (i % 2 === 1) {
|
||||
result.push(rawContent);
|
||||
}
|
||||
result.push(normalContent);
|
||||
}
|
||||
const content = result.join("");
|
||||
const users = [];
|
||||
const doc = createXmlTemplaterDocxNoRender(content, { tags: { users } });
|
||||
let now = new Date();
|
||||
doc.compile();
|
||||
const compileDuration = new Date() - now;
|
||||
if (typeof window === "undefined") {
|
||||
// Skip this assertion in the browser
|
||||
expect(compileDuration).to.be.below(3000);
|
||||
}
|
||||
now = new Date();
|
||||
doc.render();
|
||||
const renderDuration = new Date() - now;
|
||||
expect(renderDuration).to.be.below(2000);
|
||||
});
|
||||
|
||||
describe("Inspect module", function () {
|
||||
it("should not be slow after multiple generations", function () {
|
||||
let duration = 0;
|
||||
const iModule = inspectModule();
|
||||
for (let i = 0; i < 10; i++) {
|
||||
const doc = createDoc("tag-product-loop.docx");
|
||||
const startTime = new Date();
|
||||
doc.attachModule(iModule);
|
||||
const data = {
|
||||
nom: "Doe",
|
||||
prenom: "John",
|
||||
telephone: "0652455478",
|
||||
description: "New Website",
|
||||
offre: times(20000, (i) => {
|
||||
return {
|
||||
prix: 1000 + i,
|
||||
nom: "Acme" + i,
|
||||
};
|
||||
}),
|
||||
};
|
||||
doc.setData(data);
|
||||
doc.compile();
|
||||
doc.render();
|
||||
duration += new Date() - startTime;
|
||||
}
|
||||
expect(duration).to.be.below(750);
|
||||
});
|
||||
});
|
||||
|
||||
it("should not be slow when having many loops with resolveData", function () {
|
||||
this.timeout(30000);
|
||||
const OldPromise = global.Promise;
|
||||
let resolveCount = 0;
|
||||
let allCount = 0;
|
||||
let parserCount = 0;
|
||||
let parserGetCount = 0;
|
||||
global.Promise = function (arg1, arg2) {
|
||||
return new OldPromise(arg1, arg2);
|
||||
};
|
||||
global.Promise.resolve = function (arg1) {
|
||||
resolveCount++;
|
||||
return OldPromise.resolve(arg1);
|
||||
};
|
||||
global.Promise.all = function (arg1) {
|
||||
allCount++;
|
||||
return OldPromise.all(arg1);
|
||||
};
|
||||
const doc = createDoc("multi-level.docx");
|
||||
doc.setOptions({
|
||||
paragraphLoop: true,
|
||||
parser: (tag) => {
|
||||
parserCount++;
|
||||
return {
|
||||
get: (scope) => {
|
||||
parserGetCount++;
|
||||
return scope[tag];
|
||||
},
|
||||
};
|
||||
},
|
||||
});
|
||||
let start = +new Date();
|
||||
doc.compile();
|
||||
const stepCompile = +new Date() - start;
|
||||
start = +new Date();
|
||||
const multiplier = 20;
|
||||
const total = Math.pow(multiplier, 3);
|
||||
const data = {
|
||||
l1: times(multiplier),
|
||||
l2: times(multiplier),
|
||||
l3: times(multiplier, () => ({ content: "Hello" })),
|
||||
};
|
||||
return doc.resolveData(data).then(function () {
|
||||
const stepResolve = +new Date() - start;
|
||||
start = +new Date();
|
||||
doc.render();
|
||||
const stepRender = +new Date() - start;
|
||||
expect(stepCompile).to.be.below(100);
|
||||
let maxResolveTime = 2000;
|
||||
if (browserMatches(/MicrosoftEdge (16|17|18)/)) {
|
||||
maxResolveTime = 20000;
|
||||
}
|
||||
if (browserMatches(/firefox 55/)) {
|
||||
maxResolveTime = 4000;
|
||||
}
|
||||
expect(stepResolve).to.be.below(maxResolveTime);
|
||||
let maxRenderTime = 1000;
|
||||
if (
|
||||
browserMatches(/iphone 10.3/) ||
|
||||
browserMatches(/MicrosoftEdge (16|17|18)/)
|
||||
) {
|
||||
maxRenderTime = 2000;
|
||||
}
|
||||
expect(stepRender).to.be.below(maxRenderTime);
|
||||
expect(parserCount).to.be.equal(4);
|
||||
// 20**3 + 20**2 *3 + 20 * 2 + 1 = 9241
|
||||
expect(parserGetCount).to.be.equal(9241);
|
||||
expect(resolveCount).to.be.within(total, total * 1.2);
|
||||
expect(allCount).to.be.within(total, total * 1.2);
|
||||
global.Promise = OldPromise;
|
||||
});
|
||||
});
|
||||
}
|
||||
});
|
||||
40
es6/tests/string-repeat.js
Normal file
40
es6/tests/string-repeat.js
Normal file
@ -0,0 +1,40 @@
|
||||
function repeat(input, count) {
|
||||
if (input == null) {
|
||||
throw new TypeError("can't convert " + input + " to object");
|
||||
}
|
||||
|
||||
let str = "" + input;
|
||||
// To convert string to integer.
|
||||
count = +count;
|
||||
|
||||
if (count < 0) {
|
||||
throw new RangeError("repeat count must be non-negative");
|
||||
}
|
||||
|
||||
if (count === Infinity) {
|
||||
throw new RangeError("repeat count must be less than infinity");
|
||||
}
|
||||
|
||||
count = Math.floor(count);
|
||||
if (str.length === 0 || count === 0) {
|
||||
return "";
|
||||
}
|
||||
|
||||
// Ensuring count is a 31-bit integer allows us to heavily optimize the
|
||||
// main part. But anyway, most current (August 2014) browsers can't handle
|
||||
// strings 1 << 28 chars or longer, so:
|
||||
if (str.length * count >= 1 << 28) {
|
||||
throw new RangeError("repeat count must not overflow maximum string size");
|
||||
}
|
||||
|
||||
const maxCount = str.length * count;
|
||||
count = Math.floor(Math.log(count) / Math.log(2));
|
||||
while (count) {
|
||||
str += str;
|
||||
count--;
|
||||
}
|
||||
str += str.substring(0, maxCount - str.length);
|
||||
return str;
|
||||
}
|
||||
|
||||
module.exports = repeat;
|
||||
677
es6/tests/utils.js
Normal file
677
es6/tests/utils.js
Normal file
@ -0,0 +1,677 @@
|
||||
const path = require("path");
|
||||
const chai = require("chai");
|
||||
const { expect } = chai;
|
||||
const PizZip = require("pizzip");
|
||||
const fs = require("fs");
|
||||
const { get, unset, omit, uniq } = require("lodash");
|
||||
const errorLogger = require("../error-logger");
|
||||
const diff = require("diff");
|
||||
const AssertionModule = require("./assertion-module.js");
|
||||
|
||||
const Docxtemplater = require("../docxtemplater.js");
|
||||
const { first } = require("../utils.js");
|
||||
const xmlPrettify = require("./xml-prettify");
|
||||
let countFiles = 1;
|
||||
let allStarted = false;
|
||||
let examplesDirectory;
|
||||
const documentCache = {};
|
||||
const imageData = {};
|
||||
const emptyNamespace = /xmlns:[a-z0-9]+=""/;
|
||||
|
||||
function unifiedDiff(actual, expected) {
|
||||
const indent = " ";
|
||||
function cleanUp(line) {
|
||||
const firstChar = first(line);
|
||||
if (firstChar === "+") {
|
||||
return indent + line;
|
||||
}
|
||||
if (firstChar === "-") {
|
||||
return indent + line;
|
||||
}
|
||||
if (line.match(/@@/)) {
|
||||
return "--";
|
||||
}
|
||||
if (line.match(/\\ No newline/)) {
|
||||
return null;
|
||||
}
|
||||
return indent + line;
|
||||
}
|
||||
function notBlank(line) {
|
||||
return typeof line !== "undefined" && line !== null;
|
||||
}
|
||||
const msg = diff.createPatch("string", actual, expected);
|
||||
const lines = msg.split("\n").splice(5);
|
||||
return (
|
||||
"\n " +
|
||||
"+ expected" +
|
||||
" " +
|
||||
"- actual" +
|
||||
"\n\n" +
|
||||
lines.map(cleanUp).filter(notBlank).join("\n")
|
||||
);
|
||||
}
|
||||
|
||||
function isNode12() {
|
||||
return process && process.version && process.version.indexOf("v12") === 0;
|
||||
}
|
||||
|
||||
function walk(dir) {
|
||||
let results = [];
|
||||
const list = fs.readdirSync(dir);
|
||||
list.forEach(function (file) {
|
||||
if (file.indexOf(".") === 0) {
|
||||
return;
|
||||
}
|
||||
file = dir + "/" + file;
|
||||
const stat = fs.statSync(file);
|
||||
if (stat && stat.isDirectory()) {
|
||||
results = results.concat(walk(file));
|
||||
} else {
|
||||
results.push(file);
|
||||
}
|
||||
});
|
||||
return results;
|
||||
}
|
||||
|
||||
function createXmlTemplaterDocxNoRender(content, options = {}) {
|
||||
const doc = makeDocx("temporary.docx", content);
|
||||
doc.setOptions(options);
|
||||
doc.setData(options.tags);
|
||||
return doc;
|
||||
}
|
||||
|
||||
function createXmlTemplaterDocx(content, options = {}) {
|
||||
const doc = makeDocx("temporary.docx", content);
|
||||
doc.setOptions(options);
|
||||
doc.setData(options.tags);
|
||||
doc.render();
|
||||
return doc;
|
||||
}
|
||||
|
||||
function writeFile(expectedName, zip) {
|
||||
const writeFile = path.resolve(examplesDirectory, "..", expectedName);
|
||||
if (fs.writeFileSync) {
|
||||
fs.writeFileSync(
|
||||
writeFile,
|
||||
zip.generate({ type: "nodebuffer", compression: "DEFLATE" })
|
||||
);
|
||||
}
|
||||
if (typeof window !== "undefined" && window.saveAs) {
|
||||
const out = zip.generate({
|
||||
type: "blob",
|
||||
mimeType:
|
||||
"application/vnd.openxmlformats-officedocument.wordprocessingml.document",
|
||||
compression: "DEFLATE",
|
||||
});
|
||||
saveAs(out, expectedName); // comment to see the error
|
||||
}
|
||||
}
|
||||
function unlinkFile(expectedName) {
|
||||
const writeFile = path.resolve(examplesDirectory, "..", expectedName);
|
||||
if (fs.unlinkSync) {
|
||||
try {
|
||||
fs.unlinkSync(writeFile);
|
||||
} catch (e) {
|
||||
if (e.code !== "ENOENT") {
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* eslint-disable no-console */
|
||||
function shouldBeSame(options) {
|
||||
const zip = options.doc.getZip();
|
||||
const { expectedName } = options;
|
||||
let expectedZip;
|
||||
|
||||
try {
|
||||
expectedZip = documentCache[expectedName].zip;
|
||||
} catch (e) {
|
||||
writeFile(expectedName, zip);
|
||||
console.log(
|
||||
JSON.stringify({ msg: "Expected file does not exists", expectedName })
|
||||
);
|
||||
throw e;
|
||||
}
|
||||
|
||||
try {
|
||||
uniq(Object.keys(zip.files).concat(Object.keys(expectedZip.files))).map(
|
||||
function (filePath) {
|
||||
const suffix = `for "${filePath}"`;
|
||||
expect(expectedZip.files[filePath]).to.be.an(
|
||||
"object",
|
||||
`The file ${filePath} doesn't exist on ${expectedName}`
|
||||
);
|
||||
expect(zip.files[filePath]).to.be.an(
|
||||
"object",
|
||||
`The file ${filePath} doesn't exist on generated file`
|
||||
);
|
||||
expect(zip.files[filePath].name).to.be.equal(
|
||||
expectedZip.files[filePath].name,
|
||||
`Name differs ${suffix}`
|
||||
);
|
||||
expect(zip.files[filePath].options.dir).to.be.equal(
|
||||
expectedZip.files[filePath].options.dir,
|
||||
`IsDir differs ${suffix}`
|
||||
);
|
||||
const text1 = zip.files[filePath].asText().replace(/\n|\t/g, "");
|
||||
const text2 = expectedZip.files[filePath]
|
||||
.asText()
|
||||
.replace(/\n|\t/g, "");
|
||||
if (endsWith(filePath, "/")) {
|
||||
return;
|
||||
}
|
||||
if (filePath.indexOf(".png") !== -1) {
|
||||
expect(text1.length).to.be.equal(
|
||||
text2.length,
|
||||
`Content differs ${suffix}`
|
||||
);
|
||||
expect(text1).to.be.equal(text2, `Content differs ${suffix}`);
|
||||
} else {
|
||||
expect(text1).to.not.match(
|
||||
emptyNamespace,
|
||||
`The file ${filePath} has empty namespaces`
|
||||
);
|
||||
expect(text2).to.not.match(
|
||||
emptyNamespace,
|
||||
`The file ${filePath} has empty namespaces`
|
||||
);
|
||||
if (text1 === text2) {
|
||||
return;
|
||||
}
|
||||
const pText1 = xmlPrettify(text1, options);
|
||||
const pText2 = xmlPrettify(text2, options);
|
||||
|
||||
if (pText1 !== pText2) {
|
||||
const pd = unifiedDiff(pText1, pText2);
|
||||
expect(pText1).to.be.equal(
|
||||
pText2,
|
||||
"Content differs \n" + suffix + "\n" + pd
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
);
|
||||
} catch (e) {
|
||||
writeFile(expectedName, zip);
|
||||
console.log(
|
||||
JSON.stringify({
|
||||
msg: "Expected file differs from actual file",
|
||||
expectedName,
|
||||
})
|
||||
);
|
||||
throw e;
|
||||
}
|
||||
unlinkFile(expectedName);
|
||||
}
|
||||
/* eslint-enable no-console */
|
||||
|
||||
function checkLength(e, expectedError, propertyPath) {
|
||||
const propertyPathLength = propertyPath + "Length";
|
||||
const property = get(e, propertyPath);
|
||||
const expectedPropertyLength = get(expectedError, propertyPathLength);
|
||||
if (property && expectedPropertyLength) {
|
||||
expect(expectedPropertyLength).to.be.a(
|
||||
"number",
|
||||
JSON.stringify(expectedError.properties)
|
||||
);
|
||||
expect(expectedPropertyLength).to.equal(property.length);
|
||||
unset(e, propertyPath);
|
||||
unset(expectedError, propertyPathLength);
|
||||
}
|
||||
}
|
||||
|
||||
function cleanRecursive(arr) {
|
||||
arr.forEach(function (p) {
|
||||
delete p.lIndex;
|
||||
delete p.endLindex;
|
||||
delete p.offset;
|
||||
delete p.raw;
|
||||
if (p.subparsed) {
|
||||
cleanRecursive(p.subparsed);
|
||||
}
|
||||
if (p.value && p.value.forEach) {
|
||||
p.value.forEach(cleanRecursive);
|
||||
}
|
||||
if (p.expanded) {
|
||||
p.expanded.forEach(cleanRecursive);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function cleanError(e, expectedError) {
|
||||
const message = e.message;
|
||||
e = omit(e, ["line", "sourceURL", "stack"]);
|
||||
e.message = message;
|
||||
if (expectedError.properties && e.properties) {
|
||||
if (expectedError.properties.explanation != null) {
|
||||
const e1 = e.properties.explanation;
|
||||
const e2 = expectedError.properties.explanation;
|
||||
expect(e1).to.be.deep.equal(
|
||||
e2,
|
||||
`Explanations differ '${e1}' != '${e2}': for ${JSON.stringify(
|
||||
expectedError
|
||||
)}`
|
||||
);
|
||||
}
|
||||
delete e.properties.explanation;
|
||||
delete expectedError.properties.explanation;
|
||||
if (e.properties.postparsed) {
|
||||
e.properties.postparsed.forEach(function (p) {
|
||||
delete p.lIndex;
|
||||
delete p.endLindex;
|
||||
delete p.offset;
|
||||
});
|
||||
}
|
||||
if (e.properties.rootError) {
|
||||
expect(
|
||||
e.properties.rootError,
|
||||
JSON.stringify(e.properties)
|
||||
).to.be.instanceOf(Error);
|
||||
expect(
|
||||
expectedError.properties.rootError,
|
||||
JSON.stringify(expectedError.properties)
|
||||
).to.be.instanceOf(Object, "expectedError doesn't have a rootError");
|
||||
if (expectedError) {
|
||||
expect(e.properties.rootError.message).to.equal(
|
||||
expectedError.properties.rootError.message,
|
||||
"rootError.message"
|
||||
);
|
||||
}
|
||||
delete e.properties.rootError;
|
||||
delete expectedError.properties.rootError;
|
||||
}
|
||||
if (expectedError.properties.offset != null) {
|
||||
const o1 = e.properties.offset;
|
||||
const o2 = expectedError.properties.offset;
|
||||
// offset can be arrays, so deep compare
|
||||
expect(o1).to.be.deep.equal(
|
||||
o2,
|
||||
`Offset differ ${o1} != ${o2}: for ${JSON.stringify(expectedError)}`
|
||||
);
|
||||
}
|
||||
delete expectedError.properties.offset;
|
||||
delete e.properties.offset;
|
||||
checkLength(e, expectedError, "properties.paragraphParts");
|
||||
checkLength(e, expectedError, "properties.postparsed");
|
||||
checkLength(e, expectedError, "properties.parsed");
|
||||
}
|
||||
if (e.stack && expectedError) {
|
||||
expect(e.stack).to.contain("Error: " + expectedError.message);
|
||||
}
|
||||
delete e.stack;
|
||||
return e;
|
||||
}
|
||||
|
||||
function wrapMultiError(error) {
|
||||
const type = Object.prototype.toString.call(error);
|
||||
let errors;
|
||||
if (type === "[object Array]") {
|
||||
errors = error;
|
||||
} else {
|
||||
errors = [error];
|
||||
}
|
||||
|
||||
return {
|
||||
name: "TemplateError",
|
||||
message: "Multi error",
|
||||
properties: {
|
||||
id: "multi_error",
|
||||
errors,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function jsonifyError(e) {
|
||||
return JSON.parse(
|
||||
JSON.stringify(e, function (key, value) {
|
||||
if (value instanceof Promise) {
|
||||
return {};
|
||||
}
|
||||
return value;
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
function errorVerifier(e, type, expectedError) {
|
||||
expect(e, "No error has been thrown").not.to.be.equal(null);
|
||||
const toShowOnFail = e.stack;
|
||||
expect(e, toShowOnFail).to.be.instanceOf(Error);
|
||||
expect(e, toShowOnFail).to.be.instanceOf(type);
|
||||
expect(e, toShowOnFail).to.be.an("object");
|
||||
expect(e, toShowOnFail).to.have.property("properties");
|
||||
expect(e.properties, toShowOnFail).to.be.an("object");
|
||||
if (type.name && type.name !== "XTInternalError") {
|
||||
expect(e.properties, toShowOnFail).to.have.property("explanation");
|
||||
expect(e.properties.explanation, toShowOnFail).to.be.a("string");
|
||||
expect(e.properties.explanation, toShowOnFail).to.be.a("string");
|
||||
}
|
||||
expect(e.properties, toShowOnFail).to.have.property("id");
|
||||
expect(e.properties.id, toShowOnFail).to.be.a("string");
|
||||
e = cleanError(e, expectedError);
|
||||
if (e.properties.errors) {
|
||||
const msg =
|
||||
"expected : \n" +
|
||||
JSON.stringify(expectedError.properties.errors) +
|
||||
"\nactual : \n" +
|
||||
JSON.stringify(e.properties.errors);
|
||||
expect(expectedError.properties.errors).to.be.an("array", msg);
|
||||
const l1 = e.properties.errors.length;
|
||||
const l2 = expectedError.properties.errors.length;
|
||||
expect(l1).to.equal(
|
||||
l2,
|
||||
`Expected to have the same amount of e.properties.errors ${l1} !== ${l2} ` +
|
||||
msg
|
||||
);
|
||||
e.properties.errors = e.properties.errors.map(function (suberror, i) {
|
||||
const cleaned = cleanError(suberror, expectedError.properties.errors[i]);
|
||||
const jsonified = jsonifyError(cleaned);
|
||||
return jsonified;
|
||||
});
|
||||
}
|
||||
|
||||
const realError = jsonifyError(e);
|
||||
expect(realError).to.be.deep.equal(expectedError);
|
||||
}
|
||||
|
||||
function expectToThrowAsync(fn, type, expectedError) {
|
||||
return Promise.resolve(null)
|
||||
.then(function () {
|
||||
const r = fn();
|
||||
return r.then(function () {
|
||||
return null;
|
||||
});
|
||||
})
|
||||
.catch(function (error) {
|
||||
return error;
|
||||
})
|
||||
.then(function (e) {
|
||||
return errorVerifier(e, type, expectedError);
|
||||
});
|
||||
}
|
||||
|
||||
function expectToThrow(fn, type, expectedError) {
|
||||
let err = null;
|
||||
try {
|
||||
fn();
|
||||
} catch (e) {
|
||||
err = e;
|
||||
}
|
||||
errorVerifier(err, type, expectedError);
|
||||
return err;
|
||||
}
|
||||
|
||||
function load(name, content, obj) {
|
||||
const zip = new PizZip(content);
|
||||
obj[name] = new Docxtemplater();
|
||||
obj[name].loadZip(zip);
|
||||
obj[name].loadedName = name;
|
||||
obj[name].loadedContent = content;
|
||||
return obj[name];
|
||||
}
|
||||
function loadDocument(name, content) {
|
||||
return load(name, content, documentCache);
|
||||
}
|
||||
|
||||
function cacheDocument(name, content) {
|
||||
const zip = new PizZip(content);
|
||||
documentCache[name] = { loadedName: name, loadedContent: content, zip };
|
||||
return documentCache[name];
|
||||
}
|
||||
function loadImage(name, content) {
|
||||
imageData[name] = content;
|
||||
}
|
||||
|
||||
function loadFile(name, callback) {
|
||||
if (fs.readFileSync) {
|
||||
const path = require("path");
|
||||
const buffer = fs.readFileSync(
|
||||
path.join(examplesDirectory, name),
|
||||
"binary"
|
||||
);
|
||||
return callback(null, name, buffer);
|
||||
}
|
||||
return PizZipUtils.getBinaryContent("../examples/" + name, function (
|
||||
err,
|
||||
data
|
||||
) {
|
||||
if (err) {
|
||||
return callback(err);
|
||||
}
|
||||
return callback(null, name, data);
|
||||
});
|
||||
}
|
||||
|
||||
function unhandledRejectionHandler(reason) {
|
||||
throw reason;
|
||||
}
|
||||
|
||||
let startFunction;
|
||||
function setStartFunction(sf) {
|
||||
allStarted = false;
|
||||
countFiles = 1;
|
||||
startFunction = sf;
|
||||
|
||||
if (typeof window !== "undefined" && window.addEventListener) {
|
||||
window.addEventListener("unhandledrejection", unhandledRejectionHandler);
|
||||
} else {
|
||||
process.on("unhandledRejection", unhandledRejectionHandler);
|
||||
}
|
||||
}
|
||||
|
||||
function endLoadFile(change) {
|
||||
change = change || 0;
|
||||
countFiles += change;
|
||||
if (countFiles === 0 && allStarted === true) {
|
||||
const result = startFunction();
|
||||
if (typeof window !== "undefined") {
|
||||
return window.mocha.run(() => {
|
||||
const elemDiv = window.document.getElementById("status");
|
||||
elemDiv.textContent = "FINISHED";
|
||||
document.body.appendChild(elemDiv);
|
||||
});
|
||||
}
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
||||
function endsWith(str, suffix) {
|
||||
return str.indexOf(suffix, str.length - suffix.length) !== -1;
|
||||
}
|
||||
function endsWithOne(str, suffixes) {
|
||||
return suffixes.some(function (suffix) {
|
||||
return endsWith(str, suffix);
|
||||
});
|
||||
}
|
||||
function startsWith(str, suffix) {
|
||||
return str.indexOf(suffix) === 0;
|
||||
}
|
||||
|
||||
/* eslint-disable no-console */
|
||||
function start() {
|
||||
afterEach(function () {
|
||||
if (
|
||||
this.currentTest.state === "failed" &&
|
||||
this.currentTest.err.properties
|
||||
) {
|
||||
errorLogger(this.currentTest.err);
|
||||
}
|
||||
});
|
||||
/* eslint-disable import/no-unresolved */
|
||||
const fileNames = require("./filenames.js");
|
||||
/* eslint-enable import/no-unresolved */
|
||||
fileNames.forEach(function (fullFileName) {
|
||||
const fileName = fullFileName.replace(examplesDirectory + "/", "");
|
||||
let callback;
|
||||
if (startsWith(fileName, ".") || startsWith(fileName, "~")) {
|
||||
return;
|
||||
}
|
||||
if (
|
||||
endsWithOne(fileName, [
|
||||
".dotx",
|
||||
".dotm",
|
||||
".docx",
|
||||
".docm",
|
||||
".pptm",
|
||||
".pptx",
|
||||
".xlsx",
|
||||
])
|
||||
) {
|
||||
callback = cacheDocument;
|
||||
}
|
||||
if (!callback) {
|
||||
callback = loadImage;
|
||||
}
|
||||
countFiles++;
|
||||
loadFile(fileName, (e, name, buffer) => {
|
||||
if (e) {
|
||||
console.log(e);
|
||||
throw e;
|
||||
}
|
||||
endLoadFile(-1);
|
||||
callback(name, buffer);
|
||||
});
|
||||
});
|
||||
allStarted = true;
|
||||
endLoadFile(-1);
|
||||
}
|
||||
/* eslint-disable no-console */
|
||||
|
||||
function setExamplesDirectory(ed) {
|
||||
examplesDirectory = ed;
|
||||
if (fs && fs.writeFileSync) {
|
||||
const fileNames = walk(examplesDirectory).map(function (f) {
|
||||
return f.replace(examplesDirectory + "/", "");
|
||||
});
|
||||
fs.writeFileSync(
|
||||
path.resolve(__dirname, "filenames.js"),
|
||||
"module.exports=" + JSON.stringify(fileNames)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
function removeSpaces(text) {
|
||||
return text.replace(/\n|\t/g, "");
|
||||
}
|
||||
|
||||
const contentTypeContent = `<?xml version="1.0" encoding="utf-8"?>
|
||||
<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types">
|
||||
<Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/>
|
||||
<Default Extension="xml" ContentType="application/xml"/>
|
||||
<Override PartName="/word/document.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml"/>
|
||||
</Types>`;
|
||||
|
||||
function makeDocx(name, content) {
|
||||
const zip = new PizZip();
|
||||
zip.file("word/document.xml", content, { createFolders: true });
|
||||
zip.file("[Content_Types].xml", contentTypeContent);
|
||||
return load(name, zip.generate({ type: "string" }), documentCache);
|
||||
}
|
||||
|
||||
function createDoc(name) {
|
||||
const doc = loadDocument(name, documentCache[name].loadedContent);
|
||||
/* eslint-disable-next-line no-process-env */
|
||||
if (!process.env.FAST) {
|
||||
doc.attachModule(new AssertionModule());
|
||||
}
|
||||
return doc;
|
||||
}
|
||||
|
||||
function createDocV4(name, options) {
|
||||
const zip = getZip(name);
|
||||
/* eslint-disable-next-line no-process-env */
|
||||
if (!process.env.FAST) {
|
||||
options = options || {};
|
||||
if (!options.modules || options.modules instanceof Array) {
|
||||
options.modules = options.modules || [];
|
||||
options.modules.push(new AssertionModule());
|
||||
}
|
||||
}
|
||||
return new Docxtemplater(zip, options);
|
||||
}
|
||||
|
||||
function getZip(name) {
|
||||
return new PizZip(documentCache[name].loadedContent);
|
||||
}
|
||||
|
||||
function getLoadedContent(name) {
|
||||
return documentCache[name].loadedContent;
|
||||
}
|
||||
|
||||
function getContent(doc) {
|
||||
return doc.getZip().files["word/document.xml"].asText();
|
||||
}
|
||||
|
||||
function resolveSoon(data) {
|
||||
return new Promise(function (resolve) {
|
||||
setTimeout(function () {
|
||||
resolve(data);
|
||||
}, 1);
|
||||
});
|
||||
}
|
||||
|
||||
function rejectSoon(data) {
|
||||
return new Promise(function (resolve, reject) {
|
||||
setTimeout(function () {
|
||||
reject(data);
|
||||
}, 1);
|
||||
});
|
||||
}
|
||||
|
||||
function getParameterByName(name) {
|
||||
if (typeof window === "undefined") {
|
||||
return null;
|
||||
}
|
||||
const url = window.location.href;
|
||||
name = name.replace(/[\[\]]/g, "\\$&");
|
||||
const regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
|
||||
results = regex.exec(url);
|
||||
if (!results) {
|
||||
return null;
|
||||
}
|
||||
if (!results[2]) {
|
||||
return "";
|
||||
}
|
||||
return decodeURIComponent(results[2].replace(/\+/g, " "));
|
||||
}
|
||||
|
||||
function browserMatches(regex) {
|
||||
const currentBrowser = getParameterByName("browser");
|
||||
if (currentBrowser === null) {
|
||||
return false;
|
||||
}
|
||||
return regex.test(currentBrowser);
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
chai,
|
||||
cleanError,
|
||||
cleanRecursive,
|
||||
createDoc,
|
||||
getLoadedContent,
|
||||
createXmlTemplaterDocx,
|
||||
createXmlTemplaterDocxNoRender,
|
||||
expect,
|
||||
expectToThrow,
|
||||
expectToThrowAsync,
|
||||
getContent,
|
||||
imageData,
|
||||
loadDocument,
|
||||
loadFile,
|
||||
loadImage,
|
||||
makeDocx,
|
||||
removeSpaces,
|
||||
setExamplesDirectory,
|
||||
setStartFunction,
|
||||
shouldBeSame,
|
||||
resolveSoon,
|
||||
rejectSoon,
|
||||
start,
|
||||
wrapMultiError,
|
||||
isNode12,
|
||||
createDocV4,
|
||||
getZip,
|
||||
getParameterByName,
|
||||
browserMatches,
|
||||
};
|
||||
141
es6/tests/xml-matcher.js
Normal file
141
es6/tests/xml-matcher.js
Normal file
@ -0,0 +1,141 @@
|
||||
const xmlMatcher = require("../xml-matcher.js");
|
||||
const { expect } = require("./utils");
|
||||
const xmlprettify = require("./xml-prettify");
|
||||
|
||||
describe("XmlMatcher", function () {
|
||||
it("should work with simple tag", function () {
|
||||
const matcher = xmlMatcher("<w:t>Text</w:t>", ["w:t"]);
|
||||
expect(matcher.matches[0].array[0]).to.be.equal("<w:t>Text</w:t>");
|
||||
expect(matcher.matches[0].array[1]).to.be.equal("<w:t>");
|
||||
expect(matcher.matches[0].array[2]).to.be.equal("Text");
|
||||
expect(matcher.matches[0].offset).to.be.equal(0);
|
||||
});
|
||||
|
||||
it("should work with multiple tags", function () {
|
||||
const matcher = xmlMatcher("<w:t>Text</w:t> TAG <w:t>Text2</w:t>", ["w:t"]);
|
||||
expect(matcher.matches[1].array[0]).to.be.equal("<w:t>Text2</w:t>");
|
||||
expect(matcher.matches[1].array[1]).to.be.equal("<w:t>");
|
||||
expect(matcher.matches[1].array[2]).to.be.equal("Text2");
|
||||
expect(matcher.matches[1].offset).to.be.equal(20);
|
||||
});
|
||||
|
||||
it("should work with selfclosing tag", function () {
|
||||
const matcher = xmlMatcher(' <w:spacing w:before="0" w:after="200"/> ', [
|
||||
"w:spacing",
|
||||
]);
|
||||
expect(matcher.matches.length).to.be.equal(1);
|
||||
expect(matcher.matches[0].array[0]).to.be.equal(
|
||||
'<w:spacing w:before="0" w:after="200"/>'
|
||||
);
|
||||
});
|
||||
|
||||
it("should work with no tag, with w:t", function () {
|
||||
const matcher = xmlMatcher("Text1</w:t><w:t>Text2", ["w:t"]);
|
||||
expect(matcher.matches[0].array[0]).to.be.equal("Text1");
|
||||
expect(matcher.matches[0].array[1]).to.be.equal("");
|
||||
expect(matcher.matches[0].array[2]).to.be.equal("Text1");
|
||||
expect(matcher.matches[0].offset).to.be.equal(0);
|
||||
|
||||
expect(matcher.matches[1].array[0]).to.be.equal("<w:t>Text2");
|
||||
expect(matcher.matches[1].array[1]).to.be.equal("<w:t>");
|
||||
expect(matcher.matches[1].array[2]).to.be.equal("Text2");
|
||||
expect(matcher.matches[1].offset).to.be.equal(11);
|
||||
});
|
||||
|
||||
it("should work with no tag, no w:t", function () {
|
||||
const matcher = xmlMatcher("Text1", ["w:t"]);
|
||||
expect(matcher.matches[0].array[0]).to.be.equal("Text1");
|
||||
expect(matcher.matches[0].array[1]).to.be.equal("");
|
||||
expect(matcher.matches[0].array[2]).to.be.equal("Text1");
|
||||
expect(matcher.matches[0].offset).to.be.equal(0);
|
||||
});
|
||||
|
||||
it("should not match with no </w:t> starter", function () {
|
||||
const matcher = xmlMatcher("TAG<w:t>Text1</w:t>", ["w:t"]);
|
||||
expect(matcher.matches[0].array[0]).to.be.equal("<w:t>Text1</w:t>");
|
||||
expect(matcher.matches[0].array[1]).to.be.equal("<w:t>");
|
||||
expect(matcher.matches[0].array[2]).to.be.equal("Text1");
|
||||
expect(matcher.matches[0].offset).to.be.equal(3);
|
||||
});
|
||||
|
||||
it("should not match with no <w:t> ender", function () {
|
||||
const matcher = xmlMatcher("<w:t>Text1</w:t>TAG", ["w:t"]);
|
||||
expect(matcher.matches.length).to.be.equal(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe("XML prettify", function () {
|
||||
it("should sort attributes", function () {
|
||||
const str =
|
||||
'<?xml version="1.0" encoding="UTF-8" standalone="yes"?><foo zanc="bar" bar="foo"></foo><foo zak="foo" uk="bar"/>';
|
||||
|
||||
const prettified = xmlprettify(str);
|
||||
expect(prettified).to
|
||||
.equal(`<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
|
||||
<foo bar="foo" zanc="bar">
|
||||
</foo>
|
||||
<foo uk="bar" zak="foo"/>
|
||||
`);
|
||||
});
|
||||
it("should remove space inside tags", function () {
|
||||
const str = `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
|
||||
<sst count="9" uniqueCount="9" xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main">
|
||||
<si >
|
||||
<t xml:space="preserve">Property</t>
|
||||
</si>
|
||||
<si >
|
||||
<t xml:space="preserve">0 $</t>
|
||||
</si>
|
||||
<si >
|
||||
<t xml:space="preserve"/>
|
||||
</si>
|
||||
<si>
|
||||
<t xml:space="preserve"/>
|
||||
</si>
|
||||
<si>
|
||||
<t xml:space="preserve"/>
|
||||
</si>
|
||||
<si>
|
||||
<t xml:space="preserve"/>
|
||||
</si >
|
||||
<si>
|
||||
<t xml:space="preserve"/>
|
||||
</si>
|
||||
<si>
|
||||
<t xml:space="preserve"/>
|
||||
</si>
|
||||
<si />
|
||||
</sst>`;
|
||||
const prettified = xmlprettify(str);
|
||||
expect(prettified).to
|
||||
.equal(`<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
|
||||
<sst count="9" uniqueCount="9" xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main">
|
||||
<si>
|
||||
<t xml:space="preserve">Property</t>
|
||||
</si>
|
||||
<si>
|
||||
<t xml:space="preserve">0 $</t>
|
||||
</si>
|
||||
<si>
|
||||
<t xml:space="preserve"/>
|
||||
</si>
|
||||
<si>
|
||||
<t xml:space="preserve"/>
|
||||
</si>
|
||||
<si>
|
||||
<t xml:space="preserve"/>
|
||||
</si>
|
||||
<si>
|
||||
<t xml:space="preserve"/>
|
||||
</si>
|
||||
<si>
|
||||
<t xml:space="preserve"/>
|
||||
</si>
|
||||
<si>
|
||||
<t xml:space="preserve"/>
|
||||
</si>
|
||||
<si/>
|
||||
</sst>
|
||||
`);
|
||||
});
|
||||
});
|
||||
161
es6/tests/xml-prettify.js
Normal file
161
es6/tests/xml-prettify.js
Normal file
@ -0,0 +1,161 @@
|
||||
/* eslint-disable complexity */
|
||||
const repeat = require("./string-repeat");
|
||||
|
||||
function getIndent(indent) {
|
||||
return repeat(" ", indent);
|
||||
}
|
||||
|
||||
function attributeSorter(ln) {
|
||||
const aRegex = /<[A-Za-z0-9:]+ (.*?)([/ ]*)>/;
|
||||
let rest;
|
||||
if (aRegex.test(ln)) {
|
||||
rest = ln.replace(aRegex, "$1");
|
||||
}
|
||||
const attrRegex = / *([a-zA-Z0-9:]+)="([^"]+)"/g;
|
||||
let match = attrRegex.exec(rest);
|
||||
const attributes = [];
|
||||
while (match != null) {
|
||||
// matched text: match[0]
|
||||
// match start: match.index
|
||||
// capturing group n: match[n]
|
||||
attributes.push({ key: match[1], value: match[2] });
|
||||
match = attrRegex.exec(rest);
|
||||
}
|
||||
attributes.sort(function (a1, a2) {
|
||||
if (a1.key === a2.key) {
|
||||
return 0;
|
||||
}
|
||||
return a1.key > a2.key ? 1 : -1;
|
||||
});
|
||||
const stringifiedAttrs = attributes
|
||||
.map(function (attribute) {
|
||||
return `${attribute.key}="${attribute.value}"`;
|
||||
})
|
||||
.join(" ");
|
||||
if (rest != null) {
|
||||
ln = ln.replace(rest, stringifiedAttrs).replace(/ +>/, ">");
|
||||
}
|
||||
return ln;
|
||||
}
|
||||
|
||||
function xmlprettify(xml) {
|
||||
let result = "",
|
||||
skip = 0,
|
||||
indent = 0;
|
||||
const parsed = miniparser(xml);
|
||||
parsed.forEach(function ({ type, value }, i) {
|
||||
if (skip > 0) {
|
||||
skip--;
|
||||
return;
|
||||
}
|
||||
const nextType = i < parsed.length - 1 ? parsed[i + 1].type : "";
|
||||
const nnextType = i < parsed.length - 2 ? parsed[i + 2].type : "";
|
||||
if (type === "declaration") {
|
||||
result += value + "\n";
|
||||
}
|
||||
if (
|
||||
type === "opening" &&
|
||||
nextType === "content" &&
|
||||
nnextType === "closing"
|
||||
) {
|
||||
result +=
|
||||
getIndent(indent) +
|
||||
value +
|
||||
parsed[i + 1].value +
|
||||
parsed[i + 2].value +
|
||||
"\n";
|
||||
skip = 2;
|
||||
return;
|
||||
}
|
||||
if (type === "opening") {
|
||||
result += getIndent(indent) + value + "\n";
|
||||
indent++;
|
||||
}
|
||||
if (type === "closing") {
|
||||
indent--;
|
||||
if (indent < 0) {
|
||||
throw new Error(`Malformed xml : ${xml}`);
|
||||
}
|
||||
result += getIndent(indent) + value + "\n";
|
||||
}
|
||||
if (type === "single") {
|
||||
result += getIndent(indent) + value + "\n";
|
||||
}
|
||||
if (type === "content" && !/^[ \n\r\t]+$/.test(value)) {
|
||||
result += getIndent(indent) + value.trim() + "\n";
|
||||
}
|
||||
});
|
||||
if (indent !== 0) {
|
||||
throw new Error(`Malformed xml : ${xml}`);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
function miniparser(xml) {
|
||||
let cursor = 0;
|
||||
let state = "outside";
|
||||
let currentType = "";
|
||||
let content = "";
|
||||
const renderedArray = [];
|
||||
while (cursor < xml.length) {
|
||||
if (state === "outside") {
|
||||
const opening = xml.indexOf("<", cursor);
|
||||
if (opening !== -1) {
|
||||
if (opening !== cursor) {
|
||||
content = xml.substr(cursor, opening - cursor);
|
||||
content = content.replace(/>/g, ">");
|
||||
renderedArray.push({ type: "content", value: content });
|
||||
}
|
||||
state = "inside";
|
||||
cursor = opening;
|
||||
} else {
|
||||
const content = xml.substr(cursor);
|
||||
renderedArray.push({ type: "content", value: content });
|
||||
return renderedArray;
|
||||
}
|
||||
}
|
||||
if (state === "inside") {
|
||||
const closing = xml.indexOf(">", cursor);
|
||||
if (closing !== -1) {
|
||||
let tag = xml.substr(cursor, closing - cursor + 1);
|
||||
const isSingle = Boolean(tag.match(/^<.+\/>/)); // is this line a single tag? ex. <br />
|
||||
const isClosing = Boolean(tag.match(/^<\/.+>/)); // is this a closing tag? ex. </a>
|
||||
const isXMLDeclaration = Boolean(tag.match(/^<\?xml/)); // is this a closing tag? ex. </a>
|
||||
|
||||
state = "outside";
|
||||
cursor = closing + 1;
|
||||
if (isXMLDeclaration) {
|
||||
const encodingRegex = /encoding="([^"]+)"/;
|
||||
if (encodingRegex.test(tag)) {
|
||||
tag = tag.replace(encodingRegex, function (x, p0) {
|
||||
return `encoding="${p0.toUpperCase()}"`;
|
||||
});
|
||||
}
|
||||
currentType = "declaration";
|
||||
} else if (isSingle) {
|
||||
// drop whitespace at the end
|
||||
tag = tag.replace(/\s*\/\s*>$/g, "/>");
|
||||
tag = attributeSorter(tag);
|
||||
currentType = "single";
|
||||
} else if (isClosing) {
|
||||
// drop whitespace at the end
|
||||
tag = tag.replace(/\s+>$/g, ">");
|
||||
currentType = "closing";
|
||||
} else {
|
||||
// drop whitespace at the end
|
||||
tag = tag.replace(/\s+>$/g, ">");
|
||||
tag = attributeSorter(tag);
|
||||
currentType = "opening";
|
||||
}
|
||||
renderedArray.push({ type: currentType, value: tag });
|
||||
} else {
|
||||
const content = xml.substr(cursor);
|
||||
renderedArray.push({ type: "content", value: content });
|
||||
return renderedArray;
|
||||
}
|
||||
}
|
||||
}
|
||||
return renderedArray;
|
||||
}
|
||||
|
||||
module.exports = xmlprettify;
|
||||
439
es6/tests/xml-templater.js
Normal file
439
es6/tests/xml-templater.js
Normal file
@ -0,0 +1,439 @@
|
||||
const {
|
||||
createXmlTemplaterDocx,
|
||||
expect,
|
||||
getContent,
|
||||
createXmlTemplaterDocxNoRender,
|
||||
} = require("./utils");
|
||||
|
||||
describe("XmlTemplater", function () {
|
||||
it("should work with simpleContent", function () {
|
||||
const content = "<w:t>Hello {name}</w:t>";
|
||||
const scope = { name: "Edgar" };
|
||||
const xmlTemplater = createXmlTemplaterDocx(content, { tags: scope });
|
||||
expect(xmlTemplater.getFullText()).to.be.equal("Hello Edgar");
|
||||
});
|
||||
|
||||
it("should work with doublecontent in w:t", function () {
|
||||
const content = "<w:t>Hello {name}, you're {age} years old</w:t>";
|
||||
const scope = { name: "Edgar", age: "foo" };
|
||||
const xmlTemplater = createXmlTemplaterDocx(content, { tags: scope });
|
||||
expect(xmlTemplater.getFullText()).to.be.equal(
|
||||
"Hello Edgar, you're foo years old"
|
||||
);
|
||||
});
|
||||
|
||||
it("should work with {.} for this", function () {
|
||||
const content = "<w:t>Hello {.}</w:t>";
|
||||
const scope = "Edgar";
|
||||
const xmlTemplater = createXmlTemplaterDocx(content, { tags: scope });
|
||||
expect(xmlTemplater.getFullText()).to.be.equal("Hello Edgar");
|
||||
});
|
||||
|
||||
it("should work with {.} for this inside loop", function () {
|
||||
const content = "<w:t>Hello {#names}{.},{/names}</w:t>";
|
||||
const scope = { names: ["Edgar", "John"] };
|
||||
const xmlTemplater = createXmlTemplaterDocx(content, { tags: scope });
|
||||
expect(xmlTemplater.getFullText()).to.be.equal("Hello Edgar,John,");
|
||||
});
|
||||
|
||||
it("should work with non w:t content", function () {
|
||||
const content = "<w:t>{#loop}Hello {name}{/loop}</w:t>";
|
||||
const scope = { loop: { name: "edgar" } };
|
||||
const xmlTemplater = createXmlTemplaterDocx(content, { tags: scope });
|
||||
expect(getContent(xmlTemplater)).to.be.equal(
|
||||
'<w:t xml:space="preserve">Hello edgar</w:t>'
|
||||
);
|
||||
});
|
||||
|
||||
it("should handle <w:p/> in loop without error", function () {
|
||||
const content = `<w:p><w:r><w:t>{#ab}</w:t></w:r></w:p>
|
||||
<w:p w14:paraId="79563C14" w14:textId="77777777" w:rsidR="00F22CAA" w:rsidRDefault="00F22CAA" w:rsidP="00324963"/>
|
||||
<w:p><w:r><w:t>{.}{/ab}</w:t></w:r></w:p>`;
|
||||
const scope = { ab: [1, 2, 3] };
|
||||
const xmlTemplater = createXmlTemplaterDocx(content, { tags: scope });
|
||||
expect(xmlTemplater.getFullText()).to.be.equal("123");
|
||||
});
|
||||
|
||||
it("should work with tag in two elements", function () {
|
||||
const content = "<w:t>Hello {</w:t><w:t>name}</w:t>";
|
||||
const scope = { name: "Edgar" };
|
||||
const xmlTemplater = createXmlTemplaterDocx(content, { tags: scope });
|
||||
expect(xmlTemplater.getFullText()).to.be.equal("Hello Edgar");
|
||||
});
|
||||
|
||||
it("should work with splitted tag in three elements", function () {
|
||||
const content = "<w:t>Hello {</w:t><w:t>name</w:t><w:t>}</w:t>";
|
||||
const scope = { name: "Edgar" };
|
||||
const xmlTemplater = createXmlTemplaterDocx(content, { tags: scope });
|
||||
expect(xmlTemplater.getFullText()).to.be.equal("Hello Edgar");
|
||||
});
|
||||
|
||||
it("should work with simple loop with object value", function () {
|
||||
const content = "<w:t>Hello {#person}{name}{/person}</w:t>";
|
||||
const scope = { person: { name: "Edgar" } };
|
||||
const xmlTemplater = createXmlTemplaterDocx(content, { tags: scope });
|
||||
expect(xmlTemplater.getFullText()).to.be.equal("Hello Edgar");
|
||||
});
|
||||
|
||||
it("should work with simple Loop", function () {
|
||||
const content = "<w:t>Hello {#names}{name},{/names}</w:t>";
|
||||
const scope = {
|
||||
names: [{ name: "Edgar" }, { name: "Mary" }, { name: "John" }],
|
||||
};
|
||||
const xmlTemplater = createXmlTemplaterDocx(content, { tags: scope });
|
||||
expect(xmlTemplater.getFullText()).to.be.equal("Hello Edgar,Mary,John,");
|
||||
});
|
||||
it("should work with simple Loop with boolean value truthy", function () {
|
||||
const content = "<w:t>Hello {#showName}{name},{/showName}</w:t>";
|
||||
const scope = { showName: true, name: "Edgar" };
|
||||
const xmlTemplater = createXmlTemplaterDocx(content, { tags: scope });
|
||||
expect(xmlTemplater.getFullText()).to.be.equal("Hello Edgar,");
|
||||
});
|
||||
it("should work with simple Loop with boolean value falsy", function () {
|
||||
const content = "<w:t>Hello {#showName}{name},{/showName}</w:t>";
|
||||
const scope = { showName: false, name: "Edgar" };
|
||||
const xmlTemplater = createXmlTemplaterDocx(content, { tags: scope });
|
||||
expect(xmlTemplater.getFullText()).to.be.equal("Hello ");
|
||||
});
|
||||
it("should work with dash Loop", function () {
|
||||
const content = "<w:p><w:t>Hello {-w:p names}{name},{/names}</w:t></w:p>";
|
||||
const scope = {
|
||||
names: [{ name: "Edgar" }, { name: "Mary" }, { name: "John" }],
|
||||
};
|
||||
const xmlTemplater = createXmlTemplaterDocx(content, { tags: scope });
|
||||
expect(xmlTemplater.getFullText()).to.be.equal(
|
||||
"Hello Edgar,Hello Mary,Hello John,"
|
||||
);
|
||||
});
|
||||
it("should work with loop and innerContent", function () {
|
||||
const content =
|
||||
'<w:p><w:t>{#loop}</w:t></w:r></w:p><w:p w:rsidR="00923B77" w:rsidRDefault="00713414" w:rsidP="00923B77"><w:pPr><w:pStyle w:val="Titre1"/></w:pPr><w:r><w:t>{title</w:t></w:r><w:r w:rsidR="00923B77"><w:t>}</w:t></w:r></w:p><w:p w:rsidR="00923B77" w:rsidRPr="00923B77" w:rsidRDefault="00713414" w:rsidP="00923B77"><w:r><w:t>Proof that it works nicely :</w:t></w:r></w:p><w:p w:rsidR="00923B77" w:rsidRDefault="00923B77" w:rsidP="00923B77"><w:pPr><w:numPr><w:ilvl w:val="0"/><w:numId w:val="1"/></w:numPr></w:pPr><w:r><w:t>{#pr</w:t></w:r><w:r w:rsidR="00713414"><w:t>oof</w:t></w:r><w:r><w:t xml:space="preserve">} </w:t></w:r><w:r w:rsidR="00713414"><w:t>It works because</w:t></w:r><w:r><w:t xml:space="preserve"> {</w:t></w:r><w:r w:rsidR="006F26AC"><w:t>reason</w:t></w:r><w:r><w:t>}</w:t></w:r></w:p><w:p w:rsidR="00923B77" w:rsidRDefault="00713414" w:rsidP="00923B77"><w:pPr><w:numPr><w:ilvl w:val="0"/><w:numId w:val="1"/></w:numPr></w:pPr><w:r><w:t>{/proof</w:t></w:r><w:r w:rsidR="00923B77"><w:t>}</w:t></w:r></w:p><w:p w:rsidR="00FD04E9" w:rsidRDefault="00923B77"><w:r><w:t>{/loop}</w:t></w:p>';
|
||||
const scope = {
|
||||
loop: {
|
||||
title: "Everyone uses it",
|
||||
proof: [
|
||||
{ reason: "it is quite cheap" },
|
||||
{ reason: "it is quit simple" },
|
||||
{ reason: "it works on a lot of different Hardware" },
|
||||
],
|
||||
},
|
||||
};
|
||||
const xmlTemplater = createXmlTemplaterDocx(content, { tags: scope });
|
||||
expect(xmlTemplater.getFullText()).to.be.equal(
|
||||
"Everyone uses itProof that it works nicely : It works because it is quite cheap It works because it is quit simple It works because it works on a lot of different Hardware"
|
||||
);
|
||||
});
|
||||
it("should work with loop and innerContent (with last)", function () {
|
||||
const content =
|
||||
'<w:p><w:t>{#loop}Start </w:t></w:r></w:p><w:p w:rsidR="00923B77" w:rsidRDefault="00713414" w:rsidP="00923B77"><w:pPr><w:pStyle w:val="Titre1"/></w:pPr><w:r><w:t>{title</w:t></w:r><w:r w:rsidR="00923B77"><w:t>}</w:t></w:r></w:p><w:p w:rsidR="00923B77" w:rsidRPr="00923B77" w:rsidRDefault="00713414" w:rsidP="00923B77"><w:r><w:t>Proof that it works nicely :</w:t></w:r></w:p><w:p w:rsidR="00923B77" w:rsidRDefault="00923B77" w:rsidP="00923B77"><w:pPr><w:numPr><w:ilvl w:val="0"/><w:numId w:val="1"/></w:numPr></w:pPr><w:r><w:t>{#pr</w:t></w:r><w:r w:rsidR="00713414"><w:t>oof</w:t></w:r><w:r><w:t xml:space="preserve">} </w:t></w:r><w:r w:rsidR="00713414"><w:t>It works because</w:t></w:r><w:r><w:t xml:space="preserve"> {</w:t></w:r><w:r w:rsidR="006F26AC"><w:t>reason</w:t></w:r><w:r><w:t>}</w:t></w:r></w:p><w:p w:rsidR="00923B77" w:rsidRDefault="00713414" w:rsidP="00923B77"><w:pPr><w:numPr><w:ilvl w:val="0"/><w:numId w:val="1"/></w:numPr></w:pPr><w:r><w:t>{/proof</w:t></w:r><w:r w:rsidR="00923B77"><w:t>}</w:t></w:r></w:p><w:p w:rsidR="00FD04E9" w:rsidRDefault="00923B77"><w:r><w:t> End{/loop}</w:t></w:p>';
|
||||
const scope = {
|
||||
loop: {
|
||||
title: "Everyone uses it",
|
||||
proof: [
|
||||
{ reason: "it is quite cheap" },
|
||||
{ reason: "it is quit simple" },
|
||||
{ reason: "it works on a lot of different Hardware" },
|
||||
],
|
||||
},
|
||||
};
|
||||
const xmlTemplater = createXmlTemplaterDocx(content, { tags: scope });
|
||||
expect(xmlTemplater.getFullText()).to.be.equal(
|
||||
"Start Everyone uses itProof that it works nicely : It works because it is quite cheap It works because it is quit simple It works because it works on a lot of different Hardware End"
|
||||
);
|
||||
});
|
||||
it("should work with not w:t tag (if the for loop is like {#forloop} text {/forloop}) ", function () {
|
||||
const content = "<w:t>{#loop}Hello {#names}{name},{/names}{/loop}</w:t>";
|
||||
const scope = {
|
||||
loop: { names: [{ name: "Edgar" }, { name: "Mary" }, { name: "John" }] },
|
||||
};
|
||||
const xmlTemplater = createXmlTemplaterDocx(content, { tags: scope });
|
||||
expect(getContent(xmlTemplater)).to.be.equal(
|
||||
'<w:t xml:space="preserve">Hello Edgar,Mary,John,</w:t>'
|
||||
);
|
||||
});
|
||||
it("should work with delimiter in value", function () {
|
||||
const content = "<w:t>Hello {name}</w:t>";
|
||||
const scope = { name: "{edgar}" };
|
||||
const xmlTemplater = createXmlTemplaterDocx(content, { tags: scope });
|
||||
expect(xmlTemplater.getFullText()).to.be.equal("Hello {edgar}");
|
||||
});
|
||||
it("should work with delimiter in value with loop)", function () {
|
||||
const content = "<w:t>Hello {#names}{name},{/names}</w:t>";
|
||||
const scope = {
|
||||
names: [{ name: "{John}" }, { name: "M}}{ary" }, { name: "Di{{{gory" }],
|
||||
};
|
||||
const xmlTemplater = createXmlTemplaterDocx(content, { tags: scope });
|
||||
expect(xmlTemplater.getFullText()).to.be.equal(
|
||||
"Hello {John},M}}{ary,Di{{{gory,"
|
||||
);
|
||||
});
|
||||
it("should work when replacing with exact same value", function () {
|
||||
const content = '<w:p><w:t xml:space="preserve">Hello {name}</w:t></w:p>';
|
||||
const scope = { name: "{name}" };
|
||||
const xmlTemplater = createXmlTemplaterDocx(content, { tags: scope });
|
||||
xmlTemplater.getFullText();
|
||||
expect(xmlTemplater.getFullText()).to.be.equal("Hello {name}");
|
||||
});
|
||||
|
||||
it("should work with equations", function () {
|
||||
const content = `<w:p>
|
||||
<m:oMathPara>
|
||||
<m:oMath>
|
||||
<m:sSup>
|
||||
<m:e>
|
||||
<m:r>
|
||||
<m:t>y</m:t>
|
||||
</m:r>
|
||||
</m:e>
|
||||
<m:sup>
|
||||
<m:r>
|
||||
<m:t>{bar}</m:t>
|
||||
</m:r>
|
||||
</m:sup>
|
||||
</m:sSup>
|
||||
<m:r>
|
||||
<m:t>*</m:t>
|
||||
</m:r>
|
||||
<m:r>
|
||||
<m:t>cos</m:t>
|
||||
</m:r>
|
||||
<m:r>
|
||||
<m:t>(</m:t>
|
||||
</m:r>
|
||||
<m:r>
|
||||
<m:t xml:space="preserve"> {foo}</m:t>
|
||||
</m:r>
|
||||
<m:r>
|
||||
<m:t>+{baz})</m:t>
|
||||
</m:r>
|
||||
</m:oMath>
|
||||
</m:oMathPara>
|
||||
</w:p>
|
||||
<w:p>
|
||||
<w:t>Hello {</w:t>
|
||||
<w:t>name</w:t>
|
||||
<w:t>}</w:t>
|
||||
</w:p>
|
||||
`;
|
||||
const scope = { name: "John", foo: "MyFoo", bar: "MyBar", baz: "MyBaz" };
|
||||
const xmlTemplater = createXmlTemplaterDocx(content, { tags: scope });
|
||||
expect(xmlTemplater.getFullText()).to.be.equal(
|
||||
"yMyBar*cos( MyFoo+MyBaz)Hello John"
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("Change the nullGetter", function () {
|
||||
it("should work with null", function () {
|
||||
const content = "<w:t>Hello {#names}{#foo}{bar}{/foo}{/names}</w:t>";
|
||||
function nullGetter(part, scopeManager) {
|
||||
expect(part.value).to.equal("bar");
|
||||
expect(scopeManager.scopePath).to.deep.equal(["names", "foo"]);
|
||||
expect(scopeManager.scopePathItem).to.deep.equal([0, 0]);
|
||||
return "null";
|
||||
}
|
||||
const xmlTemplater = createXmlTemplaterDocx(content, {
|
||||
tags: {
|
||||
names: [{ foo: [{}] }],
|
||||
},
|
||||
nullGetter,
|
||||
});
|
||||
expect(xmlTemplater.getFullText()).to.be.equal("Hello null");
|
||||
});
|
||||
|
||||
it("should be possible to keep null tags as is", function () {
|
||||
const content = "<w:t>Hello {name}, your hobby is {hobby}</w:t>";
|
||||
function nullGetter(part) {
|
||||
if (!part.module) {
|
||||
return "{" + part.value + "}";
|
||||
}
|
||||
if (part.module === "rawxml") {
|
||||
return "";
|
||||
}
|
||||
return "";
|
||||
}
|
||||
const data = {
|
||||
hobby: "diving",
|
||||
};
|
||||
const xmlTemplater = createXmlTemplaterDocxNoRender(content, {
|
||||
nullGetter,
|
||||
});
|
||||
xmlTemplater.compile();
|
||||
return xmlTemplater.resolveData(data).then(function () {
|
||||
xmlTemplater.render();
|
||||
expect(xmlTemplater.getFullText()).to.be.equal(
|
||||
"Hello {name}, your hobby is diving"
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
it("should work with null in resolve", function () {
|
||||
const content = "<w:t>Hello {#names}{#foo}{bar}{/foo}{/names}</w:t>";
|
||||
let calls = 0;
|
||||
function nullGetter(part, scopeManager) {
|
||||
calls++;
|
||||
expect(scopeManager.scopePath).to.deep.equal(["names", "foo"]);
|
||||
expect(scopeManager.scopePathItem).to.deep.equal([0, 0]);
|
||||
return "null";
|
||||
}
|
||||
const data = {
|
||||
names: [{ foo: [{}] }],
|
||||
};
|
||||
const xmlTemplater = createXmlTemplaterDocxNoRender(content, {
|
||||
nullGetter,
|
||||
});
|
||||
xmlTemplater.compile();
|
||||
return xmlTemplater.resolveData(data).then(function () {
|
||||
expect(calls).to.be.equal(1);
|
||||
xmlTemplater.render();
|
||||
expect(calls).to.be.equal(1);
|
||||
expect(xmlTemplater.getFullText()).to.be.equal("Hello null");
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("intelligent tagging multiple tables", function () {
|
||||
it("should work with multiple rows", function () {
|
||||
const content = `<w:tbl>
|
||||
<w:tr>
|
||||
<w:tc>
|
||||
<w:p>
|
||||
<w:r>
|
||||
<w:t>{#clauses} Clause {.}</w:t>
|
||||
</w:r>
|
||||
</w:p>
|
||||
</w:tc>
|
||||
</w:tr>
|
||||
<w:tr>
|
||||
<w:tc>
|
||||
<w:p>
|
||||
<w:r>
|
||||
<w:t>{/clauses}</w:t>
|
||||
</w:r>
|
||||
</w:p>
|
||||
</w:tc>
|
||||
</w:tr>
|
||||
</w:tbl>
|
||||
`.replace(/\t|\n/g, "");
|
||||
const scope = { clauses: ["Foo", "Bar", "Baz"] };
|
||||
const doc = createXmlTemplaterDocx(content, { tags: scope });
|
||||
const c = getContent(doc);
|
||||
expect(c).to.be.equal(
|
||||
'<w:tbl><w:tr><w:tc><w:p><w:r><w:t xml:space="preserve"> Clause Foo</w:t></w:r></w:p></w:tc></w:tr><w:tr><w:tc><w:p><w:r><w:t/></w:r></w:p></w:tc></w:tr><w:tr><w:tc><w:p><w:r><w:t xml:space="preserve"> Clause Bar</w:t></w:r></w:p></w:tc></w:tr><w:tr><w:tc><w:p><w:r><w:t/></w:r></w:p></w:tc></w:tr><w:tr><w:tc><w:p><w:r><w:t xml:space="preserve"> Clause Baz</w:t></w:r></w:p></w:tc></w:tr><w:tr><w:tc><w:p><w:r><w:t/></w:r></w:p></w:tc></w:tr></w:tbl>'
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("Custom delimiters", function () {
|
||||
it("should work with custom tags", function () {
|
||||
const delimiters = {
|
||||
start: "[",
|
||||
end: "]",
|
||||
};
|
||||
const content = "<w:t>Hello [name]</w:t>";
|
||||
const scope = { name: "Edgar" };
|
||||
const xmlTemplater = createXmlTemplaterDocx(content, {
|
||||
tags: scope,
|
||||
delimiters,
|
||||
});
|
||||
expect(xmlTemplater.getFullText()).to.be.equal("Hello Edgar");
|
||||
});
|
||||
|
||||
it("should work with custom delimiters with two chars", function () {
|
||||
const delimiters = {
|
||||
start: "[[",
|
||||
end: "]]",
|
||||
};
|
||||
const content = "<w:t>Hello [[name]]</w:t>";
|
||||
const scope = { name: "Edgar" };
|
||||
const xmlTemplater = createXmlTemplaterDocx(content, {
|
||||
tags: scope,
|
||||
delimiters,
|
||||
});
|
||||
expect(xmlTemplater.getFullText()).to.be.eql("Hello Edgar");
|
||||
});
|
||||
|
||||
it("should work with custom delimiters as strings with different length", function () {
|
||||
const delimiters = {
|
||||
start: "[[[",
|
||||
end: "]]",
|
||||
};
|
||||
const content = "<w:t>Hello [[[name]]</w:t>";
|
||||
const scope = { name: "Edgar" };
|
||||
const xmlTemplater = createXmlTemplaterDocx(content, {
|
||||
tags: scope,
|
||||
delimiters,
|
||||
});
|
||||
expect(xmlTemplater.getFullText()).to.be.eql("Hello Edgar");
|
||||
});
|
||||
|
||||
it("should work with custom tags and loops", function () {
|
||||
const delimiters = {
|
||||
start: "[[[",
|
||||
end: "]]",
|
||||
};
|
||||
const content = "<w:t>Hello [[[#names]][[[.]],[[[/names]]</w:t>";
|
||||
const scope = { names: ["Edgar", "Mary", "John"] };
|
||||
const xmlTemplater = createXmlTemplaterDocx(content, {
|
||||
tags: scope,
|
||||
delimiters,
|
||||
});
|
||||
expect(xmlTemplater.getFullText()).to.be.equal("Hello Edgar,Mary,John,");
|
||||
});
|
||||
|
||||
it("should work with loops", function () {
|
||||
const content = "<w:t>{#loop}{innertag</w:t><w:t>} {/loop}</w:t>";
|
||||
const xmlt = createXmlTemplaterDocx(content, {
|
||||
tags: { loop: [{ innertag: 10 }, { innertag: 5 }] },
|
||||
});
|
||||
const c = getContent(xmlt);
|
||||
expect(c).to.be.equal(
|
||||
'<w:t xml:space="preserve">10</w:t><w:t xml:space="preserve"> 5</w:t><w:t xml:space="preserve"> </w:t>'
|
||||
);
|
||||
});
|
||||
|
||||
it("should work with complex loops (1)", function () {
|
||||
const content = "<w:t>{#looptag}{innertag</w:t><w:t>}{/looptag}</w:t>";
|
||||
const xmlt = createXmlTemplaterDocx(content, {
|
||||
tags: { looptag: true, innertag: "foo" },
|
||||
});
|
||||
const c = getContent(xmlt);
|
||||
expect(c).not.to.contain("</w:t></w:t>");
|
||||
expect(c).to.be.equal('<w:t xml:space="preserve">foo</w:t><w:t/>');
|
||||
});
|
||||
|
||||
it("should work with complex loops (2)", function () {
|
||||
const content = "<w:t>{#person}</w:t><w:t>{name}{/person}</w:t>";
|
||||
const xmlt = createXmlTemplaterDocx(content, {
|
||||
tags: { person: [{ name: "Henry" }] },
|
||||
});
|
||||
const c = getContent(xmlt);
|
||||
expect(c).to.contain("Henry</w:t>");
|
||||
expect(c).not.to.contain("</w:t>Henry</w:t>");
|
||||
});
|
||||
});
|
||||
|
||||
describe("getting parents context", function () {
|
||||
it("should work with simple loops", function () {
|
||||
const content = "<w:t>{#loop}{name}{/loop}</w:t>";
|
||||
const xmlt = createXmlTemplaterDocx(content, {
|
||||
tags: { loop: [1], name: "Henry" },
|
||||
});
|
||||
const c = getContent(xmlt);
|
||||
expect(c).to.be.equal('<w:t xml:space="preserve">Henry</w:t>');
|
||||
});
|
||||
|
||||
it("should work with double loops", function () {
|
||||
const content =
|
||||
"<w:t>{#loop_first}{#loop_second}{name_inner} {name_outer}{/loop_second}{/loop_first}</w:t>";
|
||||
const xmlt = createXmlTemplaterDocx(content, {
|
||||
tags: {
|
||||
loop_first: [1],
|
||||
loop_second: [{ name_inner: "John" }],
|
||||
name_outer: "Henry",
|
||||
},
|
||||
});
|
||||
const c = getContent(xmlt);
|
||||
expect(c).to.be.equal('<w:t xml:space="preserve">John Henry</w:t>');
|
||||
});
|
||||
});
|
||||
210
es6/traits.js
Normal file
210
es6/traits.js
Normal file
@ -0,0 +1,210 @@
|
||||
const {
|
||||
getRightOrNull,
|
||||
getRight,
|
||||
getLeft,
|
||||
getLeftOrNull,
|
||||
chunkBy,
|
||||
isTagStart,
|
||||
isTagEnd,
|
||||
isContent,
|
||||
last,
|
||||
first,
|
||||
} = require("./doc-utils");
|
||||
const {
|
||||
XTTemplateError,
|
||||
throwExpandNotFound,
|
||||
getLoopPositionProducesInvalidXMLError,
|
||||
} = require("./errors");
|
||||
|
||||
function lastTagIsOpenTag(tags, tag) {
|
||||
if (tags.length === 0) {
|
||||
return false;
|
||||
}
|
||||
const innerLastTag = last(tags).tag.substr(1);
|
||||
const innerCurrentTag = tag.substr(2, tag.length - 3);
|
||||
return innerLastTag.indexOf(innerCurrentTag) === 0;
|
||||
}
|
||||
|
||||
function addTag(tags, tag) {
|
||||
tags.push({ tag });
|
||||
return tags;
|
||||
}
|
||||
|
||||
function getListXmlElements(parts) {
|
||||
/*
|
||||
get the different closing and opening tags between two texts (doesn't take into account tags that are opened then closed (those that are closed then opened are returned)):
|
||||
returns:[{"tag":"</w:r>","offset":13},{"tag":"</w:p>","offset":265},{"tag":"</w:tc>","offset":271},{"tag":"<w:tc>","offset":828},{"tag":"<w:p>","offset":883},{"tag":"<w:r>","offset":1483}]
|
||||
*/
|
||||
const tags = parts.filter(function (part) {
|
||||
return part.type === "tag";
|
||||
});
|
||||
|
||||
let result = [];
|
||||
|
||||
for (let i = 0, tag; i < tags.length; i++) {
|
||||
tag = tags[i].value;
|
||||
// closing tag
|
||||
if (tag[1] === "/") {
|
||||
if (lastTagIsOpenTag(result, tag)) {
|
||||
result.pop();
|
||||
} else {
|
||||
result = addTag(result, tag);
|
||||
}
|
||||
} else if (tag[tag.length - 2] !== "/") {
|
||||
result = addTag(result, tag);
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
function has(name, xmlElements) {
|
||||
for (let i = 0; i < xmlElements.length; i++) {
|
||||
const xmlElement = xmlElements[i];
|
||||
if (xmlElement.tag.indexOf(`<${name}`) === 0) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
function getExpandToDefault(postparsed, pair, expandTags) {
|
||||
const parts = postparsed.slice(pair[0].offset, pair[1].offset);
|
||||
const xmlElements = getListXmlElements(parts);
|
||||
const closingTagCount = xmlElements.filter(function (xmlElement) {
|
||||
return xmlElement.tag[1] === "/";
|
||||
}).length;
|
||||
const startingTagCount = xmlElements.filter(function (xmlElement) {
|
||||
const { tag } = xmlElement;
|
||||
return tag[1] !== "/" && tag[tag.length - 2] !== "/";
|
||||
}).length;
|
||||
if (closingTagCount !== startingTagCount) {
|
||||
return {
|
||||
error: getLoopPositionProducesInvalidXMLError({
|
||||
tag: first(pair).part.value,
|
||||
offset: [first(pair).part.offset, last(pair).part.offset],
|
||||
}),
|
||||
};
|
||||
}
|
||||
for (let i = 0, len = expandTags.length; i < len; i++) {
|
||||
const { contains, expand, onlyTextInTag } = expandTags[i];
|
||||
if (has(contains, xmlElements)) {
|
||||
if (onlyTextInTag) {
|
||||
const left = getLeftOrNull(postparsed, contains, pair[0].offset);
|
||||
const right = getRightOrNull(postparsed, contains, pair[1].offset);
|
||||
if (left === null || right === null) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const chunks = chunkBy(postparsed.slice(left, right), function (p) {
|
||||
if (isTagStart(contains, p)) {
|
||||
return "start";
|
||||
}
|
||||
if (isTagEnd(contains, p)) {
|
||||
return "end";
|
||||
}
|
||||
return null;
|
||||
});
|
||||
|
||||
if (chunks.length <= 2) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const firstChunk = first(chunks);
|
||||
const lastChunk = last(chunks);
|
||||
|
||||
const firstContent = firstChunk.filter(isContent);
|
||||
const lastContent = lastChunk.filter(isContent);
|
||||
if (firstContent.length !== 1 || lastContent.length !== 1) {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
return { value: expand };
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
function expandOne(part, index, postparsed, options) {
|
||||
const expandTo = part.expandTo || options.expandTo;
|
||||
if (!expandTo) {
|
||||
return postparsed;
|
||||
}
|
||||
let right, left;
|
||||
try {
|
||||
left = getLeft(postparsed, expandTo, index);
|
||||
right = getRight(postparsed, expandTo, index);
|
||||
} catch (rootError) {
|
||||
if (rootError instanceof XTTemplateError) {
|
||||
throwExpandNotFound({
|
||||
part,
|
||||
rootError,
|
||||
postparsed,
|
||||
expandTo,
|
||||
index,
|
||||
...options.error,
|
||||
});
|
||||
}
|
||||
throw rootError;
|
||||
}
|
||||
const leftParts = postparsed.slice(left, index);
|
||||
const rightParts = postparsed.slice(index + 1, right + 1);
|
||||
let inner = options.getInner({
|
||||
postparse: options.postparse,
|
||||
index,
|
||||
part,
|
||||
leftParts,
|
||||
rightParts,
|
||||
left,
|
||||
right,
|
||||
postparsed,
|
||||
});
|
||||
if (!inner.length) {
|
||||
inner.expanded = [leftParts, rightParts];
|
||||
inner = [inner];
|
||||
}
|
||||
return { left, right, inner };
|
||||
}
|
||||
|
||||
function expandToOne(postparsed, options) {
|
||||
let errors = [];
|
||||
if (postparsed.errors) {
|
||||
errors = postparsed.errors;
|
||||
postparsed = postparsed.postparsed;
|
||||
}
|
||||
const results = [];
|
||||
for (let i = 0, len = postparsed.length; i < len; i++) {
|
||||
const part = postparsed[i];
|
||||
if (part.type === "placeholder" && part.module === options.moduleName) {
|
||||
try {
|
||||
const result = expandOne(part, i, postparsed, options);
|
||||
i = result.right;
|
||||
results.push(result);
|
||||
} catch (error) {
|
||||
if (error instanceof XTTemplateError) {
|
||||
errors.push(error);
|
||||
} else {
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
const newParsed = [];
|
||||
let currentResult = 0;
|
||||
for (let i = 0, len = postparsed.length; i < len; i++) {
|
||||
const part = postparsed[i];
|
||||
const result = results[currentResult];
|
||||
if (result && result.left === i) {
|
||||
newParsed.push(...results[currentResult].inner);
|
||||
currentResult++;
|
||||
i = result.right;
|
||||
} else {
|
||||
newParsed.push(part);
|
||||
}
|
||||
}
|
||||
return { postparsed: newParsed, errors };
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
expandToOne,
|
||||
getExpandToDefault,
|
||||
};
|
||||
11
es6/utils.js
Normal file
11
es6/utils.js
Normal file
@ -0,0 +1,11 @@
|
||||
function last(a) {
|
||||
return a[a.length - 1];
|
||||
}
|
||||
function first(a) {
|
||||
return a[0];
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
last,
|
||||
first,
|
||||
};
|
||||
65
es6/xml-matcher.js
Normal file
65
es6/xml-matcher.js
Normal file
@ -0,0 +1,65 @@
|
||||
"use strict";
|
||||
// res class responsibility is to parse the XML.
|
||||
const { pregMatchAll } = require("./doc-utils");
|
||||
|
||||
function handleRecursiveCase(res) {
|
||||
/*
|
||||
* Because xmlTemplater is recursive (meaning it can call it self), we need to handle special cases where the XML is not valid:
|
||||
* For example with res string "I am</w:t></w:r></w:p><w:p><w:r><w:t>sleeping",
|
||||
* - we need to match also the string that is inside an implicit <w:t> (that's the role of replacerUnshift) (in res case 'I am')
|
||||
* - we need to match the string that is at the right of a <w:t> (that's the role of replacerPush) (in res case 'sleeping')
|
||||
* the test: describe "scope calculation" it "should compute the scope between 2 <w:t>" makes sure that res part of code works
|
||||
* It should even work if they is no XML at all, for example if the code is just "I am sleeping", in res case however, they should only be one match
|
||||
*/
|
||||
|
||||
function replacerUnshift() {
|
||||
const pn = { array: Array.prototype.slice.call(arguments) };
|
||||
pn.array.shift();
|
||||
const match = pn.array[0] + pn.array[1];
|
||||
// add match so that pn[0] = whole match, pn[1]= first parenthesis,...
|
||||
pn.array.unshift(match);
|
||||
pn.array.pop();
|
||||
const offset = pn.array.pop();
|
||||
pn.offset = offset;
|
||||
pn.first = true;
|
||||
// add at the beginning
|
||||
res.matches.unshift(pn);
|
||||
}
|
||||
|
||||
if (res.content.indexOf("<") === -1 && res.content.indexOf(">") === -1) {
|
||||
res.content.replace(/^()([^<>]*)$/, replacerUnshift);
|
||||
}
|
||||
|
||||
let r = new RegExp(`^()([^<]+)<\/(?:${res.tagsXmlArrayJoined})>`);
|
||||
res.content.replace(r, replacerUnshift);
|
||||
|
||||
function replacerPush() {
|
||||
const pn = { array: Array.prototype.slice.call(arguments) };
|
||||
pn.array.pop();
|
||||
const offset = pn.array.pop();
|
||||
pn.offset = offset;
|
||||
pn.last = true;
|
||||
if (pn.array[0].indexOf("/>") !== -1) {
|
||||
return;
|
||||
}
|
||||
// add at the end
|
||||
res.matches.push(pn);
|
||||
}
|
||||
|
||||
r = new RegExp(`(<(?:${res.tagsXmlArrayJoined})[^>]*>)([^>]+)$`);
|
||||
res.content.replace(r, replacerPush);
|
||||
return res;
|
||||
}
|
||||
|
||||
module.exports = function xmlMatcher(content, tagsXmlArray) {
|
||||
const res = {};
|
||||
res.content = content;
|
||||
res.tagsXmlArray = tagsXmlArray;
|
||||
res.tagsXmlArrayJoined = res.tagsXmlArray.join("|");
|
||||
const regexp = new RegExp(
|
||||
`(?:(<(?:${res.tagsXmlArrayJoined})[^>]*>)([^<>]*)</(?:${res.tagsXmlArrayJoined})>)|(<(?:${res.tagsXmlArrayJoined})[^>]*/>)`,
|
||||
"g"
|
||||
);
|
||||
res.matches = pregMatchAll(regexp, res.content);
|
||||
return handleRecursiveCase(res);
|
||||
};
|
||||
174
es6/xml-templater.js
Normal file
174
es6/xml-templater.js
Normal file
@ -0,0 +1,174 @@
|
||||
const { wordToUtf8, convertSpaces, defaults } = require("./doc-utils");
|
||||
const createScope = require("./scope-manager");
|
||||
const xmlMatcher = require("./xml-matcher");
|
||||
const { throwContentMustBeString } = require("./errors");
|
||||
const Lexer = require("./lexer");
|
||||
const Parser = require("./parser.js");
|
||||
const render = require("./render.js");
|
||||
const postrender = require("./postrender.js");
|
||||
const resolve = require("./resolve.js");
|
||||
const joinUncorrupt = require("./join-uncorrupt");
|
||||
|
||||
function getFullText(content, tagsXmlArray) {
|
||||
const matcher = xmlMatcher(content, tagsXmlArray);
|
||||
const result = matcher.matches.map(function (match) {
|
||||
return match.array[2];
|
||||
});
|
||||
return wordToUtf8(convertSpaces(result.join("")));
|
||||
}
|
||||
|
||||
module.exports = class XmlTemplater {
|
||||
constructor(content, options) {
|
||||
this.filePath = options.filePath;
|
||||
this.cachedParsers = {};
|
||||
this.modules = options.modules;
|
||||
this.fileTypeConfig = options.fileTypeConfig;
|
||||
this.contentType = options.contentType;
|
||||
Object.keys(defaults).map(function (key) {
|
||||
this[key] = options[key] != null ? options[key] : defaults[key];
|
||||
}, this);
|
||||
this.setModules({ inspect: { filePath: this.filePath } });
|
||||
this.load(content);
|
||||
}
|
||||
load(content) {
|
||||
if (typeof content !== "string") {
|
||||
throwContentMustBeString(typeof content);
|
||||
}
|
||||
this.content = content;
|
||||
}
|
||||
setTags(tags) {
|
||||
this.tags = tags != null ? tags : {};
|
||||
this.scopeManager = createScope({
|
||||
tags: this.tags,
|
||||
parser: this.parser,
|
||||
cachedParsers: this.cachedParsers,
|
||||
});
|
||||
return this;
|
||||
}
|
||||
resolveTags(tags) {
|
||||
this.tags = tags != null ? tags : {};
|
||||
this.scopeManager = createScope({
|
||||
tags: this.tags,
|
||||
parser: this.parser,
|
||||
cachedParsers: this.cachedParsers,
|
||||
});
|
||||
const options = this.getOptions();
|
||||
options.scopeManager = createScope(options);
|
||||
options.resolve = resolve;
|
||||
return resolve(options).then(({ resolved, errors }) => {
|
||||
errors.forEach((error) => {
|
||||
// error properties might not be defined if some foreign
|
||||
// (unhandled error not throw by docxtemplater willingly) is
|
||||
// thrown.
|
||||
error.properties = error.properties || {};
|
||||
error.properties.file = this.filePath;
|
||||
});
|
||||
if (errors.length !== 0) {
|
||||
throw errors;
|
||||
}
|
||||
return Promise.all(resolved).then((resolved) => {
|
||||
this.setModules({ inspect: { resolved } });
|
||||
return (this.resolved = resolved);
|
||||
});
|
||||
});
|
||||
}
|
||||
getFullText() {
|
||||
return getFullText(this.content, this.fileTypeConfig.tagsXmlTextArray);
|
||||
}
|
||||
setModules(obj) {
|
||||
this.modules.forEach((module) => {
|
||||
module.set(obj);
|
||||
});
|
||||
}
|
||||
preparse() {
|
||||
this.allErrors = [];
|
||||
this.xmllexed = Lexer.xmlparse(this.content, {
|
||||
text: this.fileTypeConfig.tagsXmlTextArray,
|
||||
other: this.fileTypeConfig.tagsXmlLexedArray,
|
||||
});
|
||||
this.setModules({ inspect: { xmllexed: this.xmllexed } });
|
||||
const { lexed, errors: lexerErrors } = Lexer.parse(
|
||||
this.xmllexed,
|
||||
this.delimiters
|
||||
);
|
||||
this.allErrors = this.allErrors.concat(lexerErrors);
|
||||
this.lexed = lexed;
|
||||
this.setModules({ inspect: { lexed: this.lexed } });
|
||||
const options = this.getOptions();
|
||||
Parser.preparse(this.lexed, this.modules, options);
|
||||
}
|
||||
parse() {
|
||||
this.setModules({ inspect: { filePath: this.filePath } });
|
||||
const options = this.getOptions();
|
||||
this.parsed = Parser.parse(this.lexed, this.modules, options);
|
||||
this.setModules({ inspect: { parsed: this.parsed } });
|
||||
const { postparsed, errors: postparsedErrors } = Parser.postparse(
|
||||
this.parsed,
|
||||
this.modules,
|
||||
options
|
||||
);
|
||||
this.postparsed = postparsed;
|
||||
this.setModules({ inspect: { postparsed: this.postparsed } });
|
||||
this.allErrors = this.allErrors.concat(postparsedErrors);
|
||||
this.errorChecker(this.allErrors);
|
||||
return this;
|
||||
}
|
||||
errorChecker(errors) {
|
||||
if (errors.length) {
|
||||
errors.forEach((error) => {
|
||||
// error properties might not be defined if some foreign
|
||||
// (unhandled error not thrown by docxtemplater willingly) is
|
||||
// thrown.
|
||||
error.properties = error.properties || {};
|
||||
error.properties.file = this.filePath;
|
||||
});
|
||||
this.modules.forEach(function (module) {
|
||||
errors = module.errorsTransformer(errors);
|
||||
});
|
||||
}
|
||||
}
|
||||
baseNullGetter(part, sm) {
|
||||
const value = this.modules.reduce((value, module) => {
|
||||
if (value != null) {
|
||||
return value;
|
||||
}
|
||||
return module.nullGetter(part, sm, this);
|
||||
}, null);
|
||||
if (value != null) {
|
||||
return value;
|
||||
}
|
||||
return this.nullGetter(part, sm);
|
||||
}
|
||||
getOptions() {
|
||||
return {
|
||||
compiled: this.postparsed,
|
||||
cachedParsers: this.cachedParsers,
|
||||
tags: this.tags,
|
||||
modules: this.modules,
|
||||
parser: this.parser,
|
||||
contentType: this.contentType,
|
||||
baseNullGetter: this.baseNullGetter.bind(this),
|
||||
filePath: this.filePath,
|
||||
fileTypeConfig: this.fileTypeConfig,
|
||||
linebreaks: this.linebreaks,
|
||||
};
|
||||
}
|
||||
render(to) {
|
||||
this.filePath = to;
|
||||
const options = this.getOptions();
|
||||
options.resolved = this.resolved;
|
||||
options.scopeManager = createScope(options);
|
||||
options.render = render;
|
||||
options.joinUncorrupt = joinUncorrupt;
|
||||
const { errors, parts } = render(options);
|
||||
this.allErrors = errors;
|
||||
this.errorChecker(errors);
|
||||
if (errors.length > 0) {
|
||||
return this;
|
||||
}
|
||||
|
||||
this.content = postrender(parts, options);
|
||||
this.setModules({ inspect: { content: this.content } });
|
||||
return this;
|
||||
}
|
||||
};
|
||||
BIN
examples/angular-example.docx
Normal file
BIN
examples/angular-example.docx
Normal file
Binary file not shown.
BIN
examples/assignment.docx
Normal file
BIN
examples/assignment.docx
Normal file
Binary file not shown.
BIN
examples/comment-with-loop.docx
Normal file
BIN
examples/comment-with-loop.docx
Normal file
Binary file not shown.
BIN
examples/cyrillic.docx
Normal file
BIN
examples/cyrillic.docx
Normal file
Binary file not shown.
BIN
examples/delimiter-gt.docx
Normal file
BIN
examples/delimiter-gt.docx
Normal file
Binary file not shown.
BIN
examples/delimiter-pct.docx
Normal file
BIN
examples/delimiter-pct.docx
Normal file
Binary file not shown.
BIN
examples/errors-footer-and-header.docx
Normal file
BIN
examples/errors-footer-and-header.docx
Normal file
Binary file not shown.
BIN
examples/expected-assignment.docx
Normal file
BIN
examples/expected-assignment.docx
Normal file
Binary file not shown.
BIN
examples/expected-comment-example.docx
Normal file
BIN
examples/expected-comment-example.docx
Normal file
Binary file not shown.
BIN
examples/expected-docm.docx
Normal file
BIN
examples/expected-docm.docx
Normal file
Binary file not shown.
BIN
examples/expected-dotm.docx
Normal file
BIN
examples/expected-dotm.docx
Normal file
Binary file not shown.
BIN
examples/expected-dotx.docx
Normal file
BIN
examples/expected-dotx.docx
Normal file
Binary file not shown.
BIN
examples/expected-empty-table.docx
Normal file
BIN
examples/expected-empty-table.docx
Normal file
Binary file not shown.
BIN
examples/expected-loop-example.pptx
Normal file
BIN
examples/expected-loop-example.pptx
Normal file
Binary file not shown.
BIN
examples/expected-loop-raw-xml.docx
Normal file
BIN
examples/expected-loop-raw-xml.docx
Normal file
Binary file not shown.
BIN
examples/expected-loop-valid.docx
Normal file
BIN
examples/expected-loop-valid.docx
Normal file
Binary file not shown.
BIN
examples/expected-module-change-rels.docx
Normal file
BIN
examples/expected-module-change-rels.docx
Normal file
Binary file not shown.
BIN
examples/expected-multi-loop.docx
Normal file
BIN
examples/expected-multi-loop.docx
Normal file
Binary file not shown.
BIN
examples/expected-multi-section.docx
Normal file
BIN
examples/expected-multi-section.docx
Normal file
Binary file not shown.
BIN
examples/expected-multiline-indent.docx
Normal file
BIN
examples/expected-multiline-indent.docx
Normal file
Binary file not shown.
BIN
examples/expected-multiline.docx
Normal file
BIN
examples/expected-multiline.docx
Normal file
Binary file not shown.
BIN
examples/expected-multiline.pptx
Normal file
BIN
examples/expected-multiline.pptx
Normal file
Binary file not shown.
BIN
examples/expected-no-proofstate.docx
Normal file
BIN
examples/expected-no-proofstate.docx
Normal file
Binary file not shown.
BIN
examples/expected-noparagraph-loop-with-pagebreak.docx
Normal file
BIN
examples/expected-noparagraph-loop-with-pagebreak.docx
Normal file
Binary file not shown.
BIN
examples/expected-office365.docx
Normal file
BIN
examples/expected-office365.docx
Normal file
Binary file not shown.
Some files were not shown because too many files have changed in this diff Show More
Loading…
x
Reference in New Issue
Block a user