first commit

This commit is contained in:
MaddoScientisto 2026-03-14 20:04:39 +01:00
commit 4d332ef662
27586 changed files with 3281783 additions and 0 deletions

View 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/>.

View file

@ -0,0 +1,33 @@
package com.itextpdf.text;
import java.io.Serializable;
public class AccessibleElementId implements Comparable<AccessibleElementId>, Serializable {
private static int id_counter = 0;
private int id = 0;
public AccessibleElementId() {
this.id = ++id_counter;
}
public String toString() {
return Integer.toString(this.id);
}
public int hashCode() {
return this.id;
}
public boolean equals(Object o) {
return (o instanceof AccessibleElementId && this.id == ((AccessibleElementId)o).id);
}
public int compareTo(AccessibleElementId elementId) {
if (this.id < elementId.id)
return -1;
if (this.id > elementId.id)
return 1;
return 0;
}
}

View file

@ -0,0 +1,138 @@
package com.itextpdf.text;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Iterator;
public class Anchor extends Phrase {
private static final long serialVersionUID = -852278536049236911L;
protected String name = null;
protected String reference = null;
public Anchor() {
super(16.0F);
}
public Anchor(float leading) {
super(leading);
}
public Anchor(Chunk chunk) {
super(chunk);
}
public Anchor(String string) {
super(string);
}
public Anchor(String string, Font font) {
super(string, font);
}
public Anchor(float leading, Chunk chunk) {
super(leading, chunk);
}
public Anchor(float leading, String string) {
super(leading, string);
}
public Anchor(float leading, String string, Font font) {
super(leading, string, font);
}
public Anchor(Phrase phrase) {
super(phrase);
if (phrase instanceof Anchor) {
Anchor a = (Anchor)phrase;
setName(a.name);
setReference(a.reference);
}
}
public boolean process(ElementListener listener) {
try {
Iterator<Chunk> i = getChunks().iterator();
boolean localDestination = (this.reference != null && this.reference.startsWith("#"));
boolean notGotoOK = true;
while (i.hasNext()) {
Chunk chunk = i.next();
if (this.name != null && notGotoOK && !chunk.isEmpty()) {
chunk.setLocalDestination(this.name);
notGotoOK = false;
}
if (localDestination)
chunk.setLocalGoto(this.reference.substring(1));
listener.add(chunk);
}
return true;
} catch (DocumentException de) {
return false;
}
}
public java.util.List<Chunk> getChunks() {
boolean localDestination = (this.reference != null && this.reference.startsWith("#"));
boolean notGotoOK = true;
java.util.List<Chunk> tmp = new ArrayList<Chunk>();
Iterator<Element> i = iterator();
while (i.hasNext()) {
Element element = i.next();
if (element instanceof Chunk) {
Chunk chunk = (Chunk)element;
notGotoOK = applyAnchor(chunk, notGotoOK, localDestination);
tmp.add(chunk);
continue;
}
for (Chunk c : element.getChunks()) {
notGotoOK = applyAnchor(c, notGotoOK, localDestination);
tmp.add(c);
}
}
return tmp;
}
protected boolean applyAnchor(Chunk chunk, boolean notGotoOK, boolean localDestination) {
if (this.name != null && notGotoOK && !chunk.isEmpty()) {
chunk.setLocalDestination(this.name);
notGotoOK = false;
}
if (localDestination) {
chunk.setLocalGoto(this.reference.substring(1));
} else if (this.reference != null) {
chunk.setAnchor(this.reference);
}
return notGotoOK;
}
public int type() {
return 17;
}
public void setName(String name) {
this.name = name;
}
public void setReference(String reference) {
this.reference = reference;
}
public String getName() {
return this.name;
}
public String getReference() {
return this.reference;
}
public URL getUrl() {
try {
return new URL(this.reference);
} catch (MalformedURLException mue) {
return null;
}
}
}

View file

@ -0,0 +1,238 @@
package com.itextpdf.text;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
public class Annotation implements Element {
public static final int TEXT = 0;
public static final int URL_NET = 1;
public static final int URL_AS_STRING = 2;
public static final int FILE_DEST = 3;
public static final int FILE_PAGE = 4;
public static final int NAMED_DEST = 5;
public static final int LAUNCH = 6;
public static final int SCREEN = 7;
public static final String TITLE = "title";
public static final String CONTENT = "content";
public static final String URL = "url";
public static final String FILE = "file";
public static final String DESTINATION = "destination";
public static final String PAGE = "page";
public static final String NAMED = "named";
public static final String APPLICATION = "application";
public static final String PARAMETERS = "parameters";
public static final String OPERATION = "operation";
public static final String DEFAULTDIR = "defaultdir";
public static final String LLX = "llx";
public static final String LLY = "lly";
public static final String URX = "urx";
public static final String URY = "ury";
public static final String MIMETYPE = "mime";
protected int annotationtype;
protected HashMap<String, Object> annotationAttributes = new HashMap<String, Object>();
protected float llx = Float.NaN;
protected float lly = Float.NaN;
protected float urx = Float.NaN;
protected float ury = Float.NaN;
private Annotation(float llx, float lly, float urx, float ury) {
this.llx = llx;
this.lly = lly;
this.urx = urx;
this.ury = ury;
}
public Annotation(Annotation an) {
this.annotationtype = an.annotationtype;
this.annotationAttributes = an.annotationAttributes;
this.llx = an.llx;
this.lly = an.lly;
this.urx = an.urx;
this.ury = an.ury;
}
public Annotation(String title, String text) {
this.annotationtype = 0;
this.annotationAttributes.put("title", title);
this.annotationAttributes.put("content", text);
}
public Annotation(String title, String text, float llx, float lly, float urx, float ury) {
this(llx, lly, urx, ury);
this.annotationtype = 0;
this.annotationAttributes.put("title", title);
this.annotationAttributes.put("content", text);
}
public Annotation(float llx, float lly, float urx, float ury, URL url) {
this(llx, lly, urx, ury);
this.annotationtype = 1;
this.annotationAttributes.put("url", url);
}
public Annotation(float llx, float lly, float urx, float ury, String url) {
this(llx, lly, urx, ury);
this.annotationtype = 2;
this.annotationAttributes.put("file", url);
}
public Annotation(float llx, float lly, float urx, float ury, String file, String dest) {
this(llx, lly, urx, ury);
this.annotationtype = 3;
this.annotationAttributes.put("file", file);
this.annotationAttributes.put("destination", dest);
}
public Annotation(float llx, float lly, float urx, float ury, String moviePath, String mimeType, boolean showOnDisplay) {
this(llx, lly, urx, ury);
this.annotationtype = 7;
this.annotationAttributes.put("file", moviePath);
this.annotationAttributes.put("mime", mimeType);
this.annotationAttributes.put("parameters", new boolean[] { false, showOnDisplay });
}
public Annotation(float llx, float lly, float urx, float ury, String file, int page) {
this(llx, lly, urx, ury);
this.annotationtype = 4;
this.annotationAttributes.put("file", file);
this.annotationAttributes.put("page", Integer.valueOf(page));
}
public Annotation(float llx, float lly, float urx, float ury, int named) {
this(llx, lly, urx, ury);
this.annotationtype = 5;
this.annotationAttributes.put("named", Integer.valueOf(named));
}
public Annotation(float llx, float lly, float urx, float ury, String application, String parameters, String operation, String defaultdir) {
this(llx, lly, urx, ury);
this.annotationtype = 6;
this.annotationAttributes.put("application", application);
this.annotationAttributes.put("parameters", parameters);
this.annotationAttributes.put("operation", operation);
this.annotationAttributes.put("defaultdir", defaultdir);
}
public int type() {
return 29;
}
public boolean process(ElementListener listener) {
try {
return listener.add(this);
} catch (DocumentException de) {
return false;
}
}
public java.util.List<Chunk> getChunks() {
return new ArrayList<Chunk>();
}
public void setDimensions(float llx, float lly, float urx, float ury) {
this.llx = llx;
this.lly = lly;
this.urx = urx;
this.ury = ury;
}
public float llx() {
return this.llx;
}
public float lly() {
return this.lly;
}
public float urx() {
return this.urx;
}
public float ury() {
return this.ury;
}
public float llx(float def) {
if (Float.isNaN(this.llx))
return def;
return this.llx;
}
public float lly(float def) {
if (Float.isNaN(this.lly))
return def;
return this.lly;
}
public float urx(float def) {
if (Float.isNaN(this.urx))
return def;
return this.urx;
}
public float ury(float def) {
if (Float.isNaN(this.ury))
return def;
return this.ury;
}
public int annotationType() {
return this.annotationtype;
}
public String title() {
String s = (String)this.annotationAttributes.get("title");
if (s == null)
s = "";
return s;
}
public String content() {
String s = (String)this.annotationAttributes.get("content");
if (s == null)
s = "";
return s;
}
public HashMap<String, Object> attributes() {
return this.annotationAttributes;
}
public boolean isContent() {
return true;
}
public boolean isNestable() {
return true;
}
}

View file

@ -0,0 +1,15 @@
package com.itextpdf.text;
public class BadElementException extends DocumentException {
private static final long serialVersionUID = -799006030723822254L;
public BadElementException(Exception ex) {
super(ex);
}
BadElementException() {}
public BadElementException(String message) {
super(message);
}
}

View file

@ -0,0 +1,124 @@
package com.itextpdf.text;
import com.itextpdf.text.error_messages.MessageLocalization;
public class BaseColor {
public static final BaseColor WHITE = new BaseColor(255, 255, 255);
public static final BaseColor LIGHT_GRAY = new BaseColor(192, 192, 192);
public static final BaseColor GRAY = new BaseColor(128, 128, 128);
public static final BaseColor DARK_GRAY = new BaseColor(64, 64, 64);
public static final BaseColor BLACK = new BaseColor(0, 0, 0);
public static final BaseColor RED = new BaseColor(255, 0, 0);
public static final BaseColor PINK = new BaseColor(255, 175, 175);
public static final BaseColor ORANGE = new BaseColor(255, 200, 0);
public static final BaseColor YELLOW = new BaseColor(255, 255, 0);
public static final BaseColor GREEN = new BaseColor(0, 255, 0);
public static final BaseColor MAGENTA = new BaseColor(255, 0, 255);
public static final BaseColor CYAN = new BaseColor(0, 255, 255);
public static final BaseColor BLUE = new BaseColor(0, 0, 255);
private static final double FACTOR = 0.7D;
private int value;
public BaseColor(int red, int green, int blue, int alpha) {
setValue(red, green, blue, alpha);
}
public BaseColor(int red, int green, int blue) {
this(red, green, blue, 255);
}
public BaseColor(float red, float green, float blue, float alpha) {
this((int)((double)(red * 255.0F) + 0.5D), (int)((double)(green * 255.0F) + 0.5D), (int)((double)(blue * 255.0F) + 0.5D), (int)((double)(alpha * 255.0F) + 0.5D));
}
public BaseColor(float red, float green, float blue) {
this(red, green, blue, 1.0F);
}
public BaseColor(int argb) {
this.value = argb;
}
public int getRGB() {
return this.value;
}
public int getRed() {
return getRGB() >> 16 & 0xFF;
}
public int getGreen() {
return getRGB() >> 8 & 0xFF;
}
public int getBlue() {
return getRGB() >> 0 & 0xFF;
}
public int getAlpha() {
return getRGB() >> 24 & 0xFF;
}
public BaseColor brighter() {
int r = getRed();
int g = getGreen();
int b = getBlue();
int i = 3;
if (r == 0 && g == 0 && b == 0)
return new BaseColor(i, i, i);
if (r > 0 && r < i)
r = i;
if (g > 0 && g < i)
g = i;
if (b > 0 && b < i)
b = i;
return new BaseColor(Math.min((int)((double)r / 0.7D), 255),
Math.min((int)((double)g / 0.7D), 255),
Math.min((int)((double)b / 0.7D), 255));
}
public BaseColor darker() {
return new BaseColor(Math.max((int)((double)getRed() * 0.7D), 0),
Math.max((int)((double)getGreen() * 0.7D), 0),
Math.max((int)((double)getBlue() * 0.7D), 0));
}
public boolean equals(Object obj) {
return (obj instanceof BaseColor && ((BaseColor)obj).value == this.value);
}
public int hashCode() {
return this.value;
}
protected void setValue(int red, int green, int blue, int alpha) {
validate(red);
validate(green);
validate(blue);
validate(alpha);
this.value = (alpha & 0xFF) << 24 | (red & 0xFF) << 16 | (green & 0xFF) << 8 | (blue & 0xFF) << 0;
}
private static void validate(int value) {
if (value < 0 || value > 255)
throw new IllegalArgumentException(MessageLocalization.getComposedMessage("color.value.outside.range.0.255", new Object[0]));
}
public String toString() {
return "Color value[" + Integer.toString(this.value, 16) + "]";
}
}

View file

@ -0,0 +1,33 @@
package com.itextpdf.text;
import java.util.ArrayList;
public class Chapter extends Section {
private static final long serialVersionUID = 1791000695779357361L;
public Chapter(int number) {
super(null, 1);
this.numbers = new ArrayList<Integer>();
this.numbers.add(Integer.valueOf(number));
this.triggerNewPage = true;
}
public Chapter(Paragraph title, int number) {
super(title, 1);
this.numbers = new ArrayList<Integer>();
this.numbers.add(Integer.valueOf(number));
this.triggerNewPage = true;
}
public Chapter(String title, int number) {
this(new Paragraph(title), number);
}
public int type() {
return 16;
}
public boolean isNestable() {
return false;
}
}

View file

@ -0,0 +1,38 @@
package com.itextpdf.text;
import com.itextpdf.text.error_messages.MessageLocalization;
public class ChapterAutoNumber extends Chapter {
private static final long serialVersionUID = -9217457637987854167L;
protected boolean numberSet = false;
public ChapterAutoNumber(Paragraph para) {
super(para, 0);
}
public ChapterAutoNumber(String title) {
super(title, 0);
}
public Section addSection(String title) {
if (isAddedCompletely())
throw new IllegalStateException(MessageLocalization.getComposedMessage("this.largeelement.has.already.been.added.to.the.document"));
return addSection(title, 2);
}
public Section addSection(Paragraph title) {
if (isAddedCompletely())
throw new IllegalStateException(MessageLocalization.getComposedMessage("this.largeelement.has.already.been.added.to.the.document"));
return addSection(title, 2);
}
public int setAutomaticNumber(int number) {
if (!this.numberSet) {
number++;
setChapterNumber(number);
this.numberSet = true;
}
return number;
}
}

View file

@ -0,0 +1,519 @@
package com.itextpdf.text;
import com.itextpdf.text.error_messages.MessageLocalization;
import com.itextpdf.text.pdf.HyphenationEvent;
import com.itextpdf.text.pdf.PdfAction;
import com.itextpdf.text.pdf.PdfAnnotation;
import com.itextpdf.text.pdf.PdfName;
import com.itextpdf.text.pdf.PdfObject;
import com.itextpdf.text.pdf.PdfString;
import com.itextpdf.text.pdf.draw.DrawInterface;
import com.itextpdf.text.pdf.interfaces.IAccessibleElement;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
public class Chunk implements Element, IAccessibleElement {
public static final String OBJECT_REPLACEMENT_CHARACTER = "";
public static final Chunk NEWLINE = new Chunk("\n");
static {
NEWLINE.setRole(PdfName.P);
}
public static final Chunk NEXTPAGE = new Chunk("");
static {
NEXTPAGE.setNewPage();
}
public static final Chunk TABBING = new Chunk(Float.NaN, false);
public static final Chunk SPACETABBING = new Chunk(Float.NaN, true);
protected StringBuffer content = null;
protected Font font = null;
protected HashMap<String, Object> attributes = null;
protected PdfName role = null;
protected HashMap<PdfName, PdfObject> accessibleAttributes = null;
private AccessibleElementId id = null;
public static final String SEPARATOR = "SEPARATOR";
public static final String TAB = "TAB";
public static final String TABSETTINGS = "TABSETTINGS";
public Chunk() {
this.content = new StringBuffer();
this.font = new Font();
this.role = PdfName.SPAN;
}
public Chunk(Chunk ck) {
if (ck.content != null)
this.content = new StringBuffer(ck.content.toString());
if (ck.font != null)
this.font = new Font(ck.font);
if (ck.attributes != null)
this.attributes = new HashMap<String, Object>(ck.attributes);
this.role = ck.role;
if (ck.accessibleAttributes != null)
this.accessibleAttributes = new HashMap<PdfName, PdfObject>(ck.accessibleAttributes);
this.id = ck.getId();
}
public Chunk(String content, Font font) {
this.content = new StringBuffer(content);
this.font = font;
this.role = PdfName.SPAN;
}
public Chunk(String content) {
this(content, new Font());
}
public Chunk(char c, Font font) {
this.content = new StringBuffer();
this.content.append(c);
this.font = font;
this.role = PdfName.SPAN;
}
public Chunk(char c) {
this(c, new Font());
}
public Chunk(Image image, float offsetX, float offsetY) {
this("", new Font());
Image copyImage = Image.getInstance(image);
copyImage.setAbsolutePosition(Float.NaN, Float.NaN);
setAttribute("IMAGE", new Object[] { copyImage, new Float(offsetX), new Float(offsetY), Boolean.FALSE });
this.role = null;
}
public Chunk(DrawInterface separator) {
this(separator, false);
}
public Chunk(DrawInterface separator, boolean vertical) {
this("", new Font());
setAttribute("SEPARATOR", new Object[] { separator, vertical });
this.role = null;
}
private String contentWithNoTabs = null;
public static final String HSCALE = "HSCALE";
public static final String UNDERLINE = "UNDERLINE";
public static final String SUBSUPSCRIPT = "SUBSUPSCRIPT";
public static final String SKEW = "SKEW";
public static final String BACKGROUND = "BACKGROUND";
public static final String TEXTRENDERMODE = "TEXTRENDERMODE";
public static final String SPLITCHARACTER = "SPLITCHARACTER";
public static final String HYPHENATION = "HYPHENATION";
public static final String REMOTEGOTO = "REMOTEGOTO";
public static final String LOCALGOTO = "LOCALGOTO";
public static final String LOCALDESTINATION = "LOCALDESTINATION";
public static final String GENERICTAG = "GENERICTAG";
public static final String LINEHEIGHT = "LINEHEIGHT";
public static final String IMAGE = "IMAGE";
public static final String ACTION = "ACTION";
public static final String NEWPAGE = "NEWPAGE";
public static final String PDFANNOTATION = "PDFANNOTATION";
public static final String COLOR = "COLOR";
public static final String ENCODING = "ENCODING";
public static final String CHAR_SPACING = "CHAR_SPACING";
public static final String WORD_SPACING = "WORD_SPACING";
public static final String WHITESPACE = "WHITESPACE";
@Deprecated
public Chunk(DrawInterface separator, float tabPosition) {
this(separator, tabPosition, false);
}
@Deprecated
public Chunk(DrawInterface separator, float tabPosition, boolean newline) {
this("", new Font());
if (tabPosition < 0.0F)
throw new IllegalArgumentException(MessageLocalization.getComposedMessage("a.tab.position.may.not.be.lower.than.0.yours.is.1", String.valueOf(tabPosition)));
setAttribute("TAB", new Object[] { separator, new Float(tabPosition), newline, new Float(0.0F) });
this.role = PdfName.ARTIFACT;
}
private Chunk(Float tabInterval, boolean isWhitespace) {
this("", new Font());
if (tabInterval < 0.0F)
throw new IllegalArgumentException(MessageLocalization.getComposedMessage("a.tab.position.may.not.be.lower.than.0.yours.is.1", String.valueOf(tabInterval)));
setAttribute("TAB", new Object[] { tabInterval, isWhitespace });
setAttribute("SPLITCHARACTER", TabSplitCharacter.TAB);
setAttribute("TABSETTINGS", null);
this.role = PdfName.ARTIFACT;
}
public Chunk(Image image, float offsetX, float offsetY, boolean changeLeading) {
this("", new Font());
setAttribute("IMAGE", new Object[] { image, new Float(offsetX), new Float(offsetY), changeLeading });
this.role = PdfName.ARTIFACT;
}
public boolean process(ElementListener listener) {
try {
return listener.add(this);
} catch (DocumentException de) {
return false;
}
}
public int type() {
return 10;
}
public java.util.List<Chunk> getChunks() {
java.util.List<Chunk> tmp = new ArrayList<Chunk>();
tmp.add(this);
return tmp;
}
public StringBuffer append(String string) {
this.contentWithNoTabs = null;
return this.content.append(string);
}
public void setFont(Font font) {
this.font = font;
}
public Font getFont() {
return this.font;
}
public String getContent() {
if (this.contentWithNoTabs == null)
this.contentWithNoTabs = this.content.toString().replaceAll("\t", "");
return this.contentWithNoTabs;
}
public String toString() {
return getContent();
}
public boolean isEmpty() {
return (this.content.toString().trim().length() == 0 &&
this.content.toString().indexOf("\n") == -1 && this.attributes == null);
}
public float getWidthPoint() {
if (getImage() != null)
return getImage().getScaledWidth();
return this.font.getCalculatedBaseFont(true).getWidthPoint(getContent(), this.font.getCalculatedSize()) * getHorizontalScaling();
}
public boolean hasAttributes() {
return (this.attributes != null && !this.attributes.isEmpty());
}
public boolean hasAccessibleAttributes() {
return (this.accessibleAttributes != null && !this.accessibleAttributes.isEmpty());
}
public HashMap<String, Object> getAttributes() {
return this.attributes;
}
public void setAttributes(HashMap<String, Object> attributes) {
this.attributes = attributes;
}
private Chunk setAttribute(String name, Object obj) {
if (this.attributes == null)
this.attributes = new HashMap<String, Object>();
this.attributes.put(name, obj);
return this;
}
public Chunk setHorizontalScaling(float scale) {
return setAttribute("HSCALE", new Float(scale));
}
public float getHorizontalScaling() {
if (this.attributes == null)
return 1.0F;
Float f = (Float)this.attributes.get("HSCALE");
if (f == null)
return 1.0F;
return f;
}
public Chunk setUnderline(float thickness, float yPosition) {
return setUnderline(null, thickness, 0.0F, yPosition, 0.0F, 0);
}
public Chunk setUnderline(BaseColor color, float thickness, float thicknessMul, float yPosition, float yPositionMul, int cap) {
if (this.attributes == null)
this.attributes = new HashMap<String, Object>();
Object[] obj = { color, new float[] { thickness, thicknessMul, yPosition, yPositionMul, (float)cap } };
Object[][] unders = Utilities.addToArray((Object[][])this.attributes.get("UNDERLINE"), obj);
return setAttribute("UNDERLINE", unders);
}
public Chunk setTextRise(float rise) {
return setAttribute("SUBSUPSCRIPT", new Float(rise));
}
public float getTextRise() {
if (this.attributes != null && this.attributes.containsKey("SUBSUPSCRIPT")) {
Float f = (Float)this.attributes.get("SUBSUPSCRIPT");
return f;
}
return 0.0F;
}
public Chunk setSkew(float alpha, float beta) {
alpha = (float)Math.tan((double)alpha * Math.PI / 180.0D);
beta = (float)Math.tan((double)beta * Math.PI / 180.0D);
return setAttribute("SKEW", new float[] { alpha, beta });
}
public Chunk setBackground(BaseColor color) {
return setBackground(color, 0.0F, 0.0F, 0.0F, 0.0F);
}
public Chunk setBackground(BaseColor color, float extraLeft, float extraBottom, float extraRight, float extraTop) {
return setAttribute("BACKGROUND", new Object[] { color, new float[] { extraLeft, extraBottom, extraRight, extraTop } });
}
public Chunk setTextRenderMode(int mode, float strokeWidth, BaseColor strokeColor) {
return setAttribute("TEXTRENDERMODE", new Object[] { mode, new Float(strokeWidth), strokeColor });
}
public Chunk setSplitCharacter(SplitCharacter splitCharacter) {
return setAttribute("SPLITCHARACTER", splitCharacter);
}
public Chunk setHyphenation(HyphenationEvent hyphenation) {
return setAttribute("HYPHENATION", hyphenation);
}
public Chunk setRemoteGoto(String filename, String name) {
return setAttribute("REMOTEGOTO", new Object[] { filename, name });
}
public Chunk setRemoteGoto(String filename, int page) {
return setAttribute("REMOTEGOTO", new Object[] { filename, page });
}
public Chunk setLocalGoto(String name) {
return setAttribute("LOCALGOTO", name);
}
public Chunk setLocalDestination(String name) {
return setAttribute("LOCALDESTINATION", name);
}
public Chunk setGenericTag(String text) {
return setAttribute("GENERICTAG", text);
}
public Chunk setLineHeight(float lineheight) {
return setAttribute("LINEHEIGHT", Float.valueOf(lineheight));
}
public Image getImage() {
if (this.attributes == null)
return null;
Object[] obj = (Object[])this.attributes.get("IMAGE");
if (obj == null)
return null;
return (Image)obj[0];
}
public Chunk setAction(PdfAction action) {
setRole(PdfName.LINK);
return setAttribute("ACTION", action);
}
public Chunk setAnchor(URL url) {
setRole(PdfName.LINK);
String urlStr = url.toExternalForm();
setAccessibleAttribute(PdfName.ALT, new PdfString(urlStr));
return setAttribute("ACTION", new PdfAction(urlStr));
}
public Chunk setAnchor(String url) {
setRole(PdfName.LINK);
setAccessibleAttribute(PdfName.ALT, new PdfString(url));
return setAttribute("ACTION", new PdfAction(url));
}
public Chunk setNewPage() {
return setAttribute("NEWPAGE", null);
}
public Chunk setAnnotation(PdfAnnotation annotation) {
return setAttribute("PDFANNOTATION", annotation);
}
public boolean isContent() {
return true;
}
public boolean isNestable() {
return true;
}
public HyphenationEvent getHyphenation() {
if (this.attributes == null)
return null;
return (HyphenationEvent)this.attributes.get("HYPHENATION");
}
public Chunk setCharacterSpacing(float charSpace) {
return setAttribute("CHAR_SPACING", new Float(charSpace));
}
public float getCharacterSpacing() {
if (this.attributes != null && this.attributes.containsKey("CHAR_SPACING")) {
Float f = (Float)this.attributes.get("CHAR_SPACING");
return f;
}
return 0.0F;
}
public Chunk setWordSpacing(float wordSpace) {
return setAttribute("WORD_SPACING", new Float(wordSpace));
}
public float getWordSpacing() {
if (this.attributes != null && this.attributes.containsKey("WORD_SPACING")) {
Float f = (Float)this.attributes.get("WORD_SPACING");
return f;
}
return 0.0F;
}
public static Chunk createWhitespace(String content) {
return createWhitespace(content, false);
}
public static Chunk createWhitespace(String content, boolean preserve) {
Chunk whitespace = null;
if (!preserve) {
whitespace = new Chunk(' ');
whitespace.setAttribute("WHITESPACE", content);
} else {
whitespace = new Chunk(content);
}
return whitespace;
}
public boolean isWhitespace() {
return (this.attributes != null && this.attributes.containsKey("WHITESPACE"));
}
@Deprecated
public static Chunk createTabspace() {
return createTabspace(60.0F);
}
@Deprecated
public static Chunk createTabspace(float spacing) {
Chunk tabspace = new Chunk(spacing, true);
return tabspace;
}
@Deprecated
public boolean isTabspace() {
return (this.attributes != null && this.attributes.containsKey("TAB"));
}
public PdfObject getAccessibleAttribute(PdfName key) {
if (getImage() != null)
return getImage().getAccessibleAttribute(key);
if (this.accessibleAttributes != null)
return this.accessibleAttributes.get(key);
return null;
}
public void setAccessibleAttribute(PdfName key, PdfObject value) {
if (getImage() != null) {
getImage().setAccessibleAttribute(key, value);
} else {
if (this.accessibleAttributes == null)
this.accessibleAttributes = new HashMap<PdfName, PdfObject>();
this.accessibleAttributes.put(key, value);
}
}
public HashMap<PdfName, PdfObject> getAccessibleAttributes() {
if (getImage() != null)
return getImage().getAccessibleAttributes();
return this.accessibleAttributes;
}
public PdfName getRole() {
if (getImage() != null)
return getImage().getRole();
return this.role;
}
public void setRole(PdfName role) {
if (getImage() != null) {
getImage().setRole(role);
} else {
this.role = role;
}
}
public AccessibleElementId getId() {
if (this.id == null)
this.id = new AccessibleElementId();
return this.id;
}
public void setId(AccessibleElementId id) {
this.id = id;
}
public boolean isInline() {
return true;
}
public String getTextExpansion() {
PdfObject o = getAccessibleAttribute(PdfName.E);
if (o instanceof PdfString)
return ((PdfString)o).toUnicodeString();
return null;
}
public void setTextExpansion(String value) {
setAccessibleAttribute(PdfName.E, new PdfString(value));
}
}

View file

@ -0,0 +1,21 @@
package com.itextpdf.text;
public interface DocListener extends ElementListener {
void open();
void close();
boolean newPage();
boolean setPageSize(Rectangle paramRectangle);
boolean setMargins(float paramFloat1, float paramFloat2, float paramFloat3, float paramFloat4);
boolean setMarginMirroring(boolean paramBoolean);
boolean setMarginMirroringTopBottom(boolean paramBoolean);
void setPageCount(int paramInt);
void resetPageCount();
}

View file

@ -0,0 +1,178 @@
package com.itextpdf.text;
import com.itextpdf.text.pdf.OutputStreamCounter;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Iterator;
import java.util.Properties;
public abstract class DocWriter implements DocListener {
public static final byte NEWLINE = 10;
public static final byte TAB = 9;
public static final byte LT = 60;
public static final byte SPACE = 32;
public static final byte EQUALS = 61;
public static final byte QUOTE = 34;
public static final byte GT = 62;
public static final byte FORWARD = 47;
protected Rectangle pageSize;
protected Document document;
protected OutputStreamCounter os;
protected boolean open = false;
protected boolean pause = false;
protected boolean closeStream = true;
protected DocWriter() {}
protected DocWriter(Document document, OutputStream os) {
this.document = document;
this.os = new OutputStreamCounter(new BufferedOutputStream(os));
}
public boolean add(Element element) throws DocumentException {
return false;
}
public void open() {
this.open = true;
}
public boolean setPageSize(Rectangle pageSize) {
this.pageSize = pageSize;
return true;
}
public boolean setMargins(float marginLeft, float marginRight, float marginTop, float marginBottom) {
return false;
}
public boolean newPage() {
if (!this.open)
return false;
return true;
}
public void resetPageCount() {}
public void setPageCount(int pageN) {}
public void close() {
this.open = false;
try {
this.os.flush();
if (this.closeStream)
this.os.close();
} catch (IOException ioe) {
throw new ExceptionConverter(ioe);
}
}
public static final byte[] getISOBytes(String text) {
if (text == null)
return null;
int len = text.length();
byte[] b = new byte[len];
for (int k = 0; k < len; k++)
b[k] = (byte)text.charAt(k);
return b;
}
public void pause() {
this.pause = true;
}
public boolean isPaused() {
return this.pause;
}
public void resume() {
this.pause = false;
}
public void flush() {
try {
this.os.flush();
} catch (IOException ioe) {
throw new ExceptionConverter(ioe);
}
}
protected void write(String string) throws IOException {
this.os.write(getISOBytes(string));
}
protected void addTabs(int indent) throws IOException {
this.os.write(10);
for (int i = 0; i < indent; i++)
this.os.write(9);
}
protected void write(String key, String value) throws IOException {
this.os.write(32);
write(key);
this.os.write(61);
this.os.write(34);
write(value);
this.os.write(34);
}
protected void writeStart(String tag) throws IOException {
this.os.write(60);
write(tag);
}
protected void writeEnd(String tag) throws IOException {
this.os.write(60);
this.os.write(47);
write(tag);
this.os.write(62);
}
protected void writeEnd() throws IOException {
this.os.write(32);
this.os.write(47);
this.os.write(62);
}
protected boolean writeMarkupAttributes(Properties markup) throws IOException {
if (markup == null)
return false;
Iterator<Object> attributeIterator = markup.keySet().iterator();
while (attributeIterator.hasNext()) {
String name = String.valueOf(attributeIterator.next());
write(name, markup.getProperty(name));
}
markup.clear();
return true;
}
public boolean isCloseStream() {
return this.closeStream;
}
public void setCloseStream(boolean closeStream) {
this.closeStream = closeStream;
}
public boolean setMarginMirroring(boolean MarginMirroring) {
return false;
}
public boolean setMarginMirroringTopBottom(boolean MarginMirroring) {
return false;
}
}

View file

@ -0,0 +1,375 @@
package com.itextpdf.text;
import com.itextpdf.text.error_messages.MessageLocalization;
import com.itextpdf.text.pdf.PdfName;
import com.itextpdf.text.pdf.PdfObject;
import com.itextpdf.text.pdf.interfaces.IAccessibleElement;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
public class Document implements DocListener, IAccessibleElement {
public static boolean compress = true;
public static boolean plainRandomAccess = false;
public static float wmfFontCorrection = 0.86F;
protected ArrayList<DocListener> listeners = new ArrayList<DocListener>();
protected boolean open;
protected boolean close;
protected Rectangle pageSize;
protected float marginLeft = 0.0F;
protected float marginRight = 0.0F;
protected float marginTop = 0.0F;
protected float marginBottom = 0.0F;
protected boolean marginMirroring = false;
protected boolean marginMirroringTopBottom = false;
protected String javaScript_onLoad = null;
protected String javaScript_onUnLoad = null;
protected String htmlStyleClass = null;
protected int pageN = 0;
protected int chapternumber = 0;
protected PdfName role = PdfName.DOCUMENT;
protected HashMap<PdfName, PdfObject> accessibleAttributes = null;
protected AccessibleElementId id = new AccessibleElementId();
public Document() {
this(PageSize.A4);
}
public Document(Rectangle pageSize) {
this(pageSize, 36.0F, 36.0F, 36.0F, 36.0F);
}
public Document(Rectangle pageSize, float marginLeft, float marginRight, float marginTop, float marginBottom) {
this.pageSize = pageSize;
this.marginLeft = marginLeft;
this.marginRight = marginRight;
this.marginTop = marginTop;
this.marginBottom = marginBottom;
}
public void addDocListener(DocListener listener) {
this.listeners.add(listener);
if (listener instanceof IAccessibleElement) {
IAccessibleElement ae = (IAccessibleElement)listener;
ae.setRole(this.role);
ae.setId(this.id);
if (this.accessibleAttributes != null)
for (PdfName key : this.accessibleAttributes.keySet())
ae.setAccessibleAttribute(key, this.accessibleAttributes.get(key));
}
}
public void removeDocListener(DocListener listener) {
this.listeners.remove(listener);
}
public boolean add(Element element) throws DocumentException {
if (this.close)
throw new DocumentException(MessageLocalization.getComposedMessage("the.document.has.been.closed.you.can.t.add.any.elements"));
if (!this.open && element.isContent())
throw new DocumentException(MessageLocalization.getComposedMessage("the.document.is.not.open.yet.you.can.only.add.meta.information"));
boolean success = false;
if (element instanceof ChapterAutoNumber)
this.chapternumber = ((ChapterAutoNumber)element).setAutomaticNumber(this.chapternumber);
for (DocListener listener : this.listeners)
success |= listener.add(element);
if (element instanceof LargeElement) {
LargeElement e = (LargeElement)element;
if (!e.isComplete())
e.flushContent();
}
return success;
}
public void open() {
if (!this.close)
this.open = true;
for (DocListener listener : this.listeners) {
listener.setPageSize(this.pageSize);
listener.setMargins(this.marginLeft, this.marginRight, this.marginTop, this.marginBottom);
listener.open();
}
}
public boolean setPageSize(Rectangle pageSize) {
this.pageSize = pageSize;
for (DocListener listener : this.listeners)
listener.setPageSize(pageSize);
return true;
}
public boolean setMargins(float marginLeft, float marginRight, float marginTop, float marginBottom) {
this.marginLeft = marginLeft;
this.marginRight = marginRight;
this.marginTop = marginTop;
this.marginBottom = marginBottom;
for (DocListener listener : this.listeners)
listener.setMargins(marginLeft, marginRight, marginTop, marginBottom);
return true;
}
public boolean newPage() {
if (!this.open || this.close)
return false;
for (DocListener listener : this.listeners)
listener.newPage();
return true;
}
public void resetPageCount() {
this.pageN = 0;
for (DocListener listener : this.listeners)
listener.resetPageCount();
}
public void setPageCount(int pageN) {
this.pageN = pageN;
for (DocListener listener : this.listeners)
listener.setPageCount(pageN);
}
public int getPageNumber() {
return this.pageN;
}
public void close() {
if (!this.close) {
this.open = false;
this.close = true;
}
for (DocListener listener : this.listeners)
listener.close();
}
public boolean addHeader(String name, String content) {
try {
return add(new Header(name, content));
} catch (DocumentException de) {
throw new ExceptionConverter(de);
}
}
public boolean addTitle(String title) {
try {
return add(new Meta(1, title));
} catch (DocumentException de) {
throw new ExceptionConverter(de);
}
}
public boolean addSubject(String subject) {
try {
return add(new Meta(2, subject));
} catch (DocumentException de) {
throw new ExceptionConverter(de);
}
}
public boolean addKeywords(String keywords) {
try {
return add(new Meta(3, keywords));
} catch (DocumentException de) {
throw new ExceptionConverter(de);
}
}
public boolean addAuthor(String author) {
try {
return add(new Meta(4, author));
} catch (DocumentException de) {
throw new ExceptionConverter(de);
}
}
public boolean addCreator(String creator) {
try {
return add(new Meta(7, creator));
} catch (DocumentException de) {
throw new ExceptionConverter(de);
}
}
public boolean addProducer() {
try {
return add(new Meta(5, Version.getInstance().getVersion()));
} catch (DocumentException de) {
throw new ExceptionConverter(de);
}
}
public boolean addLanguage(String language) {
try {
return add(new Meta(8, language));
} catch (DocumentException de) {
throw new ExceptionConverter(de);
}
}
public boolean addCreationDate() {
try {
SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy");
return add(new Meta(6, sdf.format(new Date())));
} catch (DocumentException de) {
throw new ExceptionConverter(de);
}
}
public float leftMargin() {
return this.marginLeft;
}
public float rightMargin() {
return this.marginRight;
}
public float topMargin() {
return this.marginTop;
}
public float bottomMargin() {
return this.marginBottom;
}
public float left() {
return this.pageSize.getLeft(this.marginLeft);
}
public float right() {
return this.pageSize.getRight(this.marginRight);
}
public float top() {
return this.pageSize.getTop(this.marginTop);
}
public float bottom() {
return this.pageSize.getBottom(this.marginBottom);
}
public float left(float margin) {
return this.pageSize.getLeft(this.marginLeft + margin);
}
public float right(float margin) {
return this.pageSize.getRight(this.marginRight + margin);
}
public float top(float margin) {
return this.pageSize.getTop(this.marginTop + margin);
}
public float bottom(float margin) {
return this.pageSize.getBottom(this.marginBottom + margin);
}
public Rectangle getPageSize() {
return this.pageSize;
}
public boolean isOpen() {
return this.open;
}
public void setJavaScript_onLoad(String code) {
this.javaScript_onLoad = code;
}
public String getJavaScript_onLoad() {
return this.javaScript_onLoad;
}
public void setJavaScript_onUnLoad(String code) {
this.javaScript_onUnLoad = code;
}
public String getJavaScript_onUnLoad() {
return this.javaScript_onUnLoad;
}
public void setHtmlStyleClass(String htmlStyleClass) {
this.htmlStyleClass = htmlStyleClass;
}
public String getHtmlStyleClass() {
return this.htmlStyleClass;
}
public boolean setMarginMirroring(boolean marginMirroring) {
this.marginMirroring = marginMirroring;
for (DocListener element : this.listeners) {
DocListener listener = element;
listener.setMarginMirroring(marginMirroring);
}
return true;
}
public boolean setMarginMirroringTopBottom(boolean marginMirroringTopBottom) {
this.marginMirroringTopBottom = marginMirroringTopBottom;
for (DocListener element : this.listeners) {
DocListener listener = element;
listener.setMarginMirroringTopBottom(marginMirroringTopBottom);
}
return true;
}
public boolean isMarginMirroring() {
return this.marginMirroring;
}
public PdfObject getAccessibleAttribute(PdfName key) {
if (this.accessibleAttributes != null)
return this.accessibleAttributes.get(key);
return null;
}
public void setAccessibleAttribute(PdfName key, PdfObject value) {
if (this.accessibleAttributes == null)
this.accessibleAttributes = new HashMap<PdfName, PdfObject>();
this.accessibleAttributes.put(key, value);
}
public HashMap<PdfName, PdfObject> getAccessibleAttributes() {
return this.accessibleAttributes;
}
public PdfName getRole() {
return this.role;
}
public void setRole(PdfName role) {
this.role = role;
}
public AccessibleElementId getId() {
return this.id;
}
public void setId(AccessibleElementId id) {
this.id = id;
}
public boolean isInline() {
return false;
}
}

View file

@ -0,0 +1,19 @@
package com.itextpdf.text;
public class DocumentException extends Exception {
private static final long serialVersionUID = -2191131489390840739L;
public DocumentException(Exception ex) {
super(ex);
}
public DocumentException() {}
public DocumentException(String message) {
super(message);
}
public DocumentException(String message, Exception ex) {
super(message, ex);
}
}

View file

@ -0,0 +1,109 @@
package com.itextpdf.text;
public interface Element {
public static final int HEADER = 0;
public static final int TITLE = 1;
public static final int SUBJECT = 2;
public static final int KEYWORDS = 3;
public static final int AUTHOR = 4;
public static final int PRODUCER = 5;
public static final int CREATIONDATE = 6;
public static final int CREATOR = 7;
public static final int LANGUAGE = 8;
public static final int CHUNK = 10;
public static final int PHRASE = 11;
public static final int PARAGRAPH = 12;
public static final int SECTION = 13;
public static final int LIST = 14;
public static final int LISTITEM = 15;
public static final int CHAPTER = 16;
public static final int ANCHOR = 17;
public static final int PTABLE = 23;
public static final int ANNOTATION = 29;
public static final int RECTANGLE = 30;
public static final int JPEG = 32;
public static final int JPEG2000 = 33;
public static final int IMGRAW = 34;
public static final int IMGTEMPLATE = 35;
public static final int JBIG2 = 36;
public static final int DIV = 37;
public static final int BODY = 38;
public static final int MARKED = 50;
public static final int YMARK = 55;
public static final int WRITABLE_DIRECT = 666;
public static final int ALIGN_UNDEFINED = -1;
public static final int ALIGN_LEFT = 0;
public static final int ALIGN_CENTER = 1;
public static final int ALIGN_RIGHT = 2;
public static final int ALIGN_JUSTIFIED = 3;
public static final int ALIGN_TOP = 4;
public static final int ALIGN_MIDDLE = 5;
public static final int ALIGN_BOTTOM = 6;
public static final int ALIGN_BASELINE = 7;
public static final int ALIGN_JUSTIFIED_ALL = 8;
public static final int CCITTG4 = 256;
public static final int CCITTG3_1D = 257;
public static final int CCITTG3_2D = 258;
public static final int CCITT_BLACKIS1 = 1;
public static final int CCITT_ENCODEDBYTEALIGN = 2;
public static final int CCITT_ENDOFLINE = 4;
public static final int CCITT_ENDOFBLOCK = 8;
boolean process(ElementListener paramElementListener);
int type();
boolean isContent();
boolean isNestable();
java.util.List<Chunk> getChunks();
String toString();
}

View file

@ -0,0 +1,7 @@
package com.itextpdf.text;
import java.util.EventListener;
public interface ElementListener extends EventListener {
boolean add(Element paramElement) throws DocumentException;
}

View file

@ -0,0 +1,62 @@
package com.itextpdf.text;
import java.io.PrintStream;
import java.io.PrintWriter;
public class ExceptionConverter extends RuntimeException {
private static final long serialVersionUID = 8657630363395849399L;
private Exception ex;
private String prefix;
public ExceptionConverter(Exception ex) {
super(ex);
this.ex = ex;
this.prefix = (ex instanceof RuntimeException) ? "" : "ExceptionConverter: ";
}
public static final RuntimeException convertException(Exception ex) {
if (ex instanceof RuntimeException)
return (RuntimeException)ex;
return new ExceptionConverter(ex);
}
public Exception getException() {
return this.ex;
}
public String getMessage() {
return this.ex.getMessage();
}
public String getLocalizedMessage() {
return this.ex.getLocalizedMessage();
}
public String toString() {
return this.prefix + this.ex;
}
public void printStackTrace() {
printStackTrace(System.err);
}
public void printStackTrace(PrintStream s) {
synchronized (s) {
s.print(this.prefix);
this.ex.printStackTrace(s);
}
}
public void printStackTrace(PrintWriter s) {
synchronized (s) {
s.print(this.prefix);
this.ex.printStackTrace(s);
}
}
public Throwable fillInStackTrace() {
return this;
}
}

View file

@ -0,0 +1,388 @@
package com.itextpdf.text;
import com.itextpdf.text.pdf.BaseFont;
public class Font implements Comparable<Font> {
public static final int NORMAL = 0;
public static final int BOLD = 1;
public static final int ITALIC = 2;
public static final int UNDERLINE = 4;
public static final int STRIKETHRU = 8;
public static final int BOLDITALIC = 3;
public static final int UNDEFINED = -1;
public static final int DEFAULTSIZE = 12;
public enum FontFamily {
COURIER, HELVETICA, TIMES_ROMAN, SYMBOL, ZAPFDINGBATS, UNDEFINED;
}
public enum FontStyle {
NORMAL("normal"),
BOLD("bold"),
ITALIC("italic"),
OBLIQUE("oblique"),
UNDERLINE("underline"),
LINETHROUGH("line-through");
private String code;
FontStyle(String code) {
this.code = code;
}
public String getValue() {
return this.code;
}
}
private FontFamily family = FontFamily.UNDEFINED;
private float size = -1.0F;
private int style = -1;
private BaseColor color = null;
private BaseFont baseFont = null;
public Font(Font other) {
this.family = other.family;
this.size = other.size;
this.style = other.style;
this.color = other.color;
this.baseFont = other.baseFont;
}
public Font(FontFamily family, float size, int style, BaseColor color) {
this.family = family;
this.size = size;
this.style = style;
this.color = color;
}
public Font(BaseFont bf, float size, int style, BaseColor color) {
this.baseFont = bf;
this.size = size;
this.style = style;
this.color = color;
}
public Font(BaseFont bf, float size, int style) {
this(bf, size, style, null);
}
public Font(BaseFont bf, float size) {
this(bf, size, -1, null);
}
public Font(BaseFont bf) {
this(bf, -1.0F, -1, null);
}
public Font(FontFamily family, float size, int style) {
this(family, size, style, null);
}
public Font(FontFamily family, float size) {
this(family, size, -1, null);
}
public Font(FontFamily family) {
this(family, -1.0F, -1, null);
}
public Font() {
this(FontFamily.UNDEFINED, -1.0F, -1, null);
}
public int compareTo(Font font) {
if (font == null)
return -1;
try {
if (this.baseFont != null && !this.baseFont.equals(font.getBaseFont()))
return -2;
if (this.family != font.getFamily())
return 1;
if (this.size != font.getSize())
return 2;
if (this.style != font.getStyle())
return 3;
if (this.color == null) {
if (font.color == null)
return 0;
return 4;
}
if (font.color == null)
return 4;
if (this.color.equals(font.getColor()))
return 0;
return 4;
} catch (ClassCastException cce) {
return -3;
}
}
public FontFamily getFamily() {
return this.family;
}
public String getFamilyname() {
String tmp = "unknown";
switch (getFamily()) {
case COURIER:
return "Courier";
case HELVETICA:
return "Helvetica";
case TIMES_ROMAN:
return "Times-Roman";
case SYMBOL:
return "Symbol";
case ZAPFDINGBATS:
return "ZapfDingbats";
}
if (this.baseFont != null) {
String[][] names = this.baseFont.getFamilyFontName();
for (String[] name : names) {
if ("0".equals(name[2]))
return name[3];
if ("1033".equals(name[2]))
tmp = name[3];
if ("".equals(name[2]))
tmp = name[3];
}
}
return tmp;
}
public void setFamily(String family) {
this.family = getFamily(family);
}
public static FontFamily getFamily(String family) {
if (family.equalsIgnoreCase("Courier"))
return FontFamily.COURIER;
if (family.equalsIgnoreCase("Helvetica"))
return FontFamily.HELVETICA;
if (family.equalsIgnoreCase("Times-Roman"))
return FontFamily.TIMES_ROMAN;
if (family.equalsIgnoreCase("Symbol"))
return FontFamily.SYMBOL;
if (family.equalsIgnoreCase("ZapfDingbats"))
return FontFamily.ZAPFDINGBATS;
return FontFamily.UNDEFINED;
}
public float getSize() {
return this.size;
}
public float getCalculatedSize() {
float s = this.size;
if (s == -1.0F)
s = 12.0F;
return s;
}
public float getCalculatedLeading(float multipliedLeading) {
return multipliedLeading * getCalculatedSize();
}
public void setSize(float size) {
this.size = size;
}
public int getStyle() {
return this.style;
}
public int getCalculatedStyle() {
int style = this.style;
if (style == -1)
style = 0;
if (this.baseFont != null)
return style;
if (this.family == FontFamily.SYMBOL || this.family == FontFamily.ZAPFDINGBATS)
return style;
return style & 0xFFFFFFFC;
}
public boolean isBold() {
if (this.style == -1)
return false;
return ((this.style & 0x1) == 1);
}
public boolean isItalic() {
if (this.style == -1)
return false;
return ((this.style & 0x2) == 2);
}
public boolean isUnderlined() {
if (this.style == -1)
return false;
return ((this.style & 0x4) == 4);
}
public boolean isStrikethru() {
if (this.style == -1)
return false;
return ((this.style & 0x8) == 8);
}
public void setStyle(int style) {
this.style = style;
}
public void setStyle(String style) {
if (this.style == -1)
this.style = 0;
this.style |= getStyleValue(style);
}
public static int getStyleValue(String style) {
int s = 0;
if (style.indexOf(FontStyle.NORMAL.getValue()) != -1)
s |= 0x0;
if (style.indexOf(FontStyle.BOLD.getValue()) != -1)
s |= 0x1;
if (style.indexOf(FontStyle.ITALIC.getValue()) != -1)
s |= 0x2;
if (style.indexOf(FontStyle.OBLIQUE.getValue()) != -1)
s |= 0x2;
if (style.indexOf(FontStyle.UNDERLINE.getValue()) != -1)
s |= 0x4;
if (style.indexOf(FontStyle.LINETHROUGH.getValue()) != -1)
s |= 0x8;
return s;
}
public BaseColor getColor() {
return this.color;
}
public void setColor(BaseColor color) {
this.color = color;
}
public void setColor(int red, int green, int blue) {
this.color = new BaseColor(red, green, blue);
}
public BaseFont getBaseFont() {
return this.baseFont;
}
public BaseFont getCalculatedBaseFont(boolean specialEncoding) {
if (this.baseFont != null)
return this.baseFont;
int style = this.style;
if (style == -1)
style = 0;
String fontName = "Helvetica";
String encoding = "Cp1252";
BaseFont cfont = null;
switch (this.family) {
case COURIER:
switch (style & 0x3) {
case 1:
fontName = "Courier-Bold";
break;
case 2:
fontName = "Courier-Oblique";
break;
case 3:
fontName = "Courier-BoldOblique";
break;
}
fontName = "Courier";
break;
case TIMES_ROMAN:
switch (style & 0x3) {
case 1:
fontName = "Times-Bold";
break;
case 2:
fontName = "Times-Italic";
break;
case 3:
fontName = "Times-BoldItalic";
break;
}
fontName = "Times-Roman";
break;
case SYMBOL:
fontName = "Symbol";
if (specialEncoding)
encoding = "Symbol";
break;
case ZAPFDINGBATS:
fontName = "ZapfDingbats";
if (specialEncoding)
encoding = "ZapfDingbats";
break;
default:
switch (style & 0x3) {
case 1:
fontName = "Helvetica-Bold";
break;
case 2:
fontName = "Helvetica-Oblique";
break;
case 3:
fontName = "Helvetica-BoldOblique";
break;
}
fontName = "Helvetica";
break;
}
try {
cfont = BaseFont.createFont(fontName, encoding, false);
} catch (Exception ee) {
throw new ExceptionConverter(ee);
}
return cfont;
}
public boolean isStandardFont() {
return (this.family == FontFamily.UNDEFINED && this.size == -1.0F && this.style == -1 && this.color == null && this.baseFont == null);
}
public Font difference(Font font) {
if (font == null)
return this;
float dSize = font.size;
if (dSize == -1.0F)
dSize = this.size;
int dStyle = -1;
int style1 = this.style;
int style2 = font.getStyle();
if (style1 != -1 || style2 != -1) {
if (style1 == -1)
style1 = 0;
if (style2 == -1)
style2 = 0;
dStyle = style1 | style2;
}
BaseColor dColor = font.color;
if (dColor == null)
dColor = this.color;
if (font.baseFont != null)
return new Font(font.baseFont, dSize, dStyle, dColor);
if (font.getFamily() != FontFamily.UNDEFINED)
return new Font(font.family, dSize, dStyle, dColor);
if (this.baseFont != null) {
if (dStyle == style1)
return new Font(this.baseFont, dSize, dStyle, dColor);
return FontFactory.getFont(getFamilyname(), dSize, dStyle, dColor);
}
return new Font(this.family, dSize, dStyle, dColor);
}
}

View file

@ -0,0 +1,148 @@
package com.itextpdf.text;
import com.itextpdf.text.error_messages.MessageLocalization;
import java.util.Set;
public final class FontFactory {
public static final String COURIER = "Courier";
public static final String COURIER_BOLD = "Courier-Bold";
public static final String COURIER_OBLIQUE = "Courier-Oblique";
public static final String COURIER_BOLDOBLIQUE = "Courier-BoldOblique";
public static final String HELVETICA = "Helvetica";
public static final String HELVETICA_BOLD = "Helvetica-Bold";
public static final String HELVETICA_OBLIQUE = "Helvetica-Oblique";
public static final String HELVETICA_BOLDOBLIQUE = "Helvetica-BoldOblique";
public static final String SYMBOL = "Symbol";
public static final String TIMES = "Times";
public static final String TIMES_ROMAN = "Times-Roman";
public static final String TIMES_BOLD = "Times-Bold";
public static final String TIMES_ITALIC = "Times-Italic";
public static final String TIMES_BOLDITALIC = "Times-BoldItalic";
public static final String ZAPFDINGBATS = "ZapfDingbats";
private static FontFactoryImp fontImp = new FontFactoryImp();
public static String defaultEncoding = "Cp1252";
public static boolean defaultEmbedding = false;
public static Font getFont(String fontname, String encoding, boolean embedded, float size, int style, BaseColor color) {
return fontImp.getFont(fontname, encoding, embedded, size, style, color);
}
public static Font getFont(String fontname, String encoding, boolean embedded, float size, int style, BaseColor color, boolean cached) {
return fontImp.getFont(fontname, encoding, embedded, size, style, color, cached);
}
public static Font getFont(String fontname, String encoding, boolean embedded, float size, int style) {
return getFont(fontname, encoding, embedded, size, style, null);
}
public static Font getFont(String fontname, String encoding, boolean embedded, float size) {
return getFont(fontname, encoding, embedded, size, -1, null);
}
public static Font getFont(String fontname, String encoding, boolean embedded) {
return getFont(fontname, encoding, embedded, -1.0F, -1, null);
}
public static Font getFont(String fontname, String encoding, float size, int style, BaseColor color) {
return getFont(fontname, encoding, defaultEmbedding, size, style, color);
}
public static Font getFont(String fontname, String encoding, float size, int style) {
return getFont(fontname, encoding, defaultEmbedding, size, style, null);
}
public static Font getFont(String fontname, String encoding, float size) {
return getFont(fontname, encoding, defaultEmbedding, size, -1, null);
}
public static Font getFont(String fontname, String encoding) {
return getFont(fontname, encoding, defaultEmbedding, -1.0F, -1, null);
}
public static Font getFont(String fontname, float size, int style, BaseColor color) {
return getFont(fontname, defaultEncoding, defaultEmbedding, size, style, color);
}
public static Font getFont(String fontname, float size, BaseColor color) {
return getFont(fontname, defaultEncoding, defaultEmbedding, size, -1, color);
}
public static Font getFont(String fontname, float size, int style) {
return getFont(fontname, defaultEncoding, defaultEmbedding, size, style, null);
}
public static Font getFont(String fontname, float size) {
return getFont(fontname, defaultEncoding, defaultEmbedding, size, -1, null);
}
public static Font getFont(String fontname) {
return getFont(fontname, defaultEncoding, defaultEmbedding, -1.0F, -1, null);
}
public static void registerFamily(String familyName, String fullName, String path) {
fontImp.registerFamily(familyName, fullName, path);
}
public static void register(String path) {
register(path, null);
}
public static void register(String path, String alias) {
fontImp.register(path, alias);
}
public static int registerDirectory(String dir) {
return fontImp.registerDirectory(dir);
}
public static int registerDirectory(String dir, boolean scanSubdirectories) {
return fontImp.registerDirectory(dir, scanSubdirectories);
}
public static int registerDirectories() {
return fontImp.registerDirectories();
}
public static Set<String> getRegisteredFonts() {
return fontImp.getRegisteredFonts();
}
public static Set<String> getRegisteredFamilies() {
return fontImp.getRegisteredFamilies();
}
public static boolean contains(String fontname) {
return fontImp.isRegistered(fontname);
}
public static boolean isRegistered(String fontname) {
return fontImp.isRegistered(fontname);
}
public static FontFactoryImp getFontImp() {
return fontImp;
}
public static void setFontImp(FontFactoryImp fontImp) {
if (fontImp == null)
throw new NullPointerException(MessageLocalization.getComposedMessage("fontfactoryimp.cannot.be.null", new Object[0]));
FontFactory.fontImp = fontImp;
}
}

View file

@ -0,0 +1,361 @@
package com.itextpdf.text;
import com.itextpdf.text.log.Level;
import com.itextpdf.text.log.Logger;
import com.itextpdf.text.log.LoggerFactory;
import com.itextpdf.text.pdf.BaseFont;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.Set;
public class FontFactoryImp implements FontProvider {
private static final Logger LOGGER = LoggerFactory.getLogger(FontFactoryImp.class);
private final Hashtable<String, String> trueTypeFonts = new Hashtable<String, String>();
private static String[] TTFamilyOrder = new String[] {
"3", "1", "1033", "3", "0", "1033", "1", "0", "0", "0",
"3", "0" };
private final Hashtable<String, ArrayList<String>> fontFamilies = new Hashtable<String, ArrayList<String>>();
public String defaultEncoding = "Cp1252";
public boolean defaultEmbedding = false;
public FontFactoryImp() {
this.trueTypeFonts.put("Courier".toLowerCase(), "Courier");
this.trueTypeFonts.put("Courier-Bold".toLowerCase(), "Courier-Bold");
this.trueTypeFonts.put("Courier-Oblique".toLowerCase(), "Courier-Oblique");
this.trueTypeFonts.put("Courier-BoldOblique".toLowerCase(), "Courier-BoldOblique");
this.trueTypeFonts.put("Helvetica".toLowerCase(), "Helvetica");
this.trueTypeFonts.put("Helvetica-Bold".toLowerCase(), "Helvetica-Bold");
this.trueTypeFonts.put("Helvetica-Oblique".toLowerCase(), "Helvetica-Oblique");
this.trueTypeFonts.put("Helvetica-BoldOblique".toLowerCase(), "Helvetica-BoldOblique");
this.trueTypeFonts.put("Symbol".toLowerCase(), "Symbol");
this.trueTypeFonts.put("Times-Roman".toLowerCase(), "Times-Roman");
this.trueTypeFonts.put("Times-Bold".toLowerCase(), "Times-Bold");
this.trueTypeFonts.put("Times-Italic".toLowerCase(), "Times-Italic");
this.trueTypeFonts.put("Times-BoldItalic".toLowerCase(), "Times-BoldItalic");
this.trueTypeFonts.put("ZapfDingbats".toLowerCase(), "ZapfDingbats");
ArrayList<String> tmp = new ArrayList<String>();
tmp.add("Courier");
tmp.add("Courier-Bold");
tmp.add("Courier-Oblique");
tmp.add("Courier-BoldOblique");
this.fontFamilies.put("Courier".toLowerCase(), tmp);
tmp = new ArrayList<String>();
tmp.add("Helvetica");
tmp.add("Helvetica-Bold");
tmp.add("Helvetica-Oblique");
tmp.add("Helvetica-BoldOblique");
this.fontFamilies.put("Helvetica".toLowerCase(), tmp);
tmp = new ArrayList<String>();
tmp.add("Symbol");
this.fontFamilies.put("Symbol".toLowerCase(), tmp);
tmp = new ArrayList<String>();
tmp.add("Times-Roman");
tmp.add("Times-Bold");
tmp.add("Times-Italic");
tmp.add("Times-BoldItalic");
this.fontFamilies.put("Times".toLowerCase(), tmp);
this.fontFamilies.put("Times-Roman".toLowerCase(), tmp);
tmp = new ArrayList<String>();
tmp.add("ZapfDingbats");
this.fontFamilies.put("ZapfDingbats".toLowerCase(), tmp);
}
public Font getFont(String fontname, String encoding, boolean embedded, float size, int style, BaseColor color) {
return getFont(fontname, encoding, embedded, size, style, color, true);
}
public Font getFont(String fontname, String encoding, boolean embedded, float size, int style, BaseColor color, boolean cached) {
if (fontname == null)
return new Font(Font.FontFamily.UNDEFINED, size, style, color);
String lowercasefontname = fontname.toLowerCase();
ArrayList<String> tmp = this.fontFamilies.get(lowercasefontname);
if (tmp != null)
synchronized (tmp) {
int s = (style == -1) ? 0 : style;
int fs = 0;
boolean found = false;
for (String f : tmp) {
String lcf = f.toLowerCase();
fs = 0;
if (lcf.indexOf("bold") != -1)
fs |= 0x1;
if (lcf.indexOf("italic") != -1 || lcf.indexOf("oblique") != -1)
fs |= 0x2;
if ((s & 0x3) == fs) {
fontname = f;
found = true;
break;
}
}
if (style != -1 && found)
style &= fs ^ 0xFFFFFFFF;
}
BaseFont basefont = null;
try {
basefont = getBaseFont(fontname, encoding, embedded, cached);
if (basefont == null)
return new Font(Font.FontFamily.UNDEFINED, size, style, color);
} catch (DocumentException de) {
throw new ExceptionConverter(de);
} catch (IOException ioe) {
return new Font(Font.FontFamily.UNDEFINED, size, style, color);
} catch (NullPointerException npe) {
return new Font(Font.FontFamily.UNDEFINED, size, style, color);
}
return new Font(basefont, size, style, color);
}
protected BaseFont getBaseFont(String fontname, String encoding, boolean embedded, boolean cached) throws IOException, DocumentException {
BaseFont basefont = null;
try {
basefont = BaseFont.createFont(fontname, encoding, embedded, cached, null, null, true);
} catch (DocumentException e) {}
if (basefont == null) {
fontname = this.trueTypeFonts.get(fontname.toLowerCase());
if (fontname != null)
basefont = BaseFont.createFont(fontname, encoding, embedded, cached, null, null);
}
return basefont;
}
public Font getFont(String fontname, String encoding, boolean embedded, float size, int style) {
return getFont(fontname, encoding, embedded, size, style, null);
}
public Font getFont(String fontname, String encoding, boolean embedded, float size) {
return getFont(fontname, encoding, embedded, size, -1, null);
}
public Font getFont(String fontname, String encoding, boolean embedded) {
return getFont(fontname, encoding, embedded, -1.0F, -1, null);
}
public Font getFont(String fontname, String encoding, float size, int style, BaseColor color) {
return getFont(fontname, encoding, this.defaultEmbedding, size, style, color);
}
public Font getFont(String fontname, String encoding, float size, int style) {
return getFont(fontname, encoding, this.defaultEmbedding, size, style, null);
}
public Font getFont(String fontname, String encoding, float size) {
return getFont(fontname, encoding, this.defaultEmbedding, size, -1, null);
}
public Font getFont(String fontname, float size, BaseColor color) {
return getFont(fontname, this.defaultEncoding, this.defaultEmbedding, size, -1, color);
}
public Font getFont(String fontname, String encoding) {
return getFont(fontname, encoding, this.defaultEmbedding, -1.0F, -1, null);
}
public Font getFont(String fontname, float size, int style, BaseColor color) {
return getFont(fontname, this.defaultEncoding, this.defaultEmbedding, size, style, color);
}
public Font getFont(String fontname, float size, int style) {
return getFont(fontname, this.defaultEncoding, this.defaultEmbedding, size, style, null);
}
public Font getFont(String fontname, float size) {
return getFont(fontname, this.defaultEncoding, this.defaultEmbedding, size, -1, null);
}
public Font getFont(String fontname) {
return getFont(fontname, this.defaultEncoding, this.defaultEmbedding, -1.0F, -1, null);
}
public void registerFamily(String familyName, String fullName, String path) {
ArrayList<String> tmp;
if (path != null)
this.trueTypeFonts.put(fullName, path);
synchronized (this.fontFamilies) {
tmp = this.fontFamilies.get(familyName);
if (tmp == null) {
tmp = new ArrayList<String>();
this.fontFamilies.put(familyName, tmp);
}
}
synchronized (tmp) {
if (!tmp.contains(fullName)) {
int fullNameLength = fullName.length();
boolean inserted = false;
for (int j = 0; j < tmp.size(); j++) {
if (tmp.get(j).length() >= fullNameLength) {
tmp.add(j, fullName);
inserted = true;
break;
}
}
if (!inserted) {
tmp.add(fullName);
String newFullName = fullName.toLowerCase();
if (newFullName.endsWith("regular")) {
newFullName = newFullName.substring(0, newFullName.length() - 7).trim();
tmp.add(0, fullName.substring(0, newFullName.length()));
}
}
}
}
}
public void register(String path) {
register(path, null);
}
public void register(String path, String alias) {
try {
if (path.toLowerCase().endsWith(".ttf") || path.toLowerCase().endsWith(".otf") || path.toLowerCase().indexOf(".ttc,") > 0) {
Object[] allNames = BaseFont.getAllFontNames(path, "Cp1252", null);
this.trueTypeFonts.put(((String)allNames[0]).toLowerCase(), path);
if (alias != null) {
String lcAlias = alias.toLowerCase();
this.trueTypeFonts.put(lcAlias, path);
if (lcAlias.endsWith("regular"))
saveCopyOfRegularFont(lcAlias, path);
}
String[][] names = (String[][])allNames[2];
for (String[] name : names) {
String lcName = name[3].toLowerCase();
this.trueTypeFonts.put(lcName, path);
if (lcName.endsWith("regular"))
saveCopyOfRegularFont(lcName, path);
}
String fullName = null;
String familyName = null;
names = (String[][])allNames[1];
for (int k = 0; k < TTFamilyOrder.length; k += 3) {
for (String[] name : names) {
if (TTFamilyOrder[k].equals(name[0]) && TTFamilyOrder[k + 1].equals(name[1]) && TTFamilyOrder[k + 2].equals(name[2])) {
familyName = name[3].toLowerCase();
k = TTFamilyOrder.length;
break;
}
}
}
if (familyName != null) {
String lastName = "";
names = (String[][])allNames[2];
for (String[] name : names) {
for (int i = 0; i < TTFamilyOrder.length; i += 3) {
if (TTFamilyOrder[i].equals(name[0]) && TTFamilyOrder[i + 1].equals(name[1]) && TTFamilyOrder[i + 2].equals(name[2])) {
fullName = name[3];
if (!fullName.equals(lastName)) {
lastName = fullName;
registerFamily(familyName, fullName, null);
break;
}
}
}
}
}
} else if (path.toLowerCase().endsWith(".ttc")) {
if (alias != null)
LOGGER.error("You can't define an alias for a true type collection.");
String[] names = BaseFont.enumerateTTCNames(path);
for (int i = 0; i < names.length; i++)
register(path + "," + i);
} else if (path.toLowerCase().endsWith(".afm") || path.toLowerCase().endsWith(".pfm")) {
BaseFont bf = BaseFont.createFont(path, "Cp1252", false);
String fullName = bf.getFullFontName()[0][3].toLowerCase();
String familyName = bf.getFamilyFontName()[0][3].toLowerCase();
String psName = bf.getPostscriptFontName().toLowerCase();
registerFamily(familyName, fullName, null);
this.trueTypeFonts.put(psName, path);
this.trueTypeFonts.put(fullName, path);
}
if (LOGGER.isLogging(Level.TRACE))
LOGGER.trace(String.format("Registered %s", path));
} catch (DocumentException de) {
throw new ExceptionConverter(de);
} catch (IOException ioe) {
throw new ExceptionConverter(ioe);
}
}
protected boolean saveCopyOfRegularFont(String regularFontName, String path) {
String alias = regularFontName.substring(0, regularFontName.length() - 7).trim();
if (!this.trueTypeFonts.containsKey(alias)) {
this.trueTypeFonts.put(alias, path);
return true;
}
return false;
}
public int registerDirectory(String dir) {
return registerDirectory(dir, false);
}
public int registerDirectory(String dir, boolean scanSubdirectories) {
if (LOGGER.isLogging(Level.DEBUG))
LOGGER.debug(String.format("Registering directory %s, looking for fonts", dir));
int count = 0;
try {
File file = new File(dir);
if (!file.exists() || !file.isDirectory())
return 0;
String[] files = file.list();
if (files == null)
return 0;
for (int k = 0; k < files.length; k++) {
try {
file = new File(dir, files[k]);
if (file.isDirectory()) {
if (scanSubdirectories)
count += registerDirectory(file.getAbsolutePath(), true);
} else {
String name = file.getPath();
String suffix = (name.length() < 4) ? null : name.substring(name.length() - 4).toLowerCase();
if (".afm".equals(suffix) || ".pfm".equals(suffix)) {
File pfb = new File(name.substring(0, name.length() - 4) + ".pfb");
if (pfb.exists()) {
register(name, null);
count++;
}
} else if (".ttf".equals(suffix) || ".otf".equals(suffix) || ".ttc".equals(suffix)) {
register(name, null);
count++;
}
}
} catch (Exception e) {}
}
} catch (Exception e) {}
return count;
}
public int registerDirectories() {
int count = 0;
String windir = System.getenv("windir");
String fileseparator = System.getProperty("file.separator");
if (windir != null && fileseparator != null)
count += registerDirectory(windir + fileseparator + "fonts");
count += registerDirectory("/usr/share/X11/fonts", true);
count += registerDirectory("/usr/X/lib/X11/fonts", true);
count += registerDirectory("/usr/openwin/lib/X11/fonts", true);
count += registerDirectory("/usr/share/fonts", true);
count += registerDirectory("/usr/X11R6/lib/X11/fonts", true);
count += registerDirectory("/Library/Fonts");
count += registerDirectory("/System/Library/Fonts");
return count;
}
public Set<String> getRegisteredFonts() {
return this.trueTypeFonts.keySet();
}
public Set<String> getRegisteredFamilies() {
return this.fontFamilies.keySet();
}
public boolean isRegistered(String fontname) {
return this.trueTypeFonts.containsKey(fontname.toLowerCase());
}
}

View file

@ -0,0 +1,7 @@
package com.itextpdf.text;
public interface FontProvider {
boolean isRegistered(String paramString);
Font getFont(String paramString1, String paramString2, boolean paramBoolean, float paramFloat, int paramInt, BaseColor paramBaseColor);
}

View file

@ -0,0 +1,52 @@
package com.itextpdf.text;
import com.itextpdf.text.factories.GreekAlphabetFactory;
public class GreekList extends List {
public GreekList() {
super(true);
setGreekFont();
}
public GreekList(int symbolIndent) {
super(true, (float)symbolIndent);
setGreekFont();
}
public GreekList(boolean greeklower, int symbolIndent) {
super(true, (float)symbolIndent);
this.lowercase = greeklower;
setGreekFont();
}
protected void setGreekFont() {
float fontsize = this.symbol.getFont().getSize();
this.symbol.setFont(FontFactory.getFont("Symbol", fontsize, 0));
}
public boolean add(Element o) {
if (o instanceof ListItem) {
ListItem item = (ListItem)o;
Chunk chunk = new Chunk(this.preSymbol, this.symbol.getFont());
chunk.setAttributes(this.symbol.getAttributes());
chunk.append(GreekAlphabetFactory.getString(this.first + this.list.size(), this.lowercase));
chunk.append(this.postSymbol);
item.setListSymbol(chunk);
item.setIndentationLeft(this.symbolIndent, this.autoindent);
item.setIndentationRight(0.0F);
this.list.add(item);
} else if (o instanceof List) {
List nested = (List)o;
nested.setIndentationLeft(nested.getIndentationLeft() + this.symbolIndent);
this.first--;
return this.list.add(nested);
}
return false;
}
public List cloneShallow() {
GreekList clone = new GreekList();
populateProperties(clone);
return clone;
}
}

View file

@ -0,0 +1,14 @@
package com.itextpdf.text;
public class Header extends Meta {
private StringBuffer name;
public Header(String name, String content) {
super(0, content);
this.name = new StringBuffer(name);
}
public String getName() {
return this.name.toString();
}
}

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,29 @@
package com.itextpdf.text;
import com.itextpdf.text.error_messages.MessageLocalization;
import com.itextpdf.text.pdf.codec.TIFFFaxDecoder;
import java.net.URL;
public class ImgCCITT extends Image {
ImgCCITT(Image image) {
super(image);
}
public ImgCCITT(int width, int height, boolean reverseBits, int typeCCITT, int parameters, byte[] data) throws BadElementException {
super((URL)null);
if (typeCCITT != 256 && typeCCITT != 257 && typeCCITT != 258)
throw new BadElementException(MessageLocalization.getComposedMessage("the.ccitt.compression.type.must.be.ccittg4.ccittg3.1d.or.ccittg3.2d", new Object[0]));
if (reverseBits)
TIFFFaxDecoder.reverseBits(data);
this.type = 34;
this.scaledHeight = (float)height;
setTop(this.scaledHeight);
this.scaledWidth = (float)width;
setRight(this.scaledWidth);
this.colorspace = parameters;
this.bpc = typeCCITT;
this.rawData = data;
this.plainWidth = getWidth();
this.plainHeight = getHeight();
}
}

View file

@ -0,0 +1,49 @@
package com.itextpdf.text;
import java.net.URL;
import java.security.MessageDigest;
public class ImgJBIG2 extends Image {
private byte[] global;
private byte[] globalHash;
ImgJBIG2(Image image) {
super(image);
}
public ImgJBIG2() {
super((Image)null);
}
public ImgJBIG2(int width, int height, byte[] data, byte[] globals) {
super((URL)null);
this.type = 36;
this.originalType = 9;
this.scaledHeight = (float)height;
setTop(this.scaledHeight);
this.scaledWidth = (float)width;
setRight(this.scaledWidth);
this.bpc = 1;
this.colorspace = 1;
this.rawData = data;
this.plainWidth = getWidth();
this.plainHeight = getHeight();
if (globals != null) {
this.global = globals;
try {
MessageDigest md = MessageDigest.getInstance("MD5");
md.update(this.global);
this.globalHash = md.digest();
} catch (Exception e) {}
}
}
public byte[] getGlobalBytes() {
return this.global;
}
public byte[] getGlobalHash() {
return this.globalHash;
}
}

View file

@ -0,0 +1,28 @@
package com.itextpdf.text;
import com.itextpdf.text.error_messages.MessageLocalization;
import java.net.URL;
public class ImgRaw extends Image {
ImgRaw(Image image) {
super(image);
}
public ImgRaw(int width, int height, int components, int bpc, byte[] data) throws BadElementException {
super((URL)null);
this.type = 34;
this.scaledHeight = (float)height;
setTop(this.scaledHeight);
this.scaledWidth = (float)width;
setRight(this.scaledWidth);
if (components != 1 && components != 3 && components != 4)
throw new BadElementException(MessageLocalization.getComposedMessage("components.must.be.1.3.or.4", new Object[0]));
if (bpc != 1 && bpc != 2 && bpc != 4 && bpc != 8)
throw new BadElementException(MessageLocalization.getComposedMessage("bits.per.component.must.be.1.2.4.or.8", new Object[0]));
this.colorspace = components;
this.bpc = bpc;
this.rawData = data;
this.plainWidth = getWidth();
this.plainHeight = getHeight();
}
}

View file

@ -0,0 +1,27 @@
package com.itextpdf.text;
import com.itextpdf.text.error_messages.MessageLocalization;
import com.itextpdf.text.pdf.PdfTemplate;
import java.net.URL;
public class ImgTemplate extends Image {
ImgTemplate(Image image) {
super(image);
}
public ImgTemplate(PdfTemplate template) throws BadElementException {
super((URL)null);
if (template == null)
throw new BadElementException(MessageLocalization.getComposedMessage("the.template.can.not.be.null"));
if (template.getType() == 3)
throw new BadElementException(MessageLocalization.getComposedMessage("a.pattern.can.not.be.used.as.a.template.to.create.an.image"));
this.type = 35;
this.scaledHeight = template.getHeight();
setTop(this.scaledHeight);
this.scaledWidth = template.getWidth();
setRight(this.scaledWidth);
setTemplateData(template);
this.plainWidth = getWidth();
this.plainHeight = getHeight();
}
}

View file

@ -0,0 +1,88 @@
package com.itextpdf.text;
import com.itextpdf.text.error_messages.MessageLocalization;
import com.itextpdf.text.pdf.PdfTemplate;
import com.itextpdf.text.pdf.codec.wmf.InputMeta;
import com.itextpdf.text.pdf.codec.wmf.MetaDo;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
public class ImgWMF extends Image {
ImgWMF(Image image) {
super(image);
}
public ImgWMF(URL url) throws BadElementException, IOException {
super(url);
processParameters();
}
public ImgWMF(String filename) throws BadElementException, MalformedURLException, IOException {
this(Utilities.toURL(filename));
}
public ImgWMF(byte[] img) throws BadElementException, IOException {
super((URL)null);
this.rawData = img;
this.originalData = img;
processParameters();
}
private void processParameters() throws BadElementException, IOException {
this.type = 35;
this.originalType = 6;
InputStream is = null;
try {
String errorID;
if (this.rawData == null) {
is = this.url.openStream();
errorID = this.url.toString();
} else {
is = new ByteArrayInputStream(this.rawData);
errorID = "Byte array";
}
InputMeta in = new InputMeta(is);
if (in.readInt() != -1698247209)
throw new BadElementException(MessageLocalization.getComposedMessage("1.is.not.a.valid.placeable.windows.metafile", new Object[] { errorID }));
in.readWord();
int left = in.readShort();
int top = in.readShort();
int right = in.readShort();
int bottom = in.readShort();
int inch = in.readWord();
this.dpiX = 72;
this.dpiY = 72;
this.scaledHeight = (float)(bottom - top) / (float)inch * 72.0F;
setTop(this.scaledHeight);
this.scaledWidth = (float)(right - left) / (float)inch * 72.0F;
setRight(this.scaledWidth);
} finally {
if (is != null)
is.close();
this.plainWidth = getWidth();
this.plainHeight = getHeight();
}
}
public void readWMF(PdfTemplate template) throws IOException, DocumentException {
setTemplateData(template);
template.setWidth(getWidth());
template.setHeight(getHeight());
InputStream is = null;
try {
if (this.rawData == null) {
is = this.url.openStream();
} else {
is = new ByteArrayInputStream(this.rawData);
}
MetaDo meta = new MetaDo(is, template);
meta.readAll();
} finally {
if (is != null)
is.close();
}
}
}

View file

@ -0,0 +1,275 @@
package com.itextpdf.text;
import com.itextpdf.text.error_messages.MessageLocalization;
import com.itextpdf.text.pdf.ICC_Profile;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
public class Jpeg extends Image {
public static final int NOT_A_MARKER = -1;
public static final int VALID_MARKER = 0;
public static final int[] VALID_MARKERS = new int[] { 192, 193, 194 };
public static final int UNSUPPORTED_MARKER = 1;
public static final int[] UNSUPPORTED_MARKERS = new int[] {
195, 197, 198, 199, 200, 201, 202, 203, 205, 206,
207 };
public static final int NOPARAM_MARKER = 2;
public static final int[] NOPARAM_MARKERS = new int[] { 208, 209, 210, 211, 212, 213, 214, 215, 216, 1 };
public static final int M_APP0 = 224;
public static final int M_APP2 = 226;
public static final int M_APPE = 238;
public static final int M_APPD = 237;
public static final byte[] JFIF_ID = new byte[] { 74, 70, 73, 70, 0 };
public static final byte[] PS_8BIM_RESO = new byte[] { 56, 66, 73, 77, 3, -19 };
private byte[][] icc;
Jpeg(Image image) {
super(image);
}
public Jpeg(URL url) throws BadElementException, IOException {
super(url);
processParameters();
}
public Jpeg(byte[] img) throws BadElementException, IOException {
super((URL)null);
this.rawData = img;
this.originalData = img;
processParameters();
}
public Jpeg(byte[] img, float width, float height) throws BadElementException, IOException {
this(img);
this.scaledWidth = width;
this.scaledHeight = height;
}
private static final int getShort(InputStream is) throws IOException {
return (is.read() << 8) + is.read();
}
private static final int marker(int marker) {
for (int k = 0; k < VALID_MARKERS.length; k++) {
if (marker == VALID_MARKERS[k])
return 0;
}
for (int j = 0; j < NOPARAM_MARKERS.length; j++) {
if (marker == NOPARAM_MARKERS[j])
return 2;
}
for (int i = 0; i < UNSUPPORTED_MARKERS.length; i++) {
if (marker == UNSUPPORTED_MARKERS[i])
return 1;
}
return -1;
}
private void processParameters() throws BadElementException, IOException {
this.type = 32;
this.originalType = 1;
InputStream is = null;
try {
String errorID;
if (this.rawData == null) {
is = this.url.openStream();
errorID = this.url.toString();
} else {
is = new ByteArrayInputStream(this.rawData);
errorID = "Byte array";
}
if (is.read() != 255 || is.read() != 216)
throw new BadElementException(MessageLocalization.getComposedMessage("1.is.not.a.valid.jpeg.file", errorID));
boolean firstPass = true;
while (true) {
int v = is.read();
if (v < 0)
throw new IOException(MessageLocalization.getComposedMessage("premature.eof.while.reading.jpg"));
if (v == 255) {
int marker = is.read();
if (firstPass && marker == 224) {
firstPass = false;
int len = getShort(is);
if (len < 16) {
Utilities.skip(is, len - 2);
continue;
}
byte[] bcomp = new byte[JFIF_ID.length];
int r = is.read(bcomp);
if (r != bcomp.length)
throw new BadElementException(MessageLocalization.getComposedMessage("1.corrupted.jfif.marker", errorID));
boolean found = true;
for (int k = 0; k < bcomp.length; k++) {
if (bcomp[k] != JFIF_ID[k]) {
found = false;
break;
}
}
if (!found) {
Utilities.skip(is, len - 2 - bcomp.length);
continue;
}
Utilities.skip(is, 2);
int units = is.read();
int dx = getShort(is);
int dy = getShort(is);
if (units == 1) {
this.dpiX = dx;
this.dpiY = dy;
} else if (units == 2) {
this.dpiX = (int)((float)dx * 2.54F + 0.5F);
this.dpiY = (int)((float)dy * 2.54F + 0.5F);
}
Utilities.skip(is, len - 2 - bcomp.length - 7);
continue;
}
if (marker == 238) {
int len = getShort(is) - 2;
byte[] byteappe = new byte[len];
for (int k = 0; k < len; k++)
byteappe[k] = (byte)is.read();
if (byteappe.length >= 12) {
String appe = new String(byteappe, 0, 5, "ISO-8859-1");
if (appe.equals("Adobe"))
this.invert = true;
}
continue;
}
if (marker == 226) {
int len = getShort(is) - 2;
byte[] byteapp2 = new byte[len];
for (int k = 0; k < len; k++)
byteapp2[k] = (byte)is.read();
if (byteapp2.length >= 14) {
String app2 = new String(byteapp2, 0, 11, "ISO-8859-1");
if (app2.equals("ICC_PROFILE")) {
int order = byteapp2[12] & 0xFF;
int count = byteapp2[13] & 0xFF;
if (order < 1)
order = 1;
if (count < 1)
count = 1;
if (this.icc == null)
this.icc = new byte[count][];
this.icc[order - 1] = byteapp2;
}
}
continue;
}
if (marker == 237) {
int len = getShort(is) - 2;
byte[] byteappd = new byte[len];
int k;
for (k = 0; k < len; k++)
byteappd[k] = (byte)is.read();
k = 0;
for (k = 0; k < len - PS_8BIM_RESO.length; k++) {
boolean found = true;
for (int j = 0; j < PS_8BIM_RESO.length; j++) {
if (byteappd[k + j] != PS_8BIM_RESO[j]) {
found = false;
break;
}
}
if (found)
break;
}
k += PS_8BIM_RESO.length;
if (k < len - PS_8BIM_RESO.length) {
byte namelength = byteappd[k];
namelength = (byte)(namelength + 1);
if (namelength % 2 == 1)
namelength = (byte)(namelength + 1);
k += namelength;
int resosize = (byteappd[k] << 24) + (byteappd[k + 1] << 16) + (byteappd[k + 2] << 8) + byteappd[k + 3];
if (resosize != 16)
continue;
k += 4;
int dx = (byteappd[k] << 8) + (byteappd[k + 1] & 0xFF);
k += 2;
k += 2;
int unitsx = (byteappd[k] << 8) + (byteappd[k + 1] & 0xFF);
k += 2;
k += 2;
int dy = (byteappd[k] << 8) + (byteappd[k + 1] & 0xFF);
k += 2;
k += 2;
int unitsy = (byteappd[k] << 8) + (byteappd[k + 1] & 0xFF);
if (unitsx == 1 || unitsx == 2) {
dx = (unitsx == 2) ? (int)((float)dx * 2.54F + 0.5F) : dx;
if (this.dpiX == 0 || this.dpiX == dx)
this.dpiX = dx;
}
if (unitsy == 1 || unitsy == 2) {
dy = (unitsy == 2) ? (int)((float)dy * 2.54F + 0.5F) : dy;
if (this.dpiY != 0 && this.dpiY != dy)
continue;
this.dpiY = dy;
}
}
continue;
}
firstPass = false;
int markertype = marker(marker);
if (markertype == 0) {
Utilities.skip(is, 2);
if (is.read() != 8)
throw new BadElementException(MessageLocalization.getComposedMessage("1.must.have.8.bits.per.component", errorID));
this.scaledHeight = (float)getShort(is);
setTop(this.scaledHeight);
this.scaledWidth = (float)getShort(is);
setRight(this.scaledWidth);
this.colorspace = is.read();
this.bpc = 8;
break;
}
if (markertype == 1)
throw new BadElementException(MessageLocalization.getComposedMessage("1.unsupported.jpeg.marker.2", errorID, String.valueOf(marker)));
if (markertype != 2)
Utilities.skip(is, getShort(is) - 2);
}
}
} finally {
if (is != null)
is.close();
}
this.plainWidth = getWidth();
this.plainHeight = getHeight();
if (this.icc != null) {
int total = 0;
for (int k = 0; k < this.icc.length; k++) {
if (this.icc[k] == null) {
this.icc = null;
return;
}
total += (this.icc[k]).length - 14;
}
byte[] ficc = new byte[total];
total = 0;
for (int i = 0; i < this.icc.length; i++) {
System.arraycopy(this.icc[i], 14, ficc, total, (this.icc[i]).length - 14);
total += (this.icc[i]).length - 14;
}
try {
ICC_Profile icc_prof = ICC_Profile.getInstance(ficc, this.colorspace);
tagICC(icc_prof);
} catch (IllegalArgumentException e) {}
this.icc = null;
}
}
}

View file

@ -0,0 +1,242 @@
package com.itextpdf.text;
import com.itextpdf.text.error_messages.MessageLocalization;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
public class Jpeg2000 extends Image {
public static final int JP2_JP = 1783636000;
public static final int JP2_IHDR = 1768449138;
public static final int JPIP_JPIP = 1785751920;
public static final int JP2_FTYP = 1718909296;
public static final int JP2_JP2H = 1785737832;
public static final int JP2_COLR = 1668246642;
public static final int JP2_JP2C = 1785737827;
public static final int JP2_URL = 1970433056;
public static final int JP2_DBTL = 1685348972;
public static final int JP2_BPCC = 1651532643;
public static final int JP2_JP2 = 1785737760;
InputStream inp;
int boxLength;
int boxType;
int numOfComps;
ArrayList<ColorSpecBox> colorSpecBoxes = null;
boolean isJp2 = false;
byte[] bpcBoxData;
Jpeg2000(Image image) {
super(image);
if (image instanceof Jpeg2000) {
Jpeg2000 jpeg2000 = (Jpeg2000)image;
this.numOfComps = jpeg2000.numOfComps;
if (this.colorSpecBoxes != null)
this.colorSpecBoxes = (ArrayList<ColorSpecBox>)jpeg2000.colorSpecBoxes.clone();
this.isJp2 = jpeg2000.isJp2;
if (this.bpcBoxData != null)
this.bpcBoxData = (byte[])jpeg2000.bpcBoxData.clone();
}
}
public Jpeg2000(URL url) throws BadElementException, IOException {
super(url);
processParameters();
}
public Jpeg2000(byte[] img) throws BadElementException, IOException {
super((URL)null);
this.rawData = img;
this.originalData = img;
processParameters();
}
public Jpeg2000(byte[] img, float width, float height) throws BadElementException, IOException {
this(img);
this.scaledWidth = width;
this.scaledHeight = height;
}
private int cio_read(int n) throws IOException {
int v = 0;
for (int i = n - 1; i >= 0; i--)
v += this.inp.read() << i << 3;
return v;
}
public void jp2_read_boxhdr() throws IOException {
this.boxLength = cio_read(4);
this.boxType = cio_read(4);
if (this.boxLength == 1) {
if (cio_read(4) != 0)
throw new IOException(MessageLocalization.getComposedMessage("cannot.handle.box.sizes.higher.than.2.32"));
this.boxLength = cio_read(4);
if (this.boxLength == 0)
throw new IOException(MessageLocalization.getComposedMessage("unsupported.box.size.eq.eq.0"));
} else if (this.boxLength == 0) {
throw new ZeroBoxSizeException(MessageLocalization.getComposedMessage("unsupported.box.size.eq.eq.0"));
}
}
private void processParameters() throws IOException {
assert false : "Decompilation failed at line #174 -> offsets [0]";
assert false : "Decompilation failed at line #175 -> offsets [6]";
assert false : "Decompilation failed at line #176 -> offsets [12]";
assert false : "Decompilation failed at line #178 -> offsets [17]";
assert false : "Decompilation failed at line #179 -> offsets [24]";
assert false : "Decompilation failed at line #182 -> offsets [38]";
assert false : "Decompilation failed at line #184 -> offsets [53]";
assert false : "Decompilation failed at line #185 -> offsets [62]";
assert false : "Decompilation failed at line #186 -> offsets [71]";
assert false : "Decompilation failed at line #187 -> offsets [76]";
assert false : "Decompilation failed at line #188 -> offsets [85]";
assert false : "Decompilation failed at line #189 -> offsets [94]";
assert false : "Decompilation failed at line #191 -> offsets [111]";
assert false : "Decompilation failed at line #192 -> offsets [121]";
assert false : "Decompilation failed at line #195 -> offsets [138]";
assert false : "Decompilation failed at line #196 -> offsets [142]";
assert false : "Decompilation failed at line #197 -> offsets [151]";
assert false : "Decompilation failed at line #199 -> offsets [168]";
assert false : "Decompilation failed at line #200 -> offsets [182]";
assert false : "Decompilation failed at line #202 -> offsets [186]";
assert false : "Decompilation failed at line #203 -> offsets [195]";
assert false : "Decompilation failed at line #204 -> offsets [204]";
assert false : "Decompilation failed at line #206 -> offsets [221]";
assert false : "Decompilation failed at line #207 -> offsets [235]";
assert false : "Decompilation failed at line #209 -> offsets [239]";
assert false : "Decompilation failed at line #210 -> offsets [248]";
assert false : "Decompilation failed at line #211 -> offsets [252]";
assert false : "Decompilation failed at line #212 -> offsets [261]";
assert false : "Decompilation failed at line #214 -> offsets [278]";
assert false : "Decompilation failed at line #215 -> offsets [288]";
assert false : "Decompilation failed at line #216 -> offsets [296]";
assert false : "Decompilation failed at line #217 -> offsets [306]";
assert false : "Decompilation failed at line #218 -> offsets [314]";
assert false : "Decompilation failed at line #219 -> offsets [323]";
assert false : "Decompilation failed at line #220 -> offsets [328]";
assert false : "Decompilation failed at line #222 -> offsets [337]";
assert false : "Decompilation failed at line #224 -> offsets [345]";
assert false : "Decompilation failed at line #225 -> offsets [349]";
assert false : "Decompilation failed at line #226 -> offsets [358]";
assert false : "Decompilation failed at line #227 -> offsets [371]";
assert false : "Decompilation failed at line #228 -> offsets [394]";
assert false : "Decompilation failed at line #230 -> offsets [403]";
assert false : "Decompilation failed at line #231 -> offsets [410]";
assert false : "Decompilation failed at line #232 -> offsets [421]";
assert false : "Decompilation failed at line #234 -> offsets [433]";
assert false : "Decompilation failed at line #235 -> offsets [440]";
assert false : "Decompilation failed at line #237 -> offsets [437]";
assert false : "Decompilation failed at line #238 -> offsets [441]";
assert false : "Decompilation failed at line #241 -> offsets [453]";
assert false : "Decompilation failed at line #242 -> offsets [462]";
assert false : "Decompilation failed at line #243 -> offsets [470]";
assert false : "Decompilation failed at line #244 -> offsets [476]";
assert false : "Decompilation failed at line #245 -> offsets [482]";
assert false : "Decompilation failed at line #246 -> offsets [488]";
assert false : "Decompilation failed at line #247 -> offsets [495]";
assert false : "Decompilation failed at line #248 -> offsets [504]";
assert false : "Decompilation failed at line #249 -> offsets [513]";
assert false : "Decompilation failed at line #250 -> offsets [519]";
assert false : "Decompilation failed at line #251 -> offsets [528]";
assert false : "Decompilation failed at line #252 -> offsets [536]";
assert false : "Decompilation failed at line #253 -> offsets [544]";
assert false : "Decompilation failed at line #254 -> offsets [552]";
assert false : "Decompilation failed at line #256 -> offsets [555]";
assert false : "Decompilation failed at line #260 -> offsets [572, 598]";
assert false : "Decompilation failed at line #261 -> offsets [579, 607]";
assert false : "Decompilation failed at line #262 -> offsets [590, 619]";
assert false : "Decompilation failed at line #265 -> offsets [627]";
assert false : "Decompilation failed at line #266 -> offsets [635]";
assert false : "Decompilation failed at line #267 -> offsets [643]";
}
private ColorSpecBox jp2_read_colr() throws IOException {
int readBytes = 8;
ColorSpecBox colr = new ColorSpecBox();
for (int i = 0; i < 3; i++) {
colr.add(Integer.valueOf(cio_read(1)));
readBytes++;
}
if (colr.getMeth() == 1) {
colr.add(Integer.valueOf(cio_read(4)));
readBytes += 4;
} else {
colr.add(Integer.valueOf(0));
}
if (this.boxLength - readBytes > 0) {
byte[] colorProfile = new byte[this.boxLength - readBytes];
this.inp.read(colorProfile, 0, this.boxLength - readBytes);
colr.setColorProfile(colorProfile);
}
return colr;
}
public int getNumOfComps() {
return this.numOfComps;
}
public byte[] getBpcBoxData() {
return this.bpcBoxData;
}
public ArrayList<ColorSpecBox> getColorSpecBoxes() {
return this.colorSpecBoxes;
}
public boolean isJp2() {
return this.isJp2;
}
public static class ColorSpecBox extends ArrayList<Integer> {
private byte[] colorProfile;
public int getMeth() {
return get(0);
}
public int getPrec() {
return get(1);
}
public int getApprox() {
return get(2);
}
public int getEnumCs() {
return get(3);
}
public byte[] getColorProfile() {
return this.colorProfile;
}
void setColorProfile(byte[] colorProfile) {
this.colorProfile = colorProfile;
}
}
private class ZeroBoxSizeException extends IOException {
public ZeroBoxSizeException() {}
public ZeroBoxSizeException(String s) {
super(s);
}
}
}

View file

@ -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 iText Group NV, iText Group NV 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

View file

@ -0,0 +1,9 @@
package com.itextpdf.text;
public interface LargeElement extends Element {
void setComplete(boolean paramBoolean);
boolean isComplete();
void flushContent();
}

View file

@ -0,0 +1,355 @@
package com.itextpdf.text;
import com.itextpdf.text.api.Indentable;
import com.itextpdf.text.factories.RomanAlphabetFactory;
import com.itextpdf.text.pdf.PdfName;
import com.itextpdf.text.pdf.PdfObject;
import com.itextpdf.text.pdf.interfaces.IAccessibleElement;
import java.util.ArrayList;
import java.util.HashMap;
public class List implements TextElementArray, Indentable, IAccessibleElement {
public static final boolean ORDERED = true;
public static final boolean UNORDERED = false;
public static final boolean NUMERICAL = false;
public static final boolean ALPHABETICAL = true;
public static final boolean UPPERCASE = false;
public static final boolean LOWERCASE = true;
protected ArrayList<Element> list = new ArrayList<Element>();
protected boolean numbered = false;
protected boolean lettered = false;
protected boolean lowercase = false;
protected boolean autoindent = false;
protected boolean alignindent = false;
protected int first = 1;
protected Chunk symbol = new Chunk("- ");
protected String preSymbol = "";
protected String postSymbol = ". ";
protected float indentationLeft = 0.0F;
protected float indentationRight = 0.0F;
protected float symbolIndent = 0.0F;
protected PdfName role = PdfName.L;
protected HashMap<PdfName, PdfObject> accessibleAttributes = null;
private AccessibleElementId id = null;
public List() {
this(false, false);
}
public List(float symbolIndent) {
this.symbolIndent = symbolIndent;
}
public List(boolean numbered) {
this(numbered, false);
}
public List(boolean numbered, boolean lettered) {
this.numbered = numbered;
this.lettered = lettered;
this.autoindent = true;
this.alignindent = true;
}
public List(boolean numbered, float symbolIndent) {
this(numbered, false, symbolIndent);
}
public List(boolean numbered, boolean lettered, float symbolIndent) {
this.numbered = numbered;
this.lettered = lettered;
this.symbolIndent = symbolIndent;
}
public boolean process(ElementListener listener) {
try {
for (Element element : this.list)
listener.add(element);
return true;
} catch (DocumentException de) {
return false;
}
}
public int type() {
return 14;
}
public java.util.List<Chunk> getChunks() {
java.util.List<Chunk> tmp = new ArrayList<Chunk>();
for (Element element : this.list)
tmp.addAll(element.getChunks());
return tmp;
}
public boolean add(String s) {
if (s != null)
return add(new ListItem(s));
return false;
}
public boolean add(Element o) {
if (o instanceof ListItem) {
ListItem item = (ListItem)o;
if (this.numbered || this.lettered) {
Chunk chunk = new Chunk(this.preSymbol, this.symbol.getFont());
chunk.setAttributes(this.symbol.getAttributes());
int index = this.first + this.list.size();
if (this.lettered) {
chunk.append(RomanAlphabetFactory.getString(index, this.lowercase));
} else {
chunk.append(String.valueOf(index));
}
chunk.append(this.postSymbol);
item.setListSymbol(chunk);
} else {
item.setListSymbol(this.symbol);
}
item.setIndentationLeft(this.symbolIndent, this.autoindent);
item.setIndentationRight(0.0F);
return this.list.add(item);
}
if (o instanceof List) {
List nested = (List)o;
nested.setIndentationLeft(nested.getIndentationLeft() + this.symbolIndent);
this.first--;
return this.list.add(nested);
}
return false;
}
public List cloneShallow() {
List clone = new List();
populateProperties(clone);
return clone;
}
protected void populateProperties(List clone) {
clone.indentationLeft = this.indentationLeft;
clone.indentationRight = this.indentationRight;
clone.autoindent = this.autoindent;
clone.alignindent = this.alignindent;
clone.symbolIndent = this.symbolIndent;
clone.symbol = this.symbol;
}
public void normalizeIndentation() {
float max = 0.0F;
for (Element o : this.list) {
if (o instanceof ListItem)
max = Math.max(max, ((ListItem)o).getIndentationLeft());
}
for (Element o : this.list) {
if (o instanceof ListItem)
((ListItem)o).setIndentationLeft(max);
}
}
public void setNumbered(boolean numbered) {
this.numbered = numbered;
}
public void setLettered(boolean lettered) {
this.lettered = lettered;
}
public void setLowercase(boolean uppercase) {
this.lowercase = uppercase;
}
public void setAutoindent(boolean autoindent) {
this.autoindent = autoindent;
}
public void setAlignindent(boolean alignindent) {
this.alignindent = alignindent;
}
public void setFirst(int first) {
this.first = first;
}
public void setListSymbol(Chunk symbol) {
this.symbol = symbol;
}
public void setListSymbol(String symbol) {
this.symbol = new Chunk(symbol);
}
public void setIndentationLeft(float indentation) {
this.indentationLeft = indentation;
}
public void setIndentationRight(float indentation) {
this.indentationRight = indentation;
}
public void setSymbolIndent(float symbolIndent) {
this.symbolIndent = symbolIndent;
}
public ArrayList<Element> getItems() {
return this.list;
}
public int size() {
return this.list.size();
}
public boolean isEmpty() {
return this.list.isEmpty();
}
public float getTotalLeading() {
if (this.list.size() < 1)
return -1.0F;
ListItem item = (ListItem)this.list.get(0);
return item.getTotalLeading();
}
public boolean isNumbered() {
return this.numbered;
}
public boolean isLettered() {
return this.lettered;
}
public boolean isLowercase() {
return this.lowercase;
}
public boolean isAutoindent() {
return this.autoindent;
}
public boolean isAlignindent() {
return this.alignindent;
}
public int getFirst() {
return this.first;
}
public Chunk getSymbol() {
return this.symbol;
}
public float getIndentationLeft() {
return this.indentationLeft;
}
public float getIndentationRight() {
return this.indentationRight;
}
public float getSymbolIndent() {
return this.symbolIndent;
}
public boolean isContent() {
return true;
}
public boolean isNestable() {
return true;
}
public String getPostSymbol() {
return this.postSymbol;
}
public void setPostSymbol(String postSymbol) {
this.postSymbol = postSymbol;
}
public String getPreSymbol() {
return this.preSymbol;
}
public void setPreSymbol(String preSymbol) {
this.preSymbol = preSymbol;
}
public ListItem getFirstItem() {
Element lastElement = (this.list.size() > 0) ? this.list.get(0) : null;
if (lastElement != null) {
if (lastElement instanceof ListItem)
return (ListItem)lastElement;
if (lastElement instanceof List)
return ((List)lastElement).getFirstItem();
}
return null;
}
public ListItem getLastItem() {
Element lastElement = (this.list.size() > 0) ? this.list.get(this.list.size() - 1) : null;
if (lastElement != null) {
if (lastElement instanceof ListItem)
return (ListItem)lastElement;
if (lastElement instanceof List)
return ((List)lastElement).getLastItem();
}
return null;
}
public PdfObject getAccessibleAttribute(PdfName key) {
if (this.accessibleAttributes != null)
return this.accessibleAttributes.get(key);
return null;
}
public void setAccessibleAttribute(PdfName key, PdfObject value) {
if (this.accessibleAttributes == null)
this.accessibleAttributes = new HashMap<PdfName, PdfObject>();
this.accessibleAttributes.put(key, value);
}
public HashMap<PdfName, PdfObject> getAccessibleAttributes() {
return this.accessibleAttributes;
}
public PdfName getRole() {
return this.role;
}
public void setRole(PdfName role) {
this.role = role;
}
public AccessibleElementId getId() {
if (this.id == null)
this.id = new AccessibleElementId();
return this.id;
}
public void setId(AccessibleElementId id) {
this.id = id;
}
public boolean isInline() {
return false;
}
}

View file

@ -0,0 +1,58 @@
package com.itextpdf.text;
import com.itextpdf.text.pdf.PdfName;
import com.itextpdf.text.pdf.PdfObject;
import com.itextpdf.text.pdf.interfaces.IAccessibleElement;
import java.util.HashMap;
public class ListBody implements IAccessibleElement {
protected PdfName role = PdfName.LBODY;
private AccessibleElementId id = null;
protected HashMap<PdfName, PdfObject> accessibleAttributes = null;
protected ListItem parentItem = null;
protected ListBody(ListItem parentItem) {
this.parentItem = parentItem;
}
public PdfObject getAccessibleAttribute(PdfName key) {
if (this.accessibleAttributes != null)
return this.accessibleAttributes.get(key);
return null;
}
public void setAccessibleAttribute(PdfName key, PdfObject value) {
if (this.accessibleAttributes == null)
this.accessibleAttributes = new HashMap<PdfName, PdfObject>();
this.accessibleAttributes.put(key, value);
}
public HashMap<PdfName, PdfObject> getAccessibleAttributes() {
return this.accessibleAttributes;
}
public PdfName getRole() {
return this.role;
}
public void setRole(PdfName role) {
this.role = role;
}
public AccessibleElementId getId() {
if (this.id == null)
this.id = new AccessibleElementId();
return this.id;
}
public void setId(AccessibleElementId id) {
this.id = id;
}
public boolean isInline() {
return false;
}
}

View file

@ -0,0 +1,105 @@
package com.itextpdf.text;
import com.itextpdf.text.pdf.PdfName;
public class ListItem extends Paragraph {
private static final long serialVersionUID = 1970670787169329006L;
protected Chunk symbol;
private ListBody listBody = null;
private ListLabel listLabel = null;
public ListItem() {
setRole(PdfName.LI);
}
public ListItem(float leading) {
super(leading);
setRole(PdfName.LI);
}
public ListItem(Chunk chunk) {
super(chunk);
setRole(PdfName.LI);
}
public ListItem(String string) {
super(string);
setRole(PdfName.LI);
}
public ListItem(String string, Font font) {
super(string, font);
setRole(PdfName.LI);
}
public ListItem(float leading, Chunk chunk) {
super(leading, chunk);
setRole(PdfName.LI);
}
public ListItem(float leading, String string) {
super(leading, string);
setRole(PdfName.LI);
}
public ListItem(float leading, String string, Font font) {
super(leading, string, font);
setRole(PdfName.LI);
}
public ListItem(Phrase phrase) {
super(phrase);
setRole(PdfName.LI);
}
public int type() {
return 15;
}
public Paragraph cloneShallow(boolean spacingBefore) {
ListItem copy = new ListItem();
populateProperties(copy, spacingBefore);
return copy;
}
public void setListSymbol(Chunk symbol) {
if (this.symbol == null) {
this.symbol = symbol;
if (this.symbol.getFont().isStandardFont())
this.symbol.setFont(this.font);
}
}
public void setIndentationLeft(float indentation, boolean autoindent) {
if (autoindent) {
setIndentationLeft(getListSymbol().getWidthPoint());
} else {
setIndentationLeft(indentation);
}
}
public void adjustListSymbolFont() {
java.util.List<Chunk> cks = getChunks();
if (!cks.isEmpty() && this.symbol != null)
this.symbol.setFont(cks.get(0).getFont());
}
public Chunk getListSymbol() {
return this.symbol;
}
public ListBody getListBody() {
if (this.listBody == null)
this.listBody = new ListBody(this);
return this.listBody;
}
public ListLabel getListLabel() {
if (this.listLabel == null)
this.listLabel = new ListLabel(this);
return this.listLabel;
}
}

View file

@ -0,0 +1,41 @@
package com.itextpdf.text;
import com.itextpdf.text.pdf.PdfName;
public class ListLabel extends ListBody {
protected PdfName role = PdfName.LBL;
protected float indentation = 0.0F;
protected ListLabel(ListItem parentItem) {
super(parentItem);
}
public PdfName getRole() {
return this.role;
}
public void setRole(PdfName role) {
this.role = role;
}
public float getIndentation() {
return this.indentation;
}
public void setIndentation(float indentation) {
this.indentation = indentation;
}
@Deprecated
public boolean getTagLabelContent() {
return false;
}
@Deprecated
public void setTagLabelContent(boolean tagLabelContent) {}
public boolean isInline() {
return true;
}
}

View file

@ -0,0 +1,50 @@
package com.itextpdf.text;
import java.util.Properties;
@Deprecated
public class MarkedObject implements Element {
protected Element element;
protected Properties markupAttributes = new Properties();
protected MarkedObject() {
this.element = null;
}
public MarkedObject(Element element) {
this.element = element;
}
public java.util.List<Chunk> getChunks() {
return this.element.getChunks();
}
public boolean process(ElementListener listener) {
try {
return listener.add(this.element);
} catch (DocumentException de) {
return false;
}
}
public int type() {
return 50;
}
public boolean isContent() {
return true;
}
public boolean isNestable() {
return true;
}
public Properties getMarkupAttributes() {
return this.markupAttributes;
}
public void setMarkupAttribute(String key, String value) {
this.markupAttributes.setProperty(key, value);
}
}

View file

@ -0,0 +1,114 @@
package com.itextpdf.text;
import com.itextpdf.text.api.Indentable;
import java.util.Collection;
@Deprecated
public class MarkedSection extends MarkedObject implements Indentable {
protected MarkedObject title = null;
public MarkedSection(Section section) {
if (section.title != null) {
this.title = new MarkedObject(section.title);
section.setTitle(null);
}
this.element = section;
}
public void add(int index, Element o) {
((Section)this.element).add(index, o);
}
public boolean add(Element o) {
return ((Section)this.element).add(o);
}
public boolean process(ElementListener listener) {
try {
for (Element element : (Iterable<Element>)this.element)
listener.add(element);
return true;
} catch (DocumentException de) {
return false;
}
}
public boolean addAll(Collection<? extends Element> collection) {
return ((Section)this.element).addAll(collection);
}
public MarkedSection addSection(float indentation, int numberDepth) {
MarkedSection section = ((Section)this.element).addMarkedSection();
section.setIndentation(indentation);
section.setNumberDepth(numberDepth);
return section;
}
public MarkedSection addSection(float indentation) {
MarkedSection section = ((Section)this.element).addMarkedSection();
section.setIndentation(indentation);
return section;
}
public MarkedSection addSection(int numberDepth) {
MarkedSection section = ((Section)this.element).addMarkedSection();
section.setNumberDepth(numberDepth);
return section;
}
public MarkedSection addSection() {
return ((Section)this.element).addMarkedSection();
}
public void setTitle(MarkedObject title) {
if (title.element instanceof Paragraph)
this.title = title;
}
public MarkedObject getTitle() {
Paragraph result = Section.constructTitle((Paragraph)this.title.element, ((Section)this.element).numbers, ((Section)this.element).numberDepth, ((Section)this.element).numberStyle);
MarkedObject mo = new MarkedObject(result);
mo.markupAttributes = this.title.markupAttributes;
return mo;
}
public void setNumberDepth(int numberDepth) {
((Section)this.element).setNumberDepth(numberDepth);
}
public void setIndentationLeft(float indentation) {
((Section)this.element).setIndentationLeft(indentation);
}
public void setIndentationRight(float indentation) {
((Section)this.element).setIndentationRight(indentation);
}
public void setIndentation(float indentation) {
((Section)this.element).setIndentation(indentation);
}
public void setBookmarkOpen(boolean bookmarkOpen) {
((Section)this.element).setBookmarkOpen(bookmarkOpen);
}
public void setTriggerNewPage(boolean triggerNewPage) {
((Section)this.element).setTriggerNewPage(triggerNewPage);
}
public void setBookmarkTitle(String bookmarkTitle) {
((Section)this.element).setBookmarkTitle(bookmarkTitle);
}
public void newPage() {
((Section)this.element).newPage();
}
public float getIndentationLeft() {
return ((Section)this.element).getIndentationLeft();
}
public float getIndentationRight() {
return ((Section)this.element).getIndentationRight();
}
}

View file

@ -0,0 +1,99 @@
package com.itextpdf.text;
import java.util.ArrayList;
public class Meta implements Element {
private final int type;
private final StringBuffer content;
public static final String UNKNOWN = "unknown";
public static final String PRODUCER = "producer";
public static final String CREATIONDATE = "creationdate";
public static final String AUTHOR = "author";
public static final String KEYWORDS = "keywords";
public static final String SUBJECT = "subject";
public static final String TITLE = "title";
Meta(int type, String content) {
this.type = type;
this.content = new StringBuffer(content);
}
public Meta(String tag, String content) {
this.type = getType(tag);
this.content = new StringBuffer(content);
}
public boolean process(ElementListener listener) {
try {
return listener.add(this);
} catch (DocumentException de) {
return false;
}
}
public int type() {
return this.type;
}
public java.util.List<Chunk> getChunks() {
return new ArrayList<Chunk>();
}
public boolean isContent() {
return false;
}
public boolean isNestable() {
return false;
}
public StringBuffer append(String string) {
return this.content.append(string);
}
public String getContent() {
return this.content.toString();
}
public String getName() {
switch (this.type) {
case 2:
return "subject";
case 3:
return "keywords";
case 4:
return "author";
case 1:
return "title";
case 5:
return "producer";
case 6:
return "creationdate";
}
return "unknown";
}
public static int getType(String tag) {
if ("subject".equals(tag))
return 2;
if ("keywords".equals(tag))
return 3;
if ("author".equals(tag))
return 4;
if ("title".equals(tag))
return 1;
if ("producer".equals(tag))
return 5;
if ("creationdate".equals(tag))
return 6;
return 0;
}
}

View file

@ -0,0 +1,454 @@
(1)
ExceptionConverter:
The original version of this class was published in an article by Heinz Kabutz.
Read http://www.javaspecialists.eu/archive/Issue033.html
"This material from The Java(tm) Specialists' Newsletter by Maximum Solutions
(South Africa). Please contact Maximum Solutions for more information.
Heinz Kabutz granted permission to use the example we've built on.
(2)
SimpleXMLParser:
The original version of this class was published in a JavaWorld article by Steven Brandt:
http://www.javaworld.com/javaworld/javatips/jw-javatip128.html
Jennifer Orr (JavaWorld) wrote: "You have permission to use the code appearing in
Steven Brandt's JavaWorld article, 'Java Tip 128: Create a quick-and-dirty XML parser.'
We ask that you reference the author as the creator and JavaWorld as the original publisher
of the code." Steven Brandt also agreed with the use of this class.
(3)
The following files contain material that was copyrighted by SUN:
com/itextpdf/text/pdf/LZWDecoder.java (first appearance in iText: 2002-02-08)
com/itextpdf/text/pdf/codec/BmpImage.java (first appearance in iText: 2003-06-20)
com/itextpdf/text/pdf/codec/PngImage.java (first appearance in iText: 2003-04-25)
com/itextpdf/text/pdf/codec/TIFFDirectory.java (first appearance in iText: 2003-04-09)
com/itextpdf/text/pdf/codec/TIFFFaxDecoder.java (first appearance in iText: 2003-04-09)
com/itextpdf/text/pdf/codec/TIFFField.java (first appearance in iText: 2003-04-09)
com/itextpdf/text/pdf/codec/TIFFLZWDecoder.java (first appearance in iText: 2003-04-09)
The original code was released under the BSD license, and contained the following
extra restriction: "You acknowledge that Software is not designed, licensed or intended
for use in the design, construction, operation or maintenance of any nuclear facility."
In a mail sent to Bruno Lowagie on January 23, 2008, Brian Burkhalter (@sun.com)
writes: "This code is under a BSD license and supersedes the older codec packages
on which your code is based. It also includes numerous fixes among them being the
ability to handle a lot of 'broken' TIFFs."
Note that numerous fixes were applied to the code used in iText by Paulo Soares,
but apart from the fixes there were no essential changes between the code that
was originally adapted and the code that is now available under the following
license:
Copyright (c) 2005 Sun Microsystems, Inc. All Rights Reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
- Redistribution of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
- Redistribution in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the
distribution.
Neither the name of Sun Microsystems, Inc. or the names of
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
This software is provided "AS IS," without a warranty of any
kind. ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND
WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY
EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN") AND ITS LICENSORS SHALL
NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF
USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR
ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL,
CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND
REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF THE USE OF OR
INABILITY TO USE THIS SOFTWARE, EVEN IF SUN HAS BEEN ADVISED OF THE
POSSIBILITY OF SUCH DAMAGES.
You acknowledge that this software is not designed or intended for
use in the design, construction, operation or maintenance of any
nuclear facility.
The main difference can be found in the final paragraph: the restriction
that the source code is not "licensed" in this particular situation has
been removed.
FYI: Brian also added: "A bit of history might be in order.
The codec classes that you used originally were based on some
classes included with JAI but not strictly part of JAI.
As of Java SE 1.4 an official Image I/O framework was
added in javax.imageio.... This frameork supports these formats:
Java 1.4: GIF (read only), JPEG, PNG
Java 1.5: Added support for BMP and WBMP
Java 1.6: Added support for writing GIF
The JAI Image I/O Tools packages (jai-imageio-core) were created
to support formats handled by JAI but not included in Java SE
as well as some new things like JPEG2000."
(4) the file com/itextpdf/text/pdf/codec/TIFFConstants
and some other TIFF related code is derived from LIBTIFF:
Copyright (c) 1988-1997 Sam Leffler
Copyright (c) 1991-1997 Silicon Graphics, Inc.
Permission to use, copy, modify, distribute, and sell this software and
its documentation for any purpose is hereby granted without fee, provided
that (i) the above copyright notices and this permission notice appear in
all copies of the software and related documentation, and (ii) the names of
Sam Leffler and Silicon Graphics may not be used in any advertising or
publicity relating to the software without the specific, prior written
permission of Sam Leffler and Silicon Graphics.
THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND,
EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY
WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.
IN NO EVENT SHALL SAM LEFFLER OR SILICON GRAPHICS BE LIABLE FOR
ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND,
OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF
LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
OF THIS SOFTWARE.
(5)
BidiOrder:
As stated in the Javadoc comments, materials from Unicode.org
are used in the class com/itextpdf/text/pdf/BidiOrder.java
The following license applies to these materials:
http://www.unicode.org/copyright.html#Exhibit1
EXHIBIT 1
UNICODE, INC. LICENSE AGREEMENT - DATA FILES AND SOFTWARE
Unicode Data Files include all data files under the directories
http://www.unicode.org/Public/, http://www.unicode.org/reports/,
and http://www.unicode.org/cldr/data/ .
Unicode Software includes any source code published in the Unicode Standard
or under the directories http://www.unicode.org/Public/, http://www.unicode.org/reports/,
and http://www.unicode.org/cldr/data/.
NOTICE TO USER: Carefully read the following legal agreement. BY DOWNLOADING,
INSTALLING, COPYING OR OTHERWISE USING UNICODE INC.'S DATA FILES ("DATA FILES"),
AND/OR SOFTWARE ("SOFTWARE"), YOU UNEQUIVOCALLY ACCEPT, AND AGREE TO BE BOUND BY,
ALL OF THE TERMS AND CONDITIONS OF THIS AGREEMENT. IF YOU DO NOT AGREE, DO NOT
DOWNLOAD, INSTALL, COPY, DISTRIBUTE OR USE THE DATA FILES OR SOFTWARE.
COPYRIGHT AND PERMISSION NOTICE
Copyright (C) 1991-2007 Unicode, Inc. All rights reserved. Distributed under
the Terms of Use in http://www.unicode.org/copyright.html.
Permission is hereby granted, free of charge, to any person obtaining a copy
of the Unicode data files and any associated documentation (the "Data Files")
or Unicode software and any associated documentation (the "Software") to deal
in the Data Files or Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, and/or sell copies
of the Data Files or Software, and to permit persons to whom the Data Files
or Software are furnished to do so, provided that (a) the above copyright
notice(s) and this permission notice appear with all copies of the Data Files
or Software, (b) both the above copyright notice(s) and this permission notice
appear in associated documentation, and (c) there is clear notice in each
modified Data File or in the Software as well as in the documentation associated
with the Data File(s) or Software that the data or software has been modified.
THE DATA FILES AND SOFTWARE ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS.
IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS INCLUDED IN THIS NOTICE BE
LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY
DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
CONNECTION WITH THE USE OR PERFORMANCE OF THE DATA FILES OR SOFTWARE.
Except as contained in this notice, the name of a copyright holder shall not
be used in advertising or otherwise to promote the sale, use or other dealings
in these Data Files or Software without prior written authorization of the
copyright holder.
(6) Contributions by Deutsche Bahn
Our customer Deutsche Bahn provided a patch regarding tables using an agreement
different from the custom Contributor License Agreement, but as liberal as an
MIT-style license agreement.
This contribution involves:
a. extra colspan functionality added to the following classes:
ColumnText, PdfPTable, and PdfPRow.
b. an extra table event: PdfPTableEventAfterSplit (also involving
PdfPTableEventForwarder).
(7) Adobe XMP library
In package com.itextpdf.xmp, we're using the Adobe XMP library.
This library was released under the following terms:
Copyright (c) 2006, Adobe Systems Incorporated
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. All advertising materials mentioning features or use of this software
must display the following acknowledgement:
This product includes software developed by the Adobe Systems Incorporated.
4. Neither the name of the Adobe Systems Incorporated nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY ADOBE SYSTEMS INCORPORATED ''AS IS'' AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL ADOBE SYSTEMS INCORPORATED BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
http://www.adobe.com/devnet/xmp/library/eula-xmp-library-java.html
(8)
Some files use code from different Apache projects.
The source code of these files contains the appropriate copyright notices
as described in the Appendix of http://www.apache.org/licenses/LICENSE-2.0
This is a copy of the text that can be found at that specific URL:
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License.
Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License.
Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution.
You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
* You must give any other recipients of the Work or
Derivative Works a copy of this License; and
* You must cause any modified files to carry prominent notices
stating that You changed the files; and
* You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
* If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions.
Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks.
This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty.
Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability.
In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability.
While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the &quot;License&quot;);
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an &quot;AS IS&quot; BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Extra information:
if you use the PdfCleanUp tool in the xtra package, you also need the
following Apache libraries:
- Apache Commons: commons-imaging
- Apache Commons: commons-io

View file

@ -0,0 +1,135 @@
package com.itextpdf.text;
import com.itextpdf.text.error_messages.MessageLocalization;
import java.lang.reflect.Field;
public class PageSize {
public static final Rectangle LETTER = new RectangleReadOnly(612.0F, 792.0F);
public static final Rectangle NOTE = new RectangleReadOnly(540.0F, 720.0F);
public static final Rectangle LEGAL = new RectangleReadOnly(612.0F, 1008.0F);
public static final Rectangle TABLOID = new RectangleReadOnly(792.0F, 1224.0F);
public static final Rectangle EXECUTIVE = new RectangleReadOnly(522.0F, 756.0F);
public static final Rectangle POSTCARD = new RectangleReadOnly(283.0F, 416.0F);
public static final Rectangle A0 = new RectangleReadOnly(2384.0F, 3370.0F);
public static final Rectangle A1 = new RectangleReadOnly(1684.0F, 2384.0F);
public static final Rectangle A2 = new RectangleReadOnly(1191.0F, 1684.0F);
public static final Rectangle A3 = new RectangleReadOnly(842.0F, 1191.0F);
public static final Rectangle A4 = new RectangleReadOnly(595.0F, 842.0F);
public static final Rectangle A5 = new RectangleReadOnly(420.0F, 595.0F);
public static final Rectangle A6 = new RectangleReadOnly(297.0F, 420.0F);
public static final Rectangle A7 = new RectangleReadOnly(210.0F, 297.0F);
public static final Rectangle A8 = new RectangleReadOnly(148.0F, 210.0F);
public static final Rectangle A9 = new RectangleReadOnly(105.0F, 148.0F);
public static final Rectangle A10 = new RectangleReadOnly(73.0F, 105.0F);
public static final Rectangle B0 = new RectangleReadOnly(2834.0F, 4008.0F);
public static final Rectangle B1 = new RectangleReadOnly(2004.0F, 2834.0F);
public static final Rectangle B2 = new RectangleReadOnly(1417.0F, 2004.0F);
public static final Rectangle B3 = new RectangleReadOnly(1000.0F, 1417.0F);
public static final Rectangle B4 = new RectangleReadOnly(708.0F, 1000.0F);
public static final Rectangle B5 = new RectangleReadOnly(498.0F, 708.0F);
public static final Rectangle B6 = new RectangleReadOnly(354.0F, 498.0F);
public static final Rectangle B7 = new RectangleReadOnly(249.0F, 354.0F);
public static final Rectangle B8 = new RectangleReadOnly(175.0F, 249.0F);
public static final Rectangle B9 = new RectangleReadOnly(124.0F, 175.0F);
public static final Rectangle B10 = new RectangleReadOnly(87.0F, 124.0F);
public static final Rectangle ARCH_E = new RectangleReadOnly(2592.0F, 3456.0F);
public static final Rectangle ARCH_D = new RectangleReadOnly(1728.0F, 2592.0F);
public static final Rectangle ARCH_C = new RectangleReadOnly(1296.0F, 1728.0F);
public static final Rectangle ARCH_B = new RectangleReadOnly(864.0F, 1296.0F);
public static final Rectangle ARCH_A = new RectangleReadOnly(648.0F, 864.0F);
public static final Rectangle FLSA = new RectangleReadOnly(612.0F, 936.0F);
public static final Rectangle FLSE = new RectangleReadOnly(648.0F, 936.0F);
public static final Rectangle HALFLETTER = new RectangleReadOnly(396.0F, 612.0F);
public static final Rectangle _11X17 = new RectangleReadOnly(792.0F, 1224.0F);
public static final Rectangle ID_1 = new RectangleReadOnly(242.65F, 153.0F);
public static final Rectangle ID_2 = new RectangleReadOnly(297.0F, 210.0F);
public static final Rectangle ID_3 = new RectangleReadOnly(354.0F, 249.0F);
public static final Rectangle LEDGER = new RectangleReadOnly(1224.0F, 792.0F);
public static final Rectangle CROWN_QUARTO = new RectangleReadOnly(535.0F, 697.0F);
public static final Rectangle LARGE_CROWN_QUARTO = new RectangleReadOnly(569.0F, 731.0F);
public static final Rectangle DEMY_QUARTO = new RectangleReadOnly(620.0F, 782.0F);
public static final Rectangle ROYAL_QUARTO = new RectangleReadOnly(671.0F, 884.0F);
public static final Rectangle CROWN_OCTAVO = new RectangleReadOnly(348.0F, 527.0F);
public static final Rectangle LARGE_CROWN_OCTAVO = new RectangleReadOnly(365.0F, 561.0F);
public static final Rectangle DEMY_OCTAVO = new RectangleReadOnly(391.0F, 612.0F);
public static final Rectangle ROYAL_OCTAVO = new RectangleReadOnly(442.0F, 663.0F);
public static final Rectangle SMALL_PAPERBACK = new RectangleReadOnly(314.0F, 504.0F);
public static final Rectangle PENGUIN_SMALL_PAPERBACK = new RectangleReadOnly(314.0F, 513.0F);
public static final Rectangle PENGUIN_LARGE_PAPERBACK = new RectangleReadOnly(365.0F, 561.0F);
public static final Rectangle LETTER_LANDSCAPE = new RectangleReadOnly(612.0F, 792.0F, 90);
public static final Rectangle LEGAL_LANDSCAPE = new RectangleReadOnly(612.0F, 1008.0F, 90);
public static final Rectangle A4_LANDSCAPE = new RectangleReadOnly(595.0F, 842.0F, 90);
public static Rectangle getRectangle(String name) {
name = name.trim().toUpperCase();
int pos = name.indexOf(' ');
if (pos == -1)
try {
Field field = PageSize.class.getDeclaredField(name.toUpperCase());
return (Rectangle)field.get(null);
} catch (Exception e) {
throw new RuntimeException(MessageLocalization.getComposedMessage("can.t.find.page.size.1", name));
}
try {
String width = name.substring(0, pos);
String height = name.substring(pos + 1);
return new Rectangle(Float.parseFloat(width), Float.parseFloat(height));
} catch (Exception e) {
throw new RuntimeException(MessageLocalization.getComposedMessage("1.is.not.a.valid.page.size.format.2", name, e.getMessage()));
}
}
}

View file

@ -0,0 +1,308 @@
package com.itextpdf.text;
import com.itextpdf.text.api.Indentable;
import com.itextpdf.text.api.Spaceable;
import com.itextpdf.text.pdf.PdfName;
import com.itextpdf.text.pdf.PdfObject;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.interfaces.IAccessibleElement;
import java.util.ArrayList;
import java.util.HashMap;
public class Paragraph extends Phrase implements Indentable, Spaceable, IAccessibleElement {
private static final long serialVersionUID = 7852314969733375514L;
protected int alignment = -1;
protected float indentationLeft;
protected float indentationRight;
private float firstLineIndent = 0.0F;
protected float spacingBefore;
protected float spacingAfter;
private float extraParagraphSpace = 0.0F;
protected boolean keeptogether = false;
protected float paddingTop;
protected PdfName role = PdfName.P;
protected HashMap<PdfName, PdfObject> accessibleAttributes = null;
protected AccessibleElementId id = null;
public Paragraph(float leading) {
super(leading);
}
public Paragraph(Chunk chunk) {
super(chunk);
}
public Paragraph(float leading, Chunk chunk) {
super(leading, chunk);
}
public Paragraph(String string) {
super(string);
}
public Paragraph(String string, Font font) {
super(string, font);
}
public Paragraph(float leading, String string) {
super(leading, string);
}
public Paragraph(float leading, String string, Font font) {
super(leading, string, font);
}
public Paragraph(Phrase phrase) {
super(phrase);
if (phrase instanceof Paragraph) {
Paragraph p = (Paragraph)phrase;
setAlignment(p.alignment);
setIndentationLeft(p.getIndentationLeft());
setIndentationRight(p.getIndentationRight());
setFirstLineIndent(p.getFirstLineIndent());
setSpacingAfter(p.getSpacingAfter());
setSpacingBefore(p.getSpacingBefore());
setExtraParagraphSpace(p.getExtraParagraphSpace());
setRole(p.role);
this.id = p.getId();
if (p.accessibleAttributes != null)
this.accessibleAttributes = new HashMap<PdfName, PdfObject>(p.accessibleAttributes);
}
}
public Paragraph cloneShallow(boolean spacingBefore) {
Paragraph copy = new Paragraph();
populateProperties(copy, spacingBefore);
return copy;
}
protected void populateProperties(Paragraph copy, boolean spacingBefore) {
copy.setFont(getFont());
copy.setAlignment(getAlignment());
copy.setLeading(getLeading(), this.multipliedLeading);
copy.setIndentationLeft(getIndentationLeft());
copy.setIndentationRight(getIndentationRight());
copy.setFirstLineIndent(getFirstLineIndent());
copy.setSpacingAfter(getSpacingAfter());
if (spacingBefore)
copy.setSpacingBefore(getSpacingBefore());
copy.setExtraParagraphSpace(getExtraParagraphSpace());
copy.setRole(this.role);
copy.id = getId();
if (this.accessibleAttributes != null)
copy.accessibleAttributes = new HashMap<PdfName, PdfObject>(this.accessibleAttributes);
copy.setTabSettings(getTabSettings());
copy.setKeepTogether(getKeepTogether());
}
public java.util.List<Element> breakUp() {
java.util.List<Element> list = new ArrayList<Element>();
Paragraph tmp = null;
for (Element e : (Iterable<Element>)this) {
if (e.type() == 14 || e.type() == 23 || e.type() == 12) {
if (tmp != null && tmp.size() > 0) {
tmp.setSpacingAfter(0.0F);
list.add(tmp);
tmp = cloneShallow(false);
}
if (list.size() == 0) {
ListItem firstItem;
switch (e.type()) {
case 23:
((PdfPTable)e).setSpacingBefore(getSpacingBefore());
break;
case 12:
((Paragraph)e).setSpacingBefore(getSpacingBefore());
break;
case 14:
firstItem = ((List)e).getFirstItem();
if (firstItem != null)
firstItem.setSpacingBefore(getSpacingBefore());
break;
}
}
list.add(e);
continue;
}
if (tmp == null)
tmp = cloneShallow((list.size() == 0));
tmp.add(e);
}
if (tmp != null && tmp.size() > 0)
list.add(tmp);
if (list.size() != 0) {
ListItem lastItem;
Element lastElement = list.get(list.size() - 1);
switch (lastElement.type()) {
case 23:
((PdfPTable)lastElement).setSpacingAfter(getSpacingAfter());
break;
case 12:
((Paragraph)lastElement).setSpacingAfter(getSpacingAfter());
break;
case 14:
lastItem = ((List)lastElement).getLastItem();
if (lastItem != null)
lastItem.setSpacingAfter(getSpacingAfter());
break;
}
}
return list;
}
public int type() {
return 12;
}
public boolean add(Element o) {
if (o instanceof List) {
List list = (List)o;
list.setIndentationLeft(list.getIndentationLeft() + this.indentationLeft);
list.setIndentationRight(this.indentationRight);
return super.add(list);
}
if (o instanceof Image) {
addSpecial(o);
return true;
}
if (o instanceof Paragraph) {
addSpecial(o);
return true;
}
return super.add(o);
}
public void setAlignment(int alignment) {
this.alignment = alignment;
}
public void setIndentationLeft(float indentation) {
this.indentationLeft = indentation;
}
public void setIndentationRight(float indentation) {
this.indentationRight = indentation;
}
public void setFirstLineIndent(float firstLineIndent) {
this.firstLineIndent = firstLineIndent;
}
public void setSpacingBefore(float spacing) {
this.spacingBefore = spacing;
}
public void setSpacingAfter(float spacing) {
this.spacingAfter = spacing;
}
public void setKeepTogether(boolean keeptogether) {
this.keeptogether = keeptogether;
}
public boolean getKeepTogether() {
return this.keeptogether;
}
public int getAlignment() {
return this.alignment;
}
public float getIndentationLeft() {
return this.indentationLeft;
}
public float getIndentationRight() {
return this.indentationRight;
}
public float getFirstLineIndent() {
return this.firstLineIndent;
}
public float getSpacingBefore() {
return this.spacingBefore;
}
public float getSpacingAfter() {
return this.spacingAfter;
}
public float getExtraParagraphSpace() {
return this.extraParagraphSpace;
}
public void setExtraParagraphSpace(float extraParagraphSpace) {
this.extraParagraphSpace = extraParagraphSpace;
}
@Deprecated
public float spacingBefore() {
return getSpacingBefore();
}
@Deprecated
public float spacingAfter() {
return this.spacingAfter;
}
public PdfObject getAccessibleAttribute(PdfName key) {
if (this.accessibleAttributes != null)
return this.accessibleAttributes.get(key);
return null;
}
public void setAccessibleAttribute(PdfName key, PdfObject value) {
if (this.accessibleAttributes == null)
this.accessibleAttributes = new HashMap<PdfName, PdfObject>();
this.accessibleAttributes.put(key, value);
}
public HashMap<PdfName, PdfObject> getAccessibleAttributes() {
return this.accessibleAttributes;
}
public PdfName getRole() {
return this.role;
}
public void setRole(PdfName role) {
this.role = role;
}
public AccessibleElementId getId() {
if (this.id == null)
this.id = new AccessibleElementId();
return this.id;
}
public void setId(AccessibleElementId id) {
this.id = id;
}
public boolean isInline() {
return false;
}
public float getPaddingTop() {
return this.paddingTop;
}
public void setPaddingTop(float paddingTop) {
this.paddingTop = paddingTop;
}
public Paragraph() {}
}

View file

@ -0,0 +1,358 @@
package com.itextpdf.text;
import com.itextpdf.text.error_messages.MessageLocalization;
import com.itextpdf.text.pdf.HyphenationEvent;
import com.itextpdf.text.pdf.PdfName;
import java.util.ArrayList;
import java.util.Collection;
public class Phrase extends ArrayList<Element> implements TextElementArray {
private static final long serialVersionUID = 2643594602455068231L;
protected float leading = Float.NaN;
protected float multipliedLeading = 0.0F;
protected Font font;
protected HyphenationEvent hyphenation = null;
protected TabSettings tabSettings = null;
public Phrase() {
this(16.0F);
}
public Phrase(Phrase phrase) {
addAll(phrase);
setLeading(phrase.getLeading(), phrase.getMultipliedLeading());
this.font = phrase.getFont();
this.tabSettings = phrase.getTabSettings();
setHyphenation(phrase.getHyphenation());
}
public Phrase(float leading) {
this.leading = leading;
this.font = new Font();
}
public Phrase(Chunk chunk) {
super.add(chunk);
this.font = chunk.getFont();
setHyphenation(chunk.getHyphenation());
}
public Phrase(float leading, Chunk chunk) {
this.leading = leading;
super.add(chunk);
this.font = chunk.getFont();
setHyphenation(chunk.getHyphenation());
}
public Phrase(String string) {
this(Float.NaN, string, new Font());
}
public Phrase(String string, Font font) {
this(Float.NaN, string, font);
}
public Phrase(float leading, String string) {
this(leading, string, new Font());
}
public Phrase(float leading, String string, Font font) {
this.leading = leading;
this.font = font;
if (string != null && string.length() != 0)
super.add(new Chunk(string, font));
}
public boolean process(ElementListener listener) {
try {
for (Object element : (Iterable<Object>)this)
listener.add((Element)element);
return true;
} catch (DocumentException de) {
return false;
}
}
public int type() {
return 11;
}
public java.util.List<Chunk> getChunks() {
java.util.List<Chunk> tmp = new ArrayList<Chunk>();
for (Element element : (Iterable<Element>)this)
tmp.addAll(element.getChunks());
return tmp;
}
public boolean isContent() {
return true;
}
public boolean isNestable() {
return true;
}
public void add(int index, Element element) {
Chunk chunk;
if (element == null)
return;
switch (element.type()) {
case 10:
chunk = (Chunk)element;
if (!this.font.isStandardFont())
chunk.setFont(this.font.difference(chunk.getFont()));
if (this.hyphenation != null && chunk.getHyphenation() == null && !chunk.isEmpty())
chunk.setHyphenation(this.hyphenation);
super.add(index, chunk);
return;
case 11:
case 12:
case 14:
case 17:
case 23:
case 29:
case 37:
case 50:
case 55:
case 666:
super.add(index, element);
return;
}
throw new ClassCastException(MessageLocalization.getComposedMessage("insertion.of.illegal.element.1", element.getClass().getName()));
}
public boolean add(String s) {
if (s == null)
return false;
return super.add(new Chunk(s, this.font));
}
public boolean add(Element element) {
if (element == null)
return false;
try {
Phrase phrase;
boolean success;
switch (element.type()) {
case 10:
return addChunk((Chunk)element);
case 11:
case 12:
phrase = (Phrase)element;
success = true;
for (Object element2 : (Iterable<Object>)phrase) {
Element e = (Element)element2;
if (e instanceof Chunk) {
success &= addChunk((Chunk)e);
continue;
}
success &= add(e);
}
return success;
case 14:
case 17:
case 23:
case 29:
case 37:
case 50:
case 55:
case 666:
return super.add(element);
}
throw new ClassCastException(String.valueOf(element.type()));
} catch (ClassCastException cce) {
throw new ClassCastException(MessageLocalization.getComposedMessage("insertion.of.illegal.element.1", cce.getMessage()));
}
}
public boolean addAll(Collection<? extends Element> collection) {
for (Element e : collection)
add(e);
return true;
}
protected boolean addChunk(Chunk chunk) {
Font f = chunk.getFont();
String c = chunk.getContent();
if (this.font != null && !this.font.isStandardFont())
f = this.font.difference(chunk.getFont());
if (size() > 0 && !chunk.hasAttributes())
try {
boolean sameRole;
Chunk previous = (Chunk)get(size() - 1);
PdfName previousRole = previous.getRole();
PdfName chunkRole = chunk.getRole();
if (previousRole == null || chunkRole == null) {
sameRole = true;
} else {
sameRole = previousRole.equals(chunkRole);
}
if (sameRole && !previous.hasAttributes() && !chunk.hasAccessibleAttributes() && !previous.hasAccessibleAttributes() && (f == null ||
f.compareTo(previous.getFont()) == 0) &&
!"".equals(previous.getContent().trim()) &&
!"".equals(c.trim())) {
previous.append(c);
return true;
}
} catch (ClassCastException e) {}
Chunk newChunk = new Chunk(c, f);
newChunk.setAttributes(chunk.getAttributes());
newChunk.role = chunk.getRole();
newChunk.accessibleAttributes = chunk.getAccessibleAttributes();
if (this.hyphenation != null && newChunk.getHyphenation() == null && !newChunk.isEmpty())
newChunk.setHyphenation(this.hyphenation);
return super.add(newChunk);
}
protected void addSpecial(Element object) {
super.add(object);
}
public void setLeading(float fixedLeading, float multipliedLeading) {
this.leading = fixedLeading;
this.multipliedLeading = multipliedLeading;
}
public void setLeading(float fixedLeading) {
this.leading = fixedLeading;
this.multipliedLeading = 0.0F;
}
public void setMultipliedLeading(float multipliedLeading) {
this.leading = 0.0F;
this.multipliedLeading = multipliedLeading;
}
public void setFont(Font font) {
this.font = font;
}
public float getLeading() {
if (Float.isNaN(this.leading) && this.font != null)
return this.font.getCalculatedLeading(1.5F);
return this.leading;
}
public float getMultipliedLeading() {
return this.multipliedLeading;
}
public float getTotalLeading() {
float m = (this.font == null) ? (12.0F * this.multipliedLeading) :
this.font.getCalculatedLeading(this.multipliedLeading);
if (m > 0.0F && !hasLeading())
return m;
return getLeading() + m;
}
public boolean hasLeading() {
if (Float.isNaN(this.leading))
return false;
return true;
}
public Font getFont() {
return this.font;
}
public String getContent() {
StringBuffer buf = new StringBuffer();
for (Chunk c : getChunks())
buf.append(c.toString());
return buf.toString();
}
public boolean isEmpty() {
Element element;
switch (size()) {
case 0:
return true;
case 1:
element = get(0);
if (element.type() == 10 && ((Chunk)element).isEmpty())
return true;
return false;
}
return false;
}
public HyphenationEvent getHyphenation() {
return this.hyphenation;
}
public void setHyphenation(HyphenationEvent hyphenation) {
this.hyphenation = hyphenation;
}
public TabSettings getTabSettings() {
return this.tabSettings;
}
public void setTabSettings(TabSettings tabSettings) {
this.tabSettings = tabSettings;
}
public static final Phrase getInstance(String string) {
return getInstance(16, string, new Font());
}
public static final Phrase getInstance(int leading, String string) {
return getInstance(leading, string, new Font());
}
public static final Phrase getInstance(int leading, String string, Font font) {
Phrase p = new Phrase(true);
p.setLeading((float)leading);
p.font = font;
if (font.getFamily() != Font.FontFamily.SYMBOL && font.getFamily() != Font.FontFamily.ZAPFDINGBATS && font.getBaseFont() == null) {
int index;
while ((index = SpecialSymbol.index(string)) > -1) {
if (index > 0) {
String firstPart = string.substring(0, index);
p.add(new Chunk(firstPart, font));
string = string.substring(index);
}
Font symbol = new Font(Font.FontFamily.SYMBOL, font.getSize(), font.getStyle(), font.getColor());
StringBuffer buf = new StringBuffer();
buf.append(SpecialSymbol.getCorrespondingSymbol(string.charAt(0)));
string = string.substring(1);
while (SpecialSymbol.index(string) == 0) {
buf.append(SpecialSymbol.getCorrespondingSymbol(string.charAt(0)));
string = string.substring(1);
}
p.add(new Chunk(buf.toString(), symbol));
}
}
if (string != null && string.length() != 0)
p.add(new Chunk(string, font));
return p;
}
public boolean trim() {
while (size() > 0) {
Element firstChunk = get(0);
if (firstChunk instanceof Chunk && ((Chunk)firstChunk).isWhitespace()) {
remove(firstChunk);
continue;
}
break;
}
while (size() > 0) {
Element lastChunk = get(size() - 1);
if (lastChunk instanceof Chunk && ((Chunk)lastChunk).isWhitespace()) {
remove(lastChunk);
continue;
}
break;
}
return (size() > 0);
}
private Phrase(boolean dummy) {}
}

View file

@ -0,0 +1,449 @@
package com.itextpdf.text;
import com.itextpdf.text.pdf.GrayColor;
import java.util.ArrayList;
public class Rectangle implements Element {
public static final int UNDEFINED = -1;
public static final int TOP = 1;
public static final int BOTTOM = 2;
public static final int LEFT = 4;
public static final int RIGHT = 8;
public static final int NO_BORDER = 0;
public static final int BOX = 15;
protected float llx;
protected float lly;
protected float urx;
protected float ury;
protected int rotation = 0;
protected BaseColor backgroundColor = null;
protected int border = -1;
protected boolean useVariableBorders = false;
protected float borderWidth = -1.0F;
protected float borderWidthLeft = -1.0F;
protected float borderWidthRight = -1.0F;
protected float borderWidthTop = -1.0F;
protected float borderWidthBottom = -1.0F;
protected BaseColor borderColor = null;
protected BaseColor borderColorLeft = null;
protected BaseColor borderColorRight = null;
protected BaseColor borderColorTop = null;
protected BaseColor borderColorBottom = null;
public Rectangle(float llx, float lly, float urx, float ury) {
this.llx = llx;
this.lly = lly;
this.urx = urx;
this.ury = ury;
}
public Rectangle(float llx, float lly, float urx, float ury, int rotation) {
this(llx, lly, urx, ury);
setRotation(rotation);
}
public Rectangle(float urx, float ury) {
this(0.0F, 0.0F, urx, ury);
}
public Rectangle(float urx, float ury, int rotation) {
this(0.0F, 0.0F, urx, ury, rotation);
}
public Rectangle(Rectangle rect) {
this(rect.llx, rect.lly, rect.urx, rect.ury);
cloneNonPositionParameters(rect);
}
public Rectangle(com.itextpdf.awt.geom.Rectangle rect) {
this((float)rect.getX(), (float)rect.getY(), (float)(rect.getX() + rect.getWidth()), (float)(rect.getY() + rect.getHeight()));
}
public boolean process(ElementListener listener) {
try {
return listener.add(this);
} catch (DocumentException de) {
return false;
}
}
public int type() {
return 30;
}
public java.util.List<Chunk> getChunks() {
return new ArrayList<Chunk>();
}
public boolean isContent() {
return true;
}
public boolean isNestable() {
return false;
}
public void setLeft(float llx) {
this.llx = llx;
}
public float getLeft() {
return this.llx;
}
public float getLeft(float margin) {
return this.llx + margin;
}
public void setRight(float urx) {
this.urx = urx;
}
public float getRight() {
return this.urx;
}
public float getRight(float margin) {
return this.urx - margin;
}
public float getWidth() {
return this.urx - this.llx;
}
public void setTop(float ury) {
this.ury = ury;
}
public float getTop() {
return this.ury;
}
public float getTop(float margin) {
return this.ury - margin;
}
public void setBottom(float lly) {
this.lly = lly;
}
public float getBottom() {
return this.lly;
}
public float getBottom(float margin) {
return this.lly + margin;
}
public float getHeight() {
return this.ury - this.lly;
}
public void normalize() {
if (this.llx > this.urx) {
float a = this.llx;
this.llx = this.urx;
this.urx = a;
}
if (this.lly > this.ury) {
float a = this.lly;
this.lly = this.ury;
this.ury = a;
}
}
public int getRotation() {
return this.rotation;
}
public void setRotation(int rotation) {
this.rotation = rotation % 360;
switch (this.rotation) {
case 90:
case 180:
case 270:
break;
default:
this.rotation = 0;
break;
}
}
public Rectangle rotate() {
Rectangle rect = new Rectangle(this.lly, this.llx, this.ury, this.urx);
rect.setRotation(this.rotation + 90);
return rect;
}
public BaseColor getBackgroundColor() {
return this.backgroundColor;
}
public void setBackgroundColor(BaseColor backgroundColor) {
this.backgroundColor = backgroundColor;
}
public float getGrayFill() {
if (this.backgroundColor instanceof GrayColor)
return ((GrayColor)this.backgroundColor).getGray();
return 0.0F;
}
public void setGrayFill(float value) {
this.backgroundColor = new GrayColor(value);
}
public int getBorder() {
return this.border;
}
public boolean hasBorders() {
switch (this.border) {
case -1:
case 0:
return false;
}
return (this.borderWidth > 0.0F || this.borderWidthLeft > 0.0F || this.borderWidthRight > 0.0F || this.borderWidthTop > 0.0F || this.borderWidthBottom > 0.0F);
}
public boolean hasBorder(int type) {
if (this.border == -1)
return false;
return ((this.border & type) == type);
}
public void setBorder(int border) {
this.border = border;
}
public boolean isUseVariableBorders() {
return this.useVariableBorders;
}
public void setUseVariableBorders(boolean useVariableBorders) {
this.useVariableBorders = useVariableBorders;
}
public void enableBorderSide(int side) {
if (this.border == -1)
this.border = 0;
this.border |= side;
}
public void disableBorderSide(int side) {
if (this.border == -1)
this.border = 0;
this.border &= side ^ 0xFFFFFFFF;
}
public float getBorderWidth() {
return this.borderWidth;
}
public void setBorderWidth(float borderWidth) {
this.borderWidth = borderWidth;
}
private float getVariableBorderWidth(float variableWidthValue, int side) {
if ((this.border & side) != 0)
return (variableWidthValue != -1.0F) ? variableWidthValue : this.borderWidth;
return 0.0F;
}
private void updateBorderBasedOnWidth(float width, int side) {
this.useVariableBorders = true;
if (width > 0.0F) {
enableBorderSide(side);
} else {
disableBorderSide(side);
}
}
public float getBorderWidthLeft() {
return getVariableBorderWidth(this.borderWidthLeft, 4);
}
public void setBorderWidthLeft(float borderWidthLeft) {
this.borderWidthLeft = borderWidthLeft;
updateBorderBasedOnWidth(borderWidthLeft, 4);
}
public float getBorderWidthRight() {
return getVariableBorderWidth(this.borderWidthRight, 8);
}
public void setBorderWidthRight(float borderWidthRight) {
this.borderWidthRight = borderWidthRight;
updateBorderBasedOnWidth(borderWidthRight, 8);
}
public float getBorderWidthTop() {
return getVariableBorderWidth(this.borderWidthTop, 1);
}
public void setBorderWidthTop(float borderWidthTop) {
this.borderWidthTop = borderWidthTop;
updateBorderBasedOnWidth(borderWidthTop, 1);
}
public float getBorderWidthBottom() {
return getVariableBorderWidth(this.borderWidthBottom, 2);
}
public void setBorderWidthBottom(float borderWidthBottom) {
this.borderWidthBottom = borderWidthBottom;
updateBorderBasedOnWidth(borderWidthBottom, 2);
}
public BaseColor getBorderColor() {
return this.borderColor;
}
public void setBorderColor(BaseColor borderColor) {
this.borderColor = borderColor;
}
public BaseColor getBorderColorLeft() {
if (this.borderColorLeft == null)
return this.borderColor;
return this.borderColorLeft;
}
public void setBorderColorLeft(BaseColor borderColorLeft) {
this.borderColorLeft = borderColorLeft;
}
public BaseColor getBorderColorRight() {
if (this.borderColorRight == null)
return this.borderColor;
return this.borderColorRight;
}
public void setBorderColorRight(BaseColor borderColorRight) {
this.borderColorRight = borderColorRight;
}
public BaseColor getBorderColorTop() {
if (this.borderColorTop == null)
return this.borderColor;
return this.borderColorTop;
}
public void setBorderColorTop(BaseColor borderColorTop) {
this.borderColorTop = borderColorTop;
}
public BaseColor getBorderColorBottom() {
if (this.borderColorBottom == null)
return this.borderColor;
return this.borderColorBottom;
}
public void setBorderColorBottom(BaseColor borderColorBottom) {
this.borderColorBottom = borderColorBottom;
}
public Rectangle rectangle(float top, float bottom) {
Rectangle tmp = new Rectangle(this);
if (getTop() > top) {
tmp.setTop(top);
tmp.disableBorderSide(1);
}
if (getBottom() < bottom) {
tmp.setBottom(bottom);
tmp.disableBorderSide(2);
}
return tmp;
}
public void cloneNonPositionParameters(Rectangle rect) {
this.rotation = rect.rotation;
this.backgroundColor = rect.backgroundColor;
this.border = rect.border;
this.useVariableBorders = rect.useVariableBorders;
this.borderWidth = rect.borderWidth;
this.borderWidthLeft = rect.borderWidthLeft;
this.borderWidthRight = rect.borderWidthRight;
this.borderWidthTop = rect.borderWidthTop;
this.borderWidthBottom = rect.borderWidthBottom;
this.borderColor = rect.borderColor;
this.borderColorLeft = rect.borderColorLeft;
this.borderColorRight = rect.borderColorRight;
this.borderColorTop = rect.borderColorTop;
this.borderColorBottom = rect.borderColorBottom;
}
public void softCloneNonPositionParameters(Rectangle rect) {
if (rect.rotation != 0)
this.rotation = rect.rotation;
if (rect.backgroundColor != null)
this.backgroundColor = rect.backgroundColor;
if (rect.border != -1)
this.border = rect.border;
if (this.useVariableBorders)
this.useVariableBorders = rect.useVariableBorders;
if (rect.borderWidth != -1.0F)
this.borderWidth = rect.borderWidth;
if (rect.borderWidthLeft != -1.0F)
this.borderWidthLeft = rect.borderWidthLeft;
if (rect.borderWidthRight != -1.0F)
this.borderWidthRight = rect.borderWidthRight;
if (rect.borderWidthTop != -1.0F)
this.borderWidthTop = rect.borderWidthTop;
if (rect.borderWidthBottom != -1.0F)
this.borderWidthBottom = rect.borderWidthBottom;
if (rect.borderColor != null)
this.borderColor = rect.borderColor;
if (rect.borderColorLeft != null)
this.borderColorLeft = rect.borderColorLeft;
if (rect.borderColorRight != null)
this.borderColorRight = rect.borderColorRight;
if (rect.borderColorTop != null)
this.borderColorTop = rect.borderColorTop;
if (rect.borderColorBottom != null)
this.borderColorBottom = rect.borderColorBottom;
}
public String toString() {
StringBuffer buf = new StringBuffer("Rectangle: ");
buf.append(getWidth());
buf.append('x');
buf.append(getHeight());
buf.append(" (rot: ");
buf.append(this.rotation);
buf.append(" degrees)");
return buf.toString();
}
public boolean equals(Object obj) {
if (obj instanceof Rectangle) {
Rectangle other = (Rectangle)obj;
return (other.llx == this.llx && other.lly == this.lly && other.urx == this.urx && other.ury == this.ury && other.rotation == this.rotation);
}
return false;
}
}

View file

@ -0,0 +1,139 @@
package com.itextpdf.text;
import com.itextpdf.text.error_messages.MessageLocalization;
public class RectangleReadOnly extends Rectangle {
public RectangleReadOnly(float llx, float lly, float urx, float ury) {
super(llx, lly, urx, ury);
}
public RectangleReadOnly(float llx, float lly, float urx, float ury, int rotation) {
super(llx, lly, urx, ury);
super.setRotation(rotation);
}
public RectangleReadOnly(float urx, float ury) {
super(0.0F, 0.0F, urx, ury);
}
public RectangleReadOnly(float urx, float ury, int rotation) {
super(0.0F, 0.0F, urx, ury);
super.setRotation(rotation);
}
public RectangleReadOnly(Rectangle rect) {
super(rect.llx, rect.lly, rect.urx, rect.ury);
super.cloneNonPositionParameters(rect);
}
private void throwReadOnlyError() {
throw new UnsupportedOperationException(MessageLocalization.getComposedMessage("rectanglereadonly.this.rectangle.is.read.only"));
}
public void setRotation(int rotation) {
throwReadOnlyError();
}
public void setLeft(float llx) {
throwReadOnlyError();
}
public void setRight(float urx) {
throwReadOnlyError();
}
public void setTop(float ury) {
throwReadOnlyError();
}
public void setBottom(float lly) {
throwReadOnlyError();
}
public void normalize() {
throwReadOnlyError();
}
public void setBackgroundColor(BaseColor value) {
throwReadOnlyError();
}
public void setGrayFill(float value) {
throwReadOnlyError();
}
public void setBorder(int border) {
throwReadOnlyError();
}
public void setUseVariableBorders(boolean useVariableBorders) {
throwReadOnlyError();
}
public void enableBorderSide(int side) {
throwReadOnlyError();
}
public void disableBorderSide(int side) {
throwReadOnlyError();
}
public void setBorderWidth(float borderWidth) {
throwReadOnlyError();
}
public void setBorderWidthLeft(float borderWidthLeft) {
throwReadOnlyError();
}
public void setBorderWidthRight(float borderWidthRight) {
throwReadOnlyError();
}
public void setBorderWidthTop(float borderWidthTop) {
throwReadOnlyError();
}
public void setBorderWidthBottom(float borderWidthBottom) {
throwReadOnlyError();
}
public void setBorderColor(BaseColor borderColor) {
throwReadOnlyError();
}
public void setBorderColorLeft(BaseColor borderColorLeft) {
throwReadOnlyError();
}
public void setBorderColorRight(BaseColor borderColorRight) {
throwReadOnlyError();
}
public void setBorderColorTop(BaseColor borderColorTop) {
throwReadOnlyError();
}
public void setBorderColorBottom(BaseColor borderColorBottom) {
throwReadOnlyError();
}
public void cloneNonPositionParameters(Rectangle rect) {
throwReadOnlyError();
}
public void softCloneNonPositionParameters(Rectangle rect) {
throwReadOnlyError();
}
public String toString() {
StringBuffer buf = new StringBuffer("RectangleReadOnly: ");
buf.append(getWidth());
buf.append('x');
buf.append(getHeight());
buf.append(" (rot: ");
buf.append(this.rotation);
buf.append(" degrees)");
return buf.toString();
}
}

View file

@ -0,0 +1,44 @@
package com.itextpdf.text;
import com.itextpdf.text.factories.RomanNumberFactory;
public class RomanList extends List {
public RomanList() {
super(true);
}
public RomanList(int symbolIndent) {
super(true, (float)symbolIndent);
}
public RomanList(boolean lowercase, int symbolIndent) {
super(true, (float)symbolIndent);
this.lowercase = lowercase;
}
public boolean add(Element o) {
if (o instanceof ListItem) {
ListItem item = (ListItem)o;
Chunk chunk = new Chunk(this.preSymbol, this.symbol.getFont());
chunk.setAttributes(this.symbol.getAttributes());
chunk.append(RomanNumberFactory.getString(this.first + this.list.size(), this.lowercase));
chunk.append(this.postSymbol);
item.setListSymbol(chunk);
item.setIndentationLeft(this.symbolIndent, this.autoindent);
item.setIndentationRight(0.0F);
this.list.add(item);
} else if (o instanceof List) {
List nested = (List)o;
nested.setIndentationLeft(nested.getIndentationLeft() + this.symbolIndent);
this.first--;
return this.list.add(nested);
}
return false;
}
public List cloneShallow() {
RomanList clone = new RomanList();
populateProperties(clone);
return clone;
}
}

View file

@ -0,0 +1,374 @@
package com.itextpdf.text;
import com.itextpdf.text.api.Indentable;
import com.itextpdf.text.error_messages.MessageLocalization;
import com.itextpdf.text.pdf.PdfName;
import com.itextpdf.text.pdf.PdfObject;
import com.itextpdf.text.pdf.interfaces.IAccessibleElement;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
public class Section extends ArrayList<Element> implements TextElementArray, LargeElement, Indentable, IAccessibleElement {
public static final int NUMBERSTYLE_DOTTED = 0;
public static final int NUMBERSTYLE_DOTTED_WITHOUT_FINAL_DOT = 1;
private static final long serialVersionUID = 3324172577544748043L;
protected Paragraph title;
protected String bookmarkTitle;
protected int numberDepth;
protected int numberStyle = 0;
protected float indentationLeft;
protected float indentationRight;
protected float indentation;
protected boolean bookmarkOpen = true;
protected boolean triggerNewPage = false;
protected int subsections = 0;
protected ArrayList<Integer> numbers = null;
protected boolean complete = true;
protected boolean addedCompletely = false;
protected boolean notAddedYet = true;
protected Section() {
this.title = new Paragraph();
this.numberDepth = 1;
this.title.setRole(new PdfName("H" + this.numberDepth));
}
protected Section(Paragraph title, int numberDepth) {
this.numberDepth = numberDepth;
this.title = title;
if (title != null)
title.setRole(new PdfName("H" + numberDepth));
}
public boolean process(ElementListener listener) {
try {
for (Object element2 : (Iterable<Object>)this) {
Element element = (Element)element2;
listener.add(element);
}
return true;
} catch (DocumentException de) {
return false;
}
}
public int type() {
return 13;
}
public boolean isChapter() {
return (type() == 16);
}
public boolean isSection() {
return (type() == 13);
}
public java.util.List<Chunk> getChunks() {
java.util.List<Chunk> tmp = new ArrayList<Chunk>();
for (Object element : (Iterable<Object>)this)
tmp.addAll(((Element)element).getChunks());
return tmp;
}
public boolean isContent() {
return true;
}
public boolean isNestable() {
return false;
}
public void add(int index, Element element) {
if (isAddedCompletely())
throw new IllegalStateException(MessageLocalization.getComposedMessage("this.largeelement.has.already.been.added.to.the.document"));
try {
if (element.isNestable()) {
super.add(index, element);
} else {
throw new ClassCastException(MessageLocalization.getComposedMessage("you.can.t.add.a.1.to.a.section", element.getClass().getName()));
}
} catch (ClassCastException cce) {
throw new ClassCastException(MessageLocalization.getComposedMessage("insertion.of.illegal.element.1", cce.getMessage()));
}
}
public boolean add(Element element) {
if (isAddedCompletely())
throw new IllegalStateException(MessageLocalization.getComposedMessage("this.largeelement.has.already.been.added.to.the.document"));
try {
if (element.type() == 13) {
Section section = (Section)element;
section.setNumbers(++this.subsections, this.numbers);
return super.add(section);
}
if (element instanceof MarkedSection && ((MarkedObject)element).element.type() == 13) {
MarkedSection mo = (MarkedSection)element;
Section section = (Section)mo.element;
section.setNumbers(++this.subsections, this.numbers);
return super.add(mo);
}
if (element.isNestable())
return super.add(element);
throw new ClassCastException(MessageLocalization.getComposedMessage("you.can.t.add.a.1.to.a.section", element.getClass().getName()));
} catch (ClassCastException cce) {
throw new ClassCastException(MessageLocalization.getComposedMessage("insertion.of.illegal.element.1", cce.getMessage()));
}
}
public boolean addAll(Collection<? extends Element> collection) {
if (collection.size() == 0)
return false;
for (Element element : collection)
add(element);
return true;
}
public Section addSection(float indentation, Paragraph title, int numberDepth) {
if (isAddedCompletely())
throw new IllegalStateException(MessageLocalization.getComposedMessage("this.largeelement.has.already.been.added.to.the.document"));
Section section = new Section(title, numberDepth);
section.setIndentation(indentation);
add(section);
return section;
}
public Section addSection(float indentation, Paragraph title) {
return addSection(indentation, title, this.numberDepth + 1);
}
public Section addSection(Paragraph title, int numberDepth) {
return addSection(0.0F, title, numberDepth);
}
protected MarkedSection addMarkedSection() {
MarkedSection section = new MarkedSection(new Section(null, this.numberDepth + 1));
add(section);
return section;
}
public Section addSection(Paragraph title) {
return addSection(0.0F, title, this.numberDepth + 1);
}
public Section addSection(float indentation, String title, int numberDepth) {
return addSection(indentation, new Paragraph(title), numberDepth);
}
public Section addSection(String title, int numberDepth) {
return addSection(new Paragraph(title), numberDepth);
}
public Section addSection(float indentation, String title) {
return addSection(indentation, new Paragraph(title));
}
public Section addSection(String title) {
return addSection(new Paragraph(title));
}
public void setTitle(Paragraph title) {
this.title = title;
}
public Paragraph getTitle() {
return constructTitle(this.title, this.numbers, this.numberDepth, this.numberStyle);
}
public static Paragraph constructTitle(Paragraph title, ArrayList<Integer> numbers, int numberDepth, int numberStyle) {
if (title == null)
return null;
int depth = Math.min(numbers.size(), numberDepth);
if (depth < 1)
return title;
StringBuffer buf = new StringBuffer(" ");
for (int i = 0; i < depth; i++) {
buf.insert(0, ".");
buf.insert(0, numbers.get(i).intValue());
}
if (numberStyle == 1)
buf.deleteCharAt(buf.length() - 2);
Paragraph result = new Paragraph(title);
result.add(0, new Chunk(buf.toString(), title.getFont()));
return result;
}
public void setNumberDepth(int numberDepth) {
this.numberDepth = numberDepth;
}
public int getNumberDepth() {
return this.numberDepth;
}
public void setNumberStyle(int numberStyle) {
this.numberStyle = numberStyle;
}
public int getNumberStyle() {
return this.numberStyle;
}
public void setIndentationLeft(float indentation) {
this.indentationLeft = indentation;
}
public float getIndentationLeft() {
return this.indentationLeft;
}
public void setIndentationRight(float indentation) {
this.indentationRight = indentation;
}
public float getIndentationRight() {
return this.indentationRight;
}
public void setIndentation(float indentation) {
this.indentation = indentation;
}
public float getIndentation() {
return this.indentation;
}
public void setBookmarkOpen(boolean bookmarkOpen) {
this.bookmarkOpen = bookmarkOpen;
}
public boolean isBookmarkOpen() {
return this.bookmarkOpen;
}
public void setTriggerNewPage(boolean triggerNewPage) {
this.triggerNewPage = triggerNewPage;
}
public boolean isTriggerNewPage() {
return (this.triggerNewPage && this.notAddedYet);
}
public void setBookmarkTitle(String bookmarkTitle) {
this.bookmarkTitle = bookmarkTitle;
}
public Paragraph getBookmarkTitle() {
if (this.bookmarkTitle == null)
return getTitle();
return new Paragraph(this.bookmarkTitle);
}
public void setChapterNumber(int number) {
this.numbers.set(this.numbers.size() - 1, Integer.valueOf(number));
for (Object s : (Iterable<Object>)this) {
if (s instanceof Section)
((Section)s).setChapterNumber(number);
}
}
public int getDepth() {
return this.numbers.size();
}
private void setNumbers(int number, ArrayList<Integer> numbers) {
this.numbers = new ArrayList<Integer>();
this.numbers.add(Integer.valueOf(number));
this.numbers.addAll(numbers);
}
public boolean isNotAddedYet() {
return this.notAddedYet;
}
public void setNotAddedYet(boolean notAddedYet) {
this.notAddedYet = notAddedYet;
}
protected boolean isAddedCompletely() {
return this.addedCompletely;
}
protected void setAddedCompletely(boolean addedCompletely) {
this.addedCompletely = addedCompletely;
}
public void flushContent() {
setNotAddedYet(false);
this.title = null;
for (Iterator<Element> i = iterator(); i.hasNext(); ) {
Element element = i.next();
if (element instanceof Section) {
Section s = (Section)element;
if (!s.isComplete() && size() == 1) {
s.flushContent();
return;
}
s.setAddedCompletely(true);
}
i.remove();
}
}
public boolean isComplete() {
return this.complete;
}
public void setComplete(boolean complete) {
this.complete = complete;
}
public void newPage() {
add(Chunk.NEXTPAGE);
}
public PdfObject getAccessibleAttribute(PdfName key) {
return this.title.getAccessibleAttribute(key);
}
public void setAccessibleAttribute(PdfName key, PdfObject value) {
this.title.setAccessibleAttribute(key, value);
}
public HashMap<PdfName, PdfObject> getAccessibleAttributes() {
return this.title.getAccessibleAttributes();
}
public PdfName getRole() {
return this.title.getRole();
}
public void setRole(PdfName role) {
this.title.setRole(role);
}
public AccessibleElementId getId() {
return this.title.getId();
}
public void setId(AccessibleElementId id) {
this.title.setId(id);
}
public boolean isInline() {
return false;
}
}

View file

@ -0,0 +1,125 @@
package com.itextpdf.text;
public class SpecialSymbol {
public static int index(String string) {
int length = string.length();
for (int i = 0; i < length; i++) {
if (getCorrespondingSymbol(string.charAt(i)) != ' ')
return i;
}
return -1;
}
public static Chunk get(char c, Font font) {
char greek = getCorrespondingSymbol(c);
if (greek == ' ')
return new Chunk(String.valueOf(c), font);
Font symbol = new Font(Font.FontFamily.SYMBOL, font.getSize(), font.getStyle(), font.getColor());
String s = String.valueOf(greek);
return new Chunk(s, symbol);
}
public static char getCorrespondingSymbol(char c) {
switch (c) {
case 'Α':
return 'A';
case 'Β':
return 'B';
case 'Γ':
return 'G';
case 'Δ':
return 'D';
case 'Ε':
return 'E';
case 'Ζ':
return 'Z';
case 'Η':
return 'H';
case 'Θ':
return 'Q';
case 'Ι':
return 'I';
case 'Κ':
return 'K';
case 'Λ':
return 'L';
case 'Μ':
return 'M';
case 'Ν':
return 'N';
case 'Ξ':
return 'X';
case 'Ο':
return 'O';
case 'Π':
return 'P';
case 'Ρ':
return 'R';
case 'Σ':
return 'S';
case 'Τ':
return 'T';
case 'Υ':
return 'U';
case 'Φ':
return 'F';
case 'Χ':
return 'C';
case 'Ψ':
return 'Y';
case 'Ω':
return 'W';
case 'α':
return 'a';
case 'β':
return 'b';
case 'γ':
return 'g';
case 'δ':
return 'd';
case 'ε':
return 'e';
case 'ζ':
return 'z';
case 'η':
return 'h';
case 'θ':
return 'q';
case 'ι':
return 'i';
case 'κ':
return 'k';
case 'λ':
return 'l';
case 'μ':
return 'm';
case 'ν':
return 'n';
case 'ξ':
return 'x';
case 'ο':
return 'o';
case 'π':
return 'p';
case 'ρ':
return 'r';
case 'ς':
return 'V';
case 'σ':
return 's';
case 'τ':
return 't';
case 'υ':
return 'u';
case 'φ':
return 'f';
case 'χ':
return 'c';
case 'ψ':
return 'y';
case 'ω':
return 'w';
}
return ' ';
}
}

View file

@ -0,0 +1,7 @@
package com.itextpdf.text;
import com.itextpdf.text.pdf.PdfChunk;
public interface SplitCharacter {
boolean isSplitCharacter(int paramInt1, int paramInt2, int paramInt3, char[] paramArrayOfchar, PdfChunk[] paramArrayOfPdfChunk);
}

View file

@ -0,0 +1,62 @@
package com.itextpdf.text;
import java.util.ArrayList;
public class TabSettings {
public static final float DEFAULT_TAB_INTERVAL = 36.0F;
public static TabStop getTabStopNewInstance(float currentPosition, TabSettings tabSettings) {
if (tabSettings != null)
return tabSettings.getTabStopNewInstance(currentPosition);
return TabStop.newInstance(currentPosition, 36.0F);
}
private java.util.List<TabStop> tabStops = new ArrayList<TabStop>();
private float tabInterval = 36.0F;
public TabSettings() {}
public TabSettings(java.util.List<TabStop> tabStops) {
this.tabStops = tabStops;
}
public TabSettings(float tabInterval) {
this.tabInterval = tabInterval;
}
public TabSettings(java.util.List<TabStop> tabStops, float tabInterval) {
this.tabStops = tabStops;
this.tabInterval = tabInterval;
}
public java.util.List<TabStop> getTabStops() {
return this.tabStops;
}
public void setTabStops(java.util.List<TabStop> tabStops) {
this.tabStops = tabStops;
}
public float getTabInterval() {
return this.tabInterval;
}
public void setTabInterval(float tabInterval) {
this.tabInterval = tabInterval;
}
public TabStop getTabStopNewInstance(float currentPosition) {
TabStop tabStop = null;
if (this.tabStops != null)
for (TabStop currentTabStop : this.tabStops) {
if ((double)(currentTabStop.getPosition() - currentPosition) > 0.001D) {
tabStop = new TabStop(currentTabStop);
break;
}
}
if (tabStop == null)
tabStop = TabStop.newInstance(currentPosition, this.tabInterval);
return tabStop;
}
}

View file

@ -0,0 +1,11 @@
package com.itextpdf.text;
import com.itextpdf.text.pdf.PdfChunk;
public class TabSplitCharacter implements SplitCharacter {
public static final SplitCharacter TAB = new TabSplitCharacter();
public boolean isSplitCharacter(int start, int current, int end, char[] cc, PdfChunk[] ck) {
return true;
}
}

View file

@ -0,0 +1,124 @@
package com.itextpdf.text;
import com.itextpdf.text.pdf.draw.DrawInterface;
public class TabStop {
protected float position;
public static TabStop newInstance(float currentPosition, float tabInterval) {
currentPosition = (float)Math.round(currentPosition * 1000.0F) / 1000.0F;
tabInterval = (float)Math.round(tabInterval * 1000.0F) / 1000.0F;
TabStop tabStop = new TabStop(currentPosition + tabInterval - currentPosition % tabInterval);
return tabStop;
}
public enum Alignment {
LEFT, RIGHT, CENTER, ANCHOR;
}
protected Alignment alignment = Alignment.LEFT;
protected DrawInterface leader;
protected char anchorChar = '.';
public TabStop(float position) {
this(position, Alignment.LEFT);
}
public TabStop(float position, DrawInterface leader) {
this(position, leader, Alignment.LEFT);
}
public TabStop(float position, Alignment alignment) {
this(position, null, alignment);
}
public TabStop(float position, Alignment alignment, char anchorChar) {
this(position, null, alignment, anchorChar);
}
public TabStop(float position, DrawInterface leader, Alignment alignment) {
this(position, leader, alignment, '.');
}
public TabStop(float position, DrawInterface leader, Alignment alignment, char anchorChar) {
this.position = position;
this.leader = leader;
this.alignment = alignment;
this.anchorChar = anchorChar;
}
public TabStop(TabStop tabStop) {
this(tabStop.getPosition(), tabStop.getLeader(), tabStop.getAlignment(), tabStop.getAnchorChar());
}
public float getPosition() {
return this.position;
}
public void setPosition(float position) {
this.position = position;
}
public Alignment getAlignment() {
return this.alignment;
}
public void setAlignment(Alignment alignment) {
this.alignment = alignment;
}
public DrawInterface getLeader() {
return this.leader;
}
public void setLeader(DrawInterface leader) {
this.leader = leader;
}
public char getAnchorChar() {
return this.anchorChar;
}
public void setAnchorChar(char anchorChar) {
this.anchorChar = anchorChar;
}
public float getPosition(float tabPosition, float currentPosition, float anchorPosition) {
float newPosition = this.position;
float textWidth = currentPosition - tabPosition;
switch (this.alignment) {
case RIGHT:
if (tabPosition + textWidth < this.position) {
newPosition = this.position - textWidth;
} else {
newPosition = tabPosition;
}
break;
case CENTER:
if (tabPosition + textWidth / 2.0F < this.position) {
newPosition = this.position - textWidth / 2.0F;
} else {
newPosition = tabPosition;
}
break;
case ANCHOR:
if (!Float.isNaN(anchorPosition)) {
if (anchorPosition < this.position) {
newPosition = this.position - (anchorPosition - tabPosition);
} else {
newPosition = tabPosition;
}
break;
}
if (tabPosition + textWidth < this.position) {
newPosition = this.position - textWidth;
} else {
newPosition = tabPosition;
}
break;
}
return newPosition;
}
}

View file

@ -0,0 +1,5 @@
package com.itextpdf.text;
public interface TextElementArray extends Element {
boolean add(Element paramElement);
}

View file

@ -0,0 +1,171 @@
package com.itextpdf.text;
import com.itextpdf.text.pdf.ByteBuffer;
import com.itextpdf.text.pdf.PRTokeniser;
import com.itextpdf.text.pdf.PdfEncodings;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Collections;
import java.util.Hashtable;
import java.util.Properties;
import java.util.Set;
public class Utilities {
@Deprecated
public static <K, V> Set<K> getKeySet(Hashtable<K, V> table) {
return (table == null) ? Collections.<K>emptySet() : table.keySet();
}
public static Object[][] addToArray(Object[][] original, Object[] item) {
if (original == null) {
original = new Object[1][];
original[0] = item;
return original;
}
Object[][] original2 = new Object[original.length + 1][];
System.arraycopy(original, 0, original2, 0, original.length);
original2[original.length] = item;
return original2;
}
public static boolean checkTrueOrFalse(Properties attributes, String key) {
return "true".equalsIgnoreCase(attributes.getProperty(key));
}
public static String unEscapeURL(String src) {
StringBuffer bf = new StringBuffer();
char[] s = src.toCharArray();
for (int k = 0; k < s.length; k++) {
char c = s[k];
if (c == '%') {
if (k + 2 >= s.length) {
bf.append(c);
} else {
int a0 = PRTokeniser.getHex(s[k + 1]);
int a1 = PRTokeniser.getHex(s[k + 2]);
if (a0 < 0 || a1 < 0) {
bf.append(c);
} else {
bf.append((char)(a0 * 16 + a1));
k += 2;
}
}
} else {
bf.append(c);
}
}
return bf.toString();
}
public static URL toURL(String filename) throws MalformedURLException {
try {
return new URL(filename);
} catch (Exception e) {
return new File(filename).toURI().toURL();
}
}
public static void skip(InputStream is, int size) throws IOException {
while (size > 0) {
long n = is.skip((long)size);
if (n <= 0L)
break;
size = (int)((long)size - n);
}
}
public static final float millimetersToPoints(float value) {
return inchesToPoints(millimetersToInches(value));
}
public static final float millimetersToInches(float value) {
return value / 25.4F;
}
public static final float pointsToMillimeters(float value) {
return inchesToMillimeters(pointsToInches(value));
}
public static final float pointsToInches(float value) {
return value / 72.0F;
}
public static final float inchesToMillimeters(float value) {
return value * 25.4F;
}
public static final float inchesToPoints(float value) {
return value * 72.0F;
}
public static boolean isSurrogateHigh(char c) {
return (c >= '?' && c <= '?');
}
public static boolean isSurrogateLow(char c) {
return (c >= '?' && c <= '?');
}
public static boolean isSurrogatePair(String text, int idx) {
if (idx < 0 || idx > text.length() - 2)
return false;
return (isSurrogateHigh(text.charAt(idx)) && isSurrogateLow(text.charAt(idx + 1)));
}
public static boolean isSurrogatePair(char[] text, int idx) {
if (idx < 0 || idx > text.length - 2)
return false;
return (isSurrogateHigh(text[idx]) && isSurrogateLow(text[idx + 1]));
}
public static int convertToUtf32(char highSurrogate, char lowSurrogate) {
return (highSurrogate - 55296) * 1024 + lowSurrogate - 56320 + 65536;
}
public static int convertToUtf32(char[] text, int idx) {
return (text[idx] - 55296) * 1024 + text[idx + 1] - 56320 + 65536;
}
public static int convertToUtf32(String text, int idx) {
return (text.charAt(idx) - 55296) * 1024 + text.charAt(idx + 1) - 56320 + 65536;
}
public static String convertFromUtf32(int codePoint) {
if (codePoint < 65536)
return Character.toString((char)codePoint);
codePoint -= 65536;
return new String(new char[] { (char)(codePoint / 1024 + 55296), (char)(codePoint % 1024 + 56320) });
}
public static String readFileToString(String path) throws IOException {
return readFileToString(new File(path));
}
public static String readFileToString(File file) throws IOException {
byte[] jsBytes = new byte[(int)file.length()];
FileInputStream f = new FileInputStream(file);
f.read(jsBytes);
return new String(jsBytes);
}
public static String convertToHex(byte[] bytes) {
ByteBuffer buf = new ByteBuffer();
for (byte b : bytes)
buf.appendHex(b);
return PdfEncodings.convertToString(buf.toByteArray(), null).toUpperCase();
}
public static char[] copyOfRange(char[] original, int from, int to) {
int newLength = to - from;
if (newLength < 0)
throw new IllegalArgumentException(from + " > " + to);
char[] copy = new char[newLength];
System.arraycopy(original, from, copy, 0,
Math.min(original.length - from, newLength));
return copy;
}
}

View file

@ -0,0 +1,82 @@
package com.itextpdf.text;
import java.lang.reflect.Method;
public final class Version {
public static String AGPL = " (AGPL-version)";
private static Version version = null;
private String iText = "iText®";
private String release = "5.5.10";
private String iTextVersion = this.iText + " " + this.release + " ©2000-2015 iText Group NV";
private String key = null;
public static Version getInstance() {
if (version == null) {
version = new Version();
synchronized (version) {
try {
Class<?> klass = Class.forName("com.itextpdf.license.LicenseKey");
Method m = klass.getMethod("getLicenseeInfo");
String[] info = (String[])m.invoke(klass.newInstance());
if (info[3] != null && info[3].trim().length() > 0) {
version.key = info[3];
} else {
version.key = "Trial version ";
if (info[5] == null) {
version.key += "unauthorised";
} else {
version.key += info[5];
}
}
if (info[4] != null && info[4].trim().length() > 0) {
version.iTextVersion = info[4];
} else if (info[2] != null && info[2].trim().length() > 0) {
version.iTextVersion += " (" + info[2];
if (!version.key.toLowerCase().startsWith("trial")) {
version.iTextVersion += "; licensed version)";
} else {
version.iTextVersion += "; " + version.key + ")";
}
} else if (info[0] != null && info[0].trim().length() > 0) {
version.iTextVersion += " (" + info[0];
if (!version.key.toLowerCase().startsWith("trial")) {
version.iTextVersion += "; licensed version)";
} else {
version.iTextVersion += "; " + version.key + ")";
}
} else {
throw new Exception();
}
} catch (Exception e) {
version.iTextVersion += AGPL;
}
}
}
return version;
}
public String getProduct() {
return this.iText;
}
public String getRelease() {
return this.release;
}
public String getVersion() {
return this.iTextVersion;
}
public String getKey() {
return this.key;
}
public static boolean isAGPLVersion() {
return (getInstance().getVersion().indexOf(AGPL) > 0);
}
}

View file

@ -0,0 +1,42 @@
package com.itextpdf.text;
import com.itextpdf.text.api.WriterOperation;
import java.util.ArrayList;
public abstract class WritableDirectElement implements Element, WriterOperation {
public static final int DIRECT_ELEMENT_TYPE_UNKNOWN = 0;
public static final int DIRECT_ELEMENT_TYPE_HEADER = 1;
protected int directElementType = 0;
public WritableDirectElement() {}
public WritableDirectElement(int directElementType) {
this.directElementType = directElementType;
}
public boolean process(ElementListener listener) {
throw new UnsupportedOperationException();
}
public int type() {
return 666;
}
public boolean isContent() {
return false;
}
public boolean isNestable() {
throw new UnsupportedOperationException();
}
public java.util.List<Chunk> getChunks() {
return new ArrayList<Chunk>(0);
}
public int getDirectElementType() {
return this.directElementType;
}
}

View file

@ -0,0 +1,68 @@
package com.itextpdf.text;
public class ZapfDingbatsList extends List {
protected int zn;
public ZapfDingbatsList(int zn) {
super(true);
this.zn = zn;
float fontsize = this.symbol.getFont().getSize();
this.symbol.setFont(FontFactory.getFont("ZapfDingbats", fontsize, 0));
this.postSymbol = " ";
}
public ZapfDingbatsList(int zn, int symbolIndent) {
super(true, (float)symbolIndent);
this.zn = zn;
float fontsize = this.symbol.getFont().getSize();
this.symbol.setFont(FontFactory.getFont("ZapfDingbats", fontsize, 0));
this.postSymbol = " ";
}
public ZapfDingbatsList(int zn, int symbolIndent, BaseColor zapfDingbatColor) {
super(true, (float)symbolIndent);
this.zn = zn;
float fontsize = this.symbol.getFont().getSize();
this.symbol.setFont(FontFactory.getFont("ZapfDingbats", fontsize, 0, zapfDingbatColor));
this.postSymbol = " ";
}
public void setDingbatColor(BaseColor zapfDingbatColor) {
float fontsize = this.symbol.getFont().getSize();
this.symbol.setFont(FontFactory.getFont("ZapfDingbats", fontsize, 0, zapfDingbatColor));
}
public void setCharNumber(int zn) {
this.zn = zn;
}
public int getCharNumber() {
return this.zn;
}
public boolean add(Element o) {
if (o instanceof ListItem) {
ListItem item = (ListItem)o;
Chunk chunk = new Chunk(this.preSymbol, this.symbol.getFont());
chunk.setAttributes(this.symbol.getAttributes());
chunk.append(String.valueOf((char)this.zn));
chunk.append(this.postSymbol);
item.setListSymbol(chunk);
item.setIndentationLeft(this.symbolIndent, this.autoindent);
item.setIndentationRight(0.0F);
this.list.add(item);
} else if (o instanceof List) {
List nested = (List)o;
nested.setIndentationLeft(nested.getIndentationLeft() + this.symbolIndent);
this.first--;
return this.list.add(nested);
}
return false;
}
public List cloneShallow() {
ZapfDingbatsList clone = new ZapfDingbatsList(this.zn);
populateProperties(clone);
return clone;
}
}

View file

@ -0,0 +1,68 @@
package com.itextpdf.text;
public class ZapfDingbatsNumberList extends List {
protected int type;
public ZapfDingbatsNumberList(int type) {
super(true);
this.type = type;
float fontsize = this.symbol.getFont().getSize();
this.symbol.setFont(FontFactory.getFont("ZapfDingbats", fontsize, 0));
this.postSymbol = " ";
}
public ZapfDingbatsNumberList(int type, int symbolIndent) {
super(true, (float)symbolIndent);
this.type = type;
float fontsize = this.symbol.getFont().getSize();
this.symbol.setFont(FontFactory.getFont("ZapfDingbats", fontsize, 0));
this.postSymbol = " ";
}
public void setType(int type) {
this.type = type;
}
public int getType() {
return this.type;
}
public boolean add(Element o) {
if (o instanceof ListItem) {
ListItem item = (ListItem)o;
Chunk chunk = new Chunk(this.preSymbol, this.symbol.getFont());
chunk.setAttributes(this.symbol.getAttributes());
switch (this.type) {
case 0:
chunk.append(String.valueOf((char)(this.first + this.list.size() + 171)));
break;
case 1:
chunk.append(String.valueOf((char)(this.first + this.list.size() + 181)));
break;
case 2:
chunk.append(String.valueOf((char)(this.first + this.list.size() + 191)));
break;
default:
chunk.append(String.valueOf((char)(this.first + this.list.size() + 201)));
break;
}
chunk.append(this.postSymbol);
item.setListSymbol(chunk);
item.setIndentationLeft(this.symbolIndent, this.autoindent);
item.setIndentationRight(0.0F);
this.list.add(item);
} else if (o instanceof List) {
List nested = (List)o;
nested.setIndentationLeft(nested.getIndentationLeft() + this.symbolIndent);
this.first--;
return this.list.add(nested);
}
return false;
}
public List cloneShallow() {
ZapfDingbatsNumberList clone = new ZapfDingbatsNumberList(this.type);
populateProperties(clone);
return clone;
}
}

View file

@ -0,0 +1,11 @@
package com.itextpdf.text.api;
public interface Indentable {
void setIndentationLeft(float paramFloat);
void setIndentationRight(float paramFloat);
float getIndentationLeft();
float getIndentationRight();
}

View file

@ -0,0 +1,15 @@
package com.itextpdf.text.api;
public interface Spaceable {
void setSpacingBefore(float paramFloat);
void setSpacingAfter(float paramFloat);
void setPaddingTop(float paramFloat);
float getSpacingBefore();
float getSpacingAfter();
float getPaddingTop();
}

View file

@ -0,0 +1,9 @@
package com.itextpdf.text.api;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.pdf.PdfWriter;
public interface WriterOperation {
void write(PdfWriter paramPdfWriter, Document paramDocument) throws DocumentException;
}

View file

@ -0,0 +1,122 @@
package com.itextpdf.text.error_messages;
import com.itextpdf.text.io.StreamUtil;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.HashMap;
public final class MessageLocalization {
private static HashMap<String, String> defaultLanguage = new HashMap<String, String>();
private static HashMap<String, String> currentLanguage;
private static final String BASE_PATH = "com/itextpdf/text/l10n/error/";
static {
try {
defaultLanguage = getLanguageMessages("en", null);
} catch (Exception e) {}
if (defaultLanguage == null)
defaultLanguage = new HashMap<String, String>();
}
public static String getMessage(String key) {
return getMessage(key, true);
}
public static String getMessage(String key, boolean useDefaultLanguageIfMessageNotFound) {
HashMap<String, String> cl = currentLanguage;
if (cl != null) {
String val = cl.get(key);
if (val != null)
return val;
}
if (useDefaultLanguageIfMessageNotFound) {
cl = defaultLanguage;
String val = cl.get(key);
if (val != null)
return val;
}
return "No message found for " + key;
}
public static String getComposedMessage(String key, int p1) {
return getComposedMessage(key, new Object[] { String.valueOf(p1), null, null, null });
}
public static String getComposedMessage(String key, Object... param) {
String msg = getMessage(key);
if (null != param) {
int i = 1;
for (Object o : param) {
if (null != o)
msg = msg.replace("{" + i + "}", o.toString());
i++;
}
}
return msg;
}
public static boolean setLanguage(String language, String country) throws IOException {
HashMap<String, String> lang = getLanguageMessages(language, country);
if (lang == null)
return false;
currentLanguage = lang;
return true;
}
public static void setMessages(Reader r) throws IOException {
currentLanguage = readLanguageStream(r);
}
private static HashMap<String, String> getLanguageMessages(String language, String country) throws IOException {
if (language == null)
throw new IllegalArgumentException("The language cannot be null.");
InputStream is = null;
try {
if (country != null) {
file = language + "_" + country + ".lng";
} else {
file = language + ".lng";
}
is = StreamUtil.getResourceStream("com/itextpdf/text/l10n/error/" + file, new MessageLocalization().getClass().getClassLoader());
if (is != null)
return readLanguageStream(is);
if (country == null)
return null;
String file = language + ".lng";
is = StreamUtil.getResourceStream("com/itextpdf/text/l10n/error/" + file, new MessageLocalization().getClass().getClassLoader());
if (is != null)
return readLanguageStream(is);
return null;
} finally {
try {
if (null != is)
is.close();
} catch (Exception e) {}
}
}
private static HashMap<String, String> readLanguageStream(InputStream is) throws IOException {
return readLanguageStream(new InputStreamReader(is, "UTF-8"));
}
private static HashMap<String, String> readLanguageStream(Reader r) throws IOException {
HashMap<String, String> lang = new HashMap<String, String>();
BufferedReader br = new BufferedReader(r);
String line;
while ((line = br.readLine()) != null) {
int idxeq = line.indexOf('=');
if (idxeq < 0)
continue;
String key = line.substring(0, idxeq).trim();
if (key.startsWith("#"))
continue;
lang.put(key, line.substring(idxeq + 1));
}
return lang;
}
}

View file

@ -0,0 +1,11 @@
package com.itextpdf.text.exceptions;
import java.io.IOException;
public class BadPasswordException extends IOException {
private static final long serialVersionUID = -4333706268155063964L;
public BadPasswordException(String message) {
super(message);
}
}

View file

@ -0,0 +1,9 @@
package com.itextpdf.text.exceptions;
public class IllegalPdfSyntaxException extends IllegalArgumentException {
private static final long serialVersionUID = -643024246596031671L;
public IllegalPdfSyntaxException(String message) {
super(message);
}
}

View file

@ -0,0 +1,20 @@
package com.itextpdf.text.exceptions;
public class InvalidImageException extends RuntimeException {
private static final long serialVersionUID = -1319471492541702697L;
private final Throwable cause;
public InvalidImageException(String message) {
this(message, null);
}
public InvalidImageException(String message, Throwable cause) {
super(message);
this.cause = cause;
}
public Throwable getCause() {
return this.cause;
}
}

View file

@ -0,0 +1,22 @@
package com.itextpdf.text.exceptions;
import java.io.IOException;
public class InvalidPdfException extends IOException {
private static final long serialVersionUID = -2319614911517026938L;
private final Throwable cause;
public InvalidPdfException(String message) {
this(message, null);
}
public InvalidPdfException(String message, Throwable cause) {
super(message);
this.cause = cause;
}
public Throwable getCause() {
return this.cause;
}
}

View file

@ -0,0 +1,9 @@
package com.itextpdf.text.exceptions;
public class UnsupportedPdfException extends InvalidPdfException {
private static final long serialVersionUID = 2180764250839096628L;
public UnsupportedPdfException(String message) {
super(message);
}
}

View file

@ -0,0 +1,43 @@
package com.itextpdf.text.factories;
import com.itextpdf.text.SpecialSymbol;
public class GreekAlphabetFactory {
public static final String getString(int index) {
return getString(index, true);
}
public static final String getLowerCaseString(int index) {
return getString(index);
}
public static final String getUpperCaseString(int index) {
return getString(index).toUpperCase();
}
public static final String getString(int index, boolean lowercase) {
if (index < 1)
return "";
index--;
int bytes = 1;
int start = 0;
int symbols = 24;
while (index >= symbols + start) {
bytes++;
start += symbols;
symbols *= 24;
}
int c = index - start;
char[] value = new char[bytes];
while (bytes > 0) {
bytes--;
value[bytes] = (char)(c % 24);
if (value[bytes] > '\020')
value[bytes] = (char)(value[bytes] + 1);
value[bytes] = (char)(value[bytes] + (lowercase ? 945 : 913));
value[bytes] = SpecialSymbol.getCorrespondingSymbol(value[bytes]);
c /= 24;
}
return String.valueOf(value);
}
}

View file

@ -0,0 +1,40 @@
package com.itextpdf.text.factories;
import com.itextpdf.text.error_messages.MessageLocalization;
public class RomanAlphabetFactory {
public static final String getString(int index) {
if (index < 1)
throw new NumberFormatException(MessageLocalization.getComposedMessage("you.can.t.translate.a.negative.number.into.an.alphabetical.value"));
index--;
int bytes = 1;
int start = 0;
int symbols = 26;
while (index >= symbols + start) {
bytes++;
start += symbols;
symbols *= 26;
}
int c = index - start;
char[] value = new char[bytes];
while (bytes > 0) {
value[--bytes] = (char)(97 + c % 26);
c /= 26;
}
return new String(value);
}
public static final String getLowerCaseString(int index) {
return getString(index);
}
public static final String getUpperCaseString(int index) {
return getString(index).toUpperCase();
}
public static final String getString(int index, boolean lowercase) {
if (lowercase)
return getLowerCaseString(index);
return getUpperCaseString(index);
}
}

View file

@ -0,0 +1,65 @@
package com.itextpdf.text.factories;
public class RomanNumberFactory {
private static class RomanDigit {
public char digit;
public int value;
public boolean pre;
RomanDigit(char digit, int value, boolean pre) {
this.digit = digit;
this.value = value;
this.pre = pre;
}
}
private static final RomanDigit[] roman = new RomanDigit[] { new RomanDigit('m', 1000, false), new RomanDigit('d', 500, false), new RomanDigit('c', 100, true), new RomanDigit('l', 50, false), new RomanDigit('x', 10, true), new RomanDigit('v', 5, false), new RomanDigit('i', 1, true) };
public static final String getString(int index) {
StringBuffer buf = new StringBuffer();
if (index < 0) {
buf.append('-');
index = -index;
}
if (index > 3000) {
buf.append('|');
buf.append(getString(index / 1000));
buf.append('|');
index -= index / 1000 * 1000;
}
int pos = 0;
while (true) {
RomanDigit dig = roman[pos];
while (index >= dig.value) {
buf.append(dig.digit);
index -= dig.value;
}
if (index <= 0)
break;
int j = pos;
while (!(roman[++j]).pre);
if (index + (roman[j]).value >= dig.value) {
buf.append((roman[j]).digit).append(dig.digit);
index -= dig.value - (roman[j]).value;
}
pos++;
}
return buf.toString();
}
public static final String getLowerCaseString(int index) {
return getString(index);
}
public static final String getUpperCaseString(int index) {
return getString(index).toUpperCase();
}
public static final String getString(int index, boolean lowercase) {
if (lowercase)
return getLowerCaseString(index);
return getUpperCaseString(index);
}
}

View file

@ -0,0 +1,90 @@
package com.itextpdf.text.html;
import com.itextpdf.text.BaseColor;
import java.util.HashSet;
import java.util.Set;
@Deprecated
public final class HtmlEncoder {
private static final String[] HTML_CODE = new String[256];
static {
for (int m = 0; m < 10; m++)
HTML_CODE[m] = "&#00" + m + ";";
for (int k = 10; k < 32; k++)
HTML_CODE[k] = "&#0" + k + ";";
for (int j = 32; j < 128; j++)
HTML_CODE[j] = String.valueOf((char)j);
HTML_CODE[9] = "\t";
HTML_CODE[10] = "<br />\n";
HTML_CODE[34] = "&quot;";
HTML_CODE[38] = "&amp;";
HTML_CODE[60] = "&lt;";
HTML_CODE[62] = "&gt;";
for (int i = 128; i < 256; i++)
HTML_CODE[i] = "&#" + i + ";";
}
public static String encode(String string) {
int n = string.length();
StringBuffer buffer = new StringBuffer();
for (int i = 0; i < n; i++) {
char character = string.charAt(i);
if (character < 'Ā') {
buffer.append(HTML_CODE[character]);
} else {
buffer.append("&#").append(character).append(';');
}
}
return buffer.toString();
}
public static String encode(BaseColor color) {
StringBuffer buffer = new StringBuffer("#");
if (color.getRed() < 16)
buffer.append('0');
buffer.append(Integer.toString(color.getRed(), 16));
if (color.getGreen() < 16)
buffer.append('0');
buffer.append(Integer.toString(color.getGreen(), 16));
if (color.getBlue() < 16)
buffer.append('0');
buffer.append(Integer.toString(color.getBlue(), 16));
return buffer.toString();
}
public static String getAlignment(int alignment) {
switch (alignment) {
case 0:
return "left";
case 1:
return "center";
case 2:
return "right";
case 3:
case 8:
return "justify";
case 4:
return "top";
case 5:
return "middle";
case 6:
return "bottom";
case 7:
return "baseline";
}
return "";
}
private static final Set<String> NEWLINETAGS = new HashSet<String>();
static {
NEWLINETAGS.add("p");
NEWLINETAGS.add("blockquote");
NEWLINETAGS.add("br");
}
public static boolean isNewLineTag(String tag) {
return NEWLINETAGS.contains(tag);
}
}

View file

@ -0,0 +1,166 @@
package com.itextpdf.text.html;
@Deprecated
public class HtmlTags {
public static final String A = "a";
public static final String B = "b";
public static final String BODY = "body";
public static final String BLOCKQUOTE = "blockquote";
public static final String BR = "br";
public static final String DIV = "div";
public static final String EM = "em";
public static final String FONT = "font";
public static final String H1 = "h1";
public static final String H2 = "h2";
public static final String H3 = "h3";
public static final String H4 = "h4";
public static final String H5 = "h5";
public static final String H6 = "h6";
public static final String HR = "hr";
public static final String I = "i";
public static final String IMG = "img";
public static final String LI = "li";
public static final String OL = "ol";
public static final String P = "p";
public static final String PRE = "pre";
public static final String S = "s";
public static final String SPAN = "span";
public static final String STRIKE = "strike";
public static final String STRONG = "strong";
public static final String SUB = "sub";
public static final String SUP = "sup";
public static final String TABLE = "table";
public static final String TD = "td";
public static final String TH = "th";
public static final String TR = "tr";
public static final String U = "u";
public static final String UL = "ul";
public static final String ALIGN = "align";
public static final String BGCOLOR = "bgcolor";
public static final String BORDER = "border";
public static final String CELLPADDING = "cellpadding";
public static final String COLSPAN = "colspan";
public static final String EXTRAPARASPACE = "extraparaspace";
public static final String ENCODING = "encoding";
public static final String FACE = "face";
public static final String HEIGHT = "height";
public static final String HREF = "href";
public static final String HYPHENATION = "hyphenation";
public static final String IMAGEPATH = "image_path";
public static final String INDENT = "indent";
public static final String LEADING = "leading";
public static final String ROWSPAN = "rowspan";
public static final String SIZE = "size";
public static final String SRC = "src";
public static final String VALIGN = "valign";
public static final String WIDTH = "width";
public static final String ALIGN_LEFT = "left";
public static final String ALIGN_CENTER = "center";
public static final String ALIGN_RIGHT = "right";
public static final String ALIGN_JUSTIFY = "justify";
public static final String ALIGN_JUSTIFIED_ALL = "JustifyAll";
public static final String ALIGN_TOP = "top";
public static final String ALIGN_MIDDLE = "middle";
public static final String ALIGN_BOTTOM = "bottom";
public static final String ALIGN_BASELINE = "baseline";
public static final String STYLE = "style";
public static final String CLASS = "class";
public static final String COLOR = "color";
public static final String FONTFAMILY = "font-family";
public static final String FONTSIZE = "font-size";
public static final String FONTSTYLE = "font-style";
public static final String FONTWEIGHT = "font-weight";
public static final String LINEHEIGHT = "line-height";
public static final String PADDINGLEFT = "padding-left";
public static final String TEXTALIGN = "text-align";
public static final String TEXTDECORATION = "text-decoration";
public static final String VERTICALALIGN = "vertical-align";
public static final String BOLD = "bold";
public static final String ITALIC = "italic";
public static final String LINETHROUGH = "line-through";
public static final String NORMAL = "normal";
public static final String OBLIQUE = "oblique";
public static final String UNDERLINE = "underline";
public static final String AFTER = "after";
public static final String BEFORE = "before";
}

View file

@ -0,0 +1,209 @@
package com.itextpdf.text.html;
import com.itextpdf.text.BaseColor;
import java.util.HashMap;
import java.util.Properties;
import java.util.StringTokenizer;
@Deprecated
public class HtmlUtilities {
public static final float DEFAULT_FONT_SIZE = 12.0F;
private static HashMap<String, Float> sizes = new HashMap<String, Float>();
static {
sizes.put("xx-small", new Float(4.0F));
sizes.put("x-small", new Float(6.0F));
sizes.put("small", new Float(8.0F));
sizes.put("medium", new Float(10.0F));
sizes.put("large", new Float(13.0F));
sizes.put("x-large", new Float(18.0F));
sizes.put("xx-large", new Float(26.0F));
}
public static float parseLength(String string) {
return parseLength(string, 12.0F);
}
public static float parseLength(String string, float actualFontSize) {
if (string == null)
return 0.0F;
Float fl = sizes.get(string.toLowerCase());
if (fl != null)
return fl;
int pos = 0;
int length = string.length();
boolean ok = true;
while (ok && pos < length) {
switch (string.charAt(pos)) {
case '+':
case '-':
case '.':
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
pos++;
continue;
}
ok = false;
}
if (pos == 0)
return 0.0F;
if (pos == length)
return Float.parseFloat(string + "f");
float f = Float.parseFloat(string.substring(0, pos) + "f");
string = string.substring(pos);
if (string.startsWith("in"))
return f * 72.0F;
if (string.startsWith("cm"))
return f / 2.54F * 72.0F;
if (string.startsWith("mm"))
return f / 25.4F * 72.0F;
if (string.startsWith("pc"))
return f * 12.0F;
if (string.startsWith("em"))
return f * actualFontSize;
if (string.startsWith("ex"))
return f * actualFontSize / 2.0F;
return f;
}
public static BaseColor decodeColor(String s) {
if (s == null)
return null;
s = s.toLowerCase().trim();
try {
return WebColors.getRGBColor(s);
} catch (IllegalArgumentException iae) {
return null;
}
}
public static Properties parseAttributes(String string) {
Properties result = new Properties();
if (string == null)
return result;
StringTokenizer keyValuePairs = new StringTokenizer(string, ";");
while (keyValuePairs.hasMoreTokens()) {
StringTokenizer keyValuePair = new StringTokenizer(keyValuePairs.nextToken(), ":");
if (keyValuePair.hasMoreTokens()) {
String key = keyValuePair.nextToken().trim();
if (keyValuePair.hasMoreTokens()) {
String value = keyValuePair.nextToken().trim();
if (value.startsWith("\""))
value = value.substring(1);
if (value.endsWith("\""))
value = value.substring(0, value.length() - 1);
result.setProperty(key.toLowerCase(), value);
}
}
}
return result;
}
public static String removeComment(String string, String startComment, String endComment) {
StringBuffer result = new StringBuffer();
int pos = 0;
int end = endComment.length();
int start = string.indexOf(startComment, pos);
while (start > -1) {
result.append(string.substring(pos, start));
pos = string.indexOf(endComment, start) + end;
start = string.indexOf(startComment, pos);
}
result.append(string.substring(pos));
return result.toString();
}
public static String eliminateWhiteSpace(String content) {
StringBuffer buf = new StringBuffer();
int len = content.length();
boolean newline = false;
for (int i = 0; i < len; i++) {
char character;
switch (character = content.charAt(i)) {
case ' ':
if (!newline)
buf.append(character);
break;
case '\n':
if (i > 0) {
newline = true;
buf.append(' ');
}
break;
case '\r':
case '\t':
break;
default:
newline = false;
buf.append(character);
break;
}
}
return buf.toString();
}
public static final int[] FONTSIZES = new int[] { 8, 10, 12, 14, 18, 24, 36 };
public static int getIndexedFontSize(String value, String previous) {
int sIndex = 0;
if (value.startsWith("+") || value.startsWith("-")) {
if (previous == null)
previous = "12";
int c = (int)Float.parseFloat(previous);
for (int k = FONTSIZES.length - 1; k >= 0; k--) {
if (c >= FONTSIZES[k]) {
sIndex = k;
break;
}
}
int diff = Integer.parseInt(value.startsWith("+") ?
value.substring(1) : value);
sIndex += diff;
} else {
try {
sIndex = Integer.parseInt(value) - 1;
} catch (NumberFormatException nfe) {
sIndex = 0;
}
}
if (sIndex < 0) {
sIndex = 0;
} else if (sIndex >= FONTSIZES.length) {
sIndex = FONTSIZES.length - 1;
}
return FONTSIZES[sIndex];
}
public static int alignmentValue(String alignment) {
if (alignment == null)
return -1;
if ("center".equalsIgnoreCase(alignment))
return 1;
if ("left".equalsIgnoreCase(alignment))
return 0;
if ("right".equalsIgnoreCase(alignment))
return 2;
if ("justify".equalsIgnoreCase(alignment))
return 3;
if ("JustifyAll".equalsIgnoreCase(alignment))
return 8;
if ("top".equalsIgnoreCase(alignment))
return 4;
if ("middle".equalsIgnoreCase(alignment))
return 5;
if ("bottom".equalsIgnoreCase(alignment))
return 6;
if ("baseline".equalsIgnoreCase(alignment))
return 7;
return -1;
}
}

View file

@ -0,0 +1,232 @@
package com.itextpdf.text.html;
import com.itextpdf.text.BaseColor;
import com.itextpdf.text.error_messages.MessageLocalization;
import java.util.HashMap;
import java.util.StringTokenizer;
@Deprecated
public class WebColors extends HashMap<String, int[]> {
private static final long serialVersionUID = 3542523100813372896L;
public static final WebColors NAMES = new WebColors();
static {
NAMES.put("aliceblue", new int[] { 240, 248, 255, 255 });
NAMES.put("antiquewhite", new int[] { 250, 235, 215, 255 });
NAMES.put("aqua", new int[] { 0, 255, 255, 255 });
NAMES.put("aquamarine", new int[] { 127, 255, 212, 255 });
NAMES.put("azure", new int[] { 240, 255, 255, 255 });
NAMES.put("beige", new int[] { 245, 245, 220, 255 });
NAMES.put("bisque", new int[] { 255, 228, 196, 255 });
NAMES.put("black", new int[] { 0, 0, 0, 255 });
NAMES.put("blanchedalmond", new int[] { 255, 235, 205, 255 });
NAMES.put("blue", new int[] { 0, 0, 255, 255 });
NAMES.put("blueviolet", new int[] { 138, 43, 226, 255 });
NAMES.put("brown", new int[] { 165, 42, 42, 255 });
NAMES.put("burlywood", new int[] { 222, 184, 135, 255 });
NAMES.put("cadetblue", new int[] { 95, 158, 160, 255 });
NAMES.put("chartreuse", new int[] { 127, 255, 0, 255 });
NAMES.put("chocolate", new int[] { 210, 105, 30, 255 });
NAMES.put("coral", new int[] { 255, 127, 80, 255 });
NAMES.put("cornflowerblue", new int[] { 100, 149, 237, 255 });
NAMES.put("cornsilk", new int[] { 255, 248, 220, 255 });
NAMES.put("crimson", new int[] { 220, 20, 60, 255 });
NAMES.put("cyan", new int[] { 0, 255, 255, 255 });
NAMES.put("darkblue", new int[] { 0, 0, 139, 255 });
NAMES.put("darkcyan", new int[] { 0, 139, 139, 255 });
NAMES.put("darkgoldenrod", new int[] { 184, 134, 11, 255 });
NAMES.put("darkgray", new int[] { 169, 169, 169, 255 });
NAMES.put("darkgreen", new int[] { 0, 100, 0, 255 });
NAMES.put("darkkhaki", new int[] { 189, 183, 107, 255 });
NAMES.put("darkmagenta", new int[] { 139, 0, 139, 255 });
NAMES.put("darkolivegreen", new int[] { 85, 107, 47, 255 });
NAMES.put("darkorange", new int[] { 255, 140, 0, 255 });
NAMES.put("darkorchid", new int[] { 153, 50, 204, 255 });
NAMES.put("darkred", new int[] { 139, 0, 0, 255 });
NAMES.put("darksalmon", new int[] { 233, 150, 122, 255 });
NAMES.put("darkseagreen", new int[] { 143, 188, 143, 255 });
NAMES.put("darkslateblue", new int[] { 72, 61, 139, 255 });
NAMES.put("darkslategray", new int[] { 47, 79, 79, 255 });
NAMES.put("darkturquoise", new int[] { 0, 206, 209, 255 });
NAMES.put("darkviolet", new int[] { 148, 0, 211, 255 });
NAMES.put("deeppink", new int[] { 255, 20, 147, 255 });
NAMES.put("deepskyblue", new int[] { 0, 191, 255, 255 });
NAMES.put("dimgray", new int[] { 105, 105, 105, 255 });
NAMES.put("dodgerblue", new int[] { 30, 144, 255, 255 });
NAMES.put("firebrick", new int[] { 178, 34, 34, 255 });
NAMES.put("floralwhite", new int[] { 255, 250, 240, 255 });
NAMES.put("forestgreen", new int[] { 34, 139, 34, 255 });
NAMES.put("fuchsia", new int[] { 255, 0, 255, 255 });
NAMES.put("gainsboro", new int[] { 220, 220, 220, 255 });
NAMES.put("ghostwhite", new int[] { 248, 248, 255, 255 });
NAMES.put("gold", new int[] { 255, 215, 0, 255 });
NAMES.put("goldenrod", new int[] { 218, 165, 32, 255 });
NAMES.put("gray", new int[] { 128, 128, 128, 255 });
NAMES.put("green", new int[] { 0, 128, 0, 255 });
NAMES.put("greenyellow", new int[] { 173, 255, 47, 255 });
NAMES.put("honeydew", new int[] { 240, 255, 240, 255 });
NAMES.put("hotpink", new int[] { 255, 105, 180, 255 });
NAMES.put("indianred", new int[] { 205, 92, 92, 255 });
NAMES.put("indigo", new int[] { 75, 0, 130, 255 });
NAMES.put("ivory", new int[] { 255, 255, 240, 255 });
NAMES.put("khaki", new int[] { 240, 230, 140, 255 });
NAMES.put("lavender", new int[] { 230, 230, 250, 255 });
NAMES.put("lavenderblush", new int[] { 255, 240, 245, 255 });
NAMES.put("lawngreen", new int[] { 124, 252, 0, 255 });
NAMES.put("lemonchiffon", new int[] { 255, 250, 205, 255 });
NAMES.put("lightblue", new int[] { 173, 216, 230, 255 });
NAMES.put("lightcoral", new int[] { 240, 128, 128, 255 });
NAMES.put("lightcyan", new int[] { 224, 255, 255, 255 });
NAMES.put("lightgoldenrodyellow", new int[] { 250, 250, 210, 255 });
NAMES.put("lightgreen", new int[] { 144, 238, 144, 255 });
NAMES.put("lightgrey", new int[] { 211, 211, 211, 255 });
NAMES.put("lightpink", new int[] { 255, 182, 193, 255 });
NAMES.put("lightsalmon", new int[] { 255, 160, 122, 255 });
NAMES.put("lightseagreen", new int[] { 32, 178, 170, 255 });
NAMES.put("lightskyblue", new int[] { 135, 206, 250, 255 });
NAMES.put("lightslategray", new int[] { 119, 136, 153, 255 });
NAMES.put("lightsteelblue", new int[] { 176, 196, 222, 255 });
NAMES.put("lightyellow", new int[] { 255, 255, 224, 255 });
NAMES.put("lime", new int[] { 0, 255, 0, 255 });
NAMES.put("limegreen", new int[] { 50, 205, 50, 255 });
NAMES.put("linen", new int[] { 250, 240, 230, 255 });
NAMES.put("magenta", new int[] { 255, 0, 255, 255 });
NAMES.put("maroon", new int[] { 128, 0, 0, 255 });
NAMES.put("mediumaquamarine", new int[] { 102, 205, 170, 255 });
NAMES.put("mediumblue", new int[] { 0, 0, 205, 255 });
NAMES.put("mediumorchid", new int[] { 186, 85, 211, 255 });
NAMES.put("mediumpurple", new int[] { 147, 112, 219, 255 });
NAMES.put("mediumseagreen", new int[] { 60, 179, 113, 255 });
NAMES.put("mediumslateblue", new int[] { 123, 104, 238, 255 });
NAMES.put("mediumspringgreen", new int[] { 0, 250, 154, 255 });
NAMES.put("mediumturquoise", new int[] { 72, 209, 204, 255 });
NAMES.put("mediumvioletred", new int[] { 199, 21, 133, 255 });
NAMES.put("midnightblue", new int[] { 25, 25, 112, 255 });
NAMES.put("mintcream", new int[] { 245, 255, 250, 255 });
NAMES.put("mistyrose", new int[] { 255, 228, 225, 255 });
NAMES.put("moccasin", new int[] { 255, 228, 181, 255 });
NAMES.put("navajowhite", new int[] { 255, 222, 173, 255 });
NAMES.put("navy", new int[] { 0, 0, 128, 255 });
NAMES.put("oldlace", new int[] { 253, 245, 230, 255 });
NAMES.put("olive", new int[] { 128, 128, 0, 255 });
NAMES.put("olivedrab", new int[] { 107, 142, 35, 255 });
NAMES.put("orange", new int[] { 255, 165, 0, 255 });
NAMES.put("orangered", new int[] { 255, 69, 0, 255 });
NAMES.put("orchid", new int[] { 218, 112, 214, 255 });
NAMES.put("palegoldenrod", new int[] { 238, 232, 170, 255 });
NAMES.put("palegreen", new int[] { 152, 251, 152, 255 });
NAMES.put("paleturquoise", new int[] { 175, 238, 238, 255 });
NAMES.put("palevioletred", new int[] { 219, 112, 147, 255 });
NAMES.put("papayawhip", new int[] { 255, 239, 213, 255 });
NAMES.put("peachpuff", new int[] { 255, 218, 185, 255 });
NAMES.put("peru", new int[] { 205, 133, 63, 255 });
NAMES.put("pink", new int[] { 255, 192, 203, 255 });
NAMES.put("plum", new int[] { 221, 160, 221, 255 });
NAMES.put("powderblue", new int[] { 176, 224, 230, 255 });
NAMES.put("purple", new int[] { 128, 0, 128, 255 });
NAMES.put("red", new int[] { 255, 0, 0, 255 });
NAMES.put("rosybrown", new int[] { 188, 143, 143, 255 });
NAMES.put("royalblue", new int[] { 65, 105, 225, 255 });
NAMES.put("saddlebrown", new int[] { 139, 69, 19, 255 });
NAMES.put("salmon", new int[] { 250, 128, 114, 255 });
NAMES.put("sandybrown", new int[] { 244, 164, 96, 255 });
NAMES.put("seagreen", new int[] { 46, 139, 87, 255 });
NAMES.put("seashell", new int[] { 255, 245, 238, 255 });
NAMES.put("sienna", new int[] { 160, 82, 45, 255 });
NAMES.put("silver", new int[] { 192, 192, 192, 255 });
NAMES.put("skyblue", new int[] { 135, 206, 235, 255 });
NAMES.put("slateblue", new int[] { 106, 90, 205, 255 });
NAMES.put("slategray", new int[] { 112, 128, 144, 255 });
NAMES.put("snow", new int[] { 255, 250, 250, 255 });
NAMES.put("springgreen", new int[] { 0, 255, 127, 255 });
NAMES.put("steelblue", new int[] { 70, 130, 180, 255 });
NAMES.put("tan", new int[] { 210, 180, 140, 255 });
NAMES.put("teal", new int[] { 0, 128, 128, 255 });
NAMES.put("thistle", new int[] { 216, 191, 216, 255 });
NAMES.put("tomato", new int[] { 255, 99, 71, 255 });
NAMES.put("transparent", new int[] { 255, 255, 255, 0 });
NAMES.put("turquoise", new int[] { 64, 224, 208, 255 });
NAMES.put("violet", new int[] { 238, 130, 238, 255 });
NAMES.put("wheat", new int[] { 245, 222, 179, 255 });
NAMES.put("white", new int[] { 255, 255, 255, 255 });
NAMES.put("whitesmoke", new int[] { 245, 245, 245, 255 });
NAMES.put("yellow", new int[] { 255, 255, 0, 255 });
NAMES.put("yellowgreen", new int[] { 154, 205, 50, 255 });
}
private static boolean missingHashColorFormat(String colStr) {
int len = colStr.length();
if (len == 3 || len == 6) {
String match = "[0-9a-f]{" + len + "}";
return colStr.matches(match);
}
return false;
}
public static BaseColor getRGBColor(String name) {
int[] color = { 0, 0, 0, 255 };
String colorName = name.toLowerCase();
boolean colorStrWithoutHash = missingHashColorFormat(colorName);
if (colorName.startsWith("#") || colorStrWithoutHash) {
if (!colorStrWithoutHash)
colorName = colorName.substring(1);
if (colorName.length() == 3) {
String red = colorName.substring(0, 1);
color[0] = Integer.parseInt(red + red, 16);
String green = colorName.substring(1, 2);
color[1] = Integer.parseInt(green + green, 16);
String blue = colorName.substring(2);
color[2] = Integer.parseInt(blue + blue, 16);
return new BaseColor(color[0], color[1], color[2], color[3]);
}
if (colorName.length() == 6) {
color[0] = Integer.parseInt(colorName.substring(0, 2), 16);
color[1] = Integer.parseInt(colorName.substring(2, 4), 16);
color[2] = Integer.parseInt(colorName.substring(4), 16);
return new BaseColor(color[0], color[1], color[2], color[3]);
}
throw new IllegalArgumentException(
MessageLocalization.getComposedMessage("unknown.color.format.must.be.rgb.or.rrggbb", new Object[0]));
}
if (colorName.startsWith("rgb(")) {
String delim = "rgb(), \t\r\n\f";
StringTokenizer tok = new StringTokenizer(colorName, "rgb(), \t\r\n\f");
for (int k = 0; k < 3; k++) {
if (tok.hasMoreElements()) {
color[k] = getRGBChannelValue(tok.nextToken());
color[k] = Math.max(0, color[k]);
color[k] = Math.min(255, color[k]);
}
}
return new BaseColor(color[0], color[1], color[2], color[3]);
}
if (colorName.startsWith("rgba(")) {
String delim = "rgba(), \t\r\n\f";
StringTokenizer tok = new StringTokenizer(colorName, "rgba(), \t\r\n\f");
for (int k = 0; k < 3; k++) {
if (tok.hasMoreElements()) {
color[k] = getRGBChannelValue(tok.nextToken());
color[k] = Math.max(0, color[k]);
color[k] = Math.min(255, color[k]);
}
}
if (tok.hasMoreElements())
color[3] = (int)((double)(255.0F * Float.parseFloat(tok.nextToken())) + 0.5D);
return new BaseColor(color[0], color[1], color[2], color[3]);
}
if (!NAMES.containsKey(colorName))
throw new IllegalArgumentException(
MessageLocalization.getComposedMessage("color.not.found", new String[] { colorName }));
color = NAMES.get(colorName);
return new BaseColor(color[0], color[1], color[2], color[3]);
}
private static int getRGBChannelValue(String rgbChannel) {
if (rgbChannel.endsWith("%"))
return Integer.parseInt(rgbChannel.substring(0,
rgbChannel.length() - 1)) * 255 / 100;
return Integer.parseInt(rgbChannel);
}
}

View file

@ -0,0 +1,100 @@
package com.itextpdf.text.html.simpleparser;
import com.itextpdf.text.Chunk;
import com.itextpdf.text.Element;
import com.itextpdf.text.ElementListener;
import com.itextpdf.text.Phrase;
import com.itextpdf.text.TextElementArray;
import com.itextpdf.text.html.HtmlUtilities;
import com.itextpdf.text.pdf.PdfPCell;
import java.util.List;
@Deprecated
public class CellWrapper implements TextElementArray {
private final PdfPCell cell;
private float width;
private boolean percentage;
public CellWrapper(String tag, ChainedProperties chain) {
this.cell = createPdfPCell(tag, chain);
String value = chain.getProperty("width");
if (value != null) {
value = value.trim();
if (value.endsWith("%")) {
this.percentage = true;
value = value.substring(0, value.length() - 1);
}
this.width = Float.parseFloat(value);
}
}
public PdfPCell createPdfPCell(String tag, ChainedProperties chain) {
PdfPCell cell = new PdfPCell((Phrase)null);
String value = chain.getProperty("colspan");
if (value != null)
cell.setColspan(Integer.parseInt(value));
value = chain.getProperty("rowspan");
if (value != null)
cell.setRowspan(Integer.parseInt(value));
if (tag.equals("th"))
cell.setHorizontalAlignment(1);
value = chain.getProperty("align");
if (value != null)
cell.setHorizontalAlignment(HtmlUtilities.alignmentValue(value));
value = chain.getProperty("valign");
cell.setVerticalAlignment(5);
if (value != null)
cell.setVerticalAlignment(HtmlUtilities.alignmentValue(value));
value = chain.getProperty("border");
float border = 0.0F;
if (value != null)
border = Float.parseFloat(value);
cell.setBorderWidth(border);
value = chain.getProperty("cellpadding");
if (value != null)
cell.setPadding(Float.parseFloat(value));
cell.setUseDescender(true);
value = chain.getProperty("bgcolor");
cell.setBackgroundColor(HtmlUtilities.decodeColor(value));
return cell;
}
public PdfPCell getCell() {
return this.cell;
}
public float getWidth() {
return this.width;
}
public boolean isPercentage() {
return this.percentage;
}
public boolean add(Element o) {
this.cell.addElement(o);
return true;
}
public List<Chunk> getChunks() {
return null;
}
public boolean isContent() {
return false;
}
public boolean isNestable() {
return false;
}
public boolean process(ElementListener listener) {
return false;
}
public int type() {
return 0;
}
}

View file

@ -0,0 +1,70 @@
package com.itextpdf.text.html.simpleparser;
import com.itextpdf.text.html.HtmlUtilities;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
@Deprecated
public class ChainedProperties {
private static final class TagAttributes {
final String tag;
final Map<String, String> attrs;
TagAttributes(String tag, Map<String, String> attrs) {
this.tag = tag;
this.attrs = attrs;
}
}
public List<TagAttributes> chain = new ArrayList<TagAttributes>();
public String getProperty(String key) {
for (int k = this.chain.size() - 1; k >= 0; k--) {
TagAttributes p = this.chain.get(k);
Map<String, String> attrs = p.attrs;
String ret = attrs.get(key);
if (ret != null)
return ret;
}
return null;
}
public boolean hasProperty(String key) {
for (int k = this.chain.size() - 1; k >= 0; k--) {
TagAttributes p = this.chain.get(k);
Map<String, String> attrs = p.attrs;
if (attrs.containsKey(key))
return true;
}
return false;
}
public void addToChain(String tag, Map<String, String> props) {
adjustFontSize(props);
this.chain.add(new TagAttributes(tag, props));
}
public void removeChain(String tag) {
for (int k = this.chain.size() - 1; k >= 0; k--) {
if (tag.equals(((TagAttributes)this.chain.get(k)).tag)) {
this.chain.remove(k);
return;
}
}
}
protected void adjustFontSize(Map<String, String> attrs) {
String value = attrs.get("size");
if (value == null)
return;
if (value.endsWith("pt")) {
attrs.put("size",
value.substring(0, value.length() - 2));
return;
}
String old = getProperty("size");
attrs.put("size", Integer.toString(HtmlUtilities.getIndexedFontSize(value, old)));
}
}

View file

@ -0,0 +1,263 @@
package com.itextpdf.text.html.simpleparser;
import com.itextpdf.text.BaseColor;
import com.itextpdf.text.Chunk;
import com.itextpdf.text.DocListener;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Font;
import com.itextpdf.text.FontFactory;
import com.itextpdf.text.FontProvider;
import com.itextpdf.text.Image;
import com.itextpdf.text.List;
import com.itextpdf.text.ListItem;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.html.HtmlUtilities;
import com.itextpdf.text.pdf.HyphenationAuto;
import com.itextpdf.text.pdf.HyphenationEvent;
import com.itextpdf.text.pdf.draw.LineSeparator;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.StringTokenizer;
@Deprecated
public class ElementFactory {
private FontProvider provider = FontFactory.getFontImp();
public void setFontProvider(FontProvider provider) {
this.provider = provider;
}
public FontProvider getFontProvider() {
return this.provider;
}
public Font getFont(ChainedProperties chain) {
String face = chain.getProperty("face");
if (face == null || face.trim().length() == 0)
face = chain.getProperty("font-family");
if (face != null) {
StringTokenizer tok = new StringTokenizer(face, ",");
while (tok.hasMoreTokens()) {
face = tok.nextToken().trim();
if (face.startsWith("\""))
face = face.substring(1);
if (face.endsWith("\""))
face = face.substring(0, face.length() - 1);
if (this.provider.isRegistered(face))
break;
}
}
String encoding = chain.getProperty("encoding");
if (encoding == null)
encoding = "Cp1252";
String value = chain.getProperty("size");
float size = 12.0F;
if (value != null)
size = Float.parseFloat(value);
int style = 0;
String decoration = chain.getProperty("text-decoration");
if (decoration != null && decoration.trim().length() != 0)
if ("underline".equals(decoration)) {
style |= 0x4;
} else if ("line-through".equals(decoration)) {
style |= 0x8;
}
if (chain.hasProperty("i"))
style |= 0x2;
if (chain.hasProperty("b"))
style |= 0x1;
if (chain.hasProperty("u"))
style |= 0x4;
if (chain.hasProperty("s"))
style |= 0x8;
BaseColor color = HtmlUtilities.decodeColor(chain.getProperty("color"));
return this.provider.getFont(face, encoding, true, size, style, color);
}
public Chunk createChunk(String content, ChainedProperties chain) {
Font font = getFont(chain);
Chunk ck = new Chunk(content, font);
if (chain.hasProperty("sub")) {
ck.setTextRise(-font.getSize() / 2.0F);
} else if (chain.hasProperty("sup")) {
ck.setTextRise(font.getSize() / 2.0F);
}
ck.setHyphenation(getHyphenation(chain));
return ck;
}
public Paragraph createParagraph(ChainedProperties chain) {
Paragraph paragraph = new Paragraph();
updateElement(paragraph, chain);
return paragraph;
}
public ListItem createListItem(ChainedProperties chain) {
ListItem item = new ListItem();
updateElement(item, chain);
return item;
}
protected void updateElement(Paragraph paragraph, ChainedProperties chain) {
String value = chain.getProperty("align");
paragraph.setAlignment(HtmlUtilities.alignmentValue(value));
paragraph.setHyphenation(getHyphenation(chain));
setParagraphLeading(paragraph, chain.getProperty("leading"));
value = chain.getProperty("after");
if (value != null)
try {
paragraph.setSpacingBefore(Float.parseFloat(value));
} catch (Exception e) {}
value = chain.getProperty("after");
if (value != null)
try {
paragraph.setSpacingAfter(Float.parseFloat(value));
} catch (Exception e) {}
value = chain.getProperty("extraparaspace");
if (value != null)
try {
paragraph.setExtraParagraphSpace(Float.parseFloat(value));
} catch (Exception e) {}
value = chain.getProperty("indent");
if (value != null)
try {
paragraph.setIndentationLeft(Float.parseFloat(value));
} catch (Exception e) {}
}
protected static void setParagraphLeading(Paragraph paragraph, String leading) {
if (leading == null) {
paragraph.setLeading(0.0F, 1.5F);
return;
}
try {
StringTokenizer tk = new StringTokenizer(leading, " ,");
String v = tk.nextToken();
float v1 = Float.parseFloat(v);
if (!tk.hasMoreTokens()) {
paragraph.setLeading(v1, 0.0F);
return;
}
v = tk.nextToken();
float v2 = Float.parseFloat(v);
paragraph.setLeading(v1, v2);
} catch (Exception e) {
paragraph.setLeading(0.0F, 1.5F);
}
}
public HyphenationEvent getHyphenation(ChainedProperties chain) {
int leftMin;
String value = chain.getProperty("hyphenation");
if (value == null || value.length() == 0)
return null;
int pos = value.indexOf('_');
if (pos == -1)
return new HyphenationAuto(value, null, 2, 2);
String lang = value.substring(0, pos);
String country = value.substring(pos + 1);
pos = country.indexOf(',');
if (pos == -1)
return new HyphenationAuto(lang, country, 2, 2);
int rightMin = 2;
value = country.substring(pos + 1);
country = country.substring(0, pos);
pos = value.indexOf(',');
if (pos == -1) {
leftMin = Integer.parseInt(value);
} else {
leftMin = Integer.parseInt(value.substring(0, pos));
rightMin = Integer.parseInt(value.substring(pos + 1));
}
return new HyphenationAuto(lang, country, leftMin, rightMin);
}
public LineSeparator createLineSeparator(Map<String, String> attrs, float offset) {
float lineWidth = 1.0F;
String size = attrs.get("size");
if (size != null) {
float tmpSize = HtmlUtilities.parseLength(size, 12.0F);
if (tmpSize > 0.0F)
lineWidth = tmpSize;
}
String width = attrs.get("width");
float percentage = 100.0F;
if (width != null) {
float tmpWidth = HtmlUtilities.parseLength(width, 12.0F);
if (tmpWidth > 0.0F)
percentage = tmpWidth;
if (!width.endsWith("%"))
percentage = 100.0F;
}
BaseColor lineColor = null;
int align = HtmlUtilities.alignmentValue(attrs.get("align"));
return new LineSeparator(lineWidth, percentage, lineColor, align, offset);
}
public Image createImage(String src, Map<String, String> attrs, ChainedProperties chain, DocListener document, ImageProvider img_provider, HashMap<String, Image> img_store, String img_baseurl) throws DocumentException, IOException {
Image img = null;
if (img_provider != null)
img = img_provider.getImage(src, attrs, chain, document);
if (img == null && img_store != null) {
Image tim = img_store.get(src);
if (tim != null)
img = Image.getInstance(tim);
}
if (img != null)
return img;
if (!src.startsWith("http") && img_baseurl != null) {
src = img_baseurl + src;
} else if (img == null && !src.startsWith("http")) {
String path = chain.getProperty("image_path");
if (path == null)
path = "";
src = new File(path, src).getPath();
}
img = Image.getInstance(src);
if (img == null)
return null;
float actualFontSize = HtmlUtilities.parseLength(
chain.getProperty("size"), 12.0F);
if (actualFontSize <= 0.0F)
actualFontSize = 12.0F;
String width = attrs.get("width");
float widthInPoints = HtmlUtilities.parseLength(width, actualFontSize);
String height = attrs.get("height");
float heightInPoints = HtmlUtilities.parseLength(height, actualFontSize);
if (widthInPoints > 0.0F && heightInPoints > 0.0F) {
img.scaleAbsolute(widthInPoints, heightInPoints);
} else if (widthInPoints > 0.0F) {
heightInPoints = img.getHeight() * widthInPoints / img.getWidth();
img.scaleAbsolute(widthInPoints, heightInPoints);
} else if (heightInPoints > 0.0F) {
widthInPoints = img.getWidth() * heightInPoints / img.getHeight();
img.scaleAbsolute(widthInPoints, heightInPoints);
}
String before = chain.getProperty("before");
if (before != null)
img.setSpacingBefore(Float.parseFloat(before));
String after = chain.getProperty("after");
if (after != null)
img.setSpacingAfter(Float.parseFloat(after));
img.setWidthPercentage(0.0F);
return img;
}
public List createList(String tag, ChainedProperties chain) {
List list;
if ("ul".equalsIgnoreCase(tag)) {
list = new List(false);
list.setListSymbol("");
} else {
list = new List(true);
}
try {
list.setIndentationLeft(new Float(chain.getProperty("indent")).floatValue());
} catch (Exception e) {
list.setAutoindent(true);
}
return list;
}
}

View file

@ -0,0 +1,12 @@
package com.itextpdf.text.html.simpleparser;
import com.itextpdf.text.DocumentException;
import java.io.IOException;
import java.util.Map;
@Deprecated
public interface HTMLTagProcessor {
void startElement(HTMLWorker paramHTMLWorker, String paramString, Map<String, String> paramMap) throws DocumentException, IOException;
void endElement(HTMLWorker paramHTMLWorker, String paramString) throws DocumentException;
}

View file

@ -0,0 +1,268 @@
package com.itextpdf.text.html.simpleparser;
import com.itextpdf.text.DocumentException;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
@Deprecated
public class HTMLTagProcessors extends HashMap<String, HTMLTagProcessor> {
public HTMLTagProcessors() {
put("a", A);
put("b", EM_STRONG_STRIKE_SUP_SUP);
put("body", DIV);
put("br", BR);
put("div", DIV);
put("em", EM_STRONG_STRIKE_SUP_SUP);
put("font", SPAN);
put("h1", H);
put("h2", H);
put("h3", H);
put("h4", H);
put("h5", H);
put("h6", H);
put("hr", HR);
put("i", EM_STRONG_STRIKE_SUP_SUP);
put("img", IMG);
put("li", LI);
put("ol", UL_OL);
put("p", DIV);
put("pre", PRE);
put("s", EM_STRONG_STRIKE_SUP_SUP);
put("span", SPAN);
put("strike", EM_STRONG_STRIKE_SUP_SUP);
put("strong", EM_STRONG_STRIKE_SUP_SUP);
put("sub", EM_STRONG_STRIKE_SUP_SUP);
put("sup", EM_STRONG_STRIKE_SUP_SUP);
put("table", TABLE);
put("td", TD);
put("th", TD);
put("tr", TR);
put("u", EM_STRONG_STRIKE_SUP_SUP);
put("ul", UL_OL);
}
public static final HTMLTagProcessor EM_STRONG_STRIKE_SUP_SUP = new HTMLTagProcessor() {
public void startElement(HTMLWorker worker, String tag, Map<String, String> attrs) {
tag = mapTag(tag);
attrs.put(tag, null);
worker.updateChain(tag, attrs);
}
public void endElement(HTMLWorker worker, String tag) {
tag = mapTag(tag);
worker.updateChain(tag);
}
private String mapTag(String tag) {
if ("em".equalsIgnoreCase(tag))
return "i";
if ("strong".equalsIgnoreCase(tag))
return "b";
if ("strike".equalsIgnoreCase(tag))
return "s";
return tag;
}
};
public static final HTMLTagProcessor A = new HTMLTagProcessor() {
public void startElement(HTMLWorker worker, String tag, Map<String, String> attrs) {
worker.updateChain(tag, attrs);
worker.flushContent();
}
public void endElement(HTMLWorker worker, String tag) {
worker.processLink();
worker.updateChain(tag);
}
};
public static final HTMLTagProcessor BR = new HTMLTagProcessor() {
public void startElement(HTMLWorker worker, String tag, Map<String, String> attrs) {
worker.newLine();
}
public void endElement(HTMLWorker worker, String tag) {}
};
public static final HTMLTagProcessor UL_OL = new HTMLTagProcessor() {
public void startElement(HTMLWorker worker, String tag, Map<String, String> attrs) throws DocumentException {
worker.carriageReturn();
if (worker.isPendingLI())
worker.endElement("li");
worker.setSkipText(true);
worker.updateChain(tag, attrs);
worker.pushToStack(worker.createList(tag));
}
public void endElement(HTMLWorker worker, String tag) throws DocumentException {
worker.carriageReturn();
if (worker.isPendingLI())
worker.endElement("li");
worker.setSkipText(false);
worker.updateChain(tag);
worker.processList();
}
};
public static final HTMLTagProcessor HR = new HTMLTagProcessor() {
public void startElement(HTMLWorker worker, String tag, Map<String, String> attrs) throws DocumentException {
worker.carriageReturn();
worker.pushToStack(worker.createLineSeparator(attrs));
}
public void endElement(HTMLWorker worker, String tag) {}
};
public static final HTMLTagProcessor SPAN = new HTMLTagProcessor() {
public void startElement(HTMLWorker worker, String tag, Map<String, String> attrs) {
worker.updateChain(tag, attrs);
}
public void endElement(HTMLWorker worker, String tag) {
worker.updateChain(tag);
}
};
public static final HTMLTagProcessor H = new HTMLTagProcessor() {
public void startElement(HTMLWorker worker, String tag, Map<String, String> attrs) throws DocumentException {
worker.carriageReturn();
if (!attrs.containsKey("size")) {
int v = 7 - Integer.parseInt(tag.substring(1));
attrs.put("size", Integer.toString(v));
}
worker.updateChain(tag, attrs);
}
public void endElement(HTMLWorker worker, String tag) throws DocumentException {
worker.carriageReturn();
worker.updateChain(tag);
}
};
public static final HTMLTagProcessor LI = new HTMLTagProcessor() {
public void startElement(HTMLWorker worker, String tag, Map<String, String> attrs) throws DocumentException {
worker.carriageReturn();
if (worker.isPendingLI())
worker.endElement(tag);
worker.setSkipText(false);
worker.setPendingLI(true);
worker.updateChain(tag, attrs);
worker.pushToStack(worker.createListItem());
}
public void endElement(HTMLWorker worker, String tag) throws DocumentException {
worker.carriageReturn();
worker.setPendingLI(false);
worker.setSkipText(true);
worker.updateChain(tag);
worker.processListItem();
}
};
public static final HTMLTagProcessor PRE = new HTMLTagProcessor() {
public void startElement(HTMLWorker worker, String tag, Map<String, String> attrs) throws DocumentException {
worker.carriageReturn();
if (!attrs.containsKey("face"))
attrs.put("face", "Courier");
worker.updateChain(tag, attrs);
worker.setInsidePRE(true);
}
public void endElement(HTMLWorker worker, String tag) throws DocumentException {
worker.carriageReturn();
worker.updateChain(tag);
worker.setInsidePRE(false);
}
};
public static final HTMLTagProcessor DIV = new HTMLTagProcessor() {
public void startElement(HTMLWorker worker, String tag, Map<String, String> attrs) throws DocumentException {
worker.carriageReturn();
worker.updateChain(tag, attrs);
}
public void endElement(HTMLWorker worker, String tag) throws DocumentException {
worker.carriageReturn();
worker.updateChain(tag);
}
};
public static final HTMLTagProcessor TABLE = new HTMLTagProcessor() {
public void startElement(HTMLWorker worker, String tag, Map<String, String> attrs) throws DocumentException {
worker.carriageReturn();
TableWrapper table = new TableWrapper(attrs);
worker.pushToStack(table);
worker.pushTableState();
worker.setPendingTD(false);
worker.setPendingTR(false);
worker.setSkipText(true);
attrs.remove("align");
attrs.put("colspan", "1");
attrs.put("rowspan", "1");
worker.updateChain(tag, attrs);
}
public void endElement(HTMLWorker worker, String tag) throws DocumentException {
worker.carriageReturn();
if (worker.isPendingTR())
worker.endElement("tr");
worker.updateChain(tag);
worker.processTable();
worker.popTableState();
worker.setSkipText(false);
}
};
public static final HTMLTagProcessor TR = new HTMLTagProcessor() {
public void startElement(HTMLWorker worker, String tag, Map<String, String> attrs) throws DocumentException {
worker.carriageReturn();
if (worker.isPendingTR())
worker.endElement(tag);
worker.setSkipText(true);
worker.setPendingTR(true);
worker.updateChain(tag, attrs);
}
public void endElement(HTMLWorker worker, String tag) throws DocumentException {
worker.carriageReturn();
if (worker.isPendingTD())
worker.endElement("td");
worker.setPendingTR(false);
worker.updateChain(tag);
worker.processRow();
worker.setSkipText(true);
}
};
public static final HTMLTagProcessor TD = new HTMLTagProcessor() {
public void startElement(HTMLWorker worker, String tag, Map<String, String> attrs) throws DocumentException {
worker.carriageReturn();
if (worker.isPendingTD())
worker.endElement(tag);
worker.setSkipText(false);
worker.setPendingTD(true);
worker.updateChain("td", attrs);
worker.pushToStack(worker.createCell(tag));
}
public void endElement(HTMLWorker worker, String tag) throws DocumentException {
worker.carriageReturn();
worker.setPendingTD(false);
worker.updateChain("td");
worker.setSkipText(true);
}
};
public static final HTMLTagProcessor IMG = new HTMLTagProcessor() {
public void startElement(HTMLWorker worker, String tag, Map<String, String> attrs) throws DocumentException, IOException {
worker.updateChain(tag, attrs);
worker.processImage(worker.createImage(attrs), attrs);
worker.updateChain(tag);
}
public void endElement(HTMLWorker worker, String tag) {}
};
private static final long serialVersionUID = -959260811961222824L;
}

View file

@ -0,0 +1,490 @@
package com.itextpdf.text.html.simpleparser;
import com.itextpdf.text.Chunk;
import com.itextpdf.text.DocListener;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Element;
import com.itextpdf.text.ExceptionConverter;
import com.itextpdf.text.FontProvider;
import com.itextpdf.text.Image;
import com.itextpdf.text.List;
import com.itextpdf.text.ListItem;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.Phrase;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.TextElementArray;
import com.itextpdf.text.html.HtmlUtilities;
import com.itextpdf.text.log.Logger;
import com.itextpdf.text.log.LoggerFactory;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.draw.LineSeparator;
import com.itextpdf.text.xml.simpleparser.SimpleXMLDocHandler;
import com.itextpdf.text.xml.simpleparser.SimpleXMLParser;
import java.io.IOException;
import java.io.Reader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Stack;
@Deprecated
public class HTMLWorker implements SimpleXMLDocHandler, DocListener {
private static Logger LOGGER = LoggerFactory.getLogger(HTMLWorker.class);
protected DocListener document;
protected Map<String, HTMLTagProcessor> tags;
private StyleSheet style = new StyleSheet();
public HTMLWorker(DocListener document) {
this(document, null, null);
}
public HTMLWorker(DocListener document, Map<String, HTMLTagProcessor> tags, StyleSheet style) {
this.document = document;
setSupportedTags(tags);
setStyleSheet(style);
}
public void setSupportedTags(Map<String, HTMLTagProcessor> tags) {
if (tags == null)
tags = new HTMLTagProcessors();
this.tags = tags;
}
public void setStyleSheet(StyleSheet style) {
if (style == null)
style = new StyleSheet();
this.style = style;
}
public void parse(Reader reader) throws IOException {
LOGGER.info("Please note, there is a more extended version of the HTMLWorker available in the iText XMLWorker");
SimpleXMLParser.parse(this, null, reader, true);
}
protected Stack<Element> stack = new Stack<Element>();
protected Paragraph currentParagraph;
private final ChainedProperties chain = new ChainedProperties();
public static final String IMG_PROVIDER = "img_provider";
public static final String IMG_PROCESSOR = "img_interface";
public static final String IMG_STORE = "img_static";
public static final String IMG_BASEURL = "img_baseurl";
public static final String FONT_PROVIDER = "font_factory";
public static final String LINK_PROVIDER = "alink_interface";
public void startDocument() {
HashMap<String, String> attrs = new HashMap<String, String>();
this.style.applyStyle("body", attrs);
this.chain.addToChain("body", attrs);
}
public void startElement(String tag, Map<String, String> attrs) {
HTMLTagProcessor htmlTag = this.tags.get(tag);
if (htmlTag == null)
return;
this.style.applyStyle(tag, attrs);
StyleSheet.resolveStyleAttribute(attrs, this.chain);
try {
htmlTag.startElement(this, tag, attrs);
} catch (DocumentException e) {
throw new ExceptionConverter(e);
} catch (IOException e) {
throw new ExceptionConverter(e);
}
}
public void text(String content) {
if (this.skipText)
return;
if (this.currentParagraph == null)
this.currentParagraph = createParagraph();
if (!this.insidePRE) {
if (content.trim().length() == 0 && content.indexOf(' ') < 0)
return;
content = HtmlUtilities.eliminateWhiteSpace(content);
}
Chunk chunk = createChunk(content);
this.currentParagraph.add(chunk);
}
public void endElement(String tag) {
HTMLTagProcessor htmlTag = this.tags.get(tag);
if (htmlTag == null)
return;
try {
htmlTag.endElement(this, tag);
} catch (DocumentException e) {
throw new ExceptionConverter(e);
}
}
public void endDocument() {
try {
for (int k = 0; k < this.stack.size(); k++)
this.document.add(this.stack.elementAt(k));
if (this.currentParagraph != null)
this.document.add(this.currentParagraph);
this.currentParagraph = null;
} catch (Exception e) {
throw new ExceptionConverter(e);
}
}
public void newLine() {
if (this.currentParagraph == null)
this.currentParagraph = new Paragraph();
this.currentParagraph.add(createChunk("\n"));
}
public void carriageReturn() throws DocumentException {
if (this.currentParagraph == null)
return;
if (this.stack.empty()) {
this.document.add(this.currentParagraph);
} else {
Element obj = this.stack.pop();
if (obj instanceof TextElementArray) {
TextElementArray current = (TextElementArray)obj;
current.add(this.currentParagraph);
}
this.stack.push(obj);
}
this.currentParagraph = null;
}
public void flushContent() {
pushToStack(this.currentParagraph);
this.currentParagraph = new Paragraph();
}
public void pushToStack(Element element) {
if (element != null)
this.stack.push(element);
}
public void updateChain(String tag, Map<String, String> attrs) {
this.chain.addToChain(tag, attrs);
}
public void updateChain(String tag) {
this.chain.removeChain(tag);
}
private Map<String, Object> providers = new HashMap<String, Object>();
public void setProviders(Map<String, Object> providers) {
if (providers == null)
return;
this.providers = providers;
FontProvider ff = null;
if (providers != null)
ff = (FontProvider)providers.get("font_factory");
if (ff != null)
this.factory.setFontProvider(ff);
}
private final ElementFactory factory = new ElementFactory();
public Chunk createChunk(String content) {
return this.factory.createChunk(content, this.chain);
}
public Paragraph createParagraph() {
return this.factory.createParagraph(this.chain);
}
public List createList(String tag) {
return this.factory.createList(tag, this.chain);
}
public ListItem createListItem() {
return this.factory.createListItem(this.chain);
}
public LineSeparator createLineSeparator(Map<String, String> attrs) {
return this.factory.createLineSeparator(attrs, this.currentParagraph.getLeading() / 2.0F);
}
public Image createImage(Map<String, String> attrs) throws DocumentException, IOException {
String src = attrs.get("src");
if (src == null)
return null;
Image img = this.factory.createImage(src, attrs, this.chain, this.document, (ImageProvider)
this.providers.get("img_provider"), (ImageStore)
this.providers.get("img_static"), (String)
this.providers.get("img_baseurl"));
return img;
}
public CellWrapper createCell(String tag) {
return new CellWrapper(tag, this.chain);
}
public void processLink() {
if (this.currentParagraph == null)
this.currentParagraph = new Paragraph();
LinkProcessor i = (LinkProcessor)this.providers.get("alink_interface");
if (i == null || !i.process(this.currentParagraph, this.chain)) {
String href = this.chain.getProperty("href");
if (href != null)
for (Chunk ck : this.currentParagraph.getChunks())
ck.setAnchor(href);
}
if (this.stack.isEmpty()) {
Paragraph tmp = new Paragraph(new Phrase(this.currentParagraph));
this.currentParagraph = tmp;
} else {
Paragraph tmp = (Paragraph)this.stack.pop();
tmp.add(new Phrase(this.currentParagraph));
this.currentParagraph = tmp;
}
}
public void processList() throws DocumentException {
if (this.stack.empty())
return;
Element obj = this.stack.pop();
if (!(obj instanceof List)) {
this.stack.push(obj);
return;
}
if (this.stack.empty()) {
this.document.add(obj);
} else {
((TextElementArray)this.stack.peek()).add(obj);
}
}
public void processListItem() throws DocumentException {
if (this.stack.empty())
return;
Element obj = this.stack.pop();
if (!(obj instanceof ListItem)) {
this.stack.push(obj);
return;
}
if (this.stack.empty()) {
this.document.add(obj);
return;
}
ListItem item = (ListItem)obj;
Element list = this.stack.pop();
if (!(list instanceof List)) {
this.stack.push(list);
return;
}
((List)list).add(item);
item.adjustListSymbolFont();
this.stack.push(list);
}
public void processImage(Image img, Map<String, String> attrs) throws DocumentException {
ImageProcessor processor = (ImageProcessor)this.providers.get("img_interface");
if (processor == null || !processor.process(img, attrs, this.chain, this.document)) {
String align = attrs.get("align");
if (align != null)
carriageReturn();
if (this.currentParagraph == null)
this.currentParagraph = createParagraph();
this.currentParagraph.add(new Chunk(img, 0.0F, 0.0F, true));
this.currentParagraph.setAlignment(HtmlUtilities.alignmentValue(align));
if (align != null)
carriageReturn();
}
}
public void processTable() throws DocumentException {
TableWrapper table = (TableWrapper)this.stack.pop();
PdfPTable tb = table.createTable();
tb.setSplitRows(true);
if (this.stack.empty()) {
this.document.add(tb);
} else {
((TextElementArray)this.stack.peek()).add(tb);
}
}
public void processRow() {
ArrayList<PdfPCell> row = new ArrayList<PdfPCell>();
ArrayList<Float> cellWidths = new ArrayList<Float>();
boolean percentage = false;
float totalWidth = 0.0F;
int zeroWidth = 0;
TableWrapper table = null;
while (true) {
Element obj = this.stack.pop();
if (obj instanceof CellWrapper) {
CellWrapper cell = (CellWrapper)obj;
float width = cell.getWidth();
cellWidths.add(new Float(width));
percentage |= cell.isPercentage();
if (width == 0.0F) {
zeroWidth++;
} else {
totalWidth += width;
}
row.add(cell.getCell());
}
if (obj instanceof TableWrapper) {
table = (TableWrapper)obj;
table.addRow(row);
if (cellWidths.size() > 0) {
totalWidth = 100.0F - totalWidth;
Collections.reverse(cellWidths);
float[] widths = new float[cellWidths.size()];
boolean hasZero = false;
for (int i = 0; i < widths.length; i++) {
widths[i] = (Float)cellWidths.get(i);
if (widths[i] == 0.0F && percentage && zeroWidth > 0)
widths[i] = totalWidth / (float)zeroWidth;
if (widths[i] == 0.0F) {
hasZero = true;
break;
}
}
if (!hasZero)
table.setColWidths(widths);
}
this.stack.push(table);
return;
}
}
}
private final Stack<boolean[]> tableState = new Stack<boolean[]>();
private boolean pendingTR = false;
private boolean pendingTD = false;
private boolean pendingLI = false;
private boolean insidePRE = false;
protected boolean skipText = false;
protected java.util.List<Element> objectList;
public void pushTableState() {
this.tableState.push(new boolean[] { this.pendingTR, this.pendingTD });
}
public void popTableState() {
boolean[] state = this.tableState.pop();
this.pendingTR = state[0];
this.pendingTD = state[1];
}
public boolean isPendingTR() {
return this.pendingTR;
}
public void setPendingTR(boolean pendingTR) {
this.pendingTR = pendingTR;
}
public boolean isPendingTD() {
return this.pendingTD;
}
public void setPendingTD(boolean pendingTD) {
this.pendingTD = pendingTD;
}
public boolean isPendingLI() {
return this.pendingLI;
}
public void setPendingLI(boolean pendingLI) {
this.pendingLI = pendingLI;
}
public boolean isInsidePRE() {
return this.insidePRE;
}
public void setInsidePRE(boolean insidePRE) {
this.insidePRE = insidePRE;
}
public boolean isSkipText() {
return this.skipText;
}
public void setSkipText(boolean skipText) {
this.skipText = skipText;
}
public static java.util.List<Element> parseToList(Reader reader, StyleSheet style) throws IOException {
return parseToList(reader, style, null);
}
public static java.util.List<Element> parseToList(Reader reader, StyleSheet style, HashMap<String, Object> providers) throws IOException {
return parseToList(reader, style, null, providers);
}
public static java.util.List<Element> parseToList(Reader reader, StyleSheet style, Map<String, HTMLTagProcessor> tags, HashMap<String, Object> providers) throws IOException {
HTMLWorker worker = new HTMLWorker(null, tags, style);
worker.document = worker;
worker.setProviders(providers);
worker.objectList = new ArrayList<Element>();
worker.parse(reader);
return worker.objectList;
}
public boolean add(Element element) throws DocumentException {
this.objectList.add(element);
return true;
}
public void close() {}
public boolean newPage() {
return true;
}
public void open() {}
public void resetPageCount() {}
public boolean setMarginMirroring(boolean marginMirroring) {
return false;
}
public boolean setMarginMirroringTopBottom(boolean marginMirroring) {
return false;
}
public boolean setMargins(float marginLeft, float marginRight, float marginTop, float marginBottom) {
return true;
}
public void setPageCount(int pageN) {}
public boolean setPageSize(Rectangle pageSize) {
return true;
}
@Deprecated
public void setInterfaceProps(HashMap<String, Object> providers) {
setProviders(providers);
}
@Deprecated
public Map<String, Object> getInterfaceProps() {
return this.providers;
}
}

View file

@ -0,0 +1,10 @@
package com.itextpdf.text.html.simpleparser;
import com.itextpdf.text.DocListener;
import com.itextpdf.text.Image;
import java.util.Map;
@Deprecated
public interface ImageProcessor {
boolean process(Image paramImage, Map<String, String> paramMap, ChainedProperties paramChainedProperties, DocListener paramDocListener);
}

View file

@ -0,0 +1,10 @@
package com.itextpdf.text.html.simpleparser;
import com.itextpdf.text.DocListener;
import com.itextpdf.text.Image;
import java.util.Map;
@Deprecated
public interface ImageProvider {
Image getImage(String paramString, Map<String, String> paramMap, ChainedProperties paramChainedProperties, DocListener paramDocListener);
}

View file

@ -0,0 +1,9 @@
package com.itextpdf.text.html.simpleparser;
import com.itextpdf.text.Image;
import java.util.HashMap;
@Deprecated
public class ImageStore extends HashMap<String, Image> {
private static final long serialVersionUID = -148924031490995024L;
}

View file

@ -0,0 +1,8 @@
package com.itextpdf.text.html.simpleparser;
import com.itextpdf.text.Paragraph;
@Deprecated
public interface LinkProcessor {
boolean process(Paragraph paramParagraph, ChainedProperties paramChainedProperties);
}

View file

@ -0,0 +1,141 @@
package com.itextpdf.text.html.simpleparser;
import com.itextpdf.text.BaseColor;
import com.itextpdf.text.html.HtmlUtilities;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
@Deprecated
public class StyleSheet {
protected Map<String, Map<String, String>> tagMap = new HashMap<String, Map<String, String>>();
protected Map<String, Map<String, String>> classMap = new HashMap<String, Map<String, String>>();
public void loadTagStyle(String tag, Map<String, String> attrs) {
this.tagMap.put(tag.toLowerCase(), attrs);
}
public void loadTagStyle(String tag, String key, String value) {
tag = tag.toLowerCase();
Map<String, String> styles = this.tagMap.get(tag);
if (styles == null) {
styles = new HashMap<String, String>();
this.tagMap.put(tag, styles);
}
styles.put(key, value);
}
public void loadStyle(String className, HashMap<String, String> attrs) {
this.classMap.put(className.toLowerCase(), attrs);
}
public void loadStyle(String className, String key, String value) {
className = className.toLowerCase();
Map<String, String> styles = this.classMap.get(className);
if (styles == null) {
styles = new HashMap<String, String>();
this.classMap.put(className, styles);
}
styles.put(key, value);
}
public void applyStyle(String tag, Map<String, String> attrs) {
Map<String, String> map = this.tagMap.get(tag.toLowerCase());
if (map != null) {
Map<String, String> map1 = new HashMap<String, String>(map);
map1.putAll(attrs);
attrs.putAll(map1);
}
String cm = attrs.get("class");
if (cm == null)
return;
map = this.classMap.get(cm.toLowerCase());
if (map == null)
return;
attrs.remove("class");
Map<String, String> temp = new HashMap<String, String>(map);
temp.putAll(attrs);
attrs.putAll(temp);
}
public static void resolveStyleAttribute(Map<String, String> h, ChainedProperties chain) {
String style = h.get("style");
if (style == null)
return;
Properties prop = HtmlUtilities.parseAttributes(style);
for (Object element : prop.keySet()) {
String key = (String)element;
if (key.equals("font-family")) {
h.put("face", prop.getProperty(key));
continue;
}
if (key.equals("font-size")) {
float actualFontSize = HtmlUtilities.parseLength(
chain.getProperty("size"), 12.0F);
if (actualFontSize <= 0.0F)
actualFontSize = 12.0F;
h.put("size", Float.toString(HtmlUtilities.parseLength(
prop.getProperty(key), actualFontSize)) + "pt");
continue;
}
if (key.equals("font-style")) {
String ss = prop.getProperty(key).trim().toLowerCase();
if (ss.equals("italic") || ss.equals("oblique"))
h.put("i", null);
continue;
}
if (key.equals("font-weight")) {
String ss = prop.getProperty(key).trim().toLowerCase();
if (ss.equals("bold") || ss.equals("700") || ss.equals("800") ||
ss.equals("900"))
h.put("b", null);
continue;
}
if (key.equals("text-decoration")) {
String ss = prop.getProperty(key).trim().toLowerCase();
if (ss.equals("underline"))
h.put("u", null);
continue;
}
if (key.equals("color")) {
BaseColor c = HtmlUtilities.decodeColor(prop.getProperty(key));
if (c != null) {
int hh = c.getRGB();
String hs = Integer.toHexString(hh);
hs = "000000" + hs;
hs = "#" + hs.substring(hs.length() - 6);
h.put("color", hs);
}
continue;
}
if (key.equals("line-height")) {
String ss = prop.getProperty(key).trim();
float actualFontSize = HtmlUtilities.parseLength(
chain.getProperty("size"), 12.0F);
if (actualFontSize <= 0.0F)
actualFontSize = 12.0F;
float v = HtmlUtilities.parseLength(prop.getProperty(key), actualFontSize);
if (ss.endsWith("%")) {
h.put("leading", "0," + (v / 100.0F));
return;
}
if ("normal".equalsIgnoreCase(ss)) {
h.put("leading", "0,1.5");
return;
}
h.put("leading", v + ",0");
continue;
}
if (key.equals("text-align")) {
String ss = prop.getProperty(key).trim().toLowerCase();
h.put("align", ss);
continue;
}
if (key.equals("padding-left")) {
String ss = prop.getProperty(key).trim().toLowerCase();
h.put("indent", Float.toString(HtmlUtilities.parseLength(ss)));
}
}
}
}

View file

@ -0,0 +1,90 @@
package com.itextpdf.text.html.simpleparser;
import com.itextpdf.text.Chunk;
import com.itextpdf.text.Element;
import com.itextpdf.text.ElementListener;
import com.itextpdf.text.html.HtmlUtilities;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Deprecated
public class TableWrapper implements Element {
private final Map<String, String> styles = new HashMap<String, String>();
private final List<List<PdfPCell>> rows = new ArrayList<List<PdfPCell>>();
private float[] colWidths;
public TableWrapper(Map<String, String> attrs) {
this.styles.putAll(attrs);
}
public void addRow(List<PdfPCell> row) {
if (row != null) {
Collections.reverse(row);
this.rows.add(row);
row = null;
}
}
public void setColWidths(float[] colWidths) {
this.colWidths = colWidths;
}
public PdfPTable createTable() {
if (this.rows.isEmpty())
return new PdfPTable(1);
int ncol = 0;
for (PdfPCell pc : this.rows.get(0))
ncol += pc.getColspan();
PdfPTable table = new PdfPTable(ncol);
String width = this.styles.get("width");
if (width == null) {
table.setWidthPercentage(100.0F);
} else if (width.endsWith("%")) {
table.setWidthPercentage(Float.parseFloat(width.substring(0, width.length() - 1)));
} else {
table.setTotalWidth(Float.parseFloat(width));
table.setLockedWidth(true);
}
String alignment = this.styles.get("align");
int align = 0;
if (alignment != null)
align = HtmlUtilities.alignmentValue(alignment);
table.setHorizontalAlignment(align);
try {
if (this.colWidths != null)
table.setWidths(this.colWidths);
} catch (Exception e) {}
for (List<PdfPCell> col : this.rows) {
for (PdfPCell pc : col)
table.addCell(pc);
}
return table;
}
public List<Chunk> getChunks() {
return null;
}
public boolean isContent() {
return false;
}
public boolean isNestable() {
return false;
}
public boolean process(ElementListener listener) {
return false;
}
public int type() {
return 0;
}
}

View file

@ -0,0 +1,38 @@
package com.itextpdf.text.io;
import java.io.IOException;
class ArrayRandomAccessSource implements RandomAccessSource {
private byte[] array;
public ArrayRandomAccessSource(byte[] array) {
if (array == null)
throw new NullPointerException();
this.array = array;
}
public int get(long offset) {
if (offset >= (long)this.array.length)
return -1;
return 0xFF & this.array[(int)offset];
}
public int get(long offset, byte[] bytes, int off, int len) {
if (this.array == null)
throw new IllegalStateException("Already closed");
if (offset >= (long)this.array.length)
return -1;
if (offset + (long)len > (long)this.array.length)
len = (int)((long)this.array.length - offset);
System.arraycopy(this.array, (int)offset, bytes, off, len);
return len;
}
public long length() {
return (long)this.array.length;
}
public void close() throws IOException {
this.array = null;
}
}

View file

@ -0,0 +1,69 @@
package com.itextpdf.text.io;
import java.io.IOException;
import java.lang.reflect.Method;
import java.nio.BufferUnderflowException;
import java.nio.ByteBuffer;
import java.security.AccessController;
import java.security.PrivilegedAction;
class ByteBufferRandomAccessSource implements RandomAccessSource {
private final ByteBuffer byteBuffer;
public ByteBufferRandomAccessSource(ByteBuffer byteBuffer) {
this.byteBuffer = byteBuffer;
}
public int get(long position) throws IOException {
if (position > Integer.MAX_VALUE)
throw new IllegalArgumentException("Position must be less than Integer.MAX_VALUE");
try {
if (position >= (long)this.byteBuffer.limit())
return -1;
byte b = this.byteBuffer.get((int)position);
int n = b & 0xFF;
return n;
} catch (BufferUnderflowException e) {
return -1;
}
}
public int get(long position, byte[] bytes, int off, int len) throws IOException {
if (position > Integer.MAX_VALUE)
throw new IllegalArgumentException("Position must be less than Integer.MAX_VALUE");
if (position >= (long)this.byteBuffer.limit())
return -1;
this.byteBuffer.position((int)position);
int bytesFromThisBuffer = Math.min(len, this.byteBuffer.remaining());
this.byteBuffer.get(bytes, off, bytesFromThisBuffer);
return bytesFromThisBuffer;
}
public long length() {
return (long)this.byteBuffer.limit();
}
public void close() throws IOException {
clean(this.byteBuffer);
}
private static boolean clean(final ByteBuffer buffer) {
if (buffer == null || !buffer.isDirect())
return false;
Boolean b = AccessController.<Boolean>doPrivileged(new PrivilegedAction<Boolean>() {
public Boolean run() {
Boolean success = Boolean.FALSE;
try {
Method getCleanerMethod = buffer.getClass().getMethod("cleaner", null);
getCleanerMethod.setAccessible(true);
Object cleaner = getCleanerMethod.invoke(buffer, null);
Method clean = cleaner.getClass().getMethod("clean", null);
clean.invoke(cleaner, null);
success = Boolean.TRUE;
} catch (Exception e) {}
return success;
}
});
return b;
}
}

View file

@ -0,0 +1,35 @@
package com.itextpdf.text.io;
import java.io.IOException;
import java.nio.channels.FileChannel;
public class FileChannelRandomAccessSource implements RandomAccessSource {
private final FileChannel channel;
private final MappedChannelRandomAccessSource source;
public FileChannelRandomAccessSource(FileChannel channel) throws IOException {
this.channel = channel;
if (channel.size() == 0L)
throw new IOException("File size is 0 bytes");
this.source = new MappedChannelRandomAccessSource(channel, 0L, channel.size());
this.source.open();
}
public void close() throws IOException {
this.source.close();
this.channel.close();
}
public int get(long position) throws IOException {
return this.source.get(position);
}
public int get(long position, byte[] bytes, int off, int len) throws IOException {
return this.source.get(position, bytes, off, len);
}
public long length() {
return this.source.length();
}
}

View file

@ -0,0 +1,46 @@
package com.itextpdf.text.io;
import java.io.IOException;
public class GetBufferedRandomAccessSource implements RandomAccessSource {
private final RandomAccessSource source;
private final byte[] getBuffer;
private long getBufferStart = -1L;
private long getBufferEnd = -1L;
public GetBufferedRandomAccessSource(RandomAccessSource source) {
this.source = source;
this.getBuffer = new byte[(int)Math.min(Math.max(source.length() / 4L, 1L), 4096L)];
this.getBufferStart = -1L;
this.getBufferEnd = -1L;
}
public int get(long position) throws IOException {
if (position < this.getBufferStart || position > this.getBufferEnd) {
int count = this.source.get(position, this.getBuffer, 0, this.getBuffer.length);
if (count == -1)
return -1;
this.getBufferStart = position;
this.getBufferEnd = position + (long)count - 1L;
}
int bufPos = (int)(position - this.getBufferStart);
return 0xFF & this.getBuffer[bufPos];
}
public int get(long position, byte[] bytes, int off, int len) throws IOException {
return this.source.get(position, bytes, off, len);
}
public long length() {
return this.source.length();
}
public void close() throws IOException {
this.source.close();
this.getBufferStart = -1L;
this.getBufferEnd = -1L;
}
}

View file

@ -0,0 +1,109 @@
package com.itextpdf.text.io;
import java.io.IOException;
class GroupedRandomAccessSource implements RandomAccessSource {
private final SourceEntry[] sources;
private SourceEntry currentSourceEntry;
private final long size;
public GroupedRandomAccessSource(RandomAccessSource[] sources) throws IOException {
this.sources = new SourceEntry[sources.length];
long totalSize = 0L;
for (int i = 0; i < sources.length; i++) {
this.sources[i] = new SourceEntry(i, sources[i], totalSize);
totalSize += sources[i].length();
}
this.size = totalSize;
this.currentSourceEntry = this.sources[sources.length - 1];
sourceInUse(this.currentSourceEntry.source);
}
protected int getStartingSourceIndex(long offset) {
if (offset >= this.currentSourceEntry.firstByte)
return this.currentSourceEntry.index;
return 0;
}
private SourceEntry getSourceEntryForOffset(long offset) throws IOException {
if (offset >= this.size)
return null;
if (offset >= this.currentSourceEntry.firstByte && offset <= this.currentSourceEntry.lastByte)
return this.currentSourceEntry;
sourceReleased(this.currentSourceEntry.source);
int startAt = getStartingSourceIndex(offset);
for (int i = startAt; i < this.sources.length; i++) {
if (offset >= (this.sources[i]).firstByte && offset <= (this.sources[i]).lastByte) {
this.currentSourceEntry = this.sources[i];
sourceInUse(this.currentSourceEntry.source);
return this.currentSourceEntry;
}
}
return null;
}
protected void sourceReleased(RandomAccessSource source) throws IOException {}
protected void sourceInUse(RandomAccessSource source) throws IOException {}
public int get(long position) throws IOException {
SourceEntry entry = getSourceEntryForOffset(position);
if (entry == null)
return -1;
return entry.source.get(entry.offsetN(position));
}
public int get(long position, byte[] bytes, int off, int len) throws IOException {
SourceEntry entry = getSourceEntryForOffset(position);
if (entry == null)
return -1;
long offN = entry.offsetN(position);
int remaining = len;
while (remaining > 0 &&
entry != null) {
if (offN > entry.source.length())
break;
int count = entry.source.get(offN, bytes, off, remaining);
if (count == -1)
break;
off += count;
position += (long)count;
remaining -= count;
offN = 0L;
entry = getSourceEntryForOffset(position);
}
return (remaining == len) ? -1 : (len - remaining);
}
public long length() {
return this.size;
}
public void close() throws IOException {
for (SourceEntry entry : this.sources)
entry.source.close();
}
private static class SourceEntry {
final RandomAccessSource source;
final long firstByte;
final long lastByte;
final int index;
public SourceEntry(int index, RandomAccessSource source, long offset) {
this.index = index;
this.source = source;
this.firstByte = offset;
this.lastByte = offset + source.length() - 1L;
}
public long offsetN(long absoluteOffset) {
return absoluteOffset - this.firstByte;
}
}
}

View file

@ -0,0 +1,25 @@
package com.itextpdf.text.io;
import java.io.IOException;
public class IndependentRandomAccessSource implements RandomAccessSource {
private final RandomAccessSource source;
public IndependentRandomAccessSource(RandomAccessSource source) {
this.source = source;
}
public int get(long position) throws IOException {
return this.source.get(position);
}
public int get(long position, byte[] bytes, int off, int len) throws IOException {
return this.source.get(position, bytes, off, len);
}
public long length() {
return this.source.length();
}
public void close() throws IOException {}
}

View file

@ -0,0 +1,10 @@
package com.itextpdf.text.io;
import java.io.IOException;
public class MapFailedException extends IOException {
public MapFailedException(IOException e) {
super(e.getMessage());
initCause(e);
}
}

View file

@ -0,0 +1,72 @@
package com.itextpdf.text.io;
import java.io.IOException;
import java.nio.channels.FileChannel;
class MappedChannelRandomAccessSource implements RandomAccessSource {
private final FileChannel channel;
private final long offset;
private final long length;
private ByteBufferRandomAccessSource source;
public MappedChannelRandomAccessSource(FileChannel channel, long offset, long length) {
if (offset < 0L)
throw new IllegalArgumentException(offset + " is negative");
if (length <= 0L)
throw new IllegalArgumentException(length + " is zero or negative");
this.channel = channel;
this.offset = offset;
this.length = length;
this.source = null;
}
void open() throws IOException {
if (this.source != null)
return;
if (!this.channel.isOpen())
throw new IllegalStateException("Channel is closed");
try {
this.source = new ByteBufferRandomAccessSource(this.channel.map(FileChannel.MapMode.READ_ONLY, this.offset, this.length));
} catch (IOException e) {
if (exceptionIsMapFailureException(e))
throw new MapFailedException(e);
throw e;
}
}
private static boolean exceptionIsMapFailureException(IOException e) {
if (e.getMessage() != null && e.getMessage().indexOf("Map failed") >= 0)
return true;
return false;
}
public int get(long position) throws IOException {
if (this.source == null)
throw new IOException("RandomAccessSource not opened");
return this.source.get(position);
}
public int get(long position, byte[] bytes, int off, int len) throws IOException {
if (this.source == null)
throw new IOException("RandomAccessSource not opened");
return this.source.get(position, bytes, off, len);
}
public long length() {
return this.length;
}
public void close() throws IOException {
if (this.source == null)
return;
this.source.close();
this.source = null;
}
public String toString() {
return getClass().getName() + " (" + this.offset + ", " + this.length + ")";
}
}

View file

@ -0,0 +1,89 @@
package com.itextpdf.text.io;
import java.io.IOException;
import java.nio.channels.FileChannel;
import java.util.Iterator;
import java.util.LinkedList;
class PagedChannelRandomAccessSource extends GroupedRandomAccessSource implements RandomAccessSource {
public static final int DEFAULT_TOTAL_BUFSIZE = 67108864;
public static final int DEFAULT_MAX_OPEN_BUFFERS = 16;
private final int bufferSize;
private final FileChannel channel;
private final MRU<RandomAccessSource> mru;
public PagedChannelRandomAccessSource(FileChannel channel) throws IOException {
this(channel, 67108864, 16);
}
public PagedChannelRandomAccessSource(FileChannel channel, int totalBufferSize, int maxOpenBuffers) throws IOException {
super(buildSources(channel, totalBufferSize / maxOpenBuffers));
this.channel = channel;
this.bufferSize = totalBufferSize / maxOpenBuffers;
this.mru = new MRU<RandomAccessSource>(maxOpenBuffers);
}
private static RandomAccessSource[] buildSources(FileChannel channel, int bufferSize) throws IOException {
long size = channel.size();
if (size <= 0L)
throw new IOException("File size must be greater than zero");
int bufferCount = (int)(size / (long)bufferSize) + ((size % (long)bufferSize == 0L) ? 0 : 1);
MappedChannelRandomAccessSource[] sources = new MappedChannelRandomAccessSource[bufferCount];
for (int i = 0; i < bufferCount; i++) {
long pageOffset = (long)i * (long)bufferSize;
long pageLength = Math.min(size - pageOffset, (long)bufferSize);
sources[i] = new MappedChannelRandomAccessSource(channel, pageOffset, pageLength);
}
return sources;
}
protected int getStartingSourceIndex(long offset) {
return (int)(offset / (long)this.bufferSize);
}
protected void sourceReleased(RandomAccessSource source) throws IOException {
RandomAccessSource old = this.mru.enqueue(source);
if (old != null)
old.close();
}
protected void sourceInUse(RandomAccessSource source) throws IOException {
((MappedChannelRandomAccessSource)source).open();
}
public void close() throws IOException {
super.close();
this.channel.close();
}
private static class MRU<E> {
private final int limit;
private LinkedList<E> queue = new LinkedList<E>();
public MRU(int limit) {
this.limit = limit;
}
public E enqueue(E newElement) {
if (this.queue.size() > 0 && this.queue.getFirst() == newElement)
return null;
for (Iterator<E> it = this.queue.iterator(); it.hasNext(); ) {
E element = it.next();
if (newElement == element) {
it.remove();
this.queue.addFirst(newElement);
return null;
}
}
this.queue.addFirst(newElement);
if (this.queue.size() > this.limit)
return this.queue.removeLast();
return null;
}
}
}

View file

@ -0,0 +1,37 @@
package com.itextpdf.text.io;
import java.io.IOException;
import java.io.RandomAccessFile;
class RAFRandomAccessSource implements RandomAccessSource {
private final RandomAccessFile raf;
private final long length;
public RAFRandomAccessSource(RandomAccessFile raf) throws IOException {
this.raf = raf;
this.length = raf.length();
}
public int get(long position) throws IOException {
if (position > this.raf.length())
return -1;
this.raf.seek(position);
return this.raf.read();
}
public int get(long position, byte[] bytes, int off, int len) throws IOException {
if (position > this.length)
return -1;
this.raf.seek(position);
return this.raf.read(bytes, off, len);
}
public long length() {
return this.length;
}
public void close() throws IOException {
this.raf.close();
}
}

View file

@ -0,0 +1,24 @@
package com.itextpdf.text.io;
import java.io.IOException;
import java.io.InputStream;
public class RASInputStream extends InputStream {
private final RandomAccessSource source;
private long position = 0L;
public RASInputStream(RandomAccessSource source) {
this.source = source;
}
public int read(byte[] b, int off, int len) throws IOException {
int count = this.source.get(this.position, b, off, len);
this.position += (long)count;
return count;
}
public int read() throws IOException {
return this.source.get(this.position++);
}
}

View file

@ -0,0 +1,13 @@
package com.itextpdf.text.io;
import java.io.IOException;
public interface RandomAccessSource {
int get(long paramLong) throws IOException;
int get(long paramLong, byte[] paramArrayOfbyte, int paramInt1, int paramInt2) throws IOException;
long length();
void close() throws IOException;
}

View file

@ -0,0 +1,138 @@
package com.itextpdf.text.io;
import com.itextpdf.text.error_messages.MessageLocalization;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.net.URL;
import java.nio.channels.FileChannel;
public final class RandomAccessSourceFactory {
private boolean forceRead = false;
private boolean usePlainRandomAccess = false;
private boolean exclusivelyLockFile = false;
public RandomAccessSourceFactory setForceRead(boolean forceRead) {
this.forceRead = forceRead;
return this;
}
public RandomAccessSourceFactory setUsePlainRandomAccess(boolean usePlainRandomAccess) {
this.usePlainRandomAccess = usePlainRandomAccess;
return this;
}
public RandomAccessSourceFactory setExclusivelyLockFile(boolean exclusivelyLockFile) {
this.exclusivelyLockFile = exclusivelyLockFile;
return this;
}
public RandomAccessSource createSource(byte[] data) {
return new ArrayRandomAccessSource(data);
}
public RandomAccessSource createSource(RandomAccessFile raf) throws IOException {
return new RAFRandomAccessSource(raf);
}
public RandomAccessSource createSource(URL url) throws IOException {
InputStream is = url.openStream();
try {
return createSource(is);
} finally {
try {
is.close();
} catch (IOException e) {}
}
}
public RandomAccessSource createSource(InputStream is) throws IOException {
try {
return createSource(StreamUtil.inputStreamToArray(is));
} finally {
try {
is.close();
} catch (IOException e) {}
}
}
public RandomAccessSource createBestSource(String filename) throws IOException {
File file = new File(filename);
if (!file.canRead()) {
if (filename.startsWith("file:/") ||
filename.startsWith("http://") ||
filename.startsWith("https://") ||
filename.startsWith("jar:") ||
filename.startsWith("wsjar:") ||
filename.startsWith("wsjar:") ||
filename.startsWith("vfszip:"))
return createSource(new URL(filename));
return createByReadingToMemory(filename);
}
if (this.forceRead)
return createByReadingToMemory(new FileInputStream(filename));
String openMode = this.exclusivelyLockFile ? "rw" : "r";
RandomAccessFile raf = new RandomAccessFile(file, openMode);
if (this.exclusivelyLockFile)
raf.getChannel().lock();
try {
return createBestSource(raf);
} catch (IOException e) {
try {
raf.close();
} catch (IOException iOException) {}
throw e;
} catch (RuntimeException e) {
try {
raf.close();
} catch (IOException iOException) {}
throw e;
}
}
public RandomAccessSource createBestSource(RandomAccessFile raf) throws IOException {
if (this.usePlainRandomAccess)
return new RAFRandomAccessSource(raf);
if (raf.length() <= 0L)
return new RAFRandomAccessSource(raf);
try {
return createBestSource(raf.getChannel());
} catch (MapFailedException e) {
return new RAFRandomAccessSource(raf);
}
}
public RandomAccessSource createBestSource(FileChannel channel) throws IOException {
if (channel.size() <= 67108864L)
return new GetBufferedRandomAccessSource(new FileChannelRandomAccessSource(channel));
return new GetBufferedRandomAccessSource(new PagedChannelRandomAccessSource(channel));
}
public RandomAccessSource createRanged(RandomAccessSource source, long[] ranges) throws IOException {
RandomAccessSource[] sources = new RandomAccessSource[ranges.length / 2];
for (int i = 0; i < ranges.length; i += 2)
sources[i / 2] = new WindowRandomAccessSource(source, ranges[i], ranges[i + 1]);
return new GroupedRandomAccessSource(sources);
}
private RandomAccessSource createByReadingToMemory(String filename) throws IOException {
InputStream is = StreamUtil.getResourceStream(filename);
if (is == null)
throw new IOException(MessageLocalization.getComposedMessage("1.not.found.as.file.or.resource", filename));
return createByReadingToMemory(is);
}
private RandomAccessSource createByReadingToMemory(InputStream is) throws IOException {
try {
return new ArrayRandomAccessSource(StreamUtil.inputStreamToArray(is));
} finally {
try {
is.close();
} catch (IOException e) {}
}
}
}

View file

@ -0,0 +1,62 @@
package com.itextpdf.text.io;
import java.io.ByteArrayOutputStream;
import java.io.EOFException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
public final class StreamUtil {
public static byte[] inputStreamToArray(InputStream is) throws IOException {
byte[] b = new byte[8192];
ByteArrayOutputStream out = new ByteArrayOutputStream();
while (true) {
int read = is.read(b);
if (read < 1)
break;
out.write(b, 0, read);
}
out.close();
return out.toByteArray();
}
public static void CopyBytes(RandomAccessSource source, long start, long length, OutputStream outs) throws IOException {
if (length <= 0L)
return;
long idx = start;
byte[] buf = new byte[8192];
while (length > 0L) {
long n = (long)source.get(idx, buf, 0, (int)Math.min((long)buf.length, length));
if (n <= 0L)
throw new EOFException();
outs.write(buf, 0, (int)n);
idx += n;
length -= n;
}
}
public static InputStream getResourceStream(String key) {
return getResourceStream(key, null);
}
public static InputStream getResourceStream(String key, ClassLoader loader) {
if (key.startsWith("/"))
key = key.substring(1);
InputStream is = null;
if (loader != null) {
is = loader.getResourceAsStream(key);
if (is != null)
return is;
}
try {
ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
if (contextClassLoader != null)
is = contextClassLoader.getResourceAsStream(key);
} catch (Throwable e) {}
if (is == null)
is = StreamUtil.class.getResourceAsStream("/" + key);
if (is == null)
is = ClassLoader.getSystemResourceAsStream(key);
return is;
}
}

Some files were not shown because too many files have changed in this diff Show more