pax_global_header00006660000000000000000000000064134727451460014527gustar00rootroot0000000000000052 comment=58a6372b5a96dd96f8111314784b4d58fa9424f6 vectorgraphics2d-0.13/000077500000000000000000000000001347274514600147235ustar00rootroot00000000000000vectorgraphics2d-0.13/.travis.yml000066400000000000000000000010271347274514600170340ustar00rootroot00000000000000sudo: required language: java jdk: - oraclejdk8 - oraclejdk7 before_install: - sudo add-apt-repository ppa:cwchien/gradle -y - sudo apt-get update -q - sudo apt-get install gradle -y - export PATH=/usr/bin:$PATH # Use gradle from /usr/bin - gradle --version notifications: irc: channels: - "chat.freenode.net#vectorgraphics2d" on_success: change on_failure: always template: - "%{repository} (%{branch}:%{commit} by %{author}): %{message} (%{build_url})" after_success: - gradle cobertura coveralls vectorgraphics2d-0.13/CHANGES.rst000066400000000000000000000055671347274514600165420ustar00rootroot00000000000000VectorGraphics2D 0.13 (2017-08-08) ================================== - Java 7 and Gradle 4 are now required to build VectorGraphics2D - Restored compression support for PDF files - All processors now have a standard constructor - Added more JavaDoc documentation VectorGraphics2D 0.12 (2017-07-28) ================================== Be aware that due to restructuring this version does not support PDF Flate compression. Turning on compression in ``PDFProcessor`` will lead to corrupt output. - **Major API change:** The classes ``EPSGraphics2D``, ``PDFGraphics2D`` and ``SVGGraphics2D`` have been removed. ``VectorGraphics2D`` is used instead in combination with a ``Processor`` instance to generate a ``Document`` object, which can then be written to an ``OutputStream``. See `README.rst `__ for code examples. - The PDF code has seen some major restructuring as well to make it more robust and more standards compliant. - SVG documents use of pixels for page size instead of millimeters by default. - Better handling of font metrics (thanks to Anton Roslov, pull request #62) - A bug that caused number to be formatted in computerized scientific notation, which is not supported in most formats (thanks to Jakub H., issue #63). VectorGraphics2D 0.11 (2016-06-04) ================================== - Allow headless build - Added support for CMYK color space - Added optional compression to ``PDFGraphics2D`` VectorGraphics2D 0.10 (2016-03-06) ================================== - Processing a stream of commands instead of directly mapping method calls - Return valid graphics device configuration when calling ``getDeviceConfiguration()`` instead of ``null`` - Switch from Maven to Gradle for build management VectorGraphics2D 0.9.3 (2015-11-21) =================================== - Publish on MavenCentral VectorGraphics2D 0.9.2 (2015-09-15) =================================== - Fixed a bug that caused missing transformations in EPS files when calling ``EPSGraphics.transform(AffineTransform)``. - Switched from Subversion to git as version control system VectorGraphics2D 0.9.1 (2013-05-31) =================================== - Added Maven repository location to POM - Fixed issue 14 which caused invalid SVG clipping VectorGraphics2D 0.9 (2013-05-12) ================================= - Support for rendering paints (gradients, patterns, etc.) - Improvements to build system - Fixed transformation of clipping paths in SVG files - Fixed build with Java 7 VectorGraphics2D 0.8 (2010-12-03) ================================= - Added image support - Support for transforms - Various bug fixes VectorGraphics2D 0.7 (2010-11-09) ================================= - Clipping support - Dashed strokes - Added special handling for rounded rectangles VectorGraphics2D 0.6 (2010-07-11) ================================= First public release with very basic EPS, PDF, and SVG support vectorgraphics2d-0.13/LICENSE.GPL000066400000000000000000001045131347274514600163550ustar00rootroot00000000000000 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 . vectorgraphics2d-0.13/LICENSE.LGPL000066400000000000000000000167251347274514600165000ustar00rootroot00000000000000 GNU LESSER 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. This version of the GNU Lesser General Public License incorporates the terms and conditions of version 3 of the GNU General Public License, supplemented by the additional permissions listed below. 0. Additional Definitions. As used herein, "this License" refers to version 3 of the GNU Lesser General Public License, and the "GNU GPL" refers to version 3 of the GNU General Public License. "The Library" refers to a covered work governed by this License, other than an Application or a Combined Work as defined below. An "Application" is any work that makes use of an interface provided by the Library, but which is not otherwise based on the Library. Defining a subclass of a class defined by the Library is deemed a mode of using an interface provided by the Library. A "Combined Work" is a work produced by combining or linking an Application with the Library. The particular version of the Library with which the Combined Work was made is also called the "Linked Version". The "Minimal Corresponding Source" for a Combined Work means the Corresponding Source for the Combined Work, excluding any source code for portions of the Combined Work that, considered in isolation, are based on the Application, and not on the Linked Version. The "Corresponding Application Code" for a Combined Work means the object code and/or source code for the Application, including any data and utility programs needed for reproducing the Combined Work from the Application, but excluding the System Libraries of the Combined Work. 1. Exception to Section 3 of the GNU GPL. You may convey a covered work under sections 3 and 4 of this License without being bound by section 3 of the GNU GPL. 2. Conveying Modified Versions. If you modify a copy of the Library, and, in your modifications, a facility refers to a function or data to be supplied by an Application that uses the facility (other than as an argument passed when the facility is invoked), then you may convey a copy of the modified version: a) under this License, provided that you make a good faith effort to ensure that, in the event an Application does not supply the function or data, the facility still operates, and performs whatever part of its purpose remains meaningful, or b) under the GNU GPL, with none of the additional permissions of this License applicable to that copy. 3. Object Code Incorporating Material from Library Header Files. The object code form of an Application may incorporate material from a header file that is part of the Library. You may convey such object code under terms of your choice, provided that, if the incorporated material is not limited to numerical parameters, data structure layouts and accessors, or small macros, inline functions and templates (ten or fewer lines in length), you do both of the following: a) Give prominent notice with each copy of the object code that the Library is used in it and that the Library and its use are covered by this License. b) Accompany the object code with a copy of the GNU GPL and this license document. 4. Combined Works. You may convey a Combined Work under terms of your choice that, taken together, effectively do not restrict modification of the portions of the Library contained in the Combined Work and reverse engineering for debugging such modifications, if you also do each of the following: a) Give prominent notice with each copy of the Combined Work that the Library is used in it and that the Library and its use are covered by this License. b) Accompany the Combined Work with a copy of the GNU GPL and this license document. c) For a Combined Work that displays copyright notices during execution, include the copyright notice for the Library among these notices, as well as a reference directing the user to the copies of the GNU GPL and this license document. d) Do one of the following: 0) Convey the Minimal Corresponding Source under the terms of this License, and the Corresponding Application Code in a form suitable for, and under terms that permit, the user to recombine or relink the Application with a modified version of the Linked Version to produce a modified Combined Work, in the manner specified by section 6 of the GNU GPL for conveying Corresponding Source. 1) Use a suitable shared library mechanism for linking with the Library. A suitable mechanism is one that (a) uses at run time a copy of the Library already present on the user's computer system, and (b) will operate properly with a modified version of the Library that is interface-compatible with the Linked Version. e) Provide Installation Information, but only if you would otherwise be required to provide such information under section 6 of the GNU GPL, and only to the extent that such information is necessary to install and execute a modified version of the Combined Work produced by recombining or relinking the Application with a modified version of the Linked Version. (If you use option 4d0, the Installation Information must accompany the Minimal Corresponding Source and Corresponding Application Code. If you use option 4d1, you must provide the Installation Information in the manner specified by section 6 of the GNU GPL for conveying Corresponding Source.) 5. Combined Libraries. You may place library facilities that are a work based on the Library side by side in a single library together with other library facilities that are not Applications and are not covered by this License, and convey such a combined library under terms of your choice, if you do both of the following: a) Accompany the combined library with a copy of the same work based on the Library, uncombined with any other library facilities, conveyed under the terms of this License. b) Give prominent notice with the combined library that part of it is a work based on the Library, and explaining where to find the accompanying uncombined form of the same work. 6. Revised Versions of the GNU Lesser General Public License. The Free Software Foundation may publish revised and/or new versions of the GNU Lesser 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 Library as you received it specifies that a certain numbered version of the GNU Lesser General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that published version or of any later version published by the Free Software Foundation. If the Library as you received it does not specify a version number of the GNU Lesser General Public License, you may choose any version of the GNU Lesser General Public License ever published by the Free Software Foundation. If the Library as you received it specifies that a proxy can decide whether future versions of the GNU Lesser General Public License shall apply, that proxy's public statement of acceptance of any version is permanent authorization for you to choose that version for the Library. vectorgraphics2d-0.13/README.rst000066400000000000000000000064311347274514600164160ustar00rootroot00000000000000.. image:: https://eseifert.github.io/vectorgraphics2d/logo.png .. image:: https://travis-ci.org/eseifert/vectorgraphics2d.svg?branch=master :target: https://travis-ci.org/eseifert/vectorgraphics2d VectorGraphics2D ################ VectorGraphics2D provides implementations of Java's ``Graphics2D`` interface and exports the graphics in various vector file formats. Currently, there is support for the following vector file formats: - Encapsulated PostScript® (EPS) - Scalable Vector Graphics (SVG) - Portable Document Format (PDF) Additional formats can be easily added. Features ======== - Support for EPS, PDF, and SVG formats - Rendering of all geometric shapes provided by the ``java.awt.Graphics2D`` interface - Shapes and text can be made transparent (except in EPS) - Arbitrary clipping paths can be defined - Output of bitmap images - Easily extensible - Small footprint (JAR is below 100 kilobytes) Currently, most operations are supported, i.e. VectorGraphics2D is able to handle clipping gradients, or compression. Some features are still missing, like text encodings, embedded fonts, or metadata support. Although its early stage VectorGraphics2D is already used successfully in several projects to export vector graphics. Requirements ============ VectorGraphics2D requires at least Java 7 and Gradle 4 or higher to build. Installation ============ Without build management system ------------------------------- You can just add ``VectorGraphics2D-0.13.jar`` to the classpath of your project. Using VectorGraphics2D with Maven --------------------------------- .. code:: xml de.erichseifert.vectorgraphics2d VectorGraphics2D 0.13 Using VectorGraphics2D with Gradle ---------------------------------- .. code:: groovy dependencies { compile group: 'de.erichseifert.vectorgraphics2d', name: 'VectorGraphics2D', version: '0.13' } Using VectorGraphics2D with sbt ------------------------------- .. code:: scala libraryDependencies += "de.erichseifert.vectorgraphics2d" % "VectorGraphics2D" % "0.13" Usage ===== A ``VectorGraphics2D`` object can be used as a replacement for a ``Graphics2D`` object. All calls to the ``VectorGraphics2D`` instance will be recorded and can later be retrieved as a ``CommandSequence``: .. code:: java Graphics2D vg2d = new VectorGraphics2D(); vg2d.draw(new Rectangle2D.Double(0.0, 0.0, 20.0, 20.0)); CommandSequence commands = vg2d.getCommands(); This command sequence can then be exported to a EPS, PDF or SVG document using a processor for the desired file type, i.e. ``EPSProcessor`` for EPS, ``PDFProcessor`` for PDF and ``SVGProcessor`` for SVG. Additionally, format specific output options can be passed to the processor when it is created. For example, a compression option can be passed for PDF: .. code:: java PDFProcessor pdfProcessor = new PDFProcessor(true); Another method to get a processor is ``Processors.get(String)``: .. code:: java Processor pdfProcessor = Processors.get("pdf"); Finally, a document can be generated from the commands and written to an output stream: .. code:: java Document doc = pdfProcessor.getDocument(commands, PageSize.A4); doc.writeTo(new FileOutputStream("rect.pdf")); vectorgraphics2d-0.13/build.gradle000066400000000000000000000131321347274514600172020ustar00rootroot00000000000000apply plugin: 'java' sourceCompatibility = 1.7 targetCompatibility = 1.7 group = 'de.erichseifert.vectorgraphics2d' version = getVersionString() description = 'A library for adding vector export to Java(R) Graphics2D.' ext { inceptionYear = 2010 owner1_id = 'eseifert' owner1_name = 'Erich Seifert' owner1_email = 'dev[at]erichseifert.de' owner2_id = 'mseifert' owner2_name = 'Michael Seifert' owner2_email = 'mseifert[at]error-reports.org' website = 'https://github.com/eseifert/vectorgraphics2d/' // Determine the location of rt.jar (required for ProGuard) if (System.getProperty('os.name').startsWith('Mac')) { runtimeJar = "${System.getProperty("java.home")}/bundle/Classes/classes.jar" } else { runtimeJar = "${System.getProperty("java.home")}/lib/rt.jar" } } repositories { maven { url 'https://plugins.gradle.org/m2/' } } dependencies { testCompile 'junit:junit:4.12' testCompile 'org.hamcrest:hamcrest-library:1.3' testCompile 'org.ghost4j:ghost4j:1.0.1' testCompile 'org.apache.xmlgraphics:batik-transcoder:1.9' testRuntime 'org.apache.xmlgraphics:batik-codec:1.9' // Required for images with data: URLs testRuntime 'org.slf4j:slf4j-log4j12:1.7.25' // Required for Cobertura } buildscript { repositories { maven { url 'https://plugins.gradle.org/m2/' } } dependencies { classpath 'net.sf.proguard:proguard-gradle:5.2.+' classpath 'nl.javadude.gradle.plugins:license-gradle-plugin:0.11.+' classpath 'net.saliman:gradle-cobertura-plugin:2.5.0' classpath 'org.kt3k.gradle.plugin:coveralls-gradle-plugin:2.8.1' } } apply plugin: 'net.saliman.cobertura' cobertura.coverageFormats = ['html', 'xml'] apply plugin: 'com.github.kt3k.coveralls' apply plugin: 'license' license { header(rootProject.file("${projectDir}/src/etc/header.txt")) strictCheck(true) mapping { java = 'SLASHSTAR_STYLE' } def currentYear = new GregorianCalendar().get(Calendar.YEAR) ext.year = "${inceptionYear}-${currentYear}" ext.owner1 = owner1_name ext.email1 = owner1_email ext.owner2 = owner2_name ext.email2 = owner2_email } task shrinkJar(type: proguard.gradle.ProGuardTask, dependsOn: jar) { description = 'Uses ProGuard to reduce the code size of this project.' group = 'Build' // Configure ProGuard configuration("${projectDir}/src/etc/proguard.conf") target(targetCompatibility.toString()) injars(jar.archivePath) outjars("${libsDir}/shrunk/${jar.archiveName}") libraryjars(runtimeJar) libraryjars(configurations.runtime) } task sourceJar(type: Jar) { description = 'Assembles a jar archive containing the source code of the main classes.' group = 'Build' from sourceSets.main.allJava classifier 'sources' } task javadocJar(type: Jar) { description = 'Assembles a jar archive containing the API doc.' group = 'Build' from javadoc classifier 'javadoc' } apply plugin: 'maven' apply plugin: 'signing' artifacts { archives shrinkJar.getOutJarFileCollection().getSingleFile(), sourceJar, javadocJar } signing { required { hasProperty('signing.keyId') && gradle.taskGraph.hasTask('uploadArchives') } sign configurations.archives } uploadArchives { repositories { mavenDeployer { beforeDeployment { MavenDeployment deployment -> signing.signPom(deployment) } repository(url: 'https://oss.sonatype.org/service/local/staging/deploy/maven2/') { authentication(userName: project.hasProperty('ossrhUsername')?ossrhUsername:'', password: project.hasProperty('ossrhPassword')?ossrhPassword:'') } snapshotRepository(url: 'https://oss.sonatype.org/content/repositories/snapshots/') { authentication(userName: project.hasProperty('ossrhUsername')?ossrhUsername:'', password: project.hasProperty('ossrhPassword')?ossrhPassword:'') } pom.project { name rootProject.name packaging 'jar' description project.description url website inceptionYear inceptionYear licenses { license { name 'GNU Library or Lesser General Public License (LGPL)' url 'http://www.gnu.org/licenses/lgpl.txt' } } developers { developer { id owner1_id name owner1_name email owner1_email } developer { id owner2_id name owner2_name email owner2_email } } scm { connection 'scm:git:git://github.com/eseifert/vectorgraphics2d.git' developerConnection 'scm:git:git@github.com:eseifert/vectorgraphics2d.git' url website } issueManagement { system 'GitHub Issues' url website } } } } } signArchives.dependsOn(shrinkJar) /* * This method must not be named getVersion, because it would * overwrite the implicit getter of the version property in the * current Project object. */ def getVersionString() { def out = new ByteArrayOutputStream() exec { commandLine('git', 'describe', '--tags', '--always') standardOutput = out } return out.toString().trim() } vectorgraphics2d-0.13/settings.gradle000066400000000000000000000000451347274514600177420ustar00rootroot00000000000000rootProject.name = 'VectorGraphics2D'vectorgraphics2d-0.13/src/000077500000000000000000000000001347274514600155125ustar00rootroot00000000000000vectorgraphics2d-0.13/src/etc/000077500000000000000000000000001347274514600162655ustar00rootroot00000000000000vectorgraphics2d-0.13/src/etc/header.txt000066400000000000000000000014511347274514600202570ustar00rootroot00000000000000VectorGraphics2D: Vector export for Java(R) Graphics2D (C) Copyright ${year} ${owner1} <${email1}>, ${owner2} <${email2}> This file is part of VectorGraphics2D. VectorGraphics2D is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. VectorGraphics2D 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with VectorGraphics2D. If not, see . vectorgraphics2d-0.13/src/etc/proguard.conf000066400000000000000000000017631347274514600207660ustar00rootroot00000000000000-renamesourcefileattribute SourceFile -keepattributes Exceptions,InnerClasses,Signature,Deprecated, SourceFile,LineNumberTable,*Annotation*,EnclosingMethod -keep public class * { public protected *; } -keepclassmembernames class * { java.lang.Class class$(java.lang.String); java.lang.Class class$(java.lang.String, boolean); } -keepclasseswithmembernames class * { native ; } -keepclassmembers enum * { public static **[] values(); public static ** valueOf(java.lang.String); } -keepclassmembers class * implements java.io.Serializable { static final long serialVersionUID; private static final java.io.ObjectStreamField[] serialPersistentFields; private void writeObject(java.io.ObjectOutputStream); private void readObject(java.io.ObjectInputStream); java.lang.Object writeReplace(); java.lang.Object readResolve(); } -keepclassmembers class * extends de.erichseifert.vectorgraphics2d.VectorGraphics2D { byte[] getBytes(); } vectorgraphics2d-0.13/src/main/000077500000000000000000000000001347274514600164365ustar00rootroot00000000000000vectorgraphics2d-0.13/src/main/java/000077500000000000000000000000001347274514600173575ustar00rootroot00000000000000vectorgraphics2d-0.13/src/main/java/de/000077500000000000000000000000001347274514600177475ustar00rootroot00000000000000vectorgraphics2d-0.13/src/main/java/de/erichseifert/000077500000000000000000000000001347274514600224235ustar00rootroot00000000000000vectorgraphics2d-0.13/src/main/java/de/erichseifert/vectorgraphics2d/000077500000000000000000000000001347274514600256745ustar00rootroot00000000000000vectorgraphics2d-0.13/src/main/java/de/erichseifert/vectorgraphics2d/Document.java000066400000000000000000000025651347274514600303250ustar00rootroot00000000000000/* * VectorGraphics2D: Vector export for Java(R) Graphics2D * * (C) Copyright 2010-2017 Erich Seifert , * Michael Seifert * * This file is part of VectorGraphics2D. * * VectorGraphics2D is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * VectorGraphics2D 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with VectorGraphics2D. If not, see . */ package de.erichseifert.vectorgraphics2d; import java.io.IOException; import java.io.OutputStream; /** * Interface for documents that are able to output binary files in the * implemented file format. */ public interface Document { void writeTo(OutputStream out) throws IOException; /** * Returns whether or not the {@code Document} represents compressed data. * @return {@code true} if the contents are compressed, {@code false} otherwise. */ boolean isCompressed(); } vectorgraphics2d-0.13/src/main/java/de/erichseifert/vectorgraphics2d/GraphicsState.java000066400000000000000000000156561347274514600313150ustar00rootroot00000000000000/* * VectorGraphics2D: Vector export for Java(R) Graphics2D * * (C) Copyright 2010-2017 Erich Seifert , * Michael Seifert * * This file is part of VectorGraphics2D. * * VectorGraphics2D is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * VectorGraphics2D 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with VectorGraphics2D. If not, see . */ package de.erichseifert.vectorgraphics2d; import java.awt.AlphaComposite; import java.awt.BasicStroke; import java.awt.Color; import java.awt.Composite; import java.awt.Font; import java.awt.Paint; import java.awt.RenderingHints; import java.awt.Shape; import java.awt.Stroke; import java.awt.geom.AffineTransform; import java.awt.geom.NoninvertibleTransformException; import java.awt.geom.Rectangle2D; import de.erichseifert.vectorgraphics2d.util.GraphicsUtils; /** * Representation of the Graphics2D status at a certain point in time. */ public class GraphicsState implements Cloneable { /** Default background color. */ public static final Color DEFAULT_BACKGROUND = Color.BLACK; /** Default color. */ public static final Color DEFAULT_COLOR = Color.WHITE; /** Default clipping shape. */ public static final Shape DEFAULT_CLIP = null; /** Default composite mode. */ public static final Composite DEFAULT_COMPOSITE = AlphaComposite.SrcOver; /** Default font. */ public static final Font DEFAULT_FONT = Font.decode(null); /** Default paint. */ public static final Color DEFAULT_PAINT = DEFAULT_COLOR; /** Default stroke. */ public static final Stroke DEFAULT_STROKE = new BasicStroke(); /** Default transformation. */ public static final AffineTransform DEFAULT_TRANSFORM = new AffineTransform(); /** Default XOR mode. */ public static final Color DEFAULT_XOR_MODE = Color.BLACK; /** Rendering hints. */ private RenderingHints hints; /** Current background color. */ private Color background; /** Current foreground color. */ private Color color; /** Shape used for clipping paint operations. */ private Shape clip; /** Method used for compositing. */ private Composite composite; /** Current font. */ private Font font; /** Paint used to fill shapes. */ private Paint paint; /** Stroke used for drawing shapes. */ private Stroke stroke; /** Current transformation matrix. */ private AffineTransform transform; /** XOR mode used for rendering. */ private Color xorMode; public GraphicsState() { hints = new RenderingHints(null); background = DEFAULT_BACKGROUND; color = DEFAULT_COLOR; clip = DEFAULT_CLIP; composite = DEFAULT_COMPOSITE; font = DEFAULT_FONT; paint = DEFAULT_PAINT; stroke = DEFAULT_STROKE; transform = new AffineTransform(DEFAULT_TRANSFORM); xorMode = DEFAULT_XOR_MODE; } @Override public Object clone() throws CloneNotSupportedException { GraphicsState clone = (GraphicsState) super.clone(); clone.hints = (RenderingHints) hints.clone(); clone.clip = GraphicsUtils.clone(clip); clone.transform = new AffineTransform(transform); return clone; } private static Shape transformShape(Shape s, AffineTransform tx) { if (s == null) { return null; } if (tx == null || tx.isIdentity()) { return GraphicsUtils.clone(s); } boolean isRectangle = s instanceof Rectangle2D; int nonRectlinearTxMask = AffineTransform.TYPE_GENERAL_TRANSFORM | AffineTransform.TYPE_GENERAL_ROTATION; boolean isRectlinearTx = (tx.getType() & nonRectlinearTxMask) == 0; if (isRectangle && isRectlinearTx) { Rectangle2D rect = (Rectangle2D) s; double corners[] = new double[] { rect.getMinX(), rect.getMinY(), rect.getMaxX(), rect.getMaxY() }; tx.transform(corners, 0, corners, 0, 2); rect = new Rectangle2D.Double(); rect.setFrameFromDiagonal(corners[0], corners[1], corners[2], corners[3]); return rect; } return tx.createTransformedShape(s); } private static Shape untransformShape(Shape s, AffineTransform tx) { if (s == null) { return null; } try { AffineTransform inverse = tx.createInverse(); return transformShape(s, inverse); } catch (NoninvertibleTransformException e) { return null; } } public Shape transformShape(Shape shape) { return transformShape(shape, transform); } public Shape untransformShape(Shape shape) { return untransformShape(shape, transform); } public RenderingHints getHints() { return hints; } public Color getBackground() { return background; } public void setBackground(Color background) { this.background = background; } public Color getColor() { return color; } public void setColor(Color color) { this.color = color; } public Shape getClip() { return untransformShape(clip); } public void setClip(Shape clip) { this.clip = transformShape(clip); } public Composite getComposite() { return composite; } public void setComposite(Composite composite) { this.composite = composite; } public Font getFont() { return font; } public void setFont(Font font) { this.font = font; } public Paint getPaint() { return paint; } public void setPaint(Paint paint) { this.paint = paint; } public Stroke getStroke() { return stroke; } public void setStroke(Stroke stroke) { this.stroke = stroke; } public AffineTransform getTransform() { return new AffineTransform(transform); } public void setTransform(AffineTransform tx) { transform.setTransform(tx); } public Color getXorMode() { return xorMode; } public void setXorMode(Color xorMode) { this.xorMode = xorMode; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (!(obj instanceof GraphicsState)) { return false; } GraphicsState o = (GraphicsState) obj; // Compare all attributes return !(!hints.equals(o.hints) || !background.equals(o.background) || !color.equals(o.color) || !composite.equals(o.composite) || !font.equals(o.font) || !paint.equals(o.paint) || !stroke.equals(o.stroke) || !transform.equals(o.transform) || !xorMode.equals(o.xorMode) || ((clip == null || o.clip == null) && clip != o.clip) || (clip != null && !clip.equals(o.clip))); } public boolean isDefault() { return hints.isEmpty() && background.equals(DEFAULT_BACKGROUND) && color.equals(DEFAULT_COLOR) && composite.equals(DEFAULT_COMPOSITE) && font.equals(DEFAULT_FONT) && paint.equals(DEFAULT_PAINT) && stroke.equals(DEFAULT_STROKE) && transform.equals(DEFAULT_TRANSFORM) && xorMode.equals(DEFAULT_XOR_MODE) && clip == DEFAULT_CLIP; } } vectorgraphics2d-0.13/src/main/java/de/erichseifert/vectorgraphics2d/Processor.java000066400000000000000000000030571347274514600305230ustar00rootroot00000000000000/* * VectorGraphics2D: Vector export for Java(R) Graphics2D * * (C) Copyright 2010-2017 Erich Seifert , * Michael Seifert * * This file is part of VectorGraphics2D. * * VectorGraphics2D is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * VectorGraphics2D 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with VectorGraphics2D. If not, see . */ package de.erichseifert.vectorgraphics2d; import de.erichseifert.vectorgraphics2d.intermediate.CommandSequence; import de.erichseifert.vectorgraphics2d.intermediate.commands.Command; import de.erichseifert.vectorgraphics2d.util.PageSize; /** * Translates {@link Command} objects into a {@link Document}. */ public interface Processor { /** * Constructs a {@code Document} from the specified commands. * @param commands Commands used to create the {@code Document}. * @param pageSize Size of the resulting {@code Document}. * @return {@code Document} representation of the commands. */ Document getDocument(CommandSequence commands, PageSize pageSize); } vectorgraphics2d-0.13/src/main/java/de/erichseifert/vectorgraphics2d/Processors.java000066400000000000000000000040531347274514600307030ustar00rootroot00000000000000/* * VectorGraphics2D: Vector export for Java(R) Graphics2D * * (C) Copyright 2010-2017 Erich Seifert , * Michael Seifert * * This file is part of VectorGraphics2D. * * VectorGraphics2D is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * VectorGraphics2D 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with VectorGraphics2D. If not, see . */ package de.erichseifert.vectorgraphics2d; import de.erichseifert.vectorgraphics2d.eps.EPSProcessor; import de.erichseifert.vectorgraphics2d.pdf.PDFProcessor; import de.erichseifert.vectorgraphics2d.svg.SVGProcessor; /** *

Utility class that provides simplified access to processors for different * file formats. At the moment three implementations of processors are available: * {@code "eps"}, {@code "pdf"}, and {@code "svg"}

*

A new processor can be retrieved by calling the {@link #get(String)} * method with the format name:

*
Processor pdfProcessor = Processors.get("pdf");
*/ public abstract class Processors { /** * Default constructor that prevents creation of class. */ Processors() { throw new UnsupportedOperationException(); } public static Processor get(String format) { if (format == null) { throw new NullPointerException("Format cannot be null."); } switch (format) { case "eps": return new EPSProcessor(); case "pdf": return new PDFProcessor(true); case "svg": return new SVGProcessor(); default: throw new IllegalArgumentException("Unknown format \"" + format + "\""); } } } vectorgraphics2d-0.13/src/main/java/de/erichseifert/vectorgraphics2d/SizedDocument.java000066400000000000000000000027141347274514600313200ustar00rootroot00000000000000/* * VectorGraphics2D: Vector export for Java(R) Graphics2D * * (C) Copyright 2010-2017 Erich Seifert , * Michael Seifert * * This file is part of VectorGraphics2D. * * VectorGraphics2D is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * VectorGraphics2D 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with VectorGraphics2D. If not, see . */ package de.erichseifert.vectorgraphics2d; import de.erichseifert.vectorgraphics2d.util.PageSize; /** * Abstract base for documents that are restricted to a specified page size. */ public abstract class SizedDocument implements Document { private final PageSize pageSize; private final boolean compressed; public SizedDocument(PageSize pageSize, boolean compressed) { this.pageSize = pageSize; this.compressed = compressed; } public PageSize getPageSize() { return pageSize; } @Override public boolean isCompressed() { return this.compressed; } } vectorgraphics2d-0.13/src/main/java/de/erichseifert/vectorgraphics2d/VectorGraphics2D.java000066400000000000000000000530711347274514600316560ustar00rootroot00000000000000/* * VectorGraphics2D: Vector export for Java(R) Graphics2D * * (C) Copyright 2010-2017 Erich Seifert , * Michael Seifert * * This file is part of VectorGraphics2D. * * VectorGraphics2D is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * VectorGraphics2D 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with VectorGraphics2D. If not, see . */ package de.erichseifert.vectorgraphics2d; 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.Graphics; import java.awt.Graphics2D; import java.awt.GraphicsConfiguration; import java.awt.GraphicsDevice; import java.awt.GraphicsEnvironment; import java.awt.Image; import java.awt.Paint; import java.awt.Polygon; import java.awt.Rectangle; import java.awt.RenderingHints; import java.awt.RenderingHints.Key; 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.Line2D; import java.awt.geom.Path2D; import java.awt.geom.Rectangle2D; import java.awt.geom.RoundRectangle2D; import java.awt.image.AffineTransformOp; 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.util.Map; import java.util.Map.Entry; import de.erichseifert.vectorgraphics2d.intermediate.CommandSequence; import de.erichseifert.vectorgraphics2d.intermediate.MutableCommandSequence; import de.erichseifert.vectorgraphics2d.intermediate.commands.Command; import de.erichseifert.vectorgraphics2d.intermediate.commands.CreateCommand; import de.erichseifert.vectorgraphics2d.intermediate.commands.DisposeCommand; import de.erichseifert.vectorgraphics2d.intermediate.commands.DrawImageCommand; import de.erichseifert.vectorgraphics2d.intermediate.commands.DrawShapeCommand; import de.erichseifert.vectorgraphics2d.intermediate.commands.DrawStringCommand; import de.erichseifert.vectorgraphics2d.intermediate.commands.FillShapeCommand; import de.erichseifert.vectorgraphics2d.intermediate.commands.RotateCommand; import de.erichseifert.vectorgraphics2d.intermediate.commands.ScaleCommand; import de.erichseifert.vectorgraphics2d.intermediate.commands.SetBackgroundCommand; import de.erichseifert.vectorgraphics2d.intermediate.commands.SetClipCommand; import de.erichseifert.vectorgraphics2d.intermediate.commands.SetColorCommand; import de.erichseifert.vectorgraphics2d.intermediate.commands.SetCompositeCommand; import de.erichseifert.vectorgraphics2d.intermediate.commands.SetFontCommand; import de.erichseifert.vectorgraphics2d.intermediate.commands.SetHintCommand; import de.erichseifert.vectorgraphics2d.intermediate.commands.SetPaintCommand; import de.erichseifert.vectorgraphics2d.intermediate.commands.SetStrokeCommand; import de.erichseifert.vectorgraphics2d.intermediate.commands.SetTransformCommand; import de.erichseifert.vectorgraphics2d.intermediate.commands.SetXORModeCommand; import de.erichseifert.vectorgraphics2d.intermediate.commands.ShearCommand; import de.erichseifert.vectorgraphics2d.intermediate.commands.TransformCommand; import de.erichseifert.vectorgraphics2d.intermediate.commands.TranslateCommand; import de.erichseifert.vectorgraphics2d.util.GraphicsUtils; /** *

Implementation of the Graphics2D interface to Java to generate a sequence of * commands. An instance of {@code VectorGraphics2D} can be used to replace any * {@code Graphics2D} object. It can be created with its standard constructor:

*
Graphics2D g = new VectorGraphics2D();
* * @see http://www.java2s.com/Code/Java/2D-Graphics-GUI/YourownGraphics2D.htm */ public class VectorGraphics2D extends Graphics2D implements Cloneable { private final MutableCommandSequence commands; /** Device configuration settings. */ private final GraphicsConfiguration deviceConfig; /** Context settings used to render fonts. */ private final FontRenderContext fontRenderContext; /** Flag that tells whether this graphics object has been disposed. */ private boolean disposed; private GraphicsState state; public VectorGraphics2D() { this.commands = new MutableCommandSequence(); emit(new CreateCommand(this)); GraphicsEnvironment graphicsEnvironment = GraphicsEnvironment.getLocalGraphicsEnvironment(); GraphicsDevice graphicsDevice = null; if (!graphicsEnvironment.isHeadlessInstance()) { graphicsDevice = graphicsEnvironment.getDefaultScreenDevice(); deviceConfig = graphicsDevice.getDefaultConfiguration(); } else { deviceConfig = null; } fontRenderContext = new FontRenderContext(null, false, true); state = new GraphicsState(); // Ensure that document state matches default state of Graphics2D // TODO: Default graphics state does not need to be printed in the document. // Use filters in the appropriate documents setColor(Color.BLACK); // Required for EPS, PDF, and SVG setStroke(new BasicStroke(1f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER, 10f, null, 0f)); // EPS and PDF } @Override public Object clone() throws CloneNotSupportedException { VectorGraphics2D clone = (VectorGraphics2D) super.clone(); clone.state = (GraphicsState) state.clone(); return clone; } @Override public void addRenderingHints(Map hints) { if (isDisposed()) { return; } for (Entry entry : hints.entrySet()) { setRenderingHint((Key) entry.getKey(), entry.getValue()); } } @Override public void clip(Shape s) { Shape clip = getClip(); if ((clip != null) && (s != null)) { s = intersectShapes(clip, s); } setClip(s); } private static Shape intersectShapes(Shape s1, Shape s2) { if (s1 instanceof Rectangle2D && s2 instanceof Rectangle2D) { Rectangle2D r1 = (Rectangle2D) s1; Rectangle2D r2 = (Rectangle2D) s2; double x1 = Math.max(r1.getMinX(), r2.getMinX()); double y1 = Math.max(r1.getMinY(), r2.getMinY()); double x2 = Math.min(r1.getMaxX(), r2.getMaxX()); double y2 = Math.min(r1.getMaxY(), r2.getMaxY()); Rectangle2D intersection = new Rectangle2D.Double(); if ((x2 < x1) || (y2 < y1)) { intersection.setFrameFromDiagonal(0, 0, 0, 0); } else { intersection.setFrameFromDiagonal(x1, y1, x2, y2); } return intersection; } else { Area intersection = new Area(s1); intersection.intersect(new Area(s2)); return intersection; } } @Override public void draw(Shape s) { if (isDisposed() || s == null) { return; } emit(new DrawShapeCommand(s)); } @Override public void drawGlyphVector(GlyphVector g, float x, float y) { Shape s = g.getOutline(x, y); draw(s); } @Override public boolean drawImage(Image img, AffineTransform xform, ImageObserver obs) { BufferedImage bimg = getTransformedImage(img, xform); return drawImage(bimg, bimg.getMinX(), bimg.getMinY(), bimg.getWidth(), bimg.getHeight(), null, null); } /** * Returns a transformed version of an image. * @param image Image to be transformed * @param xform Affine transform to be applied * @return Image with transformed content */ private BufferedImage getTransformedImage(Image image, AffineTransform xform) { Integer interpolationType = (Integer) getRenderingHint(RenderingHints.KEY_INTERPOLATION); if (RenderingHints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR .equals(interpolationType)) { interpolationType = AffineTransformOp.TYPE_NEAREST_NEIGHBOR; } else if (RenderingHints.VALUE_INTERPOLATION_BILINEAR .equals(interpolationType)) { interpolationType = AffineTransformOp.TYPE_BILINEAR; } else { interpolationType = AffineTransformOp.TYPE_BICUBIC; } AffineTransformOp op = new AffineTransformOp(xform, interpolationType); BufferedImage bufferedImage = GraphicsUtils.toBufferedImage(image); return op.filter(bufferedImage, null); } @Override public void drawImage(BufferedImage img, BufferedImageOp op, int x, int y) { if (op != null) { img = op.filter(img, null); } drawImage(img, x, y, img.getWidth(), img.getHeight(), null, null); } @Override public void drawRenderableImage(RenderableImage img, AffineTransform xform) { drawRenderedImage(img.createDefaultRendering(), xform); } @Override public void drawRenderedImage(RenderedImage img, AffineTransform xform) { BufferedImage bimg = GraphicsUtils.toBufferedImage(img); drawImage(bimg, xform, null); } @Override public void drawString(String str, int x, int y) { drawString(str, (float) x, (float) y); } @Override public void drawString(String str, float x, float y) { if (isDisposed() || str == null || str.trim().length() == 0) { return; } boolean isTextAsVectors = false; if (isTextAsVectors) { TextLayout layout = new TextLayout(str, getFont(), getFontRenderContext()); Shape s = layout.getOutline( AffineTransform.getTranslateInstance(x, y)); fill(s); } else { emit(new DrawStringCommand(str, x, y)); } } @Override public void drawString(AttributedCharacterIterator iterator, int x, int y) { drawString(iterator, (float) x, (float) y); } @Override public void drawString(AttributedCharacterIterator iterator, float x, float y) { // TODO Draw styled text StringBuilder buf = new StringBuilder(); for (char c = iterator.first(); c != AttributedCharacterIterator.DONE; c = iterator.next()) { buf.append(c); } drawString(buf.toString(), x, y); } @Override public void fill(Shape s) { if (isDisposed() || s == null) { return; } emit(new FillShapeCommand(s)); } @Override public Color getBackground() { return state.getBackground(); } @Override public Composite getComposite() { return state.getComposite(); } @Override public GraphicsConfiguration getDeviceConfiguration() { return deviceConfig; } @Override public FontRenderContext getFontRenderContext() { return fontRenderContext; } @Override public Paint getPaint() { return state.getPaint(); } @Override public Object getRenderingHint(Key hintKey) { if (RenderingHints.KEY_ANTIALIASING.equals(hintKey)) { return RenderingHints.VALUE_ANTIALIAS_OFF; } else if (RenderingHints.KEY_TEXT_ANTIALIASING.equals(hintKey)) { return RenderingHints.VALUE_TEXT_ANTIALIAS_OFF; } else if (RenderingHints.KEY_FRACTIONALMETRICS.equals(hintKey)) { return RenderingHints.VALUE_FRACTIONALMETRICS_ON; } return state.getHints().get(hintKey); } @Override public RenderingHints getRenderingHints() { return (RenderingHints) state.getHints().clone(); } @Override public Stroke getStroke() { return state.getStroke(); } @Override public boolean hit(Rectangle rect, Shape s, boolean onStroke) { Shape hitShape = s; if (onStroke) { hitShape = getStroke().createStrokedShape(hitShape); } hitShape = state.transformShape(hitShape); return hitShape.intersects(rect); } @Override public void setBackground(Color color) { if (isDisposed() || color == null || getColor().equals(color)) { return; } emit(new SetBackgroundCommand(color)); state.setBackground(color); } @Override public void setComposite(Composite comp) { if (isDisposed()) { return; } if (comp == null) { throw new IllegalArgumentException("Cannot set a null composite."); } emit(new SetCompositeCommand(comp)); state.setComposite(comp); } @Override public void setPaint(Paint paint) { if (isDisposed() || paint == null) { return; } if (paint instanceof Color) { setColor((Color) paint); return; } if (getPaint().equals(paint)) { return; } emit(new SetPaintCommand(paint)); state.setPaint(paint); } @Override public void setRenderingHint(Key hintKey, Object hintValue) { if (isDisposed()) { return; } state.getHints().put(hintKey, hintValue); emit(new SetHintCommand(hintKey, hintValue)); } @Override public void setRenderingHints(Map hints) { if (isDisposed()) { return; } state.getHints().clear(); for (Entry hint : hints.entrySet()) { setRenderingHint((Key) hint.getKey(), hint.getValue()); } } @Override public void setStroke(Stroke s) { if (isDisposed()) { return; } if (s == null) { throw new IllegalArgumentException("Cannot set a null stroke."); } emit(new SetStrokeCommand(s)); state.setStroke(s); } @Override public AffineTransform getTransform() { return new AffineTransform(state.getTransform()); } @Override public void setTransform(AffineTransform tx) { if (isDisposed() || tx == null || state.getTransform().equals(tx)) { return; } emit(new SetTransformCommand(tx)); state.setTransform(tx); } @Override public void shear(double shx, double shy) { if (shx == 0.0 && shy == 0.0) { return; } AffineTransform txNew = getTransform(); txNew.shear(shx, shy); emit(new ShearCommand(shx, shy)); state.setTransform(txNew); } @Override public void transform(AffineTransform tx) { if (tx.isIdentity()) { return; } AffineTransform txNew = getTransform(); txNew.concatenate(tx); emit(new TransformCommand(tx)); state.setTransform(txNew); } @Override public void translate(int x, int y) { translate((double) x, (double) y); } @Override public void translate(double tx, double ty) { if (tx == 0.0 && ty == 0.0) { return; } AffineTransform txNew = getTransform(); txNew.translate(tx, ty); emit(new TranslateCommand(tx, ty)); state.setTransform(txNew); } @Override public void rotate(double theta) { rotate(theta, 0.0, 0.0); } @Override public void rotate(double theta, double x, double y) { if (theta == 0.0) { return; } AffineTransform txNew = getTransform(); if (x == 0.0 && y == 0.0) { txNew.rotate(theta); } else { txNew.rotate(theta, x, y); } emit(new RotateCommand(theta, x, y)); state.setTransform(txNew); } @Override public void scale(double sx, double sy) { if (sx == 1.0 && sy == 1.0) { return; } AffineTransform txNew = getTransform(); txNew.scale(sx, sy); emit(new ScaleCommand(sx, sy)); state.setTransform(txNew); } @Override public void clearRect(int x, int y, int width, int height) { Color colorOld = getColor(); setColor(getBackground()); fillRect(x, y, width, height); setColor(colorOld); } @Override public void clipRect(int x, int y, int width, int height) { clip(new Rectangle(x, y, width, height)); } @Override public void copyArea(int x, int y, int width, int height, int dx, int dy) { // TODO Implement //throw new UnsupportedOperationException("copyArea() isn't supported by VectorGraphics2D."); } @Override public Graphics create() { if (isDisposed()) { return null; } VectorGraphics2D clone = null; try { clone = (VectorGraphics2D) this.clone(); emit(new CreateCommand(clone)); } catch (CloneNotSupportedException e) { e.printStackTrace(); } return clone; } @Override public void dispose() { if (isDisposed()) { return; } emit(new DisposeCommand(this)); disposed = true; } @Override public void drawArc(int x, int y, int width, int height, int startAngle, int arcAngle) { draw(new Arc2D.Double(x, y, width, height, startAngle, arcAngle, Arc2D.OPEN)); } @Override public boolean drawImage(Image img, int x, int y, ImageObserver observer) { return drawImage(img, x, y, img.getWidth(observer), img.getHeight(observer), null, observer); } @Override public boolean drawImage(Image img, int x, int y, Color bgcolor, ImageObserver observer) { return drawImage(img, x, y, img.getWidth(observer), img.getHeight(observer), bgcolor, observer); } @Override public boolean drawImage(Image img, int x, int y, int width, int height, ImageObserver observer) { return drawImage(img, x, y, width, height, null, observer); } @Override public boolean drawImage(Image img, int x, int y, int width, int height, Color bgcolor, ImageObserver observer) { if (isDisposed() || img == null) { return true; } int imageWidth = img.getWidth(observer); int imageHeight = img.getHeight(observer); Rectangle bounds = new Rectangle(x, y, width, height); if (bgcolor != null) { // Fill rectangle with bgcolor Color bgcolorOld = getColor(); setColor(bgcolor); fill(bounds); setColor(bgcolorOld); } emit(new DrawImageCommand(img, imageWidth, imageHeight, x, y, width, height)); return true; } @Override public boolean drawImage(Image img, int dx1, int dy1, int dx2, int dy2, int sx1, int sy1, int sx2, int sy2, ImageObserver observer) { return drawImage(img, dx1, dy1, dx2, dy2, sx1, sy1, sx2, sy2, null, observer); } @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) { if (img == null) { return true; } int sx = Math.min(sx1, sx2); int sy = Math.min(sy1, sy2); int sw = Math.abs(sx2 - sx1); int sh = Math.abs(sy2 - sy1); int dx = Math.min(dx1, dx2); int dy = Math.min(dy1, dy2); int dw = Math.abs(dx2 - dx1); int dh = Math.abs(dy2 - dy1); // Draw image on rectangle BufferedImage bufferedImg = GraphicsUtils.toBufferedImage(img); Image cropped = bufferedImg.getSubimage(sx, sy, sw, sh); return drawImage(cropped, dx, dy, dw, dh, bgcolor, observer); } @Override public void drawLine(int x1, int y1, int x2, int y2) { draw(new Line2D.Double(x1, y1, x2, y2)); } @Override public void drawOval(int x, int y, int width, int height) { draw(new Ellipse2D.Double(x, y, width, height)); } @Override public void drawPolygon(Polygon p) { draw(p); } @Override public void drawPolygon(int[] xPoints, int[] yPoints, int nPoints) { draw(new Polygon(xPoints, yPoints, nPoints)); } @Override public void drawPolyline(int[] xPoints, int[] yPoints, int nPoints) { Path2D p = new Path2D.Float(); for (int i = 0; i < nPoints; i++) { if (i > 0) { p.lineTo(xPoints[i], yPoints[i]); } else { p.moveTo(xPoints[i], yPoints[i]); } } draw(p); } @Override public void drawRect(int x, int y, int width, int height) { draw(new Rectangle(x, y, width, height)); } @Override public void drawRoundRect(int x, int y, int width, int height, int arcWidth, int arcHeight) { draw(new RoundRectangle2D.Double(x, y, width, height, arcWidth, arcHeight)); } @Override public void fillArc(int x, int y, int width, int height, int startAngle, int arcAngle) { fill(new Arc2D.Double(x, y, width, height, startAngle, arcAngle, Arc2D.PIE)); } @Override public void fillOval(int x, int y, int width, int height) { fill(new Ellipse2D.Double(x, y, width, height)); } @Override public void fillPolygon(Polygon p) { fill(p); } @Override public void fillPolygon(int[] xPoints, int[] yPoints, int nPoints) { fill(new Polygon(xPoints, yPoints, nPoints)); } @Override public void fillRect(int x, int y, int width, int height) { fill(new Rectangle(x, y, width, height)); } @Override public void fillRoundRect(int x, int y, int width, int height, int arcWidth, int arcHeight) { fill(new RoundRectangle2D.Double(x, y, width, height, arcWidth, arcHeight)); } @Override public Shape getClip() { return state.getClip(); } @Override public Rectangle getClipBounds() { if (getClip() == null) { return null; } return getClip().getBounds(); } @Override public Color getColor() { return state.getColor(); } @Override public Font getFont() { return state.getFont(); } @Override public FontMetrics getFontMetrics(Font f) { BufferedImage bi = new BufferedImage(1, 1, BufferedImage.TYPE_INT_ARGB_PRE); Graphics g = bi.getGraphics(); FontMetrics fontMetrics = g.getFontMetrics(f); g.dispose(); return fontMetrics; } @Override public void setClip(Shape clip) { if (isDisposed()) { return; } emit(new SetClipCommand(clip)); state.setClip(clip); } @Override public void setClip(int x, int y, int width, int height) { setClip(new Rectangle(x, y, width, height)); } @Override public void setColor(Color c) { if (isDisposed() || c == null || getColor().equals(c)) { return; } emit(new SetColorCommand(c)); state.setColor(c); state.setPaint(c); } @Override public void setFont(Font font) { if (isDisposed() || (font != null && getFont().equals(font))) { return; } emit(new SetFontCommand(font)); state.setFont(font); } @Override public void setPaintMode() { setComposite(AlphaComposite.SrcOver); } public Color getXORMode() { return state.getXorMode(); } @Override public void setXORMode(Color c1) { if (isDisposed() || c1 == null) { return; } emit(new SetXORModeCommand(c1)); state.setXorMode(c1); } private void emit(Command command) { commands.add(command); } protected boolean isDisposed() { return disposed; } /** * Returns a {@code CommandSequence} representing all calls that were issued to this {@code VectorGraphics2D} object. * @return Sequence of commands since. */ public CommandSequence getCommands() { return commands; } } vectorgraphics2d-0.13/src/main/java/de/erichseifert/vectorgraphics2d/VectorHints.java000066400000000000000000000067021347274514600310140ustar00rootroot00000000000000/* * VectorGraphics2D: Vector export for Java(R) Graphics2D * * (C) Copyright 2010-2017 Erich Seifert , * Michael Seifert * * This file is part of VectorGraphics2D. * * VectorGraphics2D is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * VectorGraphics2D 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with VectorGraphics2D. If not, see . */ package de.erichseifert.vectorgraphics2d; import java.awt.RenderingHints; import java.util.HashSet; import java.util.Set; /** * Hints to control quality settings and choices for vector graphics output. */ public abstract class VectorHints { protected VectorHints() { throw new UnsupportedOperationException(); } /** * Base type of all keys used along with the {@link VectorHints} class to * control algorithm and output choices in the vector graphics output. */ public static class Key extends RenderingHints.Key { private final String description; public Key(int privateKey, String description) { super(privateKey); this.description = description; } public int getIndex() { return intKey(); } @Override public boolean isCompatibleValue(Object val) { return val instanceof Value && ((Value) val).isCompatibleKey(this); } @Override public String toString() { return description; } } /** * Base type of all values used along with the {@link VectorHints} class to * control algorithm and output choices in the vector graphics output. */ public static class Value { private static final Set values = new HashSet<>(); private synchronized static void register(Value value) { String id = value.getId(); if (values.contains(id)) { throw new ExceptionInInitializerError( "Duplicate index: "+value.getIndex()); } values.add(id); } private final Key key; private final int index; private final String description; public Value(Key key, int index, String description) { this.key = key; this.index = index; this.description = description; register(this); } public boolean isCompatibleKey(RenderingHints.Key key) { return this.key == key; } public int getIndex() { return index; } public String getId() { return key.getIndex()+":"+getIndex(); } @Override public String toString() { return description; } } public static final Key KEY_EXPORT = new Key(0, "Vector export mode"); public static final Object VALUE_EXPORT_READABILITY = new Value(KEY_EXPORT, 0, "Maximize readability for humans"); public static final Object VALUE_EXPORT_QUALITY = new Value(KEY_EXPORT, 1, "Maximize render quality"); public static final Object VALUE_EXPORT_SIZE = new Value(KEY_EXPORT, 2, "Minimize data size"); public static final Key KEY_TEXT = new Key(1, "Text export mode"); public static final Object VALUE_TEXT_DEFAULT = new Value(KEY_TEXT, 0, "Keep text"); public static final Object VALUE_TEXT_VECTOR = new Value(KEY_TEXT, 1, "Convert text to vector shapes"); } vectorgraphics2d-0.13/src/main/java/de/erichseifert/vectorgraphics2d/eps/000077500000000000000000000000001347274514600264635ustar00rootroot00000000000000vectorgraphics2d-0.13/src/main/java/de/erichseifert/vectorgraphics2d/eps/EPSDocument.java000066400000000000000000000505501347274514600314610ustar00rootroot00000000000000/* * VectorGraphics2D: Vector export for Java(R) Graphics2D * * (C) Copyright 2010-2017 Erich Seifert , * Michael Seifert * * This file is part of VectorGraphics2D. * * VectorGraphics2D is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * VectorGraphics2D 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with VectorGraphics2D. If not, see . */ package de.erichseifert.vectorgraphics2d.eps; import java.awt.BasicStroke; import java.awt.Color; import java.awt.Font; import java.awt.Image; import java.awt.Shape; import java.awt.Stroke; import java.awt.color.ColorSpace; import java.awt.geom.Arc2D; import java.awt.geom.Ellipse2D; import java.awt.geom.Line2D; import java.awt.geom.PathIterator; import java.awt.geom.Rectangle2D; import java.awt.image.BufferedImage; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.util.Arrays; import java.util.LinkedList; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; import de.erichseifert.vectorgraphics2d.GraphicsState; import de.erichseifert.vectorgraphics2d.SizedDocument; import de.erichseifert.vectorgraphics2d.intermediate.CommandSequence; import de.erichseifert.vectorgraphics2d.intermediate.commands.Command; import de.erichseifert.vectorgraphics2d.intermediate.commands.CreateCommand; import de.erichseifert.vectorgraphics2d.intermediate.commands.DisposeCommand; import de.erichseifert.vectorgraphics2d.intermediate.commands.DrawImageCommand; import de.erichseifert.vectorgraphics2d.intermediate.commands.DrawShapeCommand; import de.erichseifert.vectorgraphics2d.intermediate.commands.DrawStringCommand; import de.erichseifert.vectorgraphics2d.intermediate.commands.FillShapeCommand; import de.erichseifert.vectorgraphics2d.intermediate.commands.RotateCommand; import de.erichseifert.vectorgraphics2d.intermediate.commands.ScaleCommand; import de.erichseifert.vectorgraphics2d.intermediate.commands.SetClipCommand; import de.erichseifert.vectorgraphics2d.intermediate.commands.SetColorCommand; import de.erichseifert.vectorgraphics2d.intermediate.commands.SetCompositeCommand; import de.erichseifert.vectorgraphics2d.intermediate.commands.SetFontCommand; import de.erichseifert.vectorgraphics2d.intermediate.commands.SetPaintCommand; import de.erichseifert.vectorgraphics2d.intermediate.commands.SetStrokeCommand; import de.erichseifert.vectorgraphics2d.intermediate.commands.SetTransformCommand; import de.erichseifert.vectorgraphics2d.intermediate.commands.ShearCommand; import de.erichseifert.vectorgraphics2d.intermediate.commands.TransformCommand; import de.erichseifert.vectorgraphics2d.intermediate.commands.TranslateCommand; import de.erichseifert.vectorgraphics2d.util.ASCII85EncodeStream; import de.erichseifert.vectorgraphics2d.util.AlphaToMaskOp; import de.erichseifert.vectorgraphics2d.util.DataUtils; import de.erichseifert.vectorgraphics2d.util.FlateEncodeStream; import de.erichseifert.vectorgraphics2d.util.GraphicsUtils; import de.erichseifert.vectorgraphics2d.util.ImageDataStream; import de.erichseifert.vectorgraphics2d.util.ImageDataStream.Interleaving; import de.erichseifert.vectorgraphics2d.util.LineWrapOutputStream; import de.erichseifert.vectorgraphics2d.util.PageSize; /** * Represents a {@code Document} in the Encapsulated PostScript® * (EPS) format. */ class EPSDocument extends SizedDocument { /** Constant to convert values from millimeters to PostScript® units (1/72th inch). */ private static final double UNITS_PER_MM = 72.0 / 25.4; private static final String CHARSET = "ISO-8859-1"; private static final String EOL = "\n"; private static final int MAX_LINE_WIDTH = 255; private static final Pattern ELEMENT_SEPARATION_PATTERN = Pattern.compile("(.{1," + MAX_LINE_WIDTH + "})(\\s+|$)"); /** Mapping of stroke endcap values from Java to PostScript®. */ private static final Map STROKE_ENDCAPS = DataUtils.map( new Integer[] { BasicStroke.CAP_BUTT, BasicStroke.CAP_ROUND, BasicStroke.CAP_SQUARE }, new Integer[] { 0, 1, 2 } ); /** Mapping of line join values for path drawing from Java to PostScript®. */ private static final Map STROKE_LINEJOIN = DataUtils.map( new Integer[] { BasicStroke.JOIN_MITER, BasicStroke.JOIN_ROUND, BasicStroke.JOIN_BEVEL }, new Integer[] { 0, 1, 2 } ); private static final String FONT_LATIN1_SUFFIX = "Lat"; private final List elements; public EPSDocument(CommandSequence commands, PageSize pageSize) { super(pageSize, true); elements = new LinkedList<>(); addHeader(); for (Command command : commands) { handle(command); } } private void addHeader() { double x=getPageSize().getX()*UNITS_PER_MM, y=getPageSize().getY()*UNITS_PER_MM, width=getPageSize().getWidth()*UNITS_PER_MM, height=getPageSize().getHeight()*UNITS_PER_MM; elements.addAll(Arrays.asList( "%!PS-Adobe-3.0 EPSF-3.0", "%%BoundingBox: " + ((int) Math.floor(x)) + " " + ((int) Math.floor(y)) + " " + ((int) Math.ceil(x + width)) + " " + ((int) Math.ceil(y + height)), "%%HiResBoundingBox: " + x + " " + y + " " + (x + width) + " " + (y + height), "%%LanguageLevel: 3", "%%Pages: 1", "%%EndComments", "%%Page: 1 1", "/M /moveto load def", "/L /lineto load def", "/C /curveto load def", "/Z /closepath load def", "/RL /rlineto load def", "/rgb /setrgbcolor load def", "/cmyk /setcmykcolor load def", "/rect { /height exch def /width exch def /y exch def /x exch def x y M width 0 RL 0 height RL width neg 0 RL } bind def", "/ellipse { /endangle exch def /startangle exch def /ry exch def /rx exch def /y exch def /x exch def /savematrix matrix currentmatrix def x y translate rx ry scale 0 0 1 startangle endangle arcn savematrix setmatrix } bind def", "/imgdict { /datastream exch def /hasdata exch def /decodeScale exch def /bits exch def /bands exch def /imgheight exch def /imgwidth exch def << /ImageType 1 /Width imgwidth /Height imgheight /BitsPerComponent bits /Decode [bands {0 decodeScale} repeat] /ImageMatrix [imgwidth 0 0 imgheight 0 0] hasdata { /DataSource datastream } if >> } bind def", "/latinize { /fontName exch def /fontNameNew exch def fontName findfont 0 dict copy begin /Encoding ISOLatin1Encoding def fontNameNew /FontName def currentdict end dup /FID undef fontNameNew exch definefont pop } bind def", getOutput(GraphicsState.DEFAULT_FONT), "gsave", "clipsave", "/DeviceRGB setcolorspace", "0 " + height + " translate", UNITS_PER_MM + " " + (-UNITS_PER_MM) + " scale", "/basematrix matrix currentmatrix def" )); } public void writeTo(OutputStream out) throws IOException { OutputStreamWriter o = new OutputStreamWriter(out, CHARSET); for (String element : elements) { if (element == null) { continue; } // Write current element in lines of 255 bytes (excluding line terminators) // Numbers must not be separated by line breaks or errors will occur // TODO: Integrate functionality into LineWrapOutputStream Matcher chunkMatcher = ELEMENT_SEPARATION_PATTERN.matcher(element); boolean chunkFound = false; while (chunkMatcher.find()) { chunkFound = true; String chunk = chunkMatcher.group(); o.write(chunk, 0, chunk.length()); o.append(EOL); } if (!chunkFound) { // TODO: Exception, if no whitespace can be found in the chunk System.err.println("Unable to divide eps element into lines: " + element); } } o.append("%%EOF"); o.flush(); } public void handle(Command command) { if (command instanceof SetClipCommand) { SetClipCommand c = (SetClipCommand) command; Shape clip = c.getValue(); elements.add("cliprestore"); if (clip != null) { elements.add(getOutput(clip) + " clip"); } } else if (command instanceof SetColorCommand) { SetColorCommand c = (SetColorCommand) command; elements.add(getOutput(c.getValue())); } else if (command instanceof SetCompositeCommand) { SetCompositeCommand c = (SetCompositeCommand) command; // TODO Implement composite rendering for EPS elements.add("% composite not yet implemented: " + c.getValue()); } else if (command instanceof SetFontCommand) { SetFontCommand c = (SetFontCommand) command; elements.add(getOutput(c.getValue())); } else if (command instanceof SetPaintCommand) { SetPaintCommand c = (SetPaintCommand) command; // TODO Implement paint rendering for EPS elements.add("% paint not yet implemented: " + c.getValue()); } else if (command instanceof SetStrokeCommand) { SetStrokeCommand c = (SetStrokeCommand) command; elements.add(getOutput(c.getValue())); } else if (command instanceof SetTransformCommand) { SetTransformCommand c = (SetTransformCommand) command; StringBuilder e = new StringBuilder(); double[] matrix = new double[6]; c.getValue().getMatrix(matrix); e.append("basematrix setmatrix [") .append(DataUtils.join(" ", matrix)).append("] concat"); elements.add(e.toString()); } else if (command instanceof RotateCommand) { RotateCommand c = (RotateCommand) command; StringBuilder e = new StringBuilder(); double x = c.getCenterX(); double y = c.getCenterY(); boolean translated = x != 0.0 || y != 0.0; if (translated) { e.append(x).append(" ").append(y).append(" translate "); } e.append(Math.toDegrees(c.getTheta())).append(" rotate"); if (translated) { e.append(" "); e.append(-x).append(" ").append(-y).append(" translate"); } elements.add(e.toString()); } else if (command instanceof ScaleCommand) { ScaleCommand c = (ScaleCommand) command; elements.add(DataUtils.format(c.getScaleX()) + " " + DataUtils.format(c.getScaleY()) + " scale"); } else if (command instanceof ShearCommand) { ShearCommand c = (ShearCommand) command; elements.add("[1 " + DataUtils.format(c.getShearY()) + " " + DataUtils.format(c.getShearX()) + " 1 0 0] concat"); } else if (command instanceof TransformCommand) { TransformCommand c = (TransformCommand) command; StringBuilder e = new StringBuilder(); double[] matrix = new double[6]; c.getValue().getMatrix(matrix); e.append("[").append(DataUtils.join(" ", matrix)) .append("] concat"); elements.add(e.toString()); } else if (command instanceof TranslateCommand) { TranslateCommand c = (TranslateCommand) command; elements.add(String.valueOf(c.getDeltaX()) + " " + c.getDeltaY() + " translate"); } else if (command instanceof DrawImageCommand) { DrawImageCommand c = (DrawImageCommand) command; String e = getOutput(c.getValue(), c.getImageWidth(), c.getImageHeight(), c.getX(), c.getY(), c.getWidth(), c.getHeight()); elements.add(e); } else if (command instanceof DrawShapeCommand) { DrawShapeCommand c = (DrawShapeCommand) command; elements.add(getOutput(c.getValue()) + " stroke"); } else if (command instanceof DrawStringCommand) { DrawStringCommand c = (DrawStringCommand) command; elements.add(getOutput(c.getValue(), c.getX(), c.getY())); } else if (command instanceof FillShapeCommand) { FillShapeCommand c = (FillShapeCommand) command; elements.add(getOutput(c.getValue()) + " fill"); } else if (command instanceof CreateCommand) { elements.add("gsave"); } else if (command instanceof DisposeCommand) { elements.add("grestore"); } } private static String getOutput(Color color) { // TODO Handle transparency if (color.getColorSpace().getType() == ColorSpace.TYPE_CMYK) { float[] cmyk = color.getComponents(null); return String.format((Locale) null, "%f %f %f %f cmyk", cmyk[0], cmyk[1], cmyk[2], cmyk[3]); } else { return String.format((Locale) null, "%f %f %f rgb", color.getRed()/255f, color.getGreen()/255f, color.getBlue()/255f); } } private static String getOutput(Shape s) { StringBuilder out = new StringBuilder(); out.append("newpath "); if (s instanceof Line2D) { Line2D l = (Line2D) s; out.append(l.getX1()).append(" ").append(l.getY1()).append(" M ") .append(l.getX2()).append(" ").append(l.getY2()).append(" L"); } else if (s instanceof Rectangle2D) { Rectangle2D r = (Rectangle2D) s; out.append(r.getX()).append(" ").append(r.getY()).append(" ") .append(r.getWidth()).append(" ").append(r.getHeight()) .append(" rect Z"); } else if (s instanceof Ellipse2D) { Ellipse2D e = (Ellipse2D) s; double x = e.getX() + e.getWidth()/2.0; double y = e.getY() + e.getHeight()/2.0; double rx = e.getWidth()/2.0; double ry = e.getHeight()/2.0; out.append(x).append(" ").append(y).append(" ") .append(rx).append(" ").append(ry).append(" ") .append(360.0).append(" ").append(0.0) .append(" ellipse Z"); } else if (s instanceof Arc2D) { Arc2D e = (Arc2D) s; double x = (e.getX() + e.getWidth()/2.0); double y = (e.getY() + e.getHeight()/2.0); double rx = e.getWidth()/2.0; double ry = e.getHeight()/2.0; double startAngle = -e.getAngleStart(); double endAngle = -(e.getAngleStart() + e.getAngleExtent()); out.append(x).append(" ").append(y).append(" ") .append(rx).append(" ").append(ry).append(" ") .append(startAngle).append(" ").append(endAngle) .append(" ellipse"); if (e.getArcType() == Arc2D.CHORD) { out.append(" Z"); } else if (e.getArcType() == Arc2D.PIE) { out.append(" ").append(x).append(" ").append(y).append(" L Z"); } } else { PathIterator segments = s.getPathIterator(null); double[] coordsCur = new double[6]; double[] pointPrev = new double[2]; for (int i = 0; !segments.isDone(); i++, segments.next()) { if (i > 0) { out.append(" "); } int segmentType = segments.currentSegment(coordsCur); switch (segmentType) { case PathIterator.SEG_MOVETO: out.append(coordsCur[0]).append(" ").append(coordsCur[1]) .append(" M"); pointPrev[0] = coordsCur[0]; pointPrev[1] = coordsCur[1]; break; case PathIterator.SEG_LINETO: out.append(coordsCur[0]).append(" ").append(coordsCur[1]) .append(" L"); pointPrev[0] = coordsCur[0]; pointPrev[1] = coordsCur[1]; break; case PathIterator.SEG_CUBICTO: out.append(coordsCur[0]).append(" ").append(coordsCur[1]) .append(" ").append(coordsCur[2]).append(" ") .append(coordsCur[3]).append(" ").append(coordsCur[4]) .append(" ").append(coordsCur[5]).append(" C"); pointPrev[0] = coordsCur[4]; pointPrev[1] = coordsCur[5]; break; case PathIterator.SEG_QUADTO: double x1 = pointPrev[0] + 2.0/3.0*(coordsCur[0] - pointPrev[0]); double y1 = pointPrev[1] + 2.0/3.0*(coordsCur[1] - pointPrev[1]); double x2 = coordsCur[0] + 1.0/3.0*(coordsCur[2] - coordsCur[0]); double y2 = coordsCur[1] + 1.0/3.0*(coordsCur[3] - coordsCur[1]); double x3 = coordsCur[2]; double y3 = coordsCur[3]; out.append(x1).append(" ").append(y1).append(" ") .append(x2).append(" ").append(y2).append(" ") .append(x3).append(" ").append(y3).append(" C"); pointPrev[0] = x3; pointPrev[1] = y3; break; case PathIterator.SEG_CLOSE: out.append("Z"); break; default: throw new IllegalStateException("Unknown path operation."); } } } return out.toString(); } private static String getOutput(Image image, int imageWidth, int imageHeight, double x, double y, double width, double height) { StringBuilder out = new StringBuilder(); BufferedImage bufferedImage = GraphicsUtils.toBufferedImage(image); int bands = bufferedImage.getSampleModel().getNumBands(); int bitsPerSample = DataUtils.max(bufferedImage.getSampleModel().getSampleSize()); bitsPerSample = (int) (Math.ceil(bitsPerSample/8.0)*8.0); if (bands > 3) { bands = 3; } out.append("gsave").append(EOL); if (x != 0.0 || y != 0.0) { out.append(x).append(" ").append(y).append(" translate").append(EOL); } if (width != 1.0 || height != 1.0) { out.append(width).append(" ").append(height).append(" scale").append(EOL); } int decodeScale = 1; if (bufferedImage.getColorModel().hasAlpha()) { // TODO Use different InterleaveType (2 or 3) for more efficient compression out.append("<< /ImageType 3 /InterleaveType 1 ") .append("/MaskDict ") .append(imageWidth).append(" ").append(imageHeight).append(" ") .append(1).append(" ").append(bitsPerSample).append(" ").append(decodeScale).append(" ") .append(false).append(" ").append(0).append(" imgdict ") .append("/DataDict ") .append(imageWidth).append(" ").append(imageHeight).append(" ") .append(bands).append(" ").append(bitsPerSample).append(" ").append(decodeScale).append(" ") .append(true).append(" currentfile /ASCII85Decode filter ") .append("<< /BitsPerComponent ").append(bitsPerSample).append(" >> ") .append("/FlateDecode filter ") .append("imgdict ") .append(">> image").append(EOL); // Convert alpha values to binary mask // FIXME Do alpha conversion in a preprocessing step on commands bufferedImage = new AlphaToMaskOp(true).filter(bufferedImage, null); output(bufferedImage, out); } else { if (bands == 1) { out.append("/DeviceGray setcolorspace").append(EOL); } if (bufferedImage.getType() == BufferedImage.TYPE_BYTE_BINARY) { decodeScale = 255; } out.append(imageWidth).append(" ").append(imageHeight).append(" ") .append(bands).append(" ").append(bitsPerSample).append(" ").append(decodeScale).append(" ") .append(true).append(" currentfile /ASCII85Decode filter ") .append("<< /BitsPerComponent ").append(bitsPerSample).append(" >> ") .append("/FlateDecode filter ") .append("imgdict ") .append("image").append(EOL); output(bufferedImage, out); } out.append("grestore"); return out.toString(); } private static void output(BufferedImage image, StringBuilder out) { InputStream imageDataStream = new ImageDataStream(image, Interleaving.SAMPLE); ByteArrayOutputStream outBytes = new ByteArrayOutputStream(); OutputStream compressionStream = new FlateEncodeStream( new ASCII85EncodeStream( new LineWrapOutputStream(outBytes, 80))); try { DataUtils.transfer(imageDataStream, compressionStream, 1024); compressionStream.close(); String compressed = outBytes.toString(CHARSET); out.append(compressed).append(EOL); } catch (IOException e) { // TODO Handle exception e.printStackTrace(); } } private static String getOutput(String str, double x, double y) { return "gsave 1 -1 scale " + x + " " + -y + " M " + getOutput(str) + " show " + "grestore"; } private static StringBuilder getOutput(String str) { StringBuilder out = new StringBuilder(); // Escape text str = str.replaceAll("\\\\", "\\\\\\\\") .replaceAll("\t", "\\\\t") .replaceAll("\b", "\\\\b") .replaceAll("\f", "\\\\f") .replaceAll("\\(", "\\\\(") .replaceAll("\\)", "\\\\)") .replaceAll("[\r\n]", ""); out.append("(").append(str).append(")"); return out; } private static String getOutput(Stroke s) { StringBuilder out = new StringBuilder(); if (s instanceof BasicStroke) { BasicStroke bs = (BasicStroke) s; out.append(bs.getLineWidth()).append(" setlinewidth ") .append(STROKE_LINEJOIN.get(bs.getLineJoin())).append(" setlinejoin ") .append(STROKE_ENDCAPS.get(bs.getEndCap())).append(" setlinecap ") .append("[").append(DataUtils.join(" ", bs.getDashArray())).append("] ") .append(bs.getDashPhase()).append(" setdash"); } else { out.append("% Custom strokes aren't supported at the moment"); } return out.toString(); } private static String getOutput(Font font) { StringBuilder out = new StringBuilder(); font = GraphicsUtils.getPhysicalFont(font); String fontName = font.getPSName(); // Convert font to ISO-8859-1 encoding String fontNameLatin1 = fontName + FONT_LATIN1_SUFFIX; out.append("/").append(fontNameLatin1).append(" ") .append("/").append(font.getPSName()).append(" latinize "); // Use encoded font out.append("/").append(fontNameLatin1).append(" ") .append(font.getSize2D()).append(" selectfont"); return out.toString(); } } vectorgraphics2d-0.13/src/main/java/de/erichseifert/vectorgraphics2d/eps/EPSProcessor.java000066400000000000000000000037141347274514600316620ustar00rootroot00000000000000/* * VectorGraphics2D: Vector export for Java(R) Graphics2D * * (C) Copyright 2010-2017 Erich Seifert , * Michael Seifert * * This file is part of VectorGraphics2D. * * VectorGraphics2D is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * VectorGraphics2D 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with VectorGraphics2D. If not, see . */ package de.erichseifert.vectorgraphics2d.eps; import de.erichseifert.vectorgraphics2d.Document; import de.erichseifert.vectorgraphics2d.Processor; import de.erichseifert.vectorgraphics2d.intermediate.CommandSequence; import de.erichseifert.vectorgraphics2d.intermediate.filters.FillPaintedShapeAsImageFilter; import de.erichseifert.vectorgraphics2d.util.PageSize; /** * {@code Processor} implementation that translates {@link CommandSequence}s to * a {@code Document} in the Encapsulated PostScript® (EPS) format. */ public class EPSProcessor implements Processor { /** * Initializes an {@code EPSProcessor}. */ public EPSProcessor() {} @Override public Document getDocument(CommandSequence commands, PageSize pageSize) { // TODO Apply rotate(theta,x,y) => translate-rotate-translate filter // TODO Apply image transparency => image mask filter // TODO Apply optimization filter FillPaintedShapeAsImageFilter paintedShapeAsImageFilter = new FillPaintedShapeAsImageFilter(commands); return new EPSDocument(paintedShapeAsImageFilter, pageSize); } } vectorgraphics2d-0.13/src/main/java/de/erichseifert/vectorgraphics2d/eps/package-info.java000077500000000000000000000021241347274514600316540ustar00rootroot00000000000000/* * VectorGraphics2D: Vector export for Java(R) Graphics2D * * (C) Copyright 2010-2017 Erich Seifert , * Michael Seifert * * This file is part of VectorGraphics2D. * * VectorGraphics2D is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * VectorGraphics2D 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with VectorGraphics2D. If not, see . */ /** * Implementation of a processor to convert VectorGraphics2D intermediate * language commands to Encapsulated PostScript® (EPS). */ package de.erichseifert.vectorgraphics2d.eps; vectorgraphics2d-0.13/src/main/java/de/erichseifert/vectorgraphics2d/intermediate/000077500000000000000000000000001347274514600303465ustar00rootroot00000000000000CommandSequence.java000066400000000000000000000023411347274514600342010ustar00rootroot00000000000000vectorgraphics2d-0.13/src/main/java/de/erichseifert/vectorgraphics2d/intermediate/* * VectorGraphics2D: Vector export for Java(R) Graphics2D * * (C) Copyright 2010-2017 Erich Seifert , * Michael Seifert * * This file is part of VectorGraphics2D. * * VectorGraphics2D is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * VectorGraphics2D 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with VectorGraphics2D. If not, see . */ package de.erichseifert.vectorgraphics2d.intermediate; import de.erichseifert.vectorgraphics2d.intermediate.commands.Command; /** * Represents a sequence of {@link Command} objects. * The individual {@code Command}s can be retrieved through an {@code Iterator}. */ public interface CommandSequence extends Iterable> { } MutableCommandSequence.java000066400000000000000000000031501347274514600355120ustar00rootroot00000000000000vectorgraphics2d-0.13/src/main/java/de/erichseifert/vectorgraphics2d/intermediate/* * VectorGraphics2D: Vector export for Java(R) Graphics2D * * (C) Copyright 2010-2017 Erich Seifert , * Michael Seifert * * This file is part of VectorGraphics2D. * * VectorGraphics2D is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * VectorGraphics2D 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with VectorGraphics2D. If not, see . */ package de.erichseifert.vectorgraphics2d.intermediate; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import de.erichseifert.vectorgraphics2d.intermediate.commands.Command; /** * Mutable implementation of {@code CommandSequence}. * It is possible to add commands to this sequence. */ public class MutableCommandSequence implements CommandSequence { private final List> commands; /** * Initializes a new {@code CommandSequence} object. */ public MutableCommandSequence() { this.commands = new LinkedList<>(); } public void add(Command command) { commands.add(command); } @Override public Iterator> iterator() { return commands.iterator(); } } vectorgraphics2d-0.13/src/main/java/de/erichseifert/vectorgraphics2d/intermediate/commands/000077500000000000000000000000001347274514600321475ustar00rootroot00000000000000AffineTransformCommand.java000066400000000000000000000022441347274514600373200ustar00rootroot00000000000000vectorgraphics2d-0.13/src/main/java/de/erichseifert/vectorgraphics2d/intermediate/commands/* * VectorGraphics2D: Vector export for Java(R) Graphics2D * * (C) Copyright 2010-2017 Erich Seifert , * Michael Seifert * * This file is part of VectorGraphics2D. * * VectorGraphics2D is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * VectorGraphics2D 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with VectorGraphics2D. If not, see . */ package de.erichseifert.vectorgraphics2d.intermediate.commands; import java.awt.geom.AffineTransform; public abstract class AffineTransformCommand extends StateCommand { public AffineTransformCommand(AffineTransform transform) { super(transform); } } Command.java000066400000000000000000000027541347274514600343210ustar00rootroot00000000000000vectorgraphics2d-0.13/src/main/java/de/erichseifert/vectorgraphics2d/intermediate/commands/* * VectorGraphics2D: Vector export for Java(R) Graphics2D * * (C) Copyright 2010-2017 Erich Seifert , * Michael Seifert * * This file is part of VectorGraphics2D. * * VectorGraphics2D is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * VectorGraphics2D 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with VectorGraphics2D. If not, see . */ package de.erichseifert.vectorgraphics2d.intermediate.commands; import java.util.Locale; public abstract class Command { private final T value; public Command(T value) { this.value = value; } public T getValue() { return value; } @Override public String toString() { return String.format((Locale) null, "%s[value=%s]", getClass().getName(), getValue()); } @Override public boolean equals(Object obj) { if (obj == null || !getClass().equals(obj.getClass())) { return false; } Command o = (Command) obj; return value == o.value || value.equals(o.value); } } CreateCommand.java000066400000000000000000000022351347274514600354370ustar00rootroot00000000000000vectorgraphics2d-0.13/src/main/java/de/erichseifert/vectorgraphics2d/intermediate/commands/* * VectorGraphics2D: Vector export for Java(R) Graphics2D * * (C) Copyright 2010-2017 Erich Seifert , * Michael Seifert * * This file is part of VectorGraphics2D. * * VectorGraphics2D is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * VectorGraphics2D 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with VectorGraphics2D. If not, see . */ package de.erichseifert.vectorgraphics2d.intermediate.commands; import de.erichseifert.vectorgraphics2d.VectorGraphics2D; public class CreateCommand extends StateCommand { public CreateCommand(VectorGraphics2D graphics) { super(graphics); } } DisposeCommand.java000066400000000000000000000022371347274514600356440ustar00rootroot00000000000000vectorgraphics2d-0.13/src/main/java/de/erichseifert/vectorgraphics2d/intermediate/commands/* * VectorGraphics2D: Vector export for Java(R) Graphics2D * * (C) Copyright 2010-2017 Erich Seifert , * Michael Seifert * * This file is part of VectorGraphics2D. * * VectorGraphics2D is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * VectorGraphics2D 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with VectorGraphics2D. If not, see . */ package de.erichseifert.vectorgraphics2d.intermediate.commands; import de.erichseifert.vectorgraphics2d.VectorGraphics2D; public class DisposeCommand extends StateCommand { public DisposeCommand(VectorGraphics2D graphics) { super(graphics); } } DrawImageCommand.java000066400000000000000000000041041347274514600360710ustar00rootroot00000000000000vectorgraphics2d-0.13/src/main/java/de/erichseifert/vectorgraphics2d/intermediate/commands/* * VectorGraphics2D: Vector export for Java(R) Graphics2D * * (C) Copyright 2010-2017 Erich Seifert , * Michael Seifert * * This file is part of VectorGraphics2D. * * VectorGraphics2D is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * VectorGraphics2D 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with VectorGraphics2D. If not, see . */ package de.erichseifert.vectorgraphics2d.intermediate.commands; import java.awt.Image; import java.util.Locale; public class DrawImageCommand extends Command { private final int imageWidth; private final int imageHeight; private final double x; private final double y; private final double width; private final double height; public DrawImageCommand(Image image, int imageWidth, int imageHeight, double x, double y, double width, double height) { super(image); this.imageWidth = imageWidth; this.imageHeight = imageHeight; this.x = x; this.y = y; this.width = width; this.height = height; } public int getImageWidth() { return imageWidth; } public int getImageHeight() { return imageHeight; } public double getX() { return x; } public double getY() { return y; } public double getWidth() { return width; } public double getHeight() { return height; } @Override public String toString() { return String.format((Locale) null, "%s[value=%s, imageWidth=%d, imageHeight=%d, x=%f, y=%f, width=%f, height=%f]", getClass().getName(), getValue(), getImageWidth(), getImageHeight(), getX(), getY(), getWidth(), getHeight()); } } DrawShapeCommand.java000066400000000000000000000022611347274514600361110ustar00rootroot00000000000000vectorgraphics2d-0.13/src/main/java/de/erichseifert/vectorgraphics2d/intermediate/commands/* * VectorGraphics2D: Vector export for Java(R) Graphics2D * * (C) Copyright 2010-2017 Erich Seifert , * Michael Seifert * * This file is part of VectorGraphics2D. * * VectorGraphics2D is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * VectorGraphics2D 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with VectorGraphics2D. If not, see . */ package de.erichseifert.vectorgraphics2d.intermediate.commands; import java.awt.Shape; import de.erichseifert.vectorgraphics2d.util.GraphicsUtils; public class DrawShapeCommand extends Command { public DrawShapeCommand(Shape shape) { super(GraphicsUtils.clone(shape)); } } DrawStringCommand.java000066400000000000000000000026761347274514600363310ustar00rootroot00000000000000vectorgraphics2d-0.13/src/main/java/de/erichseifert/vectorgraphics2d/intermediate/commands/* * VectorGraphics2D: Vector export for Java(R) Graphics2D * * (C) Copyright 2010-2017 Erich Seifert , * Michael Seifert * * This file is part of VectorGraphics2D. * * VectorGraphics2D is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * VectorGraphics2D 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with VectorGraphics2D. If not, see . */ package de.erichseifert.vectorgraphics2d.intermediate.commands; import java.util.Locale; public class DrawStringCommand extends Command { private final double x; private final double y; public DrawStringCommand(String string, double x, double y) { super(string); this.x = x; this.y = y; } public double getX() { return x; } public double getY() { return y; } @Override public String toString() { return String.format((Locale) null, "%s[value=%s, x=%f, y=%f]", getClass().getName(), getValue(), getX(), getY()); } } FillShapeCommand.java000066400000000000000000000022611347274514600361020ustar00rootroot00000000000000vectorgraphics2d-0.13/src/main/java/de/erichseifert/vectorgraphics2d/intermediate/commands/* * VectorGraphics2D: Vector export for Java(R) Graphics2D * * (C) Copyright 2010-2017 Erich Seifert , * Michael Seifert * * This file is part of VectorGraphics2D. * * VectorGraphics2D is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * VectorGraphics2D 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with VectorGraphics2D. If not, see . */ package de.erichseifert.vectorgraphics2d.intermediate.commands; import java.awt.Shape; import de.erichseifert.vectorgraphics2d.util.GraphicsUtils; public class FillShapeCommand extends Command { public FillShapeCommand(Shape shape) { super(GraphicsUtils.clone(shape)); } } Group.java000066400000000000000000000023451347274514600340330ustar00rootroot00000000000000vectorgraphics2d-0.13/src/main/java/de/erichseifert/vectorgraphics2d/intermediate/commands/* * VectorGraphics2D: Vector export for Java(R) Graphics2D * * (C) Copyright 2010-2017 Erich Seifert , * Michael Seifert * * This file is part of VectorGraphics2D. * * VectorGraphics2D is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * VectorGraphics2D 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with VectorGraphics2D. If not, see . */ package de.erichseifert.vectorgraphics2d.intermediate.commands; import java.util.LinkedList; import java.util.List; public class Group extends Command>> { public Group() { super(new LinkedList>()); } public void add(Command command) { List> group = getValue(); group.add(command); } } RotateCommand.java000066400000000000000000000033671347274514600355010ustar00rootroot00000000000000vectorgraphics2d-0.13/src/main/java/de/erichseifert/vectorgraphics2d/intermediate/commands/* * VectorGraphics2D: Vector export for Java(R) Graphics2D * * (C) Copyright 2010-2017 Erich Seifert , * Michael Seifert * * This file is part of VectorGraphics2D. * * VectorGraphics2D is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * VectorGraphics2D 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with VectorGraphics2D. If not, see . */ package de.erichseifert.vectorgraphics2d.intermediate.commands; import java.awt.geom.AffineTransform; import java.util.Locale; public class RotateCommand extends AffineTransformCommand { private final double theta; private final double centerX; private final double centerY; public RotateCommand(double theta, double centerX, double centerY) { super(AffineTransform.getRotateInstance(theta, centerX, centerY)); this.theta = theta; this.centerX = centerX; this.centerY = centerY; } public double getTheta() { return theta; } public double getCenterX() { return centerX; } public double getCenterY() { return centerY; } @Override public String toString() { return String.format((Locale) null, "%s[theta=%f, centerX=%f, centerY=%f, value=%s]", getClass().getName(), getTheta(), getCenterX(), getCenterY(), getValue()); } } ScaleCommand.java000066400000000000000000000031201347274514600352550ustar00rootroot00000000000000vectorgraphics2d-0.13/src/main/java/de/erichseifert/vectorgraphics2d/intermediate/commands/* * VectorGraphics2D: Vector export for Java(R) Graphics2D * * (C) Copyright 2010-2017 Erich Seifert , * Michael Seifert * * This file is part of VectorGraphics2D. * * VectorGraphics2D is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * VectorGraphics2D 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with VectorGraphics2D. If not, see . */ package de.erichseifert.vectorgraphics2d.intermediate.commands; import java.awt.geom.AffineTransform; import java.util.Locale; public class ScaleCommand extends AffineTransformCommand { private final double scaleX; private final double scaleY; public ScaleCommand(double scaleX, double scaleY) { super(AffineTransform.getScaleInstance(scaleX, scaleY)); this.scaleX = scaleX; this.scaleY = scaleY; } public double getScaleX() { return scaleX; } public double getScaleY() { return scaleY; } @Override public String toString() { return String.format((Locale) null, "%s[scaleX=%f, scaleY=%f, value=%s]", getClass().getName(), getScaleX(), getScaleY(), getValue()); } } SetBackgroundCommand.java000066400000000000000000000021541347274514600367670ustar00rootroot00000000000000vectorgraphics2d-0.13/src/main/java/de/erichseifert/vectorgraphics2d/intermediate/commands/* * VectorGraphics2D: Vector export for Java(R) Graphics2D * * (C) Copyright 2010-2017 Erich Seifert , * Michael Seifert * * This file is part of VectorGraphics2D. * * VectorGraphics2D is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * VectorGraphics2D 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with VectorGraphics2D. If not, see . */ package de.erichseifert.vectorgraphics2d.intermediate.commands; import java.awt.Color; public class SetBackgroundCommand extends StateCommand { public SetBackgroundCommand(Color color) { super(color); } } SetClipCommand.java000066400000000000000000000021401347274514600355720ustar00rootroot00000000000000vectorgraphics2d-0.13/src/main/java/de/erichseifert/vectorgraphics2d/intermediate/commands/* * VectorGraphics2D: Vector export for Java(R) Graphics2D * * (C) Copyright 2010-2017 Erich Seifert , * Michael Seifert * * This file is part of VectorGraphics2D. * * VectorGraphics2D is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * VectorGraphics2D 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with VectorGraphics2D. If not, see . */ package de.erichseifert.vectorgraphics2d.intermediate.commands; import java.awt.Shape; public class SetClipCommand extends StateCommand { public SetClipCommand(Shape shape) { super(shape); } } SetColorCommand.java000066400000000000000000000021421347274514600357630ustar00rootroot00000000000000vectorgraphics2d-0.13/src/main/java/de/erichseifert/vectorgraphics2d/intermediate/commands/* * VectorGraphics2D: Vector export for Java(R) Graphics2D * * (C) Copyright 2010-2017 Erich Seifert , * Michael Seifert * * This file is part of VectorGraphics2D. * * VectorGraphics2D is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * VectorGraphics2D 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with VectorGraphics2D. If not, see . */ package de.erichseifert.vectorgraphics2d.intermediate.commands; import java.awt.Color; public class SetColorCommand extends StateCommand { public SetColorCommand(Color color) { super(color); } } SetCompositeCommand.java000066400000000000000000000021761347274514600366560ustar00rootroot00000000000000vectorgraphics2d-0.13/src/main/java/de/erichseifert/vectorgraphics2d/intermediate/commands/* * VectorGraphics2D: Vector export for Java(R) Graphics2D * * (C) Copyright 2010-2017 Erich Seifert , * Michael Seifert * * This file is part of VectorGraphics2D. * * VectorGraphics2D is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * VectorGraphics2D 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with VectorGraphics2D. If not, see . */ package de.erichseifert.vectorgraphics2d.intermediate.commands; import java.awt.Composite; public class SetCompositeCommand extends StateCommand { public SetCompositeCommand(Composite composite) { super(composite); } } SetFontCommand.java000066400000000000000000000021331347274514600356130ustar00rootroot00000000000000vectorgraphics2d-0.13/src/main/java/de/erichseifert/vectorgraphics2d/intermediate/commands/* * VectorGraphics2D: Vector export for Java(R) Graphics2D * * (C) Copyright 2010-2017 Erich Seifert , * Michael Seifert * * This file is part of VectorGraphics2D. * * VectorGraphics2D is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * VectorGraphics2D 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with VectorGraphics2D. If not, see . */ package de.erichseifert.vectorgraphics2d.intermediate.commands; import java.awt.Font; public class SetFontCommand extends StateCommand { public SetFontCommand(Font font) { super(font); } } SetHintCommand.java000066400000000000000000000025631347274514600356160ustar00rootroot00000000000000vectorgraphics2d-0.13/src/main/java/de/erichseifert/vectorgraphics2d/intermediate/commands/* * VectorGraphics2D: Vector export for Java(R) Graphics2D * * (C) Copyright 2010-2017 Erich Seifert , * Michael Seifert * * This file is part of VectorGraphics2D. * * VectorGraphics2D is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * VectorGraphics2D 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with VectorGraphics2D. If not, see . */ package de.erichseifert.vectorgraphics2d.intermediate.commands; import java.util.Locale; public class SetHintCommand extends StateCommand { private final Object key; public SetHintCommand(Object hintKey, Object hintValue) { super(hintValue); key = hintKey; } public Object getKey() { return key; } @Override public String toString() { return String.format((Locale) null, "%s[key=%s, value=%s]", getClass().getName(), getKey(), getValue()); } } SetPaintCommand.java000066400000000000000000000021421347274514600357600ustar00rootroot00000000000000vectorgraphics2d-0.13/src/main/java/de/erichseifert/vectorgraphics2d/intermediate/commands/* * VectorGraphics2D: Vector export for Java(R) Graphics2D * * (C) Copyright 2010-2017 Erich Seifert , * Michael Seifert * * This file is part of VectorGraphics2D. * * VectorGraphics2D is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * VectorGraphics2D 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with VectorGraphics2D. If not, see . */ package de.erichseifert.vectorgraphics2d.intermediate.commands; import java.awt.Paint; public class SetPaintCommand extends StateCommand { public SetPaintCommand(Paint paint) { super(paint); } } SetStrokeCommand.java000066400000000000000000000021511347274514600361540ustar00rootroot00000000000000vectorgraphics2d-0.13/src/main/java/de/erichseifert/vectorgraphics2d/intermediate/commands/* * VectorGraphics2D: Vector export for Java(R) Graphics2D * * (C) Copyright 2010-2017 Erich Seifert , * Michael Seifert * * This file is part of VectorGraphics2D. * * VectorGraphics2D is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * VectorGraphics2D 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with VectorGraphics2D. If not, see . */ package de.erichseifert.vectorgraphics2d.intermediate.commands; import java.awt.Stroke; public class SetStrokeCommand extends StateCommand { public SetStrokeCommand(Stroke stroke) { super(stroke); } } SetTransformCommand.java000066400000000000000000000022521347274514600366620ustar00rootroot00000000000000vectorgraphics2d-0.13/src/main/java/de/erichseifert/vectorgraphics2d/intermediate/commands/* * VectorGraphics2D: Vector export for Java(R) Graphics2D * * (C) Copyright 2010-2017 Erich Seifert , * Michael Seifert * * This file is part of VectorGraphics2D. * * VectorGraphics2D is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * VectorGraphics2D 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with VectorGraphics2D. If not, see . */ package de.erichseifert.vectorgraphics2d.intermediate.commands; import java.awt.geom.AffineTransform; public class SetTransformCommand extends StateCommand { public SetTransformCommand(AffineTransform transform) { super(new AffineTransform(transform)); } } SetXORModeCommand.java000066400000000000000000000021441347274514600361640ustar00rootroot00000000000000vectorgraphics2d-0.13/src/main/java/de/erichseifert/vectorgraphics2d/intermediate/commands/* * VectorGraphics2D: Vector export for Java(R) Graphics2D * * (C) Copyright 2010-2017 Erich Seifert , * Michael Seifert * * This file is part of VectorGraphics2D. * * VectorGraphics2D is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * VectorGraphics2D 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with VectorGraphics2D. If not, see . */ package de.erichseifert.vectorgraphics2d.intermediate.commands; import java.awt.Color; public class SetXORModeCommand extends StateCommand { public SetXORModeCommand(Color mode) { super(mode); } } ShearCommand.java000066400000000000000000000031201347274514600352700ustar00rootroot00000000000000vectorgraphics2d-0.13/src/main/java/de/erichseifert/vectorgraphics2d/intermediate/commands/* * VectorGraphics2D: Vector export for Java(R) Graphics2D * * (C) Copyright 2010-2017 Erich Seifert , * Michael Seifert * * This file is part of VectorGraphics2D. * * VectorGraphics2D is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * VectorGraphics2D 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with VectorGraphics2D. If not, see . */ package de.erichseifert.vectorgraphics2d.intermediate.commands; import java.awt.geom.AffineTransform; import java.util.Locale; public class ShearCommand extends AffineTransformCommand { private final double shearX; private final double shearY; public ShearCommand(double shearX, double shearY) { super(AffineTransform.getShearInstance(shearX, shearY)); this.shearX = shearX; this.shearY = shearY; } public double getShearX() { return shearX; } public double getShearY() { return shearY; } @Override public String toString() { return String.format((Locale) null, "%s[shearX=%f, shearY=%f, value=%s]", getClass().getName(), getShearX(), getShearY(), getValue()); } } StateCommand.java000066400000000000000000000021031347274514600353060ustar00rootroot00000000000000vectorgraphics2d-0.13/src/main/java/de/erichseifert/vectorgraphics2d/intermediate/commands/* * VectorGraphics2D: Vector export for Java(R) Graphics2D * * (C) Copyright 2010-2017 Erich Seifert , * Michael Seifert * * This file is part of VectorGraphics2D. * * VectorGraphics2D is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * VectorGraphics2D 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with VectorGraphics2D. If not, see . */ package de.erichseifert.vectorgraphics2d.intermediate.commands; public abstract class StateCommand extends Command { public StateCommand(T value) { super(value); } } TransformCommand.java000066400000000000000000000024471347274514600362140ustar00rootroot00000000000000vectorgraphics2d-0.13/src/main/java/de/erichseifert/vectorgraphics2d/intermediate/commands/* * VectorGraphics2D: Vector export for Java(R) Graphics2D * * (C) Copyright 2010-2017 Erich Seifert , * Michael Seifert * * This file is part of VectorGraphics2D. * * VectorGraphics2D is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * VectorGraphics2D 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with VectorGraphics2D. If not, see . */ package de.erichseifert.vectorgraphics2d.intermediate.commands; import java.awt.geom.AffineTransform; public class TransformCommand extends AffineTransformCommand { private final AffineTransform transform; public TransformCommand(AffineTransform transform) { super(transform); this.transform = new AffineTransform(transform); } public AffineTransform getTransform() { return transform; } } TranslateCommand.java000066400000000000000000000030761347274514600361750ustar00rootroot00000000000000vectorgraphics2d-0.13/src/main/java/de/erichseifert/vectorgraphics2d/intermediate/commands/* * VectorGraphics2D: Vector export for Java(R) Graphics2D * * (C) Copyright 2010-2017 Erich Seifert , * Michael Seifert * * This file is part of VectorGraphics2D. * * VectorGraphics2D is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * VectorGraphics2D 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with VectorGraphics2D. If not, see . */ package de.erichseifert.vectorgraphics2d.intermediate.commands; import java.awt.geom.AffineTransform; import java.util.Locale; public class TranslateCommand extends AffineTransformCommand { private final double deltaX; private final double deltaY; public TranslateCommand(double x, double y) { super(AffineTransform.getTranslateInstance(x, y)); this.deltaX = x; this.deltaY = y; } public double getDeltaX() { return deltaX; } public double getDeltaY() { return deltaY; } @Override public String toString() { return String.format((Locale) null, "%s[deltaX=%f, deltaY=%f, value=%s]", getClass().getName(), getDeltaX(), getDeltaY(), getValue()); } } package-info.java000077500000000000000000000021171347274514600352630ustar00rootroot00000000000000vectorgraphics2d-0.13/src/main/java/de/erichseifert/vectorgraphics2d/intermediate/commands/* * VectorGraphics2D: Vector export for Java(R) Graphics2D * * (C) Copyright 2010-2017 Erich Seifert , * Michael Seifert * * This file is part of VectorGraphics2D. * * VectorGraphics2D is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * VectorGraphics2D 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with VectorGraphics2D. If not, see . */ /** * Commands of the VectorGraphics2D intermediate language that describe calls * to the Graphics2D interface of Java. */ package de.erichseifert.vectorgraphics2d.intermediate.commands; vectorgraphics2d-0.13/src/main/java/de/erichseifert/vectorgraphics2d/intermediate/filters/000077500000000000000000000000001347274514600320165ustar00rootroot00000000000000AbsoluteToRelativeTransformsFilter.java000066400000000000000000000066071347274514600416150ustar00rootroot00000000000000vectorgraphics2d-0.13/src/main/java/de/erichseifert/vectorgraphics2d/intermediate/filters/* * VectorGraphics2D: Vector export for Java(R) Graphics2D * * (C) Copyright 2010-2017 Erich Seifert , * Michael Seifert * * This file is part of VectorGraphics2D. * * VectorGraphics2D is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * VectorGraphics2D 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with VectorGraphics2D. If not, see . */ package de.erichseifert.vectorgraphics2d.intermediate.filters; import java.awt.geom.AffineTransform; import java.awt.geom.NoninvertibleTransformException; import java.util.Collections; import java.util.List; import java.util.Stack; import de.erichseifert.vectorgraphics2d.intermediate.CommandSequence; import de.erichseifert.vectorgraphics2d.intermediate.commands.AffineTransformCommand; import de.erichseifert.vectorgraphics2d.intermediate.commands.Command; import de.erichseifert.vectorgraphics2d.intermediate.commands.CreateCommand; import de.erichseifert.vectorgraphics2d.intermediate.commands.DisposeCommand; import de.erichseifert.vectorgraphics2d.intermediate.commands.SetTransformCommand; import de.erichseifert.vectorgraphics2d.intermediate.commands.TransformCommand; public class AbsoluteToRelativeTransformsFilter extends StreamingFilter { private final Stack transforms; public AbsoluteToRelativeTransformsFilter(CommandSequence stream) { super(stream); transforms = new Stack<>(); } @Override public Command next() { Command nextCommand = super.next(); if (nextCommand instanceof AffineTransformCommand) { AffineTransformCommand affineTransformCommand = (AffineTransformCommand) nextCommand; getCurrentTransform().concatenate(affineTransformCommand.getValue()); } else if (nextCommand instanceof CreateCommand) { AffineTransform newTransform = transforms.isEmpty() ? new AffineTransform() : new AffineTransform(getCurrentTransform()); transforms.push(newTransform); } else if (nextCommand instanceof DisposeCommand) { transforms.pop(); } return nextCommand; } @Override protected List> filter(Command command) { if (command instanceof SetTransformCommand) { SetTransformCommand setTransformCommand = (SetTransformCommand) command; AffineTransform absoluteTransform = setTransformCommand.getValue(); AffineTransform relativeTransform = new AffineTransform(); try { AffineTransform invertedOldTransformation = getCurrentTransform().createInverse(); relativeTransform.concatenate(invertedOldTransformation); } catch (NoninvertibleTransformException e) { e.printStackTrace(); } relativeTransform.concatenate(absoluteTransform); TransformCommand transformCommand = new TransformCommand(relativeTransform); return Collections.>singletonList(transformCommand); } return Collections.>singletonList(command); } private AffineTransform getCurrentTransform() { return transforms.peek(); } } FillPaintedShapeAsImageFilter.java000066400000000000000000000070421347274514600403560ustar00rootroot00000000000000vectorgraphics2d-0.13/src/main/java/de/erichseifert/vectorgraphics2d/intermediate/filters/* * VectorGraphics2D: Vector export for Java(R) Graphics2D * * (C) Copyright 2010-2017 Erich Seifert , * Michael Seifert * * This file is part of VectorGraphics2D. * * VectorGraphics2D is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * VectorGraphics2D 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with VectorGraphics2D. If not, see . */ package de.erichseifert.vectorgraphics2d.intermediate.filters; import java.awt.Graphics2D; import java.awt.RenderingHints; import java.awt.Shape; import java.awt.geom.Rectangle2D; import java.awt.image.BufferedImage; import java.util.Collections; import java.util.List; import de.erichseifert.vectorgraphics2d.intermediate.CommandSequence; import de.erichseifert.vectorgraphics2d.intermediate.commands.Command; import de.erichseifert.vectorgraphics2d.intermediate.commands.DisposeCommand; import de.erichseifert.vectorgraphics2d.intermediate.commands.DrawImageCommand; import de.erichseifert.vectorgraphics2d.intermediate.commands.FillShapeCommand; import de.erichseifert.vectorgraphics2d.intermediate.commands.SetPaintCommand; public class FillPaintedShapeAsImageFilter extends StreamingFilter { private SetPaintCommand lastSetPaintCommand; public FillPaintedShapeAsImageFilter(CommandSequence stream) { super(stream); } @Override public Command next() { Command nextCommand = super.next(); if (nextCommand instanceof SetPaintCommand) { lastSetPaintCommand = (SetPaintCommand) nextCommand; } else if (nextCommand instanceof DisposeCommand) { lastSetPaintCommand = null; } return nextCommand; } private DrawImageCommand getDrawImageCommand(FillShapeCommand shapeCommand, SetPaintCommand paintCommand) { Shape shape = shapeCommand.getValue(); Rectangle2D shapeBounds = shape.getBounds2D(); double x = shapeBounds.getX(); double y = shapeBounds.getY(); double width = shapeBounds.getWidth(); double height = shapeBounds.getHeight(); int imageWidth = (int) Math.round(width); int imageHeight = (int) Math.round(height); BufferedImage image = new BufferedImage(imageWidth, imageHeight, BufferedImage.TYPE_INT_ARGB); Graphics2D imageGraphics = (Graphics2D) image.getGraphics(); imageGraphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); imageGraphics.scale(imageWidth/width, imageHeight/height); imageGraphics.translate(-shapeBounds.getX(), -shapeBounds.getY()); imageGraphics.setPaint(paintCommand.getValue()); imageGraphics.fill(shape); imageGraphics.dispose(); return new DrawImageCommand(image, imageWidth, imageHeight, x, y, width, height); } @Override protected List> filter(Command command) { if (lastSetPaintCommand != null && command instanceof FillShapeCommand) { FillShapeCommand fillShapeCommand = (FillShapeCommand) command; DrawImageCommand drawImageCommand = getDrawImageCommand(fillShapeCommand, lastSetPaintCommand); return Collections.>singletonList(drawImageCommand); } return Collections.>singletonList(command); } } Filter.java000066400000000000000000000021141347274514600340250ustar00rootroot00000000000000vectorgraphics2d-0.13/src/main/java/de/erichseifert/vectorgraphics2d/intermediate/filters/* * VectorGraphics2D: Vector export for Java(R) Graphics2D * * (C) Copyright 2010-2017 Erich Seifert , * Michael Seifert * * This file is part of VectorGraphics2D. * * VectorGraphics2D is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * VectorGraphics2D 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with VectorGraphics2D. If not, see . */ package de.erichseifert.vectorgraphics2d.intermediate.filters; import de.erichseifert.vectorgraphics2d.intermediate.CommandSequence; public interface Filter extends CommandSequence { } GroupingFilter.java000066400000000000000000000036631347274514600355520ustar00rootroot00000000000000vectorgraphics2d-0.13/src/main/java/de/erichseifert/vectorgraphics2d/intermediate/filters/* * VectorGraphics2D: Vector export for Java(R) Graphics2D * * (C) Copyright 2010-2017 Erich Seifert , * Michael Seifert * * This file is part of VectorGraphics2D. * * VectorGraphics2D is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * VectorGraphics2D 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with VectorGraphics2D. If not, see . */ package de.erichseifert.vectorgraphics2d.intermediate.filters; import java.util.Collections; import java.util.List; import de.erichseifert.vectorgraphics2d.intermediate.CommandSequence; import de.erichseifert.vectorgraphics2d.intermediate.commands.Command; import de.erichseifert.vectorgraphics2d.intermediate.commands.Group; public abstract class GroupingFilter extends StreamingFilter { private Group group; public GroupingFilter(CommandSequence stream) { super(stream); } @Override public boolean hasNext() { return group != null || super.hasNext(); } @Override public Command next() { if (group == null) { return super.next(); } Group g = group; group = null; return g; } @Override protected List> filter(Command command) { boolean grouped = isGrouped(command); if (grouped) { if (group == null) { group = new Group(); } group.add(command); return null; } return Collections.>singletonList(command); } protected abstract boolean isGrouped(Command command); } OptimizeFilter.java000066400000000000000000000046411347274514600355550ustar00rootroot00000000000000vectorgraphics2d-0.13/src/main/java/de/erichseifert/vectorgraphics2d/intermediate/filters/* * VectorGraphics2D: Vector export for Java(R) Graphics2D * * (C) Copyright 2010-2017 Erich Seifert , * Michael Seifert * * This file is part of VectorGraphics2D. * * VectorGraphics2D is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * VectorGraphics2D 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with VectorGraphics2D. If not, see . */ package de.erichseifert.vectorgraphics2d.intermediate.filters; import java.util.Collections; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Queue; import de.erichseifert.vectorgraphics2d.intermediate.CommandSequence; import de.erichseifert.vectorgraphics2d.intermediate.commands.AffineTransformCommand; import de.erichseifert.vectorgraphics2d.intermediate.commands.Command; import de.erichseifert.vectorgraphics2d.intermediate.commands.SetHintCommand; import de.erichseifert.vectorgraphics2d.intermediate.commands.StateCommand; public class OptimizeFilter extends StreamingFilter { private final Queue> buffer; public OptimizeFilter(CommandSequence stream) { super(stream); buffer = new LinkedList<>(); } @Override public boolean hasNext() { return super.hasNext(); } @Override public Command next() { if (buffer.isEmpty()) { return super.next(); } return buffer.poll(); } @Override protected List> filter(Command command) { if (!isStateChange(command)) { return Collections.>singletonList(command); } Iterator> i = buffer.iterator(); Class cls = command.getClass(); while (i.hasNext()) { if (cls.equals(i.next().getClass())) { i.remove(); } } buffer.add(command); return null; } private static boolean isStateChange(Command command) { return (command instanceof StateCommand) && !(command instanceof AffineTransformCommand) && !(command instanceof SetHintCommand); } } StateChangeGroupingFilter.java000066400000000000000000000026541347274514600376600ustar00rootroot00000000000000vectorgraphics2d-0.13/src/main/java/de/erichseifert/vectorgraphics2d/intermediate/filters/* * VectorGraphics2D: Vector export for Java(R) Graphics2D * * (C) Copyright 2010-2017 Erich Seifert , * Michael Seifert * * This file is part of VectorGraphics2D. * * VectorGraphics2D is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * VectorGraphics2D 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with VectorGraphics2D. If not, see . */ package de.erichseifert.vectorgraphics2d.intermediate.filters; import de.erichseifert.vectorgraphics2d.intermediate.CommandSequence; import de.erichseifert.vectorgraphics2d.intermediate.commands.Command; import de.erichseifert.vectorgraphics2d.intermediate.commands.StateCommand; public class StateChangeGroupingFilter extends GroupingFilter { public StateChangeGroupingFilter(CommandSequence stream) { super(stream); } @Override protected boolean isGrouped(Command command) { return command instanceof StateCommand; } } StreamingFilter.java000066400000000000000000000040221347274514600356770ustar00rootroot00000000000000vectorgraphics2d-0.13/src/main/java/de/erichseifert/vectorgraphics2d/intermediate/filters/* * VectorGraphics2D: Vector export for Java(R) Graphics2D * * (C) Copyright 2010-2017 Erich Seifert , * Michael Seifert * * This file is part of VectorGraphics2D. * * VectorGraphics2D is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * VectorGraphics2D 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with VectorGraphics2D. If not, see . */ package de.erichseifert.vectorgraphics2d.intermediate.filters; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Queue; import de.erichseifert.vectorgraphics2d.intermediate.CommandSequence; import de.erichseifert.vectorgraphics2d.intermediate.commands.Command; public abstract class StreamingFilter implements Iterator>, Filter { private final Queue> buffer; private final Iterator> iterator; public StreamingFilter(CommandSequence stream) { buffer = new LinkedList<>(); iterator = stream.iterator(); } public Iterator> iterator() { return this; } public boolean hasNext() { findNextCommand(); return !buffer.isEmpty(); } private void findNextCommand() { while (buffer.isEmpty() && iterator.hasNext()) { Command command = iterator.next(); List> commands = filter(command); if (commands != null) { buffer.addAll(commands); } } } public Command next() { findNextCommand(); return buffer.poll(); } public void remove() { } protected abstract List> filter(Command command); } package-info.java000077500000000000000000000021011347274514600351230ustar00rootroot00000000000000vectorgraphics2d-0.13/src/main/java/de/erichseifert/vectorgraphics2d/intermediate/filters/* * VectorGraphics2D: Vector export for Java(R) Graphics2D * * (C) Copyright 2010-2017 Erich Seifert , * Michael Seifert * * This file is part of VectorGraphics2D. * * VectorGraphics2D is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * VectorGraphics2D 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with VectorGraphics2D. If not, see . */ /** * Classes that filter or alter a sequence of commands in the VectorGraphics2D * intermediate language. */ package de.erichseifert.vectorgraphics2d.intermediate.filters; vectorgraphics2d-0.13/src/main/java/de/erichseifert/vectorgraphics2d/intermediate/package-info.java000077500000000000000000000021501347274514600335360ustar00rootroot00000000000000/* * VectorGraphics2D: Vector export for Java(R) Graphics2D * * (C) Copyright 2010-2017 Erich Seifert , * Michael Seifert * * This file is part of VectorGraphics2D. * * VectorGraphics2D is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * VectorGraphics2D 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with VectorGraphics2D. If not, see . */ /** * Classes for the VectorGraphics2D intermediate language. * It describes all calls to the Graphics2D interface of Java using commands * and filters. */ package de.erichseifert.vectorgraphics2d.intermediate; vectorgraphics2d-0.13/src/main/java/de/erichseifert/vectorgraphics2d/package-info.java000077500000000000000000000017551347274514600310760ustar00rootroot00000000000000/* * VectorGraphics2D: Vector export for Java(R) Graphics2D * * (C) Copyright 2010-2017 Erich Seifert , * Michael Seifert * * This file is part of VectorGraphics2D. * * VectorGraphics2D is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * VectorGraphics2D 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with VectorGraphics2D. If not, see . */ /** * Main classes. */ package de.erichseifert.vectorgraphics2d; vectorgraphics2d-0.13/src/main/java/de/erichseifert/vectorgraphics2d/pdf/000077500000000000000000000000001347274514600264455ustar00rootroot00000000000000vectorgraphics2d-0.13/src/main/java/de/erichseifert/vectorgraphics2d/pdf/DefaultPDFObject.java000066400000000000000000000026661347274514600323670ustar00rootroot00000000000000/* * VectorGraphics2D: Vector export for Java(R) Graphics2D * * (C) Copyright 2010-2017 Erich Seifert , * Michael Seifert * * This file is part of VectorGraphics2D. * * VectorGraphics2D is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * VectorGraphics2D 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with VectorGraphics2D. If not, see . */ package de.erichseifert.vectorgraphics2d.pdf; import java.util.LinkedHashMap; import java.util.Map; class DefaultPDFObject implements PDFObject { public final Map dict; public final Payload payload; public final boolean stream; public DefaultPDFObject(Map dict, Payload payload, boolean stream) { this.dict = new LinkedHashMap<>(); this.payload = payload; this.stream = stream; if (dict != null) { this.dict.putAll(dict); } } public String getType() { return (String) dict.get("Type"); } } vectorgraphics2d-0.13/src/main/java/de/erichseifert/vectorgraphics2d/pdf/PDFDocument.java000066400000000000000000000701321347274514600314230ustar00rootroot00000000000000/* * VectorGraphics2D: Vector export for Java(R) Graphics2D * * (C) Copyright 2010-2017 Erich Seifert , * Michael Seifert * * This file is part of VectorGraphics2D. * * VectorGraphics2D is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * VectorGraphics2D 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with VectorGraphics2D. If not, see . */ package de.erichseifert.vectorgraphics2d.pdf; import java.awt.BasicStroke; import java.awt.Color; import java.awt.Font; import java.awt.Image; import java.awt.Shape; import java.awt.Stroke; import java.awt.color.ColorSpace; import java.awt.geom.AffineTransform; import java.awt.geom.PathIterator; import java.awt.image.BufferedImage; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.UnsupportedEncodingException; import java.util.Arrays; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Stack; import de.erichseifert.vectorgraphics2d.GraphicsState; import de.erichseifert.vectorgraphics2d.SizedDocument; import de.erichseifert.vectorgraphics2d.intermediate.CommandSequence; import de.erichseifert.vectorgraphics2d.intermediate.commands.AffineTransformCommand; import de.erichseifert.vectorgraphics2d.intermediate.commands.Command; import de.erichseifert.vectorgraphics2d.intermediate.commands.CreateCommand; import de.erichseifert.vectorgraphics2d.intermediate.commands.DisposeCommand; import de.erichseifert.vectorgraphics2d.intermediate.commands.DrawImageCommand; import de.erichseifert.vectorgraphics2d.intermediate.commands.DrawShapeCommand; import de.erichseifert.vectorgraphics2d.intermediate.commands.DrawStringCommand; import de.erichseifert.vectorgraphics2d.intermediate.commands.FillShapeCommand; import de.erichseifert.vectorgraphics2d.intermediate.commands.Group; import de.erichseifert.vectorgraphics2d.intermediate.commands.SetBackgroundCommand; import de.erichseifert.vectorgraphics2d.intermediate.commands.SetClipCommand; import de.erichseifert.vectorgraphics2d.intermediate.commands.SetColorCommand; import de.erichseifert.vectorgraphics2d.intermediate.commands.SetFontCommand; import de.erichseifert.vectorgraphics2d.intermediate.commands.SetHintCommand; import de.erichseifert.vectorgraphics2d.intermediate.commands.SetPaintCommand; import de.erichseifert.vectorgraphics2d.intermediate.commands.SetStrokeCommand; import de.erichseifert.vectorgraphics2d.intermediate.commands.SetTransformCommand; import de.erichseifert.vectorgraphics2d.util.DataUtils; import de.erichseifert.vectorgraphics2d.util.FlateEncodeStream; import de.erichseifert.vectorgraphics2d.util.FormattingWriter; import de.erichseifert.vectorgraphics2d.util.GraphicsUtils; import de.erichseifert.vectorgraphics2d.util.ImageDataStream; import de.erichseifert.vectorgraphics2d.util.ImageDataStream.Interleaving; import de.erichseifert.vectorgraphics2d.util.PageSize; /** * Represents a {@code Document} in the Portable Document Format (PDF). */ // TODO Support for different image formats (binary, grayscale, etc.) class PDFDocument extends SizedDocument { private static final String CHARSET = "ISO-8859-1"; private static final String HEADER = "%PDF-1.4"; private static final String FOOTER = "%%EOF"; private static final String EOL = "\n"; /** Constant to convert values from millimeters to PostScript®/PDF units (1/72th inch). */ private static final double MM_IN_UNITS = 72.0/25.4; /** Mapping of stroke endcap values from Java to PDF. */ private static final Map STROKE_ENDCAPS = DataUtils.map( new Integer[] { BasicStroke.CAP_BUTT, BasicStroke.CAP_ROUND, BasicStroke.CAP_SQUARE }, new Integer[] { 0, 1, 2 } ); /** Mapping of line join values for path drawing from Java to PDF. */ private static final Map STROKE_LINEJOIN = DataUtils.map( new Integer[] { BasicStroke.JOIN_MITER, BasicStroke.JOIN_ROUND, BasicStroke.JOIN_BEVEL }, new Integer[] { 0, 1, 2 } ); private final List objects; /** Cross-reference table ("xref"). */ private final Map crossReferences; private final Stream contents; private Resources resources; private final Map images; private final Stack states; private boolean transformed; public PDFDocument(CommandSequence commands, PageSize pageSize, boolean compressed) { super(pageSize, compressed); states = new Stack<>(); states.push(new GraphicsState()); objects = new LinkedList<>(); crossReferences = new HashMap<>(); images = new HashMap<>(); contents = initPage(); for (Command command : commands) { try { byte[] pdfStatement = toBytes(command); contents.write(pdfStatement); contents.write(EOL.getBytes(CHARSET)); } catch (IOException e) { throw new RuntimeException(e); } } close(); } private GraphicsState getCurrentState() { return states.peek(); } /** * Initializes the document and returns a {@code Stream} representing the contents. * @return {@code Stream} to which the contents are written. */ private Stream initPage() { DefaultPDFObject catalog = addCatalog(); List pagesKids = new LinkedList<>(); PDFObject pageTree = addPageTree(catalog, pagesKids); // Page DefaultPDFObject page = addPage(pageTree); pagesKids.add(page); // Contents Stream.Filter[] filters = isCompressed() ? new Stream.Filter[] {Stream.Filter.FLATE} : new Stream.Filter[0]; Stream contents = new Stream(filters); objects.add(contents); page.dict.put("Contents", contents); // Initial content try { FormattingWriter string = new FormattingWriter(contents, CHARSET, EOL); string.writeln("q"); string.writeln(getOutput(getCurrentState().getColor())); string.write(MM_IN_UNITS).write(" 0 0 ").write(-MM_IN_UNITS) .write(" 0 ").write(getPageSize().getHeight()*MM_IN_UNITS) .writeln(" cm"); } catch (IOException e) { throw new RuntimeException(e); } // Resources resources = new Resources(); objects.add(resources); page.dict.put("Resources", resources); // Create initial font Font font = getCurrentState().getFont(); String fontResourceId = resources.getId(font); float fontSize = font.getSize2D(); setFont(fontResourceId, fontSize, contents); return contents; } private void setFont(String fontId, float fontSize, Stream contents) { try { FormattingWriter string = new FormattingWriter(contents, CHARSET, EOL); string.write("/").write(fontId).write(" ").write(fontSize).writeln(" Tf"); } catch (IOException e) { throw new RuntimeException(e); } } private DefaultPDFObject addObject(Map dict, Payload payload) { DefaultPDFObject object = new DefaultPDFObject(dict, payload, true); objects.add(object); return object; } private DefaultPDFObject addCatalog() { Map dict = DataUtils.map( new String[] {"Type"}, new Object[] {"Catalog"} ); return addDictionary(dict); } private PDFObject addPageTree(DefaultPDFObject catalog, List pages) { Map dict = DataUtils.map( new String[] {"Type", "Kids", "Count"}, new Object[] {"Pages", pages, 1} ); PDFObject pageTree = addDictionary(dict); catalog.dict.put("Pages", pageTree); return pageTree; } private DefaultPDFObject addPage(PDFObject pageTree) { double x = getPageSize().getX()*MM_IN_UNITS; double y = getPageSize().getY()*MM_IN_UNITS; double width = getPageSize().getWidth()*MM_IN_UNITS; double height = getPageSize().getHeight()*MM_IN_UNITS; Map dict = DataUtils.map( new String[] {"Type", "Parent", "MediaBox"}, new Object[] {"Page", pageTree, new double[] {x, y, width, height}} ); return addDictionary(dict); } private DefaultPDFObject addDictionary(Map dict) { DefaultPDFObject object = new DefaultPDFObject(dict, null, false); objects.add(object); return object; } private DefaultPDFObject addObject(Image image) { BufferedImage bufferedImage = GraphicsUtils.toBufferedImage(image); int width = bufferedImage.getWidth(); int height = bufferedImage.getHeight(); int bitsPerSample = DataUtils.max(bufferedImage.getSampleModel().getSampleSize()); int bands = bufferedImage.getSampleModel().getNumBands(); String colorSpaceName = (bands == 1) ? "DeviceGray" : "DeviceRGB"; Payload imagePayload = new Payload(); // Compression String[] imageFilters = {}; if (isCompressed()) { imagePayload.addFilter(FlateEncodeStream.class); imageFilters = new String[] {"FlateDecode"}; } InputStream imageDataStream = new ImageDataStream(bufferedImage, Interleaving.WITHOUT_ALPHA); try { DataUtils.transfer(imageDataStream, imagePayload, 1024); imagePayload.close(); } catch (IOException e) { // TODO Improve exception handling throw new RuntimeException(e); } int length = imagePayload.getBytes().length; Map imageDict = DataUtils.map( new String[] {"Type", "Subtype", "Width", "Height", "ColorSpace", "BitsPerComponent", "Length", "Filter"}, new Object[] {"XObject", "Image", width, height, colorSpaceName, bitsPerSample, length, imageFilters} ); DefaultPDFObject imageObject = addObject(imageDict, imagePayload); boolean hasAlpha = bufferedImage.getColorModel().hasAlpha(); if (hasAlpha) { BufferedImage mask = GraphicsUtils.getAlphaImage(bufferedImage); DefaultPDFObject maskObject = addObject(mask); boolean isBitmask = mask.getSampleModel().getSampleSize(0) == 1; if (isBitmask) { maskObject.dict.put("ImageMask", true); maskObject.dict.remove("ColorSpace"); imageObject.dict.put("Mask", maskObject); } else { imageObject.dict.put("SMask", maskObject); } } return imageObject; } public void writeTo(OutputStream out) throws IOException { FormattingWriter o = new FormattingWriter(out, CHARSET, EOL); o.writeln(HEADER); for (PDFObject obj : objects) { crossReferences.put(obj, o.tell()); byte[] objectString; if (obj instanceof Resources) { objectString = toBytes((Resources) obj); } else if (obj instanceof Stream) { objectString = toBytes((Stream) obj); } else { objectString = toBytes(obj); } o.writeln(objectString); o.flush(); } long xrefPos = o.tell(); o.writeln("xref"); o.write(0).write(" ").writeln(objects.size() + 1); o.writeln("%010d %05d f ", 0, 65535); for (PDFObject obj : objects) { o.writeln("%010d %05d n ", crossReferences.get(obj), 0); } o.flush(); o.writeln("trailer"); o.writeln(serialize(DataUtils.map( new String[] {"Size", "Root"}, new Object[] {objects.size() + 1, objects.get(0)} ))); o.writeln("startxref"); o.writeln(xrefPos); o.writeln(FOOTER); o.flush(); } private int getId(PDFObject object) { int index = objects.indexOf(object); if (index < 0) { throw new IllegalArgumentException("Object " + object + " is not part of this document."); } return index + 1; } /** * Returns the version of the specified object. * @param object {@code PDFObject} whose version should be determined. * @return Version number. */ private int getVersion(PDFObject object) { return 0; } private byte[] toBytes(Resources resources) { ByteArrayOutputStream out = new ByteArrayOutputStream(); try (FormattingWriter string = new FormattingWriter(out, CHARSET, EOL)) { string.write(getId(resources)).write(" ").write(getVersion(resources)).writeln(" obj"); string.writeln("<<"); if (!resources.getProcSet().isEmpty()) { string.write("/ProcSet ").writeln(serialize(resources.getProcSet())); } if (!resources.getFont().isEmpty()) { string.write("/Font ").writeln(serialize(resources.getFont())); } if (resources.dict.get("ExtGState") != null) { string.write("/ExtGState ").writeln(serialize(resources.dict.get("ExtGState"))); } if (resources.dict.get("XObject") != null) { string.write("/XObject ").writeln(serialize(resources.dict.get("XObject"))); } string.writeln(">>"); string.write("endobj"); return out.toByteArray(); } catch (IOException e) { return null; } } private byte[] toBytes(Stream stream) { ByteArrayOutputStream out = new ByteArrayOutputStream(); try (FormattingWriter string = new FormattingWriter(out, CHARSET, EOL)) { string.write(getId(stream)).write(" ").write(getVersion(stream)).writeln(" obj"); string.writeln(serialize(stream)); string.write("endobj"); return out.toByteArray(); } catch (IOException e) { return null; } } protected static byte[] serialize(Stream stream) { ByteArrayOutputStream out = new ByteArrayOutputStream(); try (FormattingWriter serialized = new FormattingWriter(out, CHARSET, EOL)) { serialized.writeln("<<"); serialized.write("/Length ").writeln(stream.getLength()); if (stream.getFilters().contains(Stream.Filter.FLATE)) { serialized.writeln("/Filter /FlateDecode"); } serialized.writeln(">>"); serialized.writeln("stream"); serialized.writeln(stream.getContent()); serialized.write("endstream"); return out.toByteArray(); } catch (IOException e) { return null; } } protected static byte[] serialize(TrueTypeFont font) { ByteArrayOutputStream out = new ByteArrayOutputStream(); try (FormattingWriter serialized = new FormattingWriter(out, CHARSET, EOL)) { serialized.writeln("<<"); serialized.write("/Type /").writeln(font.getType()); serialized.write("/Subtype /").writeln(font.getSubtype()); serialized.write("/Encoding /").writeln(font.getEncoding()); serialized.write("/BaseFont /").writeln(font.getBaseFont()); serialized.write(">>"); return out.toByteArray(); } catch (IOException e) { return null; } } public byte[] toBytes(PDFObject object) { DefaultPDFObject obj = (DefaultPDFObject) object; ByteArrayOutputStream out = new ByteArrayOutputStream(); try (FormattingWriter string = new FormattingWriter(out, CHARSET, EOL)) { string.write(getId(obj)).write(" ").write(getVersion(obj)).writeln(" obj"); if (!obj.dict.isEmpty()) { string.writeln(serialize(obj.dict)); } if (obj.payload != null && !obj.payload.isEmpty()) { if (obj.stream) { string.writeln("stream"); } string.writeln(obj.payload.getBytes()); if (obj.stream) { string.writeln("endstream"); } } string.write("endobj"); return out.toByteArray(); } catch (IOException e) { return null; } } private byte[] serialize(Object obj) { ByteArrayOutputStream out = new ByteArrayOutputStream(); try (FormattingWriter serialized = new FormattingWriter(out, CHARSET, EOL)) { if (obj instanceof String) { serialized.write("/").write(obj.toString()); } else if (obj instanceof float[]) { serialized.write(serialize(DataUtils.asList((float[]) obj))); } else if (obj instanceof double[]) { serialized.write(serialize(DataUtils.asList((double[]) obj))); } else if (obj instanceof Object[]) { serialized.write(serialize(Arrays.asList((Object[]) obj))); } else if (obj instanceof List) { List list = (List) obj; serialized.write("["); int i = 0; for (Object elem : list) { if (i++ > 0) { serialized.write(" "); } serialized.write(serialize(elem)); } serialized.write("]"); } else if (obj instanceof Map) { Map dict = (Map) obj; serialized.writeln("<<"); for (Map.Entry entry : dict.entrySet()) { String key = entry.getKey().toString(); Object value = entry.getValue(); serialized.write(serialize(key)).write(" ").writeln(serialize(value)); } serialized.write(">>"); } else if (obj instanceof TrueTypeFont) { serialized.write(serialize((TrueTypeFont) obj)); } else if (obj instanceof PDFObject) { PDFObject pdfObj = (PDFObject) obj; serialized.write(getId(pdfObj)).write(" ").write(getVersion(pdfObj)).write(" R"); } else { serialized.write(DataUtils.format(obj)); } return out.toByteArray(); } catch (IOException e) { return null; } } private byte[] toBytes(Command command) { byte[] s = {}; if (command instanceof Group) { Group c = (Group) command; applyStateCommands(c.getValue()); s = getOutput(getCurrentState(), resources, !transformed); transformed = true; } else if (command instanceof DrawShapeCommand) { DrawShapeCommand c = (DrawShapeCommand) command; try (ByteArrayOutputStream ba = new ByteArrayOutputStream()) { ba.write(getOutput(c.getValue())); ba.write(serialize(" S")); s = ba.toByteArray(); } catch (IOException e) { throw new IllegalStateException(e); } } else if (command instanceof FillShapeCommand) { FillShapeCommand c = (FillShapeCommand) command; try (ByteArrayOutputStream ba = new ByteArrayOutputStream()) { ba.write(getOutput(c.getValue())); ba.write(serialize(" f")); s = ba.toByteArray(); } catch (IOException e) { throw new IllegalStateException(e); } } else if (command instanceof DrawStringCommand) { DrawStringCommand c = (DrawStringCommand) command; s = getOutput(c.getValue(), c.getX(), c.getY()); } else if (command instanceof DrawImageCommand) { DrawImageCommand c = (DrawImageCommand) command; // Create object for image data Image image = c.getValue(); PDFObject imageObject = images.get(image.hashCode()); if (imageObject == null) { imageObject = addObject(image); images.put(image.hashCode(), imageObject); } s = getOutput(imageObject, c.getX(), c.getY(), c.getWidth(), c.getHeight(), resources); } return s; } private void applyStateCommands(List> commands) { for (Command command : commands) { if (command instanceof SetHintCommand) { SetHintCommand c = (SetHintCommand) command; getCurrentState().getHints().put(c.getKey(), c.getValue()); } else if (command instanceof SetBackgroundCommand) { SetBackgroundCommand c = (SetBackgroundCommand) command; getCurrentState().setBackground(c.getValue()); } else if (command instanceof SetColorCommand) { SetColorCommand c = (SetColorCommand) command; getCurrentState().setColor(c.getValue()); } else if (command instanceof SetPaintCommand) { SetPaintCommand c = (SetPaintCommand) command; getCurrentState().setPaint(c.getValue()); } else if (command instanceof SetStrokeCommand) { SetStrokeCommand c = (SetStrokeCommand) command; getCurrentState().setStroke(c.getValue()); } else if (command instanceof SetFontCommand) { SetFontCommand c = (SetFontCommand) command; getCurrentState().setFont(c.getValue()); } else if (command instanceof SetTransformCommand) { throw new UnsupportedOperationException("The PDF format has no means of setting the transformation matrix."); } else if (command instanceof AffineTransformCommand) { AffineTransformCommand c = (AffineTransformCommand) command; AffineTransform stateTransform = getCurrentState().getTransform(); AffineTransform transformToBeApplied = c.getValue(); stateTransform.concatenate(transformToBeApplied); getCurrentState().setTransform(stateTransform); } else if (command instanceof SetClipCommand) { SetClipCommand c = (SetClipCommand) command; getCurrentState().setClip(c.getValue()); } else if (command instanceof CreateCommand) { try { states.push((GraphicsState) getCurrentState().clone()); } catch (CloneNotSupportedException e) { e.printStackTrace(); } } else if (command instanceof DisposeCommand) { states.pop(); } } } private byte[] getOutput(Color color) { ByteArrayOutputStream out = new ByteArrayOutputStream(); try (FormattingWriter string = new FormattingWriter(out, CHARSET, EOL)) { if (color.getColorSpace().getType() == ColorSpace.TYPE_CMYK) { float[] cmyk = color.getComponents(null); byte[] c = serialize(cmyk[0]); byte[] m = serialize(cmyk[1]); byte[] y = serialize(cmyk[2]); byte[] k = serialize(cmyk[3]); string.write(c).write(" ").write(m).write(" ").write(y).write(" ").write(k).write(" k "); string.write(c).write(" ").write(m).write(" ").write(y).write(" ").write(k).write(" K"); } else { byte[] r = serialize(color.getRed()/255.0); byte[] g = serialize(color.getGreen()/255.0); byte[] b = serialize(color.getBlue()/255.0); string.write(r).write(" ").write(g).write(" ").write(b).write(" rg "); string.write(r).write(" ").write(g).write(" ").write(b).write(" RG"); } return out.toByteArray(); } catch (IOException e) { return null; } } private byte[] getOutput(Shape s) { ByteArrayOutputStream out = new ByteArrayOutputStream(); try (FormattingWriter string = new FormattingWriter(out, CHARSET, EOL)) { PathIterator segments = s.getPathIterator(null); double[] coordsCur = new double[6]; double[] pointPrev = new double[2]; for (int i = 0; !segments.isDone(); i++, segments.next()) { if (i > 0) { string.write(" "); } int segmentType = segments.currentSegment(coordsCur); switch (segmentType) { case PathIterator.SEG_MOVETO: string.write(serialize(coordsCur[0])).write(" ") .write(serialize(coordsCur[1])).write(" m"); pointPrev[0] = coordsCur[0]; pointPrev[1] = coordsCur[1]; break; case PathIterator.SEG_LINETO: string.write(serialize(coordsCur[0])).write(" ") .write(serialize(coordsCur[1])).write(" l"); pointPrev[0] = coordsCur[0]; pointPrev[1] = coordsCur[1]; break; case PathIterator.SEG_CUBICTO: string.write(serialize(coordsCur[0])).write(" ") .write(serialize(coordsCur[1])).write(" ") .write(serialize(coordsCur[2])).write(" ") .write(serialize(coordsCur[3])).write(" ") .write(serialize(coordsCur[4])).write(" ") .write(serialize(coordsCur[5])).write(" c"); pointPrev[0] = coordsCur[4]; pointPrev[1] = coordsCur[5]; break; case PathIterator.SEG_QUADTO: double x1 = pointPrev[0] + 2.0/3.0*(coordsCur[0] - pointPrev[0]); double y1 = pointPrev[1] + 2.0/3.0*(coordsCur[1] - pointPrev[1]); double x2 = coordsCur[0] + 1.0/3.0*(coordsCur[2] - coordsCur[0]); double y2 = coordsCur[1] + 1.0/3.0*(coordsCur[3] - coordsCur[1]); double x3 = coordsCur[2]; double y3 = coordsCur[3]; string.write(serialize(x1)).write(" ") .write(serialize(y1)).write(" ") .write(serialize(x2)).write(" ") .write(serialize(y2)).write(" ") .write(serialize(x3)).write(" ") .write(serialize(y3)).write(" c"); pointPrev[0] = x3; pointPrev[1] = y3; break; case PathIterator.SEG_CLOSE: string.write("h"); break; default: throw new IllegalStateException("Unknown path operation."); } } return out.toByteArray(); } catch (IOException e) { return null; } } private byte[] getOutput(GraphicsState state, Resources resources, boolean first) { ByteArrayOutputStream out = new ByteArrayOutputStream(); try (FormattingWriter string = new FormattingWriter(out, CHARSET, EOL)) { if (!first) { string.writeln("Q"); } string.writeln("q"); if (!state.getColor().equals(GraphicsState.DEFAULT_COLOR)) { if (state.getColor().getAlpha() != GraphicsState.DEFAULT_COLOR.getAlpha()) { double a = state.getColor().getAlpha()/255.0; String resourceId = resources.getId(a); string.write("/").write(resourceId).writeln(" gs"); } string.writeln(getOutput(state.getColor())); } if (!state.getTransform().equals(GraphicsState.DEFAULT_TRANSFORM)) { string.write(getOutput(state.getTransform())).writeln(" cm"); } if (!state.getStroke().equals(GraphicsState.DEFAULT_STROKE)) { string.writeln(getOutput(state.getStroke())); } if (state.getClip() != GraphicsState.DEFAULT_CLIP) { string.write(getOutput(state.getClip())).writeln(" W n"); } if (!state.getFont().equals(GraphicsState.DEFAULT_FONT)) { Font font = state.getFont(); String fontResourceId = resources.getId(font); float fontSize = font.getSize2D(); string.write("/").write(fontResourceId).write(" ") .write(fontSize).writeln(" Tf"); } return out.toByteArray(); } catch (IOException e) { return null; } } private byte[] getOutput(Stroke s) { if (!(s instanceof BasicStroke)) { throw new UnsupportedOperationException("Only BasicStroke objects are supported."); } ByteArrayOutputStream out = new ByteArrayOutputStream(); try (FormattingWriter string = new FormattingWriter(out, CHARSET, EOL)) { BasicStroke strokeDefault = (BasicStroke) GraphicsState.DEFAULT_STROKE; BasicStroke strokeNew = (BasicStroke) s; if (strokeNew.getLineWidth() != strokeDefault.getLineWidth()) { string.write(strokeNew.getLineWidth()).writeln(" w"); } if (strokeNew.getLineJoin() == BasicStroke.JOIN_MITER && strokeNew.getMiterLimit() != strokeDefault.getMiterLimit()) { string.write(strokeNew.getMiterLimit()).writeln(" M"); } if (strokeNew.getLineJoin() != strokeDefault.getLineJoin()) { string.write(STROKE_LINEJOIN.get(strokeNew.getLineJoin())).writeln(" j"); } if (strokeNew.getEndCap() != strokeDefault.getEndCap()) { string.write(STROKE_ENDCAPS.get(strokeNew.getEndCap())).writeln(" J"); } if (strokeNew.getDashArray() != strokeDefault.getDashArray()) { if (strokeNew.getDashArray() != null) { string.write(serialize(strokeNew.getDashArray())).write(" ") .write(strokeNew.getDashPhase()).writeln(" d"); } else { string.writeln(); string.writeln("[] 0 d"); } } return out.toByteArray(); } catch (IOException e) { return null; } } private static byte[] getOutput(AffineTransform transform) { double[] matrix = new double[6]; transform.getMatrix(matrix); try { return DataUtils.join(" ", matrix).getBytes(CHARSET); } catch (UnsupportedEncodingException e) { return null; } } private static byte[] getOutput(String str, double x, double y) { // Save current graphics state // Undo swapping of y axis // Render text // Restore previous graphics state ByteArrayOutputStream out = new ByteArrayOutputStream(); try (FormattingWriter string = new FormattingWriter(out, CHARSET, EOL)) { string.write("q 1 0 0 -1 ").write(x).write(" ").write(y) .write(" cm BT ").write(getOutput(str)).write(" Tj ET Q"); return out.toByteArray(); } catch (IOException e) { return null; } } private static byte[] getOutput(String str) { // Escape string str = str.replaceAll("\\\\", "\\\\\\\\") .replaceAll("\t", "\\\\t") .replaceAll("\b", "\\\\b") .replaceAll("\f", "\\\\f") .replaceAll("\\(", "\\\\(") .replaceAll("\\)", "\\\\)") .replaceAll("[\r\n]", ""); ByteArrayOutputStream out = new ByteArrayOutputStream(); try (FormattingWriter string = new FormattingWriter(out, CHARSET, EOL)) { string.write("(").write(str).write(")"); return out.toByteArray(); } catch (IOException e) { return null; } } private static byte[] getOutput(PDFObject image, double x, double y, double width, double height, Resources resources) { // Query image resource id String resourceId = resources.getId(image); // Save graphics state // Move image to correct position and scale it to (width, height) // Swap y axis // Draw image // Restore old graphics state ByteArrayOutputStream out = new ByteArrayOutputStream(); try (FormattingWriter string = new FormattingWriter(out, CHARSET, EOL)) { string.write("q ").write(width).write(" 0 0 ").write(height) .write(" ").write(x).write(" ").write(y) .write(" cm 1 0 0 -1 0 1 cm /").write(resourceId) .write(" Do Q"); return out.toByteArray(); } catch (IOException e) { return null; } } public void close() { try { String footer = "Q"; if (transformed) { footer += EOL + "Q"; } contents.write(footer.getBytes(CHARSET)); contents.close(); } catch (IOException e) { throw new RuntimeException(e); } } } vectorgraphics2d-0.13/src/main/java/de/erichseifert/vectorgraphics2d/pdf/PDFObject.java000066400000000000000000000017371347274514600310600ustar00rootroot00000000000000/* * VectorGraphics2D: Vector export for Java(R) Graphics2D * * (C) Copyright 2010-2017 Erich Seifert , * Michael Seifert * * This file is part of VectorGraphics2D. * * VectorGraphics2D is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * VectorGraphics2D 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with VectorGraphics2D. If not, see . */ package de.erichseifert.vectorgraphics2d.pdf; public interface PDFObject { } vectorgraphics2d-0.13/src/main/java/de/erichseifert/vectorgraphics2d/pdf/PDFProcessor.java000066400000000000000000000053441347274514600316270ustar00rootroot00000000000000/* * VectorGraphics2D: Vector export for Java(R) Graphics2D * * (C) Copyright 2010-2017 Erich Seifert , * Michael Seifert * * This file is part of VectorGraphics2D. * * VectorGraphics2D is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * VectorGraphics2D 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with VectorGraphics2D. If not, see . */ package de.erichseifert.vectorgraphics2d.pdf; import de.erichseifert.vectorgraphics2d.Document; import de.erichseifert.vectorgraphics2d.Processor; import de.erichseifert.vectorgraphics2d.intermediate.CommandSequence; import de.erichseifert.vectorgraphics2d.intermediate.filters.AbsoluteToRelativeTransformsFilter; import de.erichseifert.vectorgraphics2d.intermediate.filters.FillPaintedShapeAsImageFilter; import de.erichseifert.vectorgraphics2d.intermediate.filters.StateChangeGroupingFilter; import de.erichseifert.vectorgraphics2d.util.PageSize; /** * {@code Processor} implementation that translates {@link CommandSequence}s to * a {@code Document} in the Portable Document Format (PDF). */ public class PDFProcessor implements Processor { private final boolean compressed; /** * Initializes a {@code PDFProcessor} for compressed PDF documents. */ public PDFProcessor() { this(true); } /** * Initializes a {@code PDFProcessor} with the specified compression settings. * @param compressed {@code true} if compression is enabled, {@code false} otherwise. */ public PDFProcessor(boolean compressed) { this.compressed = compressed; } /** * Returns whether the current PDF document is compressed. * @return {@code true} if the document is compressed, {@code false} otherwise. */ public boolean isCompressed() { return compressed; } @Override public Document getDocument(CommandSequence commands, PageSize pageSize) { AbsoluteToRelativeTransformsFilter absoluteToRelativeTransformsFilter = new AbsoluteToRelativeTransformsFilter(commands); FillPaintedShapeAsImageFilter paintedShapeAsImageFilter = new FillPaintedShapeAsImageFilter(absoluteToRelativeTransformsFilter); CommandSequence filtered = new StateChangeGroupingFilter(paintedShapeAsImageFilter); return new PDFDocument(filtered, pageSize, isCompressed()); } } vectorgraphics2d-0.13/src/main/java/de/erichseifert/vectorgraphics2d/pdf/Page.java000066400000000000000000000047221347274514600301710ustar00rootroot00000000000000/* * VectorGraphics2D: Vector export for Java(R) Graphics2D * * (C) Copyright 2010-2017 Erich Seifert , * Michael Seifert * * This file is part of VectorGraphics2D. * * VectorGraphics2D is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * VectorGraphics2D 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with VectorGraphics2D. If not, see . */ package de.erichseifert.vectorgraphics2d.pdf; import java.awt.geom.Rectangle2D; /** * Represents a page of a PDF document. */ class Page implements PDFObject { private final Resources resources; private final Rectangle2D mediaBox; private final DefaultPDFObject contents; private PageTreeNode parent; /** * Initializes a {@code Page} with the specified parent node, MediaBox and contents. * @param resources Page resources * @param mediaBox Boundaries of the page. * @param contents Contents of the page. */ public Page(Resources resources, Rectangle2D mediaBox, DefaultPDFObject contents) { this.resources = resources; this.mediaBox = mediaBox; this.contents = contents; } /** * Returns the type of this object. * The return value is always {@literal Page}. * @return The String {@literal Page}. */ public String getType() { return "Page"; } public Rectangle2D getMediaBox() { return mediaBox; } /** * Returns the immediate parent of this {@code Page}. * @return Parent node. */ public PageTreeNode getParent() { return parent; } /** * Sets the parent of this {@code Page} to the specified node. * @param parent Immediate parent. */ protected void setParent(PageTreeNode parent) { this.parent = parent; } /** * Returns the {@code Resources} object associated with this {@code Page}. * @return Page resources. */ public Resources getResources() { return resources; } /** * Returns the contents of this {@code Page}. * @return Page contents. */ public DefaultPDFObject getContents() { return contents; } } vectorgraphics2d-0.13/src/main/java/de/erichseifert/vectorgraphics2d/pdf/PageTreeNode.java000066400000000000000000000047261347274514600316230ustar00rootroot00000000000000/* * VectorGraphics2D: Vector export for Java(R) Graphics2D * * (C) Copyright 2010-2017 Erich Seifert , * Michael Seifert * * This file is part of VectorGraphics2D. * * VectorGraphics2D is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * VectorGraphics2D 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with VectorGraphics2D. If not, see . */ package de.erichseifert.vectorgraphics2d.pdf; import java.util.Collections; import java.util.LinkedList; import java.util.List; /** * Represents an intermediate node in the page tree of a PDF document. */ class PageTreeNode implements PDFObject { private final PageTreeNode parent; private final List children; /** * Initializes a {@code PageTreeNode} with the specified parent node. * @param parent Parent node or {@code null} to create a root node. */ public PageTreeNode(PageTreeNode parent) { this.parent = parent; this.children = new LinkedList<>(); } /** * Returns the type of this object. * The return value is always {@literal Pages}. * @return The String {@literal Pages}. */ public String getType() { return "Pages"; } /** * Returns the parent of this node. * If this node is a root node, the method returns {@code null}. * @return Parent node or {@code null}, if this is a root node. */ public PageTreeNode getParent() { return parent; } /** * Adds the specified {@code Page} to the node's children. * @param page {@code Page} to be added. */ public void add(Page page) { page.setParent(this); children.add(page); } /** * Returns all {@code Page} objects that are immediate children of this node. * @return List of child pages. */ public List getKids() { return Collections.unmodifiableList(children); } /** * Returns the total number of {@code Page} objects in this subtree. * @return Number of pages that are direct or indirect children. */ public int getCount() { return children.size(); } } vectorgraphics2d-0.13/src/main/java/de/erichseifert/vectorgraphics2d/pdf/Payload.java000066400000000000000000000042561347274514600307100ustar00rootroot00000000000000/* * VectorGraphics2D: Vector export for Java(R) Graphics2D * * (C) Copyright 2010-2017 Erich Seifert , * Michael Seifert * * This file is part of VectorGraphics2D. * * VectorGraphics2D is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * VectorGraphics2D 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with VectorGraphics2D. If not, see . */ package de.erichseifert.vectorgraphics2d.pdf; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.OutputStream; import java.lang.reflect.InvocationTargetException; import de.erichseifert.vectorgraphics2d.util.FlateEncodeStream; class Payload extends OutputStream { private final ByteArrayOutputStream byteStream; private OutputStream filteredStream; private boolean empty; public Payload() { byteStream = new ByteArrayOutputStream(); filteredStream = byteStream; empty = true; } public byte[] getBytes() { return byteStream.toByteArray(); } @Override public void write(int b) throws IOException { filteredStream.write(b); empty = false; } public boolean isEmpty() { return empty; } @Override public void close() throws IOException { super.close(); filteredStream.close(); } public void addFilter(Class filterClass) { if (!empty) { throw new IllegalStateException("Cannot add filter after writing to payload."); } try { filteredStream = filterClass.getConstructor(OutputStream.class) .newInstance(filteredStream); } catch (InstantiationException | NoSuchMethodException | InvocationTargetException | IllegalAccessException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } vectorgraphics2d-0.13/src/main/java/de/erichseifert/vectorgraphics2d/pdf/Resources.java000066400000000000000000000107721347274514600312710ustar00rootroot00000000000000/* * VectorGraphics2D: Vector export for Java(R) Graphics2D * * (C) Copyright 2010-2017 Erich Seifert , * Michael Seifert * * This file is part of VectorGraphics2D. * * VectorGraphics2D is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * VectorGraphics2D 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with VectorGraphics2D. If not, see . */ package de.erichseifert.vectorgraphics2d.pdf; import java.awt.Font; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.concurrent.atomic.AtomicInteger; import de.erichseifert.vectorgraphics2d.util.DataUtils; import de.erichseifert.vectorgraphics2d.util.GraphicsUtils; class Resources extends DefaultPDFObject { private static final String KEY_TRANSPARENCY = "ExtGState"; private static final String KEY_IMAGE = "XObject"; private static final String[] VALUE_PROC_SET = {"PDF", "Text", "ImageB", "ImageC", "ImageI"}; private static final String PREFIX_FONT = "Fnt"; private static final String PREFIX_IMAGE = "Img"; private static final String PREFIX_TRANSPARENCY = "Trp"; private final List procSet; private final Map fontsByFontId; private final Map fontIDsByFont; private final Map images; private final Map transparencies; private final AtomicInteger currentFontId = new AtomicInteger(); private final AtomicInteger currentImageId = new AtomicInteger(); private final AtomicInteger currentTransparencyId = new AtomicInteger(); public Resources() { super(null, null, false); procSet = new LinkedList<>(); fontsByFontId = new HashMap<>(); fontIDsByFont = new HashMap<>(); images = new HashMap<>(); transparencies = new HashMap<>(); setProcSet(VALUE_PROC_SET); } private String getResourceId(Map resources, T resource, String idPrefix, AtomicInteger idCounter) { String id = resources.get(resource); if (id == null) { id = String.format("%s%d", idPrefix, idCounter.getAndIncrement()); resources.put(resource, id); } return id; } public String getId(Font font) { font = GraphicsUtils.getPhysicalFont(font); String resourceId = getResourceId(fontIDsByFont, font, PREFIX_FONT, currentFontId); String baseFontName = font.getPSName(); // TODO: Determine font encoding (e.g. MacRomanEncoding, MacExpertEncoding, WinAnsiEncoding) String fontEncoding = "WinAnsiEncoding"; TrueTypeFont pdfFont = new TrueTypeFont(fontEncoding, baseFontName); fontsByFontId.put(resourceId, pdfFont); return resourceId; } public String getId(PDFObject image) { // Make sure a dictionary entry for images exists Map dictEntry = (Map) dict.get(KEY_IMAGE); if (dictEntry == null) { dictEntry = new LinkedHashMap<>(); dict.put(KEY_IMAGE, dictEntry); } String resourceId = getResourceId(images, image, PREFIX_IMAGE, currentImageId); dictEntry.put(resourceId, image); return resourceId; } public String getId(Double transparency) { // Make sure a dictionary entry for transparency levels exists Map> dictEntry = (Map>) dict.get(KEY_TRANSPARENCY); if (dictEntry == null) { dictEntry = new LinkedHashMap<>(); dict.put(KEY_TRANSPARENCY, dictEntry); } String resourceId = getResourceId(transparencies, transparency, PREFIX_TRANSPARENCY, currentTransparencyId); dictEntry.put(resourceId, DataUtils.map( new String[] {"Type", "ca", "CA"}, new Object[] {"ExtGState", transparency, transparency} )); return resourceId; } public void setProcSet(String... procedureNames) { procSet.clear(); procSet.addAll(Arrays.asList(procedureNames)); } public List getProcSet() { return Collections.unmodifiableList(procSet); } public Map getFont() { return Collections.unmodifiableMap(fontsByFontId); } } vectorgraphics2d-0.13/src/main/java/de/erichseifert/vectorgraphics2d/pdf/Stream.java000066400000000000000000000070771347274514600305560ustar00rootroot00000000000000/* * VectorGraphics2D: Vector export for Java(R) Graphics2D * * (C) Copyright 2010-2017 Erich Seifert , * Michael Seifert * * This file is part of VectorGraphics2D. * * VectorGraphics2D is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * VectorGraphics2D 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with VectorGraphics2D. If not, see . */ package de.erichseifert.vectorgraphics2d.pdf; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.OutputStream; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.zip.DeflaterOutputStream; /** * Represents a stream object in the sense of the PDF specification. * The {@code Stream} has a defined length. */ class Stream extends OutputStream implements PDFObject { public enum Filter { FLATE } private final ByteArrayOutputStream data; private final List filters; private OutputStream filteredData; private boolean closed; /** * Initializes a new {@code Stream}. */ public Stream(Filter... filters) { data = new ByteArrayOutputStream(); this.filters = new ArrayList<>(filters.length); this.filters.addAll(Arrays.asList(filters)); filteredData = data; for (Filter filter : filters) { if (filter == Filter.FLATE) { filteredData = new DeflaterOutputStream(filteredData); } } } @Override public void write(int b) throws IOException { if (isClosed()) { throw new IOException("Unable to write to closed stream."); } try { this.filteredData.write(b); } catch (IOException e) { throw new RuntimeException("Unable to write to the output stream", e); } } /** * Appends the specified byte array to the {@code Stream}. * @param data Data to be appended. */ public void write(byte[] data) throws IOException { if (isClosed()) { throw new IOException("Unable to write to closed stream."); } try { this.filteredData.write(data); } catch (IOException e) { throw new RuntimeException("Unable to write to the output stream", e); } } /** * Returns the size of the stream contents in bytes. * @return Number of bytes. * @throws IllegalStateException if the stream is still open. */ public int getLength() { if (!isClosed()) { throw new IllegalStateException("Unable to determine the length of an open Stream. Close the stream first."); } return data.size(); } /** * Returns the content that has been written to this {@code Stream}. * @return Stream content. * @throws IllegalStateException if the stream is still open. */ public byte[] getContent() { if (!isClosed()) { throw new IllegalStateException("Unable to retrieve the content of an open Stream. Close the stream first."); } return data.toByteArray(); } private boolean isClosed() { return closed; } @Override public void close() { closed = true; try { filteredData.close(); } catch (IOException e) { throw new RuntimeException(e); } } public List getFilters() { return Collections.unmodifiableList(filters); } } vectorgraphics2d-0.13/src/main/java/de/erichseifert/vectorgraphics2d/pdf/TrueTypeFont.java000066400000000000000000000037221347274514600317240ustar00rootroot00000000000000/* * VectorGraphics2D: Vector export for Java(R) Graphics2D * * (C) Copyright 2010-2017 Erich Seifert , * Michael Seifert * * This file is part of VectorGraphics2D. * * VectorGraphics2D is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * VectorGraphics2D 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with VectorGraphics2D. If not, see . */ package de.erichseifert.vectorgraphics2d.pdf; /** * Represents a TrueType font in the sense of the PDF specification. */ class TrueTypeFont implements PDFObject { private final String encoding; private final String baseFont; /** * Creates a {@code TrueTypeFont} with the specified encoding and base font. * @param encoding Used encoding. * @param baseFont Base font name. */ public TrueTypeFont(String encoding, String baseFont) { this.encoding = encoding; this.baseFont = baseFont; } /** * Returns the encoding of this font. * @return Encoding. */ public String getEncoding() { return encoding; } /** * Returns the type of this object. * Always returns "Font". * @return The String "Font". */ public String getType() { return "Font"; } /** * Returns the subtype of this object. * Always returns "TrueType". * @return The String "TrueType". */ public String getSubtype() { return "TrueType"; } /** * Returns the name of the base font. * @return Base font name. */ public String getBaseFont() { return baseFont; } } vectorgraphics2d-0.13/src/main/java/de/erichseifert/vectorgraphics2d/pdf/package-info.java000077500000000000000000000021241347274514600316360ustar00rootroot00000000000000/* * VectorGraphics2D: Vector export for Java(R) Graphics2D * * (C) Copyright 2010-2017 Erich Seifert , * Michael Seifert * * This file is part of VectorGraphics2D. * * VectorGraphics2D is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * VectorGraphics2D 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with VectorGraphics2D. If not, see . */ /** * Implementation of a processor to convert VectorGraphics2D intermediate * language commands to the Portable Document Format (PDF). */ package de.erichseifert.vectorgraphics2d.pdf; vectorgraphics2d-0.13/src/main/java/de/erichseifert/vectorgraphics2d/svg/000077500000000000000000000000001347274514600264735ustar00rootroot00000000000000vectorgraphics2d-0.13/src/main/java/de/erichseifert/vectorgraphics2d/svg/SVGDocument.java000066400000000000000000000530601347274514600315000ustar00rootroot00000000000000/* * VectorGraphics2D: Vector export for Java(R) Graphics2D * * (C) Copyright 2010-2017 Erich Seifert , * Michael Seifert * * This file is part of VectorGraphics2D. * * VectorGraphics2D is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * VectorGraphics2D 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with VectorGraphics2D. If not, see . */ package de.erichseifert.vectorgraphics2d.svg; import java.awt.BasicStroke; import java.awt.Color; import java.awt.Font; import java.awt.Image; import java.awt.Shape; import java.awt.Stroke; import java.awt.color.ColorSpace; import java.awt.geom.AffineTransform; import java.awt.geom.Ellipse2D; import java.awt.geom.Line2D; import java.awt.geom.PathIterator; import java.awt.geom.Rectangle2D; import java.awt.geom.RoundRectangle2D; import java.awt.image.BufferedImage; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.OutputStream; import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Stack; import javax.imageio.ImageIO; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.OutputKeys; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import de.erichseifert.vectorgraphics2d.GraphicsState; import de.erichseifert.vectorgraphics2d.SizedDocument; import de.erichseifert.vectorgraphics2d.VectorHints; import de.erichseifert.vectorgraphics2d.intermediate.CommandSequence; import de.erichseifert.vectorgraphics2d.intermediate.commands.AffineTransformCommand; import de.erichseifert.vectorgraphics2d.intermediate.commands.Command; import de.erichseifert.vectorgraphics2d.intermediate.commands.CreateCommand; import de.erichseifert.vectorgraphics2d.intermediate.commands.DisposeCommand; import de.erichseifert.vectorgraphics2d.intermediate.commands.DrawImageCommand; import de.erichseifert.vectorgraphics2d.intermediate.commands.DrawShapeCommand; import de.erichseifert.vectorgraphics2d.intermediate.commands.DrawStringCommand; import de.erichseifert.vectorgraphics2d.intermediate.commands.FillShapeCommand; import de.erichseifert.vectorgraphics2d.intermediate.commands.Group; import de.erichseifert.vectorgraphics2d.intermediate.commands.SetBackgroundCommand; import de.erichseifert.vectorgraphics2d.intermediate.commands.SetClipCommand; import de.erichseifert.vectorgraphics2d.intermediate.commands.SetColorCommand; import de.erichseifert.vectorgraphics2d.intermediate.commands.SetCompositeCommand; import de.erichseifert.vectorgraphics2d.intermediate.commands.SetFontCommand; import de.erichseifert.vectorgraphics2d.intermediate.commands.SetHintCommand; import de.erichseifert.vectorgraphics2d.intermediate.commands.SetPaintCommand; import de.erichseifert.vectorgraphics2d.intermediate.commands.SetStrokeCommand; import de.erichseifert.vectorgraphics2d.intermediate.commands.SetTransformCommand; import de.erichseifert.vectorgraphics2d.util.Base64EncodeStream; import de.erichseifert.vectorgraphics2d.util.DataUtils; import de.erichseifert.vectorgraphics2d.util.GraphicsUtils; import de.erichseifert.vectorgraphics2d.util.PageSize; import org.w3c.dom.DOMImplementation; import org.w3c.dom.Document; import org.w3c.dom.DocumentType; import org.w3c.dom.Element; /** * Represents a {@code Document} in the Scaled Vector Graphics (SVG) * format. */ // TODO Implement composite support for SVG (filters?) // TODO Implement paint support for SVG class SVGDocument extends SizedDocument { private static final String SVG_DOCTYPE_QNAME = "svg"; private static final String SVG_DOCTYPE_PUBLIC_ID = "-//W3C//DTD SVG 1.1//EN"; private static final String SVG_DOCTYPE_SYSTEM_ID = "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd"; private static final String SVG_NAMESPACE_URI = "http://www.w3.org/2000/svg"; private static final String XLINK_NAMESPACE = "xlink"; private static final String XLINK_NAMESPACE_URI = "http://www.w3.org/1999/xlink"; private static final String PREFIX_CLIP = "clip"; // TODO Resolution settings private static final String CHARSET = "UTF-8"; private final Stack states; private final Document doc; private final Element root; private Element group; private boolean groupAdded; private Element defs; private final Map clippingPathElements; /** Mapping of stroke endcap values from Java to SVG. */ private static final Map STROKE_ENDCAPS = DataUtils.map( new Integer[] { BasicStroke.CAP_BUTT, BasicStroke.CAP_ROUND, BasicStroke.CAP_SQUARE }, new String[] { "butt", "round", "square" } ); /** Mapping of line join values for path drawing from Java to SVG. */ private static final Map STROKE_LINEJOIN = DataUtils.map( new Integer[] { BasicStroke.JOIN_MITER, BasicStroke.JOIN_ROUND, BasicStroke.JOIN_BEVEL }, new String[] { "miter", "round", "bevel" } ); public SVGDocument(CommandSequence commands, PageSize pageSize) { super(pageSize, true); states = new Stack<>(); states.push(new GraphicsState()); clippingPathElements = new HashMap<>(); // Prepare DOM DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); docFactory.setValidating(false); DocumentBuilder docBuilder; try { docBuilder = docFactory.newDocumentBuilder(); } catch (ParserConfigurationException e) { throw new IllegalStateException("Could not create XML builder."); } // Create XML document with DOCTYPE DOMImplementation domImpl = docBuilder.getDOMImplementation(); DocumentType docType = domImpl.createDocumentType(SVG_DOCTYPE_QNAME, SVG_DOCTYPE_PUBLIC_ID, SVG_DOCTYPE_SYSTEM_ID); doc = domImpl.createDocument(SVG_NAMESPACE_URI, "svg", docType); // FIXME: Some XML parsers don't support setting standalone to "false" try { doc.setXmlStandalone(false); } catch (AbstractMethodError e) { System.err.println("Your XML parser does not support standalone XML documents."); } root = doc.getDocumentElement(); initRoot(); group = root; for (Command command : commands) { handle(command); } } private GraphicsState getCurrentState() { return states.peek(); } private void initRoot() { double x = getPageSize().getX(); double y = getPageSize().getY(); double width = getPageSize().getWidth(); double height = getPageSize().getHeight(); // Add svg element root.setAttribute("xmlns:" + XLINK_NAMESPACE, XLINK_NAMESPACE_URI); root.setAttribute("version", "1.1"); root.setAttribute("x", DataUtils.format(x) + "px"); root.setAttribute("y", DataUtils.format(y) + "px"); root.setAttribute("width", DataUtils.format(width) + "px"); root.setAttribute("height", DataUtils.format(height) + "px"); root.setAttribute("viewBox", DataUtils.join(" ", new double[] {x, y, width, height})); } public void writeTo(OutputStream out) throws IOException { TransformerFactory transformerFactory = TransformerFactory.newInstance(); try { Transformer transformer = transformerFactory.newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty(OutputKeys.STANDALONE, "no"); transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2"); transformer.setOutputProperty(OutputKeys.ENCODING, CHARSET); transformer.setOutputProperty(OutputKeys.DOCTYPE_PUBLIC, doc.getDoctype().getPublicId()); transformer.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, doc.getDoctype().getSystemId()); transformer.transform(new DOMSource(doc), new StreamResult(out)); } catch (TransformerException e) { throw new IOException(e.getMessage()); } } @Override public String toString() { ByteArrayOutputStream out = new ByteArrayOutputStream(); try { writeTo(out); return out.toString(CHARSET); } catch (IOException e) { return ""; } } private void newGroup() { group = doc.createElement("g"); groupAdded = false; Shape clip = getCurrentState().getClip(); if (clip != GraphicsState.DEFAULT_CLIP) { Element clipElem = getClipElement(clip); String ref = "url(#" + clipElem.getAttribute("id") + ")"; group.setAttribute("clip-path", ref); } AffineTransform tx = getCurrentState().getTransform(); if (!GraphicsState.DEFAULT_TRANSFORM.equals(tx)) { group.setAttribute("transform", getOutput(tx)); } } private Element getClipElement(Shape clip) { // Look for existing entries Element path = clippingPathElements.get(clip.hashCode()); if (path != null) { return path; } // Make sure exists if (defs == null) { defs = doc.createElement("defs"); root.insertBefore(defs, root.getFirstChild()); } // Store clipping path in without styling information path = doc.createElement("clipPath"); path.setAttribute("id", PREFIX_CLIP + clip.hashCode()); Element shape = getElement(clip); shape.removeAttribute("style"); path.appendChild(shape); defs.appendChild(path); // Register path clippingPathElements.put(clip.hashCode(), path); return path; } private void addToGroup(Element e) { group.appendChild(e); if (!groupAdded && group != root) { root.appendChild(group); groupAdded = true; } } public void handle(Command command) { if (command instanceof Group) { Group c = (Group) command; applyStateCommands(c.getValue()); if (containsGroupCommand(c.getValue())) { newGroup(); } } else if (command instanceof DrawImageCommand) { DrawImageCommand c = (DrawImageCommand) command; Element e = getElement(c.getValue(), c.getX(), c.getY(), c.getWidth(), c.getHeight()); addToGroup(e); } else if (command instanceof DrawShapeCommand) { DrawShapeCommand c = (DrawShapeCommand) command; Element e = getElement(c.getValue()); e.setAttribute("style", getStyle(false)); addToGroup(e); } else if (command instanceof DrawStringCommand) { DrawStringCommand c = (DrawStringCommand) command; Element e = getElement(c.getValue(), c.getX(), c.getY()); e.setAttribute("style", getStyle(getCurrentState().getFont())); addToGroup(e); } else if (command instanceof FillShapeCommand) { FillShapeCommand c = (FillShapeCommand) command; Element e = getElement(c.getValue()); e.setAttribute("style", getStyle(true)); addToGroup(e); } } private void applyStateCommands(List> commands) { for (Command command : commands) { GraphicsState state = getCurrentState(); if (command instanceof SetBackgroundCommand) { SetBackgroundCommand c = (SetBackgroundCommand) command; state.setBackground(c.getValue()); } else if (command instanceof SetClipCommand) { SetClipCommand c = (SetClipCommand) command; state.setClip(c.getValue()); } else if (command instanceof SetColorCommand) { SetColorCommand c = (SetColorCommand) command; state.setColor(c.getValue()); } else if (command instanceof SetCompositeCommand) { SetCompositeCommand c = (SetCompositeCommand) command; state.setComposite(c.getValue()); } else if (command instanceof SetFontCommand) { SetFontCommand c = (SetFontCommand) command; state.setFont(c.getValue()); } else if (command instanceof SetPaintCommand) { SetPaintCommand c = (SetPaintCommand) command; state.setPaint(c.getValue()); } else if (command instanceof SetStrokeCommand) { SetStrokeCommand c = (SetStrokeCommand) command; state.setStroke(c.getValue()); } else if (command instanceof SetTransformCommand) { SetTransformCommand c = (SetTransformCommand) command; state.setTransform(c.getValue()); } else if (command instanceof AffineTransformCommand) { AffineTransformCommand c = (AffineTransformCommand) command; AffineTransform stateTransform = state.getTransform(); AffineTransform transformToBeApplied = c.getValue(); stateTransform.concatenate(transformToBeApplied); state.setTransform(stateTransform); } else if (command instanceof SetHintCommand) { SetHintCommand c = (SetHintCommand) command; state.getHints().put(c.getKey(), c.getValue()); } else if (command instanceof CreateCommand) { try { states.push((GraphicsState) getCurrentState().clone()); } catch (CloneNotSupportedException e) { e.printStackTrace(); } } else if (command instanceof DisposeCommand) { states.pop(); } } } private boolean containsGroupCommand(List> commands) { for (Command command : commands) { if ((command instanceof SetClipCommand) || (command instanceof SetTransformCommand) || (command instanceof AffineTransformCommand)) { return true; } } return false; } private String getStyle(boolean filled) { StringBuilder style = new StringBuilder(); Color color = getCurrentState().getColor(); String colorOutput = getOutput(color); double opacity = color.getAlpha()/255.0; if (filled) { appendStyle(style, "fill", colorOutput); if (color.getAlpha() < 255) { appendStyle(style, "fill-opacity", opacity); } } else { appendStyle(style, "fill", "none"); } if (!filled) { appendStyle(style, "stroke", colorOutput); if (color.getAlpha() < 255) { appendStyle(style, "stroke-opacity", opacity); } Stroke stroke = getCurrentState().getStroke(); if (stroke instanceof BasicStroke) { BasicStroke bs = (BasicStroke) stroke; if (bs.getLineWidth() != 1f) { appendStyle(style, "stroke-width", bs.getLineWidth()); } if (bs.getMiterLimit() != 4f) { appendStyle(style, "stroke-miterlimit", bs.getMiterLimit()); } if (bs.getEndCap() != BasicStroke.CAP_BUTT) { appendStyle(style, "stroke-linecap", STROKE_ENDCAPS.get(bs.getEndCap())); } if (bs.getLineJoin() != BasicStroke.JOIN_MITER) { appendStyle(style, "stroke-linejoin", STROKE_LINEJOIN.get(bs.getLineJoin())); } if (bs.getDashArray() != null) { appendStyle(style, "stroke-dasharray", DataUtils.join(",", bs.getDashArray())); if (bs.getDashPhase() != 0f) { appendStyle(style, "stroke-dashoffset", bs.getDashPhase()); } } } } else { appendStyle(style, "stroke", "none"); } return style.toString(); } private String getStyle(Font font) { String style = getStyle(true); if (!GraphicsState.DEFAULT_FONT.equals(font)) { style += getOutput(font); } return style; } private static void appendStyle(StringBuilder style, String attribute, Object value) { style.append(attribute).append(":") .append(DataUtils.format(value)).append(";"); } private static String getOutput(AffineTransform tx) { StringBuilder out = new StringBuilder(); // FIXME: Use tx.getType() to check for transformation components if (AffineTransform.getTranslateInstance(tx.getTranslateX(), tx.getTranslateY()).equals(tx)) { out.append("translate(") .append(DataUtils.format(tx.getTranslateX())).append(" ") .append(DataUtils.format(tx.getTranslateY())).append(")"); } else { double[] matrix = new double[6]; tx.getMatrix(matrix); out.append("matrix(").append(DataUtils.join(" ", matrix)).append(")"); } return out.toString(); } private static String getOutput(Color color) { if (color.getColorSpace().getType() == ColorSpace.TYPE_CMYK) { float[] cmyk = color.getComponents(null); return String.format((Locale) null, "rgb(%d,%d,%d) icc-color(Generic-CMYK-profile,%f,%f,%f,%f)", color.getRed(), color.getGreen(), color.getBlue(), cmyk[0], cmyk[1], cmyk[2], cmyk[3]); } else { return String.format((Locale) null, "rgb(%d,%d,%d)", color.getRed(), color.getGreen(), color.getBlue()); } } private static String getOutput(Shape shape) { StringBuilder out = new StringBuilder(); PathIterator segments = shape.getPathIterator(null); double[] coords = new double[6]; for (int i = 0; !segments.isDone(); i++, segments.next()) { if (i > 0) { out.append(" "); } int segmentType = segments.currentSegment(coords); switch (segmentType) { case PathIterator.SEG_MOVETO: out.append("M").append(DataUtils.format(coords[0])).append(",").append(DataUtils.format(coords[1])); break; case PathIterator.SEG_LINETO: out.append("L").append(coords[0]).append(",").append(DataUtils.format(coords[1])); break; case PathIterator.SEG_CUBICTO: out.append("C") .append(DataUtils.format(coords[0])).append(",").append(DataUtils.format(coords[1])).append(" ") .append(DataUtils.format(coords[2])).append(",").append(DataUtils.format(coords[3])).append(" ") .append(DataUtils.format(coords[4])).append(",").append(DataUtils.format(coords[5])); break; case PathIterator.SEG_QUADTO: out.append("Q") .append(DataUtils.format(coords[0])).append(",").append(DataUtils.format(coords[1])).append(" ") .append(DataUtils.format(coords[2])).append(",").append(DataUtils.format(coords[3])); break; case PathIterator.SEG_CLOSE: out.append("Z"); break; default: throw new IllegalStateException("Unknown path operation."); } } return out.toString(); } private static String getOutput(Font font) { StringBuilder out = new StringBuilder(); if (!GraphicsState.DEFAULT_FONT.getFamily().equals(font.getFamily())) { String physicalFamily = GraphicsUtils.getPhysicalFont(font).getFamily(); out.append("font-family:\"").append(physicalFamily).append("\";"); } if (font.getSize2D() != GraphicsState.DEFAULT_FONT.getSize2D()) { out.append("font-size:").append(DataUtils.format(font.getSize2D())).append("px;"); } if ((font.getStyle() & Font.ITALIC) != 0) { out.append("font-style:italic;"); } if ((font.getStyle() & Font.BOLD) != 0) { out.append("font-weight:bold;"); } return out.toString(); } private static String getOutput(Image image, boolean lossyAllowed) { BufferedImage bufferedImage = GraphicsUtils.toBufferedImage(image); String encoded = encodeImage(bufferedImage, "png"); if (!GraphicsUtils.usesAlpha(bufferedImage) && lossyAllowed) { String encodedLossy = encodeImage(bufferedImage, "jpeg"); if (encodedLossy.length() > 0 && encodedLossy.length() < encoded.length()) { encoded = encodedLossy; } } return encoded; } private static String encodeImage(BufferedImage bufferedImage, String format) { ByteArrayOutputStream byteStream = new ByteArrayOutputStream(); Base64EncodeStream encodeStream = new Base64EncodeStream(byteStream); try { ImageIO.write(bufferedImage, format, encodeStream); encodeStream.close(); String encoded = byteStream.toString("ISO-8859-1"); return String.format("data:image/%s;base64,%s", format, encoded); } catch (IOException e) { return ""; } } private Element getElement(Shape shape) { Element elem; if (shape instanceof Line2D) { Line2D s = (Line2D) shape; elem = doc.createElement("line"); elem.setAttribute("x1", DataUtils.format(s.getX1())); elem.setAttribute("y1", DataUtils.format(s.getY1())); elem.setAttribute("x2", DataUtils.format(s.getX2())); elem.setAttribute("y2", DataUtils.format(s.getY2())); } else if (shape instanceof Rectangle2D) { Rectangle2D s = (Rectangle2D) shape; elem = doc.createElement("rect"); elem.setAttribute("x", DataUtils.format(s.getX())); elem.setAttribute("y", DataUtils.format(s.getY())); elem.setAttribute("width", DataUtils.format(s.getWidth())); elem.setAttribute("height", DataUtils.format(s.getHeight())); } else if (shape instanceof RoundRectangle2D) { RoundRectangle2D s = (RoundRectangle2D) shape; elem = doc.createElement("rect"); elem.setAttribute("x", DataUtils.format(s.getX())); elem.setAttribute("y", DataUtils.format(s.getY())); elem.setAttribute("width", DataUtils.format(s.getWidth())); elem.setAttribute("height", DataUtils.format(s.getHeight())); elem.setAttribute("rx", DataUtils.format(s.getArcWidth()/2.0)); elem.setAttribute("ry", DataUtils.format(s.getArcHeight()/2.0)); } else if (shape instanceof Ellipse2D) { Ellipse2D s = (Ellipse2D) shape; elem = doc.createElement("ellipse"); elem.setAttribute("cx", DataUtils.format(s.getCenterX())); elem.setAttribute("cy", DataUtils.format(s.getCenterY())); elem.setAttribute("rx", DataUtils.format(s.getWidth()/2.0)); elem.setAttribute("ry", DataUtils.format(s.getHeight()/2.0)); } else { elem = doc.createElement("path"); elem.setAttribute("d", getOutput(shape)); } return elem; } private Element getElement(String text, double x, double y) { Element elem = doc.createElement("text"); elem.appendChild(doc.createTextNode(text)); elem.setAttribute("x", DataUtils.format(x)); elem.setAttribute("y", DataUtils.format(y)); return elem; } private Element getElement(Image image, double x, double y, double width, double height) { Element elem = doc.createElement("image"); elem.setAttribute("x", DataUtils.format(x)); elem.setAttribute("y", DataUtils.format(y)); elem.setAttribute("width", DataUtils.format(width)); elem.setAttribute("height", DataUtils.format(height)); elem.setAttribute("preserveAspectRatio", "none"); boolean lossyAllowed = getCurrentState().getHints().get(VectorHints.KEY_EXPORT) == VectorHints.VALUE_EXPORT_SIZE; elem.setAttribute("xlink:href", getOutput(image, lossyAllowed)); return elem; } } vectorgraphics2d-0.13/src/main/java/de/erichseifert/vectorgraphics2d/svg/SVGProcessor.java000066400000000000000000000036531347274514600317040ustar00rootroot00000000000000/* * VectorGraphics2D: Vector export for Java(R) Graphics2D * * (C) Copyright 2010-2017 Erich Seifert , * Michael Seifert * * This file is part of VectorGraphics2D. * * VectorGraphics2D is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * VectorGraphics2D 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with VectorGraphics2D. If not, see . */ package de.erichseifert.vectorgraphics2d.svg; import de.erichseifert.vectorgraphics2d.Document; import de.erichseifert.vectorgraphics2d.Processor; import de.erichseifert.vectorgraphics2d.intermediate.CommandSequence; import de.erichseifert.vectorgraphics2d.intermediate.filters.FillPaintedShapeAsImageFilter; import de.erichseifert.vectorgraphics2d.intermediate.filters.StateChangeGroupingFilter; import de.erichseifert.vectorgraphics2d.util.PageSize; /** * {@code Processor} implementation that translates {@link CommandSequence}s to * a {@code Document} in the Scaled Vector Graphics (SVG) format. */ public class SVGProcessor implements Processor { /** * Initializes an {@code SVGProcessor}. */ public SVGProcessor() {} @Override public Document getDocument(CommandSequence commands, PageSize pageSize) { FillPaintedShapeAsImageFilter shapesAsImages = new FillPaintedShapeAsImageFilter(commands); CommandSequence filtered = new StateChangeGroupingFilter(shapesAsImages); return new SVGDocument(filtered, pageSize); } } vectorgraphics2d-0.13/src/main/java/de/erichseifert/vectorgraphics2d/svg/package-info.java000077500000000000000000000021161347274514600316650ustar00rootroot00000000000000/* * VectorGraphics2D: Vector export for Java(R) Graphics2D * * (C) Copyright 2010-2017 Erich Seifert , * Michael Seifert * * This file is part of VectorGraphics2D. * * VectorGraphics2D is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * VectorGraphics2D 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with VectorGraphics2D. If not, see . */ /** * Implementation of a processor to convert VectorGraphics2D intermediate * language commands to Scaled Vector Graphics (SVG). */ package de.erichseifert.vectorgraphics2d.svg; vectorgraphics2d-0.13/src/main/java/de/erichseifert/vectorgraphics2d/util/000077500000000000000000000000001347274514600266515ustar00rootroot00000000000000vectorgraphics2d-0.13/src/main/java/de/erichseifert/vectorgraphics2d/util/ASCII85EncodeStream.java000066400000000000000000000065061347274514600330220ustar00rootroot00000000000000/* * VectorGraphics2D: Vector export for Java(R) Graphics2D * * (C) Copyright 2010-2017 Erich Seifert , * Michael Seifert * * This file is part of VectorGraphics2D. * * VectorGraphics2D is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * VectorGraphics2D 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with VectorGraphics2D. If not, see . */ package de.erichseifert.vectorgraphics2d.util; import java.io.FilterOutputStream; import java.io.IOException; import java.io.OutputStream; import java.util.Arrays; public class ASCII85EncodeStream extends FilterOutputStream { private static final int BASE = 85; private static final int[] POW_85 = { BASE*BASE*BASE*BASE, BASE*BASE*BASE, BASE*BASE, BASE, 1 }; private static final char[] CHAR_MAP = "!\"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstu" .toCharArray(); private boolean closed; private final byte[] data; private int dataSize; private final byte[] prefixBytes; private boolean prefixDone; private final byte[] suffixBytes; private final byte[] encoded; public ASCII85EncodeStream(OutputStream out, String prefix, String suffix) { super(out); prefixBytes = (prefix != null) ? prefix.getBytes() : "".getBytes(); suffixBytes = (suffix != null) ? suffix.getBytes() : "".getBytes(); data = new byte[4]; encoded = new byte[5]; } public ASCII85EncodeStream(OutputStream out) { this(out, "", "~>"); } @Override public void write(int b) throws IOException { if (closed) { return; } if (!prefixDone) { out.write(prefixBytes); prefixDone = true; } if (dataSize == data.length) { writeChunk(); dataSize = 0; } data[dataSize++] = (byte) (b & 0xff); } private void writeChunk() throws IOException { if (dataSize == 0) { return; } long uint32 = toUInt32(data, dataSize); int padByteCount = data.length - dataSize; int encodedSize = encodeChunk(uint32, padByteCount); out.write(encoded, 0, encodedSize); } private static long toUInt32(byte[] bytes, int size) { long uint32 = 0L; for (int i = 0; i < 4 && i < size; i++) { uint32 |= (bytes[i] & 0xff) << (3 - i)*8; } return toUnsignedInt(uint32); } private static long toUnsignedInt(long x) { return x & 0x00000000ffffffffL; } private int encodeChunk(long uint32, int padByteCount) { Arrays.fill(encoded, (byte) 0); if (uint32 == 0L && padByteCount == 0) { encoded[0] = 'z'; return 1; } int size = encoded.length - padByteCount; for (int i = 0; i < size; i++) { encoded[i] = (byte) CHAR_MAP[(int) (uint32/POW_85[i]%BASE)]; } return size; } @Override public void close() throws IOException { if (closed) { return; } writeChunk(); out.write(suffixBytes); super.close(); closed = true; } } vectorgraphics2d-0.13/src/main/java/de/erichseifert/vectorgraphics2d/util/AlphaToMaskOp.java000066400000000000000000000071251347274514600321640ustar00rootroot00000000000000/* * VectorGraphics2D: Vector export for Java(R) Graphics2D * * (C) Copyright 2010-2017 Erich Seifert , * Michael Seifert * * This file is part of VectorGraphics2D. * * VectorGraphics2D is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * VectorGraphics2D 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with VectorGraphics2D. If not, see . */ package de.erichseifert.vectorgraphics2d.util; import java.awt.RenderingHints; import java.awt.geom.Point2D; import java.awt.geom.Rectangle2D; import java.awt.image.BufferedImage; import java.awt.image.BufferedImageOp; import java.awt.image.ColorModel; import java.awt.image.Raster; import java.awt.image.WritableRaster; import java.util.Hashtable; public class AlphaToMaskOp implements BufferedImageOp { private final boolean inverted; public AlphaToMaskOp(boolean inverted) { this.inverted = inverted; } public AlphaToMaskOp() { this(false); } public boolean isInverted() { return inverted; } public BufferedImage filter(BufferedImage src, BufferedImage dest) { ColorModel cm = src.getColorModel(); if (dest == null) { dest = createCompatibleDestImage(src, cm); } else if (dest.getWidth() != src.getWidth() || dest.getHeight() != src.getHeight()) { throw new IllegalArgumentException("Source and destination images have different dimensions."); } else if (dest.getColorModel() != cm) { throw new IllegalArgumentException("Color models don't match."); } if (cm.hasAlpha()) { Raster srcRaster = src.getRaster(); WritableRaster destRaster = dest.getRaster(); for (int y = 0; y < srcRaster.getHeight(); y++) { for (int x = 0; x < srcRaster.getWidth(); x++) { int argb = cm.getRGB(srcRaster.getDataElements(x, y, null)); int alpha = argb >>> 24; if (alpha >= 127 && !isInverted() || alpha < 127 && isInverted()) { argb |= 0xff000000; } else { argb &= 0x00ffffff; } destRaster.setDataElements(x, y, cm.getDataElements(argb, null)); } } } return dest; } public Rectangle2D getBounds2D(BufferedImage src) { Rectangle2D bounds = new Rectangle2D.Double(); bounds.setRect(src.getRaster().getBounds()); return bounds; } public BufferedImage createCompatibleDestImage(BufferedImage src, ColorModel destCM) { if (destCM == null) { destCM = src.getColorModel(); } WritableRaster raster = destCM.createCompatibleWritableRaster( src.getWidth(), src.getHeight()); boolean isRasterPremultiplied = destCM.isAlphaPremultiplied(); Hashtable properties = null; if (src.getPropertyNames() != null) { properties = new Hashtable<>(); for (String key : src.getPropertyNames()) { properties.put(key, src.getProperty(key)); } } BufferedImage bimage = new BufferedImage(destCM, raster, isRasterPremultiplied, properties); src.copyData(raster); return bimage; } public Point2D getPoint2D(Point2D srcPt, Point2D dstPt) { if (dstPt == null) { dstPt = new Point2D.Double(); } dstPt.setLocation(srcPt); return dstPt; } public RenderingHints getRenderingHints() { return null; } } vectorgraphics2d-0.13/src/main/java/de/erichseifert/vectorgraphics2d/util/Base64EncodeStream.java000066400000000000000000000055001347274514600330320ustar00rootroot00000000000000/* * VectorGraphics2D: Vector export for Java(R) Graphics2D * * (C) Copyright 2010-2017 Erich Seifert , * Michael Seifert * * This file is part of VectorGraphics2D. * * VectorGraphics2D is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * VectorGraphics2D 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with VectorGraphics2D. If not, see . */ package de.erichseifert.vectorgraphics2d.util; import java.io.FilterOutputStream; import java.io.IOException; import java.io.OutputStream; import java.util.Arrays; public class Base64EncodeStream extends FilterOutputStream { private static final int BASE = 64; private static final int[] POW_64 = { BASE*BASE*BASE, BASE*BASE, BASE, 1 }; private static final char[] CHAR_MAP = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/" .toCharArray(); private boolean closed; private final byte[] data; private int dataSize; private final byte[] encoded; public Base64EncodeStream(OutputStream out) { super(out); data = new byte[3]; encoded = new byte[4]; } @Override public void write(int b) throws IOException { if (closed) { return; } if (dataSize == data.length) { writeChunk(); dataSize = 0; } data[dataSize++] = (byte) (b & 0xff); } private void writeChunk() throws IOException { if (dataSize == 0) { return; } long uint32 = toUInt32(data, dataSize); int padByteCount = data.length - dataSize; int encodedSize = encodeChunk(uint32, padByteCount); out.write(encoded, 0, encodedSize); } private static long toUInt32(byte[] bytes, int size) { long uint32 = 0L; int offset = (3 - size)*8; for (int i = size - 1; i >= 0; i--) { uint32 |= (bytes[i] & 0xff) << offset; offset += 8; } return toUnsignedInt(uint32); } private static long toUnsignedInt(long x) { return x & 0x00000000ffffffffL; } private int encodeChunk(long uint32, int padByteCount) { Arrays.fill(encoded, (byte) '='); int size = encoded.length - padByteCount; for (int i = 0; i < size; i++) { encoded[i] = (byte) CHAR_MAP[(int) (uint32/POW_64[i]%BASE)]; } return encoded.length; } @Override public void close() throws IOException { if (closed) { return; } writeChunk(); super.close(); closed = true; } } vectorgraphics2d-0.13/src/main/java/de/erichseifert/vectorgraphics2d/util/DataUtils.java000066400000000000000000000175111347274514600314130ustar00rootroot00000000000000/* * VectorGraphics2D: Vector export for Java(R) Graphics2D * * (C) Copyright 2010-2017 Erich Seifert , * Michael Seifert * * This file is part of VectorGraphics2D. * * VectorGraphics2D is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * VectorGraphics2D 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with VectorGraphics2D. If not, see . */ package de.erichseifert.vectorgraphics2d.util; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.text.DecimalFormat; import java.text.DecimalFormatSymbols; import java.util.ArrayList; import java.util.Arrays; import java.util.LinkedHashMap; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.regex.Pattern; /** * Abstract class that contains utility functions for working with data * collections like maps or lists. */ public abstract class DataUtils { /** Standard pattern to format numbers */ private static final DecimalFormat DOUBLE_FORMAT = new DecimalFormat("0", DecimalFormatSymbols.getInstance(Locale.ENGLISH)); private static final DecimalFormat FLOAT_FORMAT = new DecimalFormat("0", DecimalFormatSymbols.getInstance(Locale.ENGLISH)); static { DOUBLE_FORMAT.setMaximumFractionDigits(15); FLOAT_FORMAT.setMaximumFractionDigits(6); } /** * Default constructor that prevents creation of class. */ DataUtils() { throw new UnsupportedOperationException(); } /** * Creates a mapping from two arrays, one with keys, one with values. * @param Data type of the keys. * @param Data type of the values. * @param keys Array containing the keys. * @param values Array containing the values. * @return Map with keys and values from the specified arrays. */ public static Map map(K[] keys, V[] values) { // Check for valid parameters if (keys.length != values.length) { throw new IllegalArgumentException( "Cannot create a Map: " + "The number of keys and values differs."); } // Fill map with keys and values Map map = new LinkedHashMap<>(keys.length); for (int i = 0; i < keys.length; i++) { K key = keys[i]; V value = values[i]; map.put(key, value); } return map; } /** * Returns a string containing all elements concatenated by a specified * separator. * @param separator Separator string. * @param elements List of elements that should be concatenated. * @return a concatenated string. */ public static String join(String separator, List elements) { if (elements == null || elements.size() == 0) { return ""; } StringBuilder sb = new StringBuilder(elements.size()*3); int i = 0; for (Object elem : elements) { if (separator.length() > 0 && i++ > 0) { sb.append(separator); } sb.append(format(elem)); } return sb.toString(); } /** * Returns a string containing all elements concatenated by a specified * separator. * @param separator Separator string. * @param elements Array of elements that should be concatenated. * @return a concatenated string. */ public static String join(String separator, Object[] elements) { if (elements == null || elements.length == 0) { return ""; } return join(separator, Arrays.asList(elements)); } /** * Returns a string containing all double numbers concatenated by a * specified separator. * @param separator Separator string. * @param elements Array of double numbers that should be concatenated. * @return a concatenated string. */ public static String join(String separator, double[] elements) { if (elements == null || elements.length == 0) { return ""; } List list = new ArrayList<>(elements.length); for (Double element : elements) { list.add(element); } return join(separator, list); } /** * Returns a string containing all float numbers concatenated by a * specified separator. * @param separator Separator string. * @param elements Array of float numbers that should be concatenated. * @return a concatenated string. */ public static String join(String separator, float[] elements) { if (elements == null || elements.length == 0) { return ""; } List list = new ArrayList<>(elements.length); for (Float element : elements) { list.add(element); } return join(separator, list); } /** * Returns the largest of all specified values. * @param values Several integer values. * @return largest value. */ public static int max(int... values) { if (values.length == 0) { throw new IllegalArgumentException("No values provided: Cannot determine maximum value."); } int max = values[0]; for (int i = 1; i < values.length; i++) { if (values[i] > max) { max = values[i]; } } return max; } /** * Copies data from an input stream to an output stream using a buffer of * specified size. * @param in Input stream. * @param out Output stream. * @param bufferSize Size of the copy buffer. * @throws IOException when an error occurs while copying. */ public static void transfer(InputStream in, OutputStream out, int bufferSize) throws IOException { byte[] buffer = new byte[bufferSize]; int bytesRead; while ((bytesRead = in.read(buffer)) != -1) { out.write(buffer, 0, bytesRead); } } /** * Returns a formatted string of the specified number. All trailing zeroes * or decimal points will be stripped. * @param number Number to convert to a string. * @return A formatted string. */ public static String format(Number number) { String formatted; if (number instanceof Double) { formatted = DOUBLE_FORMAT.format(number.doubleValue()); } else if (number instanceof Float) { formatted = FLOAT_FORMAT.format(number.floatValue()); } else { formatted = number.toString(); } return formatted; } /** * Returns a formatted string of the specified object. * @param obj Object to convert to a string. * @return A formatted string. */ public static String format(Object obj) { if (obj instanceof Number) { return format((Number) obj); } else { return obj.toString(); } } /** * Converts an array of {@code float} numbers to a list of {@code Float}s. * The list will be empty if the array is empty or {@code null}. * @param elements Array of float numbers. * @return A list with all numbers as {@code Float}. */ public static List asList(float[] elements) { int size = (elements != null) ? elements.length : 0; List list = new ArrayList<>(size); if (elements != null) { for (Float elem : elements) { list.add(elem); } } return list; } /** * Converts an array of {@code double} numbers to a list of {@code Double}s. * The list will be empty if the array is empty or {@code null}. * @param elements Array of double numbers. * @return A list with all numbers as {@code Double}. */ public static List asList(double[] elements) { int size = (elements != null) ? elements.length : 0; List list = new ArrayList<>(size); if (elements != null) { for (Double elem : elements) { list.add(elem); } } return list; } /** * Removes the specified trailing pattern from a string. * @param s string. * @param substr trailing pattern. * @return A string without the trailing pattern. */ public static String stripTrailing(String s, String substr) { return s.replaceAll("(" + Pattern.quote(substr) + ")+$", ""); } } vectorgraphics2d-0.13/src/main/java/de/erichseifert/vectorgraphics2d/util/FlateEncodeStream.java000066400000000000000000000022121347274514600330360ustar00rootroot00000000000000/* * VectorGraphics2D: Vector export for Java(R) Graphics2D * * (C) Copyright 2010-2017 Erich Seifert , * Michael Seifert * * This file is part of VectorGraphics2D. * * VectorGraphics2D is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * VectorGraphics2D 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with VectorGraphics2D. If not, see . */ package de.erichseifert.vectorgraphics2d.util; import java.io.OutputStream; import java.util.zip.DeflaterOutputStream; public class FlateEncodeStream extends DeflaterOutputStream { public FlateEncodeStream(OutputStream out) { super(out); } } vectorgraphics2d-0.13/src/main/java/de/erichseifert/vectorgraphics2d/util/FormattingWriter.java000066400000000000000000000056741347274514600330370ustar00rootroot00000000000000/* * VectorGraphics2D: Vector export for Java(R) Graphics2D * * (C) Copyright 2010-2017 Erich Seifert , * Michael Seifert * * This file is part of VectorGraphics2D. * * VectorGraphics2D is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * VectorGraphics2D 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with VectorGraphics2D. If not, see . */ package de.erichseifert.vectorgraphics2d.util; import java.io.Closeable; import java.io.Flushable; import java.io.IOException; import java.io.OutputStream; import java.io.UnsupportedEncodingException; public class FormattingWriter implements Closeable, Flushable, AutoCloseable { private final OutputStream out; private final String encoding; private final byte[] eolBytes; private long position; public FormattingWriter(OutputStream out, String encoding, String eol) throws UnsupportedEncodingException { if (out == null) { throw new IllegalArgumentException("Output stream cannot be null."); } if (eol == null || eol.isEmpty()) { throw new IllegalArgumentException("End-of-line string cannot be empty."); } this.out = out; this.encoding = encoding; this.eolBytes = eol.getBytes(encoding); } public FormattingWriter write(byte[] bytes) throws IOException { out.write(bytes, 0, bytes.length); position += bytes.length; return this; } public FormattingWriter write(String str) throws IOException { byte[] bytes = str.getBytes(encoding); return write(bytes); } public FormattingWriter write(String format, Object... args) throws IOException { return write(String.format(null, format, args)); } public FormattingWriter write(Number number) throws IOException { return write(DataUtils.format(number)); } public FormattingWriter writeln() throws IOException { return write(eolBytes); } public FormattingWriter writeln(byte[] bytes) throws IOException { write(bytes); return writeln(); } public FormattingWriter writeln(String string) throws IOException { write(string); return writeln(); } public FormattingWriter writeln(String format, Object... args) throws IOException { write(String.format(null, format, args)); return writeln(); } public FormattingWriter writeln(Number number) throws IOException { write(number); return writeln(); } public void flush() throws IOException { out.flush(); } public void close() throws IOException { out.close(); } public long tell() { return position; } } vectorgraphics2d-0.13/src/main/java/de/erichseifert/vectorgraphics2d/util/GraphicsUtils.java000066400000000000000000000346441347274514600323100ustar00rootroot00000000000000/* * VectorGraphics2D: Vector export for Java(R) Graphics2D * * (C) Copyright 2010-2017 Erich Seifert , * Michael Seifert * * This file is part of VectorGraphics2D. * * VectorGraphics2D is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * VectorGraphics2D 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with VectorGraphics2D. If not, see . */ package de.erichseifert.vectorgraphics2d.util; import java.awt.Font; import java.awt.Graphics; import java.awt.GraphicsConfiguration; import java.awt.GraphicsDevice; import java.awt.GraphicsEnvironment; import java.awt.HeadlessException; import java.awt.Image; import java.awt.Polygon; import java.awt.Rectangle; import java.awt.Shape; import java.awt.Transparency; import java.awt.color.ColorSpace; import java.awt.font.FontRenderContext; import java.awt.font.TextLayout; import java.awt.geom.*; import java.awt.image.BufferedImage; import java.awt.image.ColorModel; import java.awt.image.ComponentColorModel; import java.awt.image.DataBuffer; import java.awt.image.PixelGrabber; import java.awt.image.Raster; import java.awt.image.RenderedImage; import java.awt.image.WritableRaster; import java.util.Comparator; import java.util.HashSet; import java.util.Hashtable; import java.util.PriorityQueue; import java.util.Queue; import java.util.Set; import javax.swing.ImageIcon; /** * Abstract class that contains utility functions for working with graphics. * For example, this includes font handling. */ public abstract class GraphicsUtils { private static final FontRenderContext FONT_RENDER_CONTEXT = new FontRenderContext(null, false, true); private static final String FONT_TEST_STRING = "Falsches Üben von Xylophonmusik quält jeden größeren Zwerg"; /** * Default constructor that prevents creation of class. */ GraphicsUtils() { throw new UnsupportedOperationException(); } /** * This method returns {@code true} if the specified image has the * possibility to store transparent pixels. * Inspired by http://www.exampledepot.com/egs/java.awt.image/HasAlpha.html * @param image Image that should be checked for alpha channel. * @return {@code true} if the specified image can have transparent pixels, * {@code false} otherwise */ public static boolean hasAlpha(Image image) { ColorModel cm; // If buffered image, the color model is readily available if (image instanceof BufferedImage) { BufferedImage bimage = (BufferedImage) image; cm = bimage.getColorModel(); } else { // Use a pixel grabber to retrieve the image's color model; // grabbing a single pixel is usually sufficient PixelGrabber pg = new PixelGrabber(image, 0, 0, 1, 1, false); try { pg.grabPixels(); } catch (InterruptedException e) { return false; } // Get the image's color model cm = pg.getColorModel(); } return cm.hasAlpha(); } /** * This method returns {@code true} if the specified image has at least one * pixel that is not fully opaque. * @param image Image that should be checked for non-opaque pixels. * @return {@code true} if the specified image has transparent pixels, * {@code false} otherwise */ public static boolean usesAlpha(Image image) { if (image == null) { return false; } BufferedImage bimage = toBufferedImage(image); Raster alphaRaster = bimage.getAlphaRaster(); if (alphaRaster == null) { return false; } DataBuffer dataBuffer = alphaRaster.getDataBuffer(); for (int i = 0; i < dataBuffer.getSize(); i++) { int alpha = dataBuffer.getElem(i); if (alpha < 255) { return true; } } return false; } /** * Converts a rendered image instance to a {@code BufferedImage}. * @param image Rendered image that should be converted. * @return a buffered image containing the image pixels, or the original * instance if the image already was of type {@code BufferedImage}. */ public static BufferedImage toBufferedImage(RenderedImage image) { if (image instanceof BufferedImage) { return (BufferedImage) image; } ColorModel cm = image.getColorModel(); WritableRaster raster = cm.createCompatibleWritableRaster( image.getWidth(), image.getHeight()); boolean isRasterPremultiplied = cm.isAlphaPremultiplied(); Hashtable properties = null; if (image.getPropertyNames() != null) { properties = new Hashtable<>(); for (String key : image.getPropertyNames()) { properties.put(key, image.getProperty(key)); } } BufferedImage bimage = new BufferedImage(cm, raster, isRasterPremultiplied, properties); image.copyData(raster); return bimage; } /** * This method returns a buffered image with the contents of an image. * Taken from http://www.exampledepot.com/egs/java.awt.image/Image2Buf.html * @param image Image to be converted * @return a buffered image with the contents of the specified image */ public static BufferedImage toBufferedImage(Image image) { if (image instanceof BufferedImage) { return (BufferedImage) image; } // This code ensures that all the pixels in the image are loaded image = new ImageIcon(image).getImage(); // Determine if the image has transparent pixels boolean hasAlpha = hasAlpha(image); // Create a buffered image with a format that's compatible with the // screen BufferedImage bimage; GraphicsEnvironment ge = GraphicsEnvironment .getLocalGraphicsEnvironment(); try { // Determine the type of transparency of the new buffered image int transparency = Transparency.OPAQUE; if (hasAlpha) { transparency = Transparency.TRANSLUCENT; } // Create the buffered image GraphicsDevice gs = ge.getDefaultScreenDevice(); GraphicsConfiguration gc = gs.getDefaultConfiguration(); bimage = gc.createCompatibleImage( image.getWidth(null), image.getHeight(null), transparency); } catch (HeadlessException e) { // The system does not have a screen bimage = null; } if (bimage == null) { // Create a buffered image using the default color model int type = BufferedImage.TYPE_INT_RGB; if (hasAlpha) { type = BufferedImage.TYPE_INT_ARGB; } bimage = new BufferedImage( image.getWidth(null), image.getHeight(null), type); } // Copy image to buffered image Graphics g = bimage.createGraphics(); // Paint the image onto the buffered image g.drawImage(image, 0, 0, null); g.dispose(); return bimage; } public static Shape clone(Shape shape) { if (shape == null) { return null; } Shape clone; if (shape instanceof Line2D) { clone = (shape instanceof Line2D.Float) ? new Line2D.Float() : new Line2D.Double(); ((Line2D) clone).setLine((Line2D) shape); } else if (shape instanceof Rectangle) { clone = new Rectangle((Rectangle) shape); } else if (shape instanceof Rectangle2D) { clone = (shape instanceof Rectangle2D.Float) ? new Rectangle2D.Float() : new Rectangle2D.Double(); ((Rectangle2D) clone).setRect((Rectangle2D) shape); } else if (shape instanceof RoundRectangle2D) { clone = (shape instanceof RoundRectangle2D.Float) ? new RoundRectangle2D.Float() : new RoundRectangle2D.Double(); ((RoundRectangle2D) clone).setRoundRect((RoundRectangle2D) shape); } else if (shape instanceof Ellipse2D) { clone = (shape instanceof Ellipse2D.Float) ? new Ellipse2D.Float() : new Ellipse2D.Double(); ((Ellipse2D) clone).setFrame(((Ellipse2D) shape).getFrame()); } else if (shape instanceof Arc2D) { clone = (shape instanceof Arc2D.Float) ? new Arc2D.Float() : new Arc2D.Double(); ((Arc2D) clone).setArc((Arc2D) shape); } else if (shape instanceof Polygon) { Polygon p = (Polygon) shape; clone = new Polygon(p.xpoints, p.ypoints, p.npoints); } else if (shape instanceof CubicCurve2D) { clone = (shape instanceof CubicCurve2D.Float) ? new CubicCurve2D.Float() : new CubicCurve2D.Double(); ((CubicCurve2D) clone).setCurve((CubicCurve2D) shape); } else if (shape instanceof QuadCurve2D) { clone = (shape instanceof QuadCurve2D.Float) ? new QuadCurve2D.Float() : new QuadCurve2D.Double(); ((QuadCurve2D) clone).setCurve((QuadCurve2D) shape); } else if (shape instanceof Path2D.Float) { clone = new Path2D.Float(shape); } else { clone = new Path2D.Double(shape); } return clone; } private static class FontExpressivenessComparator implements Comparator { private static final int[] STYLES = { Font.PLAIN, Font.ITALIC, Font.BOLD, Font.BOLD | Font.ITALIC }; public int compare(Font font1, Font font2) { if (font1 == font2) { return 0; } Set variantNames1 = new HashSet<>(); Set variantNames2 = new HashSet<>(); for (int style : STYLES) { variantNames1.add(font1.deriveFont(style).getPSName()); variantNames2.add(font2.deriveFont(style).getPSName()); } if (variantNames1.size() < variantNames2.size()) { return 1; } else if (variantNames1.size() > variantNames2.size()) { return -1; } return font1.getName().compareTo(font2.getName()); } } private static final FontExpressivenessComparator FONT_EXPRESSIVENESS_COMPARATOR = new FontExpressivenessComparator(); private static boolean isLogicalFontFamily(String family) { return (Font.DIALOG.equals(family) || Font.DIALOG_INPUT.equals(family) || Font.SANS_SERIF.equals(family) || Font.SERIF.equals(family) || Font.MONOSPACED.equals(family)); } /** * Try to guess physical font from the properties of a logical font, like * "Dialog", "Serif", "Monospaced" etc. * @param logicalFont Logical font object. * @param testText Text used to determine font properties. * @return An object of the first matching physical font. The original font * object is returned if it was a physical font or no font matched. */ public static Font getPhysicalFont(Font logicalFont, String testText) { String logicalFamily = logicalFont.getFamily(); if (!isLogicalFontFamily(logicalFamily)) { return logicalFont; } final TextLayout logicalLayout = new TextLayout(testText, logicalFont, FONT_RENDER_CONTEXT); // Create a list of matches sorted by font expressiveness (in descending order) Queue physicalFonts = new PriorityQueue<>(1, FONT_EXPRESSIVENESS_COMPARATOR); Font[] allPhysicalFonts = GraphicsEnvironment.getLocalGraphicsEnvironment().getAllFonts(); for (Font physicalFont : allPhysicalFonts) { String physicalFamily = physicalFont.getFamily(); // Skip logical fonts if (isLogicalFontFamily(physicalFamily)) { continue; } // Derive identical variant of physical font physicalFont = physicalFont.deriveFont( logicalFont.getStyle(), logicalFont.getSize2D()); TextLayout physicalLayout = new TextLayout(testText, physicalFont, FONT_RENDER_CONTEXT); // Compare various properties of physical and logical font if (physicalLayout.getBounds().equals(logicalLayout.getBounds()) && physicalLayout.getAscent() == logicalLayout.getAscent() && physicalLayout.getDescent() == logicalLayout.getDescent() && physicalLayout.getLeading() == logicalLayout.getLeading() && physicalLayout.getAdvance() == logicalLayout.getAdvance() && physicalLayout.getVisibleAdvance() == logicalLayout.getVisibleAdvance()) { // Store matching font in list physicalFonts.add(physicalFont); } } // Return a valid font even when no matching font could be found if (physicalFonts.isEmpty()) { return logicalFont; } return physicalFonts.poll(); } public static Font getPhysicalFont(Font logicalFont) { return getPhysicalFont(logicalFont, FONT_TEST_STRING); } public static BufferedImage getAlphaImage(BufferedImage image) { WritableRaster alphaRaster = image.getAlphaRaster(); int width = image.getWidth(); int height = image.getHeight(); ColorModel cm; WritableRaster raster; // TODO Handle bitmap masks (work on ImageDataStream is necessary) /* if (image.getTransparency() == BufferedImage.BITMASK) { byte[] arr = {(byte) 0, (byte) 255}; cm = new IndexColorModel(1, 2, arr, arr, arr); raster = Raster.createPackedRaster(DataBuffer.TYPE_BYTE, width, height, 1, 1, null); } else {*/ ColorSpace colorSpace = ColorSpace.getInstance(ColorSpace.CS_GRAY); int[] bits = {8}; cm = new ComponentColorModel(colorSpace, bits, false, true, Transparency.OPAQUE, DataBuffer.TYPE_BYTE); raster = cm.createCompatibleWritableRaster(width, height); //} BufferedImage alphaImage = new BufferedImage(cm, raster, false, null); int[] alphaValues = new int[image.getWidth()*alphaRaster.getNumBands()]; for (int y = 0; y < image.getHeight(); y++) { alphaRaster.getPixels(0, y, image.getWidth(), 1, alphaValues); // FIXME Don't force 8-bit alpha channel (see TODO above) if (image.getTransparency() == BufferedImage.BITMASK) { for (int i = 0; i < alphaValues.length; i++) { if (alphaValues[i] > 0) { alphaValues[i] = 255; } } } alphaImage.getRaster().setPixels(0, y, image.getWidth(), 1, alphaValues); } return alphaImage; } public static boolean equals(Shape shapeA, Shape shapeB) { PathIterator pathAIterator = shapeA.getPathIterator(null); PathIterator pathBIterator = shapeB.getPathIterator(null); if (pathAIterator.getWindingRule() != pathBIterator.getWindingRule()) { return false; } double[] pathASegment = new double[6]; double[] pathBSegment = new double[6]; while (!pathAIterator.isDone()) { int pathASegmentType = pathAIterator.currentSegment(pathASegment); int pathBSegmentType = pathBIterator.currentSegment(pathBSegment); if (pathASegmentType != pathBSegmentType) { return false; } for (int segmentIndex = 0; segmentIndex < pathASegment.length; segmentIndex++) { if (pathASegment[segmentIndex] != pathBSegment[segmentIndex]) { return false; } } pathAIterator.next(); pathBIterator.next(); } // When the iterator of shapeA is done and shapeA equals shapeB, // the iterator of shapeB must also be done if (!pathBIterator.isDone()) { return false; } return true; } } vectorgraphics2d-0.13/src/main/java/de/erichseifert/vectorgraphics2d/util/ImageDataStream.java000066400000000000000000000100231347274514600325000ustar00rootroot00000000000000/* * VectorGraphics2D: Vector export for Java(R) Graphics2D * * (C) Copyright 2010-2017 Erich Seifert , * Michael Seifert * * This file is part of VectorGraphics2D. * * VectorGraphics2D is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * VectorGraphics2D 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with VectorGraphics2D. If not, see . */ package de.erichseifert.vectorgraphics2d.util; import java.awt.image.BufferedImage; import java.awt.image.Raster; import java.io.IOException; import java.io.InputStream; import java.util.LinkedList; import java.util.Queue; public class ImageDataStream extends InputStream { public enum Interleaving { SAMPLE, ROW, WITHOUT_ALPHA, ALPHA_ONLY } private final BufferedImage image; private final int width; private final int height; private final Interleaving interleaving; private final Raster raster; private final boolean opaque; private final Queue byteBuffer; private final int[] sampleValues; private final int[] sampleSizes; private int x; private int y; //private byte currentBit; public ImageDataStream(BufferedImage image, Interleaving interleaving) { this.image = image; this.interleaving = interleaving; width = image.getWidth(); height = image.getHeight(); x = -1; y = 0; Raster alphaRaster = image.getAlphaRaster(); if (interleaving == Interleaving.ALPHA_ONLY) { raster = alphaRaster; } else { raster = image.getRaster(); } opaque = alphaRaster == null; byteBuffer = new LinkedList<>(); sampleValues = new int[raster.getNumBands()]; sampleSizes = raster.getSampleModel().getSampleSize(); } public BufferedImage getImage() { return image; } public Interleaving getInterleaving() { return interleaving; } @Override public int read() throws IOException { if (!byteBuffer.isEmpty()) { return byteBuffer.poll(); } else { if (!nextSample()) { return -1; } int bands = sampleValues.length; if (interleaving == Interleaving.WITHOUT_ALPHA || interleaving == Interleaving.ALPHA_ONLY) { if (interleaving == Interleaving.WITHOUT_ALPHA && !opaque) { // Ignore alpha band bands--; } for (int band = 0; band < bands; band++) { bufferSampleValue(band); } } else { if (opaque) { for (int band = 0; band < bands; band++) { bufferSampleValue(band); } } else { for (int band = 0; band < bands; band++) { // Fix order to be ARGB instead of RGBA if (band == 0) { bufferSampleValue(bands - 1); } else { bufferSampleValue(band - 1); } } } } if (!byteBuffer.isEmpty()) { return byteBuffer.poll(); } else { return -1; } } } private void bufferSampleValue(int band) { if (sampleSizes[band] < 8) { // TODO Handle data with sample sizes smaller than 1 byte int byteValue = sampleValues[band] & 0xFF; byteBuffer.offer(byteValue); } else { int byteCount = sampleSizes[band]/8; for (int i = byteCount - 1; i >= 0; i--) { int byteValue = (sampleValues[band] >> i*8) & 0xFF; byteBuffer.offer(byteValue); } } } private boolean nextSample() { if (interleaving == Interleaving.SAMPLE || interleaving == Interleaving.WITHOUT_ALPHA) { x++; if (x >= width) { x = 0; y++; } } if (x < 0 || x >= width || y < 0 || y >= height) { return false; } else { raster.getPixel(x, y, sampleValues); return true; } } } vectorgraphics2d-0.13/src/main/java/de/erichseifert/vectorgraphics2d/util/LineWrapOutputStream.java000066400000000000000000000033711347274514600336360ustar00rootroot00000000000000/* * VectorGraphics2D: Vector export for Java(R) Graphics2D * * (C) Copyright 2010-2017 Erich Seifert , * Michael Seifert * * This file is part of VectorGraphics2D. * * VectorGraphics2D is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * VectorGraphics2D 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with VectorGraphics2D. If not, see . */ package de.erichseifert.vectorgraphics2d.util; import java.io.FilterOutputStream; import java.io.IOException; import java.io.OutputStream; public class LineWrapOutputStream extends FilterOutputStream { public static final String STANDARD_EOL = "\r\n"; private final int lineWidth; private final byte[] eolBytes; private int written; public LineWrapOutputStream(OutputStream sink, int lineWidth, String eol) { super(sink); this.lineWidth = lineWidth; this.eolBytes = eol.getBytes(); if (lineWidth <= 0) { throw new IllegalArgumentException("Width must be at least 0."); } } public LineWrapOutputStream(OutputStream sink, int lineWidth) { this(sink, lineWidth, STANDARD_EOL); } @Override public void write(int b) throws IOException { if (written == lineWidth) { out.write(eolBytes); written = 0; } out.write(b); written++; } } vectorgraphics2d-0.13/src/main/java/de/erichseifert/vectorgraphics2d/util/PageSize.java000066400000000000000000000055701347274514600312320ustar00rootroot00000000000000/* * VectorGraphics2D: Vector export for Java(R) Graphics2D * * (C) Copyright 2010-2017 Erich Seifert , * Michael Seifert * * This file is part of VectorGraphics2D. * * VectorGraphics2D is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * VectorGraphics2D 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with VectorGraphics2D. If not, see . */ package de.erichseifert.vectorgraphics2d.util; import java.awt.geom.Rectangle2D; /** *

Class that represents a page with a specified origin and size. * The class is immutable and can be initialized with coordinates and * dimensions or only dimensions:

*
PageSize a3 = new PageSize(0.0, 0.0, 297.0, 420.0);
 *PageSize a4 = new PageSize(210.0, 297.0);
* *

For convenience the class contains static constants for common page * sizes:

*
PageSize a4 = PageSize.A4;
 *PageSize letter = PageSize.LETTER;
*/ public class PageSize { private static final double MM_PER_INCH = 2.54; public static final PageSize A3 = new PageSize(297.0, 420.0); public static final PageSize A4 = new PageSize(210.0, 297.0); public static final PageSize A5 = new PageSize(148.0, 210.0); public static final PageSize LETTER = new PageSize(8.5*MM_PER_INCH, 11.0*MM_PER_INCH); public static final PageSize LEGAL = new PageSize(8.5*MM_PER_INCH, 14.0*MM_PER_INCH); public static final PageSize TABLOID = new PageSize(11.0*MM_PER_INCH, 17.0*MM_PER_INCH); public static final PageSize LEDGER = TABLOID.getLandscape(); private final double x; private final double y; private final double width; private final double height; public PageSize(double x, double y, double width, double height) { this.x = x; this.y = y; this.width = width; this.height = height; } public PageSize(double width, double height) { this(0.0, 0.0, width, height); } public PageSize(Rectangle2D size) { this(size.getX(), size.getY(), size.getWidth(), size.getHeight()); } public PageSize getPortrait() { if (width <= height) { return this; } return new PageSize(x, y, height, width); } public PageSize getLandscape() { if (width >= height) { return this; } return new PageSize(x, y, height, width); } public double getX() { return x; } public double getY() { return y; } public double getWidth() { return width; } public double getHeight() { return height; } } vectorgraphics2d-0.13/src/main/java/de/erichseifert/vectorgraphics2d/util/package-info.java000077500000000000000000000020031347274514600320360ustar00rootroot00000000000000/* * VectorGraphics2D: Vector export for Java(R) Graphics2D * * (C) Copyright 2010-2017 Erich Seifert , * Michael Seifert * * This file is part of VectorGraphics2D. * * VectorGraphics2D is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * VectorGraphics2D 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with VectorGraphics2D. If not, see . */ /** * Utility classes for common data or graphics operations. */ package de.erichseifert.vectorgraphics2d.util; vectorgraphics2d-0.13/src/test/000077500000000000000000000000001347274514600164715ustar00rootroot00000000000000vectorgraphics2d-0.13/src/test/java/000077500000000000000000000000001347274514600174125ustar00rootroot00000000000000vectorgraphics2d-0.13/src/test/java/de/000077500000000000000000000000001347274514600200025ustar00rootroot00000000000000vectorgraphics2d-0.13/src/test/java/de/erichseifert/000077500000000000000000000000001347274514600224565ustar00rootroot00000000000000vectorgraphics2d-0.13/src/test/java/de/erichseifert/vectorgraphics2d/000077500000000000000000000000001347274514600257275ustar00rootroot00000000000000vectorgraphics2d-0.13/src/test/java/de/erichseifert/vectorgraphics2d/AllTests.java000066400000000000000000000030531347274514600303260ustar00rootroot00000000000000/* * VectorGraphics2D: Vector export for Java(R) Graphics2D * * (C) Copyright 2010-2017 Erich Seifert , * Michael Seifert * * This file is part of VectorGraphics2D. * * VectorGraphics2D is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * VectorGraphics2D 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with VectorGraphics2D. If not, see . */ package de.erichseifert.vectorgraphics2d; import org.junit.runner.RunWith; import org.junit.runners.Suite; import de.erichseifert.vectorgraphics2d.eps.EPSTests; import de.erichseifert.vectorgraphics2d.intermediate.IRTests; import de.erichseifert.vectorgraphics2d.pdf.PDFTests; import de.erichseifert.vectorgraphics2d.svg.SVGTests; import de.erichseifert.vectorgraphics2d.util.UtilTests; @RunWith(Suite.class) @Suite.SuiteClasses({ TestUtilsTest.class, UtilTests.class, IRTests.class, VectorGraphics2DTest.class, ProcessorsTest.class, EPSTests.class, PDFTests.class, SVGTests.class }) public class AllTests { } vectorgraphics2d-0.13/src/test/java/de/erichseifert/vectorgraphics2d/GraphicsStateTest.java000066400000000000000000000054461347274514600322040ustar00rootroot00000000000000/* * VectorGraphics2D: Vector export for Java(R) Graphics2D * * (C) Copyright 2010-2017 Erich Seifert , * Michael Seifert * * This file is part of VectorGraphics2D. * * VectorGraphics2D is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * VectorGraphics2D 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with VectorGraphics2D. If not, see . */ package de.erichseifert.vectorgraphics2d; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotSame; import java.awt.Color; import java.awt.Graphics2D; import java.awt.geom.AffineTransform; import java.awt.geom.Rectangle2D; import java.awt.image.BufferedImage; import org.junit.Test; public class GraphicsStateTest { @Test public void testInitialStateIsEqualToGraphics2D() { BufferedImage image = new BufferedImage(1, 1, BufferedImage.TYPE_INT_ARGB); Graphics2D g2d = (Graphics2D) image.getGraphics(); GraphicsState state = new GraphicsState(); assertEquals(state.getBackground(), g2d.getBackground()); assertEquals(state.getColor(), g2d.getColor()); assertEquals(state.getClip(), g2d.getClip()); assertEquals(state.getComposite(), g2d.getComposite()); assertEquals(state.getFont(), g2d.getFont()); assertEquals(state.getPaint(), g2d.getPaint()); assertEquals(state.getStroke(), g2d.getStroke()); assertEquals(state.getTransform(), g2d.getTransform()); } @Test public void testEquals() { GraphicsState state1 = new GraphicsState(); state1.setBackground(Color.WHITE); state1.setColor(Color.BLACK); state1.setClip(new Rectangle2D.Double(0, 0, 10, 10)); GraphicsState state2 = new GraphicsState(); state2.setBackground(Color.WHITE); state2.setColor(Color.BLACK); state2.setClip(new Rectangle2D.Double(0, 0, 10, 10)); assertEquals(state1, state2); state2.setTransform(AffineTransform.getTranslateInstance(5, 5)); assertFalse(state1.equals(state2)); } @Test public void testClone() throws CloneNotSupportedException { GraphicsState state = new GraphicsState(); state.setBackground(Color.BLUE); state.setColor(Color.GREEN); state.setClip(new Rectangle2D.Double(2, 3, 4, 2)); GraphicsState clone = (GraphicsState) state.clone(); assertNotSame(state, clone); assertEquals(state, clone); } } vectorgraphics2d-0.13/src/test/java/de/erichseifert/vectorgraphics2d/ProcessorsTest.java000066400000000000000000000036731347274514600316050ustar00rootroot00000000000000/* * VectorGraphics2D: Vector export for Java(R) Graphics2D * * (C) Copyright 2010-2017 Erich Seifert , * Michael Seifert * * This file is part of VectorGraphics2D. * * VectorGraphics2D is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * VectorGraphics2D 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with VectorGraphics2D. If not, see . */ package de.erichseifert.vectorgraphics2d; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.core.IsNull.notNullValue; import static org.junit.Assert.assertThat; import java.util.Arrays; import java.util.List; import org.junit.Test; import org.junit.experimental.theories.DataPoints; import org.junit.experimental.theories.Theories; import org.junit.experimental.theories.Theory; import org.junit.runner.RunWith; @RunWith(Theories.class) public class ProcessorsTest { @Test(expected = NullPointerException.class) public void testGetThrowsNullPointerExceptionWhenNullIsPassed() { Processors.get(null); } @Test(expected = IllegalArgumentException.class) public void testGetThrowsIllegalArgumentExceptionWhenFormatIsUnknown() { Processors.get("UnknownFormat"); } @DataPoints public static List KNOWN_FORMATS = Arrays.asList("eps", "pdf", "svg"); @Theory public void testGetReturnsNonNullWhenFormatIsKnown(String format) { Processor processor = Processors.get(format); assertThat(processor, is(notNullValue())); } } vectorgraphics2d-0.13/src/test/java/de/erichseifert/vectorgraphics2d/TestUtils.java000066400000000000000000000217331347274514600305400ustar00rootroot00000000000000/* * VectorGraphics2D: Vector export for Java(R) Graphics2D * * (C) Copyright 2010-2017 Erich Seifert , * Michael Seifert * * This file is part of VectorGraphics2D. * * VectorGraphics2D is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * VectorGraphics2D 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with VectorGraphics2D. If not, see . */ package de.erichseifert.vectorgraphics2d; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import java.util.Collections; import java.util.IdentityHashMap; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.TreeMap; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Utility class for unit tests. */ public abstract class TestUtils { protected TestUtils() { throw new UnsupportedOperationException(); } public static class Template extends LinkedList { public Template(Object... lines) { Collections.addAll(this, lines); } public Template(Template... templates) { for (Template template : templates) { addAll(template); } } } public static class XMLFragment { private static final Pattern CDATA = Pattern.compile("\\s*"); private static final Pattern COMMENT = Pattern.compile("\\s*"); private static final Pattern TAG_BEGIN = Pattern.compile("\\s*<([/?!])?\\s*([^\\s>/?]+)"); private static final Pattern TAG_END = Pattern.compile("\\s*([/?])?>"); private static final Pattern TAG_ATTRIBUTE = Pattern.compile("\\s*([^\\s>=]+)=(\"[^\"]*\"|'[^']*')"); private static final Pattern DOCTYPE_PART = Pattern.compile("\\s*(\"[^\"]*\"|'[^']*'|[^\\s>]+)"); public enum FragmentType { START_TAG, END_TAG, EMPTY_ELEMENT, CDATA, DECLARATION, DOCTYPE, COMMENT } public final String name; public final FragmentType type; public final Map attributes; public final int matchStart; public final int matchEnd; public XMLFragment(String name, FragmentType type, Map attributes, int matchStart, int matchEnd) { this.name = name; this.type = type; this.attributes = Collections.unmodifiableMap( new TreeMap<>(attributes)); this.matchStart = matchStart; this.matchEnd = matchEnd; } public static XMLFragment parse(String xmlString, int matchStart) { Map attrs = new IdentityHashMap<>(); Matcher cdataMatch = CDATA.matcher(xmlString); cdataMatch.region(matchStart, xmlString.length()); if (cdataMatch.lookingAt()) { attrs.put("value", cdataMatch.group(1)); return new XMLFragment("", FragmentType.CDATA, attrs, matchStart, cdataMatch.end()); } Matcher commentMatch = COMMENT.matcher(xmlString); commentMatch.region(matchStart, xmlString.length()); if (commentMatch.lookingAt()) { attrs.put("value", commentMatch.group(1).trim()); return new XMLFragment("", FragmentType.COMMENT, attrs, matchStart, commentMatch.end()); } Matcher beginMatch = TAG_BEGIN.matcher(xmlString); beginMatch.region(matchStart, xmlString.length()); if (!beginMatch.lookingAt()) { return null; } int matchEndPrev = beginMatch.end(); String modifiers = beginMatch.group(1); String name = beginMatch.group(2); boolean endTag = "/".equals(modifiers); boolean declarationStart = "?".equals(modifiers); boolean doctype = "!".equals(modifiers) && "DOCTYPE".equals(name); if (doctype) { int partNo = 0; while (true) { Matcher attrMatch = DOCTYPE_PART.matcher(xmlString); attrMatch.region(matchEndPrev, xmlString.length()); if (!attrMatch.lookingAt()) { break; } matchEndPrev = attrMatch.end(); String partValue = attrMatch.group(1); if (partValue.startsWith("\"") || partValue.startsWith("'")) { partValue = partValue.substring(1, partValue.length() - 1); } String partId = String.format("doctype %02d", partNo++); attrs.put(partId, partValue); } } else { while (true) { Matcher attrMatch = TAG_ATTRIBUTE.matcher(xmlString); attrMatch.region(matchEndPrev, xmlString.length()); if (!attrMatch.lookingAt()) { break; } matchEndPrev = attrMatch.end(); String attrName = attrMatch.group(1); String attrValue = attrMatch.group(2); attrValue = attrValue.substring(1, attrValue.length() - 1); attrs.put(attrName, attrValue); } } Matcher endMatch = TAG_END.matcher(xmlString); endMatch.region(matchEndPrev, xmlString.length()); if (!endMatch.lookingAt()) { throw new AssertionError(String.format("No tag end found: %s", xmlString.substring(0, matchEndPrev))); } matchEndPrev = endMatch.end(); modifiers = endMatch.group(1); boolean emptyElement = "/".equals(modifiers); boolean declarationEnd = "?".equals(modifiers); FragmentType type = FragmentType.START_TAG; if (endTag) { type = FragmentType.END_TAG; } else if (emptyElement) { type = FragmentType.EMPTY_ELEMENT; } else if (declarationStart && declarationEnd) { type = FragmentType.DECLARATION; } else if (doctype) { type = FragmentType.DOCTYPE; } return new XMLFragment(name, type, attrs, matchStart, matchEndPrev); } @Override public boolean equals(Object o) { if (!(o instanceof XMLFragment)) { return false; } XMLFragment frag = (XMLFragment) o; if (!type.equals(frag.type) || !name.equals(frag.name)) { return false; } Iterator> itThis = attributes.entrySet().iterator(); Iterator> itFrag = frag.attributes.entrySet().iterator(); while (itThis.hasNext() && itFrag.hasNext()) { Map.Entry attrThis = itThis.next(); Map.Entry attrFrag = itFrag.next(); if (!attrThis.getKey().equals(attrFrag.getKey()) || !attrThis.getValue().equals(attrFrag.getValue())) { return false; } } return true; } @Override public String toString() { StringBuilder s = new StringBuilder("<"); if (FragmentType.END_TAG.equals(type)) { s.append("/"); } else if (FragmentType.DECLARATION.equals(type)) { s.append("?"); } if (FragmentType.DOCTYPE.equals(type)) { s.append("!").append(name); for (String partValue : attributes.values()) { s.append(" ").append(partValue); } } else { s.append(name); for (Map.Entry attr : attributes.entrySet()) { s.append(" ").append(attr.getKey()).append("=\"").append(attr.getValue()).append("\""); } } if (FragmentType.DECLARATION.equals(type)) { s.append("?"); } s.append(">"); return s.toString(); } } public static void assertTemplateEquals(Template expected, Template actual) { Iterator itExpected = expected.iterator(); Iterator itActual = actual.iterator(); while (itExpected.hasNext() && itActual.hasNext()) { Object lineExpected = itExpected.next(); Object lineActual = itActual.next(); if (lineExpected == null) { continue; } assertTrue(String.format("Line is of type %s, expected String.", lineActual.getClass()), lineActual instanceof String); if (lineExpected instanceof String) { assertEquals(lineExpected, lineActual); } else if (lineExpected instanceof Pattern) { Pattern expectedPattern = (Pattern) lineExpected; Matcher matcher = expectedPattern.matcher((String) lineActual); assertTrue(String.format( "Line didn't match pattern.\nExpected: \"%s\"\nActual: \"%s\"", matcher.pattern(), lineActual), matcher.matches()); } } assertEquals("Wrong number of lines in template.", expected.size(), actual.size()); } private static List parseXML(String xmlString) { XMLFragment frag; List fragments = new LinkedList<>(); int startPos = 0; while ((frag = XMLFragment.parse(xmlString, startPos)) != null) { fragments.add(frag); startPos = frag.matchEnd; } return fragments; } public static void assertXMLEquals(String expected, String actual) { List expectedFrags = parseXML(expected); List actualFrags = parseXML(actual); Iterator itExpected = expectedFrags.iterator(); Iterator itActual = actualFrags.iterator(); while (itExpected.hasNext() && itActual.hasNext()) { XMLFragment expectedFrag = itExpected.next(); XMLFragment actualFrag = itActual.next(); assertEquals(expectedFrag, actualFrag); } assertEquals(expectedFrags.size(), actualFrags.size()); } } vectorgraphics2d-0.13/src/test/java/de/erichseifert/vectorgraphics2d/TestUtilsTest.java000066400000000000000000000164571347274514600314070ustar00rootroot00000000000000/* * VectorGraphics2D: Vector export for Java(R) Graphics2D * * (C) Copyright 2010-2017 Erich Seifert , * Michael Seifert * * This file is part of VectorGraphics2D. * * VectorGraphics2D is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * VectorGraphics2D 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with VectorGraphics2D. If not, see . */ package de.erichseifert.vectorgraphics2d; import org.junit.Test; import static de.erichseifert.vectorgraphics2d.TestUtils.XMLFragment; import static de.erichseifert.vectorgraphics2d.TestUtils.XMLFragment.FragmentType; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; public class TestUtilsTest { @Test public void testParseXmlStartTag() throws Exception { String xmlTagName = "foo:bar.baz_tag"; String xmlString; XMLFragment frag; xmlString = "<"+xmlTagName+">"; frag = XMLFragment.parse(xmlString, 0); assertEquals(xmlTagName, frag.name); assertEquals(FragmentType.START_TAG, frag.type); assertTrue(frag.attributes.isEmpty()); assertEquals(0, frag.matchStart); assertEquals(xmlString.length(), frag.matchEnd); xmlString = "< "+xmlTagName+" >"; frag = XMLFragment.parse(xmlString, 0); assertEquals(xmlTagName, frag.name); assertEquals(FragmentType.START_TAG, frag.type); assertTrue(frag.attributes.isEmpty()); assertEquals(0, frag.matchStart); assertEquals(xmlString.length(), frag.matchEnd); } @Test public void testParseXmlEndTag() throws Exception { String xmlTagName = "foo:bar.baz_tag"; String xmlString; XMLFragment frag; xmlString = ""; frag = XMLFragment.parse(xmlString, 0); assertEquals(xmlTagName, frag.name); assertEquals(FragmentType.END_TAG, frag.type); assertTrue(frag.attributes.isEmpty()); assertEquals(0, frag.matchStart); assertEquals(xmlString.length(), frag.matchEnd); xmlString = ""; frag = XMLFragment.parse(xmlString, 0); assertEquals(xmlTagName, frag.name); assertEquals(FragmentType.END_TAG, frag.type); assertTrue(frag.attributes.isEmpty()); assertEquals(0, frag.matchStart); assertEquals(xmlString.length(), frag.matchEnd); } @Test public void testParseXmlEmptyElement() throws Exception { String xmlTagName = "foo:bar.baz_tag"; String xmlString; XMLFragment frag; xmlString = "<"+xmlTagName+"/>"; frag = XMLFragment.parse(xmlString, 0); assertEquals(xmlTagName, frag.name); assertEquals(FragmentType.EMPTY_ELEMENT, frag.type); assertTrue(frag.attributes.isEmpty()); assertEquals(0, frag.matchStart); assertEquals(xmlString.length(), frag.matchEnd); xmlString = "< "+xmlTagName+" />"; frag = XMLFragment.parse(xmlString, 0); assertEquals(xmlTagName, frag.name); assertEquals(FragmentType.EMPTY_ELEMENT, frag.type); assertTrue(frag.attributes.isEmpty()); assertEquals(0, frag.matchStart); assertEquals(xmlString.length(), frag.matchEnd); } @Test public void testParseXmlCDATA() throws Exception { String xmlString; XMLFragment frag; xmlString = ""; frag = XMLFragment.parse(xmlString, 0); assertEquals("", frag.name); assertEquals(FragmentType.CDATA, frag.type); assertEquals("foo bar", frag.attributes.get("value")); assertEquals(0, frag.matchStart); assertEquals(xmlString.length(), frag.matchEnd); xmlString = "foo bar]]>"; frag = XMLFragment.parse(xmlString, 0); assertEquals("", frag.name); assertEquals(FragmentType.CDATA, frag.type); assertEquals("foo bar", frag.attributes.get("value")); assertEquals(0, frag.matchStart); assertEquals(xmlString.length(), frag.matchEnd); } @Test public void testParseXmlDeclaration() throws Exception { String xmlString; XMLFragment frag; xmlString = ""; frag = XMLFragment.parse(xmlString, 0); assertEquals("xml", frag.name); assertEquals(FragmentType.DECLARATION, frag.type); assertEquals("1.0", frag.attributes.get("version")); assertEquals("UTF-8", frag.attributes.get("encoding")); assertEquals(0, frag.matchStart); assertEquals(xmlString.length(), frag.matchEnd); } @Test public void testParseXmlDoctype() throws Exception { String xmlString; XMLFragment frag; xmlString = ""; frag = XMLFragment.parse(xmlString, 0); assertEquals(FragmentType.DOCTYPE, frag.type); assertEquals("html", frag.attributes.get("doctype 00")); assertEquals(0, frag.matchStart); assertEquals(xmlString.length(), frag.matchEnd); xmlString = ""; frag = XMLFragment.parse(xmlString, 0); assertEquals(FragmentType.DOCTYPE, frag.type); assertEquals("svg", frag.attributes.get("doctype 00")); assertEquals("PUBLIC", frag.attributes.get("doctype 01")); assertEquals("-//W3C//DTD SVG 1.1 Tiny//EN", frag.attributes.get("doctype 02")); assertEquals("http://www.w3.org/Graphics/SVG/1.1/DTD/svg11-tiny.dtd", frag.attributes.get("doctype 03")); assertEquals(0, frag.matchStart); assertEquals(xmlString.length(), frag.matchEnd); } @Test public void testParseXmlComment() throws Exception { String xmlString; XMLFragment frag; xmlString = ""; frag = XMLFragment.parse(xmlString, 0); assertEquals("", frag.name); assertEquals(FragmentType.COMMENT, frag.type); assertEquals("foo bar", frag.attributes.get("value")); assertEquals(0, frag.matchStart); assertEquals(xmlString.length(), frag.matchEnd); xmlString = ""; frag = XMLFragment.parse(xmlString, 0); assertEquals("", frag.name); assertEquals(FragmentType.COMMENT, frag.type); assertEquals("foo bar", frag.attributes.get("value")); assertEquals(0, frag.matchStart); assertEquals(xmlString.length(), frag.matchEnd); } @Test public void testParseXMLAttributesTag() throws Exception { String xmlTagName = "foo:bar.baz_tag"; String xmlString; XMLFragment frag; xmlString = "<"+xmlTagName+" foo='bar'>"; frag = XMLFragment.parse(xmlString, 0); assertEquals(xmlTagName, frag.name); assertEquals("bar", frag.attributes.get("foo")); assertEquals(0, frag.matchStart); assertEquals(xmlString.length(), frag.matchEnd); xmlString = "<"+xmlTagName+" foo=\"bar\">"; frag = XMLFragment.parse(xmlString, 0); assertEquals(xmlTagName, frag.name); assertEquals("bar", frag.attributes.get("foo")); assertEquals(0, frag.matchStart); assertEquals(xmlString.length(), frag.matchEnd); xmlString = "<"+xmlTagName+" foo=\"bar\" baz='qux'>"; frag = XMLFragment.parse(xmlString, 0); assertEquals(xmlTagName, frag.name); assertEquals("bar", frag.attributes.get("foo")); assertEquals("qux", frag.attributes.get("baz")); assertEquals(0, frag.matchStart); assertEquals(xmlString.length(), frag.matchEnd); } } vectorgraphics2d-0.13/src/test/java/de/erichseifert/vectorgraphics2d/VectorGraphics2DTest.java000066400000000000000000000106701347274514600325470ustar00rootroot00000000000000/* * VectorGraphics2D: Vector export for Java(R) Graphics2D * * (C) Copyright 2010-2017 Erich Seifert , * Michael Seifert * * This file is part of VectorGraphics2D. * * VectorGraphics2D is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * VectorGraphics2D 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with VectorGraphics2D. If not, see . */ package de.erichseifert.vectorgraphics2d; import static org.hamcrest.CoreMatchers.instanceOf; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.nullValue; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotEquals; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; import java.awt.Color; import java.awt.geom.Rectangle2D; import java.util.Iterator; import org.junit.Test; import org.junit.experimental.theories.Theories; import org.junit.runner.RunWith; import de.erichseifert.vectorgraphics2d.intermediate.CommandSequence; import de.erichseifert.vectorgraphics2d.intermediate.commands.Command; import de.erichseifert.vectorgraphics2d.intermediate.commands.CreateCommand; import de.erichseifert.vectorgraphics2d.intermediate.commands.DisposeCommand; import de.erichseifert.vectorgraphics2d.util.GraphicsUtils; @RunWith(Theories.class) public class VectorGraphics2DTest { @Test public void testVectorGraphics2DEmitsCreateCommand() { VectorGraphics2D g = new VectorGraphics2D(); CommandSequence commands = g.getCommands(); Iterator> commandIterator = commands.iterator(); assertTrue(commandIterator.hasNext()); Command firstCommand = commandIterator.next(); assertThat(firstCommand, instanceOf(CreateCommand.class)); // TODO: Move this assertion into a separate test case assertEquals(g, ((CreateCommand) firstCommand).getValue()); } @Test public void testCreateEmitsCreateCommand() { VectorGraphics2D g = new VectorGraphics2D(); CommandSequence gCommands = g.getCommands(); Iterator> gCommandIterator = gCommands.iterator(); CreateCommand gCreateCommand = (CreateCommand) gCommandIterator.next(); VectorGraphics2D g2 = (VectorGraphics2D) g.create(); CreateCommand g2CreateCommand = null; for (Command g2Command : g2.getCommands()) { if (g2Command instanceof CreateCommand) { g2CreateCommand = (CreateCommand) g2Command; } } assertNotEquals(gCreateCommand, g2CreateCommand); assertEquals(g2, g2CreateCommand.getValue()); } @Test public void testDisposeCommandEmitted() { VectorGraphics2D g = new VectorGraphics2D(); g.setColor(Color.RED); VectorGraphics2D g2 = (VectorGraphics2D) g.create(); g2.setColor(Color.BLUE); g2.dispose(); CommandSequence commands = g.getCommands(); Command lastCommand = null; for (Command command : commands) { lastCommand = command; } assertTrue(lastCommand instanceof DisposeCommand); assertEquals(Color.BLUE, ((DisposeCommand) lastCommand).getValue().getColor()); } @Test public void testClipIntersectsClipRectangle() { VectorGraphics2D vg2d = new VectorGraphics2D(); Rectangle2D currentClipShape = new Rectangle2D.Double(5, 10, 20, 30); vg2d.setClip(currentClipShape); Rectangle2D newClipShape = new Rectangle2D.Double(10, 20, 30, 40); vg2d.clip(newClipShape); Rectangle2D intersection = currentClipShape.createIntersection(newClipShape); assertTrue(GraphicsUtils.equals(vg2d.getClip(), intersection)); } @Test public void testClipClearsClippingShapeWhenNullIsPassed() { VectorGraphics2D vg2d = new VectorGraphics2D(); Rectangle2D clipShape = new Rectangle2D.Double(5, 10, 20, 30); vg2d.setClip(clipShape); vg2d.clip(null); assertThat(vg2d.getClip(), is(nullValue())); } @Test public void testSetBackgroundSetsBackgroundColor() { VectorGraphics2D vg2d = new VectorGraphics2D(); Color backgroundColor = Color.DARK_GRAY; vg2d.setBackground(backgroundColor); assertThat(vg2d.getBackground(), is(backgroundColor)); } } vectorgraphics2d-0.13/src/test/java/de/erichseifert/vectorgraphics2d/eps/000077500000000000000000000000001347274514600265165ustar00rootroot00000000000000vectorgraphics2d-0.13/src/test/java/de/erichseifert/vectorgraphics2d/eps/EPSProcessorTest.java000066400000000000000000000077121347274514600325570ustar00rootroot00000000000000/* * VectorGraphics2D: Vector export for Java(R) Graphics2D * * (C) Copyright 2010-2017 Erich Seifert , * Michael Seifert * * This file is part of VectorGraphics2D. * * VectorGraphics2D is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * VectorGraphics2D 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with VectorGraphics2D. If not, see . */ package de.erichseifert.vectorgraphics2d.eps; import static de.erichseifert.vectorgraphics2d.TestUtils.Template; import static de.erichseifert.vectorgraphics2d.TestUtils.assertTemplateEquals; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.regex.Pattern; import org.junit.Test; import de.erichseifert.vectorgraphics2d.Document; import de.erichseifert.vectorgraphics2d.intermediate.MutableCommandSequence; import de.erichseifert.vectorgraphics2d.intermediate.commands.Command; import de.erichseifert.vectorgraphics2d.util.PageSize; public class EPSProcessorTest { private static final String EOL = "\n"; private static final Object[] HEADER = { "%!PS-Adobe-3.0 EPSF-3.0", "%%BoundingBox: 0 28 57 114", "%%HiResBoundingBox: 0.0 28.34645669291339 56.69291338582678 113.38582677165356", "%%LanguageLevel: 3", "%%Pages: 1", "%%EndComments", "%%Page: 1 1", "/M /moveto load def", "/L /lineto load def", "/C /curveto load def", "/Z /closepath load def", "/RL /rlineto load def", "/rgb /setrgbcolor load def", "/cmyk /setcmykcolor load def", "/rect { /height exch def /width exch def /y exch def /x exch def x y M width 0 RL 0 height RL width neg 0 RL } bind def", "/ellipse { /endangle exch def /startangle exch def /ry exch def /rx exch def /y exch def /x exch def /savematrix matrix currentmatrix def x y translate rx ry scale 0 0 1 startangle endangle arcn savematrix setmatrix } bind def", "/imgdict { /datastream exch def /hasdata exch def /decodeScale exch def /bits exch def /bands exch def /imgheight exch def /imgwidth exch def << /ImageType 1 /Width imgwidth /Height imgheight /BitsPerComponent bits /Decode [bands {0 decodeScale} repeat] ", "/ImageMatrix [imgwidth 0 0 imgheight 0 0] hasdata { /DataSource datastream } if >> } bind def", "/latinize { /fontName exch def /fontNameNew exch def fontName findfont 0 dict copy begin /Encoding ISOLatin1Encoding def fontNameNew /FontName def currentdict end dup /FID undef fontNameNew exch definefont pop } bind def", Pattern.compile("/\\S+?Lat /\\S+ latinize /\\S+?Lat 12.0 selectfont"), "gsave", "clipsave", "/DeviceRGB setcolorspace", "0 85.03937007874016 translate", "2.834645669291339 -2.834645669291339 scale", "/basematrix matrix currentmatrix def", "%%EOF" }; private static final PageSize PAGE_SIZE = new PageSize(0.0, 10.0, 20.0, 30.0); private final EPSProcessor epsProcessor = new EPSProcessor(); private final ByteArrayOutputStream bytes = new ByteArrayOutputStream(); private String process(Command... commands) throws IOException { MutableCommandSequence sequence = new MutableCommandSequence(); for (Command command : commands) { sequence.add(command); } Document processed = epsProcessor.getDocument(sequence, PAGE_SIZE); processed.writeTo(bytes); return bytes.toString("ISO-8859-1"); } @Test public void envelopeForEmptyDocument() throws IOException { String result = process(); Template actual = new Template((Object[]) result.split(EOL)); Template expected = new Template(HEADER); assertTemplateEquals(expected, actual); } } vectorgraphics2d-0.13/src/test/java/de/erichseifert/vectorgraphics2d/eps/EPSTests.java000066400000000000000000000021441347274514600310340ustar00rootroot00000000000000/* * VectorGraphics2D: Vector export for Java(R) Graphics2D * * (C) Copyright 2010-2017 Erich Seifert , * Michael Seifert * * This file is part of VectorGraphics2D. * * VectorGraphics2D is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * VectorGraphics2D 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with VectorGraphics2D. If not, see . */ package de.erichseifert.vectorgraphics2d.eps; import org.junit.runner.RunWith; import org.junit.runners.Suite; @RunWith(Suite.class) @Suite.SuiteClasses({ EPSProcessorTest.class }) public class EPSTests { } vectorgraphics2d-0.13/src/test/java/de/erichseifert/vectorgraphics2d/intermediate/000077500000000000000000000000001347274514600304015ustar00rootroot00000000000000vectorgraphics2d-0.13/src/test/java/de/erichseifert/vectorgraphics2d/intermediate/IRTests.java000066400000000000000000000023251347274514600326030ustar00rootroot00000000000000/* * VectorGraphics2D: Vector export for Java(R) Graphics2D * * (C) Copyright 2010-2017 Erich Seifert , * Michael Seifert * * This file is part of VectorGraphics2D. * * VectorGraphics2D is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * VectorGraphics2D 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with VectorGraphics2D. If not, see . */ package de.erichseifert.vectorgraphics2d.intermediate; import org.junit.runner.RunWith; import org.junit.runners.Suite; import de.erichseifert.vectorgraphics2d.intermediate.filters.FilterTests; @RunWith(Suite.class) @Suite.SuiteClasses({ MutableCommandSequenceTest.class, FilterTests.class }) public class IRTests { } MutableCommandSequenceTest.java000066400000000000000000000026551347274514600364160ustar00rootroot00000000000000vectorgraphics2d-0.13/src/test/java/de/erichseifert/vectorgraphics2d/intermediate/* * VectorGraphics2D: Vector export for Java(R) Graphics2D * * (C) Copyright 2010-2017 Erich Seifert , * Michael Seifert * * This file is part of VectorGraphics2D. * * VectorGraphics2D is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * VectorGraphics2D 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with VectorGraphics2D. If not, see . */ package de.erichseifert.vectorgraphics2d.intermediate; import static org.hamcrest.CoreMatchers.hasItem; import static org.junit.Assert.assertThat; import org.junit.Test; import de.erichseifert.vectorgraphics2d.intermediate.commands.Command; public class MutableCommandSequenceTest { @Test public void testIteratorContainsAddedCommands() { MutableCommandSequence commands = new MutableCommandSequence(); Command command = new Command(null) {}; commands.add(command); assertThat(commands, hasItem(command)); } } vectorgraphics2d-0.13/src/test/java/de/erichseifert/vectorgraphics2d/intermediate/filters/000077500000000000000000000000001347274514600320515ustar00rootroot00000000000000AbsoluteToRelativeTransformsFilterTest.java000066400000000000000000000114761347274514600425100ustar00rootroot00000000000000vectorgraphics2d-0.13/src/test/java/de/erichseifert/vectorgraphics2d/intermediate/filters/* * VectorGraphics2D: Vector export for Java(R) Graphics2D * * (C) Copyright 2010-2017 Erich Seifert , * Michael Seifert * * This file is part of VectorGraphics2D. * * VectorGraphics2D is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * VectorGraphics2D 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with VectorGraphics2D. If not, see . */ package de.erichseifert.vectorgraphics2d.intermediate.filters; import static org.hamcrest.CoreMatchers.any; import static org.hamcrest.CoreMatchers.hasItem; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.not; import static org.junit.Assert.assertThat; import java.awt.geom.AffineTransform; import org.junit.Test; import de.erichseifert.vectorgraphics2d.intermediate.CommandSequence; import de.erichseifert.vectorgraphics2d.intermediate.MutableCommandSequence; import de.erichseifert.vectorgraphics2d.intermediate.commands.Command; import de.erichseifert.vectorgraphics2d.intermediate.commands.CreateCommand; import de.erichseifert.vectorgraphics2d.intermediate.commands.DisposeCommand; import de.erichseifert.vectorgraphics2d.intermediate.commands.SetTransformCommand; import de.erichseifert.vectorgraphics2d.intermediate.commands.TransformCommand; import de.erichseifert.vectorgraphics2d.intermediate.commands.TranslateCommand; public class AbsoluteToRelativeTransformsFilterTest { @Test public void testSetTransformCommandReplaced() { AffineTransform absoluteTransform = new AffineTransform(); absoluteTransform.rotate(42.0); absoluteTransform.translate(4.0, 2.0); CommandSequence commands = wrapCommands( new SetTransformCommand(absoluteTransform) ); AbsoluteToRelativeTransformsFilter filter = new AbsoluteToRelativeTransformsFilter(commands); assertThat(filter, not(hasItem(any(SetTransformCommand.class)))); } @Test public void testAbsoluteAndRelativeTransformsIdentical() { AffineTransform absoluteTransform = new AffineTransform(); absoluteTransform.rotate(42.0); absoluteTransform.translate(4.0, 2.0); CommandSequence commands = wrapCommands( new SetTransformCommand(absoluteTransform) ); AbsoluteToRelativeTransformsFilter filter = new AbsoluteToRelativeTransformsFilter(commands); filter.next(); AffineTransform relativeTransform = ((TransformCommand) filter.next()).getValue(); assertThat(relativeTransform, is(absoluteTransform)); } @Test public void testTranslateCorrect() { AffineTransform absoluteTransform = new AffineTransform(); absoluteTransform.scale(2.0, 2.0); absoluteTransform.translate(4.2, 4.2); // (8.4, 8.4) CommandSequence commands = wrapCommands( new TranslateCommand(4.0, 2.0), new SetTransformCommand(absoluteTransform) ); AbsoluteToRelativeTransformsFilter filter = new AbsoluteToRelativeTransformsFilter(commands); TransformCommand transformCommand = null; while (filter.hasNext()) { Command filteredCommand = filter.next(); if (filteredCommand instanceof TransformCommand) { transformCommand = (TransformCommand) filteredCommand; } } AffineTransform relativeTransform = transformCommand.getValue(); assertThat(relativeTransform.getTranslateX(), is(4.4)); assertThat(relativeTransform.getTranslateY(), is(6.4)); } @Test public void testRelativeTransformAfterDispose() { AffineTransform absoluteTransform = new AffineTransform(); absoluteTransform.rotate(42.0); absoluteTransform.translate(4.0, 2.0); CommandSequence commands = wrapCommands( new CreateCommand(null), new TransformCommand(absoluteTransform), new DisposeCommand(null), new SetTransformCommand(absoluteTransform) ); AbsoluteToRelativeTransformsFilter filter = new AbsoluteToRelativeTransformsFilter(commands); TransformCommand lastTransformCommand = null; for (Command filteredCommand : filter) { if (filteredCommand instanceof TransformCommand) { lastTransformCommand = (TransformCommand) filteredCommand; } } assertThat(lastTransformCommand.getValue(), is(absoluteTransform)); } private CommandSequence wrapCommands(Command... commands) { MutableCommandSequence commandSequence = new MutableCommandSequence(); commandSequence.add(new CreateCommand(null)); for (Command command : commands) { commandSequence.add(command); } commandSequence.add(new DisposeCommand(null)); return commandSequence; } } FillPaintedShapeAsImageFilterTest.java000066400000000000000000000057561347274514600412630ustar00rootroot00000000000000vectorgraphics2d-0.13/src/test/java/de/erichseifert/vectorgraphics2d/intermediate/filters/* * VectorGraphics2D: Vector export for Java(R) Graphics2D * * (C) Copyright 2010-2017 Erich Seifert , * Michael Seifert * * This file is part of VectorGraphics2D. * * VectorGraphics2D is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * VectorGraphics2D 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with VectorGraphics2D. If not, see . */ package de.erichseifert.vectorgraphics2d.intermediate.filters; import static org.hamcrest.CoreMatchers.any; import static org.hamcrest.CoreMatchers.hasItem; import static org.hamcrest.CoreMatchers.not; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertThat; import java.awt.Color; import java.awt.GradientPaint; import java.awt.geom.Rectangle2D; import java.util.Iterator; import org.junit.Test; import de.erichseifert.vectorgraphics2d.intermediate.MutableCommandSequence; import de.erichseifert.vectorgraphics2d.intermediate.commands.Command; import de.erichseifert.vectorgraphics2d.intermediate.commands.DrawImageCommand; import de.erichseifert.vectorgraphics2d.intermediate.commands.FillShapeCommand; import de.erichseifert.vectorgraphics2d.intermediate.commands.RotateCommand; import de.erichseifert.vectorgraphics2d.intermediate.commands.SetPaintCommand; public class FillPaintedShapeAsImageFilterTest { @Test public void testFillShapeReplacedWithDrawImage() { MutableCommandSequence commands = new MutableCommandSequence(); commands.add(new SetPaintCommand(new GradientPaint(0.0f, 0.0f, Color.BLACK, 100.0f, 100.0f, Color.WHITE))); commands.add(new RotateCommand(10.0, 4.0, 2.0)); commands.add(new FillShapeCommand(new Rectangle2D.Double(10.0, 10.0, 100.0, 100.0))); FillPaintedShapeAsImageFilter filter = new FillPaintedShapeAsImageFilter(commands); assertThat(filter, hasItem(any(DrawImageCommand.class))); assertThat(filter, not(hasItem(any(FillShapeCommand.class)))); } @Test public void testFillShapeNotReplacedWithoutPaintCommand() { MutableCommandSequence commands = new MutableCommandSequence(); commands.add(new RotateCommand(10.0, 4.0, 2.0)); commands.add(new FillShapeCommand(new Rectangle2D.Double(10.0, 10.0, 100.0, 100.0))); FillPaintedShapeAsImageFilter filter = new FillPaintedShapeAsImageFilter(commands); Iterator> filterIterator = filter.iterator(); for (Command command : commands) { assertEquals(command, filterIterator.next()); } assertFalse(filterIterator.hasNext()); } } FilterTests.java000066400000000000000000000023001347274514600351000ustar00rootroot00000000000000vectorgraphics2d-0.13/src/test/java/de/erichseifert/vectorgraphics2d/intermediate/filters/* * VectorGraphics2D: Vector export for Java(R) Graphics2D * * (C) Copyright 2010-2017 Erich Seifert , * Michael Seifert * * This file is part of VectorGraphics2D. * * VectorGraphics2D is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * VectorGraphics2D 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with VectorGraphics2D. If not, see . */ package de.erichseifert.vectorgraphics2d.intermediate.filters; import org.junit.runner.RunWith; import org.junit.runners.Suite; @RunWith(Suite.class) @Suite.SuiteClasses({ StreamingFilterTest.class, GroupingFilterTest.class, FillPaintedShapeAsImageFilterTest.class }) public class FilterTests { } GroupingFilterTest.java000066400000000000000000000063631347274514600364450ustar00rootroot00000000000000vectorgraphics2d-0.13/src/test/java/de/erichseifert/vectorgraphics2d/intermediate/filters/* * VectorGraphics2D: Vector export for Java(R) Graphics2D * * (C) Copyright 2010-2017 Erich Seifert , * Michael Seifert * * This file is part of VectorGraphics2D. * * VectorGraphics2D is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * VectorGraphics2D 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with VectorGraphics2D. If not, see . */ package de.erichseifert.vectorgraphics2d.intermediate.filters; import static org.junit.Assert.assertEquals; import java.awt.BasicStroke; import java.awt.Color; import java.awt.geom.AffineTransform; import java.awt.geom.Line2D; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import org.junit.Test; import de.erichseifert.vectorgraphics2d.intermediate.MutableCommandSequence; import de.erichseifert.vectorgraphics2d.intermediate.commands.Command; import de.erichseifert.vectorgraphics2d.intermediate.commands.DrawShapeCommand; import de.erichseifert.vectorgraphics2d.intermediate.commands.Group; import de.erichseifert.vectorgraphics2d.intermediate.commands.SetColorCommand; import de.erichseifert.vectorgraphics2d.intermediate.commands.SetStrokeCommand; import de.erichseifert.vectorgraphics2d.intermediate.commands.SetTransformCommand; import de.erichseifert.vectorgraphics2d.intermediate.commands.StateCommand; public class GroupingFilterTest { @Test public void filtered() { MutableCommandSequence resultStream = new MutableCommandSequence(); resultStream.add(new SetColorCommand(Color.BLACK)); resultStream.add(new SetStrokeCommand(new BasicStroke(1f))); resultStream.add(new DrawShapeCommand(new Line2D.Double(0.0, 1.0, 10.0, 11.0))); resultStream.add(new SetTransformCommand(AffineTransform.getTranslateInstance(5.0, 5.0))); resultStream.add(new DrawShapeCommand(new Line2D.Double(0.0, 1.0, 5.0, 6.0))); List> expectedStream = new LinkedList<>(); Iterator> resultCloneIterator = resultStream.iterator(); Group group1 = new Group(); group1.add(resultCloneIterator.next()); group1.add(resultCloneIterator.next()); expectedStream.add(group1); expectedStream.add(resultCloneIterator.next()); Group group2 = new Group(); group2.add(resultCloneIterator.next()); expectedStream.add(group2); expectedStream.add(resultCloneIterator.next()); Iterator> expectedIterator = expectedStream.iterator(); StreamingFilter resultIterator = new GroupingFilter(resultStream) { @Override protected boolean isGrouped(Command command) { return command instanceof StateCommand; } }; for (; resultIterator.hasNext() || expectedIterator.hasNext();) { Command result = resultIterator.next(); Command expected = expectedIterator.next(); assertEquals(expected, result); } } } StreamingFilterTest.java000066400000000000000000000105141347274514600365750ustar00rootroot00000000000000vectorgraphics2d-0.13/src/test/java/de/erichseifert/vectorgraphics2d/intermediate/filters/* * VectorGraphics2D: Vector export for Java(R) Graphics2D * * (C) Copyright 2010-2017 Erich Seifert , * Michael Seifert * * This file is part of VectorGraphics2D. * * VectorGraphics2D is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * VectorGraphics2D 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with VectorGraphics2D. If not, see . */ package de.erichseifert.vectorgraphics2d.intermediate.filters; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import java.awt.BasicStroke; import java.awt.Color; import java.awt.geom.AffineTransform; import java.awt.geom.Line2D; import java.util.Arrays; import java.util.Collections; import java.util.Iterator; import java.util.List; import org.junit.Test; import de.erichseifert.vectorgraphics2d.intermediate.MutableCommandSequence; import de.erichseifert.vectorgraphics2d.intermediate.commands.Command; import de.erichseifert.vectorgraphics2d.intermediate.commands.DrawShapeCommand; import de.erichseifert.vectorgraphics2d.intermediate.commands.SetColorCommand; import de.erichseifert.vectorgraphics2d.intermediate.commands.SetStrokeCommand; import de.erichseifert.vectorgraphics2d.intermediate.commands.SetTransformCommand; public class StreamingFilterTest { @Test public void filterNone() { MutableCommandSequence stream = new MutableCommandSequence(); stream.add(new SetColorCommand(Color.BLACK)); stream.add(new SetStrokeCommand(new BasicStroke(1f))); stream.add(new DrawShapeCommand(new Line2D.Double(0.0, 1.0, 10.0, 11.0))); stream.add(new SetTransformCommand(AffineTransform.getTranslateInstance(5.0, 5.0))); stream.add(new DrawShapeCommand(new Line2D.Double(0.0, 1.0, 5.0, 6.0))); Iterator> unfiltered = stream.iterator(); StreamingFilter filtered = new StreamingFilter(stream) { @Override protected List> filter(Command command) { return Collections.>singletonList(command); } }; while (filtered.hasNext() || unfiltered.hasNext()) { Command expected = unfiltered.next(); Command result = filtered.next(); assertEquals(expected, result); } } @Test public void filterAll() { MutableCommandSequence stream = new MutableCommandSequence(); stream.add(new SetColorCommand(Color.BLACK)); stream.add(new SetStrokeCommand(new BasicStroke(1f))); stream.add(new DrawShapeCommand(new Line2D.Double(0.0, 1.0, 10.0, 11.0))); stream.add(new SetTransformCommand(AffineTransform.getTranslateInstance(5.0, 5.0))); stream.add(new DrawShapeCommand(new Line2D.Double(0.0, 1.0, 5.0, 6.0))); Iterator> unfiltered = stream.iterator(); StreamingFilter filtered = new StreamingFilter(stream) { @Override protected List> filter(Command command) { return null; } }; assertTrue(unfiltered.hasNext()); assertFalse(filtered.hasNext()); } @Test public void duplicate() { MutableCommandSequence stream = new MutableCommandSequence(); stream.add(new SetColorCommand(Color.BLACK)); stream.add(new SetStrokeCommand(new BasicStroke(1f))); stream.add(new DrawShapeCommand(new Line2D.Double(0.0, 1.0, 10.0, 11.0))); stream.add(new SetTransformCommand(AffineTransform.getTranslateInstance(5.0, 5.0))); stream.add(new DrawShapeCommand(new Line2D.Double(0.0, 1.0, 5.0, 6.0))); Iterator> unfiltered = stream.iterator(); StreamingFilter filtered = new StreamingFilter(stream) { @Override protected List> filter(Command command) { return Arrays.asList(command, command); } }; while (filtered.hasNext() || unfiltered.hasNext()) { Command expected = unfiltered.next(); Command result1 = filtered.next(); Command result2 = filtered.next(); assertEquals(expected, result1); assertEquals(expected, result2); } } } vectorgraphics2d-0.13/src/test/java/de/erichseifert/vectorgraphics2d/package-info.java000077500000000000000000000017741347274514600311320ustar00rootroot00000000000000/* * VectorGraphics2D: Vector export for Java(R) Graphics2D * * (C) Copyright 2010-2017 Erich Seifert , * Michael Seifert * * This file is part of VectorGraphics2D. * * VectorGraphics2D is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * VectorGraphics2D 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with VectorGraphics2D. If not, see . */ /** * Unit tests for main classes. */ package de.erichseifert.vectorgraphics2d; vectorgraphics2d-0.13/src/test/java/de/erichseifert/vectorgraphics2d/pdf/000077500000000000000000000000001347274514600265005ustar00rootroot00000000000000vectorgraphics2d-0.13/src/test/java/de/erichseifert/vectorgraphics2d/pdf/PDFDocumentTest.java000066400000000000000000000067531347274514600323260ustar00rootroot00000000000000/* * VectorGraphics2D: Vector export for Java(R) Graphics2D * * (C) Copyright 2010-2017 Erich Seifert , * Michael Seifert * * This file is part of VectorGraphics2D. * * VectorGraphics2D is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * VectorGraphics2D 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with VectorGraphics2D. If not, see . */ package de.erichseifert.vectorgraphics2d.pdf; import static org.junit.Assert.assertArrayEquals; import java.io.ByteArrayOutputStream; import java.io.IOException; import org.junit.Test; import de.erichseifert.vectorgraphics2d.util.FormattingWriter; public class PDFDocumentTest { public static final String PDF_CHARSET = "ISO-8859-1"; public static final String PDF_EOL = "\n"; @Test public void testSerializeTrueTypeFont() throws IOException { String encoding = "CustomEncoding"; String baseFont = "MyBaseFont"; TrueTypeFont font = new TrueTypeFont(encoding, baseFont); byte[] serialized = PDFDocument.serialize(font); ByteArrayOutputStream expected = new ByteArrayOutputStream(); FormattingWriter expectedString = new FormattingWriter(expected, PDF_CHARSET, PDF_EOL); expectedString.writeln("<<"); expectedString.writeln("/Type /Font"); expectedString.writeln("/Subtype /TrueType"); expectedString.write("/Encoding /").writeln(encoding); expectedString.write("/BaseFont /").writeln(baseFont); expectedString.write(">>"); assertArrayEquals(expected.toByteArray(), serialized); } @Test public void testSerializeStreamWhenStreamIsFiltered() throws IOException { Stream stream = new Stream(Stream.Filter.FLATE); byte[] inputData = new byte[] {4, 2, 42, -1, 0}; stream.write(inputData); stream.close(); byte[] serialized = PDFDocument.serialize(stream); ByteArrayOutputStream expected = new ByteArrayOutputStream(); FormattingWriter expectedString = new FormattingWriter(expected, PDF_CHARSET, PDF_EOL); expectedString.writeln("<<"); expectedString.write("/Length ").writeln(stream.getLength()); expectedString.writeln("/Filter /FlateDecode"); expectedString.writeln(">>"); expectedString.writeln("stream"); expectedString.writeln(stream.getContent()); expectedString.write("endstream"); assertArrayEquals(expected.toByteArray(), serialized); } @Test public void testSerializeStreamWhenStreamIsNotFiltered() throws IOException { Stream stream = new Stream(); byte[] inputData = new byte[] {4, 2, 42, -1, 0}; stream.write(inputData); stream.close(); byte[] serialized = PDFDocument.serialize(stream); ByteArrayOutputStream expected = new ByteArrayOutputStream(); FormattingWriter expectedString = new FormattingWriter(expected, PDF_CHARSET, PDF_EOL); expectedString.writeln("<<"); expectedString.write("/Length ").writeln(stream.getLength()); expectedString.writeln(">>"); expectedString.writeln("stream"); expectedString.writeln(stream.getContent()); expectedString.write("endstream"); assertArrayEquals(expected.toByteArray(), serialized); } } vectorgraphics2d-0.13/src/test/java/de/erichseifert/vectorgraphics2d/pdf/PDFProcessorTest.java000066400000000000000000000072071347274514600325220ustar00rootroot00000000000000/* * VectorGraphics2D: Vector export for Java(R) Graphics2D * * (C) Copyright 2010-2017 Erich Seifert , * Michael Seifert * * This file is part of VectorGraphics2D. * * VectorGraphics2D is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * VectorGraphics2D 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with VectorGraphics2D. If not, see . */ package de.erichseifert.vectorgraphics2d.pdf; import static de.erichseifert.vectorgraphics2d.TestUtils.Template; import static de.erichseifert.vectorgraphics2d.TestUtils.assertTemplateEquals; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.regex.Pattern; import org.junit.Test; import de.erichseifert.vectorgraphics2d.Document; import de.erichseifert.vectorgraphics2d.intermediate.MutableCommandSequence; import de.erichseifert.vectorgraphics2d.intermediate.commands.Command; import de.erichseifert.vectorgraphics2d.util.PageSize; public class PDFProcessorTest { private static final String EOL = "\n"; private static final String HEADER = "%PDF-1.4"; private static final String FOOTER = "%%EOF"; private static final PageSize PAGE_SIZE = new PageSize(0.0, 10.0, 20.0, 30.0); private final PDFProcessor pdfProcessor = new PDFProcessor(false); private final ByteArrayOutputStream bytes = new ByteArrayOutputStream(); private String process(Command... commands) throws IOException { MutableCommandSequence sequence = new MutableCommandSequence(); for (Command command : commands) { sequence.add(command); } Document processed = pdfProcessor.getDocument(sequence, PAGE_SIZE); processed.writeTo(bytes); return bytes.toString("ISO-8859-1"); } @Test public void envelopeForEmptyDocument() throws IOException { String result = process(); Template actual = new Template((Object[]) result.split(EOL)); Template expected = new Template( HEADER, "1 0 obj", "<<", "/Type /Catalog", "/Pages 2 0 R", ">>", "endobj", "2 0 obj", "<<", "/Type /Pages", "/Kids [3 0 R]", "/Count 1", ">>", "endobj", "3 0 obj", "<<", "/Type /Page", "/Parent 2 0 R", "/MediaBox [0 28.34645669291339 56.69291338582678 85.03937007874016]", "/Contents 4 0 R", "/Resources 5 0 R", ">>", "endobj", "4 0 obj", "<<", "/Length 97", ">>", "stream", "q", "1 1 1 rg 1 1 1 RG", "2.834645669291339 0 0 -2.834645669291339 0 85.03937007874016 cm", "/Fnt0 12 Tf", "Q", "endstream", "endobj", "5 0 obj", "<<", "/ProcSet [/PDF /Text /ImageB /ImageC /ImageI]", "/Font <<", "/Fnt0 <<", "/Type /Font", "/Subtype /TrueType", "/Encoding /WinAnsiEncoding", Pattern.compile("/BaseFont /\\S+"), ">>", ">>", ">>", "endobj", "xref", "0 6", "0000000000 65535 f ", Pattern.compile("\\d{10} 00000 n "), Pattern.compile("\\d{10} 00000 n "), Pattern.compile("\\d{10} 00000 n "), Pattern.compile("\\d{10} 00000 n "), Pattern.compile("\\d{10} 00000 n "), "trailer", "<<", "/Size 6", "/Root 1 0 R", ">>", "startxref", Pattern.compile("[1-9]\\d*"), FOOTER ); assertTemplateEquals(expected, actual); } } vectorgraphics2d-0.13/src/test/java/de/erichseifert/vectorgraphics2d/pdf/PDFTests.java000066400000000000000000000022711347274514600310010ustar00rootroot00000000000000/* * VectorGraphics2D: Vector export for Java(R) Graphics2D * * (C) Copyright 2010-2017 Erich Seifert , * Michael Seifert * * This file is part of VectorGraphics2D. * * VectorGraphics2D is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * VectorGraphics2D 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with VectorGraphics2D. If not, see . */ package de.erichseifert.vectorgraphics2d.pdf; import org.junit.runner.RunWith; import org.junit.runners.Suite; @RunWith(Suite.class) @Suite.SuiteClasses({ PageTreeNodeTest.class, PageTest.class, StreamTest.class, PDFProcessorTest.class, PDFDocumentTest.class }) public class PDFTests { } vectorgraphics2d-0.13/src/test/java/de/erichseifert/vectorgraphics2d/pdf/PageTest.java000066400000000000000000000027311347274514600310620ustar00rootroot00000000000000/* * VectorGraphics2D: Vector export for Java(R) Graphics2D * * (C) Copyright 2010-2017 Erich Seifert , * Michael Seifert * * This file is part of VectorGraphics2D. * * VectorGraphics2D is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * VectorGraphics2D 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with VectorGraphics2D. If not, see . */ package de.erichseifert.vectorgraphics2d.pdf; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; import java.awt.geom.Rectangle2D; import org.junit.Test; public class PageTest { @Test public void testTypeIsPage() { Page page = new Page(null, null, null); String type = page.getType(); assertThat(type, is("Page")); } @Test public void testConstructorSetsMediaBox() { Rectangle2D mediaBox = new Rectangle2D.Double(2, 4, 24, 42); Page page = new Page(null, mediaBox, null); assertThat(page.getMediaBox(), is(mediaBox)); } } vectorgraphics2d-0.13/src/test/java/de/erichseifert/vectorgraphics2d/pdf/PageTreeNodeTest.java000066400000000000000000000047051347274514600325130ustar00rootroot00000000000000/* * VectorGraphics2D: Vector export for Java(R) Graphics2D * * (C) Copyright 2010-2017 Erich Seifert , * Michael Seifert * * This file is part of VectorGraphics2D. * * VectorGraphics2D is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * VectorGraphics2D 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with VectorGraphics2D. If not, see . */ package de.erichseifert.vectorgraphics2d.pdf; import static org.hamcrest.CoreMatchers.hasItem; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; import org.junit.Test; public class PageTreeNodeTest { @Test public void testTypeIsPages() { PageTreeNode pages = new PageTreeNode(null); String type = pages.getType(); assertThat(type, is("Pages")); } @Test public void testConstructorSetsParent() { PageTreeNode parent = new PageTreeNode(null); PageTreeNode pages = new PageTreeNode(parent); assertThat(pages.getParent(), is(parent)); } @Test public void testAddInsertsPage() { PageTreeNode pages = new PageTreeNode(null); Page child = new Page(null, null, null); pages.add(child); assertThat(pages.getKids(), hasItem(child)); } @Test public void testAddSetsParentOfAddedPage() { PageTreeNode pages = new PageTreeNode(null); Page child = new Page(null, null, null); pages.add(child); assertThat(child.getParent(), is(pages)); } @Test public void testCountReturnsZeroWhenEmpty() { PageTreeNode pages = new PageTreeNode(null); int count = pages.getCount(); assertThat(count, is(0)); } @Test public void testCountReturnsNumberOfDirectChildrenWhenOnlyDirectChildrenArePresent() { PageTreeNode pages = new PageTreeNode(null); Page child1 = new Page(null, null, null); Page child2 = new Page(null, null, null); Page child3 = new Page(null, null, null); pages.add(child1); pages.add(child2); pages.add(child3); int count = pages.getCount(); assertThat(count, is(3)); } } vectorgraphics2d-0.13/src/test/java/de/erichseifert/vectorgraphics2d/pdf/StreamTest.java000066400000000000000000000060101347274514600314330ustar00rootroot00000000000000/* * VectorGraphics2D: Vector export for Java(R) Graphics2D * * (C) Copyright 2010-2017 Erich Seifert , * Michael Seifert * * This file is part of VectorGraphics2D. * * VectorGraphics2D is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * VectorGraphics2D 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with VectorGraphics2D. If not, see . */ package de.erichseifert.vectorgraphics2d.pdf; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; import java.io.IOException; import java.util.zip.DataFormatException; import java.util.zip.Inflater; import org.junit.Test; public class StreamTest { @Test(expected = IllegalStateException.class) public void testGetLengthThrowsExceptionWhenStreamIsOpen() { Stream stream = new Stream(); stream.getLength(); } @Test(expected = IllegalStateException.class) public void testGetContentThrowsExceptionWhenStreamIsOpen() { Stream stream = new Stream(); stream.getContent(); } @Test(expected = IOException.class) public void testWriteThrowsExceptionWhenStreamIsClosed() throws IOException { Stream stream = new Stream(); stream.close(); stream.write(new byte[] {42}); } @Test public void testLengthIsZeroOnInitialization() { Stream stream = new Stream(); stream.close(); int length = stream.getLength(); assertThat(length, is(0)); } @Test public void testLengthEqualsByteCountInWrittenDataWhenNoFiltersAreSet() throws IOException { byte[] garbage = new byte[] {4, 2, 42, -1, 0}; Stream stream = new Stream(); stream.write(garbage); stream.close(); int length = stream.getLength(); assertThat(length, is(garbage.length)); } @Test public void testWrittenDataIsIdenticalToStreamContentWhenNoFiltersAreUsed() throws IOException { byte[] data = new byte[] {4, 2, 42, -1, 0}; Stream stream = new Stream(); stream.write(data); stream.close(); byte[] content = stream.getContent(); assertThat(content, is(data)); } @Test public void testContentsAreCompressedWhenFlateFilterIsSet() throws DataFormatException, IOException { byte[] inputData = new byte[] {4, 2, 42, -1, 0}; Stream stream = new Stream(Stream.Filter.FLATE); stream.write(inputData); stream.close(); byte[] compressedContent = stream.getContent(); Inflater decompressor = new Inflater(); decompressor.setInput(compressedContent); byte[] decompressedOutput = new byte[inputData.length]; decompressor.inflate(decompressedOutput); assertThat(decompressedOutput, is(inputData)); } } vectorgraphics2d-0.13/src/test/java/de/erichseifert/vectorgraphics2d/svg/000077500000000000000000000000001347274514600265265ustar00rootroot00000000000000vectorgraphics2d-0.13/src/test/java/de/erichseifert/vectorgraphics2d/svg/SVGProcessorTest.java000066400000000000000000000070131347274514600325710ustar00rootroot00000000000000/* * VectorGraphics2D: Vector export for Java(R) Graphics2D * * (C) Copyright 2010-2017 Erich Seifert , * Michael Seifert * * This file is part of VectorGraphics2D. * * VectorGraphics2D is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * VectorGraphics2D 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with VectorGraphics2D. If not, see . */ package de.erichseifert.vectorgraphics2d.svg; import static de.erichseifert.vectorgraphics2d.TestUtils.assertXMLEquals; import java.awt.geom.Rectangle2D; import java.io.ByteArrayOutputStream; import java.io.IOException; import org.junit.Test; import de.erichseifert.vectorgraphics2d.Document; import de.erichseifert.vectorgraphics2d.intermediate.MutableCommandSequence; import de.erichseifert.vectorgraphics2d.intermediate.commands.Command; import de.erichseifert.vectorgraphics2d.intermediate.commands.DrawShapeCommand; import de.erichseifert.vectorgraphics2d.intermediate.commands.FillShapeCommand; import de.erichseifert.vectorgraphics2d.util.PageSize; public class SVGProcessorTest { private static final String EOL = "\n"; private static final String HEADER = "" + EOL + "" + EOL + "" + EOL; private static final String FOOTER = ""; private static final PageSize PAGE_SIZE = new PageSize(0.0, 10.0, 20.0, 30.0); private final SVGProcessor svgProcessor = new SVGProcessor(); private final ByteArrayOutputStream bytes = new ByteArrayOutputStream(); private String process(Command... commands) throws IOException { MutableCommandSequence sequence = new MutableCommandSequence(); for (Command command : commands) { sequence.add(command); } Document processed = svgProcessor.getDocument(sequence, PAGE_SIZE); processed.writeTo(bytes); return bytes.toString("UTF-8"); } @Test public void envelopeForEmptyDocument() throws Exception { String result = process(); String expected = HEADER.replaceAll(">$", "/>"); assertXMLEquals(expected, result); } @Test public void drawShapeBlack() throws Exception { String result = process( new DrawShapeCommand(new Rectangle2D.Double(1, 2, 3, 4)) ); String expected = HEADER + EOL + " " + EOL + FOOTER; assertXMLEquals(expected, result); } @Test public void fillShapeBlack() throws Exception { String result = process( new FillShapeCommand(new Rectangle2D.Double(1, 2, 3, 4)) ); String expected = HEADER + EOL + " " + EOL + FOOTER; assertXMLEquals(expected, result); } } vectorgraphics2d-0.13/src/test/java/de/erichseifert/vectorgraphics2d/svg/SVGTests.java000066400000000000000000000021441347274514600310540ustar00rootroot00000000000000/* * VectorGraphics2D: Vector export for Java(R) Graphics2D * * (C) Copyright 2010-2017 Erich Seifert , * Michael Seifert * * This file is part of VectorGraphics2D. * * VectorGraphics2D is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * VectorGraphics2D 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with VectorGraphics2D. If not, see . */ package de.erichseifert.vectorgraphics2d.svg; import org.junit.runner.RunWith; import org.junit.runners.Suite; @RunWith(Suite.class) @Suite.SuiteClasses({ SVGProcessorTest.class }) public class SVGTests { } vectorgraphics2d-0.13/src/test/java/de/erichseifert/vectorgraphics2d/util/000077500000000000000000000000001347274514600267045ustar00rootroot00000000000000ASCII85EncodeStreamTest.java000066400000000000000000000053661347274514600336410ustar00rootroot00000000000000vectorgraphics2d-0.13/src/test/java/de/erichseifert/vectorgraphics2d/util/* * VectorGraphics2D: Vector export for Java(R) Graphics2D * * (C) Copyright 2010-2017 Erich Seifert , * Michael Seifert * * This file is part of VectorGraphics2D. * * VectorGraphics2D is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * VectorGraphics2D 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with VectorGraphics2D. If not, see . */ package de.erichseifert.vectorgraphics2d.util; import static org.junit.Assert.assertEquals; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.OutputStream; import org.junit.Test; public class ASCII85EncodeStreamTest { private static void assertEncodedString(String expected, String input) throws IOException { ByteArrayInputStream inputStream = new ByteArrayInputStream(input.getBytes()); ByteArrayOutputStream outStream = new ByteArrayOutputStream(); OutputStream encodeStream = new ASCII85EncodeStream(outStream); byte[] buffer = new byte[1024]; for (int count = inputStream.read(buffer); count >= 0; count = inputStream.read(buffer)) { encodeStream.write(buffer, 0, count); } encodeStream.close(); String encoded = outStream.toString("ISO-8859-1"); assertEquals(expected, encoded); } @Test public void testEncoding() throws IOException { String input = "Man is distinguished, not only by his reason, but by this singular passion " + "from other animals, which is a lust of the mind, that by a perseverance of " + "delight in the continued and indefatigable generation of knowledge, exceeds " + "the short vehemence of any carnal pleasure."; String expected = "9jqo^BlbD-BleB1DJ+*+F(f,q/0JhKFCj@.4Gp$d7F!,L7@<6@)/0JDEF@3BB/F*&OCAfu2/AKYi(DIb:@FD,*)" + "+C]U=@3BN#EcYf8ATD3s@q?d$AftVqCh[NqF-FD5W8ARlolDIal(DIduD.RTpAKYo'+CT/5+Cei#" + "DII?(E,9)oF*2M7/c~>"; assertEncodedString(expected, input); } @Test public void testPadding() throws IOException { assertEncodedString("/c~>", "."); } @Test public void testEmpty() throws IOException { assertEncodedString("~>", ""); } } Base64EncodeStreamTest.java000066400000000000000000000065541347274514600336600ustar00rootroot00000000000000vectorgraphics2d-0.13/src/test/java/de/erichseifert/vectorgraphics2d/util/* * VectorGraphics2D: Vector export for Java(R) Graphics2D * * (C) Copyright 2010-2017 Erich Seifert , * Michael Seifert * * This file is part of VectorGraphics2D. * * VectorGraphics2D is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * VectorGraphics2D 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with VectorGraphics2D. If not, see . */ package de.erichseifert.vectorgraphics2d.util; import static org.junit.Assert.assertEquals; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.OutputStream; import org.junit.Test; public class Base64EncodeStreamTest { private static void assertEncodedString(String expected, String input) throws IOException { ByteArrayInputStream inputStream = new ByteArrayInputStream(input.getBytes()); ByteArrayOutputStream outStream = new ByteArrayOutputStream(); OutputStream encodeStream = new Base64EncodeStream(outStream); byte[] buffer = new byte[1024]; for (int count = inputStream.read(buffer); count >= 0; count = inputStream.read(buffer)) { encodeStream.write(buffer, 0, count); } encodeStream.close(); String encoded = outStream.toString("ISO-8859-1"); assertEquals(expected, encoded); } @Test public void testEncoding() throws IOException { String input = "Man is distinguished, not only by his reason, but by this singular passion " + "from other animals, which is a lust of the mind, that by a perseverance of " + "delight in the continued and indefatigable generation of knowledge, exceeds " + "the short vehemence of any carnal pleasure."; String expected = "TWFuIGlzIGRpc3Rpbmd1aXNoZWQsIG5vdCBvbmx5IGJ5IGhpcyByZWFzb24sIGJ1dCBieSB0aGlz" + "IHNpbmd1bGFyIHBhc3Npb24gZnJvbSBvdGhlciBhbmltYWxzLCB3aGljaCBpcyBhIGx1c3Qgb2Yg" + "dGhlIG1pbmQsIHRoYXQgYnkgYSBwZXJzZXZlcmFuY2Ugb2YgZGVsaWdodCBpbiB0aGUgY29udGlu" + "dWVkIGFuZCBpbmRlZmF0aWdhYmxlIGdlbmVyYXRpb24gb2Yga25vd2xlZGdlLCBleGNlZWRzIHRo" + "ZSBzaG9ydCB2ZWhlbWVuY2Ugb2YgYW55IGNhcm5hbCBwbGVhc3VyZS4="; assertEncodedString(expected, input); } @Test public void testPadding() throws IOException { assertEncodedString("YW55IGNhcm5hbCBwbGVhc3VyZS4=", "any carnal pleasure."); assertEncodedString("YW55IGNhcm5hbCBwbGVhc3VyZQ==", "any carnal pleasure"); assertEncodedString("YW55IGNhcm5hbCBwbGVhc3Vy", "any carnal pleasur"); assertEncodedString("YW55IGNhcm5hbCBwbGVhc3U=", "any carnal pleasu"); assertEncodedString("YW55IGNhcm5hbCBwbGVhcw==", "any carnal pleas"); assertEncodedString("cGxlYXN1cmUu", "pleasure."); assertEncodedString("bGVhc3VyZS4=", "leasure."); assertEncodedString("ZWFzdXJlLg==", "easure."); assertEncodedString("YXN1cmUu", "asure."); assertEncodedString("c3VyZS4=", "sure."); } @Test public void testEmpty() throws IOException { assertEncodedString("", ""); } } vectorgraphics2d-0.13/src/test/java/de/erichseifert/vectorgraphics2d/util/DataUtilsTest.java000066400000000000000000000146021347274514600323040ustar00rootroot00000000000000/* * VectorGraphics2D: Vector export for Java(R) Graphics2D * * (C) Copyright 2010-2017 Erich Seifert , * Michael Seifert * * This file is part of VectorGraphics2D. * * VectorGraphics2D is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * VectorGraphics2D 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with VectorGraphics2D. If not, see . */ package de.erichseifert.vectorgraphics2d.util; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Map; import org.junit.Test; public class DataUtilsTest { @Test public void stripTrailingSpaces() { String result = DataUtils.stripTrailing(" foo bar! ", " "); String expected = " foo bar!"; assertEquals(expected, result); } @Test public void stripTrailingSpacesInMultilineString() { String result = DataUtils.stripTrailing(" foo bar! \n ", " "); String expected = " foo bar! \n"; assertEquals(expected, result); } @Test public void stripComplexSubstring() { String result = DataUtils.stripTrailing("+bar foo+bar+bar+bar", "+bar"); String expected = "+bar foo"; assertEquals(expected, result); } @Test public void formattingIntegersDoesntCauseTrailingZeros() { String smallDecimalString = DataUtils.format(42); String expected = "42"; assertEquals(expected, smallDecimalString); } @Test public void formattingSmallDecimalsDoesntCauseScientificNotation() { String result = DataUtils.format(1e-4d); String expected = "0.0001"; assertEquals(expected, result); } @Test public void formattingZeroDecimalsDoesntCauseTrailingZeros() { String result = DataUtils.format(0d); String expected = "0"; assertEquals(expected, result); } @Test public void formattingBigDecimalsDoesntCauseScientificNotation() { String result = DataUtils.format(1e+8d); String expected = "100000000"; assertEquals(expected, result); } @Test public void mapCreatesCorrectMappingWithValidParameters() { Map result = DataUtils.map( new String[] {"foo"}, new Integer[] {42}); assertTrue(result.containsKey("foo")); assertEquals(new Integer(42), result.get("foo")); } @Test(expected = IllegalArgumentException.class) public void mapFailsWithInvalidParameterCount() { Map result = DataUtils.map( new String[] {"foo", "bar"}, new Integer[] {42}); } @Test public void joinReturnsEmptyStringForEmptyList() { String result = DataUtils.join("@@", Collections.emptyList()); assertTrue(result.isEmpty()); } @Test public void joinReturnsEmptyStringForEmptyArray() { String result = DataUtils.join("@@", new String[] {}); assertTrue(result.isEmpty()); } @Test public void joinReturnsEmptyStringForFloatArray() { String result = DataUtils.join("@@", new float[] {}); assertTrue(result.isEmpty()); } @Test public void joinReturnsEmptyStringForDoubleArray() { String result = DataUtils.join("@@", new double[] {}); assertTrue(result.isEmpty()); } @Test public void joinReturnsEmptyStringForNullParameter() { String result = DataUtils.join("@@", (String[]) null); assertTrue(result.isEmpty()); } @Test public void joinReturnsOnlyElementForSingletonArray() { String result = DataUtils.join("@@", new String[] {"foo"}); assertEquals("foo", result); } @Test public void joinReturnsOnlyElementForSingletonList() { String result = DataUtils.join("@@", Collections.singletonList("foo")); assertEquals("foo", result); } @Test public void joinReturnsStringWithElementsAndSeparatorForArray() { String result = DataUtils.join("@@", new String[] {"foo", "bar"}); assertEquals("foo@@bar", result); } @Test public void joinReturnsStringWithElementsAndSeparatorForFloatArray() { String result = DataUtils.join("@@", new float[] {1.2f, 3.4f}); assertEquals("1.2@@3.4", result); } @Test public void joinReturnsStringWithElementsAndSeparatorForDoubleArray() { String result = DataUtils.join("@@", new double[] {1.2d, 3.4d}); assertEquals("1.2@@3.4", result); } @Test public void joinReturnsStringWithElementsAndSeparatorForList() { String result = DataUtils.join("@@", Arrays.asList("foo", "bar")); assertEquals("foo@@bar", result); } @Test public void maxReturnsMaximumOfIntegers() { int result = DataUtils.max(23, 42, -128, 4, 0); assertEquals(42, result); } @Test(expected = IllegalArgumentException.class) public void maxFailsWithoutParameters() { DataUtils.max(); } @Test public void asListReturnsListContainingCorrectFloatValues() { float[] floatValues = {1f, 2f, 3f}; List result = DataUtils.asList(floatValues); List expected = Arrays.asList(1f, 2f, 3f); assertEquals(expected, result); } @Test public void asListReturnsEmptyListForNullFloatArray() { List result = DataUtils.asList((float[]) null); assertEquals(Collections.emptyList(), result); } @Test public void asListReturnsListContainingCorrectDoubleValues() { double[] doubleValues = {1d, 2d, 3d}; List result = DataUtils.asList(doubleValues); List expected = Arrays.asList(1d, 2d, 3d); assertEquals(expected, result); } @Test public void asListReturnsEmptyListForNullDoubleArray() { List result = DataUtils.asList((double[]) null); assertEquals(Collections.emptyList(), result); } @Test public void transferWritesAllBytesOfInputStreamToOutputStream() throws IOException { byte[] bytes = { 86, 71, 50, 68 }; ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(4); DataUtils.transfer(inputStream, outputStream, 1); assertArrayEquals(bytes, outputStream.toByteArray()); } } vectorgraphics2d-0.13/src/test/java/de/erichseifert/vectorgraphics2d/util/FormattingWriterTest.java000066400000000000000000000137601347274514600337250ustar00rootroot00000000000000/* * VectorGraphics2D: Vector export for Java(R) Graphics2D * * (C) Copyright 2010-2017 Erich Seifert , * Michael Seifert * * This file is part of VectorGraphics2D. * * VectorGraphics2D is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * VectorGraphics2D 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with VectorGraphics2D. If not, see . */ package de.erichseifert.vectorgraphics2d.util; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.OutputStream; import java.io.UnsupportedEncodingException; import org.junit.Before; import org.junit.Test; public class FormattingWriterTest { private static final String DEFAULT_ENCODING = "ISO-8859-1"; private static final String DEFAULT_EOL = "\n"; private ByteArrayOutputStream stream; @Before public void setUp() { stream = new ByteArrayOutputStream(); } @Test(expected = IllegalArgumentException.class) public void constructorFailsWithoutStream() throws UnsupportedEncodingException { new FormattingWriter(null, DEFAULT_ENCODING, DEFAULT_EOL); } @Test(expected = UnsupportedEncodingException.class) public void constructorFailsWithUnknownEncoding() throws UnsupportedEncodingException { new FormattingWriter(stream, "", DEFAULT_EOL); } @Test(expected = IllegalArgumentException.class) public void constructorFailsWithEmptyEOL() throws UnsupportedEncodingException { new FormattingWriter(stream, DEFAULT_ENCODING, ""); } @Test public void writeBytesEmitsBytesToStream() throws IOException { FormattingWriter writer = new FormattingWriter(stream, DEFAULT_ENCODING, DEFAULT_EOL); byte[] bytes = { 86, 71, 50, 68 }; writer.write(bytes); byte[] expected = bytes; assertArrayEquals(expected, stream.toByteArray()); } @Test public void writelnBytesEmitsBytesAndEOLToStream() throws IOException { FormattingWriter writer = new FormattingWriter(stream, DEFAULT_ENCODING, DEFAULT_EOL); byte[] eolBytes = DEFAULT_EOL.getBytes(DEFAULT_ENCODING); byte[] bytes = { 86, 71, 50, 68 }; writer.writeln(bytes); byte[] expected = new byte[bytes.length + eolBytes.length]; System.arraycopy(bytes, 0, expected, 0, bytes.length); System.arraycopy(eolBytes, 0, expected, bytes.length, eolBytes.length); assertArrayEquals(expected, stream.toByteArray()); } @Test public void writeStringHasCorrectEncoding() throws IOException { FormattingWriter writer = new FormattingWriter(stream, DEFAULT_ENCODING, DEFAULT_EOL); String string = "f\\u00F6\\u00F6bar"; writer.write(string); byte[] expected = string.getBytes(DEFAULT_ENCODING); assertArrayEquals(expected, stream.toByteArray()); } @Test public void writeStringEmitsCorrectEOLs() throws IOException { FormattingWriter writer = new FormattingWriter(stream, DEFAULT_ENCODING, "\r\n"); writer.writeln("foo").writeln("bar"); byte[] expected = "foo\r\nbar\r\n".getBytes(DEFAULT_ENCODING); assertArrayEquals(expected, stream.toByteArray()); } @Test public void writeDoubleOutputsAFormattedNumber() throws IOException { FormattingWriter writer = new FormattingWriter(stream, DEFAULT_ENCODING, DEFAULT_EOL); writer.write(4.2); byte[] expected = "4.2".getBytes(DEFAULT_ENCODING); assertArrayEquals(expected, stream.toByteArray()); } @Test public void writeDoubleOutputsAFormattedNumberAndAppendsAnEOL() throws IOException { FormattingWriter writer = new FormattingWriter(stream, DEFAULT_ENCODING, DEFAULT_EOL); writer.writeln(4.2); byte[] expected = ("4.2" + DEFAULT_EOL).getBytes(DEFAULT_ENCODING); assertArrayEquals(expected, stream.toByteArray()); } @Test public void writeFormatsStringWithParameters() throws IOException { FormattingWriter writer = new FormattingWriter(stream, DEFAULT_ENCODING, DEFAULT_EOL); writer.write("%.02f => %s", 4.2, "foo"); byte[] expected = "4.20 => foo".getBytes(DEFAULT_ENCODING); assertArrayEquals(expected, stream.toByteArray()); } @Test public void writelnFormatsStringWithParametersAndAppendsAnEOL() throws IOException { FormattingWriter writer = new FormattingWriter(stream, DEFAULT_ENCODING, DEFAULT_EOL); writer.writeln("%.02f => %s", 4.2, "foo"); byte[] expected = ("4.20 => foo" + DEFAULT_EOL).getBytes(DEFAULT_ENCODING); assertArrayEquals(expected, stream.toByteArray()); } private final static class MockOutputStream extends OutputStream { private boolean flushed; private boolean closed; @Override public void write(int b) throws IOException {} @Override public void flush() throws IOException { flushed = true; } @Override public void close() throws IOException { closed = true; } } @Test public void closeClosesOutputStream() throws IOException { MockOutputStream mockStream = new MockOutputStream(); FormattingWriter writer = new FormattingWriter(mockStream, DEFAULT_ENCODING, DEFAULT_EOL); writer.close(); assertTrue(mockStream.closed); } @Test public void flushFlushesOutputStream() throws IOException { MockOutputStream mockStream = new MockOutputStream(); FormattingWriter writer = new FormattingWriter(mockStream, DEFAULT_ENCODING, DEFAULT_EOL); writer.flush(); assertTrue(mockStream.flushed); } @Test public void tellReturnsCorrectPosition() throws IOException { FormattingWriter writer = new FormattingWriter(stream, DEFAULT_ENCODING, DEFAULT_EOL); byte[] bytes = { 86, 71, 50, 68 }; writer.write(bytes); assertEquals(bytes.length, writer.tell()); } } vectorgraphics2d-0.13/src/test/java/de/erichseifert/vectorgraphics2d/util/GraphicsUtilsTest.java000066400000000000000000000313531347274514600331750ustar00rootroot00000000000000/* * VectorGraphics2D: Vector export for Java(R) Graphics2D * * (C) Copyright 2010-2017 Erich Seifert , * Michael Seifert * * This file is part of VectorGraphics2D. * * VectorGraphics2D is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * VectorGraphics2D 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with VectorGraphics2D. If not, see . */ package de.erichseifert.vectorgraphics2d.util; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNotSame; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertTrue; import static org.junit.Assume.assumeFalse; import java.awt.Font; import java.awt.GraphicsEnvironment; import java.awt.Image; import java.awt.Polygon; import java.awt.Rectangle; import java.awt.Shape; import java.awt.Toolkit; import java.awt.geom.Arc2D; import java.awt.geom.CubicCurve2D; import java.awt.geom.Ellipse2D; import java.awt.geom.Line2D; import java.awt.geom.Path2D; import java.awt.geom.PathIterator; import java.awt.geom.QuadCurve2D; import java.awt.geom.Rectangle2D; import java.awt.geom.RoundRectangle2D; import java.awt.image.BufferedImage; import java.awt.image.ColorModel; import java.awt.image.FilteredImageSource; import java.awt.image.RGBImageFilter; import java.awt.image.Raster; import java.awt.image.RenderedImage; import java.awt.image.SampleModel; import java.awt.image.WritableRaster; import java.util.Vector; import org.junit.Test; public class GraphicsUtilsTest { private static final double DELTA = 1e-15; private void assertBufferedImageEquals(Image expected, BufferedImage actual) { assertNotNull(actual); assertEquals(BufferedImage.class, actual.getClass()); assertEquals(expected.getWidth(null), actual.getWidth()); assertEquals(expected.getHeight(null), actual.getHeight()); } private void assertBufferedImageEquals(RenderedImage expected, BufferedImage actual) { assertNotNull(actual); assertEquals(BufferedImage.class, actual.getClass()); assertEquals(expected.getWidth(), actual.getWidth()); assertEquals(expected.getHeight(), actual.getHeight()); } @Test public void toBufferedImageCanConvertImageWithAlphaChannel() { Image image = new BufferedImage(320, 240, BufferedImage.TYPE_INT_ARGB); BufferedImage result = GraphicsUtils.toBufferedImage(image); assertBufferedImageEquals(image, result); } @Test public void toBufferedImageCanConvertImageWithoutAlphaChannel() { Image image = new BufferedImage(320, 240, BufferedImage.TYPE_INT_RGB); BufferedImage result = GraphicsUtils.toBufferedImage(image); assertBufferedImageEquals(image, result); } @Test public void toBufferedImageCanConvertFilteredImage() { Image image = Toolkit.getDefaultToolkit().createImage(new FilteredImageSource( new BufferedImage(320, 240, BufferedImage.TYPE_INT_RGB).getSource(), new RGBImageFilter() { @Override public int filterRGB(int x, int y, int rgb) { return rgb & 0xff; } } )); BufferedImage result = GraphicsUtils.toBufferedImage(image); assertBufferedImageEquals(image, result); } @Test public void toBufferedImageCanConvertRenderedImage() { final BufferedImage bimage = new BufferedImage(320, 240, BufferedImage.TYPE_INT_RGB); RenderedImage image = new RenderedImage() { @Override public Vector getSources() { return bimage.getSources(); } @Override public Object getProperty(String name) { if ("foo".equals(name)) return 42; else return bimage.getProperty(name); } @Override public String[] getPropertyNames() { return new String[] {"foo"}; } @Override public ColorModel getColorModel() { return bimage.getColorModel(); } @Override public SampleModel getSampleModel() { return bimage.getSampleModel(); } @Override public int getWidth() { return bimage.getWidth(); } @Override public int getHeight() { return bimage.getHeight(); } @Override public int getMinX() { return bimage.getMinX(); } @Override public int getMinY() { return bimage.getMinY(); } @Override public int getNumXTiles() { return bimage.getNumXTiles(); } @Override public int getNumYTiles() { return bimage.getNumYTiles(); } @Override public int getMinTileX() { return bimage.getMinTileX(); } @Override public int getMinTileY() { return bimage.getMinTileY(); } @Override public int getTileWidth() { return bimage.getTileWidth(); } @Override public int getTileHeight() { return bimage.getTileHeight(); } @Override public int getTileGridXOffset() { return bimage.getTileGridXOffset(); } @Override public int getTileGridYOffset() { return bimage.getTileGridYOffset(); } @Override public Raster getTile(int tileX, int tileY) { return bimage.getTile(tileX, tileY); } @Override public Raster getData() { return bimage.getData(); } @Override public Raster getData(Rectangle rect) { return bimage.getData(rect); } @Override public WritableRaster copyData(WritableRaster raster) { return bimage.copyData(raster); } }; BufferedImage result = GraphicsUtils.toBufferedImage(image); assertBufferedImageEquals(image, result); } @Test public void hasAlphaIsTrueForImageWithAlphaChannel() { Image image = new BufferedImage(320, 240, BufferedImage.TYPE_INT_ARGB); assertTrue(GraphicsUtils.hasAlpha(image)); } @Test public void hasAlphaIsFalseForImageWithoutAlphaChannel() { Image image = new BufferedImage(320, 240, BufferedImage.TYPE_INT_RGB); assertFalse(GraphicsUtils.hasAlpha(image)); } @Test public void getPhysicalFontReturnsPhysicalFontForFontFamily() { // FIXME: Use valid fonts for headless Continuous Integration environment assumeFalse(GraphicsEnvironment.isHeadless()); Font font = new Font("Monospaced", Font.PLAIN, 12); assertNotSame(font, GraphicsUtils.getPhysicalFont(font)); } @Test public void getPhysicalFontReturnsSameObjectForPhysicalFont() { // FIXME: Use valid fonts for headless Continuous Integration environment assumeFalse(GraphicsEnvironment.isHeadless()); Font font = new Font("Arial", Font.PLAIN, 12); assertSame(font, GraphicsUtils.getPhysicalFont(font)); } private static void assertShapeEquals(Shape expected, Shape actual) { if ((expected instanceof Line2D) && (actual instanceof Line2D)) { assertEquals(((Line2D) expected).getP1(), ((Line2D) actual).getP1()); assertEquals(((Line2D) expected).getP2(), ((Line2D) actual).getP2()); } else if ((expected instanceof Polygon) && (actual instanceof Polygon)) { int n = ((Polygon) actual).npoints; assertEquals(((Polygon) expected).npoints, n); if (n > 0) { assertArrayEquals(((Polygon) expected).xpoints, ((Polygon) actual).xpoints); assertArrayEquals(((Polygon) expected).ypoints, ((Polygon) actual).ypoints); } } else if ((expected instanceof QuadCurve2D) && (actual instanceof QuadCurve2D)) { assertEquals(((QuadCurve2D) expected).getP1(), ((QuadCurve2D) actual).getP1()); assertEquals(((QuadCurve2D) expected).getCtrlPt(), ((QuadCurve2D) actual).getCtrlPt()); assertEquals(((QuadCurve2D) expected).getP2(), ((QuadCurve2D) actual).getP2()); } else if ((expected instanceof CubicCurve2D) && (actual instanceof CubicCurve2D)) { assertEquals(((CubicCurve2D) expected).getP1(), ((CubicCurve2D) actual).getP1()); assertEquals(((CubicCurve2D) expected).getCtrlP1(), ((CubicCurve2D) actual).getCtrlP1()); assertEquals(((CubicCurve2D) expected).getCtrlP2(), ((CubicCurve2D) actual).getCtrlP2()); assertEquals(((CubicCurve2D) expected).getP2(), ((CubicCurve2D) actual).getP2()); } else if ((expected instanceof Path2D) && (actual instanceof Path2D)) { PathIterator itExpected = expected.getPathIterator(null); PathIterator itActual = actual.getPathIterator(null); double[] segmentExpected = new double[6]; double[] segmentActual = new double[6]; for (; !itExpected.isDone() || !itActual.isDone(); itExpected.next(), itActual.next()) { assertEquals(itExpected.getWindingRule(), itActual.getWindingRule()); itExpected.currentSegment(segmentExpected); itActual.currentSegment(segmentActual); assertArrayEquals(segmentExpected, segmentActual, DELTA); } } else { assertEquals(expected, actual); } } private void assertShapeClassIsCloneable(Class shapeClass) throws IllegalAccessException, InstantiationException { Shape shape = (Shape) shapeClass.newInstance(); Shape clone = GraphicsUtils.clone(shape); assertNotNull(clone); assertShapeEquals(shape, clone); } @Test public void linesCanBeCloned() throws InstantiationException, IllegalAccessException { for (Class shapeClass : new Class[] { Line2D.Float.class, Line2D.Double.class }) { assertShapeClassIsCloneable(shapeClass); } } @Test public void rectanglesCanBeCloned() throws InstantiationException, IllegalAccessException { for (Class shapeClass : new Class[] { Rectangle.class, Rectangle2D.Float.class, Rectangle2D.Double.class, }) { assertShapeClassIsCloneable(shapeClass); } } @Test public void roundedRectanglesCanBeCloned() throws InstantiationException, IllegalAccessException { for (Class shapeClass : new Class[] { RoundRectangle2D.Float.class, RoundRectangle2D.Double.class }) { assertShapeClassIsCloneable(shapeClass); } } @Test public void ellipsesCanBeCloned() throws InstantiationException, IllegalAccessException { for (Class shapeClass : new Class[] { Ellipse2D.Float.class, Ellipse2D.Double.class }) { assertShapeClassIsCloneable(shapeClass); } } @Test public void arcsCanBeCloned() throws InstantiationException, IllegalAccessException { for (Class shapeClass : new Class[] { Arc2D.Float.class, Arc2D.Double.class }) { assertShapeClassIsCloneable(shapeClass); } } @Test public void polygonsCanBeCloned() throws InstantiationException, IllegalAccessException { assertShapeClassIsCloneable(Polygon.class); } @Test public void cubicCurvesCanBeCloned() throws InstantiationException, IllegalAccessException { for (Class shapeClass : new Class[] { CubicCurve2D.Float.class, CubicCurve2D.Double.class }) { assertShapeClassIsCloneable(shapeClass); } } @Test public void quadCurvesCanBeCloned() throws InstantiationException, IllegalAccessException { for (Class shapeClass : new Class[] { QuadCurve2D.Float.class, QuadCurve2D.Double.class }) { assertShapeClassIsCloneable(shapeClass); } } @Test public void pathsCanBeCloned() throws InstantiationException, IllegalAccessException { for (Class shapeClass : new Class[] { Path2D.Float.class, Path2D.Double.class }) { assertShapeClassIsCloneable(shapeClass); } } @Test public void cloneNullReturnsNull() throws InstantiationException, IllegalAccessException { Shape result = GraphicsUtils.clone(null); assertNull(result); } @Test public void equalsReturnsTrueForEmptyPathsWithSameWindingRules() { Path2D path1 = new Path2D.Double(PathIterator.WIND_EVEN_ODD); Path2D path2 = new Path2D.Double(PathIterator.WIND_EVEN_ODD); assertTrue(GraphicsUtils.equals(path1, path2)); } @Test public void equalsReturnsFalseForEmptyPathsWithDifferentWindingRules() { Path2D windNonZero = new Path2D.Double(PathIterator.WIND_NON_ZERO); Path2D windEvenOdd = new Path2D.Double(PathIterator.WIND_EVEN_ODD); assertFalse(GraphicsUtils.equals(windNonZero, windEvenOdd)); } @Test public void equalsReturnsFalseForPathsWithSamePointCoordinatesButDifferentSegmentTypes() { Path2D path1 = new Path2D.Double(); path1.moveTo(12d, 34d); path1.lineTo(56d, 78d); Path2D path2 = new Path2D.Double(); path2.moveTo(12d, 34d); path2.curveTo(56d, 78d, 90d, 12d, 34d, 56d); assertFalse(GraphicsUtils.equals(path1, path2)); } @Test public void equalsReturnsFalseForPathsWithDifferentPointCoordinates() { Path2D path1 = new Path2D.Double(); path1.moveTo(12d, 34d); path1.lineTo(56d, 78d); Path2D path2 = new Path2D.Double(); path2.moveTo(12d, 34d); path2.lineTo(56d, 90d); assertFalse(GraphicsUtils.equals(path1, path2)); } @Test public void equalsReturnsFalseForPathsWithNumberOfPoints() { Path2D path1 = new Path2D.Double(); path1.moveTo(12d, 34d); path1.lineTo(56d, 78d); Path2D path2 = new Path2D.Double(); path2.moveTo(12d, 34d); path2.lineTo(56d, 78d); path2.lineTo(90d, 12d); assertFalse(GraphicsUtils.equals(path1, path2)); } } vectorgraphics2d-0.13/src/test/java/de/erichseifert/vectorgraphics2d/util/PageSizeTest.java000066400000000000000000000064131347274514600321220ustar00rootroot00000000000000/* * VectorGraphics2D: Vector export for Java(R) Graphics2D * * (C) Copyright 2010-2017 Erich Seifert , * Michael Seifert * * This file is part of VectorGraphics2D. * * VectorGraphics2D is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * VectorGraphics2D 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with VectorGraphics2D. If not, see . */ package de.erichseifert.vectorgraphics2d.util; import static org.junit.Assert.assertEquals; import java.awt.geom.Rectangle2D; import org.junit.Test; public class PageSizeTest { public static final double DELTA = 1e-15; @Test public void pageSizeGetsInitializedCorrectlyWithXYWidthHeight() { PageSize pageSize = new PageSize(1.0, 2.0, 3.0, 4.0); assertEquals(1.0, pageSize.getX(), DELTA); assertEquals(2.0, pageSize.getY(), DELTA); assertEquals(3.0, pageSize.getWidth(), DELTA); assertEquals(4.0, pageSize.getHeight(), DELTA); } @Test public void pageSizeGetsInitializedCorrectlyWithWidthHeight() { PageSize pageSize = new PageSize(3.0, 4.0); assertEquals(0.0, pageSize.getX(), DELTA); assertEquals(0.0, pageSize.getY(), DELTA); assertEquals(3.0, pageSize.getWidth(), DELTA); assertEquals(4.0, pageSize.getHeight(), DELTA); } @Test public void pageSizeGetsInitializedCorrectlyWithRectangle() { PageSize pageSize = new PageSize(new Rectangle2D.Double(1.0, 2.0, 3.0, 4.0)); assertEquals(1.0, pageSize.getX(), DELTA); assertEquals(2.0, pageSize.getY(), DELTA); assertEquals(3.0, pageSize.getWidth(), DELTA); assertEquals(4.0, pageSize.getHeight(), DELTA); } @Test public void getPortraitTurnsALandscapeFormatIntoPortrait() { PageSize portrait = new PageSize(3.0, 4.0); PageSize landscape = new PageSize(4.0, 3.0); assertEquals(portrait.getWidth(), landscape.getPortrait().getWidth(), DELTA); assertEquals(portrait.getHeight(), landscape.getPortrait().getHeight(), DELTA); } @Test public void getPortraitDoesNotChangeAPortraitFormat() { PageSize portrait = new PageSize(3.0, 4.0); assertEquals(portrait.getWidth(), portrait.getPortrait().getWidth(), DELTA); assertEquals(portrait.getHeight(), portrait.getPortrait().getHeight(), DELTA); } @Test public void getLandscapeTurnsAPortraitFormatIntoLandscape() { PageSize portrait = new PageSize(3.0, 4.0); PageSize landscape = new PageSize(4.0, 3.0); assertEquals(landscape.getWidth(), portrait.getLandscape().getWidth(), DELTA); assertEquals(landscape.getHeight(), portrait.getLandscape().getHeight(), DELTA); } @Test public void getLandscapeDoesNotChangeALandscapeFormat() { PageSize landscape = new PageSize(4.0, 3.0); assertEquals(landscape.getWidth(), landscape.getLandscape().getWidth(), DELTA); assertEquals(landscape.getHeight(), landscape.getLandscape().getHeight(), DELTA); } } vectorgraphics2d-0.13/src/test/java/de/erichseifert/vectorgraphics2d/util/UtilTests.java000066400000000000000000000023551347274514600315140ustar00rootroot00000000000000/* * VectorGraphics2D: Vector export for Java(R) Graphics2D * * (C) Copyright 2010-2017 Erich Seifert , * Michael Seifert * * This file is part of VectorGraphics2D. * * VectorGraphics2D is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * VectorGraphics2D 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with VectorGraphics2D. If not, see . */ package de.erichseifert.vectorgraphics2d.util; import org.junit.runner.RunWith; import org.junit.runners.Suite; @RunWith(Suite.class) @Suite.SuiteClasses({ DataUtilsTest.class, ASCII85EncodeStreamTest.class, Base64EncodeStreamTest.class, GraphicsUtilsTest.class, FormattingWriterTest.class, PageSizeTest.class }) public class UtilTests { } vectorgraphics2d-0.13/src/test/java/de/erichseifert/vectorgraphics2d/visual/000077500000000000000000000000001347274514600272325ustar00rootroot00000000000000vectorgraphics2d-0.13/src/test/java/de/erichseifert/vectorgraphics2d/visual/CharacterTest.java000066400000000000000000000043431347274514600326350ustar00rootroot00000000000000/* * VectorGraphics2D: Vector export for Java(R) Graphics2D * * (C) Copyright 2010-2017 Erich Seifert , * Michael Seifert * * This file is part of VectorGraphics2D. * * VectorGraphics2D is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * VectorGraphics2D 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with VectorGraphics2D. If not, see . */ package de.erichseifert.vectorgraphics2d.visual; import java.awt.Graphics2D; import java.io.IOException; import java.nio.charset.Charset; import java.nio.charset.CharsetEncoder; import java.util.ArrayList; import java.util.List; public class CharacterTest extends TestCase { public CharacterTest() throws IOException { } @Override public void draw(Graphics2D g) { double w = getPageSize().getWidth(); double h = getPageSize().getHeight(); Charset latin1 = Charset.forName("ISO-8859-1"); CharsetEncoder latin1Encoder = latin1.newEncoder(); List charactersInCharset = new ArrayList<>(); for (char char_ = Character.MIN_VALUE; char_ < Character.MAX_VALUE; char_++) { String javaString = String.valueOf(char_); if (latin1Encoder.canEncode(char_)) { charactersInCharset.add(javaString); } } final int colCount = (int) Math.ceil(Math.sqrt(charactersInCharset.size())); final int rowCount = colCount; double tileWidth = w/colCount; double tileHeight = h/rowCount; int charIndex = 0; for (double y = 0.0; y < h; y += tileHeight) { for (double x = 0.0; x < w; x += tileWidth) { String c = charactersInCharset.get(charIndex); double tileCenterX = x + tileWidth/2.0; double tileCenterY = y + tileHeight/2.0; g.drawString(c, (float) tileCenterX, (float) tileCenterY); charIndex++; } } } } vectorgraphics2d-0.13/src/test/java/de/erichseifert/vectorgraphics2d/visual/ClippingTest.java000066400000000000000000000035271347274514600325110ustar00rootroot00000000000000/* * VectorGraphics2D: Vector export for Java(R) Graphics2D * * (C) Copyright 2010-2017 Erich Seifert , * Michael Seifert * * This file is part of VectorGraphics2D. * * VectorGraphics2D is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * VectorGraphics2D 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with VectorGraphics2D. If not, see . */ package de.erichseifert.vectorgraphics2d.visual; import java.awt.Graphics2D; import java.awt.geom.AffineTransform; import java.awt.geom.Ellipse2D; import java.awt.geom.Line2D; import java.io.IOException; public class ClippingTest extends TestCase { public ClippingTest() throws IOException { } @Override public void draw(Graphics2D g) { double w = getPageSize().getWidth(); double h = getPageSize().getHeight(); AffineTransform txOrig = g.getTransform(); g.translate(w/2.0, h/2.0); g.setClip(new Ellipse2D.Double(-0.6*w/2.0, -h/2.0, 0.6*w, h)); for (double x = -w/2.0; x < w/2.0; x += 4.0) { g.draw(new Line2D.Double(x, -h/2.0, x, h/2.0)); } g.rotate(Math.toRadians(-90.0)); g.clip(new Ellipse2D.Double(-0.6*w/2.0, -h/2.0, 0.6*w, h)); for (double x = -h/2.0; x < h/2.0; x += 4.0) { g.draw(new Line2D.Double(x, -w/2.0, x, w/2.0)); } g.setTransform(txOrig); g.setClip(null); g.draw(new Line2D.Double(0.0, 0.0, w, h)); } } vectorgraphics2d-0.13/src/test/java/de/erichseifert/vectorgraphics2d/visual/CmykColorTest.java000066400000000000000000000072451347274514600326470ustar00rootroot00000000000000/* * VectorGraphics2D: Vector export for Java(R) Graphics2D * * (C) Copyright 2010-2017 Erich Seifert , * Michael Seifert * * This file is part of VectorGraphics2D. * * VectorGraphics2D is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * VectorGraphics2D 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with VectorGraphics2D. If not, see . */ package de.erichseifert.vectorgraphics2d.visual; import java.awt.Color; import java.awt.Graphics2D; import java.awt.color.ColorSpace; import java.awt.geom.Rectangle2D; import java.io.IOException; public class CmykColorTest extends TestCase { /** * @see "http://carback.us/rick/blog/java-cmyk-how-to" */ private static class CMYKColorSpace extends ColorSpace { public CMYKColorSpace() { super(ColorSpace.TYPE_CMYK, 4); } @Override public float[] fromCIEXYZ(float[] components) { ColorSpace rgbColorSpace = ColorSpace.getInstance(ColorSpace.TYPE_RGB); float[] rgb = rgbColorSpace.toCIEXYZ(components); return fromRGB(rgb); } @Override public float[] fromRGB(float[] rgb) { float[] cmyk = new float[4]; if (rgb.length >= 3) { float c = 1f - rgb[0]; float m = 1f - rgb[1]; float y = 1f - rgb[2]; float k = Math.min(Math.min(c, m), y); if (k < 1f) { float s = 1f - k; cmyk[0] = (c - k)/s; cmyk[1] = (m - k)/s; cmyk[2] = (y - k)/s; } cmyk[3] = k; } clamp(cmyk); return cmyk; } @Override public float[] toCIEXYZ(float[] cmyk) { float[] rgb = toRGB(cmyk); ColorSpace rgbColorSpace = ColorSpace.getInstance(ColorSpace.TYPE_RGB); return rgbColorSpace.toCIEXYZ(rgb); } @Override public float[] toRGB(float[] cmyk) { float[] rgb = new float[3]; if (cmyk.length >= 4) { float r = 1f - cmyk[0]; float g = 1f - cmyk[1]; float b = 1f - cmyk[2]; float s = 1f - cmyk[3]; rgb[0] = r*s; rgb[1] = g*s; rgb[2] = b*s; } clamp(rgb); return rgb; } private static void clamp(float[] components) { for (int c = 0; c < components.length; c++) { if (components[c] < 0f) { components[c] = 0f; } else if (components[c] > 1f) { components[c] = 1f; } } } } public CmykColorTest() throws IOException { } @Override public void draw(Graphics2D g) { final float wPage = (float) getPageSize().getWidth(); final float hPage = (float) getPageSize().getHeight(); final float wTile = Math.min(wPage/15f, hPage/15f); final float hTile = wTile; float w = wPage - wTile; float h = hPage - hTile; ColorSpace cmykColorSpace = new CMYKColorSpace(); float[] cmyk = new float[4]; final float SQRT2 = (float) Math.sqrt(2.0); for (float y = (hPage - h)/2f; y < h; y += hTile) { float yRel = y/h; for (float x = (wPage - w)/2f; x < w; x += wTile) { float xRel = x/w; cmyk[0] = (float) Math.sqrt(xRel*xRel + yRel*yRel) / SQRT2; cmyk[1] = (float) Math.sqrt((1 - xRel)*(1 - xRel) + yRel*yRel) / SQRT2; cmyk[2] = (float) Math.sqrt(xRel*xRel + (1 - yRel)*(1 - yRel)) / SQRT2; cmyk[3] = 0f; Color color = new Color(cmykColorSpace, cmyk, 1f); g.setColor(color); g.fill(new Rectangle2D.Float(x, y, wTile, hTile)); } } } } vectorgraphics2d-0.13/src/test/java/de/erichseifert/vectorgraphics2d/visual/ColorTest.java000066400000000000000000000034641347274514600320220ustar00rootroot00000000000000/* * VectorGraphics2D: Vector export for Java(R) Graphics2D * * (C) Copyright 2010-2017 Erich Seifert , * Michael Seifert * * This file is part of VectorGraphics2D. * * VectorGraphics2D is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * VectorGraphics2D 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with VectorGraphics2D. If not, see . */ package de.erichseifert.vectorgraphics2d.visual; import java.awt.Color; import java.awt.Graphics2D; import java.awt.geom.Rectangle2D; import java.io.IOException; public class ColorTest extends TestCase { public ColorTest() throws IOException { } @Override public void draw(Graphics2D g) { final float wPage = (float) getPageSize().getWidth(); final float hPage = (float) getPageSize().getHeight(); final float wTile = Math.min(wPage/15f, hPage/15f); final float hTile = wTile; float w = wPage - wTile; float h = hPage - hTile; for (float y = (hPage - h)/2f; y < h; y += hTile) { float yRel = y/h; for (float x = (wPage - w)/2f; x < w; x += wTile) { float xRel = x/w; Color c = Color.getHSBColor(yRel, 1f, 1f); int alpha = 255 - (int) (xRel*255f); g.setColor(new Color(c.getRed(), c.getGreen(), c.getBlue(), alpha)); g.fill(new Rectangle2D.Float(x, y, wTile, hTile)); } } } } vectorgraphics2d-0.13/src/test/java/de/erichseifert/vectorgraphics2d/visual/EmptyFileTest.java000066400000000000000000000022151347274514600326330ustar00rootroot00000000000000/* * VectorGraphics2D: Vector export for Java(R) Graphics2D * * (C) Copyright 2010-2017 Erich Seifert , * Michael Seifert * * This file is part of VectorGraphics2D. * * VectorGraphics2D is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * VectorGraphics2D 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with VectorGraphics2D. If not, see . */ package de.erichseifert.vectorgraphics2d.visual; import java.awt.Graphics2D; import java.io.IOException; public class EmptyFileTest extends TestCase { public EmptyFileTest() throws IOException { } @Override public void draw(Graphics2D g) { } } vectorgraphics2d-0.13/src/test/java/de/erichseifert/vectorgraphics2d/visual/FontTest.java000066400000000000000000000043641347274514600316520ustar00rootroot00000000000000/* * VectorGraphics2D: Vector export for Java(R) Graphics2D * * (C) Copyright 2010-2017 Erich Seifert , * Michael Seifert * * This file is part of VectorGraphics2D. * * VectorGraphics2D is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * VectorGraphics2D 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with VectorGraphics2D. If not, see . */ package de.erichseifert.vectorgraphics2d.visual; import java.awt.Font; import java.awt.Graphics2D; import java.io.IOException; import de.erichseifert.vectorgraphics2d.GraphicsState; public class FontTest extends TestCase { private static final Font DEFAULT_FONT = GraphicsState.DEFAULT_FONT; public FontTest() throws IOException { } @Override public void draw(Graphics2D g) { final int tileCountH = 4; final int tileCountV = 8; final double wTile = getPageSize().getWidth()/tileCountH; final double hTile = getPageSize().getHeight()/tileCountV; final double xOrigin = (getPageSize().getWidth() - tileCountH*wTile)/2.0; final double yOrigin = (getPageSize().getHeight() - tileCountV*hTile)/2.0; double x = xOrigin; double y = yOrigin; final float[] sizes = { DEFAULT_FONT.getSize2D(), DEFAULT_FONT.getSize2D()/2f }; final String[] names = { DEFAULT_FONT.getName(), Font.SERIF, Font.MONOSPACED, "Arial" }; final int[] styles = { Font.PLAIN, Font.ITALIC, Font.BOLD, Font.BOLD | Font.ITALIC }; for (float size: sizes) { for (String name : names) { for (int style : styles) { Font font = new Font(name, style, 10).deriveFont(size); g.setFont(font); g.drawString("vg2d", (float) x, (float) y); x += wTile; if (x >= tileCountH*wTile) { x = xOrigin; y += hTile; } } } } }} vectorgraphics2d-0.13/src/test/java/de/erichseifert/vectorgraphics2d/visual/ImageTest.java000066400000000000000000000037131347274514600317630ustar00rootroot00000000000000/* * VectorGraphics2D: Vector export for Java(R) Graphics2D * * (C) Copyright 2010-2017 Erich Seifert , * Michael Seifert * * This file is part of VectorGraphics2D. * * VectorGraphics2D is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * VectorGraphics2D 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with VectorGraphics2D. If not, see . */ package de.erichseifert.vectorgraphics2d.visual; import java.awt.Color; import java.awt.GradientPaint; import java.awt.Graphics2D; import java.awt.geom.Point2D; import java.awt.geom.Rectangle2D; import java.awt.image.BufferedImage; import java.io.IOException; public class ImageTest extends TestCase { public ImageTest() throws IOException { } @Override public void draw(Graphics2D g) { // Draw an image BufferedImage image = new BufferedImage(4, 3, BufferedImage.TYPE_INT_ARGB); Graphics2D gImage = (Graphics2D) image.getGraphics(); gImage.setPaint(new GradientPaint( new Point2D.Double(0.0, 0.0), Color.RED, new Point2D.Double(3.0, 2.0), Color.BLUE) ); gImage.fill(new Rectangle2D.Double(0.0, 0.0, 4.0, 3.0)); g.drawImage(image, 0, 0, (int) getPageSize().getWidth(), (int) (0.5*getPageSize().getHeight()), null); g.rotate(-10.0/180.0*Math.PI, 2.0, 1.5); g.drawImage(image, (int) (0.1*getPageSize().getWidth()), (int) (0.6*getPageSize().getHeight()), (int) (0.33*getPageSize().getWidth()), (int) (0.33*getPageSize().getHeight()), null); } } vectorgraphics2d-0.13/src/test/java/de/erichseifert/vectorgraphics2d/visual/PaintTest.java000066400000000000000000000042131347274514600320100ustar00rootroot00000000000000/* * VectorGraphics2D: Vector export for Java(R) Graphics2D * * (C) Copyright 2010-2017 Erich Seifert , * Michael Seifert * * This file is part of VectorGraphics2D. * * VectorGraphics2D is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * VectorGraphics2D 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with VectorGraphics2D. If not, see . */ package de.erichseifert.vectorgraphics2d.visual; import java.awt.Color; import java.awt.GradientPaint; import java.awt.Graphics2D; import java.awt.geom.AffineTransform; import java.awt.geom.Rectangle2D; import java.io.IOException; public class PaintTest extends TestCase { public PaintTest() throws IOException { } @Override public void draw(Graphics2D g) { // Draw multiple rotated rectangles final int steps = 25; final int cols = 5; final int rows = steps/cols; final double tileWidth = getPageSize().getWidth()/cols; final double tileHeight = getPageSize().getHeight()/rows; g.translate(tileWidth/2, tileHeight/2); final double rectWidth = tileWidth*0.8; final double rectHeight = tileHeight*0.8; Rectangle2D rect = new Rectangle2D.Double(-rectWidth/2, -rectHeight/2, rectWidth, rectHeight); g.setPaint(new GradientPaint(0f, (float) (-rectHeight/2), Color.RED, 0f, (float) (rectHeight/2), Color.BLUE)); for (int i = 0; i < steps; i++) { AffineTransform txOld = g.getTransform(); AffineTransform tx = new AffineTransform(txOld); int col = i%5; int row = i/5; tx.translate(col*tileWidth, row*tileHeight); tx.rotate(i*Math.toRadians(360.0/steps)); g.setTransform(tx); g.fill(rect); g.setTransform(txOld); } } } vectorgraphics2d-0.13/src/test/java/de/erichseifert/vectorgraphics2d/visual/ShapesTest.java000066400000000000000000000120131347274514600321550ustar00rootroot00000000000000/* * VectorGraphics2D: Vector export for Java(R) Graphics2D * * (C) Copyright 2010-2017 Erich Seifert , * Michael Seifert * * This file is part of VectorGraphics2D. * * VectorGraphics2D is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * VectorGraphics2D 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with VectorGraphics2D. If not, see . */ package de.erichseifert.vectorgraphics2d.visual; import java.awt.Graphics2D; import java.awt.Polygon; import java.awt.geom.AffineTransform; import java.awt.geom.Arc2D; import java.awt.geom.CubicCurve2D; import java.awt.geom.Ellipse2D; import java.awt.geom.Line2D; import java.awt.geom.Path2D; import java.awt.geom.QuadCurve2D; import java.awt.geom.Rectangle2D; import java.awt.geom.RoundRectangle2D; import java.io.IOException; public class ShapesTest extends TestCase { public ShapesTest() throws IOException { } @Override public void draw(Graphics2D g) { final int tileCountH = 4; final int tileCountV = 6; final double wTile = getPageSize().getWidth()/tileCountH; final double hTile = getPageSize().getHeight()/tileCountV; final double xOrigin = (getPageSize().getWidth() - tileCountH*wTile)/2.0; final double yOrigin = (getPageSize().getHeight() - tileCountV*hTile)/2.0; double x = xOrigin; double y = yOrigin; g.draw(new Line2D.Double(x, y, x + 0.8*wTile, y + 0.6*hTile)); x += wTile; g.draw(new QuadCurve2D.Double(x, y, x + 0.8*wTile, y, x + 0.8*wTile, y + 0.6*hTile)); x += wTile; g.draw(new CubicCurve2D.Double(x, y, x + 0.8*wTile, y, x, y + 0.6*hTile, x + 0.8*wTile, y + 0.6*hTile)); x = xOrigin; y += hTile; g.fill(new Rectangle2D.Double(x, y, 0.8*wTile, 0.6*hTile)); x += wTile; g.draw(new Rectangle2D.Double(x, y, 0.8*wTile, 0.6*hTile)); x += wTile; g.fill(new RoundRectangle2D.Double(x, y, 0.8*wTile, 0.6*hTile, 0.2*wTile, 0.2*hTile)); x += wTile; g.draw(new RoundRectangle2D.Double(x, y, 0.8*wTile, 0.6*hTile, 0.2*wTile, 0.2*hTile)); x += wTile; x = xOrigin; y += hTile; g.fill(new Ellipse2D.Double(x, y, 0.8*wTile, 0.6*hTile)); x += wTile; g.draw(new Ellipse2D.Double(x, y, 0.8*wTile, 0.6*hTile)); x += wTile; g.fill(new Polygon( new int[] {(int) (x), (int) (x + 0.8*wTile/2.0), (int) (x + 0.8*wTile)}, new int[] {(int) (y + 0.6*hTile), (int) (y), (int) (y + 0.6*hTile)}, 3 )); x += wTile; g.draw(new Polygon( new int[] {(int) (x), (int) (x + 0.8*wTile/2.0), (int) (x + 0.8*wTile)}, new int[] {(int) (y + 0.6*hTile), (int) (y), (int) (y + 0.6*hTile)}, 3 )); x = xOrigin; y += hTile; g.fill(new Arc2D.Double(x, y, 0.8*wTile, 0.6*hTile, 110, 320, Arc2D.PIE)); x += wTile; g.draw(new Arc2D.Double(x, y, 0.8*wTile, 0.6*hTile, 110, 320, Arc2D.PIE)); x += wTile; g.fill(new Arc2D.Double(x, y, 0.6*hTile, 0.8*wTile, 10, 320, Arc2D.CHORD)); x += wTile; g.draw(new Arc2D.Double(x, y, 0.6*hTile, 0.8*wTile, 10, 320, Arc2D.CHORD)); x = xOrigin; y += hTile; g.fill(new Arc2D.Double(x, y, 0.6*hTile, 0.8*wTile, 10, 320, Arc2D.OPEN)); x += wTile; g.draw(new Arc2D.Double(x, y, 0.6*hTile, 0.8*wTile, 10, 320, Arc2D.OPEN)); x += wTile; g.fill(new Arc2D.Double(x, y, 0.6*hTile, 0.8*wTile, 10, 320, Arc2D.PIE)); x += wTile; g.draw(new Arc2D.Double(x, y, 0.6*hTile, 0.8*wTile, 10, 320, Arc2D.PIE)); x = xOrigin; y += hTile; final Path2D path1 = new Path2D.Double(); path1.moveTo(0.00, 0.00); path1.lineTo(0.33, 1.00); path1.lineTo(0.67, 0.00); path1.quadTo(0.33, 0.00, 0.33, 0.50); path1.quadTo(0.33, 1.00, 0.67, 1.00); path1.quadTo(1.00, 1.00, 1.00, 0.50); path1.lineTo(0.67, 0.50); path1.transform(AffineTransform.getScaleInstance(0.8 * wTile, 0.6 * hTile)); path1.transform(AffineTransform.getTranslateInstance(x, y)); g.fill(path1); x += wTile; path1.transform(AffineTransform.getTranslateInstance(wTile, 0.0)); g.draw(path1); x += wTile; final Path2D path2 = new Path2D.Double(); path2.moveTo(0.0, 0.4); path2.curveTo(0.0, 0.3, 0.0, 0.0, 0.2, 0.0); path2.curveTo(0.3, 0.0, 0.4, 0.1, 0.4, 0.3); path2.curveTo(0.4, 0.5, 0.2, 0.8, 0.0, 1.0); path2.lineTo(0.6, 1.0); path2.lineTo(0.6, 0.0); path2.curveTo(0.8, 0.0, 1.0, 0.2, 1.0, 0.5); path2.curveTo(1.0, 0.6, 1.0, 0.8, 0.9, 0.9); path2.closePath(); path2.transform(AffineTransform.getScaleInstance(0.8*wTile, 0.6*hTile)); path2.transform(AffineTransform.getTranslateInstance(x, y)); g.fill(path2); x += wTile; path2.transform(AffineTransform.getTranslateInstance(wTile, 0.0)); g.draw(path2); } } vectorgraphics2d-0.13/src/test/java/de/erichseifert/vectorgraphics2d/visual/StrokeTest.java000066400000000000000000000104641347274514600322110ustar00rootroot00000000000000/* * VectorGraphics2D: Vector export for Java(R) Graphics2D * * (C) Copyright 2010-2017 Erich Seifert , * Michael Seifert * * This file is part of VectorGraphics2D. * * VectorGraphics2D is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * VectorGraphics2D 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with VectorGraphics2D. If not, see . */ package de.erichseifert.vectorgraphics2d.visual; import java.awt.BasicStroke; import java.awt.Graphics2D; import java.awt.Stroke; import java.awt.geom.AffineTransform; import java.awt.geom.Path2D; import java.io.IOException; public class StrokeTest extends TestCase { private static final Stroke[] strokes = { // Width new BasicStroke(0.0f), new BasicStroke(0.5f), new BasicStroke(1.0f), new BasicStroke(2.0f), // Cap new BasicStroke(1f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER), new BasicStroke(1f, BasicStroke.CAP_ROUND, BasicStroke.JOIN_MITER), new BasicStroke(1f, BasicStroke.CAP_SQUARE, BasicStroke.JOIN_MITER), null, // Join new BasicStroke(1f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL), new BasicStroke(1f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER), new BasicStroke(1f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_ROUND), null, // Miter limit new BasicStroke(1f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER, 1f), new BasicStroke(1f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER, 2f), new BasicStroke(1f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER, 3f), new BasicStroke(1f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER, 10f), // Dash pattern new BasicStroke(1f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER, 10f, new float[] {1f}, 0f), new BasicStroke(1f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER, 10f, new float[] {1f, 1f}, 0f), new BasicStroke(1f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER, 10f, new float[] {3f, 1f, 1f}, 0f), new BasicStroke(1f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER, 10f, new float[] {3f, 1f, 4f, 1f}, 0f), // Dash phase new BasicStroke(1f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER, 10f, new float[] {3f, 1f}, 0.5f), new BasicStroke(1f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER, 10f, new float[] {3f, 1f}, 1.0f), new BasicStroke(1f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER, 10f, new float[] {3f, 1f}, 1.5f), new BasicStroke(1f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER, 10f, new float[] {3f, 1f}, 2.5f), }; public StrokeTest() throws IOException { } @Override public void draw(Graphics2D g) { final int tileCountH = 4; final int tileCountV = 6; final double wTile = getPageSize().getWidth()/tileCountH; final double hTile = getPageSize().getHeight()/tileCountV; final double xOrigin = (getPageSize().getWidth() - tileCountH*wTile)/2.0; final double yOrigin = (getPageSize().getHeight() - tileCountV*hTile)/2.0; final Path2D path = new Path2D.Double(); path.moveTo(0.00, 0.00); path.lineTo(0.33, 1.00); path.lineTo(0.67, 0.00); path.quadTo(0.33, 0.00, 0.33, 0.50); path.quadTo(0.33, 1.00, 0.67, 1.00); path.quadTo(1.00, 1.00, 1.00, 0.50); path.lineTo(0.67, 0.50); path.moveTo(1.0, 0.4); path.curveTo(1.0, 0.3, 1.0, 0.0, 1.2, 0.0); path.curveTo(1.3, 0.0, 1.4, 0.1, 1.4, 0.3); path.curveTo(1.4, 0.5, 1.2, 0.8, 1.0, 1.0); path.lineTo(1.6, 1.0); path.lineTo(1.6, 0.0); path.curveTo(1.8, 0.0, 2.0, 0.2, 2.0, 0.5); path.curveTo(2.0, 0.6, 2.0, 0.8, 1.9, 0.9); path.transform(AffineTransform.getScaleInstance(0.8*wTile/2.0, 0.6*hTile)); double x = xOrigin; double y = yOrigin; for (Stroke stroke : strokes) { if (stroke != null) { Path2D p = new Path2D.Double(path); p.transform(AffineTransform.getTranslateInstance(x, y)); g.setStroke(stroke); g.draw(p); } x += wTile; if (x >= tileCountH*wTile) { x = xOrigin; y += hTile; } } } } vectorgraphics2d-0.13/src/test/java/de/erichseifert/vectorgraphics2d/visual/SwingExportTest.java000066400000000000000000000032111347274514600332230ustar00rootroot00000000000000/* * VectorGraphics2D: Vector export for Java(R) Graphics2D * * (C) Copyright 2010-2017 Erich Seifert , * Michael Seifert * * This file is part of VectorGraphics2D. * * VectorGraphics2D is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * VectorGraphics2D 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with VectorGraphics2D. If not, see . */ package de.erichseifert.vectorgraphics2d.visual; import java.awt.BorderLayout; import java.awt.Graphics2D; import java.io.IOException; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JSlider; public class SwingExportTest extends TestCase { public SwingExportTest() throws IOException { } @Override public void draw(Graphics2D g) { JFrame frame = new JFrame(); frame.getContentPane().add(new JButton("Hello Swing!"), BorderLayout.CENTER); frame.getContentPane().add(new JSlider(), BorderLayout.NORTH); frame.setSize(200, 250); //g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); frame.setVisible(true); frame.printAll(g); frame.setVisible(false); frame.dispose(); } } vectorgraphics2d-0.13/src/test/java/de/erichseifert/vectorgraphics2d/visual/TestBrowser.java000066400000000000000000000222311347274514600323600ustar00rootroot00000000000000/* * VectorGraphics2D: Vector export for Java(R) Graphics2D * * (C) Copyright 2010-2017 Erich Seifert , * Michael Seifert * * This file is part of VectorGraphics2D. * * VectorGraphics2D is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * VectorGraphics2D 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with VectorGraphics2D. If not, see . */ package de.erichseifert.vectorgraphics2d.visual; import java.awt.BorderLayout; import java.awt.Component; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.ItemEvent; import java.awt.event.ItemListener; import java.awt.image.BufferedImage; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.List; import javax.swing.Box; import javax.swing.BoxLayout; import javax.swing.DefaultListCellRenderer; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JComponent; import javax.swing.JFileChooser; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JList; import javax.swing.JPanel; import javax.swing.JSplitPane; import javax.swing.ListSelectionModel; import javax.swing.WindowConstants; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; public class TestBrowser extends JFrame { private final List testCases; private final ImageComparisonPanel imageComparisonPanel; private final JComboBox imageFormatSelector; private final JFileChooser fileChooser; private TestCase testCase; private enum ImageFormat { EPS("EPS"), PDF("PDF"), SVG("SVG"); private final String name; ImageFormat(String name) { this.name = name; } public String getName() { return name; } } private static class ImageComparisonPanel extends Box { private final JSplitPane splitPane; private final Box leftPanel; private final Box rightPanel; private ImageFormat imageFormat; // User set components private JComponent leftComponent; private JComponent rightComponent; public ImageComparisonPanel(ImageFormat imageFormat) { super(BoxLayout.PAGE_AXIS); this.imageFormat = imageFormat; splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT); splitPane.setResizeWeight(0.5); add(splitPane); leftPanel = new Box(BoxLayout.PAGE_AXIS); leftPanel.add(new JLabel("Graphics2D")); splitPane.setTopComponent(leftPanel); rightPanel = new Box(BoxLayout.PAGE_AXIS); rightPanel.add(new JLabel(imageFormat.getName())); splitPane.setBottomComponent(rightPanel); } public JComponent getLeftComponent() { return leftComponent; } public void setLeftComponent(JComponent leftComponent) { if (this.leftComponent != null) { leftPanel.remove(this.leftComponent); } this.leftComponent = leftComponent; leftPanel.add(leftComponent); leftPanel.revalidate(); leftPanel.repaint(); } public JComponent getRightComponent() { return rightComponent; } public void setRightComponent(JComponent rightComponent) { if (this.rightComponent != null) { rightPanel.remove(this.rightComponent); } this.rightComponent = rightComponent; rightPanel.add(rightComponent); rightPanel.revalidate(); rightPanel.repaint(); } public ImageFormat getImageFormat() { return imageFormat; } public void setImageFormat(ImageFormat imageFormat) { this.imageFormat = imageFormat; JLabel imageFormatLabel = (JLabel) rightPanel.getComponent(0); imageFormatLabel.setText(imageFormat.getName()); imageFormatLabel.repaint(); } } private static class ImageDisplayPanel extends JPanel { private final BufferedImage renderedImage; private final InputStream imageData; private final JFileChooser saveFileDialog; public ImageDisplayPanel(BufferedImage renderedImage, InputStream imageData, JFileChooser fileChooser) { super(new BorderLayout()); this.renderedImage = renderedImage; this.imageData = imageData; this.saveFileDialog = fileChooser; JLabel imageLabel = new JLabel(new ImageIcon(renderedImage)); add(imageLabel, BorderLayout.CENTER); JButton saveToFileButton = new JButton("Save as..."); if (imageData == null) { saveToFileButton.setEnabled(false); } saveToFileButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { saveFileDialog.setFileSelectionMode(JFileChooser.FILES_ONLY); saveFileDialog.setMultiSelectionEnabled(false); int userChoice = saveFileDialog.showSaveDialog(ImageDisplayPanel.this); if (userChoice != JFileChooser.APPROVE_OPTION) { return; } File dest = saveFileDialog.getSelectedFile(); FileOutputStream destStream = null; try { destStream = new FileOutputStream(dest); int imageDataChunk; while ((imageDataChunk = ImageDisplayPanel.this.imageData.read()) != -1){ destStream.write(imageDataChunk); } } catch (IOException e1) { e1.printStackTrace(); } finally { if (destStream != null) { try { destStream.close(); } catch (IOException e1) { e1.printStackTrace(); } } } } }); add(saveToFileButton, BorderLayout.SOUTH); } } public TestBrowser() { super("Test browser"); setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); setSize(1024, 768); fileChooser = new JFileChooser(); testCases = new ArrayList<>(); try { testCases.add(new ColorTest()); testCases.add(new CmykColorTest()); testCases.add(new StrokeTest()); testCases.add(new ShapesTest()); testCases.add(new FontTest()); testCases.add(new CharacterTest()); testCases.add(new EmptyFileTest()); testCases.add(new ImageTest()); testCases.add(new ClippingTest()); testCases.add(new PaintTest()); testCases.add(new SwingExportTest()); testCases.add(new TransformTest()); } catch (IOException e) { e.printStackTrace(); } final JList testList = new JList(testCases.toArray()); testList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); testList.setCellRenderer(new DefaultListCellRenderer() { @Override public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { String testName = value.getClass().getSimpleName(); return super.getListCellRendererComponent(list, testName, index, isSelected, cellHasFocus); } }); testList.addListSelectionListener(new ListSelectionListener() { @Override public void valueChanged(ListSelectionEvent e) { if (!e.getValueIsAdjusting()) { int index = testList.getSelectedIndex(); if (index < 0) { return; } testCase = testCases.get(index); setTestCase(testCase); } } }); getContentPane().add(testList, BorderLayout.WEST); JPanel configurableImageComparisonPanel = new JPanel(new BorderLayout()); getContentPane().add(configurableImageComparisonPanel, BorderLayout.CENTER); ImageFormat startingImageFormat = ImageFormat.EPS; imageFormatSelector = new JComboBox(ImageFormat.values()); configurableImageComparisonPanel.add(imageFormatSelector, BorderLayout.NORTH); imageFormatSelector.setSelectedItem(startingImageFormat); imageFormatSelector.addItemListener(new ItemListener() { @Override public void itemStateChanged(ItemEvent itemEvent) { ImageFormat format = (ImageFormat) itemEvent.getItem(); imageComparisonPanel.setImageFormat(format); TestCase test = getTestCase(); if (test != null) { setTestCase(test); } } }); imageComparisonPanel = new ImageComparisonPanel(startingImageFormat); configurableImageComparisonPanel.add(imageComparisonPanel, BorderLayout.CENTER); } public void setTestCase(TestCase test) { BufferedImage reference = test.getReference(); imageComparisonPanel.setLeftComponent(new ImageDisplayPanel(reference, null, fileChooser)); ImageDisplayPanel imageDisplayPanel; switch (imageComparisonPanel.getImageFormat()) { case EPS: imageDisplayPanel = new ImageDisplayPanel(test.getRasterizedEPS(), test.getEPS(), fileChooser); break; case PDF: imageDisplayPanel = new ImageDisplayPanel(test.getRasterizedPDF(), test.getPDF(), fileChooser); break; case SVG: imageDisplayPanel = new ImageDisplayPanel(test.getRasterizedSVG(), test.getSVG(), fileChooser); break; default: throw new IllegalArgumentException("Unknown image format: " + imageComparisonPanel.getImageFormat()); } imageComparisonPanel.setRightComponent(imageDisplayPanel); } public TestCase getTestCase() { return testCase; } public static void main(String[] args) { new TestBrowser().setVisible(true); } } vectorgraphics2d-0.13/src/test/java/de/erichseifert/vectorgraphics2d/visual/TestCase.java000066400000000000000000000172321347274514600316150ustar00rootroot00000000000000/* * VectorGraphics2D: Vector export for Java(R) Graphics2D * * (C) Copyright 2010-2017 Erich Seifert , * Michael Seifert * * This file is part of VectorGraphics2D. * * VectorGraphics2D is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * VectorGraphics2D 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with VectorGraphics2D. If not, see . */ package de.erichseifert.vectorgraphics2d.visual; import java.awt.Color; import java.awt.Graphics2D; import java.awt.RenderingHints; import java.awt.image.BufferedImage; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import javax.imageio.ImageIO; import de.erichseifert.vectorgraphics2d.Document; import de.erichseifert.vectorgraphics2d.Processor; import de.erichseifert.vectorgraphics2d.VectorGraphics2D; import de.erichseifert.vectorgraphics2d.eps.EPSProcessor; import de.erichseifert.vectorgraphics2d.pdf.PDFProcessor; import de.erichseifert.vectorgraphics2d.svg.SVGProcessor; import de.erichseifert.vectorgraphics2d.util.PageSize; import org.apache.batik.transcoder.TranscoderException; import org.apache.batik.transcoder.TranscoderInput; import org.apache.batik.transcoder.TranscoderOutput; import org.apache.batik.transcoder.image.ImageTranscoder; import org.ghost4j.Ghostscript; import org.ghost4j.GhostscriptException; public abstract class TestCase { private static final double EPSILON = 1; private final PageSize pageSize; private final BufferedImage reference; private final VectorGraphics2D vectorGraphics; private final Processor epsProcessor; private final Processor pdfProcessor; private final Processor svgProcessor; private BufferedImage rasterizedEPS; private BufferedImage rasterizedPDF; private BufferedImage rasterizedSVG; public TestCase() throws IOException { int width = 300; int height = 300; pageSize = new PageSize(0.0, 0.0, width, height); vectorGraphics = new VectorGraphics2D(); draw(vectorGraphics); epsProcessor = new EPSProcessor(); pdfProcessor = new PDFProcessor(false); svgProcessor = new SVGProcessor(); reference = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); Graphics2D referenceGraphics = reference.createGraphics(); referenceGraphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); referenceGraphics.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY); referenceGraphics.setBackground(new Color(1f, 1f, 1f, 0f)); referenceGraphics.clearRect(0, 0, reference.getWidth(), reference.getHeight()); referenceGraphics.setColor(Color.BLACK); draw(referenceGraphics); File referenceImage = File.createTempFile(getClass().getName() + ".reference", ".png"); referenceImage.deleteOnExit(); ImageIO.write(reference, "png", referenceImage); } public abstract void draw(Graphics2D g); public PageSize getPageSize() { return pageSize; } public BufferedImage getReference() { return reference; } public InputStream getEPS() { Document document = epsProcessor.getDocument(vectorGraphics.getCommands(), getPageSize()); ByteArrayOutputStream byteOutput = new ByteArrayOutputStream(); try { document.writeTo(byteOutput); } catch (IOException e) { e.printStackTrace(); } return new ByteArrayInputStream(byteOutput.toByteArray()); } public InputStream getPDF() { Document document = pdfProcessor.getDocument(vectorGraphics.getCommands(), getPageSize()); ByteArrayOutputStream byteOutput = new ByteArrayOutputStream(); try { document.writeTo(byteOutput); } catch (IOException e) { e.printStackTrace(); } return new ByteArrayInputStream(byteOutput.toByteArray()); } public InputStream getSVG() { Document document = svgProcessor.getDocument(vectorGraphics.getCommands(), getPageSize()); ByteArrayOutputStream byteOutput = new ByteArrayOutputStream(); try { document.writeTo(byteOutput); } catch (IOException e) { e.printStackTrace(); } return new ByteArrayInputStream(byteOutput.toByteArray()); } public BufferedImage getRasterizedEPS() { if (rasterizedEPS != null) { return rasterizedEPS; } try { File epsInputFile = File.createTempFile(getClass().getName() + ".testEPS", ".eps"); epsInputFile.deleteOnExit(); OutputStream epsInput = new FileOutputStream(epsInputFile); epsProcessor.getDocument(vectorGraphics.getCommands(), getPageSize()).writeTo(epsInput); epsInput.close(); File pngOutputFile = File.createTempFile(getClass().getName() + ".testEPS", "png"); pngOutputFile.deleteOnExit(); Ghostscript gs = Ghostscript.getInstance(); gs.initialize(new String[] { "-dBATCH", "-dQUIET", "-dNOPAUSE", "-dSAFER", String.format("-g%dx%d", Math.round(getPageSize().getWidth()), Math.round(getPageSize().getHeight())), "-dGraphicsAlphaBits=4", "-dAlignToPixels=0", "-dEPSCrop", "-dPSFitPage", "-sDEVICE=pngalpha", "-sOutputFile=" + pngOutputFile.toString(), epsInputFile.toString() }); gs.exit(); rasterizedEPS = ImageIO.read(pngOutputFile); } catch (IOException | GhostscriptException e) { e.printStackTrace(); } return rasterizedEPS; } public BufferedImage getRasterizedPDF() { if (rasterizedPDF != null) { return rasterizedPDF; } try { File pdfInputFile = File.createTempFile(getClass().getName() + ".testPDF", ".pdf"); pdfInputFile.deleteOnExit(); OutputStream pdfInput = new FileOutputStream(pdfInputFile); pdfProcessor.getDocument(vectorGraphics.getCommands(), getPageSize()).writeTo(pdfInput); pdfInput.close(); File pngOutputFile = File.createTempFile(getClass().getName() + ".testPDF", "png"); pngOutputFile.deleteOnExit(); Ghostscript gs = Ghostscript.getInstance(); gs.initialize(new String[] { "-dBATCH", "-dQUIET", "-dNOPAUSE", "-dSAFER", String.format("-g%dx%d", Math.round(getPageSize().getWidth()), Math.round(getPageSize().getHeight())), "-dGraphicsAlphaBits=4", // TODO: More robust settings for gs? DPI value is estimated. "-r25", "-dAlignToPixels=0", "-dPDFFitPage", "-sDEVICE=pngalpha", "-sOutputFile=" + pngOutputFile.toString(), pdfInputFile.toString() }); gs.exit(); rasterizedPDF = ImageIO.read(pngOutputFile); } catch (IOException | GhostscriptException e) { e.printStackTrace(); } return rasterizedPDF; } public BufferedImage getRasterizedSVG() { if (rasterizedSVG != null) { return rasterizedSVG; } try { rasterizedSVG = new BufferedImage( (int) Math.round(getPageSize().getWidth()), (int) Math.round(getPageSize().getHeight()), BufferedImage.TYPE_INT_ARGB); ImageTranscoder transcoder = new ImageTranscoder() { @Override public BufferedImage createImage(int width, int height) { return rasterizedSVG; } @Override public void writeImage(BufferedImage bufferedImage, TranscoderOutput transcoderOutput) throws TranscoderException { } }; transcoder.transcode(new TranscoderInput(getSVG()), null); } catch (TranscoderException e) { e.printStackTrace(); } return rasterizedSVG; } } vectorgraphics2d-0.13/src/test/java/de/erichseifert/vectorgraphics2d/visual/TransformTest.java000066400000000000000000000040621347274514600327120ustar00rootroot00000000000000/* * VectorGraphics2D: Vector export for Java(R) Graphics2D * * (C) Copyright 2010-2017 Erich Seifert , * Michael Seifert * * This file is part of VectorGraphics2D. * * VectorGraphics2D is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * VectorGraphics2D 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with VectorGraphics2D. If not, see . */ package de.erichseifert.vectorgraphics2d.visual; import java.awt.Graphics2D; import java.awt.Shape; import java.awt.geom.AffineTransform; import java.awt.geom.Rectangle2D; import java.io.IOException; public class TransformTest extends TestCase { public TransformTest() throws IOException { } @Override public void draw(Graphics2D g) { final int rowCount = 2; final int colCount = 4; double wTile = getPageSize().getWidth()/colCount; double hTile = wTile; g.translate(0.5*wTile, 0.5*hTile); AffineTransform txOrig = g.getTransform(); Shape s = new Rectangle2D.Double(0.0, 0.0, 0.5*wTile, 0.75*hTile); // Row 1 g.draw(s); g.translate(wTile, 0.0); g.draw(s); g.translate(wTile, 0.0); { Graphics2D g2 = (Graphics2D) g.create(); g2.scale(0.5, 0.5); g2.draw(s); g2.dispose(); } g.translate(wTile, 0.0); { Graphics2D g2 = (Graphics2D) g.create(); g2.rotate(Math.toRadians(30.0)); g2.draw(s); g2.dispose(); } // Row 2 g.setTransform(txOrig); g.translate(0.0, hTile); g.shear(0.5, 0.0); g.draw(s); g.shear(-0.5, 0.0); g.translate(wTile, 0.0); g.shear(0.0, 0.5); g.draw(s); g.shear(0.0, -0.5); } }