├── .editorconfig ├── .github ├── FUNDING.yml ├── ISSUE_TEMPLATE │ ├── bug_report.md │ └── feature_request.md ├── pull_request_template.md └── workflows │ └── check.yml ├── .gitignore ├── CODEOWNERS ├── CODE_OF_CONDUCT.md ├── CONTRIBUTING.md ├── LICENSE ├── Makefile ├── README.md ├── RELEASE ├── SECURITY.md ├── VERSION ├── composer.json ├── example └── index.php ├── phpcompatinfo.json ├── phpcs.xml ├── phpstan.neon ├── phpunit.xml.dist ├── resources ├── autoload.php ├── debian │ ├── changelog │ ├── compat │ ├── control │ ├── copyright │ ├── rules │ └── source │ │ └── format ├── rpm │ └── rpm.spec └── test │ ├── example_005.pdf │ ├── example_036.pdf │ └── example_046.pdf ├── src ├── Exception.php ├── Parser.php └── Process │ ├── RawObject.php │ ├── Xref.php │ └── XrefStream.php └── test └── ParserTest.php /.editorconfig: -------------------------------------------------------------------------------- 1 | # Ref: https://EditorConfig.org 2 | 3 | # top-most EditorConfig file 4 | root = true 5 | 6 | # Unix-style end of lines and a blank line at the end of the file 7 | [*] 8 | indent_style = tab 9 | end_of_line = lf 10 | charset = utf-8 11 | trim_trailing_whitespace = true 12 | insert_final_newline = true 13 | 14 | [*.php] 15 | indent_style = space 16 | indent_size = 4 17 | 18 | [*.{js,json,scss,css,yml,vue}] 19 | indent_style = space 20 | indent_size = 2 21 | -------------------------------------------------------------------------------- /.github/FUNDING.yml: -------------------------------------------------------------------------------- 1 | custom: ['https://www.paypal.com/donate/?hosted_button_id=NZUEC5XS8MFBJ'] 2 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/bug_report.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Bug report 3 | about: Create a report to help us improve 4 | title: '' 5 | labels: '' 6 | assignees: '' 7 | 8 | --- 9 | 10 | **Describe the bug** 11 | A clear and concise description of what the bug is. 12 | 13 | **To Reproduce** 14 | Steps to reproduce the behavior: 15 | 1. ... 16 | 17 | **Expected behavior** 18 | A clear and concise description of what you expected to happen. 19 | 20 | **Logs** 21 | If applicable, copy the relevant logs to help explain your problem. 22 | 23 | **Environment:** 24 | - OS: 25 | - PHP version: 26 | - Version: 27 | 28 | **Additional context** 29 | Add any other context about the problem here. 30 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/feature_request.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Feature request 3 | about: Suggest an idea for this project 4 | title: '' 5 | labels: '' 6 | assignees: '' 7 | 8 | --- 9 | 10 | **Is your feature request related to a problem? Please describe.** 11 | A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] 12 | 13 | **Describe the solution you'd like** 14 | A clear and concise description of what you want to happen. 15 | 16 | **Describe alternatives you've considered** 17 | A clear and concise description of any alternative solutions or features you've considered. 18 | 19 | **Additional context** 20 | Add any other context or screenshots about the feature request here. 21 | -------------------------------------------------------------------------------- /.github/pull_request_template.md: -------------------------------------------------------------------------------- 1 | # Description 2 | 3 | Please include a summary of the change and include relevant motivation and context. 4 | 5 | ... 6 | 7 | 8 | ## Checklist: 9 | 10 | - [ ] The `make buildall` command has been run successfully without any error or warning. 11 | - [ ] Any new code line is covered by unit tests and the coverage has not dropped. 12 | - [ ] Any new code follows the style guidelines of this project. 13 | - [ ] The code changes have been self-reviewed. 14 | - [ ] Corresponding changes to the documentation have been made. 15 | - [ ] The version has been updated in the VERSION file. 16 | 17 | ## Type of change: 18 | 19 | - [ ] Bug fix (non-breaking change which fixes an issue) → The patch number in the VERSION file has been increased. 20 | - [ ] New feature (non-breaking change which adds functionality) → The minor number in the VERSION file has been increased. 21 | - [ ] Breaking change (fix or feature that would cause existing functionality to not work as expected) → The major number in the VERSION file has been increased. 22 | - [ ] Automation. 23 | - [ ] Documentation. 24 | - [ ] Example. 25 | - [ ] Testing. 26 | -------------------------------------------------------------------------------- /.github/workflows/check.yml: -------------------------------------------------------------------------------- 1 | name: check 2 | 3 | env: 4 | XDEBUG_MODE: coverage 5 | 6 | permissions: 7 | contents: read 8 | 9 | on: 10 | push: 11 | branches: 12 | - 'main' 13 | pull_request: 14 | types: [opened, synchronize, reopened] 15 | branches: 16 | - main 17 | 18 | jobs: 19 | test-php: 20 | name: Test on php ${{ matrix.php-version }} and ${{ matrix.os }} 21 | runs-on: ${{ matrix.os }} 22 | continue-on-error: ${{ matrix.experimental }} 23 | strategy: 24 | fail-fast: false 25 | matrix: 26 | php-version: ["8.1", "8.2", "8.3", "8.4"] 27 | experimental: [false] 28 | os: [ubuntu-latest] 29 | coverage-extension: [pcov] 30 | steps: 31 | - uses: actions/checkout@v4 32 | - name: Use php ${{ matrix.php-version }} 33 | uses: shivammathur/setup-php@v2 34 | with: 35 | php-version: ${{ matrix.php-version }} 36 | coverage: ${{ matrix.coverage-extension }} 37 | extensions: bcmath, curl, date, gd, hash, imagick, json, mbstring, openssl, pcre, zlib 38 | ini-values: display_errors=on, error_reporting=-1, zend.assertions=1 39 | - name: List php modules 40 | run: php -m 41 | - name: List php modules using "no php ini" mode 42 | run: php -m -n 43 | - name: Cache module 44 | uses: actions/cache@v4 45 | with: 46 | path: ~/.composer/cache/ 47 | key: composer-cache 48 | - name: Install dependencies 49 | run: make deps 50 | - name: Run all tests 51 | run: make qa 52 | - name: Send coverage 53 | uses: codecov/codecov-action@v5 54 | with: 55 | flags: php-${{ matrix.php-version }}-${{ matrix.os }} 56 | name: php-${{ matrix.php-version }}-${{ matrix.os }} 57 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | **/*.bak 2 | **/*.tmp 3 | **/.#* 4 | **/.DS_Store 5 | **/._* 6 | **/.idea 7 | **/.vagrant 8 | **/auth.json 9 | **/nbproject 10 | **/temp.php 11 | **/test.php 12 | .phpdoc 13 | .phpunit.cache 14 | .phpunit.result.cache 15 | composer.lock 16 | ecs.php 17 | phpunit.xml 18 | rector.php 19 | target 20 | vendor 21 | -------------------------------------------------------------------------------- /CODEOWNERS: -------------------------------------------------------------------------------- 1 | * @nicolaasuni 2 | -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Contributor Covenant Code of Conduct 2 | 3 | ## Our Pledge 4 | 5 | We as members, contributors, and leaders pledge to make participation in our 6 | community a harassment-free experience for everyone, regardless of age, body 7 | size, visible or invisible disability, ethnicity, sex characteristics, gender 8 | identity and expression, level of experience, education, socio-economic status, 9 | nationality, personal appearance, race, religion, or sexual identity 10 | and orientation. 11 | 12 | We pledge to act and interact in ways that contribute to an open, welcoming, 13 | diverse, inclusive, and healthy community. 14 | 15 | ## Our Standards 16 | 17 | Examples of behavior that contributes to a positive environment for our 18 | community include: 19 | 20 | * Demonstrating empathy and kindness toward other people 21 | * Being respectful of differing opinions, viewpoints, and experiences 22 | * Giving and gracefully accepting constructive feedback 23 | * Accepting responsibility and apologizing to those affected by our mistakes, 24 | and learning from the experience 25 | * Focusing on what is best not just for us as individuals, but for the 26 | overall community 27 | 28 | Examples of unacceptable behavior include: 29 | 30 | * The use of sexualized language or imagery, and sexual attention or 31 | advances of any kind 32 | * Trolling, insulting or derogatory comments, and personal or political attacks 33 | * Public or private harassment 34 | * Publishing others' private information, such as a physical or email 35 | address, without their explicit permission 36 | * Other conduct which could reasonably be considered inappropriate in a 37 | professional setting 38 | 39 | ## Enforcement Responsibilities 40 | 41 | Community leaders are responsible for clarifying and enforcing our standards of 42 | acceptable behavior and will take appropriate and fair corrective action in 43 | response to any behavior that they deem inappropriate, threatening, offensive, 44 | or harmful. 45 | 46 | Community leaders have the right and responsibility to remove, edit, or reject 47 | comments, commits, code, wiki edits, issues, and other contributions that are 48 | not aligned to this Code of Conduct, and will communicate reasons for moderation 49 | decisions when appropriate. 50 | 51 | ## Scope 52 | 53 | This Code of Conduct applies within all community spaces, and also applies when 54 | an individual is officially representing the community in public spaces. 55 | Examples of representing our community include using an official e-mail address, 56 | posting via an official social media account, or acting as an appointed 57 | representative at an online or offline event. 58 | 59 | ## Enforcement 60 | 61 | Instances of abusive, harassing, or otherwise unacceptable behavior may be 62 | reported to the community leaders responsible for enforcement at 63 | . 64 | All complaints will be reviewed and investigated promptly and fairly. 65 | 66 | All community leaders are obligated to respect the privacy and security of the 67 | reporter of any incident. 68 | 69 | ## Enforcement Guidelines 70 | 71 | Community leaders will follow these Community Impact Guidelines in determining 72 | the consequences for any action they deem in violation of this Code of Conduct: 73 | 74 | ### 1. Correction 75 | 76 | **Community Impact**: Use of inappropriate language or other behavior deemed 77 | unprofessional or unwelcome in the community. 78 | 79 | **Consequence**: A private, written warning from community leaders, providing 80 | clarity around the nature of the violation and an explanation of why the 81 | behavior was inappropriate. A public apology may be requested. 82 | 83 | ### 2. Warning 84 | 85 | **Community Impact**: A violation through a single incident or series 86 | of actions. 87 | 88 | **Consequence**: A warning with consequences for continued behavior. No 89 | interaction with the people involved, including unsolicited interaction with 90 | those enforcing the Code of Conduct, for a specified period of time. This 91 | includes avoiding interactions in community spaces as well as external channels 92 | like social media. Violating these terms may lead to a temporary or 93 | permanent ban. 94 | 95 | ### 3. Temporary Ban 96 | 97 | **Community Impact**: A serious violation of community standards, including 98 | sustained inappropriate behavior. 99 | 100 | **Consequence**: A temporary ban from any sort of interaction or public 101 | communication with the community for a specified period of time. No public or 102 | private interaction with the people involved, including unsolicited interaction 103 | with those enforcing the Code of Conduct, is allowed during this period. 104 | Violating these terms may lead to a permanent ban. 105 | 106 | ### 4. Permanent Ban 107 | 108 | **Community Impact**: Demonstrating a pattern of violation of community 109 | standards, including sustained inappropriate behavior, harassment of an 110 | individual, or aggression toward or disparagement of classes of individuals. 111 | 112 | **Consequence**: A permanent ban from any sort of public interaction within 113 | the community. 114 | 115 | ## Attribution 116 | 117 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], 118 | version 2.0, available at 119 | https://www.contributor-covenant.org/version/2/0/code_of_conduct.html. 120 | 121 | Community Impact Guidelines were inspired by [Mozilla's code of conduct 122 | enforcement ladder](https://github.com/mozilla/diversity). 123 | 124 | [homepage]: https://www.contributor-covenant.org 125 | 126 | For answers to common questions about this code of conduct, see the FAQ at 127 | https://www.contributor-covenant.org/faq. Translations are available at 128 | https://www.contributor-covenant.org/translations. 129 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # How to Contribute 2 | 3 | 4 | ## Reporting a bug 5 | 6 | * **Do not open up a GitHub issue if the bug is a security vulnerability**, and instead to refer to our [Security policy](SECURITY.md). 7 | 8 | * Ensure the bug was not already reported by searching on GitHub Issues. 9 | 10 | * If you're unable to find an open issue addressing the problem, open a new one. Be sure to include a **title and clear description**, as much relevant information as possible, and a **code sample** or an **executable test case** demonstrating the expected behavior that is not occurring. 11 | 12 | 13 | ## Submitting a bug fix 14 | 15 | * Open a new GitHub pull request with the patch. 16 | 17 | * Ensure the PR description clearly describes the problem and solution. Include the relevant issue number if applicable. 18 | 19 | * Ensure the new code is following the existing conventions and the unit test coverage is 100%. 20 | 21 | * Before submitting, please run the following command locally to ensure the code is passing the automatic checks: `make buildall`. 22 | 23 | 24 | ## Add a new feature or change an existing one 25 | 26 | * Before writing any code please suggest the change by opening a new Feature Request on Issues. 27 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | ********************************************************************** 2 | * LICENSE 3 | * 4 | * SOFTWARE : tc-lib-pdf-parser 5 | * AUTHOR : Nicola Asuni 6 | * COPYRIGHT : 2011-2025 Nicola Asuni - Tecnick.com LTD 7 | ********************************************************************** 8 | 9 | This is free software: you can redistribute it and/or modify it 10 | under the terms of the GNU Lesser General Public License as 11 | published by the Free Software Foundation, either version 3 of the 12 | License, or (at your option) any later version. 13 | 14 | ********************************************************************** 15 | ********************************************************************** 16 | 17 | GNU LESSER GENERAL PUBLIC LICENSE 18 | Version 3, 29 June 2007 19 | 20 | Copyright (C) 2007 Free Software Foundation, Inc. 21 | Everyone is permitted to copy and distribute verbatim copies 22 | of this license document, but changing it is not allowed. 23 | 24 | 25 | This version of the GNU Lesser General Public License incorporates 26 | the terms and conditions of version 3 of the GNU General Public 27 | License, supplemented by the additional permissions listed below. 28 | 29 | 0. Additional Definitions. 30 | 31 | As used herein, "this License" refers to version 3 of the GNU Lesser 32 | General Public License, and the "GNU GPL" refers to version 3 of the GNU 33 | General Public License. 34 | 35 | "The Library" refers to a covered work governed by this License, 36 | other than an Application or a Combined Work as defined below. 37 | 38 | An "Application" is any work that makes use of an interface provided 39 | by the Library, but which is not otherwise based on the Library. 40 | Defining a subclass of a class defined by the Library is deemed a mode 41 | of using an interface provided by the Library. 42 | 43 | A "Combined Work" is a work produced by combining or linking an 44 | Application with the Library. The particular version of the Library 45 | with which the Combined Work was made is also called the "Linked 46 | Version". 47 | 48 | The "Minimal Corresponding Source" for a Combined Work means the 49 | Corresponding Source for the Combined Work, excluding any source code 50 | for portions of the Combined Work that, considered in isolation, are 51 | based on the Application, and not on the Linked Version. 52 | 53 | The "Corresponding Application Code" for a Combined Work means the 54 | object code and/or source code for the Application, including any data 55 | and utility programs needed for reproducing the Combined Work from the 56 | Application, but excluding the System Libraries of the Combined Work. 57 | 58 | 1. Exception to Section 3 of the GNU GPL. 59 | 60 | You may convey a covered work under sections 3 and 4 of this License 61 | without being bound by section 3 of the GNU GPL. 62 | 63 | 2. Conveying Modified Versions. 64 | 65 | If you modify a copy of the Library, and, in your modifications, a 66 | facility refers to a function or data to be supplied by an Application 67 | that uses the facility (other than as an argument passed when the 68 | facility is invoked), then you may convey a copy of the modified 69 | version: 70 | 71 | a) under this License, provided that you make a good faith effort to 72 | ensure that, in the event an Application does not supply the 73 | function or data, the facility still operates, and performs 74 | whatever part of its purpose remains meaningful, or 75 | 76 | b) under the GNU GPL, with none of the additional permissions of 77 | this License applicable to that copy. 78 | 79 | 3. Object Code Incorporating Material from Library Header Files. 80 | 81 | The object code form of an Application may incorporate material from 82 | a header file that is part of the Library. You may convey such object 83 | code under terms of your choice, provided that, if the incorporated 84 | material is not limited to numerical parameters, data structure 85 | layouts and accessors, or small macros, inline functions and templates 86 | (ten or fewer lines in length), you do both of the following: 87 | 88 | a) Give prominent notice with each copy of the object code that the 89 | Library is used in it and that the Library and its use are 90 | covered by this License. 91 | 92 | b) Accompany the object code with a copy of the GNU GPL and this license 93 | document. 94 | 95 | 4. Combined Works. 96 | 97 | You may convey a Combined Work under terms of your choice that, 98 | taken together, effectively do not restrict modification of the 99 | portions of the Library contained in the Combined Work and reverse 100 | engineering for debugging such modifications, if you also do each of 101 | the following: 102 | 103 | a) Give prominent notice with each copy of the Combined Work that 104 | the Library is used in it and that the Library and its use are 105 | covered by this License. 106 | 107 | b) Accompany the Combined Work with a copy of the GNU GPL and this license 108 | document. 109 | 110 | c) For a Combined Work that displays copyright notices during 111 | execution, include the copyright notice for the Library among 112 | these notices, as well as a reference directing the user to the 113 | copies of the GNU GPL and this license document. 114 | 115 | d) Do one of the following: 116 | 117 | 0) Convey the Minimal Corresponding Source under the terms of this 118 | License, and the Corresponding Application Code in a form 119 | suitable for, and under terms that permit, the user to 120 | recombine or relink the Application with a modified version of 121 | the Linked Version to produce a modified Combined Work, in the 122 | manner specified by section 6 of the GNU GPL for conveying 123 | Corresponding Source. 124 | 125 | 1) Use a suitable shared library mechanism for linking with the 126 | Library. A suitable mechanism is one that (a) uses at run time 127 | a copy of the Library already present on the user's computer 128 | system, and (b) will operate properly with a modified version 129 | of the Library that is interface-compatible with the Linked 130 | Version. 131 | 132 | e) Provide Installation Information, but only if you would otherwise 133 | be required to provide such information under section 6 of the 134 | GNU GPL, and only to the extent that such information is 135 | necessary to install and execute a modified version of the 136 | Combined Work produced by recombining or relinking the 137 | Application with a modified version of the Linked Version. (If 138 | you use option 4d0, the Installation Information must accompany 139 | the Minimal Corresponding Source and Corresponding Application 140 | Code. If you use option 4d1, you must provide the Installation 141 | Information in the manner specified by section 6 of the GNU GPL 142 | for conveying Corresponding Source.) 143 | 144 | 5. Combined Libraries. 145 | 146 | You may place library facilities that are a work based on the 147 | Library side by side in a single library together with other library 148 | facilities that are not Applications and are not covered by this 149 | License, and convey such a combined library under terms of your 150 | choice, if you do both of the following: 151 | 152 | a) Accompany the combined library with a copy of the same work based 153 | on the Library, uncombined with any other library facilities, 154 | conveyed under the terms of this License. 155 | 156 | b) Give prominent notice with the combined library that part of it 157 | is a work based on the Library, and explaining where to find the 158 | accompanying uncombined form of the same work. 159 | 160 | 6. Revised Versions of the GNU Lesser General Public License. 161 | 162 | The Free Software Foundation may publish revised and/or new versions 163 | of the GNU Lesser General Public License from time to time. Such new 164 | versions will be similar in spirit to the present version, but may 165 | differ in detail to address new problems or concerns. 166 | 167 | Each version is given a distinguishing version number. If the 168 | Library as you received it specifies that a certain numbered version 169 | of the GNU Lesser General Public License "or any later version" 170 | applies to it, you have the option of following the terms and 171 | conditions either of that published version or of any later version 172 | published by the Free Software Foundation. If the Library as you 173 | received it does not specify a version number of the GNU Lesser 174 | General Public License, you may choose any version of the GNU Lesser 175 | General Public License ever published by the Free Software Foundation. 176 | 177 | If the Library as you received it specifies that a proxy can decide 178 | whether future versions of the GNU Lesser General Public License shall 179 | apply, that proxy's public statement of acceptance of any version is 180 | permanent authorization for you to choose that version for the 181 | Library. 182 | 183 | ********************************************************************** 184 | ********************************************************************** 185 | 186 | GNU GENERAL PUBLIC LICENSE 187 | Version 3, 29 June 2007 188 | 189 | Copyright (C) 2007 Free Software Foundation, Inc. 190 | Everyone is permitted to copy and distribute verbatim copies 191 | of this license document, but changing it is not allowed. 192 | 193 | Preamble 194 | 195 | The GNU General Public License is a free, copyleft license for 196 | software and other kinds of works. 197 | 198 | The licenses for most software and other practical works are designed 199 | to take away your freedom to share and change the works. By contrast, 200 | the GNU General Public License is intended to guarantee your freedom to 201 | share and change all versions of a program--to make sure it remains free 202 | software for all its users. We, the Free Software Foundation, use the 203 | GNU General Public License for most of our software; it applies also to 204 | any other work released this way by its authors. You can apply it to 205 | your programs, too. 206 | 207 | When we speak of free software, we are referring to freedom, not 208 | price. Our General Public Licenses are designed to make sure that you 209 | have the freedom to distribute copies of free software (and charge for 210 | them if you wish), that you receive source code or can get it if you 211 | want it, that you can change the software or use pieces of it in new 212 | free programs, and that you know you can do these things. 213 | 214 | To protect your rights, we need to prevent others from denying you 215 | these rights or asking you to surrender the rights. Therefore, you have 216 | certain responsibilities if you distribute copies of the software, or if 217 | you modify it: responsibilities to respect the freedom of others. 218 | 219 | For example, if you distribute copies of such a program, whether 220 | gratis or for a fee, you must pass on to the recipients the same 221 | freedoms that you received. You must make sure that they, too, receive 222 | or can get the source code. And you must show them these terms so they 223 | know their rights. 224 | 225 | Developers that use the GNU GPL protect your rights with two steps: 226 | (1) assert copyright on the software, and (2) offer you this License 227 | giving you legal permission to copy, distribute and/or modify it. 228 | 229 | For the developers' and authors' protection, the GPL clearly explains 230 | that there is no warranty for this free software. For both users' and 231 | authors' sake, the GPL requires that modified versions be marked as 232 | changed, so that their problems will not be attributed erroneously to 233 | authors of previous versions. 234 | 235 | Some devices are designed to deny users access to install or run 236 | modified versions of the software inside them, although the manufacturer 237 | can do so. This is fundamentally incompatible with the aim of 238 | protecting users' freedom to change the software. The systematic 239 | pattern of such abuse occurs in the area of products for individuals to 240 | use, which is precisely where it is most unacceptable. Therefore, we 241 | have designed this version of the GPL to prohibit the practice for those 242 | products. If such problems arise substantially in other domains, we 243 | stand ready to extend this provision to those domains in future versions 244 | of the GPL, as needed to protect the freedom of users. 245 | 246 | Finally, every program is threatened constantly by software patents. 247 | States should not allow patents to restrict development and use of 248 | software on general-purpose computers, but in those that do, we wish to 249 | avoid the special danger that patents applied to a free program could 250 | make it effectively proprietary. To prevent this, the GPL assures that 251 | patents cannot be used to render the program non-free. 252 | 253 | The precise terms and conditions for copying, distribution and 254 | modification follow. 255 | 256 | TERMS AND CONDITIONS 257 | 258 | 0. Definitions. 259 | 260 | "This License" refers to version 3 of the GNU General Public License. 261 | 262 | "Copyright" also means copyright-like laws that apply to other kinds of 263 | works, such as semiconductor masks. 264 | 265 | "The Program" refers to any copyrightable work licensed under this 266 | License. Each licensee is addressed as "you". "Licensees" and 267 | "recipients" may be individuals or organizations. 268 | 269 | To "modify" a work means to copy from or adapt all or part of the work 270 | in a fashion requiring copyright permission, other than the making of an 271 | exact copy. The resulting work is called a "modified version" of the 272 | earlier work or a work "based on" the earlier work. 273 | 274 | A "covered work" means either the unmodified Program or a work based 275 | on the Program. 276 | 277 | To "propagate" a work means to do anything with it that, without 278 | permission, would make you directly or secondarily liable for 279 | infringement under applicable copyright law, except executing it on a 280 | computer or modifying a private copy. Propagation includes copying, 281 | distribution (with or without modification), making available to the 282 | public, and in some countries other activities as well. 283 | 284 | To "convey" a work means any kind of propagation that enables other 285 | parties to make or receive copies. Mere interaction with a user through 286 | a computer network, with no transfer of a copy, is not conveying. 287 | 288 | An interactive user interface displays "Appropriate Legal Notices" 289 | to the extent that it includes a convenient and prominently visible 290 | feature that (1) displays an appropriate copyright notice, and (2) 291 | tells the user that there is no warranty for the work (except to the 292 | extent that warranties are provided), that licensees may convey the 293 | work under this License, and how to view a copy of this License. If 294 | the interface presents a list of user commands or options, such as a 295 | menu, a prominent item in the list meets this criterion. 296 | 297 | 1. Source Code. 298 | 299 | The "source code" for a work means the preferred form of the work 300 | for making modifications to it. "Object code" means any non-source 301 | form of a work. 302 | 303 | A "Standard Interface" means an interface that either is an official 304 | standard defined by a recognized standards body, or, in the case of 305 | interfaces specified for a particular programming language, one that 306 | is widely used among developers working in that language. 307 | 308 | The "System Libraries" of an executable work include anything, other 309 | than the work as a whole, that (a) is included in the normal form of 310 | packaging a Major Component, but which is not part of that Major 311 | Component, and (b) serves only to enable use of the work with that 312 | Major Component, or to implement a Standard Interface for which an 313 | implementation is available to the public in source code form. A 314 | "Major Component", in this context, means a major essential component 315 | (kernel, window system, and so on) of the specific operating system 316 | (if any) on which the executable work runs, or a compiler used to 317 | produce the work, or an object code interpreter used to run it. 318 | 319 | The "Corresponding Source" for a work in object code form means all 320 | the source code needed to generate, install, and (for an executable 321 | work) run the object code and to modify the work, including scripts to 322 | control those activities. However, it does not include the work's 323 | System Libraries, or general-purpose tools or generally available free 324 | programs which are used unmodified in performing those activities but 325 | which are not part of the work. For example, Corresponding Source 326 | includes interface definition files associated with source files for 327 | the work, and the source code for shared libraries and dynamically 328 | linked subprograms that the work is specifically designed to require, 329 | such as by intimate data communication or control flow between those 330 | subprograms and other parts of the work. 331 | 332 | The Corresponding Source need not include anything that users 333 | can regenerate automatically from other parts of the Corresponding 334 | Source. 335 | 336 | The Corresponding Source for a work in source code form is that 337 | same work. 338 | 339 | 2. Basic Permissions. 340 | 341 | All rights granted under this License are granted for the term of 342 | copyright on the Program, and are irrevocable provided the stated 343 | conditions are met. This License explicitly affirms your unlimited 344 | permission to run the unmodified Program. The output from running a 345 | covered work is covered by this License only if the output, given its 346 | content, constitutes a covered work. This License acknowledges your 347 | rights of fair use or other equivalent, as provided by copyright law. 348 | 349 | You may make, run and propagate covered works that you do not 350 | convey, without conditions so long as your license otherwise remains 351 | in force. You may convey covered works to others for the sole purpose 352 | of having them make modifications exclusively for you, or provide you 353 | with facilities for running those works, provided that you comply with 354 | the terms of this License in conveying all material for which you do 355 | not control copyright. Those thus making or running the covered works 356 | for you must do so exclusively on your behalf, under your direction 357 | and control, on terms that prohibit them from making any copies of 358 | your copyrighted material outside their relationship with you. 359 | 360 | Conveying under any other circumstances is permitted solely under 361 | the conditions stated below. Sublicensing is not allowed; section 10 362 | makes it unnecessary. 363 | 364 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 365 | 366 | No covered work shall be deemed part of an effective technological 367 | measure under any applicable law fulfilling obligations under article 368 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 369 | similar laws prohibiting or restricting circumvention of such 370 | measures. 371 | 372 | When you convey a covered work, you waive any legal power to forbid 373 | circumvention of technological measures to the extent such circumvention 374 | is effected by exercising rights under this License with respect to 375 | the covered work, and you disclaim any intention to limit operation or 376 | modification of the work as a means of enforcing, against the work's 377 | users, your or third parties' legal rights to forbid circumvention of 378 | technological measures. 379 | 380 | 4. Conveying Verbatim Copies. 381 | 382 | You may convey verbatim copies of the Program's source code as you 383 | receive it, in any medium, provided that you conspicuously and 384 | appropriately publish on each copy an appropriate copyright notice; 385 | keep intact all notices stating that this License and any 386 | non-permissive terms added in accord with section 7 apply to the code; 387 | keep intact all notices of the absence of any warranty; and give all 388 | recipients a copy of this License along with the Program. 389 | 390 | You may charge any price or no price for each copy that you convey, 391 | and you may offer support or warranty protection for a fee. 392 | 393 | 5. Conveying Modified Source Versions. 394 | 395 | You may convey a work based on the Program, or the modifications to 396 | produce it from the Program, in the form of source code under the 397 | terms of section 4, provided that you also meet all of these conditions: 398 | 399 | a) The work must carry prominent notices stating that you modified 400 | it, and giving a relevant date. 401 | 402 | b) The work must carry prominent notices stating that it is 403 | released under this License and any conditions added under section 404 | 7. This requirement modifies the requirement in section 4 to 405 | "keep intact all notices". 406 | 407 | c) You must license the entire work, as a whole, under this 408 | License to anyone who comes into possession of a copy. This 409 | License will therefore apply, along with any applicable section 7 410 | additional terms, to the whole of the work, and all its parts, 411 | regardless of how they are packaged. This License gives no 412 | permission to license the work in any other way, but it does not 413 | invalidate such permission if you have separately received it. 414 | 415 | d) If the work has interactive user interfaces, each must display 416 | Appropriate Legal Notices; however, if the Program has interactive 417 | interfaces that do not display Appropriate Legal Notices, your 418 | work need not make them do so. 419 | 420 | A compilation of a covered work with other separate and independent 421 | works, which are not by their nature extensions of the covered work, 422 | and which are not combined with it such as to form a larger program, 423 | in or on a volume of a storage or distribution medium, is called an 424 | "aggregate" if the compilation and its resulting copyright are not 425 | used to limit the access or legal rights of the compilation's users 426 | beyond what the individual works permit. Inclusion of a covered work 427 | in an aggregate does not cause this License to apply to the other 428 | parts of the aggregate. 429 | 430 | 6. Conveying Non-Source Forms. 431 | 432 | You may convey a covered work in object code form under the terms 433 | of sections 4 and 5, provided that you also convey the 434 | machine-readable Corresponding Source under the terms of this License, 435 | in one of these ways: 436 | 437 | a) Convey the object code in, or embodied in, a physical product 438 | (including a physical distribution medium), accompanied by the 439 | Corresponding Source fixed on a durable physical medium 440 | customarily used for software interchange. 441 | 442 | b) Convey the object code in, or embodied in, a physical product 443 | (including a physical distribution medium), accompanied by a 444 | written offer, valid for at least three years and valid for as 445 | long as you offer spare parts or customer support for that product 446 | model, to give anyone who possesses the object code either (1) a 447 | copy of the Corresponding Source for all the software in the 448 | product that is covered by this License, on a durable physical 449 | medium customarily used for software interchange, for a price no 450 | more than your reasonable cost of physically performing this 451 | conveying of source, or (2) access to copy the 452 | Corresponding Source from a network server at no charge. 453 | 454 | c) Convey individual copies of the object code with a copy of the 455 | written offer to provide the Corresponding Source. This 456 | alternative is allowed only occasionally and noncommercially, and 457 | only if you received the object code with such an offer, in accord 458 | with subsection 6b. 459 | 460 | d) Convey the object code by offering access from a designated 461 | place (gratis or for a charge), and offer equivalent access to the 462 | Corresponding Source in the same way through the same place at no 463 | further charge. You need not require recipients to copy the 464 | Corresponding Source along with the object code. If the place to 465 | copy the object code is a network server, the Corresponding Source 466 | may be on a different server (operated by you or a third party) 467 | that supports equivalent copying facilities, provided you maintain 468 | clear directions next to the object code saying where to find the 469 | Corresponding Source. Regardless of what server hosts the 470 | Corresponding Source, you remain obligated to ensure that it is 471 | available for as long as needed to satisfy these requirements. 472 | 473 | e) Convey the object code using peer-to-peer transmission, provided 474 | you inform other peers where the object code and Corresponding 475 | Source of the work are being offered to the general public at no 476 | charge under subsection 6d. 477 | 478 | A separable portion of the object code, whose source code is excluded 479 | from the Corresponding Source as a System Library, need not be 480 | included in conveying the object code work. 481 | 482 | A "User Product" is either (1) a "consumer product", which means any 483 | tangible personal property which is normally used for personal, family, 484 | or household purposes, or (2) anything designed or sold for incorporation 485 | into a dwelling. In determining whether a product is a consumer product, 486 | doubtful cases shall be resolved in favor of coverage. For a particular 487 | product received by a particular user, "normally used" refers to a 488 | typical or common use of that class of product, regardless of the status 489 | of the particular user or of the way in which the particular user 490 | actually uses, or expects or is expected to use, the product. A product 491 | is a consumer product regardless of whether the product has substantial 492 | commercial, industrial or non-consumer uses, unless such uses represent 493 | the only significant mode of use of the product. 494 | 495 | "Installation Information" for a User Product means any methods, 496 | procedures, authorization keys, or other information required to install 497 | and execute modified versions of a covered work in that User Product from 498 | a modified version of its Corresponding Source. The information must 499 | suffice to ensure that the continued functioning of the modified object 500 | code is in no case prevented or interfered with solely because 501 | modification has been made. 502 | 503 | If you convey an object code work under this section in, or with, or 504 | specifically for use in, a User Product, and the conveying occurs as 505 | part of a transaction in which the right of possession and use of the 506 | User Product is transferred to the recipient in perpetuity or for a 507 | fixed term (regardless of how the transaction is characterized), the 508 | Corresponding Source conveyed under this section must be accompanied 509 | by the Installation Information. But this requirement does not apply 510 | if neither you nor any third party retains the ability to install 511 | modified object code on the User Product (for example, the work has 512 | been installed in ROM). 513 | 514 | The requirement to provide Installation Information does not include a 515 | requirement to continue to provide support service, warranty, or updates 516 | for a work that has been modified or installed by the recipient, or for 517 | the User Product in which it has been modified or installed. Access to a 518 | network may be denied when the modification itself materially and 519 | adversely affects the operation of the network or violates the rules and 520 | protocols for communication across the network. 521 | 522 | Corresponding Source conveyed, and Installation Information provided, 523 | in accord with this section must be in a format that is publicly 524 | documented (and with an implementation available to the public in 525 | source code form), and must require no special password or key for 526 | unpacking, reading or copying. 527 | 528 | 7. Additional Terms. 529 | 530 | "Additional permissions" are terms that supplement the terms of this 531 | License by making exceptions from one or more of its conditions. 532 | Additional permissions that are applicable to the entire Program shall 533 | be treated as though they were included in this License, to the extent 534 | that they are valid under applicable law. If additional permissions 535 | apply only to part of the Program, that part may be used separately 536 | under those permissions, but the entire Program remains governed by 537 | this License without regard to the additional permissions. 538 | 539 | When you convey a copy of a covered work, you may at your option 540 | remove any additional permissions from that copy, or from any part of 541 | it. (Additional permissions may be written to require their own 542 | removal in certain cases when you modify the work.) You may place 543 | additional permissions on material, added by you to a covered work, 544 | for which you have or can give appropriate copyright permission. 545 | 546 | Notwithstanding any other provision of this License, for material you 547 | add to a covered work, you may (if authorized by the copyright holders of 548 | that material) supplement the terms of this License with terms: 549 | 550 | a) Disclaiming warranty or limiting liability differently from the 551 | terms of sections 15 and 16 of this License; or 552 | 553 | b) Requiring preservation of specified reasonable legal notices or 554 | author attributions in that material or in the Appropriate Legal 555 | Notices displayed by works containing it; or 556 | 557 | c) Prohibiting misrepresentation of the origin of that material, or 558 | requiring that modified versions of such material be marked in 559 | reasonable ways as different from the original version; or 560 | 561 | d) Limiting the use for publicity purposes of names of licensors or 562 | authors of the material; or 563 | 564 | e) Declining to grant rights under trademark law for use of some 565 | trade names, trademarks, or service marks; or 566 | 567 | f) Requiring indemnification of licensors and authors of that 568 | material by anyone who conveys the material (or modified versions of 569 | it) with contractual assumptions of liability to the recipient, for 570 | any liability that these contractual assumptions directly impose on 571 | those licensors and authors. 572 | 573 | All other non-permissive additional terms are considered "further 574 | restrictions" within the meaning of section 10. If the Program as you 575 | received it, or any part of it, contains a notice stating that it is 576 | governed by this License along with a term that is a further 577 | restriction, you may remove that term. If a license document contains 578 | a further restriction but permits relicensing or conveying under this 579 | License, you may add to a covered work material governed by the terms 580 | of that license document, provided that the further restriction does 581 | not survive such relicensing or conveying. 582 | 583 | If you add terms to a covered work in accord with this section, you 584 | must place, in the relevant source files, a statement of the 585 | additional terms that apply to those files, or a notice indicating 586 | where to find the applicable terms. 587 | 588 | Additional terms, permissive or non-permissive, may be stated in the 589 | form of a separately written license, or stated as exceptions; 590 | the above requirements apply either way. 591 | 592 | 8. Termination. 593 | 594 | You may not propagate or modify a covered work except as expressly 595 | provided under this License. Any attempt otherwise to propagate or 596 | modify it is void, and will automatically terminate your rights under 597 | this License (including any patent licenses granted under the third 598 | paragraph of section 11). 599 | 600 | However, if you cease all violation of this License, then your 601 | license from a particular copyright holder is reinstated (a) 602 | provisionally, unless and until the copyright holder explicitly and 603 | finally terminates your license, and (b) permanently, if the copyright 604 | holder fails to notify you of the violation by some reasonable means 605 | prior to 60 days after the cessation. 606 | 607 | Moreover, your license from a particular copyright holder is 608 | reinstated permanently if the copyright holder notifies you of the 609 | violation by some reasonable means, this is the first time you have 610 | received notice of violation of this License (for any work) from that 611 | copyright holder, and you cure the violation prior to 30 days after 612 | your receipt of the notice. 613 | 614 | Termination of your rights under this section does not terminate the 615 | licenses of parties who have received copies or rights from you under 616 | this License. If your rights have been terminated and not permanently 617 | reinstated, you do not qualify to receive new licenses for the same 618 | material under section 10. 619 | 620 | 9. Acceptance Not Required for Having Copies. 621 | 622 | You are not required to accept this License in order to receive or 623 | run a copy of the Program. Ancillary propagation of a covered work 624 | occurring solely as a consequence of using peer-to-peer transmission 625 | to receive a copy likewise does not require acceptance. However, 626 | nothing other than this License grants you permission to propagate or 627 | modify any covered work. These actions infringe copyright if you do 628 | not accept this License. Therefore, by modifying or propagating a 629 | covered work, you indicate your acceptance of this License to do so. 630 | 631 | 10. Automatic Licensing of Downstream Recipients. 632 | 633 | Each time you convey a covered work, the recipient automatically 634 | receives a license from the original licensors, to run, modify and 635 | propagate that work, subject to this License. You are not responsible 636 | for enforcing compliance by third parties with this License. 637 | 638 | An "entity transaction" is a transaction transferring control of an 639 | organization, or substantially all assets of one, or subdividing an 640 | organization, or merging organizations. If propagation of a covered 641 | work results from an entity transaction, each party to that 642 | transaction who receives a copy of the work also receives whatever 643 | licenses to the work the party's predecessor in interest had or could 644 | give under the previous paragraph, plus a right to possession of the 645 | Corresponding Source of the work from the predecessor in interest, if 646 | the predecessor has it or can get it with reasonable efforts. 647 | 648 | You may not impose any further restrictions on the exercise of the 649 | rights granted or affirmed under this License. For example, you may 650 | not impose a license fee, royalty, or other charge for exercise of 651 | rights granted under this License, and you may not initiate litigation 652 | (including a cross-claim or counterclaim in a lawsuit) alleging that 653 | any patent claim is infringed by making, using, selling, offering for 654 | sale, or importing the Program or any portion of it. 655 | 656 | 11. Patents. 657 | 658 | A "contributor" is a copyright holder who authorizes use under this 659 | License of the Program or a work on which the Program is based. The 660 | work thus licensed is called the contributor's "contributor version". 661 | 662 | A contributor's "essential patent claims" are all patent claims 663 | owned or controlled by the contributor, whether already acquired or 664 | hereafter acquired, that would be infringed by some manner, permitted 665 | by this License, of making, using, or selling its contributor version, 666 | but do not include claims that would be infringed only as a 667 | consequence of further modification of the contributor version. For 668 | purposes of this definition, "control" includes the right to grant 669 | patent sublicenses in a manner consistent with the requirements of 670 | this License. 671 | 672 | Each contributor grants you a non-exclusive, worldwide, royalty-free 673 | patent license under the contributor's essential patent claims, to 674 | make, use, sell, offer for sale, import and otherwise run, modify and 675 | propagate the contents of its contributor version. 676 | 677 | In the following three paragraphs, a "patent license" is any express 678 | agreement or commitment, however denominated, not to enforce a patent 679 | (such as an express permission to practice a patent or covenant not to 680 | sue for patent infringement). To "grant" such a patent license to a 681 | party means to make such an agreement or commitment not to enforce a 682 | patent against the party. 683 | 684 | If you convey a covered work, knowingly relying on a patent license, 685 | and the Corresponding Source of the work is not available for anyone 686 | to copy, free of charge and under the terms of this License, through a 687 | publicly available network server or other readily accessible means, 688 | then you must either (1) cause the Corresponding Source to be so 689 | available, or (2) arrange to deprive yourself of the benefit of the 690 | patent license for this particular work, or (3) arrange, in a manner 691 | consistent with the requirements of this License, to extend the patent 692 | license to downstream recipients. "Knowingly relying" means you have 693 | actual knowledge that, but for the patent license, your conveying the 694 | covered work in a country, or your recipient's use of the covered work 695 | in a country, would infringe one or more identifiable patents in that 696 | country that you have reason to believe are valid. 697 | 698 | If, pursuant to or in connection with a single transaction or 699 | arrangement, you convey, or propagate by procuring conveyance of, a 700 | covered work, and grant a patent license to some of the parties 701 | receiving the covered work authorizing them to use, propagate, modify 702 | or convey a specific copy of the covered work, then the patent license 703 | you grant is automatically extended to all recipients of the covered 704 | work and works based on it. 705 | 706 | A patent license is "discriminatory" if it does not include within 707 | the scope of its coverage, prohibits the exercise of, or is 708 | conditioned on the non-exercise of one or more of the rights that are 709 | specifically granted under this License. You may not convey a covered 710 | work if you are a party to an arrangement with a third party that is 711 | in the business of distributing software, under which you make payment 712 | to the third party based on the extent of your activity of conveying 713 | the work, and under which the third party grants, to any of the 714 | parties who would receive the covered work from you, a discriminatory 715 | patent license (a) in connection with copies of the covered work 716 | conveyed by you (or copies made from those copies), or (b) primarily 717 | for and in connection with specific products or compilations that 718 | contain the covered work, unless you entered into that arrangement, 719 | or that patent license was granted, prior to 28 March 2007. 720 | 721 | Nothing in this License shall be construed as excluding or limiting 722 | any implied license or other defenses to infringement that may 723 | otherwise be available to you under applicable patent law. 724 | 725 | 12. No Surrender of Others' Freedom. 726 | 727 | If conditions are imposed on you (whether by court order, agreement or 728 | otherwise) that contradict the conditions of this License, they do not 729 | excuse you from the conditions of this License. If you cannot convey a 730 | covered work so as to satisfy simultaneously your obligations under this 731 | License and any other pertinent obligations, then as a consequence you may 732 | not convey it at all. For example, if you agree to terms that obligate you 733 | to collect a royalty for further conveying from those to whom you convey 734 | the Program, the only way you could satisfy both those terms and this 735 | License would be to refrain entirely from conveying the Program. 736 | 737 | 13. Use with the GNU Affero General Public License. 738 | 739 | Notwithstanding any other provision of this License, you have 740 | permission to link or combine any covered work with a work licensed 741 | under version 3 of the GNU Affero General Public License into a single 742 | combined work, and to convey the resulting work. The terms of this 743 | License will continue to apply to the part which is the covered work, 744 | but the special requirements of the GNU Affero General Public License, 745 | section 13, concerning interaction through a network will apply to the 746 | combination as such. 747 | 748 | 14. Revised Versions of this License. 749 | 750 | The Free Software Foundation may publish revised and/or new versions of 751 | the GNU General Public License from time to time. Such new versions will 752 | be similar in spirit to the present version, but may differ in detail to 753 | address new problems or concerns. 754 | 755 | Each version is given a distinguishing version number. If the 756 | Program specifies that a certain numbered version of the GNU General 757 | Public License "or any later version" applies to it, you have the 758 | option of following the terms and conditions either of that numbered 759 | version or of any later version published by the Free Software 760 | Foundation. If the Program does not specify a version number of the 761 | GNU General Public License, you may choose any version ever published 762 | by the Free Software Foundation. 763 | 764 | If the Program specifies that a proxy can decide which future 765 | versions of the GNU General Public License can be used, that proxy's 766 | public statement of acceptance of a version permanently authorizes you 767 | to choose that version for the Program. 768 | 769 | Later license versions may give you additional or different 770 | permissions. However, no additional obligations are imposed on any 771 | author or copyright holder as a result of your choosing to follow a 772 | later version. 773 | 774 | 15. Disclaimer of Warranty. 775 | 776 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 777 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 778 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 779 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 780 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 781 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 782 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 783 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 784 | 785 | 16. Limitation of Liability. 786 | 787 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 788 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 789 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 790 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 791 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 792 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 793 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 794 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 795 | SUCH DAMAGES. 796 | 797 | 17. Interpretation of Sections 15 and 16. 798 | 799 | If the disclaimer of warranty and limitation of liability provided 800 | above cannot be given local legal effect according to their terms, 801 | reviewing courts shall apply local law that most closely approximates 802 | an absolute waiver of all civil liability in connection with the 803 | Program, unless a warranty or assumption of liability accompanies a 804 | copy of the Program in return for a fee. 805 | 806 | END OF TERMS AND CONDITIONS 807 | 808 | How to Apply These Terms to Your New Programs 809 | 810 | If you develop a new program, and you want it to be of the greatest 811 | possible use to the public, the best way to achieve this is to make it 812 | free software which everyone can redistribute and change under these terms. 813 | 814 | To do so, attach the following notices to the program. It is safest 815 | to attach them to the start of each source file to most effectively 816 | state the exclusion of warranty; and each file should have at least 817 | the "copyright" line and a pointer to where the full notice is found. 818 | 819 | 820 | Copyright (C) 821 | 822 | This program is free software: you can redistribute it and/or modify 823 | it under the terms of the GNU General Public License as published by 824 | the Free Software Foundation, either version 3 of the License, or 825 | (at your option) any later version. 826 | 827 | This program is distributed in the hope that it will be useful, 828 | but WITHOUT ANY WARRANTY; without even the implied warranty of 829 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 830 | GNU General Public License for more details. 831 | 832 | You should have received a copy of the GNU General Public License 833 | along with this program. If not, see . 834 | 835 | Also add information on how to contact you by electronic and paper mail. 836 | 837 | If the program does terminal interaction, make it output a short 838 | notice like this when it starts in an interactive mode: 839 | 840 | Copyright (C) 841 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 842 | This is free software, and you are welcome to redistribute it 843 | under certain conditions; type `show c' for details. 844 | 845 | The hypothetical commands `show w' and `show c' should show the appropriate 846 | parts of the General Public License. Of course, your program's commands 847 | might be different; for a GUI interface, you would use an "about box". 848 | 849 | You should also get your employer (if you work as a programmer) or school, 850 | if any, to sign a "copyright disclaimer" for the program, if necessary. 851 | For more information on this, and how to apply and follow the GNU GPL, see 852 | . 853 | 854 | The GNU General Public License does not permit incorporating your program 855 | into proprietary programs. If your program is a subroutine library, you 856 | may consider it more useful to permit linking proprietary applications with 857 | the library. If this is what you want to do, use the GNU Lesser General 858 | Public License instead of this License. But first, please read 859 | . 860 | 861 | ********************************************************************** 862 | ********************************************************************** 863 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | # makefile 2 | # 3 | # @since 2015-02-21 4 | # @category Library 5 | # @package PdfParser 6 | # @author Nicola Asuni 7 | # @copyright 2011-2024 Nicola Asuni - Tecnick.com LTD 8 | # @license http://www.gnu.org/copyleft/lesser.html GNU-LGPL v3 (see LICENSE) 9 | # @link https://github.com/tecnickcom/tc-lib-pdf-parser 10 | # 11 | # This file is part of tc-lib-pdf-parser software library. 12 | # ---------------------------------------------------------------------------------------------------------------------- 13 | 14 | SHELL=/bin/bash 15 | .SHELLFLAGS=-o pipefail -c 16 | 17 | # Project owner 18 | OWNER=tecnickcom 19 | 20 | # Project vendor 21 | VENDOR=${OWNER} 22 | 23 | # Project name 24 | PROJECT=tc-lib-pdf-parser 25 | 26 | # Project version 27 | VERSION=$(shell cat VERSION) 28 | 29 | # Project release number (packaging build number) 30 | RELEASE=$(shell cat RELEASE) 31 | 32 | # Name of RPM or DEB package 33 | PKGNAME=php-${OWNER}-${PROJECT} 34 | 35 | # Data dir 36 | DATADIR=usr/share 37 | 38 | # PHP home folder 39 | PHPHOME=${DATADIR}/php/Com/Tecnick 40 | 41 | # Default installation path for code 42 | LIBPATH=${PHPHOME}/Pdf/Parser/ 43 | 44 | # Path for configuration files (etc/$(PKGNAME)/) 45 | CONFIGPATH= 46 | 47 | # Default installation path for documentation 48 | DOCPATH=${DATADIR}/doc/$(PKGNAME)/ 49 | 50 | # Installation path for the code 51 | PATHINSTBIN=$(DESTDIR)/$(LIBPATH) 52 | 53 | # Installation path for the configuration files 54 | PATHINSTCFG=$(DESTDIR)/$(CONFIGPATH) 55 | 56 | # Installation path for documentation 57 | PATHINSTDOC=$(DESTDIR)/$(DOCPATH) 58 | 59 | # Current directory 60 | CURRENTDIR=$(dir $(realpath $(firstword $(MAKEFILE_LIST)))) 61 | 62 | # Target directory 63 | TARGETDIR=$(CURRENTDIR)target 64 | 65 | # RPM Packaging path (where RPMs will be stored) 66 | PATHRPMPKG=$(TARGETDIR)/RPM 67 | 68 | # DEB Packaging path (where DEBs will be stored) 69 | PATHDEBPKG=$(TARGETDIR)/DEB 70 | 71 | # BZ2 Packaging path (where BZ2s will be stored) 72 | PATHBZ2PKG=$(TARGETDIR)/BZ2 73 | 74 | # Default port number for the example server 75 | PORT?=8000 76 | 77 | # PHP binary 78 | PHP=$(shell which php) 79 | 80 | # Composer executable (disable APC to as a work-around of a bug) 81 | COMPOSER=$(PHP) -d "apc.enable_cli=0" $(shell which composer) 82 | 83 | # phpDocumentor executable file 84 | PHPDOC=$(shell which phpDocumentor) 85 | 86 | # --- MAKE TARGETS --- 87 | 88 | # Display general help about this command 89 | .PHONY: help 90 | help: 91 | @echo "" 92 | @echo "$(PROJECT) Makefile." 93 | @echo "The following commands are available:" 94 | @echo "" 95 | @echo " make buildall : Build and test everything from scratch" 96 | @echo " make bz2 : Package the library in a compressed bz2 archive" 97 | @echo " make clean : Delete the vendor and target directories" 98 | @echo " make codefix : Fix code style violations" 99 | @echo " make deb : Build a DEB package for Debian-like Linux distributions" 100 | @echo " make deps : Download all dependencies" 101 | @echo " make doc : Generate source code documentation" 102 | @echo " make lint : Test source code for coding standard violations" 103 | @echo " make qa : Run all tests and reports" 104 | @echo " make report : Generate various reports" 105 | @echo " make rpm : Build an RPM package for RedHat-like Linux distributions" 106 | @echo " make server : Start the development server" 107 | @echo " make test : Run unit tests" 108 | @echo " make versionup: Increase the version patch number" 109 | @echo "" 110 | @echo "To test and build everything from scratch:" 111 | @echo "make buildall" 112 | @echo "" 113 | 114 | # alias for help target 115 | .PHONY: all 116 | all: help 117 | 118 | # Full build and test sequence 119 | .PHONY: x 120 | x: buildall 121 | 122 | # Full build and test sequence 123 | .PHONY: buildall 124 | buildall: deps codefix qa bz2 rpm deb 125 | 126 | # Package the library in a compressed bz2 archive 127 | .PHONY: bz2 128 | bz2: 129 | rm -rf $(PATHBZ2PKG) 130 | make install DESTDIR=$(PATHBZ2PKG) 131 | tar -jcvf $(PATHBZ2PKG)/$(PKGNAME)-$(VERSION)-$(RELEASE).tbz2 -C $(PATHBZ2PKG) $(DATADIR) 132 | 133 | # Delete the vendor and target directories 134 | .PHONY: clean 135 | clean: 136 | rm -rf ./vendor $(TARGETDIR) 137 | 138 | # Fix code style violations 139 | .PHONY: codefix 140 | codefix: 141 | ./vendor/bin/phpcbf --ignore="./vendor/" --standard=psr12 src test 142 | 143 | # Build a DEB package for Debian-like Linux distributions 144 | .PHONY: deb 145 | deb: 146 | rm -rf $(PATHDEBPKG) 147 | make install DESTDIR=$(PATHDEBPKG)/$(PKGNAME)-$(VERSION) 148 | rm -f $(PATHDEBPKG)/$(PKGNAME)-$(VERSION)/$(DOCPATH)LICENSE 149 | tar -zcvf $(PATHDEBPKG)/$(PKGNAME)_$(VERSION).orig.tar.gz -C $(PATHDEBPKG)/ $(PKGNAME)-$(VERSION) 150 | cp -rf ./resources/debian $(PATHDEBPKG)/$(PKGNAME)-$(VERSION)/debian 151 | find $(PATHDEBPKG)/$(PKGNAME)-$(VERSION)/debian/ -type f -exec sed -i "s/~#DATE#~/`date -R`/" {} \; 152 | find $(PATHDEBPKG)/$(PKGNAME)-$(VERSION)/debian/ -type f -exec sed -i "s/~#VENDOR#~/$(VENDOR)/" {} \; 153 | find $(PATHDEBPKG)/$(PKGNAME)-$(VERSION)/debian/ -type f -exec sed -i "s/~#PROJECT#~/$(PROJECT)/" {} \; 154 | find $(PATHDEBPKG)/$(PKGNAME)-$(VERSION)/debian/ -type f -exec sed -i "s/~#PKGNAME#~/$(PKGNAME)/" {} \; 155 | find $(PATHDEBPKG)/$(PKGNAME)-$(VERSION)/debian/ -type f -exec sed -i "s/~#VERSION#~/$(VERSION)/" {} \; 156 | find $(PATHDEBPKG)/$(PKGNAME)-$(VERSION)/debian/ -type f -exec sed -i "s/~#RELEASE#~/$(RELEASE)/" {} \; 157 | echo $(LIBPATH) > $(PATHDEBPKG)/$(PKGNAME)-$(VERSION)/debian/$(PKGNAME).dirs 158 | echo "$(LIBPATH)* $(LIBPATH)" > $(PATHDEBPKG)/$(PKGNAME)-$(VERSION)/debian/install 159 | echo $(DOCPATH) >> $(PATHDEBPKG)/$(PKGNAME)-$(VERSION)/debian/$(PKGNAME).dirs 160 | echo "$(DOCPATH)* $(DOCPATH)" >> $(PATHDEBPKG)/$(PKGNAME)-$(VERSION)/debian/install 161 | ifneq ($(strip $(CONFIGPATH)),) 162 | echo $(CONFIGPATH) >> $(PATHDEBPKG)/$(PKGNAME)-$(VERSION)/debian/$(PKGNAME).dirs 163 | echo "$(CONFIGPATH)* $(CONFIGPATH)" >> $(PATHDEBPKG)/$(PKGNAME)-$(VERSION)/debian/install 164 | endif 165 | echo "new-package-should-close-itp-bug" > $(PATHDEBPKG)/$(PKGNAME)-$(VERSION)/debian/$(PKGNAME).lintian-overrides 166 | cd $(PATHDEBPKG)/$(PKGNAME)-$(VERSION) && debuild -us -uc 167 | 168 | # Clean all artifacts and download all dependencies 169 | .PHONY: deps 170 | deps: ensuretarget 171 | rm -rf ./vendor/* 172 | ($(COMPOSER) install -vvv --no-interaction) 173 | curl --silent --show-error --fail --location --output ./vendor/phpstan.phar https://github.com/phpstan/phpstan/releases/download/2.1.2/phpstan.phar \ 174 | && chmod +x ./vendor/phpstan.phar 175 | 176 | # Generate source code documentation 177 | .PHONY: doc 178 | doc: ensuretarget 179 | rm -rf $(TARGETDIR)/doc 180 | $(PHPDOC) -d ./src -t $(TARGETDIR)/doc/ 181 | 182 | # Create missing target directories for test and build artifacts 183 | .PHONY: ensuretarget 184 | ensuretarget: 185 | mkdir -p $(TARGETDIR)/test 186 | mkdir -p $(TARGETDIR)/report 187 | mkdir -p $(TARGETDIR)/doc 188 | 189 | # Install this application 190 | .PHONY: install 191 | install: uninstall 192 | mkdir -p $(PATHINSTBIN) 193 | cp -rf ./src/* $(PATHINSTBIN) 194 | cp -f ./resources/autoload.php $(PATHINSTBIN) 195 | find $(PATHINSTBIN) -type d -exec chmod 755 {} \; 196 | find $(PATHINSTBIN) -type f -exec chmod 644 {} \; 197 | mkdir -p $(PATHINSTDOC) 198 | cp -f ./LICENSE $(PATHINSTDOC) 199 | cp -f ./README.md $(PATHINSTDOC) 200 | cp -f ./VERSION $(PATHINSTDOC) 201 | cp -f ./RELEASE $(PATHINSTDOC) 202 | chmod -R 644 $(PATHINSTDOC)* 203 | ifneq ($(strip $(CONFIGPATH)),) 204 | mkdir -p $(PATHINSTCFG) 205 | touch -c $(PATHINSTCFG)* 206 | cp -ru ./resources/${CONFIGPATH}* $(PATHINSTCFG) 207 | find $(PATHINSTCFG) -type d -exec chmod 755 {} \; 208 | find $(PATHINSTCFG) -type f -exec chmod 644 {} \; 209 | endif 210 | 211 | # Test source code for coding standard violations 212 | .PHONY: lint 213 | lint: 214 | ./vendor/bin/phpcs --ignore="./vendor/" --standard=phpcs.xml src test 215 | ./vendor/bin/phpmd src text codesize,unusedcode,naming,design --exclude */vendor/* 216 | ./vendor/bin/phpmd test text unusedcode,naming,design --exclude */vendor/* 217 | php -r 'exit((int)version_compare(PHP_MAJOR_VERSION, "7", ">"));' || ./vendor/phpstan.phar analyse 218 | 219 | # Run all tests and reports 220 | .PHONY: qa 221 | qa: ensuretarget lint test report 222 | 223 | # Generate various reports 224 | .PHONY: report 225 | report: ensuretarget 226 | ./vendor/bin/pdepend --jdepend-xml=$(TARGETDIR)/report/dependencies.xml --summary-xml=$(TARGETDIR)/report/metrics.xml --jdepend-chart=$(TARGETDIR)/report/dependecies.svg --overview-pyramid=$(TARGETDIR)/report/overview-pyramid.svg --ignore=vendor ./src 227 | #./vendor/bartlett/php-compatinfo/bin/phpcompatinfo --no-ansi analyser:run src/ > $(TARGETDIR)/report/phpcompatinfo.txt 228 | 229 | # Build the RPM package for RedHat-like Linux distributions 230 | .PHONY: rpm 231 | rpm: 232 | rm -rf $(PATHRPMPKG) 233 | rpmbuild \ 234 | --define "_topdir $(PATHRPMPKG)" \ 235 | --define "_vendor $(VENDOR)" \ 236 | --define "_owner $(OWNER)" \ 237 | --define "_project $(PROJECT)" \ 238 | --define "_package $(PKGNAME)" \ 239 | --define "_version $(VERSION)" \ 240 | --define "_release $(RELEASE)" \ 241 | --define "_current_directory $(CURRENTDIR)" \ 242 | --define "_libpath /$(LIBPATH)" \ 243 | --define "_docpath /$(DOCPATH)" \ 244 | --define "_configpath /$(CONFIGPATH)" \ 245 | -bb resources/rpm/rpm.spec 246 | 247 | # Start the development server 248 | .PHONY: server 249 | server: 250 | $(PHP) -t example -S localhost:$(PORT) 251 | 252 | # Tag this GIT version 253 | .PHONY: tag 254 | tag: 255 | git checkout main && \ 256 | git tag -a ${VERSION} -m "Release ${VERSION}" && \ 257 | git push origin --tags && \ 258 | git pull 259 | 260 | # Run unit tests 261 | .PHONY: test 262 | test: 263 | cp phpunit.xml.dist phpunit.xml 264 | #./vendor/bin/phpunit --migrate-configuration || true 265 | XDEBUG_MODE=coverage ./vendor/bin/phpunit --stderr test 266 | 267 | # Remove all installed files 268 | .PHONY: uninstall 269 | uninstall: 270 | rm -rf $(PATHINSTBIN) 271 | rm -rf $(PATHINSTDOC) 272 | 273 | # Increase the version patch number 274 | .PHONY: versionup 275 | versionup: 276 | echo ${VERSION} | gawk -F. '{printf("%d.%d.%d\n",$$1,$$2,(($$3+1)));}' > VERSION 277 | 278 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # tc-lib-pdf-parser 2 | *PHP library to parse PDF documents* 3 | 4 | [![Latest Stable Version](https://poser.pugx.org/tecnickcom/tc-lib-pdf-parser/version)](https://packagist.org/packages/tecnickcom/tc-lib-pdf-parser) 5 | ![Build](https://github.com/tecnickcom/tc-lib-pdf-parser/actions/workflows/check.yml/badge.svg) 6 | [![Coverage](https://codecov.io/gh/tecnickcom/tc-lib-pdf-parser/graph/badge.svg?token=SIGYQJG8D4)](https://codecov.io/gh/tecnickcom/tc-lib-pdf-parser) 7 | [![License](https://poser.pugx.org/tecnickcom/tc-lib-pdf-parser/license)](https://packagist.org/packages/tecnickcom/tc-lib-pdf-parser) 8 | [![Downloads](https://poser.pugx.org/tecnickcom/tc-lib-pdf-parser/downloads)](https://packagist.org/packages/tecnickcom/tc-lib-pdf-parser) 9 | 10 | [![Donate via PayPal](https://img.shields.io/badge/donate-paypal-87ceeb.svg)](https://www.paypal.com/donate/?hosted_button_id=NZUEC5XS8MFBJ) 11 | *Please consider supporting this project by making a donation via [PayPal](https://www.paypal.com/donate/?hosted_button_id=NZUEC5XS8MFBJ)* 12 | 13 | * **category** Library 14 | * **package** \Com\Tecnick\Pdf\Parser 15 | * **author** Nicola Asuni 16 | * **copyright** 2015-2025 Nicola Asuni - Tecnick.com LTD 17 | * **license** http://www.gnu.org/copyleft/lesser.html GNU-LGPL v3 (see LICENSE.TXT) 18 | * **link** https://github.com/tecnickcom/tc-lib-pdf-parser 19 | * **SRC DOC** https://tcpdf.org/docs/srcdoc/tc-lib-pdf-parser 20 | 21 | ## Description 22 | 23 | PHP library to parse PDF documents. 24 | 25 | The initial source code has been derived from [TCPDF](). 26 | 27 | 28 | ## Getting started 29 | 30 | First, you need to install all development dependencies using [Composer](https://getcomposer.org/): 31 | 32 | ```bash 33 | $ curl -sS https://getcomposer.org/installer | php 34 | $ mv composer.phar /usr/local/bin/composer 35 | ``` 36 | 37 | This project include a Makefile that allows you to test and build the project with simple commands. 38 | To see all available options: 39 | 40 | ```bash 41 | make help 42 | ``` 43 | 44 | To install all the development dependencies: 45 | 46 | ```bash 47 | make deps 48 | ``` 49 | 50 | ## Running all tests 51 | 52 | Before committing the code, please check if it passes all tests using 53 | 54 | ```bash 55 | make qa 56 | ``` 57 | 58 | All artifacts are generated in the target directory. 59 | 60 | 61 | ## Example 62 | 63 | Examples are located in the `example` directory. 64 | 65 | Start a development server (requires PHP 8.0+) using the command: 66 | 67 | ``` 68 | make server 69 | ``` 70 | 71 | and point your browser to 72 | 73 | 74 | ## Installation 75 | 76 | Create a composer.json in your projects root-directory: 77 | 78 | ```json 79 | { 80 | "require": { 81 | "tecnickcom/tc-lib-pdf-parser": "^3.0.0" 82 | } 83 | } 84 | ``` 85 | 86 | Or add to an existing project with: 87 | 88 | ```bash 89 | composer require tecnickcom/tc-lib-pdf-parser ^3.0.0 90 | ``` 91 | 92 | 93 | ## Packaging 94 | 95 | This library is mainly intended to be used and included in other PHP projects using Composer. 96 | However, since some production environments dictates the installation of any application as RPM or DEB packages, 97 | this library includes make targets for building these packages (`make rpm` and `make deb`). 98 | The packages are generated under the `target` directory. 99 | 100 | When this library is installed using an RPM or DEB package, you can use it your code by including the autoloader: 101 | ``` 102 | require_once ('/usr/share/php/Com/Tecnick/Pdf/Parser/autoload.php'); 103 | ``` 104 | 105 | 106 | 107 | ## Developer(s) Contact 108 | 109 | * Nicola Asuni 110 | -------------------------------------------------------------------------------- /RELEASE: -------------------------------------------------------------------------------- 1 | 0 2 | -------------------------------------------------------------------------------- /SECURITY.md: -------------------------------------------------------------------------------- 1 | # Security Policy 2 | 3 | ## Reporting a Vulnerability 4 | 5 | Please report (suspected) security vulnerabilities to info@tecnick.com. 6 | -------------------------------------------------------------------------------- /VERSION: -------------------------------------------------------------------------------- 1 | 3.0.21 2 | -------------------------------------------------------------------------------- /composer.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "tecnickcom/tc-lib-pdf-parser", 3 | "description": "PHP library to parse PDF documents", 4 | "type": "library", 5 | "homepage": "http://www.tecnick.com", 6 | "license": "LGPL-3.0-or-later", 7 | "keywords": [ 8 | "tc-lib-pdf-parser", 9 | "PDF", 10 | "parser", 11 | "document" 12 | ], 13 | "authors": [ 14 | { 15 | "name": "Nicola Asuni", 16 | "email": "info@tecnick.com", 17 | "role": "lead" 18 | } 19 | ], 20 | "require": { 21 | "php": ">=8.1", 22 | "ext-pcre": "*", 23 | "tecnickcom/tc-lib-pdf-filter": "^2.0" 24 | }, 25 | "require-dev": { 26 | "pdepend/pdepend": "2.16.2", 27 | "phpmd/phpmd": "2.15.0", 28 | "phpunit/phpunit": "12.2.0 || 11.5.7 || 10.5.40", 29 | "squizlabs/php_codesniffer": "3.13.0" 30 | }, 31 | "autoload": { 32 | "psr-4": { 33 | "Com\\Tecnick\\Pdf\\Parser\\": "src" 34 | } 35 | }, 36 | "autoload-dev": { 37 | "psr-4": { "Test\\": "test" } 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /example/index.php: -------------------------------------------------------------------------------- 1 | 9 | * @copyright 2011-2024 Nicola Asuni - Tecnick.com LTD 10 | * @license http://www.gnu.org/copyleft/lesser.html GNU-LGPL v3 (see LICENSE.TXT) 11 | * @link https://github.com/tecnickcom/tc-lib-color 12 | * 13 | * This file is part of tc-lib-pdf-parser software library. 14 | */ 15 | 16 | // autoloader when using Composer 17 | require(__DIR__ . '/../vendor/autoload.php'); 18 | 19 | // autoloader when using RPM or DEB package installation 20 | //require ('/usr/share/php/Com/Tecnick/Pdf/Parser/autoload.php'); 21 | 22 | $filename = '../resources/test/example_036.pdf'; 23 | $rawdata = file_get_contents($filename); 24 | if ($rawdata === false) { 25 | die('Unable to get the content of the file: ' . $filename); 26 | } 27 | 28 | // configuration parameters for parser 29 | $cfg = [ 30 | 'ignore_filter_errors' => true, 31 | ]; 32 | 33 | // parse PDF data 34 | $pdf = new \Com\Tecnick\Pdf\Parser\Parser($cfg); 35 | $data = $pdf->parse($rawdata); 36 | 37 | // display data 38 | var_dump($data); 39 | -------------------------------------------------------------------------------- /phpcompatinfo.json: -------------------------------------------------------------------------------- 1 | { 2 | "source-providers": [ 3 | { 4 | "in": "src as source", 5 | "exclude": "vendor", 6 | "name": "/\\.(php)$/" 7 | } 8 | ], 9 | "plugins": [ 10 | ], 11 | "analysers": [ 12 | ], 13 | "services": [ 14 | ] 15 | } 16 | -------------------------------------------------------------------------------- /phpcs.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | PSR-12 for PHP less than 7.1 4 | 5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /phpstan.neon: -------------------------------------------------------------------------------- 1 | parameters: 2 | level: max 3 | paths: 4 | - src 5 | - test 6 | excludePaths: 7 | - vendor 8 | ignoreErrors: 9 | reportUnmatchedIgnoredErrors: false 10 | treatPhpDocTypesAsCertain: false 11 | -------------------------------------------------------------------------------- /phpunit.xml.dist: -------------------------------------------------------------------------------- 1 | 2 | 12 | 13 | 14 | ./test 15 | 16 | 17 | 18 | 19 | src 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | -------------------------------------------------------------------------------- /resources/autoload.php: -------------------------------------------------------------------------------- 1 | 11 | * @copyright 2015-2024 Nicola Asuni - Tecnick.com LTD 12 | * @license http://www.gnu.org/copyleft/lesser.html GNU-LGPL v3 (see LICENSE.TXT) 13 | * @link https://github.com/tecnickcom/tc-lib-pdf-parser 14 | * 15 | * This file is part of tc-lib-pdf-parser software library. 16 | */ 17 | spl_autoload_register( 18 | function ($class) { 19 | $prefix = 'Com\\Tecnick\\'; 20 | $len = strlen($prefix); 21 | if (strncmp($prefix, $class, $len) !== 0) { 22 | return; 23 | } 24 | $relative_class = substr($class, $len); 25 | $file = dirname(dirname(__DIR__)).'/'.str_replace('\\', '/', $relative_class).'.php'; 26 | if (file_exists($file)) { 27 | require $file; 28 | } 29 | } 30 | ); 31 | -------------------------------------------------------------------------------- /resources/debian/changelog: -------------------------------------------------------------------------------- 1 | ~#PKGNAME#~ (~#VERSION#~-~#RELEASE#~) UNRELEASED; urgency=low 2 | 3 | * Please check the 4 | https://github.com/~#VENDOR#~/~#PROJECT#~ 5 | commit history 6 | 7 | -- Nicola Asuni ~#DATE#~ 8 | -------------------------------------------------------------------------------- /resources/debian/compat: -------------------------------------------------------------------------------- 1 | 10 2 | -------------------------------------------------------------------------------- /resources/debian/control: -------------------------------------------------------------------------------- 1 | Source: ~#PKGNAME#~ 2 | Maintainer: Nicola Asuni 3 | Section: php 4 | Priority: optional 5 | Build-Depends: debhelper (>= 9) 6 | Standards-Version: 3.9.7 7 | Homepage: https://github.com/~#VENDOR#~/~#PROJECT#~ 8 | Vcs-Git: https://github.com/~#VENDOR#~/~#PROJECT#~.git 9 | 10 | Package: ~#PKGNAME#~ 11 | Provides: php-~#PROJECT#~ 12 | Architecture: all 13 | Depends: php (>= 8.1.0), php-tecnickcom-tc-lib-pdf-filter (<< 2.0.0), php-tecnickcom-tc-lib-pdf-filter (>= 2.0.24), ${misc:Depends} 14 | Description: PHP PDF Parser Library 15 | PHP library to parse PDF documents. 16 | -------------------------------------------------------------------------------- /resources/debian/copyright: -------------------------------------------------------------------------------- 1 | Format: http://www.debian.org/doc/packaging-manuals/copyright-format/1.0/ 2 | Upstream-Name: ~#PROJECT#~ 3 | Source: https://github.com/~#VENDOR#~/~#PROJECT#~ 4 | 5 | Files: * 6 | Copyright: Copyright 2001-2024 Nicola Asuni 7 | License: LGPL-3 8 | 9 | License: LGPL-3 10 | This program is free software: you can redistribute it and/or modify 11 | it under the terms of the GNU Lesser General Public License as 12 | published by the Free Software Foundation, either version 3 of the 13 | License, or (at your option) any later version. 14 | This program is distributed in the hope that it will be useful, 15 | but WITHOUT ANY WARRANTY; without even the implied warranty of 16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 17 | GNU General Public License for more details. 18 | You should have received a copy of the GNU General Public License 19 | along with this program. If not, see or 20 | /usr/share/common-licenses/LGPL-3 21 | -------------------------------------------------------------------------------- /resources/debian/rules: -------------------------------------------------------------------------------- 1 | #!/usr/bin/make -f 2 | %: 3 | dh $@ 4 | -------------------------------------------------------------------------------- /resources/debian/source/format: -------------------------------------------------------------------------------- 1 | 3.0 (quilt) 2 | -------------------------------------------------------------------------------- /resources/rpm/rpm.spec: -------------------------------------------------------------------------------- 1 | # SPEC file 2 | 3 | %global c_vendor %{_vendor} 4 | %global gh_owner %{_owner} 5 | %global gh_project %{_project} 6 | 7 | Name: %{_package} 8 | Version: %{_version} 9 | Release: %{_release}%{?dist} 10 | Summary: PHP library to parse PDF documents 11 | 12 | Group: Development/Libraries 13 | License: LGPLv3+ 14 | URL: https://github.com/%{gh_owner}/%{gh_project} 15 | 16 | BuildRoot: %{_tmppath}/%{name}-%{version}-%{release}-%(%{__id_u} -n) 17 | BuildArch: noarch 18 | 19 | Requires: php(language) >= 8.1.0 20 | Requires: php-composer(%{c_vendor}/tc-lib-pdf-filter) < 2.0.0 21 | Requires: php-composer(%{c_vendor}/tc-lib-pdf-filter) >= 2.0.24 22 | Requires: php-pcre 23 | 24 | Provides: php-composer(%{c_vendor}/%{gh_project}) = %{version} 25 | Provides: php-%{gh_project} = %{version} 26 | 27 | %description 28 | PHP library to parse PDF documents. 29 | 30 | %build 31 | #(cd %{_current_directory} && make build) 32 | 33 | %install 34 | rm -rf $RPM_BUILD_ROOT 35 | (cd %{_current_directory} && make install DESTDIR=$RPM_BUILD_ROOT) 36 | 37 | %clean 38 | rm -rf $RPM_BUILD_ROOT 39 | #(cd %{_current_directory} && make clean) 40 | 41 | %files 42 | %attr(-,root,root) %{_libpath} 43 | %attr(-,root,root) %{_docpath} 44 | %docdir %{_docpath} 45 | #%config(noreplace) %{_configpath}* 46 | 47 | %changelog 48 | * Thu Jul 02 2024 Nicola Asuni 2.1.0-1 49 | - Changed package name, add provides section 50 | * Tue May 05 2024 Nicola Asuni 2.0.0-1 51 | - Initial Commit 52 | -------------------------------------------------------------------------------- /resources/test/example_005.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tecnickcom/tc-lib-pdf-parser/da7fc2dbf84208a1424ab65419cd0fe279e58db3/resources/test/example_005.pdf -------------------------------------------------------------------------------- /resources/test/example_036.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tecnickcom/tc-lib-pdf-parser/da7fc2dbf84208a1424ab65419cd0fe279e58db3/resources/test/example_036.pdf -------------------------------------------------------------------------------- /resources/test/example_046.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tecnickcom/tc-lib-pdf-parser/da7fc2dbf84208a1424ab65419cd0fe279e58db3/resources/test/example_046.pdf -------------------------------------------------------------------------------- /src/Exception.php: -------------------------------------------------------------------------------- 1 | 10 | * @copyright 2011-2024 Nicola Asuni - Tecnick.com LTD 11 | * @license http://www.gnu.org/copyleft/lesser.html GNU-LGPL v3 (see LICENSE.TXT) 12 | * @link https://github.com/tecnickcom/tc-lib-pdf-parser 13 | * 14 | * This file is part of tc-lib-pdf-parser software library. 15 | */ 16 | 17 | namespace Com\Tecnick\Pdf\Parser; 18 | 19 | /** 20 | * Com\Tecnick\Pdf\Parser\Exception 21 | * 22 | * Custom Exception class 23 | * 24 | * @since 2011-05-23 25 | * @category Library 26 | * @package PdfParser 27 | * @author Nicola Asuni 28 | * @copyright 2011-2024 Nicola Asuni - Tecnick.com LTD 29 | * @license http://www.gnu.org/copyleft/lesser.html GNU-LGPL v3 (see LICENSE.TXT) 30 | * @link https://github.com/tecnickcom/tc-lib-pdf-parser 31 | */ 32 | class Exception extends \Exception 33 | { 34 | } 35 | -------------------------------------------------------------------------------- /src/Parser.php: -------------------------------------------------------------------------------- 1 | 10 | * @copyright 2011-2024 Nicola Asuni - Tecnick.com LTD 11 | * @license http://www.gnu.org/copyleft/lesser.html GNU-LGPL v3 (see LICENSE.TXT) 12 | * @link https://github.com/tecnickcom/tc-lib-pdf-parser 13 | * 14 | * This file is part of tc-lib-pdf-parser software library. 15 | */ 16 | 17 | namespace Com\Tecnick\Pdf\Parser; 18 | 19 | use Com\Tecnick\Pdf\Filter\Filter; 20 | use Com\Tecnick\Pdf\Parser\Exception as PPException; 21 | 22 | /** 23 | * Com\Tecnick\Pdf\Parser\Parser 24 | * 25 | * PHP class for parsing PDF documents. 26 | * 27 | * @since 2011-05-23 28 | * @category Library 29 | * @package PdfParser 30 | * @author Nicola Asuni 31 | * @copyright 2011-2024 Nicola Asuni - Tecnick.com LTD 32 | * @license http://www.gnu.org/copyleft/lesser.html GNU-LGPL v3 (see LICENSE.TXT) 33 | * @link https://github.com/tecnickcom/tc-lib-pdf-parser 34 | * 35 | * @SuppressWarnings("PHPMD.ExcessiveClassComplexity") 36 | * 37 | * @phpstan-import-type RawObjectArray from \Com\Tecnick\Pdf\Parser\Process\RawObject 38 | */ 39 | class Parser extends \Com\Tecnick\Pdf\Parser\Process\Xref 40 | { 41 | /** 42 | * Array of configuration parameters. 43 | * 44 | * @var array 45 | */ 46 | private array $cfg = [ 47 | 'ignore_filter_errors' => false, 48 | ]; 49 | 50 | /** 51 | * Initialize the PDF parser 52 | * 53 | * @param array $cfg Array of configuration parameters: 54 | * 'ignore_filter_decoding_errors' : 55 | * if true ignore filter decoding 56 | * errors; 57 | * 'ignore_missing_filter_decoders' : 58 | * if true ignore missing filter 59 | * decoding errors. 60 | */ 61 | public function __construct(array $cfg = []) 62 | { 63 | if (isset($cfg['ignore_filter_errors'])) { 64 | $this->cfg['ignore_filter_errors'] = $cfg['ignore_filter_errors']; 65 | } 66 | } 67 | 68 | /** 69 | * Parse a PDF document into an array of objects 70 | * 71 | * @param string $data PDF data to parse. 72 | * 73 | * @return array{ 74 | * 0: array{ 75 | * 'trailer': array{ 76 | * 'encrypt'?: string, 77 | * 'id': array, 78 | * 'info': string, 79 | * 'root': string, 80 | * 'size': int, 81 | * }, 82 | * 'xref': array, 83 | * }, 84 | * 1: array>, 85 | * } 86 | */ 87 | public function parse(string $data): array 88 | { 89 | if ($data === '') { 90 | throw new PPException('Empty PDF data.'); 91 | } 92 | 93 | // find the pdf header starting position 94 | if (($trimpos = strpos($data, '%PDF-')) === false) { 95 | throw new PPException('Invalid PDF data: missing %PDF header.'); 96 | } 97 | 98 | // get PDF content string 99 | $this->pdfdata = substr($data, $trimpos); 100 | // get xref and trailer data 101 | $this->xref = $this->getXrefData(); 102 | // parse all document objects 103 | $this->objects = []; 104 | foreach ($this->xref['xref'] as $obj => $offset) { 105 | if (isset($this->objects[$obj])) { 106 | continue; 107 | } 108 | 109 | if ($offset <= 0) { 110 | continue; 111 | } 112 | 113 | // decode objects with positive offset 114 | $this->objects[$obj] = $this->getIndirectObject($obj, $offset, true); 115 | } 116 | 117 | // release some memory 118 | unset($this->pdfdata); 119 | return [$this->xref, $this->objects]; 120 | } 121 | 122 | /** 123 | * Get content of indirect object. 124 | * 125 | * @param string $obj_ref Object number and generation number separated by underscore character. 126 | * @param int $offset Object offset. 127 | * @param bool $decoding If true decode streams. 128 | * 129 | * @return array Object data. 130 | */ 131 | protected function getIndirectObject(string $obj_ref, int $offset = 0, bool $decoding = true): array 132 | { 133 | $obj = explode('_', $obj_ref); 134 | if (($obj == false) || (count($obj) != 2)) { 135 | throw new PPException('Invalid object reference: ' . serialize($obj)); 136 | } 137 | 138 | $objref = $obj[0] . ' ' . $obj[1] . ' obj'; 139 | // ignore leading zeros 140 | $offset += strspn($this->pdfdata, '0', $offset); 141 | if (strpos($this->pdfdata, $objref, $offset) != $offset) { 142 | ++$offset; 143 | if (strpos($this->pdfdata, $objref, $offset) != $offset) { 144 | // an indirect reference to an undefined object shall be considered a reference to the null object 145 | return [['null', 'null', $offset]]; 146 | } 147 | } 148 | 149 | // starting position of object content 150 | $offset += strlen($objref); 151 | // return raw object content 152 | return $this->getRawIndirectObject($offset, $decoding); 153 | } 154 | 155 | /** 156 | * Get content of indirect object. 157 | * 158 | * @param int $offset Object offset. 159 | * @param bool $decoding If true decode streams. 160 | * 161 | * @return array Object data. 162 | */ 163 | protected function getRawIndirectObject(int $offset, bool $decoding): array 164 | { 165 | // get array of object content 166 | $objdata = []; 167 | $idx = 0; // object main index 168 | do { 169 | $oldoffset = $offset; 170 | 171 | $element = $this->getRawObject($offset); 172 | $offset = $element[2]; 173 | // decode stream using stream's dictionary information 174 | if ( 175 | $decoding 176 | && ($element[0] == 'stream') 177 | && (isset($objdata[($idx - 1)][0])) 178 | && ($objdata[($idx - 1)][0] == '<<') 179 | && (is_array($objdata[($idx - 1)][1])) 180 | && (is_string($element[1])) 181 | ) { 182 | $element[3] = $this->decodeStream($objdata[($idx - 1)][1], $element[1]); 183 | } 184 | 185 | $objdata[$idx] = $element; 186 | ++$idx; 187 | } while (($element[0] != 'endobj') && ($offset != $oldoffset)); 188 | 189 | // remove closing delimiter 190 | array_pop($objdata); 191 | 192 | // return raw object content 193 | return $objdata; 194 | } 195 | 196 | /** 197 | * Get the content of object, resolving indect object reference if necessary. 198 | * 199 | * @param RawObjectArray $obj Object value. 200 | * 201 | * @return RawObjectArray Object data. 202 | */ 203 | protected function getObjectVal(array $obj): array 204 | { 205 | if (($obj[0] == 'objref') && is_string($obj[1])) { 206 | // reference to indirect object 207 | if (isset($this->objects[$obj[1]][0])) { 208 | // this object has been already parsed 209 | return $this->objects[$obj[1]][0]; 210 | } 211 | 212 | if (isset($this->xref['xref'][$obj[1]])) { 213 | // parse new object 214 | $this->objects[$obj[1]] = $this->getIndirectObject($obj[1], $this->xref['xref'][$obj[1]], false); 215 | return $this->objects[$obj[1]][0]; 216 | } 217 | } 218 | 219 | return $obj; 220 | } 221 | 222 | /** 223 | * Decode the specified stream. 224 | * 225 | * @param array $sdic Stream's dictionary array. 226 | * @param string $stream Stream to decode. 227 | * 228 | * @return array{ 229 | * 0: string, 230 | * 1: array, 231 | * } Decoded stream data and remaining filters. 232 | * 233 | * @SuppressWarnings("PHPMD.CyclomaticComplexity") 234 | */ 235 | protected function decodeStream(array $sdic, string $stream): array 236 | { 237 | // get stream length and filters 238 | $slength = strlen($stream); 239 | if ($slength <= 0) { 240 | return ['', []]; 241 | } 242 | 243 | $filters = []; 244 | foreach ($sdic as $key => $val) { 245 | if (! is_string($val[1])) { 246 | continue; 247 | } 248 | 249 | if ($val[0] == '/') { 250 | if (($val[1] == 'Length') && (isset($sdic[($key + 1)])) && ($sdic[($key + 1)][0] == 'numeric')) { 251 | // get declared stream length 252 | $this->getDeclaredStreamLength($stream, $slength, $sdic, $key); 253 | } elseif (($val[1] == 'Filter') && (isset($sdic[($key + 1)]))) { 254 | $filters = $this->getFilters($filters, $sdic, $key); 255 | } 256 | } 257 | } 258 | 259 | return $this->getDecodedStream($filters, $stream); 260 | } 261 | 262 | /** 263 | * Get Filters 264 | * 265 | * @param string $stream Stream 266 | * @param int $slength Stream length 267 | * @param array $sdic Stream's dictionary array. 268 | * @param int $key Index 269 | */ 270 | protected function getDeclaredStreamLength(string &$stream, int &$slength, array $sdic, int $key): void 271 | { 272 | // get declared stream length 273 | $declength = (int) $sdic[($key + 1)][1]; 274 | if ($declength < $slength) { 275 | $stream = substr($stream, 0, $declength); 276 | $slength = $declength; 277 | } 278 | } 279 | 280 | /** 281 | * Get Filters 282 | * 283 | * @param array $filters Array of Filters 284 | * @param array $sdic Stream's dictionary array. 285 | * @param int $key Index 286 | * 287 | * @return array Array of filters 288 | */ 289 | protected function getFilters(array $filters, array $sdic, int $key): array 290 | { 291 | // resolve indirect object 292 | $objval = $this->getObjectVal($sdic[($key + 1)]); 293 | 294 | switch ($objval[0]) { 295 | case '/': 296 | // single filter 297 | if (is_string($objval[1])) { 298 | $filters[] = $objval[1]; 299 | } 300 | 301 | break; 302 | case '[': 303 | if (! is_array($objval[1])) { 304 | break; 305 | } 306 | 307 | foreach ($objval[1] as $flt) { 308 | if (! is_array($flt)) { 309 | continue; 310 | } 311 | 312 | if ($flt[0] != '/') { 313 | continue; 314 | } 315 | 316 | if (! is_string($flt[1])) { 317 | continue; 318 | } 319 | 320 | $filters[] = $flt[1]; 321 | } 322 | 323 | break; 324 | } 325 | 326 | return $filters; 327 | } 328 | 329 | /** 330 | * Decode the specified stream. 331 | * 332 | * @param array $filters Array of decoding filters to apply 333 | * @param string $stream Stream to decode. 334 | * 335 | * @return array{ 336 | * 0: string, 337 | * 1: array, 338 | * } Decoded stream data and remaining filters. 339 | */ 340 | protected function getDecodedStream(array $filters, string $stream): array 341 | { 342 | // decode the stream 343 | $errorfilters = []; 344 | try { 345 | $filter = new Filter(); 346 | $stream = $filter->decodeAll($filters, $stream); 347 | } catch (\Com\Tecnick\Pdf\Filter\Exception $exception) { 348 | if ($this->cfg['ignore_filter_errors']) { 349 | $errorfilters = $filters; 350 | } else { 351 | throw new PPException($exception->getMessage()); 352 | } 353 | } 354 | 355 | return [$stream, $errorfilters]; 356 | } 357 | } 358 | -------------------------------------------------------------------------------- /src/Process/RawObject.php: -------------------------------------------------------------------------------- 1 | 10 | * @copyright 2011-2024 Nicola Asuni - Tecnick.com LTD 11 | * @license http://www.gnu.org/copyleft/lesser.html GNU-LGPL v3 (see LICENSE.TXT) 12 | * @link https://github.com/tecnickcom/tc-lib-pdf-parser 13 | * 14 | * This file is part of tc-lib-pdf-parser software library. 15 | */ 16 | 17 | namespace Com\Tecnick\Pdf\Parser\Process; 18 | 19 | /** 20 | * Com\Tecnick\Pdf\Parser\Process\RawObject 21 | * 22 | * Process Raw Objects 23 | * 24 | * @since 2011-05-23 25 | * @category Library 26 | * @package PdfParser 27 | * @author Nicola Asuni 28 | * @copyright 2011-2024 Nicola Asuni - Tecnick.com LTD 29 | * @license http://www.gnu.org/copyleft/lesser.html GNU-LGPL v3 (see LICENSE.TXT) 30 | * @link https://github.com/tecnickcom/tc-lib-pdf-parser 31 | * 32 | * @phpstan-type RawObjectArray array{ 33 | * 0: string, 34 | * 1: string|array}, 47 | * }>, 48 | * 2: int, 49 | * 3?: array{string, array}, 50 | * }>, 51 | * 2: int, 52 | * 3?: array{string, array}, 53 | * }>, 54 | * 2: int, 55 | * 3?: array{string, array}, 56 | * }>, 57 | * 2: int, 58 | * 3?: array{string, array}, 59 | * }>, 60 | * 2: int, 61 | * 3?: array{string, array}, 62 | * } 63 | */ 64 | abstract class RawObject 65 | { 66 | /** 67 | * Raw content of the PDF document. 68 | */ 69 | protected string $pdfdata = ''; 70 | 71 | /** 72 | * Array of PDF objects. 73 | * 74 | * @var array> 75 | */ 76 | protected array $objects = []; 77 | 78 | /** 79 | * Map symbols with corresponding processing methods. 80 | * 81 | * @var array 82 | */ 83 | protected const SYMBOLMETHOD = [ 84 | // \x2F SOLIDUS 85 | '/' => 'Solidus', 86 | // \x28 LEFT PARENTHESIS 87 | '(' => 'Parenthesis', 88 | // \x29 RIGHT PARENTHESIS 89 | ')' => 'Parenthesis', 90 | // \x5B LEFT SQUARE BRACKET 91 | '[' => 'Bracket', 92 | // \x5D RIGHT SQUARE BRACKET 93 | ']' => 'Bracket', 94 | // \x3C LESS-THAN SIGN 95 | '<' => 'Angular', 96 | // \x3E GREATER-THAN SIGN 97 | '>' => 'Angular', 98 | ]; 99 | 100 | /** 101 | * Get object type, raw value and offset to next object 102 | * 103 | * @param int $offset Object offset. 104 | * 105 | * @return RawObjectArray Array containing: object type, raw value and offset to next object 106 | */ 107 | protected function getRawObject(int $offset = 0): array 108 | { 109 | // skip initial white space chars: 110 | // \x00 null (NUL) 111 | // \x09 horizontal tab (HT) 112 | // \x0A line feed (LF) 113 | // \x0C form feed (FF) 114 | // \x0D carriage return (CR) 115 | // \x20 space (SP) 116 | $offset += strspn($this->pdfdata, "\x00\x09\x0a\x0c\x0d\x20", $offset); 117 | // get first char 118 | $char = $this->pdfdata[$offset]; 119 | if ($char == '%') { // \x25 PERCENT SIGN 120 | // skip comment and search for next token 121 | $next = strcspn($this->pdfdata, "\r\n", $offset); 122 | if ($next > 0) { 123 | $offset += $next; 124 | return $this->getRawObject($offset); 125 | } 126 | } 127 | 128 | $objtype = ''; 129 | $objval = ''; 130 | // map symbols with corresponding processing methods 131 | if (isset(self::SYMBOLMETHOD[$char])) { 132 | $method = 'process' . self::SYMBOLMETHOD[$char]; 133 | $this->$method($char, $offset, $objtype, $objval); 134 | } elseif ($this->processDefaultName($offset, $objtype, $objval) === false) { 135 | $this->processDefault($offset, $objtype, $objval); 136 | } 137 | 138 | return [$objtype, $objval, $offset]; 139 | } 140 | 141 | /** 142 | * Process name object 143 | * \x2F SOLIDUS 144 | * 145 | * @param string $char Symbol to process 146 | * @param int $offset Offset 147 | * @param string $objtype Object type 148 | * @param string|array, 155 | * 2: int, 156 | * }> $objval Object content 157 | */ 158 | protected function processSolidus(string $char, int &$offset, string &$objtype, string|array &$objval): void 159 | { 160 | $objtype = $char; 161 | ++$offset; 162 | if ( 163 | preg_match( 164 | '/^([^\x00\x09\x0a\x0c\x0d\x20\s\x28\x29\x3c\x3e\x5b\x5d\x7b\x7d\x2f\x25]+)/', 165 | substr($this->pdfdata, $offset, 256), 166 | $matches 167 | ) == 1 168 | ) { 169 | $objval = $matches[1]; // unescaped value 170 | $offset += strlen($objval); 171 | } 172 | } 173 | 174 | /** 175 | * Process literal string object 176 | * \x28 LEFT PARENTHESIS and \x29 RIGHT PARENTHESIS 177 | * 178 | * @param string $char Symbol to process 179 | * @param int $offset Offset 180 | * @param string $objtype Object type 181 | * @param string|array, 188 | * 2: int, 189 | * }> $objval Object content 190 | */ 191 | protected function processParenthesis(string $char, int &$offset, string &$objtype, string|array &$objval): void 192 | { 193 | $objtype = $char; 194 | ++$offset; 195 | $strpos = $offset; 196 | if ($char == '(') { 197 | $open_bracket = 1; 198 | while ($open_bracket > 0) { 199 | if (! isset($this->pdfdata[$strpos])) { 200 | break; 201 | } 202 | 203 | $chr = $this->pdfdata[$strpos]; 204 | switch ($chr) { 205 | case '\\': 206 | // REVERSE SOLIDUS (5Ch) (Backslash) 207 | // skip next character 208 | ++$strpos; 209 | break; 210 | case '(': 211 | // LEFT PARENHESIS (28h) 212 | ++$open_bracket; 213 | break; 214 | case ')': 215 | // RIGHT PARENTHESIS (29h) 216 | --$open_bracket; 217 | break; 218 | } 219 | 220 | ++$strpos; 221 | } 222 | 223 | $objval = substr($this->pdfdata, $offset, ($strpos - $offset - 1)); 224 | $offset = $strpos; 225 | } 226 | } 227 | 228 | /** 229 | * Process array content 230 | * \x5B LEFT SQUARE BRACKET and \x5D RIGHT SQUARE BRACKET 231 | * 232 | * @param string $char Symbol to process 233 | * @param int $offset Offset 234 | * @param string $objtype Object type 235 | * @param string|array, 242 | * 2: int, 243 | * }> $objval Object content 244 | */ 245 | protected function processBracket(string $char, int &$offset, string &$objtype, string|array &$objval): void 246 | { 247 | // array object 248 | $objtype = $char; 249 | ++$offset; 250 | if ($char == '[') { 251 | // get array content 252 | $objval = []; 253 | do { 254 | $element = $this->getRawObject($offset); 255 | $offset = $element[2]; 256 | $objval[] = $element; // @phpstan-ignore parameterByRef.type 257 | } while ($element[0] != ']'); 258 | 259 | // remove closing delimiter 260 | array_pop($objval); 261 | } 262 | } 263 | 264 | /** 265 | * Process \x3C LESS-THAN SIGN and \x3E GREATER-THAN SIGN 266 | * 267 | * @param string $char Symbol to process 268 | * @param int $offset Offset 269 | * @param string $objtype Object type 270 | * @param string|array, 277 | * 2: int, 278 | * }> $objval Object content 279 | */ 280 | protected function processAngular(string $char, int &$offset, string &$objtype, string|array &$objval): void 281 | { 282 | if (isset($this->pdfdata[($offset + 1)]) && ($this->pdfdata[($offset + 1)] === $char)) { 283 | // dictionary object 284 | $objtype = $char . $char; 285 | $offset += 2; 286 | if ($char == '<') { 287 | // get array content 288 | $objval = []; 289 | do { 290 | $element = $this->getRawObject($offset); 291 | $offset = $element[2]; 292 | $objval[] = $element; // @phpstan-ignore parameterByRef.type 293 | } while ($element[0] != '>>'); 294 | 295 | // remove closing delimiter 296 | array_pop($objval); 297 | } 298 | } else { 299 | // hexadecimal string object 300 | $objtype = $char; 301 | ++$offset; 302 | if ( 303 | ($char == '<') 304 | && (preg_match( 305 | '/^([0-9A-Fa-f\x09\x0a\x0c\x0d\x20]+)>/iU', 306 | substr($this->pdfdata, $offset), 307 | $matches 308 | ) == 1) 309 | ) { 310 | // remove white space characters 311 | $objval = strtr($matches[1], "\x09\x0a\x0c\x0d\x20", ''); 312 | $offset += strlen($matches[0]); 313 | } elseif (($endpos = strpos($this->pdfdata, '>', $offset)) !== false) { 314 | $offset = $endpos + 1; 315 | } 316 | } 317 | } 318 | 319 | /** 320 | * Process default 321 | * 322 | * @param int $offset Offset 323 | * @param string $objtype Object type 324 | * @param string|array, 331 | * 2: int, 332 | * }> $objval Object content 333 | * 334 | * @return bool True in case of match, flase otherwise 335 | */ 336 | protected function processDefaultName(int &$offset, string &$objtype, string|array &$objval): bool 337 | { 338 | $status = false; 339 | if (substr($this->pdfdata, $offset, 6) == 'endobj') { 340 | // indirect object 341 | $objtype = 'endobj'; 342 | $offset += 6; 343 | $status = true; 344 | } elseif (substr($this->pdfdata, $offset, 4) == 'null') { 345 | // null object 346 | $objtype = 'null'; 347 | $offset += 4; 348 | $objval = 'null'; 349 | $status = true; 350 | } elseif (substr($this->pdfdata, $offset, 4) == 'true') { 351 | // boolean true object 352 | $objtype = 'boolean'; 353 | $offset += 4; 354 | $objval = 'true'; 355 | $status = true; 356 | } elseif (substr($this->pdfdata, $offset, 5) == 'false') { 357 | // boolean false object 358 | $objtype = 'boolean'; 359 | $offset += 5; 360 | $objval = 'false'; 361 | $status = true; 362 | } elseif (substr($this->pdfdata, $offset, 6) == 'stream') { 363 | // start stream object 364 | $objtype = 'stream'; 365 | $offset += 6; 366 | if (preg_match('/^([\r]?[\n])/isU', substr($this->pdfdata, $offset), $matches) == 1) { 367 | $offset += strlen($matches[0]); 368 | if ( 369 | preg_match( 370 | '/(endstream)[\x09\x0a\x0c\x0d\x20]/isU', 371 | substr($this->pdfdata, $offset), 372 | $matches, 373 | PREG_OFFSET_CAPTURE 374 | ) == 1 375 | ) { 376 | $objval = substr($this->pdfdata, $offset, $matches[0][1]); 377 | $offset += $matches[1][1]; 378 | } 379 | } 380 | 381 | $status = true; 382 | } elseif (substr($this->pdfdata, $offset, 9) == 'endstream') { 383 | // end stream object 384 | $objtype = 'endstream'; 385 | $offset += 9; 386 | $status = true; 387 | } 388 | 389 | return $status; 390 | } 391 | 392 | /** 393 | * Process default 394 | * 395 | * @param int $offset Offset 396 | * @param string $objtype Object type 397 | * @param string|array, 404 | * 2: int, 405 | * }> $objval Object content 406 | */ 407 | protected function processDefault(int &$offset, string &$objtype, string|array &$objval): void 408 | { 409 | if ( 410 | preg_match( 411 | '/^([0-9]+)[\s]+([0-9]+)[\s]+R/iU', 412 | substr($this->pdfdata, $offset, 33), 413 | $matches 414 | ) == 1 415 | ) { 416 | // indirect object reference 417 | $objtype = 'objref'; 418 | $offset += strlen($matches[0]); 419 | $objval = (int) $matches[1] . '_' . (int) $matches[2]; 420 | } elseif ( 421 | preg_match( 422 | '/^([0-9]+)[\s]+([0-9]+)[\s]+obj/iU', 423 | substr($this->pdfdata, $offset, 33), 424 | $matches 425 | ) == 1 426 | ) { 427 | // object start 428 | $objtype = 'obj'; 429 | $objval = (int) $matches[1] . '_' . (int) $matches[2]; 430 | $offset += strlen($matches[0]); 431 | } elseif (($numlen = strspn($this->pdfdata, '+-.0123456789', $offset)) > 0) { 432 | // numeric object 433 | $objtype = 'numeric'; 434 | $objval = substr($this->pdfdata, $offset, $numlen); 435 | $offset += $numlen; 436 | } 437 | } 438 | } 439 | -------------------------------------------------------------------------------- /src/Process/Xref.php: -------------------------------------------------------------------------------- 1 | 10 | * @copyright 2011-2024 Nicola Asuni - Tecnick.com LTD 11 | * @license http://www.gnu.org/copyleft/lesser.html GNU-LGPL v3 (see LICENSE.TXT) 12 | * @link https://github.com/tecnickcom/tc-lib-pdf-parser 13 | * 14 | * This file is part of tc-lib-pdf-parser software library. 15 | */ 16 | 17 | namespace Com\Tecnick\Pdf\Parser\Process; 18 | 19 | use Com\Tecnick\Pdf\Parser\Exception as PPException; 20 | 21 | /** 22 | * Com\Tecnick\Pdf\Parser\Process\Xref 23 | * 24 | * Process XREF 25 | * 26 | * @since 2011-05-23 27 | * @category Library 28 | * @package PdfParser 29 | * @author Nicola Asuni 30 | * @copyright 2011-2024 Nicola Asuni - Tecnick.com LTD 31 | * @license http://www.gnu.org/copyleft/lesser.html GNU-LGPL v3 (see LICENSE.TXT) 32 | * @link https://github.com/tecnickcom/tc-lib-pdf-parser 33 | */ 34 | abstract class Xref extends \Com\Tecnick\Pdf\Parser\Process\XrefStream 35 | { 36 | /** 37 | * Default empty XREF data. 38 | * 39 | * @var array{ 40 | * 'trailer': array{ 41 | * 'encrypt'?: string, 42 | * 'id': array, 43 | * 'info': string, 44 | * 'root': string, 45 | * 'size': int, 46 | * }, 47 | * 'xref': array, 48 | * } 49 | */ 50 | protected const XREF_EMPTY = [ 51 | 'trailer' => [ 52 | 'encrypt' => '', 53 | 'id' => [], 54 | 'info' => '', 55 | 'root' => '', 56 | 'size' => 0, 57 | ], 58 | 'xref' => [], 59 | ]; 60 | 61 | /** 62 | * XREF data. 63 | * 64 | * @var array{ 65 | * 'trailer': array{ 66 | * 'encrypt'?: string, 67 | * 'id': array, 68 | * 'info': string, 69 | * 'root': string, 70 | * 'size': int, 71 | * }, 72 | * 'xref': array, 73 | * } 74 | */ 75 | protected array $xref = self::XREF_EMPTY; 76 | 77 | /** 78 | * Store the processed offsets 79 | * 80 | * @var array 81 | */ 82 | protected $mrkoff = []; 83 | 84 | /** 85 | * Get content of indirect object. 86 | * 87 | * @param string $obj_ref Object number and generation number separated by underscore character. 88 | * @param int $offset Object offset. 89 | * @param bool $decoding If true decode streams. 90 | * 91 | * @return array< int, array{ 92 | * 0: string, 93 | * 1: string, 94 | * 2: int, 95 | * 3?: array{string, array}, 96 | * }> Object data. 97 | */ 98 | abstract protected function getIndirectObject(string $obj_ref, int $offset = 0, bool $decoding = true): array; 99 | 100 | /** 101 | * Get Cross-Reference (xref) table and trailer data from PDF document data. 102 | * 103 | * @param int $offset Xref offset (if know). 104 | * @param array{ 105 | * 'trailer'?: array{ 106 | * 'encrypt'?: string, 107 | * 'id': array, 108 | * 'info': string, 109 | * 'root': string, 110 | * 'size': int, 111 | * }, 112 | * 'xref'?: array, 113 | * } $xref Previous xref array (if any). 114 | * 115 | * @return array{ 116 | * 'trailer': array{ 117 | * 'encrypt'?: string, 118 | * 'id': array, 119 | * 'info': string, 120 | * 'root': string, 121 | * 'size': int, 122 | * }, 123 | * 'xref': array, 124 | * } Xref and trailer data. 125 | * 126 | * @SuppressWarnings("PHPMD.CyclomaticComplexity") 127 | */ 128 | protected function getXrefData(int $offset = 0, array $xref = []): array 129 | { 130 | if (in_array($offset, $this->mrkoff)) { 131 | throw new PPException('LOOP: this XRef offset has been already processed'); 132 | } 133 | 134 | $this->mrkoff[] = $offset; 135 | if ($offset == 0) { 136 | // find last startxref 137 | if ( 138 | preg_match_all( 139 | '/[\r\n]startxref[\s]*[\r\n]+([0-9]+)[\s]*[\r\n]+%%EOF/i', 140 | $this->pdfdata, 141 | $matches, 142 | PREG_SET_ORDER, 143 | $offset 144 | ) == 0 145 | ) { 146 | throw new PPException('Unable to find startxref (1)'); 147 | } 148 | 149 | $matches = array_pop($matches); 150 | if ($matches === null) { 151 | throw new PPException('Unable to find startxref (2)'); 152 | } 153 | 154 | $startxref = (int) $matches[1]; 155 | } elseif (($pos = strpos($this->pdfdata, 'xref', $offset)) <= ($offset + 4)) { 156 | // Already pointing at the xref table 157 | $startxref = (int) $pos; 158 | } elseif (preg_match('/([0-9]+[\s][0-9]+[\s]obj)/i', $this->pdfdata, $matches, PREG_OFFSET_CAPTURE, $offset)) { 159 | // Cross-Reference Stream object 160 | $startxref = (int) $offset; 161 | } elseif ( 162 | preg_match( 163 | '/[\r\n]startxref[\s]*[\r\n]+([0-9]+)[\s]*[\r\n]+%%EOF/i', 164 | $this->pdfdata, 165 | $matches, 166 | PREG_OFFSET_CAPTURE, 167 | $offset 168 | ) 169 | ) { 170 | // startxref found 171 | $startxref = (int) $matches[1][0]; 172 | } else { 173 | throw new PPException('Unable to find startxref (3)'); 174 | } 175 | 176 | if (! isset($xref['xref'])) { 177 | $xref['xref'] = []; 178 | } 179 | 180 | // check xref position 181 | if (strpos($this->pdfdata, 'xref', $startxref) == $startxref) { 182 | // Cross-Reference 183 | $xref = $this->decodeXref($startxref, $xref); 184 | } else { 185 | // Cross-Reference Stream 186 | $xref = $this->decodeXrefStream($startxref, $xref); 187 | } 188 | 189 | if (empty($xref['xref'])) { 190 | throw new PPException('Unable to find xref (4)'); 191 | } 192 | 193 | return $xref; 194 | } 195 | 196 | /** 197 | * Decode the Cross-Reference section 198 | * 199 | * @param int $startxref Offset at which the xref section starts (position of the 'xref' keyword). 200 | * @param array{ 201 | * 'trailer'?: array{ 202 | * 'encrypt'?: string, 203 | * 'id': array, 204 | * 'info': string, 205 | * 'root': string, 206 | * 'size': int, 207 | * }, 208 | * 'xref': array, 209 | * } $xref Previous xref array (if any). 210 | * 211 | * @return array{ 212 | * 'trailer': array{ 213 | * 'encrypt'?: string, 214 | * 'id': array, 215 | * 'info': string, 216 | * 'root': string, 217 | * 'size': int, 218 | * }, 219 | * 'xref': array, 220 | * } Xref and trailer data. 221 | */ 222 | protected function decodeXref(int $startxref, array $xref): array 223 | { 224 | $startxref += 4; // 4 is the length of the word 'xref' 225 | // skip initial white space chars: 226 | // \x00 null (NUL) 227 | // \x09 horizontal tab (HT) 228 | // \x0A line feed (LF) 229 | // \x0C form feed (FF) 230 | // \x0D carriage return (CR) 231 | // \x20 space (SP) 232 | $offset = $startxref + strspn($this->pdfdata, "\x00\x09\x0a\x0c\x0d\x20", $startxref); 233 | // initialize object number 234 | $obj_num = 0; 235 | // search for cross-reference entries or subsection 236 | while ( 237 | preg_match( 238 | '/(\d+)[\x20](\d+)[\x20]?([nf]?)(\r\n|[\x20]?[\r\n])/', 239 | $this->pdfdata, 240 | $matches, 241 | PREG_OFFSET_CAPTURE, 242 | $offset 243 | ) > 0 244 | ) { 245 | if ($matches[0][1] != $offset) { 246 | // we are on another section 247 | break; 248 | } 249 | 250 | $offset += strlen($matches[0][0]); 251 | if ($matches[3][0] == 'n') { 252 | // create unique object index: [object number]_[generation number] 253 | $index = $obj_num . '_' . (int) $matches[2][0]; 254 | // check if object already exist 255 | if (! isset($xref['xref'][$index])) { 256 | // store object offset position 257 | $xref['xref'][$index] = (int) $matches[1][0]; 258 | } 259 | 260 | ++$obj_num; 261 | } elseif ($matches[3][0] == 'f') { 262 | ++$obj_num; 263 | } else { 264 | // object number (index) 265 | $obj_num = (int) $matches[1][0]; 266 | } 267 | } 268 | 269 | // get trailer data 270 | $trl = preg_match('/trailer[\s]*+<<(.*)>>/isU', $this->pdfdata, $trmatches, PREG_OFFSET_CAPTURE, $offset); 271 | if ($trl !== 1) { 272 | throw new PPException('Unable to find trailer'); 273 | } 274 | 275 | return $this->getTrailerData($xref, $trmatches); 276 | } 277 | 278 | /** 279 | * Decode the Cross-Reference section 280 | * 281 | * @param array{ 282 | * 'trailer'?: array{ 283 | * 'encrypt'?: string, 284 | * 'id': array, 285 | * 'info': string, 286 | * 'root': string, 287 | * 'size': int, 288 | * }, 289 | * 'xref': array, 290 | * } $xref Previous xref array (if any). 291 | * @param array|string>> $matches Matches containing trailer sections 292 | * 293 | * @return array{ 294 | * 'trailer': array{ 295 | * 'encrypt'?: string, 296 | * 'id': array, 297 | * 'info': string, 298 | * 'root': string, 299 | * 'size': int, 300 | * }, 301 | * 'xref': array, 302 | * } Xref and trailer data. 303 | */ 304 | protected function getTrailerData(array $xref, array $matches): array 305 | { 306 | $trailer_data = (string) $matches[1][0]; 307 | if (! isset($xref['trailer']) || empty($xref['trailer'])) { 308 | // get only the last updated version 309 | $xref['trailer'] = [ 310 | 'id' => [], 311 | 'info' => '', 312 | 'root' => '', 313 | 'size' => 0, 314 | ]; 315 | 316 | // parse trailer_data 317 | if (preg_match('/Size[\s]+([0-9]+)/i', $trailer_data, $matches) > 0) { 318 | $xref['trailer']['size'] = (int) $matches[1]; 319 | } 320 | 321 | if (preg_match('/Root[\s]+([0-9]+)[\s]+([0-9]+)[\s]+R/i', $trailer_data, $matches) > 0) { 322 | $xref['trailer']['root'] = (int) $matches[1] . '_' . (int) $matches[2]; 323 | } 324 | 325 | if (preg_match('/Encrypt[\s]+([0-9]+)[\s]+([0-9]+)[\s]+R/i', $trailer_data, $matches) > 0) { 326 | $xref['trailer']['encrypt'] = (int) $matches[1] . '_' . (int) $matches[2]; 327 | } 328 | 329 | if (preg_match('/Info[\s]+([0-9]+)[\s]+([0-9]+)[\s]+R/i', $trailer_data, $matches) > 0) { 330 | $xref['trailer']['info'] = (int) $matches[1] . '_' . (int) $matches[2]; 331 | } 332 | 333 | if (preg_match('/ID[\s]*+[\[][\s]*+[<]([^>]*+)[>][\s]*+[<]([^>]*+)[>]/i', $trailer_data, $matches) > 0) { 334 | $xref['trailer']['id'] = []; 335 | $xref['trailer']['id'][0] = $matches[1]; 336 | $xref['trailer']['id'][1] = $matches[2]; 337 | } 338 | } 339 | 340 | if (preg_match('/Prev[\s]+([0-9]+)/i', $trailer_data, $matches) > 0) { 341 | // get previous xref 342 | return $this->getXrefData((int) $matches[1], $xref); 343 | } 344 | 345 | return $xref; 346 | } 347 | 348 | /** 349 | * Decode the Cross-Reference Stream section 350 | * 351 | * @param int $startxref Offset at which the xref section starts. 352 | * @param array{ 353 | * 'trailer'?: array{ 354 | * 'encrypt'?: string, 355 | * 'id': array, 356 | * 'info': string, 357 | * 'root': string, 358 | * 'size': int, 359 | * }, 360 | * 'xref': array, 361 | * } $xref Previous xref array (if any). 362 | * 363 | * @return array{ 364 | * 'trailer': array{ 365 | * 'encrypt'?: string, 366 | * 'id': array, 367 | * 'info': string, 368 | * 'root': string, 369 | * 'size': int, 370 | * }, 371 | * 'xref': array, 372 | * } Xref and trailer data. 373 | * 374 | * @SuppressWarnings("PHPMD.CyclomaticComplexity") 375 | */ 376 | protected function decodeXrefStream(int $startxref, array $xref): array 377 | { 378 | // try to read Cross-Reference Stream 379 | $xrefobj = $this->getRawObject($startxref); 380 | if (! is_string($xrefobj[1])) { 381 | throw new PPException('Unable to find xref stream'); 382 | } 383 | 384 | $xrefcrs = $this->getIndirectObject($xrefobj[1], $startxref, true); 385 | 386 | $filltrailer = empty($xref['trailer']); 387 | if ($filltrailer) { 388 | $xref['trailer'] = self::XREF_EMPTY['trailer']; 389 | } 390 | if (! isset($xref['xref'])) { 391 | $xref['xref'] = self::XREF_EMPTY['xref']; 392 | } 393 | 394 | $valid_crs = false; 395 | $columns = 0; 396 | $sarr = $xrefcrs[0][1]; 397 | if (! is_array($sarr)) { 398 | $sarr = []; 399 | } 400 | 401 | $wbt = []; 402 | $index_first = null; 403 | $prevxref = null; 404 | $this->processXrefType($sarr, $xref, $wbt, $index_first, $prevxref, $columns, $valid_crs, $filltrailer); 405 | // decode data 406 | if ($valid_crs && isset($xrefcrs[1][3][0])) { 407 | // number of bytes in a row 408 | $rowlen = (int) ($columns + 1); 409 | // convert the stream into an array of integers 410 | $sdata = unpack('C*', $xrefcrs[1][3][0]); 411 | if ($sdata === false) { 412 | throw new PPException('Unable to unpack xref stream data'); 413 | } 414 | 415 | // split the rows 416 | $sdata = array_chunk($sdata, max(1, $rowlen), false); 417 | // initialize decoded array 418 | $ddata = []; 419 | // initialize first row with zeros 420 | $prev_row = array_fill(0, $rowlen, 0); 421 | $this->pngUnpredictor($sdata, $ddata, $columns, $prev_row); //@phpstan-ignore argument.type 422 | // complete decoding 423 | $sdata = []; 424 | $this->processDdata($sdata, $ddata, $wbt); 425 | $ddata = []; 426 | // fill xref 427 | $obj_num = $index_first ?? 0; 428 | 429 | $this->processObjIndexes($xref, $obj_num, $sdata); 430 | } 431 | 432 | // end decoding data 433 | if (is_null($prevxref)) { 434 | return $xref; 435 | } 436 | 437 | // get previous xref 438 | return $this->getXrefData($prevxref, $xref); 439 | } 440 | 441 | /** 442 | * Process ddata 443 | * 444 | * @param array> $sdata 445 | * @param array> $ddata 446 | * @param array $wbt 447 | */ 448 | protected function processDdata(array &$sdata, array $ddata, array $wbt): void 449 | { 450 | // for every row 451 | foreach ($ddata as $key => $row) { 452 | // initialize new row 453 | $sdata[$key] = [0, 0, 0]; 454 | if ($wbt[0] == 0) { 455 | // default type field 456 | $sdata[$key][0] = 1; 457 | } 458 | 459 | $idx = 0; // count bytes in the row 460 | // for every column 461 | for ($col = 0; $col < 3; ++$col) { 462 | // for every byte on the column 463 | for ($byte = 0; $byte < $wbt[$col]; ++$byte) { 464 | if (isset($row[$idx])) { 465 | $sdata[$key][$col] += ($row[$idx] << (($wbt[$col] - 1 - $byte) * 8)); 466 | } 467 | 468 | ++$idx; 469 | } 470 | } 471 | } 472 | } 473 | } 474 | -------------------------------------------------------------------------------- /src/Process/XrefStream.php: -------------------------------------------------------------------------------- 1 | 10 | * @copyright 2011-2024 Nicola Asuni - Tecnick.com LTD 11 | * @license http://www.gnu.org/copyleft/lesser.html GNU-LGPL v3 (see LICENSE.TXT) 12 | * @link https://github.com/tecnickcom/tc-lib-pdf-parser 13 | * 14 | * This file is part of tc-lib-pdf-parser software library. 15 | */ 16 | 17 | namespace Com\Tecnick\Pdf\Parser\Process; 18 | 19 | use Com\Tecnick\Pdf\Parser\Exception as PPException; 20 | 21 | /** 22 | * Com\Tecnick\Pdf\Parser\Process\XrefStream 23 | * 24 | * Process XREF 25 | * 26 | * @since 2011-05-23 27 | * @category Library 28 | * @package PdfParser 29 | * @author Nicola Asuni 30 | * @copyright 2011-2024 Nicola Asuni - Tecnick.com LTD 31 | * @license http://www.gnu.org/copyleft/lesser.html GNU-LGPL v3 (see LICENSE.TXT) 32 | * @link https://github.com/tecnickcom/tc-lib-pdf-parser 33 | * 34 | * @phpstan-import-type RawObjectArray from \Com\Tecnick\Pdf\Parser\Process\RawObject 35 | * 36 | * @SuppressWarnings("PHPMD.ExcessiveClassComplexity") 37 | */ 38 | abstract class XrefStream extends \Com\Tecnick\Pdf\Parser\Process\RawObject 39 | { 40 | /** 41 | * Process object indexes 42 | * 43 | * @param array{ 44 | * 'trailer': array{ 45 | * 'encrypt'?: string, 46 | * 'id': array, 47 | * 'info': string, 48 | * 'root': string, 49 | * 'size': int, 50 | * }, 51 | * 'xref': array, 52 | * } $xref XREF data 53 | * @param int $obj_num Object number 54 | * @param array> $sdata Stream data 55 | */ 56 | protected function processObjIndexes(array &$xref, int &$obj_num, array $sdata): void 57 | { 58 | foreach ($sdata as $sdatum) { 59 | switch ($sdatum[0]) { 60 | case 0: 61 | // (f) linked list of free objects 62 | break; 63 | case 1: 64 | // (n) objects that are in use but are not compressed 65 | // create unique object index: [object number]_[generation number] 66 | $index = $obj_num . '_' . $sdatum[2]; 67 | // check if object already exist 68 | if (! isset($xref['xref'][$index])) { 69 | // store object offset position 70 | $xref['xref'][$index] = $sdatum[1]; 71 | } 72 | 73 | break; 74 | case 2: 75 | // compressed objects 76 | // $row[1] = object number of the object stream in which this object is stored 77 | // $row[2] = index of this object within the object stream 78 | $index = $sdatum[1] . '_0_' . $sdatum[2]; 79 | $xref['xref'][$index] = -1; 80 | break; 81 | default: 82 | // null objects 83 | break; 84 | } 85 | 86 | ++$obj_num; 87 | } 88 | } 89 | 90 | /** 91 | * PNG Unpredictor 92 | * 93 | * @param array> $sdata Stream data 94 | * @param array> $ddata Decoded data 95 | * @param int $columns Number of columns 96 | * @param array $prev_row Previous row 97 | */ 98 | protected function pngUnpredictor(array $sdata, array &$ddata, int $columns, array $prev_row): void 99 | { 100 | // for each row apply PNG unpredictor 101 | foreach ($sdata as $key => $row) { 102 | // initialize new row 103 | $ddata[$key] = []; 104 | // get PNG predictor value 105 | $predictor = (10 + $row[0]); 106 | // for each byte on the row 107 | for ($idx = 1; $idx <= $columns; ++$idx) { 108 | // new index 109 | $jdx = ($idx - 1); 110 | $row_up = $prev_row[$jdx]; 111 | if ($idx == 1) { 112 | $row_left = 0; 113 | $row_upleft = 0; 114 | } else { 115 | $row_left = $row[($idx - 1)]; 116 | $row_upleft = $prev_row[($jdx - 1)]; 117 | } 118 | 119 | switch ($predictor) { 120 | case 10: 121 | // PNG prediction (on encoding, PNG None on all rows) 122 | $ddata[$key][$jdx] = $row[$idx]; 123 | break; 124 | case 11: 125 | // PNG prediction (on encoding, PNG Sub on all rows) 126 | $ddata[$key][$jdx] = (($row[$idx] + $row_left) & 0xff); 127 | break; 128 | case 12: 129 | // PNG prediction (on encoding, PNG Up on all rows) 130 | $ddata[$key][$jdx] = (($row[$idx] + $row_up) & 0xff); 131 | break; 132 | case 13: 133 | // PNG prediction (on encoding, PNG Average on all rows) 134 | $ddata[$key][$jdx] = (($row[$idx] + (($row_left + $row_up) / 2)) & 0xff); 135 | break; 136 | case 14: 137 | // PNG prediction (on encoding, PNG Paeth on all rows) 138 | $this->minDistance($ddata, $key, $row, $idx, $jdx, $row_left, $row_up, $row_upleft); 139 | break; 140 | default: 141 | // PNG prediction (on encoding, PNG optimum) 142 | throw new PPException('Unknown PNG predictor'); 143 | } 144 | } 145 | 146 | $prev_row = $ddata[$key]; 147 | } // end for each row 148 | } 149 | 150 | /** 151 | * Return minimum distance for PNG unpredictor 152 | * 153 | * @param array> $ddata Decoded data 154 | * @param int $key Key 155 | * @param array $row Row 156 | * @param int $idx Index 157 | * @param int $jdx Jdx 158 | * @param int $row_left Row left 159 | * @param int $row_up Row up 160 | * @param int $row_upleft Row upleft 161 | */ 162 | protected function minDistance( 163 | array &$ddata, 164 | int $key, 165 | array $row, 166 | int $idx, 167 | int $jdx, 168 | int $row_left, 169 | int $row_up, 170 | int $row_upleft, 171 | ): void { 172 | // initial estimate 173 | $pos = ($row_left + $row_up - $row_upleft); 174 | // distances 175 | $psa = abs($pos - $row_left); 176 | $psb = abs($pos - $row_up); 177 | $psc = abs($pos - $row_upleft); 178 | $pmin = min($psa, $psb, $psc); 179 | switch ($pmin) { 180 | case $psa: 181 | $ddata[$key][$jdx] = (($row[$idx] + $row_left) & 0xff); 182 | break; 183 | case $psb: 184 | $ddata[$key][$jdx] = (($row[$idx] + $row_up) & 0xff); 185 | break; 186 | case $psc: 187 | $ddata[$key][$jdx] = (($row[$idx] + $row_upleft) & 0xff); 188 | break; 189 | } 190 | } 191 | 192 | /** 193 | * Process XREF types 194 | * 195 | * @param array $sarr Stream data 196 | * @param array{ 197 | * 'trailer': array{ 198 | * 'encrypt'?: string, 199 | * 'id': array, 200 | * 'info': string, 201 | * 'root': string, 202 | * 'size': int, 203 | * }, 204 | * 'xref': array, 205 | * } $xref XREF data 206 | * @param array $wbt WBT data 207 | * @param int|null $index_first Index first 208 | * @param int|null $prevxref Previous XREF 209 | * @param int $columns Number of columns 210 | * @param bool $valid_crs Valid CRS 211 | * @param bool $filltrailer Fill trailer 212 | * 213 | * @SuppressWarnings("PHPMD.CyclomaticComplexity") 214 | */ 215 | protected function processXrefType( 216 | array $sarr, 217 | array &$xref, 218 | array &$wbt, 219 | ?int &$index_first, 220 | ?int &$prevxref, 221 | int &$columns, 222 | bool &$valid_crs, 223 | bool $filltrailer 224 | ): void { 225 | foreach ($sarr as $key => $val) { 226 | if ($val[0] !== '/') { 227 | continue; 228 | } 229 | 230 | if (! is_string($val[1])) { 231 | continue; 232 | } 233 | 234 | switch ($val[1]) { 235 | case 'Type': 236 | $valid_crs = (($sarr[($key + 1)][0] == '/') && ($sarr[($key + 1)][1] == 'XRef')); 237 | break; 238 | case 'Index': 239 | // first object number in the subsection 240 | $index_first = (int) $sarr[($key + 1)][1][0][1]; 241 | // number of entries in the subsection 242 | // $index_entries = intval($sarr[($key + 1)][1][1][1]); 243 | break; 244 | case 'Prev': 245 | $this->processXrefPrev($sarr, $key, $prevxref); 246 | break; 247 | case 'W': 248 | // number of bytes (in the decoded stream) of the corresponding field 249 | $wbt[0] = (int) $sarr[($key + 1)][1][0][1]; 250 | $wbt[1] = (int) $sarr[($key + 1)][1][1][1]; 251 | $wbt[2] = (int) $sarr[($key + 1)][1][2][1]; 252 | break; 253 | case 'DecodeParms': 254 | $this->processXrefDecodeParms($sarr, $key, $columns); 255 | break; 256 | } 257 | 258 | $this->processXrefTypeFt($val[1], $sarr, $key, $xref, $filltrailer); 259 | } 260 | } 261 | 262 | /** 263 | * Process XREF type Prev 264 | * 265 | * @param array $sarr Stream data 266 | * @param int $key Key 267 | * @param int|null $prevxref Previous XREF 268 | */ 269 | protected function processXrefPrev(array $sarr, int $key, ?int &$prevxref): void 270 | { 271 | if ($sarr[($key + 1)][0] == 'numeric') { 272 | // get previous xref offset 273 | $prevxref = (int) $sarr[($key + 1)][1]; 274 | } 275 | } 276 | 277 | /** 278 | * Process XREF type DecodeParms 279 | * 280 | * @param array $sarr Stream data 281 | * @param int $key Key 282 | * @param int $columns Number of columns 283 | */ 284 | protected function processXrefDecodeParms(array $sarr, int $key, int &$columns): void 285 | { 286 | $decpar = $sarr[($key + 1)][1]; 287 | if (! is_array($decpar)) { 288 | return; 289 | } 290 | 291 | foreach ($decpar as $kdc => $vdc) { 292 | if (($vdc[0] == '/') && ($vdc[1] == 'Columns') && ($decpar[($kdc + 1)][0] == 'numeric')) { 293 | $columns = (int) $decpar[($kdc + 1)][1]; 294 | break; 295 | } 296 | } 297 | 298 | $columns = max(0, $columns); 299 | } 300 | 301 | /** 302 | * Process XREF type 303 | * 304 | * @param string $type Type 305 | * @param array $sarr Stream data 306 | * @param int $key Key 307 | * @param array{ 308 | * 'trailer': array{ 309 | * 'encrypt'?: string, 310 | * 'id': array, 311 | * 'info': string, 312 | * 'root': string, 313 | * 'size': int, 314 | * }, 315 | * 'xref': array, 316 | * } $xref XREF data 317 | * @param bool $filltrailer Fill trailer 318 | */ 319 | protected function processXrefTypeFt(string $type, array $sarr, int $key, array &$xref, bool $filltrailer): void 320 | { 321 | if (! $filltrailer) { 322 | return; 323 | } 324 | 325 | switch ($type) { 326 | case 'Size': 327 | if ($sarr[($key + 1)][0] == 'numeric') { 328 | $xref['trailer']['size'] = (int) $sarr[($key + 1)][1]; 329 | } 330 | 331 | break; 332 | case 'ID': 333 | if ( 334 | empty($sarr[($key + 1)][1][0][1]) 335 | || empty($sarr[($key + 1)][1][1][1]) 336 | || !is_string($sarr[($key + 1)][1][0][1]) 337 | || !is_string($sarr[($key + 1)][1][1][1]) 338 | ) { 339 | break; 340 | } 341 | $xref['trailer']['id'] = []; 342 | $xref['trailer']['id'][0] = $sarr[($key + 1)][1][0][1]; 343 | $xref['trailer']['id'][1] = $sarr[($key + 1)][1][1][1]; 344 | break; 345 | default: 346 | $this->processXrefObjref($type, $sarr, $key, $xref); 347 | break; 348 | } 349 | } 350 | 351 | /** 352 | * Process XREF type Objref 353 | * 354 | * @param string $type Type 355 | * @param array $sarr Stream data 356 | * @param int $key Key 357 | * @param array{ 358 | * 'trailer': array{ 359 | * 'encrypt'?: string, 360 | * 'id': array, 361 | * 'info': string, 362 | * 'root': string, 363 | * 'size': int, 364 | * }, 365 | * 'xref': array, 366 | * } $xref XREF data 367 | */ 368 | protected function processXrefObjref(string $type, array $sarr, int $key, array &$xref): void 369 | { 370 | if ( 371 | empty($sarr[($key + 1)]) 372 | || empty($sarr[($key + 1)][1]) 373 | || !is_string($sarr[($key + 1)][1]) 374 | || ($sarr[($key + 1)][0] !== 'objref') 375 | ) { 376 | return; 377 | } 378 | 379 | $val = $sarr[($key + 1)][1]; 380 | 381 | switch ($type) { 382 | case 'Root': 383 | $xref['trailer']['root'] = $val; 384 | break; 385 | case 'Info': 386 | $xref['trailer']['info'] = $val; 387 | break; 388 | case 'Encrypt': 389 | $xref['trailer']['encrypt'] = $val; 390 | break; 391 | } 392 | } 393 | } 394 | -------------------------------------------------------------------------------- /test/ParserTest.php: -------------------------------------------------------------------------------- 1 | 10 | * @copyright 2011-2024 Nicola Asuni - Tecnick.com LTD 11 | * @license http://www.gnu.org/copyleft/lesser.html GNU-LGPL v3 (see LICENSE.TXT) 12 | * @link https://github.com/tecnickcom/tc-lib-pdf-parser 13 | * 14 | * This file is part of tc-lib-pdf-parser software library. 15 | */ 16 | 17 | namespace Test; 18 | 19 | use Com\Tecnick\Pdf\Parser\Parser; 20 | use PHPUnit\Framework\TestCase; 21 | use PHPUnit\Framework\Attributes\DataProvider; 22 | 23 | /** 24 | * Filter Test 25 | * 26 | * @since 2011-05-23 27 | * @category Library 28 | * @package PdfParser 29 | * @author Nicola Asuni 30 | * @copyright 2011-2024 Nicola Asuni - Tecnick.com LTD 31 | * @license http://www.gnu.org/copyleft/lesser.html GNU-LGPL v3 (see LICENSE.TXT) 32 | * @link https://github.com/tecnickcom/tc-lib-pdf-parser 33 | */ 34 | class ParserTest extends TestCase 35 | { 36 | #[DataProvider('getParseProvider')] 37 | public function testParse(string $filename, string $hash): void 38 | { 39 | $cfg = [ 40 | 'ignore_filter_errors' => true, 41 | ]; 42 | $rawdata = file_get_contents($filename); 43 | $this->assertNotFalse($rawdata); 44 | $parser = new Parser($cfg); 45 | $data = $parser->parse($rawdata); 46 | $this->assertEquals($hash, md5(serialize($data))); 47 | } 48 | 49 | /** 50 | * @return array 51 | */ 52 | public static function getParseProvider(): array 53 | { 54 | return [ 55 | ['resources/test/example_005.pdf', 'b1c58b8f34df2974a339f8fe2909cf59'], 56 | ['resources/test/example_036.pdf', '78cc03b354588660ccc1ec6453b4fdba'], 57 | ['resources/test/example_046.pdf', 'ba410ddc927da4b636d749b503b96252'], 58 | ]; 59 | } 60 | } 61 | --------------------------------------------------------------------------------