added composer files and installed vendor packages. Also modified xsls to display base project

This commit is contained in:
2026-08-09 09:59:37 -04:00
parent 53cd5430ee
commit 2d96a7b6e5
2142 changed files with 569661 additions and 240 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-graph
Thank you for your interest in contributing to **tc-lib-pdf-graph**.
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-graph.git
cd tc-lib-pdf-graph
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-graph/issues)** to avoid duplicates.
If no existing issue matches, [open a new one](https://github.com/tecnickcom/tc-lib-pdf-graph/issues/new) and include:
- A **clear title and description** of the problem.
- The **library version** (`composer show tecnickcom/tc-lib-pdf-graph`) 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-graph/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-graph/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-graph/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-graph
* 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 PdfGraph
# @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-graph
#
# This file is part of tc-lib-pdf-graph software library.
# ----------------------------------------------------------------------------------------------------------------------
SHELL=/bin/bash
.SHELLFLAGS=-o pipefail -c
# Project owner
OWNER=tecnickcom
# Project vendor
VENDOR=${OWNER}
# Project name
PROJECT=tc-lib-pdf-graph
# 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/Graph/
# 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-graph
> Geometric drawing and transformation primitives for PDF content streams.
[![Latest Stable Version](https://poser.pugx.org/tecnickcom/tc-lib-pdf-graph/version)](https://packagist.org/packages/tecnickcom/tc-lib-pdf-graph)
[![Build](https://github.com/tecnickcom/tc-lib-pdf-graph/actions/workflows/check.yml/badge.svg)](https://github.com/tecnickcom/tc-lib-pdf-graph/actions/workflows/check.yml)
[![Coverage](https://codecov.io/gh/tecnickcom/tc-lib-pdf-graph/graph/badge.svg?token=LqxfwhPB8G)](https://codecov.io/gh/tecnickcom/tc-lib-pdf-graph)
[![License](https://poser.pugx.org/tecnickcom/tc-lib-pdf-graph/license)](https://packagist.org/packages/tecnickcom/tc-lib-pdf-graph)
[![Downloads](https://poser.pugx.org/tecnickcom/tc-lib-pdf-graph/downloads)](https://packagist.org/packages/tecnickcom/tc-lib-pdf-graph)
[![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-graph` implements low-level drawing operations used to build PDF graphic content.
It exposes the primitives needed to compose paths and painting operations while keeping the API close to PDF graphics operators. This makes it suitable as a foundation layer for charting, vector drawing, and custom layout engines.
| | |
|---|---|
| **Namespace** | `\Com\Tecnick\Pdf\Graph` |
| **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-graph> |
| **Packagist** | <https://packagist.org/packages/tecnickcom/tc-lib-pdf-graph> |
---
## Features
### Drawing Primitives
- Paths, lines, curves, and clipping operations
- Style handling for stroke/fill combinations
- Gradient and shading support
### Transformations
- Matrix-based geometric transforms
- Coordinate conversion helpers
- PDF/A-aware behavior controls
---
## Requirements
- PHP 8.2 or later
- Extension: `zlib`
- Composer
---
## Installation
```bash
composer require tecnickcom/tc-lib-pdf-graph
```
---
## Quick Start
```php
<?php
require_once __DIR__ . '/vendor/autoload.php';
$draw = new \Com\Tecnick\Pdf\Graph\Draw(
1.0,
210,
297,
new \Com\Tecnick\Color\Pdf(),
new \Com\Tecnick\Pdf\Encrypt\Encrypt(),
false
);
echo $draw->getClippingRect(10, 10, 50, 20);
```
---
## 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/Graph/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-graph**.
---
## 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-graph <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-graph`).
- **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-graph) 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-graph> |
| Packagist | <https://packagist.org/packages/tecnickcom/tc-lib-pdf-graph> |
+1
View File
@@ -0,0 +1 @@
2.15.2
+64
View File
@@ -0,0 +1,64 @@
{
"name": "tecnickcom/tc-lib-pdf-graph",
"description": "PHP library containing PDF graphic and geometric methods",
"type": "library",
"homepage": "https://tcpdf.org",
"license": "LGPL-3.0-or-later",
"keywords": [
"tc-lib-pdf-graph",
"PDF",
"graphic",
"geometry",
"transformation"
],
"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\\Graph\\": "src"
}
},
"autoload-dev": {
"psr-4": {
"Test\\": "test"
}
},
"support": {
"issues": "https://github.com/tecnickcom/tc-lib-pdf-graph/issues",
"source": "https://github.com/tecnickcom/tc-lib-pdf-graph"
},
"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"]
}
}
+56
View File
@@ -0,0 +1,56 @@
#: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, volume-threshold = 2500.0, difficulty-threshold = 30.0, effort-threshold = 42000.0 }
identity-comparison = { enabled = true }
kan-defect = { enabled = false }
no-boolean-flag-parameter = { enabled = false }
no-else-clause = { enabled = false }
no-empty = { enabled = true }
too-many-methods = { enabled = false }
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-graph 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 PdfGraph
* @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-graph
*
* This file is part of tc-lib-pdf-graph 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 Graph Library
PHP library containing PDF graphic and geometric methods.
@@ -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,45 @@
# 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 graphic and geometric methods
License: LGPLv3+
URL: https://github.com/%{gh_owner}/%{gh_project}
BuildArch: noarch
Requires: php(language) >= 8.2.0
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 graphic and geometric methods
%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
* Mon Dec 14 2026 Nicola Asuni <info@tecnick.com> 1.0.0-1
- Initial Commit
+849
View File
@@ -0,0 +1,849 @@
<?php
declare(strict_types=1);
/**
* Base.php
*
* @since 2011-05-23
* @category Library
* @package PdfGraph
* @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-graph
*
* This file is part of tc-lib-pdf-graph software library.
*/
namespace Com\Tecnick\Pdf\Graph;
use Com\Tecnick\Color\Pdf as PdfColor;
use Com\Tecnick\Pdf\Encrypt\Encrypt;
/**
* Com\Tecnick\Pdf\Graph\Base
*
* @since 2011-05-23
* @category Library
* @package PdfGraph
* @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-graph
*
* @phpstan-type TTMatrix array{
* float,
* float,
* float,
* float,
* float,
* float,
* }
*
* @phpstan-type StyleData array{
* 'lineWidth': float,
* 'lineCap': string,
* 'lineJoin': string,
* 'miterLimit': float,
* 'dashArray': array<int>,
* 'dashPhase': float,
* 'lineColor': string,
* 'fillColor': string,
* }
*
* @phpstan-type StyleDataOpt array{
* 'lineWidth'?: float,
* 'lineCap'?: string,
* 'lineJoin'?: string,
* 'miterLimit'?: float,
* 'dashArray'?: array<int>,
* 'dashPhase'?: float,
* 'lineColor'?: string,
* 'fillColor'?: string,
* }
*
* @phpstan-type GradientData array{
* 'antialias': bool,
* 'background': ?\Com\Tecnick\Color\Model,
* 'colors': array<int, array{
* 'color': string,
* 'exponent'?: float,
* 'opacity'?: float,
* 'offset'?: float,
* }>,
* 'colspace': string,
* 'coords': array<float>,
* 'id': int,
* 'pattern': int,
* 'stream': string,
* 'transparency': bool,
* 'type': int,
* }
*
* @SuppressWarnings("PHPMD.ExcessiveClassComplexity")
*/
abstract class Base
{
/**
* Pi constant
* We use this instead of M_PI because HHVM has a different value.
*
* @var float
*/
public const MPI = 3.141_592_653_589_793_238_462_643_383_279_502_884_197_169_399_375_10;
/**
* Identity matrix for transformations.
*
* @var TTMatrix
*/
public const IDMATRIX = [1.0, 0.0, 0.0, 1.0, 0.0, 0.0];
/**
* PDF graphics state save operator.
*
* @var string
*/
protected const GSAVE = 'q' . "\n";
/**
* PDF graphics state restore operator.
*
* @var string
*/
protected const GRESTORE = 'Q' . "\n";
/**
* Current PDF object number
*/
protected int $pon = 0;
/**
* Current page height
*/
protected float $pageh = 0;
/**
* Current page width
*/
protected float $pagew = 0;
/**
* Unit of measure conversion ratio
*/
protected float $kunit = 1.0;
/**
* Stack index.
*/
protected int $styleid = -1;
/**
* Stack containing style data.
*
* @var array<StyleDataOpt>
*/
protected array $style = [];
/**
* Array of transparency objects and parameters.
*
* @var array<int, array{
* 'n': int,
* 'name': string,
* 'parms': array<string, int|float|bool|string>,
* }>
*/
protected array $extgstates = [];
/**
* Array of gradients
*
* @var array<int, GradientData>
*/
protected array $gradients = [];
/**
* Bookkeeping for the luminosity soft-mask patterns generated for
* transparent gradients, keyed by the transparency pattern index used as
* the resource name (/p{key}) inside the soft-mask form XObject.
*
* These are internal helper objects, referenced only from within the
* soft-mask XObject, and are deliberately kept out of $gradients so they
* are not advertised in the page-level gradient resource dictionary.
*
* @var array<int, array{'id': int, 'pattern': int}>
*/
protected array $gradientMasks = [];
/**
* Initialize
*
* @param float $kunit Unit of measure conversion ratio.
* @param float $pagew Page width.
* @param float $pageh Page height.
* @param PdfColor $pdfColor 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.
*/
public function __construct(
float $kunit,
float $pagew,
float $pageh,
/**
* Color object
*/
protected PdfColor $pdfColor,
/**
* Encrypt object
*/
protected Encrypt $encrypt,
protected bool $pdfa = false,
protected bool $compress = true,
) {
$this->setKUnit($kunit);
$this->setPageWidth($pagew);
$this->setPageHeight($pageh);
$this->initStyle();
}
/**
* Initialize default style
*/
public function initStyle(): void
{
$this->style[++$this->styleid] = $this->getDefaultStyle();
}
/**
* Returns the default style.
*
* @param StyleDataOpt $style Style parameters to merge to the default ones.
*
* @return StyleData
*/
public function getDefaultStyle(array $style = []): array
{
return [
// line thickness in user units
'lineWidth' => $style['lineWidth'] ?? (1.0 / $this->kunit),
// shape of the endpoints for any open path that is stroked
'lineCap' => $style['lineCap'] ?? 'butt',
// shape of joints between connected segments of a stroked path
'lineJoin' => $style['lineJoin'] ?? 'miter',
// maximum length of mitered line joins for stroked paths
'miterLimit' => $style['miterLimit'] ?? (10.0 / $this->kunit),
// lengths of alternating dashes and gaps
'dashArray' => $style['dashArray'] ?? [],
// distance at which to start the dash
'dashPhase' => $style['dashPhase'] ?? 0.0,
// line (drawing) color
'lineColor' => $style['lineColor'] ?? 'black',
// background (filling) color
'fillColor' => $style['fillColor'] ?? 'black',
];
}
/**
* Returns current PDF object number
*/
public function getObjectNumber(): int
{
return $this->pon;
}
/**
* Set page height and returns previous value.
*
* @param float $pageh Page height.
*
* @return float previous page height value.
*/
public function setPageHeight(float $pageh): float
{
$ret = $this->pageh;
$this->pageh = $pageh;
return $ret;
}
/**
* Set page width and returns previous value.
*
* @param float $pagew Page width.
*
* @return float previous page width value.
*/
public function setPageWidth(float $pagew): float
{
$ret = $this->pagew;
$this->pagew = $pagew;
return $ret;
}
/**
* Set unit of measure conversion ratio.
*
* @param float $kunit Unit of measure conversion ratio.
*/
public function setKUnit(float $kunit): static
{
$this->kunit = $kunit;
return $this;
}
/**
* Get the PDF output string for ExtGState
*
* @param int $pon Current PDF Object Number
*
* @return string PDF command
*/
public function getOutExtGState(int $pon): string
{
$this->pon = $pon;
$out = '';
foreach ($this->extgstates as $idx => $ext) {
$this->extgstates[$idx]['n'] = ++$this->pon;
$out .= $this->pon . ' 0 obj' . "\n" . '<< /Type /ExtGState';
foreach ($ext['parms'] as $key => $val) {
$val = match (true) {
\is_numeric($val) => \sprintf('%F', $val),
$val === true => 'true',
$val === false => 'false',
default => $val,
};
$out .= ' /' . $key . ' ' . $val;
}
$out .= ' >>' . "\n" . 'endobj' . "\n";
}
return $out;
}
/**
* Returns the last extgstate ID to be used with XObjects.
*
* @return ?int
*/
public function getLastExtGStateID(): ?int
{
return \array_key_last($this->extgstates);
}
/**
* Returns the resource names of the registered ExtGState objects that carry
* actual (non-trivial) transparency: a fill or stroke alpha below 1, a blend
* mode other than Normal, or a soft mask.
*
* The returned names match the tokens used by the `gs` operator in content
* streams (for example "GS3"), so callers can detect whether a given content
* stream actually triggers transparency (as opposed to merely resetting the
* graphics state back to fully opaque).
*
* @return array<int, string> List of ExtGState resource names.
*/
public function getTransparencyExtGStateNames(): array
{
$names = [];
foreach ($this->extgstates as $key => $ext) {
if (!self::extGStateHasTransparency($ext['parms'])) {
continue;
}
$names[] = $ext['name'] !== '' ? $ext['name'] : 'GS' . $key;
}
return $names;
}
/**
* Whether the given ExtGState parameters describe actual transparency:
* a constant alpha below 1, a non-Normal blend mode, or a soft mask.
*
* @param array<string, int|float|bool|string> $parms ExtGState parameters.
*/
private static function extGStateHasTransparency(array $parms): bool
{
$belowOne = static fn(string $key): bool => (
isset($parms[$key])
&& \is_numeric($parms[$key])
&& (float) $parms[$key] < 1.0
);
if ($belowOne('ca') || $belowOne('CA')) {
return true;
}
$blend = isset($parms['BM']) ? \ltrim((string) $parms['BM'], '/') : 'Normal';
if ($blend !== '' && $blend !== 'Normal') {
return true;
}
$smask = isset($parms['SMask']) ? \ltrim((string) $parms['SMask'], '/') : 'None';
return $smask !== '' && $smask !== 'None';
}
/**
* Get the PDF output string for ExtGState Resource Dictionary.
*
* @param array<int, array{'name': string, 'n': int, 'parms'?: array<string, int|float|bool|string>}> $data extgstates data.
*
* @return string PDF command
*/
private function getOutExtGStateResDict(array $data): string
{
if ($this->pdfa || $this->extgstates === []) {
return '';
}
$out = ' /ExtGState <<';
foreach ($data as $key => $ext) {
$out .= $ext['name'] !== '' ? ' /' . $ext['name'] : ' /GS' . $key;
$out .= ' ' . $ext['n'] . ' 0 R';
}
return $out . (' >>' . "\n");
}
/**
* Get the PDF output string for ExtGState Resource Dictionary
*
* @return string PDF command
*/
public function getOutExtGStateResources(): string
{
return $this->getOutExtGStateResDict($this->extgstates);
}
/**
* Get the PDF output string for ExtGState Resource Dictionary for XObjects.
*
* @param array<int> $keys Array of extgstates keys.
*
* @return string PDF command
*/
public function getOutExtGStateResourcesByKeys(array $keys): string
{
if ($keys === []) {
return '';
}
$data = [];
foreach ($keys as $key) {
$ext = $this->extgstates[$key] ?? null;
if (!\is_array($ext)) {
continue;
}
$data[$key] = [
'name' => $ext['name'],
'n' => $ext['n'],
];
}
return $this->getOutExtGStateResDict($data);
}
/**
* Get the PDF output string for Gradients Resource Dictionary.
*
* @param array<int, array{'id': int, 'pattern': int, 'antialias'?: bool, 'background'?: ?\Com\Tecnick\Color\Model, 'colors'?: array<int, array{'color': string, 'exponent'?: float, 'opacity'?: float, 'offset'?: float}>, 'colspace'?: string, 'coords'?: array<float>, 'stream'?: string, 'transparency'?: bool, 'type'?: int}> $data gradients data.
*
* @return string PDF command
*/
private function getOutGradientResDict(array $data): string
{
if ($this->pdfa || $data === []) {
return '';
}
$grp = '';
$grs = '';
foreach ($data as $idx => $grad) {
// gradient patterns
$grp .= ' /p' . $idx . ' ' . $grad['pattern'] . ' 0 R';
// gradient shadings
$grs .= ' /Sh' . $idx . ' ' . $grad['id'] . ' 0 R';
}
return ' /Pattern <<' . $grp . ' >>' . "\n" . ' /Shading <<' . $grs . ' >>' . "\n";
}
/**
* Get the PDF output string for Gradients Resource Dictionary
*
* @return string PDF command
*/
public function getOutGradientResources(): string
{
return $this->getOutGradientResDict($this->gradients);
}
/**
* Returns the PDF command to output gradient resources.
*
* @param array<int> $keys Array of gradient keys.
*
* @return string PDF command
*/
public function getOutGradientResourcesByKeys(array $keys): string
{
if ($keys === []) {
return '';
}
$data = [];
foreach ($keys as $key) {
$grad = $this->gradients[$key] ?? null;
if (!\is_array($grad)) {
continue;
}
$data[$key] = [
'id' => $grad['id'],
'pattern' => $grad['pattern'],
];
}
return $this->getOutGradientResDict($data);
}
/**
* Get the PDF output string for gradient colors and transparency
*
* @param GradientData $grad Array of gradient colors
* @param string $type Type of output: 'color' or 'opacity'
*
* @return string PDF command
*
* @throws \Com\Tecnick\Pdf\Encrypt\Exception
*
* @SuppressWarnings("PHPMD.CyclomaticComplexity")
*/
protected function getOutGradientCols(array $grad, string $type): string
{
if ($type === 'opacity' && !$grad['transparency']) {
return '';
}
$out = '';
if ($grad['type'] === 2 || $grad['type'] === 3) {
$num_cols = \count($grad['colors']);
$lastcols = $num_cols - 1;
$funct = []; // color and transparency objects
$bounds = [];
$encode = [];
for ($idx = 1; $idx < $num_cols; ++$idx) {
$prevcol = $grad['colors'][$idx - 1] ?? null;
$nextcol = $grad['colors'][$idx] ?? null;
if (!\is_array($prevcol) || !\is_array($nextcol)) {
continue;
}
$col0 = $prevcol[$type] ?? null;
$col1 = $nextcol[$type] ?? null;
if ($type !== 'color') {
if (!\is_numeric($col0) || !\is_numeric($col1)) {
continue;
}
$col0 = \sprintf('%F', (float) $col0);
$col1 = \sprintf('%F', (float) $col1);
} else {
if (!\is_string($col0) || !\is_string($col1)) {
continue;
}
$model0 = $this->pdfColor->getColorObject($col0);
$model1 = $this->pdfColor->getColorObject($col1);
if (!$model0 instanceof \Com\Tecnick\Color\Model) {
continue;
}
if (!$model1 instanceof \Com\Tecnick\Color\Model) {
continue;
}
$col0 = $model0->getComponentsString();
$col1 = $model1->getComponentsString();
}
$encode[] = '0 1';
$offset = $nextcol['offset'] ?? null;
if ($idx < $lastcols && \is_float($offset)) {
$bounds[] = \sprintf('%F ', $offset);
}
$out .=
++$this->pon
. ' 0 obj'
. "\n"
. '<<'
. ' /FunctionType 2'
. ' /Domain [0 1]'
. ' /C0 ['
. $col0
. ']'
. ' /C1 ['
. $col1
. ']';
$exponent = $nextcol['exponent'] ?? null;
if (\is_float($exponent)) {
$out .= ' /N ' . $exponent;
}
$out .= ' >>' . "\n" . 'endobj' . "\n";
$funct[] = $this->pon . ' 0 R';
}
$out .=
++$this->pon
. ' 0 obj'
. "\n"
. '<<'
. ' /FunctionType 3'
. ' /Domain [0 1]'
. ' /Functions ['
. \implode(' ', $funct)
. ']'
. ' /Bounds ['
. \implode(' ', $bounds)
. ']'
. ' /Encode ['
. \implode(' ', $encode)
. ']'
. ' >>'
. "\n"
. 'endobj'
. "\n";
}
return $out . $this->getOutPatternObj($grad, $this->pon);
}
/**
* Get the PDF output string for the pattern and shading object
*
* @param GradientData $grad Array of gradient colors
* @param int $objref Reference object number
*
* @return string PDF command
*
* @throws \Com\Tecnick\Pdf\Encrypt\Exception
*/
protected function getOutPatternObj(array $grad, int $objref): string
{
// set shading object
if ($grad['transparency']) {
$grad['colspace'] = 'DeviceGray';
}
$oid = ++$this->pon;
$coords = $grad['coords'];
$out = $oid . ' 0 obj' . "\n" . '<< /ShadingType ' . $grad['type'] . ' /ColorSpace /' . $grad['colspace'];
if ($grad['background'] !== null) {
$out .= ' /Background [' . $grad['background']->getComponentsString() . ']';
}
if ($grad['antialias']) {
$out .= ' /AntiAlias true';
}
if ($grad['type'] === 2) {
$out .= \sprintf(
' /Coords [%F %F %F %F] /Domain [0 1] /Function %d 0 R /Extend [true true] >>' . "\n",
$coords[0] ?? 0.0,
$coords[1] ?? 0.0,
$coords[2] ?? 0.0,
$coords[3] ?? 0.0,
$objref,
);
} elseif ($grad['type'] === 3) {
// x0, y0, r0, x1, y1, r1
// the radius of the inner circle is 0
$out .= \sprintf(
' /Coords [%F %F 0 %F %F %F] /Domain [0 1] /Function %d 0 R /Extend [true true] >>' . "\n",
$coords[0] ?? 0.0,
$coords[1] ?? 0.0,
$coords[2] ?? 0.0,
$coords[3] ?? 0.0,
$coords[4] ?? 0.0,
$objref,
);
} elseif ($grad['type'] === 6) {
$stream = $this->encrypt->encryptString($grad['stream'], $this->pon);
$out .=
' /BitsPerCoordinate 16 /BitsPerComponent 8/Decode[0 1 0 1 0 1 0 1 0 1] /BitsPerFlag 8 /Length '
. \strlen($stream)
. ' >>'
. "\n"
. ' stream'
. "\n"
. $stream
. "\n"
. 'endstream'
. "\n";
}
$out .= 'endobj' . "\n";
// pattern object
$out .=
++$this->pon
. ' 0 obj'
. "\n"
. '<<'
. ' /Type /Pattern'
. ' /PatternType 2'
. ' /Shading '
. $oid
. ' 0 R'
. ' >>'
. "\n"
. 'endobj'
. "\n";
return $out;
}
/**
* Get the PDF output string for gradient shaders
*
* @param int $pon Current PDF Object Number
*
* @return string PDF command
*
* @throws \Com\Tecnick\Pdf\Encrypt\Exception
*/
public function getOutGradientShaders(int $pon): string
{
$this->pon = $pon;
if ($this->pdfa || $this->gradients === []) {
return '';
}
$idt = \count($this->gradients); // index for transparency gradients
$out = '';
foreach ($this->gradients as $idx => $grad) {
$gcol = $this->getOutGradientCols($grad, 'color');
if ($gcol !== '') {
$out .= $gcol;
$this->gradients[$idx]['id'] = $this->pon - 1;
$this->gradients[$idx]['pattern'] = $this->pon;
}
$gopa = $this->getOutGradientCols($grad, 'opacity');
$idgs = $idx + $idt;
if ($gopa !== '') {
$out .= $gopa;
$this->gradientMasks[$idgs] = [
'id' => $this->pon - 1,
'pattern' => $this->pon,
];
}
if ($grad['transparency']) {
$mask = $this->gradientMasks[$idgs] ?? null;
if ($mask === null) {
// no transparency pattern was generated: skip without emitting a partial object
continue;
}
$oid = ++$this->pon;
$pwidth = $this->pagew * $this->kunit;
$pheight = $this->pageh * $this->kunit;
$rect = \sprintf('%F %F', $pwidth, $pheight);
$out .= $oid . ' 0 obj' . "\n" . '<< /Type /XObject /Subtype /Form /FormType 1';
$stream = 'q /a0 gs /Pattern cs /p' . $idgs . ' scn 0 0 ' . $pwidth . ' ' . $pheight . ' re f Q';
if ($this->compress) {
$cmpstream = \gzcompress($stream);
if ($cmpstream !== false) {
$stream = $cmpstream;
$out .= ' /Filter /FlateDecode';
}
}
$stream = $this->encrypt->encryptString($stream, $oid);
$out .=
' /Length '
. \strlen($stream)
. ' /BBox [0 0 '
. $rect
. ']'
. ' /Group << /Type /Group /S /Transparency /CS /DeviceGray >>'
. ' /Resources <<'
. ' /ExtGState << /a0 << /ca 1 /CA 1 >> >>'
. ' /Pattern << /p'
. $idgs
. ' '
. $mask['pattern']
. ' 0 R >>'
. ' >>'
. ' >>'
. "\n"
. ' stream'
. "\n"
. $stream
. "\n"
. 'endstream'
. "\n"
. 'endobj'
. "\n";
// SMask
$objsm = ++$this->pon;
$out .=
$objsm
. ' 0 obj'
. "\n"
. '<<'
. ' /Type /Mask'
. ' /S /Luminosity'
. ' /G '
. $oid
. ' 0 R'
. ' >>'
. "\n"
. 'endobj'
. "\n";
// ExtGState
$objext = ++$this->pon;
$out .=
$objext
. ' 0 obj'
. "\n"
. '<<'
. ' /Type /ExtGState'
. ' /SMask '
. $objsm
. ' 0 R'
. ' /AIS false'
. ' >>'
. "\n"
. 'endobj'
. "\n";
$this->extgstates[] = [
'n' => $objext,
'name' => 'TGS' . $idx,
// Record the soft mask so this entry is recognised as carrying
// actual transparency (see getTransparencyExtGStateNames()).
'parms' => [
'SMask' => $objsm . ' 0 R',
],
];
}
}
return $out;
}
}
+90
View File
@@ -0,0 +1,90 @@
<?php
declare(strict_types=1);
/**
* BlendMode.php
*
* @since 2026-07-17
* @category Library
* @package PdfGraph
* @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-graph
*
* This file is part of tc-lib-pdf-graph software library.
*/
namespace Com\Tecnick\Pdf\Graph;
/**
* Com\Tecnick\Pdf\Graph\BlendMode
*
* Backed enum for the PDF blend modes (PDF 32000-1:2008 - 11.3.5). The backing
* value of each case is the canonical /BM name validated by Gradient::getAlpha().
*
* @since 2026-07-17
* @category Library
* @package PdfGraph
* @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-graph
*/
enum BlendMode: string
{
case Normal = 'Normal';
case Multiply = 'Multiply';
case Screen = 'Screen';
case Overlay = 'Overlay';
case Darken = 'Darken';
case Lighten = 'Lighten';
case ColorDodge = 'ColorDodge';
case ColorBurn = 'ColorBurn';
case HardLight = 'HardLight';
case SoftLight = 'SoftLight';
case Difference = 'Difference';
case Exclusion = 'Exclusion';
case Hue = 'Hue';
case Saturation = 'Saturation';
case Color = 'Color';
case Luminosity = 'Luminosity';
/**
* Resolve a loose blend mode value to the matching enum case.
*
* Accepts an enum instance (returned unchanged) or a string (with an
* optional leading '/' stripped, as PDF /BM names carry). Unknown values
* fall back to Normal, matching Gradient::getAlpha().
*
* @param string|self $value Blend mode name or enum case.
*/
public static function fromLoose(string|self $value): self
{
if ($value instanceof self) {
return $value;
}
if ($value !== '' && $value[0] === '/') {
$value = \substr($value, 1);
}
return self::tryFrom($value) ?? self::Normal;
}
}
+799
View File
@@ -0,0 +1,799 @@
<?php
declare(strict_types=1);
/**
* Draw.php
*
* @since 2011-05-23
* @category Library
* @package PdfGraph
* @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-graph
*
* This file is part of tc-lib-pdf-graph software library.
*/
namespace Com\Tecnick\Pdf\Graph;
use Com\Tecnick\Pdf\Graph\Exception as GraphException;
/**
* Com\Tecnick\Pdf\Graph\Draw
*
* @since 2011-05-23
* @category Library
* @package PdfGraph
* @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-graph
*
* @phpstan-import-type StyleDataOpt from \Com\Tecnick\Pdf\Graph\Base
*
* @SuppressWarnings("PHPMD.ExcessiveClassComplexity")
*/
class Draw extends \Com\Tecnick\Pdf\Graph\Gradient
{
/**
* Draws a line between two points.
*
* @param float $posx1 Abscissa of first point.
* @param float $posy1 Ordinate of first point.
* @param float $posx2 Abscissa of second point.
* @param float $posy2 Ordinate of second point.
* @param StyleDataOpt $style Line style to apply.
*
* @return string PDF command
*/
public function getLine(float $posx1, float $posy1, float $posx2, float $posy2, array $style = []): string
{
return (
$this->getStyleCmd($style)
. $this->getRawPoint($posx1, $posy1)
. $this->getRawLine($posx2, $posy2)
. $this->getPathPaintOp('S')
);
}
/**
* Draws a Bezier curve.
* The Bezier curve is a tangent to the line between the control points at either end of the curve.
*
* @param float $posx0 Abscissa of start point.
* @param float $posy0 Ordinate of start point.
* @param float $posx1 Abscissa of control point 1.
* @param float $posy1 Ordinate of control point 1.
* @param float $posx2 Abscissa of control point 2.
* @param float $posy2 Ordinate of control point 2.
* @param float $posx3 Abscissa of end point.
* @param float $posy3 Ordinate of end point.
* @param string|PathPaintOp $mode Mode of rendering. @see getPathPaintOp()
* @param StyleDataOpt $style Style.
*
* @return string PDF command
*
* @SuppressWarnings("PHPMD.ExcessiveParameterList")
*/
public function getCurve(
float $posx0,
float $posy0,
float $posx1,
float $posy1,
float $posx2,
float $posy2,
float $posx3,
float $posy3,
string|PathPaintOp $mode = 'S',
array $style = [],
): string {
return (
$this->getStyleCmd($style)
. $this->getRawPoint($posx0, $posy0)
. $this->getRawCurve($posx1, $posy1, $posx2, $posy2, $posx3, $posy3)
. $this->getPathPaintOp($mode)
);
}
/**
* Draws a poly-Bezier curve.
* Each Bezier curve segment is a tangent to the line between the control points at either end of the curve.
*
* @param float $posx0 Abscissa of start point.
* @param float $posy0 Ordinate of start point.
* @param array<array<float>> $segments An array of bezier descriptions. Format: array(x1, y1, x2, y2, x3, y3).
* @param string|PathPaintOp $mode Mode of rendering. @see getPathPaintOp()
* @param StyleDataOpt $style Style.
*
* @return string PDF command
*/
public function getPolycurve(
float $posx0,
float $posy0,
array $segments,
string|PathPaintOp $mode = 'S',
array $style = [],
): string {
$out = $this->getStyleCmd($style) . $this->getRawPoint($posx0, $posy0);
foreach ($segments as $segment) {
if (!isset($segment[0], $segment[1], $segment[2], $segment[3], $segment[4], $segment[5])) {
continue;
}
$posx1 = $segment[0];
$posy1 = $segment[1];
$posx2 = $segment[2];
$posy2 = $segment[3];
$posx3 = $segment[4];
$posy3 = $segment[5];
$out .= $this->getRawCurve($posx1, $posy1, $posx2, $posy2, $posx3, $posy3);
}
return $out . $this->getPathPaintOp($mode);
}
/**
* Draws an ellipse.
* An ellipse is formed from n Bezier curves.
*
* @param float $posx Abscissa of center point.
* @param float $posy Ordinate of center point.
* @param float $hrad Horizontal radius.
* @param float $vrad Vertical radius.
* @param float $angle Angle oriented (anti-clockwise). Default value: 0.
* @param float $angs Angle in degrees at which starting drawing.
* @param float $angf Angle in degrees at which stop drawing.
* @param string|PathPaintOp $mode Mode of rendering. @see getPathPaintOp()
* @param StyleDataOpt $style Style.
* @param int $ncv Number of curves used to draw a 90 degrees portion of ellipse.
*
* @return string PDF command
*
* @SuppressWarnings("PHPMD.ExcessiveParameterList")
*/
public function getEllipse(
float $posx,
float $posy,
float $hrad,
float $vrad = 0,
float $angle = 0,
float $angs = 0,
float $angf = 360,
string|PathPaintOp $mode = 'S',
array $style = [],
int $ncv = 2,
): string {
if ($vrad === 0.0) {
$vrad = $hrad;
}
return (
$this->getStyleCmd($style)
. $this->getRawEllipticalArc(
$posx,
$posy,
$hrad,
$vrad,
$angle,
$angs,
$angf,
false,
$ncv,
true,
true,
false,
)
. $this->getPathPaintOp($mode)
);
}
/**
* Draws a circle.
* A circle is formed from n Bezier curves.
*
* @param float $posx Abscissa of center point.
* @param float $posy Ordinate of center point.
* @param float $rad Radius.
* @param float $angs Angle in degrees at which starting drawing.
* @param float $angf Angle in degrees at which stop drawing.
* @param string|PathPaintOp $mode Mode of rendering. @see getPathPaintOp()
* @param StyleDataOpt $style Style.
* @param int $ncv Number of curves used to draw a 90 degrees portion of ellipse.
*
* @return string PDF command
*/
public function getCircle(
float $posx,
float $posy,
float $rad,
float $angs = 0,
float $angf = 360,
string|PathPaintOp $mode = 'S',
array $style = [],
int $ncv = 2,
): string {
return $this->getEllipse($posx, $posy, $rad, $rad, 0, $angs, $angf, $mode, $style, $ncv);
}
/**
* Draws a circle pie sector.
*
* @param float $posx Abscissa of center point.
* @param float $posy Ordinate of center point.
* @param float $rad Radius.
* @param float $angs Angle in degrees at which starting drawing.
* @param float $angf Angle in degrees at which stop drawing.
* @param string|PathPaintOp $mode Mode of rendering. @see getPathPaintOp()
* @param StyleDataOpt $style Style.
* @param int $ncv Number of curves used to draw a 90 degrees portion of ellipse.
*
* @return string PDF command
*/
public function getPieSector(
float $posx,
float $posy,
float $rad,
float $angs = 0,
float $angf = 360,
string|PathPaintOp $mode = 'FD',
array $style = [],
int $ncv = 2,
): string {
return (
$this->getStyleCmd($style)
. $this->getRawEllipticalArc($posx, $posy, $rad, $rad, 0, $angs, $angf, true, $ncv, true, true, false)
. $this->getPathPaintOp($mode)
);
}
/**
* Draws a basic polygon.
*
* @param array<float> $points Points - array containing 4 points for each segment: (x0, y0, x1, y1, x2, y2, ...)
* @param string|PathPaintOp $mode Mode of rendering. @see getPathPaintOp()
* @param StyleDataOpt $style Style.
*
* @return string PDF command
*/
public function getBasicPolygon(array $points, string|PathPaintOp $mode = 'S', array $style = []): string
{
$nco = \count($points); // number of coordinates
if ($nco < 4 || ($points[0] ?? null) === null || ($points[1] ?? null) === null) {
return ''; // need at least 2 points (4 coordinates)
}
$out = $this->getStyleCmd($style) . $this->getRawPoint($points[0], $points[1]);
for ($idx = 2; $idx < $nco; $idx += 2) {
if (($points[$idx] ?? null) === null || ($points[$idx + 1] ?? null) === null) {
continue;
}
$posx = $points[$idx] ?? 0.0;
$posy = $points[$idx + 1] ?? 0.0;
$out .= $this->getRawLine($posx, $posy);
}
return $out . $this->getPathPaintOp($mode);
}
/**
* Returns the polygon default style command and initialize the first segment style if missing.
*
* @param array<StyleDataOpt> $styles Array of styles -
* one style entry for each polygon segment and/or one global "all" entry.
*
* @return string PDF command
*/
protected function getDefaultSegStyle(array $styles = []): string
{
$out = '';
$styleAll = $styles['all'] ?? [];
if ($styleAll !== []) {
$out .= $this->getStyleCmd($styleAll);
}
return $out;
}
/**
* Draws a polygon with a different style for each segment.
*
* @param array<float> $points Points - array with values (x0, y0, x1, y1,..., x(n-1), y(n-1))
* @param string|PathPaintOp $mode Mode of rendering. @see getPathPaintOp()
* @param array<StyleDataOpt> $styles Array of styles -
* one style entry for each polygon segment and/or one global "all" entry.
*
* @return string PDF command
*
* @SuppressWarnings("PHPMD.CyclomaticComplexity")
* @SuppressWarnings("PHPMD.NPathComplexity")
*/
public function getPolygon(array $points, string|PathPaintOp $mode = 'S', array $styles = []): string
{
if ($mode instanceof PathPaintOp) {
$mode = $mode->value;
}
$nco = \count($points); // number of points
if ($nco < 6 || ($points[0] ?? null) === null || ($points[1] ?? null) === null) {
return ''; // we need at least 3 points
}
$nseg = (int) ($nco / 2); // number of segments (including the closing one)
$out = $this->getDefaultSegStyle($styles);
$lastx = $points[$nco - 2] ?? null;
$lasty = $points[$nco - 1] ?? null;
if (
$this->isClosingMode($mode)
&& $lastx !== null
&& $lasty !== null
&& ($lastx !== $points[0] || $lasty !== $points[1])
) {
// close polygon by adding the first point (x, y) at the end
$points[$nco++] = $points[0];
$points[$nco++] = $points[1];
$style0 = $styles[0] ?? [];
if ($style0 !== []) {
// copy style for the last segment
$styles[$nseg - 1] = $style0;
}
}
// paint the filling
if ($this->isFillingMode($mode)) {
$out .= $this->getBasicPolygon($points, $this->getModeWithoutStroke($mode));
if ($this->isClippingMode($mode)) {
return $out;
}
}
if (!$this->isStrokingMode($mode)) {
return $out;
}
// When the outline is uniformly styled (no per-segment style overrides),
// stroke it as a single continuous path so that adjacent edges are joined
// at the vertices (miter/round/bevel) instead of being drawn as
// independent, butt-capped segments that would leave the corners open.
$hasSegmentStyles = false;
foreach ($styles as $skey => $sval) {
if (!\is_int($skey) || $sval === []) {
continue;
}
$hasSegmentStyles = true;
break;
}
if (!$hasSegmentStyles) {
$closed = $points[0] === ($points[$nco - 2] ?? null) && $points[1] === ($points[$nco - 1] ?? null);
return $out . $this->getBasicPolygon($points, $closed ? 's' : 'S');
}
$nco -= 3;
// paint the outline
for ($idx = 0; $idx < $nco; $idx += 2) {
$segid = (int) ($idx / 2);
$styles[$segid] ??= [];
if (
($points[$idx] ?? null) === null
|| ($points[$idx + 1] ?? null) === null
|| ($points[$idx + 2] ?? null) === null
|| ($points[$idx + 3] ?? null) === null
) {
continue;
}
$posx1 = $points[$idx] ?? 0.0;
$posy1 = $points[$idx + 1] ?? 0.0;
$posx2 = $points[$idx + 2] ?? 0.0;
$posy2 = $points[$idx + 3] ?? 0.0;
$segstyle = $styles[$segid] ?? [];
$out .= $this->getLine($posx1, $posy1, $posx2, $posy2, $segstyle);
}
return $out;
}
/**
* Draws a regular polygon.
*
* @param float $posx Abscissa of center point.
* @param float $posy Ordinate of center point.
* @param float $radius Radius of inscribed circle.
* @param int $sides Number of sides.
* @param float $angle Angle of the orientation (anti-clockwise).
* @param string|PathPaintOp $mode Mode of rendering. @see getPathPaintOp()
* @param array<StyleDataOpt> $styles Array of styles -
* one style entry for each polygon segment and/or one global "all" entry.
* @param string|PathPaintOp $cirmode Mode of rendering of the inscribed circle (if any). @see getPathPaintOp()
* @param StyleDataOpt $cirstyle Style of inscribed circle.
*
* @return string PDF command
*/
public function getRegularPolygon(
float $posx,
float $posy,
float $radius,
int $sides,
float $angle = 0,
string|PathPaintOp $mode = 'S',
array $styles = [],
string|PathPaintOp $cirmode = '',
array $cirstyle = [],
): string {
if ($sides < 3) { // triangle is the minimum polygon
return '';
}
$out = '';
if ($cirmode !== '') {
$out .= $this->getCircle($posx, $posy, $radius, 0, 360, $cirmode, $cirstyle);
}
$points = [];
for ($idx = 0; $idx < $sides; ++$idx) {
$angrad = $this->degToRad($angle + (($idx * 360) / $sides));
$points[] = $posx + ($radius * \sin($angrad));
$points[] = $posy + ($radius * \cos($angrad));
}
return $out . $this->getPolygon($points, $mode, $styles);
}
/**
* Draws a star polygon.
*
* @param float $posx Abscissa of center point.
* @param float $posy Ordinate of center point.
* @param float $radius Radius of inscribed circle.
* @param int $nvert Number of vertices.
* @param int $ngaps Number of gaps (if ($ngaps % $nvert = 1) then is a regular polygon).
* @param float $angle Angle oriented (anti-clockwise).
* @param string|PathPaintOp $mode Mode of rendering. @see getPathPaintOp()
* @param array<StyleDataOpt> $styles Array of styles -
* one style entry for each polygon segment and/or one global "all" entry.
* @param string|PathPaintOp $cirmode Mode of rendering of the inscribed circle (if any). @see getPathPaintOp()
* @param StyleDataOpt $cirstyle Style of inscribed circle.
*
* @return string PDF command
*
* @SuppressWarnings("PHPMD.ExcessiveParameterList")
*/
public function getStarPolygon(
float $posx,
float $posy,
float $radius,
int $nvert,
int $ngaps,
float $angle = 0,
string|PathPaintOp $mode = 'S',
array $styles = [],
string|PathPaintOp $cirmode = '',
array $cirstyle = [],
): string {
if ($nvert < 2) {
return '';
}
$out = '';
if ($cirmode !== '') {
$out .= $this->getCircle($posx, $posy, $radius, 0, 360, $cirmode, $cirstyle);
}
$points = [];
$visited = [];
$idx = 0;
while ($idx >= 0 && !isset($visited[$idx])) {
$visited[$idx] = true;
$angrad = $this->degToRad($angle + (($idx * 360) / $nvert));
$points[] = $posx + ($radius * \sin($angrad));
$points[] = $posy + ($radius * \cos($angrad));
$idx = ($idx + $ngaps) % $nvert;
}
if (\count($points) < 6) {
return $out;
}
return $out . $this->getPolygon($points, $mode, $styles);
}
/**
* Draws a rectangle with a different style for each segment.
*
* @param float $posx Abscissa of upper-left corner.
* @param float $posy Ordinate of upper-left corner.
* @param float $width Width.
* @param float $height Height.
* @param string|PathPaintOp $mode Mode of rendering. @see getPathPaintOp()
* @param array<StyleDataOpt> $styles Array of styles -
* one style entry for each side (T,R,B,L) and/or one global "all" entry.
*
* @return string PDF command
*/
public function getRect(
float $posx,
float $posy,
float $width,
float $height,
string|PathPaintOp $mode = 'S',
array $styles = [],
): string {
$points = [
$posx,
$posy,
$posx + $width,
$posy,
$posx + $width,
$posy + $height,
$posx,
$posy + $height,
$posx,
$posy,
];
return $this->getPolygon($points, $mode, $styles);
}
/**
* Draws a rounded rectangle.
*
* @param float $posx Abscissa of upper-left corner.
* @param float $posy Ordinate of upper-left corner.
* @param float $width Width.
* @param float $height Height.
* @param float $hrad X-axis radius of the ellipse used to round off the corners of the rectangle.
* @param float $vrad Y-axis radius of the ellipse used to round off the corners of the rectangle.
* @param string $corner Round corners to draw: 0 (square i-corner) or 1 (rounded i-corner) in i-position.
* Positions are in the following order: top right, bottom right, bottom left and
* top left.
* @param string|PathPaintOp $mode Mode of rendering. @see getPathPaintOp()
* @param StyleDataOpt $style Style.
*
* @return string PDF command
*
* @SuppressWarnings("PHPMD.CyclomaticComplexity")
* @SuppressWarnings("PHPMD.NPathComplexity")
*/
public function getRoundedRect(
float $posx,
float $posy,
float $width,
float $height,
float $hrad,
float $vrad,
string $corner = '1111',
string|PathPaintOp $mode = 'S',
array $style = [],
): string {
if ($corner === '0000' || $hrad === 0.0 && $vrad === 0.0) {
// basic rectangle with straight corners
return $this->getBasicRect($posx, $posy, $width, $height, $mode, $style);
}
$out = $this->getStyleCmd($style);
$out .= $corner[3] !== '0' ? $this->getRawPoint($posx + $hrad, $posy) : $this->getRawPoint($posx, $posy);
$posxc = $posx + $width - $hrad;
$posyc = $posy + $vrad;
$out .= $this->getRawLine($posxc, $posy);
$arc = (4 / 3) * (\sqrt(2) - 1);
$harc = $hrad * $arc;
$varc = $vrad * $arc;
$out .= $corner[0] !== '0'
? $this->getRawCurve($posxc + $harc, $posyc - $vrad, $posxc + $hrad, $posyc - $varc, $posxc + $hrad, $posyc)
: $this->getRawLine($posx + $width, $posy);
$posxc = $posx + $width - $hrad;
$posyc = $posy + $height - $vrad;
$out .= $this->getRawLine($posx + $width, $posyc);
$out .= $corner[1] !== '0'
? $this->getRawCurve($posxc + $hrad, $posyc + $varc, $posxc + $harc, $posyc + $vrad, $posxc, $posyc + $vrad)
: $this->getRawLine($posx + $width, $posy + $height);
$posxc = $posx + $hrad;
$posyc = $posy + $height - $vrad;
$out .= $this->getRawLine($posxc, $posy + $height);
$out .= $corner[2] !== '0'
? $this->getRawCurve($posxc - $harc, $posyc + $vrad, $posxc - $hrad, $posyc + $varc, $posxc - $hrad, $posyc)
: $this->getRawLine($posx, $posy + $height);
$posxc = $posx + $hrad;
$posyc = $posy + $vrad;
$out .= $this->getRawLine($posx, $posyc);
$out .= $corner[3] !== '0'
? $this->getRawCurve($posxc - $hrad, $posyc - $varc, $posxc - $harc, $posyc - $vrad, $posxc, $posyc - $vrad)
: $this->getRawLine($posx, $posy);
return $out . $this->getPathPaintOp($mode);
}
/**
* Draws an arrow.
*
* @param float $posx0 Abscissa of first point.
* @param float $posy0 Ordinate of first point.
* @param float $posx1 Abscissa of second point (head side).
* @param float $posy1 Ordinate of second point (head side)
* @param int $headmode Arrow head mode:
* 0 = draw only
* head arms; 1 =
* draw closed head
* without filling;
* 2 = closed and
* filled head; 3 =
* filled head.
* @param float $armsize Length of head arms.
* @param int $armangle Angle between an head arm and the arrow shaft.
* @param StyleDataOpt $style Line style to apply.
*
* @return string PDF command
*/
public function getArrow(
float $posx0,
float $posy0,
float $posx1,
float $posy1,
int $headmode = 0,
float $armsize = 5,
int $armangle = 15,
array $style = [],
): string {
// getting arrow direction angle; 0 deg angle is when both arms go along X axis; angle grows clockwise.
$dir_angle = \atan2($posy0 - $posy1, $posx0 - $posx1);
if ($dir_angle < 0) {
$dir_angle += 2 * self::MPI;
}
$armangle = $this->degToRad($armangle);
$sx1 = $posx1;
$sy1 = $posy1;
if ($headmode > 0) {
// calculate the stopping point for the arrow shaft
$linewidth = $style['lineWidth'] ?? (float) $this->getLastStyleProperty('lineWidth', 0);
$sx1 = $posx1 + (($armsize - $linewidth) * \cos($dir_angle));
$sy1 = $posy1 + (($armsize - $linewidth) * \sin($dir_angle));
}
$out = $this->getStyleCmd($style);
// main arrow line / shaft
$out .= $this->getLine($posx0, $posy0, $sx1, $sy1);
// left arrowhead arm tip
$hxl = $posx1 + ($armsize * \cos($dir_angle + $armangle));
$hyl = $posy1 + ($armsize * \sin($dir_angle + $armangle));
// right arrowhead arm tip
$hxr = $posx1 + ($armsize * \cos($dir_angle - $armangle));
$hyr = $posy1 + ($armsize * \sin($dir_angle - $armangle));
$modemap = [
0 => 'S',
1 => 's',
2 => 'b',
3 => 'f',
];
$points = [$hxl, $hyl, $posx1, $posy1, $hxr, $hyr];
// The style was already emitted above and persists in the graphics
// state, so the arrowhead does not need to repeat it.
return $out . $this->getBasicPolygon($points, $modemap[$headmode] ?? 'S');
}
/**
* Get a registration mark.
*
* @param float $posx Abscissa of center point.
* @param float $posy Ordinate of center point.
* @param float $rad Radius.
* @param bool $double If true prints two concentric crop marks.
* @param string $color Color.
*
* @return string PDF command
*
* @throws \Com\Tecnick\Pdf\Graph\Exception
*/
public function getRegistrationMark(
float $posx,
float $posy,
float $rad,
bool $double = false,
string $color = 'all',
): string {
$style = [
'lineWidth' => \max(0.5 / $this->kunit, $rad / 30),
'lineCap' => 'butt',
'lineJoin' => 'miter',
'miterLimit' => 10.0 / $this->kunit,
'dashArray' => [],
'dashPhase' => 0,
'lineColor' => $color,
'fillColor' => $color,
];
$colobj = $this->pdfColor->getColorObject($color);
if (!$colobj instanceof \Com\Tecnick\Color\Model) {
throw new GraphException('Unknown color: ' . $color);
}
$out =
$colobj->getPdfColor()
. $this->getPieSector($posx, $posy, $rad, 90, 180, 'F')
. $this->getPieSector($posx, $posy, $rad, 270, 360, 'F')
. $this->getCircle($posx, $posy, $rad, 0, 360, 'S', [], 8);
if ($double) {
$radi = $rad * 0.5;
$out .=
$colobj->invertColor()->getPdfColor()
. $this->getPieSector($posx, $posy, $radi, 90, 180, 'F')
. $this->getPieSector($posx, $posy, $radi, 270, 360, 'F')
. $this->getCircle($posx, $posy, $radi, 0, 360, 'S', [], 8)
. $colobj->getPdfColor()
. $this->getPieSector($posx, $posy, $radi, 0, 90, 'F')
. $this->getPieSector($posx, $posy, $radi, 180, 270, 'F')
. $this->getCircle($posx, $posy, $radi, 0, 360, 'S', [], 8);
}
return $this->getStartTransform() . $this->getStyleCmd($style) . $out . $this->getStopTransform();
}
/**
* Get a CMYK registration mark.
*
* @param float $posx Abscissa of center point.
* @param float $posy Ordinate of center point.
* @param float $rad Radius.
*
* @return string PDF command
*/
public function getCmykRegistrationMark(float $posx, float $posy, float $rad): string
{
// internal radius
$radi = $rad * 0.6;
// external radius
$rade = $rad * 1.3;
// line style for external circle
$style = [
'lineWidth' => \max(0.5 / $this->kunit, $rad / 30),
'lineCap' => 'butt',
'lineJoin' => 'miter',
'miterLimit' => 10.0 / $this->kunit,
'dashArray' => [],
'dashPhase' => 0,
'lineColor' => 'All',
'fillColor' => '',
];
$cyan = $this->pdfColor->getColorObject('Cyan');
$magenta = $this->pdfColor->getColorObject('Magenta');
$yellow = $this->pdfColor->getColorObject('Yellow');
$key = $this->pdfColor->getColorObject('Key');
return (
$this->getStartTransform()
. ($cyan instanceof \Com\Tecnick\Color\Model ? $cyan->getPdfColor() : '')
. $this->getPieSector($posx, $posy, $radi, 270, 360, 'F')
. ($magenta instanceof \Com\Tecnick\Color\Model ? $magenta->getPdfColor() : '')
. $this->getPieSector($posx, $posy, $radi, 0, 90, 'F')
. ($yellow instanceof \Com\Tecnick\Color\Model ? $yellow->getPdfColor() : '')
. $this->getPieSector($posx, $posy, $radi, 90, 180, 'F')
. ($key instanceof \Com\Tecnick\Color\Model ? $key->getPdfColor() : '')
. $this->getPieSector($posx, $posy, $radi, 180, 270, 'F')
. $this->getStyleCmd($style)
. $this->getCircle($posx, $posy, $rad, 0, 360, 'S', [], 8)
. $this->getLine($posx, $posy - $rade, $posx, $posy - $radi)
. $this->getLine($posx, $posy + $radi, $posx, $posy + $rade)
. $this->getLine($posx - $rade, $posy, $posx - $radi, $posy)
. $this->getLine($posx + $radi, $posy, $posx + $rade, $posy)
. $this->getStopTransform()
);
}
}
+34
View File
@@ -0,0 +1,34 @@
<?php
declare(strict_types=1);
/**
* Exception.php
*
* @since 2011-05-23
* @category Library
* @package PdfGraph
* @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-graph
*
* This file is part of tc-lib-pdf-graph software library.
*/
namespace Com\Tecnick\Pdf\Graph;
/**
* Com\Tecnick\Pdf\Graph\Exception
*
* Custom Exception class
*
* @since 2011-05-23
* @category Library
* @package PdfGraph
* @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-graph
*/
class Exception extends \Exception {}
+930
View File
@@ -0,0 +1,930 @@
<?php
declare(strict_types=1);
/**
* Gradient.php
*
* @since 2011-05-23
* @category Library
* @package PdfGraph
* @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-graph
*
* This file is part of tc-lib-pdf-graph software library.
*/
namespace Com\Tecnick\Pdf\Graph;
use Com\Tecnick\Color\ColorModelType;
use Com\Tecnick\Pdf\Graph\Exception as GraphException;
/**
* Com\Tecnick\Pdf\Graph\Gradient
*
* @since 2011-05-23
* @category Library
* @package PdfGraph
* @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-graph
*
* @phpstan-import-type GradientData from \Com\Tecnick\Pdf\Graph\Base
* @phpstan-import-type StyleDataOpt from \Com\Tecnick\Pdf\Graph\Base
*
* @SuppressWarnings("PHPMD.ExcessiveClassComplexity")
*/
abstract class Gradient extends \Com\Tecnick\Pdf\Graph\Raw
{
/**
* Returns the gradients array
*
* @return array<int, GradientData>
*/
public function getGradientsArray(): array
{
return $this->gradients;
}
/**
* Draws a basic rectangle
*
* @param float $posx Abscissa of upper-left corner.
* @param float $posy Ordinate of upper-left corner.
* @param float $width Width.
* @param float $height Height.
* @param string|PathPaintOp $mode Mode of rendering (or PathPaintOp enum case). @see getPathPaintOp()
* @param StyleDataOpt $style Style.
*
* @return string PDF command
*/
public function getBasicRect(
float $posx,
float $posy,
float $width,
float $height,
string|PathPaintOp $mode = 'S',
array $style = [],
): string {
return $this->getStyleCmd($style) . $this->getRawRect($posx, $posy, $width, $height, $mode);
}
/**
* Get a linear colour gradient command.
*
* @param float $posx Abscissa of the top left corner of the rectangle.
* @param float $posy Ordinate of the top left corner of the rectangle.
* @param float $width Width of the rectangle.
* @param float $height Height of the rectangle.
* @param string $colorstart Starting color.
* @param string $colorend Ending color.
* @param array<float> $coords Gradient vector (x1, y1, x2, y2).
*
* @return string PDF command
*
* @throws \Com\Tecnick\Pdf\Graph\Exception
*/
public function getLinearGradient(
float $posx,
float $posy,
float $width,
float $height,
string $colorstart,
string $colorend,
array $coords = [0, 0, 1, 0],
): string {
return (
$this->getStartTransform()
. $this->getClippingRect($posx, $posy, $width, $height)
. $this->getGradientTransform($posx, $posy, $width, $height)
. $this->getGradient(
2,
$coords,
[
[
'color' => $colorstart,
'exponent' => 1.0,
'offset' => 0.0,
'opacity' => 1.0,
],
[
'color' => $colorend,
'exponent' => 1.0,
'offset' => 1.0,
'opacity' => 1.0,
],
],
'',
false,
)
. $this->getStopTransform()
);
}
/**
* Get a radial colour gradient command.
*
* @param float $posx Abscissa of the top left corner of the rectangle.
* @param float $posy Ordinate of the top left corner of the rectangle.
* @param float $width Width of the rectangle.
* @param float $height Height of the rectangle.
* @param string $colorstart Starting color.
* @param string $colorend Ending color.
* @param array<float> $coords Array of the form (fx, fy, cx, cy, r) where
* (fx, fy) is the starting point of the
* gradient with $colorstart (which should be
* inside the circle), (cx, cy) is the center of the
* circle with $colorend, and r is the radius
* of the circle.
*
* @return string PDF command
*
* @throws \Com\Tecnick\Pdf\Graph\Exception
*/
public function getRadialGradient(
float $posx,
float $posy,
float $width,
float $height,
string $colorstart,
string $colorend,
array $coords = [0.5, 0.5, 0.5, 0.5, 1],
): string {
return (
$this->getStartTransform()
. $this->getClippingRect($posx, $posy, $width, $height)
. $this->getGradientTransform($posx, $posy, $width, $height)
. $this->getGradient(
3,
$coords,
[
[
'color' => $colorstart,
'exponent' => 1.0,
'offset' => 0.0,
'opacity' => 1.0,
],
[
'color' => $colorend,
'exponent' => 1.0,
'offset' => 1.0,
'opacity' => 1.0,
],
],
'',
false,
)
. $this->getStopTransform()
);
}
/**
* Rectangular clipping area.
*
* @param float $posx Abscissa of the top left corner of the rectangle.
* @param float $posy Ordinate of the top left corner of the rectangle.
* @param float $width Width of the rectangle.
* @param float $height Height of the rectangle.
* @param bool $eoclip If true, set clipping path using even-odd rule.
*/
public function getClippingRect(float $posx, float $posy, float $width, float $height, bool $eoclip = false): string
{
$mode = $eoclip ? 'CEO' : 'CNZ';
return $this->getRawRect($posx, $posy, $width, $height, $mode);
}
/**
* Returns the transformation command that maps a gradient onto a rectangular area.
*
* @param float $posx Abscissa of the top left corner of the rectangle.
* @param float $posy Ordinate of the top left corner of the rectangle.
* @param float $width Width of the rectangle.
* @param float $height Height of the rectangle.
*/
public function getGradientTransform(float $posx, float $posy, float $width, float $height): string
{
$ctm = [
$width * $this->kunit,
0,
0,
$height * $this->kunit,
$posx * $this->kunit,
($this->pageh - ($posy + $height)) * $this->kunit,
];
return $this->getTransformation($ctm);
}
/**
* Get a color gradient PDF command.
*
* @param int $type Type of gradient (Not all types are currently supported):
* 1 = Function-based shading; 2 = Axial shading; 3 = Radial
* shading; 4 = Free-form Gouraud-shaded triangle mesh; 5 =
* Lattice-form Gouraud-shaded triangle mesh; 6 = Coons
* patch mesh; 7 Tensor-product patch mesh
* @param array<float> $coords Array of coordinates.
* @param array<int, array{
* 'color': string,
* 'exponent'?: float,
* 'opacity'?: float,
* 'offset'?: float,
* }> $stops Array gradient color components:
* color = color; offset = (0 to 1)
* represents a location along the
* gradient vector; exponent =
* exponent of the exponential
* interpolation function (default
* = 1).
* @param string $bgcolor Background color
* @param bool $antialias Flag indicating whether to filter the
* shading function to prevent aliasing artifacts.
*
* @return string PDF command
*
* @throws \Com\Tecnick\Pdf\Graph\Exception
*/
public function getGradient(
int $type,
array $coords,
array $stops,
string $bgcolor,
bool $antialias = false,
): string {
if ($this->pdfa) {
return '';
}
if (!isset($stops[0]['color'])) {
throw new GraphException('Invalid gradient stops');
}
$model = $this->pdfColor->getColorObject($stops[0]['color']);
if (!$model instanceof \Com\Tecnick\Color\Model) {
throw new GraphException('Invalid color');
}
$colspace = match ($model->getTypeEnum()) {
ColorModelType::Cmyk => 'DeviceCMYK',
ColorModelType::Gray => 'DeviceGray',
default => 'DeviceRGB',
};
$ngr = 1 + \count($this->gradients);
$this->gradients[$ngr] = $this->getGradientStops([
'antialias' => $antialias,
'background' => $this->pdfColor->getColorObject($bgcolor),
'colors' => [],
'colspace' => $colspace,
'coords' => $coords,
'id' => 0,
'pattern' => 0,
'stream' => '',
'transparency' => false,
'type' => $type,
], $stops);
$out = '';
if ($this->gradients[$ngr]['transparency']) {
// paint luminosity gradient
$out .= '/TGS' . $ngr . ' gs' . "\n";
}
// paint the gradient
$out .= '/Sh' . $ngr . ' sh' . "\n";
return $out;
}
/**
* Returns the last gradient ID to be used with XObjects.
*
* @return ?int
*/
public function getLastGradientID(): ?int
{
return \array_key_last($this->gradients);
}
/**
* Process the gradient stops.
*
* @param GradientData $grad Array containing gradient info
* @param array<int, array{
* 'color': string,
* 'exponent'?: float,
* 'opacity'?: float,
* 'offset'?: float,
* }> $stops Array gradient color components:
* color = color;
* offset = (0 to 1) represents a location along the gradient vector;
* exponent = exponent of the exponential interpolation function (default = 1).
*
* @return GradientData Gradient array.
*/
protected function getGradientStops(array $grad, array $stops): array
{
$num_stops = \count($stops);
$last_stop_id = $num_stops - 1;
foreach ($stops as $key => $stop) {
$grad['colors'][$key] = ['color' => $stop['color']];
$grad['colors'][$key]['exponent'] = 1.0;
if (array_key_exists('exponent', $stop)) {
// exponent for the interpolation function
$grad['colors'][$key]['exponent'] = $stop['exponent'];
}
$grad['colors'][$key]['opacity'] = 1.0;
if (array_key_exists('opacity', $stop)) {
$grad['colors'][$key]['opacity'] = $stop['opacity'];
$grad['transparency'] = $grad['transparency'] || $stop['opacity'] < 1.0;
}
// offset represents a location along the gradient vector
$offset = array_key_exists('offset', $stop) ? $stop['offset'] : null;
if ($offset === null && $key === 0) {
$offset = 0.0;
} elseif ($offset === null && $key === $last_stop_id) {
$offset = 1.0;
} elseif ($offset === null && $key > 0 && array_key_exists('offset', $grad['colors'][$key - 1] ?? [])) {
$prevoffset = $grad['colors'][$key - 1]['offset'] ?? 0.0;
$offsetstep = (1.0 - $prevoffset) / ($num_stops - $key);
$offset = $prevoffset + $offsetstep;
}
if ($offset !== null) {
$grad['colors'][$key]['offset'] = $offset;
}
}
return $grad;
}
/**
* Paints a coons patch mesh.
*
* @param float $posx Abscissa of the top left corner of the rectangle.
* @param float $posy Ordinate of the top left corner of the rectangle.
* @param float $width Width of the rectangle.
* @param float $height Height of the rectangle.
* @param string $colll Lower-Left corner color.
* @param string $collr Lower-Right corner color.
* @param string $colur Upper-Right corner color.
* @param string $colul Upper-Left corner color.
* @param array<float> $coords Coordinates
* @param float $coords_min Minimum value used by the coordinates.
* If a coordinate's value is smaller
* than this it will be cut to
* coords_min.
* @param float $coords_max Maximum value used by the coordinates.
* If a coordinate's value is greater
* than this it will be cut to
* coords_max.
* @param bool $antialias Flag indicating whether to filter the
* shading function to prevent aliasing artifacts.
*
* @return string PDF command
*
* @SuppressWarnings("PHPMD.ExcessiveParameterList")
* @SuppressWarnings("PHPMD.ExcessiveMethodLength")
*
* @throws \Com\Tecnick\Pdf\Graph\Exception
*/
public function getCoonsPatchMeshWithCoords(
float $posx,
float $posy,
float $width,
float $height,
string $colll = 'yellow',
string $collr = 'blue',
string $colur = 'green',
string $colul = 'red',
array $coords = [
0.00,
0.00,
0.33,
0.00,
0.67,
0.00,
1.00,
0.00,
1.00,
0.33,
1.00,
0.67,
1.00,
1.00,
0.67,
1.00,
0.33,
1.00,
0.00,
1.00,
0.00,
0.67,
0.00,
0.33,
],
float $coords_min = 0.0,
float $coords_max = 1.0,
bool $antialias = false,
): string {
if ($this->pdfa) {
return '';
}
// simple array -> convert to multi patch array
$patch_array = [
0 => [
'f' => 0,
'points' => $coords,
'colors' => [
0 => [
'red' => 1,
'green' => 1,
'blue' => 0,
'alpha' => 1,
],
1 => [
'red' => 0,
'green' => 0,
'blue' => 1,
'alpha' => 1,
],
2 => [
'red' => 0,
'green' => 1,
'blue' => 0,
'alpha' => 1,
],
3 => [
'red' => 1,
'green' => 0,
'blue' => 0,
'alpha' => 1,
],
],
],
];
$colllobj = $this->pdfColor->getColorObject($colll);
if (!$colllobj instanceof \Com\Tecnick\Color\Model) {
throw new GraphException('Invalid Lower-Left corner color');
}
$patch_array[0]['colors'][0] = $colllobj->toRgbArray();
$collrobj = $this->pdfColor->getColorObject($collr);
if (!$collrobj instanceof \Com\Tecnick\Color\Model) {
throw new GraphException('Invalid Lower-Right corner color');
}
$patch_array[0]['colors'][1] = $collrobj->toRgbArray();
$colurobj = $this->pdfColor->getColorObject($colur);
if (!$colurobj instanceof \Com\Tecnick\Color\Model) {
throw new GraphException('Invalid Upper-Right corner color');
}
$patch_array[0]['colors'][2] = $colurobj->toRgbArray();
$colulobj = $this->pdfColor->getColorObject($colul);
if (!$colulobj instanceof \Com\Tecnick\Color\Model) {
throw new GraphException('Invalid Upper-Left corner color');
}
$patch_array[0]['colors'][3] = $colulobj->toRgbArray();
return $this->getCoonsPatchMesh(
$posx,
$posy,
$width,
$height,
$patch_array,
$coords_min,
$coords_max,
$antialias,
);
}
/**
* Paints a coons patch mesh.
*
* @param float $posx Abscissa of the top left corner of the rectangle.
* @param float $posy Ordinate of the top left corner of the rectangle.
* @param float $width Width of the rectangle.
* @param float $height Height of the rectangle.
* @param array<array{
* 'f': int,
* 'points': array<float>,
* 'colors': array<int, array<string, float>>,
* }> $patch_array For one patch mesh:
* array(float x1,
* float y1, ....
* float x12, float
* y12): 12 pairs of
* coordinates
* (normally from 0 to
* 1) which specify
* the Bezier control
* points that define
* the patch. First
* pair is the lower
* left edge point,
* next is its right
* control point
* (control point 2).
* Then the other
* points are defined
* in the order:
* control point 1,
* edge point, control
* point 2 going
* counter-clockwise
* around the patch.
* Last (x12, y12) is
* the first edge
* point's left
* control point
* (control point 1).
* For two or more
* patch meshes:
* array[number of
* patches] - arrays
* with the following
* keys for each
* patch: f: where to
* put that patch (0 =
* first patch, 1, 2,
* 3 = right, top and
* left) points: 12
* pairs of
* coordinates of the
* Bezier control
* points as above for
* the first patch, 8
* pairs of
* coordinates for the
* following patches,
* ignoring the
* coordinates already
* defined by the
* precedent patch
* colors: must be 4
* colors for the
* first patch, 2
* colors for the
* following patches
* @param float $coords_min Minimum value used by the coordinates.
* If a coordinate's value is smaller
* than this it will be cut to
* coords_min.
* @param float $coords_max Maximum value used by the coordinates.
* If a coordinate's value is greater
* than this it will be cut to
* coords_max.
* @param bool $antialias Flag indicating whether to filter the
* shading function to prevent aliasing artifacts.
*
* @return string PDF command
*
* @SuppressWarnings("PHPMD.ExcessiveParameterList")
* @SuppressWarnings("PHPMD.ExcessiveMethodLength")
* @SuppressWarnings("PHPMD.CyclomaticComplexity")
*
* @throws \Com\Tecnick\Pdf\Graph\Exception
*/
public function getCoonsPatchMesh(
float $posx,
float $posy,
float $width,
float $height,
array $patch_array = [],
float $coords_min = 0.0,
float $coords_max = 1.0,
bool $antialias = false,
): string {
if ($this->pdfa) {
return '';
}
if ($coords_max <= $coords_min) {
throw new GraphException('coords_max must be greater than coords_min');
}
$ngr = 1 + \count($this->gradients);
$this->gradients[$ngr] = [
'antialias' => $antialias,
'colors' => [],
'background' => null,
'colspace' => 'DeviceRGB',
'coords' => [],
'id' => 0,
'pattern' => 0,
'stream' => '',
'transparency' => false,
'type' => 6, //coons patch mesh
];
$bpcd = 65_535; // 16 bits per coordinate
foreach ($patch_array as $par) {
$this->gradients[$ngr]['stream'] .= \chr($par['f'] & 0xFF); // start with the edge flag as 8 bit
foreach ($par['points'] as $point) {
// each point as 16 bit
$point = \floor(\max(0, \min($bpcd, (($point - $coords_min) / ($coords_max - $coords_min)) * $bpcd)));
$this->gradients[$ngr]['stream'] .=
\chr((int) \floor($point / 256) & 0xFF) . \chr((int) \floor($point % 256) & 0xFF);
}
foreach ($par['colors'] as $color) {
// each color component as 8 bit
$red = $color['red'] ?? 0.0;
$green = $color['green'] ?? 0.0;
$blue = $color['blue'] ?? 0.0;
$this->gradients[$ngr]['stream'] .=
\chr((int) \floor($red * 255) & 0xFF)
. \chr((int) \floor($green * 255) & 0xFF)
. \chr((int) \floor($blue * 255) & 0xFF);
}
}
return (
$this->getStartTransform()
. $this->getClippingRect($posx, $posy, $width, $height)
. $this->getGradientTransform($posx, $posy, $width, $height)
. '/Sh'
. $ngr
. ' sh'
. "\n"
. $this->getStopTransform()
);
}
/**
* Paints registration bars with color transitions
*
* @param float $posx Abscissa of the top left corner of the rectangle.
* @param float $posy Ordinate of the top left corner of the rectangle.
* @param float $width Width of the rectangle.
* @param float $height Height of the rectangle.
* @param bool $vertical If true prints bar vertically, otherwise horizontally.
* @param array<int, array<string>> $colors Array of colors to print,
* each entry is a color
* string or an array of two
* transition colors;
*
* @return string PDF command
*
* @SuppressWarnings("PHPMD.CyclomaticComplexity")
*
* @throws \Com\Tecnick\Pdf\Graph\Exception
*/
public function getColorRegistrationBar(
float $posx,
float $posy,
float $width,
float $height,
bool $vertical = false,
array $colors = [
// GRAY : black to white
['g(0%)', 'g(100%)'],
// RGB : red to white
['rgb(100%,0%,0%)', 'rgb(100%,100%,100%)'],
// RGB : green to white
['rgb(0%,100%,0%)', 'rgb(100%,100%,100%)'],
// RGB : blue to white
['rgb(0%,0%,100%)', 'rgb(100%,100%,100%)'],
// CMYK : cyan to white
['cmyk(100%,0%,0%,0%)', 'cmyk(0%,0%,0%,0%)'],
// CMYK : magenta to white
['cmyk(0%,100%,0%,0%)', 'cmyk(0%,0%,0%,0%)'],
// CMYK : yellow to white
['cmyk(0%,0%,100%,0%)', 'cmyk(0%,0%,0%,0%)'],
// CMYK : black to white
['cmyk(0%,0%,0%,100%)', 'cmyk(0%,0%,0%,0%)'],
],
): string {
$numbars = \count($colors);
if ($numbars <= 0) {
return '';
}
// set bar measures
// default (non-vertical)
$coords = [0, 0, 1, 0];
$wbr = $width;
$hbr = $height / $numbars;
$xdt = 0.0;
$ydt = $hbr;
if ($vertical) {
$coords = [0, 1, 0, 0]; // coordinates for gradient transition
$wbr = $width / $numbars; // bar width
$hbr = $height; // bar height
$xdt = $wbr; // delta x
$ydt = 0.0; // delta y
}
$xbr = $posx;
$ybr = $posy;
$out = '';
foreach ($colors as $color) {
if ($color !== [] && isset($color[0]) && $color[0] !== '') {
if (!isset($color[1])) {
$color[1] = $color[0];
}
if ($color[0] === $color[1] || $this->pdfa) {
// colored rectangle
$out .= $this->getStartTransform();
$colobj = $this->pdfColor->getColorObject($color[0]);
if ($colobj instanceof \Com\Tecnick\Color\Model) {
$out .= $colobj->getPdfColor();
}
$out .= $this->getBasicRect($xbr, $ybr, $wbr, $hbr, 'F') . $this->getStopTransform();
} else {
// color gradient
$out .= $this->getLinearGradient($xbr, $ybr, $wbr, $hbr, $color[0], $color[1], $coords);
}
}
$xbr += $xdt;
$ybr += $ydt;
}
return $out;
}
/**
* Get a crop-mark.
*
* @param float $posx Abscissa of the crop-mark center.
* @param float $posy Ordinate of the crop-mark center.
* @param float $width Width of the crop-mark.
* @param float $height Height of the crop-mark.
* @param string $type Type of crop mark - one symbol per type:
* T = TOP, B = BOTTOM, L = LEFT, R = RIGHT
* @param StyleDataOpt $style Line style to apply.
*
* @return string PDF command
*/
public function getCropMark(
float $posx,
float $posy,
float $width,
float $height,
string $type = 'TBLR',
array $style = [],
): string {
$crops = \array_unique(\str_split(\strtoupper($type), 1));
$space_ratio = 4;
$dhw = $width / $space_ratio; // horizontal space to leave before the intersection point
$dvh = $height / $space_ratio; // vertical space to leave before the intersection point
$out = '';
foreach ($crops as $crop) {
$draw = true;
$posx1 = $posx;
$posy1 = $posy;
$posx2 = $posx;
$posy2 = $posy;
switch ($crop) {
case 'T':
$posx1 = $posx;
$posy1 = $posy - $height;
$posx2 = $posx;
$posy2 = $posy - $dvh;
break;
case 'B':
$posx1 = $posx;
$posy1 = $posy + $dvh;
$posx2 = $posx;
$posy2 = $posy + $height;
break;
case 'L':
$posx1 = $posx - $width;
$posy1 = $posy;
$posx2 = $posx - $dhw;
$posy2 = $posy;
break;
case 'R':
$posx1 = $posx + $dhw;
$posy1 = $posy;
$posx2 = $posx + $width;
$posy2 = $posy;
break;
default:
$draw = false;
break;
}
if (!$draw) {
continue;
}
$out .= $this->getRawPoint($posx1, $posy1) . $this->getRawLine($posx2, $posy2) . $this->getPathPaintOp('S');
}
if ($out === '') {
return '';
}
return $this->getStartTransform() . $this->getStyleCmd($style) . $out . $this->getStopTransform();
}
/**
* Get overprint mode for stroking (OP) and non-stroking (op) painting operations.
* (Check the "Entries in a Graphics State Parameter Dictionary" on PDF 32000-1:2008).
*
* @param bool $stroking If true apply overprint for stroking operations.
* @param bool|null $nonstroking If true apply overprint for painting operations other than stroking.
* @param int $mode Overprint mode:
* 0 = each source
* colour
* component value
* replaces the
* value
* previously
* painted for the
* corresponding
* device
* colorant; 1 = a
* tint value of
* 0.0 for a
* source colour
* component shall
* leave the
* corresponding
* component of
* the previously
* painted colour
* unchanged.
*
* @return string PDF command
*/
public function getOverprint(bool $stroking = true, ?bool $nonstroking = null, int $mode = 0): string
{
if ($nonstroking === null) {
$nonstroking = $stroking;
}
return $this->getExtGState([
'OP' => $stroking,
'op' => $nonstroking,
'OPM' => \max(0, \min(1, $mode)),
]);
}
/**
* Set alpha for stroking (CA) and non-stroking (ca) operations.
*
* @param float $stroking Alpha value for stroking operations:
* real value from 0 (transparent) to 1 (opaque).
* @param string|BlendMode $bmv Blend mode (or BlendMode enum case), one of the following:
* Normal, Multiply, Screen,
* Overlay, Darken, Lighten,
* ColorDodge, ColorBurn, HardLight,
* SoftLight, Difference, Exclusion,
* Hue, Saturation, Color,
* Luminosity.
* @param float|string $nonstroking Alpha value for non-stroking operations:
* real value from 0 (transparent) to 1
* (opaque).
* @param bool $ais Alpha-Is-Shape flag: if true the soft-mask
* alpha values are interpreted as shape
* (passed through to the /AIS ExtGState key).
*
* @return string PDF command
*/
public function getAlpha(
float $stroking = 1,
string|BlendMode $bmv = 'Normal',
float|string $nonstroking = '',
bool $ais = false,
): string {
if ($nonstroking === '') {
$nonstroking = $stroking;
}
$bmv = BlendMode::fromLoose($bmv)->value;
if (\is_string($nonstroking)) {
$nonstroking = \is_numeric($nonstroking) ? (float) $nonstroking : $stroking;
}
return $this->getExtGState([
'CA' => $stroking,
'ca' => $nonstroking,
'BM' => '/' . $bmv,
'AIS' => $ais,
]);
}
}
+100
View File
@@ -0,0 +1,100 @@
<?php
declare(strict_types=1);
/**
* PathPaintOp.php
*
* @since 2026-07-17
* @category Library
* @package PdfGraph
* @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-graph
*
* This file is part of tc-lib-pdf-graph software library.
*/
namespace Com\Tecnick\Pdf\Graph;
/**
* Com\Tecnick\Pdf\Graph\PathPaintOp
*
* Backed enum for the PDF path-painting operators (PDF 32000-1:2008 - 8.5.3).
* The backing value of each case is the canonical operator produced by
* Style::getPathPaintOp(); its many input aliases collapse onto these cases via
* fromLoose().
*
* @since 2026-07-17
* @category Library
* @package PdfGraph
* @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-graph
*/
enum PathPaintOp: string
{
case Stroke = 'S';
case CloseStroke = 's';
case Fill = 'f';
case CloseFill = 'h f';
case FillEvenOdd = 'f*';
case CloseFillEvenOdd = 'h f*';
case FillStroke = 'B';
case FillStrokeEvenOdd = 'B*';
case CloseFillStroke = 'b';
case CloseFillStrokeEvenOdd = 'b*';
case Clip = 'W n';
case ClipEvenOdd = 'W* n';
case Close = 'h';
case NoOp = 'n';
/**
* Resolve a loose path paint mode to the matching canonical operator case.
*
* Accepts an enum instance (returned unchanged) or any of the input aliases
* accepted by Style::getPathPaintOp() (case sensitive). Unknown values fall
* back to Stroke, matching the default of Style::getPathPaintOp().
*
* @param string|self $value Path paint mode or enum case.
*/
public static function fromLoose(string|self $value): self
{
if ($value instanceof self) {
return $value;
}
return match ($value) {
'S', 'D' => self::Stroke,
's', 'h S', 'd' => self::CloseStroke,
'f', 'F' => self::Fill,
'h f' => self::CloseFill,
'f*', 'F*' => self::FillEvenOdd,
'h f*' => self::CloseFillEvenOdd,
'B', 'FD', 'DF' => self::FillStroke,
'B*', 'F*D', 'DF*' => self::FillStrokeEvenOdd,
'b', 'h B', 'fd', 'df' => self::CloseFillStroke,
'b*', 'h B*', 'f*d', 'df*' => self::CloseFillStrokeEvenOdd,
'W n', 'CNZ' => self::Clip,
'W* n', 'CEO' => self::ClipEvenOdd,
'h' => self::Close,
'n' => self::NoOp,
default => self::Stroke,
};
}
}
+422
View File
@@ -0,0 +1,422 @@
<?php
declare(strict_types=1);
/**
* Raw.php
*
* @since 2011-05-23
* @category Library
* @package PdfGraph
* @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-graph
*
* This file is part of tc-lib-pdf-graph software library.
*/
namespace Com\Tecnick\Pdf\Graph;
/**
* Com\Tecnick\Pdf\Graph\Raw
*
* @since 2011-05-23
* @category Library
* @package PdfGraph
* @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-graph
*/
abstract class Raw extends \Com\Tecnick\Pdf\Graph\Transform
{
/**
* Begin a new subpath by moving the current point to the specified coordinates,
* omitting any connecting line segment.
*
* @param float $posx Abscissa of point.
* @param float $posy Ordinate of point.
*
* @return string PDF command
*/
public function getRawPoint(float $posx, float $posy): string
{
return \sprintf('%F %F m' . "\n", $posx * $this->kunit, ($this->pageh - $posy) * $this->kunit);
}
/**
* Append a straight line segment from the current point to the specified one.
* The new current point shall be the one specified.
*
* @param float $posx Abscissa of end point.
* @param float $posy Ordinate of end point.
*
* @return string PDF command
*/
public function getRawLine(float $posx, float $posy): string
{
return \sprintf('%F %F l' . "\n", $posx * $this->kunit, ($this->pageh - $posy) * $this->kunit);
}
/**
* Append a rectangle to the current path as a complete subpath,
* with lower-left corner in the specified point and dimensions width and height in user units.
*
* @param float $posx Abscissa of upper-left corner.
* @param float $posy Ordinate of upper-left corner.
* @param float $width Width.
* @param float $height Height.
* @param string|PathPaintOp $mode Mode of rendering (or PathPaintOp enum case). @see getPathPaintOp()
*
* @return string PDF command
*/
public function getRawRect(
float $posx,
float $posy,
float $width,
float $height,
string|PathPaintOp $mode = '',
): string {
return \sprintf(
'%F %F %F %F re' . "\n" . $this->getPathPaintOp($mode, ''),
$posx * $this->kunit,
($this->pageh - $posy) * $this->kunit,
$width * $this->kunit,
-$height * $this->kunit,
);
}
/**
* Append a cubic Bezier curve to the current path.
* The curve shall extend from the current point to the point (posx3, posy3),
* using (posx1, posy1) and (posx2, posy2) as the Bezier control points.
* The new current point shall be (posx3, posy3).
*
* @param float $posx1 Abscissa of control point 1.
* @param float $posy1 Ordinate of control point 1.
* @param float $posx2 Abscissa of control point 2.
* @param float $posy2 Ordinate of control point 2.
* @param float $posx3 Abscissa of end point.
* @param float $posy3 Ordinate of end point.
*
* @return string PDF command
*/
public function getRawCurve(
float $posx1,
float $posy1,
float $posx2,
float $posy2,
float $posx3,
float $posy3,
): string {
return \sprintf(
'%F %F %F %F %F %F c' . "\n",
$posx1 * $this->kunit,
($this->pageh - $posy1) * $this->kunit,
$posx2 * $this->kunit,
($this->pageh - $posy2) * $this->kunit,
$posx3 * $this->kunit,
($this->pageh - $posy3) * $this->kunit,
);
}
/**
* Append a cubic Bezier curve to the current path.
* The curve shall extend from the current point to the point (posx3, posy3),
* using the current point and (posx2, posy2) as the Bezier control points.
* The new current point shall be (posx3, posy3).
*
* @param float $posx2 Abscissa of control point 2.
* @param float $posy2 Ordinate of control point 2.
* @param float $posx3 Abscissa of end point.
* @param float $posy3 Ordinate of end point.
*
* @return string PDF command
*/
public function getRawCurveV(float $posx2, float $posy2, float $posx3, float $posy3): string
{
return \sprintf(
'%F %F %F %F v' . "\n",
$posx2 * $this->kunit,
($this->pageh - $posy2) * $this->kunit,
$posx3 * $this->kunit,
($this->pageh - $posy3) * $this->kunit,
);
}
/**
* Append a cubic Bezier curve to the current path.
* The curve shall extend from the current point to the point (posx3, posy3),
* using (posx1, posy1) and (posx3, posy3) as the Bezier control points.
* The new current point shall be (posx3, posy3).
*
* @param float $posx1 Abscissa of control point 1.
* @param float $posy1 Ordinate of control point 1.
* @param float $posx3 Abscissa of end point.
* @param float $posy3 Ordinate of end point.
*
* @return string PDF command
*/
public function getRawCurveY(float $posx1, float $posy1, float $posx3, float $posy3): string
{
return \sprintf(
'%F %F %F %F y' . "\n",
$posx1 * $this->kunit,
($this->pageh - $posy1) * $this->kunit,
$posx3 * $this->kunit,
($this->pageh - $posy3) * $this->kunit,
);
}
/**
* Initialize angles for the elliptical arc.
*
* @param float $ags Angle in degrees at which starting drawing.
* @param float $agf Angle in degrees at which stop drawing.
* @param float $rdv Vertical radius (if = 0 then it is a circle).
* @param float $rdh Horizontal radius.
* @param bool $ccw If true draws in counter-clockwise direction.
* @param bool $svg If true the angles are in svg mode (already calculated).
*/
protected function setRawEllipticalArcAngles(
float &$ags,
float &$agf,
float $rdv,
float $rdh,
bool $ccw,
bool $svg,
): void {
$ags = $this->degToRad($ags);
$agf = $this->degToRad($agf);
if (!$svg) {
$ags = \atan2(\sin($ags) / $rdv, \cos($ags) / $rdh);
$agf = \atan2(\sin($agf) / $rdv, \cos($agf) / $rdh);
}
if ($ags < 0) {
$ags += 2 * self::MPI;
}
if ($agf < 0) {
$agf += 2 * self::MPI;
}
if ($ccw && $ags > $agf) {
// reverse rotation
$ags -= 2 * self::MPI;
} elseif (!$ccw && $ags < $agf) {
// reverse rotation
$agf -= 2 * self::MPI;
}
}
/**
* Append an elliptical arc to the current path.
* An ellipse is formed from n Bezier curves.
*
* @param float $posxc Abscissa of center point.
* @param float $posyc Ordinate of center point.
* @param float $rdh Horizontal radius.
* @param float $rdv Vertical radius (if = 0 then it is a circle).
* @param float $posxang Angle between the X-axis and the major axis of the ellipse.
* @param float $angs Angle in degrees at which starting drawing.
* @param float $angf Angle in degrees at which stop drawing.
* @param bool $pie If true do not mark the border point (used to draw pie sectors).
* @param float $ncv Number of curves used to draw a 90 degrees portion of ellipse.
* @param bool $startpoint If true output a starting point.
* @param bool $ccw If true draws in counter-clockwise direction.
* @param bool $svg If true the angles are in svg mode (already calculated).
* @param array<float> $bbox If provided, it will be filled with the bounding box coordinates
* (x min, y min, x max, y max). The box is derived from the Bezier
* control points, so (by the convex-hull property) it is guaranteed
* to contain the arc but may be slightly larger than its tight bounds.
*
* @return string PDF command
*
* @SuppressWarnings("PHPMD.ExcessiveParameterList")
* @SuppressWarnings("PHPMD.ExcessiveMethodLength")
*/
public function getRawEllipticalArc(
float $posxc,
float $posyc,
float $rdh,
float $rdv,
float $posxang = 0.0,
float $angs = 0.0,
float $angf = 360.0,
bool $pie = false,
float $ncv = 2,
bool $startpoint = true,
bool $ccw = true,
bool $svg = false,
array &$bbox = [],
): string {
$out = '';
if ($rdh <= 0 || $rdv < 0) {
return '';
}
if ($rdv === 0.0) {
// a zero vertical radius means a circle: use the horizontal radius
// (also avoids a division by zero when computing the arc angles)
$rdv = $rdh;
}
$bbox = [PHP_INT_MAX, PHP_INT_MAX, PHP_INT_MIN, PHP_INT_MIN];
if ($pie) {
$out .= $this->getRawPoint($posxc, $posyc); // center of the arc
}
$posxang = $this->degToRad($posxang);
$ags = $angs;
$agf = $angf;
$this->setRawEllipticalArcAngles($ags, $agf, $rdv, $rdh, $ccw, $svg);
$total_angle = $agf - $ags;
$ncv = \max(2, $ncv);
$ncv *= (2 * \abs($total_angle)) / self::MPI; // total arcs to draw
$ncv = (int) (\round($ncv) + 1);
$arcang = $total_angle / $ncv; // angle of each arc
$pageh = $this->pageh;
$posx0 = $posxc; // X center point in PDF coordinates
$posy0 = $pageh - $posyc; // Y center point in PDF coordinates
$ang = $ags; // starting angle
$alpha = \sin($arcang) * ((\sqrt(4 + (3 * (\tan($arcang / 2) ** 2))) - 1) / 3);
$cos_xang = \cos($posxang);
$sin_xang = \sin($posxang);
// first arc point and its Bezier control point
[$px1, $py1, $qx1, $qy1] = $this->getRawEllipticalArcPoint(
$posx0,
$posy0,
$rdh,
$rdv,
$cos_xang,
$sin_xang,
$alpha,
$ang,
);
if ($pie) {
$out .= $this->getRawLine($px1, $pageh - $py1); // line from center to arc starting point
} elseif ($startpoint) {
$out .= $this->getRawPoint($px1, $pageh - $py1); // arc starting point
}
// draw arcs
for ($idx = 1; $idx <= $ncv; ++$idx) {
$ang = $ags + ($idx * $arcang); // starting angle
if ($idx === $ncv) {
$ang = $agf;
}
// second arc point and its Bezier control point
[$px2, $py2, $qx2, $qy2] = $this->getRawEllipticalArcPoint(
$posx0,
$posy0,
$rdh,
$rdv,
$cos_xang,
$sin_xang,
$alpha,
$ang,
);
// draw arc
$cx1 = $px1 + $qx1;
$cy1 = $pageh - ($py1 + $qy1);
$cx2 = $px2 - $qx2;
$cy2 = $pageh - ($py2 - $qy2);
$cx3 = $px2;
$cy3 = $pageh - $py2;
$out .= $this->getRawCurve($cx1, $cy1, $cx2, $cy2, $cx3, $cy3);
// get bounding box coordinates
$bbox = [
\min($bbox[0], $cx1, $cx2, $cx3),
\min($bbox[1], $cy1, $cy2, $cy3),
\max($bbox[2], $cx1, $cx2, $cx3),
\max($bbox[3], $cy1, $cy2, $cy3),
];
// move to next point
$px1 = $px2;
$py1 = $py2;
$qx1 = $qx2;
$qy1 = $qy2;
}
if ($pie) {
$out .= $this->getRawLine($posxc, $posyc);
// get bounding box coordinates
$bbox = [
\min($bbox[0], $posxc),
\min($bbox[1], $posyc),
\max($bbox[2], $posxc),
\max($bbox[3], $posyc),
];
}
return $out;
}
/**
* Computes an elliptical arc point and its Bezier control-point offset.
*
* @param float $posx0 X center point in PDF coordinates.
* @param float $posy0 Y center point in PDF coordinates.
* @param float $rdh Horizontal radius.
* @param float $rdv Vertical radius.
* @param float $cosXang Cosine of the ellipse orientation angle.
* @param float $sinXang Sine of the ellipse orientation angle.
* @param float $alpha Bezier control-point scaling factor.
* @param float $ang Arc angle in radians.
*
* @return array{float, float, float, float} Point and control-point offset: [px, py, qx, qy].
*
* @SuppressWarnings("PHPMD.ExcessiveParameterList")
*/
private function getRawEllipticalArcPoint(
float $posx0,
float $posy0,
float $rdh,
float $rdv,
float $cosXang,
float $sinXang,
float $alpha,
float $ang,
): array {
$cosAng = \cos($ang);
$sinAng = \sin($ang);
return [
$posx0 + ($rdh * $cosXang * $cosAng) - ($rdv * $sinXang * $sinAng),
$posy0 + ($rdh * $sinXang * $cosAng) + ($rdv * $cosXang * $sinAng),
$alpha * ((-$rdh * $cosXang * $sinAng) - ($rdv * $sinXang * $cosAng)),
$alpha * ((-$rdh * $sinXang * $sinAng) + ($rdv * $cosXang * $cosAng)),
];
}
/**
* Returns the angle in radians between two vectors with the same origin point.
* Angles are counted counter-clock wise.
*
* @param float $posx1 X coordinate of first vector point.
* @param float $posy1 Y coordinate of first vector point.
* @param float $posx2 X coordinate of second vector point.
* @param float $posy2 Y coordinate of second vector point.
*
* @return float Angle in radians
*/
public function getVectorsAngle(float $posx1, float $posy1, float $posx2, float $posy2): float
{
$dprod = ($posx1 * $posx2) + ($posy1 * $posy2);
$dist1 = \sqrt(($posx1 * $posx1) + ($posy1 * $posy1));
$dist2 = \sqrt(($posx2 * $posx2) + ($posy2 * $posy2));
$distprod = $dist1 * $dist2;
if ($distprod === 0.0) {
return 0;
}
$angle = \acos(\min(1, \max(-1, $dprod / $distprod)));
if ((($posx1 * $posy2) - ($posx2 * $posy1)) < 0) {
$angle *= -1;
}
return $angle;
}
}
+594
View File
@@ -0,0 +1,594 @@
<?php
declare(strict_types=1);
/**
* Style.php
*
* @since 2011-05-23
* @category Library
* @package PdfGraph
* @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-graph
*
* This file is part of tc-lib-pdf-graph software library.
*/
namespace Com\Tecnick\Pdf\Graph;
use Com\Tecnick\Pdf\Graph\Exception as GraphException;
/**
* Com\Tecnick\Pdf\Graph\Style
*
* @since 2011-05-23
* @category Library
* @package PdfGraph
* @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-graph
*
* @phpstan-import-type StyleDataOpt from \Com\Tecnick\Pdf\Graph\Base
*
* @SuppressWarnings("PHPMD.ExcessiveClassComplexity")
*/
abstract class Style extends \Com\Tecnick\Pdf\Graph\Base
{
/**
* Array of restore points (style ID).
*
* @var array<int>
*/
protected array $stylemark = [0];
/**
* Map values for lineCap.
*
* @var array<int|string, int>
*/
protected const LINECAPMAP = [
0 => 0,
1 => 1,
2 => 2,
'butt' => 0,
'round' => 1,
'square' => 2,
];
/**
* Map values for lineJoin.
*
* @var array<int|string, int>
*/
protected const LINEJOINMAP = [
0 => 0,
1 => 1,
2 => 2,
'miter' => 0,
'round' => 1,
'bevel' => 2,
];
/**
* Map path paint operators.
*
* @var array<string, string>
*/
protected const PPOPMAP = [
'S' => 'S',
'D' => 'S',
's' => 's',
'h S' => 's',
'd' => 's',
'f' => 'f',
'F' => 'f',
'h f' => 'h f',
'f*' => 'f*',
'F*' => 'f*',
'h f*' => 'h f*',
'B' => 'B',
'FD' => 'B',
'DF' => 'B',
'B*' => 'B*',
'F*D' => 'B*',
'DF*' => 'B*',
'b' => 'b',
'h B' => 'b',
'fd' => 'b',
'df' => 'b',
'b*' => 'b*',
'h B*' => 'b*',
'f*d' => 'b*',
'df*' => 'b*',
'W n' => 'W n',
'CNZ' => 'W n',
'W* n' => 'W* n',
'CEO' => 'W* n',
'h' => 'h',
'n' => 'n',
];
/**
* Filling modes.
*
* @var array<string, bool>
*/
protected const MODEFILLING = [
'f' => true,
'f*' => true,
'B' => true,
'B*' => true,
'b' => true,
'b*' => true,
];
/**
* Stroking Modes.
*
* @var array<string, bool>
*/
protected const MODESTROKING = [
'S' => true,
's' => true,
'B' => true,
'B*' => true,
'b' => true,
'b*' => true,
];
/**
* Closing Modes.
*
* @var array<string, bool>
*/
protected const MODECLOSING = [
'b' => true,
'b*' => true,
's' => true,
];
/**
* Clipping Modes.
*
* @var array<string, bool>
*/
protected const MODECLIPPING = [
'CEO' => true,
'CNZ' => true,
'W n' => true,
'W* n' => true,
];
/**
* Map of equivalent modes without close.
*
* @var array<string, string>
*/
protected const MODETONOCLOSE = [
's' => 'S',
'b' => 'B',
'b*' => 'B*',
];
/**
* Map of equivalent modes without fill.
*
* @var array<string, string>
*/
protected const MODETONOFILL = [
'f' => '',
'f*' => '',
'B' => 'S',
'B*' => 'S',
'b' => 's',
'b*' => 's',
];
/**
* Map of equivalent modes without STROKE.
*
* @var array<string, string>
*/
protected const MODETONOSTROKE = [
'S' => '',
's' => 'h',
'B' => 'f',
'B*' => 'f*',
'b' => 'h f',
'b*' => 'h f*',
];
/**
* Add a new style
*
* @param StyleDataOpt $style Style to add.
* @param bool $inheritlast If true inherit missing values from the last style.
*
* @return string PDF style string
*/
public function add(array $style = [], bool $inheritlast = false): string
{
if ($inheritlast) {
$style = \array_merge($this->getCurrentStyleArray(), $style);
}
$this->style[++$this->styleid] = $style;
return $this->getStyle();
}
/**
* Remove and return last style.
*
* @return string PDF style string.
*
* @throws \Com\Tecnick\Pdf\Graph\Exception
*/
public function pop(): string
{
if ($this->styleid <= 0) {
throw new GraphException('The style stack is empty');
}
$style = $this->getStyle();
unset($this->style[$this->styleid]);
--$this->styleid;
return $style;
}
/**
* Save the current style ID to be restored later.
*/
public function saveStyleStatus(): void
{
$this->stylemark[] = $this->styleid;
}
/**
* Restore the saved style status.
*/
public function restoreStyleStatus(): void
{
$styleid = \array_pop($this->stylemark);
if ($styleid === null) {
$styleid = 0;
}
$this->styleid = $styleid;
$this->style = \array_slice($this->style, 0, $this->styleid + 1, true);
}
/**
* Returns the last style array.
*
* @return StyleDataOpt
*/
public function getCurrentStyleArray(): array
{
if (isset($this->style[$this->styleid])) {
return $this->style[$this->styleid];
}
return $this->getDefaultStyle();
}
/**
* Returns the last set value of the specified property.
*
* @param string $property Property to search.
* @param int|float|bool|string|null $default Default value to return in case the property is not found.
*
* @return int|float|bool|string|null Property value or $default in case the property is not found.
*/
public function getLastStyleProperty(
string $property,
int|float|bool|string|null $default = null,
): int|float|bool|string|null {
for ($idx = $this->styleid; $idx >= 0; --$idx) {
if (
array_key_exists($property, $this->style[$idx] ?? [])
&& ($this->style[$idx][$property] ?? null) !== null
&& !\is_array($this->style[$idx][$property])
) {
return $this->style[$idx][$property];
}
}
return $default;
}
/**
* Returns the value of the specified item from the last inserted style.
*
* @param string $item Item to search.
*
* @throws \Com\Tecnick\Pdf\Graph\Exception
*/
public function getCurrentStyleItem(string $item): mixed
{
$style = $this->getCurrentStyleArray();
if (!\array_key_exists($item, $style)) {
throw new GraphException('The ' . $item . ' value is not set in the current style');
}
return $style[$item];
}
/**
* Returns the PDF string of the last style added.
*/
public function getStyle(): string
{
return $this->getStyleCmd($this->getCurrentStyleArray());
}
/**
* Returns the PDF string of the specified style.
*
* @param StyleDataOpt $style Style to represent.
*/
public function getStyleCmd(array $style = []): string
{
$out = '';
if (array_key_exists('lineWidth', $style)) {
$out .= \sprintf('%F w' . "\n", $style['lineWidth'] * $this->kunit);
}
$out .= $this->getLineModeCmd($style);
if (array_key_exists('lineColor', $style)) {
$out .= $this->pdfColor->getPdfColor($style['lineColor'], true);
}
if (array_key_exists('fillColor', $style)) {
$out .= $this->pdfColor->getPdfColor($style['fillColor'], false);
}
return $out;
}
/**
* Returns the PDF string of the specified line style.
*
* @param StyleDataOpt $style Style to represent.
*
* @SuppressWarnings("PHPMD.CyclomaticComplexity")
*/
protected function getLineModeCmd(array $style = []): string
{
$out = '';
if (array_key_exists('lineCap', $style)) {
$lineCap = $style['lineCap'];
if (isset(self::LINECAPMAP[$lineCap])) {
$out .= self::LINECAPMAP[$lineCap] . ' J' . "\n";
}
}
if (array_key_exists('lineJoin', $style)) {
$lineJoin = $style['lineJoin'];
if (isset(self::LINEJOINMAP[$lineJoin])) {
$out .= self::LINEJOINMAP[$lineJoin] . ' j' . "\n";
}
}
if (array_key_exists('miterLimit', $style)) {
$out .= \sprintf('%F M' . "\n", $style['miterLimit'] * $this->kunit);
}
if (array_key_exists('dashArray', $style)) {
$dash = [];
foreach ($style['dashArray'] as $val) {
$dash[] = \sprintf('%F', (float) $val * $this->kunit);
}
if (!array_key_exists('dashPhase', $style)) {
$style['dashPhase'] = 0;
}
$out .= \sprintf('[%s] %F d' . "\n", \implode(' ', $dash), $style['dashPhase']);
}
return $out;
}
/**
* Get the Path-Painting Operators.
*
* @param string|PathPaintOp $mode Mode of rendering (or PathPaintOp enum case). Possible values are:
* - S or D: Stroke the path. - s or d:
* Close and stroke the path. - f or F:
* Fill the path, using the nonzero
* winding number rule to determine the
* region to fill. - f* or F*: Fill the
* path, using the even-odd rule to
* determine the region to fill. - B or FD
* or DF: Fill and then stroke the path,
* using the nonzero winding number rule
* to determine the region to fill. - B*
* or F*D or DF*: Fill and then stroke the
* path, using the even-odd rule to
* determine the region to fill. - b or fd
* or df: Close, fill, and then stroke the
* path, using the nonzero winding number
* rule to determine the region to fill. -
* b* or f*d or df*: Close, fill, and then
* stroke the path, using the even-odd
* rule to determine the region to fill. -
* CNZ: Clipping mode using the nonzero
* winding number rule to determine which
* regions lie inside the clipping path. -
* CEO: Clipping mode using the even-odd
* rule to determine which regions lie
* inside the clipping path - n: End
* the path object without filling or
* stroking it.
* @param string|PathPaintOp $default Default style (or PathPaintOp enum case)
*/
public function getPathPaintOp(string|PathPaintOp $mode, string|PathPaintOp $default = 'S'): string
{
if ($mode instanceof PathPaintOp) {
$mode = $mode->value;
}
if ($default instanceof PathPaintOp) {
$default = $default->value;
}
if ($mode === '' || !isset(self::PPOPMAP[$mode])) {
return isset(self::PPOPMAP[$default]) ? self::PPOPMAP[$default] . "\n" : '';
}
return self::PPOPMAP[$mode] . "\n";
}
/**
* Returns true if the specified path paint operator includes the filling option.
*
* @param string $mode Path paint operator (mode of rendering).
*/
public function isFillingMode(string $mode): bool
{
return (
isset(self::PPOPMAP[$mode])
&& (array_key_exists(self::PPOPMAP[$mode], self::MODEFILLING) || $this->isClippingMode($mode))
);
}
/**
* Returns true if the specified mode includes the stroking option.
*
* @param string $mode Path paint operator (mode of rendering).
*/
public function isStrokingMode(string $mode): bool
{
if (!isset(self::PPOPMAP[$mode])) {
return false;
}
$paintMode = self::PPOPMAP[$mode];
return array_key_exists($paintMode, self::MODESTROKING);
}
/**
* Returns true if the specified mode includes "closing the path" option.
*
* @param string $mode Path paint operator (mode of rendering).
*/
public function isClosingMode(string $mode): bool
{
return (
isset(self::PPOPMAP[$mode])
&& (array_key_exists(self::PPOPMAP[$mode], self::MODECLOSING) || $this->isClippingMode($mode))
);
}
/**
* Returns true if the specified mode is of clipping type.
*
* @param string $mode Path paint operator (mode of rendering).
*/
public function isClippingMode(string $mode): bool
{
if (!isset(self::PPOPMAP[$mode])) {
return false;
}
$paintMode = self::PPOPMAP[$mode];
return array_key_exists($paintMode, self::MODECLIPPING);
}
/**
* Remove the Close option from the specified Path paint operator.
*
* @param string $mode Path paint operator (mode of rendering).
*/
public function getModeWithoutClose(string $mode): string
{
if (!isset(self::PPOPMAP[$mode])) {
return $mode;
}
$paintMode = self::PPOPMAP[$mode];
if (isset(self::MODETONOCLOSE[$paintMode])) {
return self::MODETONOCLOSE[$paintMode];
}
return $mode;
}
/**
* Remove the Fill option from the specified Path paint operator.
*
* @param string $mode Path paint operator (mode of rendering).
*/
public function getModeWithoutFill(string $mode): string
{
if (!isset(self::PPOPMAP[$mode])) {
return $mode;
}
$paintMode = self::PPOPMAP[$mode];
if (isset(self::MODETONOFILL[$paintMode])) {
return self::MODETONOFILL[$paintMode];
}
return $mode;
}
/**
* Remove the Stroke option from the specified Path paint operator.
*
* @param string $mode Path paint operator (mode of rendering).
*/
public function getModeWithoutStroke(string $mode): string
{
if (!isset(self::PPOPMAP[$mode])) {
return $mode;
}
$paintMode = self::PPOPMAP[$mode];
if (isset(self::MODETONOSTROKE[$paintMode])) {
return self::MODETONOSTROKE[$paintMode];
}
return $mode;
}
/**
* Add transparency parameters to the current extgstate.
*
* @param array<string, int|float|bool|string> $parms parameters.
*
* @return string PDF command.
*/
public function getExtGState(array $parms): string
{
if ($this->pdfa) {
return '';
}
$gsx = \count($this->extgstates) + 1;
// check if this ExtGState already exist
foreach ($this->extgstates as $idx => $ext) {
if ($ext['parms'] !== $parms) {
continue;
}
$gsx = $idx;
break;
}
if (($this->extgstates[$gsx] ?? []) === []) {
$this->extgstates[$gsx] = [
'n' => 0,
'name' => '',
'parms' => $parms,
];
}
return '/GS' . $gsx . ' gs' . "\n";
}
}
+394
View File
@@ -0,0 +1,394 @@
<?php
declare(strict_types=1);
/**
* Transform.php
*
* @since 2011-05-23
* @category Library
* @package PdfGraph
* @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-graph
*
* This file is part of tc-lib-pdf-graph software library.
*/
namespace Com\Tecnick\Pdf\Graph;
use Com\Tecnick\Pdf\Graph\Exception as GraphException;
/**
* Com\Tecnick\Pdf\Graph\Transform
*
* @since 2011-05-23
* @category Library
* @package PdfGraph
* @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-graph
*
* @phpstan-import-type TTMatrix from \Com\Tecnick\Pdf\Graph\Base
*/
abstract class Transform extends \Com\Tecnick\Pdf\Graph\Style
{
/**
* Current ID for transformation matrix.
*/
protected int $ctmid = -1;
/**
* Array (stack) of Current Transformation Matrix (CTM),
* which maps user space coordinates used within a PDF content stream into output device coordinates.
*
* @var array<int, array<int, TTMatrix>>
*/
protected array $ctm = [];
/**
* Returns the transformation stack.
*
* @return array<int, array<int, TTMatrix>>
*/
public function getTransformStack(): array
{
return $this->ctm;
}
/**
* Returns the transformation stack index.
*/
public function getTransformIndex(): int
{
return $this->ctmid;
}
/**
* Starts a 2D transformation saving current graphic state.
* This function must be called before calling transformation methods
*/
public function getStartTransform(): string
{
$this->saveStyleStatus();
$this->ctm[++$this->ctmid] = [];
return Base::GSAVE;
}
/**
* Stops a 2D transformation restoring previous graphic state.
* This function must be called after calling transformation methods.
*/
public function getStopTransform(): string
{
if (($this->ctm[$this->ctmid] ?? null) === null) {
return '';
}
unset($this->ctm[$this->ctmid]);
--$this->ctmid;
$this->restoreStyleStatus();
return Base::GRESTORE;
}
/**
* Get the transformation matrix (CTM) PDF string
*
* @param TTMatrix $ctm Transformation matrix array.
*/
public function getTransformation(array $ctm): string
{
$this->ctm[$this->ctmid][] = $ctm;
return \sprintf('%F %F %F %F %F %F cm' . "\n", $ctm[0], $ctm[1], $ctm[2], $ctm[3], $ctm[4], $ctm[5]);
}
/**
* Vertical and horizontal non-proportional Scaling.
*
* @param float $skx Horizontal scaling factor.
* @param float $sky vertical scaling factor.
* @param float $posx Abscissa of the scaling center.
* @param float $posy Ordinate of the scaling center.
*
* @return string Transformation string
*
* @throws \Com\Tecnick\Pdf\Graph\Exception
*/
public function getScaling(float $skx, float $sky, float $posx, float $posy): string
{
if ($skx === 0.0 || $sky === 0.0) {
throw new GraphException('Scaling factors must be different than zero');
}
$posy = ($this->pageh - $posy) * $this->kunit;
$posx *= $this->kunit;
$ctm = [$skx, 0, 0, $sky, $posx * (1 - $skx), $posy * (1 - $sky)];
return $this->getTransformation($ctm);
}
/**
* Horizontal Scaling.
*
* @param float $skx Horizontal scaling factor.
* @param float $posx Abscissa of the scaling center.
* @param float $posy Ordinate of the scaling center.
*
* @return string Transformation string
*
* @throws \Com\Tecnick\Pdf\Graph\Exception
*/
public function getHorizScaling(float $skx, float $posx, float $posy): string
{
return $this->getScaling($skx, 1, $posx, $posy);
}
/**
* Vertical Scaling.
*
* @param float $sky vertical scaling factor.
* @param float $posx Abscissa of the scaling center.
* @param float $posy Ordinate of the scaling center.
*
* @return string Transformation string
*
* @throws \Com\Tecnick\Pdf\Graph\Exception
*/
public function getVertScaling(float $sky, float $posx, float $posy): string
{
return $this->getScaling(1, $sky, $posx, $posy);
}
/**
* Vertical and horizontal proportional Scaling.
*
* @param float $skf Scaling factor.
* @param float $posx Abscissa of the scaling center.
* @param float $posy Ordinate of the scaling center.
*
* @return string Transformation string
*
* @throws \Com\Tecnick\Pdf\Graph\Exception
*/
public function getPropScaling(float $skf, float $posx, float $posy): string
{
return $this->getScaling($skf, $skf, $posx, $posy);
}
/**
* Rotation.
*
* @param float $angle Angle in degrees for counter-clockwise rotation.
* @param float $posx Abscissa of the rotation center.
* @param float $posy Ordinate of the rotation center.
*
* @return string Transformation string
*/
public function getRotation(float $angle, float $posx, float $posy): string
{
$posy = ($this->pageh - $posy) * $this->kunit;
$posx *= $this->kunit;
$ctm = [];
$ctm[0] = \cos($this->degToRad($angle));
$ctm[1] = \sin($this->degToRad($angle));
$ctm[2] = -$ctm[1];
$ctm[3] = $ctm[0];
$ctm[4] = $posx + ($ctm[1] * $posy) - ($ctm[0] * $posx);
$ctm[5] = $posy - ($ctm[0] * $posy) - ($ctm[1] * $posx);
return $this->getTransformation($ctm);
}
/**
* Horizontal Mirroring.
*
* @param float $posx Abscissa of the mirroring line.
*
* @return string Transformation string
*
* @throws \Com\Tecnick\Pdf\Graph\Exception
*/
public function getHorizMirroring(float $posx): string
{
return $this->getScaling(-1, 1, $posx, 0);
}
/**
* Vertical Mirroring.
*
* @param float $posy Ordinate of the mirroring line.
*
* @return string Transformation string
*
* @throws \Com\Tecnick\Pdf\Graph\Exception
*/
public function getVertMirroring(float $posy): string
{
return $this->getScaling(1, -1, 0, $posy);
}
/**
* Point reflection mirroring.
*
* @param float $posx Abscissa of the mirroring point.
* @param float $posy Ordinate of the mirroring point.
*
* @return string Transformation string
*
* @throws \Com\Tecnick\Pdf\Graph\Exception
*/
public function getPointMirroring(float $posx, float $posy): string
{
return $this->getScaling(-1, -1, $posx, $posy);
}
/**
* Reflection against a straight line through point (x, y) with the gradient angle (angle).
*
* @param float $ang Gradient angle in degrees of the straight line.
* @param float $posx Abscissa of the mirroring point.
* @param float $posy Ordinate of the mirroring point.
*
* @return string Transformation string
*
* @throws \Com\Tecnick\Pdf\Graph\Exception
*/
public function getReflection(float $ang, float $posx, float $posy): string
{
return $this->getScaling(-1, 1, $posx, $posy) . $this->getRotation(-2 * ($ang - 90), $posx, $posy);
}
/**
* Translate graphic object horizontally and vertically.
*
* @param float $trx Movement to the right.
* @param float $try Movement to the bottom.
*
* @return string Transformation string
*/
public function getTranslation(float $trx, float $try): string
{
//calculate elements of transformation matrix
$ctm = [1, 0, 0, 1, $trx * $this->kunit, -$try * $this->kunit];
return $this->getTransformation($ctm);
}
/**
* Translate graphic object horizontally.
*
* @param float $trx Movement to the right.
*
* @return string Transformation string
*/
public function getHorizTranslation(float $trx): string
{
return $this->getTranslation($trx, 0);
}
/**
* Translate graphic object vertically.
*
* @param float $try Movement to the bottom.
*
* @return string Transformation string
*/
public function getVertTranslation(float $try): string
{
return $this->getTranslation(0, $try);
}
/**
* Skew.
*
* @param float $angx Angle in degrees between -90 (skew to the left) and 90 (skew to the right)
* @param float $angy Angle in degrees between -90 (skew to the bottom) and 90 (skew to the top)
* @param float $posx Abscissa of the skewing center.
* @param float $posy Ordinate of the skewing center.
*
* @return string Transformation string
*
* @throws \Com\Tecnick\Pdf\Graph\Exception
*/
public function getSkewing(float $angx, float $angy, float $posx, float $posy): string
{
if ($angx <= -90 || $angx >= 90 || $angy <= -90 || $angy >= 90) {
throw new GraphException('Angle values must be between -90 and +90 degrees.');
}
$posy = ($this->pageh - $posy) * $this->kunit;
$posx *= $this->kunit;
$ctm = [];
$ctm[0] = 1;
$ctm[1] = \tan($this->degToRad($angy));
$ctm[2] = \tan($this->degToRad($angx));
$ctm[3] = 1;
$ctm[4] = -$ctm[2] * $posy;
$ctm[5] = -$ctm[1] * $posx;
return $this->getTransformation($ctm);
}
/**
* Skew horizontally.
*
* @param float $angx Angle in degrees between -90 (skew to the left) and 90 (skew to the right)
* @param float $posx Abscissa of the skewing center.
* @param float $posy Ordinate of the skewing center.
*
* @return string Transformation string
*
* @throws \Com\Tecnick\Pdf\Graph\Exception
*/
public function getHorizSkewing(float $angx, float $posx, float $posy): string
{
return $this->getSkewing($angx, 0, $posx, $posy);
}
/**
* Skew vertically.
*
* @param float $angy Angle in degrees between -90 (skew to the bottom) and 90 (skew to the top)
* @param float $posx Abscissa of the skewing center.
* @param float $posy Ordinate of the skewing center.
*
* @return string Transformation string
*
* @throws \Com\Tecnick\Pdf\Graph\Exception
*/
public function getVertSkewing(float $angy, float $posx, float $posy): string
{
return $this->getSkewing(0, $angy, $posx, $posy);
}
/**
* Get the product of two Transformation Matrix.
*
* @param TTMatrix $tma First Transformation Matrix.
* @param TTMatrix $tmb Second Transformation Matrix.
*
* @return TTMatrix CTM Transformation Matrix.
*/
public function getCtmProduct(array $tma, array $tmb): array
{
return [
($tma[0] * $tmb[0]) + ($tma[2] * $tmb[1]),
($tma[1] * $tmb[0]) + ($tma[3] * $tmb[1]),
($tma[0] * $tmb[2]) + ($tma[2] * $tmb[3]),
($tma[1] * $tmb[2]) + ($tma[3] * $tmb[3]),
($tma[0] * $tmb[4]) + ($tma[2] * $tmb[5]) + $tma[4],
($tma[1] * $tmb[4]) + ($tma[3] * $tmb[5]) + $tma[5],
];
}
/**
* Converts the number in degrees to the radian equivalent.
* We use this instead of the deg2rad() function to avoid precision problems with hhvm.
*
* @param float $deg Angular value in degrees.
*
* @return float Angle in radians
*/
public function degToRad(float $deg): float
{
return ($deg * self::MPI) / 180;
}
}
+503
View File
@@ -0,0 +1,503 @@
<?php
/**
* BaseTest.php
*
* @since 2011-05-23
* @category Library
* @package PdfGraph
* @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-graph
*
* This file is part of tc-lib-pdf-graph software library.
*/
namespace Test;
/**
* Base Test
*
* @since 2011-05-23
* @category Library
* @package PdfGraph
* @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-graph
*/
class BaseTest extends TestUtil
{
protected function getTestObject(): \Com\Tecnick\Pdf\Graph\Draw
{
return new \Com\Tecnick\Pdf\Graph\Draw(
0.75,
80,
100,
new \Com\Tecnick\Color\Pdf(),
$this->getEncryptObject(),
false,
);
}
/**
* @throws \Com\Tecnick\Pdf\Graph\Exception
*/
public function testGetOutResourcesByKeysSkipInvalidEntries(): void
{
$draw = $this->getTestObject();
$draw->getOverprint();
$draw->getGradient(
2,
[0, 0, 1, 0],
[
['color' => 'red', 'offset' => 0.0],
['color' => 'blue', 'offset' => 1.0],
],
'',
false,
);
$this->assertSame(' /ExtGState << >>' . "\n", $draw->getOutExtGStateResourcesByKeys([999]));
$this->assertSame('', $draw->getOutGradientResourcesByKeys([999]));
}
/**
* @throws \Com\Tecnick\Pdf\Graph\Exception
* @throws \Com\Tecnick\Pdf\Encrypt\Exception
*/
public function testGradientShadersHandleMalformedStopsAndFloatExponent(): void
{
$draw = $this->getTestObject();
$draw->getGradient(
2,
[0, 0, 1, 0],
[
['color' => 'red', 'offset' => 0.0, 'opacity' => 0.5],
['color' => 'blue', 'offset' => 1.0, 'opacity' => 0.6, 'exponent' => 1.5],
],
'',
false,
);
$outFloatExponent = $draw->getOutGradientShaders($draw->getObjectNumber());
$this->assertStringContainsString('/N 1.5', $outFloatExponent);
}
/**
* @throws \Com\Tecnick\Pdf\Graph\Exception
* @throws \Com\Tecnick\Pdf\Encrypt\Exception
*/
public function testGetOutGradientShadersSkipsMissingOpacityPattern(): void
{
$draw = new class(0.75, 80, 100, new \Com\Tecnick\Color\Pdf(), $this->getEncryptObject(), false) extends
\Com\Tecnick\Pdf\Graph\Draw {
/**
* @param array<int, array{
* antialias: bool,
* background: ?\Com\Tecnick\Color\Model,
* colors: array<int, array{color: string, exponent?: float, offset?: float, opacity?: float}>,
* colspace: string,
* coords: array<float>,
* id: int,
* pattern: int,
* stream: string,
* transparency: bool,
* type: int,
* }> $grads
*/
public function setGradientsForTest(array $grads): void
{
$this->gradients = $grads;
}
protected function getOutGradientCols(array $grad, string $type): string
{
if ($type === 'opacity') {
return '';
}
return parent::getOutGradientCols($grad, $type);
}
};
$draw->setGradientsForTest([
1 => [
'antialias' => false,
'background' => null,
'colors' => [
0 => ['color' => 'red', 'offset' => 0.0, 'opacity' => 0.5, 'exponent' => 1.0],
1 => ['color' => 'blue', 'offset' => 1.0, 'opacity' => 0.6, 'exponent' => 1.0],
],
'colspace' => 'DeviceRGB',
'coords' => [0.0, 0.0, 1.0, 0.0],
'id' => 0,
'pattern' => 0,
'stream' => '',
'transparency' => true,
'type' => 2,
],
]);
$out = $draw->getOutGradientShaders(10);
$this->assertNotSame('', $out);
}
/**
* @throws \Com\Tecnick\Pdf\Graph\Exception
*/
public function testGetOutExtGState(): void
{
$draw = $this->getTestObject();
$res = $draw->getOutExtGState(10);
$this->assertEquals('', $res);
$draw->getOverprint();
$draw->getAlpha();
$res = $draw->getOutExtGState(10);
$this->assertEquals(
'11 0 obj'
. "\n"
. '<< /Type /ExtGState /OP true /op true /OPM 0.000000 >>'
. "\n"
. 'endobj'
. "\n"
. '12 0 obj'
. "\n"
. '<< /Type /ExtGState /CA 1.000000 /ca 1.000000 /BM /Normal /AIS false >>'
. "\n"
. 'endobj'
. "\n",
$res,
);
$this->assertEquals(12, $draw->getObjectNumber());
$this->assertEquals(2, $draw->getLastExtGStateID());
}
/**
* @SuppressWarnings("PHPMD.LongVariable")
* @throws \Com\Tecnick\Pdf\Graph\Exception
*/
public function testGetOutExtGStateResourcesEmpty(): void
{
$draw = $this->getTestObject();
$outExtGStateResources = $draw->getOutExtGStateResources();
$this->assertEquals('', $outExtGStateResources);
}
/**
* @throws \Com\Tecnick\Pdf\Graph\Exception
*/
public function testGetOutGradientResourcesEmpty(): void
{
$draw = $this->getTestObject();
$outGradientResources = $draw->getOutGradientResources();
$this->assertEquals('', $outGradientResources);
}
/**
* @throws \Com\Tecnick\Pdf\Graph\Exception
* @throws \Com\Tecnick\Pdf\Encrypt\Exception
*/
public function testGetOutGradientShaders(): void
{
$draw = $this->getTestObject();
$res = $draw->getOutGradientShaders(10);
$this->assertEquals('', $res);
$draw->getCoonsPatchMeshWithCoords(3, 5, 7, 11);
$draw->getOutGradientShaders(11);
$this->assertEquals(13, $draw->getObjectNumber());
$res = $draw->getOutGradientResources();
$this->assertEquals(' /Pattern << /p1 13 0 R >>' . "\n" . ' /Shading << /Sh1 12 0 R >>' . "\n", $res);
$nres = $draw->getOutGradientResourcesByKeys([]);
$this->assertEmpty($nres);
$resx = $draw->getOutGradientResourcesByKeys([1]);
$this->assertEquals(' /Pattern << /p1 13 0 R >>' . "\n" . ' /Shading << /Sh1 12 0 R >>' . "\n", $resx);
}
/**
* @throws \Com\Tecnick\Pdf\Graph\Exception
* @throws \Com\Tecnick\Pdf\Encrypt\Exception
*/
public function testGetOutShaders(): void
{
$draw = $this->getTestObject();
$stops = [
[
'color' => 'red',
'exponent' => 1,
'opacity' => 0.5,
],
[
'color' => 'blue',
'exponent' => 1,
'offset' => 0.2,
'opacity' => 0.6,
],
[
'color' => '#98fb98',
'exponent' => 1,
'opacity' => 0.7,
],
[
'color' => 'rgb(64,128,191)',
'exponent' => 1,
'offset' => 0.8,
'opacity' => 0.8,
],
[
'color' => 'skyblue',
'exponent' => 1,
'opacity' => 0.9,
],
];
$this->assertEquals('/TGS1 gs' . "\n" . '/Sh1 sh' . "\n", $draw->getGradient(
2,
[0, 0, 1, 0],
$stops,
'',
false,
));
$draw->getOverprint();
$draw->getAlpha();
$draw->getOutExtGState($draw->getObjectNumber());
$draw->getOutGradientShaders($draw->getObjectNumber());
$this->assertEquals(19, $draw->getObjectNumber());
$res = $draw->getOutExtGStateResources();
$this->assertEquals(' /ExtGState << /GS1 1 0 R /GS2 2 0 R /TGS1 19 0 R >>' . "\n", $res);
$nres = $draw->getOutExtGStateResourcesByKeys([]);
$this->assertEmpty($nres);
$resx = $draw->getOutExtGStateResourcesByKeys([1, 2]);
$this->assertEquals(' /ExtGState << /GS1 1 0 R /GS2 2 0 R >>' . "\n", $resx);
}
/**
* @throws \Com\Tecnick\Pdf\Graph\Exception
* @throws \Com\Tecnick\Pdf\Encrypt\Exception
*/
public function testGetOutShadersRadial(): void
{
$draw = $this->getTestObject();
$out = $draw->getGradient(
3,
[0.6, 0.5, 0.4, 0.3, 1],
[
[
'color' => 'red',
'exponent' => 1,
'offset' => 0,
],
[
'color' => 'green',
'exponent' => 1,
'offset' => 1,
],
],
'white',
true,
);
$this->assertEquals('/Sh1 sh' . "\n", $out);
$this->assertEquals(0, $draw->getObjectNumber());
$draw->getOutGradientShaders($draw->getObjectNumber());
$this->assertEquals(4, $draw->getObjectNumber());
}
/**
* @throws \Com\Tecnick\Pdf\Graph\Exception
* @throws \Com\Tecnick\Pdf\Encrypt\Exception
*/
public function testGetOutGradientShadersInvalidColor(): void
{
$draw = $this->getTestObject();
$stops = [
[
'color' => 'red',
'exponent' => 1.0,
'opacity' => 1.0,
],
[
'color' => 'not-a-valid-color',
'exponent' => 1.0,
'opacity' => 1.0,
],
[
'color' => 'blue',
'exponent' => 1.0,
'opacity' => 1.0,
],
];
$draw->getGradient(2, [0, 0, 1, 0], $stops, '', false);
$res = $draw->getOutGradientShaders($draw->getObjectNumber());
$this->assertNotEmpty($res);
}
/**
* @throws \Com\Tecnick\Pdf\Graph\Exception
*/
public function testGetTransparencyExtGStateNamesEmpty(): void
{
$draw = $this->getTestObject();
$this->assertSame([], $draw->getTransparencyExtGStateNames());
}
/**
* @throws \Com\Tecnick\Pdf\Graph\Exception
*/
public function testGetTransparencyExtGStateNamesIgnoresOpaque(): void
{
$draw = $this->getTestObject();
// Overprint carries no alpha/blend/soft-mask information.
$draw->getOverprint();
// A fully opaque alpha (CA = ca = 1, BM = Normal, no SMask) must be ignored.
$draw->getAlpha();
$this->assertSame([], $draw->getTransparencyExtGStateNames());
}
/**
* @throws \Com\Tecnick\Pdf\Graph\Exception
*/
public function testGetTransparencyExtGStateNamesDetectsTransparency(): void
{
$draw = $this->getTestObject();
// GS1: stroking alpha below 1 (CA).
$draw->getAlpha(0.5, 'Normal', 1.0);
// GS2: non-stroking alpha below 1 (ca).
$draw->getAlpha(1.0, 'Normal', 0.4);
// GS3: non-Normal blend mode.
$draw->getAlpha(1.0, 'Multiply', 1.0);
// GS4: an explicit soft mask.
$draw->getExtGState(['SMask' => '/Foo']);
// GS5: fully opaque, must be skipped.
$draw->getAlpha();
$this->assertSame(['GS1', 'GS2', 'GS3', 'GS4'], $draw->getTransparencyExtGStateNames());
}
/**
* @throws \Com\Tecnick\Pdf\Graph\Exception
* @throws \Com\Tecnick\Pdf\Encrypt\Exception
*/
public function testGetTransparencyExtGStateNamesUsesAssignedName(): void
{
$draw = new class(0.75, 80, 100, new \Com\Tecnick\Color\Pdf(), $this->getEncryptObject(), false) extends
\Com\Tecnick\Pdf\Graph\Draw {
/**
* @param array<int, array{
* 'n': int,
* 'name': string,
* 'parms': array<string, int|float|bool|string>,
* }> $extgstates
*/
public function setExtGStatesForTest(array $extgstates): void
{
$this->extgstates = $extgstates;
}
};
$draw->setExtGStatesForTest([
// Named transparent entry: the assigned name is returned verbatim.
3 => ['n' => 0, 'name' => 'NAMEDGS', 'parms' => ['ca' => 0.25]],
// Unnamed transparent entry: the name falls back to "GS" . key.
4 => ['n' => 0, 'name' => '', 'parms' => ['CA' => 0.5]],
// Named but opaque entry: must be skipped.
5 => ['n' => 0, 'name' => 'OPAQUE', 'parms' => ['ca' => 1.0]],
]);
$this->assertSame(['NAMEDGS', 'GS4'], $draw->getTransparencyExtGStateNames());
}
/**
* Axial (type 2) and radial (type 3) shading dictionaries must terminate
* with a real newline before "endobj", not a literal backslash-n.
*
* @throws \Com\Tecnick\Pdf\Graph\Exception
* @throws \Com\Tecnick\Pdf\Encrypt\Exception
*/
public function testGradientShadingDictionaryUsesRealNewline(): void
{
$draw = $this->getTestObject();
// axial shading
$draw->getGradient(
2,
[0, 0, 1, 0],
[
['color' => 'red', 'offset' => 0.0],
['color' => 'blue', 'offset' => 1.0],
],
'',
false,
);
// radial shading
$draw->getGradient(
3,
[0.5, 0.5, 0.5, 0.5, 1],
[
['color' => 'red', 'offset' => 0.0],
['color' => 'green', 'offset' => 1.0],
],
'',
false,
);
$out = $draw->getOutGradientShaders($draw->getObjectNumber());
// the shading dictionary must end with ">>" followed by a real newline and "endobj"
$this->assertStringContainsString('/Extend [true true] >>' . "\n" . 'endobj', $out);
// it must NOT contain a literal backslash-n sequence (single-quoted: backslash + n)
$this->assertStringNotContainsString('>>\n', $out);
}
/**
* A transparent gradient registers a luminosity soft-mask ExtGState that
* must be reported as carrying actual transparency.
*
* @throws \Com\Tecnick\Pdf\Graph\Exception
* @throws \Com\Tecnick\Pdf\Encrypt\Exception
*/
public function testGetTransparencyExtGStateNamesDetectsGradientSoftMask(): void
{
$draw = $this->getTestObject();
// a gradient with opacity < 1 generates a luminosity soft mask
$draw->getGradient(
2,
[0, 0, 1, 0],
[
['color' => 'red', 'offset' => 0.0, 'opacity' => 0.5],
['color' => 'blue', 'offset' => 1.0, 'opacity' => 0.5],
],
'',
false,
);
// the TGS ExtGState only exists after the shaders have been generated
$this->assertSame([], $draw->getTransparencyExtGStateNames());
$draw->getOutGradientShaders($draw->getObjectNumber());
$this->assertContains('TGS1', $draw->getTransparencyExtGStateNames());
}
}
@@ -0,0 +1,94 @@
<?php
/**
* BlendModeTest.php
*
* @since 2026-07-17
* @category Library
* @package PdfGraph
* @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-graph
*
* This file is part of tc-lib-pdf-graph software library.
*/
namespace Test;
use Com\Tecnick\Pdf\Graph\BlendMode;
/**
* BlendMode enum test
*
* @since 2026-07-17
* @category Library
* @package PdfGraph
* @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-graph
*/
class BlendModeTest extends TestUtil
{
protected function getTestObject(): \Com\Tecnick\Pdf\Graph\Draw
{
return new \Com\Tecnick\Pdf\Graph\Draw(1, 0, 0, new \Com\Tecnick\Color\Pdf(), $this->getEncryptObject(), false);
}
public function testCaseBackingValues(): void
{
$this->assertSame('Normal', BlendMode::Normal->value);
$this->assertSame('Multiply', BlendMode::Multiply->value);
$this->assertSame('Luminosity', BlendMode::Luminosity->value);
$this->assertCount(16, BlendMode::cases());
}
public function testFromLooseCanonical(): void
{
$this->assertSame(BlendMode::Multiply, BlendMode::fromLoose('Multiply'));
$this->assertSame(BlendMode::ColorBurn, BlendMode::fromLoose('ColorBurn'));
}
public function testFromLooseStripsLeadingSlash(): void
{
$this->assertSame(BlendMode::Screen, BlendMode::fromLoose('/Screen'));
}
public function testFromLooseFallsBackToNormal(): void
{
$this->assertSame(BlendMode::Normal, BlendMode::fromLoose('bogus'));
$this->assertSame(BlendMode::Normal, BlendMode::fromLoose(''));
// case sensitive: wrong case is unknown and falls back
$this->assertSame(BlendMode::Normal, BlendMode::fromLoose('multiply'));
}
public function testFromLoosePassesThroughEnumInstance(): void
{
$this->assertSame(BlendMode::HardLight, BlendMode::fromLoose(BlendMode::HardLight));
}
public function testFromLooseRoundTrip(): void
{
foreach (BlendMode::cases() as $case) {
$this->assertSame($case, BlendMode::fromLoose($case->value));
}
}
/**
* The widened getAlpha() accepts a BlendMode enum; equal blend modes dedupe
* to the same ExtGState reference, different ones do not.
*
* @throws \Com\Tecnick\Pdf\Graph\Exception
*/
public function testGetAlphaAcceptsEnum(): void
{
$draw = $this->getTestObject();
$fromEnum = $draw->getAlpha(1.0, BlendMode::Multiply);
$this->assertSame($fromEnum, $draw->getAlpha(1.0, 'Multiply'));
$this->assertSame($fromEnum, $draw->getAlpha(1.0, '/Multiply'));
$this->assertNotSame($fromEnum, $draw->getAlpha(1.0, BlendMode::Screen));
// unknown blend mode falls back to Normal
$this->assertSame($draw->getAlpha(1.0, 'Normal'), $draw->getAlpha(1.0, 'bogus'));
}
}
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,118 @@
<?php
/**
* PathPaintOpTest.php
*
* @since 2026-07-17
* @category Library
* @package PdfGraph
* @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-graph
*
* This file is part of tc-lib-pdf-graph software library.
*/
namespace Test;
use Com\Tecnick\Pdf\Graph\PathPaintOp;
/**
* PathPaintOp enum test
*
* @since 2026-07-17
* @category Library
* @package PdfGraph
* @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-graph
*/
class PathPaintOpTest extends TestUtil
{
protected function getTestObject(): \Com\Tecnick\Pdf\Graph\Draw
{
return new \Com\Tecnick\Pdf\Graph\Draw(1, 0, 0, new \Com\Tecnick\Color\Pdf(), $this->getEncryptObject(), false);
}
public function testCaseBackingValues(): void
{
$this->assertSame('S', PathPaintOp::Stroke->value);
$this->assertSame('f', PathPaintOp::Fill->value);
$this->assertSame('h f', PathPaintOp::CloseFill->value);
$this->assertSame('B*', PathPaintOp::FillStrokeEvenOdd->value);
$this->assertSame('W n', PathPaintOp::Clip->value);
$this->assertSame('W* n', PathPaintOp::ClipEvenOdd->value);
$this->assertCount(14, PathPaintOp::cases());
}
public function testFromLooseCanonical(): void
{
$this->assertSame(PathPaintOp::Stroke, PathPaintOp::fromLoose('S'));
$this->assertSame(PathPaintOp::Fill, PathPaintOp::fromLoose('f'));
$this->assertSame(PathPaintOp::NoOp, PathPaintOp::fromLoose('n'));
}
public function testFromLooseResolvesAliases(): void
{
$this->assertSame(PathPaintOp::Stroke, PathPaintOp::fromLoose('D'));
$this->assertSame(PathPaintOp::CloseStroke, PathPaintOp::fromLoose('h S'));
$this->assertSame(PathPaintOp::Fill, PathPaintOp::fromLoose('F'));
$this->assertSame(PathPaintOp::FillStroke, PathPaintOp::fromLoose('FD'));
$this->assertSame(PathPaintOp::FillStroke, PathPaintOp::fromLoose('DF'));
$this->assertSame(PathPaintOp::FillStrokeEvenOdd, PathPaintOp::fromLoose('F*D'));
$this->assertSame(PathPaintOp::CloseFillStroke, PathPaintOp::fromLoose('df'));
$this->assertSame(PathPaintOp::Clip, PathPaintOp::fromLoose('CNZ'));
$this->assertSame(PathPaintOp::ClipEvenOdd, PathPaintOp::fromLoose('CEO'));
}
public function testFromLooseFallsBackToStroke(): void
{
$this->assertSame(PathPaintOp::Stroke, PathPaintOp::fromLoose('nonsense'));
$this->assertSame(PathPaintOp::Stroke, PathPaintOp::fromLoose(''));
}
public function testFromLoosePassesThroughEnumInstance(): void
{
$this->assertSame(PathPaintOp::Clip, PathPaintOp::fromLoose(PathPaintOp::Clip));
}
public function testFromLooseRoundTrip(): void
{
foreach (PathPaintOp::cases() as $case) {
$this->assertSame($case, PathPaintOp::fromLoose($case->value));
}
}
/**
* The widened getPathPaintOp() accepts a PathPaintOp enum for both $mode and
* $default, staying consistent with the legacy string call.
*
* @throws \Com\Tecnick\Pdf\Graph\Exception
*/
public function testGetPathPaintOpAcceptsEnum(): void
{
$draw = $this->getTestObject();
$this->assertSame("f\n", $draw->getPathPaintOp(PathPaintOp::Fill));
$this->assertSame("B\n", $draw->getPathPaintOp(PathPaintOp::FillStroke));
$this->assertSame($draw->getPathPaintOp('CEO'), $draw->getPathPaintOp(PathPaintOp::ClipEvenOdd));
// enum used as the $default when the mode is unknown/empty
$this->assertSame("b\n", $draw->getPathPaintOp('', PathPaintOp::CloseFillStroke));
}
/**
* A drawing method that funnels $mode through the string predicates accepts
* a PathPaintOp enum too (getPolygon normalizes it once).
*
* @throws \Com\Tecnick\Pdf\Graph\Exception
*/
public function testDrawingMethodAcceptsEnum(): void
{
$draw = $this->getTestObject();
$fromEnum = $draw->getRect(0, 0, 10, 10, PathPaintOp::Fill);
$fromString = $draw->getRect(0, 0, 10, 10, 'f');
$this->assertNotSame('', $fromEnum);
$this->assertSame($fromString, $fromEnum);
}
}
+284
View File
@@ -0,0 +1,284 @@
<?php
/**
* RawTest.php
*
* @since 2011-05-23
* @category Library
* @package PdfGraph
* @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-graph
*
* This file is part of tc-lib-pdf-graph software library.
*/
namespace Test;
/**
* Raw Test
*
* @since 2011-05-23
* @category Library
* @package PdfGraph
* @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-graph
*/
class RawTest extends TestUtil
{
protected function getTestObject(): \Com\Tecnick\Pdf\Graph\Draw
{
return new \Com\Tecnick\Pdf\Graph\Draw(
0.75,
80,
100,
new \Com\Tecnick\Color\Pdf(),
$this->getEncryptObject(),
false,
);
}
/**
* @throws \Com\Tecnick\Pdf\Graph\Exception
*/
public function testGetRawPoint(): void
{
$draw = $this->getTestObject();
$this->assertEquals('2.250000 71.250000 m' . "\n", $draw->getRawPoint(3, 5));
}
/**
* @throws \Com\Tecnick\Pdf\Graph\Exception
*/
public function testGetRawLine(): void
{
$draw = $this->getTestObject();
$this->assertEquals('2.250000 71.250000 l' . "\n", $draw->getRawLine(3, 5));
}
/**
* @throws \Com\Tecnick\Pdf\Graph\Exception
*/
public function testGetRawRect(): void
{
$draw = $this->getTestObject();
$this->assertEquals('2.250000 71.250000 5.250000 -8.250000 re' . "\n", $draw->getRawRect(3, 5, 7, 11));
}
/**
* @throws \Com\Tecnick\Pdf\Graph\Exception
*/
public function testGetRawCurve(): void
{
$draw = $this->getTestObject();
$this->assertEquals('2.250000 71.250000 5.250000 66.750000 9.750000 62.250000 c' . "\n", $draw->getRawCurve(
3,
5,
7,
11,
13,
17,
));
}
/**
* @throws \Com\Tecnick\Pdf\Graph\Exception
*/
public function testGetRawCurveV(): void
{
$draw = $this->getTestObject();
$this->assertEquals('2.250000 71.250000 5.250000 66.750000 v' . "\n", $draw->getRawCurveV(3, 5, 7, 11));
}
/**
* @throws \Com\Tecnick\Pdf\Graph\Exception
*/
public function testGetRawCurveY(): void
{
$draw = $this->getTestObject();
$this->assertEquals('2.250000 71.250000 5.250000 66.750000 y' . "\n", $draw->getRawCurveY(3, 5, 7, 11));
}
/**
* @throws \Com\Tecnick\Pdf\Graph\Exception
*/
public function testGetRawEllipticalArc(): void
{
$draw = $this->getTestObject();
$res = $draw->getRawEllipticalArc(0, 0, 0, 0);
$this->assertEquals('', $res);
$res = $draw->getRawEllipticalArc(3, 5, 7, 11);
$this->assertEquals(
'7.500000 71.250000 m'
. "\n"
. '7.500000 73.189135 7.064930 75.067534 6.271733 76.552998 c'
. "\n"
. '5.478536 78.038462 4.376901 79.037937 3.161653 79.374664 c'
. "\n"
. '1.946405 79.711391 0.693671 79.364277 -0.375000 78.394710 c'
. "\n"
. '-1.443671 77.425142 -2.261335 75.893857 -2.683386 74.071666 c'
. "\n"
. '-3.105437 72.249475 -3.105437 70.250525 -2.683386 68.428334 c'
. "\n"
. '-2.261335 66.606143 -1.443671 65.074858 -0.375000 64.105290 c'
. "\n"
. '0.693671 63.135723 1.946405 62.788609 3.161653 63.125336 c'
. "\n"
. '4.376901 63.462063 5.478536 64.461538 6.271733 65.947002 c'
. "\n"
. '7.064930 67.432466 7.500000 69.310865 7.500000 71.250000 c'
. "\n",
$res,
);
$bbox = [];
$res = $draw->getRawEllipticalArc(3, 5, 7, 11, 0, -180, -90, true, 1.8, false, false, true, $bbox);
$this->assertEquals(
'2.250000 71.250000 m'
. "\n"
. '-3.000000 71.250000 l'
. "\n"
. '-3.000000 73.118591 -2.596009 74.932867 -1.854615 76.393791 c'
. "\n"
. '-1.113221 77.854714 -0.077525 78.877355 1.081765 79.293155 c'
. "\n"
. '2.241055 79.708956 3.456544 79.493745 4.527890 78.682993 c'
. "\n"
. '5.599235 77.872242 6.464154 76.513084 6.980087 74.829541 c'
. "\n"
. '7.496019 73.145998 7.632972 71.235944 7.368372 69.414202 c'
. "\n"
. '7.103771 67.592460 6.453000 65.964938 5.523321 64.799890 c'
. "\n"
. '4.593643 63.634843 3.439104 63.000000 2.250000 63.000000 c'
. "\n"
. '2.250000 71.250000 l'
. "\n",
$res,
);
$res = $draw->getRawEllipticalArc(3, 5, 7, 11, 0, 90, 45);
$this->assertEquals(
'2.250000 79.500000 m'
. "\n"
. '1.084822 79.500000 -0.047846 78.890447 -0.968406 77.767993 c'
. "\n"
. '-1.888967 76.645539 -2.546049 75.072821 -2.835467 73.299209 c'
. "\n"
. '-3.124884 71.525598 -3.030486 69.650067 -2.567240 67.970002 c'
. "\n"
. '-2.103993 66.289938 -1.297750 64.899093 -0.276348 64.018002 c'
. "\n"
. '0.745054 63.136911 1.924617 62.814741 3.075308 63.102576 c'
. "\n"
. '4.225999 63.390411 5.283605 64.272189 6.080433 65.608093 c'
. "\n"
. '6.877260 66.943998 7.368843 68.659482 7.477234 70.482537 c'
. "\n"
. '7.585626 72.305591 7.304778 74.134484 6.679223 75.679223 c'
. "\n",
$res,
);
}
/**
* @throws \Com\Tecnick\Pdf\Graph\Exception
*/
public function testGetVectorsAngle(): void
{
$draw = $this->getTestObject();
$res = $draw->getVectorsAngle(0, 0, 0, 0);
$this->bcAssertEqualsWithDelta(0, $res);
$res = $draw->getVectorsAngle(0, 1, 0, 1);
$this->bcAssertEqualsWithDelta(0, $res);
$res = $draw->getVectorsAngle(1, 1, 2, 2);
$this->bcAssertEqualsWithDelta(0, $res);
$res = $draw->getVectorsAngle(1, 0, 0, 1);
$this->bcAssertEqualsWithDelta(1.57, $res);
$res = $draw->getVectorsAngle(0, 1, 1, 0);
$this->bcAssertEqualsWithDelta(-1.57, $res);
$res = $draw->getVectorsAngle(1, 0, 1, 1);
$this->bcAssertEqualsWithDelta(0.79, $res);
$res = $draw->getVectorsAngle(-1, -1, 1, 1);
$this->bcAssertEqualsWithDelta(M_PI, $res);
$res = $draw->getVectorsAngle(1, 0, -1, 0);
$this->bcAssertEqualsWithDelta(M_PI, $res);
}
/**
* @throws \Com\Tecnick\Pdf\Graph\Exception
*/
public function testGetRawEllipticalArcBboxPopulated(): void
{
$draw = $this->getTestObject();
$bbox = [];
// full circle: bbox should be fully populated (no sentinel values remaining)
$draw->getRawEllipticalArc(3, 5, 7, 11, 0, 0, 360, false, 2, true, true, false, $bbox);
$this->assertCount(4, $bbox);
$minx = $bbox[0] ?? PHP_INT_MAX;
$miny = $bbox[1] ?? PHP_INT_MAX;
$maxx = $bbox[2] ?? PHP_INT_MIN;
$maxy = $bbox[3] ?? PHP_INT_MIN;
$this->assertLessThan(PHP_INT_MAX, $minx); // min-x was updated
$this->assertLessThan(PHP_INT_MAX, $miny); // min-y was updated
$this->assertGreaterThan(PHP_INT_MIN, $maxx); // max-x was updated
$this->assertGreaterThan(PHP_INT_MIN, $maxy); // max-y was updated
}
/**
* @throws \Com\Tecnick\Pdf\Graph\Exception
*/
public function testGetRawEllipticalArcBboxNegativeMaxValues(): void
{
$draw = $this->getTestObject();
// Arc from 45° to 90° with centre at (0, 0) and vertical radius 5.
// In this range every cy control point is negative (cy = -rdv * sin(ang)).
// The PHP_INT_MIN initialisation ensures the max values are updated correctly
// even when all sampled points are negative.
$bbox = [];
$draw->getRawEllipticalArc(0, 0, 7, 5, 0, 45, 90, false, 2, true, true, false, $bbox);
$this->assertCount(4, $bbox);
$maxx = $bbox[2] ?? PHP_INT_MIN;
$maxy = $bbox[3] ?? PHP_INT_MIN;
$this->assertGreaterThan(PHP_INT_MIN, $maxx); // max-x was updated from sentinel
$this->assertGreaterThan(PHP_INT_MIN, $maxy); // max-y was updated from sentinel
$this->assertLessThan(0, $maxy); // all cy values in this arc are < 0
}
/**
* A zero vertical radius means "circle" (per the docblock) and must not
* trigger a division by zero.
*
* @throws \Com\Tecnick\Pdf\Graph\Exception
*/
public function testGetRawEllipticalArcZeroVerticalRadius(): void
{
$draw = $this->getTestObject();
// rdv = 0 must be treated as a circle (rdv = rdh), not crash.
$out = $draw->getRawEllipticalArc(3, 5, 7, 0);
$this->assertNotSame('', $out);
// identical to passing the horizontal radius as the vertical one
$this->assertSame($draw->getRawEllipticalArc(3, 5, 7, 7), $out);
}
}
+509
View File
@@ -0,0 +1,509 @@
<?php
/**
* StyleTest.php
*
* @since 2011-05-23
* @category Library
* @package PdfGraph
* @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-graph
*
* This file is part of tc-lib-pdf-graph software library.
*/
namespace Test;
/**
* Style Test
*
* @since 2011-05-23
* @category Library
* @package PdfGraph
* @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-graph
*/
class StyleTest extends TestUtil
{
protected function getTestObject(): \Com\Tecnick\Pdf\Graph\Draw
{
return new \Com\Tecnick\Pdf\Graph\Draw(1, 0, 0, new \Com\Tecnick\Color\Pdf(), $this->getEncryptObject(), false);
}
/**
* @throws \Com\Tecnick\Pdf\Graph\Exception
*/
public function testGetStyleCmd(): void
{
$draw = $this->getTestObject();
$styleCmd = $draw->getStyleCmd();
$exp1 = '';
$this->assertEquals($exp1, $styleCmd);
$style2 = [
'lineWidth' => 3,
'lineCap' => 'round',
'lineJoin' => 'bevel',
'miterLimit' => 11,
'dashArray' => [5, 7],
'dashPhase' => 0,
'lineColor' => 'greenyellow',
'fillColor' => '["RGB",0.250000,0.500000,0.750000]',
];
$res2 = $draw->getStyleCmd($style2);
$exp2 =
'3.000000 w'
. "\n"
. '1 J'
. "\n"
. '2 j'
. "\n"
. '11.000000 M'
. "\n"
. '[5.000000 7.000000] 0.000000 d'
. "\n"
. '0.678431 1.000000 0.184314 RG'
. "\n"
. '0.250000 0.500000 0.750000 rg'
. "\n";
$this->assertEquals($exp2, $res2);
}
/**
* @throws \Com\Tecnick\Pdf\Graph\Exception
*/
public function testStyle(): void
{
$draw = $this->getTestObject();
$style = [];
$res1 = $draw->add($style, true);
$exp1 =
'1.000000 w'
. "\n"
. '0 J'
. "\n"
. '0 j'
. "\n"
. '10.000000 M'
. "\n"
. '[] 0.000000 d'
. "\n"
. '/CS1 CS 1.000000 SCN'
. "\n"
. '/CS1 cs 1.000000 scn'
. "\n";
$this->assertEquals($exp1, $res1);
$style = [
'lineWidth' => 3,
'lineCap' => 'round',
'lineJoin' => 'bevel',
'miterLimit' => 11,
'dashArray' => [5, 7],
'dashPhase' => 1,
'lineColor' => 'greenyellow',
'fillColor' => '["RGB",0.250000,0.500000,0.750000]',
];
$res2 = $draw->add($style, false);
$exp2 =
'3.000000 w'
. "\n"
. '1 J'
. "\n"
. '2 j'
. "\n"
. '11.000000 M'
. "\n"
. '[5.000000 7.000000] 1.000000 d'
. "\n"
. '0.678431 1.000000 0.184314 RG'
. "\n"
. '0.250000 0.500000 0.750000 rg'
. "\n";
$this->assertEquals($exp2, $res2);
$this->assertEquals($style, $draw->getCurrentStyleArray());
$style = [
'lineCap' => 'round',
'lineJoin' => 'bevel',
'lineColor' => 'transparent',
'fillColor' => 'cmyk(67,33,0,25)',
];
$res3 = $draw->add($style, true);
$exp3 =
'3.000000 w'
. "\n"
. '1 J'
. "\n"
. '2 j'
. "\n"
. '11.000000 M'
. "\n"
. '[5.000000 7.000000] 1.000000 d'
. "\n"
. '0.670000 0.330000 0.000000 0.250000 k'
. "\n";
$this->assertEquals($exp3, $res3);
$style = [
'lineCap' => 'round',
'lineJoin' => 'bevel',
'lineColor' => 'transparent',
'fillColor' => 'cmyk(67,33,0,25)',
'dashArray' => [],
];
$res4 = $draw->add($style, true);
$exp4 =
'3.000000 w'
. "\n"
. '1 J'
. "\n"
. '2 j'
. "\n"
. '11.000000 M'
. "\n"
. '[] 1.000000 d'
. "\n"
. '0.670000 0.330000 0.000000 0.250000 k'
. "\n";
$this->assertEquals($exp4, $res4);
$style = [
'lineWidth' => 7.123,
];
$res5 = $draw->add($style, false);
$exp5 = '7.123000 w' . "\n";
$this->assertEquals($exp5, $res5);
$res = $draw->pop();
$this->assertEquals($exp5, $res);
$res = $draw->pop();
$this->assertEquals($exp4, $res);
$res = $draw->pop();
$this->assertEquals($exp3, $res);
$res = $draw->pop();
$this->assertEquals($exp2, $res);
$res = $draw->pop();
$this->assertEquals($exp1, $res);
}
/**
* @throws \Com\Tecnick\Pdf\Graph\Exception
*/
public function testStyleEx(): void
{
$this->bcExpectException(\Com\Tecnick\Pdf\Graph\Exception::class);
$draw = $this->getTestObject();
$draw->pop();
}
/**
* @throws \Com\Tecnick\Pdf\Graph\Exception
*/
public function testSaveRestoreStyle(): void
{
$draw = $this->getTestObject();
$draw->add([
'lineWidth' => 1,
], false);
$draw->add([
'lineWidth' => 2,
], false);
$draw->add([
'lineWidth' => 3,
], false);
$draw->saveStyleStatus();
$draw->add([
'lineWidth' => 4,
], false);
$draw->add([
'lineWidth' => 5,
], false);
$draw->add([
'lineWidth' => 6,
], false);
$this->assertEquals(
[
'lineWidth' => 6,
],
$draw->getCurrentStyleArray(),
);
$draw->restoreStyleStatus();
$this->assertEquals(
[
'lineWidth' => 3,
],
$draw->getCurrentStyleArray(),
);
}
/**
* @throws \Com\Tecnick\Pdf\Graph\Exception
*/
public function testStyleItem(): void
{
$draw = $this->getTestObject();
$this->assertEquals('butt', $draw->getCurrentStyleItem('lineCap'));
}
/**
* @throws \Com\Tecnick\Pdf\Graph\Exception
*/
public function testStyleItemEx(): void
{
$this->bcExpectException(\Com\Tecnick\Pdf\Graph\Exception::class);
$draw = $this->getTestObject();
$draw->getCurrentStyleItem('wrongField');
}
/**
* @throws \Com\Tecnick\Pdf\Graph\Exception
*/
public function testGetLastStyleProperty(): void
{
$draw = $this->getTestObject();
$draw->add([
'lineWidth' => 1,
], false);
$draw->add([
'lineWidth' => 2,
], false);
$draw->add([
'lineWidth' => 3,
], false);
$this->assertEquals(3, $draw->getLastStyleProperty('lineWidth', 0));
$draw->add([
'lineWidth' => 4,
], false);
$this->assertEquals(4, $draw->getLastStyleProperty('lineWidth', 0));
$this->assertEquals(7, $draw->getLastStyleProperty('unknown', 7));
}
/**
* @throws \Com\Tecnick\Pdf\Graph\Exception
*/
public function testGetPathPaintOp(): void
{
$draw = $this->getTestObject();
$res = $draw->getPathPaintOp('', '');
$this->assertEquals('', $res);
$res = $draw->getPathPaintOp('');
$this->assertEquals('S' . "\n", $res);
$res = $draw->getPathPaintOp('', 'df');
$this->assertEquals('b' . "\n", $res);
$res = $draw->getPathPaintOp('CEO');
$this->assertEquals('W* n' . "\n", $res);
$res = $draw->getPathPaintOp('F*D');
$this->assertEquals('B*' . "\n", $res);
}
/**
* @throws \Com\Tecnick\Pdf\Graph\Exception
*/
public function testIsFillingMode(): void
{
$draw = $this->getTestObject();
$this->assertTrue($draw->isFillingMode('f'));
$this->assertTrue($draw->isFillingMode('f*'));
$this->assertTrue($draw->isFillingMode('B'));
$this->assertTrue($draw->isFillingMode('B*'));
$this->assertTrue($draw->isFillingMode('b'));
$this->assertTrue($draw->isFillingMode('b*'));
$this->assertFalse($draw->isFillingMode('S'));
$this->assertFalse($draw->isFillingMode('s'));
$this->assertFalse($draw->isFillingMode('n'));
$this->assertFalse($draw->isFillingMode(''));
}
/**
* @throws \Com\Tecnick\Pdf\Graph\Exception
*/
public function testIsStrokingMode(): void
{
$draw = $this->getTestObject();
$this->assertTrue($draw->isStrokingMode('S'));
$this->assertTrue($draw->isStrokingMode('s'));
$this->assertTrue($draw->isStrokingMode('B'));
$this->assertTrue($draw->isStrokingMode('B*'));
$this->assertTrue($draw->isStrokingMode('b'));
$this->assertTrue($draw->isStrokingMode('b*'));
$this->assertFalse($draw->isStrokingMode('f'));
$this->assertFalse($draw->isStrokingMode('f*'));
$this->assertFalse($draw->isStrokingMode('n'));
$this->assertFalse($draw->isStrokingMode(''));
}
/**
* @throws \Com\Tecnick\Pdf\Graph\Exception
*/
public function testIsClosingMode(): void
{
$draw = $this->getTestObject();
$this->assertTrue($draw->isClosingMode('s'));
$this->assertTrue($draw->isClosingMode('b'));
$this->assertTrue($draw->isClosingMode('b*'));
$this->assertFalse($draw->isClosingMode('f'));
$this->assertFalse($draw->isClosingMode('f*'));
$this->assertFalse($draw->isClosingMode('S'));
$this->assertFalse($draw->isClosingMode('B'));
$this->assertFalse($draw->isClosingMode('B*'));
$this->assertFalse($draw->isClosingMode('n'));
$this->assertFalse($draw->isClosingMode(''));
}
/**
* @throws \Com\Tecnick\Pdf\Graph\Exception
*/
public function testGetModeWithoutClose(): void
{
$draw = $this->getTestObject();
$this->assertEquals('', $draw->getModeWithoutClose(''));
$this->assertEquals('S', $draw->getModeWithoutClose('s'));
$this->assertEquals('B', $draw->getModeWithoutClose('b'));
$this->assertEquals('B*', $draw->getModeWithoutClose('b*'));
$this->assertEquals('n', $draw->getModeWithoutClose('n'));
}
/**
* @throws \Com\Tecnick\Pdf\Graph\Exception
*/
public function testGetModeWithoutFill(): void
{
$draw = $this->getTestObject();
$this->assertEquals('', $draw->getModeWithoutFill(''));
$this->assertEquals('', $draw->getModeWithoutFill('f'));
$this->assertEquals('', $draw->getModeWithoutFill('f*'));
$this->assertEquals('S', $draw->getModeWithoutFill('B'));
$this->assertEquals('S', $draw->getModeWithoutFill('B*'));
$this->assertEquals('s', $draw->getModeWithoutFill('b'));
$this->assertEquals('s', $draw->getModeWithoutFill('b*'));
$this->assertEquals('n', $draw->getModeWithoutFill('n'));
}
/**
* @throws \Com\Tecnick\Pdf\Graph\Exception
*/
public function testGetModeWithoutStroke(): void
{
$draw = $this->getTestObject();
$this->assertEquals('', $draw->getModeWithoutStroke(''));
$this->assertEquals('', $draw->getModeWithoutStroke('S'));
$this->assertEquals('h', $draw->getModeWithoutStroke('s'));
$this->assertEquals('f', $draw->getModeWithoutStroke('B'));
$this->assertEquals('f*', $draw->getModeWithoutStroke('B*'));
$this->assertEquals('h f', $draw->getModeWithoutStroke('b'));
$this->assertEquals('h f*', $draw->getModeWithoutStroke('b*'));
$this->assertEquals('n', $draw->getModeWithoutStroke('n'));
}
/**
* @throws \Com\Tecnick\Pdf\Graph\Exception
*/
public function testGetExtGState(): void
{
$draw = $this->getTestObject();
$this->assertEquals('/GS1 gs' . "\n", $draw->getExtGState([
'A' => 'B',
]));
$this->assertEquals('/GS1 gs' . "\n", $draw->getExtGState([
'A' => 'B',
]));
$this->assertEquals('/GS2 gs' . "\n", $draw->getExtGState([
'C' => 'D',
]));
}
/**
* @throws \Com\Tecnick\Pdf\Graph\Exception
*/
public function testGetExtGStatePdfa(): void
{
$draw = new \Com\Tecnick\Pdf\Graph\Draw(1, 0, 0, new \Com\Tecnick\Color\Pdf(), $this->getEncryptObject(), true);
$this->assertEquals('', $draw->getExtGState([
'A' => 'B',
]));
}
/**
* @throws \Com\Tecnick\Pdf\Graph\Exception
*/
public function testRestoreStyleStatusNull(): void
{
$draw = $this->getTestObject();
// stylemark starts as [0]; first restore pops that value
$draw->restoreStyleStatus();
// stylemark is now empty; second restore pops null and falls back to 0
$draw->restoreStyleStatus();
$this->assertEquals('butt', $draw->getCurrentStyleItem('lineCap'));
}
/**
* @throws \Com\Tecnick\Pdf\Graph\Exception
*/
public function testGetCurrentStyleArrayDefaultFallback(): void
{
$draw = new class(1, 0, 0, new \Com\Tecnick\Color\Pdf(), $this->getEncryptObject(), false) extends
\Com\Tecnick\Pdf\Graph\Draw {
public function setStyleIdForTest(int $styleid): void
{
$this->styleid = $styleid;
}
};
$draw->setStyleIdForTest(999);
$this->assertSame('butt', $draw->getCurrentStyleArray()['lineCap'] ?? null);
}
/**
* @throws \Com\Tecnick\Pdf\Graph\Exception
*/
public function testIsClippingModeInvalid(): void
{
$draw = $this->getTestObject();
$this->assertFalse($draw->isClippingMode('invalid'));
}
/**
* @throws \Com\Tecnick\Pdf\Graph\Exception
*/
public function testGetLineModeWithDashArrayNoDashPhase(): void
{
$draw = $this->getTestObject();
$style = [
'dashArray' => [3, 5],
];
$res = $draw->getStyleCmd($style);
$this->assertEquals('[3.000000 5.000000] 0.000000 d' . "\n", $res);
}
}
+57
View File
@@ -0,0 +1,57 @@
<?php
/**
* TestUtil.php
*
* @since 2020-12-19
* @category Library
* @package file
* @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-file
*
* This file is part of tc-lib-file software library.
*/
namespace Test;
use PHPUnit\Framework\TestCase;
/**
* Test Util
*
* @since 2020-12-19
* @category Library
* @package file
* @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-file
*/
class TestUtil extends TestCase
{
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);
}
protected function getEncryptObject(): \Com\Tecnick\Pdf\Encrypt\Encrypt
{
return new class() extends \Com\Tecnick\Pdf\Encrypt\Encrypt {
public function __construct() {}
};
}
}
@@ -0,0 +1,421 @@
<?php
/**
* TransformTest.php
*
* @since 2011-05-23
* @category Library
* @package PdfGraph
* @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-graph
*
* This file is part of tc-lib-pdf-graph software library.
*/
namespace Test;
/**
* Transform Test
*
* @since 2011-05-23
* @category Library
* @package PdfGraph
* @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-graph
*
* @throws \Com\Tecnick\Pdf\Graph\Exception
*/
class TransformTest extends TestUtil
{
protected function getTestObject(): \Com\Tecnick\Pdf\Graph\Draw
{
$draw = new \Com\Tecnick\Pdf\Graph\Draw(
1,
0,
0,
new \Com\Tecnick\Color\Pdf(),
$this->getEncryptObject(),
false,
);
$this->assertEquals(-1, $draw->getTransformIndex());
$this->assertEquals('q' . "\n", $draw->getStartTransform());
return $draw;
}
/**
* @throws \Com\Tecnick\Pdf\Graph\Exception
*/
public function testGetStartStopTransform(): void
{
$draw = new \Com\Tecnick\Pdf\Graph\Draw(
1,
0,
0,
new \Com\Tecnick\Color\Pdf(),
$this->getEncryptObject(),
false,
);
$this->assertEquals(-1, $draw->getTransformIndex());
$this->assertEquals('q' . "\n", $draw->getStartTransform());
$this->assertEquals(0, $draw->getTransformIndex());
$tmx = [0.1, 1.2, 2.3, 3.4, 4.5, 5.6];
$this->assertEquals(
'0.100000 1.200000 2.300000 3.400000 4.500000 5.600000 cm' . "\n",
$draw->getTransformation($tmx),
);
$this->bcAssertEqualsWithDelta(
[
0 => [
0 => [0.1, 1.2, 2.3, 3.4, 4.5, 5.6],
],
],
$draw->getTransformStack(),
0.0001,
'',
);
$this->assertEquals('Q' . "\n", $draw->getStopTransform());
$this->assertEquals(-1, $draw->getTransformIndex());
$this->assertEquals('', $draw->getStopTransform());
$this->assertEquals(-1, $draw->getTransformIndex());
}
/**
* @throws \Com\Tecnick\Pdf\Graph\Exception
*/
public function testGetTransform(): void
{
$draw = $this->getTestObject();
$tmx = [0.1, 1.2, 2.3, 3.4, 4.5, 5.6];
$this->assertEquals(
'0.100000 1.200000 2.300000 3.400000 4.500000 5.600000 cm' . "\n",
$draw->getTransformation($tmx),
);
}
/**
* @throws \Com\Tecnick\Pdf\Graph\Exception
*/
public function testSetPageHeight(): void
{
$draw = new \Com\Tecnick\Pdf\Graph\Draw(
1,
0,
0,
new \Com\Tecnick\Color\Pdf(),
$this->getEncryptObject(),
false,
);
$prev = $draw->setPageHeight(100);
$this->assertEquals(0, (int) $prev);
$this->assertEquals('q' . "\n", $draw->getStartTransform());
$this->assertEquals('3.000000 0.000000 0.000000 5.000000 -14.000000 -356.000000 cm' . "\n", $draw->getScaling(
3,
5,
7,
11,
));
}
/**
* @throws \Com\Tecnick\Pdf\Graph\Exception
*/
public function testSetPageWidth(): void
{
$draw = new \Com\Tecnick\Pdf\Graph\Draw(
1,
0,
0,
new \Com\Tecnick\Color\Pdf(),
$this->getEncryptObject(),
false,
);
$prev = $draw->setPageWidth(100);
$this->assertEquals(0, (int) $prev);
$this->assertEquals('q' . "\n", $draw->getStartTransform());
$this->assertEquals('3.000000 0.000000 0.000000 5.000000 -14.000000 44.000000 cm' . "\n", $draw->getScaling(
3,
5,
7,
11,
));
}
/**
* @throws \Com\Tecnick\Pdf\Graph\Exception
*/
public function testSetKUnit(): void
{
$draw = new \Com\Tecnick\Pdf\Graph\Draw(
1,
0,
0,
new \Com\Tecnick\Color\Pdf(),
$this->getEncryptObject(),
false,
);
$draw->setKUnit(0.75);
$this->assertEquals('q' . "\n", $draw->getStartTransform());
$this->assertEquals('3.000000 0.000000 0.000000 5.000000 -10.500000 33.000000 cm' . "\n", $draw->getScaling(
3,
5,
7,
11,
));
}
/**
* @throws \Com\Tecnick\Pdf\Graph\Exception
*/
public function testGetScaling(): void
{
$draw = $this->getTestObject();
$this->assertEquals('3.000000 0.000000 0.000000 5.000000 -14.000000 44.000000 cm' . "\n", $draw->getScaling(
3,
5,
7,
11,
));
$this->assertEquals('3.000000 0.000000 0.000000 3.000000 -14.000000 22.000000 cm' . "\n", $draw->getScaling(
3,
3,
7,
11,
));
}
/**
* @throws \Com\Tecnick\Pdf\Graph\Exception
*/
public function testGetScalingEx(): void
{
$this->bcExpectException(\Com\Tecnick\Pdf\Graph\Exception::class);
$draw = $this->getTestObject();
$draw->getScaling(0, 0, 7, 11);
}
/**
* @throws \Com\Tecnick\Pdf\Graph\Exception
*/
public function testGetHorizScaling(): void
{
$draw = $this->getTestObject();
$this->assertEquals('3.000000 0.000000 0.000000 1.000000 -14.000000 0.000000 cm' . "\n", $draw->getHorizScaling(
3,
7,
11,
));
}
/**
* @throws \Com\Tecnick\Pdf\Graph\Exception
*/
public function testGetVertScaling(): void
{
$draw = $this->getTestObject();
$this->assertEquals('1.000000 0.000000 0.000000 5.000000 0.000000 44.000000 cm' . "\n", $draw->getVertScaling(
5,
7,
11,
));
}
/**
* @throws \Com\Tecnick\Pdf\Graph\Exception
*/
public function testGetPropScaling(): void
{
$draw = $this->getTestObject();
$this->assertEquals('3.000000 0.000000 0.000000 3.000000 -14.000000 22.000000 cm' . "\n", $draw->getPropScaling(
3,
7,
11,
));
}
/**
* @throws \Com\Tecnick\Pdf\Graph\Exception
*/
public function testGetRotation(): void
{
$draw = $this->getTestObject();
$this->assertEquals('0.707107 0.707107 -0.707107 0.707107 -5.727922 -8.171573 cm' . "\n", $draw->getRotation(
45,
7,
11,
));
}
/**
* @throws \Com\Tecnick\Pdf\Graph\Exception
*/
public function testGetHorizMirroring(): void
{
$draw = $this->getTestObject();
$this->assertEquals(
'-1.000000 0.000000 0.000000 1.000000 14.000000 0.000000 cm' . "\n",
$draw->getHorizMirroring(7),
);
}
/**
* @throws \Com\Tecnick\Pdf\Graph\Exception
*/
public function testGetVertMirroring(): void
{
$draw = $this->getTestObject();
$this->assertEquals(
'1.000000 0.000000 0.000000 -1.000000 0.000000 -22.000000 cm' . "\n",
$draw->getVertMirroring(11),
);
}
/**
* @throws \Com\Tecnick\Pdf\Graph\Exception
*/
public function testGetPointMirroring(): void
{
$draw = $this->getTestObject();
$this->assertEquals('-1.000000 0.000000 0.000000 -1.000000 14.000000 -22.000000 cm'
. "\n", $draw->getPointMirroring(7, 11));
}
/**
* @throws \Com\Tecnick\Pdf\Graph\Exception
*/
public function testGetReflection(): void
{
$draw = $this->getTestObject();
$this->assertEquals('-1.000000 0.000000 0.000000 1.000000 14.000000 0.000000 cm'
. "\n"
. '0.000000 1.000000 -1.000000 0.000000 -4.000000 -18.000000 cm'
. "\n", $draw->getReflection(45, 7, 11));
}
/**
* @throws \Com\Tecnick\Pdf\Graph\Exception
*/
public function testGetTranslation(): void
{
$draw = $this->getTestObject();
$this->assertEquals('1.000000 0.000000 0.000000 1.000000 3.000000 -5.000000 cm' . "\n", $draw->getTranslation(
3,
5,
));
}
/**
* @throws \Com\Tecnick\Pdf\Graph\Exception
*/
public function testGetHorizTranslation(): void
{
$draw = $this->getTestObject();
$this->assertEquals(
'1.000000 0.000000 0.000000 1.000000 3.000000 0.000000 cm' . "\n",
$draw->getHorizTranslation(3),
);
}
/**
* @throws \Com\Tecnick\Pdf\Graph\Exception
*/
public function testGetVertTranslation(): void
{
$draw = $this->getTestObject();
$this->assertEquals(
'1.000000 0.000000 0.000000 1.000000 0.000000 -5.000000 cm' . "\n",
$draw->getVertTranslation(5),
);
}
/**
* @throws \Com\Tecnick\Pdf\Graph\Exception
*/
public function testGetSkewing(): void
{
$draw = $this->getTestObject();
$this->assertEquals('1.000000 0.087489 0.052408 1.000000 0.576486 -0.612421 cm' . "\n", $draw->getSkewing(
3,
5,
7,
11,
));
}
/**
* @throws \Com\Tecnick\Pdf\Graph\Exception
*/
public function testGetSkewingEx(): void
{
$draw = $this->getTestObject();
$this->bcExpectException(\Com\Tecnick\Pdf\Graph\Exception::class);
$draw->getSkewing(90, -90, 7, 11);
}
/**
* @throws \Com\Tecnick\Pdf\Graph\Exception
*/
public function testGetHorizSkewing(): void
{
$draw = $this->getTestObject();
$this->assertEquals('1.000000 0.000000 0.052408 1.000000 0.576486 0.000000 cm' . "\n", $draw->getHorizSkewing(
3,
7,
11,
));
}
/**
* @throws \Com\Tecnick\Pdf\Graph\Exception
*/
public function testGetVertSkewing(): void
{
$draw = $this->getTestObject();
$this->assertEquals('1.000000 0.087489 0.000000 1.000000 0.000000 -0.612421 cm' . "\n", $draw->getVertSkewing(
5,
7,
11,
));
}
/**
* @throws \Com\Tecnick\Pdf\Graph\Exception
*/
public function testGetCtmProduct(): void
{
$draw = $this->getTestObject();
$tma = [3.1, 5.2, 7.3, 11.4, 13.5, 17.6];
$tmb = [19.1, 23.2, 29.3, 31.4, 37.5, 41.6];
$ctm = $draw->getCtmProduct($tma, $tmb);
$this->bcAssertEqualsWithDelta([228.570, 363.800, 320.050, 510.320, 433.430, 686.840], $ctm, 0.001);
}
}