├── .gitignore ├── ChangeLog ├── LICENSE ├── README.md ├── TODO ├── com.arminstraub.krop.desktop ├── com.arminstraub.krop.metainfo.xml ├── com.arminstraub.krop.svg ├── krop.1 ├── krop ├── .gitignore ├── __init__.py ├── __main__.py ├── application.py ├── autotrim.py ├── config.py ├── mainwindow.py ├── mainwindow.ui ├── mainwindowui_qt5.py ├── mainwindowui_qt6.py ├── pdfcropper.py ├── qt.py ├── version.py ├── vieweritem.py └── viewerselections.py └── setup.py /.gitignore: -------------------------------------------------------------------------------- 1 | build/ 2 | dist/ 3 | .pybuild/ 4 | MANIFEST 5 | krop.egg-info/ 6 | -------------------------------------------------------------------------------- /ChangeLog: -------------------------------------------------------------------------------- 1 | krop (0.7.0) 2025-04-06 -- Armin Straub 2 | 3 | + Support PyQt6 and update packaging (thanks to PunkPangolin for this work). 4 | + Support PyMuPDF for rendering and cropping. 5 | + Support pikepdf for cropping (thanks to Hongzhuo Liang for the idea and 6 | initial code). 7 | * Support the new version of pypdf in addition to its predecessor PyPDF2 8 | (thanks to Emmanuel Rosa for the idea and initial code). 9 | * Support both old (<2) and new (>=2) versions of PyPDF2 (thanks to milahu 10 | for the idea and initial code). 11 | * When using PyPDF2, preserve links within a PDF (thanks to chrthi for this). 12 | * Display PDF file name in window title. 13 | 14 | krop (0.6.0) 2020-06-09 -- Armin Straub 15 | 16 | + Fixed aspect ratios, like letter size, can be chosen for selections. 17 | + Selections (or a grid of selections) for the full page can now be created 18 | using the context menu or by pressing Insert (or Shift+Insert). Also 19 | introduced the command line option --grid to create a grid of selections on 20 | the initial page. 21 | + Auto trimming margins can now inspect all pages. 22 | + New option for whether to include pages without selections in the output. 23 | + Added the command line options --optimize (thanks to Ondrej Tichacek for 24 | suggesting this feature) and --exceptions. 25 | + Implemented several keyboard shortcuts including Shift+Arrow to move 26 | current selection and Delete to remove it. 27 | * Keep track of current selection and highlight it visually. 28 | * Don't fail on PDFs that are encrypted with an empty password. 29 | * Remember window geometry and fit in view setting. 30 | 31 | 32 | krop (0.5.1) 2018-10-27 -- Armin Straub 33 | 34 | * Replace and extend the README file with a MarkDown version (thanks to 35 | Eduardo Montenegro for doing this). 36 | + Add a manpage. 37 | * Fix a Qt5 related bug when selecting filename for saving (thanks to 38 | Lin-Buo-Ren for reporting this). 39 | 40 | 41 | krop (0.5.0) 2018-02-11 -- Armin Straub 42 | 43 | + Support PyQt5. 44 | + Use Ghostscript to optionally optimize the final PDF (thanks to Mathias 45 | Rav for the idea and code). 46 | 47 | 48 | krop (0.4.13) 2017-07-22 -- Armin Straub 49 | 50 | + Added the command line option --go, which outputs a PDF using the choices 51 | from --autotrim, --rotate and --whichpages, without opening the krop GUI 52 | (thanks to Mirko Weihrauch for the idea). 53 | + Padding for auto trimming can be specified as in CSS using one to four 54 | values. This option is now also available on the command line as 55 | --autotrim-padding. (Thanks to Jonah Langlieb for providing sanity checks!) 56 | * Fix incorrect string handling when opening files from the command line 57 | using python3 (thanks to Giuliano Costantini for observing and fixing this). 58 | 59 | 60 | krop (0.4.12) 2017-01-22 -- Armin Straub 61 | 62 | * Use CropBox instead of MediaBox when determining the region to be cropped 63 | (thanks to Tim Mueller for observing and fixing this). 64 | * Use a more proper Python package structure (thanks to Xavier Corredor 65 | Llano for advice). 66 | 67 | 68 | krop (0.4.11) 2016-08-20 -- Armin Straub 69 | 70 | * Make krop compatible with both python2 and python3. 71 | 72 | 73 | krop (0.4.10) 2016-05-29 -- Armin Straub 74 | 75 | * When cropping, all PDF page boxes (ArtBox, BleedBox, CropBox, MediaBox, 76 | TrimBox) are now adjusted. 77 | 78 | 79 | krop (0.4.9) 2015-10-31 -- Armin Straub 80 | 81 | * Reading PDF files is less strict now. As a consequence, krop doesn't give 82 | up cropping some files which resulted in an error before. 83 | * Fix a possible crash when starting krop. 84 | 85 | 86 | krop (0.4.8) 2015-07-04 -- Armin Straub 87 | 88 | + More options are accessible via command line arguments. 89 | * Mouse cursor now changes when over selections and handles. 90 | * Improved visibility of selections. 91 | 92 | 93 | krop (0.4.7) 2015-02-15 -- Armin Straub 94 | 95 | + Basic options are accessible as command line arguments (run krop with 96 | --help to see available options). 97 | * When pressing ctrl-c in the terminal, krop will shut down (not gracefully, 98 | though; only intended for when there is trouble). 99 | * Avoid hitting Python's recursion limit in the pyPdf library when working 100 | with certain large pdf files (thanks to Victor). 101 | 102 | 103 | krop (0.4.6) 2014-05-24 -- Armin Straub 104 | 105 | + Added option to specify pages which require individual selections (thanks 106 | to Roger Krebs for the suggestion and for testing). 107 | * 'Trim Margins' automatically creates a region for the full page if no 108 | regions exist. 109 | * Reorganized options across tabs. 110 | + Added appdata file (thanks to Richard Hughes). 111 | 112 | 113 | krop (0.4.5) 2014-02-01 -- Armin Straub 114 | 115 | * Load and write files with non-ascii characters in their filename. 116 | 117 | 118 | krop (0.4.4) 2013-08-18 -- Armin Straub 119 | 120 | + If available use PyPDF2 in place of pyPdf. 121 | * Correctly crop PDFs which have orientation other than 'portrait' (thanks 122 | to Gaetano Pepe for sending sample PDFs and testing). 123 | * In case of more than one selection per page, cropping is much faster now 124 | and results in smaller files. 125 | * Delete old selections when opening a new file. 126 | 127 | 128 | krop (0.4.3) 2013-08-10 -- Armin Straub 129 | 130 | * Fix a bug that prevented PDF files to be specified on the command line 131 | (thanks to roctheme for reporting). 132 | * Instead of no icon at all, use the system icon 'edit-cut' as application 133 | icon (thanks to roctheme for the suggestion). 134 | 135 | 136 | krop (0.4.2) 2013-08-04 -- Armin Straub 137 | 138 | + Use PyKDE if available (though this is not really used yet). 139 | * If default icons are missing, use text instead. 140 | 141 | 142 | krop (0.4.1) 2013-07-28 -- Armin Straub 143 | 144 | * Initial public release. 145 | + Several small bug fixes. 146 | 147 | 148 | krop (0.4.0) 2013-06-16 -- Armin Straub 149 | 150 | * Rewrote cropping code, resulting in much smaller pdf files. 151 | 152 | 153 | krop (0.3.0) 2011-07-14 -- Armin Straub 154 | 155 | + Added option to specify file name for cropped file. 156 | + Added option to specify which pages to include into the cropped file. 157 | 158 | 159 | krop (0.2.0) 2010-10-16 -- Armin Straub 160 | 161 | + Added option to automatically trim selection (right-click a selection for 162 | this option). 163 | + Added support to subdivide selections into several pages in order to 164 | exactly fit the screen size of specific devices (with eReaders, such as my 165 | Nook, in mind). 166 | 167 | 168 | krop (0.1.0) 2010-08-19 -- Armin Straub 169 | 170 | * Initial personal release. 171 | 172 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # krop [![License: GPL-3.0](https://img.shields.io/github/license/arminstraub/krop.svg)](https://www.gnu.org/licenses/gpl-3.0) ![Latest release](https://img.shields.io/github/v/tag/arminstraub/krop.svg) 2 | 3 | krop is a simple graphical tool to crop the pages of PDF files. 4 | 5 | It is written in Python and relies on PyQt and PyMuPDF (or a suitable subset of pypdf/pikepdf/python-poppler-qt) for its functionality. A unique feature of krop is its ability to automatically split pages into subpages to fit the limited screen size of devices such as eReaders. This is particularly useful, if your eReader does not support convenient scrolling. 6 | 7 | For more information and how to install krop, see: 8 | [https://arminstraub.com/software/krop](https://arminstraub.com/software/krop) 9 | 10 | ![Screenshot](https://arminstraub.com/images/krop/screenshot.png) 11 | -------------------------------------------------------------------------------- /TODO: -------------------------------------------------------------------------------- 1 | Roadmap (ideas planned for one of the next releases) 2 | + Improve support for pikepdf, PyMuPDF and pypdf (e.g. preserve links) 3 | + Support QtPy, an abstraction layer for both PyQt and PySide (for Qt5 and Qt6) 4 | + Expose further Ghostscript features (like exporting to PDF 1.7) 5 | + Save and later reuse regions for cropping 6 | + Use parallel processing for certain tasks like cropping 7 | + Allow translations (once UI has stabilized) 8 | 9 | Wishlist (ideas that are likely difficult or currently impractical) 10 | + Preserve meta data, table of contents and bookmarks when cropping 11 | + Option to overlay pages in order to improve making selections 12 | -------------------------------------------------------------------------------- /com.arminstraub.krop.desktop: -------------------------------------------------------------------------------- 1 | [Desktop Entry] 2 | Type=Application 3 | Name=krop 4 | GenericName=Crop PDF files 5 | Comment=A tool to crop PDF files 6 | TryExec=krop 7 | Exec=krop %F 8 | Icon=com.arminstraub.krop 9 | MimeType=application/pdf; 10 | Categories=Utility; 11 | Keywords=pdf;crop;rotate;ereader; 12 | -------------------------------------------------------------------------------- /com.arminstraub.krop.metainfo.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | com.arminstraub.krop 5 | com.arminstraub.krop.desktop 6 | CC0-1.0 7 | GPL-3.0+ 8 | krop 9 | 10 | Armin Straub 11 | 12 | Crop PDF files 13 | 14 |

15 | krop is a simple graphical tool to crop the pages of PDF files. It is written in Python and relies on PyQt and PyMuPDF (or a suitable subset of pypdf/pikepdf/python-poppler-qt) for its functionality. A unique feature of krop is its ability to automatically split pages into subpages to fit the limited screen size of devices such as eReaders. This is particularly useful, if your eReader does not support convenient scrolling. 16 |

17 |
18 | 19 | pdf 20 | crop 21 | rotate 22 | ereader 23 | 24 | 25 | 26 | https://arminstraub.com/images/krop/screenshot-appdata.png 27 | Main window of krop 28 | 29 | 30 | https://arminstraub.com/software/krop 31 | https://github.com/arminstraub/krop/issues 32 | mail@arminstraub.com 33 | 34 | 35 | 36 | 37 |
38 | -------------------------------------------------------------------------------- /com.arminstraub.krop.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | -------------------------------------------------------------------------------- /krop.1: -------------------------------------------------------------------------------- 1 | .TH krop 1 2 | .SH NAME 3 | krop \- a tool to crop PDF files 4 | .SH SYNOPSIS 5 | .B krop 6 | .RI [ options ] 7 | .RI [ file ] 8 | .br 9 | .SH DESCRIPTION 10 | This manual page briefly documents the 11 | .B krop 12 | command. 13 | .PP 14 | \fBkrop\fP is a simple graphical tool to crop the pages of PDF files. It is written 15 | in Python and relies on PyQt and PyMuPDF (or a suitable subset of pypdf/pikepdf/ 16 | python-poppler-qt) for its functionality. A unique feature of krop is its 17 | ability to automatically split pages into subpages to fit the limited screen 18 | size of devices such as eReaders. This is particularly useful, if your eReader 19 | does not support convenient scrolling. 20 | .SH OPTIONS 21 | A summary of options is included below. 22 | For a complete description, use the \fB\-\-help\fP option. 23 | .SS "Arguments:" 24 | .TP 25 | .B file 26 | PDF file to open 27 | .SS "Options:" 28 | .TP 29 | .B \-h, \-\-help 30 | show help, including all options, and exit 31 | .TP 32 | .B \-v, \-\-version 33 | show program's version number and exit 34 | .TP 35 | .B \-o OUTPUT, \-\-output OUTPUT 36 | where to save the cropped PDF 37 | .TP 38 | .B \-\-whichpages WHICHPAGES 39 | which pages (e.g. "1\-5" or "1,3\-") to include in cropped PDF (default: all) 40 | .TP 41 | .B \-\-rotate {0,90,180,270} 42 | how much to rotate the cropped pdf clockwise (default: 0) 43 | .TP 44 | .B \-\-optimize {gs,no} 45 | whether to optimize the final PDF using ghostscript (default: previous choice) 46 | .TP 47 | .B \-\-grid GRID 48 | if set to 2x3, for instance, creates a 2x3 grid of selections on initial page; if only one number is specified, the number of columns/rows is determined according to whether the page is landscape or portrait 49 | .TP 50 | .B \-\-initialpage INITIALPAGE 51 | which page to open initially (default: 1) 52 | .TP 53 | .B \-\-selections {all,evenodd,individual} 54 | to which pages should selections apply 55 | .TP 56 | .B \-\-exceptions EXCEPTIONS 57 | pages (e.g. "1\-5" or "1,3\-") which require individual selections 58 | .TP 59 | .B \-\-trim 60 | if specified, will auto trim initial selections 61 | .TP 62 | .B \-\-trim-use {initial,all} 63 | whether to inspect only the initial page or all pages (slow!) when auto trimming (default: previous value) 64 | .TP 65 | .B \-\-trim\-padding TRIM_PADDING 66 | how much padding to include when auto trimming (default: previous value) 67 | .TP 68 | .B \-\-go 69 | output PDF without opening the krop GUI (using the choices supplied on the command line); if used in a script without X server access, you can run krop using xvfb\-run 70 | -------------------------------------------------------------------------------- /krop/.gitignore: -------------------------------------------------------------------------------- 1 | *.pyc 2 | -------------------------------------------------------------------------------- /krop/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/arminstraub/krop/2d8f7dd20106963d70bc44ed4a571fcf41d9e1a5/krop/__init__.py -------------------------------------------------------------------------------- /krop/__main__.py: -------------------------------------------------------------------------------- 1 | from krop.application import main 2 | 3 | if __name__ == "__main__": 4 | main() 5 | -------------------------------------------------------------------------------- /krop/application.py: -------------------------------------------------------------------------------- 1 | # -*- coding: iso-8859-1 -*- 2 | 3 | """ 4 | krop: A tool to crop PDF files 5 | 6 | You can use command line arguments in addition to (or, to a degree, instead of) the graphical interface. 7 | 8 | For instance, to automatically undo 4 pages print onto a single page: 9 | krop --go --grid=2x2 file.pdf 10 | To additionally trim each of these pages: 11 | krop --go --grid=2x2 --trim --trim-use=all file.pdf 12 | 13 | Automatically crop the margins every single page individually: 14 | krop --go --selections=individual --grid=1@all --trim file.pdf 15 | Omit the --go to further edit the selections in the graphical interface before cropping. 16 | 17 | Copyright (C) 2010-2025 Armin Straub, http://arminstraub.com 18 | """ 19 | 20 | """ 21 | This program is free software; you can redistribute it and/or modify 22 | it under the terms of the GNU General Public License as published by 23 | the Free Software Foundation; either version 3 of the License, or 24 | (at your option) any later version. 25 | """ 26 | 27 | import sys 28 | 29 | from krop.version import __version__ 30 | 31 | 32 | def main(): 33 | from argparse import ArgumentParser, RawTextHelpFormatter 34 | parser = ArgumentParser(prog='krop', description=__doc__, 35 | formatter_class=RawTextHelpFormatter) 36 | 37 | parser.add_argument('-v', '--version', action='version', version='%(prog)s ' + __version__) 38 | 39 | parser.add_argument('file', nargs='?', help='PDF file to open') 40 | parser.add_argument('-o', '--output', help='where to save the cropped PDF') 41 | parser.add_argument('--whichpages', help='which pages (e.g. "1-5" or "1,3-") to include in cropped PDF (default: all)') 42 | parser.add_argument('--rotate', type=int, choices=[0,90,180,270], help='how much to rotate the cropped pdf clockwise (default: 0)') 43 | parser.add_argument('--optimize', choices=['gs', 'no'], help='whether to optimize the final PDF using ghostscript (default: previous choice)') 44 | 45 | parser.add_argument('--grid', help='if set to 2x3, for instance, creates a 2x3 grid of selections on initial page; if only one number is specified, the number of columns/rows is determined according to whether the page is landscape or portrait') 46 | 47 | parser.add_argument('--initialpage', help='which page to open initially (default: 1)') 48 | parser.add_argument('--selections', type=str, choices=['all', 'evenodd', 'individual'], help='to which pages should selections apply') 49 | parser.add_argument('--exceptions', help='pages (e.g. "1-5" or "1,3-") which require individual selections') 50 | 51 | parser.add_argument('--trim', action='store_true', help='if specified, will auto trim initial selections') 52 | parser.add_argument('--trim-use', type=str, choices=['initial', 'all'], help='whether to inspect only the initial page or all pages (slow!) when auto trimming (default: previous value)') 53 | parser.add_argument('--trim-padding', help='how much padding to include when auto trimming (default: previous value)') 54 | 55 | parser.add_argument('--go', action='store_true', help='output PDF without opening the krop GUI (using the choices supplied on the command line); if used in a script without X server access, you can run krop using xvfb-run') 56 | 57 | parser.add_argument('--use-qt5', action='store_true', help='use PyQt5 instead of PyQt6 (default: use PyQt6 if available)') 58 | parser.add_argument('--use-pymupdf', action='store_true', help='use PyMuPDF for rendering and cropping (default)') 59 | parser.add_argument('--use-pikepdf', action='store_true', help='use pikepdf for cropping (PyQt5 only, default: use PyMuPDF)') 60 | parser.add_argument('--use-pypdf', action='store_true', help='use pypdf for cropping (PyQt5 only, default: use PyMuPDF)') 61 | parser.add_argument('--use-pypdf2', action='store_true', help='use PyPDF2 for cropping (PyQt5 only, default: use PyMuPDF)') 62 | parser.add_argument('--use-poppler', action='store_true', help='use Poppler Qt for rendering (PyQt5 only, default: use PyMuPDF)') 63 | 64 | args = parser.parse_args() 65 | 66 | from krop.qt import QApplication 67 | app = QApplication(sys.argv) 68 | app.setApplicationName("krop") 69 | app.setApplicationDisplayName("krop") 70 | 71 | app.setOrganizationName("arminstraub.com") 72 | app.setOrganizationDomain("arminstraub.com") 73 | 74 | from krop.mainwindow import MainWindow 75 | window=MainWindow() 76 | 77 | if args.file is not None: 78 | fileName = args.file 79 | window.openFile(fileName) 80 | 81 | if args.output is not None: 82 | window.ui.editFile.setText(args.output) 83 | if args.whichpages is not None: 84 | window.ui.editWhichPages.setText(args.whichpages) 85 | if args.rotate is not None: 86 | window.ui.comboRotation.setCurrentIndex({0:0,90:2,180:3,270:1}[args.rotate]) 87 | if args.optimize is not None: 88 | window.ui.checkGhostscript.setChecked(args.optimize == "gs") 89 | if args.selections is not None: 90 | if args.selections == "all": 91 | window.ui.radioSelAll.setChecked(True) 92 | elif args.selections == "evenodd": 93 | window.ui.radioSelEvenOdd.setChecked(True) 94 | elif args.selections == "individual": 95 | window.ui.radioSelIndividual.setChecked(True) 96 | if args.exceptions is not None: 97 | window.ui.editSelExceptions.setText(args.exceptions) 98 | window.slotSelExceptionsChanged() 99 | if args.initialpage is not None: 100 | window.ui.editCurrentPage.setText(args.initialpage) 101 | window.slotCurrentPageEdited(args.initialpage) 102 | if args.trim_use is not None: 103 | window.ui.checkTrimUseAllPages.setChecked(args.trim_use == "all") 104 | if args.trim_padding is not None: 105 | window.ui.editPadding.setText(args.trim_padding) 106 | 107 | # args.grid is specified as 2x3 for 2 cols, 3 rows 108 | if args.grid: 109 | window.createSelectionGrid(args.grid) 110 | 111 | if args.trim: 112 | window.slotTrimMarginsAll() 113 | 114 | # shut down on ctrl+c when pressed in terminal (not gracefully, though) 115 | # http://stackoverflow.com/questions/4938723/ 116 | import signal 117 | signal.signal(signal.SIGINT, signal.SIG_DFL) 118 | 119 | if args.go: 120 | # sys.stdout.write('kropping...\n') 121 | from krop.qt import QTimer 122 | QTimer.singleShot(0, window.slotKrop) 123 | QTimer.singleShot(0, window.close) 124 | else: 125 | window.show() 126 | window.slotFitInView(window.ui.actionFitInView.isChecked()) 127 | 128 | sys.exit(app.exec()) 129 | -------------------------------------------------------------------------------- /krop/autotrim.py: -------------------------------------------------------------------------------- 1 | # -*- coding: iso-8859-1 -*- 2 | 3 | """ 4 | Code for auto trimming margins in krop. 5 | 6 | Copyright (C) 2010-2020 Armin Straub, http://arminstraub.com 7 | """ 8 | 9 | """ 10 | This program is free software; you can redistribute it and/or modify 11 | it under the terms of the GNU General Public License as published by 12 | the Free Software Foundation; either version 3 of the License, or 13 | (at your option) any later version. 14 | """ 15 | 16 | from krop.qt import * 17 | 18 | 19 | def autoTrimMargins(img, r, minr, sensitivity, allowedchanges): 20 | """Given a QImage img and a QRect r, automatically trims the margins of 21 | that rectangle according to the parameters.""" 22 | 23 | def pixAt(x, y): 24 | return qGray(img.pixel(x, y)) 25 | 26 | def isTrimmable(L): 27 | if not L: 28 | return True 29 | changes = 0 30 | y = L[0] 31 | for x in L: 32 | if abs(x-y) > sensitivity: 33 | changes += 1 34 | if changes > allowedchanges: 35 | return False 36 | y = x 37 | return True 38 | 39 | # rounding r to QRect might overshoot the picture by a pixel 40 | r = r.intersected(img.rect()) 41 | 42 | # we shouldn't trim r to something smaller than minr 43 | while r.height() > 0 and (minr is None or r.top() < minr.top()): 44 | L = [ pixAt(x, r.top()) for x in range(r.left(), r.right()) ] 45 | if not isTrimmable(L): 46 | break 47 | r.setTop(r.top()+1) 48 | while r.height() > 0 and (minr is None or r.bottom() > minr.bottom()): 49 | L = [ pixAt(x, r.bottom()) for x in range(r.left(), r.right()) ] 50 | if not isTrimmable(L): 51 | break 52 | r.setBottom(r.bottom()-1) 53 | while r.width() > 0 and (minr is None or r.left() < minr.left()): 54 | L = [ pixAt(r.left(), y) for y in range(r.top(), r.bottom()) ] 55 | if not isTrimmable(L): 56 | break 57 | r.setLeft(r.left()+1) 58 | while r.width() > 0 and (minr is None or r.right() > minr.right()): 59 | L = [ pixAt(r.right(), y) for y in range(r.top(), r.bottom()) ] 60 | if not isTrimmable(L): 61 | break 62 | r.setRight(r.right()-1) 63 | 64 | return r 65 | 66 | -------------------------------------------------------------------------------- /krop/config.py: -------------------------------------------------------------------------------- 1 | import sys 2 | 3 | PYQT6 = False 4 | 5 | try: 6 | # use PyQt6 unless PyQt5 is specified 7 | if '--use-qt5' not in sys.argv: 8 | try: 9 | from PyQt6 import QtCore 10 | PYQT6 = True 11 | except ImportError: 12 | pass 13 | if not PYQT6: 14 | from PyQt5 import QtCore 15 | except ImportError: 16 | _msg = "Please install PyQt6 (or PyQt5) first." 17 | raise RuntimeError(_msg) -------------------------------------------------------------------------------- /krop/mainwindow.py: -------------------------------------------------------------------------------- 1 | # -*- coding: iso-8859-1 -*- 2 | 3 | """ 4 | The main window of krop 5 | 6 | Copyright (C) 2010-2025 Armin Straub, http://arminstraub.com 7 | """ 8 | 9 | """ 10 | This program is free software; you can redistribute it and/or modify 11 | it under the terms of the GNU General Public License as published by 12 | the Free Software Foundation; either version 3 of the License, or 13 | (at your option) any later version. 14 | """ 15 | 16 | import sys 17 | from os.path import exists, splitext 18 | from shutil import which 19 | 20 | from krop.qt import * 21 | from krop.config import PYQT6 22 | 23 | if PYQT6: 24 | from krop.mainwindowui_qt6 import Ui_MainWindow 25 | else: 26 | from krop.mainwindowui_qt5 import Ui_MainWindow 27 | 28 | from krop.viewerselections import ViewerSelections, aspectRatioFromStr 29 | from krop.vieweritem import ViewerItem 30 | from krop.pdfcropper import PdfFile, PdfCropper, PdfEncryptedError, optimizePdfGhostscript 31 | from krop.autotrim import autoTrimMargins 32 | 33 | 34 | class AspectRatioType: 35 | def __init__(self, name, width, height): 36 | self.name = name 37 | self.width = width 38 | self.height = height 39 | 40 | class AspectRatioTypeManager: 41 | 42 | def __init__(self): 43 | self.types = [] 44 | self.defaultsUsed = False 45 | 46 | def __iter__(self): 47 | return iter(self.types) 48 | 49 | def addType(self, name, width, height): 50 | self.types.append(AspectRatioType(name, width, height)) 51 | 52 | def getType(self, index): 53 | if index >= len(self.types): 54 | return None 55 | return self.types[index] 56 | 57 | def addDefaults(self): 58 | pass 59 | 60 | def settingsCaption(self): 61 | pass 62 | 63 | def saveTypes(self, settings): 64 | c = self.settingsCaption() 65 | # if the defaults have been used, we still write them to the config 66 | # file, making it easier for the user to edit/add, but we append 67 | # Defaults to the caption so that these get automatically overriden by 68 | # future versions of krop (which may have updated defaults) 69 | if self.defaultsUsed: 70 | c += "Defaults" 71 | settings.beginWriteArray(c) 72 | for i in range(len(self.types)): 73 | t = self.types[i] 74 | settings.setArrayIndex(i) 75 | settings.setValue("Name", t.name) 76 | settings.setValue("Width", t.width) 77 | settings.setValue("Height", t.height) 78 | settings.endArray() 79 | 80 | def loadTypes(self, settings): 81 | count = settings.beginReadArray(self.settingsCaption()) 82 | for i in range(count): 83 | settings.setArrayIndex(i) 84 | name = settings.value("Name") 85 | width = float(settings.value("Width")) 86 | height = float(settings.value("Height")) 87 | self.addType(name, width, height) 88 | settings.endArray() 89 | if count==0: 90 | self.defaultsUsed = True 91 | self.addDefaults() 92 | 93 | class SelAspectRatioTypeManager(AspectRatioTypeManager): 94 | 95 | def settingsCaption(self): 96 | return "SelAspectRatios" 97 | 98 | def addDefaults(self): 99 | self.addType("Flexible aspect ratio", 0, 0) 100 | self.addType("A4/A5 etc.", 1, 1.414) 101 | self.addType("A4/A5 etc. (landscape)", 1.414, 1) 102 | self.addType("Letter", 8.5, 11) 103 | self.addType("Letter (landscape)", 11, 8.5) 104 | self.addType("Legal", 8.5, 14) 105 | self.addType("Legal (landscape)", 14, 8.5) 106 | 107 | class DeviceTypeManager(AspectRatioTypeManager): 108 | 109 | def settingsCaption(self): 110 | return "DeviceTypes" 111 | 112 | def addDefaults(self): 113 | self.addType("No fitting", 0, 0) 114 | self.addType("4:3 eReader", 4, 3) 115 | self.addType("4:3 eReader (widescreen)", 3, 4) 116 | self.addType("Nook 1st Ed.", 600, 730) 117 | self.addType("Nook 1st Ed. (widescreen)", 730, 600) 118 | 119 | 120 | class MainWindow(QMainWindow): 121 | 122 | fileName = None 123 | 124 | def __init__(self): 125 | QMainWindow.__init__(self) 126 | 127 | self.selAspectRatioTypes = SelAspectRatioTypeManager() 128 | self.deviceTypes = DeviceTypeManager() 129 | 130 | self._viewer = ViewerItem(self) 131 | 132 | self.ui=Ui_MainWindow() 133 | self.ui.setupUi(self) 134 | 135 | # these options are awkwardly named and possibly confusing, so they are 136 | # not shown by default 137 | self.ui.labelAllowedChanges.hide() 138 | self.ui.editAllowedChanges.hide() 139 | self.ui.labelSensitivity.hide() 140 | self.ui.editSensitivity.hide() 141 | 142 | # self.ui.tabWidget. 143 | 144 | # http://standards.freedesktop.org/icon-naming-spec/icon-naming-spec-latest.html 145 | self.setWindowIcon(QIcon.fromTheme('edit-cut')) 146 | self.ui.actionOpenFile.setIcon(QIcon.fromTheme('document-open')) 147 | self.ui.actionKrop.setIcon(QIcon.fromTheme('face-smile')) 148 | self.ui.actionZoomIn.setIcon(QIcon.fromTheme('zoom-in')) 149 | self.ui.actionZoomOut.setIcon(QIcon.fromTheme('zoom-out')) 150 | self.ui.actionFitInView.setIcon(QIcon.fromTheme('zoom-fit-best')) 151 | self.ui.actionPreviousPage.setIcon(QIcon.fromTheme('go-previous')) 152 | self.ui.actionNextPage.setIcon(QIcon.fromTheme('go-next')) 153 | self.ui.actionFirstPage.setIcon(QIcon.fromTheme('go-first')) 154 | self.ui.actionLastPage.setIcon(QIcon.fromTheme('go-last')) 155 | self.ui.actionTrimMargins.setIcon(QIcon.fromTheme('transform-crop')) 156 | self.ui.actionTrimMarginsAll.setIcon(QIcon.fromTheme('transform-crop')) 157 | # self.ui.actionTrimMarginsAll.setIcon(QIcon.fromTheme('select-rectangular')) 158 | # self.ui.actionTrimMarginsAll.setIcon(QIcon.fromTheme('edit-guides')) 159 | self.ui.actionNewSelection.setIcon(QIcon.fromTheme('select-rectangular')) 160 | # self.ui.actionNewSelection.setIcon(QIcon.fromTheme('draw-rectangle')) 161 | self.ui.actionDeleteSelection.setIcon(QIcon.fromTheme('edit-delete')) 162 | 163 | if QIcon.hasThemeIcon('document-open'): 164 | self.ui.buttonFileSelect.setIcon(QIcon.fromTheme('document-open')) 165 | else: 166 | self.ui.buttonFileSelect.setText('...') 167 | self.ui.buttonFileSelect.setAutoRaise(False) 168 | 169 | if QIcon.hasThemeIcon('go-first') and QIcon.hasThemeIcon('go-previous') \ 170 | and QIcon.hasThemeIcon('go-next') and QIcon.hasThemeIcon('go-last'): 171 | self.ui.buttonFirst.setIcon(QIcon.fromTheme('go-first')) 172 | self.ui.buttonPrevious.setIcon(QIcon.fromTheme('go-previous')) 173 | self.ui.buttonNext.setIcon(QIcon.fromTheme('go-next')) 174 | self.ui.buttonLast.setIcon(QIcon.fromTheme('go-last')) 175 | else: 176 | self.ui.buttonFirst.setText('<<') 177 | self.ui.buttonPrevious.setText('<') 178 | self.ui.buttonNext.setText('>') 179 | self.ui.buttonLast.setText('>>') 180 | self.ui.buttonFirst.setFlat(False) 181 | self.ui.buttonPrevious.setFlat(False) 182 | self.ui.buttonNext.setFlat(False) 183 | self.ui.buttonLast.setFlat(False) 184 | 185 | # we need to add the action to a widget in order for keyboard shortcuts to work 186 | self.addAction(self.ui.actionNewSelection) 187 | self.addAction(self.ui.actionNewSelectionGrid) 188 | self.addAction(self.ui.actionDeleteSelection) 189 | self.addAction(self.ui.actionFirstPage) 190 | self.addAction(self.ui.actionLastPage) 191 | 192 | self.ui.actionOpenFile.triggered.connect(self.slotOpenFile) 193 | self.ui.actionSelectFile.triggered.connect(self.slotSelectFile) 194 | self.ui.actionKrop.triggered.connect(self.slotKrop) 195 | self.ui.actionZoomIn.triggered.connect(self.slotZoomIn) 196 | self.ui.actionZoomOut.triggered.connect(self.slotZoomOut) 197 | self.ui.actionFitInView.toggled.connect(self.slotFitInView) 198 | self.ui.actionPreviousPage.triggered.connect(self.slotPreviousPage) 199 | self.ui.actionNextPage.triggered.connect(self.slotNextPage) 200 | self.ui.actionFirstPage.triggered.connect(self.slotFirstPage) 201 | self.ui.actionLastPage.triggered.connect(self.slotLastPage) 202 | self.ui.actionDeleteSelection.triggered.connect(self.slotDeleteSelection) 203 | self.ui.actionNewSelection.triggered.connect(self.slotNewSelection) 204 | self.ui.actionNewSelectionGrid.triggered.connect(self.slotNewSelectionGrid) 205 | self.ui.actionTrimMargins.triggered.connect(self.slotTrimMargins) 206 | self.ui.actionTrimMarginsAll.triggered.connect(self.slotTrimMarginsAll) 207 | self.ui.documentView.customContextMenuRequested.connect(self.slotContextMenu) 208 | self.ui.editCurrentPage.textEdited.connect(self.slotCurrentPageEdited) 209 | self.ui.radioSelAll.toggled.connect(self.slotSelectionMode) 210 | self.ui.radioSelEvenOdd.toggled.connect(self.slotSelectionMode) 211 | self.ui.radioSelIndividual.toggled.connect(self.slotSelectionMode) 212 | # self.ui.editSelExceptions.editingFinished.connect(self.slotSelExceptionsChanged) 213 | self.ui.editSelExceptions.textEdited.connect(self.slotSelExceptionsEdited) 214 | self.ui.comboSelAspectRatioType.currentIndexChanged.connect(self.slotSelAspectRatioTypeChanged) 215 | self.ui.editSelAspectRatio.editingFinished.connect(self.slotSelAspectRatioChanged) 216 | self.ui.comboDistributeDevice.currentIndexChanged.connect(self.slotDeviceTypeChanged) 217 | self.ui.editDistributeAspectRatio.editingFinished.connect(self.slotDistributeAspectRatioChanged) 218 | self.ui.splitter.splitterMoved.connect(self.slotSplitterMoved) 219 | 220 | self.pdfScene = QGraphicsScene(self.ui.documentView) 221 | self.pdfScene.setBackgroundBrush(self.pdfScene.palette().dark()) 222 | self.pdfScene.addItem(self.viewer) 223 | 224 | self.readSettings() 225 | 226 | # populate combobox with aspect ratio types 227 | for t in self.selAspectRatioTypes: 228 | self.ui.comboSelAspectRatioType.addItem(t.name) 229 | self.ui.comboSelAspectRatioType.addItem("Custom") 230 | # populate combobox with device types 231 | for t in self.deviceTypes: 232 | self.ui.comboDistributeDevice.addItem(t.name) 233 | self.ui.comboDistributeDevice.addItem("Custom") 234 | 235 | # disable Ghostscript option if gs is not available 236 | if not which('gs'): 237 | self.ui.checkGhostscript.setChecked(False) 238 | self.ui.checkGhostscript.setEnabled(False) 239 | 240 | self.ui.documentView.setScene(self.pdfScene) 241 | self.ui.documentView.setFocus() 242 | 243 | 244 | @property 245 | def viewer(self): 246 | return self._viewer 247 | 248 | @property 249 | def selections(self): 250 | return self.viewer.selections 251 | 252 | def currentSelectionUpdated(self): 253 | sel = self.selections.currentSelection 254 | if sel: 255 | r = sel.boundingRect() 256 | self.ui.groupCurrentSel.setEnabled(True) 257 | index, s = sel.aspectRatioData 258 | self.ui.comboSelAspectRatioType.setCurrentIndex(index) 259 | self.ui.editSelAspectRatio.setText(s) 260 | if index == 0: 261 | w, h = int(r.width()), int(r.height()) 262 | self.ui.editSelAspectRatio.setText("{} : {}".format(w, h)) 263 | else: 264 | self.ui.comboSelAspectRatioType.setCurrentIndex(0) 265 | self.ui.editSelAspectRatio.setText("") 266 | self.ui.groupCurrentSel.setEnabled(False) 267 | 268 | def readSettings(self): 269 | settings = QSettings() 270 | geometry = settings.value("Window/Geometry", "") 271 | if geometry: 272 | self.restoreGeometry(geometry) 273 | splitter = settings.value("Window/Splitter", "") 274 | if splitter: 275 | self.ui.splitter.restoreState(splitter) 276 | self.ui.actionFitInView.setChecked(settings.value("Window/FitInView", "") == "true") 277 | 278 | self.ui.checkTrimUseAllPages.setChecked(settings.value("Trim/UseAllPages", "") == "true") 279 | self.ui.editPadding.setText( 280 | settings.value("Trim/Padding", "2")) 281 | self.ui.editAllowedChanges.setText( 282 | settings.value("Trim/AllowedChanges", "0")) 283 | self.ui.editSensitivity.setText( 284 | settings.value("Trim/Sensitivity", "5")) 285 | 286 | self.ui.checkGhostscript.setChecked(settings.value("PDF/Optimize", "gs") == "gs") 287 | self.ui.checkIncludePagesWithoutSelections.setChecked( 288 | settings.value("PDF/IncludePagesWithoutSelections", "") == "true") 289 | 290 | self.selAspectRatioTypes.loadTypes(settings) 291 | self.deviceTypes.loadTypes(settings) 292 | 293 | def writeSettings(self): 294 | settings = QSettings() 295 | settings.setValue("Window/Geometry", self.saveGeometry()) 296 | settings.setValue("Window/Splitter", self.ui.splitter.saveState()) 297 | settings.setValue("Window/FitInView", "true" if 298 | self.ui.actionFitInView.isChecked() else "false") 299 | 300 | settings.setValue("Trim/UseAllPages", "true" if 301 | self.ui.checkTrimUseAllPages.isChecked() else "false") 302 | settings.setValue("Trim/Padding", 303 | self.ui.editPadding.text()) 304 | settings.setValue("Trim/AllowedChanges", 305 | self.ui.editAllowedChanges.text()) 306 | settings.setValue("Trim/Sensitivity", 307 | self.ui.editSensitivity.text()) 308 | 309 | settings.setValue("PDF/Optimize", "gs" if 310 | self.ui.checkGhostscript.isChecked() else "no") 311 | settings.setValue("PDF/IncludePagesWithoutSelections", "true" if 312 | self.ui.checkIncludePagesWithoutSelections.isChecked() else "false") 313 | 314 | self.selAspectRatioTypes.saveTypes(settings) 315 | self.deviceTypes.saveTypes(settings) 316 | 317 | def openFile(self, fileName): 318 | if fileName: 319 | self.viewer.load(fileName) 320 | if not self.viewer.isEmpty(): 321 | self.fileName = fileName 322 | outputFileName = "%s-cropped.pdf" % splitext(fileName)[0] 323 | self.slotFitInView(self.ui.actionFitInView.isChecked()) 324 | else: 325 | self.fileName = '' 326 | outputFileName = '' 327 | self.showWarning(self.tr("Something got in our way"), 328 | self.tr("The PDF file couldn't be read. " 329 | "Please check the file and its permissions.")) 330 | self.setWindowFilePath(self.fileName) 331 | self.ui.actionKrop.setEnabled(not self.viewer.isEmpty()) 332 | self.ui.actionTrimMarginsAll.setEnabled(not self.viewer.isEmpty()) 333 | self.ui.editFile.setText(outputFileName) 334 | self.updateControls() 335 | 336 | def slotOpenFile(self): 337 | fileName = QFileDialog.getOpenFileName(self, 338 | self.tr("Open PDF"), "", self.tr("PDF Files (*.pdf)")); 339 | fileName = fileName[0] 340 | self.openFile(fileName) 341 | 342 | def slotSelectFile(self): 343 | fileName = QFileDialog.getSaveFileName(self, 344 | self.tr("Save cropped PDF to ..."), "", self.tr("PDF Files (*.pdf)")) 345 | # None, QFileDialog.DontConfirmOverwrite) 346 | try: 347 | self.ui.editFile.setText(fileName) 348 | except TypeError: 349 | # new versions of Qt return a tuple (fileName, selectedFilter) 350 | self.ui.editFile.setText(fileName[0]) 351 | 352 | def showWarning(self, title, text): 353 | # if krop is called with parameter --go, then the main window is never 354 | # shown; in that case, we output the warning to the shell 355 | if self.isVisible(): 356 | QMessageBox.warning(self, title, text) 357 | else: 358 | sys.stderr.write(self.tr('WARNING: ') + title + '\n' + text + '\n') 359 | 360 | def str2pages(self, s): 361 | pages = [] 362 | intervals = [ [ n.strip() for n in i.split('-') ] 363 | for i in s.split(',') ] 364 | for i in intervals: 365 | a,b = i[0], i[-1] 366 | if a: 367 | if not b: b = self.viewer.numPages() 368 | pages.extend(range(int(a)-1,int(b))) # subtract 1 because pages are counted from 0 internally 369 | return pages 370 | 371 | def slotKrop(self): 372 | # file names 373 | inputFileName = self.fileName 374 | outputFileName = self.ui.editFile.text() 375 | 376 | # which pages 377 | s = self.ui.editWhichPages.text() 378 | if not s: 379 | pages = range(self.viewer.numPages()) 380 | else: 381 | pages = self.str2pages(s) 382 | 383 | alwaysinclude = self.ui.checkIncludePagesWithoutSelections.isChecked() 384 | 385 | rotation = [0, 270, 90, 180][self.ui.comboRotation.currentIndex()] 386 | 387 | # Done when selecting filename. 388 | # if exists(outputFileName): 389 | # self.showWarning(self.tr("Overwrite File?"), 390 | # self.tr("A file named \"...\" already exists. Are you sure you want to overwrite it?")) 391 | # return 392 | 393 | QApplication.setOverrideCursor(Qt.CursorShape.WaitCursor) 394 | try: 395 | pdf = PdfFile() 396 | pdf.loadFromFile(inputFileName) 397 | cropper = PdfCropper() 398 | cropper.copyDocumentRoot(pdf) 399 | for nr in pages: 400 | c = self.viewer.cropValues(nr) 401 | cropper.addPageCropped(pdf, nr, c, alwaysinclude, rotation) 402 | if self.ui.checkGhostscript.isChecked(): 403 | import tempfile, os 404 | with tempfile.NamedTemporaryFile(suffix='.pdf', delete=False) as fp: 405 | cropper.writeToStream(fp.file) 406 | # we close the file because it depends on the platform 407 | # whether it can be read a second time while still open 408 | fp.close() 409 | optimizePdfGhostscript(fp.name, outputFileName) 410 | os.remove(fp.name) 411 | else: 412 | cropper.writeToFile(outputFileName) 413 | QApplication.restoreOverrideCursor() 414 | except PdfEncryptedError as err: 415 | QApplication.restoreOverrideCursor() 416 | self.showWarning(self.tr("PDF is encrypted"), 417 | self.tr("This PDF needs to be decrypted before cropping. " 418 | "You could try to do that using qpdf:" 419 | "\nqpdf --password='hello' --decrypt encrypted.pdf decrypted.pdf")) 420 | raise err 421 | except IOError as err: 422 | QApplication.restoreOverrideCursor() 423 | self.showWarning(self.tr("Could not write cropped PDF"), 424 | self.tr("An error occured while writing the cropped PDF. " 425 | "Please make sure that you have permission to write to " 426 | "the selected file." 427 | "\n\nThe official error is:\n\n{0}").format(err)) 428 | except Exception as err: 429 | QApplication.restoreOverrideCursor() 430 | self.showWarning(self.tr("Something got in our way"), 431 | self.tr("The following unexpected error has occured:" 432 | "\n\n{0}").format(err)) 433 | raise err 434 | 435 | def slotZoomIn(self): 436 | self.ui.actionFitInView.setChecked(False) 437 | self.ui.documentView.scale(1.2, 1.2) 438 | 439 | def slotZoomOut(self): 440 | self.ui.actionFitInView.setChecked(False) 441 | self.ui.documentView.scale(1/1.2, 1/1.2) 442 | 443 | def slotFitInView(self, checked): 444 | if checked: 445 | self.ui.documentView.fitInView(self.pdfScene.sceneRect(), 446 | Qt.AspectRatioMode.KeepAspectRatio) 447 | 448 | def slotSplitterMoved(self, pos, idx): 449 | self.slotFitInView(self.ui.actionFitInView.isChecked()) 450 | 451 | def slotPreviousPage(self): 452 | self.viewer.previousPage() 453 | self.updateControls() 454 | 455 | def slotNextPage(self): 456 | self.viewer.nextPage() 457 | self.updateControls() 458 | 459 | def slotFirstPage(self): 460 | self.viewer.firstPage() 461 | self.updateControls() 462 | 463 | def slotLastPage(self): 464 | self.viewer.lastPage() 465 | self.updateControls() 466 | 467 | def slotCurrentPageEdited(self, text): 468 | try: 469 | n = int(text) 470 | self.viewer.currentPageIndex = n-1 471 | self.updateControls() 472 | except ValueError: 473 | pass 474 | 475 | def updateControls(self): 476 | cur = '' 477 | num = '' 478 | if not self.viewer.isEmpty(): 479 | cur = str(self.viewer.currentPageIndex+1) 480 | num = str(self.viewer.numPages()) 481 | self.ui.editCurrentPage.setText(cur) 482 | self.ui.editMaxPage.setText(num) 483 | 484 | def slotSelectionMode(self, checked): 485 | if checked: 486 | enableExceptions = True 487 | if self.ui.radioSelAll.isChecked(): 488 | self.selections.selectionMode = ViewerSelections.all 489 | elif self.ui.radioSelEvenOdd.isChecked(): 490 | self.selections.selectionMode = ViewerSelections.evenodd 491 | elif self.ui.radioSelIndividual.isChecked(): 492 | enableExceptions = False 493 | self.selections.selectionMode = ViewerSelections.individual 494 | self.ui.editSelExceptions.setEnabled(enableExceptions) 495 | 496 | def slotSelExceptionsChanged(self): 497 | s = self.ui.editSelExceptions.text() 498 | pages = self.str2pages(s) 499 | self.selections.selectionExceptions = pages 500 | 501 | def slotSelExceptionsEdited(self, text): 502 | try: 503 | pages = self.str2pages(text) 504 | self.selections.selectionExceptions = pages 505 | except ValueError: 506 | pass 507 | 508 | 509 | def slotSelAspectRatioChanged(self): 510 | sel = self.selections.currentSelection 511 | if sel: 512 | index = self.ui.comboSelAspectRatioType.currentIndex() 513 | # index=0: flexible 514 | # index=last: custom 515 | s = self.ui.editSelAspectRatio.text() 516 | sel.aspectRatioData = [index, s] 517 | 518 | def slotSelAspectRatioTypeChanged(self, index): 519 | sel = self.selections.currentSelection 520 | t = self.selAspectRatioTypes.getType(index) 521 | # index=0: flexible 522 | # t=None: custom 523 | ar = "" 524 | if index == 0 or t is None: 525 | if sel: 526 | r = sel.boundingRect() 527 | w, h = int(r.width()), int(r.height()) 528 | ar = "{} : {}".format(w, h) 529 | elif t is not None: 530 | ar = "{} : {}".format(t.width, t.height) 531 | self.ui.editSelAspectRatio.setEnabled(t is None) 532 | self.ui.editSelAspectRatio.setText(ar) 533 | if sel: 534 | s = self.ui.editSelAspectRatio.text() 535 | sel.aspectRatioData = [index, s] 536 | 537 | 538 | def distributeAspectRatioChanged(self, aspectRatio): 539 | self.selections.distributeAspectRatio = aspectRatio 540 | 541 | def slotDistributeAspectRatioChanged(self): 542 | self.selections.distributeAspectRatio = aspectRatioFromStr(self.ui.editDistributeAspectRatio.text()) 543 | 544 | def slotDeviceTypeChanged(self, index): 545 | t = self.deviceTypes.getType(index) 546 | ar = t and "%s : %s" % (t.width, t.height) or "w : h" 547 | self.ui.editDistributeAspectRatio.setEnabled(t is None) 548 | self.ui.editDistributeAspectRatio.setText(ar) 549 | self.slotDistributeAspectRatioChanged() 550 | 551 | def slotContextMenu(self, pos): 552 | if self.viewer.isEmpty(): 553 | return 554 | 555 | item = self.ui.documentView.itemAt(pos) 556 | menuForSelection= False 557 | try: 558 | self.selections.currentSelection = item.selection 559 | menuForSelection= True 560 | except AttributeError: 561 | pass 562 | popMenu = QMenu() 563 | popMenu.addAction(self.ui.actionNewSelection) 564 | popMenu.addAction(self.ui.actionNewSelectionGrid) 565 | if menuForSelection: 566 | popMenu.addAction(self.ui.actionDeleteSelection) 567 | popMenu.addAction(self.ui.actionTrimMargins) 568 | else: 569 | popMenu.addAction(self.ui.actionTrimMarginsAll) 570 | popMenu.exec_(self.ui.documentView.mapToGlobal(pos)) 571 | 572 | def slotDeleteSelection(self): 573 | if self.selections.currentSelection is not None: 574 | self.selections.deleteSelection(self.selections.currentSelection) 575 | 576 | def slotNewSelection(self): 577 | self.createSelectionGrid("1") 578 | 579 | def slotNewSelectionGrid(self): 580 | if not self.viewer.isEmpty(): 581 | default = "2x1" 582 | if self.viewer.isPortrait(): 583 | default = "1x2" 584 | grid, ok = QInputDialog.getText(self, self.tr('New Selection Grid...'), 585 | self.tr('Enter the dimensions of the grid:'), text=default) 586 | if ok: 587 | self.createSelectionGrid(grid) 588 | 589 | def createSelectionGrid(self, grid): 590 | if self.viewer.isEmpty(): 591 | return 592 | 593 | try: 594 | colsrows = [int(x) for x in grid.split('x')] 595 | cols = colsrows[0] 596 | # if only one value is specified, we determine the number of 597 | # columns/rows according to whether the page is landscape or 598 | # portrait 599 | if len(colsrows) == 1: 600 | if self.viewer.isPortrait(): 601 | cols, rows = 1, cols 602 | else: 603 | rows = 1 604 | else: 605 | rows = colsrows[1] 606 | except: 607 | self.showWarning(self.tr("Bad value for grid parameter"), self.tr("For creating a grid " 608 | "of selections, you need to specify the dimensions of the grid in the form '2x3'. " 609 | "You can also enter a single number, in which case the number of columns/rows is " 610 | "determined according to whether the page is landscape or portrait.")) 611 | return 612 | 613 | for j in range(rows): 614 | for i in range(cols): 615 | sel = self.selections.addSelection() 616 | r = sel.boundingRect() 617 | w = r.width()/cols 618 | h = r.height()/rows 619 | p0 = QPointF(r.left()+i*w, r.top()+j*h) 620 | sel.setBoundingRect(p0, p0 + QPointF(w, h)) 621 | self.pdfScene.update() 622 | 623 | def getPadding(self): 624 | """Return [top, right, bottom, left] tuple specifying padding for trimming margins.""" 625 | try: 626 | # padding can be specified as in CSS (using one to four values): 627 | # top, right, bottom, left 628 | # top, right+left, bottom 629 | # top+bottom, right+left 630 | # top+bottom+right+left 631 | padding = [ float(a) for a in self.ui.editPadding.text().split(',') if a ] 632 | if len(padding) == 0: 633 | return [0,0,0,0] 634 | if len(padding) == 1: 635 | return 4*padding 636 | if len(padding) == 2: 637 | return 2*padding 638 | if len(padding) == 3: 639 | return padding + [padding[1]] 640 | if len(padding) == 4: 641 | return padding 642 | raise ValueError 643 | except ValueError: 644 | self.showWarning(self.tr("Bad value for padding"), self.tr("The value of padding " 645 | "(under settings for trimming margins) must be a list of one to four floats, " 646 | "separated by a comma." 647 | "\n\nAs in CSS, options are: " 648 | "\n(four values) top, right, bottom, left" 649 | "\n(three values) top, right+left, bottom" 650 | "\n(two values) top+bottom, right+left")) 651 | return [0,0,0,0] 652 | 653 | def slotTrimMarginsAll(self): 654 | # trim margins of all selections on the current page 655 | noSelections = True 656 | for sel in self.selections.items: 657 | if sel.isVisible(): 658 | noSelections = False 659 | self.trimMarginsSelection(sel) 660 | # if there is no selections, then create one 661 | if noSelections and not self.viewer.isEmpty(): 662 | sel = self.selections.addSelection() 663 | self.trimMarginsSelection(sel) 664 | self.pdfScene.update() 665 | 666 | def slotTrimMargins(self): 667 | if self.selections.currentSelection is not None: 668 | self.trimMarginsSelection(self.selections.currentSelection) 669 | self.pdfScene.update() 670 | 671 | def trimMarginsSelection(self, sel): 672 | sensitivity = float(self.ui.editSensitivity.text()) 673 | allowedchanges = float(self.ui.editAllowedChanges.text()) 674 | 675 | # if requested, use all pages for trimming; otherwise, just the current page 676 | pages = [self.viewer.currentPageIndex] 677 | if self.ui.checkTrimUseAllPages.isChecked(): 678 | pages = [i for i in range(self.viewer.numPages()) if sel.selectionVisibleOnPage(i)] 679 | 680 | QApplication.setOverrideCursor(Qt.CursorShape.WaitCursor) 681 | try: 682 | # orect is the original selection, nrect is the trimmed version 683 | orect = sel.mapRectToImage(sel.rect).toRect() 684 | nrect = None 685 | for idx in pages: 686 | # calculate values for trimming 687 | img = self.viewer.getImage(idx) 688 | nrect = autoTrimMargins(img, orect, nrect, sensitivity, allowedchanges) 689 | 690 | orect = QRectF(orect) 691 | nrect = QRectF(nrect) 692 | 693 | # adjust for padding ... 694 | dtop, dright, dbottom, dleft = self.getPadding() 695 | nrect.adjust(-dleft, -dtop, dright, dbottom) 696 | # ... but don't overadjust 697 | nrect = nrect.intersected(orect) 698 | 699 | # take fixed aspect ratio into account 700 | if sel.aspectRatio: 701 | r, w, h = sel.aspectRatio, nrect.width(), nrect.height() 702 | nw, nh = max(w, h*r), max(h, w/r) 703 | if nw > w: 704 | d1 = (nw - w) / 2 705 | if nrect.left() - orect.left() < d1: 706 | d1 = nrect.left() - orect.left() 707 | elif orect.right() - nrect.right() < d1: 708 | d1 = nw - w - orect.right() + nrect.right() 709 | d2 = nw - w - d1 710 | nrect.adjust(-d1, 0, d2, 0) 711 | elif nh > h: 712 | d1 = (nh - h) / 2 713 | if nrect.top() - orect.top() < d1: 714 | d1 = nrect.top() - orect.top() 715 | elif orect.bottom() - nrect.bottom() < d1: 716 | d1 = nh - h - orect.bottom() + nrect.bottom() 717 | d2 = nh - h - d1 718 | nrect.adjust(0, -d1, 0, d2) 719 | 720 | # set selection to new values 721 | nrect = sel.mapRectFromImage(nrect) 722 | sel.setBoundingRect(nrect.topLeft(), nrect.bottomRight()) 723 | finally: 724 | QApplication.restoreOverrideCursor() 725 | 726 | def resizeEvent(self, event): 727 | self.slotFitInView(self.ui.actionFitInView.isChecked()) 728 | 729 | def closeEvent(self, event): 730 | self.writeSettings() 731 | -------------------------------------------------------------------------------- /krop/mainwindowui_qt5.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | # Form implementation generated from reading ui file 'mainwindow.ui' 4 | # 5 | # Created by: PyQt5 UI code generator 5.15.6 6 | # 7 | # WARNING: Any manual changes made to this file will be lost when pyuic5 is 8 | # run again. Do not edit this file unless you know what you are doing. 9 | 10 | 11 | from PyQt5 import QtCore, QtGui, QtWidgets 12 | 13 | 14 | class Ui_MainWindow(object): 15 | def setupUi(self, MainWindow): 16 | MainWindow.setObjectName("MainWindow") 17 | MainWindow.resize(949, 736) 18 | self.centralwidget = QtWidgets.QWidget(MainWindow) 19 | self.centralwidget.setObjectName("centralwidget") 20 | self.verticalLayout_7 = QtWidgets.QVBoxLayout(self.centralwidget) 21 | self.verticalLayout_7.setObjectName("verticalLayout_7") 22 | self.splitter = QtWidgets.QSplitter(self.centralwidget) 23 | self.splitter.setOrientation(QtCore.Qt.Horizontal) 24 | self.splitter.setChildrenCollapsible(False) 25 | self.splitter.setObjectName("splitter") 26 | self.tabWidget = QtWidgets.QTabWidget(self.splitter) 27 | sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Expanding) 28 | sizePolicy.setHorizontalStretch(0) 29 | sizePolicy.setVerticalStretch(0) 30 | sizePolicy.setHeightForWidth(self.tabWidget.sizePolicy().hasHeightForWidth()) 31 | self.tabWidget.setSizePolicy(sizePolicy) 32 | self.tabWidget.setObjectName("tabWidget") 33 | self.tabBasic = QtWidgets.QWidget() 34 | self.tabBasic.setObjectName("tabBasic") 35 | self.verticalLayout_4 = QtWidgets.QVBoxLayout(self.tabBasic) 36 | self.verticalLayout_4.setObjectName("verticalLayout_4") 37 | self.groupSaveTo = QtWidgets.QGroupBox(self.tabBasic) 38 | self.groupSaveTo.setObjectName("groupSaveTo") 39 | self.gridLayout = QtWidgets.QGridLayout(self.groupSaveTo) 40 | self.gridLayout.setObjectName("gridLayout") 41 | self.editFile = QtWidgets.QLineEdit(self.groupSaveTo) 42 | self.editFile.setObjectName("editFile") 43 | self.gridLayout.addWidget(self.editFile, 0, 0, 1, 1) 44 | self.buttonFileSelect = QtWidgets.QToolButton(self.groupSaveTo) 45 | self.buttonFileSelect.setText("") 46 | self.buttonFileSelect.setAutoRaise(True) 47 | self.buttonFileSelect.setObjectName("buttonFileSelect") 48 | self.gridLayout.addWidget(self.buttonFileSelect, 0, 1, 1, 1) 49 | self.verticalLayout_4.addWidget(self.groupSaveTo) 50 | self.groupPDFOperations = QtWidgets.QGroupBox(self.tabBasic) 51 | self.groupPDFOperations.setFlat(False) 52 | self.groupPDFOperations.setObjectName("groupPDFOperations") 53 | self.verticalLayout_8 = QtWidgets.QVBoxLayout(self.groupPDFOperations) 54 | self.verticalLayout_8.setObjectName("verticalLayout_8") 55 | self.comboRotation = QtWidgets.QComboBox(self.groupPDFOperations) 56 | self.comboRotation.setObjectName("comboRotation") 57 | self.comboRotation.addItem("") 58 | self.comboRotation.addItem("") 59 | self.comboRotation.addItem("") 60 | self.comboRotation.addItem("") 61 | self.verticalLayout_8.addWidget(self.comboRotation) 62 | self.checkGhostscript = QtWidgets.QCheckBox(self.groupPDFOperations) 63 | sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Fixed) 64 | sizePolicy.setHorizontalStretch(0) 65 | sizePolicy.setVerticalStretch(0) 66 | sizePolicy.setHeightForWidth(self.checkGhostscript.sizePolicy().hasHeightForWidth()) 67 | self.checkGhostscript.setSizePolicy(sizePolicy) 68 | self.checkGhostscript.setChecked(True) 69 | self.checkGhostscript.setObjectName("checkGhostscript") 70 | self.verticalLayout_8.addWidget(self.checkGhostscript) 71 | self.verticalLayout_4.addWidget(self.groupPDFOperations) 72 | self.groupWhichPages = QtWidgets.QGroupBox(self.tabBasic) 73 | self.groupWhichPages.setObjectName("groupWhichPages") 74 | self.verticalLayout = QtWidgets.QVBoxLayout(self.groupWhichPages) 75 | self.verticalLayout.setObjectName("verticalLayout") 76 | self.editWhichPages = QtWidgets.QLineEdit(self.groupWhichPages) 77 | self.editWhichPages.setObjectName("editWhichPages") 78 | self.verticalLayout.addWidget(self.editWhichPages) 79 | self.checkIncludePagesWithoutSelections = QtWidgets.QCheckBox(self.groupWhichPages) 80 | self.checkIncludePagesWithoutSelections.setChecked(True) 81 | self.checkIncludePagesWithoutSelections.setObjectName("checkIncludePagesWithoutSelections") 82 | self.verticalLayout.addWidget(self.checkIncludePagesWithoutSelections) 83 | self.verticalLayout_4.addWidget(self.groupWhichPages) 84 | self.groupSelectionMode = QtWidgets.QGroupBox(self.tabBasic) 85 | self.groupSelectionMode.setFlat(False) 86 | self.groupSelectionMode.setObjectName("groupSelectionMode") 87 | self.gridLayout_2 = QtWidgets.QGridLayout(self.groupSelectionMode) 88 | self.gridLayout_2.setObjectName("gridLayout_2") 89 | self.radioSelAll = QtWidgets.QRadioButton(self.groupSelectionMode) 90 | self.radioSelAll.setChecked(True) 91 | self.radioSelAll.setObjectName("radioSelAll") 92 | self.gridLayout_2.addWidget(self.radioSelAll, 0, 0, 1, 2) 93 | self.radioSelEvenOdd = QtWidgets.QRadioButton(self.groupSelectionMode) 94 | self.radioSelEvenOdd.setObjectName("radioSelEvenOdd") 95 | self.gridLayout_2.addWidget(self.radioSelEvenOdd, 1, 0, 1, 2) 96 | self.radioSelIndividual = QtWidgets.QRadioButton(self.groupSelectionMode) 97 | self.radioSelIndividual.setObjectName("radioSelIndividual") 98 | self.gridLayout_2.addWidget(self.radioSelIndividual, 2, 0, 1, 2) 99 | self.labelSelExceptions = QtWidgets.QLabel(self.groupSelectionMode) 100 | self.labelSelExceptions.setObjectName("labelSelExceptions") 101 | self.gridLayout_2.addWidget(self.labelSelExceptions, 3, 0, 1, 1) 102 | self.editSelExceptions = QtWidgets.QLineEdit(self.groupSelectionMode) 103 | self.editSelExceptions.setObjectName("editSelExceptions") 104 | self.gridLayout_2.addWidget(self.editSelExceptions, 3, 1, 1, 1) 105 | self.verticalLayout_4.addWidget(self.groupSelectionMode) 106 | spacerItem = QtWidgets.QSpacerItem(20, 484, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Expanding) 107 | self.verticalLayout_4.addItem(spacerItem) 108 | self.tabWidget.addTab(self.tabBasic, "") 109 | self.tabAdvanced = QtWidgets.QWidget() 110 | self.tabAdvanced.setObjectName("tabAdvanced") 111 | self.verticalLayout_5 = QtWidgets.QVBoxLayout(self.tabAdvanced) 112 | self.verticalLayout_5.setObjectName("verticalLayout_5") 113 | self.groupCurrentSel = QtWidgets.QGroupBox(self.tabAdvanced) 114 | self.groupCurrentSel.setEnabled(False) 115 | self.groupCurrentSel.setObjectName("groupCurrentSel") 116 | self.gridLayout_4 = QtWidgets.QGridLayout(self.groupCurrentSel) 117 | self.gridLayout_4.setObjectName("gridLayout_4") 118 | self.comboSelAspectRatioType = QtWidgets.QComboBox(self.groupCurrentSel) 119 | self.comboSelAspectRatioType.setEditable(False) 120 | self.comboSelAspectRatioType.setSizeAdjustPolicy(QtWidgets.QComboBox.AdjustToContentsOnFirstShow) 121 | self.comboSelAspectRatioType.setObjectName("comboSelAspectRatioType") 122 | self.gridLayout_4.addWidget(self.comboSelAspectRatioType, 0, 0, 1, 2) 123 | self.editSelAspectRatio = QtWidgets.QLineEdit(self.groupCurrentSel) 124 | self.editSelAspectRatio.setObjectName("editSelAspectRatio") 125 | self.gridLayout_4.addWidget(self.editSelAspectRatio, 1, 1, 1, 1) 126 | self.labelSelAspectRatio = QtWidgets.QLabel(self.groupCurrentSel) 127 | self.labelSelAspectRatio.setObjectName("labelSelAspectRatio") 128 | self.gridLayout_4.addWidget(self.labelSelAspectRatio, 1, 0, 1, 1) 129 | self.verticalLayout_5.addWidget(self.groupCurrentSel) 130 | self.groupTrimMargins = QtWidgets.QGroupBox(self.tabAdvanced) 131 | self.groupTrimMargins.setObjectName("groupTrimMargins") 132 | self.gridLayout_3 = QtWidgets.QGridLayout(self.groupTrimMargins) 133 | self.gridLayout_3.setObjectName("gridLayout_3") 134 | self.checkTrimUseAllPages = QtWidgets.QCheckBox(self.groupTrimMargins) 135 | self.checkTrimUseAllPages.setChecked(True) 136 | self.checkTrimUseAllPages.setObjectName("checkTrimUseAllPages") 137 | self.gridLayout_3.addWidget(self.checkTrimUseAllPages, 0, 0, 1, 2) 138 | self.labelPadding = QtWidgets.QLabel(self.groupTrimMargins) 139 | self.labelPadding.setObjectName("labelPadding") 140 | self.gridLayout_3.addWidget(self.labelPadding, 1, 0, 1, 1) 141 | self.editPadding = QtWidgets.QLineEdit(self.groupTrimMargins) 142 | self.editPadding.setText("") 143 | self.editPadding.setObjectName("editPadding") 144 | self.gridLayout_3.addWidget(self.editPadding, 1, 1, 1, 1) 145 | self.labelAllowedChanges = QtWidgets.QLabel(self.groupTrimMargins) 146 | self.labelAllowedChanges.setEnabled(True) 147 | self.labelAllowedChanges.setObjectName("labelAllowedChanges") 148 | self.gridLayout_3.addWidget(self.labelAllowedChanges, 2, 0, 1, 1) 149 | self.editAllowedChanges = QtWidgets.QLineEdit(self.groupTrimMargins) 150 | self.editAllowedChanges.setEnabled(True) 151 | self.editAllowedChanges.setObjectName("editAllowedChanges") 152 | self.gridLayout_3.addWidget(self.editAllowedChanges, 2, 1, 1, 1) 153 | self.labelSensitivity = QtWidgets.QLabel(self.groupTrimMargins) 154 | self.labelSensitivity.setEnabled(True) 155 | self.labelSensitivity.setObjectName("labelSensitivity") 156 | self.gridLayout_3.addWidget(self.labelSensitivity, 3, 0, 1, 1) 157 | self.editSensitivity = QtWidgets.QLineEdit(self.groupTrimMargins) 158 | self.editSensitivity.setEnabled(True) 159 | self.editSensitivity.setObjectName("editSensitivity") 160 | self.gridLayout_3.addWidget(self.editSensitivity, 3, 1, 1, 1) 161 | self.verticalLayout_5.addWidget(self.groupTrimMargins) 162 | self.groupDistribute = QtWidgets.QGroupBox(self.tabAdvanced) 163 | self.groupDistribute.setObjectName("groupDistribute") 164 | self.formLayout = QtWidgets.QFormLayout(self.groupDistribute) 165 | self.formLayout.setFieldGrowthPolicy(QtWidgets.QFormLayout.ExpandingFieldsGrow) 166 | self.formLayout.setObjectName("formLayout") 167 | self.comboDistributeDevice = QtWidgets.QComboBox(self.groupDistribute) 168 | self.comboDistributeDevice.setEditable(False) 169 | self.comboDistributeDevice.setSizeAdjustPolicy(QtWidgets.QComboBox.AdjustToContentsOnFirstShow) 170 | self.comboDistributeDevice.setObjectName("comboDistributeDevice") 171 | self.formLayout.setWidget(0, QtWidgets.QFormLayout.SpanningRole, self.comboDistributeDevice) 172 | self.labelDistributeAspectRatio = QtWidgets.QLabel(self.groupDistribute) 173 | self.labelDistributeAspectRatio.setObjectName("labelDistributeAspectRatio") 174 | self.formLayout.setWidget(1, QtWidgets.QFormLayout.LabelRole, self.labelDistributeAspectRatio) 175 | self.editDistributeAspectRatio = QtWidgets.QLineEdit(self.groupDistribute) 176 | self.editDistributeAspectRatio.setObjectName("editDistributeAspectRatio") 177 | self.formLayout.setWidget(1, QtWidgets.QFormLayout.FieldRole, self.editDistributeAspectRatio) 178 | self.labelDistributeHelp = QtWidgets.QLabel(self.groupDistribute) 179 | self.labelDistributeHelp.setWordWrap(True) 180 | self.labelDistributeHelp.setObjectName("labelDistributeHelp") 181 | self.formLayout.setWidget(2, QtWidgets.QFormLayout.SpanningRole, self.labelDistributeHelp) 182 | self.verticalLayout_5.addWidget(self.groupDistribute) 183 | spacerItem1 = QtWidgets.QSpacerItem(20, 339, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Expanding) 184 | self.verticalLayout_5.addItem(spacerItem1) 185 | self.tabWidget.addTab(self.tabAdvanced, "") 186 | self.tabHelp = QtWidgets.QWidget() 187 | self.tabHelp.setObjectName("tabHelp") 188 | self.verticalLayout_3 = QtWidgets.QVBoxLayout(self.tabHelp) 189 | self.verticalLayout_3.setObjectName("verticalLayout_3") 190 | self.labelHelp = QtWidgets.QLabel(self.tabHelp) 191 | sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Ignored, QtWidgets.QSizePolicy.Preferred) 192 | sizePolicy.setHorizontalStretch(0) 193 | sizePolicy.setVerticalStretch(0) 194 | sizePolicy.setHeightForWidth(self.labelHelp.sizePolicy().hasHeightForWidth()) 195 | self.labelHelp.setSizePolicy(sizePolicy) 196 | self.labelHelp.setMaximumSize(QtCore.QSize(16777215, 16777215)) 197 | self.labelHelp.setBaseSize(QtCore.QSize(0, 0)) 198 | self.labelHelp.setTextFormat(QtCore.Qt.AutoText) 199 | self.labelHelp.setWordWrap(True) 200 | self.labelHelp.setOpenExternalLinks(True) 201 | self.labelHelp.setObjectName("labelHelp") 202 | self.verticalLayout_3.addWidget(self.labelHelp) 203 | spacerItem2 = QtWidgets.QSpacerItem(20, 524, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Expanding) 204 | self.verticalLayout_3.addItem(spacerItem2) 205 | self.frameHelpCopyright = QtWidgets.QFrame(self.tabHelp) 206 | self.frameHelpCopyright.setFrameShape(QtWidgets.QFrame.HLine) 207 | self.frameHelpCopyright.setObjectName("frameHelpCopyright") 208 | self.verticalLayout_3.addWidget(self.frameHelpCopyright) 209 | self.labelHelpCopyright = QtWidgets.QLabel(self.tabHelp) 210 | sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Ignored, QtWidgets.QSizePolicy.Preferred) 211 | sizePolicy.setHorizontalStretch(0) 212 | sizePolicy.setVerticalStretch(0) 213 | sizePolicy.setHeightForWidth(self.labelHelpCopyright.sizePolicy().hasHeightForWidth()) 214 | self.labelHelpCopyright.setSizePolicy(sizePolicy) 215 | self.labelHelpCopyright.setTextFormat(QtCore.Qt.AutoText) 216 | self.labelHelpCopyright.setWordWrap(True) 217 | self.labelHelpCopyright.setOpenExternalLinks(True) 218 | self.labelHelpCopyright.setObjectName("labelHelpCopyright") 219 | self.verticalLayout_3.addWidget(self.labelHelpCopyright) 220 | self.tabWidget.addTab(self.tabHelp, "") 221 | self.frame = QtWidgets.QFrame(self.splitter) 222 | sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Preferred) 223 | sizePolicy.setHorizontalStretch(1) 224 | sizePolicy.setVerticalStretch(0) 225 | sizePolicy.setHeightForWidth(self.frame.sizePolicy().hasHeightForWidth()) 226 | self.frame.setSizePolicy(sizePolicy) 227 | self.frame.setFrameShape(QtWidgets.QFrame.NoFrame) 228 | self.frame.setFrameShadow(QtWidgets.QFrame.Raised) 229 | self.frame.setObjectName("frame") 230 | self.verticalLayout_2 = QtWidgets.QVBoxLayout(self.frame) 231 | self.verticalLayout_2.setContentsMargins(1, 1, 1, 1) 232 | self.verticalLayout_2.setObjectName("verticalLayout_2") 233 | self.documentView = QtWidgets.QGraphicsView(self.frame) 234 | self.documentView.setContextMenuPolicy(QtCore.Qt.CustomContextMenu) 235 | self.documentView.setFrameShadow(QtWidgets.QFrame.Sunken) 236 | self.documentView.setObjectName("documentView") 237 | self.verticalLayout_2.addWidget(self.documentView) 238 | self.frame_2 = QtWidgets.QFrame(self.frame) 239 | self.frame_2.setFrameShape(QtWidgets.QFrame.NoFrame) 240 | self.frame_2.setFrameShadow(QtWidgets.QFrame.Raised) 241 | self.frame_2.setObjectName("frame_2") 242 | self.horizontalLayout_2 = QtWidgets.QHBoxLayout(self.frame_2) 243 | self.horizontalLayout_2.setContentsMargins(0, 0, 0, 0) 244 | self.horizontalLayout_2.setObjectName("horizontalLayout_2") 245 | spacerItem3 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum) 246 | self.horizontalLayout_2.addItem(spacerItem3) 247 | self.buttonFirst = QtWidgets.QPushButton(self.frame_2) 248 | self.buttonFirst.setMinimumSize(QtCore.QSize(24, 24)) 249 | self.buttonFirst.setMaximumSize(QtCore.QSize(24, 24)) 250 | self.buttonFirst.setFocusPolicy(QtCore.Qt.NoFocus) 251 | self.buttonFirst.setText("") 252 | self.buttonFirst.setFlat(True) 253 | self.buttonFirst.setObjectName("buttonFirst") 254 | self.horizontalLayout_2.addWidget(self.buttonFirst) 255 | self.buttonPrevious = QtWidgets.QPushButton(self.frame_2) 256 | self.buttonPrevious.setMinimumSize(QtCore.QSize(24, 24)) 257 | self.buttonPrevious.setMaximumSize(QtCore.QSize(24, 24)) 258 | self.buttonPrevious.setFocusPolicy(QtCore.Qt.NoFocus) 259 | self.buttonPrevious.setText("") 260 | self.buttonPrevious.setFlat(True) 261 | self.buttonPrevious.setObjectName("buttonPrevious") 262 | self.horizontalLayout_2.addWidget(self.buttonPrevious) 263 | self.editCurrentPage = QtWidgets.QLineEdit(self.frame_2) 264 | sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed) 265 | sizePolicy.setHorizontalStretch(0) 266 | sizePolicy.setVerticalStretch(0) 267 | sizePolicy.setHeightForWidth(self.editCurrentPage.sizePolicy().hasHeightForWidth()) 268 | self.editCurrentPage.setSizePolicy(sizePolicy) 269 | self.editCurrentPage.setMinimumSize(QtCore.QSize(40, 23)) 270 | self.editCurrentPage.setMaximumSize(QtCore.QSize(40, 16777215)) 271 | self.editCurrentPage.setInputMask("") 272 | self.editCurrentPage.setAlignment(QtCore.Qt.AlignCenter) 273 | self.editCurrentPage.setObjectName("editCurrentPage") 274 | self.horizontalLayout_2.addWidget(self.editCurrentPage) 275 | self.label = QtWidgets.QLabel(self.frame_2) 276 | self.label.setObjectName("label") 277 | self.horizontalLayout_2.addWidget(self.label) 278 | self.editMaxPage = QtWidgets.QLineEdit(self.frame_2) 279 | self.editMaxPage.setEnabled(True) 280 | sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed) 281 | sizePolicy.setHorizontalStretch(0) 282 | sizePolicy.setVerticalStretch(0) 283 | sizePolicy.setHeightForWidth(self.editMaxPage.sizePolicy().hasHeightForWidth()) 284 | self.editMaxPage.setSizePolicy(sizePolicy) 285 | self.editMaxPage.setMinimumSize(QtCore.QSize(40, 23)) 286 | self.editMaxPage.setMaximumSize(QtCore.QSize(40, 16777215)) 287 | self.editMaxPage.setAutoFillBackground(False) 288 | self.editMaxPage.setInputMask("") 289 | self.editMaxPage.setFrame(True) 290 | self.editMaxPage.setAlignment(QtCore.Qt.AlignCenter) 291 | self.editMaxPage.setReadOnly(True) 292 | self.editMaxPage.setObjectName("editMaxPage") 293 | self.horizontalLayout_2.addWidget(self.editMaxPage) 294 | self.buttonNext = QtWidgets.QPushButton(self.frame_2) 295 | self.buttonNext.setMinimumSize(QtCore.QSize(24, 24)) 296 | self.buttonNext.setMaximumSize(QtCore.QSize(24, 24)) 297 | self.buttonNext.setFocusPolicy(QtCore.Qt.NoFocus) 298 | self.buttonNext.setText("") 299 | self.buttonNext.setFlat(True) 300 | self.buttonNext.setObjectName("buttonNext") 301 | self.horizontalLayout_2.addWidget(self.buttonNext) 302 | self.buttonLast = QtWidgets.QPushButton(self.frame_2) 303 | self.buttonLast.setMinimumSize(QtCore.QSize(24, 24)) 304 | self.buttonLast.setMaximumSize(QtCore.QSize(24, 24)) 305 | self.buttonLast.setFocusPolicy(QtCore.Qt.NoFocus) 306 | self.buttonLast.setText("") 307 | self.buttonLast.setFlat(True) 308 | self.buttonLast.setObjectName("buttonLast") 309 | self.horizontalLayout_2.addWidget(self.buttonLast) 310 | spacerItem4 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum) 311 | self.horizontalLayout_2.addItem(spacerItem4) 312 | self.verticalLayout_2.addWidget(self.frame_2) 313 | self.verticalLayout_7.addWidget(self.splitter) 314 | MainWindow.setCentralWidget(self.centralwidget) 315 | self.menubar = QtWidgets.QMenuBar(MainWindow) 316 | self.menubar.setGeometry(QtCore.QRect(0, 0, 949, 21)) 317 | self.menubar.setObjectName("menubar") 318 | MainWindow.setMenuBar(self.menubar) 319 | self.toolBar = QtWidgets.QToolBar(MainWindow) 320 | self.toolBar.setContextMenuPolicy(QtCore.Qt.ActionsContextMenu) 321 | self.toolBar.setMovable(True) 322 | self.toolBar.setToolButtonStyle(QtCore.Qt.ToolButtonFollowStyle) 323 | self.toolBar.setFloatable(False) 324 | self.toolBar.setObjectName("toolBar") 325 | MainWindow.addToolBar(QtCore.Qt.TopToolBarArea, self.toolBar) 326 | self.actionZoomIn = QtWidgets.QAction(MainWindow) 327 | self.actionZoomIn.setObjectName("actionZoomIn") 328 | self.actionZoomOut = QtWidgets.QAction(MainWindow) 329 | self.actionZoomOut.setObjectName("actionZoomOut") 330 | self.actionPreviousPage = QtWidgets.QAction(MainWindow) 331 | self.actionPreviousPage.setObjectName("actionPreviousPage") 332 | self.actionNextPage = QtWidgets.QAction(MainWindow) 333 | self.actionNextPage.setObjectName("actionNextPage") 334 | self.actionOpenFile = QtWidgets.QAction(MainWindow) 335 | self.actionOpenFile.setObjectName("actionOpenFile") 336 | self.actionFitInView = QtWidgets.QAction(MainWindow) 337 | self.actionFitInView.setCheckable(True) 338 | self.actionFitInView.setObjectName("actionFitInView") 339 | self.actionKrop = QtWidgets.QAction(MainWindow) 340 | self.actionKrop.setEnabled(False) 341 | self.actionKrop.setObjectName("actionKrop") 342 | self.actionDeleteSelection = QtWidgets.QAction(MainWindow) 343 | self.actionDeleteSelection.setObjectName("actionDeleteSelection") 344 | self.actionFirstPage = QtWidgets.QAction(MainWindow) 345 | self.actionFirstPage.setObjectName("actionFirstPage") 346 | self.actionLastPage = QtWidgets.QAction(MainWindow) 347 | self.actionLastPage.setObjectName("actionLastPage") 348 | self.actionTrimMargins = QtWidgets.QAction(MainWindow) 349 | self.actionTrimMargins.setObjectName("actionTrimMargins") 350 | self.actionSelectFile = QtWidgets.QAction(MainWindow) 351 | self.actionSelectFile.setObjectName("actionSelectFile") 352 | self.actionTrimMarginsAll = QtWidgets.QAction(MainWindow) 353 | self.actionTrimMarginsAll.setEnabled(False) 354 | self.actionTrimMarginsAll.setObjectName("actionTrimMarginsAll") 355 | self.actionNewSelection = QtWidgets.QAction(MainWindow) 356 | self.actionNewSelection.setObjectName("actionNewSelection") 357 | self.actionNewSelectionGrid = QtWidgets.QAction(MainWindow) 358 | self.actionNewSelectionGrid.setObjectName("actionNewSelectionGrid") 359 | self.toolBar.addAction(self.actionOpenFile) 360 | self.toolBar.addAction(self.actionKrop) 361 | self.toolBar.addAction(self.actionZoomIn) 362 | self.toolBar.addAction(self.actionZoomOut) 363 | self.toolBar.addAction(self.actionFitInView) 364 | self.toolBar.addAction(self.actionPreviousPage) 365 | self.toolBar.addAction(self.actionNextPage) 366 | self.toolBar.addAction(self.actionTrimMarginsAll) 367 | 368 | self.retranslateUi(MainWindow) 369 | self.tabWidget.setCurrentIndex(0) 370 | self.buttonPrevious.clicked.connect(self.actionPreviousPage.trigger) # type: ignore 371 | self.buttonNext.clicked.connect(self.actionNextPage.trigger) # type: ignore 372 | self.buttonFirst.clicked.connect(self.actionFirstPage.trigger) # type: ignore 373 | self.buttonLast.clicked.connect(self.actionLastPage.trigger) # type: ignore 374 | self.buttonFileSelect.clicked.connect(self.actionSelectFile.trigger) # type: ignore 375 | QtCore.QMetaObject.connectSlotsByName(MainWindow) 376 | 377 | def retranslateUi(self, MainWindow): 378 | _translate = QtCore.QCoreApplication.translate 379 | self.groupSaveTo.setTitle(_translate("MainWindow", "Save cropped PDF to")) 380 | self.editFile.setToolTip(_translate("MainWindow", "

This is where the cropped PDF will be saved after you choose Krop! in the menu.

")) 381 | self.buttonFileSelect.setToolTip(_translate("MainWindow", "

This is where the cropped PDF will be saved after you choose Krop! in the menu.

")) 382 | self.groupPDFOperations.setTitle(_translate("MainWindow", "Extra operations on the final PDF")) 383 | self.comboRotation.setItemText(0, _translate("MainWindow", "don\'t rotate")) 384 | self.comboRotation.setItemText(1, _translate("MainWindow", "rotate left (90° counterclockwise)")) 385 | self.comboRotation.setItemText(2, _translate("MainWindow", "rotate right (90° clockwise)")) 386 | self.comboRotation.setItemText(3, _translate("MainWindow", "upside down")) 387 | self.checkGhostscript.setToolTip(_translate("MainWindow", "

In order to use this option, Ghostscript must be installed and available as gs. Whether this option actually improves the file size depends on the PDF file.

")) 388 | self.checkGhostscript.setText(_translate("MainWindow", "Use Ghostscript to optimize")) 389 | self.groupWhichPages.setTitle(_translate("MainWindow", "Which pages to include")) 390 | self.editWhichPages.setToolTip(_translate("MainWindow", "

Which pages to include in the output file.

Eg: 1-5 for the first 5 pages\n" 391 | "
Eg: 2- for all but the first page\n" 392 | "
Eg: 1,4-5,7- to omit pages 2,3,6

")) 393 | self.checkIncludePagesWithoutSelections.setToolTip(_translate("MainWindow", "

If checked, pages without selections will be included in the output unchanged. Otherwise, such pages will be removed from the output.

")) 394 | self.checkIncludePagesWithoutSelections.setText(_translate("MainWindow", "Include pages without selections")) 395 | self.groupSelectionMode.setToolTip(_translate("MainWindow", "

Should all pages be cropped based on the same selections? Maybe you want to treat even and odd pages differently? For full control you can crop each page using individual selections.

")) 396 | self.groupSelectionMode.setTitle(_translate("MainWindow", "Selections apply to")) 397 | self.radioSelAll.setText(_translate("MainWindow", "all pages")) 398 | self.radioSelEvenOdd.setText(_translate("MainWindow", "even/odd pages")) 399 | self.radioSelIndividual.setText(_translate("MainWindow", "individual page")) 400 | self.labelSelExceptions.setToolTip(_translate("MainWindow", "

List pages which require individual selections.

")) 401 | self.labelSelExceptions.setText(_translate("MainWindow", "Exceptions:")) 402 | self.editSelExceptions.setToolTip(_translate("MainWindow", "

List pages which require individual selections.

")) 403 | self.tabWidget.setTabText(self.tabWidget.indexOf(self.tabBasic), _translate("MainWindow", "Basic")) 404 | self.groupCurrentSel.setToolTip(_translate("MainWindow", "

Click a selection to make it the current one. You can then set a fixed aspect ratio for this selection here.

")) 405 | self.groupCurrentSel.setTitle(_translate("MainWindow", "Current Selection")) 406 | self.comboSelAspectRatioType.setToolTip(_translate("MainWindow", "

If your favorite aspect ratio is missing here, you can add it by editing the config file.

")) 407 | self.labelSelAspectRatio.setText(_translate("MainWindow", "Aspect ratio:")) 408 | self.groupTrimMargins.setToolTip(_translate("MainWindow", "

Right-click a selection to automatically trim it.

")) 409 | self.groupTrimMargins.setTitle(_translate("MainWindow", "Settings for trimming margins")) 410 | self.checkTrimUseAllPages.setToolTip(_translate("MainWindow", "

If selected, all pages will be inspected (which can be very slow!) in order to determine the margins for auto trimming. Otherwise, only the current page is inspected.

")) 411 | self.checkTrimUseAllPages.setText(_translate("MainWindow", "Use all pages (slow!)")) 412 | self.labelPadding.setToolTip(_translate("MainWindow", "

How much padding to use when trimming.

Eg: 2 or 5,2 or 5,2,5,5 (interpreted as in CSS)

")) 413 | self.labelPadding.setText(_translate("MainWindow", "Padding:")) 414 | self.editPadding.setToolTip(_translate("MainWindow", "

How much padding to use when trimming.

Eg: 2 or 5,2 or 5,2,5,5 (interpreted as in CSS)

")) 415 | self.labelAllowedChanges.setText(_translate("MainWindow", "Allowed changes:")) 416 | self.labelSensitivity.setText(_translate("MainWindow", "Color sensitivity:")) 417 | self.groupDistribute.setToolTip(_translate("MainWindow", "

Use this option if you want to break up each selection into pieces that exactly fit a certain aspect ratio. This is useful for displaying files on devices that don\'t support scrolling well.

")) 418 | self.groupDistribute.setTitle(_translate("MainWindow", "Fit screen of device")) 419 | self.labelDistributeAspectRatio.setText(_translate("MainWindow", "Aspect ratio:")) 420 | self.labelDistributeHelp.setText(_translate("MainWindow", "

Eg: 600:730 (ratio of width to height)

")) 421 | self.tabWidget.setTabText(self.tabWidget.indexOf(self.tabAdvanced), _translate("MainWindow", "Advanced")) 422 | self.labelHelp.setText(_translate("MainWindow", "

Getting started

\n" 423 | "

Using your mouse, create one or more selections on the pdf document. These are the regions that will be included into the cropped file.

\n" 424 | "

When you are done, click Krop! in the menu to create a cropped version of your document.

\n" 425 | "

Hints

\n" 426 | "

Right-click the page to create a selection for the full page (or a grid of selections).

\n" 427 | "

Right-click a selection to delete it. Or simply press the Delete key.

\n" 428 | "

You can choose to create individual selections for each page.

\n" 429 | "

You can automatically trim the margins of your selections.

\n" 430 | "

Examples and more information can be found at: arminstraub.com

\n" 431 | "")) 432 | self.labelHelpCopyright.setToolTip(_translate("MainWindow", "

This program is free software and available to you in the hope that it will be useful; but without any warranty. It is distributed under the terms of the GNU General Public License (GPLv3+). See the accompanying files for more information.

")) 433 | self.labelHelpCopyright.setText(_translate("MainWindow", "

Copyright (C) 2010-2025 Armin Straub\n" 434 | "
https://arminstraub.com

")) 435 | self.tabWidget.setTabText(self.tabWidget.indexOf(self.tabHelp), _translate("MainWindow", "Help")) 436 | self.label.setText(_translate("MainWindow", "of")) 437 | self.toolBar.setWindowTitle(_translate("MainWindow", "toolBar")) 438 | self.actionZoomIn.setText(_translate("MainWindow", "Zoom In")) 439 | self.actionZoomIn.setShortcut(_translate("MainWindow", "Ctrl+=")) 440 | self.actionZoomOut.setText(_translate("MainWindow", "Zoom Out")) 441 | self.actionZoomOut.setShortcut(_translate("MainWindow", "Ctrl+-")) 442 | self.actionPreviousPage.setText(_translate("MainWindow", "Previous Page")) 443 | self.actionPreviousPage.setShortcut(_translate("MainWindow", "PgUp")) 444 | self.actionNextPage.setText(_translate("MainWindow", "Next Page")) 445 | self.actionNextPage.setShortcut(_translate("MainWindow", "PgDown")) 446 | self.actionOpenFile.setText(_translate("MainWindow", "Open")) 447 | self.actionOpenFile.setShortcut(_translate("MainWindow", "Ctrl+O")) 448 | self.actionFitInView.setText(_translate("MainWindow", "Fit In View")) 449 | self.actionKrop.setText(_translate("MainWindow", "Krop!")) 450 | self.actionDeleteSelection.setText(_translate("MainWindow", "Delete Selection")) 451 | self.actionDeleteSelection.setShortcut(_translate("MainWindow", "Del")) 452 | self.actionFirstPage.setText(_translate("MainWindow", "First Page")) 453 | self.actionFirstPage.setShortcut(_translate("MainWindow", "Home")) 454 | self.actionLastPage.setText(_translate("MainWindow", "Last Page")) 455 | self.actionLastPage.setShortcut(_translate("MainWindow", "End")) 456 | self.actionTrimMargins.setText(_translate("MainWindow", "Trim Margins")) 457 | self.actionSelectFile.setText(_translate("MainWindow", "Select File")) 458 | self.actionTrimMarginsAll.setText(_translate("MainWindow", "Trim Margins")) 459 | self.actionTrimMarginsAll.setToolTip(_translate("MainWindow", "Trim Margins")) 460 | self.actionTrimMarginsAll.setShortcut(_translate("MainWindow", "Ctrl+T")) 461 | self.actionNewSelection.setText(_translate("MainWindow", "New Selection")) 462 | self.actionNewSelection.setToolTip(_translate("MainWindow", "New Selection")) 463 | self.actionNewSelection.setShortcut(_translate("MainWindow", "Ins")) 464 | self.actionNewSelectionGrid.setText(_translate("MainWindow", "New Selection Grid...")) 465 | self.actionNewSelectionGrid.setToolTip(_translate("MainWindow", "New Selection Grid...")) 466 | self.actionNewSelectionGrid.setShortcut(_translate("MainWindow", "Shift+Ins")) 467 | -------------------------------------------------------------------------------- /krop/mainwindowui_qt6.py: -------------------------------------------------------------------------------- 1 | # Form implementation generated from reading ui file 'mainwindow.ui' 2 | # 3 | # Created by: PyQt6 UI code generator 6.6.0 4 | # 5 | # WARNING: Any manual changes made to this file will be lost when pyuic6 is 6 | # run again. Do not edit this file unless you know what you are doing. 7 | 8 | 9 | from PyQt6 import QtCore, QtGui, QtWidgets 10 | 11 | 12 | class Ui_MainWindow(object): 13 | def setupUi(self, MainWindow): 14 | MainWindow.setObjectName("MainWindow") 15 | MainWindow.resize(949, 736) 16 | self.centralwidget = QtWidgets.QWidget(parent=MainWindow) 17 | self.centralwidget.setObjectName("centralwidget") 18 | self.verticalLayout_7 = QtWidgets.QVBoxLayout(self.centralwidget) 19 | self.verticalLayout_7.setObjectName("verticalLayout_7") 20 | self.splitter = QtWidgets.QSplitter(parent=self.centralwidget) 21 | self.splitter.setOrientation(QtCore.Qt.Orientation.Horizontal) 22 | self.splitter.setChildrenCollapsible(False) 23 | self.splitter.setObjectName("splitter") 24 | self.tabWidget = QtWidgets.QTabWidget(parent=self.splitter) 25 | sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Policy.Preferred, QtWidgets.QSizePolicy.Policy.Expanding) 26 | sizePolicy.setHorizontalStretch(0) 27 | sizePolicy.setVerticalStretch(0) 28 | sizePolicy.setHeightForWidth(self.tabWidget.sizePolicy().hasHeightForWidth()) 29 | self.tabWidget.setSizePolicy(sizePolicy) 30 | self.tabWidget.setObjectName("tabWidget") 31 | self.tabBasic = QtWidgets.QWidget() 32 | self.tabBasic.setObjectName("tabBasic") 33 | self.verticalLayout_4 = QtWidgets.QVBoxLayout(self.tabBasic) 34 | self.verticalLayout_4.setObjectName("verticalLayout_4") 35 | self.groupSaveTo = QtWidgets.QGroupBox(parent=self.tabBasic) 36 | self.groupSaveTo.setObjectName("groupSaveTo") 37 | self.gridLayout = QtWidgets.QGridLayout(self.groupSaveTo) 38 | self.gridLayout.setObjectName("gridLayout") 39 | self.editFile = QtWidgets.QLineEdit(parent=self.groupSaveTo) 40 | self.editFile.setObjectName("editFile") 41 | self.gridLayout.addWidget(self.editFile, 0, 0, 1, 1) 42 | self.buttonFileSelect = QtWidgets.QToolButton(parent=self.groupSaveTo) 43 | self.buttonFileSelect.setText("") 44 | self.buttonFileSelect.setAutoRaise(True) 45 | self.buttonFileSelect.setObjectName("buttonFileSelect") 46 | self.gridLayout.addWidget(self.buttonFileSelect, 0, 1, 1, 1) 47 | self.verticalLayout_4.addWidget(self.groupSaveTo) 48 | self.groupPDFOperations = QtWidgets.QGroupBox(parent=self.tabBasic) 49 | self.groupPDFOperations.setFlat(False) 50 | self.groupPDFOperations.setObjectName("groupPDFOperations") 51 | self.verticalLayout_8 = QtWidgets.QVBoxLayout(self.groupPDFOperations) 52 | self.verticalLayout_8.setObjectName("verticalLayout_8") 53 | self.comboRotation = QtWidgets.QComboBox(parent=self.groupPDFOperations) 54 | self.comboRotation.setObjectName("comboRotation") 55 | self.comboRotation.addItem("") 56 | self.comboRotation.addItem("") 57 | self.comboRotation.addItem("") 58 | self.comboRotation.addItem("") 59 | self.verticalLayout_8.addWidget(self.comboRotation) 60 | self.checkGhostscript = QtWidgets.QCheckBox(parent=self.groupPDFOperations) 61 | sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Policy.Minimum, QtWidgets.QSizePolicy.Policy.Fixed) 62 | sizePolicy.setHorizontalStretch(0) 63 | sizePolicy.setVerticalStretch(0) 64 | sizePolicy.setHeightForWidth(self.checkGhostscript.sizePolicy().hasHeightForWidth()) 65 | self.checkGhostscript.setSizePolicy(sizePolicy) 66 | self.checkGhostscript.setChecked(True) 67 | self.checkGhostscript.setObjectName("checkGhostscript") 68 | self.verticalLayout_8.addWidget(self.checkGhostscript) 69 | self.verticalLayout_4.addWidget(self.groupPDFOperations) 70 | self.groupWhichPages = QtWidgets.QGroupBox(parent=self.tabBasic) 71 | self.groupWhichPages.setObjectName("groupWhichPages") 72 | self.verticalLayout = QtWidgets.QVBoxLayout(self.groupWhichPages) 73 | self.verticalLayout.setObjectName("verticalLayout") 74 | self.editWhichPages = QtWidgets.QLineEdit(parent=self.groupWhichPages) 75 | self.editWhichPages.setObjectName("editWhichPages") 76 | self.verticalLayout.addWidget(self.editWhichPages) 77 | self.checkIncludePagesWithoutSelections = QtWidgets.QCheckBox(parent=self.groupWhichPages) 78 | self.checkIncludePagesWithoutSelections.setChecked(True) 79 | self.checkIncludePagesWithoutSelections.setObjectName("checkIncludePagesWithoutSelections") 80 | self.verticalLayout.addWidget(self.checkIncludePagesWithoutSelections) 81 | self.verticalLayout_4.addWidget(self.groupWhichPages) 82 | self.groupSelectionMode = QtWidgets.QGroupBox(parent=self.tabBasic) 83 | self.groupSelectionMode.setFlat(False) 84 | self.groupSelectionMode.setObjectName("groupSelectionMode") 85 | self.gridLayout_2 = QtWidgets.QGridLayout(self.groupSelectionMode) 86 | self.gridLayout_2.setObjectName("gridLayout_2") 87 | self.radioSelAll = QtWidgets.QRadioButton(parent=self.groupSelectionMode) 88 | self.radioSelAll.setChecked(True) 89 | self.radioSelAll.setObjectName("radioSelAll") 90 | self.gridLayout_2.addWidget(self.radioSelAll, 0, 0, 1, 2) 91 | self.radioSelEvenOdd = QtWidgets.QRadioButton(parent=self.groupSelectionMode) 92 | self.radioSelEvenOdd.setObjectName("radioSelEvenOdd") 93 | self.gridLayout_2.addWidget(self.radioSelEvenOdd, 1, 0, 1, 2) 94 | self.radioSelIndividual = QtWidgets.QRadioButton(parent=self.groupSelectionMode) 95 | self.radioSelIndividual.setObjectName("radioSelIndividual") 96 | self.gridLayout_2.addWidget(self.radioSelIndividual, 2, 0, 1, 2) 97 | self.labelSelExceptions = QtWidgets.QLabel(parent=self.groupSelectionMode) 98 | self.labelSelExceptions.setObjectName("labelSelExceptions") 99 | self.gridLayout_2.addWidget(self.labelSelExceptions, 3, 0, 1, 1) 100 | self.editSelExceptions = QtWidgets.QLineEdit(parent=self.groupSelectionMode) 101 | self.editSelExceptions.setObjectName("editSelExceptions") 102 | self.gridLayout_2.addWidget(self.editSelExceptions, 3, 1, 1, 1) 103 | self.verticalLayout_4.addWidget(self.groupSelectionMode) 104 | spacerItem = QtWidgets.QSpacerItem(20, 484, QtWidgets.QSizePolicy.Policy.Minimum, QtWidgets.QSizePolicy.Policy.Expanding) 105 | self.verticalLayout_4.addItem(spacerItem) 106 | self.tabWidget.addTab(self.tabBasic, "") 107 | self.tabAdvanced = QtWidgets.QWidget() 108 | self.tabAdvanced.setObjectName("tabAdvanced") 109 | self.verticalLayout_5 = QtWidgets.QVBoxLayout(self.tabAdvanced) 110 | self.verticalLayout_5.setObjectName("verticalLayout_5") 111 | self.groupCurrentSel = QtWidgets.QGroupBox(parent=self.tabAdvanced) 112 | self.groupCurrentSel.setEnabled(False) 113 | self.groupCurrentSel.setObjectName("groupCurrentSel") 114 | self.gridLayout_4 = QtWidgets.QGridLayout(self.groupCurrentSel) 115 | self.gridLayout_4.setObjectName("gridLayout_4") 116 | self.comboSelAspectRatioType = QtWidgets.QComboBox(parent=self.groupCurrentSel) 117 | self.comboSelAspectRatioType.setEditable(False) 118 | self.comboSelAspectRatioType.setSizeAdjustPolicy(QtWidgets.QComboBox.SizeAdjustPolicy.AdjustToContentsOnFirstShow) 119 | self.comboSelAspectRatioType.setObjectName("comboSelAspectRatioType") 120 | self.gridLayout_4.addWidget(self.comboSelAspectRatioType, 0, 0, 1, 2) 121 | self.editSelAspectRatio = QtWidgets.QLineEdit(parent=self.groupCurrentSel) 122 | self.editSelAspectRatio.setObjectName("editSelAspectRatio") 123 | self.gridLayout_4.addWidget(self.editSelAspectRatio, 1, 1, 1, 1) 124 | self.labelSelAspectRatio = QtWidgets.QLabel(parent=self.groupCurrentSel) 125 | self.labelSelAspectRatio.setObjectName("labelSelAspectRatio") 126 | self.gridLayout_4.addWidget(self.labelSelAspectRatio, 1, 0, 1, 1) 127 | self.verticalLayout_5.addWidget(self.groupCurrentSel) 128 | self.groupTrimMargins = QtWidgets.QGroupBox(parent=self.tabAdvanced) 129 | self.groupTrimMargins.setObjectName("groupTrimMargins") 130 | self.gridLayout_3 = QtWidgets.QGridLayout(self.groupTrimMargins) 131 | self.gridLayout_3.setObjectName("gridLayout_3") 132 | self.checkTrimUseAllPages = QtWidgets.QCheckBox(parent=self.groupTrimMargins) 133 | self.checkTrimUseAllPages.setChecked(True) 134 | self.checkTrimUseAllPages.setObjectName("checkTrimUseAllPages") 135 | self.gridLayout_3.addWidget(self.checkTrimUseAllPages, 0, 0, 1, 2) 136 | self.labelPadding = QtWidgets.QLabel(parent=self.groupTrimMargins) 137 | self.labelPadding.setObjectName("labelPadding") 138 | self.gridLayout_3.addWidget(self.labelPadding, 1, 0, 1, 1) 139 | self.editPadding = QtWidgets.QLineEdit(parent=self.groupTrimMargins) 140 | self.editPadding.setText("") 141 | self.editPadding.setObjectName("editPadding") 142 | self.gridLayout_3.addWidget(self.editPadding, 1, 1, 1, 1) 143 | self.labelAllowedChanges = QtWidgets.QLabel(parent=self.groupTrimMargins) 144 | self.labelAllowedChanges.setEnabled(True) 145 | self.labelAllowedChanges.setObjectName("labelAllowedChanges") 146 | self.gridLayout_3.addWidget(self.labelAllowedChanges, 2, 0, 1, 1) 147 | self.editAllowedChanges = QtWidgets.QLineEdit(parent=self.groupTrimMargins) 148 | self.editAllowedChanges.setEnabled(True) 149 | self.editAllowedChanges.setObjectName("editAllowedChanges") 150 | self.gridLayout_3.addWidget(self.editAllowedChanges, 2, 1, 1, 1) 151 | self.labelSensitivity = QtWidgets.QLabel(parent=self.groupTrimMargins) 152 | self.labelSensitivity.setEnabled(True) 153 | self.labelSensitivity.setObjectName("labelSensitivity") 154 | self.gridLayout_3.addWidget(self.labelSensitivity, 3, 0, 1, 1) 155 | self.editSensitivity = QtWidgets.QLineEdit(parent=self.groupTrimMargins) 156 | self.editSensitivity.setEnabled(True) 157 | self.editSensitivity.setObjectName("editSensitivity") 158 | self.gridLayout_3.addWidget(self.editSensitivity, 3, 1, 1, 1) 159 | self.verticalLayout_5.addWidget(self.groupTrimMargins) 160 | self.groupDistribute = QtWidgets.QGroupBox(parent=self.tabAdvanced) 161 | self.groupDistribute.setObjectName("groupDistribute") 162 | self.formLayout = QtWidgets.QFormLayout(self.groupDistribute) 163 | self.formLayout.setFieldGrowthPolicy(QtWidgets.QFormLayout.FieldGrowthPolicy.ExpandingFieldsGrow) 164 | self.formLayout.setObjectName("formLayout") 165 | self.comboDistributeDevice = QtWidgets.QComboBox(parent=self.groupDistribute) 166 | self.comboDistributeDevice.setEditable(False) 167 | self.comboDistributeDevice.setSizeAdjustPolicy(QtWidgets.QComboBox.SizeAdjustPolicy.AdjustToContentsOnFirstShow) 168 | self.comboDistributeDevice.setObjectName("comboDistributeDevice") 169 | self.formLayout.setWidget(0, QtWidgets.QFormLayout.ItemRole.SpanningRole, self.comboDistributeDevice) 170 | self.labelDistributeAspectRatio = QtWidgets.QLabel(parent=self.groupDistribute) 171 | self.labelDistributeAspectRatio.setObjectName("labelDistributeAspectRatio") 172 | self.formLayout.setWidget(1, QtWidgets.QFormLayout.ItemRole.LabelRole, self.labelDistributeAspectRatio) 173 | self.editDistributeAspectRatio = QtWidgets.QLineEdit(parent=self.groupDistribute) 174 | self.editDistributeAspectRatio.setObjectName("editDistributeAspectRatio") 175 | self.formLayout.setWidget(1, QtWidgets.QFormLayout.ItemRole.FieldRole, self.editDistributeAspectRatio) 176 | self.labelDistributeHelp = QtWidgets.QLabel(parent=self.groupDistribute) 177 | self.labelDistributeHelp.setWordWrap(True) 178 | self.labelDistributeHelp.setObjectName("labelDistributeHelp") 179 | self.formLayout.setWidget(2, QtWidgets.QFormLayout.ItemRole.SpanningRole, self.labelDistributeHelp) 180 | self.verticalLayout_5.addWidget(self.groupDistribute) 181 | spacerItem1 = QtWidgets.QSpacerItem(20, 339, QtWidgets.QSizePolicy.Policy.Minimum, QtWidgets.QSizePolicy.Policy.Expanding) 182 | self.verticalLayout_5.addItem(spacerItem1) 183 | self.tabWidget.addTab(self.tabAdvanced, "") 184 | self.tabHelp = QtWidgets.QWidget() 185 | self.tabHelp.setObjectName("tabHelp") 186 | self.verticalLayout_3 = QtWidgets.QVBoxLayout(self.tabHelp) 187 | self.verticalLayout_3.setObjectName("verticalLayout_3") 188 | self.labelHelp = QtWidgets.QLabel(parent=self.tabHelp) 189 | sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Policy.Ignored, QtWidgets.QSizePolicy.Policy.Preferred) 190 | sizePolicy.setHorizontalStretch(0) 191 | sizePolicy.setVerticalStretch(0) 192 | sizePolicy.setHeightForWidth(self.labelHelp.sizePolicy().hasHeightForWidth()) 193 | self.labelHelp.setSizePolicy(sizePolicy) 194 | self.labelHelp.setMaximumSize(QtCore.QSize(16777215, 16777215)) 195 | self.labelHelp.setBaseSize(QtCore.QSize(0, 0)) 196 | self.labelHelp.setTextFormat(QtCore.Qt.TextFormat.AutoText) 197 | self.labelHelp.setWordWrap(True) 198 | self.labelHelp.setOpenExternalLinks(True) 199 | self.labelHelp.setObjectName("labelHelp") 200 | self.verticalLayout_3.addWidget(self.labelHelp) 201 | spacerItem2 = QtWidgets.QSpacerItem(20, 524, QtWidgets.QSizePolicy.Policy.Minimum, QtWidgets.QSizePolicy.Policy.Expanding) 202 | self.verticalLayout_3.addItem(spacerItem2) 203 | self.frameHelpCopyright = QtWidgets.QFrame(parent=self.tabHelp) 204 | self.frameHelpCopyright.setFrameShape(QtWidgets.QFrame.Shape.HLine) 205 | self.frameHelpCopyright.setObjectName("frameHelpCopyright") 206 | self.verticalLayout_3.addWidget(self.frameHelpCopyright) 207 | self.labelHelpCopyright = QtWidgets.QLabel(parent=self.tabHelp) 208 | sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Policy.Ignored, QtWidgets.QSizePolicy.Policy.Preferred) 209 | sizePolicy.setHorizontalStretch(0) 210 | sizePolicy.setVerticalStretch(0) 211 | sizePolicy.setHeightForWidth(self.labelHelpCopyright.sizePolicy().hasHeightForWidth()) 212 | self.labelHelpCopyright.setSizePolicy(sizePolicy) 213 | self.labelHelpCopyright.setTextFormat(QtCore.Qt.TextFormat.AutoText) 214 | self.labelHelpCopyright.setWordWrap(True) 215 | self.labelHelpCopyright.setOpenExternalLinks(True) 216 | self.labelHelpCopyright.setObjectName("labelHelpCopyright") 217 | self.verticalLayout_3.addWidget(self.labelHelpCopyright) 218 | self.tabWidget.addTab(self.tabHelp, "") 219 | self.frame = QtWidgets.QFrame(parent=self.splitter) 220 | sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Policy.Expanding, QtWidgets.QSizePolicy.Policy.Preferred) 221 | sizePolicy.setHorizontalStretch(1) 222 | sizePolicy.setVerticalStretch(0) 223 | sizePolicy.setHeightForWidth(self.frame.sizePolicy().hasHeightForWidth()) 224 | self.frame.setSizePolicy(sizePolicy) 225 | self.frame.setFrameShape(QtWidgets.QFrame.Shape.NoFrame) 226 | self.frame.setFrameShadow(QtWidgets.QFrame.Shadow.Raised) 227 | self.frame.setObjectName("frame") 228 | self.verticalLayout_2 = QtWidgets.QVBoxLayout(self.frame) 229 | self.verticalLayout_2.setContentsMargins(1, 1, 1, 1) 230 | self.verticalLayout_2.setObjectName("verticalLayout_2") 231 | self.documentView = QtWidgets.QGraphicsView(parent=self.frame) 232 | self.documentView.setContextMenuPolicy(QtCore.Qt.ContextMenuPolicy.CustomContextMenu) 233 | self.documentView.setFrameShadow(QtWidgets.QFrame.Shadow.Sunken) 234 | self.documentView.setObjectName("documentView") 235 | self.verticalLayout_2.addWidget(self.documentView) 236 | self.frame_2 = QtWidgets.QFrame(parent=self.frame) 237 | self.frame_2.setFrameShape(QtWidgets.QFrame.Shape.NoFrame) 238 | self.frame_2.setFrameShadow(QtWidgets.QFrame.Shadow.Raised) 239 | self.frame_2.setObjectName("frame_2") 240 | self.horizontalLayout_2 = QtWidgets.QHBoxLayout(self.frame_2) 241 | self.horizontalLayout_2.setContentsMargins(0, 0, 0, 0) 242 | self.horizontalLayout_2.setObjectName("horizontalLayout_2") 243 | spacerItem3 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Policy.Expanding, QtWidgets.QSizePolicy.Policy.Minimum) 244 | self.horizontalLayout_2.addItem(spacerItem3) 245 | self.buttonFirst = QtWidgets.QPushButton(parent=self.frame_2) 246 | self.buttonFirst.setMinimumSize(QtCore.QSize(24, 24)) 247 | self.buttonFirst.setMaximumSize(QtCore.QSize(24, 24)) 248 | self.buttonFirst.setFocusPolicy(QtCore.Qt.FocusPolicy.NoFocus) 249 | self.buttonFirst.setText("") 250 | self.buttonFirst.setFlat(True) 251 | self.buttonFirst.setObjectName("buttonFirst") 252 | self.horizontalLayout_2.addWidget(self.buttonFirst) 253 | self.buttonPrevious = QtWidgets.QPushButton(parent=self.frame_2) 254 | self.buttonPrevious.setMinimumSize(QtCore.QSize(24, 24)) 255 | self.buttonPrevious.setMaximumSize(QtCore.QSize(24, 24)) 256 | self.buttonPrevious.setFocusPolicy(QtCore.Qt.FocusPolicy.NoFocus) 257 | self.buttonPrevious.setText("") 258 | self.buttonPrevious.setFlat(True) 259 | self.buttonPrevious.setObjectName("buttonPrevious") 260 | self.horizontalLayout_2.addWidget(self.buttonPrevious) 261 | self.editCurrentPage = QtWidgets.QLineEdit(parent=self.frame_2) 262 | sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Policy.Fixed, QtWidgets.QSizePolicy.Policy.Fixed) 263 | sizePolicy.setHorizontalStretch(0) 264 | sizePolicy.setVerticalStretch(0) 265 | sizePolicy.setHeightForWidth(self.editCurrentPage.sizePolicy().hasHeightForWidth()) 266 | self.editCurrentPage.setSizePolicy(sizePolicy) 267 | self.editCurrentPage.setMinimumSize(QtCore.QSize(40, 23)) 268 | self.editCurrentPage.setMaximumSize(QtCore.QSize(40, 16777215)) 269 | self.editCurrentPage.setInputMask("") 270 | self.editCurrentPage.setAlignment(QtCore.Qt.AlignmentFlag.AlignCenter) 271 | self.editCurrentPage.setObjectName("editCurrentPage") 272 | self.horizontalLayout_2.addWidget(self.editCurrentPage) 273 | self.label = QtWidgets.QLabel(parent=self.frame_2) 274 | self.label.setObjectName("label") 275 | self.horizontalLayout_2.addWidget(self.label) 276 | self.editMaxPage = QtWidgets.QLineEdit(parent=self.frame_2) 277 | self.editMaxPage.setEnabled(True) 278 | sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Policy.Fixed, QtWidgets.QSizePolicy.Policy.Fixed) 279 | sizePolicy.setHorizontalStretch(0) 280 | sizePolicy.setVerticalStretch(0) 281 | sizePolicy.setHeightForWidth(self.editMaxPage.sizePolicy().hasHeightForWidth()) 282 | self.editMaxPage.setSizePolicy(sizePolicy) 283 | self.editMaxPage.setMinimumSize(QtCore.QSize(40, 23)) 284 | self.editMaxPage.setMaximumSize(QtCore.QSize(40, 16777215)) 285 | self.editMaxPage.setAutoFillBackground(False) 286 | self.editMaxPage.setInputMask("") 287 | self.editMaxPage.setFrame(True) 288 | self.editMaxPage.setAlignment(QtCore.Qt.AlignmentFlag.AlignCenter) 289 | self.editMaxPage.setReadOnly(True) 290 | self.editMaxPage.setObjectName("editMaxPage") 291 | self.horizontalLayout_2.addWidget(self.editMaxPage) 292 | self.buttonNext = QtWidgets.QPushButton(parent=self.frame_2) 293 | self.buttonNext.setMinimumSize(QtCore.QSize(24, 24)) 294 | self.buttonNext.setMaximumSize(QtCore.QSize(24, 24)) 295 | self.buttonNext.setFocusPolicy(QtCore.Qt.FocusPolicy.NoFocus) 296 | self.buttonNext.setText("") 297 | self.buttonNext.setFlat(True) 298 | self.buttonNext.setObjectName("buttonNext") 299 | self.horizontalLayout_2.addWidget(self.buttonNext) 300 | self.buttonLast = QtWidgets.QPushButton(parent=self.frame_2) 301 | self.buttonLast.setMinimumSize(QtCore.QSize(24, 24)) 302 | self.buttonLast.setMaximumSize(QtCore.QSize(24, 24)) 303 | self.buttonLast.setFocusPolicy(QtCore.Qt.FocusPolicy.NoFocus) 304 | self.buttonLast.setText("") 305 | self.buttonLast.setFlat(True) 306 | self.buttonLast.setObjectName("buttonLast") 307 | self.horizontalLayout_2.addWidget(self.buttonLast) 308 | spacerItem4 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Policy.Expanding, QtWidgets.QSizePolicy.Policy.Minimum) 309 | self.horizontalLayout_2.addItem(spacerItem4) 310 | self.verticalLayout_2.addWidget(self.frame_2) 311 | self.verticalLayout_7.addWidget(self.splitter) 312 | MainWindow.setCentralWidget(self.centralwidget) 313 | self.menubar = QtWidgets.QMenuBar(parent=MainWindow) 314 | self.menubar.setGeometry(QtCore.QRect(0, 0, 949, 21)) 315 | self.menubar.setObjectName("menubar") 316 | MainWindow.setMenuBar(self.menubar) 317 | self.toolBar = QtWidgets.QToolBar(parent=MainWindow) 318 | self.toolBar.setContextMenuPolicy(QtCore.Qt.ContextMenuPolicy.ActionsContextMenu) 319 | self.toolBar.setMovable(True) 320 | self.toolBar.setToolButtonStyle(QtCore.Qt.ToolButtonStyle.ToolButtonFollowStyle) 321 | self.toolBar.setFloatable(False) 322 | self.toolBar.setObjectName("toolBar") 323 | MainWindow.addToolBar(QtCore.Qt.ToolBarArea.TopToolBarArea, self.toolBar) 324 | self.actionZoomIn = QtGui.QAction(parent=MainWindow) 325 | self.actionZoomIn.setObjectName("actionZoomIn") 326 | self.actionZoomOut = QtGui.QAction(parent=MainWindow) 327 | self.actionZoomOut.setObjectName("actionZoomOut") 328 | self.actionPreviousPage = QtGui.QAction(parent=MainWindow) 329 | self.actionPreviousPage.setObjectName("actionPreviousPage") 330 | self.actionNextPage = QtGui.QAction(parent=MainWindow) 331 | self.actionNextPage.setObjectName("actionNextPage") 332 | self.actionOpenFile = QtGui.QAction(parent=MainWindow) 333 | self.actionOpenFile.setObjectName("actionOpenFile") 334 | self.actionFitInView = QtGui.QAction(parent=MainWindow) 335 | self.actionFitInView.setCheckable(True) 336 | self.actionFitInView.setObjectName("actionFitInView") 337 | self.actionKrop = QtGui.QAction(parent=MainWindow) 338 | self.actionKrop.setEnabled(False) 339 | self.actionKrop.setObjectName("actionKrop") 340 | self.actionDeleteSelection = QtGui.QAction(parent=MainWindow) 341 | self.actionDeleteSelection.setObjectName("actionDeleteSelection") 342 | self.actionFirstPage = QtGui.QAction(parent=MainWindow) 343 | self.actionFirstPage.setObjectName("actionFirstPage") 344 | self.actionLastPage = QtGui.QAction(parent=MainWindow) 345 | self.actionLastPage.setObjectName("actionLastPage") 346 | self.actionTrimMargins = QtGui.QAction(parent=MainWindow) 347 | self.actionTrimMargins.setObjectName("actionTrimMargins") 348 | self.actionSelectFile = QtGui.QAction(parent=MainWindow) 349 | self.actionSelectFile.setObjectName("actionSelectFile") 350 | self.actionTrimMarginsAll = QtGui.QAction(parent=MainWindow) 351 | self.actionTrimMarginsAll.setEnabled(False) 352 | self.actionTrimMarginsAll.setObjectName("actionTrimMarginsAll") 353 | self.actionNewSelection = QtGui.QAction(parent=MainWindow) 354 | self.actionNewSelection.setObjectName("actionNewSelection") 355 | self.actionNewSelectionGrid = QtGui.QAction(parent=MainWindow) 356 | self.actionNewSelectionGrid.setObjectName("actionNewSelectionGrid") 357 | self.toolBar.addAction(self.actionOpenFile) 358 | self.toolBar.addAction(self.actionKrop) 359 | self.toolBar.addAction(self.actionZoomIn) 360 | self.toolBar.addAction(self.actionZoomOut) 361 | self.toolBar.addAction(self.actionFitInView) 362 | self.toolBar.addAction(self.actionPreviousPage) 363 | self.toolBar.addAction(self.actionNextPage) 364 | self.toolBar.addAction(self.actionTrimMarginsAll) 365 | 366 | self.retranslateUi(MainWindow) 367 | self.tabWidget.setCurrentIndex(0) 368 | self.buttonPrevious.clicked.connect(self.actionPreviousPage.trigger) # type: ignore 369 | self.buttonNext.clicked.connect(self.actionNextPage.trigger) # type: ignore 370 | self.buttonFirst.clicked.connect(self.actionFirstPage.trigger) # type: ignore 371 | self.buttonLast.clicked.connect(self.actionLastPage.trigger) # type: ignore 372 | self.buttonFileSelect.clicked.connect(self.actionSelectFile.trigger) # type: ignore 373 | QtCore.QMetaObject.connectSlotsByName(MainWindow) 374 | 375 | def retranslateUi(self, MainWindow): 376 | _translate = QtCore.QCoreApplication.translate 377 | self.groupSaveTo.setTitle(_translate("MainWindow", "Save cropped PDF to")) 378 | self.editFile.setToolTip(_translate("MainWindow", "

This is where the cropped PDF will be saved after you choose Krop! in the menu.

")) 379 | self.buttonFileSelect.setToolTip(_translate("MainWindow", "

This is where the cropped PDF will be saved after you choose Krop! in the menu.

")) 380 | self.groupPDFOperations.setTitle(_translate("MainWindow", "Extra operations on the final PDF")) 381 | self.comboRotation.setItemText(0, _translate("MainWindow", "don\'t rotate")) 382 | self.comboRotation.setItemText(1, _translate("MainWindow", "rotate left (90° counterclockwise)")) 383 | self.comboRotation.setItemText(2, _translate("MainWindow", "rotate right (90° clockwise)")) 384 | self.comboRotation.setItemText(3, _translate("MainWindow", "upside down")) 385 | self.checkGhostscript.setToolTip(_translate("MainWindow", "

In order to use this option, Ghostscript must be installed and available as gs. Whether this option actually improves the file size depends on the PDF file.

")) 386 | self.checkGhostscript.setText(_translate("MainWindow", "Use Ghostscript to optimize")) 387 | self.groupWhichPages.setTitle(_translate("MainWindow", "Which pages to include")) 388 | self.editWhichPages.setToolTip(_translate("MainWindow", "

Which pages to include in the output file.

Eg: 1-5 for the first 5 pages\n" 389 | "
Eg: 2- for all but the first page\n" 390 | "
Eg: 1,4-5,7- to omit pages 2,3,6

")) 391 | self.checkIncludePagesWithoutSelections.setToolTip(_translate("MainWindow", "

If checked, pages without selections will be included in the output unchanged. Otherwise, such pages will be removed from the output.

")) 392 | self.checkIncludePagesWithoutSelections.setText(_translate("MainWindow", "Include pages without selections")) 393 | self.groupSelectionMode.setToolTip(_translate("MainWindow", "

Should all pages be cropped based on the same selections? Maybe you want to treat even and odd pages differently? For full control you can crop each page using individual selections.

")) 394 | self.groupSelectionMode.setTitle(_translate("MainWindow", "Selections apply to")) 395 | self.radioSelAll.setText(_translate("MainWindow", "all pages")) 396 | self.radioSelEvenOdd.setText(_translate("MainWindow", "even/odd pages")) 397 | self.radioSelIndividual.setText(_translate("MainWindow", "individual page")) 398 | self.labelSelExceptions.setToolTip(_translate("MainWindow", "

List pages which require individual selections.

")) 399 | self.labelSelExceptions.setText(_translate("MainWindow", "Exceptions:")) 400 | self.editSelExceptions.setToolTip(_translate("MainWindow", "

List pages which require individual selections.

")) 401 | self.tabWidget.setTabText(self.tabWidget.indexOf(self.tabBasic), _translate("MainWindow", "Basic")) 402 | self.groupCurrentSel.setToolTip(_translate("MainWindow", "

Click a selection to make it the current one. You can then set a fixed aspect ratio for this selection here.

")) 403 | self.groupCurrentSel.setTitle(_translate("MainWindow", "Current Selection")) 404 | self.comboSelAspectRatioType.setToolTip(_translate("MainWindow", "

If your favorite aspect ratio is missing here, you can add it by editing the config file.

")) 405 | self.labelSelAspectRatio.setText(_translate("MainWindow", "Aspect ratio:")) 406 | self.groupTrimMargins.setToolTip(_translate("MainWindow", "

Right-click a selection to automatically trim it.

")) 407 | self.groupTrimMargins.setTitle(_translate("MainWindow", "Settings for trimming margins")) 408 | self.checkTrimUseAllPages.setToolTip(_translate("MainWindow", "

If selected, all pages will be inspected (which can be very slow!) in order to determine the margins for auto trimming. Otherwise, only the current page is inspected.

")) 409 | self.checkTrimUseAllPages.setText(_translate("MainWindow", "Use all pages (slow!)")) 410 | self.labelPadding.setToolTip(_translate("MainWindow", "

How much padding to use when trimming.

Eg: 2 or 5,2 or 5,2,5,5 (interpreted as in CSS)

")) 411 | self.labelPadding.setText(_translate("MainWindow", "Padding:")) 412 | self.editPadding.setToolTip(_translate("MainWindow", "

How much padding to use when trimming.

Eg: 2 or 5,2 or 5,2,5,5 (interpreted as in CSS)

")) 413 | self.labelAllowedChanges.setText(_translate("MainWindow", "Allowed changes:")) 414 | self.labelSensitivity.setText(_translate("MainWindow", "Color sensitivity:")) 415 | self.groupDistribute.setToolTip(_translate("MainWindow", "

Use this option if you want to break up each selection into pieces that exactly fit a certain aspect ratio. This is useful for displaying files on devices that don\'t support scrolling well.

")) 416 | self.groupDistribute.setTitle(_translate("MainWindow", "Fit screen of device")) 417 | self.labelDistributeAspectRatio.setText(_translate("MainWindow", "Aspect ratio:")) 418 | self.labelDistributeHelp.setText(_translate("MainWindow", "

Eg: 600:730 (ratio of width to height)

")) 419 | self.tabWidget.setTabText(self.tabWidget.indexOf(self.tabAdvanced), _translate("MainWindow", "Advanced")) 420 | self.labelHelp.setText(_translate("MainWindow", "

Getting started

\n" 421 | "

Using your mouse, create one or more selections on the pdf document. These are the regions that will be included into the cropped file.

\n" 422 | "

When you are done, click Krop! in the menu to create a cropped version of your document.

\n" 423 | "

Hints

\n" 424 | "

Right-click the page to create a selection for the full page (or a grid of selections).

\n" 425 | "

Right-click a selection to delete it. Or simply press the Delete key.

\n" 426 | "

You can choose to create individual selections for each page.

\n" 427 | "

You can automatically trim the margins of your selections.

\n" 428 | "

Examples and more information can be found at: arminstraub.com

\n" 429 | "")) 430 | self.labelHelpCopyright.setToolTip(_translate("MainWindow", "

This program is free software and available to you in the hope that it will be useful; but without any warranty. It is distributed under the terms of the GNU General Public License (GPLv3+). See the accompanying files for more information.

")) 431 | self.labelHelpCopyright.setText(_translate("MainWindow", "

Copyright (C) 2010-2025 Armin Straub\n" 432 | "
https://arminstraub.com

")) 433 | self.tabWidget.setTabText(self.tabWidget.indexOf(self.tabHelp), _translate("MainWindow", "Help")) 434 | self.label.setText(_translate("MainWindow", "of")) 435 | self.toolBar.setWindowTitle(_translate("MainWindow", "toolBar")) 436 | self.actionZoomIn.setText(_translate("MainWindow", "Zoom In")) 437 | self.actionZoomIn.setShortcut(_translate("MainWindow", "Ctrl+=")) 438 | self.actionZoomOut.setText(_translate("MainWindow", "Zoom Out")) 439 | self.actionZoomOut.setShortcut(_translate("MainWindow", "Ctrl+-")) 440 | self.actionPreviousPage.setText(_translate("MainWindow", "Previous Page")) 441 | self.actionPreviousPage.setShortcut(_translate("MainWindow", "PgUp")) 442 | self.actionNextPage.setText(_translate("MainWindow", "Next Page")) 443 | self.actionNextPage.setShortcut(_translate("MainWindow", "PgDown")) 444 | self.actionOpenFile.setText(_translate("MainWindow", "Open")) 445 | self.actionOpenFile.setShortcut(_translate("MainWindow", "Ctrl+O")) 446 | self.actionFitInView.setText(_translate("MainWindow", "Fit In View")) 447 | self.actionKrop.setText(_translate("MainWindow", "Krop!")) 448 | self.actionDeleteSelection.setText(_translate("MainWindow", "Delete Selection")) 449 | self.actionDeleteSelection.setShortcut(_translate("MainWindow", "Del")) 450 | self.actionFirstPage.setText(_translate("MainWindow", "First Page")) 451 | self.actionFirstPage.setShortcut(_translate("MainWindow", "Home")) 452 | self.actionLastPage.setText(_translate("MainWindow", "Last Page")) 453 | self.actionLastPage.setShortcut(_translate("MainWindow", "End")) 454 | self.actionTrimMargins.setText(_translate("MainWindow", "Trim Margins")) 455 | self.actionSelectFile.setText(_translate("MainWindow", "Select File")) 456 | self.actionTrimMarginsAll.setText(_translate("MainWindow", "Trim Margins")) 457 | self.actionTrimMarginsAll.setToolTip(_translate("MainWindow", "Trim Margins")) 458 | self.actionTrimMarginsAll.setShortcut(_translate("MainWindow", "Ctrl+T")) 459 | self.actionNewSelection.setText(_translate("MainWindow", "New Selection")) 460 | self.actionNewSelection.setToolTip(_translate("MainWindow", "New Selection")) 461 | self.actionNewSelection.setShortcut(_translate("MainWindow", "Ins")) 462 | self.actionNewSelectionGrid.setText(_translate("MainWindow", "New Selection Grid...")) 463 | self.actionNewSelectionGrid.setToolTip(_translate("MainWindow", "New Selection Grid...")) 464 | self.actionNewSelectionGrid.setShortcut(_translate("MainWindow", "Shift+Ins")) 465 | -------------------------------------------------------------------------------- /krop/pdfcropper.py: -------------------------------------------------------------------------------- 1 | # -*- coding: iso-8859-1 -*- 2 | 3 | """ 4 | Cropping functionality for krop. 5 | 6 | Copyright (C) 2010-2025 Armin Straub, http://arminstraub.com 7 | """ 8 | 9 | """ 10 | This program is free software; you can redistribute it and/or modify 11 | it under the terms of the GNU General Public License as published by 12 | the Free Software Foundation; either version 3 of the License, or 13 | (at your option) any later version. 14 | """ 15 | 16 | import copy 17 | import sys 18 | 19 | from krop.config import PYQT6 20 | 21 | 22 | class PdfEncryptedError(Exception): 23 | pass 24 | 25 | 26 | class AbstractPdfFile: 27 | """Abstract class for loading a PDF document used in a corresponding 28 | PdfCropper class""" 29 | def loadFromStream(self, stream): 30 | pass 31 | def loadFromFile(self, filename): 32 | self.loadFromStream(open(filename, "rb")) 33 | 34 | class PyPdfFile(AbstractPdfFile): 35 | """Implementation of PdfFile using the new pypdf""" 36 | def __init__(self): 37 | self.reader = None 38 | def loadFromStream(self, stream): 39 | self.reader = self.PdfReader(stream) 40 | if self.reader.is_encrypted: 41 | try: 42 | if not self.reader.decrypt(''): 43 | raise PdfEncryptedError 44 | except: 45 | raise PdfEncryptedError 46 | def getPage(self, nr): 47 | return self.reader.pages[nr] 48 | 49 | class PyPdfOldFile(PyPdfFile): 50 | """Implementation of PdfFile using PyPDF2 (<2) which uses camelCase rather 51 | than snake_case""" 52 | def loadFromStream(self, stream): 53 | self.reader = self.PdfReader(stream, strict=False) 54 | if self.reader.isEncrypted: 55 | try: 56 | if not self.reader.decrypt(''): 57 | raise PdfEncryptedError 58 | except: 59 | raise PdfEncryptedError 60 | def getPage(self, nr): 61 | return self.reader.getPage(nr) 62 | 63 | class PyMuPdfFile(AbstractPdfFile): 64 | """Implementation of PdfFile using PyMuPDF""" 65 | def __init__(self): 66 | self.reader = None 67 | def loadFromStream(self, stream): 68 | self.reader = self.pymupdf.open(stream) 69 | if self.reader.is_encrypted: 70 | raise PdfEncryptedError 71 | def getPage(self, nr): 72 | return self.reader[nr] 73 | 74 | class PikePdfFile(AbstractPdfFile): 75 | """Implementation of PdfFile using pikepdf""" 76 | def __init__(self): 77 | self.reader = None 78 | def loadFromStream(self, stream): 79 | self.reader = self.Pdf.open(stream) 80 | if self.reader.is_encrypted: 81 | raise PdfEncryptedError 82 | def getPage(self, nr): 83 | return self.reader.pages[nr] 84 | 85 | 86 | class AbstractPdfCropper: 87 | """Abstract class for writing a PDF documents composed of cropped pages 88 | from PdfFile instances""" 89 | def writeToStream(self, stream): 90 | pass 91 | def writeToFile(self, filename): 92 | stream = open(filename, "wb") 93 | self.writeToStream(stream) 94 | stream.close() 95 | def addPageCropped(self, pdffile, pagenumber, croplist, rotate=0): 96 | pass 97 | def copyDocumentRoot(self, pdffile): 98 | pass 99 | 100 | class SemiAbstractPdfCropper(AbstractPdfCropper): 101 | """An extension of AbstractPdfCropper that implements the basic logic 102 | breaking it down to certain functions on pages""" 103 | def addPageCropped(self, pdffile, pagenumber, croplist, alwaysinclude, rotate=0): 104 | page = pdffile.getPage(pagenumber) 105 | if not croplist and alwaysinclude: 106 | self.doAddPage(page, rotate) 107 | else: 108 | box = self.pageGetCropBox(page) 109 | for crop in croplist: 110 | new_page = copy.copy(page) 111 | new_box = computeCropBoxCoords(box, crop) 112 | self.pageSetCropBox(new_page, new_box) 113 | self.doAddPage(new_page, rotate) 114 | def doAddPage(self, page, rotate): 115 | pass 116 | def pageGetCropBox(self, page): 117 | pass 118 | def pageSetCropBox(self, page, box): 119 | pass 120 | 121 | class PyPdfCropper(SemiAbstractPdfCropper): 122 | """Implementation of PdfCropper using pypdf""" 123 | def __init__(self): 124 | self.output = self.PdfWriter() 125 | def writeToStream(self, stream): 126 | # For certain large pdf files, PdfWriter.write() causes the error: 127 | # maximum recursion depth exceeded while calling a Python object 128 | # This issue is present, for instance, in PyPDF2 1.23. 129 | # We therefore temporarily increase the recursion limit. 130 | old_reclimit = sys.getrecursionlimit() 131 | sys.setrecursionlimit(10000) 132 | self.output.write(stream) 133 | sys.setrecursionlimit(old_reclimit) 134 | def doAddPage(self, page, rotate): 135 | if rotate != 0: 136 | page.rotate(rotate) 137 | self.output.add_page(page) 138 | def pageGetCropBox(self, page): 139 | x0, y0 = page.cropbox.lower_left 140 | x1, y1 = page.cropbox.upper_right 141 | return x0, y0, x1, y1 142 | def pageSetCropBox(self, page, box): 143 | x0, y0, x1, y1 = box 144 | for page_box in (page.artbox, page.bleedbox, page.cropbox, page.mediabox, page.trimbox): 145 | page_box.lower_left = (x0, y0) 146 | page_box.upper_right = (x1, y1) 147 | def copyDocumentRoot(self, pdffile): 148 | # Copy the named destinations for links. 149 | # TODO: this worked for links in PyPDF2 but doesn't seem to work for pypdf 150 | for dest in pdffile.reader.named_destinations.values(): 151 | self.output.add_named_destination_object(dest) 152 | 153 | class PyPdfOldCropper(PyPdfCropper): 154 | """Implementation of PdfCropper using PyPDF2 (<2)""" 155 | def doAddPage(self, page, rotate): 156 | if rotate != 0: 157 | page.rotateClockwise(rotate) 158 | self.output.addPage(page) 159 | def pageGetCropBox(self, page): 160 | x0, y0 = page.cropBox.lowerLeft 161 | x1, y1 = page.cropBox.upperRight 162 | return x0, y0, x1, y1 163 | def pageSetCropBox(self, page, box): 164 | x0, y0, x1, y1 = box 165 | for page_box in (page.artBox, page.bleedBox, page.cropBox, page.mediaBox, page.trimBox): 166 | page_box.lowerLeft = (x0, y0) 167 | page_box.upperRight = (x1, y1) 168 | def copyDocumentRoot(self, pdffile): 169 | # Copy the named destinations for links. 170 | for dest in pdffile.reader.namedDestinations.values(): 171 | self.output.addNamedDestinationObject(dest) 172 | 173 | 174 | class PyMuPdfCropper(SemiAbstractPdfCropper): 175 | """Implementation of PdfCropper using PyMuPDF""" 176 | def __init__(self): 177 | self.output = self.pymupdf.open() 178 | def writeToStream(self, stream): 179 | self.output.save(stream) 180 | def addPageCropped(self, pdffile, pagenumber, croplist, alwaysinclude, rotate=0): 181 | def addPage(): 182 | # https://pymupdf.readthedocs.io/en/latest/the-basics.html 183 | r = pdffile.reader[pagenumber].rotation + rotate 184 | self.output.insert_pdf(pdffile.reader, from_page=pagenumber, to_page=pagenumber, rotate=r) 185 | if not croplist and alwaysinclude: 186 | addPage() 187 | else: 188 | for crop in croplist: 189 | addPage() 190 | new_page = self.output[-1] 191 | box = self.pageGetCropBox(new_page) 192 | # MuPDF uses coordinates where (0,0) is the top-right point, unlike 193 | # PDF where (0,0) is the bottom-left. 194 | new_box = computeCropBoxCoords(box, crop, pdf_coords=False) 195 | self.pageSetCropBox(new_page, new_box) 196 | # if rotate != 0: 197 | # self.pageRotateClockwise(new_page, rotate) 198 | def pageGetCropBox(self, page): 199 | return page.cropbox 200 | def pageSetCropBox(self, page, box): 201 | page.set_cropbox(box) 202 | try: 203 | page.set_artbox(page.cropbox) 204 | page.set_bleedbox(page.cropbox) 205 | # careful: mediabox in MuPDF is an exception and uses PDF coordinates 206 | # page.set_mediabox(page.cropbox) 207 | page.set_trimbox(page.cropbox) 208 | except: 209 | # these functions did not exist prior to v1.19.4 210 | pass 211 | def copyDocumentRoot(self, pdffile): 212 | pass 213 | 214 | 215 | class PikePdfCropper(SemiAbstractPdfCropper): 216 | """Implementation of PdfCropper using pikepdf""" 217 | def __init__(self): 218 | self.output = self.Pdf.new() 219 | def writeToStream(self, stream): 220 | self.output.save(stream) 221 | def doAddPage(self, page, rotate): 222 | if rotate != 0: 223 | page.rotate(rotate, relative=True) 224 | self.output.pages.append(page) 225 | def pageGetCropBox(self, page): 226 | try: 227 | # only page.MediaBox exists in pikepdf version 1.10.3 as currently in Ubuntu 20.04 228 | return page.cropbox 229 | except AttributeError: 230 | raise RuntimeError("Please install a more recent version of pikepdf.") 231 | def pageSetCropBox(self, page, box): 232 | page.cropbox = box 233 | page.mediabox = box 234 | page.trimbox = box 235 | def copyDocumentRoot(self, pdffile): 236 | pass 237 | 238 | 239 | def computeCropBoxCoords(box, crop, pdf_coords=True): 240 | x0, y0, x1, y1 = box 241 | x0, y0, x1, y1 = float(x0), float(y0), float(x1), float(y1) 242 | # In PDF coordinates (0,0) is the bottom-left point; otherwise, as in 243 | # MuPDF or Qt, this would be the top-left point. 244 | if not pdf_coords: 245 | crop = (crop[0], crop[3], crop[2], crop[1]) 246 | x0, x1 = x0+crop[0]*(x1-x0), x1-crop[2]*(x1-x0) 247 | y0, y1 = y0+crop[3]*(y1-y0), y1-crop[1]*(y1-y0) 248 | return x0, y0, x1, y1 249 | 250 | def optimizePdfGhostscript(oldfilename, newfilename): 251 | import subprocess 252 | subprocess.check_call(('gs', '-sDEVICE=pdfwrite', '-sOutputFile=' + newfilename, 253 | '-dNOPAUSE', '-dBATCH', oldfilename)) 254 | 255 | 256 | # In the following, we determine which cropping library to use. 257 | # See lib_crop_options below for a list of the supported libraries. 258 | 259 | def import_pymupdf(): 260 | import fitz 261 | # note: since 1.24.3, one can use 'import pymupdf' instead but fitz is 262 | # promised to always be supported as well 263 | PyMuPdfFile.pymupdf = fitz 264 | PyMuPdfCropper.pymupdf = fitz 265 | return PyMuPdfFile, PyMuPdfCropper 266 | 267 | def import_pikepdf(): 268 | from pikepdf import Pdf 269 | PikePdfFile.Pdf = Pdf 270 | PikePdfCropper.Pdf = Pdf 271 | return PikePdfFile, PikePdfCropper 272 | 273 | def import_pypdf(): 274 | from pypdf import PdfReader, PdfWriter 275 | PyPdfFile.PdfReader = PdfReader 276 | PyPdfCropper.PdfWriter = PdfWriter 277 | return PyPdfFile, PyPdfCropper 278 | 279 | def import_pypdf2(): 280 | import PyPDF2 281 | # PyPDF2 (<2) uses camelCase while newer versions (just like pypdf) use snake_case 282 | if PyPDF2.__version__.startswith("1."): 283 | from PyPDF2 import PdfFileReader as PdfReader, PdfFileWriter as PdfWriter 284 | PdfFile = PyPdfOldFile 285 | PdfCropper = PyPdfOldCropper 286 | else: 287 | from PyPDF2 import PdfReader, PdfWriter 288 | PdfFile = PyPdfFile 289 | PdfCropper = PyPdfCropper 290 | PdfFile.PdfReader = PdfReader 291 | PdfCropper.PdfWriter = PdfWriter 292 | return PdfFile, PdfCropper 293 | 294 | # for each cropping library: [name, import function, flag to request it] 295 | lib_crop_options = [ 296 | ['PyMuPDF', import_pymupdf, '--use-pymupdf'], 297 | ['pikepdf', import_pikepdf, '--use-pikepdf'], 298 | ['pypdf', import_pypdf, '--use-pypdf'], 299 | ['PyPDF2', import_pypdf2, '--use-pypdf2'], 300 | ] 301 | # lib_crop will be set to the name of the cropping library in use 302 | lib_crop = None 303 | 304 | # We go through all options for libraries twice: 305 | # during the first round, we load a library if it is specifically requested, 306 | # and during the second round, we load the first available library. 307 | for load_only_if_requested in [True, False]: 308 | for lib, import_func, flag in lib_crop_options: 309 | if not lib_crop and (not load_only_if_requested or (flag and flag in sys.argv)): 310 | try: 311 | PdfFile, PdfCropper = import_func() 312 | lib_crop = lib 313 | print(f"Using {lib} for cropping.", file=sys.stderr) 314 | except ImportError: 315 | if load_only_if_requested: 316 | print(f"{lib} was requested but failed to load.", file=sys.stderr) 317 | 318 | # complain if no library could be imported 319 | if not lib_crop: 320 | _msg = "Please install one of the supported cropping libraries first (PyMuPDF, pypdf, or pikepdf)." 321 | if PYQT6: 322 | _msg += "\n\tFor instance, on recent versions of Ubuntu, the following should do the trick:"\ 323 | "\n\tsudo apt-get install python3-pymupdf" 324 | else: 325 | _msg += "\n\tFor instance, on versions of Ubuntu such as 22.04, one of the following should do the trick:"\ 326 | "\n\tsudo apt install python3-fitz"\ 327 | "\n\tsudo apt-get install python3-pypdf2" 328 | raise RuntimeError(_msg) 329 | 330 | -------------------------------------------------------------------------------- /krop/qt.py: -------------------------------------------------------------------------------- 1 | from krop.config import PYQT6 2 | 3 | if PYQT6: 4 | from PyQt6.QtCore import * 5 | from PyQt6.QtGui import * 6 | from PyQt6.QtWidgets import * 7 | else: 8 | from PyQt5.QtCore import * 9 | from PyQt5.QtGui import * 10 | from PyQt5.QtWidgets import * 11 | -------------------------------------------------------------------------------- /krop/version.py: -------------------------------------------------------------------------------- 1 | __version__ = '0.7.0' 2 | -------------------------------------------------------------------------------- /krop/vieweritem.py: -------------------------------------------------------------------------------- 1 | # -*- coding: iso-8859-1 -*- 2 | 3 | """ 4 | Viewer for krop used to display PDF files. 5 | 6 | Copyright (C) 2010-2025 Armin Straub, http://arminstraub.com 7 | """ 8 | 9 | """ 10 | This program is free software; you can redistribute it and/or modify 11 | it under the terms of the GNU General Public License as published by 12 | the Free Software Foundation; either version 3 of the License, or 13 | (at your option) any later version. 14 | """ 15 | 16 | import sys 17 | 18 | from krop.config import PYQT6 19 | from krop.qt import * 20 | 21 | from krop.viewerselections import ViewerSelections 22 | 23 | 24 | class AbstractViewerItem(QGraphicsItem): 25 | """Abstract class for displaying a PDF document and for allowing the user 26 | to create selections.""" 27 | def __init__(self, mainwindow): 28 | QGraphicsItem.__init__(self) 29 | self.selections = ViewerSelections(self) 30 | self.reset() 31 | self.mainwindow = mainwindow 32 | 33 | def reset(self): 34 | self._currentPageIndex = 0 35 | self.brect = QRectF() 36 | self.irect = QRectF() 37 | self._images = [] 38 | self.selections.deleteSelections() 39 | 40 | def boundingRect(self): 41 | return self.brect 42 | 43 | def isPortrait(self): 44 | return self.irect.width() <= self.irect.height() 45 | 46 | def paint(self, painter, option, widget): 47 | img = self.getImage(self.currentPageIndex) 48 | if img is None: 49 | return 50 | painter.drawRect(self.irect.adjusted(-1,-1,1,1)) 51 | painter.drawImage(self.irect, img) 52 | 53 | def mapRectToImage(self, r): 54 | return r.translated(-self.irect.left(), -self.irect.top()) 55 | 56 | def mapRectFromImage(self, r): 57 | return r.translated(self.irect.left(), self.irect.top()) 58 | 59 | def getCurrentPageIndex(self): 60 | return self._currentPageIndex 61 | 62 | def setCurrentPageIndex(self, idx): 63 | if idx >= self.numPages(): 64 | idx = self.numPages()-1 65 | if idx < 0: 66 | idx = 0 67 | self._currentPageIndex = idx 68 | 69 | img = self.getImage(idx) 70 | if img is None: 71 | return 72 | self.selections.updateSelectionVisibility() 73 | 74 | self.prepareGeometryChange() 75 | rect = QRectF(img.rect()) 76 | # inflate slightly so that bounding rect will be visible 77 | padding = 5 78 | self.brect = QRectF(0,0,rect.width()+2*padding,rect.height()+2*padding) 79 | self.irect = QRectF(padding,padding,rect.width(),rect.height()) 80 | self.scene().setSceneRect(self.brect) 81 | 82 | currentPageIndex = property(getCurrentPageIndex, setCurrentPageIndex) 83 | 84 | def previousPage(self): 85 | self.currentPageIndex = self.currentPageIndex-1 86 | 87 | def nextPage(self): 88 | self.currentPageIndex = self.currentPageIndex+1 89 | 90 | def firstPage(self): 91 | self.currentPageIndex = 0 92 | 93 | def lastPage(self): 94 | self.currentPageIndex = self.numPages()-1 95 | 96 | def getImage(self, idx): 97 | if idx < 0 or idx >= self.numPages(): 98 | return None 99 | if self._images[idx] is None: 100 | self._images[idx] = self.cacheImage(idx) 101 | return self._images[idx] 102 | 103 | def mousePressEvent(self, event): 104 | self.selections.mousePressEvent(event) 105 | 106 | def mouseMoveEvent(self, event): 107 | self.selections.mouseMoveEvent(event) 108 | 109 | def mouseReleaseEvent(self, event): 110 | self.selections.mouseReleaseEvent(event) 111 | 112 | def load(self, filename): 113 | self.reset() 114 | self.doLoad(filename) 115 | self._images = [None for i in range(self.numPages())] 116 | self.firstPage() 117 | 118 | # To be implemented in deriving classes: 119 | 120 | def doLoad(self, filename): 121 | pass 122 | 123 | def numPages(self): 124 | return 0 125 | 126 | def isEmpty(self): 127 | return self.numPages() <= 0 128 | 129 | def cacheImage(self, idx): 130 | return None 131 | 132 | def pageGetRotation(self, idx): 133 | return 0 134 | 135 | def cropValues(self, idx): 136 | def adjustForOrientation(cv): 137 | if r == 90: # Landscape 138 | return [ cv[1], cv[2], cv[3], cv[0] ] 139 | elif r == 180: # UpsideDown 140 | return [ cv[2], cv[3], cv[0], cv[1] ] 141 | elif r == 270: # Seascape 142 | return [ cv[3], cv[0], cv[1], cv[2] ] 143 | else: # r == 0, Portrait 144 | return cv 145 | crop_values = self.selections.cropValues(idx) 146 | r = self.pageGetRotation(idx) 147 | return [ adjustForOrientation(cv) for cv in crop_values ] 148 | 149 | 150 | class PopplerViewerItem(AbstractViewerItem): 151 | """Viewer implementation which uses Poppler to display PDF documents.""" 152 | def reset(self): 153 | AbstractViewerItem.reset(self) 154 | self._pdfdoc = None 155 | 156 | def doLoad(self, filename): 157 | self._pdfdoc = Poppler.Document.load(filename) 158 | if self._pdfdoc: 159 | self._pdfdoc.setRenderHint(Poppler.Document.Antialiasing and 160 | Poppler.Document.TextAntialiasing) 161 | 162 | def numPages(self): 163 | if self._pdfdoc is None: 164 | return 0 165 | else: 166 | return self._pdfdoc.numPages() 167 | 168 | def cacheImage(self, idx): 169 | page = self._pdfdoc.page(idx) 170 | return page.renderToImage(96.0, 96.0) # dpi = 96 171 | # return page.renderToImage() # default dpi = 72 172 | 173 | def pageGetRotation(self, idx): 174 | page = self._pdfdoc.page(idx) 175 | o = page.orientation() 176 | if o == page.Landscape: 177 | return 90 178 | elif o == page.UpsideDown: 179 | return 180 180 | elif o == page.Seascape: 181 | return 270 182 | else: # o == page.Portrait 183 | return 0 184 | 185 | 186 | class MuPDFViewerItem(AbstractViewerItem): 187 | """Viewer implementation which uses PyMuPDF to display PDF documents.""" 188 | def reset(self): 189 | AbstractViewerItem.reset(self) 190 | self._pdfdoc = None 191 | 192 | def doLoad(self, filename): 193 | self._pdfdoc = fitz.open(filename) 194 | # if self._pdfdoc: 195 | # self._pdfdoc.setRenderHint(Poppler.Document.Antialiasing and 196 | # Poppler.Document.TextAntialiasing) 197 | 198 | def numPages(self): 199 | if self._pdfdoc is None: 200 | return 0 201 | else: 202 | return len(self._pdfdoc) 203 | 204 | def cacheImage(self, idx): 205 | page = self._pdfdoc[idx] 206 | pix = page.get_pixmap(alpha=False, dpi=96) # default dpi is 72 207 | return QImage(pix.samples, pix.width, pix.height, pix.stride, QImage.Format.Format_RGB888) 208 | # It might be faster to use samples_ptr but the code results in crashes. 209 | # https://pymupdf.readthedocs.io/en/latest/tutorial.html 210 | # pix = page.get_pixmap() 211 | # set the correct QImage format depending on alpha 212 | # fmt = QImage.Format_RGBA8888 if pix.alpha else QImage.Format.Format_RGB888 213 | # return QImage(pix.samples_ptr, pix.width, pix.height, fmt) 214 | 215 | def pageGetRotation(self, idx): 216 | page = self._pdfdoc[idx] 217 | return page.rotation 218 | 219 | 220 | # determine whether to use PopplerQt or PyMuPDF for rendering 221 | POPPLERQT = 1 222 | PYMUPDF = 2 223 | lib_render = 0 224 | 225 | from krop.config import PYQT6 226 | 227 | # for PyQt6 use PyMuPDF 228 | if PYQT6: 229 | try: 230 | import fitz 231 | lib_render = PYMUPDF 232 | except ImportError: 233 | _msg = "Please install PyMuPDF first (PyQt6 is being used)."\ 234 | "\n\tOn recent versions of Ubuntu, the following should do the trick:"\ 235 | "\n\tsudo apt-get install python3-pymupdf" 236 | raise RuntimeError(_msg) 237 | else: 238 | # PyQt5 was requested 239 | if not '--use-poppler' in sys.argv: 240 | try: 241 | import fitz 242 | lib_render = PYMUPDF 243 | except ImportError: 244 | pass 245 | if not lib_render: 246 | try: 247 | from popplerqt5 import Poppler 248 | lib_render = POPPLERQT 249 | except ImportError: 250 | pass 251 | # complain if no version is available 252 | if not lib_render: 253 | _msg = "Please install PyMuPDF or Poppler Qt first (PyQt5 is being used)."\ 254 | "\n\tOn versions of Ubuntu such as 22.04, one of the following should do the trick:"\ 255 | "\n\tsudo apt install python3-fitz"\ 256 | "\n\tsudo apt install python3-poppler-qt5" 257 | raise RuntimeError(_msg) 258 | 259 | if lib_render == PYMUPDF: 260 | ViewerItem = MuPDFViewerItem 261 | print("Using PyMuPDF for rendering.", file=sys.stderr) 262 | else: 263 | ViewerItem = PopplerViewerItem 264 | print("Using PopplerQt for rendering.", file=sys.stderr) 265 | -------------------------------------------------------------------------------- /krop/viewerselections.py: -------------------------------------------------------------------------------- 1 | # -*- coding: iso-8859-1 -*- 2 | 3 | """ 4 | User-created selections used in ViewerItem. 5 | 6 | Copyright (C) 2010-2020 Armin Straub, http://arminstraub.com 7 | """ 8 | 9 | """ 10 | This program is free software; you can redistribute it and/or modify 11 | it under the terms of the GNU General Public License as published by 12 | the Free Software Foundation; either version 3 of the License, or 13 | (at your option) any later version. 14 | """ 15 | 16 | from math import ceil 17 | 18 | from krop.qt import * 19 | 20 | 21 | class ViewerSelections(object): 22 | """A collection of user-created selections""" 23 | 24 | # possible selection modes 25 | all = 0 26 | evenodd = 1 27 | individual = 2 28 | 29 | def __init__(self, viewer): 30 | self.viewer = viewer 31 | self._selections = [] 32 | self._currentSelection = None 33 | self._distributeAspectRatio = None 34 | self._selectionMode = ViewerSelections.all 35 | self._selectionExceptions = [] # list of page numbers which require individual selections 36 | self.lastPos = None 37 | 38 | @property 39 | def items(self): 40 | """Returns a list of the selections.""" 41 | # the list equals self.viewer.childItems() except for the ordering: 42 | # we preserve the order in which the selections were created, whereas 43 | # childItems() gets reordered when stackBefore (or setZValue are 44 | # called) 45 | return self._selections 46 | 47 | def addSelection(self, rect=None): 48 | s = ViewerSelectionItem(self.viewer, rect) 49 | self._selections.append(s) 50 | s.setAsCurrent() 51 | return s 52 | 53 | def deleteSelection(self, s): 54 | self._selections.remove(s) 55 | s.scene().removeItem(s) 56 | if s is self.currentSelection: 57 | self.currentSelection = None 58 | self.autoSetCurrentSelection() 59 | 60 | def deleteSelections(self): 61 | for s in self.items: 62 | self.deleteSelection(s) 63 | 64 | def getCurrentSelection(self): 65 | return self._currentSelection 66 | 67 | def setCurrentSelection(self, currentSelection): 68 | self._currentSelection = currentSelection 69 | if currentSelection: 70 | for s in self.items: 71 | if s is not currentSelection: 72 | s.stackBefore(currentSelection) 73 | currentSelection.setFocus() 74 | self.viewer.scene().update() 75 | self.currentSelectionUpdated() 76 | 77 | currentSelection = property(getCurrentSelection, setCurrentSelection) 78 | 79 | def autoSetCurrentSelection(self): 80 | s = self.currentSelection 81 | idx = self.viewer.currentPageIndex 82 | # check if currentSelection is visible 83 | if s and not s.selectionVisibleOnPage(idx): 84 | s = None 85 | # if currentSelection is None, we auto select if possible 86 | if s is None: 87 | for i in reversed(self.items): 88 | if i.selectionVisibleOnPage(idx): 89 | s = i 90 | break 91 | self.currentSelection = s 92 | 93 | def currentSelectionUpdated(self): 94 | self.viewer.mainwindow.currentSelectionUpdated() 95 | 96 | def getDistributeAspectRatio(self): 97 | return self._distributeAspectRatio 98 | 99 | def setDistributeAspectRatio(self, distributeAspectRatio): 100 | self._distributeAspectRatio = distributeAspectRatio 101 | self.viewer.update() 102 | 103 | distributeAspectRatio = property(getDistributeAspectRatio, setDistributeAspectRatio) 104 | 105 | def getSelectionMode(self): 106 | return self._selectionMode 107 | 108 | def setSelectionMode(self, mode): 109 | self._selectionMode = mode 110 | self.updateSelectionVisibility() 111 | 112 | selectionMode = property(getSelectionMode, setSelectionMode) 113 | 114 | def getSelectionExceptions(self): 115 | return self._selectionExceptions 116 | 117 | def setSelectionExceptions(self, exceptions): 118 | self._selectionExceptions = exceptions 119 | self.updateSelectionVisibility() 120 | 121 | selectionExceptions = property(getSelectionExceptions, setSelectionExceptions) 122 | 123 | def updateSelectionVisibility(self): 124 | idx = self.viewer.currentPageIndex 125 | for s in self.items: 126 | s.setVisible(s.selectionVisibleOnPage(idx)) 127 | self.autoSetCurrentSelection() 128 | 129 | def cropValues(self, idx): 130 | return [ c for s in self.items if s.selectionVisibleOnPage(idx) 131 | for c in s.cropValues() ] 132 | 133 | def mousePressEvent(self, event): 134 | if event.button() == Qt.MouseButton.LeftButton: 135 | pos = event.pos() 136 | rect = QRectF(pos, QSizeF()) 137 | self.currentSelection = self.addSelection(rect) 138 | self.lastPos = pos 139 | 140 | def mouseMoveEvent(self, event): 141 | if self.lastPos is not None: 142 | pos2 = event.pos() 143 | self.currentSelection.setBoundingRect(self.lastPos, pos2) 144 | 145 | def mouseReleaseEvent(self, event): 146 | self.lastPos = None 147 | 148 | 149 | class ViewerSelectionItem(QGraphicsItem): 150 | 151 | handleColor = QColor(0,0,128) 152 | handleColorCurrent = QColor(0,128,0) 153 | 154 | """An individual user-created selection""" 155 | def __init__(self, parent, rect=None): 156 | QGraphicsItem.__init__(self, parent) 157 | self.setFlag(QGraphicsItem.GraphicsItemFlag.ItemIsFocusable) 158 | 159 | if rect is None: 160 | rect = self.mapRectFromParent(self.viewer.irect) 161 | 162 | self.rect = rect 163 | self._aspectRatioData = None 164 | self._aspectRatio = None 165 | self.minWidth = 1 166 | self.minHeight = 1 167 | self.pageIndex = self.viewer.currentPageIndex 168 | self.lastPos = None 169 | SelectionHandleItem(self, SelectionHandleItem.LeftHandle) 170 | SelectionHandleItem(self, SelectionHandleItem.RightHandle) 171 | SelectionHandleItem(self, SelectionHandleItem.TopHandle) 172 | SelectionHandleItem(self, SelectionHandleItem.BottomHandle) 173 | SelectionCornerHandleItem(self, 0, 0) 174 | SelectionCornerHandleItem(self, 0, 1) 175 | SelectionCornerHandleItem(self, 1, 0) 176 | SelectionCornerHandleItem(self, 1, 1) 177 | self.adjustBoundingRect() 178 | 179 | self.setCursor(Qt.CursorShape.OpenHandCursor) 180 | 181 | 182 | @property 183 | def selection(self): 184 | # this is used in mainwindow.slotContextMenu 185 | return self 186 | 187 | @property 188 | def viewer(self): 189 | return self.parentItem() 190 | 191 | @property 192 | def selections(self): 193 | return self.viewer.selections 194 | 195 | 196 | def isCurrent(self): 197 | return self is self.selections.currentSelection 198 | 199 | def setAsCurrent(self): 200 | self.selections.currentSelection = self 201 | 202 | 203 | @property 204 | def orderIndex(self): 205 | nr = 1 206 | for c in self.selections.items: 207 | if c is self: 208 | return nr 209 | if c.isVisible(): 210 | nr += 1 211 | 212 | 213 | @property 214 | def aspectRatio(self): 215 | return self._aspectRatio 216 | 217 | def getAspectRatioData(self): 218 | return self._aspectRatioData or [0, ""] 219 | 220 | def setAspectRatioData(self, data): 221 | index, s = data 222 | # index=0: flexible 223 | if index == 0: 224 | self._aspectRatio = None 225 | data[1] = "" 226 | else: 227 | self._aspectRatio = aspectRatioFromStr(s) 228 | self._aspectRatioData = data 229 | self.adjustBoundingRect() 230 | for c in self.childItems(): 231 | if isinstance(c, SelectionHandleItem): 232 | c.setVisible(self._aspectRatio is None) 233 | 234 | aspectRatioData= property(getAspectRatioData, setAspectRatioData) 235 | 236 | 237 | @property 238 | def distributeAspectRatio(self): 239 | return self.selections.distributeAspectRatio 240 | 241 | 242 | def selectionVisibleOnPage(self, pageIndex): 243 | """Determines if this selection is visible on a given page.""" 244 | mode = self.selections.selectionMode 245 | exceptions = self.selections.selectionExceptions 246 | if pageIndex in exceptions or self.pageIndex in exceptions or mode == ViewerSelections.individual: 247 | return pageIndex == self.pageIndex 248 | if mode == ViewerSelections.all: 249 | return True 250 | if mode == ViewerSelections.evenodd: 251 | return (pageIndex - self.pageIndex) % 2 == 0 252 | 253 | 254 | def boundingRect(self): 255 | return self.rect 256 | 257 | def setBoundingRect(self, pt1, pt2): 258 | orect = self.rect 259 | nrect = QRectF(pt1, pt2).normalized() 260 | self.adjustBoundingRect( 261 | nrect.left()-orect.left(), 262 | nrect.top()-orect.top(), 263 | nrect.right()-orect.right(), 264 | nrect.bottom()-orect.bottom()) 265 | 266 | 267 | def adjustBoundingRect(self, dx1=0, dy1=0, dx2=0, dy2=0): 268 | orect = self.mapRectToParent(self.rect) 269 | prect = self.viewer.irect 270 | nrect = orect.adjusted(dx1, dy1, dx2, dy2) 271 | 272 | # make sure we are still inside the parent 273 | if nrect.left() < prect.left(): 274 | nrect.setLeft(prect.left()) 275 | if nrect.right() > prect.right(): 276 | nrect.setRight(prect.right()) 277 | if nrect.top() < prect.top(): 278 | nrect.setTop(prect.top()) 279 | if nrect.bottom() > prect.bottom(): 280 | nrect.setBottom(prect.bottom()) 281 | # similar but not quite the same... 282 | # nrect = nrect.normalized().intersected(prect) 283 | 284 | # ensure minimum size 285 | extra = self.minWidth - nrect.width() 286 | if extra > 0: 287 | if dx1 == 0: 288 | nrect.setRight(nrect.right()+extra) 289 | elif dx2 == 0: 290 | nrect.setLeft(nrect.left()-extra) 291 | else: 292 | nrect.setLeft(nrect.left()-extra/2) 293 | nrect.setRight(nrect.right()+extra/2) 294 | extra = self.minHeight - nrect.height() 295 | if extra > 0: 296 | if dy1 == 0: 297 | nrect.setBottom(nrect.bottom()+extra) 298 | elif dy2 == 0: 299 | nrect.setTop(nrect.top()-extra) 300 | else: 301 | nrect.setTop(nrect.top()-extra/2) 302 | nrect.setBottom(nrect.bottom()+extra/2) 303 | 304 | # enforce aspectRatio r = w/h if set 305 | if self.aspectRatio: 306 | r, w, h = self.aspectRatio, nrect.width(), nrect.height() 307 | nw, nh = min(w, h*r), min(h, w/r) 308 | if dx1==0 and dx2!=0: 309 | # move right side 310 | nrect.adjust(0, 0, nw-w, 0) 311 | elif dx2==0 and dx1!=0: 312 | # move left side 313 | nrect.adjust(w-nw, 0, 0, 0) 314 | else: 315 | # center horizontally 316 | nrect.adjust((w-nw)/2, 0, -(w-nw)/2, 0) 317 | if dy1==0 and dy2!=0: 318 | # move bottom side 319 | nrect.adjust(0, 0, 0, nh-h) 320 | elif dy2==0 and dy1!=0: 321 | # move top side 322 | nrect.adjust(0, h-nh, 0, 0) 323 | else: 324 | # center vertically 325 | nrect.adjust(0, (h-nh)/2, 0, -(h-nh)/2) 326 | 327 | # store parent rect for comparison (when cropping later) 328 | self.parentrect = self.mapRectFromParent(self.viewer.irect) 329 | 330 | # change size of boundingRect 331 | self.prepareGeometryChange() 332 | self.rect = self.mapRectFromParent(nrect) 333 | self.selections.currentSelectionUpdated() 334 | 335 | return [nrect.left()-orect.left(), nrect.top()-orect.top(), 336 | nrect.right()-orect.right(), nrect.bottom()-orect.bottom() ] 337 | 338 | 339 | def moveBoundingRect(self, dx, dy): 340 | """moves boundingRect but never changes its size""" 341 | orect = self.mapRectToParent(self.rect) 342 | prect = self.viewer.irect 343 | if dx < 0: 344 | dx = max(dx, prect.left() - orect.left()) 345 | if dx > 0: 346 | dx = min(dx, prect.right() - orect.right()) 347 | if dy < 0: 348 | dy = max(dy, prect.top() - orect.top()) 349 | if dy > 0: 350 | dy = min(dy, prect.bottom() - orect.bottom()) 351 | self.adjustBoundingRect(dx, dy, dx, dy) 352 | 353 | 354 | def distributeRect(self): 355 | r = self.distributeAspectRatio 356 | if r is None: 357 | return [ self.rect ] 358 | x0,y0,x1,y1 = self.rect.getCoords() 359 | h = (x1-x0) / r # height of each piece 360 | # how many pieces? 361 | nr = int(ceil((y1-y0) / h)) 362 | if nr == 1: 363 | return [ self.rect ] 364 | o = (nr*h - (y1-y0)) / float(nr-1) # overlap 365 | return [ QRectF(x0, y0+i*(h-o), x1-x0, h) for i in range(nr) ] 366 | 367 | def cropValues(self): 368 | p = self.parentrect 369 | def cV(r): 370 | return ((r.left()-p.left())/p.width(), 371 | (r.top()-p.top())/p.height(), 372 | (p.right()-r.right())/p.width(), 373 | (p.bottom()-r.bottom())/p.height()) 374 | return [ cV(r) for r in self.distributeRect() ] 375 | 376 | def mapRectToImage(self, r): 377 | m = self.mapRectToParent(r) 378 | return self.viewer.mapRectToImage(m) 379 | 380 | def mapRectFromImage(self, r): 381 | m = self.viewer.mapRectFromImage(r) 382 | return self.mapRectFromParent(m) 383 | 384 | def paint(self, painter, option, widget): 385 | rect = self.boundingRect() 386 | 387 | # outer dashed rectangle 388 | outerPen = QPen() 389 | outerPen.setStyle(Qt.PenStyle.DashLine) 390 | painter.setPen(QColorConstants.White) 391 | painter.drawRect(rect) 392 | painter.setPen(outerPen) 393 | painter.drawRect(rect) 394 | 395 | def drawLine(pt1, pt2): 396 | painter.setPen(QColorConstants.White) 397 | painter.drawLine(pt1, pt2) 398 | painter.setPen(outerPen) 399 | painter.drawLine(pt1, pt2) 400 | 401 | # distributed rectangles 402 | even = True 403 | brush = QBrush() 404 | brush.setColor(QColor(0,0,0,50)) 405 | for r in self.distributeRect(): 406 | brush.setStyle(even and Qt.BrushStyle.BDiagPattern or Qt.BrushStyle.FDiagPattern) 407 | painter.setBrush(brush) 408 | painter.setPen(Qt.PenStyle.NoPen) 409 | painter.drawRect(r) 410 | if r.top() > self.rect.top(): 411 | drawLine(r.topLeft(),r.topRight()) 412 | if r.bottom() < self.rect.bottom(): 413 | drawLine(r.bottomLeft(),r.bottomRight()) 414 | even = not even 415 | 416 | # inner number 417 | font = QFont() 418 | font.setPointSize(20) 419 | font.setWeight(700) 420 | painter.setPen(QColor(0,0,0,155)) 421 | painter.setFont(font) 422 | painter.drawText(rect, Qt.AlignmentFlag.AlignCenter, str(self.orderIndex)) 423 | 424 | def mousePressEvent(self, event): 425 | # happens after right-click (trim margins) and then clicking 426 | # somewhere in the document 427 | if not self.boundingRect().contains(event.pos()): 428 | self.lastPos = None 429 | # event.ignore() 430 | elif event.button() == Qt.MouseButton.LeftButton: 431 | pos = event.pos() 432 | self.lastPos = pos 433 | self.setCursor(Qt.CursorShape.ClosedHandCursor) 434 | self.setAsCurrent() 435 | 436 | def mouseMoveEvent(self, event): 437 | if self.lastPos: 438 | newPos = event.pos() 439 | mov = newPos - self.lastPos 440 | nrect = self.mapRectToParent(self.boundingRect().translated(mov)) 441 | prect = self.viewer.irect 442 | if nrect.left() < prect.left(): 443 | newPos.setX(newPos.x() - nrect.left() + prect.left()) 444 | if nrect.right() > prect.right(): 445 | newPos.setX(newPos.x() - nrect.right() + prect.right()) 446 | if nrect.top() < prect.top(): 447 | newPos.setY(newPos.y() - nrect.top() + prect.top()) 448 | if nrect.bottom() > prect.bottom(): 449 | newPos.setY(newPos.y() - nrect.bottom() + prect.bottom()) 450 | mov = newPos - self.lastPos 451 | r = self.boundingRect().translated(mov) 452 | self.setBoundingRect(r.topLeft(), r.bottomRight()) 453 | self.lastPos = newPos 454 | 455 | def mouseReleaseEvent(self, event): 456 | self.lastPos = None 457 | self.setCursor(Qt.CursorShape.OpenHandCursor) 458 | 459 | def keyPressEvent(self, event): 460 | accepted = False 461 | if event.modifiers() == Qt.KeyboardModifier.ShiftModifier: 462 | accepted = True 463 | if event.key() == Qt.Key.Key_Left: 464 | self.moveBoundingRect(-1, 0) 465 | elif event.key() == Qt.Key.Key_Right: 466 | self.moveBoundingRect(1, 0) 467 | elif event.key() == Qt.Key.Key_Down: 468 | self.moveBoundingRect(0, 1) 469 | elif event.key() == Qt.Key.Key_Up: 470 | self.moveBoundingRect(0, -1) 471 | else: 472 | accepted = False 473 | if accepted: 474 | event.accept() 475 | else: 476 | event.ignore() 477 | 478 | 479 | class SelectionHandleItem(QGraphicsItem): 480 | 481 | LeftHandle = 1 482 | RightHandle = 2 483 | TopHandle = 3 484 | BottomHandle = 4 485 | 486 | def __init__(self, parent, role): 487 | QGraphicsItem.__init__(self, parent) 488 | 489 | self.role = role 490 | self.lastPos = None 491 | # arrow width and height (half, that is) 492 | self.aw = 8 493 | self.ah = 4 494 | # arrow center (0 means centered on boundary) 495 | self.ac = self.ah 496 | 497 | if self.role==SelectionHandleItem.LeftHandle or self.role==SelectionHandleItem.RightHandle: 498 | self.setCursor(Qt.CursorShape.SizeHorCursor) 499 | elif self.role==SelectionHandleItem.TopHandle or self.role==SelectionHandleItem.BottomHandle: 500 | self.setCursor(Qt.CursorShape.SizeVerCursor) 501 | 502 | @property 503 | def selection(self): 504 | return self.parentItem() 505 | 506 | @property 507 | def handleColor(self): 508 | if self.selection.isCurrent(): 509 | return self.selection.handleColorCurrent 510 | return self.selection.handleColor 511 | 512 | def boundingRect(self): 513 | rect = self.selection.boundingRect() 514 | pt = rect.center() 515 | if self.role==SelectionHandleItem.LeftHandle: 516 | pt.setX(rect.left()-self.ac) 517 | return QRectF(pt-QPointF(self.ah,self.aw), 518 | QSizeF(2*self.ah,2*self.aw)) 519 | if self.role==SelectionHandleItem.RightHandle: 520 | pt.setX(rect.right()+self.ac) 521 | return QRectF(pt-QPointF(self.ah,self.aw), 522 | QSizeF(2*self.ah,2*self.aw)) 523 | if self.role==SelectionHandleItem.TopHandle: 524 | pt.setY(rect.top()-self.ac) 525 | return QRectF(pt-QPointF(self.aw,self.ah), 526 | QSizeF(2*self.aw,2*self.ah)) 527 | if self.role==SelectionHandleItem.BottomHandle: 528 | pt.setY(rect.bottom()+self.ac) 529 | return QRectF(pt-QPointF(self.aw,self.ah), 530 | QSizeF(2*self.aw,2*self.ah)) 531 | 532 | def paint(self, painter, option, widget): 533 | rect = self.boundingRect() 534 | pt = rect.center() 535 | if self.role==SelectionHandleItem.LeftHandle: 536 | pts = [QPointF(-self.ah,0), QPointF(self.ah,-self.aw), 537 | QPointF(self.ah,self.aw)] 538 | if self.role==SelectionHandleItem.RightHandle: 539 | pts = [QPointF(self.ah,0), QPointF(-self.ah,-self.aw), 540 | QPointF(-self.ah,self.aw)] 541 | if self.role==SelectionHandleItem.TopHandle: 542 | pts = [QPointF(0,-self.ah), QPointF(self.aw,self.ah), 543 | QPointF(-self.aw,self.ah)] 544 | if self.role==SelectionHandleItem.BottomHandle: 545 | pts = [QPointF(0,self.ah), QPointF(self.aw,-self.ah), 546 | QPointF(-self.aw,-self.ah)] 547 | painter.setPen(self.handleColor) 548 | painter.setBrush(self.handleColor) 549 | painter.drawConvexPolygon(QPolygonF([pt+p for p in pts])) 550 | 551 | def mousePressEvent(self, event): 552 | if event.button() == Qt.MouseButton.LeftButton: 553 | pos = event.pos() 554 | self.lastPos = pos 555 | self.selection.setAsCurrent() 556 | 557 | def mouseMoveEvent(self, event): 558 | if self.lastPos: 559 | pos2 = event.pos() 560 | mov = pos2 - self.lastPos 561 | if self.role==SelectionHandleItem.LeftHandle: 562 | d = self.selection.adjustBoundingRect(mov.x(),0,0,0)[0] 563 | pos2.setX(self.lastPos.x() + d) 564 | if self.role==SelectionHandleItem.RightHandle: 565 | d = self.selection.adjustBoundingRect(0,0,mov.x(),0)[2] 566 | pos2.setX(self.lastPos.x() + d) 567 | if self.role==SelectionHandleItem.TopHandle: 568 | d = self.selection.adjustBoundingRect(0,mov.y(),0,0)[1] 569 | pos2.setY(self.lastPos.y() + d) 570 | if self.role==SelectionHandleItem.BottomHandle: 571 | d = self.selection.adjustBoundingRect(0,0,0,mov.y())[3] 572 | pos2.setY(self.lastPos.y() + d) 573 | self.lastPos = pos2 574 | 575 | def mouseReleaseEvent(self, event): 576 | self.lastPos = None 577 | 578 | 579 | class SelectionCornerHandleItem(QGraphicsItem): 580 | def __init__(self, parent, lr, tb): 581 | QGraphicsItem.__init__(self, parent) 582 | 583 | self.lr = lr 584 | self.tb = tb 585 | self.lastPos = None 586 | # size (half, that is) 587 | self.bs = 4 588 | 589 | self.setCursor((Qt.CursorShape.SizeFDiagCursor, Qt.CursorShape.SizeBDiagCursor)[(lr+tb)%2]) 590 | 591 | @property 592 | def selection(self): 593 | return self.parentItem() 594 | 595 | @property 596 | def handleColor(self): 597 | if self.selection.isCurrent(): 598 | return self.selection.handleColorCurrent 599 | return self.selection.handleColor 600 | 601 | def corner(self, rect): 602 | c = rect.getCoords() 603 | return QPointF(c[2*self.lr], c[2*self.tb+1]) 604 | 605 | def direction(self, pt): 606 | d = [0,0,0,0] 607 | d[2*self.lr] = pt.x() 608 | d[2*self.tb+1] = pt.y() 609 | return d 610 | 611 | def boundingRect(self): 612 | pt = self.corner(self.selection.boundingRect()) 613 | rect = QRectF(0,0,2*self.bs,2*self.bs) 614 | rect.moveCenter(pt) 615 | return rect 616 | 617 | def paint(self, painter, option, widget): 618 | rect = self.boundingRect() 619 | painter.setPen(self.handleColor) 620 | painter.setBrush(self.handleColor) 621 | painter.drawRect(rect) 622 | 623 | def mousePressEvent(self, event): 624 | if event.button() == Qt.MouseButton.LeftButton: 625 | pos = event.pos() 626 | self.lastPos = pos 627 | self.selection.setAsCurrent() 628 | 629 | def mouseMoveEvent(self, event): 630 | if self.lastPos: 631 | mov = event.pos() - self.lastPos 632 | d = self.selection.adjustBoundingRect(*self.direction(mov)) 633 | self.lastPos = self.lastPos + self.corner(QRectF().adjusted(*d)) 634 | 635 | def mouseReleaseEvent(self, event): 636 | self.lastPos = None 637 | 638 | 639 | def aspectRatioFromStr(s): 640 | try: 641 | a = [float(x) for x in s.split(":")] 642 | if len(a) == 1: 643 | aspectRatio = a[0] 644 | else: 645 | aspectRatio = a[0] / a[1] 646 | if aspectRatio <= 0: 647 | aspectRatio = None 648 | except: 649 | aspectRatio = None 650 | return aspectRatio 651 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python 2 | # -*- coding: iso-8859-1 -*- 3 | 4 | """ 5 | Copyright (C) 2014-2025 Armin Straub, http://arminstraub.com 6 | """ 7 | 8 | """ 9 | This program is free software; you can redistribute it and/or modify 10 | it under the terms of the GNU General Public License as published by 11 | the Free Software Foundation; either version 3 of the License, or 12 | (at your option) any later version. 13 | """ 14 | 15 | from setuptools import setup 16 | 17 | 18 | # Automatically determine version from first line of ChangeLog file 19 | import re 20 | with open('ChangeLog') as f: 21 | s = f.readline() 22 | version = re.search('\((.*)\)', s).group(1) 23 | 24 | # Update version in version.py 25 | with open('krop/version.py', 'w') as f: 26 | f.write("__version__ = '%s'\n" % (version,)) 27 | 28 | 29 | setup( 30 | name = 'krop', 31 | version = version, 32 | author = 'Armin Straub', 33 | author_email = 'mail@arminstraub.com', 34 | url = 'https://arminstraub.com/software/krop', 35 | description = 'A tool to crop PDF files', 36 | long_description = 'krop is a simple graphical tool to crop the pages of PDF files. It is written in Python and relies on PyQt and PyMuPDF (or a suitable subset of pypdf/pikepdf/python-poppler-qt) for its functionality. A unique feature of krop is its ability to automatically split pages into subpages to fit the limited screen size of devices such as eReaders. This is particularly useful, if your eReader does not support convenient scrolling.', 37 | # this is redundant but the egg/wheel produced by setuptools otherwise reports "License: UNKNOWN" 38 | license = 'GPL-3.0-or-later', 39 | keywords = 'pdf crop ereader', 40 | packages = ['krop'], 41 | entry_points = { 42 | 'console_scripts': ['krop = krop.__main__:main'] 43 | }, 44 | data_files = [ 45 | ('share/applications', ['com.arminstraub.krop.desktop']), 46 | ('share/man/man1', ['krop.1']), 47 | ('share/metainfo', ['com.arminstraub.krop.metainfo.xml']), 48 | ('share/icons/hicolor/scalable/apps', ['com.arminstraub.krop.svg']) 49 | ], 50 | # https://pypi.org/classifiers/ 51 | classifiers = [ 52 | 'Development Status :: 4 - Beta', 53 | 'License :: OSI Approved :: GNU General Public License v3 or later (GPLv3+)', 54 | 'Topic :: Utilities', 55 | 'Intended Audience :: End Users/Desktop', 56 | 'Programming Language :: Python :: 3', 57 | 'Environment :: X11 Applications :: Qt', 58 | ], 59 | ) 60 | --------------------------------------------------------------------------------