Initial commit

This commit is contained in:
2026-08-30 22:02:02 +00:00
commit b6bd2277f5
2334 changed files with 646393 additions and 0 deletions
+20
View File
@@ -0,0 +1,20 @@
# Ref: https://EditorConfig.org
# top-most EditorConfig file
root = true
# Unix-style end of lines and a blank line at the end of the file
[*]
indent_style = tab
end_of_line = lf
charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = true
[*.php]
indent_style = space
indent_size = 4
[*.{js,json,scss,css,yml,vue}]
indent_style = space
indent_size = 2
@@ -0,0 +1,22 @@
# Normalize text sources to LF in the repository and on checkout everywhere.
# Critical for a byte-level library: keeps source and fixtures byte-identical
# across Windows/macOS/Linux checkouts regardless of core.autocrlf.
*.php text eol=lf
*.md text eol=lf
*.xml text eol=lf
*.xml.dist text eol=lf
*.json text eol=lf
*.toml text eol=lf
*.yml text eol=lf
*.yaml text eol=lf
*.txt text eol=lf
Makefile text eol=lf
# Byte-exact fixtures must never be transformed (CRLF/auto-detection off).
test/**/*.bin -text
*.png binary
*.jpg binary
*.gif binary
*.pdf binary
*.ttf binary
*.otf binary
@@ -0,0 +1,29 @@
---
name: Bug report
about: Create a report to help us improve
title: ''
labels: ''
assignees: ''
---
**Describe the bug**
A clear and concise description of what the bug is.
**To Reproduce**
Steps to reproduce the behavior:
1. ...
**Expected behavior**
A clear and concise description of what you expected to happen.
**Logs**
If applicable, copy the relevant logs to help explain your problem.
**Environment:**
- OS:
- PHP version:
- Version:
**Additional context**
Add any other context about the problem here.
@@ -0,0 +1,20 @@
---
name: Feature request
about: Suggest an idea for this project
title: ''
labels: ''
assignees: ''
---
**Is your feature request related to a problem? Please describe.**
A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]
**Describe the solution you'd like**
A clear and concise description of what you want to happen.
**Describe alternatives you've considered**
A clear and concise description of any alternative solutions or features you've considered.
**Additional context**
Add any other context or screenshots about the feature request here.
@@ -0,0 +1,25 @@
# Description
Please include a summary of the change and include relevant motivation and context.
...
## Checklist:
- [ ] The `make buildall` command has been run successfully without any error or warning.
- [ ] Any new code line is covered by unit tests and the coverage has not dropped.
- [ ] Any new code follows the style guidelines of this project.
- [ ] The code changes have been self-reviewed.
- [ ] Corresponding changes to the documentation have been made.
- [ ] The version has been updated in the VERSION file.
## Type of change:
- [ ] Bug fix (non-breaking change which fixes an issue) → The patch number in the VERSION file has been increased.
- [ ] New feature (non-breaking change which adds functionality) → The minor number in the VERSION file has been increased.
- [ ] 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.
- [ ] Automation.
- [ ] Documentation.
- [ ] Example.
- [ ] Testing.
@@ -0,0 +1,59 @@
name: check
env:
XDEBUG_MODE: coverage
permissions:
contents: read
on:
push:
branches:
- 'main'
pull_request:
types: [opened, synchronize, reopened]
branches:
- main
workflow_dispatch:
jobs:
test-php:
name: Test on php ${{ matrix.php-version }} and ${{ matrix.os }}
runs-on: ${{ matrix.os }}
continue-on-error: ${{ matrix.experimental }}
strategy:
fail-fast: false
matrix:
php-version: ["8.2", "8.3", "8.4", "8.5"]
experimental: [false]
os: [ubuntu-latest]
coverage-extension: [pcov]
steps:
- uses: actions/checkout@v7
- name: Use php ${{ matrix.php-version }}
uses: shivammathur/setup-php@v2
with:
php-version: ${{ matrix.php-version }}
coverage: ${{ matrix.coverage-extension }}
extensions: bcmath, curl, date, gd, hash, imagick, json, mbstring, openssl, pcre, zlib
ini-values: display_errors=on, error_reporting=-1, zend.assertions=1
- name: List php modules
run: php -m
- name: List php modules using "no php ini" mode
run: php -m -n
- name: Cache module
uses: actions/cache@v6
with:
path: ~/.composer/cache/
key: composer-cache
- name: Install dependencies
env:
GH_TOKEN: ${{ github.token }}
run: make deps
- name: Run all tests
run: make qa
- name: Send coverage
uses: codecov/codecov-action@v7
with:
flags: php-${{ matrix.php-version }}-${{ matrix.os }}
name: php-${{ matrix.php-version }}-${{ matrix.os }}
@@ -0,0 +1,21 @@
.phpdoc
.phpunit.cache
.phpunit.result.cache
**/._*
**/.#*
**/.DS_Store
**/.idea
**/.vagrant
**/*.bak
**/*.tmp
**/auth.json
**/nbproject
**/temp.php
**/test.php
composer.lock
ecs.php
phpunit.xml
PLAN_*
rector.php
target
vendor
+1
View File
@@ -0,0 +1 @@
* @nicolaasuni
+128
View File
@@ -0,0 +1,128 @@
# Contributor Covenant Code of Conduct
## Our Pledge
We as members, contributors, and leaders pledge to make participation in our
community a harassment-free experience for everyone, regardless of age, body
size, visible or invisible disability, ethnicity, sex characteristics, gender
identity and expression, level of experience, education, socio-economic status,
nationality, personal appearance, race, religion, or sexual identity
and orientation.
We pledge to act and interact in ways that contribute to an open, welcoming,
diverse, inclusive, and healthy community.
## Our Standards
Examples of behavior that contributes to a positive environment for our
community include:
* Demonstrating empathy and kindness toward other people
* Being respectful of differing opinions, viewpoints, and experiences
* Giving and gracefully accepting constructive feedback
* Accepting responsibility and apologizing to those affected by our mistakes,
and learning from the experience
* Focusing on what is best not just for us as individuals, but for the
overall community
Examples of unacceptable behavior include:
* The use of sexualized language or imagery, and sexual attention or
advances of any kind
* Trolling, insulting or derogatory comments, and personal or political attacks
* Public or private harassment
* Publishing others' private information, such as a physical or email
address, without their explicit permission
* Other conduct which could reasonably be considered inappropriate in a
professional setting
## Enforcement Responsibilities
Community leaders are responsible for clarifying and enforcing our standards of
acceptable behavior and will take appropriate and fair corrective action in
response to any behavior that they deem inappropriate, threatening, offensive,
or harmful.
Community leaders have the right and responsibility to remove, edit, or reject
comments, commits, code, wiki edits, issues, and other contributions that are
not aligned to this Code of Conduct, and will communicate reasons for moderation
decisions when appropriate.
## Scope
This Code of Conduct applies within all community spaces, and also applies when
an individual is officially representing the community in public spaces.
Examples of representing our community include using an official e-mail address,
posting via an official social media account, or acting as an appointed
representative at an online or offline event.
## Enforcement
Instances of abusive, harassing, or otherwise unacceptable behavior may be
reported to the community leaders responsible for enforcement at
.
All complaints will be reviewed and investigated promptly and fairly.
All community leaders are obligated to respect the privacy and security of the
reporter of any incident.
## Enforcement Guidelines
Community leaders will follow these Community Impact Guidelines in determining
the consequences for any action they deem in violation of this Code of Conduct:
### 1. Correction
**Community Impact**: Use of inappropriate language or other behavior deemed
unprofessional or unwelcome in the community.
**Consequence**: A private, written warning from community leaders, providing
clarity around the nature of the violation and an explanation of why the
behavior was inappropriate. A public apology may be requested.
### 2. Warning
**Community Impact**: A violation through a single incident or series
of actions.
**Consequence**: A warning with consequences for continued behavior. No
interaction with the people involved, including unsolicited interaction with
those enforcing the Code of Conduct, for a specified period of time. This
includes avoiding interactions in community spaces as well as external channels
like social media. Violating these terms may lead to a temporary or
permanent ban.
### 3. Temporary Ban
**Community Impact**: A serious violation of community standards, including
sustained inappropriate behavior.
**Consequence**: A temporary ban from any sort of interaction or public
communication with the community for a specified period of time. No public or
private interaction with the people involved, including unsolicited interaction
with those enforcing the Code of Conduct, is allowed during this period.
Violating these terms may lead to a permanent ban.
### 4. Permanent Ban
**Community Impact**: Demonstrating a pattern of violation of community
standards, including sustained inappropriate behavior, harassment of an
individual, or aggression toward or disparagement of classes of individuals.
**Consequence**: A permanent ban from any sort of public interaction within
the community.
## Attribution
This Code of Conduct is adapted from the [Contributor Covenant][homepage],
version 2.0, available at
https://www.contributor-covenant.org/version/2/0/code_of_conduct.html.
Community Impact Guidelines were inspired by [Mozilla's code of conduct
enforcement ladder](https://github.com/mozilla/diversity).
[homepage]: https://www.contributor-covenant.org
For answers to common questions about this code of conduct, see the FAQ at
https://www.contributor-covenant.org/faq. Translations are available at
https://www.contributor-covenant.org/translations.
+194
View File
@@ -0,0 +1,194 @@
# Contributing to tc-lib-pdf-page
Thank you for your interest in contributing to **tc-lib-pdf-page**.
Contributions of all kinds are welcome: bug reports, bug fixes, documentation improvements, new features, and refactors.
Please take a moment to read this guide before opening an issue or pull request.
---
## Table of Contents
- [Code of Conduct](#code-of-conduct)
- [Security Vulnerabilities](#security-vulnerabilities)
- [Getting Started](#getting-started)
- [Reporting a Bug](#reporting-a-bug)
- [Submitting a Bug Fix](#submitting-a-bug-fix)
- [Proposing a New Feature](#proposing-a-new-feature)
- [Development Workflow](#development-workflow)
- [Coding Standards](#coding-standards)
- [Testing](#testing)
- [Pull Request Guidelines](#pull-request-guidelines)
- [Commit Message Guidelines](#commit-message-guidelines)
---
## Code of Conduct
This project follows the [Contributor Covenant Code of Conduct](CODE_OF_CONDUCT.md). By participating you agree to abide by its terms. Please report unacceptable behaviour to [info@tecnick.com](mailto:info@tecnick.com).
---
## Security Vulnerabilities
**Do not open a public GitHub issue for security vulnerabilities.**
Please follow the [Security Policy](SECURITY.md) and report them privately.
---
## Getting Started
### Requirements
- PHP **≥ 8.2**
- [Composer](https://getcomposer.org/) v2
- `make`, `git`
- Optional: `rpmbuild` (RPM packaging), `dpkg-buildpackage` (DEB packaging)
### Local setup
```bash
git clone https://github.com/tecnickcom/tc-lib-pdf-page.git
cd tc-lib-pdf-page
make buildall
```
To verify everything is working after a change:
```bash
make qa
```
This runs linting, static analysis, and the full unit-test suite with coverage.
---
## Reporting a Bug
Before opening an issue:
1. **Check the [Security Policy](SECURITY.md)** — if the bug is a security vulnerability, do not file a public issue.
2. **Search [existing issues](https://github.com/tecnickcom/tc-lib-pdf-page/issues)** to avoid duplicates.
If no existing issue matches, [open a new one](https://github.com/tecnickcom/tc-lib-pdf-page/issues/new) and include:
- A **clear title and description** of the problem.
- The **library version** (`composer show tecnickcom/tc-lib-pdf-page`) and PHP version.
- A **minimal, self-contained reproduction** — a short PHP script or a failing PHPUnit test case is ideal.
- **Expected vs. actual behaviour** — what you expected to happen and what actually happened.
- Any relevant **stack trace or error output**.
The more precise and reproducible the report, the faster it can be triaged and fixed.
---
## Submitting a Bug Fix
1. [Fork the repository](https://github.com/tecnickcom/tc-lib-pdf-page/fork) and create a branch from `main`:
```bash
git checkout -b fix/short-description-of-bug
```
2. Make your changes, following the [Coding Standards](#coding-standards) below.
3. Add or update unit tests to cover the changes.
4. Run the full quality-assurance suite locally and ensure it passes:
```bash
make qa
```
5. Commit your changes (see [Commit Message Guidelines](#commit-message-guidelines)).
6. Open a pull request against `main` and fill in the PR template:
- Describe the problem and your solution.
- Reference the related issue number (e.g. `Fixes #123`).
---
## Proposing a New Feature
Before writing any code:
1. **Open a Feature Request** on [GitHub Issues](https://github.com/tecnickcom/tc-lib-pdf-page/issues/new) describing the use case and proposed API.
2. Wait for feedback from the maintainer. This avoids investing time in a direction that may not be accepted.
Once the feature is agreed upon, follow the same branch → code → test → PR workflow as for bug fixes, using a branch named `feature/short-description`.
---
## Development Workflow
The `Makefile` exposes all common development tasks:
| Command | Description |
|---------|-------------|
| `make qa` | Run linting, static analysis, tests, and reports |
| `make test` | Run PHPUnit with code coverage |
| `make lint` | Check coding standards |
| `make format` | Auto-format the code |
| `make buildall` | Install dependencies, fix style, run QA, and build packages |
| `make clean` | Remove `vendor/` and `target/` directories |
| `make server` | Start the built-in PHP development server for the examples |
Run `make help` to see the full list of available targets.
---
## Coding Standards
- The codebase follows **PSR-12** for formatting.
- Run `make format` to auto-format the code.
- Run `make lint` to catch remaining issues.
- All source files live under `src/`, all tests under `test/`.
- Use strict types and explicit visibility on all class members.
- Avoid introducing new external dependencies without prior discussion.
---
## Testing
Tests are written with [PHPUnit](https://phpunit.de/) and live in `test/`.
```bash
# Run the full test suite with coverage
make test
# Run a specific test file
XDEBUG_MODE=coverage ./vendor/bin/phpunit test/HTMLTest.php
```
Requirements for contributions:
- Every bug fix must be accompanied by a regression test that fails before the fix and passes after.
- Every new feature must be accompanied by tests that cover both the happy path and edge cases.
Coverage reports are generated in `target/coverage/`.
---
## Pull Request Guidelines
- Target the `main` branch.
- Keep PRs focused — one fix or feature per PR.
- Ensure `make qa` passes locally before opening the PR.
- Do not bump the version number in your PR; that is handled by the maintainer at release time.
- Be responsive to review feedback; stale PRs may be closed after an extended period of inactivity.
---
## Commit Message Guidelines
Use concise, imperative-mood commit messages:
```
fix: correct path traversal in font loader
feat: add support for XYZ
test: add regression test for #123
docs: update CONTRIBUTING workflow
refactor: extract text measurement into helper
```
Prefix tags: `fix`, `feat`, `test`, `docs`, `refactor`, `chore`, `ci`.
Reference issues where relevant: `fix: correct X (closes #42)`.
---
## Questions?
If you have a question that is not covered here, feel free to open a [GitHub Discussion](https://github.com/tecnickcom/tc-lib-pdf-page/discussions) or contact the maintainer at [info@tecnick.com](mailto:info@tecnick.com).
+862
View File
@@ -0,0 +1,862 @@
**********************************************************************
* LICENSE
*
* SOFTWARE : tc-lib-pdf-page
* AUTHOR : Nicola Asuni <info@tecnick.com>
* COPYRIGHT : 2011-2026 Nicola Asuni - Tecnick.com LTD
**********************************************************************
This is free software: you can redistribute it and/or modify it
under the terms of the GNU Lesser General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
**********************************************************************
**********************************************************************
GNU LESSER GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://www.fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
This version of the GNU Lesser General Public License incorporates
the terms and conditions of version 3 of the GNU General Public
License, supplemented by the additional permissions listed below.
0. Additional Definitions.
As used herein, "this License" refers to version 3 of the GNU Lesser
General Public License, and the "GNU GPL" refers to version 3 of the GNU
General Public License.
"The Library" refers to a covered work governed by this License,
other than an Application or a Combined Work as defined below.
An "Application" is any work that makes use of an interface provided
by the Library, but which is not otherwise based on the Library.
Defining a subclass of a class defined by the Library is deemed a mode
of using an interface provided by the Library.
A "Combined Work" is a work produced by combining or linking an
Application with the Library. The particular version of the Library
with which the Combined Work was made is also called the "Linked
Version".
The "Minimal Corresponding Source" for a Combined Work means the
Corresponding Source for the Combined Work, excluding any source code
for portions of the Combined Work that, considered in isolation, are
based on the Application, and not on the Linked Version.
The "Corresponding Application Code" for a Combined Work means the
object code and/or source code for the Application, including any data
and utility programs needed for reproducing the Combined Work from the
Application, but excluding the System Libraries of the Combined Work.
1. Exception to Section 3 of the GNU GPL.
You may convey a covered work under sections 3 and 4 of this License
without being bound by section 3 of the GNU GPL.
2. Conveying Modified Versions.
If you modify a copy of the Library, and, in your modifications, a
facility refers to a function or data to be supplied by an Application
that uses the facility (other than as an argument passed when the
facility is invoked), then you may convey a copy of the modified
version:
a) under this License, provided that you make a good faith effort to
ensure that, in the event an Application does not supply the
function or data, the facility still operates, and performs
whatever part of its purpose remains meaningful, or
b) under the GNU GPL, with none of the additional permissions of
this License applicable to that copy.
3. Object Code Incorporating Material from Library Header Files.
The object code form of an Application may incorporate material from
a header file that is part of the Library. You may convey such object
code under terms of your choice, provided that, if the incorporated
material is not limited to numerical parameters, data structure
layouts and accessors, or small macros, inline functions and templates
(ten or fewer lines in length), you do both of the following:
a) Give prominent notice with each copy of the object code that the
Library is used in it and that the Library and its use are
covered by this License.
b) Accompany the object code with a copy of the GNU GPL and this license
document.
4. Combined Works.
You may convey a Combined Work under terms of your choice that,
taken together, effectively do not restrict modification of the
portions of the Library contained in the Combined Work and reverse
engineering for debugging such modifications, if you also do each of
the following:
a) Give prominent notice with each copy of the Combined Work that
the Library is used in it and that the Library and its use are
covered by this License.
b) Accompany the Combined Work with a copy of the GNU GPL and this license
document.
c) For a Combined Work that displays copyright notices during
execution, include the copyright notice for the Library among
these notices, as well as a reference directing the user to the
copies of the GNU GPL and this license document.
d) Do one of the following:
0) Convey the Minimal Corresponding Source under the terms of this
License, and the Corresponding Application Code in a form
suitable for, and under terms that permit, the user to
recombine or relink the Application with a modified version of
the Linked Version to produce a modified Combined Work, in the
manner specified by section 6 of the GNU GPL for conveying
Corresponding Source.
1) Use a suitable shared library mechanism for linking with the
Library. A suitable mechanism is one that (a) uses at run time
a copy of the Library already present on the user's computer
system, and (b) will operate properly with a modified version
of the Library that is interface-compatible with the Linked
Version.
e) Provide Installation Information, but only if you would otherwise
be required to provide such information under section 6 of the
GNU GPL, and only to the extent that such information is
necessary to install and execute a modified version of the
Combined Work produced by recombining or relinking the
Application with a modified version of the Linked Version. (If
you use option 4d0, the Installation Information must accompany
the Minimal Corresponding Source and Corresponding Application
Code. If you use option 4d1, you must provide the Installation
Information in the manner specified by section 6 of the GNU GPL
for conveying Corresponding Source.)
5. Combined Libraries.
You may place library facilities that are a work based on the
Library side by side in a single library together with other library
facilities that are not Applications and are not covered by this
License, and convey such a combined library under terms of your
choice, if you do both of the following:
a) Accompany the combined library with a copy of the same work based
on the Library, uncombined with any other library facilities,
conveyed under the terms of this License.
b) Give prominent notice with the combined library that part of it
is a work based on the Library, and explaining where to find the
accompanying uncombined form of the same work.
6. Revised Versions of the GNU Lesser General Public License.
The Free Software Foundation may publish revised and/or new versions
of the GNU Lesser General Public License from time to time. Such new
versions will be similar in spirit to the present version, but may
differ in detail to address new problems or concerns.
Each version is given a distinguishing version number. If the
Library as you received it specifies that a certain numbered version
of the GNU Lesser General Public License "or any later version"
applies to it, you have the option of following the terms and
conditions either of that published version or of any later version
published by the Free Software Foundation. If the Library as you
received it does not specify a version number of the GNU Lesser
General Public License, you may choose any version of the GNU Lesser
General Public License ever published by the Free Software Foundation.
If the Library as you received it specifies that a proxy can decide
whether future versions of the GNU Lesser General Public License shall
apply, that proxy's public statement of acceptance of any version is
permanent authorization for you to choose that version for the
Library.
**********************************************************************
**********************************************************************
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://www.fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<https://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<https://www.gnu.org/philosophy/why-not-lgpl.html>.
**********************************************************************
**********************************************************************
+280
View File
@@ -0,0 +1,280 @@
# makefile
#
# @since 2015-05-14
# @category Library
# @package PdfPage
# @author Nicola Asuni <info@tecnick.com>
# @copyright 2011-2026 Nicola Asuni - Tecnick.com LTD
# @license https://www.gnu.org/copyleft/lesser.html GNU-LGPL v3 (see LICENSE)
# @link https://github.com/tecnickcom/tc-lib-pdf-page
#
# This file is part of tc-lib-pdf-page software library.
# ----------------------------------------------------------------------------------------------------------------------
SHELL=/bin/bash
.SHELLFLAGS=-o pipefail -c
# Project owner
OWNER=tecnickcom
# Project vendor
VENDOR=${OWNER}
# Project name
PROJECT=tc-lib-pdf-page
# Project version
VERSION=$(shell cat VERSION)
# Project release number (packaging build number)
RELEASE=$(shell cat RELEASE)
# Name of RPM or DEB package
PKGNAME=php-${OWNER}-${PROJECT}
# Data dir
DATADIR=usr/share
# PHP home folder
PHPHOME=${DATADIR}/php/Com/Tecnick
# Default installation path for code
LIBPATH=${PHPHOME}/Pdf/Page/
# Path for configuration files (etc/$(PKGNAME)/)
CONFIGPATH=
# Default installation path for documentation
DOCPATH=${DATADIR}/doc/$(PKGNAME)/
# Installation path for the code
PATHINSTBIN=$(DESTDIR)/$(LIBPATH)
# Installation path for the configuration files
PATHINSTCFG=$(DESTDIR)/$(CONFIGPATH)
# Installation path for documentation
PATHINSTDOC=$(DESTDIR)/$(DOCPATH)
# Current directory
CURRENTDIR=$(CURDIR)/
# Target directory
TARGETDIR=target
# RPM Packaging path (where RPMs will be stored)
PATHRPMPKG=$(TARGETDIR)/RPM
# RPM local database path (avoid host rpmdb permission issues)
RPMDBPATH=$(PATHRPMPKG)/.rpmdb
# DEB Packaging path (where DEBs will be stored)
PATHDEBPKG=$(TARGETDIR)/DEB
# BZ2 Packaging path (where BZ2s will be stored)
PATHBZ2PKG=$(TARGETDIR)/BZ2
# sed argument for in-place substitutions
SEDINPLACE=-i
ifeq ($(shell uname -s),Darwin)
SEDINPLACE=-i ''
endif
# Default port number for the example server
PORT?=8000
# PHP binary
PHP=$(shell which php)
# Composer executable (disable APC to as a work-around of a bug)
COMPOSER=$(PHP) -d "apc.enable_cli=0" $(shell which composer)
# phpDocumentor executable file
PHPDOC=$(shell which phpDocumentor)
# Mago version
MAGOVERSION=1.43.0
# --- MAKE TARGETS ---
# Display general help about this command
.PHONY: help
help:
@echo ""
@echo "$(PROJECT) Makefile."
@echo "The following commands are available:"
@echo ""
@awk '/^## /{desc=substr($$0,4)} /^\.PHONY:/{if(NF>1) {target=$$2; if(desc) printf " make %-15s: %s\n",target,desc; desc=""}}' Makefile
@echo ""
@echo "To test and build everything from scratch, use the shortcut:"
@echo " make x"
@echo ""
# alias for help target
.PHONY: all
all: help
# Full build and test sequence
.PHONY: x
x: buildall
## Full build and test sequence
.PHONY: buildall
buildall: deps format qa bz2 rpm deb
## Package the library in a compressed bz2 archive
.PHONY: bz2
bz2:
rm -rf "$(PATHBZ2PKG)"
make install DESTDIR="$(PATHBZ2PKG)"
tar -jcvf "$(PATHBZ2PKG)/$(PKGNAME)-$(VERSION)-$(RELEASE).tbz2" -C "$(PATHBZ2PKG)" "$(DATADIR)"
## Delete the vendor and target directories
.PHONY: clean
clean:
rm -rf ./vendor "$(TARGETDIR)"
## Build a DEB package for Debian-like Linux distributions
.PHONY: deb
deb:
rm -rf "$(PATHDEBPKG)"
$(MAKE) install DESTDIR="$(PATHDEBPKG)/$(PKGNAME)-$(VERSION)"
rm -f "$(PATHDEBPKG)/$(PKGNAME)-$(VERSION)/$(DOCPATH)LICENSE"
tar -zcvf "$(PATHDEBPKG)/$(PKGNAME)_$(VERSION).orig.tar.gz" -C "$(PATHDEBPKG)/" "$(PKGNAME)-$(VERSION)"
cp -rf ./resources/debian "$(PATHDEBPKG)/$(PKGNAME)-$(VERSION)/debian"
find "$(PATHDEBPKG)/$(PKGNAME)-$(VERSION)/debian/" -type f -name '*.bak' -delete
chmod 755 "$(PATHDEBPKG)/$(PKGNAME)-$(VERSION)/debian/rules"
find "$(PATHDEBPKG)/$(PKGNAME)-$(VERSION)/debian/" -type f -exec sed $(SEDINPLACE) "s/~#DATE#~/`date -R`/" {} \;
find "$(PATHDEBPKG)/$(PKGNAME)-$(VERSION)/debian/" -type f -exec sed $(SEDINPLACE) "s/~#VENDOR#~/$(VENDOR)/" {} \;
find "$(PATHDEBPKG)/$(PKGNAME)-$(VERSION)/debian/" -type f -exec sed $(SEDINPLACE) "s/~#PROJECT#~/$(PROJECT)/" {} \;
find "$(PATHDEBPKG)/$(PKGNAME)-$(VERSION)/debian/" -type f -exec sed $(SEDINPLACE) "s/~#PKGNAME#~/$(PKGNAME)/" {} \;
find "$(PATHDEBPKG)/$(PKGNAME)-$(VERSION)/debian/" -type f -exec sed $(SEDINPLACE) "s/~#VERSION#~/$(VERSION)/" {} \;
find "$(PATHDEBPKG)/$(PKGNAME)-$(VERSION)/debian/" -type f -exec sed $(SEDINPLACE) "s/~#RELEASE#~/$(RELEASE)/" {} \;
echo "$(LIBPATH)" > "$(PATHDEBPKG)/$(PKGNAME)-$(VERSION)/debian/$(PKGNAME).dirs"
echo "$(LIBPATH)* $(LIBPATH)" > "$(PATHDEBPKG)/$(PKGNAME)-$(VERSION)/debian/install"
echo "$(DOCPATH)" >> "$(PATHDEBPKG)/$(PKGNAME)-$(VERSION)/debian/$(PKGNAME).dirs"
echo "$(DOCPATH)* $(DOCPATH)" >> "$(PATHDEBPKG)/$(PKGNAME)-$(VERSION)/debian/install"
ifneq ($(strip $(CONFIGPATH)),)
echo "$(CONFIGPATH)" >> "$(PATHDEBPKG)/$(PKGNAME)-$(VERSION)/debian/$(PKGNAME).dirs"
echo "$(CONFIGPATH)* $(CONFIGPATH)" >> "$(PATHDEBPKG)/$(PKGNAME)-$(VERSION)/debian/install"
endif
echo "new-package-should-close-itp-bug" > "$(PATHDEBPKG)/$(PKGNAME)-$(VERSION)/debian/$(PKGNAME).lintian-overrides"
cd "$(PATHDEBPKG)/$(PKGNAME)-$(VERSION)" && debuild -us -uc
## Clean all artifacts and download all dependencies
.PHONY: deps
deps: ensuretarget
rm -rf ./vendor/*
($(COMPOSER) install -vvv --no-interaction)
curl --proto '=https' --tlsv1.2 --silent --show-error --fail --location https://carthage.software/mago.sh | bash -s -- --install-dir=./vendor/bin --version=$(MAGOVERSION)
## Generate source code documentation
.PHONY: doc
doc: ensuretarget
rm -rf "$(TARGETDIR)/doc"
$(PHPDOC) -d ./src -t "$(TARGETDIR)/doc/"
## Create missing target directories for test and build artifacts
.PHONY: ensuretarget
ensuretarget:
mkdir -p "$(TARGETDIR)/test"
mkdir -p "$(TARGETDIR)/report"
mkdir -p "$(TARGETDIR)/doc"
## Install this application
.PHONY: install
install: uninstall
mkdir -p "$(PATHINSTBIN)"
cp -rf ./src/* "$(PATHINSTBIN)"
cp -f ./resources/autoload.php "$(PATHINSTBIN)"
find "$(PATHINSTBIN)" -type d -exec chmod 755 {} \;
find "$(PATHINSTBIN)" -type f -exec chmod 644 {} \;
mkdir -p "$(PATHINSTDOC)"
cp -f ./LICENSE "$(PATHINSTDOC)"
cp -f ./README.md "$(PATHINSTDOC)"
cp -f ./VERSION "$(PATHINSTDOC)"
cp -f ./RELEASE "$(PATHINSTDOC)"
chmod -R 644 "$(PATHINSTDOC)"*
ifneq ($(strip $(CONFIGPATH)),)
mkdir -p "$(PATHINSTCFG)"
touch -c "$(PATHINSTCFG)"*
cp -ru "./resources/${CONFIGPATH}"* "$(PATHINSTCFG)"
find "$(PATHINSTCFG)" -type d -exec chmod 755 {} \;
find "$(PATHINSTCFG)" -type f -exec chmod 644 {} \;
endif
## Format the source code
.PHONY: format
format:
./vendor/bin/mago fmt src test
## Analyze and Lint the source code
.PHONY: lint
lint:
./vendor/bin/mago --config ./mago.src.toml analyze src
./vendor/bin/mago --config ./mago.test.toml analyze test
./vendor/bin/mago --config ./mago.src.toml lint src
./vendor/bin/mago --config ./mago.test.toml lint test
## Run all tests and reports
.PHONY: qa
qa: ensuretarget lint test report
## Generate various reports
.PHONY: report
report: ensuretarget
./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
#./vendor/bartlett/php-compatinfo/bin/phpcompatinfo --no-ansi analyser:run src/ > $(TARGETDIR)/report/phpcompatinfo.txt
## Build the RPM package for RedHat-like Linux distributions
.PHONY: rpm
rpm:
@test $(words $(CURDIR)) -eq 1 || { echo "ERROR: rpmbuild does not support spaces in the project path: $(CURDIR)"; exit 1; }
rm -rf "$(PATHRPMPKG)"
mkdir -p "$(RPMDBPATH)" "$(PATHRPMPKG)/tmp"
rpmbuild \
--define "_topdir $(CURRENTDIR)$(PATHRPMPKG)" \
--define "_dbpath $(CURRENTDIR)$(RPMDBPATH)" \
--define "_tmppath $(CURRENTDIR)$(PATHRPMPKG)/tmp" \
--define "_vendor $(VENDOR)" \
--define "_owner $(OWNER)" \
--define "_project $(PROJECT)" \
--define "_package $(PKGNAME)" \
--define "_version $(VERSION)" \
--define "_release $(RELEASE)" \
--define "_current_directory $(CURRENTDIR)" \
--define "_libpath /$(LIBPATH)" \
--define "_docpath /$(DOCPATH)" \
--define "_configpath /$(CONFIGPATH)" \
-bb resources/rpm/rpm.spec
## Start the development server
.PHONY: server
server:
$(PHP) -t example -S localhost:$(PORT)
## Tag this GIT version
.PHONY: tag
tag:
git checkout main && \
git tag -a ${VERSION} -m "Release ${VERSION}" && \
git push origin --tags && \
git pull
## Run unit tests
.PHONY: test
test:
cp phpunit.xml.dist phpunit.xml
#./vendor/bin/phpunit --migrate-configuration || true
XDEBUG_MODE=coverage ./vendor/bin/phpunit --stderr test
## Remove all installed files
.PHONY: uninstall
uninstall:
rm -rf "$(PATHINSTBIN)"
rm -rf "$(PATHINSTDOC)"
## Increase the version patch number
.PHONY: versionup
versionup:
echo ${VERSION} | gawk -F. '{printf("%d.%d.%d\n",$$1,$$2,(($$3+1)));}' > VERSION
+112
View File
@@ -0,0 +1,112 @@
# tc-lib-pdf-page
> Page geometry, boxes, and format definitions for PDF documents.
[![Latest Stable Version](https://poser.pugx.org/tecnickcom/tc-lib-pdf-page/version)](https://packagist.org/packages/tecnickcom/tc-lib-pdf-page)
[![Build](https://github.com/tecnickcom/tc-lib-pdf-page/actions/workflows/check.yml/badge.svg)](https://github.com/tecnickcom/tc-lib-pdf-page/actions/workflows/check.yml)
[![Coverage](https://codecov.io/gh/tecnickcom/tc-lib-pdf-page/graph/badge.svg?token=F6CPFHI3ED)](https://codecov.io/gh/tecnickcom/tc-lib-pdf-page)
[![License](https://poser.pugx.org/tecnickcom/tc-lib-pdf-page/license)](https://packagist.org/packages/tecnickcom/tc-lib-pdf-page)
[![Downloads](https://poser.pugx.org/tecnickcom/tc-lib-pdf-page/downloads)](https://packagist.org/packages/tecnickcom/tc-lib-pdf-page)
[![Sponsor on GitHub](https://img.shields.io/badge/sponsor-github-EA4AAA.svg?logo=githubsponsors&logoColor=white)](https://github.com/sponsors/tecnickcom)
> 💖 Part of the [tc-lib-pdf / TCPDF](https://github.com/tecnickcom/tc-lib-pdf) ecosystem (100M+ installs). [Sponsor its maintenance →](https://github.com/sponsors/tecnickcom)
---
## Overview
`tc-lib-pdf-page` manages page sizing, orientation, box definitions, and related geometry metadata.
It provides the structural model that document builders use to define media boxes, orientation changes, and page-level defaults consistently. Centralizing these rules improves correctness in multi-page layouts and simplifies downstream rendering code.
| | |
|---|---|
| **Namespace** | `\Com\Tecnick\Pdf\Page` |
| **Author** | Nicola Asuni <info@tecnick.com> |
| **License** | [GNU LGPL v3](https://www.gnu.org/copyleft/lesser.html) - see [LICENSE](LICENSE) |
| **API docs** | <https://tcpdf.org/docs/srcdoc/tc-lib-pdf-page> |
| **Packagist** | <https://packagist.org/packages/tecnickcom/tc-lib-pdf-page> |
---
## Features
### Page Model
- Standard and custom page size handling
- Orientation and unit conversion helpers
- Region and box definitions (CropBox, TrimBox, and related metadata)
### Integration
- Supports PDF composition stacks that need deterministic page geometry
- Pairs with color/encryption libraries for complete page objects
- Typed exceptions for invalid layout parameters
---
## Requirements
- PHP 8.2 or later
- Extension: `zlib`
- Composer
---
## Installation
```bash
composer require tecnickcom/tc-lib-pdf-page
```
---
## Quick Start
```php
<?php
require_once __DIR__ . '/vendor/autoload.php';
$page = new \Com\Tecnick\Pdf\Page\Page(
'mm',
new \Com\Tecnick\Color\Pdf(),
new \Com\Tecnick\Pdf\Encrypt\Encrypt(false),
false,
false
);
$dims = $page->setBox([], 'CropBox', 0, 0, 210, 297);
var_dump($dims['CropBox']);
```
---
## Development
```bash
make deps
make help
make qa
```
---
## Packaging
```bash
make rpm
make deb
```
For system packages, bootstrap with:
```php
require_once '/usr/share/php/Com/Tecnick/Pdf/Page/autoload.php';
```
---
## Contributing
Contributions are welcome. Please review [CONTRIBUTING.md](CONTRIBUTING.md), [CODE_OF_CONDUCT.md](CODE_OF_CONDUCT.md), and [SECURITY.md](SECURITY.md).
+1
View File
@@ -0,0 +1 @@
1
+62
View File
@@ -0,0 +1,62 @@
# Security Policy
This document describes the security policy for **tc-lib-pdf-page**.
---
## Supported Versions
Security fixes are applied only to the **latest stable release** on the `main` branch.
We strongly recommend always running the latest release.
---
## Reporting a Vulnerability
**Please do not open a public GitHub issue for security vulnerabilities.**
If you discover a security vulnerability — or suspect one — follow responsible disclosure:
1. **Email** the maintainer directly at **[info@tecnick.com](mailto:info@tecnick.com)** with the subject line:
`[SECURITY] tc-lib-pdf-page <brief description>`
2. Include as much detail as possible (see [What to include](#what-to-include) below).
3. You will receive an acknowledgement as soon as possible.
4. We will work on a fix or mitigation as promptly as the complexity of the issue allows.
If you do not receive a timely response, please follow up by replying to the same email thread.
---
## What to Include
A high-quality report helps us triage and fix issues faster. Please provide:
- **Description** — a clear summary of the vulnerability and its potential impact.
- **Affected component** — which class, method, or feature is involved (e.g., `HTML::render()`, font loading, image processing).
- **Steps to reproduce** — a minimal, self-contained PHP script or unit test that demonstrates the issue.
- **Expected vs. actual behaviour** — what you expected to happen and what actually happened.
- **Environment** — PHP version, OS, library version (output of `composer show tecnickcom/tc-lib-pdf-page`).
- **CVE / CWE reference** (optional) — if you have already identified a relevant classification.
- **Suggested fix** (optional) — a patch or proposed mitigation if you have one.
---
## Security Best Practices for Integrators
Integrators are responsible for sanitising input **before** passing it to the library. We recommend:
- **Validate and sanitise all user-supplied data**. Use a dedicated sanitiser when accepting content from end users.
- **Keep dependencies up to date.** Run `composer update` regularly and monitor advisories via [Packagist Security Advisories](https://packagist.org/packages/tecnickcom/tc-lib-pdf-page) or tools such as `composer audit`.
- **Pin versions in production.** Use `composer.lock` and review changes on every update.
---
## Contact
| Channel | Details |
|---------|---------|
| Security email | [info@tecnick.com](mailto:info@tecnick.com) |
| Project website | <https://tcpdf.org> |
| GitHub repository | <https://github.com/tecnickcom/tc-lib-pdf-page> |
| Packagist | <https://packagist.org/packages/tecnickcom/tc-lib-pdf-page> |
+1
View File
@@ -0,0 +1 @@
4.14.2
+63
View File
@@ -0,0 +1,63 @@
{
"name": "tecnickcom/tc-lib-pdf-page",
"description": "PHP library containing PDF page formats and definitions",
"type": "library",
"homepage": "https://tcpdf.org",
"license": "LGPL-3.0-or-later",
"keywords": [
"tc-lib-pdf-page",
"PDF",
"page",
"format"
],
"authors": [
{
"name": "Nicola Asuni",
"email": "info@tecnick.com",
"role": "lead"
}
],
"funding": [
{
"type": "github",
"url": "https://github.com/sponsors/tecnickcom"
}
],
"require": {
"php": ">=8.2",
"ext-zlib": "*",
"tecnickcom/tc-lib-color": "^2.13",
"tecnickcom/tc-lib-pdf-encrypt": "^2.9"
},
"minimum-stability": "stable",
"prefer-stable": true,
"require-dev": {
"pdepend/pdepend": "^2.16",
"phpunit/phpunit": "^11.5 || ^12.5 || ^13.2"
},
"autoload": {
"psr-4": {
"Com\\Tecnick\\Pdf\\Page\\": "src"
}
},
"autoload-dev": {
"psr-4": {
"Test\\": "test"
}
},
"support": {
"issues": "https://github.com/tecnickcom/tc-lib-pdf-page/issues",
"source": "https://github.com/tecnickcom/tc-lib-pdf-page"
},
"scripts": {
"test": "@php -d xdebug.mode=coverage vendor/bin/phpunit --stderr test",
"analyse": ["@analyse:src", "@analyse:test"],
"analyse:src": "mago --config mago.src.toml analyze src",
"analyse:test": "mago --config mago.test.toml analyze test",
"cs-check": ["@cs-check:src", "@cs-check:test"],
"cs-check:src": "mago --config mago.src.toml lint src",
"cs-check:test": "mago --config mago.test.toml lint test",
"cs-fix": "mago fmt src test",
"qa": ["@cs-check", "@analyse", "@test"]
}
}
+57
View File
@@ -0,0 +1,57 @@
#:schema https://mago.carthage.software/1.43.0/schema.json
version = "1"
php-version = "8.2.0"
[source]
workspace = "."
paths = ["src"]
includes = ["vendor"]
excludes = []
[source.glob]
literal-separator = true
[formatter]
print-width = 120
tab-width = 4
use-tabs = false
[linter]
integrations = []
[linter.rules]
ambiguous-function-call = { enabled = false }
literal-named-argument = { enabled = false }
cyclomatic-complexity = { enabled = false }
excessive-parameter-list = { enabled = false }
halstead = { enabled = true, effort-threshold = 7000 }
identity-comparison = { enabled = true }
kan-defect = { enabled = false }
no-boolean-flag-parameter = { enabled = false }
no-else-clause = { enabled = false }
no-empty = { enabled = false }
too-many-methods = { enabled = false }
too-many-properties = { enabled = true, threshold = 15 }
no-isset = { enabled = true, allow-array-checks = true }
[analyzer]
plugins = []
find-unused-definitions = true
find-unused-expressions = true
analyze-dead-code = true
memoize-properties = true
check-throws = true
unchecked-exceptions = [
"Error",
"LogicException",
"ReflectionException",
]
unchecked-exception-classes = []
check-missing-override = true
find-unused-parameters = true
strict-list-index-checks = true
strict-array-index-existence = true
allow-array-truthy-operand = false
no-boolean-literal-comparison = true
check-missing-type-hints = true
register-super-globals = true
+66
View File
@@ -0,0 +1,66 @@
#:schema https://mago.carthage.software/1.43.0/schema.json
version = "1"
php-version = "8.2.0"
[source]
workspace = "."
paths = ["src", "test"]
includes = ["vendor"]
excludes = []
[source.glob]
literal-separator = true
[formatter]
print-width = 120
tab-width = 4
use-tabs = false
[linter]
integrations = ["phpunit"]
[linter.rules]
ambiguous-function-call = { enabled = false }
literal-named-argument = { enabled = false }
assertion-style = { enabled = false }
cyclomatic-complexity = { enabled = false }
excessive-parameter-list = { enabled = false }
halstead = { enabled = false, effort-threshold = 7000 }
identity-comparison = { enabled = false }
kan-defect = { enabled = false }
no-boolean-flag-parameter = { enabled = false }
no-else-clause = { enabled = false }
no-empty = { enabled = false }
no-empty-catch-clause = { enabled = false }
no-isset = { enabled = false }
readable-literal = { enabled = false }
str-contains = { enabled = false }
strict-assertions = { enabled = false }
strict-behavior = { enabled = false }
strict-types = { enabled = false }
too-many-methods = { enabled = false }
[analyzer]
plugins = []
find-unused-definitions = true
find-unused-expressions = true
analyze-dead-code = true
memoize-properties = true
check-throws = true
unchecked-exceptions = [
"Error",
"LogicException",
"ReflectionException",
"PHPUnit\\Framework\\Exception",
"PHPUnit\\Framework\\ExpectationFailedException",
"PHPUnit\\Framework\\UnknownClassOrInterfaceException",
]
unchecked-exception-classes = []
check-missing-override = true
find-unused-parameters = true
strict-list-index-checks = true
strict-array-index-existence = true
allow-array-truthy-operand = false
no-boolean-literal-comparison = true
check-missing-type-hints = true
register-super-globals = true
+15
View File
@@ -0,0 +1,15 @@
{
"source-providers": [
{
"in": "src as source",
"exclude": "vendor",
"name": "/\\.(php)$/"
}
],
"plugins": [
],
"analysers": [
],
"services": [
]
}
+31
View File
@@ -0,0 +1,31 @@
<?xml version="1.0" encoding="UTF-8"?>
<phpunit backupGlobals="false"
bootstrap="vendor/autoload.php"
colors="true"
displayDetailsOnTestsThatTriggerDeprecations="true"
displayDetailsOnTestsThatTriggerErrors="true"
displayDetailsOnTestsThatTriggerNotices="true"
displayDetailsOnTestsThatTriggerWarnings="true"
displayDetailsOnPhpunitDeprecations="true"
processIsolation="false"
stopOnFailure="false">
<testsuites>
<testsuite name="tc-lib-pdf-page Test Suite">
<directory>./test</directory>
</testsuite>
</testsuites>
<source>
<include>
<directory suffix=".php">src</directory>
</include>
</source>
<coverage>
<report>
<clover outputFile="target/coverage/coverage.xml"/>
<html outputDirectory="target/coverage" lowUpperBound="50" highLowerBound="90"/>
</report>
</coverage>
<logging>
<junit outputFile="target/logs/junit.xml"/>
</logging>
</phpunit>
@@ -0,0 +1,30 @@
<?php
/**
* autoload.php
*
* Autoloader for Tecnick.com libraries
*
* @since 2015-03-04
* @category Library
* @package PdfPage
* @author Nicola Asuni <info@tecnick.com>
* @copyright 2015-2026 Nicola Asuni - Tecnick.com LTD
* @license https://www.gnu.org/copyleft/lesser.html GNU-LGPL v3 (see LICENSE)
* @link https://github.com/tecnickcom/tc-lib-pdf-page
*
* This file is part of tc-lib-pdf-page software library.
*/
\spl_autoload_register(
function ($class) {
$prefix = 'Com\\Tecnick\\';
$len = \strlen($prefix);
if (\strncmp($prefix, $class, $len) !== 0) {
return;
}
$relative_class = \substr($class, $len);
$file = \dirname(\dirname(__DIR__)).'/'.\str_replace('\\', '/', $relative_class).'.php';
if (\file_exists($file)) {
require $file;
}
}
);
@@ -0,0 +1,7 @@
~#PKGNAME#~ (~#VERSION#~-~#RELEASE#~) UNRELEASED; urgency=low
* Please check the
https://github.com/~#VENDOR#~/~#PROJECT#~
commit history
-- Nicola Asuni <info@tecnick.com> ~#DATE#~
@@ -0,0 +1,17 @@
Source: ~#PKGNAME#~
Maintainer: Nicola Asuni <info@tecnick.com>
Section: php
Priority: optional
Build-Depends: debhelper-compat (= 13)
Standards-Version: 4.7.2
Rules-Requires-Root: no
Homepage: https://github.com/~#VENDOR#~/~#PROJECT#~
Vcs-Git: https://github.com/~#VENDOR#~/~#PROJECT#~.git
Vcs-Browser: https://github.com/~#VENDOR#~/~#PROJECT#~
Package: ~#PKGNAME#~
Provides: php-~#PROJECT#~
Architecture: all
Depends: php (>= 8.2.0), php-tecnickcom-tc-lib-color (<< 3.0.0), php-tecnickcom-tc-lib-color (>= 2.13.3), php-tecnickcom-tc-lib-pdf-encrypt (<< 3.0.0), php-tecnickcom-tc-lib-pdf-encrypt (>= 2.9.3), ${misc:Depends}
Description: PHP PDF Page Library
PHP library containing PDF page formats and definitions.
@@ -0,0 +1,20 @@
Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/
Upstream-Name: ~#PROJECT#~
Source: https://github.com/~#VENDOR#~/~#PROJECT#~
Files: *
Copyright: Copyright 2001-2026 Nicola Asuni <info@tecnick.com>
License: LGPL-3
License: LGPL-3
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/> or
/usr/share/common-licenses/LGPL-3
@@ -0,0 +1,3 @@
#!/usr/bin/make -f
%:
dh $@
@@ -0,0 +1 @@
3.0 (quilt)
@@ -0,0 +1,4 @@
version=4
opts=filenamemangle=s/.+\/v?(\d[\d\.]+)\.tar\.gz/~#PKGNAME#~_$1.orig.tar.gz/ \
https://github.com/~#VENDOR#~/~#PROJECT#~/tags \
.*/archive/refs/tags/v?(\d[\d\.]*)\.tar\.gz
@@ -0,0 +1,48 @@
# SPEC file
%global c_vendor %{_vendor}
%global gh_owner %{_owner}
%global gh_project %{_project}
Name: %{_package}
Version: %{_version}
Release: %{_release}%{?dist}
Summary: PHP library containing PDF page formats and definitions
License: LGPLv3+
URL: https://github.com/%{gh_owner}/%{gh_project}
BuildArch: noarch
Requires: php(language) >= 8.2.0
Requires: php-date
Requires: php-zlib
Requires: php-composer(%{c_vendor}/tc-lib-color) < 3.0.0
Requires: php-composer(%{c_vendor}/tc-lib-color) >= 2.13.3
Requires: php-composer(%{c_vendor}/tc-lib-pdf-encrypt) < 3.0.0
Requires: php-composer(%{c_vendor}/tc-lib-pdf-encrypt) >= 2.9.3
Provides: php-composer(%{c_vendor}/%{gh_project}) = %{version}
Provides: php-%{gh_project} = %{version}
%description
PHP library containing PDF page formats and definitions
%build
#(cd %{_current_directory} && make build)
%install
rm -rf "%{buildroot}"
(cd "%{_current_directory}" && make install DESTDIR="%{buildroot}")
%files
%attr(-,root,root) %{_libpath}
%attr(-,root,root) %{_docpath}
%docdir %{_docpath}
# Optional config files can be listed here when used by a project.
%changelog
* Thu Jul 02 2026 Nicola Asuni <info@tecnick.com> 1.1.0-1
- Changed package name, add provides section
* Thu May 14 2026 Nicola Asuni <info@tecnick.com> 1.0.0-1
- Initial Commit
+412
View File
@@ -0,0 +1,412 @@
<?php
declare(strict_types=1);
/**
* Box.php
*
* @since 2011-05-23
* @category Library
* @package PdfPage
* @author Nicola Asuni <info@tecnick.com>
* @copyright 2011-2026 Nicola Asuni - Tecnick.com LTD
* @license https://www.gnu.org/copyleft/lesser.html GNU-LGPL v3 (see LICENSE)
* @link https://github.com/tecnickcom/tc-lib-pdf-page
*
* This file is part of tc-lib-pdf-page software library.
*/
namespace Com\Tecnick\Pdf\Page;
use Com\Tecnick\Color\Pdf as Color;
use Com\Tecnick\Pdf\Page\Exception as PageException;
/**
* Com\Tecnick\Pdf\Page\Box
*
* @since 2011-05-23
* @category Library
* @package PdfPage
* @author Nicola Asuni <info@tecnick.com>
* @copyright 2011-2026 Nicola Asuni - Tecnick.com LTD
* @license https://www.gnu.org/copyleft/lesser.html GNU-LGPL v3 (see LICENSE)
* @link https://github.com/tecnickcom/tc-lib-pdf-page
*
* @phpstan-type PageBci array{
* 'color': string,
* 'width': float,
* 'style': string,
* 'dash': array<int>,
* }
*
* @phpstan-type PageBox array{
* 'llx': float,
* 'lly': float,
* 'urx': float,
* 'ury': float,
* 'bci'?: PageBci,
* }
*
* @phpstan-type MarginData array{
* 'CB': float,
* 'CT': float,
* 'FT': float,
* 'HB': float,
* 'PB': float,
* 'PL': float,
* 'PR': float,
* 'PT': float,
* }
*
* @phpstan-type RegionData array{
* 'RB': float,
* 'RH': float,
* 'RL': float,
* 'RR': float,
* 'RT': float,
* 'RW': float,
* 'RX': float,
* 'RY': float,
* 'x' : float,
* 'y' : float,
* }
*
* @phpstan-type NoWriteArea array{
* 'side'?: string,
* 'xt'?: float,
* 'yt'?: float,
* 'xb'?: float,
* 'yb'?: float,
* 'x'?: float,
* 'y'?: float,
* 'w'?: float,
* 'h'?: float,
* }
*
*
* @phpstan-type TransitionData array{
* 'B': bool,
* 'D': int,
* 'Di': string|int,
* 'Dm': string,
* 'Dur': float,
* 'M': string,
* 'S': string,
* 'SS': float,
* }
*
* @phpstan-type PageData array{
* 'annotrefs': array<int,int>,
* 'autobreak': bool,
* 'box': array<string, array{
* 'llx': float,
* 'lly': float,
* 'urx': float,
* 'ury': float,
* 'bci': PageBci,
* }>,
* 'columns': int,
* 'content': array<string>,
* 'content_mark': array<int>,
* 'ContentHeight': float,
* 'ContentWidth': float,
* 'FooterHeight': float,
* 'HeaderHeight': float,
* 'currentRegion': int,
* 'format': string,
* 'group': int,
* 'height': float,
* 'margin': MarginData,
* 'n': int,
* 'num': int,
* 'orientation': string,
* 'pagenum': int,
* 'pheight': float,
* 'pid': int,
* 'pwidth': float,
* 'region': array<int, RegionData>,
* 'rotation': int,
* 'time': int,
* 'transition': TransitionData,
* 'width': float,
* 'zoom': float,
* }
*
* @phpstan-type PageInputData array{
* 'annotrefs'?: array<int,int>,
* 'autobreak'?: bool,
* 'box'?: array<string, array{
* 'llx'?: float,
* 'lly'?: float,
* 'urx'?: float,
* 'ury'?: float,
* 'bci'?: array{
* 'color'?: string,
* 'width'?: float,
* 'style'?: string,
* 'dash'?: array<int>,
* },
* }>,
* 'columns'?: int,
* 'content'?: array<string>|string,
* 'content_mark'?: array<int>,
* 'ContentHeight'?: float,
* 'ContentWidth'?: float,
* 'FooterHeight'?: float,
* 'HeaderHeight'?: float,
* 'currentRegion'?: int,
* 'format'?: string,
* 'group'?: int,
* 'height'?: float,
* 'margin'?: array{
* 'booklet'?: bool,
* 'CB'?: float,
* 'CT'?: float,
* 'FT'?: float,
* 'HB'?: float,
* 'PB'?: float,
* 'PL'?: float,
* 'PR'?: float,
* 'PT'?: float,
* },
* 'n'?: int,
* 'num'?: int,
* 'orientation'?: string,
* 'pagenum'?: int,
* 'pheight'?: float,
* 'pid'?: int,
* 'pwidth'?: float,
* 'region'?: array<int, array{
* 'RB'?: float,
* 'RH'?: float,
* 'RL'?: float,
* 'RR'?: float,
* 'RT'?: float,
* 'RW'?: float,
* 'RX'?: float,
* 'RY'?: float,
* 'x' ?: float,
* 'y' ?: float,
* }>,
* 'rotation'?: int,
* 'time'?: int,
* 'transition'?: array{
* 'B'?: bool,
* 'D'?: int,
* 'Di'?: string|int,
* 'Dm'?: string,
* 'Dur'?: float,
* 'M'?: string,
* 'S'?: string,
* 'SS'?: float,
* },
* 'width'?: float,
* 'zoom'?: float,
* }
*/
abstract class Box extends \Com\Tecnick\Pdf\Page\Mode
{
/**
* Unit of measure conversion ratio.
*/
protected float $kunit = 1.0;
/**
* Color object.
*/
protected Color $col;
/**
* Page box names.
*
* @var array<string>
*/
public const BOX = [
'MediaBox',
'CropBox',
'BleedBox',
'TrimBox',
'ArtBox',
];
/**
* Swap X and Y coordinates of page boxes (change page boxes orientation).
*
* @param array<string, PageBox> $dims Array of page dimensions.
*
* @return array<string, PageBox> Page dimensions.
*/
public function swapCoordinates(array $dims): array
{
foreach (self::BOX as $type) {
// swap X and Y coordinates
if (!array_key_exists($type, $dims)) {
continue;
}
$llx = $dims[$type]['llx'];
$lly = $dims[$type]['lly'];
$urx = $dims[$type]['urx'];
$ury = $dims[$type]['ury'];
$dims[$type]['llx'] = $lly;
$dims[$type]['lly'] = $llx;
$dims[$type]['urx'] = $ury;
$dims[$type]['ury'] = $urx;
}
return $dims;
}
/**
* Set page boundaries.
*
* @param array<string, PageBox> $dims Array of page dimensions to modify.
* @param string|PageBoxType $type Box type: MediaBox, CropBox, BleedBox, TrimBox, ArtBox, or enum case.
* @param float $llx Lower-left x coordinate in user units.
* @param float $lly Lower-left y coordinate in user units.
* @param float $urx Upper-right x coordinate in user units.
* @param float $ury Upper-right y coordinate in user units.
* @param PageBci $bci BoxColorInfo: guideline style (color, width, style, dash).
*
* @return array<string, PageBox> Page dimensions.
*
* @throws PageException
*/
public function setBox(
array $dims,
string|PageBoxType $type,
float $llx,
float $lly,
float $urx,
float $ury,
?array $bci = null,
): array {
if ($type instanceof PageBoxType) {
$type = $type->value;
}
if (!\in_array($type, self::BOX, true)) {
throw new PageException('unknown page box type: ' . $type);
}
$dims[$type]['llx'] = $llx;
$dims[$type]['lly'] = $lly;
$dims[$type]['urx'] = $urx;
$dims[$type]['ury'] = $ury;
if ($bci === null) {
// set default values
$bci = [
'color' => '#000000',
'width' => 1.0 / $this->kunit,
'style' => 'S', // S = solid; D = dash
'dash' => [3],
];
}
$dims[$type]['bci'] = $bci;
return $dims;
}
/**
* Initialize page boxes.
*
* @param float $width Page width in points.
* @param float $height Page height in points.
*
* @return array<string, PageBox> Page boxes.
*
* @throws PageException
*/
public function setPageBoxes(float $width, float $height): array
{
$dims = [];
foreach (self::BOX as $type) {
$dims = $this->setBox($dims, $type, 0, 0, $width, $height);
}
return $dims;
}
/**
* Returns the PDF command to output the specified page boxes.
*
* @param array<string, array{
* 'llx': float,
* 'lly': float,
* 'urx': float,
* 'ury': float,
* }> $dims Array of page dimensions.
*/
protected function getBox(array $dims): string
{
$out = '';
foreach (self::BOX as $box) {
if (empty($dims[$box])) {
// @codeCoverageIgnoreStart
continue;
// @codeCoverageIgnoreEnd
}
$out .= \sprintf(
'/%s [%F %F %F %F]' . "\n",
$box,
$dims[$box]['llx'],
$dims[$box]['lly'],
$dims[$box]['urx'],
$dims[$box]['ury'],
);
}
return $out;
}
/**
* Returns the PDF command to output the specified page BoxColorInfo.
*
* @param array<string, array{
* 'bci': PageBci,
* }> $dims Array of page dimensions.
*
* @SuppressWarnings("PHPMD.CyclomaticComplexity")
*/
protected function getBoxColorInfo(array $dims): string
{
$out = '/BoxColorInfo <<' . "\n";
foreach (self::BOX as $box) {
$out .= '/' . $box . ' <<' . "\n";
if (!empty($dims[$box]['bci']['color'])) {
$out .= '/C [' . $this->col->getPdfRgbComponents($dims[$box]['bci']['color']) . ']' . "\n";
}
if (!empty($dims[$box]['bci']['width'])) {
$out .= \sprintf('/W %F' . "\n", $dims[$box]['bci']['width'] * $this->kunit);
}
if (!empty($dims[$box]['bci']['style'])) {
$mode = \strtoupper($dims[$box]['bci']['style'][0]);
if ($mode !== 'D') {
$mode = 'S';
}
$out .= '/S /' . $mode . "\n";
}
if (!empty($dims[$box]['bci']['dash'])) {
$out .= '/D [';
foreach ($dims[$box]['bci']['dash'] as $dash) {
$out .= \sprintf(' %F', (float) $dash * $this->kunit);
}
$out .= ' ]' . "\n";
}
$out .= '>>' . "\n";
}
return $out . ('>>' . "\n");
}
}
+34
View File
@@ -0,0 +1,34 @@
<?php
declare(strict_types=1);
/**
* Exception.php
*
* @since 2011-05-23
* @category Library
* @package PdfPage
* @author Nicola Asuni <info@tecnick.com>
* @copyright 2011-2026 Nicola Asuni - Tecnick.com LTD
* @license https://www.gnu.org/copyleft/lesser.html GNU-LGPL v3 (see LICENSE)
* @link https://github.com/tecnickcom/tc-lib-pdf-page
*
* This file is part of tc-lib-pdf-page software library.
*/
namespace Com\Tecnick\Pdf\Page;
/**
* Com\Tecnick\Pdf\Page\Exception
*
* Custom Exception class.
*
* @since 2011-05-23
* @category Library
* @package PdfPage
* @author Nicola Asuni <info@tecnick.com>
* @copyright 2011-2026 Nicola Asuni - Tecnick.com LTD
* @license https://www.gnu.org/copyleft/lesser.html GNU-LGPL v3 (see LICENSE)
* @link https://github.com/tecnickcom/tc-lib-pdf-page
*/
class Exception extends \Exception {}
+589
View File
@@ -0,0 +1,589 @@
<?php
declare(strict_types=1);
/**
* Format.php
*
* @since 2011-05-23
* @category Library
* @package PdfPage
* @author Nicola Asuni <info@tecnick.com>
* @copyright 2011-2026 Nicola Asuni - Tecnick.com LTD
* @license https://www.gnu.org/copyleft/lesser.html GNU-LGPL v3 (see LICENSE)
* @link https://github.com/tecnickcom/tc-lib-pdf-page
*
* This file is part of tc-lib-pdf-page software library.
*/
namespace Com\Tecnick\Pdf\Page;
use Com\Tecnick\Pdf\Page\Exception as PageException;
/**
* Com\Tecnick\Pdf\Page\Format
*
* @since 2011-05-23
* @category Library
* @package PdfPage
* @author Nicola Asuni <info@tecnick.com>
* @copyright 2011-2026 Nicola Asuni - Tecnick.com LTD
* @license https://www.gnu.org/copyleft/lesser.html GNU-LGPL v3 (see LICENSE)
* @link https://github.com/tecnickcom/tc-lib-pdf-page
*/
abstract class Format
{
/**
* Array of conversion ratios relative to points.
* 72 is the default DPI (Dot Per Inch) document resolution.
*
* @var array<string, float>
*/
public const UNITRATIO = [
'' => 1.0, // default to points
'px' => 1.0,
'pt' => 1.0,
'points' => 1.0,
'millimeters' => 2.834_645_669_291_34, // (72 / 25.4)
'mm' => 2.834_645_669_291_34, // (72 / 25.4)
'centimeters' => 28.346_456_692_913_4, // (72 / 2.54)
'cm' => 28.346_456_692_913_4, // (72 / 2.54)
'inches' => 72.0,
'in' => 72.0,
];
/**
* Array of page formats (width, height).
* Measures are calculated in this way: (inches * 72) or (millimeters * 72 / 25.4)
*
* @var array<string, array{0:float, 1:float}>
*/
public const FORMAT = [
// ISO 216 A Series + 2 SIS 014711 extensions
'A0' => [2383.937, 3370.394], // = ( 841 x 1189 ) mm = ( 33.11 x 46.81 ) in
'A1' => [1683.780, 2383.937], // = ( 594 x 841 ) mm = ( 23.39 x 33.11 ) in
'A2' => [1190.551, 1683.780], // = ( 420 x 594 ) mm = ( 16.54 x 23.39 ) in
'A3' => [841.890, 1190.551], // = ( 297 x 420 ) mm = ( 11.69 x 16.54 ) in
'A4' => [595.276, 841.890], // = ( 210 x 297 ) mm = ( 8.27 x 11.69 ) in
'A5' => [419.528, 595.276], // = ( 148 x 210 ) mm = ( 5.83 x 8.27 ) in
'A6' => [297.638, 419.528], // = ( 105 x 148 ) mm = ( 4.13 x 5.83 ) in
'A7' => [209.764, 297.638], // = ( 74 x 105 ) mm = ( 2.91 x 4.13 ) in
'A8' => [147.402, 209.764], // = ( 52 x 74 ) mm = ( 2.05 x 2.91 ) in
'A9' => [104.882, 147.402], // = ( 37 x 52 ) mm = ( 1.46 x 2.05 ) in
'A10' => [73.701, 104.882], // = ( 26 x 37 ) mm = ( 1.02 x 1.46 ) in
'A11' => [51.024, 73.701], // = ( 18 x 26 ) mm = ( 0.71 x 1.02 ) in
'A12' => [36.850, 51.024], // = ( 13 x 18 ) mm = ( 0.51 x 0.71 ) in
// ISO 216 B Series + 2 SIS 014711 extensions
'B0' => [2834.646, 4008.189], // = ( 1000 x 1414 ) mm = ( 39.37 x 55.67 ) in
'B1' => [2004.094, 2834.646], // = ( 707 x 1000 ) mm = ( 27.83 x 39.37 ) in
'B2' => [1417.323, 2004.094], // = ( 500 x 707 ) mm = ( 19.69 x 27.83 ) in
'B3' => [1000.630, 1417.323], // = ( 353 x 500 ) mm = ( 13.90 x 19.69 ) in
'B4' => [708.661, 1000.630], // = ( 250 x 353 ) mm = ( 9.84 x 13.90 ) in
'B5' => [498.898, 708.661], // = ( 176 x 250 ) mm = ( 6.93 x 9.84 ) in
'B6' => [354.331, 498.898], // = ( 125 x 176 ) mm = ( 4.92 x 6.93 ) in
'B7' => [249.449, 354.331], // = ( 88 x 125 ) mm = ( 3.46 x 4.92 ) in
'B8' => [175.748, 249.449], // = ( 62 x 88 ) mm = ( 2.44 x 3.46 ) in
'B9' => [124.724, 175.748], // = ( 44 x 62 ) mm = ( 1.73 x 2.44 ) in
'B10' => [87.874, 124.724], // = ( 31 x 44 ) mm = ( 1.22 x 1.73 ) in
'B11' => [62.362, 87.874], // = ( 22 x 31 ) mm = ( 0.87 x 1.22 ) in
'B12' => [42.520, 62.362], // = ( 15 x 22 ) mm = ( 0.59 x 0.87 ) in
// ISO 216 C Series + 2 SIS 014711 extensions + 5 EXTENSION
'C0' => [2599.370, 3676.535], // = ( 917 x 1297 ) mm = ( 36.10 x 51.06 ) in
'C1' => [1836.850, 2599.370], // = ( 648 x 917 ) mm = ( 25.51 x 36.10 ) in
'C2' => [1298.268, 1836.850], // = ( 458 x 648 ) mm = ( 18.03 x 25.51 ) in
'C3' => [918.425, 1298.268], // = ( 324 x 458 ) mm = ( 12.76 x 18.03 ) in
'C4' => [649.134, 918.425], // = ( 229 x 324 ) mm = ( 9.02 x 12.76 ) in
'C5' => [459.213, 649.134], // = ( 162 x 229 ) mm = ( 6.38 x 9.02 ) in
'C6' => [323.150, 459.213], // = ( 114 x 162 ) mm = ( 4.49 x 6.38 ) in
'C7' => [229.606, 323.150], // = ( 81 x 114 ) mm = ( 3.19 x 4.49 ) in
'C8' => [161.575, 229.606], // = ( 57 x 81 ) mm = ( 2.24 x 3.19 ) in
'C9' => [113.386, 161.575], // = ( 40 x 57 ) mm = ( 1.57 x 2.24 ) in
'C10' => [79.370, 113.386], // = ( 28 x 40 ) mm = ( 1.10 x 1.57 ) in
'C11' => [56.693, 79.370], // = ( 20 x 28 ) mm = ( 0.79 x 1.10 ) in
'C12' => [39.685, 56.693], // = ( 14 x 20 ) mm = ( 0.55 x 0.79 ) in
'C76' => [229.606, 459.213], // = ( 81 x 162 ) mm = ( 3.19 x 6.38 ) in
'DL' => [311.811, 623.622], // = ( 110 x 220 ) mm = ( 4.33 x 8.66 ) in
'DLE' => [323.150, 637.795], // = ( 114 x 225 ) mm = ( 4.49 x 8.86 ) in
'DLX' => [340.158, 666.142], // = ( 120 x 235 ) mm = ( 4.72 x 9.25 ) in
'DLP' => [280.630, 595.276], // = ( 99 x 210 ) mm = ( 3.90 x 8.27 ) in (A4/3)
// SIS 014711 E Series
'E0' => [2491.654, 3517.795], // = ( 879 x 1241 ) mm = ( 34.61 x 48.86 ) in
'E1' => [1757.480, 2491.654], // = ( 620 x 879 ) mm = ( 24.41 x 34.61 ) in
'E2' => [1247.244, 1757.480], // = ( 440 x 620 ) mm = ( 17.32 x 24.41 ) in
'E3' => [878.740, 1247.244], // = ( 310 x 440 ) mm = ( 12.20 x 17.32 ) in
'E4' => [623.622, 878.740], // = ( 220 x 310 ) mm = ( 8.66 x 12.20 ) in
'E5' => [439.370, 623.622], // = ( 155 x 220 ) mm = ( 6.10 x 8.66 ) in
'E6' => [311.811, 439.370], // = ( 110 x 155 ) mm = ( 4.33 x 6.10 ) in
'E7' => [221.102, 311.811], // = ( 78 x 110 ) mm = ( 3.07 x 4.33 ) in
'E8' => [155.906, 221.102], // = ( 55 x 78 ) mm = ( 2.17 x 3.07 ) in
'E9' => [110.551, 155.906], // = ( 39 x 55 ) mm = ( 1.54 x 2.17 ) in
'E10' => [76.535, 110.551], // = ( 27 x 39 ) mm = ( 1.06 x 1.54 ) in
'E11' => [53.858, 76.535], // = ( 19 x 27 ) mm = ( 0.75 x 1.06 ) in
'E12' => [36.850, 53.858], // = ( 13 x 19 ) mm = ( 0.51 x 0.75 ) in
// SIS 014711 G Series
'G0' => [2715.591, 3838.110], // = ( 958 x 1354 ) mm = ( 37.72 x 53.31 ) in
'G1' => [1919.055, 2715.591], // = ( 677 x 958 ) mm = ( 26.65 x 37.72 ) in
'G2' => [1357.795, 1919.055], // = ( 479 x 677 ) mm = ( 18.86 x 26.65 ) in
'G3' => [958.110, 1357.795], // = ( 338 x 479 ) mm = ( 13.31 x 18.86 ) in
'G4' => [677.480, 958.110], // = ( 239 x 338 ) mm = ( 9.41 x 13.31 ) in
'G5' => [479.055, 677.480], // = ( 169 x 239 ) mm = ( 6.65 x 9.41 ) in
'G6' => [337.323, 479.055], // = ( 119 x 169 ) mm = ( 4.69 x 6.65 ) in
'G7' => [238.110, 337.323], // = ( 84 x 119 ) mm = ( 3.31 x 4.69 ) in
'G8' => [167.244, 238.110], // = ( 59 x 84 ) mm = ( 2.32 x 3.31 ) in
'G9' => [119.055, 167.244], // = ( 42 x 59 ) mm = ( 1.65 x 2.32 ) in
'G10' => [82.205, 119.055], // = ( 29 x 42 ) mm = ( 1.14 x 1.65 ) in
'G11' => [59.528, 82.205], // = ( 21 x 29 ) mm = ( 0.83 x 1.14 ) in
'G12' => [39.685, 59.528], // = ( 14 x 21 ) mm = ( 0.55 x 0.83 ) in
// ISO Press
'RA0' => [2437.795, 3458.268], // = ( 860 x 1220 ) mm = ( 33.86 x 48.03 ) in
'RA1' => [1729.134, 2437.795], // = ( 610 x 860 ) mm = ( 24.02 x 33.86 ) in
'RA2' => [1218.898, 1729.134], // = ( 430 x 610 ) mm = ( 16.93 x 24.02 ) in
'RA3' => [864.567, 1218.898], // = ( 305 x 430 ) mm = ( 12.01 x 16.93 ) in
'RA4' => [609.449, 864.567], // = ( 215 x 305 ) mm = ( 8.46 x 12.01 ) in
'SRA0' => [2551.181, 3628.346], // = ( 900 x 1280 ) mm = ( 35.43 x 50.39 ) in
'SRA1' => [1814.173, 2551.181], // = ( 640 x 900 ) mm = ( 25.20 x 35.43 ) in
'SRA2' => [1275.591, 1814.173], // = ( 450 x 640 ) mm = ( 17.72 x 25.20 ) in
'SRA3' => [907.087, 1275.591], // = ( 320 x 450 ) mm = ( 12.60 x 17.72 ) in
'SRA4' => [637.795, 907.087], // = ( 225 x 320 ) mm = ( 8.86 x 12.60 ) in
// German DIN 476
'4A0' => [4767.874, 6740.787], // = ( 1682 x 2378 ) mm = ( 66.22 x 93.62 ) in
'2A0' => [3370.394, 4767.874], // = ( 1189 x 1682 ) mm = ( 46.81 x 66.22 ) in
// Variations on the ISO Standard
'A2_EXTRA' => [1261.417, 1754.646], // = ( 445 x 619 ) mm = ( 17.52 x 24.37 ) in
'A3+' => [932.598, 1369.134], // = ( 329 x 483 ) mm = ( 12.95 x 19.02 ) in
'A3_EXTRA' => [912.756, 1261.417], // = ( 322 x 445 ) mm = ( 12.68 x 17.52 ) in
'A3_SUPER' => [864.567, 1440.000], // = ( 305 x 508 ) mm = ( 12.01 x 20.00 ) in
'SUPER_A3' => [864.567, 1380.472], // = ( 305 x 487 ) mm = ( 12.01 x 19.17 ) in
'A4_EXTRA' => [666.142, 912.756], // = ( 235 x 322 ) mm = ( 9.25 x 12.68 ) in
'A4_SUPER' => [649.134, 912.756], // = ( 229 x 322 ) mm = ( 9.02 x 12.68 ) in
'SUPER_A4' => [643.465, 1009.134], // = ( 227 x 356 ) mm = ( 8.94 x 14.02 ) in
'A4_LONG' => [595.276, 986.457], // = ( 210 x 348 ) mm = ( 8.27 x 13.70 ) in
'F4' => [595.276, 935.433], // = ( 210 x 330 ) mm = ( 8.27 x 12.99 ) in
'SO_B5_EXTRA' => [572.598, 782.362], // = ( 202 x 276 ) mm = ( 7.95 x 10.87 ) in
'A5_EXTRA' => [490.394, 666.142], // = ( 173 x 235 ) mm = ( 6.81 x 9.25 ) in
// ANSI Series
'ANSI_E' => [2448.000, 3168.000], // = ( 864 x 1118 ) mm = ( 34.00 x 44.00 ) in
'ANSI_D' => [1584.000, 2448.000], // = ( 559 x 864 ) mm = ( 22.00 x 34.00 ) in
'ANSI_C' => [1224.000, 1584.000], // = ( 432 x 559 ) mm = ( 17.00 x 22.00 ) in
'ANSI_B' => [792.000, 1224.000], // = ( 279 x 432 ) mm = ( 11.00 x 17.00 ) in
'ANSI_A' => [612.000, 792.000], // = ( 216 x 279 ) mm = ( 8.50 x 11.00 ) in
// Traditional 'Loose' North American Paper Sizes
'USLEDGER' => [1224.000, 792.000], // = ( 432 x 279 ) mm = ( 17.00 x 11.00 ) in
'LEDGER' => [1224.000, 792.000], // = ( 432 x 279 ) mm = ( 17.00 x 11.00 ) in
'ORGANIZERK' => [792.000, 1224.000], // = ( 279 x 432 ) mm = ( 11.00 x 17.00 ) in
'BIBLE' => [792.000, 1224.000], // = ( 279 x 432 ) mm = ( 11.00 x 17.00 ) in
'USTABLOID' => [792.000, 1224.000], // = ( 279 x 432 ) mm = ( 11.00 x 17.00 ) in
'TABLOID' => [792.000, 1224.000], // = ( 279 x 432 ) mm = ( 11.00 x 17.00 ) in
'ORGANIZERM' => [612.000, 792.000], // = ( 216 x 279 ) mm = ( 8.50 x 11.00 ) in
'USLETTER' => [612.000, 792.000], // = ( 216 x 279 ) mm = ( 8.50 x 11.00 ) in
'LETTER' => [612.000, 792.000], // = ( 216 x 279 ) mm = ( 8.50 x 11.00 ) in
'USLEGAL' => [612.000, 1008.000], // = ( 216 x 356 ) mm = ( 8.50 x 14.00 ) in
'LEGAL' => [612.000, 1008.000], // = ( 216 x 356 ) mm = ( 8.50 x 14.00 ) in
'GOVERNMENTLETTER' => [576.000, 756.000], // = ( 203 x 267 ) mm = ( 8.00 x 10.50 ) in
'GLETTER' => [576.000, 756.000], // = ( 203 x 267 ) mm = ( 8.00 x 10.50 ) in
'JUNIORLEGAL' => [576.000, 360.000], // = ( 203 x 127 ) mm = ( 8.00 x 5.00 ) in
'JLEGAL' => [576.000, 360.000], // = ( 203 x 127 ) mm = ( 8.00 x 5.00 ) in
// Other North American Paper Sizes
'QUADDEMY' => [2520.000, 3240.000], // = ( 889 x 1143 ) mm = ( 35.00 x 45.00 ) in
'SUPER_B' => [936.000, 1368.000], // = ( 330 x 483 ) mm = ( 13.00 x 19.00 ) in
'QUARTO' => [648.000, 792.000], // = ( 229 x 279 ) mm = ( 9.00 x 11.00 ) in
'GOVERNMENTLEGAL' => [612.000, 936.000], // = ( 216 x 330 ) mm = ( 8.50 x 13.00 ) in
'FOLIO' => [612.000, 936.000], // = ( 216 x 330 ) mm = ( 8.50 x 13.00 ) in
'MONARCH' => [522.000, 756.000], // = ( 184 x 267 ) mm = ( 7.25 x 10.50 ) in
'EXECUTIVE' => [522.000, 756.000], // = ( 184 x 267 ) mm = ( 7.25 x 10.50 ) in
'ORGANIZERL' => [396.000, 612.000], // = ( 140 x 216 ) mm = ( 5.50 x 8.50 ) in
'STATEMENT' => [396.000, 612.000], // = ( 140 x 216 ) mm = ( 5.50 x 8.50 ) in
'MEMO' => [396.000, 612.000], // = ( 140 x 216 ) mm = ( 5.50 x 8.50 ) in
'FOOLSCAP' => [595.440, 936.000], // = ( 210 x 330 ) mm = ( 8.27 x 13.00 ) in
'COMPACT' => [306.000, 486.000], // = ( 108 x 171 ) mm = ( 4.25 x 6.75 ) in
'ORGANIZERJ' => [198.000, 360.000], // = ( 70 x 127 ) mm = ( 2.75 x 5.00 ) in
// Canadian standard CAN 2-9.60M
'P1' => [1587.402, 2437.795], // = ( 560 x 860 ) mm = ( 22.05 x 33.86 ) in
'P2' => [1218.898, 1587.402], // = ( 430 x 560 ) mm = ( 16.93 x 22.05 ) in
'P3' => [793.701, 1218.898], // = ( 280 x 430 ) mm = ( 11.02 x 16.93 ) in
'P4' => [609.449, 793.701], // = ( 215 x 280 ) mm = ( 8.46 x 11.02 ) in
'P5' => [396.850, 609.449], // = ( 140 x 215 ) mm = ( 5.51 x 8.46 ) in
'P6' => [303.307, 396.850], // = ( 107 x 140 ) mm = ( 4.21 x 5.51 ) in
// North American Architectural Sizes
'ARCH_E' => [2592.000, 3456.000], // = ( 914 x 1219 ) mm = ( 36.00 x 48.00 ) in
'ARCH_E1' => [2160.000, 3024.000], // = ( 762 x 1067 ) mm = ( 30.00 x 42.00 ) in
'ARCH_D' => [1728.000, 2592.000], // = ( 610 x 914 ) mm = ( 24.00 x 36.00 ) in
'BROADSHEET' => [1296.000, 1728.000], // = ( 457 x 610 ) mm = ( 18.00 x 24.00 ) in
'ARCH_C' => [1296.000, 1728.000], // = ( 457 x 610 ) mm = ( 18.00 x 24.00 ) in
'ARCH_B' => [864.000, 1296.000], // = ( 305 x 457 ) mm = ( 12.00 x 18.00 ) in
'ARCH_A' => [648.000, 864.000], // = ( 229 x 305 ) mm = ( 9.00 x 12.00 ) in
// -- North American Envelope Sizes
// - Announcement Envelopes
'ANNENV_A2' => [314.640, 414.000], // = ( 111 x 146 ) mm = ( 4.37 x 5.75 ) in
'ANNENV_A6' => [342.000, 468.000], // = ( 121 x 165 ) mm = ( 4.75 x 6.50 ) in
'ANNENV_A7' => [378.000, 522.000], // = ( 133 x 184 ) mm = ( 5.25 x 7.25 ) in
'ANNENV_A8' => [396.000, 584.640], // = ( 140 x 206 ) mm = ( 5.50 x 8.12 ) in
'ANNENV_A10' => [450.000, 692.640], // = ( 159 x 244 ) mm = ( 6.25 x 9.62 ) in
'ANNENV_SLIM' => [278.640, 638.640], // = ( 98 x 225 ) mm = ( 3.87 x 8.87 ) in
// - Commercial Envelopes
'COMMENV_N6_1/4' => [252.000, 432.000], // = ( 89 x 152 ) mm = ( 3.50 x 6.00 ) in
'COMMENV_N6_3/4' => [260.640, 468.000], // = ( 92 x 165 ) mm = ( 3.62 x 6.50 ) in
'COMMENV_N8' => [278.640, 540.000], // = ( 98 x 191 ) mm = ( 3.87 x 7.50 ) in
'COMMENV_N9' => [278.640, 638.640], // = ( 98 x 225 ) mm = ( 3.87 x 8.87 ) in
'COMMENV_N10' => [296.640, 684.000], // = ( 105 x 241 ) mm = ( 4.12 x 9.50 ) in
'COMMENV_N11' => [324.000, 746.640], // = ( 114 x 263 ) mm = ( 4.50 x 10.37 ) in
'COMMENV_N12' => [342.000, 792.000], // = ( 121 x 279 ) mm = ( 4.75 x 11.00 ) in
'COMMENV_N14' => [360.000, 828.000], // = ( 127 x 292 ) mm = ( 5.00 x 11.50 ) in
// - Catalogue Envelopes
'CATENV_N1' => [432.000, 648.000], // = ( 152 x 229 ) mm = ( 6.00 x 9.00 ) in
'CATENV_N1_3/4' => [468.000, 684.000], // = ( 165 x 241 ) mm = ( 6.50 x 9.50 ) in
'CATENV_N2' => [468.000, 720.000], // = ( 165 x 254 ) mm = ( 6.50 x 10.00 ) in
'CATENV_N3' => [504.000, 720.000], // = ( 178 x 254 ) mm = ( 7.00 x 10.00 ) in
'CATENV_N6' => [540.000, 756.000], // = ( 191 x 267 ) mm = ( 7.50 x 10.50 ) in
'CATENV_N7' => [576.000, 792.000], // = ( 203 x 279 ) mm = ( 8.00 x 11.00 ) in
'CATENV_N8' => [594.000, 810.000], // = ( 210 x 286 ) mm = ( 8.25 x 11.25 ) in
'CATENV_N9_1/2' => [612.000, 756.000], // = ( 216 x 267 ) mm = ( 8.50 x 10.50 ) in
'CATENV_N9_3/4' => [630.000, 810.000], // = ( 222 x 286 ) mm = ( 8.75 x 11.25 ) in
'CATENV_N10_1/2' => [648.000, 864.000], // = ( 229 x 305 ) mm = ( 9.00 x 12.00 ) in
'CATENV_N12_1/2' => [684.000, 900.000], // = ( 241 x 318 ) mm = ( 9.50 x 12.50 ) in
'CATENV_N13_1/2' => [720.000, 936.000], // = ( 254 x 330 ) mm = ( 10.00 x 13.00 ) in
'CATENV_N14_1/4' => [810.000, 882.000], // = ( 286 x 311 ) mm = ( 11.25 x 12.25 ) in
'CATENV_N14_1/2' => [828.000, 1044.000], // = ( 292 x 368 ) mm = ( 11.50 x 14.50 ) in
// Japanese (JIS P 0138-61) Standard B-Series
'JIS_B0' => [2919.685, 4127.244], // = ( 1030 x 1456 ) mm = ( 40.55 x 57.32 ) in
'JIS_B1' => [2063.622, 2919.685], // = ( 728 x 1030 ) mm = ( 28.66 x 40.55 ) in
'JIS_B2' => [1459.843, 2063.622], // = ( 515 x 728 ) mm = ( 20.28 x 28.66 ) in
'JIS_B3' => [1031.811, 1459.843], // = ( 364 x 515 ) mm = ( 14.33 x 20.28 ) in
'JIS_B4' => [728.504, 1031.811], // = ( 257 x 364 ) mm = ( 10.12 x 14.33 ) in
'JIS_B5' => [515.906, 728.504], // = ( 182 x 257 ) mm = ( 7.17 x 10.12 ) in
'JIS_B6' => [362.835, 515.906], // = ( 128 x 182 ) mm = ( 5.04 x 7.17 ) in
'JIS_B7' => [257.953, 362.835], // = ( 91 x 128 ) mm = ( 3.58 x 5.04 ) in
'JIS_B8' => [181.417, 257.953], // = ( 64 x 91 ) mm = ( 2.52 x 3.58 ) in
'JIS_B9' => [127.559, 181.417], // = ( 45 x 64 ) mm = ( 1.77 x 2.52 ) in
'JIS_B10' => [90.709, 127.559], // = ( 32 x 45 ) mm = ( 1.26 x 1.77 ) in
'JIS_B11' => [62.362, 90.709], // = ( 22 x 32 ) mm = ( 0.87 x 1.26 ) in
'JIS_B12' => [45.354, 62.362], // = ( 16 x 22 ) mm = ( 0.63 x 0.87 ) in
// PA Series
'PA0' => [2381.102, 3174.803], // = ( 840 x 1120 ) mm = ( 33.07 x 44.09 ) in
'PA1' => [1587.402, 2381.102], // = ( 560 x 840 ) mm = ( 22.05 x 33.07 ) in
'PA2' => [1190.551, 1587.402], // = ( 420 x 560 ) mm = ( 16.54 x 22.05 ) in
'PA3' => [793.701, 1190.551], // = ( 280 x 420 ) mm = ( 11.02 x 16.54 ) in
'PA4' => [595.276, 793.701], // = ( 210 x 280 ) mm = ( 8.27 x 11.02 ) in
'PA5' => [396.850, 595.276], // = ( 140 x 210 ) mm = ( 5.51 x 8.27 ) in
'PA6' => [297.638, 396.850], // = ( 105 x 140 ) mm = ( 4.13 x 5.51 ) in
'PA7' => [198.425, 297.638], // = ( 70 x 105 ) mm = ( 2.76 x 4.13 ) in
'PA8' => [147.402, 198.425], // = ( 52 x 70 ) mm = ( 2.05 x 2.76 ) in
'PA9' => [99.213, 147.402], // = ( 35 x 52 ) mm = ( 1.38 x 2.05 ) in
'PA10' => [73.701, 99.213], // = ( 26 x 35 ) mm = ( 1.02 x 1.38 ) in
// Standard Photographic Print Sizes
'PASSPORT_PHOTO' => [99.213, 127.559], // = ( 35 x 45 ) mm = ( 1.38 x 1.77 ) in
'E' => [233.858, 340.157], // = ( 82 x 120 ) mm = ( 3.25 x 4.72 ) in
'L' => [252.283, 360.000], // = ( 89 x 127 ) mm = ( 3.50 x 5.00 ) in
'3R' => [252.283, 360.000], // = ( 89 x 127 ) mm = ( 3.50 x 5.00 ) in
'KG' => [289.134, 430.866], // = ( 102 x 152 ) mm = ( 4.02 x 5.98 ) in
'4R' => [289.134, 430.866], // = ( 102 x 152 ) mm = ( 4.02 x 5.98 ) in
'4D' => [340.157, 430.866], // = ( 120 x 152 ) mm = ( 4.72 x 5.98 ) in
'2L' => [360.000, 504.567], // = ( 127 x 178 ) mm = ( 5.00 x 7.01 ) in
'5R' => [360.000, 504.567], // = ( 127 x 178 ) mm = ( 5.00 x 7.01 ) in
'8P' => [430.866, 575.433], // = ( 152 x 203 ) mm = ( 5.98 x 7.99 ) in
'6R' => [430.866, 575.433], // = ( 152 x 203 ) mm = ( 5.98 x 7.99 ) in
'6P' => [575.433, 720.000], // = ( 203 x 254 ) mm = ( 7.99 x 10.00 ) in
'8R' => [575.433, 720.000], // = ( 203 x 254 ) mm = ( 7.99 x 10.00 ) in
'6PW' => [575.433, 864.567], // = ( 203 x 305 ) mm = ( 7.99 x 12.01 ) in
'S8R' => [575.433, 864.567], // = ( 203 x 305 ) mm = ( 7.99 x 12.01 ) in
'4P' => [720.000, 864.567], // = ( 254 x 305 ) mm = ( 10.00 x 12.01 ) in
'10R' => [720.000, 864.567], // = ( 254 x 305 ) mm = ( 10.00 x 12.01 ) in
'4PW' => [720.000, 1080.000], // = ( 254 x 381 ) mm = ( 10.00 x 15.00 ) in
'S10R' => [720.000, 1080.000], // = ( 254 x 381 ) mm = ( 10.00 x 15.00 ) in
'11R' => [790.866, 1009.134], // = ( 279 x 356 ) mm = ( 10.98 x 14.02 ) in
'S11R' => [790.866, 1224.567], // = ( 279 x 432 ) mm = ( 10.98 x 17.01 ) in
'12R' => [864.567, 1080.000], // = ( 305 x 381 ) mm = ( 12.01 x 15.00 ) in
'S12R' => [864.567, 1292.598], // = ( 305 x 456 ) mm = ( 12.01 x 17.95 ) in
// Common Newspaper Sizes
'NEWSPAPER_BROADSHEET' => [2125.984, 1700.787], // = ( 750 x 600 ) mm = ( 29.53 x 23.62 ) in
'NEWSPAPER_BERLINER' => [1332.283, 892.913], // = ( 470 x 315 ) mm = ( 18.50 x 12.40 ) in
'NEWSPAPER_TABLOID' => [1218.898, 793.701], // = ( 430 x 280 ) mm = ( 16.93 x 11.02 ) in
'NEWSPAPER_COMPACT' => [1218.898, 793.701], // = ( 430 x 280 ) mm = ( 16.93 x 11.02 ) in
// Business Cards
'CREDIT_CARD' => [153.014, 242.646], // = ( 54 x 86 ) mm = ( 2.13 x 3.37 ) in
'BUSINESS_CARD' => [153.014, 242.646], // = ( 54 x 86 ) mm = ( 2.13 x 3.37 ) in
'BUSINESS_CARD_ISO7810' => [153.014, 242.646], // = ( 54 x 86 ) mm = ( 2.13 x 3.37 ) in
'BUSINESS_CARD_ISO216' => [147.402, 209.764], // = ( 52 x 74 ) mm = ( 2.05 x 2.91 ) in
'BUSINESS_CARD_IT' => [155.906, 240.945], // = ( 55 x 85 ) mm = ( 2.17 x 3.35 ) in
'BUSINESS_CARD_UK' => [155.906, 240.945], // = ( 55 x 85 ) mm = ( 2.17 x 3.35 ) in
'BUSINESS_CARD_FR' => [155.906, 240.945], // = ( 55 x 85 ) mm = ( 2.17 x 3.35 ) in
'BUSINESS_CARD_DE' => [155.906, 240.945], // = ( 55 x 85 ) mm = ( 2.17 x 3.35 ) in
'BUSINESS_CARD_ES' => [155.906, 240.945], // = ( 55 x 85 ) mm = ( 2.17 x 3.35 ) in
'BUSINESS_CARD_CA' => [144.567, 252.283], // = ( 51 x 89 ) mm = ( 2.01 x 3.50 ) in
'BUSINESS_CARD_US' => [144.567, 252.283], // = ( 51 x 89 ) mm = ( 2.01 x 3.50 ) in
'BUSINESS_CARD_JP' => [155.906, 257.953], // = ( 55 x 91 ) mm = ( 2.17 x 3.58 ) in
'BUSINESS_CARD_HK' => [153.071, 255.118], // = ( 54 x 90 ) mm = ( 2.13 x 3.54 ) in
'BUSINESS_CARD_AU' => [155.906, 255.118], // = ( 55 x 90 ) mm = ( 2.17 x 3.54 ) in
'BUSINESS_CARD_DK' => [155.906, 255.118], // = ( 55 x 90 ) mm = ( 2.17 x 3.54 ) in
'BUSINESS_CARD_SE' => [155.906, 255.118], // = ( 55 x 90 ) mm = ( 2.17 x 3.54 ) in
'BUSINESS_CARD_RU' => [141.732, 255.118], // = ( 50 x 90 ) mm = ( 1.97 x 3.54 ) in
'BUSINESS_CARD_CZ' => [141.732, 255.118], // = ( 50 x 90 ) mm = ( 1.97 x 3.54 ) in
'BUSINESS_CARD_FI' => [141.732, 255.118], // = ( 50 x 90 ) mm = ( 1.97 x 3.54 ) in
'BUSINESS_CARD_HU' => [141.732, 255.118], // = ( 50 x 90 ) mm = ( 1.97 x 3.54 ) in
'BUSINESS_CARD_IL' => [141.732, 255.118], // = ( 50 x 90 ) mm = ( 1.97 x 3.54 ) in
// Billboards
'4SHEET' => [2880.000, 4320.000], // = ( 1016 x 1524 ) mm = ( 40.00 x 60.00 ) in
'6SHEET' => [3401.575, 5102.362], // = ( 1200 x 1800 ) mm = ( 47.24 x 70.87 ) in
'12SHEET' => [8640.000, 4320.000], // = ( 3048 x 1524 ) mm = (120.00 x 60.00 ) in
'16SHEET' => [5760.000, 8640.000], // = ( 2032 x 3048 ) mm = ( 80.00 x 120.00) in
'32SHEET' => [11_520.000, 8640.000], // = ( 4064 x 3048 ) mm = (160.00 x 120.00) in
'48SHEET' => [17_280.000, 8640.000], // = ( 6096 x 3048 ) mm = (240.00 x 120.00) in
'64SHEET' => [23_040.000, 8640.000], // = ( 8128 x 3048 ) mm = (320.00 x 120.00) in
'96SHEET' => [34_560.000, 8640.000], // = (12192 x 3048 ) mm = (480.00 x 120.00) in
// -- Old European Sizes
// - Old Imperial English Sizes
'EN_EMPEROR' => [3456.000, 5184.000], // = ( 1219 x 1829 ) mm = ( 48.00 x 72.00 ) in
'EN_ANTIQUARIAN' => [2232.000, 3816.000], // = ( 787 x 1346 ) mm = ( 31.00 x 53.00 ) in
'EN_GRAND_EAGLE' => [2070.000, 3024.000], // = ( 730 x 1067 ) mm = ( 28.75 x 42.00 ) in
'EN_DOUBLE_ELEPHANT' => [1926.000, 2880.000], // = ( 679 x 1016 ) mm = ( 26.75 x 40.00 ) in
'EN_ATLAS' => [1872.000, 2448.000], // = ( 660 x 864 ) mm = ( 26.00 x 34.00 ) in
'EN_COLOMBIER' => [1692.000, 2484.000], // = ( 597 x 876 ) mm = ( 23.50 x 34.50 ) in
'EN_ELEPHANT' => [1656.000, 2016.000], // = ( 584 x 711 ) mm = ( 23.00 x 28.00 ) in
'EN_DOUBLE_DEMY' => [1620.000, 2556.000], // = ( 572 x 902 ) mm = ( 22.50 x 35.50 ) in
'EN_IMPERIAL' => [1584.000, 2160.000], // = ( 559 x 762 ) mm = ( 22.00 x 30.00 ) in
'EN_PRINCESS' => [1548.000, 2016.000], // = ( 546 x 711 ) mm = ( 21.50 x 28.00 ) in
'EN_CARTRIDGE' => [1512.000, 1872.000], // = ( 533 x 660 ) mm = ( 21.00 x 26.00 ) in
'EN_DOUBLE_LARGE_POST' => [1512.000, 2376.000], // = ( 533 x 838 ) mm = ( 21.00 x 33.00 ) in
'EN_ROYAL' => [1440.000, 1800.000], // = ( 508 x 635 ) mm = ( 20.00 x 25.00 ) in
'EN_SHEET' => [1404.000, 1692.000], // = ( 495 x 597 ) mm = ( 19.50 x 23.50 ) in
'EN_HALF_POST' => [1404.000, 1692.000], // = ( 495 x 597 ) mm = ( 19.50 x 23.50 ) in
'EN_SUPER_ROYAL' => [1368.000, 1944.000], // = ( 483 x 686 ) mm = ( 19.00 x 27.00 ) in
'EN_DOUBLE_POST' => [1368.000, 2196.000], // = ( 483 x 775 ) mm = ( 19.00 x 30.50 ) in
'EN_MEDIUM' => [1260.000, 1656.000], // = ( 445 x 584 ) mm = ( 17.50 x 23.00 ) in
'EN_DEMY' => [1260.000, 1620.000], // = ( 445 x 572 ) mm = ( 17.50 x 22.50 ) in
'EN_LARGE_POST' => [1188.000, 1512.000], // = ( 419 x 533 ) mm = ( 16.50 x 21.00 ) in
'EN_COPY_DRAUGHT' => [1152.000, 1440.000], // = ( 406 x 508 ) mm = ( 16.00 x 20.00 ) in
'EN_POST' => [1116.000, 1386.000], // = ( 394 x 489 ) mm = ( 15.50 x 19.25 ) in
'EN_CROWN' => [1080.000, 1440.000], // = ( 381 x 508 ) mm = ( 15.00 x 20.00 ) in
'EN_PINCHED_POST' => [1062.000, 1332.000], // = ( 375 x 470 ) mm = ( 14.75 x 18.50 ) in
'EN_BRIEF' => [972.000, 1152.000], // = ( 343 x 406 ) mm = ( 13.50 x 16.00 ) in
'EN_FOOLSCAP' => [972.000, 1224.000], // = ( 343 x 432 ) mm = ( 13.50 x 17.00 ) in
'EN_SMALL_FOOLSCAP' => [954.000, 1188.000], // = ( 337 x 419 ) mm = ( 13.25 x 16.50 ) in
'EN_POTT' => [900.000, 1080.000], // = ( 318 x 381 ) mm = ( 12.50 x 15.00 ) in
// - Old Imperial Belgian Sizes
'BE_GRAND_AIGLE' => [1984.252, 2948.031], // = ( 700 x 1040 ) mm = ( 27.56 x 40.94 ) in
'BE_COLOMBIER' => [1757.480, 2409.449], // = ( 620 x 850 ) mm = ( 24.41 x 33.46 ) in
'BE_DOUBLE_CARRE' => [1757.480, 2607.874], // = ( 620 x 920 ) mm = ( 24.41 x 36.22 ) in
'BE_ELEPHANT' => [1746.142, 2182.677], // = ( 616 x 770 ) mm = ( 24.25 x 30.31 ) in
'BE_PETIT_AIGLE' => [1700.787, 2381.102], // = ( 600 x 840 ) mm = ( 23.62 x 33.07 ) in
'BE_GRAND_JESUS' => [1559.055, 2069.291], // = ( 550 x 730 ) mm = ( 21.65 x 28.74 ) in
'BE_JESUS' => [1530.709, 2069.291], // = ( 540 x 730 ) mm = ( 21.26 x 28.74 ) in
'BE_RAISIN' => [1417.323, 1842.520], // = ( 500 x 650 ) mm = ( 19.69 x 25.59 ) in
'BE_GRAND_MEDIAN' => [1303.937, 1714.961], // = ( 460 x 605 ) mm = ( 18.11 x 23.82 ) in
'BE_DOUBLE_POSTE' => [1233.071, 1601.575], // = ( 435 x 565 ) mm = ( 17.13 x 22.24 ) in
'BE_COQUILLE' => [1218.898, 1587.402], // = ( 430 x 560 ) mm = ( 16.93 x 22.05 ) in
'BE_PETIT_MEDIAN' => [1176.378, 1502.362], // = ( 415 x 530 ) mm = ( 16.34 x 20.87 ) in
'BE_RUCHE' => [1020.472, 1303.937], // = ( 360 x 460 ) mm = ( 14.17 x 18.11 ) in
'BE_PROPATRIA' => [977.953, 1218.898], // = ( 345 x 430 ) mm = ( 13.58 x 16.93 ) in
'BE_LYS' => [898.583, 1125.354], // = ( 317 x 397 ) mm = ( 12.48 x 15.63 ) in
'BE_POT' => [870.236, 1088.504], // = ( 307 x 384 ) mm = ( 12.09 x 15.12 ) in
'BE_ROSETTE' => [765.354, 983.622], // = ( 270 x 347 ) mm = ( 10.63 x 13.66 ) in
// - Old Imperial French Sizes
'FR_UNIVERS' => [2834.646, 3685.039], // = ( 1000 x 1300 ) mm = ( 39.37 x 51.18 ) in
'FR_DOUBLE_COLOMBIER' => [2551.181, 3571.654], // = ( 900 x 1260 ) mm = ( 35.43 x 49.61 ) in
'FR_GRANDE_MONDE' => [2551.181, 3571.654], // = ( 900 x 1260 ) mm = ( 35.43 x 49.61 ) in
'FR_DOUBLE_SOLEIL' => [2267.717, 3401.575], // = ( 800 x 1200 ) mm = ( 31.50 x 47.24 ) in
'FR_DOUBLE_JESUS' => [2154.331, 3174.803], // = ( 760 x 1120 ) mm = ( 29.92 x 44.09 ) in
'FR_GRAND_AIGLE' => [2125.984, 3004.724], // = ( 750 x 1060 ) mm = ( 29.53 x 41.73 ) in
'FR_PETIT_AIGLE' => [1984.252, 2664.567], // = ( 700 x 940 ) mm = ( 27.56 x 37.01 ) in
'FR_DOUBLE_RAISIN' => [1842.520, 2834.646], // = ( 650 x 1000 ) mm = ( 25.59 x 39.37 ) in
'FR_JOURNAL' => [1842.520, 2664.567], // = ( 650 x 940 ) mm = ( 25.59 x 37.01 ) in
'FR_COLOMBIER_AFFICHE' => [1785.827, 2551.181], // = ( 630 x 900 ) mm = ( 24.80 x 35.43 ) in
'FR_DOUBLE_CAVALIER' => [1757.480, 2607.874], // = ( 620 x 920 ) mm = ( 24.41 x 36.22 ) in
'FR_CLOCHE' => [1700.787, 2267.717], // = ( 600 x 800 ) mm = ( 23.62 x 31.50 ) in
'FR_SOLEIL' => [1700.787, 2267.717], // = ( 600 x 800 ) mm = ( 23.62 x 31.50 ) in
'FR_DOUBLE_CARRE' => [1587.402, 2551.181], // = ( 560 x 900 ) mm = ( 22.05 x 35.43 ) in
'FR_DOUBLE_COQUILLE' => [1587.402, 2494.488], // = ( 560 x 880 ) mm = ( 22.05 x 34.65 ) in
'FR_JESUS' => [1587.402, 2154.331], // = ( 560 x 760 ) mm = ( 22.05 x 29.92 ) in
'FR_RAISIN' => [1417.323, 1842.520], // = ( 500 x 650 ) mm = ( 19.69 x 25.59 ) in
'FR_CAVALIER' => [1303.937, 1757.480], // = ( 460 x 620 ) mm = ( 18.11 x 24.41 ) in
'FR_DOUBLE_COURONNE' => [1303.937, 2040.945], // = ( 460 x 720 ) mm = ( 18.11 x 28.35 ) in
'FR_CARRE' => [1275.591, 1587.402], // = ( 450 x 560 ) mm = ( 17.72 x 22.05 ) in
'FR_COQUILLE' => [1247.244, 1587.402], // = ( 440 x 560 ) mm = ( 17.32 x 22.05 ) in
'FR_DOUBLE_TELLIERE' => [1247.244, 1927.559], // = ( 440 x 680 ) mm = ( 17.32 x 26.77 ) in
'FR_DOUBLE_CLOCHE' => [1133.858, 1700.787], // = ( 400 x 600 ) mm = ( 15.75 x 23.62 ) in
'FR_DOUBLE_POT' => [1133.858, 1757.480], // = ( 400 x 620 ) mm = ( 15.75 x 24.41 ) in
'FR_ECU' => [1133.858, 1474.016], // = ( 400 x 520 ) mm = ( 15.75 x 20.47 ) in
'FR_COURONNE' => [1020.472, 1303.937], // = ( 360 x 460 ) mm = ( 14.17 x 18.11 ) in
'FR_TELLIERE' => [963.780, 1247.244], // = ( 340 x 440 ) mm = ( 13.39 x 17.32 ) in
'FR_POT' => [878.740, 1133.858], // = ( 310 x 400 ) mm = ( 12.20 x 15.75 ) in
// Colombian Sizes
'CO_CARTA' => [612.283, 790.866], // = ( 216 x 279 ) mm = ( 8.50 x 10.98 ) in
'CO_EXTRA_TABLOIDE' => [864.000, 1296.000], // = ( 304 x 457 ) mm = ( 12.00 x 18.00 ) in
'CO_OFICIO' => [612.283, 935.433], // = ( 216 x 330 ) mm = ( 8.50 x 12.99 ) in
'CO_PLIEGO' => [1984.252, 2834.646], // = ( 700 x 1000 ) mm = ( 27.56 x 39.37 ) in
'CO_PLIEGO2' => [1417.323, 1984.252], // = ( 500 x 700 ) mm = ( 19.69 x 27.56 ) in
'CO_PLIEGO4' => [992.126, 1417.323], // = ( 350 x 500 ) mm = ( 13.78 x 19.69 ) in
'CO_PLIEGO8' => [708.661, 992.126], // = ( 250 x 350 ) mm = ( 9.84 x 13.78 ) in
// Japanese Sizes
'JP_AB_BAN' => [2494.488, 3075.591], // = ( 880 x 1085 ) mm = ( 34.65 x 42.72 ) in
'JP_AIBAN' => [637.795, 977.953], // = ( 225 x 345 ) mm = ( 8.86 x 13.58 ) in
'JP_A_KO_BAN' => [1723.465, 2454.803], // = ( 608 x 866 ) mm = ( 23.94 x 34.09 ) in
'JP_B_KO_BAN' => [2137.323, 2967.874], // = ( 754 x 1047 ) mm = ( 29.69 x 41.22 ) in
'JP_CHOUBO_BAN' => [2318.740, 3092.598], // = ( 818 x 1091 ) mm = ( 32.20 x 42.95 ) in
'JP_CHUBAN' => [538.583, 722.835], // = ( 190 x 255 ) mm = ( 7.48 x 10.04 ) in
'JP_CHU_TANZAKU' => [368.504, 1077.165], // = ( 130 x 380 ) mm = ( 5.12 x 14.96 ) in
'JP_DAI OBAN' => [977.953, 1289.764], // = ( 345 x 455 ) mm = ( 13.58 x 17.91 ) in
'JP_EBANKIRI' => [538.583, 1459.843], // = ( 190 x 515 ) mm = ( 7.48 x 20.28 ) in
'JP_FUURUSU_KO_BAN' => [943.937, 1201.890], // = ( 333 x 424 ) mm = ( 13.11 x 16.69 ) in
'JP_GAYOUSHI' => [1649.764, 2148.661], // = ( 582 x 758 ) mm = ( 22.91 x 29.84 ) in
'JP_HASHIRE_E' => [368.504, 2069.291], // = ( 130 x 730 ) mm = ( 5.12 x 28.74 ) in
'JP_HATORON_BAN' => [2551.181, 3401.575], // = ( 900 x 1200 ) mm = ( 35.43 x 47.24 ) in
'JP_HOM_BAN' => [1842.520, 2211.024], // = ( 650 x 780 ) mm = ( 25.59 x 30.71 ) in
'JP_HOSOBAN' => [411.024, 935.433], // = ( 145 x 330 ) mm = ( 5.71 x 12.99 ) in
'JP_JIS_A_BAN' => [1771.654, 2494.488], // = ( 625 x 880 ) mm = ( 24.61 x 34.65 ) in
'JP_JIS_B_BAN' => [2168.504, 3075.591], // = ( 765 x 1085 ) mm = ( 30.12 x 42.72 ) in
'JP_KAKEMONO_E' => [651.969, 2154.331], // = ( 230 x 760 ) mm = ( 9.06 x 29.92 ) in
'JP_KAKUBAN' => [504.567, 575.433], // = ( 178 x 203 ) mm = ( 7.01 x 7.99 ) in
'JP_KAKU_SURIMONO' => [510.236, 609.449], // = ( 180 x 215 ) mm = ( 7.09 x 8.46 ) in
'JP_KENTO_BAN' => [1374.803, 1768.819], // = ( 485 x 624 ) mm = ( 19.09 x 24.57 ) in
'JP_KIKU_BAN' => [1802.835, 2661.732], // = ( 636 x 939 ) mm = ( 25.04 x 36.97 ) in
'JP_KIKU_BAN4' => [643.465, 867.402], // = ( 227 x 306 ) mm = ( 8.94 x 12.05 ) in
'JP_KIKU_BAN5' => [428.031, 643.465], // = ( 151 x 227 ) mm = ( 5.94 x 8.94 ) in
'JP_KIKU_BAN5_OLD' => [430.866, 617.953], // = ( 152 x 218 ) mm = ( 5.98 x 8.58 ) in
'JP_KIKU_BAN_A20_DORI' => [419.528, 473.386], // = ( 148 x 167 ) mm = ( 5.83 x 6.57 ) in
'JP_KOBAN' => [481.890, 651.969], // = ( 170 x 230 ) mm = ( 6.69 x 9.06 ) in
'JP_KO_BAN_B6' => [317.480, 493.228], // = ( 112 x 174 ) mm = ( 4.41 x 6.85 ) in
'JP_KO_TANZAKU' => [215.433, 977.953], // = ( 76 x 345 ) mm = ( 2.99 x 13.58 ) in
'JP_MOKUTANSHI' => [1332.283, 1760.315], // = ( 470 x 621 ) mm = ( 18.50 x 24.45 ) in
'JP_NAGA_BAN' => [651.969, 1459.843], // = ( 230 x 515 ) mm = ( 9.06 x 20.28 ) in
'JP_OBAN' => [720.000, 1077.165], // = ( 254 x 380 ) mm = ( 10.00 x 14.96 ) in
'JP_OGATA_CHUBAN' => [615.118, 830.551], // = ( 217 x 293 ) mm = ( 8.54 x 11.54 ) in
'JP_O_HOSOBAN' => [481.890, 1077.165], // = ( 170 x 380 ) mm = ( 6.69 x 14.96 ) in
'JP_POSTCARD' => [283.465, 419.528], // = ( 100 x 148 ) mm = ( 3.94 x 5.83 ) in
'JP_SANGO_BAN' => [238.110, 419.528], // = ( 84 x 148 ) mm = ( 3.31 x 5.83 ) in
'JP_SANGO_BAN_A48_DORI' => [209.764, 396.850], // = ( 74 x 140 ) mm = ( 2.91 x 5.51 ) in
'JP_SANGO_BAN_B20_DORI' => [515.906, 583.937], // = ( 182 x 206 ) mm = ( 7.17 x 8.11 ) in
'JP_SANGO_BAN_B36_DORI' => [342.992, 484.724], // = ( 121 x 171 ) mm = ( 4.76 x 6.73 ) in
'JP_SANGO_BAN_B40_DORI' => [238.110, 419.528], // = ( 84 x 148 ) mm = ( 3.31 x 5.83 ) in
'JP_SANROKU_BAN_B48_DORI' => [257.953, 484.724], // = ( 91 x 171 ) mm = ( 3.58 x 6.73 ) in
'JP_SANSAN_BAN' => [1975.748, 2834.646], // = ( 697 x 1000 ) mm = ( 27.44 x 39.37 ) in
'JP_SANSHI_BAN' => [2060.787, 2834.646], // = ( 727 x 1000 ) mm = ( 28.62 x 39.37 ) in
'JP_SHIKISHIBAN' => [581.102, 651.969], // = ( 205 x 230 ) mm = ( 8.07 x 9.06 ) in
'JP_SHIMBUNYOUSHI' => [2304.567, 1547.717], // = ( 813 x 546 ) mm = ( 32.01 x 21.50 ) in
'JP_SHINSHO_BAN_B40_A' => [300.472, 490.394], // = ( 106 x 173 ) mm = ( 4.17 x 6.81 ) in
'JP_SHINSHO_BAN_B40_B' => [291.969, 515.906], // = ( 103 x 182 ) mm = ( 4.06 x 7.17 ) in
'JP_SHIROKU_BAN' => [2233.701, 3092.598], // = ( 788 x 1091 ) mm = ( 31.02 x 42.95 ) in
'JP_SHIROKU_BAN4' => [748.346, 1074.331], // = ( 264 x 379 ) mm = ( 10.39 x 14.92 ) in
'JP_SHIROKU_BAN5' => [535.748, 742.677], // = ( 189 x 262 ) mm = ( 7.44 x 10.31 ) in
'JP_SHIROKU_BAN5_OLD' => [541.417, 734.173], // = ( 191 x 259 ) mm = ( 7.52 x 10.20 ) in
'JP_SHIROKU_BAN6' => [360.000, 532.913], // = ( 127 x 188 ) mm = ( 5.00 x 7.40 ) in
'JP_SHO_TANZAKU' => [269.291, 722.835], // = ( 95 x 255 ) mm = ( 3.74 x 10.04 ) in
'JP_SUITORISHI' => [1252.913, 1615.748], // = ( 442 x 570 ) mm = ( 17.40 x 22.44 ) in
'JP_TANZAKU' => [360.000, 1218.898], // = ( 127 x 430 ) mm = ( 5.00 x 16.93 ) in
'JP_TSUYA_GAMI' => [1440.000, 2160.000], // = ( 508 x 762 ) mm = ( 20.00 x 30.00 ) in
'JP_UCHIWA' => [649.134, 720.000], // = ( 229 x 254 ) mm = ( 9.02 x 10.00 ) in
'JP_WAIDO_BAN' => [595.276, 728.504], // = ( 210 x 257 ) mm = ( 8.27 x 10.12 ) in
'JP_YATSUGIRI_BAN' => [269.291, 360.000], // = ( 95 x 127 ) mm = ( 3.74 x 5.00 ) in
];
/**
* Get page dimensions.
*
* @param string $format The page format name.
* @param string|Orientation $orientation Page orientation ('P' portrait; 'L' landscape; '' default) or enum case.
* @param string|Unit $unit Unit name (default points) or Unit enum case.
* @param int $dec Number of decimals to return.
*
* @return array{0:float, 1:float, 2:string} Page width, height and orientation in specified unit.
*
* @throws PageException
*/
public function getPageFormatSize(
string $format,
string|Orientation $orientation = '',
string|Unit $unit = '',
int $dec = 6,
): array {
$formatSize = self::FORMAT[$format] ?? null;
if ($formatSize === null) {
throw new PageException('unknown page format: ' . $format);
}
return $this->getPageOrientedSize(
$this->convertPoints($formatSize[0], $unit, $dec),
$this->convertPoints($formatSize[1], $unit, $dec),
$orientation,
);
}
/**
* Returns the page dimensions oriented as specified.
*
* @param float $width Page width.
* @param float $height Page height.
* @param string|Orientation $orientation Page orientation ('P' portrait; 'L' landscape; '' default) or enum case.
*
* @return array{0:float, 1:float, 2:string} Page width, height in points and orientation.
*/
public function getPageOrientedSize(float $width, float $height, string|Orientation $orientation = ''): array
{
if ($orientation instanceof Orientation) {
$orientation = $orientation->value;
}
if ($orientation === 'P') {
return [\min($width, $height), \max($width, $height), 'P'];
}
if ($orientation === 'L') {
return [\max($width, $height), \min($width, $height), 'L'];
}
$orientation = $this->getPageOrientation($width, $height);
return [$width, $height, $orientation];
}
/**
* Returns the page orientation.
*
* @param float $width Page width.
* @param float $height Page height.
*
* @return string page orientation 'P' or 'L'.
*/
public function getPageOrientation(float $width, float $height): string
{
if ($width <= $height) {
return 'P';
}
return 'L';
}
/**
* Get the unit ratio for the specified unit of measure.
*
* @param string|Unit $unit Name of the unit of measure, or a Unit enum case.
*
* @throws PageException
*/
public function getUnitRatio(string|Unit $unit): float
{
if ($unit instanceof Unit) {
$unit = $unit->value;
}
$unit = \strtolower($unit);
$ratio = self::UNITRATIO[$unit] ?? null;
if (!is_float($ratio)) {
throw new PageException('unknown unit: ' . $unit);
}
return $ratio;
}
/**
* Convert Points to another unit.
*
* @param float $points Value to convert.
* @param string|Unit $unit Name of the unit to convert to, or a Unit enum case.
* @param int $dec Number of decimals to return.
*
* @throws PageException
*/
public function convertPoints(float $points, string|Unit $unit, int $dec = 6): float
{
return \round($points / $this->getUnitRatio($unit), $dec);
}
}
+100
View File
@@ -0,0 +1,100 @@
<?php
declare(strict_types=1);
/**
* Mode.php
*
* @since 2011-05-23
* @category Library
* @package PdfPage
* @author Nicola Asuni <info@tecnick.com>
* @copyright 2011-2026 Nicola Asuni - Tecnick.com LTD
* @license https://www.gnu.org/copyleft/lesser.html GNU-LGPL v3 (see LICENSE)
* @link https://github.com/tecnickcom/tc-lib-pdf-page
*
* This file is part of tc-lib-pdf-page software library.
*/
namespace Com\Tecnick\Pdf\Page;
/**
* Com\Tecnick\Pdf\Page\Mode
*
* @since 2011-05-23
* @category Library
* @package PdfPage
* @author Nicola Asuni <info@tecnick.com>
* @copyright 2011-2026 Nicola Asuni - Tecnick.com LTD
* @license https://www.gnu.org/copyleft/lesser.html GNU-LGPL v3 (see LICENSE)
* @link https://github.com/tecnickcom/tc-lib-pdf-page
*/
abstract class Mode extends \Com\Tecnick\Pdf\Page\Format
{
/**
* Map layouts with their canonical names
*
* @var array<string, string>
*/
protected const LAYOUT = [
'singlepage' => 'SinglePage', // Display one page at a time
'default' => 'SinglePage',
'single' => 'SinglePage',
'onecolumn' => 'OneColumn', // Display the pages in one column
'continuous' => 'OneColumn',
'twocolumnleft' => 'TwoColumnLeft', // Display the pages in two columns, with odd-numbered pages on the left
'two' => 'TwoColumnLeft',
'twocolumnright' => 'TwoColumnRight', // Display the pages in two columns, with odd-numbered pages on the right
'twopageleft' => 'TwoPageLeft', // Display the pages two at a time, with odd-numbered pages on the left
'twopageright' => 'TwoPageRight', // Display the pages two at a time, with odd-numbered pages on the right
];
/**
* Map display modes with their canonical names
*
* @var array<string, string>
*/
protected const DISPLAY = [
'usenone' => 'UseNone', // Neither document outline nor thumbnail images visible
'useoutlines' => 'UseOutlines', // Document outline visible
'usethumbs' => 'UseThumbs', // Thumbnail images visible
'fullscreen' => 'FullScreen', // Full-screen mode, with no menu bar or window controls
'useoc' => 'UseOC', // (PDF 1.5) Optional content group panel visible
'useattachments' => 'UseAttachments', // (PDF 1.6) Attachments panel visible
'' => 'UseAttachments', // (PDF 1.6) Attachments panel visible
];
/**
* Get the canonical page layout name.
*
* @param string|PageLayout $name Page layout name or PageLayout enum case.
*
* @return string Canonical page layout name.
*/
public function getLayout(string|PageLayout $name = ''): string
{
if ($name instanceof PageLayout) {
return $name->value;
}
$name = \strtolower($name);
return self::LAYOUT[$name] ?? 'SinglePage';
}
/**
* Get the canonical page display mode.
*
* @param string|PageDisplayMode $mode Display mode name or PageDisplayMode enum case.
*
* @return string Canonical page display mode.
*/
public function getDisplay(string|PageDisplayMode $mode = ''): string
{
if ($mode instanceof PageDisplayMode) {
return $mode->value;
}
$mode = \strtolower($mode);
return self::DISPLAY[$mode] ?? 'UseNone';
}
}
+64
View File
@@ -0,0 +1,64 @@
<?php
declare(strict_types=1);
/**
* Orientation.php
*
* @since 2026-07-17
* @category Library
* @package PdfPage
* @author Nicola Asuni <info@tecnick.com>
* @copyright 2011-2026 Nicola Asuni - Tecnick.com LTD
* @license https://www.gnu.org/copyleft/lesser.html GNU-LGPL v3 (see LICENSE)
* @link https://github.com/tecnickcom/tc-lib-pdf-page
*
* This file is part of tc-lib-pdf-page software library.
*/
namespace Com\Tecnick\Pdf\Page;
/**
* Com\Tecnick\Pdf\Page\Orientation
*
* Backed enum for the requested page orientation: 'P' (portrait), 'L'
* (landscape) or '' (auto-detect from the page dimensions).
*
* @since 2026-07-17
* @category Library
* @package PdfPage
* @author Nicola Asuni <info@tecnick.com>
* @copyright 2011-2026 Nicola Asuni - Tecnick.com LTD
* @license https://www.gnu.org/copyleft/lesser.html GNU-LGPL v3 (see LICENSE)
* @link https://github.com/tecnickcom/tc-lib-pdf-page
*/
enum Orientation: string
{
case Portrait = 'P';
case Landscape = 'L';
case Auto = '';
/**
* Resolve a loose orientation value to the matching enum case.
*
* Accepts an enum instance (returned unchanged) or a string. Matching the
* legacy behavior of getPageOrientedSize(), only the exact values 'P' and
* 'L' select an orientation; anything else means auto (never throws).
*
* @param string|self $value Orientation identifier or enum case.
*/
public static function fromLoose(string|self $value): self
{
if ($value instanceof self) {
return $value;
}
return match ($value) {
'P' => self::Portrait,
'L' => self::Landscape,
default => self::Auto,
};
}
}
+707
View File
@@ -0,0 +1,707 @@
<?php
declare(strict_types=1);
/**
* Page.php
*
* @since 2011-05-23
* @category Library
* @package PdfPage
* @author Nicola Asuni <info@tecnick.com>
* @copyright 2011-2026 Nicola Asuni - Tecnick.com LTD
* @license https://www.gnu.org/copyleft/lesser.html GNU-LGPL v3 (see LICENSE)
* @link https://github.com/tecnickcom/tc-lib-pdf-page
*
* This file is part of tc-lib-pdf-page software library.
*/
namespace Com\Tecnick\Pdf\Page;
use Com\Tecnick\Color\Pdf as Color;
use Com\Tecnick\Pdf\Encrypt\Encrypt;
use Com\Tecnick\Pdf\Encrypt\Exception as EncryptException;
use Com\Tecnick\Pdf\Page\Exception as PageException;
/**
* Com\Tecnick\Pdf\Page\Page
*
* @since 2011-05-23
* @category Library
* @package PdfPage
* @author Nicola Asuni <info@tecnick.com>
* @copyright 2011-2026 Nicola Asuni - Tecnick.com LTD
* @license https://www.gnu.org/copyleft/lesser.html GNU-LGPL v3 (see LICENSE)
* @link https://github.com/tecnickcom/tc-lib-pdf-page
*
* @phpstan-import-type PageBci from \Com\Tecnick\Pdf\Page\Box
* @phpstan-import-type PageBox from \Com\Tecnick\Pdf\Page\Box
* @phpstan-import-type MarginData from \Com\Tecnick\Pdf\Page\Box
* @phpstan-import-type RegionData from \Com\Tecnick\Pdf\Page\Box
* @phpstan-import-type TransitionData from \Com\Tecnick\Pdf\Page\Box
* @phpstan-import-type PageData from \Com\Tecnick\Pdf\Page\Box
*
* @SuppressWarnings("PHPMD.TooManyPublicMethods")
*/
class Page extends \Com\Tecnick\Pdf\Page\Region
{
/**
* Initialize page data.
*
* @param string|Unit $unit Unit of measure ('pt', 'mm', 'cm', 'in') or a Unit enum case.
* @param Color $color Color object.
* @param Encrypt $encrypt Encrypt object.
* @param bool $pdfa True if we are in PDF/A mode.
* @param bool $compress Set to false to disable stream compression.
* @param bool $sigapp True if the signature approval is enabled (for incremental updates).
*
* @throws PageException
*/
public function __construct(
string|Unit $unit,
Color $color,
Encrypt $encrypt,
bool $pdfa = false,
bool $compress = true,
bool $sigapp = false,
) {
$this->kunit = $this->getUnitRatio($unit);
$this->col = $color;
$this->enc = $encrypt;
$this->pdfa = $pdfa;
$this->compress = $compress;
$this->sigapp = $sigapp;
}
/**
* Get the unit ratio.
*
* @return float Unit Ratio.
*/
public function getKUnit(): float
{
return $this->kunit;
}
/**
* Enable Signature Approval.
*
* @param bool $sigapp True if the signature approval is enabled (for incremental updates).
*/
public function enableSignatureApproval(bool $sigapp): static
{
$this->sigapp = $sigapp;
return $this;
}
/**
* Record whether the given page actually uses transparency.
*
* When a page is flagged false, the per-page transparency /Group is omitted
* for that page in getPdfPages(). This lets the document assembler flatten
* fully-opaque pages (friendlier to conservative print interpreters) without
* affecting pages that genuinely blend. Pages never flagged keep emitting
* the group, preserving backward-compatible output.
*
* @param bool $hasTransparency True if the page uses actual transparency.
* @param int $pid Page index. Omit or set it to -1 for the current page ID.
*
* @throws PageException
*/
public function setPageTransparency(bool $hasTransparency = true, int $pid = -1): static
{
$pid = $this->sanitizePageID($pid);
$this->pagetransparency[$pid] = $hasTransparency;
return $this;
}
/**
* Set the policy for emitting the per-page transparency /Group on standard
* (non PDF/A) pages.
*
* - 'auto' : opt-out policy (default). The group is emitted on every
* standard page except those explicitly flagged as opaque via
* setPageTransparency(false, $pid). There is no automatic
* transparency detection, so pages that are never flagged keep
* emitting the group, preserving backward-compatible output.
* - 'always' : emit the group on every standard page (legacy behaviour).
* - 'never' : never emit the group.
*
* The mode is matched case-insensitively and unknown values are treated as 'auto'.
*
* @param string|TransparencyGroupMode $mode One of 'auto', 'always', 'never', or a TransparencyGroupMode case.
*/
public function setPageTransparencyGroupMode(string|TransparencyGroupMode $mode): static
{
if ($mode instanceof TransparencyGroupMode) {
$mode = $mode->value;
}
$this->transparencygroupmode = \strtolower($mode);
return $this;
}
/**
* Whether the per-page transparency /Group must be emitted for a page,
* according to the configured mode and the page's recorded transparency.
*
* @param int $pid Page index.
*/
protected function emitPageTransparencyGroup(int $pid): bool
{
return match ($this->transparencygroupmode) {
'always' => true,
'never' => false,
default => $this->pagetransparency[$pid] ?? true,
};
}
/**
* Remove the specified page.
*
* @param int $pid page index. Omit or set it to -1 for the current page ID.
*
* @return PageData Removed page.
*
* @throws PageException
*/
public function delete(int $pid = -1): array
{
$pid = $this->sanitizePageID($pid);
$page = $this->getPage($pid);
$group = $page['group'];
$groupCount = $this->group[$group] ?? 0;
if ($groupCount > 0) {
$this->group[$group] = $groupCount - 1;
}
unset($this->page[$pid]);
$this->page = \array_values($this->page); // reindex array
$this->reindexPageIds();
// Keep the per-page side maps aligned with the reindexed page stack:
// drop the deleted entry and shift the entries above it down by one.
$transparency = [];
foreach ($this->pagetransparency as $idx => $flag) {
if ($idx === $pid) {
continue;
}
$transparency[$idx > $pid ? $idx - 1 : $idx] = $flag;
}
$this->pagetransparency = $transparency;
$nowrite = [];
foreach ($this->nowrite as $idx => $area) {
if ($idx === $pid) {
continue;
}
$nowrite[$idx > $pid ? $idx - 1 : $idx] = $area;
}
$this->nowrite = $nowrite;
--$this->pmaxid;
// Keep the current-page pointer valid and tracking the same page where possible.
if ($this->pid > $pid) {
--$this->pid;
}
if ($this->pid > $this->pmaxid) {
$this->pid = $this->pmaxid;
}
return $page;
}
/**
* Remove and return last page.
*
* @return PageData Removed page.
*
* @throws PageException
*/
public function pop(): array
{
return $this->delete($this->pmaxid);
}
/**
* Move a page to a previous position.
*
* @param int $from Index of the page to move.
* @param int $new Destination index.
*
* @throws PageException
*/
public function move(int $from, int $new): void
{
$page = $this->page[$from] ?? null;
if ($from <= $new || $new < 0 || $from > $this->pmaxid || !is_array($page)) {
throw new PageException('The new position must be lower than the starting position');
}
$pages = $this->page;
unset($pages[$from]);
$pages = \array_values($pages);
\array_splice($pages, $new, 0, [$page]);
/** @var array<int, PageData> $pages */
$this->page = $pages;
$this->reindexPageIds();
// Keep the per-page side maps and the current-page pointer aligned with
// the reordered page stack.
$transparency = [];
foreach ($this->pagetransparency as $idx => $flag) {
$transparency[$this->movedIndex($idx, $from, $new)] = $flag;
}
$this->pagetransparency = $transparency;
$nowrite = [];
foreach ($this->nowrite as $idx => $area) {
$nowrite[$this->movedIndex($idx, $from, $new)] = $area;
}
$this->nowrite = $nowrite;
$this->pid = $this->movedIndex($this->pid, $from, $new);
}
/**
* Compute the new index of a page after move($from, $new) is applied.
*
* @param int $idx Original page index.
* @param int $from Index of the moved page.
* @param int $new Destination index.
*
* @return int The index the page occupies after the move.
*/
private function movedIndex(int $idx, int $from, int $new): int
{
if ($idx === $from) {
return $new;
}
if ($idx >= $new && $idx < $from) {
return $idx + 1;
}
return $idx;
}
/**
* Re-sync the embedded 'pid' field of every page with its index in the stack.
*
* The page stack is reindexed with array_values() after a delete or move, so the
* 'pid' stored inside each page (set once at add() time) would otherwise drift out
* of sync with the array key callers use to address the page.
*/
private function reindexPageIds(): void
{
foreach (\array_keys($this->page) as $idx) {
$this->page[$idx]['pid'] = $idx;
}
}
/**
* Returns the array (stack) containing all pages data.
*
* @return array<int, PageData> Pages.
*/
public function getPages(): array
{
return $this->page;
}
/**
* Add Annotation references.
*
* @param int $oid Annotation object IDs.
* @param int $pid page index. Omit or set it to -1 for the current page ID.
*
* @throws PageException
*/
public function addAnnotRef(int $oid, int $pid = -1): void
{
$pid = $this->sanitizePageID($pid);
$annotrefs = $this->page[$pid]['annotrefs'] ?? [];
if (\in_array($oid, $annotrefs, strict: true)) {
return;
}
$annotrefs[] = $oid;
$this->page[$pid]['annotrefs'] = $annotrefs;
}
/**
* Add page content.
*
* @param string $content Page content.
* @param int $pid Page index. Omit or set it to -1 for the current page ID.
*
* @throws PageException
*/
public function addContent(string $content, int $pid = -1): void
{
$pid = $this->sanitizePageID($pid);
$pageContent = $this->page[$pid]['content'] ?? [''];
$pageContent[] = $content;
$this->page[$pid]['content'] = $pageContent;
}
/**
* Remove and return last page content.
*
* @param int $pid page index. Omit or set it to -1 for the current page ID.
*
* @throws PageException
*/
public function popContent(int $pid = -1): string
{
$pid = $this->sanitizePageID($pid);
$pageContent = $this->page[$pid]['content'] ?? null;
if ($pageContent === null) {
throw new PageException('Page content is empty');
}
$page = \array_pop($pageContent);
if ($page === null) {
throw new PageException('Page content is empty');
}
$this->page[$pid]['content'] = $pageContent;
return $page;
}
/**
* Add page content mark.
*
* @param int $pid page index. Omit or set it to -1 for the current page ID.
*
* @throws PageException
*/
public function addContentMark(int $pid = -1): void
{
$pid = $this->sanitizePageID($pid);
$pageContent = $this->page[$pid]['content'] ?? [''];
$contentMark = $this->page[$pid]['content_mark'] ?? [0];
$contentMark[] = \count($pageContent);
$this->page[$pid]['content'] = $pageContent;
$this->page[$pid]['content_mark'] = $contentMark;
}
/**
* Remove the last marked page content.
*
* @param int $pid page index. Omit or set it to -1 for the current page ID.
*
* @throws PageException
*/
public function popContentToLastMark(int $pid = -1): void
{
$pid = $this->sanitizePageID($pid);
$pageContent = $this->page[$pid]['content'] ?? null;
if (empty($pageContent)) {
return;
}
$contentMark = $this->page[$pid]['content_mark'] ?? [0];
$mark = \array_pop($contentMark);
$this->page[$pid]['content_mark'] = $contentMark;
$this->page[$pid]['content'] = \array_slice($pageContent, 0, (int) ($mark ?? 0), true);
}
/**
* Returns the PDF command to output all page sections.
*
* @param int $pon Current PDF object number.
*
* @return string PDF command.
*
* @throws EncryptException
*/
public function getPdfPages(int &$pon): string
{
$out = $this->getPageRootObj($pon);
foreach ($this->page as $num => $page) {
if (!array_key_exists('num', $page)) {
$page['num'] = $this->getPageNumInGroup($num, $page);
}
$this->page[$num]['num'] = $page['num'];
$content = $this->replacePageTemplates($page);
$out .= $this->getPageContentObj($pon, $content);
$contentobjid = $pon;
$out .=
$page['n']
. ' 0 obj'
. "\n"
. '<<'
. "\n"
. '/Type /Page'
. "\n"
. '/Parent '
. $this->rootoid
. ' 0 R'
. "\n";
if (!$this->pdfa && $this->emitPageTransparencyGroup($num)) {
$out .= '/Group << /Type /Group /S /Transparency /CS /DeviceRGB >>' . "\n";
}
if (!$this->sigapp) {
$out .= '/LastModified ' . $this->enc->getFormattedDate($page['time'], $pon) . "\n";
}
[$boxdims, $boxinfo] = $this->getPageBoxData($page);
$out .=
'/Resources '
. $this->rdoid
. ' 0 R'
. "\n"
. $this->getBox($boxdims)
. $this->getBoxColorInfo($boxinfo)
. '/Contents '
. $contentobjid
. ' 0 R'
. "\n"
. '/Rotate '
. $page['rotation']
. "\n";
$out .= \sprintf('/PZ %F' . "\n", $page['zoom']);
$out .= $this->getPageTransition($page) . $this->getAnnotationRef($page) . '>>' . "\n" . 'endobj' . "\n";
}
return $out;
}
/**
* @param int $num Page index.
* @param PageData $page
*/
protected function getPageNumInGroup(int $num, array $page): int
{
$pnum = 1 + $num;
if ($num <= 0) {
return $pnum;
}
$prevPage = $this->page[$num - 1] ?? null;
if (!is_array($prevPage)) {
return $pnum;
}
return $prevPage['group'] === $page['group'] ? 1 + $prevPage['num'] : 1;
}
/**
* @param PageData $page
*
* @return array{0: array<string, array{llx: float, lly: float, urx: float, ury: float}>, 1: array<string, array{bci: PageBci}>}
*/
protected function getPageBoxData(array $page): array
{
$boxdims = [];
$boxinfo = [];
foreach ($page['box'] as $name => $box) {
$boxdims[$name] = [
'llx' => $box['llx'],
'lly' => $box['lly'],
'urx' => $box['urx'],
'ury' => $box['ury'],
];
$boxinfo[$name] = [
'bci' => $box['bci'],
];
}
return [$boxdims, $boxinfo];
}
/**
* Returns the reserved Object ID for the Resource dictionary.
*
* @return int Resource dictionary Object ID.
*/
public function getResourceDictObjID(): int
{
return $this->rdoid;
}
/**
* Returns the root object ID.
*
* @return int Root Object ID.
*/
public function getRootObjID(): int
{
return $this->rootoid;
}
/**
* Returns the PDF command to output the page content.
*
* @param array<string, mixed> $page Page data.
*
* @return string PDF command.
*/
protected function getPageTransition(array $page): string
{
if (!array_key_exists('transition', $page) || !is_array($page['transition']) || $page['transition'] === []) {
return '';
}
$transition = $page['transition'];
/** @var array<string, bool|int|float|string> $transition */
$entries = ['B', 'D', 'Di', 'Dm', 'M', 'S', 'SS'];
// Entries that are PDF name objects. Everything else among $entries is a
// number (/D, /SS, numeric /Di) or a boolean (/B). /Di may also be the
// name /None, which is handled explicitly below.
$nameKeys = ['S', 'Dm', 'M'];
$out = '';
$out .= \sprintf('/Dur %F' . "\n", (float) ($transition['Dur'] ?? 0.0));
$out .= '/Trans <<' . "\n" . '/Type /Trans' . "\n";
foreach ($transition as $key => $val) {
if (!\in_array($key, $entries, strict: true)) {
continue;
}
if (\is_bool($val)) {
$out .= '/' . $key . ' ' . ($val ? 'true' : 'false') . "\n";
continue;
}
if (\in_array($key, $nameKeys, strict: true) || $val === 'None') {
$out .= '/' . $key . ' /' . (string) $val . "\n";
continue;
}
if (\is_float($val)) {
$out .= \sprintf('/%s %F' . "\n", $key, $val);
continue;
}
$out .= \sprintf('/%s %d' . "\n", $key, (int) $val);
}
return $out . '>>' . "\n";
}
/**
* Get references to page annotations.
*
* @param PageData $page Page data.
*
* @return string PDF command.
*/
protected function getAnnotationRef(array $page): string
{
if (empty($page['annotrefs'])) {
return '';
}
$out = '/Annots [ ';
\sort($page['annotrefs']);
foreach ($page['annotrefs'] as $val) {
$out .= (int) $val . ' 0 R ';
}
return $out . ']' . "\n";
}
/**
* Returns the PDF command to output the page content.
*
* @param int $pon Current PDF object number.
* @param string $content Page content.
*
* @return string PDF command.
*
* @throws EncryptException
*/
protected function getPageContentObj(int &$pon, string $content = ''): string
{
$out = ++$pon . ' 0 obj' . "\n" . '<<';
if ($this->compress) {
$out .= ' /Filter /FlateDecode';
$cmpr = \gzcompress($content);
if ($cmpr !== false) {
$content = $cmpr;
}
}
$stream = $this->enc->encryptString($content, $pon);
return (
$out
. ' /Length '
. \strlen($stream)
. ' >>'
. "\n"
. 'stream'
. "\n"
. $stream
. "\n"
. 'endstream'
. "\n"
. 'endobj'
. "\n"
);
}
/**
* Returns the PDF command to output the page root object.
*
* @param int $pon Current PDF object number.
*
* @return string PDF command.
*/
protected function getPageRootObj(int &$pon): string
{
$this->rdoid = ++$pon; // reserve object ID for the resource dictionary
$this->rootoid = ++$pon;
$out = $this->rootoid . ' 0 obj' . "\n";
$out .= '<< /Type /Pages /Kids [ ';
$numpages = \count($this->page);
for ($pid = 0; $pid < $numpages; ++$pid) {
$this->page[$pid]['n'] = ++$pon;
$out .= $this->page[$pid]['n'] . ' 0 R ';
}
return $out . '] /Count ' . $numpages . ' >>' . "\n" . 'endobj' . "\n";
}
/**
* Replace page templates and numbers.
*
* @param PageData $data Page data.
*/
protected function replacePageTemplates(array $data): string
{
return \implode("\n", \str_replace(
[self::PAGE_TOT, self::PAGE_NUM],
[(string) ($this->group[$data['group']] ?? 0), (string) $data['num']],
$data['content'],
));
}
}
+67
View File
@@ -0,0 +1,67 @@
<?php
declare(strict_types=1);
/**
* PageBoxType.php
*
* @since 2026-07-17
* @category Library
* @package PdfPage
* @author Nicola Asuni <info@tecnick.com>
* @copyright 2011-2026 Nicola Asuni - Tecnick.com LTD
* @license https://www.gnu.org/copyleft/lesser.html GNU-LGPL v3 (see LICENSE)
* @link https://github.com/tecnickcom/tc-lib-pdf-page
*
* This file is part of tc-lib-pdf-page software library.
*/
namespace Com\Tecnick\Pdf\Page;
use Com\Tecnick\Pdf\Page\Exception as PageException;
/**
* Com\Tecnick\Pdf\Page\PageBoxType
*
* Backed enum for the PDF page boundary box names. The backing value of each
* case matches an entry of Box::BOX validated by Box::setBox().
*
* @since 2026-07-17
* @category Library
* @package PdfPage
* @author Nicola Asuni <info@tecnick.com>
* @copyright 2011-2026 Nicola Asuni - Tecnick.com LTD
* @license https://www.gnu.org/copyleft/lesser.html GNU-LGPL v3 (see LICENSE)
* @link https://github.com/tecnickcom/tc-lib-pdf-page
*/
enum PageBoxType: string
{
case MediaBox = 'MediaBox';
case CropBox = 'CropBox';
case BleedBox = 'BleedBox';
case TrimBox = 'TrimBox';
case ArtBox = 'ArtBox';
/**
* Resolve a loose page box value to the matching enum case.
*
* Accepts the exact box name (as validated by Box::setBox) or an enum
* instance (returned unchanged). Unknown values throw.
*
* @param string|self $value Page box name or enum case.
*
* @throws PageException if the value does not match a known page box.
*/
public static function fromLoose(string|self $value): self
{
if ($value instanceof self) {
return $value;
}
return self::tryFrom($value) ?? throw new PageException('unknown page box type: ' . $value);
}
}
@@ -0,0 +1,74 @@
<?php
declare(strict_types=1);
/**
* PageDisplayMode.php
*
* @since 2026-07-17
* @category Library
* @package PdfPage
* @author Nicola Asuni <info@tecnick.com>
* @copyright 2011-2026 Nicola Asuni - Tecnick.com LTD
* @license https://www.gnu.org/copyleft/lesser.html GNU-LGPL v3 (see LICENSE)
* @link https://github.com/tecnickcom/tc-lib-pdf-page
*
* This file is part of tc-lib-pdf-page software library.
*/
namespace Com\Tecnick\Pdf\Page;
/**
* Com\Tecnick\Pdf\Page\PageDisplayMode
*
* Backed enum for the PDF /PageMode name. The backing value of each case is the
* canonical name produced by Mode::getDisplay().
*
* @since 2026-07-17
* @category Library
* @package PdfPage
* @author Nicola Asuni <info@tecnick.com>
* @copyright 2011-2026 Nicola Asuni - Tecnick.com LTD
* @license https://www.gnu.org/copyleft/lesser.html GNU-LGPL v3 (see LICENSE)
* @link https://github.com/tecnickcom/tc-lib-pdf-page
*/
enum PageDisplayMode: string
{
case UseNone = 'UseNone';
case UseOutlines = 'UseOutlines';
case UseThumbs = 'UseThumbs';
case FullScreen = 'FullScreen';
case UseOC = 'UseOC';
case UseAttachments = 'UseAttachments';
/**
* Resolve a loose display mode value to the matching enum case.
*
* Accepts the canonical name (case-insensitively) or an enum instance
* (returned unchanged). The empty string maps to UseAttachments and any
* other unknown value falls back to UseNone, matching Mode::getDisplay().
*
* @param string|self $value Display mode name or enum case.
*/
public static function fromLoose(string|self $value): self
{
if ($value instanceof self) {
return $value;
}
return match (\strtolower($value)) {
'usenone' => self::UseNone,
'useoutlines' => self::UseOutlines,
'usethumbs' => self::UseThumbs,
'fullscreen' => self::FullScreen,
'useoc' => self::UseOC,
'useattachments', '' => self::UseAttachments,
default => self::UseNone,
};
}
}
+74
View File
@@ -0,0 +1,74 @@
<?php
declare(strict_types=1);
/**
* PageLayout.php
*
* @since 2026-07-17
* @category Library
* @package PdfPage
* @author Nicola Asuni <info@tecnick.com>
* @copyright 2011-2026 Nicola Asuni - Tecnick.com LTD
* @license https://www.gnu.org/copyleft/lesser.html GNU-LGPL v3 (see LICENSE)
* @link https://github.com/tecnickcom/tc-lib-pdf-page
*
* This file is part of tc-lib-pdf-page software library.
*/
namespace Com\Tecnick\Pdf\Page;
/**
* Com\Tecnick\Pdf\Page\PageLayout
*
* Backed enum for the PDF /PageLayout name. The backing value of each case is
* the canonical name produced by Mode::getLayout().
*
* @since 2026-07-17
* @category Library
* @package PdfPage
* @author Nicola Asuni <info@tecnick.com>
* @copyright 2011-2026 Nicola Asuni - Tecnick.com LTD
* @license https://www.gnu.org/copyleft/lesser.html GNU-LGPL v3 (see LICENSE)
* @link https://github.com/tecnickcom/tc-lib-pdf-page
*/
enum PageLayout: string
{
case SinglePage = 'SinglePage';
case OneColumn = 'OneColumn';
case TwoColumnLeft = 'TwoColumnLeft';
case TwoColumnRight = 'TwoColumnRight';
case TwoPageLeft = 'TwoPageLeft';
case TwoPageRight = 'TwoPageRight';
/**
* Resolve a loose page layout value to the matching enum case.
*
* Accepts the canonical name, its legacy aliases and the empty-string
* default, case-insensitively, or an enum instance (returned unchanged).
* Unknown values fall back to SinglePage, matching Mode::getLayout().
*
* @param string|self $value Page layout name or enum case.
*/
public static function fromLoose(string|self $value): self
{
if ($value instanceof self) {
return $value;
}
return match (\strtolower($value)) {
'singlepage', 'default', 'single' => self::SinglePage,
'onecolumn', 'continuous' => self::OneColumn,
'twocolumnleft', 'two' => self::TwoColumnLeft,
'twocolumnright' => self::TwoColumnRight,
'twopageleft' => self::TwoPageLeft,
'twopageright' => self::TwoPageRight,
default => self::SinglePage,
};
}
}
+948
View File
@@ -0,0 +1,948 @@
<?php
declare(strict_types=1);
/**
* Region.php
*
* @since 2011-05-23
* @category Library
* @package PdfPage
* @author Nicola Asuni <info@tecnick.com>
* @copyright 2011-2026 Nicola Asuni - Tecnick.com LTD
* @license https://www.gnu.org/copyleft/lesser.html GNU-LGPL v3 (see LICENSE)
* @link https://github.com/tecnickcom/tc-lib-pdf-page
*
* This file is part of tc-lib-pdf-page software library.
*/
namespace Com\Tecnick\Pdf\Page;
use Com\Tecnick\Pdf\Page\Exception as PageException;
/**
* Com\Tecnick\Pdf\Page\Region
*
* @since 2011-05-23
* @category Library
* @package PdfPage
* @author Nicola Asuni <info@tecnick.com>
* @copyright 2011-2026 Nicola Asuni - Tecnick.com LTD
* @license https://www.gnu.org/copyleft/lesser.html GNU-LGPL v3 (see LICENSE)
* @link https://github.com/tecnickcom/tc-lib-pdf-page
*
* @phpstan-import-type RegionData from \Com\Tecnick\Pdf\Page\Box
* @phpstan-import-type PageData from \Com\Tecnick\Pdf\Page\Box
* @phpstan-import-type PageInputData from \Com\Tecnick\Pdf\Page\Box
* @phpstan-import-type NoWriteArea from \Com\Tecnick\Pdf\Page\Box
*
* A page region defines the writable area of the page.
*/
abstract class Region extends \Com\Tecnick\Pdf\Page\Settings
{
/**
* Stored no-write areas per page, used to (re)build the writable regions.
* Keyed by page ID.
*
* @var array<int, array{band: float, areas: array<int, NoWriteArea>}>
*/
protected array $nowrite = [];
/**
* Add a new page.
*
* @param PageInputData $data Page data:
* annotrefs : array containing the annotation object references.
* autobreak : true to automatically add a page when the content reaches the breaking point.
* box : array containing page box boundaries and settings (@see setBox).
* columns : number of equal vertical columns, if set it will automatically populate the region array.
* content : string containing the raw page content.
* format : page format name, or alternatively you can set width and height as below.
* group : page group number.
* height : page height.
* margin : page margins:
* - booklet : true to enable booklet mode
* - PL : page left margin measured from the left page edge
* - PR : page right margin measured from the right page edge
* - PT : page top or header top measured distance from the top page edge
* - HB : header bottom measured from the top page edge
* - CT : content top measured from the top page edge
* - CB : content bottom (page breaking point) measured from the top page edge
* - FT : footer top measured from the bottom page edge
* - PB : page bottom (footer bottom) measured from the bottom page edge
* num : if set overwrites the page number.
* orientation : page orientation ('P' or 'L').
* region : array containing the ordered list of rectangular areas where it is allowed to write,
* each region is defined by:
* - RX : horizontal coordinate of top-left corner
* - RY : vertical coordinate of top-left corner
* - RW : region width
* - RH : region height
* rotation : the number of degrees by which the page shall be rotated clockwise when displayed or printed.
* time : UTC page modification time in seconds.
* transition : array containing page transition data (@see getPageTransition).
* width : page width.
* zoom : preferred zoom (magnification) factor: 1.0 = 100%.
*
* NOTE: if $data is null, then the last page format will be cloned.
*
* @return PageData Page data with additional Page ID property 'pid'.
*
* @throws PageException
*/
public function add(array $data = []): array
{
$cloneLastPage = $data === [] && $this->pmaxid >= 0;
if ($cloneLastPage) {
// clone last page data
$data = $this->getPage($this->pmaxid);
unset($data['time'], $data['content'], $data['annotrefs'], $data['pagenum']);
if (!empty($this->nowrite[$this->pmaxid]['areas'])) {
// No-write regions are page-specific: a cloned page (e.g. created when the text
// flow reaches the bottom of a no-write page with automatic page break enabled)
// starts with the default full-content region instead of inheriting the bands.
unset($data['region'], $data['columns']);
$this->sanitizeRegions($data);
}
}
if (!$cloneLastPage) {
$this->sanitizeNewPageData($data);
}
$this->sanitizeCommonPageData($data);
$data['content_mark'] = [0];
$data['currentRegion'] = 0;
$data['pid'] = ++$this->pmaxid;
$this->pid = $data['pid'];
$data['group'] ??= 0;
/** @var PageData $data */
$this->page[$this->pid] = $data; // @phpstan-ignore assign.propertyType
$group = (int) $data['group'];
$this->group[$group] = ($this->group[$group] ?? 0) + 1;
return $data;
}
/**
* @param PageInputData $data
*
* @throws PageException
*/
protected function sanitizeNewPageData(array &$data): void
{
$this->sanitizeGroup($data);
$this->sanitizeRotation($data);
$this->sanitizeZoom($data);
$this->sanitizePageFormat($data);
$this->sanitizeBoxData($data);
$this->sanitizeTransitions($data);
$this->sanitizeMargins($data);
$this->sanitizeRegions($data);
}
/**
* @param PageInputData $data
*/
protected function sanitizeCommonPageData(array &$data): void
{
$this->sanitizeTime($data);
$this->sanitizeContent($data);
$this->sanitizeAnnotRefs($data);
$this->sanitizePageNumber($data);
}
/**
* Set the current page number (move to the specified page).
*
* @param int $pid page index. Omit or set it to -1 for the current page ID.
*
* @return PageData Page data.
*
* @throws PageException
*/
public function setCurrentPage(int $pid = -1): array
{
$pid = $this->sanitizePageID($pid);
$this->pid = $pid;
return $this->getPage($this->pid);
}
/**
* Returns the specified page data.
*
* @param int $pid page index. Omit or set it to -1 for the current page ID.
*
* @return PageData Page data.
*
* @throws PageException
*/
public function getPage(int $pid = -1): array
{
$pid = $this->sanitizePageID($pid);
$page = $this->page[$pid] ?? null;
if ($page === null) {
throw new PageException('The page with index ' . $pid . ' does not exist.');
}
return $page;
}
/**
* Overrides the page height and returns the current value in points.
*
* @param float $pheight new page height in internal points.
* @param int $pid page index. Omit or set it to -1 for the current page ID.
*
* @return float original page height in points.
*
* @throws PageException
*/
public function setPagePHeight(float $pheight, int $pid = -1): float
{
$pid = $this->sanitizePageID($pid);
if (!\array_key_exists($pid, $this->page)) {
throw new PageException('The page with index ' . $pid . ' does not exist.');
}
$ret = $this->page[$pid]['pheight'];
$this->page[$pid]['pheight'] = $pheight;
$this->page[$pid]['height'] = $pheight / $this->kunit;
return $ret;
}
/**
* Overrides the page width and returns the current value in points.
*
* @param float $pwidth new page width in internal points.
* @param int $pid page index. Omit or set it to -1 for the current page ID.
*
* @return float original page width in points.
*
* @throws PageException
*/
public function setPagePWidth(float $pwidth, int $pid = -1): float
{
$pid = $this->sanitizePageID($pid);
if (!\array_key_exists($pid, $this->page)) {
throw new PageException('The page with index ' . $pid . ' does not exist.');
}
$ret = $this->page[$pid]['pwidth'];
$this->page[$pid]['pwidth'] = $pwidth;
$this->page[$pid]['width'] = $pwidth / $this->kunit;
return $ret;
}
/**
* Check if the specified page ID exist.
*
* @param int $pid page index. Omit or set it to -1 for the current page ID.
*
* @return int Page ID.
*
* @throws PageException
*/
protected function sanitizePageID(int $pid = -1): int
{
if ($pid < 0) {
$pid = $this->pid;
}
if (!\array_key_exists($pid, $this->page)) {
throw new PageException('The page with index ' . $pid . ' does not exist.');
}
return $pid;
}
/**
* Select the specified page region.
*
* @param int $idr ID of the region.
* @param int $pid page index. Omit or set it to -1 for the current page ID.
*
* @return RegionData Selected region data.
*
* @throws PageException
*/
public function selectRegion(int $idr, int $pid = -1): array
{
$pid = $this->sanitizePageID($pid);
if (!\array_key_exists($pid, $this->page)) {
throw new PageException('The page with index ' . $pid . ' does not exist.');
}
$columns = (int) $this->page[$pid]['columns'];
// 'columns' is the region count, so the last valid index is columns - 1.
$this->page[$pid]['currentRegion'] = \min(\max(0, $idr), \max(0, $columns - 1));
return $this->getRegion($pid);
}
/**
* Returns the current region data.
*
* @param int $pid page index. Omit or set it to -1 for the current page ID.
*
* @return RegionData Region.
*
* @throws PageException
*/
public function getRegion(int $pid = -1): array
{
$pid = $this->sanitizePageID($pid);
$page = $this->getPage($pid);
$currentRegion = $page['currentRegion'];
$regions = $page['region'];
if (!\array_key_exists($currentRegion, $regions)) {
throw new PageException('The current region with index ' . $currentRegion . ' does not exist.');
}
return $regions[$currentRegion];
}
/**
* Returns the next page data.
* Creates a new page if required and page break is enabled.
*
* @param int $pid page index. Omit or set it to -1 for the current page ID.
*
* @return PageData Page data.
*
* @throws PageException
*/
public function getNextPage(int $pid = -1): array
{
$pid = $this->sanitizePageID($pid);
if ($pid < $this->pmaxid) {
$this->pid = ++$pid;
return $this->getPage($this->pid);
}
if (!$this->isAutoPageBreakEnabled($pid)) {
return $this->setCurrentPage($pid);
}
return $this->add();
}
/**
* Returns the page data with the next selected region.
* If there are no more regions available, then the first region on the next page is selected.
* A new page is added if required.
*
* @param int $pid page index. Omit or set it to -1 for the current page ID.
*
* @return PageData Current page data.
*
* @throws PageException
*/
public function getNextRegion(int $pid = -1): array
{
$pid = $this->sanitizePageID($pid);
if (!\array_key_exists($pid, $this->page)) {
throw new PageException('The page with index ' . $pid . ' does not exist.');
}
$nextid = (int) $this->page[$pid]['currentRegion'] + 1;
if (\array_key_exists($nextid, $this->page[$pid]['region'])) {
$this->page[$pid]['currentRegion'] = $nextid;
return $this->getPage($pid);
}
return $this->getNextPage($pid);
}
/**
* Move to the next page region if required.
*
* @param float $height Height of the block to add.
* @param ?float $ypos Starting Y position or NULL for current position.
* @param int $pid Page index. Omit or set it to -1 for the current page ID.
*
* @return PageData Page data.
*
* @throws PageException
*/
public function checkRegionBreak(float $height = 0.0, ?float $ypos = null, int $pid = -1): array
{
if ($this->isYOutRegion($ypos, $height, $pid)) {
return $this->getNextRegion($pid);
}
return $this->getPage($pid);
}
/**
* Return the auto-page-break status.
*
* @param int $pid page index. Omit or set it to -1 for the current page ID.
*
* @return bool True if the auto page break is enabled, false otherwise.
*
* @throws PageException
*/
public function isAutoPageBreakEnabled(int $pid = -1): bool
{
$pid = $this->sanitizePageID($pid);
if (!\array_key_exists($pid, $this->page)) {
throw new PageException('The page with index ' . $pid . ' does not exist.');
}
return $this->page[$pid]['autobreak'];
}
/**
* Enable or disable automatic page break.
*
* @param bool $isenabled Set this to true to enable automatic page break.
* @param int $pid page index. Omit or set it to -1 for the current page ID.
*
* @throws PageException
*/
public function enableAutoPageBreak(bool $isenabled = true, int $pid = -1): void
{
$pid = $this->sanitizePageID($pid);
if (!\array_key_exists($pid, $this->page)) {
throw new PageException('The page with index ' . $pid . ' does not exist.');
}
$this->page[$pid]['autobreak'] = $isenabled;
}
/**
* Check if the specified position is outside the region.
*
* @param float $pos Position.
* @param 'RX'|'RY' $min ID of the min region value to check.
* @param int $pid page index. Omit or set it to -1 for the current page ID.
*
* @throws PageException
*/
private function isOutRegion(float $pos, string $min, int $pid = -1): bool
{
$region = $this->getRegion($pid);
$minpos = $region['RY'];
$maxpos = $region['RT'];
if ($min === 'RX') {
$minpos = $region['RX'];
$maxpos = $region['RL'];
}
return $pos < ($minpos - self::EPS) || $pos > ($maxpos + self::EPS);
}
/**
* Check if the specified vertical position is outside the region.
*
* @param ?float $posy Y position or NULL for current position.
* @param float $height Additional height to add.
* @param int $pid page index. Omit or set it to -1 for the current page ID.
*
* @throws PageException
*/
public function isYOutRegion(?float $posy = null, float $height = 0.0, int $pid = -1): bool
{
if ($posy === null) {
$posy = $this->getY();
}
return $this->isOutRegion($posy + $height, 'RY', $pid);
}
/**
* Check if the specified horizontal position is outside the region.
*
* @param ?float $posx X position or NULL for current position.
* @param float $width Additional width to add.
* @param int $pid page index. Omit or set it to -1 for the current page ID.
*
* @throws PageException
*/
public function isXOutRegion(?float $posx = null, float $width = 0.0, int $pid = -1): bool
{
if ($posx === null) {
$posx = $this->getX();
}
return $this->isOutRegion($posx + $width, 'RX', $pid);
}
/**
* Return the absolute horizontal cursor position for the current region.
*
* @param int $pid page index. Omit or set it to -1 for the current page ID.
*
* @throws PageException
*/
public function getX(int $pid = -1): float
{
$region = $this->getRegion($pid);
return $region['x'];
}
/**
* Return the absolute vertical cursor position for the current region.
*
* @param int $pid page index. Omit or set it to -1 for the current page ID.
*
* @throws PageException
*/
public function getY(int $pid = -1): float
{
$region = $this->getRegion($pid);
return $region['y'];
}
/**
* Set the absolute horizontal cursor position for the current region.
*
* @param float $xpos X position relative to the page coordinates.
* @param int $pid page index. Omit or set it to -1 for the current page ID.
*
* @throws PageException
*/
public function setX(float $xpos, int $pid = -1): static
{
$pid = $this->sanitizePageID($pid);
if (!\array_key_exists($pid, $this->page)) {
throw new PageException('The page with index ' . $pid . ' does not exist.');
}
$currentRegion = (int) $this->page[$pid]['currentRegion'];
if (!\array_key_exists($currentRegion, $this->page[$pid]['region'])) {
throw new PageException('The current region with index ' . $currentRegion . ' does not exist.');
}
$this->page[$pid]['region'][$currentRegion]['x'] = $xpos;
return $this;
}
/**
* Set the absolute vertical cursor position for the current region.
*
* @param float $ypos Y position relative to the page coordinates.
* @param int $pid page index. Omit or set it to -1 for the current page ID.
*
* @throws PageException
*/
public function setY(float $ypos, int $pid = -1): static
{
$pid = $this->sanitizePageID($pid);
if (!\array_key_exists($pid, $this->page)) {
throw new PageException('The page with index ' . $pid . ' does not exist.');
}
$currentRegion = (int) $this->page[$pid]['currentRegion'];
if (!\array_key_exists($currentRegion, $this->page[$pid]['region'])) {
throw new PageException('The current region with index ' . $currentRegion . ' does not exist.');
}
$this->page[$pid]['region'][$currentRegion]['y'] = $ypos;
return $this;
}
/**
* Build the ordered list of writable rectangular regions that avoid the given no-write areas.
*
* This approximates the legacy TCPDF no-write page regions: the content area is sliced into
* horizontal bands of height $bandHeight, and for each band the widest rectangle that does
* not overlap any no-write area is returned. Vertically-contiguous bands that share the same
* horizontal extent are merged, so the area above and below an obstacle collapses to a single
* tall region and only the obstacle span is finely banded. The result is a stack of
* axis-aligned rectangles ordered top-to-bottom, suitable as the 'region' value of add() or
* as the input of setNoWriteRegions().
*
* Each no-write area can be defined in one of two ways (page coordinates, user units):
* - side-anchored segment (legacy form), where the obstacle spans from a page side to a
* vertical, possibly slanted, segment:
* 'xt','yt' : segment top point, 'xb','yb' : segment bottom point,
* 'side' : 'L' to block from the left page edge to the segment, 'R' for the right.
* - free rectangle (floating obstacle, e.g. an image):
* 'x','y' : top-left corner, 'w' : width, 'h' : height.
*
* NOTE: the text engine fills one region before moving to the next, so when a floating area
* splits a band into two writable columns only the widest one is kept; text does not wrap on
* both sides of a floating obstacle.
*
* @param array<int, NoWriteArea> $noWriteAreas No-write areas (page coordinates, user units).
* @param float $bandHeight Height of each horizontal slice (must be > 0).
* @param int $pid Page index. Omit or set it to -1 for the current page.
*
* @return array<int, array{RX: float, RY: float, RW: float, RH: float}> Ordered writable regions.
*
* @throws PageException
*/
public function buildWritableRegions(array $noWriteAreas, float $bandHeight, int $pid = -1): array
{
if ($bandHeight <= self::EPS) {
throw new PageException('The band height must be a positive value.');
}
$page = $this->getPage($pid);
$cx0 = $page['margin']['PL'];
$cy0 = $page['margin']['CT'];
$cx1 = $cx0 + $page['ContentWidth'];
$cy1 = $cy0 + $page['ContentHeight'];
$norm = $this->normalizeNoWriteAreas($noWriteAreas, $cx0, $cx1);
return $this->bandWritableRegions($norm, $cx0, $cy0, $cx1, $cy1, $bandHeight);
}
/**
* Set the no-write page regions, replacing any previously stored areas for the page.
* The writable regions are (re)built and assigned to the page. Mirrors the legacy
* setPageRegions() behaviour using rectangular regions.
*
* @param array<int, NoWriteArea> $noWriteAreas No-write areas (page coordinates, user units).
* @param float $bandHeight Height of each horizontal slice (must be > 0).
* @param int $pid Page index. Omit or set it to -1 for the current page.
*
* @return PageData Page data.
*
* @throws PageException
*/
public function setNoWriteRegions(array $noWriteAreas, float $bandHeight, int $pid = -1): array
{
if ($bandHeight <= self::EPS) {
throw new PageException('The band height must be a positive value.');
}
$pid = $this->sanitizePageID($pid);
$this->nowrite[$pid] = [
'band' => $bandHeight,
'areas' => \array_values($noWriteAreas),
];
return $this->applyNoWriteRegions($pid);
}
/**
* Append a single no-write area to the page and rebuild the writable regions.
* setNoWriteRegions() must have been called first to set the band height.
*
* @param NoWriteArea $noWriteArea No-write area (page coordinates, user units).
* @param int $pid Page index. Omit or set it to -1 for the current page.
*
* @return PageData Page data.
*
* @throws PageException
*/
public function addNoWriteRegion(array $noWriteArea, int $pid = -1): array
{
$pid = $this->sanitizePageID($pid);
if (!isset($this->nowrite[$pid]) || $this->nowrite[$pid]['band'] <= self::EPS) {
throw new PageException('Call setNoWriteRegions() to set the band height before adding a region.');
}
$this->nowrite[$pid]['areas'][] = $noWriteArea;
return $this->applyNoWriteRegions($pid);
}
/**
* Return the no-write areas currently stored for the page.
*
* @param int $pid Page index. Omit or set it to -1 for the current page.
*
* @return array<int, NoWriteArea> No-write areas.
*
* @throws PageException
*/
public function getNoWriteRegions(int $pid = -1): array
{
$pid = $this->sanitizePageID($pid);
return $this->nowrite[$pid]['areas'] ?? [];
}
/**
* Remove the no-write area with the given index and rebuild the writable regions.
*
* @param int $index Index of the no-write area to remove.
* @param int $pid Page index. Omit or set it to -1 for the current page.
*
* @return PageData Page data.
*
* @throws PageException
*/
public function removeNoWriteRegion(int $index, int $pid = -1): array
{
$pid = $this->sanitizePageID($pid);
if (!isset($this->nowrite[$pid]['areas'][$index])) {
throw new PageException('The no-write region with index ' . $index . ' does not exist.');
}
unset($this->nowrite[$pid]['areas'][$index]);
$this->nowrite[$pid]['areas'] = \array_values($this->nowrite[$pid]['areas']);
return $this->applyNoWriteRegions($pid);
}
/**
* (Re)build the writable regions for the page from its stored no-write areas and assign them.
*
* @param int $pid Page index (already sanitized).
*
* @return PageData Page data.
*
* @throws PageException
*/
private function applyNoWriteRegions(int $pid): array
{
$store = $this->nowrite[$pid] ?? ['band' => 0.0, 'areas' => []];
$page = $this->getPage($pid);
$raw = $this->buildWritableRegions($store['areas'], $store['band'], $pid);
if ($raw === []) {
// Everything is blocked: fall back to the full content region so text can still flow.
$raw = [[
'RX' => $page['margin']['PL'],
'RY' => $page['margin']['CT'],
'RW' => $page['ContentWidth'],
'RH' => $page['ContentHeight'],
]];
}
$regions = [];
foreach ($raw as $reg) {
$regions[] = $this->normalizeRegionData(
$reg,
$page['ContentWidth'],
$page['ContentHeight'],
$page['width'],
$page['height'],
$page['margin']['PR'],
$page['margin']['CB'],
);
}
$this->page[$pid]['region'] = $regions;
$this->page[$pid]['columns'] = \count($regions);
$this->page[$pid]['currentRegion'] = 0;
return $this->getPage($pid);
}
/**
* Convert the public no-write area definitions into internal occupied-edge records.
* Each record stores the occupied X interval as two linear functions of Y over [y0, y1]:
* a left edge (lt -> lb) and a right edge (rt -> rb).
*
* @param array<int, NoWriteArea> $areas No-write areas.
* @param float $cx0 Left edge of the content area.
* @param float $cx1 Right edge of the content area.
*
* @return array<int, array{y0: float, y1: float, lt: float, lb: float, rt: float, rb: float}>
*/
private function normalizeNoWriteAreas(array $areas, float $cx0, float $cx1): array
{
$norm = [];
foreach ($areas as $area) {
if (isset($area['side'])) {
$yt = (float) ($area['yt'] ?? 0);
$yb = (float) ($area['yb'] ?? 0);
$xt = (float) ($area['xt'] ?? 0);
$xb = (float) ($area['xb'] ?? 0);
if ($yb < $yt) {
[$yt, $yb] = [$yb, $yt];
[$xt, $xb] = [$xb, $xt];
}
if (\strtoupper($area['side']) === 'L') {
// Obstacle on the left: it occupies from the left content edge to the segment.
$norm[] = ['y0' => $yt, 'y1' => $yb, 'lt' => $cx0, 'lb' => $cx0, 'rt' => $xt, 'rb' => $xb];
} else {
// Obstacle on the right: it occupies from the segment to the right content edge.
$norm[] = ['y0' => $yt, 'y1' => $yb, 'lt' => $xt, 'lb' => $xb, 'rt' => $cx1, 'rb' => $cx1];
}
continue;
}
$xpos = (float) ($area['x'] ?? 0);
$ypos = (float) ($area['y'] ?? 0);
$width = (float) ($area['w'] ?? 0);
$height = (float) ($area['h'] ?? 0);
$norm[] = [
'y0' => $ypos,
'y1' => $ypos + $height,
'lt' => $xpos,
'lb' => $xpos,
'rt' => $xpos + $width,
'rb' => $xpos + $width,
];
}
return $norm;
}
/**
* Slice the content height into bands and compute the widest writable rectangle per band,
* merging vertically-contiguous bands that share the same horizontal extent.
*
* @param array<int, array{y0: float, y1: float, lt: float, lb: float, rt: float, rb: float}> $norm
* @param float $cx0 Left edge of the content area.
* @param float $cy0 Top edge of the content area.
* @param float $cx1 Right edge of the content area.
* @param float $cy1 Bottom edge of the content area.
* @param float $bandHeight Height of each horizontal slice.
*
* @return array<int, array{RX: float, RY: float, RW: float, RH: float}>
*/
private function bandWritableRegions(
array $norm,
float $cx0,
float $cy0,
float $cx1,
float $cy1,
float $bandHeight,
): array {
$regions = [];
/** @var array{RX: float, RY: float, RW: float, RH: float}|null $pending */
$pending = null;
$ypos = $cy0;
while ($ypos < ($cy1 - self::EPS)) {
$yTop = $ypos;
$yBot = \min($ypos + $bandHeight, $cy1);
$ypos = $yBot;
$best = $this->widestBandInterval($norm, $cx0, $cx1, $yTop, $yBot);
if ($best === null) {
// Fully blocked band: leaves a gap and breaks the vertical merge.
if ($pending !== null) {
$regions[] = $pending;
$pending = null;
}
continue;
}
$rposx = $best[0];
$rwidth = $best[1] - $best[0];
if (
$pending !== null
&& \abs($pending['RX'] - $rposx) <= self::EPS
&& \abs($pending['RW'] - $rwidth) <= self::EPS
&& \abs($pending['RY'] + $pending['RH'] - $yTop) <= self::EPS
) {
// Same horizontal extent and vertically contiguous: extend the pending region.
$pending['RH'] += $yBot - $yTop;
continue;
}
if ($pending !== null) {
$regions[] = $pending;
}
$pending = ['RX' => $rposx, 'RY' => $yTop, 'RW' => $rwidth, 'RH' => $yBot - $yTop];
}
if ($pending !== null) {
$regions[] = $pending;
}
return $regions;
}
/**
* Return the widest writable X interval [left, right] for a single band, or null if the band
* is fully blocked. The occupied span of each overlapping area is taken at its widest within
* the band so that no text can overlap a slanted edge.
*
* @param array<int, array{y0: float, y1: float, lt: float, lb: float, rt: float, rb: float}> $norm
* @param float $cx0 Left edge of the content area.
* @param float $cx1 Right edge of the content area.
* @param float $yTop Top of the band.
* @param float $yBot Bottom of the band.
*
* @return array{0: float, 1: float}|null
*/
private function widestBandInterval(array $norm, float $cx0, float $cx1, float $yTop, float $yBot): ?array
{
$free = [[$cx0, $cx1]];
foreach ($norm as $nwa) {
$ovlTop = \max($yTop, $nwa['y0']);
$ovlBot = \min($yBot, $nwa['y1']);
if ($ovlBot <= ($ovlTop + self::EPS)) {
continue;
}
$occl = \max($cx0, \min(
$this->lerpEdge($nwa['lt'], $nwa['lb'], $nwa['y0'], $nwa['y1'], $ovlTop),
$this->lerpEdge($nwa['lt'], $nwa['lb'], $nwa['y0'], $nwa['y1'], $ovlBot),
));
$occr = \min($cx1, \max(
$this->lerpEdge($nwa['rt'], $nwa['rb'], $nwa['y0'], $nwa['y1'], $ovlTop),
$this->lerpEdge($nwa['rt'], $nwa['rb'], $nwa['y0'], $nwa['y1'], $ovlBot),
));
if ($occr <= ($occl + self::EPS)) {
continue;
}
$free = $this->subtractInterval($free, $occl, $occr);
}
$best = null;
foreach ($free as $interval) {
$fwidth = $interval[1] - $interval[0];
if ($fwidth <= self::EPS) {
continue;
}
if ($best === null || $fwidth > ($best[1] - $best[0])) {
$best = $interval;
}
}
return $best;
}
/**
* Linearly interpolate an edge X value at the vertical position $yy between (y0 -> vt) and
* (y1 -> vb).
*/
private function lerpEdge(float $vt, float $vb, float $y0, float $y1, float $yy): float
{
$span = $y1 - $y0;
if ($span <= self::EPS) {
return $vt;
}
return $vt + (($vb - $vt) * (($yy - $y0) / $span));
}
/**
* Subtract the occupied interval [occl, occr] from a set of disjoint free intervals.
*
* @param array<int, array{0: float, 1: float}> $free Free intervals.
* @param float $occl Left edge of the occupied interval.
* @param float $occr Right edge of the occupied interval.
*
* @return array<int, array{0: float, 1: float}> Remaining free intervals.
*/
private function subtractInterval(array $free, float $occl, float $occr): array
{
$out = [];
foreach ($free as $interval) {
$fleft = $interval[0];
$fright = $interval[1];
if ($occr <= ($fleft + self::EPS) || $occl >= ($fright - self::EPS)) {
$out[] = [$fleft, $fright];
continue;
}
if ($occl > ($fleft + self::EPS)) {
$out[] = [$fleft, $occl];
}
if ($occr < ($fright - self::EPS)) {
$out[] = [$occr, $fright];
}
}
return $out;
}
}
+756
View File
@@ -0,0 +1,756 @@
<?php
declare(strict_types=1);
/**
* Settings.php
*
* @since 2011-05-23
* @category Library
* @package PdfPage
* @author Nicola Asuni <info@tecnick.com>
* @copyright 2011-2026 Nicola Asuni - Tecnick.com LTD
* @license https://www.gnu.org/copyleft/lesser.html GNU-LGPL v3 (see LICENSE)
* @link https://github.com/tecnickcom/tc-lib-pdf-page
*
* This file is part of tc-lib-pdf-page software library.
*/
namespace Com\Tecnick\Pdf\Page;
use Com\Tecnick\Pdf\Encrypt\Encrypt;
/**
* Com\Tecnick\Pdf\Page\Settings
*
* @since 2011-05-23
* @category Library
* @package PdfPage
* @author Nicola Asuni <info@tecnick.com>
* @copyright 2011-2026 Nicola Asuni - Tecnick.com LTD
* @license https://www.gnu.org/copyleft/lesser.html GNU-LGPL v3 (see LICENSE)
* @link https://github.com/tecnickcom/tc-lib-pdf-page
*
* @phpstan-import-type PageBci from \Com\Tecnick\Pdf\Page\Box
* @phpstan-import-type PageBox from \Com\Tecnick\Pdf\Page\Box
* @phpstan-import-type MarginData from \Com\Tecnick\Pdf\Page\Box
* @phpstan-import-type RegionData from \Com\Tecnick\Pdf\Page\Box
* @phpstan-import-type TransitionData from \Com\Tecnick\Pdf\Page\Box
* @phpstan-import-type PageData from \Com\Tecnick\Pdf\Page\Box
* @phpstan-import-type PageInputData from \Com\Tecnick\Pdf\Page\Box
*
* @SuppressWarnings("PHPMD.TooManyPublicMethods")
* @SuppressWarnings("PHPMD.ExcessiveClassComplexity")
*/
abstract class Settings extends \Com\Tecnick\Pdf\Page\Box
{
/**
* Epsilon precision used to compare floating point values.
*/
public const EPS = 0.0001;
/**
* Alias for total number of pages in a group.
*
* @var string
*/
public const PAGE_TOT = '~#PT';
/**
* Alias for page number.
*
* @var string
*/
public const PAGE_NUM = '~#PN';
/**
* Array of pages (stack).
*
* @var array<int, PageData>
*/
protected array $page = [];
/**
* Current page ID.
*/
protected int $pid = -1;
/**
* Maximum page ID.
*/
protected int $pmaxid = -1;
/**
* Count pages in each group.
*
* @var array<int, int>
*/
protected array $group = [
0 => 0,
];
/**
* Encrypt object.
*/
protected Encrypt $enc;
/**
* True if we are in PDF/A mode.
*/
protected bool $pdfa = false;
/**
* Enable stream compression.
*/
protected bool $compress = true;
/**
* True if the signature approval is enabled (for incremental updates).
*/
protected bool $sigapp = false;
/**
* Per-page flag indicating whether the page actually uses transparency.
*
* Maps a page index to true/false. When a page is flagged false the
* per-page transparency /Group is omitted (a fully-opaque page does not
* need it, and the group would otherwise force conforming interpreters onto
* the slower transparency-compositing path). Unset pages default to emitting
* the group, preserving backward-compatible output.
*
* @var array<int, bool>
*/
protected array $pagetransparency = [];
/**
* Policy for emitting the per-page transparency /Group on standard pages:
* 'auto' (only on pages flagged as using transparency, default), 'always'
* (every standard page) or 'never'.
*/
protected string $transparencygroupmode = 'auto';
/**
* Reserved Object ID for the resource dictionary.
*/
protected int $rdoid = 1;
/**
* Root object ID.
*/
protected int $rootoid = 0;
/**
* Return the current page ID.
*
* @return int Page ID.
*/
public function getPageID(): int
{
return $this->pid;
}
/**
* Sanitize or set the page number.
*
* @param PageInputData $data Page data.
*/
public function sanitizePageNumber(array &$data): void
{
if (!empty($data['num'])) {
$data['num'] = \max(0, (int) $data['num']);
}
}
/**
* Sanitize or set the page modification time.
*
* @param PageInputData $data Page data.
*/
public function sanitizeTime(array &$data): void
{
$data['time'] = empty($data['time']) ? \time() : \max(0, (int) $data['time']);
}
/**
* Sanitize or set the page group.
*
* @param PageInputData $data Page data.
*/
public function sanitizeGroup(array &$data): void
{
$data['group'] = empty($data['group']) ? 0 : \max(0, $data['group']);
}
/**
* Sanitize or set the page content.
*
* @param PageInputData $data Page data.
*/
public function sanitizeContent(array &$data): void
{
if (!\array_key_exists('content', $data) || $data['content'] === []) {
$data['content'] = [''];
return;
}
if (\is_string($data['content'])) {
$data['content'] = [$data['content']];
return;
}
$data['content'] = \array_values($data['content']);
}
/**
* Sanitize or set the annotation references.
*
* @param PageInputData $data Page data.
*/
public function sanitizeAnnotRefs(array &$data): void
{
if (empty($data['annotrefs'])) {
$data['annotrefs'] = [];
}
}
/**
* Sanitize or set the page rotation.
* The number of degrees by which the page shall be rotated clockwise when displayed or printed.
* The value shall be a multiple of 90.
*
* @param PageInputData $data Page data.
*/
public function sanitizeRotation(array &$data): void
{
$data['rotation'] = empty($data['rotation']) || ($data['rotation'] % 90) !== 0 ? 0 : (int) $data['rotation'];
}
/**
* Sanitize or set the page preferred zoom (magnification) factor.
*
* @param PageInputData $data Page data.
*/
public function sanitizeZoom(array &$data): void
{
$data['zoom'] = empty($data['zoom']) ? 1.0 : $data['zoom'];
}
/**
* Sanitize or set the page transitions.
*
* @param PageInputData $data Page data.
*
* @SuppressWarnings("PHPMD.CyclomaticComplexity")
* @SuppressWarnings("PHPMD.NPathComplexity")
*/
public function sanitizeTransitions(array &$data): void
{
if (empty($data['transition'])) {
return;
}
$transition = $data['transition'];
// display duration before advancing page
if (empty($transition['Dur'])) {
unset($transition['Dur']);
}
if (!empty($transition['Dur'])) {
$transition['Dur'] = \max(0, $transition['Dur']);
}
// transition style
$styles = [
'Split',
'Blinds',
'Box',
'Wipe',
'Dissolve',
'Glitter',
'R',
'Fly',
'Push',
'Cover',
'Uncover',
'Fade',
];
if (empty($transition['S']) || !\in_array($transition['S'], $styles, true)) {
$transition['S'] = 'R';
}
// duration of the transition effect, in seconds
$transition['D'] ??= 1;
// dimension in which the specified transition effect shall occur
if (
empty($transition['Dm'])
|| !\in_array($transition['S'] ?? '', ['Split', 'Blinds'], true)
|| !\in_array($transition['Dm'], ['H', 'V'], true)
) {
unset($transition['Dm']);
}
// direction of motion for the specified transition effect
if (
empty($transition['M'])
|| !\in_array($transition['S'] ?? '', ['Split', 'Box', 'Fly'], true)
|| !\in_array($transition['M'], ['I', 'O'], true)
) {
unset($transition['M']);
}
// direction in which the specified transition effect shall moves
if (
empty($transition['Di'])
|| !\in_array($transition['S'] ?? '', ['Wipe', 'Glitter', 'Fly', 'Cover', 'Uncover', 'Push'], true)
|| !\in_array($transition['Di'], ['None', 0, 90, 180, 270, 315], true)
|| \in_array($transition['Di'], [90, 180], true) && ($transition['S'] ?? '') !== 'Wipe'
|| $transition['Di'] === 315 && ($transition['S'] ?? '') !== 'Glitter'
|| $transition['Di'] === 'None' && ($transition['S'] ?? '') !== 'Fly'
) {
unset($transition['Di']);
}
// If true, the area that shall be flown in is rectangular and opaque
$transition['B'] = !empty($transition['B']);
$data['transition'] = $transition;
}
/**
* Sanitize or set the page margins.
*
* @param PageInputData $data Page data.
* @param-out PageInputData $data
*
* @SuppressWarnings("PHPMD.CyclomaticComplexity")
* @SuppressWarnings("PHPMD.NPathComplexity")
*
* @throws Exception
*/
public function sanitizeMargins(array &$data): void
{
$defmargin = $this->getDefaultMargins();
$marginData = is_array($data['margin'] ?? null) ? $data['margin'] : [];
$dataWidth = $data['width'] ?? 0.0;
$dataHeight = $data['height'] ?? 0.0;
$booklet = !empty($marginData['booklet']);
if (empty($data['margin'])) {
if (empty($data['width']) || empty($data['height'])) {
[$data['width'], $data['height'], $data['orientation']] = $this->getPageFormatSize('A4', 'P');
$data['width'] /= $this->kunit;
$data['height'] /= $this->kunit;
$dataWidth = $data['width'];
$dataHeight = $data['height'];
}
}
$margin = $this->normalizeMargins($marginData, $defmargin, $dataWidth, $dataHeight, $booklet);
$data['margin'] = ['booklet' => $booklet] + $margin;
$data['ContentWidth'] = $dataWidth - $margin['PL'] - $margin['PR'];
$data['ContentHeight'] = $dataHeight - $margin['CT'] - $margin['CB'];
$data['HeaderHeight'] = $margin['HB'] - $margin['PT'];
$data['FooterHeight'] = $margin['FT'] - $margin['PB'];
}
/**
* @return MarginData
*/
protected function getDefaultMargins(): array
{
return [
'CB' => 0.0,
'CT' => 0.0,
'FT' => 0.0,
'HB' => 0.0,
'PB' => 0.0,
'PL' => 0.0,
'PR' => 0.0,
'PT' => 0.0,
];
}
/**
* @param array<string, scalar|null> $marginData
* @param MarginData $defaultMargins
*
* @return MarginData
*/
protected function normalizeMargins(
array $marginData,
array $defaultMargins,
float $dataWidth,
float $dataHeight,
bool $booklet,
): array {
$hasCT = \array_key_exists('CT', $marginData);
$hasCB = \array_key_exists('CB', $marginData);
$margin = $this->getNormalizedMarginInput($marginData, $defaultMargins);
$margin = $this->applyMarginBounds($margin, $dataWidth, $dataHeight);
$margin = $this->applyBookletMarginSwap($margin, $booklet);
$margin = $this->applyImplicitCtCb($margin, $hasCT, $hasCB);
return $this->applyMarginConstraints($margin, $dataWidth, $dataHeight);
}
/**
* @param array<string, scalar|null> $marginData
* @param MarginData $defaultMargins
*
* @return MarginData
*/
protected function getNormalizedMarginInput(array $marginData, array $defaultMargins): array
{
$margin = $defaultMargins;
foreach ($defaultMargins as $key => $default) {
$marginValue = $marginData[$key] ?? null;
if (is_scalar($marginValue)) {
$margin[$key] = (float) $marginValue;
continue;
}
$margin[$key] = $default;
}
return $margin;
}
/**
* @param MarginData $margin
*
* @return MarginData
*/
protected function applyMarginBounds(array $margin, float $dataWidth, float $dataHeight): array
{
$marginBounds = [
'PL' => $dataWidth,
'PR' => $dataWidth,
'PT' => $dataHeight,
'HB' => $dataHeight,
'CT' => $dataHeight,
'CB' => $dataHeight,
'FT' => $dataHeight,
'PB' => $dataHeight,
];
foreach ($marginBounds as $type => $max) {
$margin[$type] = empty($margin[$type]) ? 0.0 : \min(\max(0.0, $margin[$type]), $max);
}
return $margin;
}
/**
* @param MarginData $margin
*
* @return MarginData
*/
protected function applyBookletMarginSwap(array $margin, bool $booklet): array
{
if ($booklet && ($this->pid % 2) === 0) {
// swap margins on odd pages
// NOTE: $this->pid is the previous page (0 indexed).
$tmp = $margin['PL'];
$margin['PL'] = $margin['PR'];
$margin['PR'] = $tmp;
}
return $margin;
}
/**
* @param MarginData $margin
*
* @return MarginData
*/
protected function applyImplicitCtCb(array $margin, bool $hasCT, bool $hasCB): array
{
if (!$hasCT) {
$margin['CT'] = \max($margin['PT'], $margin['HB']);
}
if (!$hasCB && ($margin['PB'] > 0.0 || $margin['FT'] > 0.0)) {
$margin['CB'] = \max($margin['PB'], $margin['FT']);
}
return $margin;
}
/**
* @param MarginData $margin
*
* @return MarginData
*/
protected function applyMarginConstraints(array $margin, float $dataWidth, float $dataHeight): array
{
$margin['PR'] = \min($margin['PR'], $dataWidth - $margin['PL']);
$margin['HB'] = \max($margin['HB'], $margin['PT']);
$margin['CT'] = \max($margin['CT'], $margin['HB']);
$margin['CB'] = \min($margin['CB'], $dataHeight - $margin['CT']);
$margin['FT'] = \min($margin['FT'], $margin['CB']);
$margin['PB'] = \min($margin['PB'], $margin['FT']);
return $margin;
}
/**
* Sanitize or set the page regions (columns).
*
* @param PageInputData $data Page data.
*/
public function sanitizeRegions(array &$data): void
{
$contentWidth = (float) ($data['ContentWidth'] ?? 0);
$contentHeight = (float) ($data['ContentHeight'] ?? 0);
$pageWidth = (float) ($data['width'] ?? 0);
$pageHeight = (float) ($data['height'] ?? 0);
$marginLeft = (float) ($data['margin']['PL'] ?? 0);
$marginTop = (float) ($data['margin']['CT'] ?? 0);
$marginRight = (float) ($data['margin']['PR'] ?? 0);
$marginBottom = (float) ($data['margin']['CB'] ?? 0);
if (!empty($data['columns'])) {
// set equal columns
$data['region'] = [];
$numColumns = \max(1, (int) $data['columns']);
$width = $contentWidth / $numColumns;
for ($idx = 0; $idx < $numColumns; ++$idx) {
$data['region'][] = [ // @phpstan-ignore parameterByRef.type
'RX' => $marginLeft + ($idx * $width),
'RY' => $marginTop,
'RW' => $width,
'RH' => $contentHeight,
];
}
}
if (empty($data['region'])) {
// default single region
$data['region'] = [[ // @phpstan-ignore parameterByRef.type
'RX' => $marginLeft,
'RY' => $marginTop,
'RW' => $contentWidth,
'RH' => $contentHeight,
]];
}
$regions = $data['region'] ?? [];
$columnCount = 0;
foreach ($regions as $key => $val) {
$regions[$key] = $this->normalizeRegionData(
$val,
$contentWidth,
$contentHeight,
$pageWidth,
$pageHeight,
$marginRight,
$marginBottom,
);
++$columnCount;
}
$data['region'] = $regions; // @phpstan-ignore parameterByRef.type
$data['columns'] = $columnCount; // @phpstan-ignore parameterByRef.type
if (!\array_key_exists('autobreak', $data)) {
$data['autobreak'] = true; // @phpstan-ignore parameterByRef.type
}
}
/**
* @param array<string, float|int> $region
*
* @return RegionData
*/
protected function normalizeRegionData(
array $region,
float $contentWidth,
float $contentHeight,
float $pageWidth,
float $pageHeight,
float $marginRight,
float $marginBottom,
): array {
$regionWidth = (float) ($region['RW'] ?? 0);
$regionHeight = (float) ($region['RH'] ?? 0);
$regionX = (float) ($region['RX'] ?? 0);
$regionY = (float) ($region['RY'] ?? 0);
$rw = \min(\max(0.0, $regionWidth), $contentWidth);
$rx = \min(\max(0.0, $regionX), $pageWidth - $marginRight - $regionWidth);
$rl = $regionX + $regionWidth;
$rr = $pageWidth - $regionX - $regionWidth;
$rh = \min(\max(0.0, $regionHeight), $contentHeight);
$ry = \min(\max(0.0, $regionY), $pageHeight - $marginBottom - $regionHeight);
$rt = $regionY + $regionHeight;
$rb = $pageHeight - $regionY - $regionHeight;
return [
'RW' => $rw,
'RX' => $rx,
'RL' => $rl,
'RR' => $rr,
'RH' => $rh,
'RY' => $ry,
'RT' => $rt,
'RB' => $rb,
'x' => $rx,
'y' => $ry,
];
}
/**
* Sanitize or set the page boxes containing the page boundaries.
*
* @param PageInputData $data Page data.
*
* @SuppressWarnings("PHPMD.CyclomaticComplexity")
* @SuppressWarnings("PHPMD.NPathComplexity")
*
* @throws Exception
*/
public function sanitizeBoxData(array &$data): void
{
/** @var array<string, PageBox> $box */
$box = $data['box'] ?? [];
if (empty($box)) {
if (empty($data['pwidth']) || empty($data['pheight'])) {
[$data['pwidth'], $data['pheight'], $data['orientation']] = $this->getPageFormatSize('A4', 'P');
}
$box = $this->setPageBoxes($data['pwidth'] ?? 0, $data['pheight'] ?? 0);
}
if (!empty($box)) {
if (\array_key_exists('format', $data) && $data['format'] !== '' && $data['format'] === 'MediaBox') {
$data['format'] = '';
$data['width'] = \abs(($box['MediaBox']['urx'] ?? 0) - ($box['MediaBox']['llx'] ?? 0)) / $this->kunit;
$data['height'] = \abs(($box['MediaBox']['ury'] ?? 0) - ($box['MediaBox']['lly'] ?? 0)) / $this->kunit;
$this->sanitizePageFormat($data);
}
if (empty($box['MediaBox'])) {
$box = $this->setBox($box, 'MediaBox', 0, 0, $data['pwidth'] ?? 0, $data['pheight'] ?? 0);
}
$box = $this->inheritMissingBox($box, 'CropBox', 'MediaBox');
$box = $this->inheritMissingBox($box, 'BleedBox', 'CropBox');
$box = $this->inheritMissingBox($box, 'TrimBox', 'CropBox');
$box = $this->inheritMissingBox($box, 'ArtBox', 'CropBox');
}
$data['box'] = $box;
$orientation = $this->getPageOrientation(
\abs(($box['MediaBox']['urx'] ?? 0) - ($box['MediaBox']['llx'] ?? 0)),
\abs(($box['MediaBox']['ury'] ?? 0) - ($box['MediaBox']['lly'] ?? 0)),
);
if (empty($data['orientation'])) {
$data['orientation'] = $orientation;
}
if (($data['orientation'] ?? '') !== $orientation) {
$data['box'] = $this->swapCoordinates($box);
}
}
/**
* @param array<string, PageBox> $box
*
* @return array<string, PageBox>
*
* @throws Exception
*/
protected function inheritMissingBox(array $box, string $targetBox, string $sourceBox): array
{
if (!empty($box[$targetBox])) {
return $box;
}
return $this->setBox(
$box,
$targetBox,
$box[$sourceBox]['llx'] ?? 0,
$box[$sourceBox]['lly'] ?? 0,
$box[$sourceBox]['urx'] ?? 0,
$box[$sourceBox]['ury'] ?? 0,
);
}
/**
* Sanitize or set the page format.
*
* @param PageInputData $data Page data.
*
* @throws Exception
*/
public function sanitizePageFormat(array &$data): void
{
$this->ensurePageOrientation($data);
if (!empty($data['format'])) {
$this->applyNamedPageFormat($data);
}
if (empty($data['format'])) {
$this->applyCustomPageFormat($data);
}
// convert values in points
$data['pwidth'] = ($data['width'] ?? 0.0) * $this->kunit;
$data['pheight'] = ($data['height'] ?? 0.0) * $this->kunit;
}
/**
* @param PageInputData $data
*/
protected function ensurePageOrientation(array &$data): void
{
if (empty($data['orientation'])) {
$data['orientation'] = '';
}
}
/**
* @param PageInputData $data
*
* @throws Exception
*/
protected function applyNamedPageFormat(array &$data): void
{
[$data['pwidth'], $data['pheight'], $data['orientation']] = $this->getPageFormatSize(
$data['format'] ?? '',
$data['orientation'] ?? '',
);
$data['width'] = $data['pwidth'] / $this->kunit;
$data['height'] = $data['pheight'] / $this->kunit;
}
/**
* @param PageInputData $data
*
* @throws Exception
*/
protected function applyCustomPageFormat(array &$data): void
{
$data['format'] = 'CUSTOM';
if (empty($data['width']) || empty($data['height'])) {
// default page format
$data['format'] = 'A4';
$data['orientation'] = 'P';
$this->sanitizePageFormat($data);
return;
}
[$data['width'], $data['height'], $data['orientation']] = $this->getPageOrientedSize(
$data['width'],
$data['height'],
$data['orientation'] ?? 'P',
);
}
}
@@ -0,0 +1,60 @@
<?php
declare(strict_types=1);
/**
* TransparencyGroupMode.php
*
* @since 2026-07-17
* @category Library
* @package PdfPage
* @author Nicola Asuni <info@tecnick.com>
* @copyright 2011-2026 Nicola Asuni - Tecnick.com LTD
* @license https://www.gnu.org/copyleft/lesser.html GNU-LGPL v3 (see LICENSE)
* @link https://github.com/tecnickcom/tc-lib-pdf-page
*
* This file is part of tc-lib-pdf-page software library.
*/
namespace Com\Tecnick\Pdf\Page;
/**
* Com\Tecnick\Pdf\Page\TransparencyGroupMode
*
* Backed enum for the per-page transparency /Group emission policy: 'auto'
* (only on pages flagged as using transparency), 'always' or 'never'.
*
* @since 2026-07-17
* @category Library
* @package PdfPage
* @author Nicola Asuni <info@tecnick.com>
* @copyright 2011-2026 Nicola Asuni - Tecnick.com LTD
* @license https://www.gnu.org/copyleft/lesser.html GNU-LGPL v3 (see LICENSE)
* @link https://github.com/tecnickcom/tc-lib-pdf-page
*/
enum TransparencyGroupMode: string
{
case Auto = 'auto';
case Always = 'always';
case Never = 'never';
/**
* Resolve a loose transparency group mode value to the matching enum case.
*
* Accepts the canonical value (case-insensitively) or an enum instance
* (returned unchanged). Unknown values fall back to Auto, matching the
* lenient behavior of Page::setPageTransparencyGroupMode().
*
* @param string|self $value Transparency group mode or enum case.
*/
public static function fromLoose(string|self $value): self
{
if ($value instanceof self) {
return $value;
}
return self::tryFrom(\strtolower($value)) ?? self::Auto;
}
}
+72
View File
@@ -0,0 +1,72 @@
<?php
declare(strict_types=1);
/**
* Unit.php
*
* @since 2026-07-17
* @category Library
* @package PdfPage
* @author Nicola Asuni <info@tecnick.com>
* @copyright 2011-2026 Nicola Asuni - Tecnick.com LTD
* @license https://www.gnu.org/copyleft/lesser.html GNU-LGPL v3 (see LICENSE)
* @link https://github.com/tecnickcom/tc-lib-pdf-page
*
* This file is part of tc-lib-pdf-page software library.
*/
namespace Com\Tecnick\Pdf\Page;
use Com\Tecnick\Pdf\Page\Exception as PageException;
/**
* Com\Tecnick\Pdf\Page\Unit
*
* Backed enum for the document unit of measure. The backing value of each case
* is the canonical unit name used as a key of Format::UNITRATIO.
*
* @since 2026-07-17
* @category Library
* @package PdfPage
* @author Nicola Asuni <info@tecnick.com>
* @copyright 2011-2026 Nicola Asuni - Tecnick.com LTD
* @license https://www.gnu.org/copyleft/lesser.html GNU-LGPL v3 (see LICENSE)
* @link https://github.com/tecnickcom/tc-lib-pdf-page
*/
enum Unit: string
{
case Point = 'pt';
case Millimeter = 'mm';
case Centimeter = 'cm';
case Inch = 'in';
/**
* Resolve a loose unit value to the matching enum case.
*
* Accepts the canonical value, its legacy aliases and the empty-string
* default, case-insensitively, or an enum instance (returned unchanged).
* Unknown values throw, matching Format::getUnitRatio().
*
* @param string|self $value Unit name or enum case.
*
* @throws PageException if the value does not match a known unit.
*/
public static function fromLoose(string|self $value): self
{
if ($value instanceof self) {
return $value;
}
return match (\strtolower($value)) {
'', 'pt', 'points', 'px' => self::Point,
'mm', 'millimeters' => self::Millimeter,
'cm', 'centimeters' => self::Centimeter,
'in', 'inches' => self::Inch,
default => throw new PageException('unknown unit: ' . $value),
};
}
}
+151
View File
@@ -0,0 +1,151 @@
<?php
/**
* BoxTest.php
*
* @since 2011-05-23
* @category Library
* @package PdfPage
* @author Nicola Asuni <info@tecnick.com>
* @copyright 2011-2026 Nicola Asuni - Tecnick.com LTD
* @license https://www.gnu.org/copyleft/lesser.html GNU-LGPL v3 (see LICENSE)
* @link https://github.com/tecnickcom/tc-lib-pdf-page
*
* This file is part of tc-lib-pdf-page software library.
*/
namespace Test;
/**
* Box Test
*
* @since 2011-05-23
* @category Library
* @package PdfPage
* @author Nicola Asuni <info@tecnick.com>
* @copyright 2011-2026 Nicola Asuni - Tecnick.com LTD
* @license https://www.gnu.org/copyleft/lesser.html GNU-LGPL v3 (see LICENSE)
* @link https://github.com/tecnickcom/tc-lib-pdf-page
*/
class BoxTest extends TestUtil
{
/**
* @throws \Com\Tecnick\Pdf\Page\Exception
*/
protected function getTestObject(): \Com\Tecnick\Pdf\Page\Page
{
$pdf = new \Com\Tecnick\Color\Pdf();
$encrypt = $this->getEncryptObject();
return new \Com\Tecnick\Pdf\Page\Page('mm', $pdf, $encrypt, false, false);
}
/**
* @throws \Com\Tecnick\Pdf\Page\Exception
*/
public function testSetBox(): void
{
$page = $this->getTestObject();
$dims = $page->setBox([], 'CropBox', 2, 4, 6, 8);
$this->bcAssertEqualsWithDelta([
'CropBox' => [
'llx' => 2,
'lly' => 4,
'urx' => 6,
'ury' => 8,
'bci' => [
'color' => '#000000',
'width' => 0.353,
'style' => 'S',
'dash' => [3],
],
],
], $dims);
$dims = $page->setBox([], 'TrimBox', 3, 5, 7, 11, [
'color' => 'aquamarine',
'width' => 2,
'style' => 'D',
'dash' => [2, 3, 5, 7],
]);
$this->bcAssertEqualsWithDelta([
'TrimBox' => [
'llx' => 3,
'lly' => 5,
'urx' => 7,
'ury' => 11,
'bci' => [
'color' => 'aquamarine',
'width' => 2,
'style' => 'D',
'dash' => [2, 3, 5, 7],
],
],
], $dims);
}
/**
* @throws \Com\Tecnick\Pdf\Page\Exception
*/
public function testSetBoxEx(): void
{
$this->bcExpectException(\Com\Tecnick\Pdf\Page\Exception::class);
$page = $this->getTestObject();
$page->setBox([], 'ERROR', 1, 2, 3, 4);
}
/**
* @throws \Com\Tecnick\Pdf\Page\Exception
*/
public function testSwapCoordinates(): void
{
$page = $this->getTestObject();
$dims = [
'CropBox' => [
'llx' => 2,
'lly' => 4,
'urx' => 6,
'ury' => 8,
],
];
$newpagedim = $page->swapCoordinates($dims);
$this->assertEquals(
[
'CropBox' => [
'llx' => 4,
'lly' => 2,
'urx' => 8,
'ury' => 6,
],
],
$newpagedim,
);
}
/**
* @throws \Com\Tecnick\Pdf\Page\Exception
*/
public function testSetPageBoxes(): void
{
$page = $this->getTestObject();
$dims = $page->setPageBoxes(100, 200);
$exp = [
'llx' => 0,
'lly' => 0,
'urx' => 100,
'ury' => 200,
'bci' => [
'color' => '#000000',
'width' => 0.353,
'style' => 'S',
'dash' => [3],
],
];
$this->bcAssertEqualsWithDelta([
'MediaBox' => $exp,
'CropBox' => $exp,
'BleedBox' => $exp,
'TrimBox' => $exp,
'ArtBox' => $exp,
], $dims);
}
}
+111
View File
@@ -0,0 +1,111 @@
<?php
/**
* FormatTest.php
*
* @since 2011-05-23
* @category Library
* @package PdfPage
* @author Nicola Asuni <info@tecnick.com>
* @copyright 2011-2026 Nicola Asuni - Tecnick.com LTD
* @license https://www.gnu.org/copyleft/lesser.html GNU-LGPL v3 (see LICENSE)
* @link https://github.com/tecnickcom/tc-lib-pdf-page
*
* This file is part of tc-lib-pdf-page software library.
*/
namespace Test;
/**
* Format Test
*
* @since 2011-05-23
* @category Library
* @package PdfPage
* @author Nicola Asuni <info@tecnick.com>
* @copyright 2011-2026 Nicola Asuni - Tecnick.com LTD
* @license https://www.gnu.org/copyleft/lesser.html GNU-LGPL v3 (see LICENSE)
* @link https://github.com/tecnickcom/tc-lib-pdf-page
*/
class FormatTest extends TestUtil
{
/**
* @throws \Com\Tecnick\Pdf\Page\Exception
*/
protected function getTestObject(): \Com\Tecnick\Pdf\Page\Page
{
$pdf = new \Com\Tecnick\Color\Pdf();
$encrypt = $this->getEncryptObject();
return new \Com\Tecnick\Pdf\Page\Page('mm', $pdf, $encrypt, false, false);
}
/**
* @throws \Com\Tecnick\Pdf\Page\Exception
*/
public function testGetPageSize(): void
{
$page = $this->getTestObject();
$dims = $page->getPageFormatSize('A0');
$this->assertEquals([2383.937, 3370.394, 'P'], $dims);
$dims = $page->getPageFormatSize('A4', '', 'in', 2);
$this->assertEquals([8.27, 11.69, 'P'], $dims);
$dims = $page->getPageFormatSize('LEGAL', '', 'mm', 0);
$this->assertEquals([216, 356, 'P'], $dims);
$dims = $page->getPageFormatSize('LEGAL', 'P', 'mm', 0);
$this->assertEquals([216, 356, 'P'], $dims);
$dims = $page->getPageFormatSize('LEGAL', 'L', 'mm', 0);
$this->assertEquals([356, 216, 'L'], $dims);
}
/**
* @throws \Com\Tecnick\Pdf\Page\Exception
*/
public function testGetPageSizeEx(): void
{
$this->bcExpectException(\Com\Tecnick\Pdf\Page\Exception::class);
$page = $this->getTestObject();
$page->getPageFormatSize('*ERROR*');
}
/**
* @throws \Com\Tecnick\Pdf\Page\Exception
*/
public function testGetPageOrientedSize(): void
{
$page = $this->getTestObject();
$dims = $page->getPageOrientedSize(10, 20);
$this->assertEquals([10, 20, 'P'], $dims);
$dims = $page->getPageOrientedSize(10, 20, 'P');
$this->assertEquals([10, 20, 'P'], $dims);
$dims = $page->getPageOrientedSize(10, 20, 'L');
$this->assertEquals([20, 10, 'L'], $dims);
$dims = $page->getPageOrientedSize(20, 10, 'P');
$this->assertEquals([10, 20, 'P'], $dims);
$dims = $page->getPageOrientedSize(20, 10, 'L');
$this->assertEquals([20, 10, 'L'], $dims);
$dims = $page->getPageOrientedSize(20, 10);
$this->assertEquals([20, 10, 'L'], $dims);
}
/**
* @throws \Com\Tecnick\Pdf\Page\Exception
*/
public function testGetPageOrientation(): void
{
$page = $this->getTestObject();
$orient = $page->getPageOrientation(10, 20);
$this->assertEquals('P', $orient);
$orient = $page->getPageOrientation(20, 10);
$this->assertEquals('L', $orient);
}
}
+63
View File
@@ -0,0 +1,63 @@
<?php
/**
* ModeTest.php
*
* @since 2011-05-23
* @category Library
* @package PdfPage
* @author Nicola Asuni <info@tecnick.com>
* @copyright 2011-2026 Nicola Asuni - Tecnick.com LTD
* @license https://www.gnu.org/copyleft/lesser.html GNU-LGPL v3 (see LICENSE)
* @link https://github.com/tecnickcom/tc-lib-pdf-page
*
* This file is part of tc-lib-pdf-page software library.
*/
namespace Test;
/**
* Mode Test
*
* @since 2011-05-23
* @category Library
* @package PdfPage
* @author Nicola Asuni <info@tecnick.com>
* @copyright 2011-2026 Nicola Asuni - Tecnick.com LTD
* @license https://www.gnu.org/copyleft/lesser.html GNU-LGPL v3 (see LICENSE)
* @link https://github.com/tecnickcom/tc-lib-pdf-page
*/
class ModeTest extends TestUtil
{
/**
* @throws \Com\Tecnick\Pdf\Page\Exception
*/
protected function getTestObject(): \Com\Tecnick\Pdf\Page\Page
{
$pdf = new \Com\Tecnick\Color\Pdf();
$encrypt = $this->getEncryptObject();
return new \Com\Tecnick\Pdf\Page\Page('mm', $pdf, $encrypt, false, false);
}
/**
* @throws \Com\Tecnick\Pdf\Page\Exception
*/
public function testGetLayout(): void
{
$page = $this->getTestObject();
$this->assertEquals('TwoColumnLeft', $page->getLayout('two'));
$this->assertEquals('SinglePage', $page->getLayout(''));
$this->assertEquals('SinglePage', $page->getLayout());
}
/**
* @throws \Com\Tecnick\Pdf\Page\Exception
*/
public function testGetDisplay(): void
{
$page = $this->getTestObject();
$this->assertEquals('UseThumbs', $page->getDisplay('usethumbs'));
$this->assertEquals('UseAttachments', $page->getDisplay(''));
$this->assertEquals('UseNone', $page->getDisplay('something'));
}
}
@@ -0,0 +1,95 @@
<?php
/**
* OrientationTest.php
*
* @since 2026-07-17
* @category Library
* @package PdfPage
* @author Nicola Asuni <info@tecnick.com>
* @copyright 2011-2026 Nicola Asuni - Tecnick.com LTD
* @license https://www.gnu.org/copyleft/lesser.html GNU-LGPL v3 (see LICENSE)
* @link https://github.com/tecnickcom/tc-lib-pdf-page
*
* This file is part of tc-lib-pdf-page software library.
*/
namespace Test;
use Com\Tecnick\Pdf\Page\Orientation;
/**
* Orientation enum test
*
* @since 2026-07-17
* @category Library
* @package PdfPage
* @author Nicola Asuni <info@tecnick.com>
* @copyright 2011-2026 Nicola Asuni - Tecnick.com LTD
* @license https://www.gnu.org/copyleft/lesser.html GNU-LGPL v3 (see LICENSE)
* @link https://github.com/tecnickcom/tc-lib-pdf-page
*/
class OrientationTest extends TestUtil
{
/**
* @throws \Com\Tecnick\Pdf\Page\Exception
*/
protected function getTestObject(): \Com\Tecnick\Pdf\Page\Page
{
$pdf = new \Com\Tecnick\Color\Pdf();
$encrypt = $this->getEncryptObject();
return new \Com\Tecnick\Pdf\Page\Page('mm', $pdf, $encrypt, false, false);
}
public function testCaseBackingValues(): void
{
$this->assertSame('P', Orientation::Portrait->value);
$this->assertSame('L', Orientation::Landscape->value);
$this->assertSame('', Orientation::Auto->value);
}
public function testFromLooseCanonical(): void
{
$this->assertSame(Orientation::Portrait, Orientation::fromLoose('P'));
$this->assertSame(Orientation::Landscape, Orientation::fromLoose('L'));
$this->assertSame(Orientation::Auto, Orientation::fromLoose(''));
}
public function testFromLooseFallsBackToAuto(): void
{
// Matching legacy behavior: only exact 'P'/'L' select an orientation.
$this->assertSame(Orientation::Auto, Orientation::fromLoose('p'));
$this->assertSame(Orientation::Auto, Orientation::fromLoose('portrait'));
$this->assertSame(Orientation::Auto, Orientation::fromLoose('X'));
}
public function testFromLoosePassesThroughEnumInstance(): void
{
$this->assertSame(Orientation::Landscape, Orientation::fromLoose(Orientation::Landscape));
}
public function testFromLooseRoundTrip(): void
{
foreach (Orientation::cases() as $case) {
$this->assertSame($case, Orientation::fromLoose($case->value));
}
}
/**
* The widened getPageOrientedSize() accepts an Orientation enum.
*
* @throws \Com\Tecnick\Pdf\Page\Exception
*/
public function testGetPageOrientedSizeAcceptsEnum(): void
{
$page = $this->getTestObject();
$this->assertSame(
$page->getPageOrientedSize(100, 200, 'L'),
$page->getPageOrientedSize(100, 200, Orientation::Landscape),
);
$this->assertSame(
$page->getPageOrientedSize(100, 200, ''),
$page->getPageOrientedSize(100, 200, Orientation::Auto),
);
}
}
@@ -0,0 +1,114 @@
<?php
/**
* PageBoxTypeTest.php
*
* @since 2026-07-17
* @category Library
* @package PdfPage
* @author Nicola Asuni <info@tecnick.com>
* @copyright 2011-2026 Nicola Asuni - Tecnick.com LTD
* @license https://www.gnu.org/copyleft/lesser.html GNU-LGPL v3 (see LICENSE)
* @link https://github.com/tecnickcom/tc-lib-pdf-page
*
* This file is part of tc-lib-pdf-page software library.
*/
namespace Test;
use Com\Tecnick\Pdf\Page\PageBoxType;
/**
* PageBoxType enum test
*
* @since 2026-07-17
* @category Library
* @package PdfPage
* @author Nicola Asuni <info@tecnick.com>
* @copyright 2011-2026 Nicola Asuni - Tecnick.com LTD
* @license https://www.gnu.org/copyleft/lesser.html GNU-LGPL v3 (see LICENSE)
* @link https://github.com/tecnickcom/tc-lib-pdf-page
*/
class PageBoxTypeTest extends TestUtil
{
/**
* @throws \Com\Tecnick\Pdf\Page\Exception
*/
protected function getTestObject(): \Com\Tecnick\Pdf\Page\Page
{
$pdf = new \Com\Tecnick\Color\Pdf();
$encrypt = $this->getEncryptObject();
return new \Com\Tecnick\Pdf\Page\Page('mm', $pdf, $encrypt, false, false);
}
public function testCaseBackingValues(): void
{
$this->assertSame('MediaBox', PageBoxType::MediaBox->value);
$this->assertSame('CropBox', PageBoxType::CropBox->value);
$this->assertSame('BleedBox', PageBoxType::BleedBox->value);
$this->assertSame('TrimBox', PageBoxType::TrimBox->value);
$this->assertSame('ArtBox', PageBoxType::ArtBox->value);
}
/**
* @throws \Com\Tecnick\Pdf\Page\Exception
*/
public function testFromLooseCanonical(): void
{
$this->assertSame(PageBoxType::MediaBox, PageBoxType::fromLoose('MediaBox'));
$this->assertSame(PageBoxType::ArtBox, PageBoxType::fromLoose('ArtBox'));
}
/**
* @throws \Com\Tecnick\Pdf\Page\Exception
*/
public function testFromLoosePassesThroughEnumInstance(): void
{
$this->assertSame(PageBoxType::TrimBox, PageBoxType::fromLoose(PageBoxType::TrimBox));
}
/**
* @throws \Com\Tecnick\Pdf\Page\Exception
*/
public function testFromLooseRoundTrip(): void
{
foreach (PageBoxType::cases() as $case) {
$this->assertSame($case, PageBoxType::fromLoose($case->value));
}
}
/**
* Box names are case sensitive, so a wrong-case value is unknown.
*
* @throws \Com\Tecnick\Pdf\Page\Exception
*/
public function testFromLooseIsCaseSensitive(): void
{
$this->bcExpectException(\Com\Tecnick\Pdf\Page\Exception::class);
PageBoxType::fromLoose('mediabox');
}
/**
* @throws \Com\Tecnick\Pdf\Page\Exception
*/
public function testFromLooseUnknownThrows(): void
{
$this->bcExpectException(\Com\Tecnick\Pdf\Page\Exception::class);
PageBoxType::fromLoose('WobbleBox');
}
/**
* The widened setBox() accepts a PageBoxType enum and keys the dimensions
* array on the same string as the legacy call.
*
* @throws \Com\Tecnick\Pdf\Page\Exception
*/
public function testSetBoxAcceptsEnum(): void
{
$page = $this->getTestObject();
$fromEnum = $page->setBox([], PageBoxType::CropBox, 0.0, 0.0, 100.0, 200.0);
$fromString = $page->setBox([], 'CropBox', 0.0, 0.0, 100.0, 200.0);
$this->assertArrayHasKey('CropBox', $fromEnum);
$this->assertSame($fromString, $fromEnum);
}
}
@@ -0,0 +1,95 @@
<?php
/**
* PageDisplayModeTest.php
*
* @since 2026-07-17
* @category Library
* @package PdfPage
* @author Nicola Asuni <info@tecnick.com>
* @copyright 2011-2026 Nicola Asuni - Tecnick.com LTD
* @license https://www.gnu.org/copyleft/lesser.html GNU-LGPL v3 (see LICENSE)
* @link https://github.com/tecnickcom/tc-lib-pdf-page
*
* This file is part of tc-lib-pdf-page software library.
*/
namespace Test;
use Com\Tecnick\Pdf\Page\PageDisplayMode;
/**
* PageDisplayMode enum test
*
* @since 2026-07-17
* @category Library
* @package PdfPage
* @author Nicola Asuni <info@tecnick.com>
* @copyright 2011-2026 Nicola Asuni - Tecnick.com LTD
* @license https://www.gnu.org/copyleft/lesser.html GNU-LGPL v3 (see LICENSE)
* @link https://github.com/tecnickcom/tc-lib-pdf-page
*/
class PageDisplayModeTest extends TestUtil
{
/**
* @throws \Com\Tecnick\Pdf\Page\Exception
*/
protected function getTestObject(): \Com\Tecnick\Pdf\Page\Page
{
$pdf = new \Com\Tecnick\Color\Pdf();
$encrypt = $this->getEncryptObject();
return new \Com\Tecnick\Pdf\Page\Page('mm', $pdf, $encrypt, false, false);
}
public function testCaseBackingValues(): void
{
$this->assertSame('UseNone', PageDisplayMode::UseNone->value);
$this->assertSame('UseOutlines', PageDisplayMode::UseOutlines->value);
$this->assertSame('UseThumbs', PageDisplayMode::UseThumbs->value);
$this->assertSame('FullScreen', PageDisplayMode::FullScreen->value);
$this->assertSame('UseOC', PageDisplayMode::UseOC->value);
$this->assertSame('UseAttachments', PageDisplayMode::UseAttachments->value);
}
public function testFromLooseCanonical(): void
{
$this->assertSame(PageDisplayMode::UseThumbs, PageDisplayMode::fromLoose('usethumbs'));
$this->assertSame(PageDisplayMode::FullScreen, PageDisplayMode::fromLoose('FullScreen'));
$this->assertSame(PageDisplayMode::UseOC, PageDisplayMode::fromLoose('USEOC'));
}
public function testFromLooseEmptyMapsToUseAttachments(): void
{
// Preserves the legacy Mode::DISPLAY quirk: '' maps to UseAttachments.
$this->assertSame(PageDisplayMode::UseAttachments, PageDisplayMode::fromLoose(''));
}
public function testFromLooseUnknownFallsBackToUseNone(): void
{
$this->assertSame(PageDisplayMode::UseNone, PageDisplayMode::fromLoose('nonsense'));
}
public function testFromLoosePassesThroughEnumInstance(): void
{
$this->assertSame(PageDisplayMode::UseOutlines, PageDisplayMode::fromLoose(PageDisplayMode::UseOutlines));
}
public function testFromLooseRoundTrip(): void
{
foreach (PageDisplayMode::cases() as $case) {
$this->assertSame($case, PageDisplayMode::fromLoose($case->value));
}
}
/**
* The widened getDisplay() accepts a PageDisplayMode enum.
*
* @throws \Com\Tecnick\Pdf\Page\Exception
*/
public function testGetDisplayAcceptsEnum(): void
{
$page = $this->getTestObject();
$this->assertSame('UseThumbs', $page->getDisplay(PageDisplayMode::UseThumbs));
$this->assertSame($page->getDisplay('usethumbs'), $page->getDisplay(PageDisplayMode::UseThumbs));
}
}
@@ -0,0 +1,95 @@
<?php
/**
* PageLayoutTest.php
*
* @since 2026-07-17
* @category Library
* @package PdfPage
* @author Nicola Asuni <info@tecnick.com>
* @copyright 2011-2026 Nicola Asuni - Tecnick.com LTD
* @license https://www.gnu.org/copyleft/lesser.html GNU-LGPL v3 (see LICENSE)
* @link https://github.com/tecnickcom/tc-lib-pdf-page
*
* This file is part of tc-lib-pdf-page software library.
*/
namespace Test;
use Com\Tecnick\Pdf\Page\PageLayout;
/**
* PageLayout enum test
*
* @since 2026-07-17
* @category Library
* @package PdfPage
* @author Nicola Asuni <info@tecnick.com>
* @copyright 2011-2026 Nicola Asuni - Tecnick.com LTD
* @license https://www.gnu.org/copyleft/lesser.html GNU-LGPL v3 (see LICENSE)
* @link https://github.com/tecnickcom/tc-lib-pdf-page
*/
class PageLayoutTest extends TestUtil
{
/**
* @throws \Com\Tecnick\Pdf\Page\Exception
*/
protected function getTestObject(): \Com\Tecnick\Pdf\Page\Page
{
$pdf = new \Com\Tecnick\Color\Pdf();
$encrypt = $this->getEncryptObject();
return new \Com\Tecnick\Pdf\Page\Page('mm', $pdf, $encrypt, false, false);
}
public function testCaseBackingValues(): void
{
$this->assertSame('SinglePage', PageLayout::SinglePage->value);
$this->assertSame('OneColumn', PageLayout::OneColumn->value);
$this->assertSame('TwoColumnLeft', PageLayout::TwoColumnLeft->value);
$this->assertSame('TwoColumnRight', PageLayout::TwoColumnRight->value);
$this->assertSame('TwoPageLeft', PageLayout::TwoPageLeft->value);
$this->assertSame('TwoPageRight', PageLayout::TwoPageRight->value);
}
public function testFromLooseCanonicalAndAliases(): void
{
$this->assertSame(PageLayout::SinglePage, PageLayout::fromLoose('SinglePage'));
$this->assertSame(PageLayout::SinglePage, PageLayout::fromLoose('single'));
$this->assertSame(PageLayout::SinglePage, PageLayout::fromLoose('default'));
$this->assertSame(PageLayout::OneColumn, PageLayout::fromLoose('onecolumn'));
$this->assertSame(PageLayout::OneColumn, PageLayout::fromLoose('continuous'));
$this->assertSame(PageLayout::TwoColumnLeft, PageLayout::fromLoose('two'));
$this->assertSame(PageLayout::TwoColumnRight, PageLayout::fromLoose('TWOCOLUMNRIGHT'));
}
public function testFromLooseFallsBackToSinglePage(): void
{
$this->assertSame(PageLayout::SinglePage, PageLayout::fromLoose(''));
$this->assertSame(PageLayout::SinglePage, PageLayout::fromLoose('nonsense'));
}
public function testFromLoosePassesThroughEnumInstance(): void
{
$this->assertSame(PageLayout::TwoPageLeft, PageLayout::fromLoose(PageLayout::TwoPageLeft));
}
public function testFromLooseRoundTrip(): void
{
foreach (PageLayout::cases() as $case) {
$this->assertSame($case, PageLayout::fromLoose($case->value));
}
}
/**
* The widened getLayout() accepts a PageLayout enum, staying consistent with
* the legacy alias resolution.
*
* @throws \Com\Tecnick\Pdf\Page\Exception
*/
public function testGetLayoutAcceptsEnum(): void
{
$page = $this->getTestObject();
$this->assertSame('TwoColumnLeft', $page->getLayout(PageLayout::TwoColumnLeft));
$this->assertSame($page->getLayout('two'), $page->getLayout(PageLayout::TwoColumnLeft));
}
}
+827
View File
@@ -0,0 +1,827 @@
<?php
/**
* PageTest.php
*
* @since 2011-05-23
* @category Library
* @package PdfPage
* @author Nicola Asuni <info@tecnick.com>
* @copyright 2011-2026 Nicola Asuni - Tecnick.com LTD
* @license https://www.gnu.org/copyleft/lesser.html GNU-LGPL v3 (see LICENSE)
* @link https://github.com/tecnickcom/tc-lib-pdf-page
*
* This file is part of tc-lib-pdf-page software library.
*/
namespace Test;
/**
* Page Test
*
* @since 2011-05-23
* @category Library
* @package PdfPage
* @author Nicola Asuni <info@tecnick.com>
* @copyright 2011-2026 Nicola Asuni - Tecnick.com LTD
* @license https://www.gnu.org/copyleft/lesser.html GNU-LGPL v3 (see LICENSE)
* @link https://github.com/tecnickcom/tc-lib-pdf-page
*/
class PageTest extends TestUtil
{
/**
* PDF marker for the per-page transparency group.
*/
private const TRANSPARENCY_GROUP = '/Group << /Type /Group /S /Transparency /CS /DeviceRGB >>';
/**
* @throws \Com\Tecnick\Pdf\Page\Exception
*/
protected function getTestObject(): \Com\Tecnick\Pdf\Page\Page
{
$pdf = new \Com\Tecnick\Color\Pdf();
$encrypt = $this->getEncryptObject();
return new \Com\Tecnick\Pdf\Page\Page('mm', $pdf, $encrypt, false, true, false);
}
/**
* @throws \Com\Tecnick\Pdf\Page\Exception
*/
protected function getPdfaTestObject(): \Com\Tecnick\Pdf\Page\Page
{
$pdf = new \Com\Tecnick\Color\Pdf();
$encrypt = $this->getEncryptObject();
return new \Com\Tecnick\Pdf\Page\Page('mm', $pdf, $encrypt, true, true, false);
}
/**
* @throws \Com\Tecnick\Pdf\Page\Exception
*/
public function testGetKUnit(): void
{
$page = $this->getTestObject();
$this->bcAssertEqualsWithDelta(2.83464566929134, $page->getKUnit(), 0.001);
}
/**
* @throws \Com\Tecnick\Pdf\Page\Exception
*/
public function testEnableSignatureApproval(): void
{
$page = $this->getTestObject();
$res = $page->enableSignatureApproval(true);
$this->assertNotNull($res); // @phpstan-ignore method.alreadyNarrowedType
}
/**
* @throws \Com\Tecnick\Pdf\Page\Exception
*/
public function testAdd(): void
{
$page = $this->getTestObject();
// 1
$res = $page->add();
$box = [
'llx' => 0,
'lly' => 0,
'urx' => 595.2765,
'ury' => 841.890,
'bci' => [
'color' => '#000000',
'width' => 0.353,
'style' => 'S',
'dash' => [
0 => 3,
],
],
];
$exp = [
'group' => 0,
'rotation' => 0,
'zoom' => 1,
'orientation' => 'P',
'format' => 'A4',
'pheight' => 841.890,
'pwidth' => 595.2765,
'width' => 210,
'height' => 297,
'box' => [
'MediaBox' => $box,
'CropBox' => $box,
'BleedBox' => $box,
'TrimBox' => $box,
'ArtBox' => $box,
],
'margin' => [
'booklet' => false,
'PL' => 0,
'PR' => 0,
'PT' => 0,
'HB' => 0,
'CT' => 0,
'CB' => 0,
'FT' => 0,
'PB' => 0,
],
'ContentWidth' => 210,
'ContentHeight' => 297,
'HeaderHeight' => 0,
'FooterHeight' => 0,
'region' => [[
'RX' => 0,
'RY' => 0,
'RW' => 210,
'RH' => 297,
'RL' => 210,
'RR' => 0.0,
'RT' => 297,
'RB' => 0.0,
'x' => 0.0,
'y' => 0.0,
]],
'currentRegion' => 0,
'columns' => 1,
'content' => [
0 => '',
],
'annotrefs' => [],
'content_mark' => [
0 => 0,
],
'autobreak' => true,
];
unset($res['time']);
$exp['pid'] = 0;
$this->bcAssertEqualsWithDelta($exp, $res);
// 2
$res = $page->add();
unset($res['time']);
$exp['pid'] = 1;
$this->bcAssertEqualsWithDelta($exp, $res);
// 3
$res = $page->add([
'group' => 1,
]);
unset($res['time']);
$exp['pid'] = 2;
$exp['group'] = 1;
$this->bcAssertEqualsWithDelta($exp, $res);
// 3
$res = $page->add([
'columns' => 2,
]);
unset($res['time']);
$exp['pid'] = 3;
$exp['group'] = 0;
$exp['columns'] = 2;
$exp['region'] = [
0 => [
'RX' => 0,
'RY' => 0,
'RW' => 105,
'RH' => 297,
'RL' => 105,
'RR' => 105,
'RT' => 297,
'RB' => 0,
'x' => 0,
'y' => 0,
],
1 => [
'RX' => 105,
'RY' => 0,
'RW' => 105,
'RH' => 297,
'RL' => 210,
'RR' => 0.0,
'RT' => 297,
'RB' => 0,
'x' => 105,
'y' => 0,
],
];
$this->bcAssertEqualsWithDelta($exp, $res);
$pid = $page->getPageID();
$this->assertEquals(3, $pid);
}
/**
* @throws \Com\Tecnick\Pdf\Page\Exception
*/
public function testGetNextPage(): void
{
$page = $this->getTestObject();
$page->add();
$page->add();
$page->add();
$page->add();
$page->setCurrentPage(2);
$page->getNextPage();
$page->enableAutoPageBreak(false);
$page->getNextPage();
$page->enableAutoPageBreak(true);
$page->getNextPage();
$page->getNextPage();
$this->assertCount(6, $page->getPages());
}
/**
* @throws \Com\Tecnick\Pdf\Page\Exception
*/
public function testDelete(): void
{
$page = $this->getTestObject();
$page->add();
$page->add();
$page->add();
$this->assertCount(3, $page->getPages());
$res = $page->delete(1);
$this->assertCount(2, $page->getPages());
$this->assertArrayHasKey('time', $res);
}
/**
* @throws \Com\Tecnick\Pdf\Page\Exception
*/
public function testDeleteEx(): void
{
$this->bcExpectException(\Com\Tecnick\Pdf\Page\Exception::class);
$page = $this->getTestObject();
$page->delete(2);
}
/**
* @throws \Com\Tecnick\Pdf\Page\Exception
*/
public function testPop(): void
{
$page = $this->getTestObject();
$page->add();
$page->add();
$page->add();
$this->assertCount(3, $page->getPages());
$res = $page->pop();
$this->assertCount(2, $page->getPages());
$this->assertArrayHasKey('time', $res);
}
/**
* @throws \Com\Tecnick\Pdf\Page\Exception
*/
public function testMove(): void
{
$page = $this->getTestObject();
$page->add();
$page->add([
'group' => 1,
]);
$page->add([
'group' => 2,
]);
$page->add([
'group' => 3,
]);
$this->assertEquals($page->getPage(3), $page->getPage());
$page->move(3, 0);
$this->assertCount(4, $page->getPages());
$res = $page->getPage(0);
$this->assertEquals(3, $res['group']);
}
/**
* @throws \Com\Tecnick\Pdf\Page\Exception
*/
public function testMoveEx(): void
{
$this->bcExpectException(\Com\Tecnick\Pdf\Page\Exception::class);
$page = $this->getTestObject();
$page->move(1, 2);
}
/**
* @throws \Com\Tecnick\Pdf\Page\Exception
*/
public function testGetPageEx(): void
{
$this->bcExpectException(\Com\Tecnick\Pdf\Page\Exception::class);
$page = $this->getTestObject();
$page->getPage(2);
}
/**
* @throws \Com\Tecnick\Pdf\Page\Exception
*/
public function testContent(): void
{
$testObj = $this->getTestObject();
$testObj->add();
$testObj->addContent('Lorem');
$testObj->addContent('ipsum');
$testObj->addContentMark();
$testObj->addContent('dolor');
$testObj->addContent('sit');
$testObj->addContent('amet');
$this->assertEquals('amet', $testObj->popContent());
$page = $testObj->getPage();
$this->assertEquals([0, 3], $page['content_mark']);
$this->assertEquals(['', 'Lorem', 'ipsum', 'dolor', 'sit'], $page['content']);
$testObj->popContentToLastMark();
$page = $testObj->getPage();
$this->assertEquals([0], $page['content_mark']);
$this->assertEquals(['', 'Lorem', 'ipsum'], $page['content']);
}
/**
* @throws \Com\Tecnick\Pdf\Page\Exception
* @throws \Com\Tecnick\Pdf\Encrypt\Exception
*/
public function testGetPdfPages(): void
{
$page = $this->getTestObject();
$page->add();
$page->addContent('TEST1');
$page->add();
$page->addContent('TEST2');
$page->add([
'group' => 1,
'transition' => [
'Dur' => 2,
'D' => 3,
'Dm' => 'V',
'S' => 'Glitter',
'M' => 'O',
'Di' => 315,
'SS' => 1.3,
'B' => true,
],
'annotrefs' => [10, 20],
]);
$page->addContent('TEST2');
$pon = 0;
$out = $page->getPdfPages($pon);
$this->assertEquals(1, $page->getResourceDictObjID());
$this->assertEquals(2, $page->getRootObjID());
$this->assertStringContainsString('<< /Type /Pages /Kids [ 3 0 R 4 0 R 5 0 R ] /Count 3 >>', $out);
}
/**
* @throws \Com\Tecnick\Pdf\Page\Exception
*/
public function testaddAnnotRef(): void
{
$testObj = $this->getTestObject();
$testObj->add();
$testObj->addAnnotRef(13);
$testObj->addAnnotRef(17);
$page = $testObj->getPage();
$this->assertEquals(13, $page['annotrefs'][0] ?? null);
$this->assertEquals(17, $page['annotrefs'][1] ?? null);
}
/**
* @throws \Com\Tecnick\Pdf\Page\Exception
*/
public function testSetPagePHeight(): void
{
$testObj = $this->getTestObject();
$testObj->add();
$page = $testObj->getPage();
$this->assertEquals(841, (int) $page['pheight']);
$testObj->setPagePHeight(123.4);
$page = $testObj->getPage();
$this->assertEquals(123.4, $page['pheight']);
}
/**
* @throws \Com\Tecnick\Pdf\Page\Exception
*/
public function testSetPagePWidth(): void
{
$testObj = $this->getTestObject();
$testObj->add();
$page = $testObj->getPage();
$this->assertEquals(595, (int) $page['pwidth']);
$testObj->setPagePWidth(123.4);
$page = $testObj->getPage();
$this->assertEquals(123.4, $page['pwidth']);
}
/**
* @throws \Com\Tecnick\Pdf\Page\Exception
*/
public function testAddAnnotRefDuplicate(): void
{
$testObj = $this->getTestObject();
$testObj->add();
$testObj->addAnnotRef(42);
$testObj->addAnnotRef(42);
$page = $testObj->getPage();
$this->assertCount(1, $page['annotrefs']);
$this->assertEquals(42, $page['annotrefs'][0] ?? null);
}
/**
* @throws \Com\Tecnick\Pdf\Page\Exception
*/
public function testPopContentEmptyEx(): void
{
$this->bcExpectException(\Com\Tecnick\Pdf\Page\Exception::class);
$testObj = $this->getTestObject();
$testObj->add();
$testObj->popContent();
$testObj->popContent();
}
/**
* @throws \Com\Tecnick\Pdf\Page\Exception
*/
public function testPopContentToLastMarkEmpty(): void
{
$testObj = $this->getTestObject();
$testObj->add();
$testObj->popContent();
$testObj->popContentToLastMark();
$page = $testObj->getPage();
$this->assertEmpty($page['content']);
}
/**
* @throws \Com\Tecnick\Pdf\Page\Exception
*/
public function testSetPageTransparencyReturnsStatic(): void
{
$page = $this->getTestObject();
$page->add();
$this->assertSame($page, $page->setPageTransparency(true, 0));
$this->assertSame($page, $page->setPageTransparency(false, 0));
// -1 targets the current page, mirroring the rest of the page API.
$this->assertSame($page, $page->setPageTransparency(false, -1));
}
/**
* setPageTransparency() validates the page index like every other
* page-targeting method.
*
* @throws \Com\Tecnick\Pdf\Page\Exception
*/
public function testSetPageTransparencyInvalidPageThrows(): void
{
$this->bcExpectException(\Com\Tecnick\Pdf\Page\Exception::class);
$page = $this->getTestObject();
$page->add();
$page->setPageTransparency(false, 99);
}
/**
* The transparency mode is matched case-insensitively.
*
* @throws \Com\Tecnick\Pdf\Page\Exception
* @throws \Com\Tecnick\Pdf\Encrypt\Exception
*/
public function testSetPageTransparencyGroupModeIsCaseInsensitive(): void
{
$page = $this->getTestObject();
$page->add();
$page->add();
$page->setPageTransparency(true, 0);
$page->setPageTransparencyGroupMode('NEVER');
$pon = 0;
$out = $page->getPdfPages($pon);
$this->assertStringNotContainsString(self::TRANSPARENCY_GROUP, $out);
}
/**
* Per-page transparency flags stay aligned with the page they were set on
* after a page is deleted and the stack is reindexed.
*
* @throws \Com\Tecnick\Pdf\Page\Exception
* @throws \Com\Tecnick\Pdf\Encrypt\Exception
*/
public function testSetPageTransparencyFollowsPageAfterDelete(): void
{
$page = $this->getTestObject();
$page->add(); // 0
$page->add(); // 1
$page->add(); // 2
// Flag the last page opaque, then remove the first page so it becomes index 1.
$page->setPageTransparency(false, 2);
$page->delete(0);
$pon = 0;
$out = $page->getPdfPages($pon);
// Two pages remain; the opaque flag must still suppress exactly one group.
$this->assertEquals(1, substr_count($out, self::TRANSPARENCY_GROUP));
}
/**
* Deleting a page keeps the current-page pointer valid.
*
* @throws \Com\Tecnick\Pdf\Page\Exception
*/
public function testDeleteKeepsCurrentPageValid(): void
{
$page = $this->getTestObject();
$page->add(); // 0
$page->add(); // 1
$page->add(); // 2 (current)
$page->delete(0);
// The current-page pointer must stay within the reindexed stack so that
// getPage() resolves instead of throwing "page ... do not exist".
$this->assertGreaterThanOrEqual(0, $page->getPageID());
$this->assertLessThanOrEqual(1, $page->getPageID());
$current = $page->getPage();
$this->assertArrayHasKey('time', $current);
}
/**
* @throws \Com\Tecnick\Pdf\Page\Exception
*/
public function testSetPageTransparencyGroupModeReturnsStatic(): void
{
$page = $this->getTestObject();
$this->assertSame($page, $page->setPageTransparencyGroupMode('auto'));
}
/**
* By default (auto mode) pages that are never flagged keep emitting the
* transparency group, preserving backward-compatible output.
*
* @throws \Com\Tecnick\Pdf\Page\Exception
* @throws \Com\Tecnick\Pdf\Encrypt\Exception
*/
public function testGetPdfPagesTransparencyAutoDefault(): void
{
$page = $this->getTestObject();
$page->add();
$page->add();
$pon = 0;
$out = $page->getPdfPages($pon);
$this->assertEquals(2, substr_count($out, self::TRANSPARENCY_GROUP));
}
/**
* In auto mode, a page flagged as not using transparency omits the group,
* while unflagged pages keep emitting it.
*
* @throws \Com\Tecnick\Pdf\Page\Exception
* @throws \Com\Tecnick\Pdf\Encrypt\Exception
*/
public function testGetPdfPagesTransparencyAutoFlaggedFalse(): void
{
$page = $this->getTestObject();
$page->add();
$page->add();
$page->setPageTransparency(false, 0);
$pon = 0;
$out = $page->getPdfPages($pon);
// page 0 omits the group, page 1 (unflagged) keeps it.
$this->assertEquals(1, substr_count($out, self::TRANSPARENCY_GROUP));
}
/**
* In auto mode, a page explicitly flagged as using transparency emits the
* group.
*
* @throws \Com\Tecnick\Pdf\Page\Exception
* @throws \Com\Tecnick\Pdf\Encrypt\Exception
*/
public function testGetPdfPagesTransparencyAutoFlaggedTrue(): void
{
$page = $this->getTestObject();
$page->add();
$page->add();
$page->setPageTransparency(false, 0);
$page->setPageTransparency(true, 1);
$pon = 0;
$out = $page->getPdfPages($pon);
$this->assertEquals(1, substr_count($out, self::TRANSPARENCY_GROUP));
}
/**
* The 'always' mode emits the group on every standard page, even those
* flagged as not using transparency.
*
* @throws \Com\Tecnick\Pdf\Page\Exception
* @throws \Com\Tecnick\Pdf\Encrypt\Exception
*/
public function testGetPdfPagesTransparencyAlways(): void
{
$page = $this->getTestObject();
$page->add();
$page->add();
$page->setPageTransparency(false, 0);
$page->setPageTransparency(false, 1);
$page->setPageTransparencyGroupMode('always');
$pon = 0;
$out = $page->getPdfPages($pon);
$this->assertEquals(2, substr_count($out, self::TRANSPARENCY_GROUP));
}
/**
* The 'never' mode never emits the group, even on pages flagged as using
* transparency.
*
* @throws \Com\Tecnick\Pdf\Page\Exception
* @throws \Com\Tecnick\Pdf\Encrypt\Exception
*/
public function testGetPdfPagesTransparencyNever(): void
{
$page = $this->getTestObject();
$page->add();
$page->add();
$page->setPageTransparency(true, 0);
$page->setPageTransparencyGroupMode('never');
$pon = 0;
$out = $page->getPdfPages($pon);
$this->assertStringNotContainsString(self::TRANSPARENCY_GROUP, $out);
}
/**
* Unknown modes are treated as 'auto'.
*
* @throws \Com\Tecnick\Pdf\Page\Exception
* @throws \Com\Tecnick\Pdf\Encrypt\Exception
*/
public function testGetPdfPagesTransparencyUnknownModeIsAuto(): void
{
$page = $this->getTestObject();
$page->add();
$page->add();
$page->setPageTransparency(false, 0);
$page->setPageTransparencyGroupMode('bogus');
$pon = 0;
$out = $page->getPdfPages($pon);
// behaves like auto: page 0 omits, page 1 keeps the group.
$this->assertEquals(1, substr_count($out, self::TRANSPARENCY_GROUP));
}
/**
* PDF/A documents never emit the transparency group, regardless of the
* configured mode or per-page flags.
*
* @throws \Com\Tecnick\Pdf\Page\Exception
* @throws \Com\Tecnick\Pdf\Encrypt\Exception
*/
public function testGetPdfPagesTransparencyPdfa(): void
{
$page = $this->getPdfaTestObject();
$page->add();
$page->add();
$page->setPageTransparency(true, 0);
$page->setPageTransparencyGroupMode('always');
$pon = 0;
$out = $page->getPdfPages($pon);
$this->assertStringNotContainsString(self::TRANSPARENCY_GROUP, $out);
}
/**
* Numeric transition entries (/D, /Di, /SS) must be emitted as PDF numbers,
* not as name objects, while name entries (/S) stay names.
*
* @throws \Com\Tecnick\Pdf\Page\Exception
* @throws \Com\Tecnick\Pdf\Encrypt\Exception
*/
public function testGetPdfPagesTransitionNumericEntries(): void
{
$page = $this->getTestObject();
$page->add([
'transition' => [
'Dur' => 2,
'D' => 3,
'S' => 'Glitter',
'Di' => 315,
'SS' => 1.3,
'B' => true,
],
]);
$page->addContent('TEST');
$pon = 0;
$out = $page->getPdfPages($pon);
$this->bcAssertStringContainsString('/D 3' . "\n", $out);
$this->bcAssertStringContainsString('/Di 315' . "\n", $out);
$this->bcAssertStringContainsString('/SS 1.300000' . "\n", $out);
$this->bcAssertStringContainsString('/S /Glitter' . "\n", $out);
$this->bcAssertStringContainsString('/B true' . "\n", $out);
// Regression guard: numeric keys must not be rendered as name objects.
$this->assertStringNotContainsString('/D /3', $out);
$this->assertStringNotContainsString('/Di /315', $out);
$this->assertStringNotContainsString('/SS /', $out);
}
/**
* The /Di direction may legitimately be the name /None (Fly transitions).
*
* @throws \Com\Tecnick\Pdf\Page\Exception
* @throws \Com\Tecnick\Pdf\Encrypt\Exception
*/
public function testGetPdfPagesTransitionDiNoneIsName(): void
{
$page = $this->getTestObject();
$page->add([
'transition' => [
'S' => 'Fly',
'Di' => 'None',
'SS' => 0.5,
],
]);
$page->addContent('TEST');
$pon = 0;
$out = $page->getPdfPages($pon);
$this->bcAssertStringContainsString('/S /Fly' . "\n", $out);
$this->bcAssertStringContainsString('/Di /None' . "\n", $out);
$this->bcAssertStringContainsString('/SS 0.500000' . "\n", $out);
}
/**
* delete() reindexes the stack, so the embedded 'pid' of every remaining page
* must keep matching its array index.
*
* @throws \Com\Tecnick\Pdf\Page\Exception
*/
public function testDeleteReindexesPageIds(): void
{
$page = $this->getTestObject();
$page->add();
$page->add();
$page->add();
$page->delete(0);
foreach ($page->getPages() as $idx => $data) {
$this->assertSame($idx, $data['pid']);
}
}
/**
* move() reindexes the stack, so the embedded 'pid' of every page must keep
* matching its array index.
*
* @throws \Com\Tecnick\Pdf\Page\Exception
*/
public function testMoveReindexesPageIds(): void
{
$page = $this->getTestObject();
$page->add();
$page->add();
$page->add();
$page->add();
$page->move(3, 0);
foreach ($page->getPages() as $idx => $data) {
$this->assertSame($idx, $data['pid']);
}
}
/**
* getNextPage() must decide auto-break based on the queried page, not the
* current-page pointer when they differ.
*
* @throws \Com\Tecnick\Pdf\Page\Exception
*/
public function testGetNextPageUsesQueriedPageAutoBreak(): void
{
$page = $this->getTestObject();
$page->add();
$page->add();
$page->enableAutoPageBreak(true, 0);
$page->enableAutoPageBreak(false, 1);
// Current pointer is page 0 (auto-break on), but page 1 (auto-break off)
// is queried: no new page must be appended.
$page->setCurrentPage(0);
$page->getNextRegion(1);
$this->assertCount(2, $page->getPages());
}
}
+511
View File
@@ -0,0 +1,511 @@
<?php
/**
* RegionTest.php
*
* @since 2011-05-23
* @category Library
* @package PdfPage
* @author Nicola Asuni <info@tecnick.com>
* @copyright 2011-2026 Nicola Asuni - Tecnick.com LTD
* @license https://www.gnu.org/copyleft/lesser.html GNU-LGPL v3 (see LICENSE)
* @link https://github.com/tecnickcom/tc-lib-pdf-page
*
* This file is part of tc-lib-pdf-page software library.
*/
namespace Test;
use Com\Tecnick\Color\Pdf;
use Com\Tecnick\Pdf\Page\Page;
/**
* Page Test
*
* @since 2011-05-23
* @category Library
* @package PdfPage
* @author Nicola Asuni <info@tecnick.com>
* @copyright 2011-2026 Nicola Asuni - Tecnick.com LTD
* @license https://www.gnu.org/copyleft/lesser.html GNU-LGPL v3 (see LICENSE)
* @link https://github.com/tecnickcom/tc-lib-pdf-page
*/
class RegionTest extends TestUtil
{
/**
* @throws \Com\Tecnick\Pdf\Page\Exception
*/
protected function getTestObject(): \Com\Tecnick\Pdf\Page\Page
{
$pdf = new Pdf();
$encrypt = $this->getEncryptObject();
return new Page('mm', $pdf, $encrypt, false, false);
}
/**
* @throws \Com\Tecnick\Pdf\Page\Exception
*/
public function testRegion(): void
{
$page = $this->getTestObject();
$page->add([
'columns' => 3,
]);
$res = $page->selectRegion(1);
$exp = [
'RX' => 70,
'RY' => 0,
'RW' => 70,
'RH' => 297,
'RL' => 140,
'RR' => 70,
'RT' => 297,
'RB' => 0,
'x' => 70,
'y' => 0,
];
$this->bcAssertEqualsWithDelta($exp, $res);
$res = $page->getRegion();
$this->bcAssertEqualsWithDelta($exp, $res);
$res = $page->getNextRegion();
$this->bcAssertEqualsWithDelta(2, $res['currentRegion']);
$res = $page->getNextRegion();
$this->bcAssertEqualsWithDelta(0, $res['currentRegion']);
$page->setCurrentPage(0);
$res = $page->getNextRegion();
$this->bcAssertEqualsWithDelta(0, $res['currentRegion']);
$res = $page->checkRegionBreak(1000);
$this->bcAssertEqualsWithDelta(1, $res['currentRegion']);
$res = $page->checkRegionBreak();
$this->bcAssertEqualsWithDelta(1, $res['currentRegion']);
$page->setX(13)->setY(17);
$this->bcAssertEqualsWithDelta(13, $page->getX());
$this->bcAssertEqualsWithDelta(17, $page->getY());
}
/**
* @throws \Com\Tecnick\Pdf\Page\Exception
*/
public function testRegionBoundaries(): void
{
$page = $this->getTestObject();
$page->add([
'columns' => 3,
]);
$region = $page->getRegion();
$res = $page->isYOutRegion(null, 1);
$this->assertFalse($res);
$res = $page->isYOutRegion(-1);
$this->assertTrue($res);
$res = $page->isYOutRegion($region['RY']);
$this->assertFalse($res);
$res = $page->isYOutRegion(0);
$this->assertFalse($res);
$res = $page->isYOutRegion(100);
$this->assertFalse($res);
$res = $page->isYOutRegion(297);
$this->assertFalse($res);
$res = $page->isYOutRegion($region['RT']);
$this->assertFalse($res);
$res = $page->isYOutRegion(298);
$this->assertTrue($res);
$page->getNextRegion();
$region = $page->getRegion();
$res = $page->isXOutRegion(null, 1);
$this->assertFalse($res);
$res = $page->isXOutRegion(69);
$this->assertTrue($res);
$res = $page->isXOutRegion($region['RX']);
$this->assertFalse($res);
$res = $page->isXOutRegion(70);
$this->assertFalse($res);
$res = $page->isXOutRegion(90);
$this->assertFalse($res);
$res = $page->isXOutRegion(140);
$this->assertFalse($res);
$res = $page->isXOutRegion($region['RL']);
$this->assertFalse($res);
$res = $page->isXOutRegion(141);
$this->assertTrue($res);
$pid = $page->getPageID();
$this->assertEquals(0, $pid);
}
/**
* @throws \Com\Tecnick\Pdf\Page\Exception
*/
public function testSetNoWriteRegionsSideRectangle(): void
{
$page = $this->getTestObject();
$page->add();
// Obstacle on the right side blocking x in [150, 210] for y in [100, 200].
$res = $page->setNoWriteRegions([
['xt' => 150, 'yt' => 100, 'xb' => 150, 'yb' => 200, 'side' => 'R'],
], 50.0);
$this->bcAssertEqualsWithDelta(3, $res['columns']);
$exp = [
[
'RW' => 210,
'RX' => 0,
'RL' => 210,
'RR' => 0,
'RH' => 100,
'RY' => 0,
'RT' => 100,
'RB' => 197,
'x' => 0,
'y' => 0,
],
[
'RW' => 150,
'RX' => 0,
'RL' => 150,
'RR' => 60,
'RH' => 100,
'RY' => 100,
'RT' => 200,
'RB' => 97,
'x' => 0,
'y' => 100,
],
[
'RW' => 210,
'RX' => 0,
'RL' => 210,
'RR' => 0,
'RH' => 97,
'RY' => 200,
'RT' => 297,
'RB' => 0,
'x' => 0,
'y' => 200,
],
];
$this->bcAssertEqualsWithDelta($exp, $res['region']);
}
/**
* @throws \Com\Tecnick\Pdf\Page\Exception
*/
public function testBuildWritableRegionsSlantedSegment(): void
{
$page = $this->getTestObject();
$page->add();
// Slanted right-side segment from (100,100) to (150,200): a staircase approximation.
$res = $page->buildWritableRegions([
['xt' => 100, 'yt' => 100, 'xb' => 150, 'yb' => 200, 'side' => 'R'],
], 50.0);
$exp = [
['RX' => 0, 'RY' => 0, 'RW' => 210, 'RH' => 100],
['RX' => 0, 'RY' => 100, 'RW' => 100, 'RH' => 50],
['RX' => 0, 'RY' => 150, 'RW' => 125, 'RH' => 50],
['RX' => 0, 'RY' => 200, 'RW' => 210, 'RH' => 97],
];
$this->bcAssertEqualsWithDelta($exp, $res);
}
/**
* @throws \Com\Tecnick\Pdf\Page\Exception
*/
public function testBuildWritableRegionsFloatingBoxKeepsWidestSide(): void
{
$page = $this->getTestObject();
$page->add();
// Floating obstacle blocking x in [60, 100] for y in [100, 150]:
// the band splits into [0,60] (w=60) and [100,210] (w=110); the widest is kept.
$res = $page->buildWritableRegions([
['x' => 60, 'y' => 100, 'w' => 40, 'h' => 50],
], 50.0);
$exp = [
['RX' => 0, 'RY' => 0, 'RW' => 210, 'RH' => 100],
['RX' => 100, 'RY' => 100, 'RW' => 110, 'RH' => 50],
['RX' => 0, 'RY' => 150, 'RW' => 210, 'RH' => 147],
];
$this->bcAssertEqualsWithDelta($exp, $res);
}
/**
* @throws \Com\Tecnick\Pdf\Page\Exception
*/
public function testNoWriteRegionsAddGetRemove(): void
{
$page = $this->getTestObject();
$page->add();
$page->setNoWriteRegions([
['xt' => 150, 'yt' => 100, 'xb' => 150, 'yb' => 200, 'side' => 'R'],
], 50.0);
$this->assertCount(1, $page->getNoWriteRegions());
// The added left-side obstacle pushes the bottom region's left edge to x=60.
$res = $page->addNoWriteRegion(['xt' => 60, 'yt' => 230, 'xb' => 60, 'yb' => 270, 'side' => 'L']);
$this->assertCount(2, $page->getNoWriteRegions());
$this->bcAssertEqualsWithDelta(3, $res['columns']);
$expAdded = [
[
'RW' => 210,
'RX' => 0,
'RL' => 210,
'RR' => 0,
'RH' => 100,
'RY' => 0,
'RT' => 100,
'RB' => 197,
'x' => 0,
'y' => 0,
],
[
'RW' => 150,
'RX' => 0,
'RL' => 150,
'RR' => 60,
'RH' => 100,
'RY' => 100,
'RT' => 200,
'RB' => 97,
'x' => 0,
'y' => 100,
],
[
'RW' => 150,
'RX' => 60,
'RL' => 210,
'RR' => 0,
'RH' => 97,
'RY' => 200,
'RT' => 297,
'RB' => 0,
'x' => 60,
'y' => 200,
],
];
$this->bcAssertEqualsWithDelta($expAdded, $res['region']);
// Removing the first (right) area leaves only the left-side area.
$page->removeNoWriteRegion(0);
$this->bcAssertEqualsWithDelta([[
'xt' => 60,
'yt' => 230,
'xb' => 60,
'yb' => 270,
'side' => 'L',
]], $page->getNoWriteRegions());
// Removing the last area leaves the page with a single full content region.
$res = $page->removeNoWriteRegion(0);
$this->assertCount(0, $page->getNoWriteRegions());
$this->bcAssertEqualsWithDelta(1, $res['columns']);
$this->bcAssertEqualsWithDelta([[
'RW' => 210,
'RX' => 0,
'RL' => 210,
'RR' => 0,
'RH' => 297,
'RY' => 0,
'RT' => 297,
'RB' => 0,
'x' => 0,
'y' => 0,
]], $res['region']);
}
/**
* @throws \Com\Tecnick\Pdf\Page\Exception
*/
public function testNoWriteRegionsResetOnClonedPage(): void
{
$page = $this->getTestObject();
$page->add();
$res = $page->setNoWriteRegions([
['xt' => 150, 'yt' => 100, 'xb' => 150, 'yb' => 200, 'side' => 'R'],
], 50.0);
$this->assertGreaterThan(1, $res['columns']);
// Cloning the page (e.g. an automatic page break) must NOT inherit the no-write bands:
// the new page starts with a single default full-content region.
$cloned = $page->add();
$this->bcAssertEqualsWithDelta(1, $cloned['columns']);
$this->assertCount(0, $page->getNoWriteRegions($cloned['pid']));
$this->bcAssertEqualsWithDelta([[
'RW' => 210,
'RX' => 0,
'RL' => 210,
'RR' => 0,
'RH' => 297,
'RY' => 0,
'RT' => 297,
'RB' => 0,
'x' => 0,
'y' => 0,
]], $cloned['region']);
}
/**
* @throws \Com\Tecnick\Pdf\Page\Exception
*/
public function testNoWriteRegionsValidation(): void
{
$page = $this->getTestObject();
$page->add();
try {
$page->setNoWriteRegions([], 0.0);
$this->fail('Expected exception was not thrown.');
} catch (\Com\Tecnick\Pdf\Page\Exception $e) {
$this->assertStringContainsString('band height', $e->getMessage());
}
try {
$page->buildWritableRegions([], -5.0);
$this->fail('Expected exception was not thrown.');
} catch (\Com\Tecnick\Pdf\Page\Exception $e) {
$this->assertStringContainsString('band height', $e->getMessage());
}
try {
$page->addNoWriteRegion(['x' => 10, 'y' => 10, 'w' => 10, 'h' => 10]);
$this->fail('Expected exception was not thrown.');
} catch (\Com\Tecnick\Pdf\Page\Exception $e) {
$this->assertStringContainsString('setNoWriteRegions', $e->getMessage());
}
try {
$page->removeNoWriteRegion(7);
$this->fail('Expected exception was not thrown.');
} catch (\Com\Tecnick\Pdf\Page\Exception $e) {
$this->assertStringContainsString('index 7', $e->getMessage());
}
}
/**
* @throws \Com\Tecnick\Pdf\Page\Exception
*/
public function testDefensiveChecksOnMissingPageAfterForcedSanitizeId(): void
{
$pdf = new Pdf();
$encrypt = $this->getEncryptObject();
$page = new class('mm', $pdf, $encrypt, false, false) extends Page {
public bool $forceSanitizePageId = false;
public int $forcedPid = 0;
protected function sanitizePageID(int $pid = -1): int
{
if ($this->forceSanitizePageId) {
return $this->forcedPid;
}
return parent::sanitizePageID($pid);
}
};
$page->add();
$page->forceSanitizePageId = true;
$page->forcedPid = 99;
try {
$page->getPage(99);
$this->fail('Expected exception was not thrown.');
} catch (\Com\Tecnick\Pdf\Page\Exception $e) {
$this->assertStringContainsString('index 99', $e->getMessage());
}
try {
$page->setPagePHeight(10, 99);
$this->fail('Expected exception was not thrown.');
} catch (\Com\Tecnick\Pdf\Page\Exception $e) {
$this->assertStringContainsString('index 99', $e->getMessage());
}
try {
$page->setPagePWidth(10, 99);
$this->fail('Expected exception was not thrown.');
} catch (\Com\Tecnick\Pdf\Page\Exception $e) {
$this->assertStringContainsString('index 99', $e->getMessage());
}
try {
$page->selectRegion(0, 99);
$this->fail('Expected exception was not thrown.');
} catch (\Com\Tecnick\Pdf\Page\Exception $e) {
$this->assertStringContainsString('index 99', $e->getMessage());
}
try {
$page->getNextRegion(99);
$this->fail('Expected exception was not thrown.');
} catch (\Com\Tecnick\Pdf\Page\Exception $e) {
$this->assertStringContainsString('index 99', $e->getMessage());
}
try {
$page->isAutoPageBreakEnabled(99);
$this->fail('Expected exception was not thrown.');
} catch (\Com\Tecnick\Pdf\Page\Exception $e) {
$this->assertStringContainsString('index 99', $e->getMessage());
}
try {
$page->enableAutoPageBreak(true, 99);
$this->fail('Expected exception was not thrown.');
} catch (\Com\Tecnick\Pdf\Page\Exception $e) {
$this->assertStringContainsString('index 99', $e->getMessage());
}
try {
$page->setX(1, 99);
$this->fail('Expected exception was not thrown.');
} catch (\Com\Tecnick\Pdf\Page\Exception $e) {
$this->assertStringContainsString('index 99', $e->getMessage());
}
try {
$page->setY(1, 99);
$this->fail('Expected exception was not thrown.');
} catch (\Com\Tecnick\Pdf\Page\Exception $e) {
$this->assertStringContainsString('index 99', $e->getMessage());
}
}
/**
* An out-of-range region index must clamp to the nearest valid region instead
* of selecting a non-existent index (which previously threw).
*
* @throws \Com\Tecnick\Pdf\Page\Exception
*/
public function testSelectRegionClampsOutOfRangeIndex(): void
{
$page = $this->getTestObject();
$page->add([
'columns' => 3,
]);
// Index beyond the last region (valid: 0..2) clamps to the last region.
$res = $page->selectRegion(99);
$this->bcAssertEqualsWithDelta(2, $page->getPage()['currentRegion']);
$this->bcAssertEqualsWithDelta($res, $page->getRegion());
// Negative index clamps to the first region.
$page->selectRegion(-5);
$this->bcAssertEqualsWithDelta(0, $page->getPage()['currentRegion']);
}
}
File diff suppressed because it is too large Load Diff
+62
View File
@@ -0,0 +1,62 @@
<?php
/**
* TestUtil.php
*
* @since 2020-12-19
* @category Library
* @package PdfPage
* @author Nicola Asuni <info@tecnick.com>
* @copyright 2015-2026 Nicola Asuni - Tecnick.com LTD
* @license https://www.gnu.org/copyleft/lesser.html GNU-LGPL v3 (see LICENSE)
* @link https://github.com/tecnickcom/tc-lib-pdf-page
*
* This file is part of tc-lib-color software library.
*/
namespace Test;
use PHPUnit\Framework\TestCase;
/**
* Web Color class test
*
* @since 2020-12-19
* @category Library
* @package PdfPage
* @author Nicola Asuni <info@tecnick.com>
* @copyright 2015-2026 Nicola Asuni - Tecnick.com LTD
* @license https://www.gnu.org/copyleft/lesser.html GNU-LGPL v3 (see LICENSE)
* @link https://github.com/tecnickcom/tc-lib-pdf-page
*/
class TestUtil extends TestCase
{
protected function getEncryptObject(): \Com\Tecnick\Pdf\Encrypt\Encrypt
{
return new class() extends \Com\Tecnick\Pdf\Encrypt\Encrypt {
public function __construct() {}
};
}
public function bcAssertEqualsWithDelta(
mixed $expected,
mixed $actual,
float $delta = 0.01,
string $message = '',
): void {
parent::assertEqualsWithDelta($expected, $actual, $delta, $message);
}
/**
* @param class-string<\Throwable> $exception
*/
public function bcExpectException(string $exception): void
{
parent::expectException($exception);
}
public function bcAssertStringContainsString(string $needle, string $haystack): void
{
parent::assertStringContainsString($needle, $haystack);
}
}
@@ -0,0 +1,92 @@
<?php
/**
* TransparencyGroupModeTest.php
*
* @since 2026-07-17
* @category Library
* @package PdfPage
* @author Nicola Asuni <info@tecnick.com>
* @copyright 2011-2026 Nicola Asuni - Tecnick.com LTD
* @license https://www.gnu.org/copyleft/lesser.html GNU-LGPL v3 (see LICENSE)
* @link https://github.com/tecnickcom/tc-lib-pdf-page
*
* This file is part of tc-lib-pdf-page software library.
*/
namespace Test;
use Com\Tecnick\Pdf\Page\TransparencyGroupMode;
/**
* TransparencyGroupMode enum test
*
* @since 2026-07-17
* @category Library
* @package PdfPage
* @author Nicola Asuni <info@tecnick.com>
* @copyright 2011-2026 Nicola Asuni - Tecnick.com LTD
* @license https://www.gnu.org/copyleft/lesser.html GNU-LGPL v3 (see LICENSE)
* @link https://github.com/tecnickcom/tc-lib-pdf-page
*/
class TransparencyGroupModeTest extends TestUtil
{
/**
* @throws \Com\Tecnick\Pdf\Page\Exception
*/
protected function getTestObject(): \Com\Tecnick\Pdf\Page\Page
{
$pdf = new \Com\Tecnick\Color\Pdf();
$encrypt = $this->getEncryptObject();
return new \Com\Tecnick\Pdf\Page\Page('mm', $pdf, $encrypt, false, false);
}
public function testCaseBackingValues(): void
{
$this->assertSame('auto', TransparencyGroupMode::Auto->value);
$this->assertSame('always', TransparencyGroupMode::Always->value);
$this->assertSame('never', TransparencyGroupMode::Never->value);
}
public function testFromLooseCanonical(): void
{
$this->assertSame(TransparencyGroupMode::Auto, TransparencyGroupMode::fromLoose('auto'));
$this->assertSame(TransparencyGroupMode::Always, TransparencyGroupMode::fromLoose('always'));
$this->assertSame(TransparencyGroupMode::Never, TransparencyGroupMode::fromLoose('never'));
}
public function testFromLooseIsCaseInsensitive(): void
{
$this->assertSame(TransparencyGroupMode::Always, TransparencyGroupMode::fromLoose('ALWAYS'));
}
public function testFromLooseUnknownFallsBackToAuto(): void
{
$this->assertSame(TransparencyGroupMode::Auto, TransparencyGroupMode::fromLoose('sometimes'));
$this->assertSame(TransparencyGroupMode::Auto, TransparencyGroupMode::fromLoose(''));
}
public function testFromLoosePassesThroughEnumInstance(): void
{
$this->assertSame(TransparencyGroupMode::Never, TransparencyGroupMode::fromLoose(TransparencyGroupMode::Never));
}
public function testFromLooseRoundTrip(): void
{
foreach (TransparencyGroupMode::cases() as $case) {
$this->assertSame($case, TransparencyGroupMode::fromLoose($case->value));
}
}
/**
* The widened setter accepts a TransparencyGroupMode enum and stays chainable.
*
* @throws \Com\Tecnick\Pdf\Page\Exception
*/
public function testSetPageTransparencyGroupModeAcceptsEnum(): void
{
$page = $this->getTestObject();
$this->assertSame($page, $page->setPageTransparencyGroupMode(TransparencyGroupMode::Always));
$this->assertSame($page, $page->setPageTransparencyGroupMode('never'));
}
}
+116
View File
@@ -0,0 +1,116 @@
<?php
/**
* UnitEnumTest.php
*
* @since 2026-07-17
* @category Library
* @package PdfPage
* @author Nicola Asuni <info@tecnick.com>
* @copyright 2011-2026 Nicola Asuni - Tecnick.com LTD
* @license https://www.gnu.org/copyleft/lesser.html GNU-LGPL v3 (see LICENSE)
* @link https://github.com/tecnickcom/tc-lib-pdf-page
*
* This file is part of tc-lib-pdf-page software library.
*/
namespace Test;
use Com\Tecnick\Pdf\Page\Unit;
/**
* Unit enum test
*
* @since 2026-07-17
* @category Library
* @package PdfPage
* @author Nicola Asuni <info@tecnick.com>
* @copyright 2011-2026 Nicola Asuni - Tecnick.com LTD
* @license https://www.gnu.org/copyleft/lesser.html GNU-LGPL v3 (see LICENSE)
* @link https://github.com/tecnickcom/tc-lib-pdf-page
*/
class UnitEnumTest extends TestUtil
{
/**
* @throws \Com\Tecnick\Pdf\Page\Exception
*/
protected function getTestObject(): \Com\Tecnick\Pdf\Page\Page
{
$pdf = new \Com\Tecnick\Color\Pdf();
$encrypt = $this->getEncryptObject();
return new \Com\Tecnick\Pdf\Page\Page('mm', $pdf, $encrypt, false, false);
}
public function testCaseBackingValues(): void
{
$this->assertSame('pt', Unit::Point->value);
$this->assertSame('mm', Unit::Millimeter->value);
$this->assertSame('cm', Unit::Centimeter->value);
$this->assertSame('in', Unit::Inch->value);
}
/**
* @throws \Com\Tecnick\Pdf\Page\Exception
*/
public function testFromLooseCanonicalAliasesAndDefault(): void
{
$this->assertSame(Unit::Point, Unit::fromLoose(''));
$this->assertSame(Unit::Point, Unit::fromLoose('pt'));
$this->assertSame(Unit::Point, Unit::fromLoose('points'));
$this->assertSame(Unit::Point, Unit::fromLoose('px'));
$this->assertSame(Unit::Millimeter, Unit::fromLoose('mm'));
$this->assertSame(Unit::Millimeter, Unit::fromLoose('millimeters'));
$this->assertSame(Unit::Centimeter, Unit::fromLoose('cm'));
$this->assertSame(Unit::Centimeter, Unit::fromLoose('centimeters'));
$this->assertSame(Unit::Inch, Unit::fromLoose('in'));
$this->assertSame(Unit::Inch, Unit::fromLoose('inches'));
}
/**
* @throws \Com\Tecnick\Pdf\Page\Exception
*/
public function testFromLooseIsCaseInsensitive(): void
{
$this->assertSame(Unit::Millimeter, Unit::fromLoose('MM'));
$this->assertSame(Unit::Inch, Unit::fromLoose('Inches'));
}
/**
* @throws \Com\Tecnick\Pdf\Page\Exception
*/
public function testFromLoosePassesThroughEnumInstance(): void
{
$this->assertSame(Unit::Centimeter, Unit::fromLoose(Unit::Centimeter));
}
/**
* @throws \Com\Tecnick\Pdf\Page\Exception
*/
public function testFromLooseRoundTrip(): void
{
foreach (Unit::cases() as $case) {
$this->assertSame($case, Unit::fromLoose($case->value));
}
}
/**
* @throws \Com\Tecnick\Pdf\Page\Exception
*/
public function testFromLooseUnknownThrows(): void
{
$this->bcExpectException(\Com\Tecnick\Pdf\Page\Exception::class);
Unit::fromLoose('parsec');
}
/**
* The widened getUnitRatio()/convertPoints() accept a Unit enum.
*
* @throws \Com\Tecnick\Pdf\Page\Exception
*/
public function testUnitRatioAcceptsEnum(): void
{
$page = $this->getTestObject();
$this->assertSame($page->getUnitRatio('in'), $page->getUnitRatio(Unit::Inch));
$this->assertSame($page->convertPoints(72, 'in', 3), $page->convertPoints(72, Unit::Inch, 3));
}
}
+64
View File
@@ -0,0 +1,64 @@
<?php
/**
* UnitTest.php
*
* @since 2011-05-23
* @category Library
* @package PdfPage
* @author Nicola Asuni <info@tecnick.com>
* @copyright 2011-2026 Nicola Asuni - Tecnick.com LTD
* @license https://www.gnu.org/copyleft/lesser.html GNU-LGPL v3 (see LICENSE)
* @link https://github.com/tecnickcom/tc-lib-pdf-page
*
* This file is part of tc-lib-pdf-page software library.
*/
namespace Test;
/**
* Unit Test
*
* @since 2011-05-23
* @category Library
* @package PdfPage
* @author Nicola Asuni <info@tecnick.com>
* @copyright 2011-2026 Nicola Asuni - Tecnick.com LTD
* @license https://www.gnu.org/copyleft/lesser.html GNU-LGPL v3 (see LICENSE)
* @link https://github.com/tecnickcom/tc-lib-pdf-page
*/
class UnitTest extends TestUtil
{
/**
* @throws \Com\Tecnick\Pdf\Page\Exception
*/
protected function getTestObject(): \Com\Tecnick\Pdf\Page\Page
{
$pdf = new \Com\Tecnick\Color\Pdf();
$encrypt = $this->getEncryptObject();
return new \Com\Tecnick\Pdf\Page\Page('mm', $pdf, $encrypt, false, false);
}
/**
* @throws \Com\Tecnick\Pdf\Page\Exception
*/
public function testGetPageSize(): void
{
$page = $this->getTestObject();
$val = $page->convertPoints(72, 'in', 3);
$this->assertEquals(1, $val);
$val = $page->convertPoints(72, 'mm', 3);
$this->assertEquals(25.4, $val);
}
/**
* @throws \Com\Tecnick\Pdf\Page\Exception
*/
public function testGetPageSizeEx(): void
{
$this->bcExpectException(\Com\Tecnick\Pdf\Page\Exception::class);
$page = $this->getTestObject();
$page->convertPoints(1, '*ERROR*', 2);
}
}