first commit
This commit is contained in:
commit
4d332ef662
27586 changed files with 3281783 additions and 0 deletions
661
rus/WEB-INF/lib/itext-xtra-5.5.10_src/com/itextpdf/text/AGPL.txt
Normal file
661
rus/WEB-INF/lib/itext-xtra-5.5.10_src/com/itextpdf/text/AGPL.txt
Normal file
|
|
@ -0,0 +1,661 @@
|
|||
GNU AFFERO GENERAL PUBLIC LICENSE
|
||||
Version 3, 19 November 2007
|
||||
|
||||
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
|
||||
Everyone is permitted to copy and distribute verbatim copies
|
||||
of this license document, but changing it is not allowed.
|
||||
|
||||
Preamble
|
||||
|
||||
The GNU Affero General Public License is a free, copyleft license for
|
||||
software and other kinds of works, specifically designed to ensure
|
||||
cooperation with the community in the case of network server software.
|
||||
|
||||
The licenses for most software and other practical works are designed
|
||||
to take away your freedom to share and change the works. By contrast,
|
||||
our General Public Licenses are 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.
|
||||
|
||||
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.
|
||||
|
||||
Developers that use our General Public Licenses protect your rights
|
||||
with two steps: (1) assert copyright on the software, and (2) offer
|
||||
you this License which gives you legal permission to copy, distribute
|
||||
and/or modify the software.
|
||||
|
||||
A secondary benefit of defending all users' freedom is that
|
||||
improvements made in alternate versions of the program, if they
|
||||
receive widespread use, become available for other developers to
|
||||
incorporate. Many developers of free software are heartened and
|
||||
encouraged by the resulting cooperation. However, in the case of
|
||||
software used on network servers, this result may fail to come about.
|
||||
The GNU General Public License permits making a modified version and
|
||||
letting the public access it on a server without ever releasing its
|
||||
source code to the public.
|
||||
|
||||
The GNU Affero General Public License is designed specifically to
|
||||
ensure that, in such cases, the modified source code becomes available
|
||||
to the community. It requires the operator of a network server to
|
||||
provide the source code of the modified version running there to the
|
||||
users of that server. Therefore, public use of a modified version, on
|
||||
a publicly accessible server, gives the public access to the source
|
||||
code of the modified version.
|
||||
|
||||
An older license, called the Affero General Public License and
|
||||
published by Affero, was designed to accomplish similar goals. This is
|
||||
a different license, not a version of the Affero GPL, but Affero has
|
||||
released a new version of the Affero GPL which permits relicensing under
|
||||
this license.
|
||||
|
||||
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 Affero 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. Remote Network Interaction; Use with the GNU General Public License.
|
||||
|
||||
Notwithstanding any other provision of this License, if you modify the
|
||||
Program, your modified version must prominently offer all users
|
||||
interacting with it remotely through a computer network (if your version
|
||||
supports such interaction) an opportunity to receive the Corresponding
|
||||
Source of your version by providing access to the Corresponding Source
|
||||
from a network server at no charge, through some standard or customary
|
||||
means of facilitating copying of software. This Corresponding Source
|
||||
shall include the Corresponding Source for any work covered by version 3
|
||||
of the GNU General Public License that is incorporated pursuant to the
|
||||
following paragraph.
|
||||
|
||||
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 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 work with which it is combined will remain governed by version
|
||||
3 of the GNU General Public License.
|
||||
|
||||
14. Revised Versions of this License.
|
||||
|
||||
The Free Software Foundation may publish revised and/or new versions of
|
||||
the GNU Affero 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 Affero 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 Affero 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 Affero 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
|
||||
|
||||
How to Apply These Terms to Your New Programs
|
||||
|
||||
If you develop a new program, and you want it to be of the greatest
|
||||
possible use to the public, the best way to achieve this is to make it
|
||||
free software which everyone can redistribute and change under these terms.
|
||||
|
||||
To do so, attach the following notices to the program. It is safest
|
||||
to attach them to the start of each source file to most effectively
|
||||
state the exclusion of warranty; and each file should have at least
|
||||
the "copyright" line and a pointer to where the full notice is found.
|
||||
|
||||
<one line to give the program's name and a brief idea of what it does.>
|
||||
Copyright (C) <year> <name of author>
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as published by
|
||||
the Free Software Foundation, either version 3 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
Also add information on how to contact you by electronic and paper mail.
|
||||
|
||||
If your software can interact with users remotely through a computer
|
||||
network, you should also make sure that it provides a way for users to
|
||||
get its source. For example, if your program is a web application, its
|
||||
interface could display a "Source" link that leads users to an archive
|
||||
of the code. There are many ways you could offer source, and different
|
||||
solutions will be better for different programs; see section 13 for the
|
||||
specific requirements.
|
||||
|
||||
You should also get your employer (if you work as a programmer) or school,
|
||||
if any, to sign a "copyright disclaimer" for the program, if necessary.
|
||||
For more information on this, and how to apply and follow the GNU AGPL, see
|
||||
<http://www.gnu.org/licenses/>.
|
||||
|
|
@ -0,0 +1,15 @@
|
|||
This program is free software; you can redistribute it and/or modify it under the terms of the GNU Affero General Public License version 3 as published by the Free Software Foundation with the addition of the following permission added to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK IN WHICH THE COPYRIGHT IS OWNED BY 1T3XT, 1T3XT DISCLAIMS THE WARRANTY OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
|
||||
|
||||
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details.
|
||||
You should have received a copy of the GNU Affero General Public License along with this program; if not, see http://www.gnu.org/licenses or write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA, 02110-1301 USA, or download the license from the following URL:
|
||||
|
||||
http://itextpdf.com/terms-of-use/
|
||||
|
||||
The interactive user interfaces in modified source and object code versions of this program must display Appropriate Legal Notices, as required under Section 5 of the GNU Affero General Public License.
|
||||
|
||||
In accordance with Section 7(b) of the GNU Affero General Public License, a covered work must retain the producer line in every PDF that is created or manipulated using iText.
|
||||
|
||||
You can be released from the requirements of the license by purchasing a commercial license. Buying such a license is mandatory as soon as you develop commercial activities involving the iText software without disclosing the source code of your own applications.
|
||||
These activities include: offering paid services to customers as an ASP, serving PDFs on the fly in a web application, shipping iText with a closed source product.
|
||||
|
||||
For more information, please contact iText Software Corp. at this address: sales@itextpdf.com
|
||||
|
|
@ -0,0 +1,28 @@
|
|||
package com.itextpdf.text.pdf.mc;
|
||||
|
||||
import com.itextpdf.text.DocumentException;
|
||||
import com.itextpdf.text.pdf.PdfDictionary;
|
||||
import com.itextpdf.text.pdf.PdfIndirectReference;
|
||||
import com.itextpdf.text.pdf.PdfName;
|
||||
import com.itextpdf.text.pdf.PdfReader;
|
||||
import com.itextpdf.text.pdf.PdfStamper;
|
||||
import java.io.IOException;
|
||||
import java.io.OutputStream;
|
||||
|
||||
public class MCFieldFlattener {
|
||||
public void process(PdfReader reader, OutputStream os) throws IOException, DocumentException {
|
||||
int n = reader.getNumberOfPages();
|
||||
PdfDictionary catalog = reader.getCatalog();
|
||||
catalog.remove(PdfName.ACROFORM);
|
||||
StructureItems items = new StructureItems(reader);
|
||||
MCParser parser = new MCParser(items);
|
||||
for (int i = 1; i <= n; i++) {
|
||||
reader.setPageContent(i, reader.getPageContent(i));
|
||||
parser.parse(reader.getPageN(i), (PdfIndirectReference)reader.getPageOrigRef(i));
|
||||
}
|
||||
reader.removeUnusedObjects();
|
||||
PdfStamper stamper = new PdfStamper(reader, os);
|
||||
items.writeParentTree(stamper.getWriter());
|
||||
stamper.close();
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,414 @@
|
|||
package com.itextpdf.text.pdf.mc;
|
||||
|
||||
import com.itextpdf.text.DocumentException;
|
||||
import com.itextpdf.text.Rectangle;
|
||||
import com.itextpdf.text.error_messages.MessageLocalization;
|
||||
import com.itextpdf.text.io.RandomAccessSourceFactory;
|
||||
import com.itextpdf.text.log.Logger;
|
||||
import com.itextpdf.text.log.LoggerFactory;
|
||||
import com.itextpdf.text.pdf.ByteBuffer;
|
||||
import com.itextpdf.text.pdf.PRStream;
|
||||
import com.itextpdf.text.pdf.PRTokeniser;
|
||||
import com.itextpdf.text.pdf.PdfArray;
|
||||
import com.itextpdf.text.pdf.PdfContentParser;
|
||||
import com.itextpdf.text.pdf.PdfDictionary;
|
||||
import com.itextpdf.text.pdf.PdfIndirectReference;
|
||||
import com.itextpdf.text.pdf.PdfLiteral;
|
||||
import com.itextpdf.text.pdf.PdfName;
|
||||
import com.itextpdf.text.pdf.PdfNumber;
|
||||
import com.itextpdf.text.pdf.PdfObject;
|
||||
import com.itextpdf.text.pdf.PdfReader;
|
||||
import com.itextpdf.text.pdf.PdfStream;
|
||||
import com.itextpdf.text.pdf.PdfString;
|
||||
import com.itextpdf.text.pdf.RandomAccessFileOrArray;
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
public class MCParser {
|
||||
protected static final Logger LOGGER = LoggerFactory.getLogger(MCParser.class);
|
||||
|
||||
protected static final RandomAccessSourceFactory RASFACTORY = new RandomAccessSourceFactory();
|
||||
|
||||
public static final String DEFAULTOPERATOR = "DefaultOperator";
|
||||
|
||||
public static final PdfLiteral TSTAR = new PdfLiteral("T*");
|
||||
|
||||
protected Map<String, PdfOperator> operators = null;
|
||||
|
||||
protected StructureItems items;
|
||||
|
||||
protected ByteArrayOutputStream baos;
|
||||
|
||||
protected PdfDictionary page;
|
||||
|
||||
protected PdfIndirectReference pageref;
|
||||
|
||||
protected PdfArray annots;
|
||||
|
||||
protected PdfNumber structParents;
|
||||
|
||||
protected PdfDictionary xobjects;
|
||||
|
||||
protected boolean btWrite = false;
|
||||
|
||||
protected boolean etExtra = false;
|
||||
|
||||
protected boolean inText = false;
|
||||
|
||||
protected StringBuffer text;
|
||||
|
||||
public MCParser(StructureItems items) {
|
||||
populateOperators();
|
||||
this.items = items;
|
||||
}
|
||||
|
||||
protected void populateOperators() {
|
||||
if (this.operators != null)
|
||||
return;
|
||||
this.operators = new HashMap<String, PdfOperator>();
|
||||
this.operators.put("DefaultOperator", new CopyContentOperator());
|
||||
PdfOperator markedContent = new BeginMarkedContentDictionaryOperator();
|
||||
this.operators.put("BDC", markedContent);
|
||||
PdfOperator doOperator = new DoOperator();
|
||||
this.operators.put("Do", doOperator);
|
||||
PdfOperator beginText = new BeginTextOperator();
|
||||
this.operators.put("BT", beginText);
|
||||
PdfOperator endText = new EndTextOperator();
|
||||
this.operators.put("ET", endText);
|
||||
PdfOperator textPos = new TextPositioningOperator();
|
||||
this.operators.put("Td", textPos);
|
||||
this.operators.put("TD", textPos);
|
||||
this.operators.put("Tm", textPos);
|
||||
this.operators.put("T*", textPos);
|
||||
PdfOperator textState = new TextStateOperator();
|
||||
this.operators.put("Tc", textState);
|
||||
this.operators.put("Tw", textState);
|
||||
this.operators.put("Tz", textState);
|
||||
this.operators.put("TL", textState);
|
||||
this.operators.put("Tf", textState);
|
||||
this.operators.put("Tr", textState);
|
||||
this.operators.put("Ts", textState);
|
||||
PdfOperator textNL = new TextNewLineOperator();
|
||||
this.operators.put("'", textNL);
|
||||
this.operators.put("\"", textNL);
|
||||
}
|
||||
|
||||
public void parse(PdfDictionary page, PdfIndirectReference pageref) throws IOException, DocumentException {
|
||||
LOGGER.info("Parsing page with reference " + pageref);
|
||||
this.baos = new ByteArrayOutputStream();
|
||||
this.page = page;
|
||||
this.pageref = pageref;
|
||||
this.structParents = page.getAsNumber(PdfName.STRUCTPARENTS);
|
||||
if (this.structParents == null)
|
||||
throw new DocumentException(MessageLocalization.getComposedMessage("can.t.read.document.structure", new Object[0]));
|
||||
this.annots = page.getAsArray(PdfName.ANNOTS);
|
||||
if (this.annots == null)
|
||||
this.annots = new PdfArray();
|
||||
PdfDictionary resources = page.getAsDict(PdfName.RESOURCES);
|
||||
this.xobjects = resources.getAsDict(PdfName.XOBJECT);
|
||||
if (this.xobjects == null) {
|
||||
this.xobjects = new PdfDictionary();
|
||||
resources.put(PdfName.XOBJECT, (PdfObject)this.xobjects);
|
||||
}
|
||||
PRStream stream = (PRStream)page.getAsStream(PdfName.CONTENTS);
|
||||
byte[] contentBytes = PdfReader.getStreamBytes(stream);
|
||||
PRTokeniser tokeniser = new PRTokeniser(new RandomAccessFileOrArray(RASFACTORY.createSource(contentBytes)));
|
||||
PdfContentParser ps = new PdfContentParser(tokeniser);
|
||||
ArrayList<PdfObject> operands = new ArrayList<PdfObject>();
|
||||
while (ps.parse(operands).size() > 0) {
|
||||
PdfLiteral operator = (PdfLiteral)operands.get(operands.size() - 1);
|
||||
processOperator(operator, operands);
|
||||
}
|
||||
while (this.items.size() > 0 && this.items.get(0).getPageref() == pageref.getNumber()) {
|
||||
StructureItem item = this.items.get(0);
|
||||
if (item instanceof StructureObject) {
|
||||
convertToXObject((StructureObject)item);
|
||||
this.items.remove(0);
|
||||
}
|
||||
}
|
||||
if (this.annots.size() == 0) {
|
||||
page.remove(PdfName.ANNOTS);
|
||||
} else {
|
||||
for (int i = 0; i < this.annots.size(); i++) {
|
||||
PdfDictionary annot = this.annots.getAsDict(i);
|
||||
if (annot.getAsNumber(PdfName.STRUCTPARENT) == null)
|
||||
throw new DocumentException(MessageLocalization.getComposedMessage("could.not.flatten.file.untagged.annotations.found", new Object[0]));
|
||||
}
|
||||
}
|
||||
this.baos.flush();
|
||||
this.baos.close();
|
||||
stream.setData(this.baos.toByteArray());
|
||||
LOGGER.info(String.format("There are %d items left for processing", this.items.size()));
|
||||
}
|
||||
|
||||
protected void dealWithXObj(PdfName xobj) {
|
||||
PdfStream pdfStream = this.xobjects.getAsStream(xobj);
|
||||
PdfNumber structParent = pdfStream.getAsNumber(PdfName.STRUCTPARENT);
|
||||
LOGGER.info(String.format("Encountered StructParent %s in content", structParent));
|
||||
if (structParent == null)
|
||||
return;
|
||||
StructureItem item = this.items.get(0);
|
||||
if (item.checkStructParent(this.pageref.getNumber(), structParent.intValue()) == 1)
|
||||
this.items.remove(0);
|
||||
}
|
||||
|
||||
protected void dealWithMcid(PdfNumber mcid) throws IOException, DocumentException {
|
||||
StructureObject obj;
|
||||
if (mcid == null)
|
||||
return;
|
||||
StructureItem item = this.items.get(0);
|
||||
LOGGER.info(String.format("Encountered MCID %s in content, comparing with %s", mcid, item));
|
||||
switch (item.checkMCID(this.pageref.getNumber(), mcid.intValue())) {
|
||||
case 0:
|
||||
obj = (StructureObject)item;
|
||||
convertToXObject(obj);
|
||||
LOGGER.info("Removed structure item from stack.");
|
||||
this.items.remove(0);
|
||||
dealWithMcid(mcid);
|
||||
return;
|
||||
case 1:
|
||||
LOGGER.info("Removed structure item from stack.");
|
||||
this.items.remove(0);
|
||||
return;
|
||||
}
|
||||
LOGGER.warn("MCID not found! There's probably an error in your form!");
|
||||
for (int i = 1; i < this.items.size(); i++) {
|
||||
item = this.items.get(i);
|
||||
int check = item.checkMCID(this.pageref.getNumber(), mcid.intValue());
|
||||
switch (check) {
|
||||
case 1:
|
||||
LOGGER.info("Removed structure item from stack.");
|
||||
this.items.remove(i);
|
||||
return;
|
||||
}
|
||||
}
|
||||
throw new DocumentException(MessageLocalization.getComposedMessage("can.t.read.document.structure", new Object[0]));
|
||||
}
|
||||
|
||||
protected void convertToXObject(StructureObject item) throws IOException, DocumentException {
|
||||
PdfDictionary structElem = item.getStructElem();
|
||||
if (structElem == null)
|
||||
return;
|
||||
PdfDictionary dict = item.getObjAsDict();
|
||||
if (dict == null || !dict.checkType(PdfName.ANNOT))
|
||||
return;
|
||||
PdfDictionary ap = dict.getAsDict(PdfName.AP);
|
||||
if (ap == null)
|
||||
return;
|
||||
PdfNumber structParent = dict.getAsNumber(PdfName.STRUCTPARENT);
|
||||
if (structParent == null)
|
||||
return;
|
||||
PdfStream stream = ap.getAsStream(PdfName.N);
|
||||
if (stream == null)
|
||||
return;
|
||||
PdfIndirectReference xobjr = ap.getAsIndirectObject(PdfName.N);
|
||||
if (xobjr == null)
|
||||
return;
|
||||
for (int i = 0; i < this.annots.size(); i++) {
|
||||
PdfIndirectReference annotref = this.annots.getAsIndirectObject(i);
|
||||
if (item.getObjRef().getNumber() == annotref.getNumber()) {
|
||||
this.annots.remove(i);
|
||||
break;
|
||||
}
|
||||
}
|
||||
PdfDictionary attribute = new PdfDictionary();
|
||||
attribute.put(PdfName.O, (PdfObject)PdfName.PRINTFIELD);
|
||||
PdfString description = dict.getAsString(PdfName.TU);
|
||||
if (description == null)
|
||||
description = dict.getAsString(PdfName.T);
|
||||
if (PdfName.BTN.equals(dict.get(PdfName.FT))) {
|
||||
PdfNumber fflags = dict.getAsNumber(PdfName.FF);
|
||||
if (fflags != null) {
|
||||
int ff = fflags.intValue();
|
||||
if ((ff & 0x10000) != 0)
|
||||
attribute.put(PdfName.ROLE, (PdfObject)PdfName.PB);
|
||||
if ((ff & 0x8000) != 0) {
|
||||
attribute.put(PdfName.ROLE, (PdfObject)PdfName.rb);
|
||||
} else {
|
||||
attribute.put(PdfName.ROLE, (PdfObject)PdfName.CB);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
attribute.put(PdfName.ROLE, (PdfObject)PdfName.TV);
|
||||
}
|
||||
attribute.put(PdfName.DESC, (PdfObject)description);
|
||||
PdfString t = structElem.getAsString(PdfName.T);
|
||||
if (t == null || t.toString().trim().length() == 0)
|
||||
structElem.put(PdfName.T, (PdfObject)dict.getAsString(PdfName.T));
|
||||
structElem.put(PdfName.A, (PdfObject)attribute);
|
||||
structElem.put(PdfName.S, (PdfObject)PdfName.P);
|
||||
structElem.put(PdfName.PG, (PdfObject)this.pageref);
|
||||
int mcid = this.items.processMCID(this.structParents, item.getRef());
|
||||
LOGGER.info("Using MCID " + mcid);
|
||||
structElem.put(PdfName.K, new PdfNumber(mcid));
|
||||
this.items.removeFromParentTree(structParent);
|
||||
PdfName xobj = new PdfName("XObj" + structParent.intValue());
|
||||
LOGGER.info("Creating XObject with name " + xobj);
|
||||
this.xobjects.put(xobj, (PdfObject)xobjr);
|
||||
PdfArray array = dict.getAsArray(PdfName.RECT);
|
||||
Rectangle rect = new Rectangle(
|
||||
array.getAsNumber(0).floatValue(), array.getAsNumber(1).floatValue(),
|
||||
array.getAsNumber(2).floatValue(), array.getAsNumber(3).floatValue());
|
||||
rect.normalize();
|
||||
if (this.inText && !this.btWrite) {
|
||||
LOGGER.debug("Introducing extra ET");
|
||||
this.baos.write("ET\n".getBytes());
|
||||
this.etExtra = true;
|
||||
}
|
||||
ByteBuffer buf = new ByteBuffer();
|
||||
buf.append("/P <</MCID ");
|
||||
buf.append(mcid);
|
||||
buf.append(">> BDC\n");
|
||||
buf.append("q 1 0 0 1 ");
|
||||
buf.append(rect.getLeft());
|
||||
buf.append(" ");
|
||||
buf.append(rect.getBottom());
|
||||
buf.append(" cm ");
|
||||
buf.append(xobj.getBytes());
|
||||
buf.append(" Do Q\n");
|
||||
buf.append("EMC\n");
|
||||
buf.flush();
|
||||
buf.writeTo(this.baos);
|
||||
if (this.inText)
|
||||
this.btWrite = true;
|
||||
}
|
||||
|
||||
protected void processOperator(PdfLiteral operator, List<PdfObject> operands) throws IOException, DocumentException {
|
||||
PdfOperator op = this.operators.get(operator.toString());
|
||||
if (op == null)
|
||||
op = this.operators.get("DefaultOperator");
|
||||
op.process(this, operator, operands);
|
||||
}
|
||||
|
||||
protected void printOperator(PdfLiteral operator, List<PdfObject> operands) throws IOException {
|
||||
operands.remove(operator);
|
||||
for (PdfObject o : operands)
|
||||
printsp(o);
|
||||
println((PdfObject)operator);
|
||||
}
|
||||
|
||||
protected void printTextOperator(PdfLiteral operator, List<PdfObject> operands) throws IOException {
|
||||
for (PdfObject obj : operands)
|
||||
this.text.append(obj).append(" ");
|
||||
this.text.append("\n");
|
||||
printOperator(operator, operands);
|
||||
}
|
||||
|
||||
protected void printsp(PdfObject o) throws IOException {
|
||||
checkBT();
|
||||
o.toPdf(null, this.baos);
|
||||
this.baos.write(32);
|
||||
}
|
||||
|
||||
protected void println(PdfObject o) throws IOException {
|
||||
checkBT();
|
||||
o.toPdf(null, this.baos);
|
||||
this.baos.write(10);
|
||||
}
|
||||
|
||||
protected void checkBT() throws IOException {
|
||||
if (this.btWrite) {
|
||||
this.baos.write("BT ".getBytes());
|
||||
if (this.etExtra) {
|
||||
this.baos.write(this.text.toString().getBytes());
|
||||
this.etExtra = false;
|
||||
this.text = new StringBuffer();
|
||||
}
|
||||
LOGGER.debug("BT written");
|
||||
}
|
||||
this.btWrite = false;
|
||||
}
|
||||
|
||||
protected void setInText(boolean inText) {
|
||||
if (inText) {
|
||||
this.text = new StringBuffer();
|
||||
this.btWrite = true;
|
||||
} else {
|
||||
this.etExtra = false;
|
||||
}
|
||||
this.inText = inText;
|
||||
}
|
||||
|
||||
public static interface PdfOperator {
|
||||
void process(MCParser param1MCParser, PdfLiteral param1PdfLiteral, List<PdfObject> param1List) throws DocumentException, IOException;
|
||||
}
|
||||
|
||||
private static class CopyContentOperator implements PdfOperator {
|
||||
private CopyContentOperator() {}
|
||||
|
||||
public void process(MCParser parser, PdfLiteral operator, List<PdfObject> operands) throws IOException {
|
||||
parser.printOperator(operator, operands);
|
||||
}
|
||||
}
|
||||
|
||||
private static class BeginMarkedContentDictionaryOperator implements PdfOperator {
|
||||
private BeginMarkedContentDictionaryOperator() {}
|
||||
|
||||
public void process(MCParser parser, PdfLiteral operator, List<PdfObject> operands) throws IOException, DocumentException {
|
||||
if (operands.get(1).isDictionary()) {
|
||||
PdfDictionary dict = (PdfDictionary)operands.get(1);
|
||||
parser.dealWithMcid(dict.getAsNumber(PdfName.MCID));
|
||||
}
|
||||
parser.printOperator(operator, operands);
|
||||
}
|
||||
}
|
||||
|
||||
private static class DoOperator implements PdfOperator {
|
||||
private DoOperator() {}
|
||||
|
||||
public void process(MCParser parser, PdfLiteral operator, List<PdfObject> operands) throws IOException {
|
||||
if (operands.get(0).isName())
|
||||
parser.dealWithXObj((PdfName)operands.get(0));
|
||||
parser.printOperator(operator, operands);
|
||||
}
|
||||
}
|
||||
|
||||
private static class BeginTextOperator implements PdfOperator {
|
||||
private BeginTextOperator() {}
|
||||
|
||||
public void process(MCParser parser, PdfLiteral operator, List<PdfObject> operands) throws IOException {
|
||||
MCParser.LOGGER.debug("BT: begin text on hold");
|
||||
parser.setInText(true);
|
||||
}
|
||||
}
|
||||
|
||||
private static class EndTextOperator implements PdfOperator {
|
||||
private EndTextOperator() {}
|
||||
|
||||
public void process(MCParser parser, PdfLiteral operator, List<PdfObject> operands) throws IOException {
|
||||
MCParser.LOGGER.debug("ET: end text block");
|
||||
parser.setInText(false);
|
||||
parser.printOperator(operator, operands);
|
||||
}
|
||||
}
|
||||
|
||||
private static class TextPositioningOperator implements PdfOperator {
|
||||
private TextPositioningOperator() {}
|
||||
|
||||
public void process(MCParser parser, PdfLiteral operator, List<PdfObject> operands) throws IOException {
|
||||
parser.printTextOperator(operator, operands);
|
||||
}
|
||||
}
|
||||
|
||||
private static class TextStateOperator implements PdfOperator {
|
||||
private TextStateOperator() {}
|
||||
|
||||
public void process(MCParser parser, PdfLiteral operator, List<PdfObject> operands) throws IOException {
|
||||
parser.printTextOperator(operator, operands);
|
||||
}
|
||||
}
|
||||
|
||||
private static class TextNewLineOperator implements PdfOperator {
|
||||
private TextNewLineOperator() {}
|
||||
|
||||
public void process(MCParser parser, PdfLiteral operator, List<PdfObject> operands) throws IOException {
|
||||
List<PdfObject> list = new ArrayList<PdfObject>();
|
||||
list.add(MCParser.TSTAR);
|
||||
parser.printTextOperator(MCParser.TSTAR, list);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,17 @@
|
|||
package com.itextpdf.text.pdf.mc;
|
||||
|
||||
public abstract class StructureItem {
|
||||
protected int pageref = -1;
|
||||
|
||||
public int getPageref() {
|
||||
return this.pageref;
|
||||
}
|
||||
|
||||
public int checkMCID(int pageref, int mcid) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
public int checkStructParent(int pageref, int structParent) {
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,136 @@
|
|||
package com.itextpdf.text.pdf.mc;
|
||||
|
||||
import com.itextpdf.text.DocumentException;
|
||||
import com.itextpdf.text.error_messages.MessageLocalization;
|
||||
import com.itextpdf.text.log.Logger;
|
||||
import com.itextpdf.text.log.LoggerFactory;
|
||||
import com.itextpdf.text.pdf.PdfArray;
|
||||
import com.itextpdf.text.pdf.PdfDictionary;
|
||||
import com.itextpdf.text.pdf.PdfIndirectReference;
|
||||
import com.itextpdf.text.pdf.PdfName;
|
||||
import com.itextpdf.text.pdf.PdfNumber;
|
||||
import com.itextpdf.text.pdf.PdfNumberTree;
|
||||
import com.itextpdf.text.pdf.PdfObject;
|
||||
import com.itextpdf.text.pdf.PdfReader;
|
||||
import com.itextpdf.text.pdf.PdfWriter;
|
||||
import java.io.IOException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.HashMap;
|
||||
|
||||
public class StructureItems extends ArrayList<StructureItem> {
|
||||
protected static final Logger LOGGER = LoggerFactory.getLogger(StructureItems.class);
|
||||
|
||||
protected PdfDictionary structTreeRoot;
|
||||
|
||||
protected HashMap<Integer, PdfObject> parentTree;
|
||||
|
||||
private static final long serialVersionUID = -8247348202717165564L;
|
||||
|
||||
public StructureItems(PdfReader reader) throws DocumentException {
|
||||
PdfArray array;
|
||||
int i;
|
||||
PdfDictionary catalog = reader.getCatalog();
|
||||
this.structTreeRoot = catalog.getAsDict(PdfName.STRUCTTREEROOT);
|
||||
if (this.structTreeRoot == null)
|
||||
throw new DocumentException(MessageLocalization.getComposedMessage("can.t.read.document.structure", new Object[0]));
|
||||
this.parentTree = PdfNumberTree.readTree(this.structTreeRoot.getAsDict(PdfName.PARENTTREE));
|
||||
this.structTreeRoot.remove(PdfName.STRUCTPARENTS);
|
||||
PdfObject object = this.structTreeRoot.getDirectObject(PdfName.K);
|
||||
if (object == null)
|
||||
return;
|
||||
switch (object.type()) {
|
||||
case 6:
|
||||
LOGGER.info("StructTreeRoot refers to dictionary");
|
||||
processStructElems((PdfDictionary)object, this.structTreeRoot.getAsIndirectObject(PdfName.K));
|
||||
break;
|
||||
case 5:
|
||||
LOGGER.info("StructTreeRoot refers to array");
|
||||
array = (PdfArray)object;
|
||||
for (i = 0; i < array.size(); i++)
|
||||
processStructElems(array.getAsDict(i), array.getAsIndirectObject(i));
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
protected void processStructElems(PdfDictionary structElem, PdfIndirectReference ref) {
|
||||
LOGGER.info(String.format("addStructureItems(%s, %s)", structElem, ref));
|
||||
if (structElem == null)
|
||||
return;
|
||||
processStructElemKids(structElem, ref, structElem.getDirectObject(PdfName.K));
|
||||
}
|
||||
|
||||
protected void processStructElemKids(PdfDictionary structElem, PdfIndirectReference ref, PdfObject object) {
|
||||
StructureItem item;
|
||||
PdfArray array;
|
||||
int i;
|
||||
PdfDictionary dict;
|
||||
LOGGER.info(String.format("addStructureItem(%s, %s, %s)", structElem, ref, object));
|
||||
if (object == null)
|
||||
return;
|
||||
switch (object.type()) {
|
||||
case 2:
|
||||
item = new StructureMCID(structElem.getAsIndirectObject(PdfName.PG), (PdfNumber)object);
|
||||
add(item);
|
||||
LOGGER.info("Added " + item);
|
||||
break;
|
||||
case 5:
|
||||
array = (PdfArray)object;
|
||||
for (i = 0; i < array.size(); i++)
|
||||
processStructElemKids(structElem, array.getAsIndirectObject(i), array.getDirectObject(i));
|
||||
break;
|
||||
case 6:
|
||||
dict = (PdfDictionary)object;
|
||||
if (dict.checkType(PdfName.MCR)) {
|
||||
item = new StructureMCID(dict);
|
||||
add(item);
|
||||
LOGGER.info("Added " + item);
|
||||
} else if (dict.checkType(PdfName.OBJR)) {
|
||||
item = new StructureObject(structElem, ref, dict);
|
||||
add(item);
|
||||
LOGGER.info("Added " + item);
|
||||
} else {
|
||||
processStructElems(dict, ref);
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
public void removeFromParentTree(PdfNumber structParent) {
|
||||
this.parentTree.remove(Integer.valueOf(structParent.intValue()));
|
||||
}
|
||||
|
||||
public int processMCID(PdfNumber structParents, PdfIndirectReference ref) throws DocumentException {
|
||||
if (ref == null)
|
||||
throw new DocumentException(MessageLocalization.getComposedMessage("can.t.read.document.structure", new Object[0]));
|
||||
PdfObject object = this.parentTree.get(Integer.valueOf(structParents.intValue()));
|
||||
PdfArray array = (PdfArray)PdfReader.getPdfObject(object);
|
||||
int i = getNextMCID(structParents);
|
||||
if (i < array.size()) {
|
||||
array.set(i, (PdfObject)ref);
|
||||
return i;
|
||||
}
|
||||
array.add((PdfObject)ref);
|
||||
return array.size() - 1;
|
||||
}
|
||||
|
||||
public int getNextMCID(PdfNumber structParents) {
|
||||
PdfObject object = this.parentTree.get(Integer.valueOf(structParents.intValue()));
|
||||
PdfArray array = (PdfArray)PdfReader.getPdfObject(object);
|
||||
for (int i = 0; i < array.size(); i++) {
|
||||
if (array.getAsIndirectObject(i) == null)
|
||||
return i;
|
||||
}
|
||||
return array.size();
|
||||
}
|
||||
|
||||
public void writeParentTree(PdfWriter writer) throws IOException {
|
||||
if (this.structTreeRoot == null)
|
||||
return;
|
||||
Integer[] numbers = new Integer[this.parentTree.size()];
|
||||
numbers = (Integer[])this.parentTree.keySet().toArray(numbers);
|
||||
Arrays.sort(numbers);
|
||||
this.structTreeRoot.put(PdfName.PARENTTREENEXTKEY, new PdfNumber(numbers[numbers.length - 1] + 1));
|
||||
this.structTreeRoot.put(PdfName.PARENTTREE, (PdfObject)PdfNumberTree.writeTree(this.parentTree, writer));
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,32 @@
|
|||
package com.itextpdf.text.pdf.mc;
|
||||
|
||||
import com.itextpdf.text.pdf.PdfDictionary;
|
||||
import com.itextpdf.text.pdf.PdfIndirectReference;
|
||||
import com.itextpdf.text.pdf.PdfName;
|
||||
import com.itextpdf.text.pdf.PdfNumber;
|
||||
|
||||
public class StructureMCID extends StructureItem {
|
||||
protected int mcid = -1;
|
||||
|
||||
public StructureMCID(PdfIndirectReference pg, PdfNumber mcid) {
|
||||
this.pageref = pg.getNumber();
|
||||
this.mcid = mcid.intValue();
|
||||
}
|
||||
|
||||
public StructureMCID(PdfDictionary mcr) {
|
||||
this.mcid = mcr.getAsNumber(PdfName.MCID).intValue();
|
||||
this.pageref = mcr.getAsIndirectObject(PdfName.PG).getNumber();
|
||||
}
|
||||
|
||||
public int checkMCID(int pg, int mcid) {
|
||||
if (this.pageref == -1)
|
||||
throw new RuntimeException();
|
||||
if (pg == this.pageref && this.mcid == mcid)
|
||||
return 1;
|
||||
return -1;
|
||||
}
|
||||
|
||||
public String toString() {
|
||||
return "MCID " + this.mcid + " on page with reference " + this.pageref;
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,58 @@
|
|||
package com.itextpdf.text.pdf.mc;
|
||||
|
||||
import com.itextpdf.text.pdf.PdfDictionary;
|
||||
import com.itextpdf.text.pdf.PdfIndirectReference;
|
||||
import com.itextpdf.text.pdf.PdfName;
|
||||
import com.itextpdf.text.pdf.PdfObject;
|
||||
|
||||
public class StructureObject extends StructureItem {
|
||||
protected PdfDictionary structElem;
|
||||
|
||||
protected PdfIndirectReference ref;
|
||||
|
||||
protected PdfObject obj;
|
||||
|
||||
protected PdfIndirectReference objref;
|
||||
|
||||
protected int structParent;
|
||||
|
||||
public StructureObject(PdfDictionary structElem, PdfIndirectReference ref, PdfDictionary dict) {
|
||||
this.structElem = structElem;
|
||||
this.ref = ref;
|
||||
this.obj = dict.getDirectObject(PdfName.OBJ);
|
||||
this.objref = dict.getAsIndirectObject(PdfName.OBJ);
|
||||
this.structParent = ((PdfDictionary)this.obj).getAsNumber(PdfName.STRUCTPARENT).intValue();
|
||||
PdfIndirectReference pg = dict.getAsIndirectObject(PdfName.PG);
|
||||
if (pg == null)
|
||||
pg = structElem.getAsIndirectObject(PdfName.PG);
|
||||
this.pageref = pg.getNumber();
|
||||
}
|
||||
|
||||
public PdfDictionary getStructElem() {
|
||||
return this.structElem;
|
||||
}
|
||||
|
||||
public PdfIndirectReference getRef() {
|
||||
return this.ref;
|
||||
}
|
||||
|
||||
public PdfDictionary getObjAsDict() {
|
||||
if (this.obj.isDictionary())
|
||||
return (PdfDictionary)this.obj;
|
||||
return null;
|
||||
}
|
||||
|
||||
public PdfIndirectReference getObjRef() {
|
||||
return this.objref;
|
||||
}
|
||||
|
||||
public int checkStructParent(int pg, int sp) {
|
||||
if (pg == this.pageref && sp == this.structParent)
|
||||
return 1;
|
||||
return -1;
|
||||
}
|
||||
|
||||
public String toString() {
|
||||
return "StructParent " + this.structParent + " of object " + this.obj + " on page with reference " + this.pageref;
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,312 @@
|
|||
package com.itextpdf.text.pdf.ocg;
|
||||
|
||||
import com.itextpdf.text.ExceptionConverter;
|
||||
import com.itextpdf.text.pdf.PRStream;
|
||||
import com.itextpdf.text.pdf.PRTokeniser;
|
||||
import com.itextpdf.text.pdf.PdfContentParser;
|
||||
import com.itextpdf.text.pdf.PdfDictionary;
|
||||
import com.itextpdf.text.pdf.PdfLiteral;
|
||||
import com.itextpdf.text.pdf.PdfName;
|
||||
import com.itextpdf.text.pdf.PdfObject;
|
||||
import com.itextpdf.text.pdf.PdfReader;
|
||||
import com.itextpdf.text.pdf.PdfString;
|
||||
import com.itextpdf.text.pdf.RandomAccessFileOrArray;
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
public class OCGParser {
|
||||
public static final String DEFAULTOPERATOR = "DefaultOperator";
|
||||
|
||||
protected static final Map<String, PdfOperator> operators = new HashMap<String, PdfOperator>();
|
||||
|
||||
protected ByteArrayOutputStream baos;
|
||||
|
||||
static {
|
||||
populateOperators();
|
||||
}
|
||||
|
||||
protected int mc_balance = 0;
|
||||
|
||||
protected Set<PdfName> xobj;
|
||||
|
||||
protected Set<String> ocgs;
|
||||
|
||||
protected PdfDictionary properties = null;
|
||||
|
||||
public OCGParser(Set<String> ocgs) {
|
||||
this.ocgs = ocgs;
|
||||
}
|
||||
|
||||
public void parse(PRStream stream, PdfDictionary resources) throws IOException {
|
||||
this.baos = new ByteArrayOutputStream();
|
||||
this.properties = resources.getAsDict(PdfName.PROPERTIES);
|
||||
this.xobj = new HashSet<PdfName>();
|
||||
PdfDictionary xobjects = resources.getAsDict(PdfName.XOBJECT);
|
||||
if (xobjects != null) {
|
||||
for (PdfName name : (Iterable<PdfName>)xobjects.getKeys()) {
|
||||
PRStream xobject = (PRStream)xobjects.getAsStream(name);
|
||||
PdfDictionary oc = xobject.getAsDict(PdfName.OC);
|
||||
if (oc != null) {
|
||||
PdfString ocname = oc.getAsString(PdfName.NAME);
|
||||
if (ocname != null && this.ocgs.contains(ocname.toString()))
|
||||
this.xobj.add(name);
|
||||
}
|
||||
}
|
||||
for (PdfName name : this.xobj)
|
||||
xobjects.remove(name);
|
||||
}
|
||||
try {
|
||||
byte[] contentBytes = PdfReader.getStreamBytes(stream);
|
||||
PRTokeniser tokeniser = new PRTokeniser(new RandomAccessFileOrArray(contentBytes));
|
||||
PdfContentParser ps = new PdfContentParser(tokeniser);
|
||||
ArrayList<PdfObject> operands = new ArrayList<PdfObject>();
|
||||
while (ps.parse(operands).size() > 0) {
|
||||
PdfLiteral operator = (PdfLiteral)operands.get(operands.size() - 1);
|
||||
processOperator(this, operator, operands);
|
||||
if ("BI".equals(operator.toString())) {
|
||||
int found = 0;
|
||||
boolean immediateAfterBI = true;
|
||||
int ch;
|
||||
while ((ch = tokeniser.read()) != -1) {
|
||||
if (!immediateAfterBI || !PRTokeniser.isWhitespace(ch))
|
||||
this.baos.write(ch);
|
||||
immediateAfterBI = false;
|
||||
if (found == 0 && PRTokeniser.isWhitespace(ch)) {
|
||||
found++;
|
||||
continue;
|
||||
}
|
||||
if (found == 1 && ch == 69) {
|
||||
found++;
|
||||
continue;
|
||||
}
|
||||
if (found == 1 && PRTokeniser.isWhitespace(ch))
|
||||
continue;
|
||||
if (found == 2 && ch == 73) {
|
||||
found++;
|
||||
continue;
|
||||
}
|
||||
if (found == 3 && PRTokeniser.isWhitespace(ch))
|
||||
break;
|
||||
found = 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (Exception e) {
|
||||
throw new ExceptionConverter(e);
|
||||
}
|
||||
this.baos.flush();
|
||||
this.baos.close();
|
||||
stream.setData(this.baos.toByteArray());
|
||||
}
|
||||
|
||||
protected static void processOperator(OCGParser parser, PdfLiteral operator, List<PdfObject> operands) throws Exception {
|
||||
PdfOperator op = operators.get(operator.toString());
|
||||
if (op == null)
|
||||
op = operators.get("DefaultOperator");
|
||||
op.process(parser, operator, operands);
|
||||
}
|
||||
|
||||
protected static void populateOperators() {
|
||||
operators.put("DefaultOperator", new CopyContentOperator());
|
||||
PathConstructionOrPaintingOperator opConstructionPainting = new PathConstructionOrPaintingOperator();
|
||||
operators.put("m", opConstructionPainting);
|
||||
operators.put("l", opConstructionPainting);
|
||||
operators.put("c", opConstructionPainting);
|
||||
operators.put("v", opConstructionPainting);
|
||||
operators.put("y", opConstructionPainting);
|
||||
operators.put("h", opConstructionPainting);
|
||||
operators.put("re", opConstructionPainting);
|
||||
operators.put("S", opConstructionPainting);
|
||||
operators.put("s", opConstructionPainting);
|
||||
operators.put("f", opConstructionPainting);
|
||||
operators.put("F", opConstructionPainting);
|
||||
operators.put("f*", opConstructionPainting);
|
||||
operators.put("B", opConstructionPainting);
|
||||
operators.put("B*", opConstructionPainting);
|
||||
operators.put("b", opConstructionPainting);
|
||||
operators.put("b*", opConstructionPainting);
|
||||
operators.put("n", opConstructionPainting);
|
||||
operators.put("W", opConstructionPainting);
|
||||
operators.put("W*", opConstructionPainting);
|
||||
GraphicsOperator graphics = new GraphicsOperator();
|
||||
operators.put("q", graphics);
|
||||
operators.put("Q", graphics);
|
||||
operators.put("w", graphics);
|
||||
operators.put("J", graphics);
|
||||
operators.put("j", graphics);
|
||||
operators.put("M", graphics);
|
||||
operators.put("d", graphics);
|
||||
operators.put("ri", graphics);
|
||||
operators.put("i", graphics);
|
||||
operators.put("gs", graphics);
|
||||
operators.put("cm", graphics);
|
||||
operators.put("g", graphics);
|
||||
operators.put("G", graphics);
|
||||
operators.put("rg", graphics);
|
||||
operators.put("RG", graphics);
|
||||
operators.put("k", graphics);
|
||||
operators.put("K", graphics);
|
||||
operators.put("cs", graphics);
|
||||
operators.put("CS", graphics);
|
||||
operators.put("sc", graphics);
|
||||
operators.put("SC", graphics);
|
||||
operators.put("scn", graphics);
|
||||
operators.put("SCN", graphics);
|
||||
operators.put("sh", graphics);
|
||||
XObjectOperator xObject = new XObjectOperator();
|
||||
operators.put("Do", xObject);
|
||||
InlineImageOperator inlineImage = new InlineImageOperator();
|
||||
operators.put("BI", inlineImage);
|
||||
operators.put("EI", inlineImage);
|
||||
TextOperator text = new TextOperator();
|
||||
operators.put("BT", text);
|
||||
operators.put("ID", text);
|
||||
operators.put("ET", text);
|
||||
operators.put("Tc", text);
|
||||
operators.put("Tw", text);
|
||||
operators.put("Tz", text);
|
||||
operators.put("TL", text);
|
||||
operators.put("Tf", text);
|
||||
operators.put("Tr", text);
|
||||
operators.put("Ts", text);
|
||||
operators.put("Td", text);
|
||||
operators.put("TD", text);
|
||||
operators.put("Tm", text);
|
||||
operators.put("T*", text);
|
||||
operators.put("Tj", text);
|
||||
operators.put("'", text);
|
||||
operators.put("\"", text);
|
||||
operators.put("TJ", text);
|
||||
MarkedContentOperator markedContent = new MarkedContentOperator();
|
||||
operators.put("BMC", markedContent);
|
||||
operators.put("BDC", markedContent);
|
||||
operators.put("EMC", markedContent);
|
||||
}
|
||||
|
||||
protected boolean isVisible(List<PdfObject> operands) {
|
||||
if (operands.size() > 1 && this.xobj.contains(operands.get(0)))
|
||||
return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
protected boolean isToRemoved() {
|
||||
if (this.mc_balance > 0)
|
||||
return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
protected void checkMarkedContentStart(PdfName ocref) {
|
||||
if (this.mc_balance > 0) {
|
||||
this.mc_balance++;
|
||||
return;
|
||||
}
|
||||
if (this.properties == null)
|
||||
return;
|
||||
PdfDictionary ocdict = this.properties.getAsDict(ocref);
|
||||
if (ocdict == null)
|
||||
return;
|
||||
PdfString ocname = ocdict.getAsString(PdfName.NAME);
|
||||
if (ocname == null)
|
||||
return;
|
||||
if (this.ocgs.contains(ocname.toString()))
|
||||
this.mc_balance++;
|
||||
}
|
||||
|
||||
protected void checkMarkedContentEnd() {
|
||||
if (this.mc_balance > 0)
|
||||
this.mc_balance--;
|
||||
}
|
||||
|
||||
protected void process(PdfLiteral operator, List<PdfObject> operands, boolean removable) throws IOException {
|
||||
if (removable && isToRemoved())
|
||||
return;
|
||||
operands.remove(operator);
|
||||
for (PdfObject o : operands)
|
||||
printsp(o);
|
||||
println((PdfObject)operator);
|
||||
}
|
||||
|
||||
protected void printsp(PdfObject o) throws IOException {
|
||||
o.toPdf(null, this.baos);
|
||||
this.baos.write(32);
|
||||
}
|
||||
|
||||
protected void println(PdfObject o) throws IOException {
|
||||
o.toPdf(null, this.baos);
|
||||
this.baos.write(10);
|
||||
}
|
||||
|
||||
public static interface PdfOperator {
|
||||
void process(OCGParser param1OCGParser, PdfLiteral param1PdfLiteral, List<PdfObject> param1List) throws IOException;
|
||||
}
|
||||
|
||||
private static class PathConstructionOrPaintingOperator implements PdfOperator {
|
||||
private PathConstructionOrPaintingOperator() {}
|
||||
|
||||
public void process(OCGParser parser, PdfLiteral operator, List<PdfObject> operands) throws IOException {
|
||||
parser.process(operator, operands, true);
|
||||
}
|
||||
}
|
||||
|
||||
private static class GraphicsOperator implements PdfOperator {
|
||||
private GraphicsOperator() {}
|
||||
|
||||
public void process(OCGParser parser, PdfLiteral operator, List<PdfObject> operands) throws IOException {
|
||||
parser.process(operator, operands, false);
|
||||
}
|
||||
}
|
||||
|
||||
private static class XObjectOperator implements PdfOperator {
|
||||
private XObjectOperator() {}
|
||||
|
||||
public void process(OCGParser parser, PdfLiteral operator, List<PdfObject> operands) throws IOException {
|
||||
if (parser.isVisible(operands))
|
||||
parser.process(operator, operands, true);
|
||||
}
|
||||
}
|
||||
|
||||
private static class InlineImageOperator implements PdfOperator {
|
||||
private InlineImageOperator() {}
|
||||
|
||||
public void process(OCGParser parser, PdfLiteral operator, List<PdfObject> operands) throws IOException {
|
||||
parser.process(operator, operands, true);
|
||||
}
|
||||
}
|
||||
|
||||
private static class TextOperator implements PdfOperator {
|
||||
private TextOperator() {}
|
||||
|
||||
public void process(OCGParser parser, PdfLiteral operator, List<PdfObject> operands) throws IOException {
|
||||
parser.process(operator, operands, true);
|
||||
}
|
||||
}
|
||||
|
||||
private static class MarkedContentOperator implements PdfOperator {
|
||||
private MarkedContentOperator() {}
|
||||
|
||||
public void process(OCGParser parser, PdfLiteral operator, List<PdfObject> operands) throws IOException {
|
||||
if ("BDC".equals(operator.toString()) && operands.size() > 1 && PdfName.OC.equals(operands.get(0))) {
|
||||
parser.checkMarkedContentStart((PdfName)operands.get(1));
|
||||
} else if ("BMC".equals(operator.toString())) {
|
||||
parser.checkMarkedContentStart(null);
|
||||
}
|
||||
parser.process(operator, operands, true);
|
||||
if ("EMC".equals(operator.toString()))
|
||||
parser.checkMarkedContentEnd();
|
||||
}
|
||||
}
|
||||
|
||||
private static class CopyContentOperator implements PdfOperator {
|
||||
private CopyContentOperator() {}
|
||||
|
||||
public void process(OCGParser parser, PdfLiteral operator, List<PdfObject> operands) throws IOException {
|
||||
parser.process(operator, operands, true);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,137 @@
|
|||
package com.itextpdf.text.pdf.ocg;
|
||||
|
||||
import com.itextpdf.text.pdf.PRStream;
|
||||
import com.itextpdf.text.pdf.PdfArray;
|
||||
import com.itextpdf.text.pdf.PdfDictionary;
|
||||
import com.itextpdf.text.pdf.PdfName;
|
||||
import com.itextpdf.text.pdf.PdfObject;
|
||||
import com.itextpdf.text.pdf.PdfReader;
|
||||
import com.itextpdf.text.pdf.PdfString;
|
||||
import java.io.IOException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
|
||||
public class OCGRemover {
|
||||
public void removeLayers(PdfReader reader, String... layers) throws IOException {
|
||||
int n = reader.getNumberOfPages();
|
||||
for (int i = 1; i <= n; i++)
|
||||
reader.setPageContent(i, reader.getPageContent(i));
|
||||
Set<String> ocgs = new HashSet<String>();
|
||||
for (int j = 0; j < layers.length; j++)
|
||||
ocgs.add(layers[j]);
|
||||
OCGParser parser = new OCGParser(ocgs);
|
||||
for (int k = 1; k <= n; k++) {
|
||||
PdfDictionary page = reader.getPageN(k);
|
||||
parse(parser, page);
|
||||
page.remove(PdfName.PIECEINFO);
|
||||
removeAnnots(page, ocgs);
|
||||
removeProperties(page, ocgs);
|
||||
}
|
||||
PdfDictionary root = reader.getCatalog();
|
||||
PdfDictionary ocproperties = root.getAsDict(PdfName.OCPROPERTIES);
|
||||
if (ocproperties != null) {
|
||||
removeOCGsFromArray(ocproperties, PdfName.OCGS, ocgs);
|
||||
PdfDictionary d = ocproperties.getAsDict(PdfName.D);
|
||||
if (d != null) {
|
||||
removeOCGsFromArray(d, PdfName.ON, ocgs);
|
||||
removeOCGsFromArray(d, PdfName.OFF, ocgs);
|
||||
removeOCGsFromArray(d, PdfName.LOCKED, ocgs);
|
||||
removeOCGsFromArray(d, PdfName.RBGROUPS, ocgs);
|
||||
removeOCGsFromArray(d, PdfName.ORDER, ocgs);
|
||||
removeOCGsFromArray(d, PdfName.AS, ocgs);
|
||||
}
|
||||
PdfArray ocgsArray = ocproperties.getAsArray(PdfName.OCGS);
|
||||
if (ocgsArray != null && ocgsArray.isEmpty()) {
|
||||
root.remove(PdfName.OCPROPERTIES);
|
||||
if (PdfName.USEOC.equals(root.getAsName(PdfName.PAGEMODE)))
|
||||
root.remove(PdfName.PAGEMODE);
|
||||
}
|
||||
}
|
||||
reader.removeUnusedObjects();
|
||||
}
|
||||
|
||||
private void removeOCGsFromArray(PdfDictionary dict, PdfName name, Set<String> ocgs) {
|
||||
if (dict == null)
|
||||
return;
|
||||
PdfArray array = dict.getAsArray(name);
|
||||
if (array == null)
|
||||
return;
|
||||
removeOCGsFromArray(array, ocgs);
|
||||
}
|
||||
|
||||
private void removeOCGsFromArray(PdfArray array, Set<String> ocgs) {
|
||||
if (array == null)
|
||||
return;
|
||||
List<Integer> remove = new ArrayList<Integer>();
|
||||
for (int i = array.size(); i > 0; ) {
|
||||
PdfObject o = array.getDirectObject(--i);
|
||||
if (o.isDictionary()) {
|
||||
PdfDictionary dict = (PdfDictionary)o;
|
||||
if (isToBeRemoved(dict, ocgs)) {
|
||||
remove.add(Integer.valueOf(i));
|
||||
} else {
|
||||
removeOCGsFromArray(dict, PdfName.OCGS, ocgs);
|
||||
}
|
||||
}
|
||||
if (o.isArray())
|
||||
removeOCGsFromArray((PdfArray)o, ocgs);
|
||||
}
|
||||
for (Integer integer : remove)
|
||||
array.remove(integer.intValue());
|
||||
}
|
||||
|
||||
private void removeAnnots(PdfDictionary page, Set<String> ocgs) {
|
||||
PdfArray annots = page.getAsArray(PdfName.ANNOTS);
|
||||
if (annots == null)
|
||||
return;
|
||||
List<Integer> remove = new ArrayList<Integer>();
|
||||
for (int i = annots.size(); i > 0; ) {
|
||||
PdfDictionary annot = annots.getAsDict(--i);
|
||||
if (isToBeRemoved(annot.getAsDict(PdfName.OC), ocgs)) {
|
||||
remove.add(Integer.valueOf(i));
|
||||
continue;
|
||||
}
|
||||
removeOCGsFromArray(annot.getAsDict(PdfName.A), PdfName.STATE, ocgs);
|
||||
}
|
||||
for (Integer integer : remove)
|
||||
annots.remove(integer.intValue());
|
||||
}
|
||||
|
||||
private void removeProperties(PdfDictionary page, Set<String> ocgs) {
|
||||
PdfDictionary resources = page.getAsDict(PdfName.RESOURCES);
|
||||
if (resources == null)
|
||||
return;
|
||||
PdfDictionary properties = resources.getAsDict(PdfName.PROPERTIES);
|
||||
if (properties == null)
|
||||
return;
|
||||
Set<PdfName> names = properties.getKeys();
|
||||
List<PdfName> remove = new ArrayList<PdfName>();
|
||||
for (PdfName name : names) {
|
||||
PdfDictionary dict = properties.getAsDict(name);
|
||||
if (isToBeRemoved(dict, ocgs)) {
|
||||
remove.add(name);
|
||||
continue;
|
||||
}
|
||||
removeOCGsFromArray(dict, PdfName.OCGS, ocgs);
|
||||
}
|
||||
for (PdfName name : remove)
|
||||
properties.remove(name);
|
||||
}
|
||||
|
||||
private boolean isToBeRemoved(PdfDictionary ocg, Set<String> names) {
|
||||
if (ocg == null)
|
||||
return false;
|
||||
PdfString n = ocg.getAsString(PdfName.NAME);
|
||||
if (n == null)
|
||||
return false;
|
||||
return names.contains(n.toString());
|
||||
}
|
||||
|
||||
private void parse(OCGParser parser, PdfDictionary page) throws IOException {
|
||||
PRStream stream = (PRStream)page.getAsStream(PdfName.CONTENTS);
|
||||
PdfDictionary resources = page.getAsDict(PdfName.RESOURCES);
|
||||
parser.parse(stream, resources);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,63 @@
|
|||
package com.itextpdf.text.pdf.pdfcleanup;
|
||||
|
||||
import com.itextpdf.text.pdf.PdfString;
|
||||
import com.itextpdf.text.pdf.parser.Vector;
|
||||
|
||||
abstract class PdfCleanUpContentChunk {
|
||||
private boolean visible;
|
||||
|
||||
public PdfCleanUpContentChunk(boolean visible) {
|
||||
this.visible = visible;
|
||||
}
|
||||
|
||||
public boolean isVisible() {
|
||||
return this.visible;
|
||||
}
|
||||
|
||||
public static class Text extends PdfCleanUpContentChunk {
|
||||
private PdfString text;
|
||||
|
||||
private float startX;
|
||||
|
||||
private float endX;
|
||||
|
||||
private int numOfStrTextBelongsTo;
|
||||
|
||||
public Text(PdfString text, Vector startLocation, Vector endLocation, boolean visible, int numOfStrTextBelongsTo) {
|
||||
super(visible);
|
||||
this.text = text;
|
||||
this.startX = startLocation.get(0);
|
||||
this.endX = endLocation.get(0);
|
||||
this.numOfStrTextBelongsTo = numOfStrTextBelongsTo;
|
||||
}
|
||||
|
||||
public PdfString getText() {
|
||||
return this.text;
|
||||
}
|
||||
|
||||
public float getStartX() {
|
||||
return this.startX;
|
||||
}
|
||||
|
||||
public float getEndX() {
|
||||
return this.endX;
|
||||
}
|
||||
|
||||
public int getNumOfStrTextBelongsTo() {
|
||||
return this.numOfStrTextBelongsTo;
|
||||
}
|
||||
}
|
||||
|
||||
public static class Image extends PdfCleanUpContentChunk {
|
||||
private byte[] newImageData;
|
||||
|
||||
public Image(boolean visible, byte[] newImageData) {
|
||||
super(visible);
|
||||
this.newImageData = newImageData;
|
||||
}
|
||||
|
||||
public byte[] getNewImageData() {
|
||||
return this.newImageData;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,387 @@
|
|||
package com.itextpdf.text.pdf.pdfcleanup;
|
||||
|
||||
import com.itextpdf.awt.geom.Point2D;
|
||||
import com.itextpdf.text.BadElementException;
|
||||
import com.itextpdf.text.DocWriter;
|
||||
import com.itextpdf.text.Image;
|
||||
import com.itextpdf.text.pdf.BadPdfFormatException;
|
||||
import com.itextpdf.text.pdf.PRStream;
|
||||
import com.itextpdf.text.pdf.PdfArray;
|
||||
import com.itextpdf.text.pdf.PdfContentByte;
|
||||
import com.itextpdf.text.pdf.PdfDictionary;
|
||||
import com.itextpdf.text.pdf.PdfImage;
|
||||
import com.itextpdf.text.pdf.PdfLiteral;
|
||||
import com.itextpdf.text.pdf.PdfName;
|
||||
import com.itextpdf.text.pdf.PdfNumber;
|
||||
import com.itextpdf.text.pdf.PdfObject;
|
||||
import com.itextpdf.text.pdf.PdfStream;
|
||||
import com.itextpdf.text.pdf.PdfString;
|
||||
import com.itextpdf.text.pdf.PdfWriter;
|
||||
import com.itextpdf.text.pdf.parser.BezierCurve;
|
||||
import com.itextpdf.text.pdf.parser.ContentOperator;
|
||||
import com.itextpdf.text.pdf.parser.GraphicsState;
|
||||
import com.itextpdf.text.pdf.parser.Line;
|
||||
import com.itextpdf.text.pdf.parser.Path;
|
||||
import com.itextpdf.text.pdf.parser.PdfContentStreamProcessor;
|
||||
import com.itextpdf.text.pdf.parser.Shape;
|
||||
import com.itextpdf.text.pdf.parser.Subpath;
|
||||
import java.io.IOException;
|
||||
import java.io.OutputStream;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collections;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
class PdfCleanUpContentOperator implements ContentOperator {
|
||||
private static final byte[] TStar = DocWriter.getISOBytes("T*\n");
|
||||
|
||||
private static final byte[] Tw = DocWriter.getISOBytes(" Tw ");
|
||||
|
||||
private static final byte[] TcTStar = DocWriter.getISOBytes(" Tc T*\n");
|
||||
|
||||
private static final byte[] TJ = DocWriter.getISOBytes("] TJ\n");
|
||||
|
||||
private static final byte[] Tc = DocWriter.getISOBytes(" Tc\n");
|
||||
|
||||
private static final byte[] m = DocWriter.getISOBytes(" m\n");
|
||||
|
||||
private static final byte[] l = DocWriter.getISOBytes(" l\n");
|
||||
|
||||
private static final byte[] c = DocWriter.getISOBytes(" c\n");
|
||||
|
||||
private static final byte[] h = DocWriter.getISOBytes("h\n");
|
||||
|
||||
private static final byte[] S = DocWriter.getISOBytes("S\n");
|
||||
|
||||
private static final byte[] f = DocWriter.getISOBytes("f\n");
|
||||
|
||||
private static final byte[] eoF = DocWriter.getISOBytes("f*\n");
|
||||
|
||||
private static final byte[] n = DocWriter.getISOBytes("n\n");
|
||||
|
||||
private static final byte[] W = DocWriter.getISOBytes("W\n");
|
||||
|
||||
private static final byte[] eoW = DocWriter.getISOBytes("W*\n");
|
||||
|
||||
private static final byte[] q = DocWriter.getISOBytes("q\n");
|
||||
|
||||
private static final byte[] Q = DocWriter.getISOBytes("Q\n");
|
||||
|
||||
private static final byte[] cs = DocWriter.getISOBytes("cs\n");
|
||||
|
||||
private static final Set<String> textShowingOperators = new HashSet<String>(Arrays.<String>asList("TJ", "Tj", "'", "\""));
|
||||
|
||||
private static final Set<String> pathConstructionOperators = new HashSet<String>(Arrays.<String>asList("m", "l", "c", "v", "y", "h", "re"));
|
||||
|
||||
private static final Set<String> strokeOperators = new HashSet<String>(Arrays.<String>asList("S", "s", "B", "B*", "b", "b*"));
|
||||
|
||||
private static final Set<String> nwFillOperators = new HashSet<String>(Arrays.<String>asList("f", "F", "B", "b"));
|
||||
|
||||
private static final Set<String> eoFillOperators = new HashSet<String>(Arrays.<String>asList("f*", "B*", "b*"));
|
||||
|
||||
private static final Set<String> pathPaintingOperators = new HashSet<String>() {
|
||||
{
|
||||
addAll(PdfCleanUpContentOperator.strokeOperators);
|
||||
addAll(PdfCleanUpContentOperator.nwFillOperators);
|
||||
addAll(PdfCleanUpContentOperator.eoFillOperators);
|
||||
add("n");
|
||||
}
|
||||
};
|
||||
|
||||
private static final Set<String> clippingPathOperators = new HashSet<String>(Arrays.<String>asList("W", "W*"));
|
||||
|
||||
private static final Set<String> lineStyleOperators = new HashSet<String>(Arrays.<String>asList("w", "J", "j", "M", "d"));
|
||||
|
||||
private static final Set<String> strokeColorOperators = new HashSet<String>(Arrays.<String>asList("CS", "SC", "SCN", "G", "RG", "K"));
|
||||
|
||||
protected PdfCleanUpRenderListener cleanUpStrategy;
|
||||
|
||||
protected ContentOperator originalContentOperator;
|
||||
|
||||
public PdfCleanUpContentOperator(PdfCleanUpRenderListener cleanUpStrategy) {
|
||||
this.cleanUpStrategy = cleanUpStrategy;
|
||||
}
|
||||
|
||||
public static void populateOperators(PdfContentStreamProcessor contentProcessor, PdfCleanUpRenderListener pdfCleanUpRenderListener) {
|
||||
for (String operator : (Iterable<String>)contentProcessor.getRegisteredOperatorStrings()) {
|
||||
PdfCleanUpContentOperator contentOperator = new PdfCleanUpContentOperator(pdfCleanUpRenderListener);
|
||||
contentOperator.originalContentOperator = contentProcessor.registerContentOperator(operator, contentOperator);
|
||||
}
|
||||
}
|
||||
|
||||
public void invoke(PdfContentStreamProcessor pdfContentStreamProcessor, PdfLiteral operator, ArrayList<PdfObject> operands) throws Exception {
|
||||
String operatorStr = operator.toString();
|
||||
PdfContentByte canvas = this.cleanUpStrategy.getContext().getCanvas();
|
||||
PRStream xFormStream = null;
|
||||
boolean disableOutput = (pathConstructionOperators.contains(operatorStr) || pathPaintingOperators.contains(operatorStr) || clippingPathOperators.contains(operatorStr));
|
||||
GraphicsState gs = pdfContentStreamProcessor.gs();
|
||||
Map<Integer, Float> structuredTJoperands = null;
|
||||
if ("Do".equals(operatorStr) &&
|
||||
operands.size() == 2 && operands.get(0).isName()) {
|
||||
PdfDictionary xObjResources = this.cleanUpStrategy.getContext().getResources().getAsDict(PdfName.XOBJECT);
|
||||
if (xObjResources != null) {
|
||||
PdfStream xObj = xObjResources.getAsStream((PdfName)operands.get(0));
|
||||
if (xObj instanceof PRStream && xObj.getAsName(PdfName.SUBTYPE) != null &&
|
||||
xObj.getAsName(PdfName.SUBTYPE).compareTo(PdfName.FORM) == 0) {
|
||||
xFormStream = (PRStream)xObj;
|
||||
this.cleanUpStrategy.registerNewContext(xObj.getAsDict(PdfName.RESOURCES), null);
|
||||
}
|
||||
}
|
||||
}
|
||||
this.originalContentOperator.invoke(pdfContentStreamProcessor, operator, operands);
|
||||
List<PdfCleanUpContentChunk> chunks = this.cleanUpStrategy.getChunks();
|
||||
if (xFormStream != null) {
|
||||
xFormStream.setData(this.cleanUpStrategy.getContext().getCanvas().toPdf(this.cleanUpStrategy.getContext().getCanvas().getPdfWriter()));
|
||||
this.cleanUpStrategy.popContext();
|
||||
canvas = this.cleanUpStrategy.getContext().getCanvas();
|
||||
}
|
||||
if ("Do".equals(operatorStr)) {
|
||||
if (chunks.size() > 0 && chunks.get(0) instanceof PdfCleanUpContentChunk.Image) {
|
||||
PdfCleanUpContentChunk.Image chunk = (PdfCleanUpContentChunk.Image)chunks.get(0);
|
||||
if (chunk.isVisible()) {
|
||||
PdfDictionary xObjResources = this.cleanUpStrategy.getContext().getResources().getAsDict(PdfName.XOBJECT);
|
||||
PRStream imageStream = (PRStream)xObjResources.getAsStream((PdfName)operands.get(0));
|
||||
updateImageStream(imageStream, chunk.getNewImageData());
|
||||
} else {
|
||||
disableOutput = true;
|
||||
}
|
||||
}
|
||||
} else if (lineStyleOperators.contains(operatorStr)) {
|
||||
disableOutput = true;
|
||||
} else if (textShowingOperators.contains(operatorStr) && !allChunksAreVisible(this.cleanUpStrategy.getChunks())) {
|
||||
disableOutput = true;
|
||||
if ("'".equals(operatorStr)) {
|
||||
canvas.getInternalBuffer().append(TStar);
|
||||
} else if ("\"".equals(operatorStr)) {
|
||||
operands.get(0).toPdf(canvas.getPdfWriter(), (OutputStream)canvas.getInternalBuffer());
|
||||
canvas.getInternalBuffer().append(Tw);
|
||||
operands.get(1).toPdf(canvas.getPdfWriter(), (OutputStream)canvas.getInternalBuffer());
|
||||
canvas.getInternalBuffer().append(TcTStar);
|
||||
} else if ("TJ".equals(operatorStr)) {
|
||||
structuredTJoperands = structureTJarray((PdfArray)operands.get(0));
|
||||
}
|
||||
writeTextChunks(structuredTJoperands, chunks, canvas, gs.getCharacterSpacing(), gs.getWordSpacing(),
|
||||
gs.getFontSize(), gs.getHorizontalScaling());
|
||||
} else if (pathPaintingOperators.contains(operatorStr)) {
|
||||
writePath(operatorStr, canvas, gs.getColorSpaceStroke());
|
||||
} else if (strokeColorOperators.contains(operatorStr)) {
|
||||
this.cleanUpStrategy.getContext().popStrokeColor();
|
||||
this.cleanUpStrategy.getContext().pushStrokeColor(operands);
|
||||
} else if ("q".equals(operatorStr)) {
|
||||
this.cleanUpStrategy.getContext().pushStrokeColor(this.cleanUpStrategy.getContext().peekStrokeColor());
|
||||
} else if ("Q".equals(operatorStr)) {
|
||||
this.cleanUpStrategy.getContext().popStrokeColor();
|
||||
}
|
||||
if (!disableOutput)
|
||||
writeOperands(canvas, operands);
|
||||
this.cleanUpStrategy.clearChunks();
|
||||
}
|
||||
|
||||
private void writeOperands(PdfContentByte canvas, List<PdfObject> operands) throws IOException {
|
||||
int index = 0;
|
||||
for (PdfObject o : operands) {
|
||||
toPdf(o, canvas.getPdfWriter(), (OutputStream)canvas.getInternalBuffer());
|
||||
canvas.getInternalBuffer().append((byte)((operands.size() > ++index) ? 32 : 10));
|
||||
}
|
||||
}
|
||||
|
||||
private boolean allChunksAreVisible(List<PdfCleanUpContentChunk> chunks) {
|
||||
for (PdfCleanUpContentChunk chunk : chunks) {
|
||||
if (!chunk.isVisible())
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
private static void toPdf(PdfObject object, PdfWriter writer, OutputStream os) throws IOException {
|
||||
if (object instanceof PdfDictionary) {
|
||||
os.write(60);
|
||||
os.write(60);
|
||||
List<PdfName> keys = new ArrayList<PdfName>(((PdfDictionary)object).getKeys());
|
||||
Collections.<PdfName>sort(keys);
|
||||
for (PdfName key : keys) {
|
||||
toPdf((PdfObject)key, writer, os);
|
||||
PdfObject value = ((PdfDictionary)object).get(key);
|
||||
int type = value.type();
|
||||
if (type != 5 && type != 6 && type != 4 && type != 3)
|
||||
os.write(32);
|
||||
toPdf(value, writer, os);
|
||||
}
|
||||
os.write(62);
|
||||
os.write(62);
|
||||
} else {
|
||||
object.toPdf(writer, os);
|
||||
}
|
||||
}
|
||||
|
||||
private Map<Integer, Float> structureTJarray(PdfArray array) {
|
||||
Map<Integer, Float> structuredTJoperands = new HashMap<Integer, Float>();
|
||||
if (array.size() == 0)
|
||||
return structuredTJoperands;
|
||||
Integer previousStrNum = 0;
|
||||
structuredTJoperands.put(previousStrNum, Float.valueOf(0.0F));
|
||||
for (int i = 0; i < array.size(); i++) {
|
||||
PdfObject currentObj = array.getPdfObject(i);
|
||||
if (currentObj instanceof PdfString && ((PdfString)currentObj).toUnicodeString().length() > 0) {
|
||||
previousStrNum = previousStrNum + 1;
|
||||
structuredTJoperands.put(previousStrNum, Float.valueOf(0.0F));
|
||||
} else {
|
||||
Float oldOffset = structuredTJoperands.get(previousStrNum);
|
||||
structuredTJoperands.put(previousStrNum, Float.valueOf(oldOffset + ((PdfNumber)currentObj).floatValue()));
|
||||
}
|
||||
}
|
||||
return structuredTJoperands;
|
||||
}
|
||||
|
||||
private void writeTextChunks(Map<Integer, Float> structuredTJoperands, List<PdfCleanUpContentChunk> chunks, PdfContentByte canvas, float characterSpacing, float wordSpacing, float fontSize, float horizontalScaling) throws IOException {
|
||||
canvas.setCharacterSpacing(0.0F);
|
||||
canvas.setWordSpacing(0.0F);
|
||||
canvas.getInternalBuffer().append((byte)91);
|
||||
float convertedCharacterSpacing = -characterSpacing * 1000.0F / fontSize;
|
||||
float convertedWordSpacing = -wordSpacing * 1000.0F / fontSize;
|
||||
float shift = (structuredTJoperands != null) ? structuredTJoperands.get(Integer.valueOf(0)) : 0.0F;
|
||||
PdfCleanUpContentChunk.Text prevChunk = null;
|
||||
for (PdfCleanUpContentChunk chunk : chunks) {
|
||||
PdfCleanUpContentChunk.Text textChunk = (PdfCleanUpContentChunk.Text)chunk;
|
||||
if (prevChunk != null && prevChunk.getNumOfStrTextBelongsTo() != textChunk.getNumOfStrTextBelongsTo() && structuredTJoperands != null)
|
||||
shift += structuredTJoperands.get(Integer.valueOf(prevChunk.getNumOfStrTextBelongsTo()));
|
||||
if (textChunk.isVisible()) {
|
||||
if (Float.compare(shift, 0.0F) != 0 && Float.compare(shift, -0.0F) != 0)
|
||||
canvas.getInternalBuffer().append(shift).append(' ');
|
||||
textChunk.getText().toPdf(canvas.getPdfWriter(), (OutputStream)canvas.getInternalBuffer());
|
||||
canvas.getInternalBuffer().append(' ');
|
||||
shift = convertedCharacterSpacing + (isSpace(textChunk) ? convertedWordSpacing : 0.0F);
|
||||
} else {
|
||||
shift += getUnscaledTextChunkWidth(textChunk, characterSpacing, wordSpacing, fontSize, horizontalScaling);
|
||||
}
|
||||
prevChunk = textChunk;
|
||||
}
|
||||
if (Float.compare(shift, 0.0F) != 0 && Float.compare(shift, -0.0F) != 0)
|
||||
canvas.getInternalBuffer().append(shift);
|
||||
canvas.getInternalBuffer().append(TJ);
|
||||
if (Float.compare(characterSpacing, 0.0F) != 0 && Float.compare(characterSpacing, -0.0F) != 0) {
|
||||
new PdfNumber(characterSpacing).toPdf(canvas.getPdfWriter(), (OutputStream)canvas.getInternalBuffer());
|
||||
canvas.getInternalBuffer().append(Tc);
|
||||
}
|
||||
if (Float.compare(wordSpacing, 0.0F) != 0 && Float.compare(wordSpacing, -0.0F) != 0) {
|
||||
new PdfNumber(wordSpacing).toPdf(canvas.getPdfWriter(), (OutputStream)canvas.getInternalBuffer());
|
||||
canvas.getInternalBuffer().append(Tw);
|
||||
}
|
||||
}
|
||||
|
||||
private float getUnscaledTextChunkWidth(PdfCleanUpContentChunk.Text chunk, float characterSpacing, float wordSpacing, float fontSize, float horizontalScaling) {
|
||||
float scaledChunkWidth = chunk.getEndX() - chunk.getStartX() + (characterSpacing + (
|
||||
isSpace(chunk) ? wordSpacing : 0.0F)) * horizontalScaling;
|
||||
return -scaledChunkWidth * 1000.0F / (horizontalScaling * fontSize);
|
||||
}
|
||||
|
||||
private boolean isSpace(PdfCleanUpContentChunk.Text chunk) {
|
||||
return chunk.getText().toUnicodeString().equals(" ");
|
||||
}
|
||||
|
||||
private void updateImageStream(PRStream imageStream, byte[] newData) throws BadElementException, IOException, BadPdfFormatException {
|
||||
PdfImage image = new PdfImage(Image.getInstance(newData), "", null);
|
||||
if (imageStream.contains(PdfName.SMASK))
|
||||
image.put(PdfName.SMASK, imageStream.get(PdfName.SMASK));
|
||||
if (imageStream.contains(PdfName.MASK))
|
||||
image.put(PdfName.MASK, imageStream.get(PdfName.MASK));
|
||||
if (imageStream.contains(PdfName.SMASKINDATA))
|
||||
image.put(PdfName.SMASKINDATA, imageStream.get(PdfName.SMASKINDATA));
|
||||
imageStream.clear();
|
||||
imageStream.putAll((PdfDictionary)image);
|
||||
imageStream.setDataRaw(image.getBytes());
|
||||
}
|
||||
|
||||
private void writePath(String operatorStr, PdfContentByte canvas, PdfName strokeColorSpace) throws IOException {
|
||||
if (nwFillOperators.contains(operatorStr)) {
|
||||
writePath(this.cleanUpStrategy.getCurrentFillPath(), f, canvas);
|
||||
} else if (eoFillOperators.contains(operatorStr)) {
|
||||
writePath(this.cleanUpStrategy.getCurrentFillPath(), eoF, canvas);
|
||||
}
|
||||
if (strokeOperators.contains(operatorStr))
|
||||
writeStroke(canvas, this.cleanUpStrategy.getCurrentStrokePath(), strokeColorSpace);
|
||||
if (this.cleanUpStrategy.isClipped()) {
|
||||
if (!this.cleanUpStrategy.getNewClipPath().isEmpty()) {
|
||||
byte[] clippingOperator = (this.cleanUpStrategy.getClippingRule() == 1) ? W : eoW;
|
||||
writePath(this.cleanUpStrategy.getNewClipPath(), clippingOperator, canvas);
|
||||
} else {
|
||||
Path degeneratePath = new Path();
|
||||
degeneratePath.moveTo(0.0F, 0.0F);
|
||||
writePath(degeneratePath, W, canvas);
|
||||
}
|
||||
canvas.getInternalBuffer().append(n);
|
||||
this.cleanUpStrategy.setClipped(false);
|
||||
}
|
||||
}
|
||||
|
||||
private void writePath(Path path, byte[] pathPaintingOperator, PdfContentByte canvas) throws IOException {
|
||||
if (path.isEmpty())
|
||||
return;
|
||||
for (Subpath subpath : (Iterable<Subpath>)path.getSubpaths()) {
|
||||
writeMoveTo(subpath.getStartPoint(), canvas);
|
||||
for (Shape segment : (Iterable<Shape>)subpath.getSegments()) {
|
||||
if (segment instanceof BezierCurve) {
|
||||
writeBezierCurve((BezierCurve)segment, canvas);
|
||||
continue;
|
||||
}
|
||||
writeLine((Line)segment, canvas);
|
||||
}
|
||||
if (subpath.isClosed())
|
||||
canvas.getInternalBuffer().append(h);
|
||||
}
|
||||
if (pathPaintingOperator != null)
|
||||
canvas.getInternalBuffer().append(pathPaintingOperator);
|
||||
}
|
||||
|
||||
private void writeMoveTo(Point2D destinationPoint, PdfContentByte canvas) throws IOException {
|
||||
new PdfNumber(destinationPoint.getX()).toPdf(canvas.getPdfWriter(), (OutputStream)canvas.getInternalBuffer());
|
||||
canvas.getInternalBuffer().append(' ');
|
||||
new PdfNumber(destinationPoint.getY()).toPdf(canvas.getPdfWriter(), (OutputStream)canvas.getInternalBuffer());
|
||||
canvas.getInternalBuffer().append(m);
|
||||
}
|
||||
|
||||
private void writeBezierCurve(BezierCurve curve, PdfContentByte canvas) throws IOException {
|
||||
List<Point2D> basePoints = curve.getBasePoints();
|
||||
Point2D p2 = basePoints.get(1);
|
||||
Point2D p3 = basePoints.get(2);
|
||||
Point2D p4 = basePoints.get(3);
|
||||
new PdfNumber(p2.getX()).toPdf(canvas.getPdfWriter(), (OutputStream)canvas.getInternalBuffer());
|
||||
canvas.getInternalBuffer().append(' ');
|
||||
new PdfNumber(p2.getY()).toPdf(canvas.getPdfWriter(), (OutputStream)canvas.getInternalBuffer());
|
||||
canvas.getInternalBuffer().append(' ');
|
||||
new PdfNumber(p3.getX()).toPdf(canvas.getPdfWriter(), (OutputStream)canvas.getInternalBuffer());
|
||||
canvas.getInternalBuffer().append(' ');
|
||||
new PdfNumber(p3.getY()).toPdf(canvas.getPdfWriter(), (OutputStream)canvas.getInternalBuffer());
|
||||
canvas.getInternalBuffer().append(' ');
|
||||
new PdfNumber(p4.getX()).toPdf(canvas.getPdfWriter(), (OutputStream)canvas.getInternalBuffer());
|
||||
canvas.getInternalBuffer().append(' ');
|
||||
new PdfNumber(p4.getY()).toPdf(canvas.getPdfWriter(), (OutputStream)canvas.getInternalBuffer());
|
||||
canvas.getInternalBuffer().append(c);
|
||||
}
|
||||
|
||||
private void writeLine(Line line, PdfContentByte canvas) throws IOException {
|
||||
Point2D destination = line.getBasePoints().get(1);
|
||||
new PdfNumber(destination.getX()).toPdf(canvas.getPdfWriter(), (OutputStream)canvas.getInternalBuffer());
|
||||
canvas.getInternalBuffer().append(' ');
|
||||
new PdfNumber(destination.getY()).toPdf(canvas.getPdfWriter(), (OutputStream)canvas.getInternalBuffer());
|
||||
canvas.getInternalBuffer().append(l);
|
||||
}
|
||||
|
||||
private void writeStroke(PdfContentByte canvas, Path path, PdfName strokeColorSpace) throws IOException {
|
||||
canvas.getInternalBuffer().append(q);
|
||||
if (strokeColorSpace != null) {
|
||||
strokeColorSpace.toPdf(canvas.getPdfWriter(), (OutputStream)canvas.getInternalBuffer());
|
||||
canvas.getInternalBuffer().append(' ').append(cs);
|
||||
}
|
||||
List<PdfObject> strokeColorOperands = this.cleanUpStrategy.getContext().peekStrokeColor();
|
||||
String strokeOperatorStr = strokeColorOperands.get(strokeColorOperands.size() - 1).toString();
|
||||
strokeColorOperands.set(strokeColorOperands.size() - 1, new PdfLiteral(strokeOperatorStr.toLowerCase()));
|
||||
writeOperands(canvas, strokeColorOperands);
|
||||
writePath(path, f, canvas);
|
||||
canvas.getInternalBuffer().append(Q);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,61 @@
|
|||
package com.itextpdf.text.pdf.pdfcleanup;
|
||||
|
||||
import com.itextpdf.text.pdf.PdfContentByte;
|
||||
import com.itextpdf.text.pdf.PdfDictionary;
|
||||
import com.itextpdf.text.pdf.PdfLiteral;
|
||||
import com.itextpdf.text.pdf.PdfName;
|
||||
import com.itextpdf.text.pdf.PdfObject;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.Stack;
|
||||
|
||||
class PdfCleanUpContext {
|
||||
private PdfDictionary resources;
|
||||
|
||||
private PdfContentByte canvas;
|
||||
|
||||
private Stack<List<PdfObject>> strokeColorOperands;
|
||||
|
||||
public PdfCleanUpContext() {
|
||||
List<PdfObject> initialStrokeColor = new ArrayList<PdfObject>(Arrays.<PdfObject>asList((PdfObject)PdfName.DEVICEGRAY, new PdfLiteral("CS")));
|
||||
this.strokeColorOperands = new Stack<List<PdfObject>>();
|
||||
this.strokeColorOperands.push(initialStrokeColor);
|
||||
}
|
||||
|
||||
public PdfCleanUpContext(PdfDictionary resources, PdfContentByte canvas) {
|
||||
this();
|
||||
this.resources = resources;
|
||||
this.canvas = canvas;
|
||||
}
|
||||
|
||||
public PdfDictionary getResources() {
|
||||
return this.resources;
|
||||
}
|
||||
|
||||
public void setResources(PdfDictionary resources) {
|
||||
this.resources = resources;
|
||||
}
|
||||
|
||||
public PdfContentByte getCanvas() {
|
||||
return this.canvas;
|
||||
}
|
||||
|
||||
public void setCanvas(PdfContentByte canvas) {
|
||||
this.canvas = canvas;
|
||||
}
|
||||
|
||||
public void pushStrokeColor(List<PdfObject> strokeColorOperands) {
|
||||
this.strokeColorOperands.push(new ArrayList<PdfObject>(strokeColorOperands));
|
||||
}
|
||||
|
||||
public List<PdfObject> peekStrokeColor() {
|
||||
if (this.strokeColorOperands.size() == 0)
|
||||
return null;
|
||||
return this.strokeColorOperands.peek();
|
||||
}
|
||||
|
||||
public List<PdfObject> popStrokeColor() {
|
||||
return this.strokeColorOperands.pop();
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,34 @@
|
|||
package com.itextpdf.text.pdf.pdfcleanup;
|
||||
|
||||
import com.itextpdf.text.BaseColor;
|
||||
import com.itextpdf.text.Rectangle;
|
||||
|
||||
public class PdfCleanUpLocation {
|
||||
private int page;
|
||||
|
||||
private Rectangle region;
|
||||
|
||||
private BaseColor cleanUpColor;
|
||||
|
||||
public PdfCleanUpLocation(int page, Rectangle region) {
|
||||
this.page = page;
|
||||
this.region = region;
|
||||
}
|
||||
|
||||
public PdfCleanUpLocation(int page, Rectangle region, BaseColor cleanUpColor) {
|
||||
this(page, region);
|
||||
this.cleanUpColor = cleanUpColor;
|
||||
}
|
||||
|
||||
public int getPage() {
|
||||
return this.page;
|
||||
}
|
||||
|
||||
public Rectangle getRegion() {
|
||||
return this.region;
|
||||
}
|
||||
|
||||
public BaseColor getCleanUpColor() {
|
||||
return this.cleanUpColor;
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,395 @@
|
|||
package com.itextpdf.text.pdf.pdfcleanup;
|
||||
|
||||
import com.itextpdf.text.BaseColor;
|
||||
import com.itextpdf.text.DocumentException;
|
||||
import com.itextpdf.text.Font;
|
||||
import com.itextpdf.text.Phrase;
|
||||
import com.itextpdf.text.Rectangle;
|
||||
import com.itextpdf.text.io.RandomAccessSourceFactory;
|
||||
import com.itextpdf.text.pdf.BaseFont;
|
||||
import com.itextpdf.text.pdf.ColumnText;
|
||||
import com.itextpdf.text.pdf.PRIndirectReference;
|
||||
import com.itextpdf.text.pdf.PRTokeniser;
|
||||
import com.itextpdf.text.pdf.PdfArray;
|
||||
import com.itextpdf.text.pdf.PdfBoolean;
|
||||
import com.itextpdf.text.pdf.PdfContentByte;
|
||||
import com.itextpdf.text.pdf.PdfDictionary;
|
||||
import com.itextpdf.text.pdf.PdfIndirectReference;
|
||||
import com.itextpdf.text.pdf.PdfName;
|
||||
import com.itextpdf.text.pdf.PdfNumber;
|
||||
import com.itextpdf.text.pdf.PdfReader;
|
||||
import com.itextpdf.text.pdf.PdfStamper;
|
||||
import com.itextpdf.text.pdf.PdfStream;
|
||||
import com.itextpdf.text.pdf.PdfString;
|
||||
import com.itextpdf.text.pdf.RandomAccessFileOrArray;
|
||||
import com.itextpdf.text.pdf.parser.ContentByteUtils;
|
||||
import com.itextpdf.text.pdf.parser.PdfContentStreamProcessor;
|
||||
import com.itextpdf.text.pdf.parser.RenderListener;
|
||||
import java.io.IOException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collection;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
public class PdfCleanUpProcessor {
|
||||
public static double floatMultiplier = Math.pow(10.0D, 14.0D);
|
||||
|
||||
public static boolean fillCleanedArea = true;
|
||||
|
||||
public static double arcTolerance = 0.0025D;
|
||||
|
||||
private static final String XOBJ_NAME_PREFIX = "Fm";
|
||||
|
||||
private static final String STROKE_COLOR = "StrokeColor";
|
||||
|
||||
private static final String FILL_COLOR = "FillColor";
|
||||
|
||||
private int currentXObjNum = 0;
|
||||
|
||||
private PdfStamper pdfStamper;
|
||||
|
||||
private Map<Integer, List<PdfCleanUpLocation>> pdfCleanUpLocations;
|
||||
|
||||
private Map<Integer, Set<String>> redactAnnotIndirRefs;
|
||||
|
||||
private Map<Integer, List<Rectangle>> clippingRects;
|
||||
|
||||
public PdfCleanUpProcessor(List<PdfCleanUpLocation> pdfCleanUpLocations, PdfStamper pdfStamper) {
|
||||
this.pdfCleanUpLocations = organizeLocationsByPage(pdfCleanUpLocations);
|
||||
this.pdfStamper = pdfStamper;
|
||||
}
|
||||
|
||||
public PdfCleanUpProcessor(PdfStamper pdfStamper) {
|
||||
this.redactAnnotIndirRefs = new HashMap<Integer, Set<String>>();
|
||||
this.clippingRects = new HashMap<Integer, List<Rectangle>>();
|
||||
this.pdfStamper = pdfStamper;
|
||||
extractLocationsFromRedactAnnots();
|
||||
}
|
||||
|
||||
public void cleanUp() throws IOException, DocumentException {
|
||||
for (Map.Entry<Integer, List<PdfCleanUpLocation>> entry : this.pdfCleanUpLocations.entrySet())
|
||||
cleanUpPage(entry.getKey().intValue(), entry.getValue());
|
||||
this.pdfStamper.getReader().removeUnusedObjects();
|
||||
}
|
||||
|
||||
private void cleanUpPage(int pageNum, List<PdfCleanUpLocation> cleanUpLocations) throws IOException, DocumentException {
|
||||
if (cleanUpLocations.size() == 0)
|
||||
return;
|
||||
PdfReader pdfReader = this.pdfStamper.getReader();
|
||||
PdfDictionary page = pdfReader.getPageN(pageNum);
|
||||
PdfContentByte canvas = this.pdfStamper.getUnderContent(pageNum);
|
||||
byte[] pageContentInput = ContentByteUtils.getContentBytesForPage(pdfReader, pageNum);
|
||||
page.remove(PdfName.CONTENTS);
|
||||
canvas.saveState();
|
||||
PdfCleanUpRegionFilter filter = createFilter(cleanUpLocations);
|
||||
PdfCleanUpRenderListener pdfCleanUpRenderListener = new PdfCleanUpRenderListener(this.pdfStamper, filter);
|
||||
pdfCleanUpRenderListener.registerNewContext(pdfReader.getPageResources(page), canvas);
|
||||
PdfContentStreamProcessor contentProcessor = new PdfContentStreamProcessor((RenderListener)pdfCleanUpRenderListener);
|
||||
PdfCleanUpContentOperator.populateOperators(contentProcessor, pdfCleanUpRenderListener);
|
||||
contentProcessor.processContent(pageContentInput, page.getAsDict(PdfName.RESOURCES));
|
||||
pdfCleanUpRenderListener.popContext();
|
||||
canvas.restoreState();
|
||||
colorCleanedLocations(canvas, cleanUpLocations);
|
||||
if (this.redactAnnotIndirRefs != null)
|
||||
deleteRedactAnnots(pageNum);
|
||||
}
|
||||
|
||||
private PdfCleanUpRegionFilter createFilter(List<PdfCleanUpLocation> cleanUpLocations) {
|
||||
List<Rectangle> regions = new ArrayList<Rectangle>(cleanUpLocations.size());
|
||||
for (PdfCleanUpLocation location : cleanUpLocations)
|
||||
regions.add(location.getRegion());
|
||||
return new PdfCleanUpRegionFilter(regions);
|
||||
}
|
||||
|
||||
private void colorCleanedLocations(PdfContentByte canvas, List<PdfCleanUpLocation> cleanUpLocations) {
|
||||
if (fillCleanedArea)
|
||||
for (PdfCleanUpLocation location : cleanUpLocations) {
|
||||
if (location.getCleanUpColor() != null)
|
||||
addColoredRectangle(canvas, location);
|
||||
}
|
||||
}
|
||||
|
||||
private void addColoredRectangle(PdfContentByte canvas, PdfCleanUpLocation cleanUpLocation) {
|
||||
Rectangle cleanUpRegion = cleanUpLocation.getRegion();
|
||||
canvas.saveState();
|
||||
canvas.setColorFill(cleanUpLocation.getCleanUpColor());
|
||||
canvas.moveTo(cleanUpRegion.getLeft(), cleanUpRegion.getBottom());
|
||||
canvas.lineTo(cleanUpRegion.getRight(), cleanUpRegion.getBottom());
|
||||
canvas.lineTo(cleanUpRegion.getRight(), cleanUpRegion.getTop());
|
||||
canvas.lineTo(cleanUpRegion.getLeft(), cleanUpRegion.getTop());
|
||||
canvas.closePath();
|
||||
canvas.fill();
|
||||
canvas.restoreState();
|
||||
}
|
||||
|
||||
private Map<Integer, List<PdfCleanUpLocation>> organizeLocationsByPage(Collection<PdfCleanUpLocation> pdfCleanUpLocations) {
|
||||
Map<Integer, List<PdfCleanUpLocation>> organizedLocations = new HashMap<Integer, List<PdfCleanUpLocation>>();
|
||||
for (PdfCleanUpLocation location : pdfCleanUpLocations) {
|
||||
Integer page = location.getPage();
|
||||
if (!organizedLocations.containsKey(page))
|
||||
organizedLocations.put(page, new ArrayList<PdfCleanUpLocation>());
|
||||
organizedLocations.get(page).add(location);
|
||||
}
|
||||
return organizedLocations;
|
||||
}
|
||||
|
||||
private void extractLocationsFromRedactAnnots() {
|
||||
this.pdfCleanUpLocations = new HashMap<Integer, List<PdfCleanUpLocation>>();
|
||||
PdfReader reader = this.pdfStamper.getReader();
|
||||
for (int i = 1; i <= reader.getNumberOfPages(); i++) {
|
||||
PdfDictionary pageDict = reader.getPageN(i);
|
||||
this.pdfCleanUpLocations.put(Integer.valueOf(i), extractLocationsFromRedactAnnots(i, pageDict));
|
||||
}
|
||||
}
|
||||
|
||||
private List<PdfCleanUpLocation> extractLocationsFromRedactAnnots(int page, PdfDictionary pageDict) {
|
||||
List<PdfCleanUpLocation> locations = new ArrayList<PdfCleanUpLocation>();
|
||||
if (pageDict.contains(PdfName.ANNOTS)) {
|
||||
PdfArray annotsArray = pageDict.getAsArray(PdfName.ANNOTS);
|
||||
for (int i = 0; i < annotsArray.size(); i++) {
|
||||
PdfIndirectReference annotIndirRef = annotsArray.getAsIndirectObject(i);
|
||||
PdfDictionary annotDict = annotsArray.getAsDict(i);
|
||||
PdfName annotSubtype = annotDict.getAsName(PdfName.SUBTYPE);
|
||||
if (annotSubtype.equals(PdfName.REDACT)) {
|
||||
saveRedactAnnotIndirRef(page, annotIndirRef.toString());
|
||||
locations.addAll(extractLocationsFromRedactAnnot(page, i, annotDict));
|
||||
}
|
||||
}
|
||||
}
|
||||
return locations;
|
||||
}
|
||||
|
||||
private void saveRedactAnnotIndirRef(int page, String indRefStr) {
|
||||
if (!this.redactAnnotIndirRefs.containsKey(Integer.valueOf(page)))
|
||||
this.redactAnnotIndirRefs.put(Integer.valueOf(page), new HashSet<String>());
|
||||
this.redactAnnotIndirRefs.get(Integer.valueOf(page)).add(indRefStr);
|
||||
}
|
||||
|
||||
private List<PdfCleanUpLocation> extractLocationsFromRedactAnnot(int page, int annotIndex, PdfDictionary annotDict) {
|
||||
List<PdfCleanUpLocation> locations = new ArrayList<PdfCleanUpLocation>();
|
||||
List<Rectangle> markedRectangles = new ArrayList<Rectangle>();
|
||||
PdfArray quadPoints = annotDict.getAsArray(PdfName.QUADPOINTS);
|
||||
if (quadPoints.size() != 0) {
|
||||
markedRectangles.addAll(translateQuadPointsToRectangles(quadPoints));
|
||||
} else {
|
||||
PdfArray annotRect = annotDict.getAsArray(PdfName.RECT);
|
||||
markedRectangles.add(new Rectangle(annotRect.getAsNumber(0).floatValue(),
|
||||
annotRect.getAsNumber(1).floatValue(),
|
||||
annotRect.getAsNumber(2).floatValue(),
|
||||
annotRect.getAsNumber(3).floatValue()));
|
||||
}
|
||||
this.clippingRects.put(Integer.valueOf(annotIndex), markedRectangles);
|
||||
BaseColor cleanUpColor = null;
|
||||
PdfArray ic = annotDict.getAsArray(PdfName.IC);
|
||||
if (ic != null)
|
||||
cleanUpColor = new BaseColor(ic.getAsNumber(0).floatValue(), ic.getAsNumber(1).floatValue(), ic.getAsNumber(2).floatValue());
|
||||
PdfStream ro = annotDict.getAsStream(PdfName.RO);
|
||||
if (ro != null)
|
||||
cleanUpColor = null;
|
||||
for (Rectangle rect : markedRectangles)
|
||||
locations.add(new PdfCleanUpLocation(page, rect, cleanUpColor));
|
||||
return locations;
|
||||
}
|
||||
|
||||
private List<Rectangle> translateQuadPointsToRectangles(PdfArray quadPoints) {
|
||||
List<Rectangle> rectangles = new ArrayList<Rectangle>();
|
||||
for (int i = 0; i < quadPoints.size(); i += 8)
|
||||
rectangles.add(new Rectangle(quadPoints.getAsNumber(i + 4).floatValue(),
|
||||
quadPoints.getAsNumber(i + 5).floatValue(),
|
||||
quadPoints.getAsNumber(i + 2).floatValue(),
|
||||
quadPoints.getAsNumber(i + 3).floatValue()));
|
||||
return rectangles;
|
||||
}
|
||||
|
||||
private void deleteRedactAnnots(int pageNum) throws IOException, DocumentException {
|
||||
Set<String> indirRefs = this.redactAnnotIndirRefs.get(Integer.valueOf(pageNum));
|
||||
if (indirRefs == null || indirRefs.isEmpty())
|
||||
return;
|
||||
PdfReader reader = this.pdfStamper.getReader();
|
||||
PdfContentByte canvas = this.pdfStamper.getOverContent(pageNum);
|
||||
PdfDictionary pageDict = reader.getPageN(pageNum);
|
||||
PdfArray annotsArray = pageDict.getAsArray(PdfName.ANNOTS);
|
||||
for (int i = 0, j = 0; i < annotsArray.size(); i++, j++) {
|
||||
PdfIndirectReference annotIndRef = annotsArray.getAsIndirectObject(i);
|
||||
PdfDictionary annotDict = annotsArray.getAsDict(i);
|
||||
if (indirRefs.contains(annotIndRef.toString()) || indirRefs.contains(getParentIndRefStr(annotDict))) {
|
||||
PdfStream formXObj = annotDict.getAsStream(PdfName.RO);
|
||||
PdfString overlayText = annotDict.getAsString(PdfName.OVERLAYTEXT);
|
||||
if (fillCleanedArea && formXObj != null) {
|
||||
PdfArray rectArray = annotDict.getAsArray(PdfName.RECT);
|
||||
Rectangle annotRect = new Rectangle(rectArray.getAsNumber(0).floatValue(),
|
||||
rectArray.getAsNumber(1).floatValue(),
|
||||
rectArray.getAsNumber(2).floatValue(),
|
||||
rectArray.getAsNumber(3).floatValue());
|
||||
insertFormXObj(canvas, pageDict, formXObj, this.clippingRects.get(Integer.valueOf(j)), annotRect);
|
||||
} else if (fillCleanedArea && overlayText != null && overlayText.toUnicodeString().length() > 0) {
|
||||
drawOverlayText(canvas, this.clippingRects.get(Integer.valueOf(j)), overlayText,
|
||||
annotDict.getAsString(PdfName.DA),
|
||||
annotDict.getAsNumber(PdfName.Q),
|
||||
annotDict.getAsBoolean(PdfName.REPEAT));
|
||||
}
|
||||
annotsArray.remove(i--);
|
||||
}
|
||||
}
|
||||
if (annotsArray.size() == 0)
|
||||
pageDict.remove(PdfName.ANNOTS);
|
||||
}
|
||||
|
||||
private void insertFormXObj(PdfContentByte canvas, PdfDictionary pageDict, PdfStream formXObj, List<Rectangle> clippingRects, Rectangle annotRect) throws IOException {
|
||||
PdfName xobjName = generateNameForXObj(pageDict);
|
||||
canvas.saveState();
|
||||
for (Rectangle rect : clippingRects)
|
||||
canvas.rectangle(rect.getLeft(), rect.getBottom(), rect.getWidth(), rect.getHeight());
|
||||
canvas.clip();
|
||||
canvas.newPath();
|
||||
canvas.addFormXObj(formXObj, xobjName, 1.0F, 0.0F, 0.0F, 1.0F, annotRect.getLeft(), annotRect.getBottom());
|
||||
canvas.restoreState();
|
||||
}
|
||||
|
||||
private void drawOverlayText(PdfContentByte canvas, List<Rectangle> textRectangles, PdfString overlayText, PdfString otDA, PdfNumber otQ, PdfBoolean otRepeat) throws DocumentException, IOException {
|
||||
ColumnText ct = new ColumnText(canvas);
|
||||
ct.setLeading(0.0F, 1.2F);
|
||||
ct.setUseAscender(true);
|
||||
String otStr = overlayText.toUnicodeString();
|
||||
canvas.saveState();
|
||||
Map<String, List> parsedDA = parseDAParam(otDA);
|
||||
Font font = null;
|
||||
if (parsedDA.containsKey("StrokeColor")) {
|
||||
List strokeColorArgs = parsedDA.get("StrokeColor");
|
||||
setStrokeColor(canvas, strokeColorArgs);
|
||||
}
|
||||
if (parsedDA.containsKey("FillColor")) {
|
||||
List fillColorArgs = parsedDA.get("FillColor");
|
||||
setFillColor(canvas, fillColorArgs);
|
||||
}
|
||||
if (parsedDA.containsKey("Tf")) {
|
||||
List<PdfName> tfArgs = parsedDA.get("Tf");
|
||||
font = retrieveFontFromAcroForm(tfArgs.get(0), (PdfNumber)tfArgs.get(1));
|
||||
}
|
||||
for (Rectangle textRect : textRectangles) {
|
||||
Phrase otPhrase;
|
||||
ct.setSimpleColumn(textRect);
|
||||
if (otQ != null)
|
||||
ct.setAlignment(otQ.intValue());
|
||||
if (font != null) {
|
||||
otPhrase = new Phrase(otStr, font);
|
||||
} else {
|
||||
otPhrase = new Phrase(otStr);
|
||||
}
|
||||
float y = ct.getYLine();
|
||||
if (otRepeat != null && otRepeat.booleanValue()) {
|
||||
int status = ct.go(true);
|
||||
while (!ColumnText.hasMoreText(status)) {
|
||||
otPhrase.add(otStr);
|
||||
ct.setText(otPhrase);
|
||||
ct.setYLine(y);
|
||||
status = ct.go(true);
|
||||
}
|
||||
}
|
||||
ct.setText(otPhrase);
|
||||
ct.setYLine(y);
|
||||
ct.go();
|
||||
}
|
||||
canvas.restoreState();
|
||||
}
|
||||
|
||||
private Font retrieveFontFromAcroForm(PdfName fontName, PdfNumber size) {
|
||||
PdfIndirectReference fontIndirReference = this.pdfStamper.getReader().getAcroForm().getAsDict(PdfName.DR).getAsDict(PdfName.FONT).getAsIndirectObject(fontName);
|
||||
BaseFont bfont = BaseFont.createFont((PRIndirectReference)fontIndirReference);
|
||||
return new Font(bfont, size.floatValue());
|
||||
}
|
||||
|
||||
Map<String, List> parseDAParam(PdfString DA) throws IOException {
|
||||
Map<String, List> commandArguments = new HashMap<String, List>();
|
||||
PRTokeniser tokeniser = new PRTokeniser(new RandomAccessFileOrArray(new RandomAccessSourceFactory().createSource(DA.getBytes())));
|
||||
List<PdfNumber> currentArguments = new ArrayList();
|
||||
while (tokeniser.nextToken()) {
|
||||
if (tokeniser.getTokenType() == PRTokeniser.TokenType.OTHER) {
|
||||
String key = tokeniser.getStringValue();
|
||||
if (key.equals("RG") || key.equals("G") || key.equals("K")) {
|
||||
key = "StrokeColor";
|
||||
} else if (key.equals("rg") || key.equals("g") || key.equals("k")) {
|
||||
key = "FillColor";
|
||||
}
|
||||
commandArguments.put(key, currentArguments);
|
||||
currentArguments = new ArrayList();
|
||||
continue;
|
||||
}
|
||||
switch (tokeniser.getTokenType()) {
|
||||
case NUMBER:
|
||||
currentArguments.add(new PdfNumber(tokeniser.getStringValue()));
|
||||
continue;
|
||||
case NAME:
|
||||
currentArguments.add(new PdfName(tokeniser.getStringValue()));
|
||||
continue;
|
||||
}
|
||||
currentArguments.add(tokeniser.getStringValue());
|
||||
}
|
||||
return commandArguments;
|
||||
}
|
||||
|
||||
private String getParentIndRefStr(PdfDictionary dict) {
|
||||
return dict.getAsIndirectObject(PdfName.PARENT).toString();
|
||||
}
|
||||
|
||||
private PdfName generateNameForXObj(PdfDictionary pageDict) {
|
||||
PdfDictionary resourcesDict = pageDict.getAsDict(PdfName.RESOURCES);
|
||||
PdfDictionary xobjDict = resourcesDict.getAsDict(PdfName.XOBJECT);
|
||||
if (xobjDict != null)
|
||||
for (PdfName xobjName : (Iterable<PdfName>)xobjDict.getKeys()) {
|
||||
int xobjNum = getXObjNum(xobjName);
|
||||
if (this.currentXObjNum <= xobjNum)
|
||||
this.currentXObjNum = xobjNum + 1;
|
||||
}
|
||||
return new PdfName("Fm" + this.currentXObjNum++);
|
||||
}
|
||||
|
||||
private int getXObjNum(PdfName xobjName) {
|
||||
String decodedPdfName = PdfName.decodeName(xobjName.toString());
|
||||
if (decodedPdfName.lastIndexOf("Fm") == -1)
|
||||
return 0;
|
||||
String numStr = decodedPdfName.substring(decodedPdfName.lastIndexOf("Fm") + "Fm".length());
|
||||
return Integer.parseInt(numStr);
|
||||
}
|
||||
|
||||
private void setFillColor(PdfContentByte canvas, List fillColorArgs) {
|
||||
switch (fillColorArgs.size()) {
|
||||
case 1:
|
||||
canvas.setGrayFill(fillColorArgs.get(0).floatValue());
|
||||
break;
|
||||
case 3:
|
||||
canvas.setRGBColorFillF(fillColorArgs.get(0).floatValue(),
|
||||
fillColorArgs.get(1).floatValue(),
|
||||
fillColorArgs.get(2).floatValue());
|
||||
break;
|
||||
case 4:
|
||||
canvas.setCMYKColorFillF(fillColorArgs.get(0).floatValue(),
|
||||
fillColorArgs.get(1).floatValue(),
|
||||
fillColorArgs.get(2).floatValue(),
|
||||
fillColorArgs.get(3).floatValue());
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
private void setStrokeColor(PdfContentByte canvas, List strokeColorArgs) {
|
||||
switch (strokeColorArgs.size()) {
|
||||
case 1:
|
||||
canvas.setGrayStroke(strokeColorArgs.get(0).floatValue());
|
||||
break;
|
||||
case 3:
|
||||
canvas.setRGBColorStrokeF(strokeColorArgs.get(0).floatValue(),
|
||||
strokeColorArgs.get(1).floatValue(),
|
||||
strokeColorArgs.get(2).floatValue());
|
||||
break;
|
||||
case 4:
|
||||
canvas.setCMYKColorFillF(strokeColorArgs.get(0).floatValue(),
|
||||
strokeColorArgs.get(1).floatValue(),
|
||||
strokeColorArgs.get(2).floatValue(),
|
||||
strokeColorArgs.get(3).floatValue());
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,473 @@
|
|||
package com.itextpdf.text.pdf.pdfcleanup;
|
||||
|
||||
import com.itextpdf.awt.geom.AffineTransform;
|
||||
import com.itextpdf.awt.geom.NoninvertibleTransformException;
|
||||
import com.itextpdf.awt.geom.Point2D;
|
||||
import com.itextpdf.text.Rectangle;
|
||||
import com.itextpdf.text.pdf.parser.BezierCurve;
|
||||
import com.itextpdf.text.pdf.parser.ImageRenderInfo;
|
||||
import com.itextpdf.text.pdf.parser.Line;
|
||||
import com.itextpdf.text.pdf.parser.LineDashPattern;
|
||||
import com.itextpdf.text.pdf.parser.LineSegment;
|
||||
import com.itextpdf.text.pdf.parser.Matrix;
|
||||
import com.itextpdf.text.pdf.parser.Path;
|
||||
import com.itextpdf.text.pdf.parser.RenderFilter;
|
||||
import com.itextpdf.text.pdf.parser.Shape;
|
||||
import com.itextpdf.text.pdf.parser.Subpath;
|
||||
import com.itextpdf.text.pdf.parser.TextRenderInfo;
|
||||
import com.itextpdf.text.pdf.parser.clipper.Clipper;
|
||||
import com.itextpdf.text.pdf.parser.clipper.ClipperOffset;
|
||||
import com.itextpdf.text.pdf.parser.clipper.DefaultClipper;
|
||||
import com.itextpdf.text.pdf.parser.clipper.Paths;
|
||||
import com.itextpdf.text.pdf.parser.clipper.Point;
|
||||
import com.itextpdf.text.pdf.parser.clipper.PolyNode;
|
||||
import com.itextpdf.text.pdf.parser.clipper.PolyTree;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collection;
|
||||
import java.util.Collections;
|
||||
import java.util.HashSet;
|
||||
import java.util.Iterator;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
|
||||
class PdfCleanUpRegionFilter extends RenderFilter {
|
||||
private List<Rectangle> rectangles;
|
||||
|
||||
private static final double circleApproximationConst = 0.55191502449D;
|
||||
|
||||
public PdfCleanUpRegionFilter(List<Rectangle> rectangles) {
|
||||
this.rectangles = rectangles;
|
||||
}
|
||||
|
||||
public boolean allowText(TextRenderInfo renderInfo) {
|
||||
LineSegment ascent = renderInfo.getAscentLine();
|
||||
LineSegment descent = renderInfo.getDescentLine();
|
||||
Point2D[] glyphRect = { new Point2D.Float(
|
||||
ascent.getStartPoint().get(0), ascent.getStartPoint().get(1)), new Point2D.Float(
|
||||
ascent.getEndPoint().get(0), ascent.getEndPoint().get(1)), new Point2D.Float(
|
||||
descent.getEndPoint().get(0), descent.getEndPoint().get(1)), new Point2D.Float(
|
||||
descent.getStartPoint().get(0), descent.getStartPoint().get(1)) };
|
||||
for (Rectangle rectangle : this.rectangles) {
|
||||
Point2D[] redactRect = getVertices(rectangle);
|
||||
if (intersect(glyphRect, redactRect))
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
public boolean allowImage(ImageRenderInfo renderInfo) {
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
|
||||
protected List<Rectangle> getCoveredAreas(ImageRenderInfo renderInfo) {
|
||||
Rectangle imageRect = calcImageRect(renderInfo);
|
||||
List<Rectangle> coveredAreas = new ArrayList<Rectangle>();
|
||||
if (imageRect == null)
|
||||
return null;
|
||||
for (Rectangle rectangle : this.rectangles) {
|
||||
Rectangle intersectionRect = intersection(imageRect, rectangle);
|
||||
if (intersectionRect != null) {
|
||||
if (imageRect.equals(intersectionRect))
|
||||
return null;
|
||||
coveredAreas.add(transformIntersection(renderInfo.getImageCTM(), intersectionRect));
|
||||
}
|
||||
}
|
||||
return coveredAreas;
|
||||
}
|
||||
|
||||
protected Path filterStrokePath(Path sourcePath, Matrix ctm, float lineWidth, int lineCapStyle, int lineJoinStyle, float miterLimit, LineDashPattern lineDashPattern) {
|
||||
Path path = sourcePath;
|
||||
Clipper.JoinType joinType = getJoinType(lineJoinStyle);
|
||||
Clipper.EndType endType = getEndType(lineCapStyle);
|
||||
if (lineDashPattern != null &&
|
||||
!lineDashPattern.isSolid())
|
||||
path = applyDashPattern(path, lineDashPattern);
|
||||
ClipperOffset offset = new ClipperOffset((double)miterLimit, PdfCleanUpProcessor.arcTolerance * PdfCleanUpProcessor.floatMultiplier);
|
||||
List<Subpath> degenerateSubpaths = addPath(offset, path, joinType, endType);
|
||||
PolyTree resultTree = new PolyTree();
|
||||
offset.execute(resultTree, (double)lineWidth * PdfCleanUpProcessor.floatMultiplier / 2.0D);
|
||||
Path offsetedPath = convertToPath(resultTree);
|
||||
if (degenerateSubpaths.size() > 0)
|
||||
if (endType == Clipper.EndType.OPEN_ROUND) {
|
||||
List<Subpath> circles = convertToCircles(degenerateSubpaths, (double)(lineWidth / 2.0F));
|
||||
offsetedPath.addSubpaths(circles);
|
||||
} else if (endType == Clipper.EndType.OPEN_SQUARE && lineDashPattern != null) {
|
||||
List<Subpath> squares = convertToSquares(degenerateSubpaths, (double)lineWidth, sourcePath);
|
||||
offsetedPath.addSubpaths(squares);
|
||||
}
|
||||
return filterFillPath(offsetedPath, ctm, 1);
|
||||
}
|
||||
|
||||
protected Path filterFillPath(Path path, Matrix ctm, int fillingRule) {
|
||||
path.closeAllSubpaths();
|
||||
DefaultClipper defaultClipper = new DefaultClipper();
|
||||
addPath((Clipper)defaultClipper, path);
|
||||
for (Rectangle rectangle : this.rectangles) {
|
||||
Point2D[] transfRectVertices = transformPoints(ctm, true, getVertices(rectangle));
|
||||
addRect((Clipper)defaultClipper, transfRectVertices, Clipper.PolyType.CLIP);
|
||||
}
|
||||
Clipper.PolyFillType fillType = Clipper.PolyFillType.NON_ZERO;
|
||||
if (fillingRule == 2)
|
||||
fillType = Clipper.PolyFillType.EVEN_ODD;
|
||||
PolyTree resultTree = new PolyTree();
|
||||
defaultClipper.execute(Clipper.ClipType.DIFFERENCE, resultTree, fillType, Clipper.PolyFillType.NON_ZERO);
|
||||
return convertToPath(resultTree);
|
||||
}
|
||||
|
||||
private static Clipper.JoinType getJoinType(int lineJoinStyle) {
|
||||
switch (lineJoinStyle) {
|
||||
case 2:
|
||||
return Clipper.JoinType.BEVEL;
|
||||
case 0:
|
||||
return Clipper.JoinType.MITER;
|
||||
}
|
||||
return Clipper.JoinType.ROUND;
|
||||
}
|
||||
|
||||
private static Clipper.EndType getEndType(int lineCapStyle) {
|
||||
switch (lineCapStyle) {
|
||||
case 0:
|
||||
return Clipper.EndType.OPEN_BUTT;
|
||||
case 2:
|
||||
return Clipper.EndType.OPEN_SQUARE;
|
||||
}
|
||||
return Clipper.EndType.OPEN_ROUND;
|
||||
}
|
||||
|
||||
private static List<Subpath> convertToCircles(List<Subpath> degenerateSubpaths, double radius) {
|
||||
List<Subpath> circles = new ArrayList<Subpath>(degenerateSubpaths.size());
|
||||
for (Subpath subpath : degenerateSubpaths) {
|
||||
BezierCurve[] circleSectors = approximateCircle(subpath.getStartPoint(), radius);
|
||||
Subpath circle = new Subpath();
|
||||
circle.addSegment((Shape)circleSectors[0]);
|
||||
circle.addSegment((Shape)circleSectors[1]);
|
||||
circle.addSegment((Shape)circleSectors[2]);
|
||||
circle.addSegment((Shape)circleSectors[3]);
|
||||
circles.add(circle);
|
||||
}
|
||||
return circles;
|
||||
}
|
||||
|
||||
private static List<Subpath> convertToSquares(List<Subpath> degenerateSubpaths, double squareWidth, Path sourcePath) {
|
||||
List<Point2D> pathApprox = getPathApproximation(sourcePath);
|
||||
if (pathApprox.size() < 2)
|
||||
return Collections.EMPTY_LIST;
|
||||
Iterator<Point2D> approxIter = pathApprox.iterator();
|
||||
Point2D approxPt1 = approxIter.next();
|
||||
Point2D approxPt2 = approxIter.next();
|
||||
StandardLine line = new StandardLine(approxPt1, approxPt2);
|
||||
List<Subpath> squares = new ArrayList<Subpath>(degenerateSubpaths.size());
|
||||
float widthHalf = (float)squareWidth / 2.0F;
|
||||
for (int i = 0; i < degenerateSubpaths.size(); i++) {
|
||||
double angle;
|
||||
Point2D point = degenerateSubpaths.get(i).getStartPoint();
|
||||
while (!line.contains(point)) {
|
||||
approxPt1 = approxPt2;
|
||||
approxPt2 = approxIter.next();
|
||||
line = new StandardLine(approxPt1, approxPt2);
|
||||
}
|
||||
double slope = (double)line.getSlope();
|
||||
if (slope != Double.POSITIVE_INFINITY) {
|
||||
angle = Math.atan(slope);
|
||||
} else {
|
||||
angle = 1.5707963267948966D;
|
||||
}
|
||||
squares.add(constructSquare(point, (double)widthHalf, angle));
|
||||
}
|
||||
return squares;
|
||||
}
|
||||
|
||||
private static List<Point2D> getPathApproximation(Path path) {
|
||||
List<Point2D> approx = new ArrayList<Point2D>() {
|
||||
public boolean addAll(Collection<? extends Point2D> c) {
|
||||
Point2D prevPoint = (size() - 1 < 0) ? null : get(size() - 1);
|
||||
boolean ret = false;
|
||||
for (Point2D pt : c) {
|
||||
if (!pt.equals(prevPoint)) {
|
||||
add(pt);
|
||||
prevPoint = pt;
|
||||
ret = true;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
};
|
||||
for (Subpath subpath : (Iterable<Subpath>)path.getSubpaths())
|
||||
approx.addAll(subpath.getPiecewiseLinearApproximation());
|
||||
return approx;
|
||||
}
|
||||
|
||||
private static Subpath constructSquare(Point2D squareCenter, double widthHalf, double rotationAngle) {
|
||||
Point2D[] ortogonalSquareVertices = { new Point2D.Double(-widthHalf, -widthHalf), new Point2D.Double(-widthHalf, widthHalf), new Point2D.Double(widthHalf, widthHalf), new Point2D.Double(widthHalf, -widthHalf) };
|
||||
Point2D[] rotatedSquareVertices = getRotatedSquareVertices(ortogonalSquareVertices, rotationAngle, squareCenter);
|
||||
Subpath square = new Subpath();
|
||||
square.addSegment(new Line(rotatedSquareVertices[0], rotatedSquareVertices[1]));
|
||||
square.addSegment(new Line(rotatedSquareVertices[1], rotatedSquareVertices[2]));
|
||||
square.addSegment(new Line(rotatedSquareVertices[2], rotatedSquareVertices[3]));
|
||||
square.addSegment(new Line(rotatedSquareVertices[3], rotatedSquareVertices[0]));
|
||||
return square;
|
||||
}
|
||||
|
||||
private static Point2D[] getRotatedSquareVertices(Point2D[] orthogonalSquareVertices, double angle, Point2D squareCenter) {
|
||||
Point2D[] rotatedSquareVertices = new Point2D[orthogonalSquareVertices.length];
|
||||
AffineTransform.getRotateInstance(angle)
|
||||
.transform(orthogonalSquareVertices, 0, rotatedSquareVertices, 0, rotatedSquareVertices.length);
|
||||
AffineTransform.getTranslateInstance(squareCenter.getX(), squareCenter.getY())
|
||||
.transform(rotatedSquareVertices, 0, rotatedSquareVertices, 0, orthogonalSquareVertices.length);
|
||||
return rotatedSquareVertices;
|
||||
}
|
||||
|
||||
private static List<Subpath> addPath(ClipperOffset offset, Path path, Clipper.JoinType joinType, Clipper.EndType endType) {
|
||||
List<Subpath> degenerateSubpaths = new ArrayList<Subpath>();
|
||||
for (Subpath subpath : (Iterable<Subpath>)path.getSubpaths()) {
|
||||
if (subpath.isDegenerate()) {
|
||||
degenerateSubpaths.add(subpath);
|
||||
continue;
|
||||
}
|
||||
if (!subpath.isSinglePointClosed() && !subpath.isSinglePointOpen()) {
|
||||
Clipper.EndType et;
|
||||
if (subpath.isClosed()) {
|
||||
et = Clipper.EndType.CLOSED_LINE;
|
||||
} else {
|
||||
et = endType;
|
||||
}
|
||||
List<Point2D> linearApproxPoints = subpath.getPiecewiseLinearApproximation();
|
||||
offset.addPath(convertToIntPoints(linearApproxPoints), joinType, et);
|
||||
}
|
||||
}
|
||||
return degenerateSubpaths;
|
||||
}
|
||||
|
||||
private static BezierCurve[] approximateCircle(Point2D center, double radius) {
|
||||
BezierCurve[] approximation = new BezierCurve[4];
|
||||
double x = center.getX();
|
||||
double y = center.getY();
|
||||
approximation[0] = new BezierCurve(Arrays.<Point2D>asList(new Point2D.Double(x, y + radius), new Point2D.Double(x + radius * 0.55191502449D, y + radius), new Point2D.Double(x + radius, y + radius * 0.55191502449D), new Point2D.Double(x + radius, y)));
|
||||
approximation[1] = new BezierCurve(Arrays.<Point2D>asList(new Point2D.Double(x + radius, y), new Point2D.Double(x + radius, y - radius * 0.55191502449D), new Point2D.Double(x + radius * 0.55191502449D, y - radius), new Point2D.Double(x, y - radius)));
|
||||
approximation[2] = new BezierCurve(Arrays.<Point2D>asList(new Point2D.Double(x, y - radius), new Point2D.Double(x - radius * 0.55191502449D, y - radius), new Point2D.Double(x - radius, y - radius * 0.55191502449D), new Point2D.Double(x - radius, y)));
|
||||
approximation[3] = new BezierCurve(Arrays.<Point2D>asList(new Point2D.Double(x - radius, y), new Point2D.Double(x - radius, y + radius * 0.55191502449D), new Point2D.Double(x - radius * 0.55191502449D, y + radius), new Point2D.Double(x, y + radius)));
|
||||
return approximation;
|
||||
}
|
||||
|
||||
private static void addPath(Clipper clipper, Path path) {
|
||||
for (Subpath subpath : (Iterable<Subpath>)path.getSubpaths()) {
|
||||
if (!subpath.isSinglePointClosed() && !subpath.isSinglePointOpen()) {
|
||||
List<Point2D> linearApproxPoints = subpath.getPiecewiseLinearApproximation();
|
||||
clipper.addPath(convertToIntPoints(linearApproxPoints), Clipper.PolyType.SUBJECT, subpath.isClosed());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static void addRect(Clipper clipper, Point2D[] rectVertices, Clipper.PolyType polyType) {
|
||||
clipper.addPath(convertToIntPoints(new ArrayList<Point2D>(Arrays.<Point2D>asList(rectVertices))), polyType, true);
|
||||
}
|
||||
|
||||
private static com.itextpdf.text.pdf.parser.clipper.Path convertToIntPoints(List<Point2D> points) {
|
||||
List<Point.LongPoint> convertedPoints = new ArrayList<Point.LongPoint>(points.size());
|
||||
for (Point2D point : points)
|
||||
convertedPoints.add(new Point.LongPoint(PdfCleanUpProcessor.floatMultiplier * point.getX(), PdfCleanUpProcessor.floatMultiplier *
|
||||
point.getY()));
|
||||
return new com.itextpdf.text.pdf.parser.clipper.Path(convertedPoints);
|
||||
}
|
||||
|
||||
private static List<Point2D> convertToFloatPoints(List<Point.LongPoint> points) {
|
||||
List<Point2D> convertedPoints = new ArrayList<Point2D>(points.size());
|
||||
for (Point.LongPoint point : points)
|
||||
convertedPoints.add(new Point2D.Float((float)((double)point.getX() / PdfCleanUpProcessor.floatMultiplier),
|
||||
(float)((double)point.getY() / PdfCleanUpProcessor.floatMultiplier)));
|
||||
return convertedPoints;
|
||||
}
|
||||
|
||||
private static Path convertToPath(PolyTree result) {
|
||||
Path path = new Path();
|
||||
PolyNode node = result.getFirst();
|
||||
while (node != null) {
|
||||
addContour(path, node.getContour(), Boolean.valueOf(!node.isOpen()));
|
||||
node = node.getNext();
|
||||
}
|
||||
return path;
|
||||
}
|
||||
|
||||
private static void addContour(Path path, List<Point.LongPoint> contour, Boolean close) {
|
||||
List<Point2D> floatContour = convertToFloatPoints(contour);
|
||||
Iterator<Point2D> iter = floatContour.iterator();
|
||||
Point2D point = iter.next();
|
||||
path.moveTo((float)point.getX(), (float)point.getY());
|
||||
while (iter.hasNext()) {
|
||||
point = iter.next();
|
||||
path.lineTo((float)point.getX(), (float)point.getY());
|
||||
}
|
||||
if (close)
|
||||
path.closeSubpath();
|
||||
}
|
||||
|
||||
private Point2D[] getVertices(Rectangle rect) {
|
||||
Point2D[] points = { new Point2D.Double(
|
||||
(double)rect.getLeft(), (double)rect.getBottom()), new Point2D.Double(
|
||||
(double)rect.getRight(), (double)rect.getBottom()), new Point2D.Double(
|
||||
(double)rect.getRight(), (double)rect.getTop()), new Point2D.Double(
|
||||
(double)rect.getLeft(), (double)rect.getTop()) };
|
||||
return points;
|
||||
}
|
||||
|
||||
private boolean intersect(Point2D[] rect1, Point2D[] rect2) {
|
||||
DefaultClipper defaultClipper = new DefaultClipper();
|
||||
addRect((Clipper)defaultClipper, rect1, Clipper.PolyType.SUBJECT);
|
||||
addRect((Clipper)defaultClipper, rect2, Clipper.PolyType.CLIP);
|
||||
Paths paths = new Paths();
|
||||
defaultClipper.execute(Clipper.ClipType.INTERSECTION, paths, Clipper.PolyFillType.NON_ZERO, Clipper.PolyFillType.NON_ZERO);
|
||||
return !paths.isEmpty();
|
||||
}
|
||||
|
||||
private Rectangle calcImageRect(ImageRenderInfo renderInfo) {
|
||||
Matrix ctm = renderInfo.getImageCTM();
|
||||
if (ctm == null)
|
||||
return null;
|
||||
Point2D[] points = transformPoints(ctm, false, new Point2D[] { new com.itextpdf.awt.geom.Point(0, 0), new com.itextpdf.awt.geom.Point(0, 1), new com.itextpdf.awt.geom.Point(1, 0), new com.itextpdf.awt.geom.Point(1, 1) });
|
||||
return getRectangle(points[0], points[1], points[2], points[3]);
|
||||
}
|
||||
|
||||
private Rectangle intersection(Rectangle rect1, Rectangle rect2) {
|
||||
com.itextpdf.awt.geom.Rectangle awtRect1 = new com.itextpdf.awt.geom.Rectangle(rect1);
|
||||
com.itextpdf.awt.geom.Rectangle awtRect2 = new com.itextpdf.awt.geom.Rectangle(rect2);
|
||||
com.itextpdf.awt.geom.Rectangle awtIntersection = awtRect1.intersection(awtRect2);
|
||||
return awtIntersection.isEmpty() ? null : new Rectangle(awtIntersection);
|
||||
}
|
||||
|
||||
private Rectangle transformIntersection(Matrix imageCTM, Rectangle rect) {
|
||||
Point2D[] points = transformPoints(imageCTM, true, new com.itextpdf.awt.geom.Point((double)rect.getLeft(), (double)rect.getBottom()), new com.itextpdf.awt.geom.Point(
|
||||
(double)rect.getLeft(), (double)rect.getTop()), new com.itextpdf.awt.geom.Point(
|
||||
(double)rect.getRight(), (double)rect.getBottom()), new com.itextpdf.awt.geom.Point(
|
||||
(double)rect.getRight(), (double)rect.getTop()));
|
||||
return getRectangle(points[0], points[1], points[2], points[3]);
|
||||
}
|
||||
|
||||
private Rectangle getRectangle(Point2D p1, Point2D p2, Point2D p3, Point2D p4) {
|
||||
List<Double> xs = Arrays.<Double>asList(p1.getX(), p2.getX(), p3.getX(), p4.getX());
|
||||
List<Double> ys = Arrays.<Double>asList(p1.getY(), p2.getY(), p3.getY(), p4.getY());
|
||||
double left = (Double)Collections.min((Collection)xs);
|
||||
double bottom = (Double)Collections.min((Collection)ys);
|
||||
double right = (Double)Collections.max((Collection)xs);
|
||||
double top = (Double)Collections.max((Collection)ys);
|
||||
return new Rectangle((float)left, (float)bottom, (float)right, (float)top);
|
||||
}
|
||||
|
||||
private static Path applyDashPattern(Path path, LineDashPattern lineDashPattern) {
|
||||
Set<Integer> modifiedSubpaths = new HashSet<Integer>(path.replaceCloseWithLine());
|
||||
Path dashedPath = new Path();
|
||||
int currentSubpath = 0;
|
||||
for (Subpath subpath : (Iterable<Subpath>)path.getSubpaths()) {
|
||||
List<Point2D> subpathApprox = subpath.getPiecewiseLinearApproximation();
|
||||
if (subpathApprox.size() > 1) {
|
||||
dashedPath.moveTo((float)subpathApprox.get(0).getX(), (float)subpathApprox.get(0).getY());
|
||||
float remainingDist = 0.0F;
|
||||
boolean remainingIsGap = false;
|
||||
for (int i = 1; i < subpathApprox.size(); i++) {
|
||||
Point2D nextPoint = null;
|
||||
if (remainingDist != 0.0F) {
|
||||
nextPoint = getNextPoint(subpathApprox.get(i - 1), subpathApprox.get(i), remainingDist);
|
||||
remainingDist = applyDash(dashedPath, subpathApprox.get(i - 1), subpathApprox.get(i), nextPoint, remainingIsGap);
|
||||
}
|
||||
while (Float.compare(remainingDist, 0.0F) == 0 && !dashedPath.getCurrentPoint().equals(subpathApprox.get(i))) {
|
||||
LineDashPattern.DashArrayElem currentElem = lineDashPattern.next();
|
||||
nextPoint = getNextPoint((nextPoint != null) ? nextPoint : subpathApprox.get(i - 1), subpathApprox.get(i), currentElem.getVal());
|
||||
remainingDist = applyDash(dashedPath, subpathApprox.get(i - 1), subpathApprox.get(i), nextPoint, currentElem.isGap());
|
||||
remainingIsGap = currentElem.isGap();
|
||||
}
|
||||
}
|
||||
if (modifiedSubpaths.contains(Integer.valueOf(currentSubpath))) {
|
||||
lineDashPattern.reset();
|
||||
LineDashPattern.DashArrayElem currentElem = lineDashPattern.next();
|
||||
Point2D nextPoint = getNextPoint(subpathApprox.get(0), subpathApprox.get(1), currentElem.getVal());
|
||||
applyDash(dashedPath, subpathApprox.get(0), subpathApprox.get(1), nextPoint, currentElem.isGap());
|
||||
}
|
||||
}
|
||||
lineDashPattern.reset();
|
||||
currentSubpath++;
|
||||
}
|
||||
return dashedPath;
|
||||
}
|
||||
|
||||
private static Point2D getNextPoint(Point2D segStart, Point2D segEnd, float dist) {
|
||||
Point2D vector = componentwiseDiff(segEnd, segStart);
|
||||
Point2D unitVector = getUnitVector(vector);
|
||||
return new Point2D.Float((float)(segStart.getX() + (double)dist * unitVector.getX()),
|
||||
(float)(segStart.getY() + (double)dist * unitVector.getY()));
|
||||
}
|
||||
|
||||
private static Point2D componentwiseDiff(Point2D minuend, Point2D subtrahend) {
|
||||
return new Point2D.Float((float)(minuend.getX() - subtrahend.getX()),
|
||||
(float)(minuend.getY() - subtrahend.getY()));
|
||||
}
|
||||
|
||||
private static Point2D getUnitVector(Point2D vector) {
|
||||
double vectorLength = getVectorEuclideanNorm(vector);
|
||||
return new Point2D.Float((float)(vector.getX() / vectorLength),
|
||||
(float)(vector.getY() / vectorLength));
|
||||
}
|
||||
|
||||
private static double getVectorEuclideanNorm(Point2D vector) {
|
||||
return vector.distance(0.0D, 0.0D);
|
||||
}
|
||||
|
||||
private static float applyDash(Path dashedPath, Point2D segStart, Point2D segEnd, Point2D dashTo, boolean isGap) {
|
||||
float remainingDist = 0.0F;
|
||||
if (!liesOnSegment(segStart, segEnd, dashTo)) {
|
||||
remainingDist = (float)dashTo.distance(segEnd);
|
||||
dashTo = segEnd;
|
||||
}
|
||||
if (isGap) {
|
||||
dashedPath.moveTo((float)dashTo.getX(), (float)dashTo.getY());
|
||||
} else {
|
||||
dashedPath.lineTo((float)dashTo.getX(), (float)dashTo.getY());
|
||||
}
|
||||
return remainingDist;
|
||||
}
|
||||
|
||||
private static boolean liesOnSegment(Point2D segStart, Point2D segEnd, Point2D point) {
|
||||
return (point.getX() >= Math.min(segStart.getX(), segEnd.getX()) &&
|
||||
point.getX() <= Math.max(segStart.getX(), segEnd.getX()) &&
|
||||
point.getY() >= Math.min(segStart.getY(), segEnd.getY()) &&
|
||||
point.getY() <= Math.max(segStart.getY(), segEnd.getY()));
|
||||
}
|
||||
|
||||
private Point2D[] transformPoints(Matrix transormationMatrix, boolean inverse, Point2D... points) {
|
||||
AffineTransform t = new AffineTransform(transormationMatrix.get(0), transormationMatrix.get(1),
|
||||
transormationMatrix.get(3), transormationMatrix.get(4),
|
||||
transormationMatrix.get(6), transormationMatrix.get(7));
|
||||
Point2D[] transformed = new Point2D[points.length];
|
||||
if (inverse)
|
||||
try {
|
||||
t = t.createInverse();
|
||||
} catch (NoninvertibleTransformException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
t.transform(points, 0, transformed, 0, points.length);
|
||||
return transformed;
|
||||
}
|
||||
|
||||
private static class StandardLine {
|
||||
float A;
|
||||
|
||||
float B;
|
||||
|
||||
float C;
|
||||
|
||||
StandardLine(Point2D p1, Point2D p2) {
|
||||
this.A = (float)(p2.getY() - p1.getY());
|
||||
this.B = (float)(p1.getX() - p2.getX());
|
||||
this.C = (float)(p1.getY() * (double)-this.B - p1.getX() * (double)this.A);
|
||||
}
|
||||
|
||||
float getSlope() {
|
||||
if (this.B == 0.0F)
|
||||
return Float.POSITIVE_INFINITY;
|
||||
return -this.A / this.B;
|
||||
}
|
||||
|
||||
boolean contains(Point2D point) {
|
||||
return (Float.compare(Math.abs(this.A * (float)point.getX() + this.B * (float)point.getY() + this.C), 0.1F) < 0);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,288 @@
|
|||
package com.itextpdf.text.pdf.pdfcleanup;
|
||||
|
||||
import com.itextpdf.text.Image;
|
||||
import com.itextpdf.text.Rectangle;
|
||||
import com.itextpdf.text.pdf.PdfBoolean;
|
||||
import com.itextpdf.text.pdf.PdfContentByte;
|
||||
import com.itextpdf.text.pdf.PdfDictionary;
|
||||
import com.itextpdf.text.pdf.PdfName;
|
||||
import com.itextpdf.text.pdf.PdfObject;
|
||||
import com.itextpdf.text.pdf.PdfStamper;
|
||||
import com.itextpdf.text.pdf.parser.ExtRenderListener;
|
||||
import com.itextpdf.text.pdf.parser.ImageRenderInfo;
|
||||
import com.itextpdf.text.pdf.parser.LineDashPattern;
|
||||
import com.itextpdf.text.pdf.parser.LineSegment;
|
||||
import com.itextpdf.text.pdf.parser.Matrix;
|
||||
import com.itextpdf.text.pdf.parser.Path;
|
||||
import com.itextpdf.text.pdf.parser.PathConstructionRenderInfo;
|
||||
import com.itextpdf.text.pdf.parser.PathPaintingRenderInfo;
|
||||
import com.itextpdf.text.pdf.parser.PdfImageObject;
|
||||
import com.itextpdf.text.pdf.parser.TextRenderInfo;
|
||||
import java.awt.Color;
|
||||
import java.awt.Graphics2D;
|
||||
import java.awt.image.BufferedImage;
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.OutputStream;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Stack;
|
||||
import javax.imageio.IIOImage;
|
||||
import javax.imageio.ImageIO;
|
||||
import javax.imageio.ImageWriteParam;
|
||||
import javax.imageio.ImageWriter;
|
||||
import javax.imageio.stream.MemoryCacheImageOutputStream;
|
||||
import org.apache.commons.imaging.ImageFormats;
|
||||
import org.apache.commons.imaging.ImageInfo;
|
||||
import org.apache.commons.imaging.Imaging;
|
||||
|
||||
class PdfCleanUpRenderListener implements ExtRenderListener {
|
||||
private static final Color CLEANED_AREA_FILL_COLOR = Color.WHITE;
|
||||
|
||||
private PdfStamper pdfStamper;
|
||||
|
||||
private PdfCleanUpRegionFilter filter;
|
||||
|
||||
private List<PdfCleanUpContentChunk> chunks = new ArrayList<PdfCleanUpContentChunk>();
|
||||
|
||||
private Stack<PdfCleanUpContext> contextStack = new Stack<PdfCleanUpContext>();
|
||||
|
||||
private int strNumber = 1;
|
||||
|
||||
private Path unfilteredCurrentPath = new Path();
|
||||
|
||||
private Path currentStrokePath = new Path();
|
||||
|
||||
private Path currentFillPath = new Path();
|
||||
|
||||
private Path newClippingPath;
|
||||
|
||||
private boolean clipPath;
|
||||
|
||||
private int clippingRule;
|
||||
|
||||
public PdfCleanUpRenderListener(PdfStamper pdfStamper, PdfCleanUpRegionFilter filter) {
|
||||
this.pdfStamper = pdfStamper;
|
||||
this.filter = filter;
|
||||
}
|
||||
|
||||
public void renderText(TextRenderInfo renderInfo) {
|
||||
if (renderInfo.getPdfString().toUnicodeString().length() == 0)
|
||||
return;
|
||||
for (TextRenderInfo ri : (Iterable<TextRenderInfo>)renderInfo.getCharacterRenderInfos()) {
|
||||
boolean isAllowed = this.filter.allowText(ri);
|
||||
LineSegment baseline = ri.getUnscaledBaseline();
|
||||
this.chunks.add(new PdfCleanUpContentChunk.Text(ri.getPdfString(), baseline.getStartPoint(),
|
||||
baseline.getEndPoint(), isAllowed, this.strNumber));
|
||||
}
|
||||
this.strNumber++;
|
||||
}
|
||||
|
||||
public void renderImage(ImageRenderInfo renderInfo) {
|
||||
List<Rectangle> areasToBeCleaned = getImageAreasToBeCleaned(renderInfo);
|
||||
if (areasToBeCleaned == null) {
|
||||
this.chunks.add(new PdfCleanUpContentChunk.Image(false, null));
|
||||
} else {
|
||||
try {
|
||||
PdfImageObject pdfImage = renderInfo.getImage();
|
||||
byte[] imageBytes = processImage(pdfImage.getImageAsBytes(), areasToBeCleaned);
|
||||
if (renderInfo.getRef() == null && pdfImage != null) {
|
||||
PdfDictionary dict = pdfImage.getDictionary();
|
||||
PdfObject imageMask = dict.get(PdfName.IMAGEMASK);
|
||||
Image image = Image.getInstance(imageBytes);
|
||||
if (imageMask == null)
|
||||
imageMask = dict.get(PdfName.IM);
|
||||
if (imageMask != null && imageMask.equals(PdfBoolean.PDFTRUE))
|
||||
image.makeMask();
|
||||
PdfContentByte canvas = getContext().getCanvas();
|
||||
canvas.addImage(image, 1.0F, 0.0F, 0.0F, 1.0F, 0.0F, 0.0F, true);
|
||||
} else if (pdfImage != null && imageBytes != pdfImage.getImageAsBytes()) {
|
||||
this.chunks.add(new PdfCleanUpContentChunk.Image(true, imageBytes));
|
||||
}
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void beginTextBlock() {}
|
||||
|
||||
public void endTextBlock() {}
|
||||
|
||||
public void modifyPath(PathConstructionRenderInfo renderInfo) {
|
||||
List<Float> segmentData = renderInfo.getSegmentData();
|
||||
switch (renderInfo.getOperation()) {
|
||||
case 1:
|
||||
this.unfilteredCurrentPath.moveTo(segmentData.get(0).floatValue(), segmentData.get(1).floatValue());
|
||||
break;
|
||||
case 2:
|
||||
this.unfilteredCurrentPath.lineTo(segmentData.get(0).floatValue(), segmentData.get(1).floatValue());
|
||||
break;
|
||||
case 3:
|
||||
this.unfilteredCurrentPath.curveTo(segmentData.get(0).floatValue(), segmentData.get(1).floatValue(), segmentData.get(2).floatValue(),
|
||||
segmentData.get(3).floatValue(), segmentData.get(4).floatValue(), segmentData.get(5).floatValue());
|
||||
break;
|
||||
case 4:
|
||||
this.unfilteredCurrentPath.curveTo(segmentData.get(0).floatValue(), segmentData.get(1).floatValue(), segmentData.get(2).floatValue(), segmentData.get(3).floatValue());
|
||||
break;
|
||||
case 5:
|
||||
this.unfilteredCurrentPath.curveFromTo(segmentData.get(0).floatValue(), segmentData.get(1).floatValue(), segmentData.get(2).floatValue(), segmentData.get(3).floatValue());
|
||||
break;
|
||||
case 6:
|
||||
this.unfilteredCurrentPath.closeSubpath();
|
||||
break;
|
||||
case 7:
|
||||
this.unfilteredCurrentPath.rectangle(segmentData.get(0).floatValue(), segmentData.get(1).floatValue(), segmentData.get(2).floatValue(), segmentData.get(3).floatValue());
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
public Path renderPath(PathPaintingRenderInfo renderInfo) {
|
||||
boolean stroke = ((renderInfo.getOperation() & 0x1) != 0);
|
||||
boolean fill = ((renderInfo.getOperation() & 0x2) != 0);
|
||||
float lineWidth = renderInfo.getLineWidth();
|
||||
int lineCapStyle = renderInfo.getLineCapStyle();
|
||||
int lineJoinStyle = renderInfo.getLineJoinStyle();
|
||||
float miterLimit = renderInfo.getMiterLimit();
|
||||
LineDashPattern lineDashPattern = renderInfo.getLineDashPattern();
|
||||
if (stroke)
|
||||
this.currentStrokePath = filterCurrentPath(renderInfo.getCtm(), true, -1, lineWidth, lineCapStyle, lineJoinStyle, miterLimit, lineDashPattern);
|
||||
if (fill)
|
||||
this.currentFillPath = filterCurrentPath(renderInfo.getCtm(), false, renderInfo.getRule(), lineWidth, lineCapStyle, lineJoinStyle, miterLimit, lineDashPattern);
|
||||
if (this.clipPath)
|
||||
if (fill && renderInfo.getRule() == this.clippingRule) {
|
||||
this.newClippingPath = this.currentFillPath;
|
||||
} else {
|
||||
this.newClippingPath = filterCurrentPath(renderInfo.getCtm(), false, this.clippingRule, lineWidth, lineCapStyle, lineJoinStyle, miterLimit, lineDashPattern);
|
||||
}
|
||||
this.unfilteredCurrentPath = new Path();
|
||||
return this.newClippingPath;
|
||||
}
|
||||
|
||||
public void clipPath(int rule) {
|
||||
this.clipPath = true;
|
||||
this.clippingRule = rule;
|
||||
}
|
||||
|
||||
public boolean isClipped() {
|
||||
return this.clipPath;
|
||||
}
|
||||
|
||||
public void setClipped(boolean clipPath) {
|
||||
this.clipPath = clipPath;
|
||||
}
|
||||
|
||||
public int getClippingRule() {
|
||||
return this.clippingRule;
|
||||
}
|
||||
|
||||
public Path getCurrentStrokePath() {
|
||||
return this.currentStrokePath;
|
||||
}
|
||||
|
||||
public Path getCurrentFillPath() {
|
||||
return this.currentFillPath;
|
||||
}
|
||||
|
||||
public Path getNewClipPath() {
|
||||
return this.newClippingPath;
|
||||
}
|
||||
|
||||
public List<PdfCleanUpContentChunk> getChunks() {
|
||||
return this.chunks;
|
||||
}
|
||||
|
||||
public PdfCleanUpContext getContext() {
|
||||
return this.contextStack.peek();
|
||||
}
|
||||
|
||||
public void registerNewContext(PdfDictionary resources, PdfContentByte canvas) {
|
||||
canvas = (canvas == null) ? new PdfContentByte(this.pdfStamper.getWriter()) : canvas;
|
||||
this.contextStack.push(new PdfCleanUpContext(resources, canvas));
|
||||
}
|
||||
|
||||
public void popContext() {
|
||||
this.contextStack.pop();
|
||||
}
|
||||
|
||||
public void clearChunks() {
|
||||
this.chunks.clear();
|
||||
this.strNumber = 1;
|
||||
}
|
||||
|
||||
private List<Rectangle> getImageAreasToBeCleaned(ImageRenderInfo renderInfo) {
|
||||
return this.filter.getCoveredAreas(renderInfo);
|
||||
}
|
||||
|
||||
private byte[] processImage(byte[] imageBytes, List<Rectangle> areasToBeCleaned) {
|
||||
if (areasToBeCleaned.isEmpty())
|
||||
return imageBytes;
|
||||
try {
|
||||
BufferedImage image = Imaging.getBufferedImage(imageBytes);
|
||||
ImageInfo imageInfo = Imaging.getImageInfo(imageBytes);
|
||||
cleanImage(image, areasToBeCleaned);
|
||||
if (imageInfo.getFormat() == ImageFormats.JPEG)
|
||||
return getJPGBytes(image);
|
||||
Map<String, Object> params = new HashMap<String, Object>();
|
||||
if (imageInfo.getFormat() == ImageFormats.TIFF)
|
||||
params.put("COMPRESSION", Integer.valueOf(5));
|
||||
return Imaging.writeImageToBytes(image, imageInfo.getFormat(), params);
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
|
||||
private void cleanImage(BufferedImage image, List<Rectangle> areasToBeCleaned) {
|
||||
Graphics2D graphics = image.createGraphics();
|
||||
graphics.setColor(CLEANED_AREA_FILL_COLOR);
|
||||
for (Rectangle rect : areasToBeCleaned) {
|
||||
int scaledBottomY = (int)Math.ceil((double)(rect.getBottom() * (float)image.getHeight()));
|
||||
int scaledTopY = (int)Math.floor((double)(rect.getTop() * (float)image.getHeight()));
|
||||
int x = (int)Math.ceil((double)(rect.getLeft() * (float)image.getWidth()));
|
||||
int y = scaledTopY * -1 + image.getHeight();
|
||||
int width = (int)Math.floor((double)(rect.getRight() * (float)image.getWidth())) - x;
|
||||
int height = scaledTopY - scaledBottomY;
|
||||
graphics.fillRect(x, y, width, height);
|
||||
}
|
||||
graphics.dispose();
|
||||
}
|
||||
|
||||
private byte[] getJPGBytes(BufferedImage image) {
|
||||
ByteArrayOutputStream outputStream = null;
|
||||
try {
|
||||
ImageWriter jpgWriter = ImageIO.getImageWritersByFormatName("jpg").next();
|
||||
ImageWriteParam jpgWriteParam = jpgWriter.getDefaultWriteParam();
|
||||
jpgWriteParam.setCompressionMode(2);
|
||||
jpgWriteParam.setCompressionQuality(1.0F);
|
||||
outputStream = new ByteArrayOutputStream();
|
||||
jpgWriter.setOutput(new MemoryCacheImageOutputStream(outputStream));
|
||||
IIOImage outputImage = new IIOImage(image, null, null);
|
||||
jpgWriter.write(null, outputImage, jpgWriteParam);
|
||||
jpgWriter.dispose();
|
||||
outputStream.flush();
|
||||
return outputStream.toByteArray();
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException(e);
|
||||
} finally {
|
||||
closeOutputStream(outputStream);
|
||||
}
|
||||
}
|
||||
|
||||
private Path filterCurrentPath(Matrix ctm, boolean stroke, int fillingRule, float lineWidth, int lineCapStyle, int lineJoinStyle, float miterLimit, LineDashPattern lineDashPattern) {
|
||||
Path path = new Path(this.unfilteredCurrentPath.getSubpaths());
|
||||
if (stroke)
|
||||
return this.filter.filterStrokePath(path, ctm, lineWidth, lineCapStyle, lineJoinStyle, miterLimit, lineDashPattern);
|
||||
return this.filter.filterFillPath(path, ctm, fillingRule);
|
||||
}
|
||||
|
||||
private void closeOutputStream(OutputStream os) {
|
||||
if (os != null)
|
||||
try {
|
||||
os.close();
|
||||
} catch (IOException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,31 @@
|
|||
package com.itextpdf.text.pdf.richmedia;
|
||||
|
||||
import com.itextpdf.text.exceptions.IllegalPdfSyntaxException;
|
||||
import com.itextpdf.text.pdf.PdfDictionary;
|
||||
import com.itextpdf.text.pdf.PdfName;
|
||||
import com.itextpdf.text.pdf.PdfNumber;
|
||||
import com.itextpdf.text.pdf.PdfObject;
|
||||
import com.itextpdf.text.pdf.PdfString;
|
||||
|
||||
public class CuePoint extends PdfDictionary {
|
||||
public CuePoint(PdfName subtype) {
|
||||
super(PdfName.CUEPOINT);
|
||||
put(PdfName.SUBTYPE, (PdfObject)subtype);
|
||||
}
|
||||
|
||||
public void setName(PdfString name) {
|
||||
put(PdfName.NAME, (PdfObject)name);
|
||||
}
|
||||
|
||||
public void setTime(int time) {
|
||||
put(PdfName.TIME, new PdfNumber(time));
|
||||
}
|
||||
|
||||
public void setAction(PdfObject action) {
|
||||
if (action instanceof PdfDictionary || action instanceof com.itextpdf.text.pdf.PdfIndirectReference) {
|
||||
put(PdfName.A, action);
|
||||
} else {
|
||||
throw new IllegalPdfSyntaxException("An action should be defined as a dictionary");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,37 @@
|
|||
package com.itextpdf.text.pdf.richmedia;
|
||||
|
||||
import com.itextpdf.text.pdf.PdfArray;
|
||||
import com.itextpdf.text.pdf.PdfDictionary;
|
||||
import com.itextpdf.text.pdf.PdfIndirectReference;
|
||||
import com.itextpdf.text.pdf.PdfName;
|
||||
import com.itextpdf.text.pdf.PdfObject;
|
||||
|
||||
public class RichMediaActivation extends PdfDictionary {
|
||||
public RichMediaActivation() {
|
||||
super(PdfName.RICHMEDIAACTIVATION);
|
||||
}
|
||||
|
||||
public void setCondition(PdfName condition) {
|
||||
put(PdfName.CONDITION, (PdfObject)condition);
|
||||
}
|
||||
|
||||
public void setAnimation(RichMediaAnimation animation) {
|
||||
put(PdfName.ANIMATION, (PdfObject)animation);
|
||||
}
|
||||
|
||||
public void setView(PdfIndirectReference view) {
|
||||
put(PdfName.VIEW, (PdfObject)view);
|
||||
}
|
||||
|
||||
public void setConfiguration(PdfIndirectReference configuration) {
|
||||
put(PdfName.CONFIGURATION, (PdfObject)configuration);
|
||||
}
|
||||
|
||||
public void setPresentation(RichMediaPresentation richMediaPresentation) {
|
||||
put(PdfName.PRESENTATION, (PdfObject)richMediaPresentation);
|
||||
}
|
||||
|
||||
public void setScripts(PdfArray scripts) {
|
||||
put(PdfName.SCRIPTS, (PdfObject)scripts);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,25 @@
|
|||
package com.itextpdf.text.pdf.richmedia;
|
||||
|
||||
import com.itextpdf.text.pdf.PdfDictionary;
|
||||
import com.itextpdf.text.pdf.PdfName;
|
||||
import com.itextpdf.text.pdf.PdfNumber;
|
||||
import com.itextpdf.text.pdf.PdfObject;
|
||||
|
||||
public class RichMediaAnimation extends PdfDictionary {
|
||||
public RichMediaAnimation(PdfName subtype) {
|
||||
super(PdfName.RICHMEDIAANIMATION);
|
||||
put(PdfName.SUBTYPE, (PdfObject)subtype);
|
||||
}
|
||||
|
||||
public void setPlayCount(int playCount) {
|
||||
put(PdfName.PLAYCOUNT, new PdfNumber(playCount));
|
||||
}
|
||||
|
||||
public void setSpeed(int speed) {
|
||||
put(PdfName.SPEED, new PdfNumber(speed));
|
||||
}
|
||||
|
||||
public void setSpeed(float speed) {
|
||||
put(PdfName.SPEED, new PdfNumber(speed));
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,125 @@
|
|||
package com.itextpdf.text.pdf.richmedia;
|
||||
|
||||
import com.itextpdf.text.Rectangle;
|
||||
import com.itextpdf.text.exceptions.IllegalPdfSyntaxException;
|
||||
import com.itextpdf.text.pdf.PdfAnnotation;
|
||||
import com.itextpdf.text.pdf.PdfArray;
|
||||
import com.itextpdf.text.pdf.PdfDeveloperExtension;
|
||||
import com.itextpdf.text.pdf.PdfDictionary;
|
||||
import com.itextpdf.text.pdf.PdfFileSpecification;
|
||||
import com.itextpdf.text.pdf.PdfIndirectReference;
|
||||
import com.itextpdf.text.pdf.PdfName;
|
||||
import com.itextpdf.text.pdf.PdfNameTree;
|
||||
import com.itextpdf.text.pdf.PdfObject;
|
||||
import com.itextpdf.text.pdf.PdfWriter;
|
||||
import java.io.IOException;
|
||||
import java.util.HashMap;
|
||||
|
||||
public class RichMediaAnnotation {
|
||||
protected PdfWriter writer;
|
||||
|
||||
protected PdfAnnotation annot;
|
||||
|
||||
protected PdfDictionary richMediaContent = null;
|
||||
|
||||
protected PdfIndirectReference richMediaContentReference = null;
|
||||
|
||||
protected PdfDictionary richMediaSettings = new PdfDictionary(PdfName.RICHMEDIASETTINGS);
|
||||
|
||||
protected HashMap<String, PdfIndirectReference> assetsmap = null;
|
||||
|
||||
protected PdfArray configurations = null;
|
||||
|
||||
protected PdfArray views = null;
|
||||
|
||||
public RichMediaAnnotation(PdfWriter writer, Rectangle rect) {
|
||||
this.writer = writer;
|
||||
this.annot = writer.createAnnotation(rect, PdfName.RICHMEDIA);
|
||||
this.richMediaContent = new PdfDictionary(PdfName.RICHMEDIACONTENT);
|
||||
this.assetsmap = new HashMap<String, PdfIndirectReference>();
|
||||
this.configurations = new PdfArray();
|
||||
this.views = new PdfArray();
|
||||
}
|
||||
|
||||
public RichMediaAnnotation(PdfWriter writer, Rectangle rect, PdfIndirectReference richMediaContentReference) {
|
||||
this.richMediaContentReference = richMediaContentReference;
|
||||
this.richMediaContent = null;
|
||||
this.writer = writer;
|
||||
this.annot = writer.createAnnotation(rect, PdfName.RICHMEDIA);
|
||||
}
|
||||
|
||||
public PdfIndirectReference getRichMediaContentReference() {
|
||||
return this.richMediaContentReference;
|
||||
}
|
||||
|
||||
public PdfIndirectReference addAsset(String name, PdfFileSpecification fs) throws IOException {
|
||||
if (this.assetsmap == null)
|
||||
throw new IllegalPdfSyntaxException("You can't add assets to reused RichMediaContent.");
|
||||
PdfIndirectReference ref = this.writer.addToBody((PdfObject)fs).getIndirectReference();
|
||||
this.assetsmap.put(name, ref);
|
||||
return ref;
|
||||
}
|
||||
|
||||
public PdfIndirectReference addAsset(String name, PdfIndirectReference ref) throws IOException {
|
||||
if (this.views == null)
|
||||
throw new IllegalPdfSyntaxException("You can't add assets to reused RichMediaContent.");
|
||||
this.assetsmap.put(name, ref);
|
||||
return ref;
|
||||
}
|
||||
|
||||
public PdfIndirectReference addConfiguration(RichMediaConfiguration configuration) throws IOException {
|
||||
if (this.configurations == null)
|
||||
throw new IllegalPdfSyntaxException("You can't add configurations to reused RichMediaContent.");
|
||||
PdfIndirectReference ref = this.writer.addToBody((PdfObject)configuration).getIndirectReference();
|
||||
this.configurations.add((PdfObject)ref);
|
||||
return ref;
|
||||
}
|
||||
|
||||
public PdfIndirectReference addConfiguration(PdfIndirectReference ref) throws IOException {
|
||||
if (this.configurations == null)
|
||||
throw new IllegalPdfSyntaxException("You can't add configurations to reused RichMediaContent.");
|
||||
this.configurations.add((PdfObject)ref);
|
||||
return ref;
|
||||
}
|
||||
|
||||
public PdfIndirectReference addView(PdfDictionary view) throws IOException {
|
||||
if (this.views == null)
|
||||
throw new IllegalPdfSyntaxException("You can't add views to reused RichMediaContent.");
|
||||
PdfIndirectReference ref = this.writer.addToBody((PdfObject)view).getIndirectReference();
|
||||
this.views.add((PdfObject)ref);
|
||||
return ref;
|
||||
}
|
||||
|
||||
public PdfIndirectReference addView(PdfIndirectReference ref) throws IOException {
|
||||
if (this.views == null)
|
||||
throw new IllegalPdfSyntaxException("You can't add views to reused RichMediaContent.");
|
||||
this.views.add((PdfObject)ref);
|
||||
return ref;
|
||||
}
|
||||
|
||||
public void setActivation(RichMediaActivation richMediaActivation) {
|
||||
this.richMediaSettings.put(PdfName.ACTIVATION, (PdfObject)richMediaActivation);
|
||||
}
|
||||
|
||||
public void setDeactivation(RichMediaDeactivation richMediaDeactivation) {
|
||||
this.richMediaSettings.put(PdfName.DEACTIVATION, (PdfObject)richMediaDeactivation);
|
||||
}
|
||||
|
||||
public PdfAnnotation createAnnotation() throws IOException {
|
||||
if (this.richMediaContent != null) {
|
||||
if (!this.assetsmap.isEmpty()) {
|
||||
PdfDictionary assets = PdfNameTree.writeTree(this.assetsmap, this.writer);
|
||||
this.richMediaContent.put(PdfName.ASSETS, (PdfObject)this.writer.addToBody((PdfObject)assets).getIndirectReference());
|
||||
}
|
||||
if (this.configurations.size() > 0)
|
||||
this.richMediaContent.put(PdfName.CONFIGURATION, (PdfObject)this.writer.addToBody((PdfObject)this.configurations).getIndirectReference());
|
||||
if (this.views.size() > 0)
|
||||
this.richMediaContent.put(PdfName.VIEWS, (PdfObject)this.writer.addToBody((PdfObject)this.views).getIndirectReference());
|
||||
this.richMediaContentReference = this.writer.addToBody((PdfObject)this.richMediaContent).getIndirectReference();
|
||||
}
|
||||
this.writer.addDeveloperExtension(PdfDeveloperExtension.ADOBE_1_7_EXTENSIONLEVEL3);
|
||||
this.annot.put(PdfName.RICHMEDIACONTENT, (PdfObject)this.richMediaContentReference);
|
||||
this.annot.put(PdfName.RICHMEDIASETTINGS, (PdfObject)this.writer.addToBody((PdfObject)this.richMediaSettings).getIndirectReference());
|
||||
return this.annot;
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,17 @@
|
|||
package com.itextpdf.text.pdf.richmedia;
|
||||
|
||||
import com.itextpdf.text.pdf.PdfDictionary;
|
||||
import com.itextpdf.text.pdf.PdfName;
|
||||
import com.itextpdf.text.pdf.PdfObject;
|
||||
import com.itextpdf.text.pdf.PdfString;
|
||||
|
||||
public class RichMediaCommand extends PdfDictionary {
|
||||
public RichMediaCommand(PdfString command) {
|
||||
super(PdfName.RICHMEDIACOMMAND);
|
||||
put(PdfName.C, (PdfObject)command);
|
||||
}
|
||||
|
||||
public void setArguments(PdfObject args) {
|
||||
put(PdfName.A, args);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,25 @@
|
|||
package com.itextpdf.text.pdf.richmedia;
|
||||
|
||||
import com.itextpdf.text.pdf.PdfArray;
|
||||
import com.itextpdf.text.pdf.PdfDictionary;
|
||||
import com.itextpdf.text.pdf.PdfName;
|
||||
import com.itextpdf.text.pdf.PdfObject;
|
||||
import com.itextpdf.text.pdf.PdfString;
|
||||
|
||||
public class RichMediaConfiguration extends PdfDictionary {
|
||||
protected PdfArray instances = new PdfArray();
|
||||
|
||||
public RichMediaConfiguration(PdfName subtype) {
|
||||
super(PdfName.RICHMEDIACONFIGURATION);
|
||||
put(PdfName.SUBTYPE, (PdfObject)subtype);
|
||||
put(PdfName.INSTANCES, (PdfObject)this.instances);
|
||||
}
|
||||
|
||||
public void setName(PdfString name) {
|
||||
put(PdfName.NAME, (PdfObject)name);
|
||||
}
|
||||
|
||||
public void addInstance(RichMediaInstance instance) {
|
||||
this.instances.add((PdfObject)instance);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,15 @@
|
|||
package com.itextpdf.text.pdf.richmedia;
|
||||
|
||||
import com.itextpdf.text.pdf.PdfDictionary;
|
||||
import com.itextpdf.text.pdf.PdfName;
|
||||
import com.itextpdf.text.pdf.PdfObject;
|
||||
|
||||
public class RichMediaDeactivation extends PdfDictionary {
|
||||
public RichMediaDeactivation() {
|
||||
super(PdfName.RICHMEDIADEACTIVATION);
|
||||
}
|
||||
|
||||
public void setCondition(PdfName condition) {
|
||||
put(PdfName.CONDITION, (PdfObject)condition);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,18 @@
|
|||
package com.itextpdf.text.pdf.richmedia;
|
||||
|
||||
import com.itextpdf.text.pdf.PdfAction;
|
||||
import com.itextpdf.text.pdf.PdfIndirectReference;
|
||||
import com.itextpdf.text.pdf.PdfName;
|
||||
import com.itextpdf.text.pdf.PdfObject;
|
||||
|
||||
public class RichMediaExecuteAction extends PdfAction {
|
||||
public RichMediaExecuteAction(PdfIndirectReference ref, RichMediaCommand command) {
|
||||
put(PdfName.S, (PdfObject)PdfName.RICHMEDIAEXECUTE);
|
||||
put(PdfName.TA, (PdfObject)ref);
|
||||
put(PdfName.CMD, (PdfObject)command);
|
||||
}
|
||||
|
||||
public void setRichMediaInstance(PdfIndirectReference ref) {
|
||||
put(PdfName.TI, (PdfObject)ref);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,29 @@
|
|||
package com.itextpdf.text.pdf.richmedia;
|
||||
|
||||
import com.itextpdf.text.exceptions.IllegalPdfSyntaxException;
|
||||
import com.itextpdf.text.pdf.PdfDictionary;
|
||||
import com.itextpdf.text.pdf.PdfIndirectReference;
|
||||
import com.itextpdf.text.pdf.PdfName;
|
||||
import com.itextpdf.text.pdf.PdfObject;
|
||||
|
||||
public class RichMediaInstance extends PdfDictionary {
|
||||
protected boolean flash;
|
||||
|
||||
public RichMediaInstance(PdfName subtype) {
|
||||
super(PdfName.RICHMEDIAINSTANCE);
|
||||
put(PdfName.SUBTYPE, (PdfObject)subtype);
|
||||
this.flash = PdfName.FLASH.equals(subtype);
|
||||
}
|
||||
|
||||
public void setParams(RichMediaParams params) {
|
||||
if (this.flash) {
|
||||
put(PdfName.PARAMS, (PdfObject)params);
|
||||
} else {
|
||||
throw new IllegalPdfSyntaxException("Parameters can only be set for Flash instances.");
|
||||
}
|
||||
}
|
||||
|
||||
public void setAsset(PdfIndirectReference asset) {
|
||||
put(PdfName.ASSET, (PdfObject)asset);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,33 @@
|
|||
package com.itextpdf.text.pdf.richmedia;
|
||||
|
||||
import com.itextpdf.text.pdf.PdfArray;
|
||||
import com.itextpdf.text.pdf.PdfDictionary;
|
||||
import com.itextpdf.text.pdf.PdfName;
|
||||
import com.itextpdf.text.pdf.PdfObject;
|
||||
import com.itextpdf.text.pdf.PdfString;
|
||||
|
||||
public class RichMediaParams extends PdfDictionary {
|
||||
public RichMediaParams() {
|
||||
super(PdfName.RICHMEDIAPARAMS);
|
||||
}
|
||||
|
||||
public void setFlashVars(String flashVars) {
|
||||
put(PdfName.FLASHVARS, new PdfString(flashVars));
|
||||
}
|
||||
|
||||
public void setBinding(PdfName binding) {
|
||||
put(PdfName.BINDING, (PdfObject)binding);
|
||||
}
|
||||
|
||||
public void setBindingMaterialName(PdfString bindingMaterialName) {
|
||||
put(PdfName.BINDINGMATERIALNAME, (PdfObject)bindingMaterialName);
|
||||
}
|
||||
|
||||
public void setCuePoints(PdfArray cuePoints) {
|
||||
put(PdfName.CUEPOINTS, (PdfObject)cuePoints);
|
||||
}
|
||||
|
||||
public void setSettings(PdfString settings) {
|
||||
put(PdfName.SETTINGS, (PdfObject)settings);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,28 @@
|
|||
package com.itextpdf.text.pdf.richmedia;
|
||||
|
||||
import com.itextpdf.text.pdf.PdfDictionary;
|
||||
import com.itextpdf.text.pdf.PdfName;
|
||||
import com.itextpdf.text.pdf.PdfNumber;
|
||||
import com.itextpdf.text.pdf.PdfObject;
|
||||
|
||||
public class RichMediaPosition extends PdfDictionary {
|
||||
public RichMediaPosition() {
|
||||
super(PdfName.RICHMEDIAPOSITION);
|
||||
}
|
||||
|
||||
public void setHAlign(PdfName hAlign) {
|
||||
put(PdfName.HALIGN, (PdfObject)hAlign);
|
||||
}
|
||||
|
||||
public void setVAlign(PdfName vAlign) {
|
||||
put(PdfName.VALIGN, (PdfObject)vAlign);
|
||||
}
|
||||
|
||||
public void setHOffset(float hOffset) {
|
||||
put(PdfName.HOFFSET, new PdfNumber(hOffset));
|
||||
}
|
||||
|
||||
public void setVOffset(float vOffset) {
|
||||
put(PdfName.VOFFSET, new PdfNumber(vOffset));
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,35 @@
|
|||
package com.itextpdf.text.pdf.richmedia;
|
||||
|
||||
import com.itextpdf.text.pdf.PdfBoolean;
|
||||
import com.itextpdf.text.pdf.PdfName;
|
||||
import com.itextpdf.text.pdf.PdfObject;
|
||||
|
||||
public class RichMediaPresentation extends Object {
|
||||
public RichMediaPresentation() {
|
||||
super(PdfName.RICHMEDIAPRESENTATION);
|
||||
}
|
||||
|
||||
public void setStyle(PdfName style) {
|
||||
put(PdfName.STYLE, (PdfObject)style);
|
||||
}
|
||||
|
||||
public void setWindow(RichMediaWindow window) {
|
||||
put(PdfName.WINDOW, (PdfObject)window);
|
||||
}
|
||||
|
||||
public void setTransparent(PdfBoolean transparent) {
|
||||
put(PdfName.TRANSPARENT, (PdfObject)transparent);
|
||||
}
|
||||
|
||||
public void setNavigationPane(PdfBoolean navigationPane) {
|
||||
put(PdfName.NAVIGATIONPANE, (PdfObject)navigationPane);
|
||||
}
|
||||
|
||||
public void setToolbar(PdfBoolean toolbar) {
|
||||
put(PdfName.TOOLBAR, (PdfObject)toolbar);
|
||||
}
|
||||
|
||||
public void setPassContextClick(PdfBoolean passContextClick) {
|
||||
put(PdfName.PASSCONTEXTCLICK, (PdfObject)passContextClick);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,32 @@
|
|||
package com.itextpdf.text.pdf.richmedia;
|
||||
|
||||
import com.itextpdf.text.pdf.PdfDictionary;
|
||||
import com.itextpdf.text.pdf.PdfName;
|
||||
import com.itextpdf.text.pdf.PdfNumber;
|
||||
import com.itextpdf.text.pdf.PdfObject;
|
||||
|
||||
public class RichMediaWindow extends PdfDictionary {
|
||||
public RichMediaWindow() {
|
||||
super(PdfName.RICHMEDIAWINDOW);
|
||||
}
|
||||
|
||||
public void setWidth(float defaultWidth, float maxWidth, float minWidth) {
|
||||
put(PdfName.WIDTH, (PdfObject)createDimensionDictionary(defaultWidth, maxWidth, minWidth));
|
||||
}
|
||||
|
||||
public void setHeight(float defaultHeight, float maxHeight, float minHeight) {
|
||||
put(PdfName.HEIGHT, (PdfObject)createDimensionDictionary(defaultHeight, maxHeight, minHeight));
|
||||
}
|
||||
|
||||
private PdfDictionary createDimensionDictionary(float d, float max, float min) {
|
||||
PdfDictionary dict = new PdfDictionary();
|
||||
dict.put(PdfName.DEFAULT, new PdfNumber(d));
|
||||
dict.put(PdfName.MAX_CAMEL_CASE, new PdfNumber(max));
|
||||
dict.put(PdfName.MIN_CAMEL_CASE, new PdfNumber(min));
|
||||
return dict;
|
||||
}
|
||||
|
||||
public void setPosition(RichMediaPosition position) {
|
||||
put(PdfName.POSITION, (PdfObject)position);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,20 @@
|
|||
package com.itextpdf.text.pdf.spatial;
|
||||
|
||||
import com.itextpdf.text.pdf.PdfDictionary;
|
||||
import com.itextpdf.text.pdf.PdfName;
|
||||
import com.itextpdf.text.pdf.PdfNumber;
|
||||
import com.itextpdf.text.pdf.PdfString;
|
||||
|
||||
public abstract class CoordinateSystem extends PdfDictionary {
|
||||
public CoordinateSystem(PdfName type) {
|
||||
super(type);
|
||||
}
|
||||
|
||||
public void setEPSG(int epsg) {
|
||||
put(PdfName.EPSG, new PdfNumber(epsg));
|
||||
}
|
||||
|
||||
public void setWKT(String wkt) {
|
||||
put(PdfName.WKT, new PdfString(wkt));
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,9 @@
|
|||
package com.itextpdf.text.pdf.spatial;
|
||||
|
||||
import com.itextpdf.text.pdf.PdfName;
|
||||
|
||||
public class GeographicCoordinateSystem extends CoordinateSystem {
|
||||
public GeographicCoordinateSystem() {
|
||||
super(PdfName.GEOGCS);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,14 @@
|
|||
package com.itextpdf.text.pdf.spatial;
|
||||
|
||||
import com.itextpdf.text.pdf.PdfDictionary;
|
||||
import com.itextpdf.text.pdf.PdfName;
|
||||
import com.itextpdf.text.pdf.PdfObject;
|
||||
|
||||
public abstract class Measure extends PdfDictionary {
|
||||
public Measure() {
|
||||
super(PdfName.MEASURE);
|
||||
put(PdfName.SUBTYPE, (PdfObject)getSubType());
|
||||
}
|
||||
|
||||
abstract PdfName getSubType();
|
||||
}
|
||||
|
|
@ -0,0 +1,43 @@
|
|||
package com.itextpdf.text.pdf.spatial;
|
||||
|
||||
import com.itextpdf.text.pdf.NumberArray;
|
||||
import com.itextpdf.text.pdf.PdfArray;
|
||||
import com.itextpdf.text.pdf.PdfName;
|
||||
import com.itextpdf.text.pdf.PdfObject;
|
||||
import com.itextpdf.text.pdf.spatial.units.Angular;
|
||||
import com.itextpdf.text.pdf.spatial.units.Linear;
|
||||
import com.itextpdf.text.pdf.spatial.units.Square;
|
||||
|
||||
public class MeasureGeospatial extends Measure {
|
||||
PdfName getSubType() {
|
||||
return PdfName.GEO;
|
||||
}
|
||||
|
||||
public void setBounds(NumberArray bounds) {
|
||||
put(PdfName.BOUNDS, (PdfObject)bounds);
|
||||
}
|
||||
|
||||
public void setCoordinateSystem(CoordinateSystem cs) {
|
||||
put(PdfName.GCS, (PdfObject)cs);
|
||||
}
|
||||
|
||||
public void setDisplayCoordinateSystem(GeographicCoordinateSystem cs) {
|
||||
put(PdfName.DCS, (PdfObject)cs);
|
||||
}
|
||||
|
||||
public void setDisplayUnits(Linear l, Square s, Angular a) {
|
||||
PdfArray arr = new PdfArray();
|
||||
arr.add((PdfObject)l.getPdfName());
|
||||
arr.add((PdfObject)s.getPdfName());
|
||||
arr.add((PdfObject)a.getPdfName());
|
||||
put(PdfName.PDU, (PdfObject)arr);
|
||||
}
|
||||
|
||||
public void setGPTS(NumberArray pairedpoints) {
|
||||
put(PdfName.GPTS, (PdfObject)pairedpoints);
|
||||
}
|
||||
|
||||
public void setLPTS(NumberArray pairedpoints) {
|
||||
put(PdfName.LPTS, (PdfObject)pairedpoints);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,50 @@
|
|||
package com.itextpdf.text.pdf.spatial;
|
||||
|
||||
import com.itextpdf.text.pdf.PdfName;
|
||||
import com.itextpdf.text.pdf.PdfNumber;
|
||||
import com.itextpdf.text.pdf.PdfObject;
|
||||
import com.itextpdf.text.pdf.PdfString;
|
||||
import com.itextpdf.text.pdf.spatial.objects.NumberFormatArray;
|
||||
import com.itextpdf.text.pdf.spatial.objects.XYArray;
|
||||
|
||||
public class MeasureRectilinear extends Measure {
|
||||
PdfName getSubType() {
|
||||
return PdfName.RL;
|
||||
}
|
||||
|
||||
public void setScaleRatio(PdfString scaleratio) {
|
||||
put(new PdfName("R"), (PdfObject)scaleratio);
|
||||
}
|
||||
|
||||
public void setX(NumberFormatArray x) {
|
||||
put(new PdfName("X"), (PdfObject)x);
|
||||
}
|
||||
|
||||
public void setY(NumberFormatArray y) {
|
||||
put(new PdfName("Y"), (PdfObject)y);
|
||||
}
|
||||
|
||||
public void setD(NumberFormatArray d) {
|
||||
put(new PdfName("D"), (PdfObject)d);
|
||||
}
|
||||
|
||||
public void setA(NumberFormatArray a) {
|
||||
put(new PdfName("A"), (PdfObject)a);
|
||||
}
|
||||
|
||||
public void setT(NumberFormatArray t) {
|
||||
put(new PdfName("T"), (PdfObject)t);
|
||||
}
|
||||
|
||||
public void setS(NumberFormatArray s) {
|
||||
put(new PdfName("S"), (PdfObject)s);
|
||||
}
|
||||
|
||||
public void setO(XYArray o) {
|
||||
put(new PdfName("O"), (PdfObject)o);
|
||||
}
|
||||
|
||||
public void setCYX(PdfNumber cyx) {
|
||||
put(PdfName.CYX, (PdfObject)cyx);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,26 @@
|
|||
package com.itextpdf.text.pdf.spatial;
|
||||
|
||||
import com.itextpdf.text.pdf.PdfArray;
|
||||
import com.itextpdf.text.pdf.PdfDictionary;
|
||||
import com.itextpdf.text.pdf.PdfName;
|
||||
import com.itextpdf.text.pdf.PdfNumber;
|
||||
import com.itextpdf.text.pdf.PdfObject;
|
||||
import com.itextpdf.text.pdf.spatial.units.PtIdentifier;
|
||||
|
||||
public class PointData extends PdfDictionary {
|
||||
protected PdfArray names = new PdfArray();
|
||||
|
||||
protected PdfArray xpts = new PdfArray();
|
||||
|
||||
public PointData() {
|
||||
super(PdfName.PTDATA);
|
||||
putEx(PdfName.SUBTYPE, (PdfObject)PdfName.CLOUD);
|
||||
putEx(PdfName.NAMES, (PdfObject)this.names);
|
||||
putEx(PdfName.XPTS, (PdfObject)this.xpts);
|
||||
}
|
||||
|
||||
public void addXPTSValue(PdfNumber value, PtIdentifier identifier) {
|
||||
this.xpts.add((PdfObject)value);
|
||||
this.names.add((PdfObject)identifier.getPdfName());
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,9 @@
|
|||
package com.itextpdf.text.pdf.spatial;
|
||||
|
||||
import com.itextpdf.text.pdf.PdfName;
|
||||
|
||||
public class ProjectedCoordinateSystem extends CoordinateSystem {
|
||||
public ProjectedCoordinateSystem() {
|
||||
super(PdfName.PROJCS);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,30 @@
|
|||
package com.itextpdf.text.pdf.spatial;
|
||||
|
||||
import com.itextpdf.text.Rectangle;
|
||||
import com.itextpdf.text.pdf.PdfDictionary;
|
||||
import com.itextpdf.text.pdf.PdfName;
|
||||
import com.itextpdf.text.pdf.PdfObject;
|
||||
import com.itextpdf.text.pdf.PdfRectangle;
|
||||
import com.itextpdf.text.pdf.PdfString;
|
||||
|
||||
public class Viewport extends PdfDictionary {
|
||||
public Viewport() {
|
||||
super(PdfName.VIEWPORT);
|
||||
}
|
||||
|
||||
public void setBBox(Rectangle bbox) {
|
||||
put(PdfName.BBOX, new PdfRectangle(bbox, bbox.getRotation()));
|
||||
}
|
||||
|
||||
public void setName(PdfString value) {
|
||||
put(PdfName.NAME, (PdfObject)value);
|
||||
}
|
||||
|
||||
public void setMeasure(Measure measure) {
|
||||
put(PdfName.MEASURE, (PdfObject)measure);
|
||||
}
|
||||
|
||||
public void setPtData(PointData ptData) {
|
||||
put(PdfName.PTDATA, (PdfObject)ptData);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,17 @@
|
|||
package com.itextpdf.text.pdf.spatial.objects;
|
||||
|
||||
import com.itextpdf.text.pdf.PdfArray;
|
||||
import com.itextpdf.text.pdf.PdfObject;
|
||||
import java.util.List;
|
||||
|
||||
public class NumberFormatArray extends PdfArray {
|
||||
public NumberFormatArray(NumberFormatDictionary... formats) {
|
||||
for (NumberFormatDictionary dict : formats)
|
||||
add((PdfObject)dict);
|
||||
}
|
||||
|
||||
public NumberFormatArray(List<NumberFormatDictionary> formats) {
|
||||
for (NumberFormatDictionary dict : formats)
|
||||
add((PdfObject)dict);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,55 @@
|
|||
package com.itextpdf.text.pdf.spatial.objects;
|
||||
|
||||
import com.itextpdf.text.pdf.PdfBoolean;
|
||||
import com.itextpdf.text.pdf.PdfDictionary;
|
||||
import com.itextpdf.text.pdf.PdfName;
|
||||
import com.itextpdf.text.pdf.PdfNumber;
|
||||
import com.itextpdf.text.pdf.PdfObject;
|
||||
import com.itextpdf.text.pdf.PdfString;
|
||||
import com.itextpdf.text.pdf.spatial.units.Fraction;
|
||||
|
||||
public class NumberFormatDictionary extends PdfDictionary {
|
||||
public NumberFormatDictionary() {
|
||||
super(PdfName.NUMBERFORMAT);
|
||||
}
|
||||
|
||||
public void setLabel(PdfString label) {
|
||||
put(PdfName.U, (PdfObject)label);
|
||||
}
|
||||
|
||||
public void setConversionFactor(PdfNumber n) {
|
||||
put(PdfName.C, (PdfObject)n);
|
||||
}
|
||||
|
||||
public void setFractionalValue(Fraction f) {
|
||||
put(PdfName.F, (PdfObject)f.getPdfName());
|
||||
}
|
||||
|
||||
public void setPrecision(PdfNumber precision) {
|
||||
put(PdfName.D, (PdfObject)precision);
|
||||
}
|
||||
|
||||
public void setFixedDenominator(PdfBoolean isFixedDenominator) {
|
||||
put(PdfName.FD, (PdfObject)isFixedDenominator);
|
||||
}
|
||||
|
||||
public void setCipherGroupingCharacter(PdfString rt) {
|
||||
put(PdfName.RT, (PdfObject)rt);
|
||||
}
|
||||
|
||||
public void setDecimalChartacter(PdfString dc) {
|
||||
put(PdfName.RD, (PdfObject)dc);
|
||||
}
|
||||
|
||||
public void setLabelLeftString(PdfString ps) {
|
||||
put(PdfName.PS, (PdfObject)ps);
|
||||
}
|
||||
|
||||
public void setLabelRightString(PdfString ss) {
|
||||
put(PdfName.SS, (PdfObject)ss);
|
||||
}
|
||||
|
||||
public void setLabelPosition(PdfName pos) {
|
||||
put(PdfName.O, (PdfObject)pos);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,9 @@
|
|||
package com.itextpdf.text.pdf.spatial.objects;
|
||||
|
||||
import com.itextpdf.text.pdf.NumberArray;
|
||||
|
||||
public class XYArray extends NumberArray {
|
||||
public XYArray(float x, float y) {
|
||||
super(new float[] { x, y });
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,18 @@
|
|||
package com.itextpdf.text.pdf.spatial.units;
|
||||
|
||||
import com.itextpdf.text.pdf.PdfName;
|
||||
|
||||
public enum Angular {
|
||||
DEGREE("DEG"),
|
||||
GRAD("GRD");
|
||||
|
||||
private String name;
|
||||
|
||||
Angular(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public PdfName getPdfName() {
|
||||
return new PdfName(this.name);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,20 @@
|
|||
package com.itextpdf.text.pdf.spatial.units;
|
||||
|
||||
import com.itextpdf.text.pdf.PdfName;
|
||||
|
||||
public enum Fraction {
|
||||
DECIMAL("D"),
|
||||
FRACTION("F"),
|
||||
ROUND("R"),
|
||||
TRUNCATE("T");
|
||||
|
||||
private String name;
|
||||
|
||||
Fraction(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public PdfName getPdfName() {
|
||||
return new PdfName(this.name);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,22 @@
|
|||
package com.itextpdf.text.pdf.spatial.units;
|
||||
|
||||
import com.itextpdf.text.pdf.PdfName;
|
||||
|
||||
public enum Linear {
|
||||
METER("M"),
|
||||
KILOMETER("KM"),
|
||||
INTERNATIONAL_FOOT("FT"),
|
||||
US_SURVEY_FOOT("USFT"),
|
||||
INTERNATIONAL_MILE("MI"),
|
||||
INTERNATIONAL_NAUTICAL_MILE("NM");
|
||||
|
||||
private String name;
|
||||
|
||||
Linear(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public PdfName getPdfName() {
|
||||
return new PdfName(this.name);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,19 @@
|
|||
package com.itextpdf.text.pdf.spatial.units;
|
||||
|
||||
import com.itextpdf.text.pdf.PdfName;
|
||||
|
||||
public enum PtIdentifier {
|
||||
LATITUDE("LAT"),
|
||||
LONGITUDE("LON"),
|
||||
ALTITUDE("ALT");
|
||||
|
||||
private String name;
|
||||
|
||||
PtIdentifier(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public PdfName getPdfName() {
|
||||
return new PdfName(this.name);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,22 @@
|
|||
package com.itextpdf.text.pdf.spatial.units;
|
||||
|
||||
import com.itextpdf.text.pdf.PdfName;
|
||||
|
||||
public enum Square {
|
||||
SQUARE_METER("SQM"),
|
||||
HECTARE("HA"),
|
||||
SQUARE_KILOMETER("SQKM"),
|
||||
SQUARE_FOOT("SQFT"),
|
||||
ACRE("A"),
|
||||
SQUARE_MILE("SQMI");
|
||||
|
||||
private String name;
|
||||
|
||||
Square(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public PdfName getPdfName() {
|
||||
return new PdfName(this.name);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,66 @@
|
|||
package com.itextpdf.text.pdf.util;
|
||||
|
||||
import com.itextpdf.text.pdf.PRIndirectReference;
|
||||
import com.itextpdf.text.pdf.PdfArray;
|
||||
import com.itextpdf.text.pdf.PdfDictionary;
|
||||
import com.itextpdf.text.pdf.PdfName;
|
||||
import com.itextpdf.text.pdf.PdfObject;
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.util.HashMap;
|
||||
import java.util.Iterator;
|
||||
import java.util.Map;
|
||||
|
||||
public class PdfResourceCounter {
|
||||
protected Map<Integer, PdfObject> resources;
|
||||
|
||||
public PdfResourceCounter(PdfObject object) {
|
||||
this.resources = new HashMap<Integer, PdfObject>();
|
||||
process(object);
|
||||
}
|
||||
|
||||
protected final void process(PdfObject object) {
|
||||
PRIndirectReference ref = object.getIndRef();
|
||||
if (ref == null || this.resources.put(Integer.valueOf(ref.getNumber()), object) == null)
|
||||
loopOver(object);
|
||||
}
|
||||
|
||||
protected final void loopOver(PdfObject object) {
|
||||
PdfArray array;
|
||||
int i;
|
||||
PdfDictionary dict;
|
||||
switch (object.type()) {
|
||||
case 5:
|
||||
array = (PdfArray)object;
|
||||
for (i = 0; i < array.size(); i++)
|
||||
process(array.getDirectObject(i));
|
||||
break;
|
||||
case 6:
|
||||
case 7:
|
||||
dict = (PdfDictionary)object;
|
||||
if (dict.isPages())
|
||||
break;
|
||||
for (PdfName name : (Iterable<PdfName>)dict.getKeys())
|
||||
process(dict.getDirectObject(name));
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
public Map<Integer, PdfObject> getResources() {
|
||||
return this.resources;
|
||||
}
|
||||
|
||||
public long getLength(Map<Integer, PdfObject> res) throws IOException {
|
||||
long length = 0L;
|
||||
for (Iterator<Integer> iterator = this.resources.keySet().iterator(); iterator.hasNext(); ) {
|
||||
int ref = iterator.next();
|
||||
if (res != null && res.containsKey(Integer.valueOf(ref)))
|
||||
continue;
|
||||
ByteArrayOutputStream baos = new ByteArrayOutputStream();
|
||||
PdfObject object = this.resources.get(Integer.valueOf(ref));
|
||||
object.toPdf(null, baos);
|
||||
length += (long)baos.size();
|
||||
}
|
||||
return length;
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,81 @@
|
|||
package com.itextpdf.text.pdf.util;
|
||||
|
||||
import com.itextpdf.text.Document;
|
||||
import com.itextpdf.text.DocumentException;
|
||||
import com.itextpdf.text.log.Logger;
|
||||
import com.itextpdf.text.log.LoggerFactory;
|
||||
import com.itextpdf.text.pdf.PdfObject;
|
||||
import com.itextpdf.text.pdf.PdfReader;
|
||||
import com.itextpdf.text.pdf.PdfSmartCopy;
|
||||
import java.io.IOException;
|
||||
import java.io.OutputStream;
|
||||
import java.util.Map;
|
||||
|
||||
public class SmartPdfSplitter {
|
||||
private final Logger LOGGER = LoggerFactory.getLogger(SmartPdfSplitter.class);
|
||||
|
||||
protected PdfReader reader;
|
||||
|
||||
protected int numberOfPages = 0;
|
||||
|
||||
protected int currentPage = 1;
|
||||
|
||||
protected boolean overSized = false;
|
||||
|
||||
public SmartPdfSplitter(PdfReader reader) throws IOException {
|
||||
this.reader = reader;
|
||||
reader.setAppendable(true);
|
||||
this.numberOfPages = reader.getNumberOfPages();
|
||||
this.LOGGER.info(String.format("Creating a splitter for a document with %s pages", this.numberOfPages));
|
||||
}
|
||||
|
||||
public boolean hasMorePages() {
|
||||
return (this.currentPage <= this.numberOfPages);
|
||||
}
|
||||
|
||||
public boolean isOverSized() {
|
||||
return this.overSized;
|
||||
}
|
||||
|
||||
public boolean split(OutputStream os, long sizeInBytes) throws IOException, DocumentException {
|
||||
if (!hasMorePages()) {
|
||||
os.close();
|
||||
return false;
|
||||
}
|
||||
this.overSized = false;
|
||||
Document document = new Document();
|
||||
PdfSmartCopy pdfSmartCopy = new PdfSmartCopy(document, os);
|
||||
document.open();
|
||||
boolean hasPage = false;
|
||||
PdfResourceCounter counter = new PdfResourceCounter((PdfObject)this.reader.getTrailer());
|
||||
long trailer = counter.getLength(null);
|
||||
Map<Integer, PdfObject> resources = counter.getResources();
|
||||
long length = 0L;
|
||||
while (hasMorePages()) {
|
||||
counter = new PdfResourceCounter((PdfObject)this.reader.getPageN(this.currentPage));
|
||||
long page = counter.getLength(resources);
|
||||
resources = counter.getResources();
|
||||
length += page + trailer + xrefLength(resources.size());
|
||||
this.LOGGER.info(String.format("Page %s: Comparing %s with %s", this.currentPage, length, sizeInBytes));
|
||||
this.LOGGER.info(String.format(" page %s trailer %s xref %s", page, trailer, xrefLength(resources.size())));
|
||||
if (!hasPage || length < sizeInBytes) {
|
||||
hasPage = true;
|
||||
pdfSmartCopy.addPage(pdfSmartCopy.getImportedPage(this.reader, this.currentPage));
|
||||
length = pdfSmartCopy.getOs().getCounter();
|
||||
this.LOGGER.info(String.format("Size after adding page: %s", length));
|
||||
if (length > sizeInBytes)
|
||||
this.overSized = true;
|
||||
this.currentPage++;
|
||||
continue;
|
||||
}
|
||||
this.LOGGER.info("Page doesn't fit");
|
||||
break;
|
||||
}
|
||||
document.close();
|
||||
return true;
|
||||
}
|
||||
|
||||
private long xrefLength(int size) {
|
||||
return 20L * (long)(size + 1);
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue