pax_global_header00006660000000000000000000000064143317623240014517gustar00rootroot0000000000000052 comment=e3255ef5b2fa077c5a098f0926efe073d82371c0 jfreepdf-2.0.1/000077500000000000000000000000001433176232400133045ustar00rootroot00000000000000jfreepdf-2.0.1/.github/000077500000000000000000000000001433176232400146445ustar00rootroot00000000000000jfreepdf-2.0.1/.github/workflows/000077500000000000000000000000001433176232400167015ustar00rootroot00000000000000jfreepdf-2.0.1/.github/workflows/ci.yaml000066400000000000000000000010531433176232400201570ustar00rootroot00000000000000--- name: Java CI on: [push] jobs: test: runs-on: ${{ matrix.os }} strategy: matrix: os: [ubuntu-18.04, macOS-latest, windows-2016] java: [11, 11.0.3, 12, 13, 13.0.4, 14, 15, 16-ea] fail-fast: false max-parallel: 4 name: Test JDK ${{ matrix.java }}, ${{ matrix.os }} steps: - uses: actions/checkout@v1 - name: Set up JDK uses: actions/setup-java@v1 with: java-version: ${{ matrix.java }} - name: Test with Maven run: mvn test -B --file pom.xml ...jfreepdf-2.0.1/.gitignore000066400000000000000000000004721433176232400152770ustar00rootroot00000000000000# Compiled class file *.class # Log file *.log # BlueJ files *.ctxt # Mobile Tools for Java (J2ME) .mtj.tmp/ # Package Files # *.jar *.war *.nar *.ear *.zip *.tar.gz *.rar # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml hs_err_pid* # Maven target/ # MacOSX .DS_Storejfreepdf-2.0.1/LICENSE000066400000000000000000001045151433176232400143170ustar00rootroot00000000000000 GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The GNU General Public License is a free, copyleft license for software and other kinds of works. The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others. For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it. For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions. Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users. Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free. The precise terms and conditions for copying, distribution and modification follow. TERMS AND CONDITIONS 0. Definitions. "This License" refers to version 3 of the GNU General Public License. "Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. "The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. A "covered work" means either the unmodified Program or a work based on the Program. To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. 1. Source Code. The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work. A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. The Corresponding Source for a work in source code form is that same work. 2. Basic Permissions. All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. 3. Protecting Users' Legal Rights From Anti-Circumvention Law. No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. 4. Conveying Verbatim Copies. You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. 5. Conveying Modified Source Versions. You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: a) The work must carry prominent notices stating that you modified it, and giving a relevant date. b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices". c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. 6. Conveying Non-Source Forms. You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. "Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. 7. Additional Terms. "Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or d) Limiting the use for publicity purposes of names of licensors or authors of the material; or e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. 8. Termination. You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. 9. Acceptance Not Required for Having Copies. You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. 10. Automatic Licensing of Downstream Recipients. Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. 11. Patents. A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. 12. No Surrender of Others' Freedom. If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. 13. Use with the GNU Affero General Public License. Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such. 14. Revised Versions of this License. The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation. If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. 15. Disclaimer of Warranty. THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. Limitation of Liability. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 17. Interpretation of Sections 15 and 16. If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. END OF TERMS AND CONDITIONS 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. Copyright (C) This program is free software: you can redistribute it and/or modify it under the terms of the GNU 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 General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . Also add information on how to contact you by electronic and paper mail. If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode: Copyright (C) This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an "about box". 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 GPL, see . The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read . jfreepdf-2.0.1/README.md000066400000000000000000000052461433176232400145720ustar00rootroot00000000000000JFreePDF ======== Version 2.0.1, by David Gilbert, 6 November 2022. (C)opyright 2013-2022, by David Gilbert. All rights reserved. [![Maven Central](https://maven-badges.herokuapp.com/maven-central/org.jfree/org.jfree.pdf/badge.svg)](https://maven-badges.herokuapp.com/maven-central/org.jfree/org.jfree.pdf) Overview -------- JFreePDF is a library module for the Java(tm) platform that allows you to create content in Adobe's Portable Document Format (PDF) using the standard Java2D drawing API (`Graphics2D`). JFreePDF is light-weight, fast, and has no dependencies other than the Java runtime (11 or later). The home page for the project is: https://github.com/jfree/jfreepdf Getting Started --------------- The Javadoc page for the `PDFDocument` class gives an example of typical usage. Oracle provides tutorials for Java2D here: http://docs.oracle.com/javase/tutorial/2d/ There are some demonstration applications included in the [JFree Demos](https://github.com/jfree/jfree-demos) project. Include ------- JFreePDF is published to the Central Repository. You can include it in your projects with the following dependency: org.jfree org.jfree.pdf 2.0 JFreePDF defines the module name `org.jfree.pdf`. If you are using Java 8, an earlier version of this library (OrsonPDF) can be used instead: com.orsonpdf orsonpdf 1.9 Build ----- You can build JFreePDF from sources using Maven: mvn clean install Testing ------- `JFreePDF` is being tested using [Graphics2D Tester](https://github.com/jfree/graphics2d-tester) and produces the output shown below. ![jfreepdf-test](https://user-images.githubusercontent.com/1835893/200183395-1a9c4479-6fe1-469e-a62a-65529d9a731a.png) Dual Licensing -------------- JFreePDF is dual licensed. You can use JFreePDF under the terms of the GNU General Public License version 3 (GPLv3) or later. If you prefer not to be bound by the terms of the GPLv3, an alternative license is available to JFree sponsors. JFreePDF integrates the `Ascii85OutputStream` class written by Ben Upsavs and distributed freely under the (BSD-style) terms listed in the `Ascii85OutputStream-license.txt file`. Change History -------------- Version 2.0.1 (6 November 2022) - fix various warnings - update Maven plugin versions in pom.xml - updated JUnit to version 5.9.1. Version 2.0 (1 March 2020) - converted to a Java module; - renamed `OrsonPDF` to `JFreePDF`. jfreepdf-2.0.1/pom.xml000066400000000000000000000157741433176232400146370ustar00rootroot00000000000000 4.0.0 org.jfree org.jfree.pdf 2.0.1 jar org.jfree.pdf http://www.jfree.org JFreePDF is an API that provides a Graphics2D implementation that generates PDF output. GNU General Public License (GPL) http://www.gnu.org/licenses/gpl.txt repo scm:git:git:https://github.com/jfree/jfreepdf.git https://github.com/jfree/jfreepdf David Gilbert dave@jfree.org UTF-8 org.junit.jupiter junit-jupiter-api 5.9.1 test org.junit.jupiter junit-jupiter-engine 5.9.1 test org.apache.maven.plugins maven-clean-plugin 3.2.0 org.apache.maven.plugins maven-resources-plugin 3.3.0 ${project.build.sourceEncoding} org.apache.maven.plugins maven-compiler-plugin 3.10.1 11 11 -Xlint:unchecked ${project.build.sourceEncoding} org.apache.maven.plugins maven-jar-plugin 3.3.0 org.apache.maven.plugins maven-javadoc-plugin 3.4.1 true attach-javadoc jar maven-surefire-plugin 3.0.0-M7 maven-failsafe-plugin 3.0.0-M7 org.apache.maven.plugins maven-install-plugin 3.0.1 ossrh https://oss.sonatype.org/content/repositories/snapshots release org.apache.maven.plugins maven-gpg-plugin 1.5 sign-artifacts verify sign org.sonatype.plugins nexus-staging-maven-plugin 1.6.13 true ossrh https://oss.sonatype.org/ false org.apache.maven.plugins maven-javadoc-plugin 3.4.1 true attach-javadoc jar org.apache.maven.plugins maven-source-plugin 3.2.1 attach-sources jar-no-fork jfreepdf-2.0.1/src/000077500000000000000000000000001433176232400140735ustar00rootroot00000000000000jfreepdf-2.0.1/src/main/000077500000000000000000000000001433176232400150175ustar00rootroot00000000000000jfreepdf-2.0.1/src/main/java/000077500000000000000000000000001433176232400157405ustar00rootroot00000000000000jfreepdf-2.0.1/src/main/java/module-info.java000066400000000000000000000007051433176232400210230ustar00rootroot00000000000000/** * JFreePDF provides an implementation of the {@code Graphics2D} API that * produces output in Adobe's Portable Document Format (PDF). *

For the latest information about JFreePDF, please refer to the project page * at GitHub: https://github.com/jfree/jfreepdf */ module org.jfree.pdf { requires java.base; requires java.desktop; requires java.logging; exports org.jfree.pdf; } jfreepdf-2.0.1/src/main/java/org/000077500000000000000000000000001433176232400165275ustar00rootroot00000000000000jfreepdf-2.0.1/src/main/java/org/jfree/000077500000000000000000000000001433176232400176225ustar00rootroot00000000000000jfreepdf-2.0.1/src/main/java/org/jfree/pdf/000077500000000000000000000000001433176232400203735ustar00rootroot00000000000000jfreepdf-2.0.1/src/main/java/org/jfree/pdf/DefaultFontMapper.java000066400000000000000000000145551433176232400246300ustar00rootroot00000000000000/* ===================================================================== * JFreePDF : a fast, light-weight PDF library for the Java(tm) platform * ===================================================================== * * (C)opyright 2013-2022, by David Gilbert. All rights reserved. * * https://github.com/jfree/orsonpdf * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * If you do not wish to be bound by the terms of the GPL, an alternative * runtime license is available to JFree sponsors: * * https://github.com/sponsors/jfree * */ package org.jfree.pdf; import java.awt.Font; import java.util.HashMap; import java.util.Map; import org.jfree.pdf.internal.FontKey; import org.jfree.pdf.internal.PDFFont; /** * A class that can be used to map AWT/Java2D fonts to PDF built-in font names. * This is a very minimal way to support fonts in this {@link PDFGraphics2D} * implementation. *

* Note that there is an option to draw text as vector graphics which you can * specify using the rendering hint {@link PDFHints#KEY_DRAW_STRING_TYPE}. * This can be useful, for example, if you need to display characters (such * as the euro symbol) that are not supported by the PDF built-in fonts. * */ public class DefaultFontMapper implements FontMapper { private final Map map; /** * Creates a new instance with default mappings. */ public DefaultFontMapper() { this.map = new HashMap<>(); this.map.put(new FontKey("Dialog", false, false), PDFFont.HELVETICA); this.map.put(new FontKey("Dialog", true, false), PDFFont.HELVETICA_BOLD); this.map.put(new FontKey("Dialog", false, true), PDFFont.HELVETICA_OBLIQUE); this.map.put(new FontKey("Dialog", true, true), PDFFont.HELVETICA_BOLDOBLIQUE); this.map.put(new FontKey("Arial", false, false), PDFFont.HELVETICA); this.map.put(new FontKey("Arial", true, false), PDFFont.HELVETICA_BOLD); this.map.put(new FontKey("Arial", false, true), PDFFont.HELVETICA_OBLIQUE); this.map.put(new FontKey("Arial", true, true), PDFFont.HELVETICA_BOLDOBLIQUE); this.map.put(new FontKey("Courier", false, false), PDFFont.COURIER); this.map.put(new FontKey("Courier", true, false), PDFFont.COURIER_BOLD); this.map.put(new FontKey("Courier", false, true), PDFFont.COURIER_ITALIC); this.map.put(new FontKey("Courier", true, true), PDFFont.COURIER_BOLDITALIC); this.map.put(new FontKey("Courier_New", false, false), PDFFont.COURIER); this.map.put(new FontKey("Courier_New", true, false), PDFFont.COURIER_BOLD); this.map.put(new FontKey("Courier_New", false, true), PDFFont.COURIER_ITALIC); this.map.put(new FontKey("Courier_New", true, true), PDFFont.COURIER_BOLDITALIC); this.map.put(new FontKey("DialogInput", false, false), PDFFont.HELVETICA); this.map.put(new FontKey("DialogInput", true, false), PDFFont.HELVETICA_BOLD); this.map.put(new FontKey("DialogInput", false, true), PDFFont.HELVETICA_OBLIQUE); this.map.put(new FontKey("DialogInput", true, true), PDFFont.HELVETICA_BOLDOBLIQUE); this.map.put(new FontKey("MgOpen_Cosmetica", false, false), PDFFont.TIMES_ROMAN); this.map.put(new FontKey("MgOpen_Cosmetica", true, false), PDFFont.TIMES_BOLD); this.map.put(new FontKey("MgOpen_Cosmetica", false, true), PDFFont.TIMES_ITALIC); this.map.put(new FontKey("MgOpen_Cosmetica", true, true), PDFFont.TIMES_BOLDITALIC); this.map.put(new FontKey("Monospaced", false, false), PDFFont.COURIER); this.map.put(new FontKey("Monospaced", true, false), PDFFont.COURIER_BOLD); this.map.put(new FontKey("Monospaced", false, true), PDFFont.COURIER_ITALIC); this.map.put(new FontKey("Monospaced", true, true), PDFFont.COURIER_BOLDITALIC); this.map.put(new FontKey("Palatino", false, false), PDFFont.TIMES_ROMAN); this.map.put(new FontKey("Palatino", true, false), PDFFont.TIMES_BOLD); this.map.put(new FontKey("Palatino", false, true), PDFFont.TIMES_ITALIC); this.map.put(new FontKey("Palatino", true, true), PDFFont.TIMES_BOLDITALIC); this.map.put(new FontKey("SansSerif", false, false), PDFFont.HELVETICA); this.map.put(new FontKey("SansSerif", true, false), PDFFont.HELVETICA_BOLD); this.map.put(new FontKey("SansSerif", false, true), PDFFont.HELVETICA_OBLIQUE); this.map.put(new FontKey("SansSerif", true, true), PDFFont.HELVETICA_BOLDOBLIQUE); this.map.put(new FontKey("Serif", false, false), PDFFont.TIMES_ROMAN); this.map.put(new FontKey("Serif", true, false), PDFFont.TIMES_BOLD); this.map.put(new FontKey("Serif", false, true), PDFFont.TIMES_ITALIC); this.map.put(new FontKey("Serif", true, true), PDFFont.TIMES_BOLDITALIC); this.map.put(new FontKey("Tahoma", false, false), PDFFont.TIMES_ROMAN); this.map.put(new FontKey("Tahoma", true, false), PDFFont.TIMES_BOLD); this.map.put(new FontKey("Tahoma", false, true), PDFFont.TIMES_ITALIC); this.map.put(new FontKey("Tahoma", true, true), PDFFont.TIMES_BOLDITALIC); this.map.put(new FontKey("Times_New_Roman", false, false), PDFFont.TIMES_ROMAN); this.map.put(new FontKey("Times_New_Roman", true, false), PDFFont.TIMES_BOLD); this.map.put(new FontKey("Times_New_Roman", false, true), PDFFont.TIMES_ITALIC); this.map.put(new FontKey("Times_New_Roman", true, true), PDFFont.TIMES_BOLDITALIC); } @Override public String mapToBaseFont(Font f) { String result = this.map.get(FontKey.createFontKey(f)); if (result == null) { result = "Courier"; } return result; } } jfreepdf-2.0.1/src/main/java/org/jfree/pdf/FontMapper.java000066400000000000000000000032411433176232400233110ustar00rootroot00000000000000/* ===================================================================== * JFreePDF : a fast, light-weight PDF library for the Java(tm) platform * ===================================================================== * * (C)opyright 2013-2022, by David Gilbert. All rights reserved. * * https://github.com/jfree/orsonpdf * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * If you do not wish to be bound by the terms of the GPL, an alternative * runtime license is available to JFree sponsors: * * https://github.com/sponsors/jfree * */ package org.jfree.pdf; import java.awt.Font; /** * Maps an AWT font to a PDF built-in font. */ public interface FontMapper { /** * Returns the name of the PDF built-in font that should be used in place * of the specified AWT/Java2D font. * * @param f the font. * * @return The name of the built-in PDF font. */ String mapToBaseFont(Font f); } jfreepdf-2.0.1/src/main/java/org/jfree/pdf/PDFDocument.java000066400000000000000000000271571433176232400233620ustar00rootroot00000000000000/* ===================================================================== * JFreePDF : a fast, light-weight PDF library for the Java(tm) platform * ===================================================================== * * (C)opyright 2013-2022, by David Gilbert. All rights reserved. * * https://github.com/jfree/orsonpdf * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * If you do not wish to be bound by the terms of the GPL, an alternative * runtime license is available to JFree sponsors: * * https://github.com/sponsors/jfree * */ package org.jfree.pdf; import java.awt.geom.Rectangle2D; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import org.jfree.pdf.dictionary.Dictionary; import org.jfree.pdf.dictionary.DictionaryObject; import org.jfree.pdf.internal.PDFFont; import org.jfree.pdf.internal.Pages; import org.jfree.pdf.internal.PDFObject; import org.jfree.pdf.util.Args; import org.jfree.pdf.util.PDFUtils; /** * Represents a PDF document. The focus of this implementation is to * allow the use of the {@link PDFGraphics2D} class to generate PDF content, * typically in the following manner: *

* PDFDocument pdfDoc = new PDFDocument();
* Page page = pdfDoc.createPage(new Rectangle(612, 468));
* PDFGraphics2D g2 = page.getGraphics2D();
* g2.setPaint(Color.RED);
* g2.draw(new Rectangle(10, 10, 40, 50));
* pdfDoc.writeToFile(new File("demo.pdf"));
*

* The implementation is light-weight and works very well alongside packages * such as JFreeChart and Orson Charts. */ public class PDFDocument { private static final Logger LOGGER = Logger.getLogger( PDFDocument.class.getName()); /** Producer string. */ private static final String PRODUCER = "JFreePDF 2.0"; /** The document catalog. */ private DictionaryObject catalog; /** The outlines (placeholder, outline support is not implemented). */ private DictionaryObject outlines; /** Document info. */ private DictionaryObject info; /** The document title (can be null). */ private String title; /** The author of the document (can be null). */ private String author; /** The pages of the document. */ private Pages pages; /** A list of other objects added to the document. */ private List otherObjects; /** The next PDF object number in the document. */ private int nextNumber = 1; /** * A flag that is used to indicate that we are in DEBUG mode. In this * mode, the graphics stream for a page does not have a filter applied, so * the output can be read in a text editor. */ private boolean debug; /** * Creates a new {@code PDFDocument}, initially with no content. */ public PDFDocument() { this.catalog = new DictionaryObject(this.nextNumber++, "/Catalog"); this.outlines = new DictionaryObject(this.nextNumber++, "/Outlines"); this.info = new DictionaryObject(this.nextNumber++, "/Info"); StringBuilder producer = new StringBuilder("(").append(PRODUCER); producer.append(")"); this.info.put("Producer", producer.toString()); Date now = new Date(); String creationDateStr = "(" + PDFUtils.toDateFormat(now) + ")"; this.info.put("CreationDate", creationDateStr); this.info.put("ModDate", creationDateStr); this.outlines.put("Count", 0); this.catalog.put("Outlines", this.outlines); this.pages = new Pages(this.nextNumber++, 0, this); this.catalog.put("Pages", this.pages); this.otherObjects = new ArrayList<>(); } /** * Returns the title for the document. The default value is {@code null}. * * @return The title for the document (possibly {@code null}). */ public String getTitle() { return this.title; } /** * Sets the title for the document. * * @param title the title ({@code null} permitted). */ public void setTitle(String title) { this.title = title; if (title != null) { this.info.put("Title", "(" + title + ")"); } else { this.info.remove("Title"); } } /** * Returns the author for the document. The default value is {@code null}. * * @return The author for the document (possibly {@code null}). */ public String getAuthor() { return this.author; } /** * Sets the author for the document. * * @param author the author ({@code null} permitted). */ public void setAuthor(String author) { this.author = author; if (author != null) { this.info.put("Author", "(" + this.author + ")"); } else { this.info.remove("Author"); } } /** * Returns the debug mode flag that controls whether or not the output * stream is filtered. * * @return The debug flag. * * @since 1.4 */ public boolean isDebugMode() { return this.debug; } /** * Sets the debug MODE flag (this needs to be set before any call to * {@link #createPage(java.awt.geom.Rectangle2D)}). * * @param debug the new flag value. * * @since 1.4 */ public void setDebugMode(boolean debug) { this.debug = debug; } /** * Creates a new {@code Page}, adds it to the document, and returns * a reference to the {@code Page}. * * @param bounds the page bounds ({@code null} not permitted). * * @return The new page. */ public Page createPage(Rectangle2D bounds) { Page page = new Page(this.nextNumber++, 0, this.pages, bounds, !this.debug); this.pages.add(page); return page; } /** * Adds an object to the document. * * @param object the object ({@code null} not permitted). */ void addObject(PDFObject object) { Args.nullNotPermitted(object, "object"); this.otherObjects.add(object); } /** * Returns a new PDF object number and increments the internal counter * for the next PDF object number. This method is used to ensure that * all objects in the document are assigned a unique number. * * @return A new PDF object number. */ public int getNextNumber() { int result = this.nextNumber; this.nextNumber++; return result; } /** * Returns a byte array containing the encoding of this PDF document. * * @return A byte array containing the encoding of this PDF document. */ public byte[] getPDFBytes() { int[] xref = new int[this.nextNumber]; ByteArrayOutputStream bos = new ByteArrayOutputStream(); try { bos.write(toBytes("%PDF-1.4\n")); bos.write(new byte[] { (byte) 37, (byte) 128, (byte) 129, (byte) 130, (byte) 131, (byte) 10}); xref[this.catalog.getNumber() - 1] = bos.size(); // offset to catalog bos.write(this.catalog.toPDFBytes()); xref[this.outlines.getNumber() - 1] = bos.size(); // offset to outlines bos.write(this.outlines.toPDFBytes()); xref[this.info.getNumber() - 1] = bos.size(); // offset to info bos.write(this.info.toPDFBytes()); xref[this.pages.getNumber() - 1] = bos.size(); // offset to pages bos.write(this.pages.toPDFBytes()); for (Page page : this.pages.getPages()) { xref[page.getNumber() - 1] = bos.size(); bos.write(page.toPDFBytes()); PDFObject contents = page.getContents(); xref[contents.getNumber() - 1] = bos.size(); bos.write(contents.toPDFBytes()); } for (PDFFont font: this.pages.getFonts()) { xref[font.getNumber() - 1] = bos.size(); bos.write(font.toPDFBytes()); } for (PDFObject object: this.otherObjects) { xref[object.getNumber() - 1] = bos.size(); bos.write(object.toPDFBytes()); } xref[xref.length - 1] = bos.size(); // write the xref table bos.write(toBytes("xref\n")); bos.write(toBytes("0 " + String.valueOf(this.nextNumber) + "\n")); bos.write(toBytes("0000000000 65535 f \n")); for (int i = 0; i < this.nextNumber - 1; i++) { String offset = String.valueOf(xref[i]); int len = offset.length(); String offset10 = "0000000000".substring(len) + offset; bos.write(toBytes(offset10 + " 00000 n \n")); } // write the trailer bos.write(toBytes("trailer\n")); Dictionary trailer = new Dictionary(); trailer.put("/Size", this.nextNumber); trailer.put("/Root", this.catalog); trailer.put("/Info", this.info); bos.write(trailer.toPDFBytes()); bos.write(toBytes("startxref\n")); bos.write(toBytes(String.valueOf(xref[this.nextNumber - 1]) + "\n")); bos.write(toBytes("%%EOF")); } catch (IOException ex) { throw new RuntimeException(ex); } return bos.toByteArray(); } /** * Writes the PDF document to a file. This is not a robust method, it * exists mainly for the demo output. * * @param f the file. */ public void writeToFile(File f) { FileOutputStream fos = null; try { fos = new FileOutputStream(f); fos.write(getPDFBytes()); } catch (FileNotFoundException ex) { LOGGER.log(Level.SEVERE, null, ex); } catch (IOException ex) { LOGGER.log(Level.SEVERE, null, ex); } finally { try { if (fos != null) { fos.close(); } } catch (IOException ex) { LOGGER.log(Level.SEVERE, null, ex); } } } /** * A utility method to convert a string to US-ASCII byte format. * * @param s the string. * * @return The corresponding byte array. */ private byte[] toBytes(String s) { byte[] result = null; try { result = s.getBytes("US-ASCII"); } catch (UnsupportedEncodingException ex) { throw new RuntimeException(ex); } return result; } } jfreepdf-2.0.1/src/main/java/org/jfree/pdf/PDFGraphics2D.java000066400000000000000000001417571433176232400235350ustar00rootroot00000000000000/* ===================================================================== * JFreePDF : a fast, light-weight PDF library for the Java(tm) platform * ===================================================================== * * (C)opyright 2013-2022, by David Gilbert. All rights reserved. * * https://github.com/jfree/orsonpdf * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * If you do not wish to be bound by the terms of the GPL, an alternative * runtime license is available to JFree sponsors: * * https://github.com/sponsors/jfree * */ package org.jfree.pdf; import java.awt.AlphaComposite; import java.awt.BasicStroke; import java.awt.Color; import java.awt.Composite; import java.awt.Font; import java.awt.FontMetrics; import java.awt.GradientPaint; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.GraphicsConfiguration; import java.awt.Image; import java.awt.Paint; import java.awt.RadialGradientPaint; import java.awt.Rectangle; import java.awt.RenderingHints; import java.awt.Shape; import java.awt.Stroke; import java.awt.font.FontRenderContext; import java.awt.font.GlyphVector; import java.awt.font.TextLayout; import java.awt.geom.AffineTransform; import java.awt.geom.Arc2D; import java.awt.geom.Area; import java.awt.geom.Ellipse2D; import java.awt.geom.GeneralPath; import java.awt.geom.Line2D; import java.awt.geom.NoninvertibleTransformException; import java.awt.geom.Path2D; import java.awt.geom.Rectangle2D; import java.awt.geom.RoundRectangle2D; import java.awt.image.BufferedImage; import java.awt.image.BufferedImageOp; import java.awt.image.ImageObserver; import java.awt.image.RenderedImage; import java.awt.image.renderable.RenderableImage; import java.text.AttributedCharacterIterator; import java.text.AttributedString; import java.util.Map; import org.jfree.pdf.stream.GraphicsStream; import org.jfree.pdf.util.Args; import org.jfree.pdf.util.GraphicsUtils; /** * A {@code Graphics2D} implementation that writes to PDF format. For * typical usage, see the documentation for the {@link PDFDocument} class. *

* For some demos of the use of this class, please check out the * JFree Demos project at GitHub (https://github.com/jfree/jfree-demos). */ public final class PDFGraphics2D extends Graphics2D { int width; int height; /** Rendering hints (all ignored). */ private RenderingHints hints; private Paint paint = Color.WHITE; private Color color = Color.WHITE; private Color background = Color.WHITE; private Composite composite = AlphaComposite.getInstance( AlphaComposite.SRC_OVER, 1.0f); private Stroke stroke = new BasicStroke(1.0f); private AffineTransform transform = new AffineTransform(); /** The user clip (can be null). */ private Shape clip = null; private Font font = new Font("SansSerif", Font.PLAIN, 12); /** A hidden image used for font metrics. */ private final BufferedImage image = new BufferedImage(10, 10, BufferedImage.TYPE_INT_RGB); /** * An instance that is lazily instantiated in drawLine and then * subsequently reused to avoid creating a lot of garbage. */ private Line2D line; /** * An instance that is lazily instantiated in fillRect and then * subsequently reused to avoid creating a lot of garbage. */ Rectangle2D rect; /** * An instance that is lazily instantiated in draw/fillRoundRect and then * subsequently reused to avoid creating a lot of garbage. */ private RoundRectangle2D roundRect; /** * An instance that is lazily instantiated in draw/fillOval and then * subsequently reused to avoid creating a lot of garbage. */ private Ellipse2D oval; /** * An instance that is lazily instantiated in draw/fillArc and then * subsequently reused to avoid creating a lot of garbage. */ private Arc2D arc; /** The content created by the Graphics2D instance. */ private GraphicsStream gs; private GraphicsConfiguration deviceConfiguration; /** * The font render context. The fractional metrics flag solves the glyph * positioning issue identified by Christoph Nahr: * http://news.kynosarges.org/2014/06/28/glyph-positioning-in-jfreesvg-orsonpdf/ */ private final FontRenderContext fontRenderContext = new FontRenderContext( null, false, true); /** * When an instance is created via the {@link #create()} method, a copy * of the transform in effect is retained so it can be restored once the * child instance is disposed. See issue #4 at GitHub. */ AffineTransform originalTransform; /** * Creates a new instance of {@code PDFGraphics2D}. You won't * normally create this directly, instead you will call the * {@link Page#getGraphics2D()} method. * * @param gs the graphics stream ({@code null} not permitted). * @param width the width. * @param height the height. */ PDFGraphics2D(GraphicsStream gs, int width, int height) { this(gs, width, height, false); } /** * Creates a new instance of {@code PDFGraphics2D}. You won't * normally create this directly, instead you will call the * {@link Page#getGraphics2D()} method. * * @param gs the graphics stream ({@code null} not permitted). * @param width the width. * @param height the height. * @param skipJava2DTransform a flag that allows the PDF to Java2D * transform to be skipped (used for watermarks which are appended * to an existing stream that already has the transform). */ PDFGraphics2D(GraphicsStream gs, int width, int height, boolean skipJava2DTransform) { Args.nullNotPermitted(gs, "gs"); this.width = width; this.height = height; this.hints = new RenderingHints(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); this.gs = gs; // flip the y-axis to match the Java2D convention if (!skipJava2DTransform) { this.gs.applyTransform(AffineTransform.getTranslateInstance(0.0, height)); this.gs.applyTransform(AffineTransform.getScaleInstance(1.0, -1.0)); } this.gs.applyFont(getFont()); this.gs.applyStrokeColor(getColor()); this.gs.applyFillColor(getColor()); this.gs.applyStroke(getStroke()); } /** * Returns a new {@code PDFGraphics2D} instance that is a copy of this * instance. * * @return A new graphics object. */ @Override public Graphics create() { PDFGraphics2D copy = new PDFGraphics2D(this.gs, this.width, this.height, true); copy.setRenderingHints(getRenderingHints()); copy.setTransform(getTransform()); copy.originalTransform = getTransform(); copy.setClip(getClip()); copy.setPaint(getPaint()); copy.setColor(getColor()); copy.setComposite(getComposite()); copy.setStroke(getStroke()); copy.setFont(getFont()); copy.setBackground(getBackground()); return copy; } /** * Returns the paint used to draw or fill shapes (or text). The default * value is {@link Color#WHITE}. * * @return The paint (never {@code null}). * * @see #setPaint(java.awt.Paint) */ @Override public Paint getPaint() { return this.paint; } /** * Sets the paint used to draw or fill shapes (or text). If * {@code paint} is an instance of {@code Color}, this method will * also update the current color attribute (see {@link #getColor()}). If * you pass {@code null} to this method, it does nothing (in * accordance with the JDK specification). * * @param paint the paint ({@code null} is permitted but ignored). * * @see #getPaint() */ @Override public void setPaint(Paint paint) { if (paint == null) { return; } if (paint instanceof Color) { setColor((Color) paint); return; } this.paint = paint; if (paint instanceof GradientPaint) { GradientPaint gp = (GradientPaint) paint; this.gs.applyStrokeGradient(gp); this.gs.applyFillGradient(gp); } else if (paint instanceof RadialGradientPaint) { RadialGradientPaint rgp = (RadialGradientPaint) paint; this.gs.applyStrokeGradient(rgp); this.gs.applyFillGradient(rgp); } } /** * Returns the foreground color. This method exists for backwards * compatibility in AWT, you should normally use the {@link #getPaint()} * method instead. * * @return The foreground color (never {@code null}). * * @see #getPaint() */ @Override public Color getColor() { return this.color; } /** * Sets the foreground color. This method exists for backwards * compatibility in AWT, you should normally use the * {@link #setPaint(java.awt.Paint)} method. * * @param c the color ({@code null} permitted but ignored). * * @see #setPaint(java.awt.Paint) */ @Override public void setColor(Color c) { if (c == null || this.paint.equals(c)) { return; } this.color = c; this.paint = c; this.gs.applyStrokeColor(c); this.gs.applyFillColor(c); } /** * Returns the background color. The default value is {@link Color#BLACK}. * This is used by the {@link #clearRect(int, int, int, int)} method. * * @return The background color (possibly {@code null}). * * @see #setBackground(java.awt.Color) */ @Override public Color getBackground() { return this.background; } /** * Sets the background color. This is used by the * {@link #clearRect(int, int, int, int)} method. The reference * implementation allows {@code null} for the background color so we allow * that too (but for that case, the {@code clearRect()} method will do * nothing). * * @param color the color ({@code null} permitted). * * @see #getBackground() */ @Override public void setBackground(Color color) { this.background = color; } /** * Returns the current composite. * * @return The current composite (never {@code null}). * * @see #setComposite(java.awt.Composite) */ @Override public Composite getComposite() { return this.composite; } /** * Sets the composite (only {@code AlphaComposite} is handled). * * @param comp the composite ({@code null} not permitted). * * @see #getComposite() */ @Override public void setComposite(Composite comp) { Args.nullNotPermitted(comp, "comp"); this.composite = comp; if (comp instanceof AlphaComposite) { AlphaComposite ac = (AlphaComposite) comp; this.gs.applyComposite(ac); } else { this.gs.applyComposite(null); } } /** * Returns the current stroke (used when drawing shapes). * * @return The current stroke (never {@code null}). * * @see #setStroke(java.awt.Stroke) */ @Override public Stroke getStroke() { return this.stroke; } /** * Sets the stroke that will be used to draw shapes. Only * {@code BasicStroke} is supported. * * @param s the stroke ({@code null} not permitted). * * @see #getStroke() */ @Override public void setStroke(Stroke s) { Args.nullNotPermitted(s, "s"); if (this.stroke.equals(s)) { return; } this.stroke = s; this.gs.applyStroke(s); } /** * Returns the current value for the specified hint. See the * {@link PDFHints} class for details of the supported hints. * * @param hintKey the hint key ({@code null} permitted, but the * result will be {@code null} also). * * @return The current value for the specified hint (possibly {@code null}). * * @see #setRenderingHint(java.awt.RenderingHints.Key, java.lang.Object) */ @Override public Object getRenderingHint(RenderingHints.Key hintKey) { return this.hints.get(hintKey); } /** * Sets the value for a hint. See the {@link PDFHints} class for details * of the supported hints. * * @param hintKey the hint key. * @param hintValue the hint value. * * @see #getRenderingHint(java.awt.RenderingHints.Key) */ @Override public void setRenderingHint(RenderingHints.Key hintKey, Object hintValue) { this.hints.put(hintKey, hintValue); } /** * Returns a copy of the rendering hints. Modifying the returned copy * will have no impact on the state of this {@code Graphics2D} * instance. * * @return The rendering hints (never {@code null}). * * @see #setRenderingHints(java.util.Map) */ @Override public RenderingHints getRenderingHints() { return (RenderingHints) this.hints.clone(); } /** * Sets the rendering hints to the specified collection. * * @param hints the new set of hints ({@code null} not permitted). * * @see #getRenderingHints() */ @Override public void setRenderingHints(Map hints) { this.hints.clear(); this.hints.putAll(hints); } /** * Adds all the supplied rendering hints. * * @param hints the hints ({@code null} not permitted). */ @Override public void addRenderingHints(Map hints) { this.hints.putAll(hints); } private Shape invTransformedClip(Shape clip) { Shape result = clip; try { AffineTransform inv = this.transform.createInverse(); result = inv.createTransformedShape(clip); } catch (NoninvertibleTransformException e) { // } return result; } /** * Draws the specified shape with the current {@code paint} and * {@code stroke}. There is direct handling for {@code Line2D} * and {@code Path2D} instances. All other shapes are mapped to a * {@code GeneralPath} and then drawn (effectively as {@code Path2D} * objects). * * @param s the shape ({@code null} not permitted). * * @see #fill(java.awt.Shape) */ @Override public void draw(Shape s) { if (!(this.stroke instanceof BasicStroke)) { fill(this.stroke.createStrokedShape(s)); return; } if (s instanceof Line2D) { if (this.clip != null) { this.gs.pushGraphicsState(); this.gs.applyClip(invTransformedClip(this.clip)); this.gs.drawLine((Line2D) s); this.gs.popGraphicsState(); } else { this.gs.drawLine((Line2D) s); } } else if (s instanceof Path2D) { if (this.clip != null) { this.gs.pushGraphicsState(); this.gs.applyClip(invTransformedClip(this.clip)); this.gs.drawPath2D((Path2D) s); this.gs.popGraphicsState(); } else { this.gs.drawPath2D((Path2D) s); } } else { draw(new GeneralPath(s)); // fallback } } /** * Fills the specified shape with the current {@code paint}. There is * direct handling for {@code Path2D} instances. All other shapes are * mapped to a {@code GeneralPath} and then filled. * * @param s the shape ({@code null} not permitted). * * @see #draw(java.awt.Shape) */ @Override public void fill(Shape s) { if (s instanceof Path2D) { if (this.clip != null) { this.gs.pushGraphicsState(); this.gs.applyClip(invTransformedClip(this.clip)); this.gs.fillPath2D((Path2D) s); this.gs.popGraphicsState(); } else { this.gs.fillPath2D((Path2D) s); } } else { fill(new GeneralPath(s)); // fallback } } /** * Returns the current font used for drawing text. * * @return The current font (never {@code null}). * * @see #setFont(java.awt.Font) */ @Override public Font getFont() { return this.font; } /** * Sets the font to be used for drawing text. * * @param font the font ({@code null} is permitted but ignored). * * @see #getFont() */ @Override public void setFont(Font font) { if (font == null || this.font.equals(font)) { return; } this.font = font; this.gs.applyFont(font); } /** * Returns the font metrics for the specified font. * * @param f the font. * * @return The font metrics. */ @Override public FontMetrics getFontMetrics(Font f) { return this.image.createGraphics().getFontMetrics(f); } /** * Returns the font render context. The implementation here returns the * {@code FontRenderContext} for an image that is maintained * internally (as for {@link #getFontMetrics}). * * @return The font render context. */ @Override public FontRenderContext getFontRenderContext() { return this.fontRenderContext; } /** * Draws a string at {@code (x, y)}. The start of the text at the * baseline level will be aligned with the {@code (x, y)} point. * * @param str the string ({@code null} not permitted). * @param x the x-coordinate. * @param y the y-coordinate. * * @see #drawString(java.lang.String, float, float) */ @Override public void drawString(String str, int x, int y) { drawString(str, (float) x, (float) y); } /** * Draws a string at {@code (x, y)}. The start of the text at the * baseline level will be aligned with the {@code (x, y)} point. * * @param str the string ({@code null} not permitted). * @param x the x-coordinate. * @param y the y-coordinate. */ @Override public void drawString(String str, float x, float y) { if (str == null) { throw new NullPointerException("Null 'str' argument."); } if (str.isEmpty()) { return; // nothing to do } if (this.clip != null) { this.gs.pushGraphicsState(); this.gs.applyClip(invTransformedClip(this.clip)); } // the following hint allows the user to switch between standard // text output and drawing text as vector graphics if (!PDFHints.VALUE_DRAW_STRING_TYPE_VECTOR.equals( this.hints.get(PDFHints.KEY_DRAW_STRING_TYPE))) { this.gs.drawString(str, x, y); } else { AttributedString as = new AttributedString(str, this.font.getAttributes()); drawString(as.getIterator(), x, y); } if (this.clip != null) { this.gs.popGraphicsState(); } } /** * Draws a string of attributed characters at {@code (x, y)}. The call is * delegated to * {@link #drawString(java.text.AttributedCharacterIterator, float, float)}. * * @param iterator an iterator for the characters. * @param x the x-coordinate. * @param y the x-coordinate. */ @Override public void drawString(AttributedCharacterIterator iterator, int x, int y) { drawString(iterator, (float) x, (float) y); } /** * Draws a string of attributed characters at {@code (x, y)}. *

* LIMITATION: in the current implementation, the string is drawn * using the current font and the formatting is ignored. * * @param iterator an iterator over the characters ({@code null} not * permitted). * @param x the x-coordinate. * @param y the y-coordinate. */ @Override public void drawString(AttributedCharacterIterator iterator, float x, float y) { TextLayout layout = new TextLayout(iterator, getFontRenderContext()); layout.draw(this, x, y); } /** * Draws the specified glyph vector at the location {@code (x, y)}. * * @param g the glyph vector ({@code null} not permitted). * @param x the x-coordinate. * @param y the y-coordinate. */ @Override public void drawGlyphVector(GlyphVector g, float x, float y) { fill(g.getOutline(x, y)); } /** * Applies the translation {@code (tx, ty)}. This call is delegated * to {@link #translate(double, double)}. * * @param tx the x-translation. * @param ty the y-translation. * * @see #translate(double, double) */ @Override public void translate(int tx, int ty) { translate((double) tx, (double) ty); } /** * Applies the translation {@code (tx, ty)}. * * @param tx the x-translation. * @param ty the y-translation. */ @Override public void translate(double tx, double ty) { AffineTransform t = getTransform(); t.translate(tx, ty); setTransform(t); } /** * Applies a rotation (anti-clockwise) about {@code (0, 0)}. * * @param theta the rotation angle (in radians). */ @Override public void rotate(double theta) { AffineTransform t = getTransform(); t.rotate(theta); setTransform(t); } /** * Applies a rotation (anti-clockwise) about {@code (x, y)}. * * @param theta the rotation angle (in radians). * @param x the x-coordinate. * @param y the y-coordinate. */ @Override public void rotate(double theta, double x, double y) { translate(x, y); rotate(theta); translate(-x, -y); } /** * Applies a scale transformation. * * @param sx the x-scaling factor. * @param sy the y-scaling factor. */ @Override public void scale(double sx, double sy) { AffineTransform t = getTransform(); t.scale(sx, sy); setTransform(t); } /** * Applies a shear transformation. This is equivalent to the following * call to the {@code transform} method: * *

  • * {@code transform(AffineTransform.getShearInstance(shx, shy));} *
* * @param shx the x-shear factor. * @param shy the y-shear factor. */ @Override public void shear(double shx, double shy) { AffineTransform t = AffineTransform.getShearInstance(shx, shy); transform(t); } /** * Applies this transform to the existing transform by concatenating it. * * @param t the transform ({@code null} not permitted). */ @Override public void transform(AffineTransform t) { AffineTransform tx = getTransform(); tx.concatenate(t); setTransform(tx); } /** * Returns a copy of the current transform. * * @return A copy of the current transform (never {@code null}). * * @see #setTransform(java.awt.geom.AffineTransform) */ @Override public AffineTransform getTransform() { return (AffineTransform) this.transform.clone(); } /** * Sets the transform. * * @param t the new transform ({@code null} permitted, resets to the * identity transform). * * @see #getTransform() */ @Override public void setTransform(AffineTransform t) { if (t == null) { this.transform = new AffineTransform(); } else { this.transform = new AffineTransform(t); } this.gs.setTransform(this.transform); } /** * Returns {@code true} if the rectangle (in device space) intersects * with the shape (the interior, if {@code onStroke} is false, * otherwise the stroked outline of the shape). * * @param rect a rectangle (in device space). * @param s the shape. * @param onStroke test the stroked outline only? * * @return A boolean. */ @Override public boolean hit(Rectangle rect, Shape s, boolean onStroke) { Shape ts; if (onStroke) { ts = this.transform.createTransformedShape( this.stroke.createStrokedShape(s)); } else { ts = this.transform.createTransformedShape(s); } if (!rect.getBounds2D().intersects(ts.getBounds2D())) { return false; } Area a1 = new Area(rect); Area a2 = new Area(ts); a1.intersect(a2); return !a1.isEmpty(); } /** * Returns the device configuration associated with this {@code Graphics2D}. * * @return The graphics configuration. */ @Override public GraphicsConfiguration getDeviceConfiguration() { if (this.deviceConfiguration == null) { this.deviceConfiguration = new PDFGraphicsConfiguration(this.width, this.height); } return this.deviceConfiguration; } /** * Does nothing in this {@code PDFGraphics2D} implementation. */ @Override public void setPaintMode() { // do nothing } /** * Does nothing in this {@code PDFGraphics2D} implementation. * * @param c ignored */ @Override public void setXORMode(Color c) { // do nothing } /** * Returns the user clipping region. The initial default value is * {@code null}. * * @return The user clipping region (possibly {@code null}). * * @see #setClip(java.awt.Shape) */ @Override public Shape getClip() { if (this.clip == null) { return null; } AffineTransform inv; try { inv = this.transform.createInverse(); return inv.createTransformedShape(this.clip); } catch (NoninvertibleTransformException ex) { return null; } } /** * Sets the user clipping region. * * @param shape the new user clipping region ({@code null} permitted). * * @see #getClip() */ @Override public void setClip(Shape shape) { // null is handled fine here... this.clip = this.transform.createTransformedShape(shape); // the clip does not get applied to the PDF output immediately, // instead it is applied with each draw (or fill) operation by // pushing the current graphics state, applying the clip, doing the // draw/fill, then popping the graphics state to restore it to the // previous clip } /** * Returns the bounds of the user clipping region. If the user clipping * region is {@code null}, this method will return {@code null}. * * @return The clip bounds (possibly {@code null}). * * @see #getClip() */ @Override public Rectangle getClipBounds() { Shape s = getClip(); return s != null ? s.getBounds() : null; } /** * Clips to the intersection of the current clipping region and the * specified shape. *

* According to the Oracle API specification, this method will accept a * {@code null} argument, but there is an open bug report (since 2004) * that suggests this is wrong: *

* * http://bugs.java.com/bugdatabase/view_bug.do?bug_id=6206189 * * @param s the clip shape ({@code null} not permitted). */ @Override public void clip(Shape s) { if (this.clip == null) { setClip(s); return; } Shape ts = this.transform.createTransformedShape(s); if (!ts.intersects(this.clip.getBounds2D())) { setClip(new Rectangle2D.Double()); } else { Area a1 = new Area(ts); Area a2 = new Area(this.clip); a1.intersect(a2); this.clip = new Path2D.Double(a1); } } /** * Clips to the intersection of the current clipping region and the * specified rectangle. * * @param x the x-coordinate. * @param y the y-coordinate. * @param width the width. * @param height the height. */ @Override public void clipRect(int x, int y, int width, int height) { setRect(x, y, width, height); clip(this.rect); } /** * Sets the user clipping region to the specified rectangle. * * @param x the x-coordinate. * @param y the y-coordinate. * @param width the width. * @param height the height. * * @see #getClip() */ @Override public void setClip(int x, int y, int width, int height) { // delegate... setClip(new Rectangle(x, y, width, height)); } /** * Draws a line from {@code (x1, y1)} to {@code (x2, y2)} using * the current {@code paint} and {@code stroke}. * * @param x1 the x-coordinate of the start point. * @param y1 the y-coordinate of the start point. * @param x2 the x-coordinate of the end point. * @param y2 the x-coordinate of the end point. */ @Override public void drawLine(int x1, int y1, int x2, int y2) { if (this.line == null) { this.line = new Line2D.Double(x1, y1, x2, y2); } else { this.line.setLine(x1, y1, x2, y2); } draw(this.line); } /** * Fills the specified rectangle with the current {@code paint}. * * @param x the x-coordinate. * @param y the y-coordinate. * @param width the rectangle width. * @param height the rectangle height. */ @Override public void fillRect(int x, int y, int width, int height) { if (this.rect == null) { this.rect = new Rectangle2D.Double(x, y, width, height); } else { this.rect.setRect(x, y, width, height); } fill(this.rect); } /** * Clears the specified rectangle by filling it with the current * background color. If the background color is {@code null}, this * method will do nothing. * * @param x the x-coordinate. * @param y the y-coordinate. * @param width the width. * @param height the height. * * @see #getBackground() */ @Override public void clearRect(int x, int y, int width, int height) { if (getBackground() == null) { return; // we can't do anything } Paint saved = getPaint(); setPaint(getBackground()); fillRect(x, y, width, height); setPaint(saved); } /** * Draws a rectangle with rounded corners using the current * {@code paint} and {@code stroke}. * * @param x the x-coordinate. * @param y the y-coordinate. * @param width the width. * @param height the height. * @param arcWidth the arc-width. * @param arcHeight the arc-height. * * @see #fillRoundRect(int, int, int, int, int, int) */ @Override public void drawRoundRect(int x, int y, int width, int height, int arcWidth, int arcHeight) { setRoundRect(x, y, width, height, arcWidth, arcHeight); draw(this.roundRect); } /** * Fills a rectangle with rounded corners. * * @param x the x-coordinate. * @param y the y-coordinate. * @param width the width. * @param height the height. * @param arcWidth the arc-width. * @param arcHeight the arc-height. */ @Override public void fillRoundRect(int x, int y, int width, int height, int arcWidth, int arcHeight) { setRoundRect(x, y, width, height, arcWidth, arcHeight); fill(this.roundRect); } /** * Draws an oval framed by the rectangle {@code (x, y, width, height)} * using the current {@code paint} and {@code stroke}. * * @param x the x-coordinate. * @param y the y-coordinate. * @param width the width. * @param height the height. * * @see #fillOval(int, int, int, int) */ @Override public void drawOval(int x, int y, int width, int height) { setOval(x, y, width, height); draw(this.oval); } /** * Fills an oval framed by the rectangle {@code (x, y, width, height)}. * * @param x the x-coordinate. * @param y the y-coordinate. * @param width the width. * @param height the height. * * @see #drawOval(int, int, int, int) */ @Override public void fillOval(int x, int y, int width, int height) { setOval(x, y, width, height); fill(this.oval); } /** * Draws an arc contained within the rectangle * {@code (x, y, width, height)}, starting at {@code startAngle} * and continuing through {@code arcAngle} degrees using * the current {@code paint} and {@code stroke}. * * @param x the x-coordinate. * @param y the y-coordinate. * @param width the width. * @param height the height. * @param startAngle the start angle in degrees, 0 = 3 o'clock. * @param arcAngle the angle (anticlockwise) in degrees. * * @see #fillArc(int, int, int, int, int, int) */ @Override public void drawArc(int x, int y, int width, int height, int startAngle, int arcAngle) { setArc(x, y, width, height, startAngle, arcAngle); draw(this.arc); } /** * Fills an arc contained within the rectangle * {@code (x, y, width, height)}, starting at {@code startAngle} * and continuing through {@code arcAngle} degrees, using * the current {@code paint} * * @param x the x-coordinate. * @param y the y-coordinate. * @param width the width. * @param height the height. * @param startAngle the start angle in degrees, 0 = 3 o'clock. * @param arcAngle the angle (anticlockwise) in degrees. * * @see #drawArc(int, int, int, int, int, int) */ @Override public void fillArc(int x, int y, int width, int height, int startAngle, int arcAngle) { setArc(x, y, width, height, startAngle, arcAngle); fill(this.arc); } /** * Draws the specified multi-segment line using the current * {@code paint} and {@code stroke}. * * @param xPoints the x-points. * @param yPoints the y-points. * @param nPoints the number of points to use for the polyline. */ @Override public void drawPolyline(int[] xPoints, int[] yPoints, int nPoints) { GeneralPath p = GraphicsUtils.createPolygon(xPoints, yPoints, nPoints, false); draw(p); } /** * Draws the specified polygon using the current {@code paint} and * {@code stroke}. * * @param xPoints the x-points. * @param yPoints the y-points. * @param nPoints the number of points to use for the polygon. * * @see #fillPolygon(int[], int[], int) */ @Override public void drawPolygon(int[] xPoints, int[] yPoints, int nPoints) { GeneralPath p = GraphicsUtils.createPolygon(xPoints, yPoints, nPoints, true); draw(p); } /** * Fills the specified polygon using the current {@code paint}. * * @param xPoints the x-points. * @param yPoints the y-points. * @param nPoints the number of points to use for the polygon. * * @see #drawPolygon(int[], int[], int) */ @Override public void fillPolygon(int[] xPoints, int[] yPoints, int nPoints) { GeneralPath p = GraphicsUtils.createPolygon(xPoints, yPoints, nPoints, true); fill(p); } /** * Draws an image with the specified transform. Note that the * {@code obs} is ignored. * * @param img the image. * @param xform the transform ({@code null} permitted). * @param observer the image observer (ignored). * * @return {@code true} if the image is drawn. */ @Override public boolean drawImage(Image img, AffineTransform xform, ImageObserver observer) { AffineTransform savedTransform = getTransform(); if (xform != null) { transform(xform); } boolean result = drawImage(img, 0, 0, observer); if (xform != null) { setTransform(savedTransform); } return result; } /** * Draws the image resulting from applying the {@code BufferedImageOp} * to the specified image at the location {@code (x, y)}. * * @param img the image. * @param op the operation. * @param x the x-coordinate. * @param y the y-coordinate. */ @Override public void drawImage(BufferedImage img, BufferedImageOp op, int x, int y) { BufferedImage imageToDraw = img; if (op != null) { imageToDraw = op.filter(img, null); } drawImage(imageToDraw, new AffineTransform(1f, 0f, 0f, 1f, x, y), null); } /** * Draws the rendered image. When {@code img} is {@code null} this method * does nothing. * * @param img the image ({@code null} permitted). * @param xform the transform. */ @Override public void drawRenderedImage(RenderedImage img, AffineTransform xform) { if (img == null) { // to match the behaviour specified in the JDK return; } BufferedImage bi = GraphicsUtils.convertRenderedImage(img); drawImage(bi, xform, null); } /** * Draws the renderable image. * * @param img the renderable image. * @param xform the transform. */ @Override public void drawRenderableImage(RenderableImage img, AffineTransform xform) { RenderedImage ri = img.createDefaultRendering(); drawRenderedImage(ri, xform); } /** * Draws an image at the location {@code (x, y)}. Note that the * {@code observer} is ignored. * * @param img the image ({@code null} permitted...method will do nothing). * @param x the x-coordinate. * @param y the y-coordinate. * @param observer ignored. * * @return {@code true} if the image is drawn. */ @Override public boolean drawImage(Image img, int x, int y, ImageObserver observer) { if (img == null) { return true; } int w = img.getWidth(observer); if (w < 0) { return false; } int h = img.getHeight(observer); if (h < 0) { return false; } return drawImage(img, x, y, w, h, observer); } /** * Draws the image into the rectangle defined by {@code (x, y, w, h)}. * Note that the {@code observer} is ignored (it is not useful in this * context). * * @param img the image ({@code null} permitted...draws nothing). * @param x the x-coordinate. * @param y the y-coordinate. * @param w the width. * @param h the height. * @param observer ignored. * * @return {@code true} if the image is drawn. */ @Override public boolean drawImage(Image img, int x, int y, int w, int h, ImageObserver observer) { if (img == null) { return true; } if (this.clip != null) { this.gs.pushGraphicsState(); this.gs.applyClip(invTransformedClip(this.clip)); this.gs.drawImage(img, x, y, w, h); this.gs.popGraphicsState(); } else { this.gs.drawImage(img, x, y, w, h); } return true; } /** * Draws an image at the location {@code (x, y)}. Note that the * {@code observer} is ignored. * * @param img the image ({@code null} permitted...draws nothing). * @param x the x-coordinate. * @param y the y-coordinate. * @param bgcolor the background color ({@code null} permitted). * @param observer ignored. * * @return {@code true} if the image is drawn. */ @Override public boolean drawImage(Image img, int x, int y, Color bgcolor, ImageObserver observer) { if (img == null) { return true; } int w = img.getWidth(null); if (w < 0) { return false; } int h = img.getHeight(null); if (h < 0) { return false; } return drawImage(img, x, y, w, h, bgcolor, observer); } /** * Draws an image to the rectangle {@code (x, y, w, h)} (scaling it if * required), first filling the background with the specified color. Note * that the {@code observer} is ignored. * * @param img the image. * @param x the x-coordinate. * @param y the y-coordinate. * @param w the width. * @param h the height. * @param bgcolor the background color ({@code null} permitted). * @param observer ignored. * * @return {@code true} if the image is drawn. */ @Override public boolean drawImage(Image img, int x, int y, int w, int h, Color bgcolor, ImageObserver observer) { Paint saved = getPaint(); setPaint(bgcolor); fillRect(x, y, w, h); setPaint(saved); return drawImage(img, x, y, w, h, observer); } /** * Draws part of an image (defined by the source rectangle * {@code (sx1, sy1, sx2, sy2)}) into the destination rectangle * {@code (dx1, dy1, dx2, dy2)}. Note that the {@code observer} * is ignored. * * @param img the image. * @param dx1 the x-coordinate for the top left of the destination. * @param dy1 the y-coordinate for the top left of the destination. * @param dx2 the x-coordinate for the bottom right of the destination. * @param dy2 the y-coordinate for the bottom right of the destination. * @param sx1 the x-coordinate for the top left of the source. * @param sy1 the y-coordinate for the top left of the source. * @param sx2 the x-coordinate for the bottom right of the source. * @param sy2 the y-coordinate for the bottom right of the source. * * @return {@code true} if the image is drawn. */ @Override public boolean drawImage(Image img, int dx1, int dy1, int dx2, int dy2, int sx1, int sy1, int sx2, int sy2, ImageObserver observer) { int w = dx2 - dx1; int h = dy2 - dy1; BufferedImage img2 = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB); Graphics2D g2 = img2.createGraphics(); g2.drawImage(img, 0, 0, w, h, sx1, sy1, sx2, sy2, null); return drawImage(img2, dx1, dy1, null); } /** * Draws part of an image (defined by the source rectangle * {@code (sx1, sy1, sx2, sy2)}) into the destination rectangle * {@code (dx1, dy1, dx2, dy2)}. The destination rectangle is first * cleared by filling it with the specified {@code bgcolor}. Note that * the {@code observer} is ignored. * * @param img the image. * @param dx1 the x-coordinate for the top left of the destination. * @param dy1 the y-coordinate for the top left of the destination. * @param dx2 the x-coordinate for the bottom right of the destination. * @param dy2 the y-coordinate for the bottom right of the destination. * @param sx1 the x-coordinate for the top left of the source. * @param sy1 the y-coordinate for the top left of the source. * @param sx2 the x-coordinate for the bottom right of the source. * @param sy2 the y-coordinate for the bottom right of the source. * @param bgcolor the background color ({@code null} permitted). * @param observer ignored. * * @return {@code true} if the image is drawn. */ @Override public boolean drawImage(Image img, int dx1, int dy1, int dx2, int dy2, int sx1, int sy1, int sx2, int sy2, Color bgcolor, ImageObserver observer) { Paint saved = getPaint(); setPaint(bgcolor); fillRect(dx1, dy1, dx2 - dx1, dy2 - dy1); setPaint(saved); return drawImage(img, dx1, dy1, dx2, dy2, sx1, sy1, sx2, sy2, observer); } /** * This method does nothing. The operation assumes that the output is in * bitmap form, which is not the case for PDF, so we silently ignore * this method call. * * @param x the x-coordinate. * @param y the y-coordinate. * @param width the width of the area. * @param height the height of the area. * @param dx the delta x. * @param dy the delta y. */ @Override public void copyArea(int x, int y, int width, int height, int dx, int dy) { // do nothing, this operation is silently ignored. } /** * Performs any actions required when the graphics instance is finished * with. Here we restore the transform on the graphics stream if this * instance was created via the {@link #create() } method. See issue #4 * at GitHub for background info. */ @Override public void dispose() { if (this.originalTransform != null) { this.gs.setTransform(this.originalTransform); } } /** * Sets the attributes of the reusable {@link Rectangle2D} object that is * used by the {@link #drawRect(int, int, int, int)} and * {@link #fillRect(int, int, int, int)} methods. * * @param x the x-coordinate. * @param y the y-coordinate. * @param width the width. * @param height the height. */ private void setRect(int x, int y, int width, int height) { if (this.rect == null) { this.rect = new Rectangle2D.Double(x, y, width, height); } else { this.rect.setRect(x, y, width, height); } } /** * Sets the attributes of the reusable {@link RoundRectangle2D} object that * is used by the {@link #drawRoundRect(int, int, int, int, int, int)} and * {@link #fillRoundRect(int, int, int, int, int, int)} methods. * * @param x the x-coordinate. * @param y the y-coordinate. * @param width the width. * @param height the height. * @param arcWidth the arc width. * @param arcHeight the arc height. */ private void setRoundRect(int x, int y, int width, int height, int arcWidth, int arcHeight) { if (this.roundRect == null) { this.roundRect = new RoundRectangle2D.Double(x, y, width, height, arcWidth, arcHeight); } else { this.roundRect.setRoundRect(x, y, width, height, arcWidth, arcHeight); } } /** * Sets the attributes of the reusable {@link Ellipse2D} object that is * used by the {@link #drawOval(int, int, int, int)} and * {@link #fillOval(int, int, int, int)} methods. * * @param x the x-coordinate. * @param y the y-coordinate. * @param width the width. * @param height the height. */ private void setOval(int x, int y, int width, int height) { if (this.oval == null) { this.oval = new Ellipse2D.Double(x, y, width, height); } else { this.oval.setFrame(x, y, width, height); } } /** * Sets the attributes of the reusable {@link Arc2D} object that is used by * {@link #drawArc(int, int, int, int, int, int)} and * {@link #fillArc(int, int, int, int, int, int)} methods. * * @param x the x-coordinate. * @param y the y-coordinate. * @param width the width. * @param height the height. * @param startAngle the start angle in degrees, 0 = 3 o'clock. * @param arcAngle the angle (anticlockwise) in degrees. */ private void setArc(int x, int y, int width, int height, int startAngle, int arcAngle) { if (this.arc == null) { this.arc = new Arc2D.Double(x, y, width, height, startAngle, arcAngle, Arc2D.OPEN); } else { this.arc.setArc(x, y, width, height, startAngle, arcAngle, Arc2D.OPEN); } } } jfreepdf-2.0.1/src/main/java/org/jfree/pdf/PDFGraphicsConfiguration.java000066400000000000000000000107061433176232400260640ustar00rootroot00000000000000/* ===================================================================== * JFreePDF : a fast, light-weight PDF library for the Java(tm) platform * ===================================================================== * * (C)opyright 2013-2022, by David Gilbert. All rights reserved. * * https://github.com/jfree/orsonpdf * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * If you do not wish to be bound by the terms of the GPL, an alternative * runtime license is available to JFree sponsors: * * https://github.com/sponsors/jfree * */ package org.jfree.pdf; import java.awt.AWTException; import java.awt.GraphicsConfiguration; import java.awt.GraphicsDevice; import java.awt.ImageCapabilities; import java.awt.Rectangle; import java.awt.Transparency; import java.awt.geom.AffineTransform; import java.awt.image.BufferedImage; import java.awt.image.ColorModel; import java.awt.image.DirectColorModel; import java.awt.image.VolatileImage; /** * A graphics configuration for the {@link PDFGraphics2D} class. */ public class PDFGraphicsConfiguration extends GraphicsConfiguration { private GraphicsDevice device; private int width, height; /** * Creates a new instance. * * @param width the width of the bounds. * @param height the height of the bounds. */ public PDFGraphicsConfiguration(int width, int height) { super(); this.width = width; this.height = height; } /** * Returns the graphics device that this configuration is associated with. * * @return The graphics device (never {@code null}). */ @Override public GraphicsDevice getDevice() { if (this.device == null) { this.device = new PDFGraphicsDevice("JFreePDF-GraphicsDevice", this); } return this.device; } /** * Returns the color model for this configuration. * * @return The color model. */ @Override public ColorModel getColorModel() { return getColorModel(Transparency.TRANSLUCENT); } /** * Returns the color model for the specified transparency type, or * {@code null}. * * @param transparency the transparency type. * * @return A color model (possibly {@code null}). */ @Override public ColorModel getColorModel(int transparency) { if (transparency == Transparency.TRANSLUCENT) { return ColorModel.getRGBdefault(); } else if (transparency == Transparency.OPAQUE) { return new DirectColorModel(32, 0x00ff0000, 0x0000ff00, 0x000000ff); } else { return null; } } /** * Returns the default transform. * * @return The default transform. */ @Override public AffineTransform getDefaultTransform() { return new AffineTransform(); } /** * Returns the normalizing transform. * * @return The normalizing transform. */ @Override public AffineTransform getNormalizingTransform() { return new AffineTransform(); } /** * Returns the bounds for this configuration. * * @return The bounds. */ @Override public Rectangle getBounds() { return new Rectangle(this.width, this.height); } private BufferedImage img = new BufferedImage(10, 10, BufferedImage.TYPE_INT_ARGB); @Override public VolatileImage createCompatibleVolatileImage(int width, int height, ImageCapabilities caps, int transparency) throws AWTException { return img.createGraphics().getDeviceConfiguration() .createCompatibleVolatileImage(width, height, caps, transparency); } } jfreepdf-2.0.1/src/main/java/org/jfree/pdf/PDFGraphicsDevice.java000066400000000000000000000053541433176232400244570ustar00rootroot00000000000000/* ===================================================================== * JFreePDF : a fast, light-weight PDF library for the Java(tm) platform * ===================================================================== * * (C)opyright 2013-2022, by David Gilbert. All rights reserved. * * https://github.com/jfree/orsonpdf * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * If you do not wish to be bound by the terms of the GPL, an alternative * runtime license is available to JFree sponsors: * * https://github.com/sponsors/jfree * */ package org.jfree.pdf; import java.awt.GraphicsConfiguration; import java.awt.GraphicsDevice; /** * A graphics device for use in the {@link PDFGraphicsConfiguration} class. */ public class PDFGraphicsDevice extends GraphicsDevice { private final String id; GraphicsConfiguration defaultConfig; /** * Creates a new instance. * * @param id the id. * @param defaultConfig the default configuration. */ public PDFGraphicsDevice(String id, GraphicsConfiguration defaultConfig) { this.id = id; this.defaultConfig = defaultConfig; } /** * Returns the device type. * * @return The device type. */ @Override public int getType() { return GraphicsDevice.TYPE_PRINTER; } /** * Returns the id string. * * @return The id string. */ @Override public String getIDstring() { return this.id; } /** * Returns all configurations for this device. * * @return All configurations for this device. */ @Override public GraphicsConfiguration[] getConfigurations() { return new GraphicsConfiguration[] { getDefaultConfiguration() }; } /** * Returns the default configuration for this device. * * @return The default configuration for this device. */ @Override public GraphicsConfiguration getDefaultConfiguration() { return this.defaultConfig; } } jfreepdf-2.0.1/src/main/java/org/jfree/pdf/PDFHints.java000066400000000000000000000076471433176232400226730ustar00rootroot00000000000000/* ===================================================================== * JFreePDF : a fast, light-weight PDF library for the Java(tm) platform * ===================================================================== * * (C)opyright 2013-2022, by David Gilbert. All rights reserved. * * https://github.com/jfree/orsonpdf * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * If you do not wish to be bound by the terms of the GPL, an alternative * runtime license is available to JFree sponsors: * * https://github.com/sponsors/jfree * */ package org.jfree.pdf; import java.awt.RenderingHints; /** * Defines the rendering hints that can be used with the {@link PDFGraphics2D} * class. There is just one hint defined at present:
*

    *
  • {@link #KEY_DRAW_STRING_TYPE} that controls how the drawString() methods * generate output (regular text or vector graphics);
  • *
* * @since 1.5 */ public final class PDFHints { private PDFHints() { // no need to instantiate this } /** * The key for the hint that controls whether strings are rendered as * characters (standard PDF output) or vector graphics (implemented using * TextLayout). The latter will result in larger output files * but permits rendering Unicode characters without font embedding (which is * not supported by JFreePDF at this point). Valid hint * values are {@link #VALUE_DRAW_STRING_TYPE_STANDARD} and * {@link #VALUE_DRAW_STRING_TYPE_VECTOR}. */ public static final PDFHints.Key KEY_DRAW_STRING_TYPE = new PDFHints.Key(0); /** * Hint value for KEY_DRAW_STRING_TYPE to specify that strings * should be written to the output using standard PDF text primitives. */ public static final Object VALUE_DRAW_STRING_TYPE_STANDARD = "VALUE_DRAW_STRING_TYPE_STANDARD"; /** * Hint value for KEY_DRAW_STRING_TYPE to say that strings * should be written to the output using vector graphics primitives. */ public static final Object VALUE_DRAW_STRING_TYPE_VECTOR = "VALUE_DRAW_STRING_TYPE_VECTOR"; /** * A key for hints used by the {@link PDFGraphics2D} class. */ public static class Key extends RenderingHints.Key { /** * Creates a new instance with the specified key. * * @param privateKey the key. */ public Key(int privateKey) { super(privateKey); } /** * Returns {@code true} if {@code val} is a value that is * compatible with this key, and {@code false} otherwise. * * @param val the value. * * @return A boolean. */ @Override public boolean isCompatibleValue(Object val) { switch (intKey()) { case 0: return val == null || VALUE_DRAW_STRING_TYPE_STANDARD.equals(val) || VALUE_DRAW_STRING_TYPE_VECTOR.equals(val); default: throw new RuntimeException("Not expected!"); } } } } jfreepdf-2.0.1/src/main/java/org/jfree/pdf/Page.java000066400000000000000000000372741433176232400221270ustar00rootroot00000000000000/* ===================================================================== * JFreePDF : a fast, light-weight PDF library for the Java(tm) platform * ===================================================================== * * (C)opyright 2013-2022, by David Gilbert. All rights reserved. * * https://github.com/jfree/orsonpdf * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * If you do not wish to be bound by the terms of the GPL, an alternative * runtime license is available to JFree sponsors: * * https://github.com/sponsors/jfree * */ package org.jfree.pdf; import java.awt.Font; import java.awt.GradientPaint; import java.awt.Image; import java.awt.MultipleGradientPaint; import java.awt.RadialGradientPaint; import java.awt.geom.AffineTransform; import java.awt.geom.Rectangle2D; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.jfree.pdf.internal.Pattern.ShadingPattern; import org.jfree.pdf.dictionary.Dictionary; import org.jfree.pdf.dictionary.GraphicsStateDictionary; import org.jfree.pdf.filter.FlateFilter; import org.jfree.pdf.function.ExponentialInterpolationFunction; import org.jfree.pdf.function.Function; import org.jfree.pdf.function.StitchingFunction; import org.jfree.pdf.internal.PDFFont; import org.jfree.pdf.internal.Pages; import org.jfree.pdf.internal.PDFObject; import org.jfree.pdf.internal.Pattern; import org.jfree.pdf.shading.AxialShading; import org.jfree.pdf.shading.RadialShading; import org.jfree.pdf.shading.Shading; import org.jfree.pdf.stream.GraphicsStream; import org.jfree.pdf.stream.PDFImage; import org.jfree.pdf.stream.PDFSoftMaskImage; import org.jfree.pdf.util.Args; import org.jfree.pdf.util.GradientPaintKey; import org.jfree.pdf.util.RadialGradientPaintKey; /** * Represents a page in a {@link PDFDocument}. Our objective is to be able * to write to the page using the {@link PDFGraphics2D} class (see the * {@link #getGraphics2D()} method). */ public class Page extends PDFObject { /** The pages of the document. */ private Pages parent; /** The page bounds. */ private Rectangle2D bounds; /** The page contents. */ private GraphicsStream contents; /** The Graphics2D for writing to the page contents. */ private PDFGraphics2D graphics2d; /** * The list of font (names) used on the page. We let the parent take * care of tracking the font objects. */ private List fontsOnPage; /** * A map between gradient paints and the names used to define the * associated pattern in the page resources. */ private Map gradientPaintsOnPage; private Map radialGradientPaintsOnPage; /** The pattern dictionary for this page. */ private Dictionary patterns; /** The ExtGState dictionary for the page. */ private Dictionary graphicsStates; /** * The transform between Page and Java2D coordinates, used in Shading * patterns. */ private AffineTransform j2DTransform; private Dictionary xObjects = new Dictionary(); /** * Creates a new page. * * @param number the PDF object number. * @param generation the PDF object generation number. * @param parent the parent (manages the pages in the {@code PDFDocument}). * @param bounds the page bounds ({@code null} not permitted). */ Page(int number, int generation, Pages parent, Rectangle2D bounds) { this(number, generation, parent, bounds, true); } /** * Creates a new page. * * @param number the PDF object number. * @param generation the PDF object generation number. * @param parent the parent (manages the pages in the {@code PDFDocument}). * @param bounds the page bounds ({@code null} not permitted). * @param filter a flag that controls whether or not the graphics stream * for the page has a FlateFilter applied. * * @since 1.4 */ Page(int number, int generation, Pages parent, Rectangle2D bounds, boolean filter) { super(number, generation); Args.nullNotPermitted(bounds, "bounds"); this.parent = parent; this.bounds = (Rectangle2D) bounds.clone(); this.fontsOnPage = new ArrayList<>(); int n = this.parent.getDocument().getNextNumber(); this.contents = new GraphicsStream(n, this); if (filter) { this.contents.addFilter(new FlateFilter()); } this.gradientPaintsOnPage = new HashMap<>(); this.radialGradientPaintsOnPage = new HashMap<>(); this.patterns = new Dictionary(); this.graphicsStates = new Dictionary(); this.j2DTransform = AffineTransform.getTranslateInstance(0.0, bounds.getHeight()); this.j2DTransform.concatenate(AffineTransform.getScaleInstance(1.0, -1.0)); } /** * Returns a new rectangle containing the bounds for this page (as supplied * to the constructor). * * @return The page bounds. */ public Rectangle2D getBounds() { return (Rectangle2D) this.bounds.clone(); } /** * Returns the {@code PDFObject} that represents the page content. * * @return The {@code PDFObject} that represents the page content. */ public PDFObject getContents() { return this.contents; } /** * Returns the {@link PDFGraphics2D} instance for drawing to the page. * * @return The {@code PDFGraphics2D} instance for drawing to the page. */ public PDFGraphics2D getGraphics2D() { if (this.graphics2d == null) { this.graphics2d = new PDFGraphics2D(this.contents, (int) this.bounds.getWidth(), (int) this.bounds.getHeight()); } return this.graphics2d; } /** * Finds the font reference corresponding to the given Java2D font, * creating a new one if there isn't one already. * * @param font the AWT font. * * @return The font reference. */ public String findOrCreateFontReference(Font font) { String ref = this.parent.findOrCreateFontReference(font); if (!this.fontsOnPage.contains(ref)) { this.fontsOnPage.add(ref); } return ref; } private Dictionary createFontDictionary() { Dictionary d = new Dictionary(); for (String name : this.fontsOnPage) { PDFFont f = this.parent.getFont(name); d.put(name, f.getReference()); } return d; } /** * Returns the name of the pattern for the specified {@code GradientPaint}, * reusing an existing pattern if possible, otherwise creating a new * pattern if necessary. * * @param gp the gradient ({@code null} not permitted). * * @return The pattern name. */ public String findOrCreatePattern(GradientPaint gp) { GradientPaintKey key = new GradientPaintKey(gp); String patternName = this.gradientPaintsOnPage.get(key); if (patternName == null) { PDFDocument doc = this.parent.getDocument(); Function f = new ExponentialInterpolationFunction( doc.getNextNumber(), gp.getColor1().getRGBColorComponents(null), gp.getColor2().getRGBColorComponents(null)); doc.addObject(f); double[] coords = new double[4]; coords[0] = gp.getPoint1().getX(); coords[1] = gp.getPoint1().getY(); coords[2] = gp.getPoint2().getX(); coords[3] = gp.getPoint2().getY(); Shading s = new AxialShading(doc.getNextNumber(), coords, f); doc.addObject(s); Pattern p = new ShadingPattern(doc.getNextNumber(), s, this.j2DTransform); doc.addObject(p); patternName = "/P" + (this.patterns.size() + 1); this.patterns.put(patternName, p); this.gradientPaintsOnPage.put(key, patternName); } return patternName; } /** * Returns the name of the pattern for the specified * {@code RadialGradientPaint}, reusing an existing pattern if * possible, otherwise creating a new pattern if necessary. * * @param gp the gradient ({@code null} not permitted). * * @return The pattern name. */ public String findOrCreatePattern(RadialGradientPaint gp) { RadialGradientPaintKey key = new RadialGradientPaintKey(gp); String patternName = this.radialGradientPaintsOnPage.get(key); if (patternName == null) { PDFDocument doc = this.parent.getDocument(); Function f = createFunctionForMultipleGradient(gp); doc.addObject(f); double[] coords = new double[6]; coords[0] = gp.getFocusPoint().getX(); coords[1] = gp.getFocusPoint().getY(); coords[2] = 0.0; coords[3] = gp.getCenterPoint().getX(); coords[4] = gp.getCenterPoint().getY(); coords[5] = gp.getRadius(); Shading s = new RadialShading(doc.getNextNumber(), coords, f); doc.addObject(s); Pattern p = new ShadingPattern(doc.getNextNumber(), s, this.j2DTransform); doc.addObject(p); patternName = "/P" + (this.patterns.size() + 1); this.patterns.put(patternName, p); this.radialGradientPaintsOnPage.put(key, patternName); } return patternName; } private Function createFunctionForMultipleGradient( MultipleGradientPaint mgp) { PDFDocument doc = this.parent.getDocument(); if (mgp.getColors().length == 2) { Function f = new ExponentialInterpolationFunction( doc.getNextNumber(), mgp.getColors()[0].getRGBColorComponents(null), mgp.getColors()[1].getRGBColorComponents(null)); return f; } else { int count = mgp.getColors().length - 1; Function[] functions = new Function[count]; float[] fbounds = new float[count - 1]; float[] encode = new float[count * 2]; for (int i = 0; i < count; i++) { // create a linear function for each pair of colors functions[i] = new ExponentialInterpolationFunction( doc.getNextNumber(), mgp.getColors()[i].getRGBColorComponents(null), mgp.getColors()[i + 1].getRGBColorComponents(null)); doc.addObject(functions[i]); if (i < count - 1) { fbounds[i] = mgp.getFractions()[i + 1]; } encode[i * 2] = 0; encode[i * 2 + 1] = 1; } return new StitchingFunction(doc.getNextNumber(), functions, fbounds, encode); } } private Map alphaDictionaries = new HashMap<>(); /** * Returns the name of the Graphics State Dictionary that can be used * for the specified alpha value - if there is no existing dictionary * then a new one is created. * * @param alpha the alpha value in the range 0 to 255. * * @return The graphics state dictionary reference. */ public String findOrCreateGSDictionary(int alpha) { Integer key = alpha; float alphaValue = alpha / 255f; String name = this.alphaDictionaries.get(key); if (name == null) { PDFDocument pdfDoc = this.parent.getDocument(); GraphicsStateDictionary gsd = new GraphicsStateDictionary( pdfDoc.getNextNumber()); gsd.setNonStrokeAlpha(alphaValue); gsd.setStrokeAlpha(alphaValue); pdfDoc.addObject(gsd); name = "/GS" + (this.graphicsStates.size() + 1); this.graphicsStates.put(name, gsd); this.alphaDictionaries.put(key, name); } return name; } /** * Adds a soft mask image to the page. This is called from the * {@link #addImage(java.awt.Image, boolean)} method to support image transparency. * * @param img the image ({@code null} not permitted). * * @return The soft mask image reference. */ String addSoftMaskImage(Image img) { Args.nullNotPermitted(img, "img"); PDFDocument pdfDoc = this.parent.getDocument(); PDFSoftMaskImage softMaskImage = new PDFSoftMaskImage( pdfDoc.getNextNumber(), img); softMaskImage.addFilter(new FlateFilter()); pdfDoc.addObject(softMaskImage); String reference = "/Image" + this.xObjects.size(); this.xObjects.put(reference, softMaskImage); return softMaskImage.getReference(); } /** * Adds an image to the page.This creates the required PDF object, * as well as adding a reference in the {@code xObjects} resources. * You should not call this method directly, it exists for the use of the * {@link PDFGraphics2D#drawImage(java.awt.Image, int, int, int, int, java.awt.image.ImageObserver)} * method. * * @param img the image ({@code null} not permitted). * @param addSoftMaskImage add as a soft mask image? * * @return The image reference name. */ public String addImage(Image img, boolean addSoftMaskImage) { Args.nullNotPermitted(img, "img"); PDFDocument pdfDoc = this.parent.getDocument(); String softMaskImageRef = null; if (addSoftMaskImage) { softMaskImageRef = addSoftMaskImage(img); } PDFImage image = new PDFImage(pdfDoc.getNextNumber(), img, softMaskImageRef); image.addFilter(new FlateFilter()); pdfDoc.addObject(image); String reference = "/Image" + this.xObjects.size(); this.xObjects.put(reference, image); return reference; } @Override public byte[] getObjectBytes() { return createDictionary().toPDFBytes(); } private Dictionary createDictionary() { Dictionary dictionary = new Dictionary("/Page"); dictionary.put("/Parent", this.parent); dictionary.put("/MediaBox", this.bounds); dictionary.put("/Contents", this.contents); Dictionary resources = new Dictionary(); resources.put("/ProcSet", "[/PDF /Text /ImageB /ImageC /ImageI]"); if (!this.xObjects.isEmpty()) { resources.put("/XObject", this.xObjects); } if (!this.fontsOnPage.isEmpty()) { resources.put("/Font", createFontDictionary()); } if (!this.patterns.isEmpty()) { resources.put("/Pattern", this.patterns); } if (!this.graphicsStates.isEmpty()) { resources.put("/ExtGState", this.graphicsStates); } dictionary.put("/Resources", resources); return dictionary; } } jfreepdf-2.0.1/src/main/java/org/jfree/pdf/dictionary/000077500000000000000000000000001433176232400225405ustar00rootroot00000000000000jfreepdf-2.0.1/src/main/java/org/jfree/pdf/dictionary/Dictionary.java000066400000000000000000000167241433176232400255220ustar00rootroot00000000000000/* ===================================================================== * JFreePDF : a fast, light-weight PDF library for the Java(tm) platform * ===================================================================== * * (C)opyright 2013-2022, by David Gilbert. All rights reserved. * * https://github.com/jfree/orsonpdf * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * If you do not wish to be bound by the terms of the GPL, an alternative * runtime license is available to JFree sponsors: * * https://github.com/sponsors/jfree * */ package org.jfree.pdf.dictionary; import java.awt.geom.Rectangle2D; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.HashMap; import java.util.Map; import org.jfree.pdf.internal.PDFObject; import org.jfree.pdf.util.PDFUtils; /** * A dictionary is a map and supports writing the bytes for the dictionary * in the PDF syntax. The dictionary has an optional {@code type} entry * which is treated as a special case (to ensure it comes first in the output * if it is specified). */ public class Dictionary { /** * The type entry. We treat this as a special case, because when a type is * defined, we want it to appear first in the PDF output. Note that it * can be set to null for some dictionaries. */ private String type; /** Data storage. */ private Map map; /** * Creates a new instance with no type. */ public Dictionary() { this(null); } /** * Creates a new dictionary with the specified type (which can be * {@code null}). * * @param type the type value (for example, "/Catalog"). */ public Dictionary(String type) { this.type = type; this.map = new HashMap<>(); } /** * Returns the dictionary type. * * @return The dictionary type (possibly ({@code null}). */ public String getType() { return this.type; } /** * Sets the type (for example, "/Catalog"). * * @param type the type ({@code null} permitted). */ public void setType(String type) { this.type = type; } /** * Returns {@code true} if the dictionary has no entries, and * {@code false} otherwise. * * @return A boolean. * * @see #size() */ public boolean isEmpty() { return this.map.isEmpty(); } /** * Returns the number of items in the dictionary. * * @return The number of items in the dictionary. */ public int size() { return this.map.size(); } /** * Puts an entry in the dictionary. * * @param key the key. * @param value the value. */ public void put(String key, Object value) { this.map.put(key, value); } /** * Removes an entry from the dictionary, returning the value that was * stored previously. * * @param key the key. * * @return The value that was associated with the key. */ public Object remove(String key) { return this.map.remove(key); } /** * Returns a byte array containing the ASCII encoding of the dictionary. * * @return A byte array. */ public byte[] toPDFBytes() { ByteArrayOutputStream baos = new ByteArrayOutputStream(); try { // here we are first creating the String version, then encoding // to bytes...it would be more efficient to go direct to bytes // but this will do for now baos.write(PDFUtils.toBytes(toPDFString())); } catch (IOException ex) { throw new RuntimeException("Dictionary.toPDFBytes() failed.", ex); } return baos.toByteArray(); } /** * Returns a string containing the PDF text describing the dictionary. * Note that this is a Java string, conversion to byte format happens * elsewhere. * * @return A string. */ public String toPDFString() { StringBuilder b = new StringBuilder(); b.append("<< "); if (this.type != null) { b.append("/Type ").append(this.type).append("\n"); } // now iterate through the dictionary and write its values for (String key : this.map.keySet()) { Object value = this.map.get(key); if (value instanceof Number || value instanceof String) { b.append(key).append(" "); b.append(value.toString()).append("\n"); } else if (value instanceof PDFObject) { PDFObject pdfObj = (PDFObject) value; b.append(key).append(" "); b.append(pdfObj.getReference()).append("\n"); } else if (value instanceof String[]) { b.append(key).append(" "); String[] array = (String[]) value; b.append("["); for (int i = 0; i < array.length; i++) { if (i != 0) { b.append(" "); } b.append(array[i]); } b.append("]\n"); } else if (value instanceof PDFObject[]) { b.append(key).append(" "); PDFObject[] array = (PDFObject[]) value; b.append("["); for (int i = 0; i < array.length; i++) { if (i != 0) { b.append(" "); } b.append(array[i].getReference()); } b.append("]\n"); } else if (value instanceof Rectangle2D) { Rectangle2D r = (Rectangle2D) value; b.append(key).append(" "); b.append("[").append(r.getX()).append(" "); b.append(r.getY()).append(" ").append(r.getWidth()).append(" "); b.append(r.getHeight()).append("]\n"); } else if (value instanceof Dictionary) { b.append(key).append(" "); Dictionary d = (Dictionary) value; b.append(d.toPDFString()); } else if (value instanceof float[]) { b.append(key).append(" "); float[] array = (float[]) value; b.append("["); for (int i = 0; i < array.length; i++) { if (i != 0) { b.append(" "); } b.append(array[i]); } b.append("]\n"); } else { throw new RuntimeException("Unrecognised value type: " + value); } } b.append(">>\n"); return b.toString(); } } jfreepdf-2.0.1/src/main/java/org/jfree/pdf/dictionary/DictionaryObject.java000066400000000000000000000056441433176232400266500ustar00rootroot00000000000000/* ===================================================================== * JFreePDF : a fast, light-weight PDF library for the Java(tm) platform * ===================================================================== * * (C)opyright 2013-2022, by David Gilbert. All rights reserved. * * https://github.com/jfree/orsonpdf * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * If you do not wish to be bound by the terms of the GPL, an alternative * runtime license is available to JFree sponsors: * * https://github.com/sponsors/jfree * */ package org.jfree.pdf.dictionary; import org.jfree.pdf.internal.PDFObject; import org.jfree.pdf.util.Args; /** * A PDF object that is represented by a dictionary. This is used to * represent the {@code Catalog} and the {@code Outlines} (the latter * being a placeholder implementation only since we don't presently generate * outlines). */ public class DictionaryObject extends PDFObject { protected Dictionary dictionary; /** * Creates a new instance. * * @param number the object number. * @param type the object type (for example, "/Catalog"). */ public DictionaryObject(int number, String type) { super(number); this.dictionary = new Dictionary(type); } /** * Puts an item in the dictionary. * * @param name the name (without the leading "/", {@code null} not * permitted). * @param value the value ({@code null} not permitted). */ public void put(String name, Object value) { Args.nullNotPermitted(value, "value"); this.dictionary.put("/" + name, value); } /** * Removes an item from the dictionary. * * @param name the name (without the leading "/"). * * @return The value that was previously stored with the given name. */ public Object remove(String name) { return this.dictionary.remove("/" + name); } /** * Returns the bytes that go between the 'obj' and 'endobj' in the * PDF output for this object. * * @return A byte array. */ @Override public byte[] getObjectBytes() { return this.dictionary.toPDFBytes(); } } jfreepdf-2.0.1/src/main/java/org/jfree/pdf/dictionary/GraphicsStateDictionary.java000066400000000000000000000053231433176232400301750ustar00rootroot00000000000000/* ===================================================================== * JFreePDF : a fast, light-weight PDF library for the Java(tm) platform * ===================================================================== * * (C)opyright 2013-2022, by David Gilbert. All rights reserved. * * https://github.com/jfree/orsonpdf * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * If you do not wish to be bound by the terms of the GPL, an alternative * runtime license is available to JFree sponsors: * * https://github.com/sponsors/jfree * */ package org.jfree.pdf.dictionary; /** * A graphics state dictionary. */ public class GraphicsStateDictionary extends DictionaryObject { private float strokeAlpha; private float nonStrokeAlpha; /** * Creates a new instance with the type {@code /ExtGState}. * * @param number the PDF object number. */ public GraphicsStateDictionary(int number) { super(number, "/ExtGState"); } /** * Returns the stroke alpha (in the range {@code 0.0} to {@code 1.0}). * * @return The stroke alpha. */ public float getStrokeAlpha() { return this.strokeAlpha; } /** * Sets the stroke alpha. * * @param alpha the stroke alpha (in the range {@code 0.0} to {@code 1.0}). */ public void setStrokeAlpha(float alpha) { this.strokeAlpha = alpha; this.dictionary.put("/CA", alpha); } /** * Returns the non-stroke alpha (a value in the range {@code 0.0} to * {@code 1.0}). * * @return The non-stroke alpha. */ public float getNonStrokeAlpha() { return this.nonStrokeAlpha; } /** * Sets the non-stroke alpha. * * @param alpha the new alpha value (in the range {@code 0.0} to * {@code 1.0}). */ public void setNonStrokeAlpha(float alpha) { this.nonStrokeAlpha = alpha; this.dictionary.put("/ca", alpha); } } jfreepdf-2.0.1/src/main/java/org/jfree/pdf/filter/000077500000000000000000000000001433176232400216605ustar00rootroot00000000000000jfreepdf-2.0.1/src/main/java/org/jfree/pdf/filter/ASCII85Filter.java000066400000000000000000000042771433176232400247100ustar00rootroot00000000000000/* ===================================================================== * JFreePDF : a fast, light-weight PDF library for the Java(tm) platform * ===================================================================== * * (C)opyright 2013-2022, by David Gilbert. All rights reserved. * * https://github.com/jfree/orsonpdf * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * If you do not wish to be bound by the terms of the GPL, an alternative * runtime license is available to JFree sponsors: * * https://github.com/sponsors/jfree * */ package org.jfree.pdf.filter; import java.io.ByteArrayOutputStream; import java.io.IOException; /** * A filter that can encode in ASCII-85 format. */ public class ASCII85Filter implements Filter { /** * Default contructor. */ public ASCII85Filter() { } /** * Returns the filter type. * * @return {@link FilterType#ASCII85}. */ @Override public FilterType getFilterType() { return FilterType.ASCII85; } @Override public byte[] encode(byte[] source) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); Ascii85OutputStream out = new Ascii85OutputStream(baos); try { out.write(source); out.flush(); out.close(); } catch (IOException e) { // didn't expect this... throw new RuntimeException(e); } return baos.toByteArray(); } } jfreepdf-2.0.1/src/main/java/org/jfree/pdf/filter/Ascii85OutputStream.java000066400000000000000000000223411433176232400263270ustar00rootroot00000000000000/* * Copyright (c) 2009-2013, i Data Connect! * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 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. * * Neither the name of the copyright holder 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 THE COPYRIGHT HOLDER AND CONTRIBUTORS "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 THE COPYRIGHT OWNER OR CONTRIBUTORS 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. */ package org.jfree.pdf.filter; import java.io.FilterOutputStream; import java.io.IOException; import java.io.OutputStream; /** *

* An ascii85 encoder, implemented as an {@link OutputStream}. *

*

* Call flush() or close() to properly close the * ascii85 block. The block must be closed for the encoded data to be valid. * Do not call flush() before you intend to end the ascii85 block. * Multiple ascii85 blocks may be encoded by calling flush() and then writing * more bytes to the stream. *

*

* Note that if you use the constructor with the * useSpaceCompression option, the encoded text will be shorter * when there are many consecutive space characters in the encoded data, but * it will not be compatible with Adobe's ascii85 implementation. It makes sense * to use this option if interoperability with other ascii85 implementations * is not a requirement. *

* @author Ben Upsavs */ public class Ascii85OutputStream extends FilterOutputStream { private int width = 72; private int pos; private int tuple; private int count; private boolean encoding; private boolean useSpaceCompression; /** * Creates an output stream to encode ascii85 data, using a default line * with of 72 characters and not using the space character compression * option. Call flush() to add the padding and end the ascii85 * block. * @param out the output stream. */ public Ascii85OutputStream(OutputStream out) { super(out); } /** * Creates an output stream to encode ascii85 data, using a default line * width of 72 characters. Call flush() to end the ascii85 * block. * @param out the output stream. * @param useSpaceCompression Whether to use space character compression in * the output. */ public Ascii85OutputStream(OutputStream out, boolean useSpaceCompression) { this(out); this.useSpaceCompression = useSpaceCompression; } /** * Creates an output stream to encode ascii85 data. Call * flush() to end the ascii85 block. * @param out the output stream. * @param width The maximum line width of the encoded output text. * Whitespace characters are ignored when decoding. * @param useSpaceCompression Whether to use space character compression in * the output. */ public Ascii85OutputStream(OutputStream out, int width, boolean useSpaceCompression) { this(out); this.width = width; this.useSpaceCompression = useSpaceCompression; } private void startEncoding() throws IOException { //out.write('<'); //out.write('~'); //pos = 2; encoding = true; } /** * Writes a single byte to the stream. See * {@link OutputStream#write(int b)} for details. * @param b The byte to encode. * @throws java.io.IOException If an I/O error occurs in the underlying * output stream. */ @Override public void write(int b) throws IOException { if (!encoding) startEncoding(); switch (count++) { case 0: tuple |= ((b & 0xff) << 24); break; case 1: tuple |= ((b & 0xff) << 16); break; case 2: tuple |= ((b & 0xff) << 8); break; case 3: tuple |= (b & 0xff); if (tuple == 0) { // Use null compression out.write('z'); if (pos++ >= width) { pos = 0; out.write('\r'); out.write('\n'); } } else if (useSpaceCompression && (tuple == 0x20202020)) { // Use space compression out.write('y'); if (pos++ >= width) { pos = 0; out.write('\r'); out.write('\n'); } } else encode(tuple, count); tuple = 0; count = 0; break; } } /** * Writes a single byte to the underlying output stream, unencoded. If * done improperly, this may corrupt the ascii85 data stream. Writing * a byte using this method may cause the line length to increase since * the line length counter will not be updated by this method. * @param b The byte to write. * @throws java.io.IOException If the underlying output stream has an I/O * error. */ public void writeUnencoded(int b) throws IOException { super.write(b); } /** * Writes bytes to the underlying output stream, unencoded. If done * improperly, this may corrupt the ascii85 data stream. Writing bytes * using this method may cause the line length to increase since the line * length counter will not be updated by this method. * @param b The bytes to write. * @throws java.io.IOException If the underlying output stream has an I/O * error. */ public void writeUnencoded(byte[] b) throws IOException { writeUnencoded(b, 0, b.length); } /** * Writes bytes to the underlying output stream, unencoded. If done * improperly, this may corrupt the ascii85 data stream. Writing bytes * using this method may cause the line length to increase since the line * length counter will not be updated by this method. * @param b The bytes to write. * @param off The offset of b to start reading from. * @param len The amount of bytes to read from b. * @throws java.io.IOException If the underlying output stream has an I/O * error. */ public void writeUnencoded(byte[] b, int off, int len) throws IOException { for (int i = 0; i < len; i++) writeUnencoded(b[off + i]); } /** * Encodes tuple and writes it to the output stream. The number * of bytes in the tuple, and thus the value of count is * normally 4, however less bytes may also be encoded, particularly if the * input stream has ended before the current tuple is full. * @param tuple The tuple to encode. * @param count The number of bytes stuffed into the tuple. * @throws IOException If an I/O error occurs. */ private void encode(int tuple, int count) throws IOException { int i = 5; byte[] buf = new byte[5]; short bufPos = 0; long longTuple = (tuple & 0xffffffffL); do { buf[bufPos++] = (byte)(longTuple % 85); longTuple /= 85; } while (--i > 0); i = count; do { out.write(buf[--bufPos] + '!'); if (pos++ >= width) { pos = 0; out.write('\r'); out.write('\n'); } } while (i-- > 0); } /** * Adds the closing block and flushes the underlying output stream. This * method should only be called if it is intended that the ascii85 block * should be closed. */ @Override public void flush() throws IOException { // Add padding if required. if (encoding) { if (count > 0) encode(tuple, count); if (pos + 2 > width) { out.write('\r'); out.write('\n'); } out.write('~'); out.write('>'); out.write('\r'); out.write('\n'); encoding = false; tuple = count = 0; } super.flush(); } } jfreepdf-2.0.1/src/main/java/org/jfree/pdf/filter/Filter.java000066400000000000000000000034711433176232400237550ustar00rootroot00000000000000/* ===================================================================== * JFreePDF : a fast, light-weight PDF library for the Java(tm) platform * ===================================================================== * * (C)opyright 2013-2022, by David Gilbert. All rights reserved. * * https://github.com/jfree/orsonpdf * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * If you do not wish to be bound by the terms of the GPL, an alternative * runtime license is available to JFree sponsors: * * https://github.com/sponsors/jfree * */ package org.jfree.pdf.filter; /** * A filter that can be used to encode stream data in PDF output. */ public interface Filter { /** * Returns the filter type. * * @return The filter type (never {@code null}). */ FilterType getFilterType(); /** * Apply the encoding to the bytes in {@code source} and return the * encoded data in a new array. * * @param source the source ({@code null} not permitted). * * @return The encoded bytes. */ byte[] encode(byte[] source); } jfreepdf-2.0.1/src/main/java/org/jfree/pdf/filter/FilterType.java000066400000000000000000000040151433176232400246120ustar00rootroot00000000000000/* ===================================================================== * JFreePDF : a fast, light-weight PDF library for the Java(tm) platform * ===================================================================== * * (C)opyright 2013-2022, by David Gilbert. All rights reserved. * * https://github.com/jfree/orsonpdf * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * If you do not wish to be bound by the terms of the GPL, an alternative * runtime license is available to JFree sponsors: * * https://github.com/sponsors/jfree * */ package org.jfree.pdf.filter; import org.jfree.pdf.util.Args; /** * Filter types for PDF streams. */ public enum FilterType { /** ASCII85 encoding. */ ASCII85("/ASCII85Decode"), /** Flate encoding. */ FLATE("/FlateDecode"); private final String decode; /** * Creates a new filter type. * * @param decode the decode value. */ FilterType(String decode) { Args.nullNotPermitted(decode, "decode"); this.decode = decode; } /** * Returns the decode value that can be written in the PDF output for * this filter type. * * @return The decode value (never {@code null}). */ public String getDecode() { return this.decode; } } jfreepdf-2.0.1/src/main/java/org/jfree/pdf/filter/FlateFilter.java000066400000000000000000000043231433176232400247260ustar00rootroot00000000000000/* ===================================================================== * JFreePDF : a fast, light-weight PDF library for the Java(tm) platform * ===================================================================== * * (C)opyright 2013-2022, by David Gilbert. All rights reserved. * * https://github.com/jfree/orsonpdf * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * If you do not wish to be bound by the terms of the GPL, an alternative * runtime license is available to JFree sponsors: * * https://github.com/sponsors/jfree * */ package org.jfree.pdf.filter; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.zip.DeflaterOutputStream; /** * Encodes data using Flate. */ public class FlateFilter implements Filter { /** * Default constructor. */ public FlateFilter() { } /** * Returns the filter type. * * @return {@link FilterType#FLATE} */ @Override public FilterType getFilterType() { return FilterType.FLATE; } @Override public byte[] encode(byte[] source) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); DeflaterOutputStream out = new DeflaterOutputStream(baos); try { out.write(source); out.flush(); out.close(); } catch (IOException e) { // didn't expect this... throw new RuntimeException(e); } return baos.toByteArray(); } } jfreepdf-2.0.1/src/main/java/org/jfree/pdf/filter/package-info.java000066400000000000000000000001711433176232400250460ustar00rootroot00000000000000/** * Filters that support the {@link org.jfree.pdf.PDFGraphics2D} * implementation. */ package org.jfree.pdf.filter;jfreepdf-2.0.1/src/main/java/org/jfree/pdf/function/000077500000000000000000000000001433176232400222205ustar00rootroot00000000000000jfreepdf-2.0.1/src/main/java/org/jfree/pdf/function/ExponentialInterpolationFunction.java000066400000000000000000000070661433176232400316400ustar00rootroot00000000000000/* ===================================================================== * JFreePDF : a fast, light-weight PDF library for the Java(tm) platform * ===================================================================== * * (C)opyright 2013-2022, by David Gilbert. All rights reserved. * * https://github.com/jfree/orsonpdf * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * If you do not wish to be bound by the terms of the GPL, an alternative * runtime license is available to JFree sponsors: * * https://github.com/sponsors/jfree * */ package org.jfree.pdf.function; import org.jfree.pdf.util.PDFUtils; /** * A PDF "Type 2" function. */ public final class ExponentialInterpolationFunction extends Function { double n; float[] c0; float[] c1; /** * Creates a new function. * * @param number the PDF object number. * @param c0 the function result at 0.0. * @param c1 the function result at 1.0. */ public ExponentialInterpolationFunction(int number, float[] c0, float[] c1) { super(number, FunctionType.EXPONENTIAL_INTERPOLATION); this.dictionary.put("/N", "1"); this.n = 1; setC0(c0); setC1(c1); } /** * Returns the interpolation exponent. The default value is {@code 1}. * * @return The interpolation exponent. */ public double getN() { return this.n; } /** * Sets the interpolation exponent. * * @param n the new interpolation exponent. */ public void setN(double n) { this.n = n; this.dictionary.put("/N", String.valueOf(n)); } /** * Returns the function result when x is 0.0. The returned array is a * copy. * * @return The function result when x is 0.0. */ public float[] getC0() { return this.c0.clone(); } /** * Sets the function result to be used when x is 0.0. The array passed to * this method will be copied. * * @param c0 the function result ({@code null} not permitted). */ public void setC0(float[] c0) { this.c0 = c0.clone(); this.dictionary.put("/C0", PDFUtils.toPDFArray(c0)); } /** * Returns the function result when x is 1.0. The returned array is a * copy. * * @return The function result when x is 1.0. */ public float[] getC1() { return this.c1.clone(); } /** * Sets the function result to be used when x is 1.0. The array passed to * this method will be copied. * * @param c1 the function result ({@code null} not permitted). */ public void setC1(float[] c1) { this.c1 = c1.clone(); this.dictionary.put("/C1", PDFUtils.toPDFArray(c1)); } }jfreepdf-2.0.1/src/main/java/org/jfree/pdf/function/Function.java000066400000000000000000000071111433176232400246500ustar00rootroot00000000000000/* ===================================================================== * JFreePDF : a fast, light-weight PDF library for the Java(tm) platform * ===================================================================== * * (C)opyright 2013-2022, by David Gilbert. All rights reserved. * * https://github.com/jfree/orsonpdf * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * If you do not wish to be bound by the terms of the GPL, an alternative * runtime license is available to JFree sponsors: * * https://github.com/sponsors/jfree * */ package org.jfree.pdf.function; import org.jfree.pdf.PDFGraphics2D; import org.jfree.pdf.dictionary.Dictionary; import org.jfree.pdf.internal.PDFObject; import org.jfree.pdf.util.Args; import org.jfree.pdf.util.PDFUtils; /** * A PDF function object. For the {@link PDFGraphics2D} class, only * {@code EXPONENTIAL_INTERPOLATION} and {@code STITCHING} are used * so far (to support gradient paint implementations). */ public abstract class Function extends PDFObject { /** The function type. */ private final FunctionType functionType; /** The function domain. */ private double[] domain; /** The function dictionary. */ protected Dictionary dictionary; /** * Creates a new function. * * @param number the PDF object number. * @param functionType the function type ({@code null} not permitted). */ protected Function(int number, FunctionType functionType) { super(number); Args.nullNotPermitted(functionType, "functionType"); this.functionType = functionType; this.domain = new double[] {0.0, 1.0}; this.dictionary = new Dictionary(); this.dictionary.put("/Domain", PDFUtils.toPDFArray(this.domain)); this.dictionary.put("/FunctionType", String.valueOf( functionType.getNumber())); } /** * Returns the function type. * * @return The function type (never {@code null}). */ public FunctionType getFunctionType() { return this.functionType; } /** * Returns the function domain. * * @return The function domain (never {@code null}). */ public double[] getDomain() { return this.domain.clone(); } /** * Sets the domain for the function. * * @param domain the domain ({@code null} not permitted). */ public void setDomain(double[] domain) { Args.nullNotPermitted(domain, "domain"); this.domain = domain.clone(); this.dictionary.put("/Domain", PDFUtils.toPDFArray(this.domain)); } /** * Returns the bytes that go between the 'obj' and 'endobj' in the * PDF output for this object. * * @return A byte array. */ @Override public byte[] getObjectBytes() { return this.dictionary.toPDFBytes(); } } jfreepdf-2.0.1/src/main/java/org/jfree/pdf/function/FunctionType.java000066400000000000000000000042001433176232400255060ustar00rootroot00000000000000/* ===================================================================== * JFreePDF : a fast, light-weight PDF library for the Java(tm) platform * ===================================================================== * * (C)opyright 2013-2022, by David Gilbert. All rights reserved. * * https://github.com/jfree/orsonpdf * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * If you do not wish to be bound by the terms of the GPL, an alternative * runtime license is available to JFree sponsors: * * https://github.com/sponsors/jfree * */ package org.jfree.pdf.function; import org.jfree.pdf.PDFGraphics2D; /** * The PDF function types. For the {@link PDFGraphics2D} class, only * {@code EXPONENTIAL_INTERPOLATION} and {@code STITCHING} are used at present * (to support gradient paint implementations). */ public enum FunctionType { /** PDF function type 0. */ SAMPLED(0), /** PDF function type 2. */ EXPONENTIAL_INTERPOLATION(2), /** PDF function type 3. */ STITCHING(3), /** PDF function type 4. */ POSTSCRIPT_CALCULATOR(4); /** The PDF number for the function type. */ private final int number; FunctionType(int number) { this.number = number; } /** * Returns the PDF number for the function type. * * @return The PDF number. */ public int getNumber() { return this.number; } } jfreepdf-2.0.1/src/main/java/org/jfree/pdf/function/StitchingFunction.java000066400000000000000000000041771433176232400265360ustar00rootroot00000000000000/* ===================================================================== * JFreePDF : a fast, light-weight PDF library for the Java(tm) platform * ===================================================================== * * (C)opyright 2013-2022, by David Gilbert. All rights reserved. * * https://github.com/jfree/orsonpdf * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * If you do not wish to be bound by the terms of the GPL, an alternative * runtime license is available to JFree sponsors: * * https://github.com/sponsors/jfree * */ package org.jfree.pdf.function; /** * A stitching function. */ public final class StitchingFunction extends Function { private Function[] functions; private float[] bounds; private float[] encode; /** * Creates a new stitching function. * * @param number the PDF object number. * @param functions the functions to be stitched. * @param bounds the bounds. * @param encode the encoding. */ public StitchingFunction(int number, Function[] functions, float[] bounds, float[] encode) { super(number, FunctionType.STITCHING); this.functions = functions; this.dictionary.put("/Functions", functions); this.bounds = bounds; this.dictionary.put("/Bounds", bounds); this.encode = encode; this.dictionary.put("/Encode", encode); } } jfreepdf-2.0.1/src/main/java/org/jfree/pdf/internal/000077500000000000000000000000001433176232400222075ustar00rootroot00000000000000jfreepdf-2.0.1/src/main/java/org/jfree/pdf/internal/FontKey.java000066400000000000000000000100101433176232400244210ustar00rootroot00000000000000/* ===================================================================== * JFreePDF : a fast, light-weight PDF library for the Java(tm) platform * ===================================================================== * * (C)opyright 2013-2022, by David Gilbert. All rights reserved. * * https://github.com/jfree/orsonpdf * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * If you do not wish to be bound by the terms of the GPL, an alternative * runtime license is available to JFree sponsors: * * https://github.com/sponsors/jfree * */ package org.jfree.pdf.internal; import java.awt.Font; import org.jfree.pdf.util.Args; import org.jfree.pdf.util.ObjectUtils; /** * A key to represent a Java2D font. This is used to maintain a mapping * between Java2D fonts and PDF fonts. */ public class FontKey { /** The key name. */ private String name; /** Flag for bold. */ private boolean isBold; /** Flag for italic. */ private boolean isItalic; /** * Creates a new key for a given font. * * @param f the font ({@code null} not permitted). * * @return The font key. */ public static FontKey createFontKey(Font f) { Args.nullNotPermitted(f, "f"); String family = f.getFamily().replace(' ', '_'); boolean bold = f.isBold(); boolean italic = f.isItalic(); return new FontKey(family, bold, italic); } /** * Creates a new font key. * * @param name the name. * @param bold the bold flag. * @param italic the italic flag. * * @see FontKey#createFontKey(java.awt.Font) */ public FontKey(String name, boolean bold, boolean italic) { this.name = name; this.isBold = bold; this.isItalic = italic; } /** * Tests this key for equality with an arbitrary object. * * @param obj the object to test against ({@code null} permitted). * * @return A boolean. */ @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final FontKey other = (FontKey) obj; if (!ObjectUtils.equals(this.name, other.name)) { return false; } if (this.isBold != other.isBold) { return false; } if (this.isItalic != other.isItalic) { return false; } return true; } /** * Returns a hash code for this instance. * * @return A hash code. */ @Override public int hashCode() { int hash = 3; hash = 97 * hash + ObjectUtils.hashCode(this.name); hash = 97 * hash + (this.isBold ? 1 : 0); hash = 97 * hash + (this.isItalic ? 1 : 0); return hash; } /** * Returns a string representation of this instance, primarily for * debugging purposes. * * @return A string. */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("FontKey[name=").append(this.name); sb.append(",isBold=").append(this.isBold); sb.append(",isItalic=").append(this.isItalic); sb.append("]"); return sb.toString(); } } jfreepdf-2.0.1/src/main/java/org/jfree/pdf/internal/PDFFont.java000066400000000000000000000110361433176232400243130ustar00rootroot00000000000000/* ===================================================================== * JFreePDF : a fast, light-weight PDF library for the Java(tm) platform * ===================================================================== * * (C)opyright 2013-2022, by David Gilbert. All rights reserved. * * https://github.com/jfree/orsonpdf * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * If you do not wish to be bound by the terms of the GPL, an alternative * runtime license is available to JFree sponsors: * * https://github.com/sponsors/jfree * */ package org.jfree.pdf.internal; import org.jfree.pdf.dictionary.Dictionary; /** * A {@link PDFObject} representing a PDF font. */ public class PDFFont extends PDFObject { /** Identifier for the standard PDF font 'Helvetica'. */ public static final String HELVETICA = "Helvetica"; /** Identifier for the standard PDF font 'Helvetica-Bold'. */ public static final String HELVETICA_BOLD = "Helvetica-Bold"; /** Identifier for the standard PDF font 'Helvetica-Oblique'. */ public static final String HELVETICA_OBLIQUE = "Helvetica-Oblique"; /** Identifier for the standard PDF font 'Helvetica-BoldOblique'. */ public static final String HELVETICA_BOLDOBLIQUE = "Helvetica-BoldOblique"; /** Identifier for the standard PDF font 'Times-Roman'. */ public static final String TIMES_ROMAN = "Times-Roman"; /** Identifier for the standard PDF font 'Times-Bold'. */ public static final String TIMES_BOLD = "Times-Bold"; /** Identifier for the standard PDF font 'Times-Italic'. */ public static final String TIMES_ITALIC = "Times-Italic"; /** Identifier for the standard PDF font 'Times-BoldItalic'. */ public static final String TIMES_BOLDITALIC = "Times-BoldItalic"; /** Identifier for the standard PDF font 'Courier'. */ public static final String COURIER = "Courier"; /** Identifier for the standard PDF font 'Courier-Bold'. */ public static final String COURIER_BOLD = "Courier-Bold"; /** Identifier for the standard PDF font 'Courier-Italic'. */ public static final String COURIER_ITALIC = "Courier-Italic"; /** Identifier for the standard PDF font 'Courier-BoldItalic'. */ public static final String COURIER_BOLDITALIC = "Courier-BoldItalic"; private String name; /** The BaseFont (for example, "/Helvetica"). */ private String baseFont; private String encoding; /** * Creates a new {@code PDFFont} instance. * * @param number the PDF object number. * @param generation the PDF object generation number. * @param name the font name within the PDF document. * @param baseFont the base font name. * @param encoding the encoding. */ public PDFFont(int number, int generation, String name, String baseFont, String encoding) { super(number, generation); this.name = name; this.baseFont = baseFont; this.encoding = encoding; } /** * Returns the name of the font within the PDF document (this is not the * same as the font name). * * @return The font name. */ public String getName() { return this.name; } /** * Returns the bytes that go between the 'obj' and 'endobj' in the * PDF output for this object. * * @return A byte array. */ @Override public byte[] getObjectBytes() { return createDictionary().toPDFBytes(); } private Dictionary createDictionary() { Dictionary dictionary = new Dictionary("/Font"); dictionary.put("/Subtype", "/Type1"); dictionary.put("/Name", this.name); dictionary.put("/BaseFont", this.baseFont); dictionary.put("/Encoding", this.encoding); return dictionary; } } jfreepdf-2.0.1/src/main/java/org/jfree/pdf/internal/PDFObject.java000066400000000000000000000102431433176232400246120ustar00rootroot00000000000000/* ===================================================================== * JFreePDF : a fast, light-weight PDF library for the Java(tm) platform * ===================================================================== * * (C)opyright 2013-2022, by David Gilbert. All rights reserved. * * https://github.com/jfree/orsonpdf * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * If you do not wish to be bound by the terms of the GPL, an alternative * runtime license is available to JFree sponsors: * * https://github.com/sponsors/jfree * */ package org.jfree.pdf.internal; import java.io.ByteArrayOutputStream; import java.io.IOException; import org.jfree.pdf.util.PDFUtils; /** * A PDF Object (also referred to as an 'Indirect Object' in the PDF * specification). Objects are identified within a document by their * PDF object number (which must be unique within the document) and their * PDF object generation number. */ public abstract class PDFObject { private int number; private int generation; /** * Creates a new instance with the specified object number and the default * generation number (0). * * @param number the object number. */ protected PDFObject(int number) { this(number, 0); } /** * Creates a new instance. * * @param number the PDF object number (must be unique within the * document). * @param generation the PDF generation number. */ protected PDFObject(int number, int generation) { this.number = number; this.generation = generation; } /** * Returns the PDF object number (specified in the constructor). * * @return The PDF object number. */ public int getNumber() { return this.number; } /** * Returns the PDF object generation number. * * @return The PDF object generation number. */ public int getGeneration() { return this.generation; } /** * Returns the PDF reference string for this object (for example, * {@code "2 0 R"}). This is the PDF object number followed by a space * followed by the PDF object generation number, followed by a space and * an {@code 'R'}. * * @return The PDF reference string. */ public String getReference() { return this.number + " " + this.generation + " R"; } /** * Returns the PDF bytes representing this object. * * @return The PDF bytes representing this object. * * @throws IOException if there is a problem writing to the byte array. */ public byte[] toPDFBytes() throws IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); baos.write(PDFUtils.toBytes(objectIntroString())); baos.write(getObjectBytes()); baos.write(PDFUtils.toBytes("endobj\n")); return baos.toByteArray(); } /** * Returns the bytes that go between the 'obj' and 'endobj' in the * PDF output for this object. * * @return A byte array. * @throws IOException if there is a problem writing to the byte array. */ public abstract byte[] getObjectBytes() throws IOException; private String objectIntroString() { StringBuilder b = new StringBuilder(); b.append(this.number).append(" ").append(this.generation).append(" "); b.append("obj\n"); return b.toString(); } } jfreepdf-2.0.1/src/main/java/org/jfree/pdf/internal/Pages.java000066400000000000000000000127071433176232400241200ustar00rootroot00000000000000/* ===================================================================== * JFreePDF : a fast, light-weight PDF library for the Java(tm) platform * ===================================================================== * * (C)opyright 2013-2022, by David Gilbert. All rights reserved. * * https://github.com/jfree/orsonpdf * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * If you do not wish to be bound by the terms of the GPL, an alternative * runtime license is available to JFree sponsors: * * https://github.com/sponsors/jfree * */ package org.jfree.pdf.internal; import java.awt.Font; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.jfree.pdf.DefaultFontMapper; import org.jfree.pdf.FontMapper; import org.jfree.pdf.PDFDocument; import org.jfree.pdf.Page; import org.jfree.pdf.dictionary.Dictionary; import org.jfree.pdf.util.Args; /** * A {@code PDFObject} that maintains the list of pages for the document. * When a {@link PDFDocument} is created, it will create an instance of * {@code Pages} and add it to the document catalog. You won't normally * interact directly with this class. */ public final class Pages extends PDFObject { /** The PDF document. */ private final PDFDocument parent; private final List pages; /** The list of font objects used in the document. */ private final List fonts; private final Map fontMap; private int nextFont = 1; private final FontMapper fontMapper; /** * Creates a new {@code Pages} object. * * @param number the PDF object number. * @param generation the PDF object generation number. * @param parent the PDF document ({@code null} not permitted). */ public Pages(int number, int generation, PDFDocument parent) { super(number, generation); Args.nullNotPermitted(parent, "parent"); this.parent = parent; this.pages = new ArrayList<>(); this.fonts = new ArrayList<>(); this.fontMap = new HashMap<>(); this.fontMapper = new DefaultFontMapper(); } /** * Returns the PDF document that the pages belong to. * * @return The PDF document (never {@code null}). */ public PDFDocument getDocument() { return this.parent; } /** * Returns a list of the pages in this object. * * @return A list of the pages. */ public List getPages() { return this.pages; } /** * Returns a list of fonts used in these pages. * * @return A list of fonts. */ public List getFonts() { return this.fonts; } /** * Returns the PDF font with the specified name, or {@code null} if * there is no font with that name. * * @param name the font name. * * @return The PDF font or {@code null}. */ public PDFFont getFont(String name) { for (PDFFont f : this.fonts) { if (f.getName().equals(name)) { return f; } } return null; } /** * Adds a page to the collection. * * @param page the page. */ public void add(Page page) { this.pages.add(page); } /** * Finds or creates a font reference for the specified AWT font. * * @param f the font ({@code null} not permitted). * * @return The font reference. */ public String findOrCreateFontReference(Font f) { // for now, map all fonts to one of the standard PDF fonts FontKey fontKey = FontKey.createFontKey(f); PDFFont pdfFont = this.fontMap.get(fontKey); if (pdfFont == null) { int number = this.parent.getNextNumber(); String name = "/F" + this.nextFont + "-" + f.getFamily().replace(' ', '_'); String baseFont = this.fontMapper.mapToBaseFont(f); this.nextFont++; pdfFont = new PDFFont(number, 0, name, "/" + baseFont, "/MacRomanEncoding"); this.fonts.add(pdfFont); this.fontMap.put(fontKey, pdfFont); } return pdfFont.getName(); } private Dictionary createDictionary() { Dictionary dictionary = new Dictionary("/Pages"); Page[] pagesArray = new Page[this.pages.size()]; for (int i = 0; i < this.pages.size(); i++) { pagesArray[i] = this.pages.get(i); } dictionary.put("/Kids", pagesArray); dictionary.put("/Count", pages.size()); return dictionary; } @Override public byte[] getObjectBytes() { return createDictionary().toPDFBytes(); } } jfreepdf-2.0.1/src/main/java/org/jfree/pdf/internal/Pattern.java000066400000000000000000000065661433176232400245040ustar00rootroot00000000000000/* ===================================================================== * JFreePDF : a fast, light-weight PDF library for the Java(tm) platform * ===================================================================== * * (C)opyright 2013-2022, by David Gilbert. All rights reserved. * * https://github.com/jfree/orsonpdf * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * If you do not wish to be bound by the terms of the GPL, an alternative * runtime license is available to JFree sponsors: * * https://github.com/sponsors/jfree * */ package org.jfree.pdf.internal; import java.awt.geom.AffineTransform; import org.jfree.pdf.dictionary.Dictionary; import org.jfree.pdf.shading.Shading; import org.jfree.pdf.util.Args; import org.jfree.pdf.util.PDFUtils; /** * A pattern object (see the concrete subclass {@link ShadingPattern}). */ public abstract class Pattern extends PDFObject { /** * A shading pattern object. */ public static final class ShadingPattern extends Pattern { private Shading shading; /** * Creates a new shading pattern. * * @param number the PDF object number. * @param shading the shading. * @param t the transform from the initial page space to Java2D space. */ public ShadingPattern(int number, Shading shading, AffineTransform t) { super(number); this.dictionary.put("/PatternType", "2"); this.dictionary.put("/Matrix", PDFUtils.transformToPDF(t)); setShading(shading); } /** * Returns the shading. * * @return The shading (never {@code null}). */ public Shading getShading() { return this.shading; } /** * Sets the shading. * * @param shading the shading ({@code null} not permitted). */ public void setShading(Shading shading) { Args.nullNotPermitted(shading, "shading"); this.shading = shading; this.dictionary.put("/Shading", this.shading); } } protected Dictionary dictionary; /** * Creates a new pattern object. * * @param number the PDF object number. */ protected Pattern(int number) { super(number); this.dictionary = new Dictionary("/Pattern"); } /** * Returns the bytes that go between the 'obj' and 'endobj' in the * PDF output for this object. * * @return A byte array. */ @Override public byte[] getObjectBytes() { return this.dictionary.toPDFBytes(); } } jfreepdf-2.0.1/src/main/java/org/jfree/pdf/package-info.java000066400000000000000000000002561433176232400235650ustar00rootroot00000000000000/** * Contains {@link org.jfree.pdf.PDFGraphics2D} and supporting * classes to allow Java2D rendering to Adobe's Portable Document Format (PDF). */ package org.jfree.pdf;jfreepdf-2.0.1/src/main/java/org/jfree/pdf/shading/000077500000000000000000000000001433176232400220105ustar00rootroot00000000000000jfreepdf-2.0.1/src/main/java/org/jfree/pdf/shading/AxialShading.java000066400000000000000000000113341433176232400252110ustar00rootroot00000000000000/* ===================================================================== * JFreePDF : a fast, light-weight PDF library for the Java(tm) platform * ===================================================================== * * (C)opyright 2013-2022, by David Gilbert. All rights reserved. * * https://github.com/jfree/orsonpdf * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * If you do not wish to be bound by the terms of the GPL, an alternative * runtime license is available to JFree sponsors: * * https://github.com/sponsors/jfree * */ package org.jfree.pdf.shading; import org.jfree.pdf.function.Function; import org.jfree.pdf.util.Args; import org.jfree.pdf.util.PDFUtils; /** * An axial shading. */ public final class AxialShading extends Shading { /** Coordinates (x0, y0, x1, y1) defining the axis. */ private double[] coords; /** The shading function. */ private Function function; /** The domain. */ private double[] domain; /** The extend flags (two of them). */ private boolean[] extend; /** * Creates a new axial shading. * * @param number the object number. * @param coords the coordinates of the axis (x1, y1, x2, y2). * @param function the function object for the shading ({@code null} not * permitted). */ public AxialShading(int number, double[] coords, Function function) { super(number, ShadingType.AXIAL); Args.arrayMustHaveLength(4, coords, "coords"); Args.nullNotPermitted(function, "function"); this.dictionary.put("/ColorSpace", "/DeviceRGB"); setCoords(coords); setFunction(function); setExtend(new boolean[] {true, true}); this.domain = new double[] {0.0, 1.0}; } /** * Returns a copy of the axis coordinates array {@code (x1, y1, x2, y2)}. * * @return A copy of the axis coordinates array (never {@code null}). */ public double[] getCoords() { return this.coords.clone(); } /** * Sets the axis coordinates array {@code (x1, y1, x2, y2)}. * * @param coords the axis coordinates ({@code null} not permitted). */ public void setCoords(double[] coords) { Args.arrayMustHaveLength(4, coords, "coords"); this.coords = coords.clone(); this.dictionary.put("/Coords", PDFUtils.toPDFArray(this.coords)); } /** * Returns the function for this shading. * * @return The function (never {@code null}). */ public Function getFunction() { return this.function; } /** * Sets the function for this shading. * * @param function the function ({@code null} not permitted). */ public void setFunction(Function function) { Args.nullNotPermitted(function, "function"); this.function = function; this.dictionary.put("/Function", this.function); } /** * Returns the function domain. The default value is {@code [0.0, 1.0]}. * * @return The function domain. */ public double[] getDomain() { return this.domain.clone(); } /** * Sets the domain. * * @param domain the domain (array must have length 2). */ public void setDomain(double[] domain) { Args.arrayMustHaveLength(2, domain, "domain"); this.domain = domain.clone(); this.dictionary.put("/Domain", PDFUtils.toPDFArray(this.domain)); } /** * Returns the extend array. * * @return The extend array. */ public boolean[] getExtend() { return this.extend.clone(); } /** * Sets the extend array. * * @param extend the extend array (must have length 2). */ public void setExtend(boolean[] extend) { Args.arrayMustHaveLength(2, extend, "extend"); this.extend = extend.clone(); this.dictionary.put("/Extend", PDFUtils.toPDFArray(this.extend)); } }jfreepdf-2.0.1/src/main/java/org/jfree/pdf/shading/RadialShading.java000066400000000000000000000114251433176232400253500ustar00rootroot00000000000000/* ===================================================================== * JFreePDF : a fast, light-weight PDF library for the Java(tm) platform * ===================================================================== * * (C)opyright 2013-2022, by David Gilbert. All rights reserved. * * https://github.com/jfree/orsonpdf * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * If you do not wish to be bound by the terms of the GPL, an alternative * runtime license is available to JFree sponsors: * * https://github.com/sponsors/jfree * */ package org.jfree.pdf.shading; import org.jfree.pdf.function.Function; import org.jfree.pdf.util.Args; import org.jfree.pdf.util.PDFUtils; /** * A radial shading. */ public final class RadialShading extends Shading { /** Coordinates (x0, y0, r0, x1, y1, r1). */ private double[] coords; /** The shading function. */ private Function function; /** The domain. */ private double[] domain; /** The extend flags (two of them). */ private boolean[] extend; /** * Creates a new radial shading instance. * * @param number the PDF object number. * @param coords the coordinates {@code (x1, y1, r1, x2, y2, r2)}. * @param function the interpolation function ({@code null} not * permitted). */ public RadialShading(int number, double[] coords, Function function) { super(number, ShadingType.RADIAL); Args.arrayMustHaveLength(6, coords, "coords"); Args.nullNotPermitted(function, "function"); this.dictionary.put("/ColorSpace", "/DeviceRGB"); setCoords(coords); setFunction(function); setExtend(new boolean[] {true, true}); this.domain = new double[] {0.0, 1.0}; } /** * Returns a copy of the axis coordinates array {@code (x1, y1, x2, y2)}. * * @return A copy of the axis coordinates array (never {@code null}). */ public double[] getCoords() { return this.coords.clone(); } /** * Sets the array containing the coordinates {@code (x1, y1, r1, x2, y2, * r2)} of the starting circle and the ending circle. * * @param coords the circle coordinates ({@code null} not permitted). */ public void setCoords(double[] coords) { Args.arrayMustHaveLength(6, coords, "coords"); this.coords = coords.clone(); this.dictionary.put("/Coords", PDFUtils.toPDFArray(this.coords)); } /** * Returns the function for this shading. * * @return The function (never {@code null}). */ public Function getFunction() { return this.function; } /** * Sets the function for this shading. * * @param function the function ({@code null} not permitted). */ public void setFunction(Function function) { Args.nullNotPermitted(function, "function"); this.function = function; this.dictionary.put("/Function", this.function); } /** * Returns the function domain. The default value is {@code [0.0, 1.0]}. * * @return The function domain. */ public double[] getDomain() { return this.domain.clone(); } /** * Sets the domain. * * @param domain the domain (array must have length 2). */ public void setDomain(double[] domain) { Args.arrayMustHaveLength(2, domain, "domain"); this.domain = domain.clone(); this.dictionary.put("/Domain", PDFUtils.toPDFArray(this.domain)); } /** * Returns the extend array. * * @return The extend array. */ public boolean[] getExtend() { return this.extend.clone(); } /** * Sets the extend array. * * @param extend the extend array (must have length 2). */ public void setExtend(boolean[] extend) { Args.arrayMustHaveLength(2, extend, "extend"); this.extend = extend.clone(); this.dictionary.put("/Extend", PDFUtils.toPDFArray(this.extend)); } } jfreepdf-2.0.1/src/main/java/org/jfree/pdf/shading/Shading.java000066400000000000000000000052501433176232400242320ustar00rootroot00000000000000/* ===================================================================== * JFreePDF : a fast, light-weight PDF library for the Java(tm) platform * ===================================================================== * * (C)opyright 2013-2022, by David Gilbert. All rights reserved. * * https://github.com/jfree/orsonpdf * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * If you do not wish to be bound by the terms of the GPL, an alternative * runtime license is available to JFree sponsors: * * https://github.com/sponsors/jfree * */ package org.jfree.pdf.shading; import org.jfree.pdf.dictionary.Dictionary; import org.jfree.pdf.internal.PDFObject; import org.jfree.pdf.util.Args; /** * A PDF shading object (this class is abstract, subclasses implement * particular shading types). */ public abstract class Shading extends PDFObject { /** The shading type. */ private ShadingType shadingType; /** The dictionary. */ protected Dictionary dictionary; /** * Creates a new shading instance. * * @param number the PDF object number. * @param shadingType the shading type ({@code null} not permitted). */ protected Shading(int number, ShadingType shadingType) { super(number); Args.nullNotPermitted(shadingType, "shadingType"); this.shadingType = shadingType; this.dictionary = new Dictionary(); this.dictionary.put("/ShadingType", String.valueOf( shadingType.getNumber())); } /** * Returns the shading type. * * @return The shading type (never {@code null}). */ public ShadingType getShadingType() { return this.shadingType; } /** * Returns the bytes that go between the 'obj' and 'endobj' in the * PDF output for this object. * * @return A byte array. */ @Override public byte[] getObjectBytes() { return this.dictionary.toPDFBytes(); } } jfreepdf-2.0.1/src/main/java/org/jfree/pdf/shading/ShadingType.java000066400000000000000000000040421433176232400250720ustar00rootroot00000000000000/* ===================================================================== * JFreePDF : a fast, light-weight PDF library for the Java(tm) platform * ===================================================================== * * (C)opyright 2013-2022, by David Gilbert. All rights reserved. * * https://github.com/jfree/orsonpdf * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * If you do not wish to be bound by the terms of the GPL, an alternative * runtime license is available to JFree sponsors: * * https://github.com/sponsors/jfree * */ package org.jfree.pdf.shading; /** * An enumeration of the PDF shading types. */ public enum ShadingType { FUNCTION(1), /** Axial shading. */ AXIAL(2), /** Radial shading. */ RADIAL(3), FREE_FORM(4), LATTICE_FORM(5), COONS(6), TENSOR(7); /** The PDF number for this shading type. */ private final int number; /** * Creates a new shading type. * * @param number the PDF number for the shading type. */ ShadingType(int number) { this.number = number; } /** * Returns the PDF number for the shading type. * * @return The PDF number for the shading type. */ public int getNumber() { return this.number; } } jfreepdf-2.0.1/src/main/java/org/jfree/pdf/shading/package-info.java000066400000000000000000000002131433176232400251730ustar00rootroot00000000000000/** * Contains shading classes that support the {@link org.jfree.pdf.PDFGraphics2D} * implementation. */ package org.jfree.pdf.shading;jfreepdf-2.0.1/src/main/java/org/jfree/pdf/stream/000077500000000000000000000000001433176232400216665ustar00rootroot00000000000000jfreepdf-2.0.1/src/main/java/org/jfree/pdf/stream/GraphicsStream.java000066400000000000000000000443741433176232400254610ustar00rootroot00000000000000/* ===================================================================== * JFreePDF : a fast, light-weight PDF library for the Java(tm) platform * ===================================================================== * * (C)opyright 2013-2022, by David Gilbert. All rights reserved. * * https://github.com/jfree/orsonpdf * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * If you do not wish to be bound by the terms of the GPL, an alternative * runtime license is available to JFree sponsors: * * https://github.com/sponsors/jfree * */ package org.jfree.pdf.stream; import java.awt.AlphaComposite; import java.awt.BasicStroke; import java.awt.Color; import java.awt.Font; import java.awt.GradientPaint; import java.awt.Image; import java.awt.RadialGradientPaint; import java.awt.Shape; import java.awt.Stroke; import java.awt.geom.AffineTransform; import java.awt.geom.Line2D; import java.awt.geom.NoninvertibleTransformException; import java.awt.geom.Path2D; import java.awt.geom.PathIterator; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.text.DecimalFormat; import java.text.DecimalFormatSymbols; import org.jfree.pdf.PDFGraphics2D; import org.jfree.pdf.Page; import org.jfree.pdf.util.Args; import org.jfree.pdf.util.PDFUtils; /** * A {@code Stream} that contains graphics for the PDF document that * can be generated via the {@link PDFGraphics2D} class. The {@link Page} * class will create a {@code GraphicsStream} instance to represent its * content. You won't normally interact directly with this class, it is * intended that the {@code PDFGraphics2D} class drives the calls to the * methods of this class. */ public class GraphicsStream extends Stream { /** * The page the graphics stream belongs to. We need this reference to * our "parent" so that we can access fonts in the document. */ private Page page; /** The stream content. */ private ByteArrayOutputStream content; /** The most recent font applied. */ private Font font; /** The most recent alpha transparency value (in the range 0 to 255). */ private int alpha; private AffineTransform prevTransInv; /** * The decimal formatter for coordinates of geometrical shapes. */ private DecimalFormat geometryFormat; /** * The decimal formatter for transform matrices. */ private DecimalFormat transformFormat; /** * Creates a new instance. * * @param number the PDF object number. * @param page the parent page ({@code null} not permitted). */ public GraphicsStream(int number, Page page) { super(number); this.page = page; this.content = new ByteArrayOutputStream(); this.font = new Font("Dialog", Font.PLAIN, 12); this.alpha = 255; // force the formatters to use a '.' for the decimal point DecimalFormatSymbols dfs = new DecimalFormatSymbols(); dfs.setDecimalSeparator('.'); this.geometryFormat = new DecimalFormat("0.##", dfs); this.transformFormat = new DecimalFormat("0.######", dfs); } private void addContent(String s) { try { this.content.write(PDFUtils.toBytes(s)); } catch (IOException e) { throw new RuntimeException(e); } } /** * Pushes the current graphics state onto a stack for later retrieval. */ public void pushGraphicsState() { addContent("q\n"); } /** * Pops the graphics state that was previously pushed onto the stack. */ public void popGraphicsState() { addContent("Q\n"); } /** * Applies a graphics transform. * * @param t the transform ({@code null} not permitted). */ public void applyTransform(AffineTransform t) { StringBuilder b = new StringBuilder(); b.append(transformDP(t.getScaleX())).append(" "); b.append(transformDP(t.getShearY())).append(" "); b.append(transformDP(t.getShearX())).append(" "); b.append(transformDP(t.getScaleY())).append(" "); b.append(transformDP(t.getTranslateX())).append(" "); b.append(transformDP(t.getTranslateY())).append(" cm\n"); addContent(b.toString()); } /** * Sets the transform. * * @param t the transform ({@code null} not permitted). */ public void setTransform(AffineTransform t) { AffineTransform tt = new AffineTransform(t); try { AffineTransform inv = tt.createInverse(); AffineTransform comb; if (this.prevTransInv != null) { comb = new AffineTransform(this.prevTransInv); comb.concatenate(tt); } else { comb = tt; } this.prevTransInv = inv; applyTransform(comb); } catch (NoninvertibleTransformException e) { // do nothing } } /** * Applies a text transform. * * @param t the transform ({@code null} not permitted). */ private void applyTextTransform(AffineTransform t) { StringBuilder b = new StringBuilder(); b.append(t.getScaleX()).append(" "); b.append(t.getShearY()).append(" "); b.append(t.getShearX()).append(" "); b.append(t.getScaleY()).append(" "); b.append(t.getTranslateX()).append(" "); b.append(t.getTranslateY()).append(" Tm\n"); addContent(b.toString()); } /** * Applies the specified clip to the current clip. * * @param clip the clip ({@code null} not permitted). */ public void applyClip(Shape clip) { Args.nullNotPermitted(clip, "clip"); StringBuilder b = new StringBuilder(); Path2D p = new Path2D.Double(clip); b.append(getPDFPath(p)); b.append("W n\n"); addContent(b.toString()); } /** * Applies a stroke. If the stroke is not an instance of * {@code BasicStroke} this method will do nothing. * * @param s the stroke. */ public void applyStroke(Stroke s) { if (!(s instanceof BasicStroke)) { return; } BasicStroke bs = (BasicStroke) s; StringBuilder b = new StringBuilder(); b.append(bs.getLineWidth()).append(" ").append("w\n"); b.append(bs.getEndCap()).append(" J\n"); b.append(bs.getLineJoin()).append(" j\n"); float[] dashArray = bs.getDashArray(); if (dashArray != null) { b.append(PDFUtils.toPDFArray(dashArray)).append(" 0 d\n"); } else { b.append("[] 0 d\n"); } addContent(b.toString()); } /** * Applies a color for stroking. * * @param c the color ({@code null} not permitted). */ public void applyStrokeColor(Color c) { float red = c.getRed() / 255f; float green = c.getGreen() / 255f; float blue = c.getBlue() / 255f; StringBuilder b = new StringBuilder(); b.append(red).append(" ").append(green).append(" ").append(blue) .append(" RG\n"); addContent(b.toString()); applyAlpha(c.getAlpha()); } /** * Applies a color for filling. * * @param c the color ({@code null} not permitted). */ public void applyFillColor(Color c) { float red = c.getRed() / 255f; float green = c.getGreen() / 255f; float blue = c.getBlue() / 255f; StringBuilder b = new StringBuilder(); b.append(red).append(" ").append(green).append(" ").append(blue) .append(" rg\n"); addContent(b.toString()); applyAlpha(c.getAlpha()); } /** * Applies a {@code GradientPaint} for stroking. * * @param gp the gradient paint ({@code null} not permitted). */ public void applyStrokeGradient(GradientPaint gp) { // delegate arg checking String patternName = this.page.findOrCreatePattern(gp); StringBuilder b = new StringBuilder("/Pattern CS\n"); b.append(patternName).append(" SCN\n"); addContent(b.toString()); } /** * Applies a {@code RadialGradientPaint} for stroking. * * @param rgp the gradient paint ({@code null} not permitted). */ public void applyStrokeGradient(RadialGradientPaint rgp) { // delegate arg checking String patternName = this.page.findOrCreatePattern(rgp); StringBuilder b = new StringBuilder("/Pattern CS\n"); b.append(patternName).append(" SCN\n"); addContent(b.toString()); } /** * Applies a {@code GradientPaint} for filling. * * @param gp the gradient paint ({@code null} not permitted). */ public void applyFillGradient(GradientPaint gp) { // delegate arg checking String patternName = this.page.findOrCreatePattern(gp); StringBuilder b = new StringBuilder("/Pattern cs\n"); b.append(patternName).append(" scn\n"); addContent(b.toString()); } /** * Applies a {@code RadialGradientPaint} for filling. * * @param rgp the gradient paint ({@code null} not permitted). */ public void applyFillGradient(RadialGradientPaint rgp) { // delegate arg checking String patternName = this.page.findOrCreatePattern(rgp); StringBuilder b = new StringBuilder("/Pattern cs\n"); b.append(patternName).append(" scn\n"); addContent(b.toString()); } private float alphaFactor = 1.0f; /** * Applies the specified alpha composite. * * @param alphaComp the alpha composite ({@code null} permitted). */ public void applyComposite(AlphaComposite alphaComp) { if (alphaComp == null) { this.alphaFactor = 1.0f; } else { this.alphaFactor = alphaComp.getAlpha(); int a = (int) (alphaComp.getAlpha() * 255f); if (this.alpha != a) { String name = this.page.findOrCreateGSDictionary(a); StringBuilder b = new StringBuilder(); b.append(name).append(" gs\n"); addContent(b.toString()); this.alpha = a; } } } /** * Applies the alpha transparency. * * @param alpha the new alpha value (in the range {@code 0} * to {@code 255}). */ private void applyAlpha(int alpha) { int a = (int) (alpha * this.alphaFactor); if (this.alpha != a) { String name = this.page.findOrCreateGSDictionary(a); StringBuilder b = new StringBuilder(); b.append(name).append(" gs\n"); addContent(b.toString()); this.alpha = a; } } private String geomDP(double d) { if (this.geometryFormat != null) { return geometryFormat.format(d); } else { return String.valueOf(d); } } private String transformDP(double d) { if (this.transformFormat != null) { return transformFormat.format(d); } else { return String.valueOf(d); } } /** * Draws the specified line. * * @param line the line ({@code null} not permitted). */ public void drawLine(Line2D line) { StringBuilder b = new StringBuilder(); b.append(geomDP(line.getX1())).append(" ").append(geomDP(line.getY1())) .append(" ").append("m\n"); b.append(geomDP(line.getX2())).append(" ").append(geomDP(line.getY2())) .append(" ").append("l\n"); b.append("S\n"); addContent(b.toString()); } /** * Draws the specified path. * * @param path the path ({@code null} not permitted). */ public void drawPath2D(Path2D path) { StringBuilder b = new StringBuilder(); b.append(getPDFPath(path)).append("S\n"); addContent(b.toString()); } /** * Fills the specified path. * * @param path the path ({@code null} not permitted). */ public void fillPath2D(Path2D path) { StringBuilder b = new StringBuilder(); b.append(getPDFPath(path)).append("f\n"); addContent(b.toString()); } /** * Applies the specified font (in fact, no change is made to the stream * until the next call * to {@link #drawString(java.lang.String, float, float)}). * * @param font the font. */ public void applyFont(Font font) { this.font = font; } /** * Draws a string at the specified location. * * @param text the text. * @param x the x-coordinate. * @param y the y-coordinate. */ public void drawString(String text, float x, float y) { // we need to get the reference for the current font (creating a // new font object if there isn't already one) String fontRef = this.page.findOrCreateFontReference(this.font); addContent("BT "); AffineTransform t = new AffineTransform(1.0, 0.0, 0.0, -1.0, 0.0, y * 2); applyTextTransform(t); StringBuilder b = new StringBuilder(); b.append(fontRef).append(" ").append(this.font.getSize()) .append(" Tf "); b.append(geomDP(x)).append(" ").append(geomDP(y)).append(" Td (") .append(text).append(") Tj ET\n"); addContent(b.toString()); } /** * Draws the specified image into the rectangle {@code (x, y, w, h)}. * * @param img the image. * @param x the x-coordinate of the destination. * @param y the y-coordinate of the destination. * @param w the width of the destination. * @param h the height of the destination. */ public void drawImage(Image img, int x, int y, int w, int h) { String imageRef = this.page.addImage(img, true); StringBuilder b = new StringBuilder(); b.append("q\n"); b.append(geomDP(w)).append(" 0 0 ").append(geomDP(h)).append(" "); b.append(geomDP(x)).append(" ").append(geomDP(y)).append(" cm\n"); b.append(imageRef).append(" Do\n"); b.append("Q\n"); addContent(b.toString()); } /** * A utility method to convert a {@code Path2D} instance to a PDF * path string. * * @param path the path ({@code null} not permitted). * * @return The string. */ private String getPDFPath(Path2D path) { StringBuilder b = new StringBuilder(); float[] coords = new float[6]; float lastX = 0; float lastY = 0; PathIterator iterator = path.getPathIterator(null); while (!iterator.isDone()) { int type = iterator.currentSegment(coords); switch (type) { case (PathIterator.SEG_MOVETO): b.append(geomDP(coords[0])).append(" "); b.append(geomDP(coords[1])).append(" m\n"); lastX = coords[0]; lastY = coords[1]; break; case (PathIterator.SEG_LINETO): b.append(geomDP(coords[0])).append(" "); b.append(geomDP(coords[1])).append(" l\n"); lastX = coords[0]; lastY = coords[1]; break; case (PathIterator.SEG_QUADTO): // PDF doesn't support quadratic Bézier curves; it only supports // cubic Bézier curves, so we need to perform "degree elevation" // to convert the quadratic Bézier curve into a cubic Bézier // curve. This is the only way to preserve the original curve's // shape accurately for all arbitrary cases. // // https://pages.mtu.edu/~shene/COURSES/cs3621/NOTES/spline/Bezier/bezier-elev.html // // https://en.wikipedia.org/wiki/Bézier_curve#Degree_elevation // // A quadratic curve has degree 2; a cubic curve has degree 3. // // The code is simplified to improve performance and accuracy final float x0 = ( lastX + ( 2f * coords[0] ) ) / 3f; final float y0 = ( lastY + ( 2f * coords[1] ) ) / 3f; final float x1 = ( ( 2f * coords[0] ) + coords[2] ) / 3f; final float y1 = ( ( 2f * coords[1] ) + coords[3] ) / 3f; b.append(geomDP(x0)).append(" "); b.append(geomDP(y0)).append(" "); b.append(geomDP(x1)).append(" "); b.append(geomDP(y1)).append(" "); b.append(geomDP(coords[2])).append(" "); b.append(geomDP(coords[3])).append(" c\n"); lastX = coords[2]; lastY = coords[3]; break; case (PathIterator.SEG_CUBICTO): b.append(geomDP(coords[0])).append(" "); b.append(geomDP(coords[1])).append(" "); b.append(geomDP(coords[2])).append(" "); b.append(geomDP(coords[3])).append(" "); b.append(geomDP(coords[4])).append(" "); b.append(geomDP(coords[5])).append(" c\n"); lastX = coords[4]; lastY = coords[5]; break; case (PathIterator.SEG_CLOSE): b.append("h\n"); break; default: break; } iterator.next(); } return b.toString(); } @Override public byte[] getRawStreamData() { return this.content.toByteArray(); } } jfreepdf-2.0.1/src/main/java/org/jfree/pdf/stream/PDFImage.java000066400000000000000000000104731433176232400241120ustar00rootroot00000000000000/* ===================================================================== * JFreePDF : a fast, light-weight PDF library for the Java(tm) platform * ===================================================================== * * (C)opyright 2013-2022, by David Gilbert. All rights reserved. * * https://github.com/jfree/orsonpdf * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * If you do not wish to be bound by the terms of the GPL, an alternative * runtime license is available to JFree sponsors: * * https://github.com/sponsors/jfree * */ package org.jfree.pdf.stream; import java.awt.Color; import java.awt.Graphics2D; import java.awt.Image; import java.awt.image.BufferedImage; import org.jfree.pdf.dictionary.Dictionary; import org.jfree.pdf.util.Args; /** * Represents an image in a PDF document. */ public class PDFImage extends Stream { /** The width. */ int width; /** The height. */ int height; /** The image. */ Image image; String softMaskImageRef; /** * Creates a new image object. * * @param number the PDF object number. * @param img the AWT image object ({@code null} not permitted). * @param softMaskImageRef the soft mask image reference ({@code null} * permitted). */ public PDFImage(int number, Image img, String softMaskImageRef) { super(number); Args.nullNotPermitted(img, "img"); this.width = img.getWidth(null); this.height = img.getHeight(null); this.image = img; this.softMaskImageRef = softMaskImageRef; } /** * Returns the raw image data. Each call will resample the image data * and populate a new array. Note that the stream may encode this * data before it is written to the PDF output. * * @return The raw stream data. */ @Override public byte[] getRawStreamData() { BufferedImage bi; if (!(this.image instanceof BufferedImage)) { bi = new BufferedImage(this.width, this.height, BufferedImage.TYPE_INT_ARGB); Graphics2D g2 = bi.createGraphics(); g2.setBackground(new Color(255, 255, 255, 0)); g2.clearRect(0, 0, this.width, this.height); g2.drawImage(this.image, 0, 0, null); } else { bi = (BufferedImage) this.image; } // create a byte array of the image data to go in the PDF byte[] result = new byte[this.width * this.height * 3]; int i = 0; for (int hh = this.height - 1; hh >= 0; hh--) { for (int ww = 0; ww < this.width; ww++) { int rgb = bi.getRGB(ww, hh); result[i++] = (byte) (rgb >> 16); result[i++] = (byte) (rgb >> 8); result[i++] = (byte) rgb; } } return result; } /** * Creates a dictionary reflecting the current configuration for this * image. * * @param streamLength the stream length. * * @return A dictionary. */ @Override protected Dictionary createDictionary(int streamLength) { Dictionary dictionary = super.createDictionary(streamLength); dictionary.setType("/XObject"); dictionary.put("/Subtype", "/Image"); dictionary.put("/ColorSpace", "/DeviceRGB"); dictionary.put("/BitsPerComponent", 8); dictionary.put("/Width", this.width); dictionary.put("/Height", this.height); if (this.softMaskImageRef != null) { dictionary.put("/SMask", this.softMaskImageRef); } return dictionary; } } jfreepdf-2.0.1/src/main/java/org/jfree/pdf/stream/PDFSoftMaskImage.java000066400000000000000000000074601433176232400255640ustar00rootroot00000000000000/* ===================================================================== * JFreePDF : a fast, light-weight PDF library for the Java(tm) platform * ===================================================================== * * (C)opyright 2013-2022, by David Gilbert. All rights reserved. * * https://github.com/jfree/orsonpdf * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * If you do not wish to be bound by the terms of the GPL, an alternative * runtime license is available to JFree sponsors: * * https://github.com/sponsors/jfree * */ package org.jfree.pdf.stream; import java.awt.Graphics2D; import java.awt.Image; import java.awt.image.BufferedImage; import org.jfree.pdf.dictionary.Dictionary; import org.jfree.pdf.util.Args; /** * Represents a soft mask image in a PDF document. */ public class PDFSoftMaskImage extends Stream { /** The width. */ int width; /** The height. */ int height; /** The image. */ Image image; /** * Creates a new soft mask image object. * * @param number the PDF object number. * @param img the AWT image object ({@code null} not permitted). */ public PDFSoftMaskImage(int number, Image img) { super(number); Args.nullNotPermitted(img, "img"); this.width = img.getWidth(null); this.height = img.getHeight(null); this.image = img; } /** * Returns the raw image data. Each call will resample the image data * and populate a new array. Note that the stream may encode this * data before it is written to the PDF output. * * @return The raw stream data. */ @Override public byte[] getRawStreamData() { BufferedImage bi; if (!(this.image instanceof BufferedImage)) { bi = new BufferedImage(this.width, this.height, BufferedImage.TYPE_INT_ARGB); Graphics2D g2 = bi.createGraphics(); g2.drawImage(this.image, 0, 0, null); } else { bi = (BufferedImage) this.image; } // create a byte array of the image data to go in the PDF byte[] result = new byte[this.width * this.height]; int i = 0; for (int hh = this.height - 1; hh >= 0; hh--) { for (int ww = 0; ww < this.width; ww++) { int rgb = bi.getRGB(ww, hh); result[i++] = (byte) (rgb >> 24); } } return result; } /** * Creates a dictionary reflecting the current configuration for this * image. * * @param streamLength the stream length. * * @return A dictionary. */ @Override protected Dictionary createDictionary(int streamLength) { Dictionary dictionary = super.createDictionary(streamLength); dictionary.setType("/XObject"); dictionary.put("/Subtype", "/Image"); dictionary.put("/ColorSpace", "/DeviceGray"); dictionary.put("/BitsPerComponent", 8); dictionary.put("/Width", this.width); dictionary.put("/Height", this.height); return dictionary; } } jfreepdf-2.0.1/src/main/java/org/jfree/pdf/stream/Stream.java000066400000000000000000000105411433176232400237650ustar00rootroot00000000000000/* ===================================================================== * JFreePDF : a fast, light-weight PDF library for the Java(tm) platform * ===================================================================== * * (C)opyright 2013-2022, by David Gilbert. All rights reserved. * * https://github.com/jfree/orsonpdf * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * If you do not wish to be bound by the terms of the GPL, an alternative * runtime license is available to JFree sponsors: * * https://github.com/sponsors/jfree * */ package org.jfree.pdf.stream; import org.jfree.pdf.filter.Filter; import org.jfree.pdf.util.Args; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.List; import org.jfree.pdf.dictionary.Dictionary; import org.jfree.pdf.internal.PDFObject; import org.jfree.pdf.util.PDFUtils; /** * A {@code Stream} is a {@link PDFObject} that has a {@link Dictionary} * and a byte stream. */ public abstract class Stream extends PDFObject { /** Filters (if any) to apply to the stream data. */ private final List filters; /** * Creates a new stream. * * @param number the PDF object number. */ Stream(int number) { super(number); this.filters = new ArrayList<>(); } /** * Adds a filter to the stream. * * @param f the filter ({@code null} not permitted). * * @see #removeFilters() */ public void addFilter(Filter f) { Args.nullNotPermitted(f, "f"); this.filters.add(f); } /** * Removes any filters that were previously added. * * @see #addFilter(org.jfree.pdf.filter.Filter) */ public void removeFilters() { this.filters.clear(); } /** * Returns the PDF bytes for this stream object, with all current filters * applied. * * @return The PDF bytes for this stream object. * * @throws IOException if there is a problem writing to the byte array. */ @Override public byte[] getObjectBytes() throws IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte[] streamData = getRawStreamData(); for (Filter f: this.filters) { streamData = f.encode(streamData); } Dictionary dictionary = createDictionary(streamData.length); baos.write(dictionary.toPDFBytes()); baos.write(PDFUtils.toBytes("stream\n")); baos.write(streamData); baos.write(PDFUtils.toBytes("endstream\n")); return baos.toByteArray(); } /** * Creates the dictionary for this stream object. The dictionary will * be populated with the stream length and the decode values for any * filters that are currently applied. * * @param streamLength the stream length. * * @return The dictionary. */ protected Dictionary createDictionary(int streamLength) { Dictionary dictionary = new Dictionary(); dictionary.put("/Length", streamLength); if (!this.filters.isEmpty()) { String[] decodes = new String[this.filters.size()]; int count = this.filters.size(); for (int i = 0; i < count; i++) { Filter f = this.filters.get(count - i - 1); decodes[i] = f.getFilterType().getDecode(); } dictionary.put("/Filter", decodes); } return dictionary; } /** * Returns the raw data for the stream. * * @return The raw data for the stream. */ public abstract byte[] getRawStreamData(); } jfreepdf-2.0.1/src/main/java/org/jfree/pdf/util/000077500000000000000000000000001433176232400213505ustar00rootroot00000000000000jfreepdf-2.0.1/src/main/java/org/jfree/pdf/util/Args.java000066400000000000000000000063471433176232400231210ustar00rootroot00000000000000/* ===================================================================== * JFreePDF : a fast, light-weight PDF library for the Java(tm) platform * ===================================================================== * * (C)opyright 2013-2022, by David Gilbert. All rights reserved. * * https://github.com/jfree/orsonpdf * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * If you do not wish to be bound by the terms of the GPL, an alternative * runtime license is available to JFree sponsors: * * https://github.com/sponsors/jfree * */ package org.jfree.pdf.util; /** * A utility class that performs checks for method argument validity. */ public class Args { private Args() { // no need to instantiate this } /** * Checks that an argument is non-{@code null} and throws an * {@code IllegalArgumentException} otherwise. * * @param obj the object to check for {@code null}. * @param ref the text name for the parameter (to include in the exception * message). */ public static void nullNotPermitted(Object obj, String ref) { if (obj == null) { throw new IllegalArgumentException("Null '" + ref + "' argument."); } } /** * Checks an array to ensure it has the correct length and throws an * {@code IllegalArgumentException} if it does not. * * @param length the required length. * @param array the array to check. * @param ref the text name of the array parameter (to include in the * exception message). */ public static void arrayMustHaveLength(int length, boolean[] array, String ref) { nullNotPermitted(array, "array"); if (array.length != length) { throw new IllegalArgumentException("Array '" + ref + "' requires length " + length); } } /** * Checks an array to ensure it has the correct length and throws an * {@code IllegalArgumentException} if it does not. * * @param length the required length. * @param array the array to check. * @param ref the text name of the array parameter (to include in the * exception message). */ public static void arrayMustHaveLength(int length, double[] array, String ref) { nullNotPermitted(array, "array"); if (array.length != length) { throw new IllegalArgumentException("Array '" + ref + "' requires length " + length); } } } jfreepdf-2.0.1/src/main/java/org/jfree/pdf/util/GradientPaintKey.java000066400000000000000000000075501433176232400254240ustar00rootroot00000000000000/* ===================================================================== * JFreePDF : a fast, light-weight PDF library for the Java(tm) platform * ===================================================================== * * (C)opyright 2013-2022, by David Gilbert. All rights reserved. * * https://github.com/jfree/orsonpdf * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * If you do not wish to be bound by the terms of the GPL, an alternative * runtime license is available to JFree sponsors: * * https://github.com/sponsors/jfree * */ package org.jfree.pdf.util; import java.awt.GradientPaint; /** * A wrapper for a {@code GradientPaint} that can be used as the key for * a {@code HashMap}. This class is used internally by * {@code PDFGraphics2D} to track and re-use gradient definitions. * {@code GradientPaint} itself does not implement the {@code equals()} and * {@code hashCode()} methods, so it doesn't make a good key for a {@code Map}. */ public final class GradientPaintKey { private GradientPaint paint; /** * Creates a new instance based on the specified {@code paint}. * * @param paint the paint ({@code null} not permitted). */ public GradientPaintKey(GradientPaint paint) { Args.nullNotPermitted(paint, "paint"); this.paint = paint; } /** * Returns the {@code GradientPaint} that was supplied to the * constructor. * * @return The {@code GradientPaint} (never {@code null}). */ public GradientPaint getPaint() { return this.paint; } /** * Checks this instance for equality with an arbitrary object. * * @param obj the object to test against ({@code null} permitted). * * @return A boolean. */ @Override public boolean equals(Object obj) { if (obj == this) { return true; } if (!(obj instanceof GradientPaintKey)) { return false; } GradientPaintKey that = (GradientPaintKey) obj; GradientPaint thisGP = this.paint; GradientPaint thatGP = that.getPaint(); if (!thisGP.getColor1().equals(thatGP.getColor1())) { return false; } if (!thisGP.getColor2().equals(thatGP.getColor2())) { return false; } if (!thisGP.getPoint1().equals(thatGP.getPoint1())) { return false; } if (!thisGP.getPoint2().equals(thatGP.getPoint2())) { return false; } if (thisGP.getTransparency() != thatGP.getTransparency()) { return false; } if (thisGP.isCyclic() != thatGP.isCyclic()) { return false; } return true; } /** * Returns a hash code for this instance. * * @return A hash code. */ @Override public int hashCode() { int hash = 5; hash = 47 * hash + this.paint.getPoint1().hashCode(); hash = 47 * hash + this.paint.getPoint2().hashCode(); hash = 47 * hash + this.paint.getColor1().hashCode(); hash = 47 * hash + this.paint.getColor2().hashCode(); return hash; } } jfreepdf-2.0.1/src/main/java/org/jfree/pdf/util/GraphicsUtils.java000066400000000000000000000127131433176232400250000ustar00rootroot00000000000000/* ===================================================================== * JFreePDF : a fast, light-weight PDF library for the Java(tm) platform * ===================================================================== * * (C)opyright 2013-2022, by David Gilbert. All rights reserved. * * https://github.com/jfree/orsonpdf * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * If you do not wish to be bound by the terms of the GPL, an alternative * runtime license is available to JFree sponsors: * * https://github.com/sponsors/jfree * */ package org.jfree.pdf.util; import java.awt.Polygon; import java.awt.Shape; import java.awt.geom.Arc2D; import java.awt.geom.Ellipse2D; import java.awt.geom.GeneralPath; import java.awt.geom.Line2D; import java.awt.geom.Path2D; import java.awt.geom.Rectangle2D; import java.awt.geom.RoundRectangle2D; import java.awt.image.BufferedImage; import java.awt.image.ColorModel; import java.awt.image.RenderedImage; import java.awt.image.WritableRaster; import java.util.Hashtable; /** * Utility methods for shapes and images. */ public class GraphicsUtils { private GraphicsUtils() { // no need to instantiate this } /** * Returns a shape that is more or less equivalent to the supplied shape. * * @param shape the shape ({@code null} not permitted). * * @return A copy of the shape (it may not be the same class). */ public static Shape copyOf(Shape shape) { Args.nullNotPermitted(shape, "shape"); if (shape instanceof Line2D) { Line2D l = (Line2D) shape; return new Line2D.Double(l.getX1(), l.getY1(), l.getX2(), l.getY2()); } if (shape instanceof Rectangle2D) { Rectangle2D r = (Rectangle2D) shape; return new Rectangle2D.Double(r.getX(), r.getY(), r.getWidth(), r.getHeight()); } if (shape instanceof RoundRectangle2D) { RoundRectangle2D rr = (RoundRectangle2D) shape; return new RoundRectangle2D.Double(rr.getX(), rr.getY(), rr.getWidth(), rr.getHeight(), rr.getArcWidth(), rr.getArcHeight()); } if (shape instanceof Arc2D) { Arc2D arc = (Arc2D) shape; return new Arc2D.Double(arc.getX(), arc.getY(), arc.getWidth(), arc.getHeight(), arc.getAngleStart(), arc.getAngleExtent(), arc.getArcType()); } if (shape instanceof Ellipse2D) { Ellipse2D ell = (Ellipse2D) shape; return new Ellipse2D.Double(ell.getX(), ell.getY(), ell.getWidth(), ell.getHeight()); } if (shape instanceof Polygon) { Polygon p = (Polygon) shape; return new Polygon(p.xpoints, p.ypoints, p.npoints); } return new Path2D.Double(shape); } /** * Creates a polygon for from the specified {@code x} and * {@code y} coordinates. * * @param xPoints the x-points. * @param yPoints the y-points. * @param nPoints the number of points to use for the polyline. * @param close closed? * * @return A polygon. */ public static GeneralPath createPolygon(int[] xPoints, int[] yPoints, int nPoints, boolean close) { GeneralPath p = new GeneralPath(); p.moveTo(xPoints[0], yPoints[0]); for (int i = 1; i < nPoints; i++) { p.lineTo(xPoints[i], yPoints[i]); } if (close) { p.closePath(); } return p; } /** * Converts a rendered image to a {@code BufferedImage}. This utility * method has come from a forum post by Jim Moore at: *

* * http://www.jguru.com/faq/view.jsp?EID=114602 * * @param img the rendered image. * * @return A buffered image. */ public static BufferedImage convertRenderedImage(RenderedImage img) { if (img instanceof BufferedImage) { return (BufferedImage) img; } ColorModel cm = img.getColorModel(); int width = img.getWidth(); int height = img.getHeight(); WritableRaster raster = cm.createCompatibleWritableRaster(width, height); boolean isAlphaPremultiplied = cm.isAlphaPremultiplied(); Hashtable properties = new Hashtable(); String[] keys = img.getPropertyNames(); if (keys != null) { for (int i = 0; i < keys.length; i++) { properties.put(keys[i], img.getProperty(keys[i])); } } BufferedImage result = new BufferedImage(cm, raster, isAlphaPremultiplied, properties); img.copyData(raster); return result; } } jfreepdf-2.0.1/src/main/java/org/jfree/pdf/util/ObjectUtils.java000066400000000000000000000045201433176232400244430ustar00rootroot00000000000000/* ===================================================================== * JFreePDF : a fast, light-weight PDF library for the Java(tm) platform * ===================================================================== * * (C)opyright 2013-2022, by David Gilbert. All rights reserved. * * https://github.com/jfree/orsonpdf * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * If you do not wish to be bound by the terms of the GPL, an alternative * runtime license is available to JFree sponsors: * * https://github.com/sponsors/jfree * */ package org.jfree.pdf.util; /** * Some utility methods. */ public class ObjectUtils { private ObjectUtils() { // no need to instantiate } /** * Returns {@code true} if the objects are equal or both * {@code null}, and {@code false} otherwise. In Java 7, we * could use the {@code Objects} class instead. * * @param obj1 object 1. * @param obj2 object 2. * * @return A boolean. */ public static boolean equals(Object obj1, Object obj2) { if (obj1 == null) { return obj2 == null; } else { return obj1.equals(obj2); } } /** * Returns the hash code for the object, or 0 if the object is * {@code null}. In Java 7, we could use the {@code Objects} * class instead. * * @param obj the object ({@code null} permitted). * * @return The hash code or 0. */ public static int hashCode(Object obj) { if (obj == null) { return 0; } return obj.hashCode(); } } jfreepdf-2.0.1/src/main/java/org/jfree/pdf/util/PDFUtils.java000066400000000000000000000130601433176232400236450ustar00rootroot00000000000000/* ===================================================================== * JFreePDF : a fast, light-weight PDF library for the Java(tm) platform * ===================================================================== * * (C)opyright 2013-2022, by David Gilbert. All rights reserved. * * https://github.com/jfree/orsonpdf * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * If you do not wish to be bound by the terms of the GPL, an alternative * runtime license is available to JFree sponsors: * * https://github.com/sponsors/jfree * */ package org.jfree.pdf.util; import java.awt.geom.AffineTransform; import java.io.UnsupportedEncodingException; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; /** * Various utility functions for working with the PDF format. */ public class PDFUtils { private PDFUtils() { // no need to instantiate this } /** * A utility method to convert a boolean[] to a PDF array string. * * @param b the array ({@code null} not permitted). * * @return The string. */ public static String toPDFArray(boolean[] b) { Args.nullNotPermitted(b, "b"); StringBuilder sb = new StringBuilder("["); for (int i = 0; i < b.length; i++) { if (i != 0) { sb.append(" "); } sb.append(String.valueOf(b[i])); } return sb.append("]").toString(); } /** * A utility method to convert a float[] to a PDF array string. * * @param f the array ({@code null} not permitted). * * @return The string. */ public static String toPDFArray(float[] f) { Args.nullNotPermitted(f, "f"); StringBuilder b = new StringBuilder("["); for (int i = 0; i < f.length; i++) { if (i != 0) { b.append(" "); } b.append(String.valueOf(f[i])); } return b.append("]").toString(); } /** * A utility method to convert a double[] to a PDF array string. * * @param d the array ({@code null} not permitted). * * @return The string. */ public static String toPDFArray(double[] d) { Args.nullNotPermitted(d, "d"); StringBuilder b = new StringBuilder("["); for (int i = 0; i < d.length; i++) { if (i != 0) { b.append(" "); } b.append(String.valueOf(d[i])); } return b.append("]").toString(); } /** * Returns a Java2D AffineTransform in PDF matrix format. * * @param t the transform ({@code null} not permitted). * * @return A PDF matrix string. */ public static String transformToPDF(AffineTransform t) { Args.nullNotPermitted(t, "t"); StringBuilder b = new StringBuilder("["); b.append(t.getScaleX()).append(" "); b.append(t.getShearY()).append(" "); b.append(t.getShearX()).append(" "); b.append(t.getScaleY()).append(" "); b.append(t.getTranslateX()).append(" "); b.append(t.getTranslateY()); return b.append("]").toString(); } /** * Returns a string in standard PDF date format representing the specified * date (in the default timezone). * * @param date the date ({@code null} not permitted). * * @return A string in standard PDF date format. */ public static String toDateFormat(Date date) { Calendar c = Calendar.getInstance(); c.setTime(date); return toPDFDateFormat(c); } /** * Returns a string in standard PDF date format representing the date * contained by the specified calendar. * * @param calendar the date and timezone ({@code null} not permitted). * * @return A string in standard PDF date format. */ public static String toPDFDateFormat(Calendar calendar) { Date d = calendar.getTime(); DateFormat df1 = new SimpleDateFormat("yyyyMMddHHmmss"); DateFormat df2 = new SimpleDateFormat("Z"); String part1 = df1.format(d); String part2 = df2.format(d); String tzinfo; if (part2.equals("z")) { tzinfo = "Z00'00'"; } else { tzinfo = part2.substring(0, 3) + "'" + part2.substring(4) + "'"; } return "D:" + part1 + tzinfo; } /** * A utility method to convert a string to US-ASCII byte format. * * @param s the string. * * @return The corresponding byte array. */ public static byte[] toBytes(String s) { byte[] result = null; try { result = s.getBytes("US-ASCII"); } catch (UnsupportedEncodingException ex) { throw new RuntimeException(ex); } return result; } } jfreepdf-2.0.1/src/main/java/org/jfree/pdf/util/RadialGradientPaintKey.java000066400000000000000000000074601433176232400265410ustar00rootroot00000000000000/* ===================================================================== * JFreePDF : a fast, light-weight PDF library for the Java(tm) platform * ===================================================================== * * (C)opyright 2013-2022, by David Gilbert. All rights reserved. * * https://github.com/jfree/orsonpdf * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * If you do not wish to be bound by the terms of the GPL, an alternative * runtime license is available to JFree sponsors: * * https://github.com/sponsors/jfree * */ package org.jfree.pdf.util; import java.awt.RadialGradientPaint; import java.util.Arrays; /** * A wrapper for a {@code RadialGradientPaint} that can be used as the key * for a {@code HashMap}. This class is used internally by * {@code PDFGraphics2D} to track and re-use gradient definitions. * {@code RadialGradientPaint} itself does not implement the {@code equals()} * and {@code hashCode()} methods, so it doesn't make a good key for a * {@code Map}. */ public class RadialGradientPaintKey { private RadialGradientPaint paint; float f = 0.0f; /** * Creates a new key instance. * * @param rgp the radial gradient paint ({@code null} not permitted). */ public RadialGradientPaintKey(RadialGradientPaint rgp) { Args.nullNotPermitted(rgp, "rgp"); this.paint = rgp; } /** * Returns the {@code RadialGradientPaint} that was supplied to the * constructor. * * @return The {@code RadialGradientPaint} (never {@code null}). */ public RadialGradientPaint getPaint() { return this.paint; } /** * Tests this instance for equality with an arbitrary object. * * @param obj the object to test ({@code null} permitted). * * @return A boolean. */ @Override public boolean equals(Object obj) { if (obj == this) { return true; } if (! (obj instanceof RadialGradientPaint)) { return false; } RadialGradientPaint that = (RadialGradientPaint) obj; if (!this.paint.getCenterPoint().equals(that.getCenterPoint())) { return false; } if (!this.paint.getFocusPoint().equals(that.getCenterPoint())) { return false; } if (!Arrays.equals(this.paint.getColors(), that.getColors())) { return false; } if (!Arrays.equals(this.paint.getFractions(), that.getFractions())) { return false; } return true; } /** * Returns a hash code for this instance. * * @return A hash code. */ @Override public int hashCode() { int hash = 5; hash = 47 * hash + this.paint.getCenterPoint().hashCode(); hash = 47 * hash + this.paint.getFocusPoint().hashCode(); hash = 47 * hash + Float.floatToIntBits(this.paint.getRadius()); hash = 47 * hash + Arrays.hashCode(this.paint.getColors()); hash = 47 * hash + Arrays.hashCode(this.paint.getFractions()); return hash; } } jfreepdf-2.0.1/src/main/java/org/jfree/pdf/util/package-info.java000066400000000000000000000001311433176232400245320ustar00rootroot00000000000000/** * A utility package for the JFreePDF library. */ package org.jfree.pdf.util;jfreepdf-2.0.1/src/test/000077500000000000000000000000001433176232400150525ustar00rootroot00000000000000jfreepdf-2.0.1/src/test/java/000077500000000000000000000000001433176232400157735ustar00rootroot00000000000000jfreepdf-2.0.1/src/test/java/org/000077500000000000000000000000001433176232400165625ustar00rootroot00000000000000jfreepdf-2.0.1/src/test/java/org/jfree/000077500000000000000000000000001433176232400176555ustar00rootroot00000000000000jfreepdf-2.0.1/src/test/java/org/jfree/pdf/000077500000000000000000000000001433176232400204265ustar00rootroot00000000000000jfreepdf-2.0.1/src/test/java/org/jfree/pdf/TestGraphics2D.java000066400000000000000000000673201433176232400240670ustar00rootroot00000000000000/* ===================================================================== * JFreePDF : a fast, light-weight PDF library for the Java(tm) platform * ===================================================================== * * (C)opyright 2013-2022, by David Gilbert. All rights reserved. * * https://github.com/jfree/orsonpdf * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * If you do not wish to be bound by the terms of the GPL, an alternative * runtime license is available to JFree sponsors: * * https://github.com/sponsors/jfree * */ package org.jfree.pdf; import java.awt.BasicStroke; import java.awt.Color; import java.awt.Font; import java.awt.FontMetrics; import java.awt.GradientPaint; import java.awt.Graphics2D; import java.awt.Image; import java.awt.Rectangle; import java.awt.RenderingHints; import java.awt.Shape; import java.awt.geom.AffineTransform; import java.awt.geom.Line2D; import java.awt.geom.Point2D; import java.awt.geom.Rectangle2D; import java.awt.image.BufferedImage; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Disabled; import static org.junit.jupiter.api.Assertions.*; /** * Some tests for a Graphics2D implementation. All tests should pass with the * Graphics2D instance from a BufferedImage (which we can treat as a reference * implementation). */ public class TestGraphics2D { private Graphics2D g2; @BeforeEach public void setUp() { // to test a reference implementation, use this Graphics2D from a // BufferedImage in the JDK // BufferedImage img = new BufferedImage(10, 20, BufferedImage.TYPE_INT_ARGB); // this.g2 = img.createGraphics(); // Test PDFGraphics2D... PDFDocument pdfDoc = new PDFDocument(); Page page = pdfDoc.createPage(new Rectangle(0, 0, 300, 200)); this.g2 = page.getGraphics2D(); } /** * Checks that the default transform is an identity transform. */ @Test public void checkDefaultTransform() { assertEquals(new AffineTransform(), g2.getTransform()); } /** * Modifying the transform returned by the Graphics2D should not affect * the state of the Graphics2D. In order for that to happen, the method * should be returning a copy of the actual transform object. */ @Test public void checkGetTransformSafety() { AffineTransform t = g2.getTransform(); t.rotate(Math.PI); assertNotEquals(t, g2.getTransform()); assertEquals(new AffineTransform(), g2.getTransform()); } /** * A basic check that setTransform() does indeed update the transform. */ @Test public void setTransform() { AffineTransform t = new AffineTransform(1, 2, 3, 4, 5, 6); g2.setTransform(t); assertEquals(t, g2.getTransform()); t.setTransform(6, 5, 4, 3, 2, 1); g2.setTransform(t); assertEquals(t, g2.getTransform()); // in spite of the docs saying that null is accepted this gives // a NullPointerException with SunGraphics2D. // g2.setTransform(null); // assertEquals(new AffineTransform(), g2.getTransform()); } /** * When calling setTransform() the caller passes in an AffineTransform * instance. If the caller retains a reference to the AffineTransform * and subsequently modifies it, we don't want the Graphics2D object to * be affected...so it should be making an internal copy of the * AffineTransform. */ @Test public void checkSetTransformSafety() { AffineTransform t = AffineTransform.getTranslateInstance(1.0, 2.0); g2.setTransform(t); assertEquals(t, g2.getTransform()); t.setToRotation(Math.PI); assertNotEquals(t, g2.getTransform()); } @Test public void checkSetNonInvertibleTransform() { AffineTransform t = AffineTransform.getScaleInstance(0.0, 0.0); g2.setTransform(t); assertEquals(t, g2.getTransform()); // after setting the clip, we cannot retrieve it while the transform // is non-invertible... Rectangle2D clip = new Rectangle2D.Double(1, 2, 3, 4); g2.setClip(clip); assertNull(g2.getClip()); g2.setTransform(new AffineTransform()); assertEquals(new Rectangle2D.Double(0, 0, 0, 0), g2.getClip().getBounds2D()); } /** * A check for a call to transform() with a rotation, that follows a * translation. */ @Test public void checkTransform() { AffineTransform t = new AffineTransform(); this.g2.setTransform(t); this.g2.translate(30, 30); AffineTransform rt = AffineTransform.getRotateInstance(Math.PI / 2.0, 300, 200); this.g2.transform(rt); t = this.g2.getTransform(); assertEquals(0, t.getScaleX(), EPSILON); assertEquals(0, t.getScaleY(), EPSILON); assertEquals(-1.0, t.getShearX(), EPSILON); assertEquals(1.0, t.getShearY(), EPSILON); assertEquals(530.0, t.getTranslateX(), EPSILON); assertEquals(-70, t.getTranslateY(), EPSILON); } @Test public void checkTransformNull() { try { this.g2.transform(null); fail("Expected a NullPointerException."); } catch (NullPointerException e) { // this exception is expected } } /** * Basic checks for the scale(x, y) method. */ @Test public void scale() { g2.scale(0.5, 2.0); assertEquals(AffineTransform.getScaleInstance(0.5, 2.0), g2.getTransform()); g2.scale(2.0, -1.0); assertEquals(AffineTransform.getScaleInstance(1.0, -2.0), g2.getTransform()); } /** * Checks that a call to scale(x, y) on top of an existing translation * gives the correct values. */ @Test public void translateFollowedByScale() { g2.translate(2, 3); assertEquals(AffineTransform.getTranslateInstance(2.0, 3.0), g2.getTransform()); g2.scale(10, 20); assertEquals(new AffineTransform(10.0, 0.0, 0.0, 20.0, 2.0, 3.0), g2.getTransform()); } /** * Checks that a call to translate(x, y) on top of an existing scale * gives the correct values. */ @Test public void scaleFollowedByTranslate() { g2.scale(2, 2); assertEquals(AffineTransform.getScaleInstance(2.0, 2.0), g2.getTransform()); g2.translate(10, 20); assertEquals(new AffineTransform(2.0, 0.0, 0.0, 2.0, 20.0, 40.0), g2.getTransform()); } private static final double EPSILON = 0.000000001; @Test public void scaleFollowedByRotate() { g2.scale(2, 2); assertEquals(AffineTransform.getScaleInstance(2.0, 2.0), g2.getTransform()); g2.rotate(Math.PI / 3); AffineTransform t = g2.getTransform(); assertEquals(1.0, t.getScaleX(), EPSILON); assertEquals(1.0, t.getScaleY(), EPSILON); assertEquals(-1.7320508075688772, t.getShearX(), EPSILON); assertEquals(1.7320508075688772, t.getShearY(), EPSILON); assertEquals(0.0, t.getTranslateX(), EPSILON); assertEquals(0.0, t.getTranslateY(), EPSILON); } @Test public void rotateFollowedByScale() { g2.rotate(Math.PI); assertEquals(AffineTransform.getRotateInstance(Math.PI), g2.getTransform()); g2.scale(2.0, 2.0); assertEquals(new AffineTransform(-2.0, 0.0, 0.0, -2.0, 0.0, 0.0), g2.getTransform()); } /** * Checks that the getClip() method returns a different object than what * was passed to setClip(), and that multiple calls to getClip() return * a new object each time. */ @Test public void checkGetClipSafety() { Rectangle2D r = new Rectangle2D.Double(0, 0, 1, 1); this.g2.setClip(r); Shape s = this.g2.getClip(); assertNotSame(r, s); Shape s2 = this.g2.getClip(); assertNotSame(s, s2); } /** * The default user clip should be {@code null}. */ @Test public void checkDefaultClip() { assertNull(g2.getClip(), "Default user clip should be null."); } /** * Checks that getClipBounds() is returning an integer approximation of * the bounds. */ @Test public void checkGetClipBounds() { Rectangle2D r = new Rectangle2D.Double(0.25, 0.25, 0.5, 0.5); this.g2.setClip(r); assertEquals(new Rectangle(0, 0, 1, 1), this.g2.getClipBounds()); } /** * Checks that getClipBounds() returns {@code null} when the clip is * {@code null}. */ @Test public void checkGetClipBoundsWhenClipIsNull() { this.g2.setClip(null); assertNull(this.g2.getClipBounds()); } /** * Simple check that the clip() methods creates an intersection with the * existing clip region. */ @Test public void checkClip() { Rectangle2D r = new Rectangle2D.Double(1.0, 1.0, 3.0, 3.0); this.g2.setClip(r); this.g2.clip(new Rectangle2D.Double(0.0, 0.0, 2.0, 2.0)); assertEquals(new Rectangle2D.Double(1.0, 1.0, 1.0, 1.0), this.g2.getClip().getBounds2D()); } @Test public void checkNonIntersectingClip() { Rectangle2D r = new Rectangle2D.Double(1.0, 1.0, 3.0, 3.0); this.g2.setClip(r); this.g2.clip(new Rectangle2D.Double(5.0, 5.0, 1.0, 1.0)); assertTrue(this.g2.getClip().getBounds2D().isEmpty()); } /** * After applying a scale transformation, getClip() will return a * modified clip. */ @Test public void checkClipAfterScaling() { Rectangle2D r = new Rectangle2D.Double(1, 2, 3, 0.5); this.g2.setClip(r); assertEquals(r, this.g2.getClip().getBounds2D()); this.g2.scale(0.5, 2.0); assertEquals(new Rectangle2D.Double(2, 1, 6, 0.25), this.g2.getClip().getBounds2D()); // check that we get a good intersection when clipping after the // scaling has been done... r = new Rectangle2D.Double(3, 0, 2, 2); this.g2.clip(r); assertEquals(new Rectangle2D.Double(3, 1, 2, 0.25), this.g2.getClip().getBounds2D()); } /** * Translating will change the existing clip. */ @Test public void checkClipAfterTranslate() { Rectangle2D clip = new Rectangle2D.Double(0.0, 0.0, 1.0, 1.0); this.g2.setClip(clip); assertEquals(clip, this.g2.getClip().getBounds2D()); this.g2.translate(1.0, 2.0); assertEquals(new Rectangle(-1, -2, 1 ,1), this.g2.getClip().getBounds2D()); } @Test public void checkSetClipAfterTranslate() { this.g2.translate(1.0, 2.0); this.g2.setClip(0, 0, 1, 1); assertEquals(new Rectangle(0, 0, 1, 1), this.g2.getClip().getBounds()); this.g2.translate(1.0, 2.0); assertEquals(new Rectangle(-1, -2, 1, 1), this.g2.getClip().getBounds()); } /** * Transforming will change the reported clipping shape. */ @Test public void checkClipAfterTransform() { Rectangle2D clip = new Rectangle2D.Double(0, 0, 1, 1); this.g2.setClip(clip); assertEquals(clip, this.g2.getClip().getBounds2D()); this.g2.transform(AffineTransform.getRotateInstance(Math.PI)); assertEquals(new Rectangle(-1, -1, 1 ,1), this.g2.getClip().getBounds2D()); this.g2.setTransform(new AffineTransform()); assertEquals(clip, this.g2.getClip().getBounds2D()); } /** * Clipping with a line makes no sense, but the API allows it so we should * not fail. In fact, running with a JDK Graphics2D (from a BufferedImage) * it seems that the bounding rectangle of the line is used for clipping... * does that make sense? Switching off the test for now. */ @Test @Disabled public void checkClipWithLine2D() { Rectangle2D r = new Rectangle2D.Double(1.0, 1.0, 3.0, 3.0); this.g2.setClip(r); this.g2.clip(new Line2D.Double(1.0, 2.0, 3.0, 4.0)); //assertEquals(new Rectangle2D.Double(1.0, 2.0, 2.0, 2.0), // this.g2.getClip().getBounds2D()); //assertTrue(this.g2.getClip().getBounds2D().isEmpty()); } /** * Clipping with a null argument is "not recommended" according to the * latest API docs (https://bugs.java.com/bugdatabase/view_bug.do?bug_id=6206189). */ @Test public void checkClipWithNullArgument() { // when there is a current clip set, a null pointer exception is expected this.g2.setClip(new Rectangle2D.Double(1.0, 2.0, 3.0, 4.0)); Exception exception = assertThrows(NullPointerException.class, () -> this.g2.clip(null)); this.g2.setClip(null); try { this.g2.clip(null); } catch (Exception e) { fail("No exception expected."); } } /** * A simple check for a call to clipRect(). */ @Test public void checkClipRect() { Rectangle2D clip = new Rectangle2D.Double(0, 0, 5, 5); this.g2.setClip(clip); this.g2.clipRect(2, 1, 4, 2); assertEquals(new Rectangle(2, 1, 3, 2), g2.getClip().getBounds2D()); } @Test public void checkClipRectParams() { Rectangle2D clip = new Rectangle2D.Double(0, 0, 5, 5); this.g2.setClip(clip); // negative width this.g2.clipRect(2, 1, -4, 2); assertTrue(this.g2.getClip().getBounds2D().isEmpty()); // negative height this.g2.setClip(clip); this.g2.clipRect(2, 1, 4, -2); assertTrue(this.g2.getClip().getBounds2D().isEmpty()); } @Test public void checkDrawStringWithNullString() { try { g2.drawString((String) null, 1, 2); fail("There should be a NullPointerException."); } catch (NullPointerException e) { // this exception is expected } try { g2.drawString((String) null, 1.0f, 2.0f); fail("There should be a NullPointerException."); } catch (NullPointerException e) { // this exception is expected } } @Test public void checkDrawStringWithEmptyString() { // this should not cause any exception g2.setRenderingHint(PDFHints.KEY_DRAW_STRING_TYPE, PDFHints.VALUE_DRAW_STRING_TYPE_VECTOR); g2.drawString("", 1, 2); g2.setRenderingHint(PDFHints.KEY_DRAW_STRING_TYPE, null); g2.drawString("", 1, 2); } /** * Some checks for the create() method. */ @Test public void checkCreate() { this.g2.setClip(new Rectangle(1, 2, 3, 4)); Graphics2D copy = (Graphics2D) g2.create(); assertEquals(copy.getBackground(), g2.getBackground()); assertEquals(copy.getClip().getBounds2D(), g2.getClip().getBounds2D()); assertEquals(copy.getColor(), g2.getColor()); assertEquals(copy.getComposite(), g2.getComposite()); assertEquals(copy.getFont(), g2.getFont()); assertEquals(copy.getRenderingHints(), g2.getRenderingHints()); assertEquals(copy.getStroke(), g2.getStroke()); assertEquals(copy.getTransform(), g2.getTransform()); } /** * The setPaint() method allows a very minor state leakage in the sense * that it is possible to modify a GradientPaint externally after a call * to the setPaint() method and have it impact the state of the * Graphics2D implementation. Avoiding this would require cloning the * Paint object, but there is no good way to do that for an arbitrary * Paint instance. */ @Test public void checkSetPaintSafety() { Point2D pt1 = new Point2D.Double(1.0, 2.0); Point2D pt2 = new Point2D.Double(3.0, 4.0); GradientPaint gp = new GradientPaint(pt1, Color.RED, pt2, Color.BLUE); this.g2.setPaint(gp); assertEquals(gp, this.g2.getPaint()); assertSame(gp, this.g2.getPaint()); pt1.setLocation(7.0, 7.0); assertEquals(gp, this.g2.getPaint()); } /** * According to the Javadocs, setting the paint to null should have no * impact on the current paint (that is, the call is silently ignored). */ @Test public void checkSetPaintNull() { this.g2.setPaint(Color.RED); // this next call should have no impact this.g2.setPaint(null); assertEquals(Color.RED, this.g2.getPaint()); } /** * Passing a Color to setPaint() also updates the color, but not the * background color. */ @Test public void checkSetPaintAlsoUpdatesColorButNotBackground() { Color existingBackground = this.g2.getBackground(); this.g2.setPaint(Color.MAGENTA); assertEquals(Color.MAGENTA, this.g2.getPaint()); assertEquals(Color.MAGENTA, this.g2.getColor()); assertEquals(existingBackground, this.g2.getBackground()); } @Test public void checkSetColorAlsoUpdatesPaint() { this.g2.setColor(Color.MAGENTA); assertEquals(Color.MAGENTA, this.g2.getPaint()); assertEquals(Color.MAGENTA, this.g2.getColor()); } /** * The behaviour of the reference implementation has been observed as * ignoring null. This matches the documented behaviour of the * setPaint() method. */ @Test public void checkSetColorNull() { this.g2.setColor(Color.RED); this.g2.setColor(null); assertEquals(Color.RED, this.g2.getColor()); } /** * Setting the background color does not change the color or paint. */ @Test public void checkSetBackground() { this.g2.setBackground(Color.CYAN); assertEquals(Color.CYAN, this.g2.getBackground()); assertNotEquals(Color.CYAN, this.g2.getColor()); assertNotEquals(Color.CYAN, this.g2.getPaint()); } /** * The behaviour of the reference implementation has been observed as * allowing null (this is inconsistent with the behaviour of setColor()). */ @Test public void checkSetBackgroundNull() { this.g2.setBackground(Color.RED); this.g2.setBackground(null); assertNull(this.g2.getBackground()); } /** * Since the setBackground() method is allowing null, we should ensure * that the clearRect() method doesn't fail in this case. With no * background color, the clearRect() method should be a no-op but there * is no easy way to test for that. */ @Test public void checkClearRectWithNullBackground() { this.g2.setBackground(null); this.g2.clearRect(1, 2, 3, 4); //no exceptions and we're good } /** * In the reference implementation, setting a null composite has been * observed to throw an IllegalArgumentException. */ @Test public void checkSetCompositeNull() { try { this.g2.setComposite(null); fail("Expected an IllegalArgumentException."); } catch (IllegalArgumentException e) { // this exception is expected in the test } } @Test public void checkSetStrokeNull() { try { this.g2.setStroke(null); fail("Expected an IllegalArgumentException."); } catch (IllegalArgumentException e) { // this exception is expected in the test } } /** * Basic check of set then get. */ @Test public void checkSetRenderingHint() { this.g2.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_PURE); assertEquals(RenderingHints.VALUE_STROKE_PURE, this.g2.getRenderingHint(RenderingHints.KEY_STROKE_CONTROL)); } /** * The reference implementation has been observed to throw a * NullPointerException when the key is null. */ @Test public void checkSetRenderingHintWithNullKey() { try { this.g2.setRenderingHint(null, "XYZ"); fail("NullPointerException is expected here."); } catch (NullPointerException e) { // this is expected } } /** * The reference implementation has been observed to accept a null key * and return null in that case. */ @Test public void checkGetRenderingHintWithNullKey() { assertNull(this.g2.getRenderingHint(null)); } /** * Check setting a hint with a value that doesn't match the key. */ @Test public void checkSetRenderingHintWithInconsistentValue() { try { this.g2.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_ANTIALIAS_DEFAULT); fail("Expected an IllegalArgumentException."); } catch (IllegalArgumentException e) { // we expect this exception } } /** * A call to getRenderingHints() is returning a copy of the hints, so * changing it will not affect the state of the Graphics2D instance. */ @Test public void checkGetRenderingHintsSafety() { this.g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF); RenderingHints hints = this.g2.getRenderingHints(); hints.put(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); assertEquals(RenderingHints.VALUE_ANTIALIAS_OFF, this.g2.getRenderingHint(RenderingHints.KEY_ANTIALIASING)); } @Test public void checkSetRenderingHintsNull() { try { this.g2.setRenderingHints(null); fail("NullPointerException expected."); } catch (NullPointerException e) { // this is expected } } @Test public void checkHit() { Shape shape = new Rectangle2D.Double(0.0, 0.0, 1.0, 1.0); Rectangle r = new Rectangle(2, 2, 2, 2); assertFalse(this.g2.hit(r, shape, false)); this.g2.scale(3.0, 3.0); assertTrue(this.g2.hit(r, shape, false)); } @Test public void checkHitForOutline() { Shape shape = new Rectangle2D.Double(0.0, 0.0, 3.0, 3.0); Rectangle r = new Rectangle(1, 1, 1, 1); assertFalse(this.g2.hit(r, shape, true)); this.g2.scale(0.5, 0.5); // now the rectangle is entirely inside the shape, but does not touch // the outline... assertTrue(this.g2.hit(r, shape, true)); } /** * We have observed in the reference implementation that setting the font * to null does not change the current font setting. */ @Test public void checkSetFontNull() { Font f = new Font("Serif", Font.PLAIN, 8); this.g2.setFont(f); assertEquals(f, this.g2.getFont()); this.g2.setFont(null); assertEquals(f, this.g2.getFont()); } @Test public void checkDefaultStroke() { BasicStroke s = (BasicStroke) this.g2.getStroke(); assertEquals(BasicStroke.CAP_SQUARE, s.getEndCap()); assertEquals(1.0f, s.getLineWidth(), EPSILON); assertEquals(BasicStroke.JOIN_MITER, s.getLineJoin()); } /** * Check that a null GlyphVector throws a {@code NullPointerException}. */ @Test public void drawGlyphVectorNull() { try { g2.drawGlyphVector(null, 10, 10); fail("Expecting a NullPointerException."); } catch (NullPointerException e) { // expected } } /** * Check the shear() method. */ @Test public void shear() { g2.setTransform(new AffineTransform()); g2.shear(2.0, 3.0); assertEquals(new AffineTransform(1, 3, 2, 1, 0, 0), g2.getTransform()); } /** * Checks a translate() followed by a shear(). */ @Test public void shearFollowingTranslate() { g2.setTransform(new AffineTransform()); g2.translate(10.0, 20.0); g2.shear(2.0, 3.0); assertEquals(new AffineTransform(1, 3, 2, 1, 10, 20), g2.getTransform()); } @Test public void drawImageWithNullBackground() { Image img = new BufferedImage(10, 10, BufferedImage.TYPE_INT_ARGB); g2.drawImage(img, 10, 10, null, null); assertTrue(true); // won't get here if there's an exception above } /** * https://github.com/jfree/jfreesvg/issues/6 */ @Test public void drawImageWithNullTransform() { Image img = new BufferedImage(10, 10, BufferedImage.TYPE_INT_ARGB); g2.drawImage(img, null, null); assertTrue(true); // won't get here if there's an exception above } @Test public void drawImageWithNullImage() { // API docs say method does nothing if img is null // still seems to return true assertTrue(g2.drawImage(null, 10, 20, null)); assertTrue(g2.drawImage(null, 10, 20, 30, 40, null)); assertTrue(g2.drawImage(null, 10, 20, Color.YELLOW, null)); assertTrue(g2.drawImage(null, 1, 2, 3, 4, Color.RED, null)); assertTrue(g2.drawImage(null, 1, 2, 3, 4, 5, 6, 7, 8, null)); assertTrue(g2.drawImage(null, 1, 2, 3, 4, 5, 6, 7, 8, Color.RED, null)); } @Test public void drawImageWithNegativeDimensions() { Image img = new BufferedImage(10, 10, BufferedImage.TYPE_INT_ARGB); assertTrue(g2.drawImage(img, 1, 2, -10, 10, null)); assertTrue(g2.drawImage(img, 1, 2, 10, -10, null)); } /** * A test to check whether setting a transform on the Graphics2D affects * the results of text measurements performed via getFontMetrics(). */ @Test public void testGetFontMetrics() { Font f = new Font(Font.SANS_SERIF, Font.PLAIN, 10); FontMetrics fm = this.g2.getFontMetrics(f); int w = fm.stringWidth("ABC"); Rectangle2D bounds = fm.getStringBounds("ABC", this.g2); // after scaling, the string width is not changed this.g2.setTransform(AffineTransform.getScaleInstance(3.0, 2.0)); fm = this.g2.getFontMetrics(f); assertEquals(w, fm.stringWidth("ABC")); assertEquals(bounds.getWidth(), fm.getStringBounds("ABC", this.g2).getWidth(), EPSILON); } @Test public void drawImageWithNullImageOp() { BufferedImage img = new BufferedImage(10, 10, BufferedImage.TYPE_INT_ARGB); g2.drawImage(img, null, 2, 3); assertTrue(true); // won't get here if there's an exception above } /** * API docs say the method does nothing when called with a null image. */ @Test public void drawRenderedImageWithNullImage() { g2.drawRenderedImage(null, AffineTransform.getTranslateInstance(0, 0)); assertTrue(true); // won't get here if there's an exception above } }