pax_global_header00006660000000000000000000000064140207227050014511gustar00rootroot0000000000000052 comment=95def8ed58f21f18163f84e81278de8fe61954d8 python-ghostscript-0.7/000077500000000000000000000000001402072270500152475ustar00rootroot00000000000000python-ghostscript-0.7/.gitignore000066400000000000000000000012441402072270500172400ustar00rootroot00000000000000# crazy-compiler standard excludes /projectlogo.png /docs/_build/ *.[1-9] # editor artefacts *~ .#* \#*# .*.swp # build artefacts /.sconf_temp /.sconsign.* /config.h /config.log /config.status /autom4te*.cache /options.cache /stamp-h1 # C, C++ build artefacts *.[oa] *.l[oa] *.al .libs .deps *.so *.so.[0-9]* *.rej *.dll .idea # Python build artefacts /build/ /dist/ /_venv/ /pip-selfcheck.json /pyvenv.cfg *.py[cod] *.egg *.egg-info *.egg-link /nosetests.xml /.coverage /.tox /.achievements /.installed.cfg /.ropeproject /.cache # Mr Developer /.mr.developer.cfg /.project /.pydevproject # OS generated files *.DS_[sS]Store* ehthumbs.db Icon? Thumbs.db *.pid ._.**~ python-ghostscript-0.7/.gitlab-ci.yml000066400000000000000000000011251402072270500177020ustar00rootroot00000000000000image: python stages: - test - build - release before_script: - apt-get update -qq && apt-get install -y -q ghostscript - pip install -r requirements.txt python36: image: python:3.6 stage: test script: tox -e py36 python37: image: python:3.7 stage: test script: tox -e py37 python38: image: python:3.8 stage: test script: tox -e py38 python39: image: python:3.9 stage: test script: tox -e py39 linters: image: python:3.9 stage: test script: tox -e linters build: stage: build script: tox -e build artifacts: paths: - dist/ expire_in: 1 week python-ghostscript-0.7/CHANGES.txt000066400000000000000000000060421402072270500170620ustar00rootroot00000000000000Changes ================== 0.7 (2021-03-06) ---------------- * BREAKING: ``Ghostscript()`` no longer allows passing arbitrary keyword arguments. * The high-level interface now allows passing unicode strings as arguments. Passing bytes as arguments is still possible, but now deprecated. * The high-level interface now requires ghostscript >= 9.0.8 (released 2013-08-14). * Allow multiple Ghostscript instances. Actually using this requires the library is compiled with -DGS_THREADSAFE. * Ensure proper clean-up on error. * High-level revision() now returns unicode strings instead of byte strings. * Add low-level interface for set_arg_encoding(). * Miscellaneous small fixes. * Drop support for Python 2.7, 3.4 and 3.5. Minimum required Python version is now 3.6. :0.6 (2018-01-16): * Add support for Python 3.x (tested with Python 3.4). Minimum required Python version is now 2.7. * Add support for display callback and an example program using it. Thanks to Lasse Fister. * Add context-interface (for the ``with``-statement). * ``GhostscriptError`` now has an attribute ``code`` holding the numeric error-code. * ``Ghostscript()`` now accepts keyword-arguments ``stdin``, ``stdout``, ``stderr`` for setting the respective stream. This was already implementd in version 0.4.1, but not documented. * Add unittest suite (using pytest). * Several bug fixes and smaller changes. * Switch version control to git and move project to gitlab. See Readme-file for the new URL. * Set up continuous integration tests. :0.5 (skipped): * v0.5 was skipped to avoid version conflicts with fork `python3-ghostscript`. All changes of that fork are integrated into v0.6. :0.4.1 (2011-02-09): * Fixed import module on Windows XP. Thanks to Akihiro Takizawa for the patch. :0.4 (2011-01-29): * Fixed typo in function call name ctypes.util.find_library * (Unix) No longer try to load a specific version (version 8) of libgs.so * Added low-level interface for set_stdio() plus wrappers for file handles * (win32) Improved search for best Ghostscript installation: Consider Aladdin and GNU Ghostscript, too; Check for existence of DLL found in registry; take highest version available. * Added win32 example-batch file for testing and other improvements/fixes on examples an documentation. :0.3 (2010-08-12): * Added support for win32: The DLL to load is searched in registry. * On other platforms: Be more inteligent about finding Ghostscript shared object file (fall back to ctypes.util.find_library() if `libgs.8.so` can not be loaded * Better error messages if lib/dll is not found. * Removed relative imports, so older versions of Python can be used. * Added nice project logo :0.2 (2010-08-06): * Fixed several bugs, esp. for running strings by Ghostscript. :0.1 (2010-08-06): * This is the first public release of the Python Ghostscript C-API interface. .. Emacs config: Local Variables: mode: rst ispell-local-dictionary: "american" End: python-ghostscript-0.7/COPYING000066400000000000000000001045131402072270500163060ustar00rootroot00000000000000 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 . python-ghostscript-0.7/MANIFEST.in000066400000000000000000000001771402072270500170120ustar00rootroot00000000000000include COPYING include README.txt exclude .gitgnore recursive-include test *.xml *.py *.bmp #recursive-include doc *.html *.1 python-ghostscript-0.7/Makefile000066400000000000000000000001751402072270500167120ustar00rootroot00000000000000 # create PNG projectlogo for project homepage projectlogo.png: projectlogo.svg inkscape -z -f $< -e $@ --export-height=100 python-ghostscript-0.7/README.rst000066400000000000000000000062241402072270500167420ustar00rootroot00000000000000========================== `python-ghostscript` ========================== --------------------------------------------------------------------- Python-Interface to the Ghostscript C-API --------------------------------------------------------------------- :Author: Hartmut Goebel :Version: 0.7 :License: GNU General Public License v3 or later (GPLv3+) :Homepage: https://gitlab.com/pdftools/python-ghostscript `Ghostscript`__ is a well known interpreter for the PostScript language and for PDF. This package implements a interface to the `Ghostscript C-API`__ using `ctypes`__. Both a low-level and a pythonic, high-level interface are provided. __ http://www.ghostscript.com/ __ http://pages.cs.wisc.edu/~ghost/doc/cvs/API.htm __ http://docs.python.org/library/ctypes.html This package is currently tested only under GNU/Linux. Please report whether it works in your environment, too. Thanks. Example ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Here is an example for how to use the high-level interface of `python-ghostscript`. This implements a very basic ps2pdf-tool:: import sys import locale import ghostscript args = [ "ps2pdf", # actual value doesn't matter "-dNOPAUSE", "-dBATCH", "-dSAFER", "-sDEVICE=pdfwrite", "-sOutputFile=" + sys.argv[1], "-c", ".setpdfwrite", "-f", sys.argv[2] ] # arguments have to be bytes, encode them encoding = locale.getpreferredencoding() args = [a.encode(encoding) for a in args] ghostscript.Ghostscript(*args) Here an example for passing a string document to Ghostscript:: doc = b"""%! /Helvetica findfont 20 scalefont setfont 50 50 moveto (Hello World) show showpage quit """ import ghostscript args = b"""test.py -dNOPAUSE -dBATCH -dSAFER -sDEVICE=pdfwrite -sOutputFile=/tmp/out.pdf -c .setpdfwrite""".split() with ghostscript.Ghostscript(*args) as gs: gs.run_string(doc) More examples can be found in the `examples` subdirectory of the distribution archive. Requirements and Installation ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ :Please note: This package is meant for developers. Even if there are some usable examples included, installations instructions are meant for developers. `python-ghostscript` requires * `Python`__ 3.6 or higher (tested with Python 3.6–3.9) * `setuptools`__ for installation (see below) * `Ghostscript`__ Version 9.0.8 or higher __ http://www.python.org/download/ __ http://pypi.python.org/pypi/setuptools __ http://www.ghostscript.com/ Installing python-ghostscript --------------------------------- Since this package is meant for developers, we assume you have experience in installing Python packages. `python-ghostscript` is listed on `PyPI (Python Package Index)`__, so you can install it using `pip install ghostscript` as usual. Please refer to the manuals of `pip` for further information. __ http://pypi.python.org/pypi Alternatively you my download and unpack the source package of `python-ghostscript` from http://pypi.python.org/pypi/ghostscript and run:: python ./setup.py install .. Emacs config: Local Variables: mode: rst ispell-local-dictionary: "american" End: python-ghostscript-0.7/_zest_release_hooks.py000066400000000000000000000040741402072270500216550ustar00rootroot00000000000000# Copyright 2020-2021 Hartmut Goebel # This file is licensed under the # GNU Affero General Public License v3 or later (AGPLv3+) # SPDX-License-Identifier: AGPL-3.0-or-later import glob import os import shutil import subprocess import sys import zest.releaser.utils def sign_release(data): "Sign the archive that will be uploaded to PYPI." # zest.releaser does a clean checkout where it generates tgz/zip in 'dist' # directory and those files will be then uploaded to pypi. dist_dir = os.path.join(data['tagdir'], 'dist') cmd = ['gpg', '--detach-sign', '--armor'] codesigning_id = os.getenv("CODESIGNING_ID") if not codesigning_id: rc, codesigning_id = subprocess.getstatusoutput( "git config --get user.signingkey") if rc: raise SystemExit(f"ERROR in sign_release hook: {codesigning_id}") codesigning_id = None if codesigning_id: print("Using gpg identity", codesigning_id, "for signing.") cmd.extend(['--local-user', codesigning_id]) # Sign all files in the 'dist' directory. for f in list(os.listdir(dist_dir)): f = os.path.join(dist_dir, f) print('Signing file %s' % f) subprocess.run(cmd + [f]) def run_twine_check(data): import twine.cli dist_dir = os.path.join(data['tagdir'], 'dist') dist_files = list(glob.glob(os.path.join(dist_dir, "*"))) twine.cli.dispatch(["check"] + dist_files) def safe_dist_files(data): repo_dist_dir = os.path.join(data['reporoot'], 'dist') dist_dir = os.path.join(data['tagdir'], 'dist') dist_files = glob.glob(os.path.join(dist_dir, "*")) for fn in sorted(os.listdir(dist_dir)): src = os.path.join(dist_dir, fn) dest = os.path.join(repo_dist_dir, fn) if (os.path.exists(dest) and not zest.releaser.utils.ask("Overwrite dist/%s" % fn, default=True)): # skip this file print("Skipping", fn) continue print("Saving", fn) shutil.copy2(src, dest) python-ghostscript-0.7/examples/000077500000000000000000000000001402072270500170655ustar00rootroot00000000000000python-ghostscript-0.7/examples/dxmain.py000077500000000000000000001065471402072270500207370ustar00rootroot00000000000000#!/usr/bin/python # -*- coding: utf-8 -*- """ Ghostscript frontend which provides a graphical window using PyGtk and python-ghostscript. For running the demo you need PyGI (aka python-gi). You will need to use Python 2.x because cairo.ImageSurface.create_for_data is not yet available in Python 3, see . and this was not tested in Python 3. Run this like the gs command is used. However, using the `display` device is required:: ./dxmain.py -dBATCH -sDEVICE=display -dFitPage /path/to/eps_or_pdf more options: http://www.ghostscript.com/doc/current/Use.htm#Output_device see the main function to change the setup of the display device """ # # This is a python port from dxmain.c by artifex http://www.artifex.com # dxmain.c is int the ghostscript repositoty at ghostpdl/gs/psi/dxmain.c # # Please do not take this as an example for a GTK programm written in # Python since the GTK-part is yet quite C-ish. This program focuses on # interacting with the desplay device. # # Copyright 2013 by Lasse Fister # # 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 . # __author__ = "Lasse Fister " __copyright__ = "Copyright 2013 by Lasse Fister " __licence__ = "GNU General Public License version 3 (GPL v3)" import ghostscript._gsprint as gs import ctypes as c from gi.repository import Gtk, Gdk, GLib, GdkPixbuf # fails when being used: # from gi.repository import cairo # using regular bindings: import cairo import sys from array import array start_string = "systemdict /start get exec\n" ##################################################################### # stdio functions # this looks like not needed in python. a simple dict would do it class Stdin_buf (c.Structure): _fields_ = [ ('buf', c.POINTER(c.c_char)), # length of buffer ('len', c.c_int), # number of characters returned ('count', c.c_int), ] # handler for reading non-blocking stdin def read_stdin_handler(channel, condition, inputBuffer): """ where channel is fd, the file descriptor; cb_condition is the condition that triggered the signal; and, ... are the zero or more arguments that were passed to the GLib.io_add_watch() function. If the callback function returns False it will be automatically removed from the list of event sources and will not be called again. If it returns True it will be called again when the condition is matched. """ if condition & GLib.IOCondition.PRI: print ('input exception') inputBuffer.count = 0 #EOF elif condition & GLib.IOCondition.IN: try: data = channel.readline(inputBuffer.len) except Exception as exception: print (exception) # dunno yet what exceptions occur here. inputBuffer.count = -1 # this keeps the loop going else: if not data: inputBuffer.count = 0 else: inputBuffer.count = len(data) # copy data to inputBuffer.buf c.memmove(inputBuffer.buf, c.c_char_p(data), inputBuffer.count) else: print ('input condition unknown') inputBuffer.count = 0 #EOF return True; # callback for reading stdin # static int gsdll_stdin(void *instance, char *buf, int len); def _gsdll_stdin(instance, buf, length): inputBuffer = Stdin_buf(buf, length, -1) # buf, len, count channel = sys.stdin # (fd, condition, callback, user_data=None) -> source id # callable receives (fd, condition, user_data) # Arranges for the fd to be monitored by the main loop for the # specified condition. # fd : a Python file object or an integer file descriptor ID input_tag = GLib.io_add_watch( channel, # condition is a combination of GLib.IOCondition.IN, GLib.IOCondition.OUT, # GLib.IOCondition.PRI, GLib.IOCondition.ERR and GLib.IOCondition.HUP. (GLib.IOCondition.IN | GLib.IOCondition.PRI | GLib.IOCondition.ERR | GLib.IOCondition.HUP), read_stdin_handler, inputBuffer ) while inputBuffer.count < 0: # The Gtk.main_iteration_do() function runs a single iteration of # the main loop. If block is True block until an event occurs. Gtk.main_iteration_do(True) GLib.source_remove(input_tag) return inputBuffer.count gsdll_stdin = gs.c_stdstream_call_t(_gsdll_stdin) ##################################################################### # dll display device class ImageDeviceN(object): used = 0 # int, non-zero if in use visible = True # bool name = None # char name[64] cyan = 0 # int magenta = 0 # int yellow = 0 # int black = 0 # int menu = None # int, non-zero if menu item added to system menu IMAGE_DEVICEN_MAX = 8 class ImageData(object): def __init__ (self): self.separation = [None] * IMAGE_DEVICEN_MAX self.devicen = [ImageDeviceN() for i in range(0, IMAGE_DEVICEN_MAX)] handle = None # void *handle device = None # void *device window = None # GtkWidget *window; vbox = None # GtkWidget *vbox; cmyk_bar = None # GtkWidget *cmyk_bar; #separation = # GtkWidget *separation[IMAGE_DEVICEN_MAX]; show_as_gray = None # GtkWidget *show_as_gray; scroll = None # GtkWidget *scroll; darea = None # GtkWidget *darea; buf = None # guchar *buf; width = None # gint width; height = None # gint height; rowstride = None # gint rowstride; format = None # unsigned int format; devicen_gray = False # bool devicen_gray; true if a single separation should be shown gray #devicen = [] # IMAGE_DEVICEN devicen[IMAGE_DEVICEN_MAX]; rgbbuf = None # guchar *rgbbuf; used when we need to convert raster format # IMAGE *next; # no need for this as we use the images dict for lookup images = {}; def image_find(handle, device): try: return images[(handle, device)] except KeyError: return None def window_draw(widget, cr, img): """ widget is a gtk_drawing_area_new and should be equal to img.darea this callback is called via: img.darea.connect('draw', window_draw, img) """ if img and img.window and img.buf: bgcol = widget.get_style_context().get_background_color(Gtk.StateFlags.NORMAL) cr.set_source_rgba(bgcol.red, bgcol.blue, bgcol.green, bgcol.alpha) cr.paint() if img.rgbbuf: cairo_surface = cairo.ImageSurface.create_for_data(img.rgbbuf, cairo.FORMAT_RGB24, img.width, img.height, img.width * 4) cr.set_source_surface(cairo_surface, 0, 0) cr.paint() return True def window_destroy(widget, img): del img.window del img.scroll del img.darea def widget_delete(widget, *args): widget.hide_on_delete() def window_create(img): """ Create a gtk window """ img.window = Gtk.Window(Gtk.WindowType.TOPLEVEL) img.window.set_title("python gs"); img.vbox = Gtk.Box(orientation=Gtk.Orientation.VERTICAL) img.vbox.set_homogeneous(False) img.window.add(img.vbox) img.vbox.show() img.darea = Gtk.DrawingArea() img.darea.show() img.scroll = Gtk.ScrolledWindow(None, None) img.scroll.show() img.scroll.set_policy(Gtk.PolicyType.ALWAYS, Gtk.PolicyType.ALWAYS) img.scroll.add_with_viewport(img.darea) img.vbox.pack_start(img.scroll, True, True, 0) img.darea.connect('draw', window_draw, img) img.window.connect('destroy', window_destroy, img) img.window.connect('delete-event', widget_delete) # do not show img->window until we know the image size def window_resize(img): img.darea.set_size_request(img.width, img.height) visible = img.window.get_visible() if not visible: # We haven't yet shown the window, so set a default size # which is smaller than the desktop to allow room for # desktop toolbars, and if possible a little larger than # the image to allow room for the scroll bars. # We don't know the width of the scroll bars, so just guess. img.window.set_default_size( min(Gdk.Screen.width()-96, img.width+24), min(Gdk.Screen.height()-96, img.height+24) ) def window_separation(img, sep): img.devicen[sep].visible = not img.devicen[sep].visible display_sync(img.handle, img.device) def get_signal_separation(sep): def signal_sep_i(widget, img): window_separation(img, sep) return signal_sep_i def window_add_button(img, label, callback): w = Gtk.CheckButton.new_with_label(label or '') img.cmyk_bar.pack_start(w, False, False, 5) w.set_active(True) w.connect('clicked', callback, img) w.show() return w def signal_show_as_gray(widget, img): img.devicen_gray = not img.devicen_gray display_sync(img.handle, img.device) def display_open(handle, device): """ New device has been opened """ img = ImageData() # add to list images[(handle, device)] = img # remember device and handle img.handle = handle img.device = device # create window window_create(img); Gtk.main_iteration_do(False) return 0; def display_preclose(handle, device): img = image_find(handle, device) if img is None: return -1 Gtk.main_iteration_do(False) img.buf = None img.width = 0 img.height = 0 img.rowstride = 0 img.format = 0 img.window.destroy() img.window = None img.scroll = None img.darea = None img.rgbbuf = None Gtk.main_iteration_do(False) return 0; def display_close(handle, device): img = image_find(handle, device) if img is None: return -1 # remove from list del images[(handle, device)] return 0; def display_presize(handle, device, width, height, raster, format): # Assume everything is OK. # It would be better to return e_rangecheck if we can't # support the format. return 0; def display_size(handle, device, width, height, raster, format, pimage): img = image_find(handle, device) if img is None: return -1 img.rgbbuf = None img.width = width img.height = height img.rowstride = raster img.buf = pimage img.format = format # Reset separations for i in range(0, IMAGE_DEVICEN_MAX): img.devicen[i].used = 0 img.devicen[i].visible = True img.devicen[i].name = None img.devicen[i].cyan = 0 img.devicen[i].magenta = 0 img.devicen[i].yellow = 0 img.devicen[i].black = 0 color = img.format & gs.DISPLAY_COLORS_MASK depth = img.format & gs.DISPLAY_DEPTH_MASK alpha = img.format & gs.DISPLAY_ALPHA_MASK if color == gs.DISPLAY_COLORS_CMYK: if depth == gs.DISPLAY_DEPTH_1 or depth == gs.DISPLAY_DEPTH_8: # We already know about the CMYK components img.devicen[0].used = 1 img.devicen[0].cyan = 65535 img.devicen[0].name = 'Cyan' img.devicen[1].used = 1 img.devicen[1].magenta = 65535 img.devicen[1].name = 'Magenta' img.devicen[2].used = 1 img.devicen[2].yellow = 65535 img.devicen[2].name = 'Yellow' img.devicen[3].used = 1 img.devicen[3].black = 65535 img.devicen[3].name = 'Black' else: return gs.e_rangecheck # not supported elif color == gs.DISPLAY_COLORS_NATIVE \ and not (depth == gs.DISPLAY_DEPTH_8 or depth == gs.DISPLAY_DEPTH_16): return gs.e_rangecheck # not supported elif color == gs.DISPLAY_COLORS_GRAY and depth != gs.DISPLAY_DEPTH_8: return gs.e_rangecheck # not supported elif color == gs.DISPLAY_COLORS_RGB and depth != gs.DISPLAY_DEPTH_8: return gs.e_rangecheck # not supported elif color == gs.DISPLAY_COLORS_SEPARATION and depth != gs.DISPLAY_DEPTH_8: return gs.e_rangecheck # not supported if color == gs.DISPLAY_COLORS_CMYK or color == gs.DISPLAY_COLORS_SEPARATION: if not isinstance(img.cmyk_bar, Gtk.Widget): # add bar to select separation img.cmyk_bar = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL) img.cmyk_bar.set_homogeneous(False) img.vbox.pack_start(img.cmyk_bar, False, False, 0) for i in range(0, IMAGE_DEVICEN_MAX): img.separation[i] = window_add_button(img, img.devicen[i].name, get_signal_separation(i)) img.show_as_gray = Gtk.CheckButton.new_with_label('Show as Gray') img.cmyk_bar.pack_end(img.show_as_gray, False, False, 5) img.show_as_gray.set_active(False) img.show_as_gray.connect('clicked', signal_show_as_gray, img) img.show_as_gray.show() img.cmyk_bar.show() elif isinstance(img.cmyk_bar, Gtk.Widget): img.cmyk_bar.hide() window_resize(img) visible = img.window.get_visible() if not visible: img.window.show_all() Gtk.main_iteration_do(False) return 0 def display_sync(handle, device): """ This will set a pixel buffer to img.rgbbuf in the the cairo.FORMAT_RGB24 However the Format is documented as: "each pixel is a 32-bit quantity, with the upper 8 bits unused. Red, Green, and Blue are stored in the remaining 24 bits in that order." But on my local machine its BGRx not RGBx Real Alpha values where not tested just DISPLAY_ALPHA_NONE DISPLAY_UNUSED_FIRST and DISPLAY_UNUSED_LAST This should be in C or something like that, as most of it would be a hundred times faster See the case for the native cairo.FORMAT_RGB24. Thats the only fast case. """ img = image_find(handle, device) if img is None: return -1 color = img.format & gs.DISPLAY_COLORS_MASK depth = img.format & gs.DISPLAY_DEPTH_MASK endian = img.format & gs.DISPLAY_ENDIAN_MASK native555 = img.format & gs.DISPLAY_555_MASK alpha = img.format & gs.DISPLAY_ALPHA_MASK if (color == gs.DISPLAY_COLORS_CMYK) or (color == gs.DISPLAY_COLORS_SEPARATION): #check if separations have changed for i in range(0, IMAGE_DEVICEN_MAX): label = img.separation[i].get_label() if not img.devicen[i].used: img.separation[i].hide() elif img.devicen[i].name != label: # text has changed, update it img.separation[i].set_label(img.devicen[i].name) img.separation[i].show() # some formats need to be converted for use by GdkRgb if color == gs.DISPLAY_COLORS_NATIVE: if depth == gs.DISPLAY_DEPTH_16: if endian == gs.DISPLAY_LITTLEENDIAN: if native555 == gs.DISPLAY_NATIVE_555: # RGB555 # worked with # gs.DISPLAY_COLORS_NATIVE | gs.DISPLAY_DEPTH_16 | gs.DISPLAY_LITTLEENDIAN | gs.DISPLAY_NATIVE_555 img.rgbbuf = array('B') bufIdx = 0 stride = img.rowstride - (img.width * 2) for idx in range(0, img.height * img.width): if idx % img.width == 0 and idx != 0: bufIdx += stride w = img.buf[bufIdx] + (img.buf[bufIdx+1] << 8) value = w & 0x1f #blue img.rgbbuf.append((value << 3) + (value >> 2)) value = (w >> 5) & 0x1f #green img.rgbbuf.append((value << 3) + (value >> 2)) value = (w >> 10) & 0x1f #red img.rgbbuf.append( (value << 3) + (value >> 2)) img.rgbbuf.append(0) # x bufIdx += 2 else: # RGB565 # worked with # gs.DISPLAY_COLORS_NATIVE | gs.DISPLAY_DEPTH_16 | gs.DISPLAY_LITTLEENDIAN | gs.DISPLAY_NATIVE_565 img.rgbbuf = array('B') bufIdx = 0 stride = img.rowstride - (img.width * 2) for idx in range(0, img.height * img.width): if idx % img.width == 0 and idx != 0: bufIdx += stride w = img.buf[bufIdx] + (img.buf[bufIdx+1] << 8) value = w & 0x1f # blue img.rgbbuf.append((value << 3) + (value >> 2)) value = (w >> 5) & 0x3f # green img.rgbbuf.append((value << 2) + (value >> 4)) value = (w >> 11) & 0x1f #red img.rgbbuf.append((value << 3) + (value >> 2)) img.rgbbuf.append(0) # x bufIdx += 2 else: if native555 == gs.DISPLAY_NATIVE_555: # RGB555 # worked with # gs.DISPLAY_COLORS_NATIVE | gs.DISPLAY_DEPTH_16 | gs.DISPLAY_NATIVE_555 | gs.DISPLAY_BIGENDIAN img.rgbbuf = array('B') bufIdx = 0 stride = img.rowstride - (img.width * 2) for idx in range(0, img.height * img.width): if idx % img.width == 0 and idx != 0: bufIdx += stride w = img.buf[bufIdx+1] + (img.buf[bufIdx] << 8) value = w & 0x1f # blue img.rgbbuf.append((value << 3) + (value >> 2)) value = (w >> 5) & 0x1f # green img.rgbbuf.append((value << 3) + (value >> 2)) value = (w >> 10) & 0x1f #red img.rgbbuf.append((value << 3) + (value >> 2)) img.rgbbuf.append(0) # x bufIdx += 2 else: # RGB565 # worked with # gs.DISPLAY_COLORS_NATIVE | gs.DISPLAY_DEPTH_16 | gs.DISPLAY_NATIVE_565 | gs.DISPLAY_BIGENDIAN img.rgbbuf = array('B') bufIdx = 0 stride = img.rowstride - (img.width * 2) for idx in range(0, img.height * img.width): if idx % img.width == 0 and idx != 0: bufIdx += stride w = img.buf[bufIdx+1] + (img.buf[bufIdx] << 8) value = w & 0x1f # blue img.rgbbuf.append((value << 3) + (value >> 2)) value = (w >> 5) & 0x3f # green img.rgbbuf.append((value << 2) + (value >> 4)) value = (w >> 11) & 0x1f # red img.rgbbuf.append((value << 3) + (value >> 2)) img.rgbbuf.append(0) # x bufIdx += 2 if depth == gs.DISPLAY_DEPTH_8: # palette of 96 colors # worked with # gs.DISPLAY_COLORS_NATIVE | gs.DISPLAY_DEPTH_8 color = [[0,0,0]] * 96 one = 255 // 3 for i in range(0, 96): # 0->63 = 00RRGGBB, 64->95 = 010YYYYY if i < 64: color[i] = ( ((i & 0x30) >> 4) * one, # r ((i & 0x0c) >> 2) * one, # g (i & 0x03) * one # b ) else: value = i & 0x1f value = (value << 3) + (value >> 2) color[i] = (value, value, value) img.rgbbuf = array('B') bufIdx = 0 stride = img.rowstride - img.width for idx in range(0, img.height * img.width): if idx % img.width == 0 and idx != 0: bufIdx += stride w = img.buf[bufIdx] img.rgbbuf.extend([ color[w][2], # b color[w][1], # g color[w][0], # r 0 # x ]) bufIdx += 1 elif color == gs.DISPLAY_COLORS_GRAY: if depth == gs.DISPLAY_DEPTH_8: # gray 8 bit # worked with # gs.DISPLAY_COLORS_GRAY | gs.DISPLAY_DEPTH_8 img.rgbbuf = array('B') bufIdx = 0 stride = img.rowstride - img.width for idx in range(0, img.height * img.width): if idx % img.width == 0 and idx != 0: bufIdx += stride w = img.buf[bufIdx] img.rgbbuf.extend([ w, # b w, # g w, # r 0 # x ]) bufIdx += 1 elif color == gs.DISPLAY_COLORS_RGB: if depth == gs.DISPLAY_DEPTH_8 and ( alpha == gs.DISPLAY_ALPHA_FIRST or alpha == gs.DISPLAY_UNUSED_FIRST ) and endian == gs.DISPLAY_BIGENDIAN: # xRGB # worked with # gs.DISPLAY_COLORS_RGB | gs.DISPLAY_UNUSED_FIRST | gs.DISPLAY_DEPTH_8 | gs.DISPLAY_BIGENDIAN img.rgbbuf = array('B') bufIdx = 0 stride = img.rowstride - (img.width * 4) for idx in range(0, img.height * img.width): if idx % img.width == 0 and idx != 0: bufIdx += stride # img.buf[bufIdx] x = filler img.rgbbuf.extend([ img.buf[bufIdx + 3], # b img.buf[bufIdx + 2], # g img.buf[bufIdx + 1], # r 0 # x ]) bufIdx += 4 elif depth == gs.DISPLAY_DEPTH_8 and endian == gs.DISPLAY_LITTLEENDIAN: if alpha == gs.DISPLAY_UNUSED_LAST or alpha == gs.DISPLAY_ALPHA_LAST: # cairo.FORMAT_RGB24 BGRx. no conversation is needed to display this with cairo # worked with # gs.DISPLAY_COLORS_RGB | gs.DISPLAY_UNUSED_LAST | gs.DISPLAY_DEPTH_8 | gs.DISPLAY_LITTLEENDIAN bufIdx = 0 hasStride = img.rowstride > img.width * 4 if not hasStride: # fast buffer_size = img.height * img.width * 4 img.rgbbuf = c.create_string_buffer(buffer_size) c.memmove(img.rgbbuf, img.buf, buffer_size) else: # slow. This has a stride between the rows, what is a bad thing # thus we can't copy the buffer directly, like above img.rgbbuf = array('B') for y in range(0, img.height): bufIdx = y * img.rowstride img.rgbbuf.extend(img.buf[bufIdx:bufIdx+img.width * 4]) elif alpha == gs.DISPLAY_UNUSED_FIRST or alpha == gs.DISPLAY_ALPHA_FIRST: # xBGR # worked with # gs.DISPLAY_COLORS_RGB | gs.DISPLAY_UNUSED_FIRST | gs.DISPLAY_DEPTH_8 | gs.DISPLAY_LITTLEENDIAN img.rgbbuf = array('B') bufIdx = 0 stride = img.rowstride - (img.width * 4) for idx in range(0, img.height * img.width): if idx % img.width == 0 and idx != 0: bufIdx += stride img.rgbbuf.extend([ img.buf[bufIdx + 1], # r img.buf[bufIdx + 2], # g img.buf[bufIdx + 3], # b 0 # x ]) bufIdx += 4 else: # BGR24 # worked with # gs.DISPLAY_COLORS_RGB | gs.DISPLAY_UNUSED_FIRST | gs.DISPLAY_DEPTH_8 | gs.DISPLAY_ALPHA_NONE img.rgbbuf = array('B') bufIdx = 0 stride = img.rowstride - (img.width * 3) for idx in range(0, img.height * img.width): if idx % img.width == 0 and idx != 0: bufIdx += stride img.rgbbuf.extend([ img.buf[bufIdx ], # b img.buf[bufIdx + 1], # g img.buf[bufIdx + 2], # r 0 # x ]) bufIdx += 3 elif depth == gs.DISPLAY_DEPTH_8 and alpha == gs.DISPLAY_ALPHA_NONE \ and endian == gs.DISPLAY_BIGENDIAN: # RGB24 # worked with: # gs.DISPLAY_COLORS_RGB | gs.DISPLAY_ALPHA_NONE | gs.DISPLAY_DEPTH_8 | gs.DISPLAY_BIGENDIAN img.rgbbuf = array('B') bufIdx = 0 stride = img.rowstride - (img.width * 3) for idx in range(0, img.height * img.width): if idx % img.width == 0 and idx != 0: bufIdx += stride img.rgbbuf.extend([ img.buf[bufIdx + 2], # b img.buf[bufIdx + 1], # g img.buf[bufIdx + 0], # r 0 # x ]) bufIdx += 3 elif color == gs.DISPLAY_COLORS_CMYK: if depth == gs.DISPLAY_DEPTH_8: # worked with: # gs.DISPLAY_COLORS_CMYK | gs.DISPLAY_ALPHA_NONE | gs.DISPLAY_DEPTH_8 | gs.DISPLAY_BIGENDIAN vc = img.devicen[0].visible vm = img.devicen[1].visible vy = img.devicen[2].visible vk = img.devicen[3].visible vall = vc and vm and vy and vk show_gray = (vc + vm + vy + vk == 1) and img.devicen_gray img.rgbbuf = array('B') bufIdx = 0 stride = img.rowstride - (img.width * 4) for idx in range(0, img.height * img.width): if idx % img.width == 0 and idx != 0: bufIdx += stride cyan = img.buf[bufIdx ] magenta = img.buf[bufIdx + 1] yellow = img.buf[bufIdx + 2] black = img.buf[bufIdx + 3] if not vall: if not vc: cyan = 0 if not vm: magenta = 0 if not vy: yellow = 0 if not vk: black = 0 if show_gray: black += cyan + magenta + yellow cyan = magenta = yellow = 0 img.rgbbuf.extend([ (255-yellow) * (255-black) // 255, # b (255-magenta) * (255-black) // 255, # g (255-cyan) * (255-black) // 255, # r 0 # x ]) bufIdx += 4 elif depth == gs.DISPLAY_DEPTH_1: # worked with: # gs.DISPLAY_COLORS_CMYK | gs.DISPLAY_ALPHA_NONE | gs.DISPLAY_DEPTH_1 | gs.DISPLAY_BIGENDIAN vc = img.devicen[0].visible vm = img.devicen[1].visible vy = img.devicen[2].visible vk = img.devicen[3].visible vall = vc and vm and vy and vk show_gray = (vc + vm + vy + vk == 1) and img.devicen_gray img.rgbbuf = array('B') for y in range(0, img.height): bufIdx = y * img.rowstride for x in range(0, img.width): value = img.buf[bufIdx + x//2] # (x & 0) always evaluates to 0. What are you trying to do? # If you're trying to test the bit, you want to do "!(x & 1)". # if x & 0: if not (x & 1): value >>= 4 cyan = ((value >> 3) & 1) * 255 magenta = ((value >> 2) & 1) * 255 yellow = ((value >> 1) & 1) * 255 black = ( value & 1) * 255 if not vall: if not vc: cyan = 0 if not vm: magenta = 0 if not vy: yellow = 0 if not vk: black = 0 if show_gray: black += cyan + magenta + yellow cyan = magenta = yellow = 0 img.rgbbuf.extend([ (255-yellow) * (255-black) // 255, # b (255-magenta) * (255-black) // 255, # g (255-cyan) * (255-black) // 255, # r 0 # x ]) elif color == gs.DISPLAY_COLORS_SEPARATION: if depth == gs.DISPLAY_DEPTH_8: # worked with: # gs.DISPLAY_COLORS_SEPARATION | gs.DISPLAY_ALPHA_NONE | gs.DISPLAY_DEPTH_8 | gs.DISPLAY_BIGENDIAN num_comp = 0 num_visible = 0 show_gray = False for j in range(0, IMAGE_DEVICEN_MAX): if img.devicen[j].used: num_comp = j+1 if img.devicen[j].visible: num_visible += 1 if num_visible == 1 and img.devicen_gray: show_gray = True img.rgbbuf = array('B') bufIdx = 0 stride = img.rowstride - (img.width * 8) for idx in range(0, img.height * img.width): if idx % img.width == 0 and idx != 0: bufIdx += stride cyan = magenta = yellow = black = 0 if show_gray: for j in range(0, num_comp): devicen = img.devicen[j] if devicen.visible and devicen.used: black += img.buf[bufIdx + j] else: for j in range(0, num_comp): devicen = img.devicen[j] if devicen.visible and devicen.used: value = img.buf[bufIdx + j] cyan += value * devicen.cyan // 65535 magenta += value * devicen.magenta // 65535 yellow += value * devicen.yellow // 65535 black += value * devicen.black // 65535 cyan = min(255, cyan) magenta = min(255, magenta) yellow = min(255, yellow) black = min(255, black) img.rgbbuf.extend([ (255-yellow) * (255-black) // 255, # b (255-magenta) * (255-black) // 255, # g (255-cyan) * (255-black) // 255, # r 0 # x ]) bufIdx += 8 if not isinstance(img.window, Gtk.Widget): window_create(img) window_resize(img) visible = img.window.get_visible() if not visible: img.window.show_all() img.darea.queue_draw() Gtk.main_iteration_do(False) return 0 def display_page(handle, device, copies, flush): display_sync(handle, device) return 0; def display_update(handle, device, x, y, w, h): """ not implemented - eventually this will be used for progressive update """ return 0 def display_separation(handle, device, comp_num, name, c, m, y, k): """ setup the colors for each used ink""" img = image_find(handle, device) if img is None: return -1 if comp_num < 0 or comp_num > IMAGE_DEVICEN_MAX: return -1 img.devicen[comp_num].used = 1 img.devicen[comp_num].name = name img.devicen[comp_num].cyan = c img.devicen[comp_num].magenta = m img.devicen[comp_num].yellow = y img.devicen[comp_num].black = k return 0 # callback structure for "display" device display = gs.Display_callback_s( c.c_int(c.sizeof(gs.Display_callback_s)), c.c_int(gs.DISPLAY_VERSION_MAJOR), c.c_int(gs.DISPLAY_VERSION_MINOR), gs.c_display_open(display_open), gs.c_display_preclose(display_preclose), gs.c_display_close(display_close), gs.c_display_presize(display_presize), gs.c_display_size(display_size), gs.c_display_sync(display_sync), gs.c_display_page(display_page), #gs.c_display_update(display_update), c.cast(None, gs.c_display_update), c.cast(None, gs.c_display_memalloc), # NULL, /* memalloc */ c.cast(None, gs.c_display_memfree), # NULL, /* memfree */ gs.c_display_separation(display_separation) ) def main(argv): code = 1 use_gui, _ = Gtk.init_check(argv) # insert display device parameters as first arguments # this controls the format of the pixbuf that ghostscript will deliver # see display_sync for details # fast CAIRO_FORMAT_RGB24 = gs.DISPLAY_COLORS_RGB | gs.DISPLAY_UNUSED_LAST | \ gs.DISPLAY_DEPTH_8 | gs.DISPLAY_LITTLEENDIAN # interesting SEPARATION_FORMAT = gs.DISPLAY_COLORS_SEPARATION | gs.DISPLAY_ALPHA_NONE | \ gs.DISPLAY_DEPTH_8 | gs.DISPLAY_BIGENDIAN # if there are spot colors they are mixed into the cmyk values CMYK_FORMAT = gs.DISPLAY_COLORS_CMYK | gs.DISPLAY_ALPHA_NONE | \ gs.DISPLAY_DEPTH_8 | gs.DISPLAY_BIGENDIAN dformat = "-dDisplayFormat=%d" % \ ( CAIRO_FORMAT_RGB24 | gs.DISPLAY_TOPFIRST ) nargv = [argv[0], dformat] + argv[1:] #run Ghostscript try: instance = gs.new_instance() gs.set_stdio(instance, gsdll_stdin, None, None) if use_gui: gs.set_display_callback(instance, c.byref(display)) code = gs.init_with_args(instance, nargv) if code == 0: code = gs.run_string(instance, start_string) code1 = gs.exit(instance) if code == 0 or code == gs.e_Quit: code = code1 if code == gs.e_Quit: code = 0 # user executed 'quit' gs.delete_instance(instance) except gs.GhostscriptError as e: code = e.code sys.stderr.write(e.message) finally: exit_status = 0; if code in [0, gs.e_Info, gs.e_Quit]: pass elif code == gs.e_Fatal: exit_status = 1 else: exit_status = 255 return exit_status if __name__ == '__main__': code = main(sys.argv) sys.stdout.write('\n') # or bash will get out of sync ... sys.exit(code) python-ghostscript-0.7/examples/gs.py000066400000000000000000000023141402072270500200500ustar00rootroot00000000000000#!/usr/bin/env python # -*- coding: utf-8 -*- # # This file is part of python-ghostscript. # Copyright 2010-2021 by Hartmut Goebel # # 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 . # __author__ = "Hartmut Goebel " __copyright__ = "Copyright 2010-2021 by Hartmut Goebel " __licence__ = "GNU General Public License version 3 (GPL v3)" import sys import ghostscript import locale encoding = locale.getpreferredencoding() # arguments have to be bytes, encode them args = sys.argv args = [a.encode(encoding) for a in args] ghostscript.Ghostscript(*args) python-ghostscript-0.7/examples/lowlevel1.py000066400000000000000000000031111402072270500213450ustar00rootroot00000000000000#!/usr/bin/env python # -*- coding: utf-8 -*- # # This file is part of python-ghostscript. # Copyright 2010-2021 by Hartmut Goebel # # 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 . # __author__ = "Hartmut Goebel " __copyright__ = "Copyright 2010-2021 by Hartmut Goebel " __licence__ = "GNU General Public License version 3 (GPL v3)" __credits__ = "Based on an example from http://www.ghostscript.com/doc/8.63/API.htm" import sys from ghostscript import _gsprint as gs args = [ b"ps2pdf", # actual value doesn't matter b"-dNOPAUSE", b"-dBATCH", b"-dSAFER", b"-sDEVICE=pdfwrite", b"-sOutputFile=/tmp/out.pdf", b"-c", b".setpdfwrite", b"-f", b"test.ps" ] instance = gs.new_instance() code = gs.init_with_args(instance, args) code1 = gs.exit(instance) if code == 0 or code == gs.e_Quit: code = code1 gs.delete_instance(instance) if not (code == 0 or code == gs.e_Quit): sys.exit(1) python-ghostscript-0.7/examples/lowlevel2.py000066400000000000000000000033241402072270500213540ustar00rootroot00000000000000#!/usr/bin/env python # -*- coding: utf-8 -*- # # This file is part of python-ghostscript. # Copyright 2010-2021 by Hartmut Goebel # # 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 . # __author__ = "Hartmut Goebel " __copyright__ = "Copyright 2010-2021 by Hartmut Goebel " __licence__ = "GNU General Public License version 3 (GPL v3)" __credits__ = "Based on an example from http://www.ghostscript.com/doc/8.63/API.htm" import sys from ghostscript import _gsprint as gs import locale start_string = b"systemdict /start get exec\n" # arguments have to be bytes, encode them encoding = locale.getpreferredencoding() args = sys.argv args = [a.encode(encoding) for a in args] instance = gs.new_instance() # no benefit in using set_stdio() #gs.set_stdio(isntance, gsdll_stdin, gsdll_stdout, gsdll_stderr) code = gs.init_with_args(instance, args) if code == 0: code = gs.run_string(instance, start_string) code1 = gs.exit(instance) if code == 0 or code == gs.e_Quit: code = code1 gs.delete_instance(instance) if not (code == 0 or code == gs.e_Quit): sys.exit(1) python-ghostscript-0.7/examples/lowlevel3.py000066400000000000000000000035461402072270500213630ustar00rootroot00000000000000#!/usr/bin/env python # -*- coding: utf-8 -*- # # This file is part of python-ghostscript. # Copyright 2010-2021 by Hartmut Goebel # # 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 . # __author__ = "Hartmut Goebel " __copyright__ = "Copyright 2010-2021 by Hartmut Goebel " __licence__ = "GNU General Public License version 3 (GPL v3)" __credits__ = "Based on an example from http://www.ghostscript.com/doc/8.63/API.htm" import sys from ghostscript import _gsprint as gs import locale command = b"1 2 add == flush\n" # arguments have to be bytes, encode them encoding = locale.getpreferredencoding() args = sys.argv args = [a.encode(encoding) for a in args] instance = gs.new_instance() # no benefit in using set_stdio() #gs.set_stdio(isntance, gsdll_stdin, gsdll_stdout, gsdll_stderr) code = gs.init_with_args(instance, args) if code == 0: gs.run_string_begin(instance); gs.run_string_continue(instance, command); gs.run_string_continue(instance, b"qu"); gs.run_string_continue(instance, b"it"); gs.run_string_end(instance); code1 = gs.exit(instance) if code == 0 or code == gs.e_Quit: code = code1 gs.delete_instance(instance) if not (code == 0 or code == gs.e_Quit): sys.exit(1) python-ghostscript-0.7/examples/ps2pdf.py000066400000000000000000000047271402072270500206470ustar00rootroot00000000000000#!/usr/bin/env python """ This is a rough Python implementation of the shellscript ps2pdfwr which comes with Ghostscript. """ # -*- coding: utf-8 -*- # # This file is part of python-ghostscript. # Copyright 2010-2021 by Hartmut Goebel # # 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 . # __author__ = "Hartmut Goebel " __copyright__ = "Copyright 2010-2021 by Hartmut Goebel " __licence__ = "GNU General Public License version 3 (GPL v3)" import sys import os import locale encoding = locale.getpreferredencoding() import ghostscript options = ["-dSAFER"] args = sys.argv[1:] while args: arg = args[0] if arg.startswith('-') and len(arg) > 1: options.append(arg) arg = args.pop(0) else: break def usage(): print("Usage:", os.path.basename(sys.argv[0]), "[options...] (input.[e]ps|-) [output.pdf|-]", file=sys.stderr) sys.exit(1) if len(args) not in (1,2): usage() infile = args[0] if len(args) == 1: if infile == '-': outfile = '-' else: base, ext = os.path.splitext(os.path.basename(infile)) if ext in ('.ps', '.eps'): outfile = base + '.pdf' else: outfile = base + ext + '.pdf' else: outfile = args[1] # We have to include the options twice because -I only takes effect if # it appears before other options. args = [os.path.basename(sys.argv[0])] # actual value doesn't matter args.extend(options) args.extend(["-q", "-dNOPAUSE","-dBATCH", "-sDEVICE=pdfwrite", "-sstdout=%stderr", "-sOutputFile=" + outfile]) args.extend(options) args.extend(["-c", ".setpdfwrite", "-f", infile]) # arguments have to be bytes, encode them args = [a.encode(encoding) for a in args] # After all these preperations, calling Ghostscript is a piece of cake: ghostscript.Ghostscript(*args) python-ghostscript-0.7/examples/run-dxmain.sh000066400000000000000000000003171402072270500215040ustar00rootroot00000000000000#!/bin/sh if [ -z "$PYTHON" ] ; then PYTHON=python ; fi cd $(dirname $0) PYTHONPATH=$(realpath ..):$PYTHONPATH $PYTHON ./dxmain.py -dBATCH -sDEVICE=display \ -sDEFAULTPAPERSIZE=a5 -dFitPage ./test.ps python-ghostscript-0.7/examples/run-string.bat000066400000000000000000000015521402072270500216700ustar00rootroot00000000000000@REM based on http://bugs.python.org/file13578/install_scripts.py @echo off set SCRIPT=%~dp0\run-string.py set PYTHON=C:\Python27\python.exe set SCRIPT_ERRORLEVEL= @REM Credit where credit is due: we return the exit code despite our @REM use of setlocal+endlocal using a technique from Bear's Journal: @REM http://code-bear.com/bearlog/2007/06/01/getting-the-exit-code-from-a-batch-file-that-is-run-from-a-python-program/ setlocal @REM ensure the script will be executed with the Python it was installed for set path=%~dp0;%~dp0..;%path% %PYTHON% "%SCRIPT%" %* endlocal & set SCRIPT_ERRORLEVEL=%ERRORLEVEL% if NOT "%COMSPEC%" == "%SystemRoot%\\system32\\cmd.exe" goto returncode if errorlevel 9009 echo You do not have python in your PATH. goto endscript :returncode exit /B %SCRIPT_ERRORLEVEL% :endscript call :returncode %SCRIPT_ERRORLEVEL% python-ghostscript-0.7/examples/run-string.py000066400000000000000000000030361402072270500215510ustar00rootroot00000000000000#!/usr/bin/env python """ Simple test program using run_string() and run_file() """ # -*- coding: utf-8 -*- # # This file is part of python-ghostscript. # Copyright 2010-2021 by Hartmut Goebel # # 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 . # __author__ = "Hartmut Goebel " __copyright__ = "Copyright 2010-2021 by Hartmut Goebel " __licence__ = "GNU General Public License version 3 (GPL v3)" doc = b"""%! /Helvetica findfont 20 scalefont setfont 50 50 moveto (Hallo \(W \)elt!) show 1 0 0 setrgbcolor <416c6c20646f6e652e> show 0 1 0 setrgbcolor <48616c6c6f205c2857205c29656c5c7421> show showpage """ import io import ghostscript args = b"""test.py -dNOPAUSE -dBATCH -dSAFER -sDEVICE=pdfwrite -sOutputFile=/tmp/out.pdf -c .setpdfwrite""".split() GS = ghostscript.Ghostscript(*args) try: GS.run_string(doc) GS.run_file(io.BytesIO(doc)) finally: GS.exit() python-ghostscript-0.7/examples/test-gs.sh000066400000000000000000000003621402072270500210100ustar00rootroot00000000000000#!/bin/sh if [ -z "$PYTHON" ] ; then PYTHON=python ; fi cd $(dirname $0) PYTHONPATH=$(realpath ..):$PYTHONPATH $PYTHON ./gs.py \ -dNOPAUSE -dBATCH -dSAFER -sDEVICE=pdfwrite -sOutputFile=/tmp/out.pdf \ -c .setpdfwrite -f ./test.ps python-ghostscript-0.7/examples/test-lowlevel1.sh000066400000000000000000000002111402072270500223020ustar00rootroot00000000000000#!/bin/sh if [ -z "$PYTHON" ] ; then PYTHON=python ; fi cd $(dirname $0) PYTHONPATH=$(realpath ..):$PYTHONPATH $PYTHON ./lowlevel1.py python-ghostscript-0.7/examples/test-lowlevel2.sh000066400000000000000000000003701402072270500223110ustar00rootroot00000000000000#!/bin/sh if [ -z "$PYTHON" ] ; then PYTHON=python ; fi cd $(dirname $0) PYTHONPATH=$(realpath ..):$PYTHONPATH $PYTHON ./lowlevel2.py \ -dNOPAUSE -dBATCH -dSAFER -sDEVICE=pdfwrite -sOutputFile=/tmp/out.pdf \ -c .setpdfwrite -f ./test.ps python-ghostscript-0.7/examples/test-lowlevel3.sh000066400000000000000000000003711402072270500223130ustar00rootroot00000000000000#!/bin/sh if [ -z "$PYTHON" ] ; then PYTHON=python ; fi cd $(dirname $0) PYTHONPATH=$(realpath ..):$PYTHONPATH $PYTHON ./lowlevel3.py \ -dNOPAUSE -dBATCH -dSAFER -sDEVICE=pdfwrite -sOutputFile=/tmp/out.pdf \ -c .setpdfwrite -f ./test.ps python-ghostscript-0.7/examples/test-ps2pdf.sh000066400000000000000000000002351402072270500215740ustar00rootroot00000000000000#!/bin/sh if [ -z "$PYTHON" ] ; then PYTHON=python ; fi cd $(dirname $0) PYTHONPATH=$(realpath ..):$PYTHONPATH $PYTHON ./ps2pdf.py ./test.ps /tmp/out.pdf python-ghostscript-0.7/examples/test.ps000066400000000000000000000003021402072270500204030ustar00rootroot00000000000000%! /Helvetica findfont 20 scalefont setfont 50 50 moveto (Hallo \(W \)elt!) show 1 0 0 setrgbcolor <416c6c20646f6e652e> show 0 1 0 setrgbcolor <48616c6c6f205c2857205c29656c5c7421> show showpage python-ghostscript-0.7/ghostscript/000077500000000000000000000000001402072270500176205ustar00rootroot00000000000000python-ghostscript-0.7/ghostscript/__init__.py000066400000000000000000000133551402072270500217400ustar00rootroot00000000000000#!/usr/bin/env python # -*- coding: utf-8 -*- """ ghostscript - A Python interface for the Ghostscript interpreter C-API """ # # This file is part of python-ghostscript. # Copyright 2010-2021 by Hartmut Goebel # # 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 . # __author__ = "Hartmut Goebel " __copyright__ = "Copyright 2010-2021 by Hartmut Goebel " __licence__ = "GNU General Public License version 3 (GPL v3)" __all__ = ['Ghostscript', 'revision', 'GhostscriptError', 'PleaseDisplayUsage'] import sys # :todo: remove, debugging only from . import _gsprint as gs __version__ = gs.__version__ GhostscriptError = gs.GhostscriptError class PleaseDisplayUsage(Warning): """ This exception is raised when Ghostscript asks the application to display the usage. The application should catch the exception an print the usage message. """ pass def revision(): """ This function returns the revision numbers and strings of the Ghostscript interpreter library as a dict. You should call it before any other interpreter library functions to make sure that the correct version of the Ghostscript interpreter has been loaded. """ rev = gs.revision() # we assume that the underlying function returns utf-8 strings return { "product": rev.product.decode('utf-8'), "copyright": rev.copyright.decode('utf-8'), "revision": rev.revision, "revisiondate": rev.revisiondate } MAX_STRING_LENGTH = gs.MAX_STRING_LENGTH class Ghostscript(object): @staticmethod def revision(): return revision() def __init__(self, *args, stdin=None, stdout=None, stderr=None): assert self.revision()['revision'] >= 908, \ "high-level interface requires ghostscript >= 9.08" self._callbacks = None self._instance = gs.new_instance() if not isinstance(args[0], str): import warnings warnings.warn( "Passing bytes-arguments to 'Ghostscript()' is deprecated", DeprecationWarning, stacklevel=2) else: gs.set_arg_encoding(self._instance, gs.ARG_ENCODING_UTF8) args = [a.encode('utf-8') for a in args] try: self.set_stdio(stdin, stdout, stderr) rc = gs.init_with_args(self._instance, args) if rc == gs.e_Info: raise PleaseDisplayUsage() if rc == gs.e_Quit: self.exit() except: self.exit() raise def __enter__(self): return self def __exit__(self, *args): self.exit() def set_stdio(self, stdin=None, stdout=None, stderr=None): """Set stdin, stdout and stderr of the ghostscript interpreter. The ``stdin`` stream has to support the ``readline()`` interface. The ``stdout`` and ``stderr`` streams have to support the ``write()`` and ``flush()`` interface. Please note that this does not affect the input- and output- streams of the devices. Esp. setting stdout does not allow catching the devise-output even when using ``-sOutputFile=-``. """ if not stdin and not stdout and not stderr: return self._callbacks = ( stdin and gs._wrap_stdin(stdin) or None, stdout and gs._wrap_stdout(stdout) or None, stderr and gs._wrap_stderr(stderr) or None, ) gs.set_stdio(self._instance, *self._callbacks) def __del__(self): self.exit() def exit(self): if self._instance: try: gs.exit(self._instance) gs.delete_instance(self._instance) finally: self._instance = None def run_string(self, str, user_errors=False): """ Run the string ``str`` by Ghostscript This takes care of Ghostscripts size-limitations and passes the string in pieces if necessary. """ instance = self._instance if len(str) < MAX_STRING_LENGTH: gs.run_string(instance, str) else: gs.run_string_begin(instance) for start in range(0, len(str), MAX_STRING_LENGTH): gs.run_string_continue(instance, str[start:start+MAX_STRING_LENGTH]) gs.run_string_end(instance) def run_filename(self, filename, user_errors=False): """ Run the file named by ``filename`` by Ghostscript """ return gs.run_file(self._instance, filename, user_errors) def run_file(self, file, user_errors=False): """ Read ``file`` and run the content by Ghostscript. ``file`` must already by opened and may by any file-like object supporting the ``read()`` method. """ instance = self._instance gs.run_string_begin(instance) while True: str = file.read(MAX_STRING_LENGTH) if not str: break gs.run_string_continue(instance, str) gs.run_string_end(instance) def cleanup(): pass python-ghostscript-0.7/ghostscript/_errors.py000066400000000000000000000122351402072270500216500ustar00rootroot00000000000000""" Definition of Ghostscript error codes """ # # This file is part of python-ghostscript. # Copyright (C) 2010-2018 by Hartmut Goebel # # Based on iapi.h which is # Copyright (C) 1989, 1995, 1998, 1999 Aladdin Enterprises. All rights reserved. # # 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 . # __author__ = "Hartmut Goebel " __copyright__ = "Copyright 2010-2021 by Hartmut Goebel " __licence__ = "GNU General Public License version 3 (GPL v3)" # # A procedure that may return an error always returns # a non-negative value (zero, unless otherwise noted) for success, # or negative for failure. # We use ints rather than an enum to avoid a lot of casting. # # ------ PostScript Level 1 errors ------ e_unknownerror = -1 # unknown error e_dictfull = -2 e_dictstackoverflow = -3 e_dictstackunderflow = -4 e_execstackoverflow = -5 e_interrupt = -6 # We also need to define gs_error_interrupt, for gpcheck.h gs_error_interrupt = e_interrupt e_invalidaccess = -7 e_invalidexit = -8 e_invalidfileaccess = -9 e_invalidfont = -10 e_invalidrestore = -11 e_ioerror = -12 e_limitcheck = -13 e_nocurrentpoint = -14 e_rangecheck = -15 e_stackoverflow = -16 e_stackunderflow = -17 e_syntaxerror = -18 e_timeout = -19 e_typecheck = -20 e_undefined = -21 e_undefinedfilename = -22 e_undefinedresult = -23 e_unmatchedmark = -24 e_VMerror = -25 LEVEL1_ERROR_NAMES = ["unknownerror", "dictfull", "dictstackoverflow", "dictstackunderflow", "execstackoverflow", "interrupt", "invalidaccess", "invalidexit", "invalidfileaccess", "invalidfont", "invalidrestore", "ioerror", "limitcheck", "nocurrentpoint", "rangecheck", "stackoverflow", "stackunderflow", "syntaxerror", "timeout", "typecheck", "undefined", "undefinedfilename", "undefinedresult", "unmatchedmark", "VMerror"] # ------ Additional Level 2 and DPS errors ------ e_configurationerror = -26 e_invalidcontext = -27 e_undefinedresource = -28 e_unregistered = -29 # invalidid is for the NeXT DPS extension. e_invalidid = -30 LEVEL2_ERROR_NAMES = ["configurationerror", "invalidcontext", "undefinedresource", "unregistered", "invalidid"] ERROR_NAMES = LEVEL1_ERROR_NAMES + LEVEL2_ERROR_NAMES _PSEUDO_ERRORS = ['Fatal', 'Quit', 'InterpreterExit', 'RemapColor', 'ExecStackUnderflow', 'VMreclaim', 'NeedInput', 'NeedStdin', 'NeedStdout', 'NeedStderr', 'Info'] def error2name(ecode): if ecode <= e_Fatal: return _PSEUDO_ERRORS[-ecode-100] else: return ERROR_NAMES[-ecode-1] # ------ Pseudo-errors used internally ------ # # Internal code for a fatal error. # gs_interpret also returns this for a .quit with a positive exit code. # e_Fatal = -100 # # Internal code for the .quit operator. # The real quit code is an integer on the operand stack. # gs_interpret returns this only for a .quit with a zero exit code. # e_Quit = -101 # # Internal code for a normal exit from the interpreter. # Do not use outside of interp.c. # e_InterpreterExit = -102 # # Internal code that indicates that a procedure has been stored in the # remap_proc of the graphics state, and should be called before retrying # the current token. This is used for color remapping involving a call # back into the interpreter -- inelegant, but effective. # e_RemapColor = -103 # # Internal code to indicate we have underflowed the top block # of the e-stack. # e_ExecStackUnderflow = -104 # # Internal code for the vmreclaim operator with a positive operand. # We need to handle this as an error because otherwise the interpreter # won't reload enough of its state when the operator returns. # e_VMreclaim = -105 # # Internal code for requesting more input from run_string. # e_NeedInput = -106 # # Internal code for stdin callout. # e_NeedStdin = -107 # # Internal code for stdout callout. # e_NeedStdout = -108 # # Internal code for stderr callout. # e_NeedStderr = -109 # # Internal code for a normal exit when usage info is displayed. # This allows Window versions of Ghostscript to pause until # the message can be read. # e_Info = -110 # # Define which error codes require re-executing the current object. # def ERROR_IS_INTERRUPT(ecode): return ecode == e_interrupt or ecode == e_timeout if __name__ == '__main__': print(error2name(e_unknownerror) == "unknownerror") print(error2name(e_VMerror) == "VMerror") print(error2name(e_invalidid) == "invalidid") print(error2name(e_VMreclaim) == "VMreclaim") python-ghostscript-0.7/ghostscript/_gsprint.py000066400000000000000000000422521402072270500220240ustar00rootroot00000000000000#!/usr/bin/env python # -*- coding: utf-8 -*- """ ghostscript._gsprint - A low-lewel interface to the Ghostscript C-API using ctypes """ # # This file is part of python-ghostscript. # Copyright 2010-2021 by Hartmut Goebel # # Display_callback Structure by Lasse Fister in 2013 # # 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 . # __author__ = "Hartmut Goebel " __copyright__ = "Copyright 2010-2021 by Hartmut Goebel " __licence__ = "GNU General Public License version 3 (GPL v3)" __version__ = "0.7" from ctypes import * import sys from ._errors import * MAX_STRING_LENGTH = 65535 ARG_ENCODING_LOCAL = 0 ARG_ENCODING_UTF8 = 1 ARG_ENCODING_UTF16LE = 2 DISPLAY_VERSION_MAJOR = 2 DISPLAY_VERSION_MINOR = 0 DISPLAY_VERSION_MAJOR_V1 = 1 # before separation format was added DISPLAY_VERSION_MINOR_V1 = 0 # The display format is set by a combination of the following bitfields # Define the color space alternatives # DISPLAY_FORMAT_COLOR DISPLAY_COLORS_NATIVE = (1<<0) DISPLAY_COLORS_GRAY = (1<<1) DISPLAY_COLORS_RGB = (1<<2) DISPLAY_COLORS_CMYK = (1<<3) DISPLAY_COLORS_SEPARATION = (1<<19) DISPLAY_COLORS_MASK = 0x8000f # Define whether alpha information, or an extra unused bytes is included # DISPLAY_ALPHA_FIRST and DISPLAY_ALPHA_LAST are not implemented # DISPLAY_FORMAT_ALPHA DISPLAY_ALPHA_NONE = (0<<4) DISPLAY_ALPHA_FIRST = (1<<4) DISPLAY_ALPHA_LAST = (1<<5) DISPLAY_UNUSED_FIRST = (1<<6) # e.g. Mac xRGB DISPLAY_UNUSED_LAST = (1<<7) # e.g. Windows BGRx DISPLAY_ALPHA_MASK = 0x00f0 # Define the depth per component for DISPLAY_COLORS_GRAY, # DISPLAY_COLORS_RGB and DISPLAY_COLORS_CMYK, # or the depth per pixel for DISPLAY_COLORS_NATIVE # DISPLAY_DEPTH_2 and DISPLAY_DEPTH_12 have not been tested. # DISPLAY_FORMAT_DEPTH DISPLAY_DEPTH_1 = (1<< 8) DISPLAY_DEPTH_2 = (1<< 9) DISPLAY_DEPTH_4 = (1<<10) DISPLAY_DEPTH_8 = (1<<11) DISPLAY_DEPTH_12 = (1<<12) DISPLAY_DEPTH_16 = (1<<13) # unused (1<<14) # unused (1<<15) DISPLAY_DEPTH_MASK = 0xff00 # Define whether Red/Cyan should come first, # or whether Blue/Black should come first # DISPLAY_FORMAT_ENDIAN DISPLAY_BIGENDIAN = (0<<16) # Red/Cyan first DISPLAY_LITTLEENDIAN = (1<<16) # Blue/Black first DISPLAY_ENDIAN_MASK = 0x00010000 # Define whether the raster starts at the top or bottom of the bitmap # DISPLAY_FORMAT_FIRSTROW DISPLAY_TOPFIRST = (0<<17) # Unix, Mac DISPLAY_BOTTOMFIRST = (1<<17) # Windows DISPLAY_FIRSTROW_MASK = 0x00020000 # Define whether packing RGB in 16-bits should use 555 # or 565 (extra bit for green) # DISPLAY_FORMAT_555 DISPLAY_NATIVE_555 = (0<<18) DISPLAY_NATIVE_565 = (1<<18) DISPLAY_555_MASK = 0x00040000 # Define the row alignment, which must be equal to or greater than # the size of a pointer. # The default (DISPLAY_ROW_ALIGN_DEFAULT) is the size of a pointer, # 4 bytes (DISPLAY_ROW_ALIGN_4) on 32-bit systems or 8 bytes # (DISPLAY_ROW_ALIGN_8) on 64-bit systems. # DISPLAY_FORMAT_ROW_ALIGN DISPLAY_ROW_ALIGN_DEFAULT = (0<<20) # DISPLAY_ROW_ALIGN_1 = (1<<20), # not currently possible # DISPLAY_ROW_ALIGN_2 = (2<<20), # not currently possible DISPLAY_ROW_ALIGN_4 = (3<<20) DISPLAY_ROW_ALIGN_8 = (4<<20) DISPLAY_ROW_ALIGN_16 = (5<<20) DISPLAY_ROW_ALIGN_32 = (6<<20) DISPLAY_ROW_ALIGN_64 = (7<<20) DISPLAY_ROW_ALIGN_MASK = 0x00700000 class Revision(Structure): _fields_ = [ ("product", c_char_p), ("copyright", c_char_p), ("revision", c_long), ("revisiondate", c_long) ] gs_main_instance = c_void_p display_callback = c_void_p class GhostscriptError(Exception): def __init__(self, ecode): # :todo: Exception.__init__(self, error2name(ecode)) self.code = ecode def revision(): """ Get version numbers and strings. This is safe to call at any time. You should call this first to make sure that the correct version of the Ghostscript is being used. Returns a Revision instance """ revision = Revision() rc = libgs.gsapi_revision(pointer(revision), sizeof(revision)) if rc: raise ArgumentError("Revision structure size is incorrect, " "requires %s bytes" % rc) return revision def new_instance(): # display_callback=None): """ Create a new instance of Ghostscript This instance is passed to most other API functions. """ # :todo: The caller_handle will be provided to callback functions. display_callback=None instance = gs_main_instance() rc = libgs.gsapi_new_instance(pointer(instance), display_callback) if rc != 0: raise GhostscriptError(rc) return instance def delete_instance(instance): """ Destroy an instance of Ghostscript Before you call this, Ghostscript must have finished. If Ghostscript has been initialised, you must call exit() before delete_instance() """ return libgs.gsapi_delete_instance(instance) c_stdstream_call_t = CFUNCTYPE(c_int, gs_main_instance, POINTER(c_char), c_int) def _wrap_stdin(infp): """ Wrap a filehandle into a C function to be used as `stdin` callback for ``set_stdio``. The filehandle has to support the readline() method. """ def _wrap(instance, dest, count): try: data = infp.readline(count) except: count = -1 else: if not data: count = 0 else: count = len(data) memmove(dest, c_char_p(data), count) return count return c_stdstream_call_t(_wrap) def _wrap_stdout(outfp): """ Wrap a filehandle into a C function to be used as `stdout` or `stderr` callback for ``set_stdio``. The filehandle has to support the write() and flush() methods. """ def _wrap(instance, str, count): outfp.write(str[:count]) outfp.flush() return count return c_stdstream_call_t(_wrap) _wrap_stderr = _wrap_stdout def set_stdio(instance, stdin, stdout, stderr): """ Set the callback functions for stdio. ``stdin``, ``stdout`` and ``stderr`` have to be ``ctypes`` callback functions matching the ``_gsprint.c_stdstream_call_t`` prototype. You may want to use _wrap_* to wrap file handles. Note 1: This function only changes stdio of the Postscript interpreter, not that of the devices. Note 2: Make sure you keep references to C function objects as long as they are used from C code. Otherwise they may be garbage collected, crashing your program when a callback is made. The ``stdin`` callback function should return the number of characters read, `0` for EOF, or `-1` for error. The `stdout` and `stderr` callback functions should return the number of characters written. You may pass ``None`` for any of stdin, stdout or stderr , in which case the system stdin, stdout resp. stderr will be used. """ rc = libgs.gsapi_set_stdio(instance, stdin, stdout, stderr) if rc not in (0, e_Quit, e_Info): raise GhostscriptError(rc) return rc # :todo: set_poll (instance, int(*poll_fn)(void *caller_handle)); # :todo: set_display_callback(instance, callback): def set_arg_encoding(instance, encoding): assert encoding in ( ARG_ENCODING_LOCAL, ARG_ENCODING_UTF8, ARG_ENCODING_UTF16LE, ) rc = libgs.gsapi_set_arg_encoding(instance, c_int(encoding)) if rc < 0: raise GhostscriptError(rc) return rc def init_with_args(instance, argv): """ Initialise the interpreter. 1. If quit or EOF occur during init_with_args(), the return value will be e_Quit. This is not an error. You must call exit() and must not call any other functions. 2. If usage info should be displayed, the return value will be e_Info which is not an error. Do not call exit(). 3. Under normal conditions this returns 0. You would then call one or more run_*() functions and then finish with exit() """ ArgArray = c_char_p * len(argv) c_argv = ArgArray(*argv) rc = libgs.gsapi_init_with_args(instance, len(argv), c_argv) if rc not in (0, e_Quit, e_Info): raise GhostscriptError(rc) return rc def exit(instance): """ Exit the interpreter This must be called on shutdown if init_with_args() has been called, and just before delete_instance() """ rc = libgs.gsapi_exit(instance) if rc != 0: raise GhostscriptError(rc) return rc def run_string_begin(instance, user_errors=False): exit_code = c_int() rc = libgs.gsapi_run_string_begin(instance, c_int(user_errors), pointer(exit_code)) if rc != 0: raise GhostscriptError(rc) return exit_code.value def run_string_continue(instance, str, user_errors=False): exit_code = c_int() rc = libgs.gsapi_run_string_continue( instance, c_char_p(str), c_int(len(str)), c_int(user_errors), pointer(exit_code)) if rc != e_NeedInput and rc != 0: raise GhostscriptError(rc) return exit_code.value def run_string_end(instance, user_errors=False): exit_code = c_int() rc = libgs.gsapi_run_string_end(instance, c_int(user_errors), pointer(exit_code)) if rc != 0: raise GhostscriptError(rc) return exit_code.value def run_string_with_length(*args, **kw): raise NotImpelmentedError('Use run_string() instead') def run_string(instance, str, user_errors=False): exit_code = c_int() rc = libgs.gsapi_run_string_with_length( instance, c_char_p(str), c_int(len(str)), c_int(user_errors), pointer(exit_code)) if rc != 0: raise GhostscriptError(rc) return exit_code.value def run_file(instance, filename, user_errors=False): exit_code = c_int() rc = libgs.gsapi_run_file(instance, c_char_p(filename), c_int(user_errors), pointer(exit_code)) if rc != 0: raise GhostscriptError(rc) return exit_code.value def set_visual_tracer(I): raise NotImplementedError # New device has been opened # This is the first event from this device. # int (*display_open)(void *handle, void *device); c_display_open = CFUNCTYPE(c_int, c_void_p, c_void_p) # Device is about to be closed. # Device will not be closed until this function returns. #int (*display_preclose)(void *handle, void *device); c_display_preclose = CFUNCTYPE(c_int, c_void_p, c_void_p) # Device has been closed. # This is the last event from this device. # int (*display_close)(void *handle, void *device); c_display_close = CFUNCTYPE(c_int, c_void_p, c_void_p) # Device is about to be resized. # Resize will only occur if this function returns 0. # raster is byte count of a row. # int (*display_presize)(void *handle, void *device, # int width, int height, int raster, unsigned int format); c_display_presize = CFUNCTYPE(c_int, c_void_p, c_void_p, c_int, c_int, c_int, c_uint) # Device has been resized. # New pointer to raster returned in pimage # int (*display_size)(void *handle, void *device, int width, int height, # int raster, unsigned int format, unsigned char *pimage); c_display_size = CFUNCTYPE(c_int, c_void_p, c_void_p, c_int, c_int, c_int, c_uint, POINTER(c_ubyte)) # flushpage #int (*display_sync)(void *handle, void *device); c_display_sync = CFUNCTYPE(c_int, c_void_p, c_void_p) # showpage # If you want to pause on showpage, then don't return immediately # int (*display_page)(void *handle, void *device, int copies, int flush); c_display_page = CFUNCTYPE(c_int, c_void_p, c_void_p, c_int, c_int) # Notify the caller whenever a portion of the raster is updated. # This can be used for cooperative multitasking or for # progressive update of the display. # This function pointer may be set to NULL if not required. # int (*display_update)(void *handle, void *device, int x, int y, # int w, int h); c_display_update = CFUNCTYPE(c_int, c_void_p, c_void_p, c_int, c_int, c_int, c_int) # Allocate memory for bitmap # This is provided in case you need to create memory in a special # way, e.g. shared. If this is NULL, the Ghostscript memory device # allocates the bitmap. This will only called to allocate the # image buffer. The first row will be placed at the address # returned by display_memalloc. # void *(*display_memalloc)(void *handle, void *device, unsigned long size); c_display_memalloc = CFUNCTYPE(c_void_p, c_void_p, c_void_p, c_ulong) # Free memory for bitmap # If this is NULL, the Ghostscript memory device will free the bitmap # int (*display_memfree)(void *handle, void *device, void *mem); c_display_memfree = CFUNCTYPE(c_int, c_void_p, c_void_p, c_void_p) # Added in V2 */ # When using separation color space (DISPLAY_COLORS_SEPARATION), # give a mapping for one separation component. # This is called for each new component found. # It may be called multiple times for each component. # It may be called at any time between display_size # and display_close. # The client uses this to map from the separations to CMYK # and hence to RGB for display. # GS must only use this callback if version_major >= 2. # The unsigned short c,m,y,k values are 65535 = 1.0. # This function pointer may be set to NULL if not required. # # int (*display_separation)(void *handle, void *device, # int component, const char *component_name, # unsigned short c, unsigned short m, # unsigned short y, unsigned short k); c_display_separation = CFUNCTYPE(c_int, c_void_p, c_void_p, c_int, c_char_p, c_ushort, c_ushort, c_ushort, c_ushort) class Display_callback_s (Structure): _fields_ = [ # Size of this structure # Used for checking if we have been handed a valid structure # int size; ("size", c_int), # Major version of this structure # The major version number will change if this structure changes. # int version_major; ("version_major", c_int), # Minor version of this structure # The minor version number will change if new features are added # without changes to this structure. For example, a new color # format. #int version_minor; ("version_minor", c_int), ("display_open", c_display_open), ("display_preclose", c_display_preclose), ("display_close", c_display_close), ("display_presize", c_display_presize), ("display_size", c_display_size), ("display_sync", c_display_sync), ("display_page", c_display_page), ("display_update", c_display_update), ("display_memalloc", c_display_memalloc), ("display_memfree", c_display_memfree), ("display_separation", c_display_separation) ] def set_display_callback(instance, callback): rc = libgs.gsapi_set_display_callback(instance, callback) if rc != 0: raise GhostscriptError(rc) return rc def __win32_finddll(): try: import winreg except ImportError: # assume Python 2 from _winreg import OpenKey, CloseKey, EnumKey, QueryValueEx, \ QueryInfoKey, HKEY_LOCAL_MACHINE else: from winreg import OpenKey, CloseKey, EnumKey, QueryValueEx, \ QueryInfoKey, HKEY_LOCAL_MACHINE from distutils.version import LooseVersion import os dlls = [] # Look up different variants of Ghostscript and take the highest # version for which the DLL is to be found in the filesystem. for key_name in ('AFPL Ghostscript', 'Aladdin Ghostscript', 'GPL Ghostscript', 'GNU Ghostscript'): try: k1 = OpenKey(HKEY_LOCAL_MACHINE, "Software\\%s" % key_name) for num in range(0, QueryInfoKey(k1)[0]): version = EnumKey(k1, num) try: k2 = OpenKey(k1, version) dll_path = QueryValueEx(k2, 'GS_DLL')[0] CloseKey(k2) if os.path.exists(dll_path): dlls.append((LooseVersion(version), dll_path)) except WindowsError: pass CloseKey(k1) except WindowsError: pass if dlls: dlls.sort() return dlls[-1][-1] else: return None if sys.platform == 'win32': libgs = __win32_finddll() if not libgs: raise RuntimeError('Can not find Ghostscript DLL in registry') libgs = windll.LoadLibrary(libgs) else: try: libgs = cdll.LoadLibrary("libgs.so") except OSError: # shared object file not found import ctypes.util libgs = ctypes.util.find_library('gs') if not libgs: raise RuntimeError('Can not find Ghostscript library (libgs)') libgs = cdll.LoadLibrary(libgs) del __win32_finddll python-ghostscript-0.7/projectlogo.svg000066400000000000000000000464321402072270500203300ustar00rootroot00000000000000 python-ghostsctipt project logo image/svg+xmlpython-ghostsctipt project logolemmling, see http://www.openclipart.org/detail/178472010-08-12 python-ghostscript-0.7/requirements.txt000066400000000000000000000000451402072270500205320ustar00rootroot00000000000000setuptools >= 38.6.0 wheel tox twine python-ghostscript-0.7/setup.cfg000066400000000000000000000032631402072270500170740ustar00rootroot00000000000000[sdist] formats=gztar [bdist] formats=egg [bdist_wheel] universal=1 [zest.releaser] python-file-with-version = ghostscript/_gsprint.py push-changes = no tag-format = v{version} tag-message = python-ghostscript {version} tag-signing = yes create-wheel = yes releaser.before_upload = _zest_release_hooks.sign_release _zest_release_hooks.run_twine_check _zest_release_hooks.safe_dist_files [metadata] name = ghostscript version = attr:ghostscript.__version__ author = Hartmut Goebel author_email = h.goebel@crazy-compilers.com description = Interface to the Ghostscript C-API, both high- and low-level, based on ctypes long_description = file:README.rst long_description_content_type = text/x-rst keywords = Ghostscript, PDF, Postscript url = https://gitlab.com/pdftools/python-ghostscript download_url = http://pypi.python.org/pypi/ghostscript license = GNU General Public License v3 or later (GPLv3+) classifiers = Development Status :: 5 - Production/Stable Intended Audience :: Developers License :: OSI Approved :: GNU General Public License v3 or later (GPLv3+) Natural Language :: English Operating System :: OS Independent Programming Language :: Python Programming Language :: Python :: 3 Programming Language :: Python :: 3.6 Programming Language :: Python :: 3.7 Programming Language :: Python :: 3.8 Programming Language :: Python :: 3.9 Topic :: Software Development :: Libraries :: Python Modules [options] packages = find: zip_safe = True install_requires = setuptools >= 38.6.0 [options.packages.find] exclude = tests [options.package_data] # If any package contains *.txt or *.rst files, include them: * = *.txt, *.rst python-ghostscript-0.7/setup.py000066400000000000000000000015721402072270500167660ustar00rootroot00000000000000#!/usr/bin/env python # -*- coding: utf-8 -*- # # This file is part of python-ghostscript. # Copyright 2010-2021 by Hartmut Goebel # # 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 . # from setuptools import setup setup( install_requires = ['setuptools >= 38.6.0'] ) python-ghostscript-0.7/test/000077500000000000000000000000001402072270500162265ustar00rootroot00000000000000python-ghostscript-0.7/test/hello_world.bmp000066400000000000000000000011261402072270500212400ustar00rootroot00000000000000BMVv(P à  ÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿðÿÿðÿÿðÿÿÿÿðÿðÿðÿÿÿÿÿÿÿÿÿÿÿðÿÿðÿÿðÿÿÿÿðÿÿðÿðÿÿÿÿÿÿÿÿÿÿÿÿðÿÿðÿÿÿððÿÿÿðÿÿðÿÿÿÿÿÿÿÿÿÿÿÿÿðÿÿðÿððÿÿÿÿððÿÿðÿÿÿÿÿÿÿÿÿÿÿÿÿðÿÿðÿÿÿÿððÿðÿðÿÿÿÿÿÿÿÿÿÿÿÿðÿÿðÿÿðÿÿÿÿððÿðÿÿÿÿÿÿÿÿÿÿðÿÿðÿÿÿÿðÿÿÿÿÿÿððÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿðÿÿðÿÿÿÿðÿÿÿÿÿÿÿÿðÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿðÿÿðÿÿÿÿðÿÿÿÿÿðÿÿðÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿpython-ghostscript-0.7/test/test_highlevel.py000066400000000000000000000157361402072270500216220ustar00rootroot00000000000000# -*- coding: utf-8 -*- # # This file is part of python-ghostscript. # Copyright 2010-2021 by Hartmut Goebel # # 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 . # __author__ = "Hartmut Goebel " __copyright__ = "Copyright 2010-2021 by Hartmut Goebel " __licence__ = "GNU General Public License version 3 (GPL v3)" import io import sys, os import locale # required to encode file paths import binascii import warnings import py, pytest import ghostscript as gslib postscript_img = b""" /Helvetica findfont 12 scalefont setfont 0 0 moveto (Hello World) show showpage """ HELLO_WORLD = ''.join(('%x' % ord(c) for c in 'Hello World')) postscript_doc = ('<%s> = flush' % HELLO_WORLD).encode('ascii') STDARGS = ['test.py', '-dNOPAUSE', '-dBATCH', '-dSAFER', '-q', '-sDEVICE=bmp16', '-g80x12'] TEST_PIC_FILENAME = os.path.join(os.path.dirname(__file__), 'hello_world.bmp') TEST_PIC_DATA = py.path.local(TEST_PIC_FILENAME).read('rb') # Ensure the instanse is removed after all high-level tests have been # done. Otherwise low-level tests will fail if run afterwards. @pytest.fixture(scope='module') def instance(request): def fin(): gslib.cleanup() request.addfinalizer(fin) def test_revision_func(instance): rev = gslib.revision() assert type(rev) is dict assert type(rev['copyright']) is str assert type(rev['product']) is str assert type(rev['revision']) is int assert type(rev['revisiondate']) is int assert 'Copyright' in rev['copyright'] assert 'ghostscript' in rev['product'].lower() assert rev['revisiondate'] > 19900101 assert rev['revision'] > 700 def test_revision_instance(instance): with gslib.Ghostscript('-dBATCH', '-q') as gs: rev1 = gs.revision() rev2 = gslib.revision() assert rev1 == rev2 def test_simple(instance, tmpdir): """Let ghostscript read from a file and write to a file""" infile = tmpdir.join('in.ps') infile.write(postscript_img) outfile = tmpdir.join('out.bmp') # Using a context with an empty body looks not like good code, So # do not use a ``with``-stmt. gs = gslib.Ghostscript(*STDARGS, '-sOutputFile=%s' % outfile, str(infile)) gs.exit() data = outfile.read('rb') assert data == TEST_PIC_DATA def test_unicode_arguments(instance, tmpdir): """Let ghostscript read from a file and write to a file""" infile = tmpdir.join('in-äöü.ps') infile.write(postscript_img) outfile = tmpdir.join('outäöü.bmp') gs = gslib.Ghostscript(*STDARGS, '-sOutputFile=%s' % outfile, str(infile)) gs.exit() data = outfile.read('rb') assert data == TEST_PIC_DATA def test_run_string_empty(instance, tmpdir): """Let ghostscript read from a file and write to a file""" infile = tmpdir.join('in.ps') infile.write(postscript_img) outfile = tmpdir.join('out.bmp') with gslib.Ghostscript(*STDARGS, '-sOutputFile=%s' % outfile) as gs: gs.run_string(b'') # It depends on the ghostscript implementation, whether the file # if created. As of gs 9.14 the file is not created, but this # could change. if outfile.exists(): # But if the file exists, it must be empty data = outfile.read('rb') assert data == '' def test_run_string(instance, tmpdir): """Let ghostscript read from a file and write to a file""" outfile = tmpdir.join('out.bmp') with gslib.Ghostscript(*STDARGS, '-sOutputFile=%s' % outfile) as gs: gs.run_string(postscript_img) data = outfile.read('rb') assert data == TEST_PIC_DATA def test_stdin(tmpdir): """Let ghostscript read from stdin and write to a file""" outfile = tmpdir.join('out.bmp') gs = gslib.Ghostscript(*STDARGS, '-sOutputFile=%s' % outfile, '-', stdin=io.BytesIO(postscript_img)) gs.exit() data = outfile.read('rb') assert data == TEST_PIC_DATA def test_stdout(tmpdir): """Let ghostscript read from a file and write to stdout""" infile = tmpdir.join('in.ps') infile.write(postscript_doc) stdout = io.BytesIO() # buffer for collecting the output gs = gslib.Ghostscript(*STDARGS, str(infile), stdout=stdout) gs.exit() data = stdout.getvalue() assert data == b'Hello World\n' def test_stdin_stdout(tmpdir): """Let ghostscript read from stdin and write to stdout""" stdout = io.BytesIO() # buffer for collecting the output gs = gslib.Ghostscript(*STDARGS, '-', stdin=io.BytesIO(postscript_doc), stdout=stdout) gs.exit() data = stdout.getvalue() assert data == b'Hello World\n' def test_stderr(tmpdir): """ Make ghostscript write some error message to stderr and keep stdout on the console. """ stderr = io.BytesIO() # buffer for collecting stderr try: with gslib.Ghostscript(*STDARGS, '-', stdin=io.BytesIO(b'foobar'), stderr=stderr): # this call is expected to fail due to the intended error in # the postscript code pass except gslib.GhostscriptError: pass data = stderr.getvalue() assert b'Unrecoverable error' in data def test_stdout_stderr(tmpdir): """ Make ghostscript write some error message to stderr and catch stdout, too. """ stdout = io.BytesIO() # buffer for collecting the output stderr = io.BytesIO() # buffer for collecting stderr try: with gslib.Ghostscript(*STDARGS, '-', stdin=io.BytesIO(b'foobar'), stdout=stdout, stderr=stderr): # this call is expected to fail due to the intended error in # the postscript code pass except gslib.GhostscriptError: pass data = stdout.getvalue() assert b'Error: /undefined in foobar' in data data = stderr.getvalue() assert b'Unrecoverable error' in data def test_byte_argments_raise_warning(tmpdir): with warnings.catch_warnings(record=True) as w: # Cause all warnings to always be triggered warnings.simplefilter("always") # Trigger the warning with gslib.Ghostscript(b'-dBATCH', b'-q') as gs: pass assert len(w) == 1 assert issubclass(w[-1].category, DeprecationWarning) assert "deprecated" in str(w[-1].message) python-ghostscript-0.7/test/test_lowlevel.py000066400000000000000000000136511402072270500214760ustar00rootroot00000000000000# -*- coding: utf-8 -*- # # This file is part of python-ghostscript. # Copyright 2010-2021 by Hartmut Goebel # # 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 . # __author__ = "Hartmut Goebel " __copyright__ = "Copyright 2010-2021 by Hartmut Goebel " __licence__ = "GNU General Public License version 3 (GPL v3)" import io import sys, os import locale # required to encode file paths import binascii import py import ghostscript._gsprint as gs postscript_img = b""" /Helvetica findfont 12 scalefont setfont 0 0 moveto (Hello World) show showpage """ HELLO_WORLD = ''.join(('%x' % ord(c) for c in 'Hello World')) #HELLO_WORLD = binascii.hexlify('Hello World') postscript_doc = ('<%s> = flush' % HELLO_WORLD).encode('ascii') STDARGS = [b'test.py', b'-dNOPAUSE', b'-dBATCH', b'-dSAFER', b'-q', b'-sDEVICE=bmp16', b'-g80x12'] TEST_PIC_FILENAME = os.path.join(os.path.dirname(__file__), 'hello_world.bmp') TEST_PIC_DATA = py.path.local(TEST_PIC_FILENAME).read('rb') def _encode(*args): encoding = locale.getpreferredencoding() return [a.encode(encoding) for a in args] def test_revision(): rev = gs.revision() assert type(rev.copyright) is bytes assert type(rev.product) is bytes assert type(rev.revision) is int assert type(rev.revisiondate) is int def test_run_string(tmpdir): """Let ghostscript read from a file and write to stdout""" outfile = tmpdir.join('out.bmp') args = STDARGS + _encode('-sOutputFile=%s' % outfile) instance = gs.new_instance() try: gs.init_with_args(instance, args) gs.run_string(instance, postscript_img) finally: gs.exit(instance) gs.delete_instance(instance) data = outfile.read('rb') assert data == TEST_PIC_DATA def test_simple(tmpdir): """Let ghostscript read from a file and write to a file""" infile = tmpdir.join('in.ps') infile.write(postscript_img) outfile = tmpdir.join('out.bmp') args = STDARGS + _encode('-sOutputFile=%s' % outfile, str(infile)) instance = gs.new_instance() try: gs.init_with_args(instance, args) finally: gs.exit(instance) gs.delete_instance(instance) data = outfile.read('rb') assert data == TEST_PIC_DATA def _gs_stdio(args, stdin=None, stdout=None, stderr=None): instance = gs.new_instance() # wrappers like in # http://ghostscript.com/doc/8.54/API.htm#Example_usage if stdin is not None: stdin = gs._wrap_stdin(stdin) if stdout is not None: stdout = gs._wrap_stdout(stdout) if stderr is not None: stderr = gs._wrap_stderr(stderr) gs.set_stdio(instance, stdin, stdout, stderr) try: gs.init_with_args(instance, args) finally: gs.exit(instance) gs.delete_instance(instance) def test_stdin(tmpdir): """Let ghostscript read from stdin and write to a file""" outfile = tmpdir.join('out.bmp') args = STDARGS + _encode('-sOutputFile=%s' % outfile, '-') _gs_stdio(args, stdin=io.BytesIO(postscript_img)) data = outfile.read('rb') assert data == TEST_PIC_DATA def test_stdout(tmpdir): """Let ghostscript read from a file and write to stdout""" infile = tmpdir.join('in.ps') infile.write(postscript_doc) args = STDARGS + _encode(str(infile)) stdout = io.BytesIO() # buffer for collecting the output _gs_stdio(args, stdout=stdout) data = stdout.getvalue() assert data == b'Hello World\n' def test_stdin_stdout(tmpdir): """Let ghostscript read from stdin and write to stdout""" args = STDARGS + _encode('-') stdout = io.BytesIO() # buffer for collecting the output _gs_stdio(args, stdin=io.BytesIO(postscript_doc), stdout=stdout) data = stdout.getvalue() assert data == b'Hello World\n' def test_stderr(tmpdir): """ Make ghostscript write some error message to stderr and keep stdout on the console. """ args = STDARGS + _encode('-') stderr = io.BytesIO() # buffer for collecting stderr try: # this call is expected to fail due to the intended error in # the postscript code _gs_stdio(args, stdin=io.BytesIO(b'foobar'), stderr=stderr) except gs.GhostscriptError: pass data = stderr.getvalue() assert b'Unrecoverable error' in data def test_stdout_stderr(tmpdir): """ Make ghostscript write some error message to stderr and catch stdout, too. """ args = STDARGS + _encode('-') stdout = io.BytesIO() # buffer for collecting the output stderr = io.BytesIO() # buffer for collecting stderr try: # this call is expected to fail due to the intended error in # the postscript code _gs_stdio(args, stdin=io.BytesIO(b'foobar'), stdout=stdout, stderr=stderr) except gs.GhostscriptError: pass data = stdout.getvalue() assert b'Error: /undefined in foobar' in data data = stderr.getvalue() assert b'Unrecoverable error' in data def generate_test_picture(): """ Use command line ghostscript to generate the image used in testing """ import subprocess outfile = TEST_PIC_FILENAME args = ['gs'] + STDARGS[1:] + _encode('-sOutputFile=%s' % outfile, '-') subprocess.Popen(args).communicate(postscript_doc) if __name__ == '__main__': generate_test_picture() python-ghostscript-0.7/tox.ini000066400000000000000000000023641402072270500165670ustar00rootroot00000000000000[tox] minversion=2.3.1 envlist = py36,py37,py38,py39,linters [testenv] deps = pytest!=3.0.5 commands = pytest {posargs} #---- Documentation ---- [testenv:docs] basepython = python3 deps = -rdocs/source/requirements.txt commands = sphinx-build -E -W -c docs/source/ -b html docs/source/ docs/build/html sphinx-build -E -W -c docs/source/ -b man docs/source/ docs/build/man [testenv:serve-docs] basepython = python3 skip_install = true changedir = docs/build/html deps = commands = python -m http.server {posargs} #---- Linters ---- [testenv:readme] basepython = python3 deps = setuptools >= 38.6.0 wheel twine commands = python setup.py -q sdist bdist_wheel twine check dist/* [testenv:linters] basepython = python3 skip_install = true deps = {[testenv:readme]deps} commands = {[testenv:readme]commands} #---- Release tooling ---- [testenv:build] basepython = python3 skip_install = true deps = setuptools >= 38.6.0 wheel twine commands = python setup.py -q sdist bdist_wheel twine check dist/* [testenv:release] basepython = python3 skip_install = true deps = {[testenv:build]deps} twine >= 1.5.0 commands = {[testenv:build]commands} twine upload --skip-existing dist/*