generated from jric11/baseProject
Initial commit
This commit is contained in:
+20
@@ -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,61 @@
|
||||
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: pcov-1.0.10, 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: Install fonts
|
||||
run: cd util && composer install --no-dev --no-interaction && ./bulk_convert.php && cd ..
|
||||
- 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,24 @@
|
||||
**/*.bak
|
||||
**/*.tmp
|
||||
**/.#*
|
||||
**/.DS_Store
|
||||
**/._*
|
||||
**/.idea
|
||||
**/.vagrant
|
||||
**/auth.json
|
||||
**/nbproject
|
||||
**/temp.php
|
||||
**/test.php
|
||||
.phpdoc
|
||||
.phpunit.cache
|
||||
.phpunit.result.cache
|
||||
PLAN_*
|
||||
composer.lock
|
||||
ecs.php
|
||||
phpunit.xml
|
||||
rector.php
|
||||
resources/util/vendor
|
||||
src/fonts
|
||||
target
|
||||
target/fonts
|
||||
vendor
|
||||
@@ -0,0 +1 @@
|
||||
* @nicolaasuni
|
||||
@@ -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
@@ -0,0 +1,194 @@
|
||||
# Contributing to tc-lib-pdf-font
|
||||
|
||||
Thank you for your interest in contributing to **tc-lib-pdf-font**.
|
||||
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-font.git
|
||||
cd tc-lib-pdf-font
|
||||
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-font/issues)** to avoid duplicates.
|
||||
|
||||
If no existing issue matches, [open a new one](https://github.com/tecnickcom/tc-lib-pdf-font/issues/new) and include:
|
||||
|
||||
- A **clear title and description** of the problem.
|
||||
- The **library version** (`composer show tecnickcom/tc-lib-pdf-font`) 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-font/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-font/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-font/discussions) or contact the maintainer at [info@tecnick.com](mailto:info@tecnick.com).
|
||||
+862
@@ -0,0 +1,862 @@
|
||||
**********************************************************************
|
||||
* LICENSE
|
||||
*
|
||||
* SOFTWARE : tc-lib-pdf-font
|
||||
* 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>.
|
||||
|
||||
**********************************************************************
|
||||
**********************************************************************
|
||||
+313
@@ -0,0 +1,313 @@
|
||||
# makefile
|
||||
#
|
||||
# @since 2015-05-14
|
||||
# @category Library
|
||||
# @package PdfFont
|
||||
# @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-font
|
||||
#
|
||||
# This file is part of tc-lib-pdf-font software library.
|
||||
# ----------------------------------------------------------------------------------------------------------------------
|
||||
|
||||
SHELL=/bin/bash
|
||||
.SHELLFLAGS=-o pipefail -c
|
||||
|
||||
# Project owner
|
||||
OWNER=tecnickcom
|
||||
|
||||
# Project vendor
|
||||
VENDOR=${OWNER}
|
||||
|
||||
# Project name
|
||||
PROJECT=tc-lib-pdf-font
|
||||
|
||||
# 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/Font/
|
||||
|
||||
# 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)
|
||||
|
||||
# List of fonts to process
|
||||
FONTLIST=core pdfa cid0 freefont unifont dejavu noto
|
||||
|
||||
# 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 fonts 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)"
|
||||
cd util && make clean
|
||||
|
||||
## 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)
|
||||
cd util && make deps
|
||||
|
||||
## 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"
|
||||
mkdir -p "$(TARGETDIR)/fonts"
|
||||
|
||||
## 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
|
||||
|
||||
# ----------
|
||||
|
||||
## import and convert fonts
|
||||
fonts:
|
||||
rm -rf "$(TARGETDIR)/fonts"
|
||||
test -f vendor/autoload.php || $(COMPOSER) install --no-dev --no-interaction
|
||||
cd util && ($(COMPOSER) install -vvv --no-interaction)
|
||||
cd util && make build
|
||||
|
||||
## Build fonts RPM packages for RedHat-like Linux distributions
|
||||
rpm_fonts:
|
||||
$(foreach PKGFONTDIR,$(FONTLIST), \
|
||||
cd "${CURRENTDIR}/util" && make rpm PKGFONTDIR="${PKGFONTDIR}" ; \
|
||||
)
|
||||
|
||||
## Build fonts DEB packages for Debian-like Linux distributions
|
||||
deb_fonts:
|
||||
$(foreach PKGFONTDIR,$(FONTLIST), \
|
||||
cd "${CURRENTDIR}/util" && make deb PKGFONTDIR="${PKGFONTDIR}" ; \
|
||||
)
|
||||
|
||||
## build fonts compressed bz2 archives
|
||||
bz2_fonts:
|
||||
$(foreach PKGFONTDIR,$(FONTLIST), \
|
||||
cd "${CURRENTDIR}/util" && make bz2 PKGFONTDIR="${PKGFONTDIR}" ; \
|
||||
)
|
||||
+244
@@ -0,0 +1,244 @@
|
||||
# tc-lib-pdf-font
|
||||
|
||||
> Font import, metrics, and stack management utilities for PDF generation.
|
||||
|
||||
[](https://packagist.org/packages/tecnickcom/tc-lib-pdf-font)
|
||||
[](https://github.com/tecnickcom/tc-lib-pdf-font/actions/workflows/check.yml)
|
||||
[](https://codecov.io/gh/tecnickcom/tc-lib-pdf-font)
|
||||
[](https://packagist.org/packages/tecnickcom/tc-lib-pdf-font)
|
||||
[](https://packagist.org/packages/tecnickcom/tc-lib-pdf-font)
|
||||
|
||||
[](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-font` provides font import and runtime font-stack services used by PDF composition engines.
|
||||
|
||||
It bridges static font assets and runtime document composition by handling metrics, encodings, and font program references in a PDF-friendly way. This modular design lets applications evolve font workflows independently from the rest of the rendering stack.
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| **Namespace** | `\Com\Tecnick\Pdf\Font` |
|
||||
| **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-font> |
|
||||
| **Packagist** | <https://packagist.org/packages/tecnickcom/tc-lib-pdf-font> |
|
||||
|
||||
---
|
||||
|
||||
## Features
|
||||
|
||||
### Font Processing
|
||||
- Import support for core, Type1, and TrueType sources
|
||||
- Font metadata extraction and normalization
|
||||
- Utilities for subset and output dictionary generation
|
||||
- Optional injectable cache to reuse computed TrueType font subsets
|
||||
|
||||
### Runtime Font Stack
|
||||
- Font stack insertion and switching
|
||||
- Glyph width/bounding-box helpers
|
||||
- Character replacement and fallback handling
|
||||
|
||||
---
|
||||
|
||||
## Requirements
|
||||
|
||||
- PHP 8.2 or later
|
||||
- Extensions: `json`, `zlib`
|
||||
- Composer
|
||||
|
||||
---
|
||||
|
||||
## Installation
|
||||
|
||||
```bash
|
||||
composer require tecnickcom/tc-lib-pdf-font
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Quick Start
|
||||
|
||||
```php
|
||||
<?php
|
||||
|
||||
require_once __DIR__ . '/vendor/autoload.php';
|
||||
|
||||
$font = new \Com\Tecnick\Pdf\Font\Import('/path/to/font.ttf');
|
||||
$metrics = $font->getFontMetrics();
|
||||
|
||||
var_dump($font->getFontName(), $metrics['type']);
|
||||
```
|
||||
|
||||
For larger examples, refer to `test/OutputTest.php` and the conversion tooling in this repository.
|
||||
|
||||
---
|
||||
|
||||
## Subset Caching
|
||||
|
||||
TrueType font subsetting is computational and memory intensive. When the same
|
||||
fonts and character sets are embedded repeatedly (for example across many
|
||||
generated documents), you can inject an optional cache into
|
||||
`\Com\Tecnick\Pdf\Font\Output` to reuse previously computed subset programs.
|
||||
|
||||
Provide any object implementing
|
||||
`\Com\Tecnick\Pdf\Font\FontSubsetCacheInterface`:
|
||||
|
||||
```php
|
||||
interface FontSubsetCacheInterface
|
||||
{
|
||||
public function get(string $key): ?string; // null on cache miss
|
||||
public function set(string $key, string $subsetFont): void;
|
||||
}
|
||||
```
|
||||
|
||||
Pass it as the last constructor argument:
|
||||
|
||||
```php
|
||||
$output = new \Com\Tecnick\Pdf\Font\Output(
|
||||
$fonts,
|
||||
$objectNumber,
|
||||
$encrypt,
|
||||
$fileHelper, // or null
|
||||
$subsetCache, // your FontSubsetCacheInterface implementation
|
||||
);
|
||||
```
|
||||
|
||||
When no cache is supplied (the default), behavior is unchanged and every
|
||||
subset is recomputed. The library never evicts entries — the injected backend
|
||||
owns expiration and size limits. The cache key already accounts for the font
|
||||
program bytes, the cmap-selection metrics, and the requested subset
|
||||
characters, so distinct inputs never collide.
|
||||
|
||||
### Using a PSR-16 cache
|
||||
|
||||
No PSR-16 adapter is bundled, because the interface above is intentionally
|
||||
trivial to wrap around any backend (PSR-16/PSR-6, Symfony Cache, Laravel,
|
||||
Redis, APCu, …). A correct PSR-16 wrapper is a few lines:
|
||||
|
||||
```php
|
||||
use Com\Tecnick\Pdf\Font\FontSubsetCacheInterface;
|
||||
use Psr\SimpleCache\CacheInterface;
|
||||
|
||||
final class Psr16SubsetCache implements FontSubsetCacheInterface
|
||||
{
|
||||
public function __construct(private CacheInterface $cache) {}
|
||||
|
||||
public function get(string $key): ?string
|
||||
{
|
||||
$value = $this->cache->get($this->normalize($key));
|
||||
|
||||
return \is_string($value) ? $value : null;
|
||||
}
|
||||
|
||||
public function set(string $key, string $subsetFont): void
|
||||
{
|
||||
$this->cache->set($this->normalize($key), $subsetFont);
|
||||
}
|
||||
|
||||
/**
|
||||
* PSR-16 only guarantees keys matching [A-Za-z0-9_.] up to 64 chars and
|
||||
* reserves {}()/\@: — the library's raw key uses ':' and '-' and is longer,
|
||||
* so hash it into a guaranteed-legal, fixed-length key.
|
||||
*/
|
||||
private function normalize(string $key): string
|
||||
{
|
||||
return 'tclpf_' . \sha1($key);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
The `normalize()` step matters: the library's raw key is human-readable and
|
||||
works with permissive backends, but stricter PSR-16 implementations may reject
|
||||
or mangle it. Hashing it keeps the wrapper portable. Note that hashing discards
|
||||
the readable namespace, so scope the underlying PSR-16 pool to this library if
|
||||
you share it with other consumers.
|
||||
|
||||
---
|
||||
|
||||
## Converting Existing Fonts
|
||||
|
||||
Use the CLI utilities in `util/` to convert existing font files into the JSON/Z format consumed by this library.
|
||||
|
||||
### Convert One or More Fonts
|
||||
|
||||
Run `util/convert.php` and pass one or more input files with `--fonts`:
|
||||
|
||||
```bash
|
||||
php util/convert.php \
|
||||
--outpath=./target/fonts/custom/ \
|
||||
--type=TrueTypeUnicode \
|
||||
--flags=32 \
|
||||
--encoding_id=1 \
|
||||
--fonts=/path/to/MyFont-Regular.ttf,/path/to/MyFont-Bold.ttf
|
||||
```
|
||||
|
||||
The command writes generated font definition files to `--outpath`.
|
||||
|
||||
Common options:
|
||||
|
||||
- `--type`: Explicit font type (`TrueTypeUnicode`, `TrueType`, `Type1`, `CID0JP`, `CID0KR`, `CID0CS`, `CID0CT`). Leave empty for autodetect.
|
||||
- `--encoding`: Encoding table (for example `cp1252` for many non-Unicode Type1/Core cases). Omit for Unicode and symbolic fonts.
|
||||
- `--flags`: PDF descriptor flags. Default is `32` (non-symbolic).
|
||||
- `--platform_id` and `--encoding_id`: CMAP selection for TrueType Unicode imports (defaults: `3` and `1`).
|
||||
- `--linked`: Link to system font file instead of embedding/copying it (not transportable).
|
||||
|
||||
To see full usage help:
|
||||
|
||||
```bash
|
||||
php util/convert.php --help
|
||||
```
|
||||
|
||||
### Bulk Conversion
|
||||
|
||||
For batch generation from the mirrored font set:
|
||||
|
||||
```bash
|
||||
cd util
|
||||
make build
|
||||
```
|
||||
|
||||
This installs `util` dependencies and runs `bulk_convert.php`, which scans the mirror package and writes converted fonts under `target/fonts/`.
|
||||
|
||||
Notes:
|
||||
|
||||
- `bulk_convert.php` also attempts OTF conversion via FontForge (`fontforge -script otf2ttf.ff ...`) before import.
|
||||
- If you run bulk conversion directly, customize destination with `php util/bulk_convert.php --outpath=/your/path/`.
|
||||
|
||||
---
|
||||
|
||||
## Development
|
||||
|
||||
```bash
|
||||
make deps
|
||||
make help
|
||||
make qa
|
||||
```
|
||||
|
||||
Font generation helpers are also available through Make targets such as `fonts`.
|
||||
|
||||
---
|
||||
|
||||
## Packaging
|
||||
|
||||
```bash
|
||||
make rpm
|
||||
make deb
|
||||
```
|
||||
|
||||
For system packages, bootstrap with:
|
||||
|
||||
```php
|
||||
require_once '/usr/share/php/Com/Tecnick/Pdf/Font/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
@@ -0,0 +1 @@
|
||||
1
|
||||
+62
@@ -0,0 +1,62 @@
|
||||
# Security Policy
|
||||
|
||||
This document describes the security policy for **tc-lib-pdf-font**.
|
||||
|
||||
---
|
||||
|
||||
## 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-font – <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-font`).
|
||||
- **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-font) 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-font> |
|
||||
| Packagist | <https://packagist.org/packages/tecnickcom/tc-lib-pdf-font> |
|
||||
+1
@@ -0,0 +1 @@
|
||||
3.13.2
|
||||
+74
@@ -0,0 +1,74 @@
|
||||
{
|
||||
"name": "tecnickcom/tc-lib-pdf-font",
|
||||
"description": "PHP library containing PDF page formats and definitions",
|
||||
"type": "library",
|
||||
"homepage": "https://tcpdf.org",
|
||||
"license": "LGPL-3.0-or-later",
|
||||
"keywords": [
|
||||
"tc-lib-pdf-font",
|
||||
"PDF",
|
||||
"font",
|
||||
"TTF",
|
||||
"AFM",
|
||||
"PFB",
|
||||
"import"
|
||||
],
|
||||
"authors": [
|
||||
{
|
||||
"name": "Nicola Asuni",
|
||||
"email": "info@tecnick.com",
|
||||
"role": "lead"
|
||||
}
|
||||
],
|
||||
"funding": [
|
||||
{
|
||||
"type": "github",
|
||||
"url": "https://github.com/sponsors/tecnickcom"
|
||||
}
|
||||
],
|
||||
"require": {
|
||||
"php": ">=8.2",
|
||||
"ext-hash": "*",
|
||||
"ext-json": "*",
|
||||
"ext-pcre": "*",
|
||||
"ext-zlib": "*",
|
||||
"tecnickcom/tc-lib-file": "^3.7",
|
||||
"tecnickcom/tc-lib-unicode-data": "^3.0",
|
||||
"tecnickcom/tc-lib-pdf-encrypt": "^2.9"
|
||||
},
|
||||
"suggest": {
|
||||
"ext-iconv": "Decodes legacy Macintosh (MacRoman) TrueType name strings",
|
||||
"ext-mbstring": "Decodes UTF-16BE and Windows-1252 TrueType name strings"
|
||||
},
|
||||
"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\\Font\\": "src"
|
||||
}
|
||||
},
|
||||
"autoload-dev": {
|
||||
"psr-4": {
|
||||
"Test\\": "test"
|
||||
}
|
||||
},
|
||||
"support": {
|
||||
"issues": "https://github.com/tecnickcom/tc-lib-pdf-font/issues",
|
||||
"source": "https://github.com/tecnickcom/tc-lib-pdf-font"
|
||||
},
|
||||
"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
@@ -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 = false, effort-threshold = 7000 }
|
||||
identity-comparison = { enabled = true }
|
||||
kan-defect = { enabled = false }
|
||||
no-boolean-flag-parameter = { enabled = false }
|
||||
no-else-clause = { enabled = false }
|
||||
no-empty = { enabled = 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 = false
|
||||
unchecked-exceptions = [
|
||||
"Error",
|
||||
"LogicException",
|
||||
"ReflectionException",
|
||||
]
|
||||
unchecked-exception-classes = []
|
||||
check-missing-override = true
|
||||
find-unused-parameters = true
|
||||
strict-list-index-checks = false
|
||||
strict-array-index-existence = false
|
||||
allow-array-truthy-operand = false
|
||||
no-boolean-literal-comparison = true
|
||||
check-missing-type-hints = true
|
||||
register-super-globals = true
|
||||
@@ -0,0 +1,67 @@
|
||||
#: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 }
|
||||
inline-variable-return = { 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
|
||||
@@ -0,0 +1,15 @@
|
||||
{
|
||||
"source-providers": [
|
||||
{
|
||||
"in": "src as source",
|
||||
"exclude": "vendor",
|
||||
"name": "/\\.(php)$/"
|
||||
}
|
||||
],
|
||||
"plugins": [
|
||||
],
|
||||
"analysers": [
|
||||
],
|
||||
"services": [
|
||||
]
|
||||
}
|
||||
@@ -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-font 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 PdfFont
|
||||
* @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-font
|
||||
*
|
||||
* This file is part of tc-lib-pdf-font 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,18 @@
|
||||
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-json, php-tecnickcom-tc-lib-file (<< 3.0.0), php-tecnickcom-tc-lib-file (>= 3.7.3), php-tecnickcom-tc-lib-unicode-data (<< 3.0.0), php-tecnickcom-tc-lib-unicode-data (>= 3.0.2), php-tecnickcom-tc-lib-pdf-encrypt (<< 3.0.0), php-tecnickcom-tc-lib-pdf-encrypt (>= 2.9.3), php-tecnickcom-tc-lib-pdf-font-core (<< 2.0.0), php-tecnickcom-tc-lib-pdf-font-data-core (>= 1.8.7), ${misc:Depends}
|
||||
Recommends: php-iconv, php-mbstring
|
||||
Description: PHP PDF Fonts Library
|
||||
PHP library containing PDF font methods and utilities.
|
||||
@@ -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,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 @@
|
||||
10
|
||||
@@ -0,0 +1,16 @@
|
||||
Source: ~#PKGNAME#~
|
||||
Maintainer: Nicola Asuni <info@tecnick.com>
|
||||
Section: php
|
||||
Priority: optional
|
||||
Build-Depends: debhelper (>= 9)
|
||||
Standards-Version: 3.9.6
|
||||
Homepage: https://github.com/tecnickcom/tc-lib-pdf-font
|
||||
Vcs-Git: https://github.com/tecnickcom/tc-lib-pdf-font.git
|
||||
|
||||
Package: ~#PKGNAME#~
|
||||
Provides: php-~#PROJECT#~
|
||||
Architecture: all
|
||||
Depends: ${misc:Depends}
|
||||
Description: ~#FONT#~ fonts data for tc-lib-pdf-font
|
||||
This package contains data extracted from the ~#FONT#~ fonts
|
||||
for the tc-lib-pdf-font library.
|
||||
@@ -0,0 +1,14 @@
|
||||
Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/
|
||||
Upstream-Name: ~#PROJECT#~
|
||||
Source: https://github.com/tecnickcom/tc-lib-pdf-font
|
||||
|
||||
Files: *
|
||||
Copyright: © 0000 Please check the README file for copyright information.
|
||||
License: ~#LICENSE#~
|
||||
|
||||
License: ~#LICENSE#~
|
||||
The font files in this package are free software:
|
||||
you can redistribute it and/or modify it under the terms of the
|
||||
~#LICENSE#~ License.
|
||||
Please check the README and LICENSE file for further information.
|
||||
Common licenses can be also found in: /usr/share/common-licenses
|
||||
@@ -0,0 +1,3 @@
|
||||
#!/usr/bin/make -f
|
||||
%:
|
||||
dh $@
|
||||
@@ -0,0 +1 @@
|
||||
3.0 (quilt)
|
||||
@@ -0,0 +1,42 @@
|
||||
# SPEC file
|
||||
|
||||
%global c_vendor %{_vendor}
|
||||
%global gh_owner %{_owner}
|
||||
%global gh_project %{_project}
|
||||
|
||||
Name: %{_package}
|
||||
Version: %{_version}
|
||||
Release: %{_release}%{?dist}
|
||||
Summary: %{_fontdir} fonts data for tc-lib-pdf-font
|
||||
|
||||
Group: Development/Libraries
|
||||
License: %{_license}
|
||||
URL: https://github.com/%{gh_owner}/%{gh_project}
|
||||
|
||||
BuildRoot: %{_tmppath}/%{name}-%{version}-%{release}-%(%{__id_u} -n)
|
||||
BuildArch: noarch
|
||||
|
||||
Provides: php-%{gh_project} = %{version}
|
||||
|
||||
%description
|
||||
This package contains data extracted from the %{_fontdir} fonts for the tc-lib-pdf-font library.
|
||||
|
||||
%build
|
||||
#(cd %{_current_directory} && make build)
|
||||
|
||||
%install
|
||||
rm -rf "$RPM_BUILD_ROOT"
|
||||
(cd "%{_current_directory}" && make install DESTDIR="$RPM_BUILD_ROOT" PKGFONTDIR="%{_fontdir}")
|
||||
|
||||
%clean
|
||||
rm -rf "$RPM_BUILD_ROOT"
|
||||
#(cd %{_current_directory} && make clean)
|
||||
|
||||
%files
|
||||
%attr(-,root,root) %{_fontpath}
|
||||
%attr(-,root,root) %{_docpath}
|
||||
%docdir %{_docpath}
|
||||
|
||||
%changelog
|
||||
* Tue Dec 01 2026 Nicola Asuni <info@tecnick.com> 1.0.0-1
|
||||
- Initial Commit
|
||||
@@ -0,0 +1,55 @@
|
||||
# SPEC file
|
||||
|
||||
%global c_vendor %{_vendor}
|
||||
%global gh_owner %{_owner}
|
||||
%global gh_project %{_project}
|
||||
|
||||
Name: %{_package}
|
||||
Version: %{_version}
|
||||
Release: %{_release}%{?dist}
|
||||
Summary: PHP PDF Fonts Library
|
||||
|
||||
License: LGPL-3.0+
|
||||
URL: https://github.com/%{gh_owner}/%{gh_project}
|
||||
|
||||
BuildArch: noarch
|
||||
|
||||
Requires: php(language) >= 8.2.0
|
||||
Requires: php-hash
|
||||
Requires: php-json
|
||||
Requires: php-pcre
|
||||
Requires: php-zlib
|
||||
Requires: php-composer(%{c_vendor}/tc-lib-file) < 3.0.0
|
||||
Requires: php-composer(%{c_vendor}/tc-lib-file) >= 3.7.3
|
||||
Requires: php-composer(%{c_vendor}/tc-lib-unicode-data) < 3.0.0
|
||||
Requires: php-composer(%{c_vendor}/tc-lib-unicode-data) >= 3.0.2
|
||||
Requires: php-composer(%{c_vendor}/tc-lib-pdf-encrypt) < 3.0.0
|
||||
Requires: php-composer(%{c_vendor}/tc-lib-pdf-encrypt) >= 2.9.3
|
||||
Requires: php-composer(%{c_vendor}/tc-lib-pdf-font-data-core) < 2.0.0
|
||||
Requires: php-composer(%{c_vendor}/tc-lib-pdf-font-data-core) >= 1.8.7
|
||||
|
||||
Recommends: php-iconv
|
||||
Recommends: php-mbstring
|
||||
|
||||
Provides: php-composer(%{c_vendor}/%{gh_project}) = %{version}
|
||||
Provides: php-%{gh_project} = %{version}
|
||||
|
||||
%description
|
||||
PHP library containing PDF font methods and utilities
|
||||
|
||||
%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 Aug 10 2026 Nicola Asuni <info@tecnick.com> 1.0.0-1
|
||||
- Initial Commit
|
||||
+342
@@ -0,0 +1,342 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
/**
|
||||
* Buffer.php
|
||||
*
|
||||
* @since 2011-05-23
|
||||
* @category Library
|
||||
* @package PdfFont
|
||||
* @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-font
|
||||
*
|
||||
* This file is part of tc-lib-pdf-font software library.
|
||||
*/
|
||||
|
||||
namespace Com\Tecnick\Pdf\Font;
|
||||
|
||||
use Com\Tecnick\File\File as ObjFile;
|
||||
use Com\Tecnick\Pdf\Font\Exception as FontException;
|
||||
|
||||
/**
|
||||
* Com\Tecnick\Pdf\Font\Buffer
|
||||
*
|
||||
* @since 2011-05-23
|
||||
* @category Library
|
||||
* @package PdfFont
|
||||
* @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-font
|
||||
*
|
||||
* @phpstan-type TFileOptions array{
|
||||
* allowedHosts?: array<string>,
|
||||
* maxRemoteSize?: int,
|
||||
* curlopts?: array<int, bool|int|string>,
|
||||
* defaultCurlOpts?: array<int, bool|int|string>,
|
||||
* fixedCurlOpts?: array<int, bool|int|string>
|
||||
* }
|
||||
*
|
||||
* @phpstan-import-type TFontData from Load
|
||||
*/
|
||||
abstract class Buffer
|
||||
{
|
||||
/**
|
||||
* Array containing all fonts data
|
||||
*
|
||||
* @var array<string, TFontData>
|
||||
*/
|
||||
protected array $font = [];
|
||||
|
||||
/**
|
||||
* Font counter
|
||||
*/
|
||||
protected int $numfonts = 0;
|
||||
|
||||
/**
|
||||
* Cache mapping a (font family, style) pair to its resolved font key, so repeated
|
||||
* lookups of an already-loaded font skip constructing a throwaway Font object.
|
||||
*
|
||||
* @var array<string, array<string, string>>
|
||||
*/
|
||||
protected array $fontKeyCache = [];
|
||||
|
||||
/**
|
||||
* Array containing encoding differences
|
||||
*
|
||||
* @var array<int, string>
|
||||
*/
|
||||
protected array $encdiff = [];
|
||||
|
||||
/**
|
||||
* Index for Encoding differences
|
||||
*/
|
||||
protected int $numdiffs = 0;
|
||||
|
||||
/**
|
||||
* Array containing font definitions grouped by file
|
||||
*
|
||||
* @var array<string, array{
|
||||
* 'dir': string,
|
||||
* 'keys': array<string>,
|
||||
* 'length1': int,
|
||||
* 'length2': int,
|
||||
* 'subset': bool,
|
||||
* }>
|
||||
*/
|
||||
protected array $file = [];
|
||||
|
||||
/**
|
||||
* Optional file helper forwarded to font loaders.
|
||||
*
|
||||
* @var ObjFile|null
|
||||
*/
|
||||
protected ?ObjFile $fileHelper;
|
||||
|
||||
/**
|
||||
* Initialize fonts buffer
|
||||
*
|
||||
* @param float $kunit Unit of measure conversion ratio.
|
||||
* @param bool $subset If true embed only a subset of the fonts
|
||||
* (stores only the information related to
|
||||
* the used characters); If false embed
|
||||
* full font; This option is valid only for
|
||||
* TrueTypeUnicode fonts and is disabled
|
||||
* for PDF/A. If you want to enable users to
|
||||
* modify the document, set this parameter
|
||||
* to false. If you subset the font, the
|
||||
* person who receives your PDF would need
|
||||
* to have your same font in order to make
|
||||
* changes to your PDF. The file size of the
|
||||
* PDF would also be smaller because you are
|
||||
* embedding only a subset. NOTE: This
|
||||
* option is computational and memory
|
||||
* intensive.
|
||||
* @param bool $unicode True if we are in Unicode mode, False otherwise.
|
||||
* @param bool $pdfa True if we are in PDF/A mode, False otherwise.
|
||||
* @param ObjFile|null $fileHelper Optional file helper for font loading.
|
||||
*/
|
||||
public function __construct(
|
||||
protected float $kunit,
|
||||
protected bool $subset = false,
|
||||
protected bool $unicode = true,
|
||||
protected bool $pdfa = false,
|
||||
?ObjFile $fileHelper = null,
|
||||
) {
|
||||
$this->fileHelper = $fileHelper;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the default subset mode
|
||||
*/
|
||||
public function isSubsetMode(): bool
|
||||
{
|
||||
return $this->subset;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the fonts buffer
|
||||
*
|
||||
* @return array<string, TFontData>
|
||||
*/
|
||||
public function getFonts(): array
|
||||
{
|
||||
return $this->font;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the fonts buffer
|
||||
*
|
||||
* @return array<int, string>
|
||||
*/
|
||||
public function getEncDiffs(): array
|
||||
{
|
||||
return $this->encdiff;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns true if the specified font key exist on buffer
|
||||
*
|
||||
* @param string $key Font key
|
||||
*/
|
||||
public function isValidKey(string $key): bool
|
||||
{
|
||||
return isset($this->font[$key]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get font by key
|
||||
*
|
||||
* @param string $key Font key
|
||||
*
|
||||
* @return TFontData Returns the fonts array.
|
||||
*
|
||||
* @throws FontException in case of error
|
||||
*/
|
||||
public function getFont(string $key): array
|
||||
{
|
||||
if (!isset($this->font[$key])) {
|
||||
throw new FontException('The font ' . $key . ' has not been loaded');
|
||||
}
|
||||
|
||||
return $this->font[$key];
|
||||
}
|
||||
|
||||
/**
|
||||
* Add a character to the subset list
|
||||
*
|
||||
* @param string $key The font key
|
||||
* @param int $char The Unicode character value to add
|
||||
*
|
||||
* @throws FontException
|
||||
*/
|
||||
public function addSubsetChar(string $key, int $char): void
|
||||
{
|
||||
if (!isset($this->font[$key])) {
|
||||
throw new FontException('The font ' . $key . ' has not been loaded');
|
||||
}
|
||||
|
||||
$this->font[$key]['subsetchars'][$char] = true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Add a new font to the fonts buffer
|
||||
*
|
||||
* The definition file (and the font file itself when embedding) must be present either in the current directory
|
||||
* or in the one indicated by K_PATH_FONTS if the constant is defined.
|
||||
*
|
||||
* @param int $objnum Current PDF object number
|
||||
* @param string $font Font family.
|
||||
* If it is a standard family name, it will override the corresponding font.
|
||||
* @param string $style Font style.
|
||||
* Possible values are (case-insensitive):
|
||||
* regular (default)
|
||||
* B: bold
|
||||
* I: italic
|
||||
* U: underline
|
||||
* D: strikeout (linethrough)
|
||||
* O: overline
|
||||
* @param string $ifile The font definition file (or empty for autodetect).
|
||||
* By default, the name is built from the family and style, in lower case with no spaces.
|
||||
* @param ?bool $subset If true embed only a subset of the font
|
||||
* (stores only the information related to
|
||||
* the used characters); If false embed
|
||||
* full font; This option is valid only
|
||||
* for TrueTypeUnicode fonts and is
|
||||
* disabled for PDF/A. If you want to
|
||||
* enable users to modify the document,
|
||||
* set this parameter to false. If you
|
||||
* subset the font, the person who
|
||||
* receives your PDF would need to have
|
||||
* your same font in order to make changes
|
||||
* to your PDF. The file size of the PDF
|
||||
* would also be smaller because you are
|
||||
* embedding only a subset. Set this to
|
||||
* null to use the default value. NOTE:
|
||||
* This option is computational and memory
|
||||
* intensive.
|
||||
*
|
||||
* @return string Font key
|
||||
*
|
||||
* @throws FontException in case of error
|
||||
*/
|
||||
public function add(
|
||||
int &$objnum,
|
||||
string $font,
|
||||
string $style = '',
|
||||
string $ifile = '',
|
||||
?bool $subset = null,
|
||||
): string {
|
||||
if ($subset === null) {
|
||||
$subset = $this->subset;
|
||||
}
|
||||
|
||||
// The font key depends only on (family, style, unicode, pdfa) - all known without
|
||||
// constructing a Font. When autodetecting the definition file (ifile === '') and the
|
||||
// resolved font is already loaded, skip the expensive Font allocation.
|
||||
if ($ifile === '' && isset($this->fontKeyCache[$font][$style])) {
|
||||
$cachedKey = $this->fontKeyCache[$font][$style];
|
||||
if (isset($this->font[$cachedKey])) {
|
||||
return $cachedKey;
|
||||
}
|
||||
}
|
||||
|
||||
$fobj = new Font($font, $style, $ifile, $subset, $this->unicode, $this->pdfa, true, $this->fileHelper);
|
||||
$key = $fobj->getFontkey();
|
||||
if ($ifile === '') {
|
||||
$this->fontKeyCache[$font][$style] = $key;
|
||||
}
|
||||
|
||||
if (isset($this->font[$key])) {
|
||||
return $key;
|
||||
}
|
||||
|
||||
$fobj->load();
|
||||
$this->font[$key] = $fobj->getFontData();
|
||||
|
||||
$this->setFontFile($key);
|
||||
$this->setFontDiff($key);
|
||||
|
||||
$this->font[$key]['i'] = ++$this->numfonts;
|
||||
$this->font[$key]['n'] = ++$objnum; // @phpstan-ignore assign.propertyType
|
||||
|
||||
return $key;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set font file and subset
|
||||
*
|
||||
* @param string $key Font key
|
||||
*/
|
||||
protected function setFontFile(string $key): void
|
||||
{
|
||||
if ($this->font[$key]['file'] === '') {
|
||||
return;
|
||||
}
|
||||
|
||||
$file = $this->font[$key]['file'];
|
||||
if (!isset($this->file[$file])) {
|
||||
$this->file[$file] = [
|
||||
'dir' => '',
|
||||
'keys' => [],
|
||||
'length1' => 0,
|
||||
'length2' => 0,
|
||||
// a shared font file may only be subset if every font referencing it is subset
|
||||
'subset' => $this->font[$key]['subset'],
|
||||
];
|
||||
} else {
|
||||
$this->file[$file]['subset'] = $this->file[$file]['subset'] && $this->font[$key]['subset'];
|
||||
}
|
||||
|
||||
if (!\in_array($key, $this->file[$file]['keys'], true)) {
|
||||
$this->file[$file]['keys'][] = $key;
|
||||
}
|
||||
|
||||
$this->file[$file]['dir'] = $this->font[$key]['dir'];
|
||||
$this->file[$file]['length1'] = $this->font[$key]['length1'];
|
||||
$this->file[$file]['length2'] = $this->font[$key]['length2'];
|
||||
}
|
||||
|
||||
/**
|
||||
* Set font diff
|
||||
*
|
||||
* @param string $key Font key
|
||||
*/
|
||||
protected function setFontDiff(string $key): void
|
||||
{
|
||||
if ($this->font[$key]['diff'] === '') {
|
||||
return;
|
||||
}
|
||||
|
||||
$diffid = \array_search($this->font[$key]['diff'], $this->encdiff, true);
|
||||
if ($diffid === false) {
|
||||
$diffid = ++$this->numdiffs;
|
||||
$this->encdiff[$diffid] = $this->font[$key]['diff'];
|
||||
}
|
||||
|
||||
$this->font[$key]['diffid'] = $diffid;
|
||||
}
|
||||
}
|
||||
+62
@@ -0,0 +1,62 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
/**
|
||||
* Core.php
|
||||
*
|
||||
* @since 2011-05-23
|
||||
* @category Library
|
||||
* @package PdfFont
|
||||
* @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-font
|
||||
*
|
||||
* This file is part of tc-lib-pdf-font software library.
|
||||
*/
|
||||
|
||||
namespace Com\Tecnick\Pdf\Font;
|
||||
|
||||
/**
|
||||
* Com\Tecnick\Pdf\Font\Core
|
||||
*
|
||||
* @since 2011-05-23
|
||||
* @category Library
|
||||
* @package PdfFont
|
||||
* @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-font
|
||||
*/
|
||||
class Core
|
||||
{
|
||||
/**
|
||||
* Core fonts
|
||||
*
|
||||
* @var array<string, string>
|
||||
*/
|
||||
public const FONT = [
|
||||
'courier' => 'Courier',
|
||||
'courierB' => 'Courier-Bold',
|
||||
'courierI' => 'Courier-Oblique',
|
||||
'courierBI' => 'Courier-BoldOblique',
|
||||
'helvetica' => 'Helvetica',
|
||||
'helveticaB' => 'Helvetica-Bold',
|
||||
'helveticaI' => 'Helvetica-Oblique',
|
||||
'helveticaBI' => 'Helvetica-BoldOblique',
|
||||
'timesroman' => 'Times-Roman',
|
||||
'times' => 'Times-Roman',
|
||||
'timesB' => 'Times-Bold',
|
||||
'timesI' => 'Times-Italic',
|
||||
'timesBI' => 'Times-BoldItalic',
|
||||
'symbol' => 'Symbol',
|
||||
'symbolB' => 'Symbol',
|
||||
'symbolI' => 'Symbol',
|
||||
'symbolBI' => 'Symbol',
|
||||
'zapfdingbats' => 'ZapfDingbats',
|
||||
'zapfdingbatsB' => 'ZapfDingbats',
|
||||
'zapfdingbatsI' => 'ZapfDingbats',
|
||||
'zapfdingbatsBI' => 'ZapfDingbats',
|
||||
];
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
/**
|
||||
* Exception.php
|
||||
*
|
||||
* @since 2011-05-23
|
||||
* @category Library
|
||||
* @package PdfFont
|
||||
* @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-font
|
||||
*
|
||||
* This file is part of tc-lib-pdf-font software library.
|
||||
*/
|
||||
|
||||
namespace Com\Tecnick\Pdf\Font;
|
||||
|
||||
/**
|
||||
* Com\Tecnick\Pdf\Font\Exception
|
||||
*
|
||||
* Custom Exception class
|
||||
*
|
||||
* @since 2011-05-23
|
||||
* @category Library
|
||||
* @package PdfFont
|
||||
* @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-font
|
||||
*/
|
||||
class Exception extends \Exception {}
|
||||
+202
@@ -0,0 +1,202 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
/**
|
||||
* Font.php
|
||||
*
|
||||
* @since 2011-05-23
|
||||
* @category Library
|
||||
* @package PdfFont
|
||||
* @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-font
|
||||
*
|
||||
* This file is part of tc-lib-pdf-font software library.
|
||||
*/
|
||||
|
||||
namespace Com\Tecnick\Pdf\Font;
|
||||
|
||||
use Com\Tecnick\File\File as ObjFile;
|
||||
use Com\Tecnick\Pdf\Font\Exception as FontException;
|
||||
|
||||
/**
|
||||
* Com\Tecnick\Pdf\Font\Font
|
||||
*
|
||||
* @since 2011-05-23
|
||||
* @category Library
|
||||
* @package PdfFont
|
||||
* @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-font
|
||||
*
|
||||
* @phpstan-import-type TFontData from Load
|
||||
*/
|
||||
class Font extends \Com\Tecnick\Pdf\Font\Load
|
||||
{
|
||||
/**
|
||||
* Load an imported font
|
||||
*
|
||||
* The definition file (and the font file itself when embedding) must be present either in the current directory
|
||||
* or in the one indicated by K_PATH_FONTS if the constant is defined.
|
||||
*
|
||||
* @param string $font Font family.
|
||||
* If it is a standard family name, it will override the corresponding font.
|
||||
* @param string $style Font style. Possible values are (case-insensitive):
|
||||
* regular (default)
|
||||
* B: bold
|
||||
* I: italic
|
||||
* U: underline
|
||||
* D: strikeout (linethrough)
|
||||
* O: overline
|
||||
* @param string $ifile The font definition file (or empty for autodetect).
|
||||
* By default, the name is built from the family and
|
||||
* style, in lower case with no spaces.
|
||||
* @param bool $subset If true embed only a subset of the font
|
||||
* (stores only the information related to
|
||||
* the used characters); If false embed
|
||||
* full font; This option is valid only for
|
||||
* TrueTypeUnicode fonts and is disabled
|
||||
* for PDF/A. If you want to enable users
|
||||
* to modify the document, set this
|
||||
* parameter to false. If you subset the
|
||||
* font, the person who receives your PDF
|
||||
* would need to have your same font in
|
||||
* order to make changes to your PDF. The
|
||||
* file size of the PDF would also be
|
||||
* smaller because you are embedding only a subset.
|
||||
* @param bool $unicode True in Unicode mode, False otherwise.
|
||||
* @param bool $pdfa True in PDF/A mode, False otherwise.
|
||||
* @param bool $compress Set to false to disable stream compression.
|
||||
* @param ObjFile|null $fileHelper Optional file helper for font loading.
|
||||
*
|
||||
* @throws FontException in case of error
|
||||
*/
|
||||
public function __construct(
|
||||
string $font,
|
||||
string $style = '',
|
||||
string $ifile = '',
|
||||
bool $subset = false,
|
||||
bool $unicode = true,
|
||||
bool $pdfa = false,
|
||||
bool $compress = true,
|
||||
?ObjFile $fileHelper = null,
|
||||
) {
|
||||
parent::__construct($fileHelper);
|
||||
|
||||
if ($font === '') {
|
||||
throw new FontException('empty font family name');
|
||||
}
|
||||
|
||||
if ($ifile !== '') {
|
||||
$validatedIfile = $ifile;
|
||||
if (!$this->fileHelper->isValidFile($validatedIfile)) {
|
||||
throw new FontException('Invalid font ifile: ' . $ifile);
|
||||
}
|
||||
}
|
||||
|
||||
$this->data['ifile'] = $ifile;
|
||||
$this->data['family'] = $font;
|
||||
$this->data['unicode'] = $unicode;
|
||||
$this->data['pdfa'] = $pdfa;
|
||||
$this->data['compress'] = $compress;
|
||||
$this->data['subset'] = $subset;
|
||||
$this->data['subsetchars'] = \array_fill(0, 256, true);
|
||||
|
||||
// generate the font key and set styles
|
||||
$this->setStyle($style);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the font key
|
||||
*/
|
||||
public function getFontkey(): string
|
||||
{
|
||||
return $this->data['key'];
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the font data
|
||||
*
|
||||
* @return TFontData
|
||||
*/
|
||||
public function getFontData(): array
|
||||
{
|
||||
return $this->data;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set style and normalize the font name
|
||||
*
|
||||
* @param string $style Style
|
||||
*/
|
||||
protected function setStyle(string $style): void
|
||||
{
|
||||
$style = \strtoupper($style);
|
||||
if (\str_ends_with($this->data['family'], 'I')) {
|
||||
$style .= 'I';
|
||||
$this->data['family'] = \substr($this->data['family'], 0, -1);
|
||||
}
|
||||
|
||||
if (\str_ends_with($this->data['family'], 'B')) {
|
||||
$style .= 'B';
|
||||
$this->data['family'] = \substr($this->data['family'], 0, -1);
|
||||
}
|
||||
|
||||
// normalize family name
|
||||
$this->data['family'] = \strtolower($this->data['family']);
|
||||
if (!$this->data['unicode'] && $this->data['family'] === 'arial') {
|
||||
$this->data['family'] = 'helvetica';
|
||||
}
|
||||
|
||||
if ($this->data['family'] === 'symbol' || $this->data['family'] === 'zapfdingbats') {
|
||||
$style = '';
|
||||
}
|
||||
|
||||
if ($this->data['pdfa'] && isset(Core::FONT[$this->data['family']])) {
|
||||
// core fonts must be embedded in PDF/A
|
||||
$this->data['family'] = 'pdfa' . $this->data['family'];
|
||||
}
|
||||
|
||||
$this->setStyleMode($style);
|
||||
}
|
||||
|
||||
/**
|
||||
* Set style mode properties
|
||||
*
|
||||
* @param string $style Style
|
||||
*/
|
||||
protected function setStyleMode(string $style): void
|
||||
{
|
||||
$suffix = '';
|
||||
if (\str_contains($style, 'B')) {
|
||||
$this->data['mode']['bold'] = true;
|
||||
$suffix .= 'B';
|
||||
}
|
||||
|
||||
if (\str_contains($style, 'I')) {
|
||||
$this->data['mode']['italic'] = true;
|
||||
$suffix .= 'I';
|
||||
}
|
||||
|
||||
$this->data['style'] = $suffix;
|
||||
if (\str_contains($style, 'U')) {
|
||||
$this->data['style'] .= 'U';
|
||||
$this->data['mode']['underline'] = true;
|
||||
}
|
||||
|
||||
if (\str_contains($style, 'D')) {
|
||||
$this->data['style'] .= 'D';
|
||||
$this->data['mode']['linethrough'] = true;
|
||||
}
|
||||
|
||||
if (\str_contains($style, 'O')) {
|
||||
$this->data['style'] .= 'O';
|
||||
$this->data['mode']['overline'] = true;
|
||||
}
|
||||
|
||||
$this->data['key'] = $this->data['family'] . $suffix;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
/**
|
||||
* FontPaths.php
|
||||
*
|
||||
* @since 2026-06-08
|
||||
* @category Library
|
||||
* @package PdfFont
|
||||
* @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-font
|
||||
*
|
||||
* This file is part of tc-lib-pdf-font software library.
|
||||
*/
|
||||
|
||||
namespace Com\Tecnick\Pdf\Font;
|
||||
|
||||
/**
|
||||
* Shared font paths rooted at the library base directory.
|
||||
*/
|
||||
class FontPaths
|
||||
{
|
||||
/**
|
||||
* Returns the library root directory.
|
||||
*/
|
||||
public static function getLibraryRoot(): string
|
||||
{
|
||||
return \rtrim(\dirname(__DIR__), '/\\');
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the default input font directory.
|
||||
*/
|
||||
public static function getInputPath(): string
|
||||
{
|
||||
return self::getLibraryRoot() . '/fonts';
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the default output font directory.
|
||||
*/
|
||||
public static function getOutputPath(): string
|
||||
{
|
||||
return self::getLibraryRoot() . '/target/fonts';
|
||||
}
|
||||
|
||||
/**
|
||||
* Build trusted roots for local font file access.
|
||||
*
|
||||
* @return array<string>
|
||||
*/
|
||||
public static function buildAllowedPaths(): array
|
||||
{
|
||||
$roots = [
|
||||
self::getInputPath(),
|
||||
self::getOutputPath(),
|
||||
];
|
||||
|
||||
if (\defined('K_PATH_FONTS')) {
|
||||
$kpathfonts = (string) \constant('K_PATH_FONTS');
|
||||
if ($kpathfonts !== '') {
|
||||
$roots[] = $kpathfonts;
|
||||
}
|
||||
}
|
||||
|
||||
$allowed = [];
|
||||
foreach ($roots as $root) {
|
||||
$normalized = \rtrim($root, '/\\');
|
||||
if ($normalized === '') {
|
||||
continue;
|
||||
}
|
||||
|
||||
$allowed[] = $normalized;
|
||||
|
||||
$resolved = \realpath($normalized);
|
||||
if ($resolved !== false) {
|
||||
$allowed[] = \rtrim($resolved, '/\\');
|
||||
}
|
||||
}
|
||||
|
||||
return \array_values(\array_unique($allowed));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
/**
|
||||
* FontSubsetCacheInterface.php
|
||||
*
|
||||
* @since 2026-06-16
|
||||
* @category Library
|
||||
* @package PdfFont
|
||||
* @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-font
|
||||
*
|
||||
* This file is part of tc-lib-pdf-font software library.
|
||||
*/
|
||||
|
||||
namespace Com\Tecnick\Pdf\Font;
|
||||
|
||||
/**
|
||||
* Com\Tecnick\Pdf\Font\FontSubsetCacheInterface
|
||||
*
|
||||
* Optional cache contract for reusing TrueType font subset programs.
|
||||
*
|
||||
* Implementations are injected into Output and consulted before the
|
||||
* (computational and memory intensive) subsetting is performed. The cached
|
||||
* value is the raw subset font program string, i.e. the output of
|
||||
* Subset::getSubsetFont() before any compression or encryption.
|
||||
*
|
||||
* The library never evicts entries; backends own their own expiration and
|
||||
* size limits.
|
||||
*
|
||||
* @since 2026-06-16
|
||||
* @category Library
|
||||
* @package PdfFont
|
||||
* @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-font
|
||||
*/
|
||||
interface FontSubsetCacheInterface
|
||||
{
|
||||
/**
|
||||
* Return the cached subset font program for the given key, or null on miss.
|
||||
*
|
||||
* @param string $key Cache key identifying the font subset.
|
||||
*/
|
||||
public function get(string $key): ?string;
|
||||
|
||||
/**
|
||||
* Store the subset font program for the given key.
|
||||
*
|
||||
* @param string $key Cache key identifying the font subset.
|
||||
* @param string $subsetFont Raw subset font program (uncompressed).
|
||||
*/
|
||||
public function set(string $key, string $subsetFont): void;
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
/**
|
||||
* FontType.php
|
||||
*
|
||||
* @since 2026-07-17
|
||||
* @category Library
|
||||
* @package PdfFont
|
||||
* @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-font
|
||||
*
|
||||
* This file is part of tc-lib-pdf-font software library.
|
||||
*/
|
||||
|
||||
namespace Com\Tecnick\Pdf\Font;
|
||||
|
||||
use Com\Tecnick\Pdf\Font\Exception as FontException;
|
||||
|
||||
/**
|
||||
* Com\Tecnick\Pdf\Font\FontType
|
||||
*
|
||||
* Backed enum for the font type accepted by Import::__construct. The backing
|
||||
* value of each case is the canonical type name; the empty string selects
|
||||
* autodetection.
|
||||
*
|
||||
* @since 2026-07-17
|
||||
* @category Library
|
||||
* @package PdfFont
|
||||
* @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-font
|
||||
*/
|
||||
enum FontType: string
|
||||
{
|
||||
/** Autodetect the font type from the file contents. */
|
||||
case Auto = '';
|
||||
|
||||
/** Adobe Font Metrics (one of the 14 Core fonts). */
|
||||
case Core = 'Core';
|
||||
|
||||
case TrueType = 'TrueType';
|
||||
|
||||
case TrueTypeUnicode = 'TrueTypeUnicode';
|
||||
|
||||
case Type1 = 'Type1';
|
||||
|
||||
/** CID-0 Japanese. */
|
||||
case Cid0Jp = 'CID0JP';
|
||||
|
||||
/** CID-0 Korean. */
|
||||
case Cid0Kr = 'CID0KR';
|
||||
|
||||
/** CID-0 Chinese Simplified. */
|
||||
case Cid0Cs = 'CID0CS';
|
||||
|
||||
/** CID-0 Chinese Traditional. */
|
||||
case Cid0Ct = 'CID0CT';
|
||||
|
||||
/**
|
||||
* Resolve a loose font type value to the matching enum case.
|
||||
*
|
||||
* Accepts the canonical type name (or the empty string for autodetection)
|
||||
* or an enum instance (returned unchanged). Unknown values throw, matching
|
||||
* the closed set validated by Import::getFontType().
|
||||
*
|
||||
* @param string|self $value Font type name or enum case.
|
||||
*
|
||||
* @throws FontException if the value does not match a known font type.
|
||||
*/
|
||||
public static function fromLoose(string|self $value): self
|
||||
{
|
||||
if ($value instanceof self) {
|
||||
return $value;
|
||||
}
|
||||
|
||||
return self::tryFrom($value) ?? throw new FontException('unknown or unsupported font type: ' . $value);
|
||||
}
|
||||
}
|
||||
+741
@@ -0,0 +1,741 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
/**
|
||||
* Import.php
|
||||
*
|
||||
* @since 2011-05-23
|
||||
* @category Library
|
||||
* @package PdfFont
|
||||
* @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-font
|
||||
*
|
||||
* This file is part of tc-lib-pdf-font software library.
|
||||
*/
|
||||
|
||||
namespace Com\Tecnick\Pdf\Font;
|
||||
|
||||
use Com\Tecnick\File\Byte;
|
||||
use Com\Tecnick\File\Dir;
|
||||
use Com\Tecnick\File\Exception as FileException;
|
||||
use Com\Tecnick\File\File as ObjFile;
|
||||
use Com\Tecnick\Pdf\Font\Exception as FontException;
|
||||
use Com\Tecnick\Pdf\Font\Import\Core;
|
||||
use Com\Tecnick\Pdf\Font\Import\TrueType;
|
||||
use Com\Tecnick\Pdf\Font\Import\TypeOne;
|
||||
use Com\Tecnick\Unicode\Data\Encoding;
|
||||
|
||||
/**
|
||||
* Com\Tecnick\Pdf\Font\Import
|
||||
*
|
||||
* @since 2011-05-23
|
||||
* @category Library
|
||||
* @package PdfFont
|
||||
* @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-font
|
||||
*
|
||||
* @phpstan-import-type TFontData from Load
|
||||
*
|
||||
* @SuppressWarnings("PHPMD.ExcessiveClassComplexity")
|
||||
*/
|
||||
class Import
|
||||
{
|
||||
/**
|
||||
* File helper used to load font definition files.
|
||||
*/
|
||||
protected ObjFile $fileHelper;
|
||||
|
||||
/**
|
||||
* True when the file helper is created internally by this class.
|
||||
*/
|
||||
protected bool $ownsFileHelper = false;
|
||||
|
||||
/**
|
||||
* Content of the input font file
|
||||
*/
|
||||
protected string $font = '';
|
||||
|
||||
/**
|
||||
* Object used to read font bytes
|
||||
*/
|
||||
protected Byte $fbyte;
|
||||
|
||||
/**
|
||||
* Extracted font metrics
|
||||
*
|
||||
* @var TFontData
|
||||
*/
|
||||
protected array $fdt = [
|
||||
'Ascender' => 0,
|
||||
'Ascent' => 0,
|
||||
'AvgWidth' => 0.0,
|
||||
'CapHeight' => 0,
|
||||
'CharacterSet' => '',
|
||||
'Descender' => 0,
|
||||
'Descent' => 0,
|
||||
'EncodingScheme' => '',
|
||||
'FamilyName' => '',
|
||||
'Flags' => 0,
|
||||
'FontBBox' => [],
|
||||
'FontName' => '',
|
||||
'FullName' => '',
|
||||
'IsFixedPitch' => false,
|
||||
'ItalicAngle' => 0,
|
||||
'Leading' => 0,
|
||||
'MaxWidth' => 0,
|
||||
'MissingWidth' => 0,
|
||||
'StdHW' => 0,
|
||||
'StdVW' => 0,
|
||||
'StemH' => 0,
|
||||
'StemV' => 0,
|
||||
'UnderlinePosition' => 0,
|
||||
'UnderlineThickness' => 0,
|
||||
'Version' => '',
|
||||
'Weight' => '',
|
||||
'XHeight' => 0,
|
||||
'bbox' => '',
|
||||
'cbbox' => [],
|
||||
'cidinfo' => [
|
||||
'Ordering' => '',
|
||||
'Registry' => '',
|
||||
'Supplement' => 0,
|
||||
'uni2cid' => [],
|
||||
],
|
||||
'compress' => false,
|
||||
'ctg' => '',
|
||||
'ctgdata' => [],
|
||||
'cw' => [],
|
||||
'cwu' => [],
|
||||
'datafile' => '',
|
||||
'desc' => [
|
||||
'Ascent' => 0,
|
||||
'AvgWidth' => 0,
|
||||
'CapHeight' => 0,
|
||||
'Descent' => 0,
|
||||
'Flags' => 0,
|
||||
'FontBBox' => '',
|
||||
'ItalicAngle' => 0,
|
||||
'Leading' => 0,
|
||||
'MaxWidth' => 0,
|
||||
'MissingWidth' => 0,
|
||||
'StemH' => 0,
|
||||
'StemV' => 0,
|
||||
'XHeight' => 0,
|
||||
],
|
||||
'diff' => '',
|
||||
'diff_n' => 0,
|
||||
'dir' => '',
|
||||
'dw' => 0,
|
||||
'enc' => '',
|
||||
'enc_map' => [],
|
||||
'encodingTables' => [],
|
||||
'encoding_id' => 0,
|
||||
'encrypted' => '',
|
||||
'fakestyle' => false,
|
||||
'family' => '',
|
||||
'file' => '',
|
||||
'file_n' => 0,
|
||||
'file_name' => '',
|
||||
'i' => 0,
|
||||
'ifile' => '',
|
||||
'indexToLoc' => [],
|
||||
'input_file' => '',
|
||||
'isUnicode' => false,
|
||||
'italicAngle' => 0,
|
||||
'key' => '',
|
||||
'lenIV' => 0,
|
||||
'length1' => 0,
|
||||
'length2' => 0,
|
||||
'linked' => false,
|
||||
'mode' => [
|
||||
'bold' => false,
|
||||
'italic' => false,
|
||||
'linethrough' => false,
|
||||
'overline' => false,
|
||||
'underline' => false,
|
||||
],
|
||||
'n' => 0,
|
||||
'name' => '',
|
||||
'numGlyphs' => 0,
|
||||
'numHMetrics' => 0,
|
||||
'originalsize' => 0,
|
||||
'pdfa' => false,
|
||||
'platform_id' => 0,
|
||||
'settype' => '',
|
||||
'short_offset' => false,
|
||||
'size1' => 0,
|
||||
'size2' => 0,
|
||||
'style' => '',
|
||||
'subset' => false,
|
||||
'subsetchars' => [],
|
||||
'table' => [],
|
||||
'tot_num_glyphs' => 0,
|
||||
'type' => '',
|
||||
'underlinePosition' => 0,
|
||||
'underlineThickness' => 0,
|
||||
'unicode' => false,
|
||||
'unitsPerEm' => 0,
|
||||
'up' => 0,
|
||||
'urk' => 0.0,
|
||||
'ut' => 0,
|
||||
'weight' => '',
|
||||
];
|
||||
|
||||
/**
|
||||
* Import the specified font and create output files.
|
||||
*
|
||||
* @param string $file Font file to process
|
||||
* @param string $output_path Output path for generated font files (must be writeable by the web server).
|
||||
* Leave null for default font folder.
|
||||
* @param string|FontType $type Font type (or FontType enum case). Leave empty for autodetect mode.
|
||||
* Valid values are:
|
||||
* Core (AFM - Adobe Font Metrics) TrueTypeUnicode TrueType
|
||||
* Type1 CID0JP (CID-0 Japanese) CID0KR (CID-0 Korean) CID0CS
|
||||
* (CID-0 Chinese Simplified) CID0CT (CID-0 Chinese Traditional)
|
||||
* @param string $encoding Name of the encoding table to use. Leave empty for default mode.
|
||||
* Omit this parameter for TrueType Unicode and symbolic fonts like
|
||||
* Symbol or ZapfDingBats.
|
||||
* @param int $flags Unsigned 32-bit integer containing flags specifying various characteristics
|
||||
* of the font as described in "PDF32000:2008 - 9.8.2 Font Descriptor Flags":
|
||||
* +1 for fixed width font +4 for symbol or +32 for non-symbol +64 for italic
|
||||
* Note: Fixed and Italic mode are generally autodetected, so you have to set
|
||||
* it to 32 = non-symbolic font (default) or 4 = symbolic font.
|
||||
* @param int $platform_id Platform ID for CMAP table to extract.
|
||||
* For a Unicode font for Windows this
|
||||
* value should be 3, for Macintosh
|
||||
* should be 1.
|
||||
* @param int $encoding_id Encoding ID for CMAP table to extract.
|
||||
* For a Unicode font for Windows this
|
||||
* value should be 1, for Macintosh
|
||||
* should be 0. When Platform ID is 3,
|
||||
* legal values for Encoding ID are: 0 =
|
||||
* Symbol, 1 = Unicode, 2 = ShiftJIS, 3 =
|
||||
* PRC, 4 = Big5, 5 = Wansung, 6 = Johab,
|
||||
* 7 = Reserved, 8 = Reserved, 9 =
|
||||
* Reserved, 10 = UCS-4.
|
||||
* @param bool $linked If true, links the font file to system font instead of copying the font data
|
||||
* (not transportable). Note: this option do not work with Type1 fonts.
|
||||
* @param ObjFile|null $fileHelper Optional file helper for font loading.
|
||||
*
|
||||
* @throws FileException in case of error
|
||||
* @throws FontException in case of error
|
||||
* @throws \RangeException in case of byte-range errors
|
||||
*/
|
||||
public function __construct(
|
||||
string $file,
|
||||
string $output_path = '',
|
||||
string|FontType $type = '',
|
||||
string $encoding = '',
|
||||
int $flags = 32,
|
||||
int $platform_id = 3,
|
||||
int $encoding_id = 1,
|
||||
bool $linked = false,
|
||||
?ObjFile $fileHelper = null,
|
||||
) {
|
||||
$this->ownsFileHelper = $fileHelper === null;
|
||||
$this->fileHelper = $fileHelper ?? new ObjFile(allowedPaths: self::buildAllowedPaths($file));
|
||||
$validatedFile = $file;
|
||||
if (!$this->fileHelper->isValidFile($validatedFile)) {
|
||||
throw new FontException('Invalid font file name: ' . $file);
|
||||
}
|
||||
|
||||
$this->fdt['input_file'] = $file;
|
||||
$this->fdt['file_name'] = $this->makeFontName($file);
|
||||
if ($this->fdt['file_name'] === '') {
|
||||
throw new FontException('the font name is empty');
|
||||
}
|
||||
|
||||
$this->fdt['dir'] = $this->findOutputPath($output_path);
|
||||
if ($this->ownsFileHelper) {
|
||||
$this->fileHelper->setAllowedPaths(self::buildAllowedPaths($file, $this->fdt['dir']));
|
||||
}
|
||||
|
||||
$this->fdt['datafile'] = $this->fdt['dir'] . $this->fdt['file_name'] . '.json';
|
||||
if (\file_exists($this->fdt['datafile'])) {
|
||||
throw new FontException('this font has been already imported: ' . $this->fdt['datafile']);
|
||||
}
|
||||
|
||||
// get font data
|
||||
if (!is_file($file)) {
|
||||
throw new FontException('invalid font file: ' . $file);
|
||||
}
|
||||
|
||||
if (($font = $this->fileHelper->getLocalFileData($file)) === false) {
|
||||
throw new FontException('unable to read the input font file: ' . $file);
|
||||
}
|
||||
|
||||
$this->font = $font;
|
||||
|
||||
$this->fbyte = new Byte($this->font);
|
||||
|
||||
if ($type instanceof FontType) {
|
||||
$type = $type->value;
|
||||
}
|
||||
|
||||
$this->fdt['settype'] = $type;
|
||||
$this->fdt['type'] = $this->getFontType($type);
|
||||
$this->fdt['isUnicode'] = $this->fdt['type'] === 'TrueTypeUnicode' || $this->fdt['type'] === 'cidfont0';
|
||||
$this->fdt['Flags'] = $flags;
|
||||
$this->initFlags();
|
||||
$this->fdt['enc'] = $this->getEncodingTable($encoding);
|
||||
$this->fdt['diff'] = $this->getEncodingDiff();
|
||||
$this->fdt['originalsize'] = \strlen($this->font);
|
||||
$this->fdt['ctg'] = $this->fdt['file_name'] . '.ctg.z';
|
||||
$this->fdt['platform_id'] = $platform_id;
|
||||
$this->fdt['encoding_id'] = $encoding_id;
|
||||
$this->fdt['linked'] = $linked;
|
||||
|
||||
$processor = match ($this->fdt['type']) {
|
||||
'Core' => new Core(font: $this->font, fdt: $this->fdt, fileHelper: $this->fileHelper),
|
||||
'Type1' => new TypeOne(font: $this->font, fdt: $this->fdt, fileHelper: $this->fileHelper),
|
||||
default => new TrueType(
|
||||
font: $this->font,
|
||||
fdt: $this->fdt,
|
||||
fileHelper: $this->fileHelper,
|
||||
fbyte: $this->fbyte,
|
||||
),
|
||||
};
|
||||
|
||||
$this->fdt = $processor->getFontMetrics();
|
||||
|
||||
$this->saveFontData();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all the extracted font metrics
|
||||
*
|
||||
* @return TFontData
|
||||
*/
|
||||
public function getFontMetrics(): array
|
||||
{
|
||||
return $this->fdt;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the output font name
|
||||
*/
|
||||
public function getFontName(): string
|
||||
{
|
||||
return $this->fdt['file_name'];
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialize font flags from font name
|
||||
*/
|
||||
protected function initFlags(): void
|
||||
{
|
||||
$filename = \strtolower(\basename($this->fdt['input_file']));
|
||||
|
||||
if (
|
||||
\str_contains($filename, 'mono')
|
||||
|| \str_contains($filename, 'courier')
|
||||
|| \str_contains($filename, 'fixed')
|
||||
) {
|
||||
$this->fdt['Flags'] |= 1;
|
||||
}
|
||||
|
||||
if (\str_contains($filename, 'symbol') || \str_contains($filename, 'zapfdingbats')) {
|
||||
$this->fdt['Flags'] |= 4;
|
||||
}
|
||||
|
||||
if (\str_contains($filename, 'italic') || \str_contains($filename, 'oblique')) {
|
||||
$this->fdt['Flags'] |= 64;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Check for unsafe path components that were previously rejected by the
|
||||
* file helper's internal validation.
|
||||
*/
|
||||
private static function hasUnsafePath(string $path): bool
|
||||
{
|
||||
return (
|
||||
$path !== ''
|
||||
&& (
|
||||
\str_contains($path, '://')
|
||||
|| \str_contains(\str_ireplace('%2E', '.', \html_entity_decode($path, ENT_QUOTES, 'UTF-8')), '..')
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Build trusted roots for local file validation.
|
||||
*
|
||||
* The minimum roots required by Import are:
|
||||
* - the input font directory (read access)
|
||||
* - the output directory (write access), when available
|
||||
*
|
||||
* For each root we include both the given path and, when resolvable,
|
||||
* its canonical realpath to support symlinked directories.
|
||||
*
|
||||
* @return array<string>
|
||||
*/
|
||||
private static function buildAllowedPaths(string $fontFile, string $outputDir = ''): array
|
||||
{
|
||||
$roots = [];
|
||||
|
||||
$fontDir = \dirname($fontFile);
|
||||
if ($fontDir !== '' && $fontDir !== '.') {
|
||||
$roots[] = $fontDir;
|
||||
}
|
||||
|
||||
if ($outputDir !== '') {
|
||||
$roots[] = $outputDir;
|
||||
}
|
||||
|
||||
$allowed = [];
|
||||
foreach ($roots as $root) {
|
||||
$normalized = \rtrim($root, '/\\');
|
||||
if ($normalized === '') {
|
||||
continue;
|
||||
}
|
||||
|
||||
$allowed[] = $normalized;
|
||||
|
||||
$resolved = \realpath($normalized);
|
||||
if ($resolved !== false) {
|
||||
$allowed[] = \rtrim($resolved, '/\\');
|
||||
}
|
||||
}
|
||||
|
||||
return \array_values(\array_unique($allowed));
|
||||
}
|
||||
|
||||
/**
|
||||
* Save the exported metadata font file
|
||||
*
|
||||
* @throws FileException
|
||||
* @throws FontException
|
||||
*
|
||||
* @SuppressWarnings("PHPMD.CyclomaticComplexity")
|
||||
* @SuppressWarnings("PHPMD.NPathComplexity")
|
||||
* @SuppressWarnings("PHPMD.ExcessiveMethodLength")
|
||||
*/
|
||||
protected function saveFontData(): void
|
||||
{
|
||||
$missingWidth = $this->fdt['MissingWidth'];
|
||||
$pfile =
|
||||
'{"type":"'
|
||||
. $this->fdt['type']
|
||||
. '"'
|
||||
. ',"name":"'
|
||||
. $this->fdt['name']
|
||||
. '"'
|
||||
. ',"up":'
|
||||
. $this->fdt['underlinePosition']
|
||||
. ',"ut":'
|
||||
. $this->fdt['underlineThickness']
|
||||
. ',"dw":'
|
||||
. ($missingWidth !== null && $missingWidth > 0 ? $missingWidth : $this->fdt['AvgWidth'])
|
||||
. ',"diff":"'
|
||||
. $this->fdt['diff']
|
||||
. '"'
|
||||
. ',"platform_id":'
|
||||
. $this->fdt['platform_id']
|
||||
. ',"encoding_id":'
|
||||
. $this->fdt['encoding_id'];
|
||||
|
||||
if ($this->fdt['type'] === 'Core') {
|
||||
// Core
|
||||
$pfile .= ',"enc":""';
|
||||
} elseif ($this->fdt['type'] === 'Type1') {
|
||||
// Type 1
|
||||
$pfile .=
|
||||
',"enc":"'
|
||||
. $this->fdt['enc']
|
||||
. '"'
|
||||
. ',"file":"'
|
||||
. $this->fdt['file']
|
||||
. '"'
|
||||
. ',"size1":'
|
||||
. $this->fdt['size1']
|
||||
. ',"size2":'
|
||||
. $this->fdt['size2'];
|
||||
} else {
|
||||
$pfile .= ',"originalsize":' . $this->fdt['originalsize'];
|
||||
if ($this->fdt['type'] === 'cidfont0') {
|
||||
$pfile .= ',' . (UniToCid::TYPE[$this->fdt['settype']] ?? '');
|
||||
} else {
|
||||
// TrueType
|
||||
$pfile .=
|
||||
',"enc":"'
|
||||
. $this->fdt['enc']
|
||||
. '"'
|
||||
. ',"file":"'
|
||||
. $this->fdt['file']
|
||||
. '"'
|
||||
. ',"ctg":"'
|
||||
. $this->fdt['ctg']
|
||||
. '"';
|
||||
// create CIDToGIDMap
|
||||
$cidtogidmap = \str_pad('', 131_072, "\x00"); // (256 * 256 * 2) = 131072
|
||||
foreach ($this->fdt['ctgdata'] as $cid => $gid) {
|
||||
$cidtogidmap = $this->updateCIDtoGIDmap($cidtogidmap, (int) $cid, (int) $gid);
|
||||
}
|
||||
|
||||
// store compressed CIDToGIDMap
|
||||
$fpt = $this->fileHelper->fopenLocal($this->fdt['dir'] . $this->fdt['ctg'], 'wb');
|
||||
|
||||
$cmpr = \gzcompress($cidtogidmap);
|
||||
if ($cmpr === false) {
|
||||
throw new FontException('unable to compress CIDToGIDMap');
|
||||
}
|
||||
|
||||
\fwrite($fpt, $cmpr);
|
||||
\fclose($fpt);
|
||||
}
|
||||
}
|
||||
|
||||
if ($this->fdt['isUnicode']) {
|
||||
$pfile .= ',"isUnicode":true';
|
||||
} else {
|
||||
$pfile .= ',"isUnicode":false';
|
||||
}
|
||||
|
||||
$pfile .=
|
||||
',"desc":{"Flags":'
|
||||
. $this->fdt['Flags']
|
||||
. ',"FontBBox":"['
|
||||
. $this->fdt['bbox']
|
||||
. ']"'
|
||||
. ',"ItalicAngle":'
|
||||
. $this->fdt['italicAngle']
|
||||
. ',"Ascent":'
|
||||
. $this->fdt['Ascent']
|
||||
. ',"Descent":'
|
||||
. $this->fdt['Descent']
|
||||
. ',"Leading":'
|
||||
. $this->fdt['Leading']
|
||||
. ',"CapHeight":'
|
||||
. $this->fdt['CapHeight']
|
||||
. ',"XHeight":'
|
||||
. $this->fdt['XHeight']
|
||||
. ',"StemV":'
|
||||
. $this->fdt['StemV']
|
||||
. ',"StemH":'
|
||||
. $this->fdt['StemH']
|
||||
. ',"AvgWidth":'
|
||||
. $this->fdt['AvgWidth']
|
||||
. ',"MaxWidth":'
|
||||
. $this->fdt['MaxWidth']
|
||||
. ',"MissingWidth":'
|
||||
. (string) ($missingWidth ?? 0)
|
||||
. '}';
|
||||
if ($this->fdt['cbbox'] !== []) {
|
||||
$ccboxstr = '';
|
||||
foreach ($this->fdt['cbbox'] as $cid => $bbox) {
|
||||
$box = \array_pad(\array_values($bbox), 4, 0);
|
||||
$ccboxstr .= ',"' . $cid . '":[' . $box[0] . ',' . $box[1] . ',' . $box[2] . ',' . $box[3] . ']';
|
||||
}
|
||||
|
||||
$pfile .= ',"cbbox":{' . \substr($ccboxstr, 1) . '}';
|
||||
}
|
||||
|
||||
if ($this->fdt['cw'] !== []) {
|
||||
$cwstr = '';
|
||||
foreach ($this->fdt['cw'] as $cid => $width) {
|
||||
$cwstr .= ',"' . $cid . '":' . $width;
|
||||
}
|
||||
|
||||
$pfile .= ',"cw":{' . \substr($cwstr, 1) . '}';
|
||||
}
|
||||
|
||||
if ($this->fdt['cwu'] !== []) {
|
||||
$cwustr = '';
|
||||
foreach ($this->fdt['cwu'] as $codepoint => $width) {
|
||||
$cwustr .= ',"' . $codepoint . '":' . $width;
|
||||
}
|
||||
|
||||
$pfile .= ',"cwu":{' . \substr($cwustr, 1) . '}';
|
||||
}
|
||||
|
||||
$pfile .= '}' . "\n";
|
||||
|
||||
// store file
|
||||
$fpt = $this->fileHelper->fopenLocal($this->fdt['datafile'], 'wb');
|
||||
\fwrite($fpt, $pfile);
|
||||
\fclose($fpt);
|
||||
}
|
||||
|
||||
/**
|
||||
* Make the output font name
|
||||
*
|
||||
* @param string $font_file Input font file
|
||||
*
|
||||
* @throws FontException
|
||||
*/
|
||||
protected function makeFontName(string $font_file): string
|
||||
{
|
||||
$font_path_parts = \pathinfo($font_file);
|
||||
if ($font_path_parts['filename'] === '') {
|
||||
throw new FontException('Invalid font file name: ' . $font_file);
|
||||
}
|
||||
|
||||
$fname = \preg_replace('/[^a-z0-9_]/', '', \strtolower($font_path_parts['filename']));
|
||||
if ($fname === null) {
|
||||
throw new FontException('Invalid font file name: ' . $font_file);
|
||||
}
|
||||
|
||||
return \str_replace(['bold', 'oblique', 'italic', 'regular'], ['b', 'i', 'i', ''], $fname);
|
||||
}
|
||||
|
||||
/**
|
||||
* Find the path where to store the processed font.
|
||||
*
|
||||
* @param string $output_path Output path for generated font files (must be writeable by the web server).
|
||||
* Leave null for default font folder (K_PATH_FONTS).
|
||||
*/
|
||||
protected function findOutputPath(string $output_path = ''): string
|
||||
{
|
||||
if ($output_path !== '' && !self::hasUnsafePath($output_path) && \is_writable($output_path)) {
|
||||
return $output_path;
|
||||
}
|
||||
|
||||
if (\defined('K_PATH_FONTS')) {
|
||||
$kpathfonts = (string) \constant('K_PATH_FONTS');
|
||||
if ($kpathfonts !== '' && \is_writable($kpathfonts)) {
|
||||
return $kpathfonts;
|
||||
}
|
||||
}
|
||||
|
||||
$dirobj = new Dir();
|
||||
$dir = $dirobj->findParentDir('fonts', __DIR__);
|
||||
if ($dir === '/') {
|
||||
$dir = \sys_get_temp_dir();
|
||||
}
|
||||
|
||||
if (!\str_ends_with($dir, '/')) {
|
||||
$dir .= '/';
|
||||
}
|
||||
|
||||
return $dir;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the font type
|
||||
*
|
||||
* @param string $font_type Font type. Leave empty for autodetect mode.
|
||||
*
|
||||
* @throws FontException
|
||||
*/
|
||||
protected function getFontType(string $font_type): string
|
||||
{
|
||||
// autodetect font type
|
||||
if ($font_type === '') {
|
||||
if (\str_starts_with($this->font, 'StartFontMetrics')) {
|
||||
// AFM type - we use this type only for the 14 Core fonts
|
||||
return 'Core';
|
||||
}
|
||||
|
||||
if (\str_starts_with($this->font, 'OTTO')) {
|
||||
throw new FontException('Unsupported font format: OpenType with CFF data');
|
||||
}
|
||||
|
||||
if ($this->fbyte->getULong(0) === 0x1_0000) {
|
||||
return 'TrueTypeUnicode';
|
||||
}
|
||||
|
||||
return 'Type1';
|
||||
}
|
||||
|
||||
if (\str_starts_with($font_type, 'CID0')) {
|
||||
return 'cidfont0';
|
||||
}
|
||||
|
||||
if (\in_array($font_type, ['Core', 'Type1', 'TrueType', 'TrueTypeUnicode'], true)) {
|
||||
return $font_type;
|
||||
}
|
||||
|
||||
throw new FontException('unknown or unsupported font type: ' . $font_type);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the encoding table
|
||||
*
|
||||
* @param string $encoding Name of the encoding table to use. Leave empty for default mode.
|
||||
* Omit this parameter for TrueType Unicode and symbolic fonts like
|
||||
* Symbol or ZapfDingBats.
|
||||
*
|
||||
* @throws FontException
|
||||
*/
|
||||
protected function getEncodingTable(string $encoding = ''): string
|
||||
{
|
||||
if ($encoding === '') {
|
||||
if ($this->fdt['type'] === 'Type1' && ($this->fdt['Flags'] & 4) === 0) {
|
||||
return 'cp1252';
|
||||
}
|
||||
|
||||
return '';
|
||||
}
|
||||
|
||||
$enc = \preg_replace('/[^A-Za-z0-9_\-]/', '', $encoding);
|
||||
if ($enc === null) {
|
||||
throw new FontException('Invalid encoding name: ' . $encoding);
|
||||
}
|
||||
|
||||
return $enc;
|
||||
}
|
||||
|
||||
/**
|
||||
* If required, get differences between the reference encoding (cp1252) and the current encoding
|
||||
*
|
||||
* @SuppressWarnings("PHPMD.CyclomaticComplexity")
|
||||
*/
|
||||
protected function getEncodingDiff(): string
|
||||
{
|
||||
$diff = '';
|
||||
if (
|
||||
($this->fdt['type'] === 'TrueType' || $this->fdt['type'] === 'Type1')
|
||||
&& ($this->fdt['enc'] !== '' && $this->fdt['enc'] !== 'cp1252' && isset(Encoding::MAP[$this->fdt['enc']]))
|
||||
) {
|
||||
// build differences from reference encoding
|
||||
$enc_ref = Encoding::MAP['cp1252'] ?? [];
|
||||
$enc_target = Encoding::MAP[$this->fdt['enc']];
|
||||
$last = 0;
|
||||
for ($idx = 32; $idx <= 255; ++$idx) {
|
||||
$target = $enc_target[$idx] ?? '';
|
||||
$ref = $enc_ref[$idx] ?? '';
|
||||
if ($target === $ref) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if ($idx !== ($last + 1)) {
|
||||
$diff .= $idx . ' ';
|
||||
}
|
||||
|
||||
$last = $idx;
|
||||
$diff .= '/' . $target . ' ';
|
||||
}
|
||||
}
|
||||
|
||||
return $diff;
|
||||
}
|
||||
|
||||
/**
|
||||
* Update the CIDToGIDMap string with a new value
|
||||
*
|
||||
* The CIDToGIDMap is made up of 16-bit values mapping a zero-based
|
||||
* Character Identifier index to its zero-based glyph id index.
|
||||
*
|
||||
* @param string $map CIDToGIDMap (binary).
|
||||
* @param int $cid CID value.
|
||||
* @param int $gid GID value.
|
||||
*/
|
||||
protected function updateCIDtoGIDmap(string $map, int $cid, int $gid): string
|
||||
{
|
||||
// The CIDToGIDMap is a table of 16-bit big-endian values, so a glyph id outside
|
||||
// 0..0xFFFF cannot be represented; such entries are left as 0 (notdef) rather than
|
||||
// being silently wrapped into a bogus glyph id.
|
||||
if ($cid >= 0 && $cid <= 0xFFFF && $gid >= 0 && $gid <= 0xFFFF) {
|
||||
$map[$cid * 2] = \chr($gid >> 8);
|
||||
$map[($cid * 2) + 1] = \chr($gid & 0xFF);
|
||||
}
|
||||
|
||||
return $map;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,622 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
/**
|
||||
* Core.php
|
||||
*
|
||||
* @since 2011-05-23
|
||||
* @category Library
|
||||
* @package PdfFont
|
||||
* @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-font
|
||||
*
|
||||
* This file is part of tc-lib-pdf-font software library.
|
||||
*/
|
||||
|
||||
namespace Com\Tecnick\Pdf\Font\Import;
|
||||
|
||||
use Com\Tecnick\File\File as ObjFile;
|
||||
use Com\Tecnick\Pdf\Font\Exception as FontException;
|
||||
use Com\Tecnick\Unicode\Data\Encoding;
|
||||
|
||||
/**
|
||||
* Com\Tecnick\Pdf\Font\Import\Core
|
||||
*
|
||||
* @since 2011-05-23
|
||||
* @category Library
|
||||
* @package PdfFont
|
||||
* @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-font
|
||||
*
|
||||
* @phpstan-import-type TFontData from \Com\Tecnick\Pdf\Font\Load
|
||||
* @SuppressWarnings("PHPMD.ExcessiveClassComplexity")
|
||||
*/
|
||||
class Core
|
||||
{
|
||||
/**
|
||||
* Adobe Glyph List subset covering all Core14 AFM glyph names.
|
||||
* Maps AFM glyph names to Unicode codepoints.
|
||||
*
|
||||
* @var array<string, int>
|
||||
*/
|
||||
private const GLYPH_UNICODE = [
|
||||
'A' => 0x0041,
|
||||
'AE' => 0x00C6,
|
||||
'Aacute' => 0x00C1,
|
||||
'Abreve' => 0x0102,
|
||||
'Acircumflex' => 0x00C2,
|
||||
'Adieresis' => 0x00C4,
|
||||
'Agrave' => 0x00C0,
|
||||
'Amacron' => 0x0100,
|
||||
'Aogonek' => 0x0104,
|
||||
'Aring' => 0x00C5,
|
||||
'Atilde' => 0x00C3,
|
||||
'B' => 0x0042,
|
||||
'C' => 0x0043,
|
||||
'Cacute' => 0x0106,
|
||||
'Ccaron' => 0x010C,
|
||||
'Ccedilla' => 0x00C7,
|
||||
'D' => 0x0044,
|
||||
'Dcaron' => 0x010E,
|
||||
'Dcroat' => 0x0110,
|
||||
'Delta' => 0x2206,
|
||||
'E' => 0x0045,
|
||||
'Eacute' => 0x00C9,
|
||||
'Ecaron' => 0x011A,
|
||||
'Ecircumflex' => 0x00CA,
|
||||
'Edieresis' => 0x00CB,
|
||||
'Edotaccent' => 0x0116,
|
||||
'Egrave' => 0x00C8,
|
||||
'Emacron' => 0x0112,
|
||||
'Eogonek' => 0x0118,
|
||||
'Eth' => 0x00D0,
|
||||
'Euro' => 0x20AC,
|
||||
'F' => 0x0046,
|
||||
'G' => 0x0047,
|
||||
'Gbreve' => 0x011E,
|
||||
'Gcommaaccent' => 0x0122,
|
||||
'H' => 0x0048,
|
||||
'I' => 0x0049,
|
||||
'Iacute' => 0x00CD,
|
||||
'Icircumflex' => 0x00CE,
|
||||
'Idieresis' => 0x00CF,
|
||||
'Idotaccent' => 0x0130,
|
||||
'Igrave' => 0x00CC,
|
||||
'Imacron' => 0x012A,
|
||||
'Iogonek' => 0x012E,
|
||||
'J' => 0x004A,
|
||||
'K' => 0x004B,
|
||||
'Kcommaaccent' => 0x0136,
|
||||
'L' => 0x004C,
|
||||
'Lacute' => 0x0139,
|
||||
'Lcaron' => 0x013D,
|
||||
'Lcommaaccent' => 0x013B,
|
||||
'Lslash' => 0x0141,
|
||||
'M' => 0x004D,
|
||||
'N' => 0x004E,
|
||||
'Nacute' => 0x0143,
|
||||
'Ncaron' => 0x0147,
|
||||
'Ncommaaccent' => 0x0145,
|
||||
'Ntilde' => 0x00D1,
|
||||
'O' => 0x004F,
|
||||
'OE' => 0x0152,
|
||||
'Oacute' => 0x00D3,
|
||||
'Ocircumflex' => 0x00D4,
|
||||
'Odieresis' => 0x00D6,
|
||||
'Ograve' => 0x00D2,
|
||||
'Ohungarumlaut' => 0x0150,
|
||||
'Omacron' => 0x014C,
|
||||
'Oslash' => 0x00D8,
|
||||
'Otilde' => 0x00D5,
|
||||
'P' => 0x0050,
|
||||
'Q' => 0x0051,
|
||||
'R' => 0x0052,
|
||||
'Racute' => 0x0154,
|
||||
'Rcaron' => 0x0158,
|
||||
'Rcommaaccent' => 0x0156,
|
||||
'S' => 0x0053,
|
||||
'Sacute' => 0x015A,
|
||||
'Scaron' => 0x0160,
|
||||
'Scedilla' => 0x015E,
|
||||
'Scommaaccent' => 0x0218,
|
||||
'T' => 0x0054,
|
||||
'Tcaron' => 0x0164,
|
||||
'Tcommaaccent' => 0x0162,
|
||||
'Thorn' => 0x00DE,
|
||||
'U' => 0x0055,
|
||||
'Uacute' => 0x00DA,
|
||||
'Ucircumflex' => 0x00DB,
|
||||
'Udieresis' => 0x00DC,
|
||||
'Ugrave' => 0x00D9,
|
||||
'Uhungarumlaut' => 0x0170,
|
||||
'Umacron' => 0x016A,
|
||||
'Uogonek' => 0x0172,
|
||||
'Uring' => 0x016E,
|
||||
'V' => 0x0056,
|
||||
'W' => 0x0057,
|
||||
'X' => 0x0058,
|
||||
'Y' => 0x0059,
|
||||
'Yacute' => 0x00DD,
|
||||
'Ydieresis' => 0x0178,
|
||||
'Z' => 0x005A,
|
||||
'Zacute' => 0x0179,
|
||||
'Zcaron' => 0x017D,
|
||||
'Zdotaccent' => 0x017B,
|
||||
'a' => 0x0061,
|
||||
'aacute' => 0x00E1,
|
||||
'abreve' => 0x0103,
|
||||
'acircumflex' => 0x00E2,
|
||||
'acute' => 0x00B4,
|
||||
'adieresis' => 0x00E4,
|
||||
'ae' => 0x00E6,
|
||||
'agrave' => 0x00E0,
|
||||
'amacron' => 0x0101,
|
||||
'ampersand' => 0x0026,
|
||||
'aogonek' => 0x0105,
|
||||
'aring' => 0x00E5,
|
||||
'asciicircum' => 0x005E,
|
||||
'asciitilde' => 0x007E,
|
||||
'asterisk' => 0x002A,
|
||||
'at' => 0x0040,
|
||||
'atilde' => 0x00E3,
|
||||
'b' => 0x0062,
|
||||
'backslash' => 0x005C,
|
||||
'bar' => 0x007C,
|
||||
'braceleft' => 0x007B,
|
||||
'braceright' => 0x007D,
|
||||
'bracketleft' => 0x005B,
|
||||
'bracketright' => 0x005D,
|
||||
'breve' => 0x02D8,
|
||||
'brokenbar' => 0x00A6,
|
||||
'bullet' => 0x2022,
|
||||
'c' => 0x0063,
|
||||
'cacute' => 0x0107,
|
||||
'caron' => 0x02C7,
|
||||
'ccaron' => 0x010D,
|
||||
'ccedilla' => 0x00E7,
|
||||
'cedilla' => 0x00B8,
|
||||
'cent' => 0x00A2,
|
||||
'circumflex' => 0x02C6,
|
||||
'colon' => 0x003A,
|
||||
'comma' => 0x002C,
|
||||
'commaaccent' => 0x0326,
|
||||
'copyright' => 0x00A9,
|
||||
'currency' => 0x00A4,
|
||||
'd' => 0x0064,
|
||||
'dagger' => 0x2020,
|
||||
'daggerdbl' => 0x2021,
|
||||
'dcaron' => 0x010F,
|
||||
'dcroat' => 0x0111,
|
||||
'degree' => 0x00B0,
|
||||
'dieresis' => 0x00A8,
|
||||
'divide' => 0x00F7,
|
||||
'dollar' => 0x0024,
|
||||
'dotaccent' => 0x02D9,
|
||||
'dotlessi' => 0x0131,
|
||||
'e' => 0x0065,
|
||||
'eacute' => 0x00E9,
|
||||
'ecaron' => 0x011B,
|
||||
'ecircumflex' => 0x00EA,
|
||||
'edieresis' => 0x00EB,
|
||||
'edotaccent' => 0x0117,
|
||||
'egrave' => 0x00E8,
|
||||
'eight' => 0x0038,
|
||||
'ellipsis' => 0x2026,
|
||||
'emacron' => 0x0113,
|
||||
'emdash' => 0x2014,
|
||||
'endash' => 0x2013,
|
||||
'eogonek' => 0x0119,
|
||||
'equal' => 0x003D,
|
||||
'eth' => 0x00F0,
|
||||
'exclam' => 0x0021,
|
||||
'exclamdown' => 0x00A1,
|
||||
'f' => 0x0066,
|
||||
'fi' => 0xFB01,
|
||||
'five' => 0x0035,
|
||||
'fl' => 0xFB02,
|
||||
'florin' => 0x0192,
|
||||
'four' => 0x0034,
|
||||
'fraction' => 0x2044,
|
||||
'g' => 0x0067,
|
||||
'gbreve' => 0x011F,
|
||||
'gcommaaccent' => 0x0123,
|
||||
'germandbls' => 0x00DF,
|
||||
'grave' => 0x0060,
|
||||
'greater' => 0x003E,
|
||||
'greaterequal' => 0x2265,
|
||||
'guillemotleft' => 0x00AB,
|
||||
'guillemotright' => 0x00BB,
|
||||
'guilsinglleft' => 0x2039,
|
||||
'guilsinglright' => 0x203A,
|
||||
'h' => 0x0068,
|
||||
'hungarumlaut' => 0x02DD,
|
||||
'hyphen' => 0x002D,
|
||||
'i' => 0x0069,
|
||||
'iacute' => 0x00ED,
|
||||
'icircumflex' => 0x00EE,
|
||||
'idieresis' => 0x00EF,
|
||||
'igrave' => 0x00EC,
|
||||
'imacron' => 0x012B,
|
||||
'iogonek' => 0x012F,
|
||||
'j' => 0x006A,
|
||||
'k' => 0x006B,
|
||||
'kcommaaccent' => 0x0137,
|
||||
'l' => 0x006C,
|
||||
'lacute' => 0x013A,
|
||||
'lcaron' => 0x013E,
|
||||
'lcommaaccent' => 0x013C,
|
||||
'less' => 0x003C,
|
||||
'lessequal' => 0x2264,
|
||||
'logicalnot' => 0x00AC,
|
||||
'lozenge' => 0x25CA,
|
||||
'lslash' => 0x0142,
|
||||
'm' => 0x006D,
|
||||
'macron' => 0x00AF,
|
||||
'minus' => 0x2212,
|
||||
'mu' => 0x00B5,
|
||||
'multiply' => 0x00D7,
|
||||
'n' => 0x006E,
|
||||
'nacute' => 0x0144,
|
||||
'ncaron' => 0x0148,
|
||||
'ncommaaccent' => 0x0146,
|
||||
'nine' => 0x0039,
|
||||
'notequal' => 0x2260,
|
||||
'ntilde' => 0x00F1,
|
||||
'numbersign' => 0x0023,
|
||||
'o' => 0x006F,
|
||||
'oacute' => 0x00F3,
|
||||
'ocircumflex' => 0x00F4,
|
||||
'odieresis' => 0x00F6,
|
||||
'oe' => 0x0153,
|
||||
'ogonek' => 0x02DB,
|
||||
'ograve' => 0x00F2,
|
||||
'ohungarumlaut' => 0x0151,
|
||||
'omacron' => 0x014D,
|
||||
'one' => 0x0031,
|
||||
'onehalf' => 0x00BD,
|
||||
'onequarter' => 0x00BC,
|
||||
'onesuperior' => 0x00B9,
|
||||
'ordfeminine' => 0x00AA,
|
||||
'ordmasculine' => 0x00BA,
|
||||
'oslash' => 0x00F8,
|
||||
'otilde' => 0x00F5,
|
||||
'p' => 0x0070,
|
||||
'paragraph' => 0x00B6,
|
||||
'parenleft' => 0x0028,
|
||||
'parenright' => 0x0029,
|
||||
'partialdiff' => 0x2202,
|
||||
'percent' => 0x0025,
|
||||
'period' => 0x002E,
|
||||
'periodcentered' => 0x00B7,
|
||||
'perthousand' => 0x2030,
|
||||
'plus' => 0x002B,
|
||||
'plusminus' => 0x00B1,
|
||||
'q' => 0x0071,
|
||||
'question' => 0x003F,
|
||||
'questiondown' => 0x00BF,
|
||||
'quotedbl' => 0x0022,
|
||||
'quotedblbase' => 0x201E,
|
||||
'quotedblleft' => 0x201C,
|
||||
'quotedblright' => 0x201D,
|
||||
'quoteleft' => 0x2018,
|
||||
'quoteright' => 0x2019,
|
||||
'quotesinglbase' => 0x201A,
|
||||
'quotesingle' => 0x0027,
|
||||
'r' => 0x0072,
|
||||
'racute' => 0x0155,
|
||||
'radical' => 0x221A,
|
||||
'rcaron' => 0x0159,
|
||||
'rcommaaccent' => 0x0157,
|
||||
'registered' => 0x00AE,
|
||||
'ring' => 0x02DA,
|
||||
's' => 0x0073,
|
||||
'sacute' => 0x015B,
|
||||
'scaron' => 0x0161,
|
||||
'scedilla' => 0x015F,
|
||||
'scommaaccent' => 0x0219,
|
||||
'section' => 0x00A7,
|
||||
'semicolon' => 0x003B,
|
||||
'seven' => 0x0037,
|
||||
'six' => 0x0036,
|
||||
'slash' => 0x002F,
|
||||
'space' => 0x0020,
|
||||
'sterling' => 0x00A3,
|
||||
'summation' => 0x2211,
|
||||
't' => 0x0074,
|
||||
'tcaron' => 0x0165,
|
||||
'tcommaaccent' => 0x0163,
|
||||
'thorn' => 0x00FE,
|
||||
'three' => 0x0033,
|
||||
'threequarters' => 0x00BE,
|
||||
'threesuperior' => 0x00B3,
|
||||
'tilde' => 0x02DC,
|
||||
'trademark' => 0x2122,
|
||||
'two' => 0x0032,
|
||||
'twosuperior' => 0x00B2,
|
||||
'u' => 0x0075,
|
||||
'uacute' => 0x00FA,
|
||||
'ucircumflex' => 0x00FB,
|
||||
'udieresis' => 0x00FC,
|
||||
'ugrave' => 0x00F9,
|
||||
'uhungarumlaut' => 0x0171,
|
||||
'umacron' => 0x016B,
|
||||
'underscore' => 0x005F,
|
||||
'uogonek' => 0x0173,
|
||||
'uring' => 0x016F,
|
||||
'v' => 0x0076,
|
||||
'w' => 0x0077,
|
||||
'x' => 0x0078,
|
||||
'y' => 0x0079,
|
||||
'yacute' => 0x00FD,
|
||||
'ydieresis' => 0x00FF,
|
||||
'yen' => 0x00A5,
|
||||
'z' => 0x007A,
|
||||
'zacute' => 0x017A,
|
||||
'zcaron' => 0x017E,
|
||||
'zdotaccent' => 0x017C,
|
||||
'zero' => 0x0030,
|
||||
];
|
||||
|
||||
/**
|
||||
* WinAnsi (cp1252) glyph-name → byte index (inverse of ENCMAP['cp1252']).
|
||||
* Built once on first use.
|
||||
*
|
||||
* @var array<string, int>|null
|
||||
*/
|
||||
private static ?array $winAnsiByName = null;
|
||||
|
||||
/**
|
||||
* Unicode-keyed widths accumulated during AFM parsing.
|
||||
*
|
||||
* @var array<int, int>
|
||||
*/
|
||||
private array $cwu = [];
|
||||
|
||||
/**
|
||||
* File helper used to load font definition files.
|
||||
*/
|
||||
protected ObjFile $fileHelper;
|
||||
|
||||
/**
|
||||
* @param string $font Content of the input font file
|
||||
* @param TFontData $fdt Extracted font metrics
|
||||
* @param ObjFile $fileHelper File helper for font loading.
|
||||
*
|
||||
* @throws FontException in case of error
|
||||
*/
|
||||
public function __construct(
|
||||
protected string $font,
|
||||
protected array $fdt,
|
||||
ObjFile $fileHelper,
|
||||
) {
|
||||
$this->fileHelper = $fileHelper;
|
||||
$this->process();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all the extracted font metrics
|
||||
*
|
||||
* @return TFontData
|
||||
*/
|
||||
public function getFontMetrics(): array
|
||||
{
|
||||
return $this->fdt;
|
||||
}
|
||||
|
||||
protected function setFlags(): void
|
||||
{
|
||||
if ($this->fdt['FontName'] === 'Symbol' || $this->fdt['FontName'] === 'ZapfDingbats') {
|
||||
$this->fdt['Flags'] |= 4;
|
||||
} else {
|
||||
$this->fdt['Flags'] |= 32;
|
||||
}
|
||||
|
||||
if ($this->fdt['IsFixedPitch']) {
|
||||
$this->fdt['Flags'] = (int) $this->fdt['Flags'] | 1;
|
||||
}
|
||||
|
||||
if ((int) $this->fdt['ItalicAngle'] !== 0) {
|
||||
$this->fdt['Flags'] = (int) $this->fdt['Flags'] | 64;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Set Char widths
|
||||
*
|
||||
* @param array<int, int> $cwidths Extracted widths
|
||||
*/
|
||||
protected function setCharWidths(array $cwidths): void
|
||||
{
|
||||
$this->fdt['MissingWidth'] = 600;
|
||||
if (isset($cwidths[32]) && $cwidths[32] !== 0) {
|
||||
$this->fdt['MissingWidth'] = $cwidths[32];
|
||||
}
|
||||
|
||||
$this->fdt['MaxWidth'] = (int) $this->fdt['MissingWidth'];
|
||||
$this->fdt['AvgWidth'] = 0;
|
||||
$this->fdt['cw'] = [];
|
||||
for ($cid = 0; $cid <= 255; ++$cid) {
|
||||
if (isset($cwidths[$cid])) {
|
||||
if ($cwidths[$cid] > $this->fdt['MaxWidth']) {
|
||||
$this->fdt['MaxWidth'] = $cwidths[$cid];
|
||||
}
|
||||
|
||||
$this->fdt['AvgWidth'] += $cwidths[$cid];
|
||||
$this->fdt['cw'][$cid] = $cwidths[$cid];
|
||||
} else {
|
||||
$this->fdt['cw'][$cid] = (int) $this->fdt['MissingWidth'];
|
||||
}
|
||||
}
|
||||
|
||||
$numWidths = \count($cwidths);
|
||||
$this->fdt['AvgWidth'] = $numWidths > 0 ? (int) \round($this->fdt['AvgWidth'] / $numWidths) : 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Build (once) the WinAnsi glyph-name → byte-index reverse map.
|
||||
*
|
||||
* @return array<string, int>
|
||||
*/
|
||||
private static function getWinAnsiByName(): array
|
||||
{
|
||||
if (self::$winAnsiByName === null) {
|
||||
self::$winAnsiByName = [];
|
||||
// Iterate high-to-low so the lowest byte wins for duplicate names
|
||||
// (e.g. 'space' appears at bytes 32 and 160 — we want 32).
|
||||
for ($cid = 255; $cid >= 0; --$cid) {
|
||||
$name = Encoding::MAP['cp1252'][$cid];
|
||||
if ($name !== '.notdef') {
|
||||
self::$winAnsiByName[$name] = $cid;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return self::$winAnsiByName;
|
||||
}
|
||||
|
||||
/**
|
||||
* Extract Metrics
|
||||
*/
|
||||
protected function extractMetrics(): void
|
||||
{
|
||||
$cwd = [];
|
||||
$this->cwu = [];
|
||||
$this->fdt['cbbox'] = [];
|
||||
$lines = \explode("\n", \str_replace("\r", '', $this->font));
|
||||
// process each row
|
||||
foreach ($lines as $line) {
|
||||
$col = \explode(' ', \rtrim($line));
|
||||
if (\count($col) > 1) {
|
||||
$this->processMetricRow($col, $cwd);
|
||||
}
|
||||
}
|
||||
|
||||
$this->fdt['Leading'] = 0;
|
||||
$this->fdt['cwu'] = $this->cwu;
|
||||
$this->setCharWidths($cwd);
|
||||
}
|
||||
|
||||
/**
|
||||
* Extract Metrics
|
||||
*
|
||||
* @param array<int, string> $col Array containing row elements to process
|
||||
* @param array<int, int> $cwd Array containing cid widths
|
||||
*
|
||||
* @SuppressWarnings("PHPMD.CyclomaticComplexity")
|
||||
*/
|
||||
protected function processMetricRow(array $col, array &$cwd): void
|
||||
{
|
||||
switch ($col[0]) {
|
||||
case 'IsFixedPitch':
|
||||
$this->fdt['IsFixedPitch'] = $col[1] === 'true';
|
||||
break;
|
||||
case 'FontBBox':
|
||||
$this->fdt['FontBBox'] = [(int) $col[1], (int) $col[2], (int) $col[3], (int) $col[4]];
|
||||
break;
|
||||
case 'C':
|
||||
$name = $col[7] ?? '';
|
||||
if ($name === '' || $name === '.notdef') {
|
||||
break;
|
||||
}
|
||||
|
||||
$width = (int) $col[4];
|
||||
// Map glyph name to the WinAnsi byte actually used in the PDF stream.
|
||||
$winAnsi = self::getWinAnsiByName();
|
||||
$winansiCid = $winAnsi[$name] ?? null;
|
||||
if ($winansiCid !== null) {
|
||||
$cwd[$winansiCid] = $width;
|
||||
if (isset($col[14]) && $col[14] !== '') {
|
||||
$this->fdt['cbbox'][$winansiCid] = [
|
||||
(int) $col[10],
|
||||
(int) $col[11],
|
||||
(int) $col[12],
|
||||
(int) $col[13],
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
// Also store under the Unicode codepoint for Stack::getCharWidth().
|
||||
$unicode = self::GLYPH_UNICODE[$name] ?? null;
|
||||
if ($unicode !== null) {
|
||||
$this->cwu[$unicode] = $width;
|
||||
}
|
||||
|
||||
break;
|
||||
case 'FontName':
|
||||
case 'FullName':
|
||||
case 'FamilyName':
|
||||
case 'Weight':
|
||||
case 'CharacterSet':
|
||||
case 'Version':
|
||||
case 'EncodingScheme':
|
||||
$this->fdt[$col[0]] = $col[1];
|
||||
break;
|
||||
case 'ItalicAngle':
|
||||
case 'UnderlinePosition':
|
||||
case 'UnderlineThickness':
|
||||
case 'CapHeight':
|
||||
case 'XHeight':
|
||||
case 'Ascender':
|
||||
case 'Descender':
|
||||
case 'StdHW':
|
||||
case 'StdVW':
|
||||
$this->fdt[$col[0]] = (int) $col[1];
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Map values to the correct key name
|
||||
*
|
||||
* @throws FontException
|
||||
*/
|
||||
protected function remapValues(): void
|
||||
{
|
||||
// rename properties
|
||||
$this->fdt['name'] = $this->fdt['FullName'];
|
||||
$this->fdt['underlinePosition'] = $this->fdt['UnderlinePosition'];
|
||||
$this->fdt['underlineThickness'] = $this->fdt['UnderlineThickness'];
|
||||
$this->fdt['italicAngle'] = $this->fdt['ItalicAngle'];
|
||||
$this->fdt['Ascent'] = $this->fdt['Ascender'];
|
||||
$this->fdt['Descent'] = $this->fdt['Descender'];
|
||||
$this->fdt['StemV'] = $this->fdt['StdVW'];
|
||||
$this->fdt['StemH'] = $this->fdt['StdHW'];
|
||||
|
||||
$name = \preg_replace('/[^a-zA-Z0-9_\-]/', '', $this->fdt['name']);
|
||||
if ($name === null) {
|
||||
throw new FontException('Invalid font name');
|
||||
}
|
||||
|
||||
$this->fdt['name'] = $name;
|
||||
$this->fdt['bbox'] = \implode(' ', $this->fdt['FontBBox']);
|
||||
}
|
||||
|
||||
protected function setMissingValues(): void
|
||||
{
|
||||
$this->fdt['Descender'] = $this->fdt['FontBBox'][1];
|
||||
|
||||
$this->fdt['Ascender'] = $this->fdt['FontBBox'][3];
|
||||
|
||||
if ($this->fdt['CapHeight'] === 0) {
|
||||
$this->fdt['CapHeight'] = $this->fdt['Ascender'];
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Process Core font
|
||||
*
|
||||
* @throws FontException
|
||||
*/
|
||||
protected function process(): void
|
||||
{
|
||||
$this->extractMetrics();
|
||||
$this->setFlags();
|
||||
$this->setMissingValues();
|
||||
$this->remapValues();
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,419 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
/**
|
||||
* TypeOne.php
|
||||
*
|
||||
* @since 2011-05-23
|
||||
* @category Library
|
||||
* @package PdfFont
|
||||
* @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-font
|
||||
*
|
||||
* This file is part of tc-lib-pdf-font software library.
|
||||
*/
|
||||
|
||||
namespace Com\Tecnick\Pdf\Font\Import;
|
||||
|
||||
use Com\Tecnick\File\Exception as FileException;
|
||||
use Com\Tecnick\Pdf\Font\Exception as FontException;
|
||||
use Com\Tecnick\Unicode\Data\Encoding;
|
||||
|
||||
/**
|
||||
* Com\Tecnick\Pdf\Font\Import\TypeOne
|
||||
*
|
||||
* @since 2011-05-23
|
||||
* @category Library
|
||||
* @package PdfFont
|
||||
* @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-font
|
||||
*
|
||||
* @SuppressWarnings("PHPMD.ExcessiveClassComplexity")
|
||||
*/
|
||||
class TypeOne extends \Com\Tecnick\Pdf\Font\Import\Core
|
||||
{
|
||||
/**
|
||||
* Store font data
|
||||
*
|
||||
* @throws FileException
|
||||
* @throws FontException
|
||||
*/
|
||||
protected function storeFontData(): void
|
||||
{
|
||||
// read first segment
|
||||
$dat = \unpack('Cmarker/Ctype/Vsize', \substr($this->font, 0, 6));
|
||||
if ($dat === false || $dat['marker'] !== 128) {
|
||||
throw new FontException('Font file is not a valid binary Type1');
|
||||
}
|
||||
|
||||
$this->fdt['size1'] = $dat['size'];
|
||||
$fontlen = \strlen($this->font);
|
||||
// the first segment plus the 6-byte header of the second segment must fit in the file
|
||||
if ((6 + $this->fdt['size1'] + 6) > $fontlen) {
|
||||
throw new FontException('Type1 font segment 1 length exceeds the file size');
|
||||
}
|
||||
|
||||
$data = \substr($this->font, 6, $this->fdt['size1']);
|
||||
// read second segment
|
||||
$dat = \unpack('Cmarker/Ctype/Vsize', \substr($this->font, 6 + $this->fdt['size1'], 6));
|
||||
if ($dat === false || $dat['marker'] !== 128) {
|
||||
throw new FontException('Font file is not a valid binary Type1');
|
||||
}
|
||||
|
||||
$this->fdt['size2'] = $dat['size'];
|
||||
if ((12 + $this->fdt['size1'] + $this->fdt['size2']) > $fontlen) {
|
||||
throw new FontException('Type1 font segment 2 length exceeds the file size');
|
||||
}
|
||||
|
||||
$this->fdt['encrypted'] = \substr($this->font, 12 + $this->fdt['size1'], $this->fdt['size2']);
|
||||
$data .= $this->fdt['encrypted'];
|
||||
// store compressed font
|
||||
$this->fdt['file'] = $this->fdt['file_name'] . '.z';
|
||||
$fpt = $this->fileHelper->fopenLocal($this->fdt['dir'] . $this->fdt['file'], 'wb');
|
||||
|
||||
$cmpr = \gzcompress($data);
|
||||
if ($cmpr === false) {
|
||||
throw new FontException('Unable to compress font data');
|
||||
}
|
||||
|
||||
\fwrite($fpt, $cmpr);
|
||||
\fclose($fpt);
|
||||
}
|
||||
|
||||
/**
|
||||
* Extract Font information
|
||||
*
|
||||
* @throws FontException
|
||||
*/
|
||||
protected function extractFontInfo(): void
|
||||
{
|
||||
$matches = [];
|
||||
if (
|
||||
\preg_match('#/FontName[\s]*+\/([^\s]*+)#', $this->font, $matches) !== 1
|
||||
&& \preg_match('#/FullName[\s]*+\(([^\)]*+)#', $this->font, $matches) !== 1
|
||||
) {
|
||||
throw new FontException('Unable to extract font name');
|
||||
}
|
||||
|
||||
$name = \preg_replace('/[^a-zA-Z0-9_\-]/', '', $matches[1]);
|
||||
if ($name === null) {
|
||||
throw new FontException('Unable to extract font name');
|
||||
}
|
||||
|
||||
$this->fdt['name'] = $name;
|
||||
|
||||
$bvl = [0, 0, 0, 0];
|
||||
if (\preg_match('#/FontBBox[\s]*+{([^}]*+)#', $this->font, $matches) === 1) {
|
||||
$rawbvl = \explode(' ', \trim($matches[1]));
|
||||
$bvl = [
|
||||
(int) $rawbvl[0],
|
||||
(int) ($rawbvl[1] ?? 0),
|
||||
(int) ($rawbvl[2] ?? 0),
|
||||
(int) ($rawbvl[3] ?? 0),
|
||||
];
|
||||
}
|
||||
|
||||
$this->fdt['bbox'] = \implode(' ', $bvl);
|
||||
$this->fdt['Ascent'] = $bvl[3];
|
||||
$this->fdt['Descent'] = $bvl[1];
|
||||
|
||||
$this->fdt['italicAngle'] = \preg_match('#/ItalicAngle[\s]*+([0-9\+\-]*+)#', $this->font, $matches) === 1
|
||||
? (int) $matches[1]
|
||||
: 0;
|
||||
|
||||
if ($this->fdt['italicAngle'] !== 0) {
|
||||
$this->fdt['Flags'] |= 64;
|
||||
}
|
||||
|
||||
$this->fdt['underlinePosition'] = \preg_match('#/UnderlinePosition[\s]*+([0-9\+\-]*+)#', $this->font, $matches)
|
||||
=== 1
|
||||
? (int) $matches[1]
|
||||
: 0;
|
||||
$this->fdt['underlineThickness'] = \preg_match(
|
||||
'#/UnderlineThickness[\s]*+([0-9\+\-]*+)#',
|
||||
$this->font,
|
||||
$matches,
|
||||
) === 1
|
||||
? (int) $matches[1]
|
||||
: 0;
|
||||
|
||||
if (\preg_match('#/isFixedPitch[\s]*+([^\s]*+)#', $this->font, $matches) === 1 && $matches[1] === 'true') {
|
||||
$this->fdt['Flags'] = (int) $this->fdt['Flags'] | 1;
|
||||
}
|
||||
|
||||
$this->fdt['weight'] = 'Book';
|
||||
if (\preg_match('#/Weight[\s]*+\(([^\)]*+)#', $this->font, $matches) === 1 && $matches[1] !== '') {
|
||||
$this->fdt['weight'] = \strtolower($matches[1]);
|
||||
}
|
||||
|
||||
$this->fdt['Leading'] = 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Extract Font information
|
||||
*
|
||||
* @return array<string, int>
|
||||
*/
|
||||
protected function getInternalMap(): array
|
||||
{
|
||||
$imap = [];
|
||||
$fmap = [];
|
||||
$matches = \preg_match_all('#dup[\s]([0-9]+)[\s]*+/([^\s]*+)[\s]put#sU', $this->font, $fmap, PREG_SET_ORDER);
|
||||
if ($matches !== false && $matches >= 1) {
|
||||
foreach ($fmap as $val) {
|
||||
$imap[$val[2]] = (int) $val[1];
|
||||
}
|
||||
}
|
||||
|
||||
return $imap;
|
||||
}
|
||||
|
||||
/**
|
||||
* Decrypt eexec encrypted part
|
||||
*/
|
||||
protected function getEplain(): string
|
||||
{
|
||||
$csr = 55_665; // eexec encryption constant
|
||||
$cc1 = 52_845;
|
||||
$cc2 = 22_719;
|
||||
$elen = \strlen($this->fdt['encrypted']);
|
||||
$eplain = '';
|
||||
for ($idx = 0; $idx < $elen; ++$idx) {
|
||||
$chr = \ord($this->fdt['encrypted'][$idx]);
|
||||
$eplain .= \chr($chr ^ ($csr >> 8));
|
||||
$csr = ((($chr + $csr) * $cc1) + $cc2) % 65_536;
|
||||
}
|
||||
|
||||
return $eplain;
|
||||
}
|
||||
|
||||
/**
|
||||
* Extract eexec info
|
||||
*
|
||||
* @return array<int, array<int, string>>
|
||||
*/
|
||||
protected function extractEplainInfo(): array
|
||||
{
|
||||
$eplain = $this->getEplain();
|
||||
$matches = [];
|
||||
if (\preg_match('#/ForceBold[\s]*+([^\s]*+)#', $eplain, $matches) === 1 && $matches[1] === 'true') {
|
||||
$this->fdt['Flags'] |= 0x4_0000;
|
||||
}
|
||||
|
||||
$this->extractStem($eplain);
|
||||
if (\preg_match('#/BlueValues[\s]*+\[([^\]]*+)#', $eplain, $matches) === 1) {
|
||||
$bvl = \explode(' ', $matches[1]);
|
||||
if (\count($bvl) >= 6) {
|
||||
$vl1 = (int) $bvl[2];
|
||||
$vl2 = (int) $bvl[4];
|
||||
$this->fdt['XHeight'] = \min($vl1, $vl2);
|
||||
$this->fdt['CapHeight'] = \max($vl1, $vl2);
|
||||
}
|
||||
}
|
||||
|
||||
$this->getRandomBytes($eplain);
|
||||
return $this->getCharstringData($eplain);
|
||||
}
|
||||
|
||||
/**
|
||||
* Extract eexec info
|
||||
*
|
||||
* @param string $eplain Decoded eexec encrypted part
|
||||
*/
|
||||
protected function extractStem(string $eplain): void
|
||||
{
|
||||
$matches = [];
|
||||
if (\preg_match('#/StdVW[\s]*+\[([^\]]*+)#', $eplain, $matches) === 1) {
|
||||
$this->fdt['StemV'] = (int) $matches[1];
|
||||
} elseif ($this->fdt['weight'] === 'bold' || $this->fdt['weight'] === 'black') {
|
||||
$this->fdt['StemV'] = 123;
|
||||
} else {
|
||||
$this->fdt['StemV'] = 70;
|
||||
}
|
||||
|
||||
$this->fdt['StemH'] = \preg_match('#/StdHW[\s]*+\[([^\]]*+)#', $eplain, $matches) === 1
|
||||
? (int) $matches[1]
|
||||
: 30;
|
||||
|
||||
if (\preg_match('#/Cap[X]?Height[\s]*+\[([^\]]*+)#', $eplain, $matches) === 1) {
|
||||
$this->fdt['CapHeight'] = (int) $matches[1];
|
||||
} else {
|
||||
$this->fdt['CapHeight'] = (int) $this->fdt['Ascent'];
|
||||
}
|
||||
|
||||
$this->fdt['XHeight'] = (int) $this->fdt['Ascent'] + (int) $this->fdt['Descent'];
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the number of random bytes at the beginning of charstrings
|
||||
*/
|
||||
protected function getRandomBytes(string $eplain): void
|
||||
{
|
||||
$this->fdt['lenIV'] = 4;
|
||||
$matches = [];
|
||||
if (\preg_match('#/lenIV[\s]*+([\d]*+)#', $eplain, $matches) === 1) {
|
||||
$this->fdt['lenIV'] = (int) $matches[1];
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<int, array<int, string>>
|
||||
*/
|
||||
protected function getCharstringData(string $eplain): array
|
||||
{
|
||||
$this->fdt['enc_map'] = [];
|
||||
$charstringsPos = \strpos($eplain, '/CharStrings');
|
||||
if ($charstringsPos === false) {
|
||||
return [];
|
||||
}
|
||||
|
||||
$eplain = \substr($eplain, $charstringsPos + 1);
|
||||
$matches = [];
|
||||
\preg_match_all('#/([A-Za-z0-9\.]*+)[\s][0-9]+[\s]RD[\s](.*)[\s]ND#sU', $eplain, $matches, PREG_SET_ORDER);
|
||||
/** @var array<int, array<int, string>> $matches */
|
||||
if ($this->fdt['enc'] === '') {
|
||||
return $matches;
|
||||
}
|
||||
|
||||
if (!isset(Encoding::MAP[$this->fdt['enc']])) {
|
||||
return $matches;
|
||||
}
|
||||
|
||||
$this->fdt['enc_map'] = Encoding::MAP[$this->fdt['enc']];
|
||||
return $matches;
|
||||
}
|
||||
|
||||
/**
|
||||
* get CID
|
||||
*
|
||||
* @param array<string, int> $imap
|
||||
* @param array<int, string> $val
|
||||
*/
|
||||
protected function getCid(array $imap, array $val): int
|
||||
{
|
||||
if (isset($imap[$val[1]])) {
|
||||
return $imap[$val[1]];
|
||||
}
|
||||
|
||||
$cid = \array_search($val[1], $this->fdt['enc_map'], true);
|
||||
|
||||
if ($cid === false) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
if ($cid > 1000) {
|
||||
return 1000;
|
||||
}
|
||||
|
||||
return (int) $cid;
|
||||
}
|
||||
|
||||
/**
|
||||
* Decode number
|
||||
*
|
||||
* @param array<int, int> $ccom
|
||||
* @param array<int, int> $cdec
|
||||
* @param array<int, int> $cwidths
|
||||
*
|
||||
* @throws FontException
|
||||
*/
|
||||
protected function decodeNumber(int $idx, int &$cck, int &$cid, array &$ccom, array &$cdec, array &$cwidths): int
|
||||
{
|
||||
if ($ccom[$idx] === 255) {
|
||||
if (!isset($ccom[$idx + 4])) {
|
||||
throw new FontException('Truncated Type1 charstring number operand');
|
||||
}
|
||||
|
||||
$sval = \chr($ccom[$idx + 1]) . \chr($ccom[$idx + 2]) . \chr($ccom[$idx + 3]) . \chr($ccom[$idx + 4]);
|
||||
$vsval = \unpack('li', $sval);
|
||||
if ($vsval === false) {
|
||||
throw new FontException('Unable to unpack number');
|
||||
}
|
||||
|
||||
$cdec[$cck] = (int) $vsval['i'];
|
||||
return $idx + 5;
|
||||
}
|
||||
|
||||
if ($ccom[$idx] >= 251) {
|
||||
if (!isset($ccom[$idx + 1])) {
|
||||
throw new FontException('Truncated Type1 charstring number operand');
|
||||
}
|
||||
|
||||
$cdec[$cck] = (-($ccom[$idx] - 251) * 256) - $ccom[$idx + 1] - 108;
|
||||
return $idx + 2;
|
||||
}
|
||||
|
||||
if ($ccom[$idx] >= 247) {
|
||||
if (!isset($ccom[$idx + 1])) {
|
||||
throw new FontException('Truncated Type1 charstring number operand');
|
||||
}
|
||||
|
||||
$cdec[$cck] = (($ccom[$idx] - 247) * 256) + $ccom[$idx + 1] + 108;
|
||||
return $idx + 2;
|
||||
}
|
||||
|
||||
if ($ccom[$idx] >= 32) {
|
||||
$cdec[$cck] = $ccom[$idx] - 139;
|
||||
return ++$idx;
|
||||
}
|
||||
|
||||
$cdec[$cck] = $ccom[$idx];
|
||||
if ($cck <= 0) {
|
||||
return ++$idx;
|
||||
}
|
||||
|
||||
if ($cdec[$cck] !== 13) {
|
||||
return ++$idx;
|
||||
}
|
||||
|
||||
// hsbw command: update width
|
||||
$cwidths[$cid] = $cdec[$cck - 1];
|
||||
return ++$idx;
|
||||
}
|
||||
|
||||
/**
|
||||
* Process Type1 font
|
||||
*
|
||||
* @throws FileException
|
||||
* @throws FontException
|
||||
*/
|
||||
protected function process(): void
|
||||
{
|
||||
$this->storeFontData();
|
||||
$this->extractFontInfo();
|
||||
$imap = $this->getInternalMap();
|
||||
$matches = $this->extractEplainInfo();
|
||||
$cwidths = [];
|
||||
$cc1 = 52_845;
|
||||
$cc2 = 22_719;
|
||||
foreach ($matches as $match) {
|
||||
$cid = $this->getCid($imap, $match);
|
||||
// decrypt charstring encrypted part
|
||||
$csr = 4330; // charstring encryption constant
|
||||
$ccd = $match[2];
|
||||
$clen = \strlen($ccd);
|
||||
$ccom = [];
|
||||
for ($idx = 0; $idx < $clen; ++$idx) {
|
||||
$chr = \ord($ccd[$idx]);
|
||||
$ccom[] = $chr ^ ($csr >> 8);
|
||||
$csr = ((($chr + $csr) * $cc1) + $cc2) % 65_536;
|
||||
}
|
||||
|
||||
// decode numbers
|
||||
$cdec = [];
|
||||
$cck = 0;
|
||||
$idx = $this->fdt['lenIV'];
|
||||
while ($idx < $clen) {
|
||||
$idx = $this->decodeNumber($idx, $cck, $cid, $ccom, $cdec, $cwidths);
|
||||
++$cck;
|
||||
}
|
||||
}
|
||||
|
||||
$this->setCharWidths($cwidths);
|
||||
}
|
||||
}
|
||||
+558
@@ -0,0 +1,558 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
/**
|
||||
* Load.php
|
||||
*
|
||||
* @since 2011-05-23
|
||||
* @category Library
|
||||
* @package PdfFont
|
||||
* @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-font
|
||||
*
|
||||
* This file is part of tc-lib-pdf-font software library.
|
||||
*/
|
||||
|
||||
namespace Com\Tecnick\Pdf\Font;
|
||||
|
||||
use Com\Tecnick\File\Dir;
|
||||
use Com\Tecnick\File\File as ObjFile;
|
||||
use Com\Tecnick\Pdf\Font\Exception as FontException;
|
||||
|
||||
/**
|
||||
* Com\Tecnick\Pdf\Font\Load
|
||||
*
|
||||
* @since 2011-05-23
|
||||
* @category Library
|
||||
* @package PdfFont
|
||||
* @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-font
|
||||
*
|
||||
* @phpstan-type TFontDataCidInfo array{
|
||||
* 'Ordering': string,
|
||||
* 'Registry': string,
|
||||
* 'Supplement': int,
|
||||
* 'uni2cid': array<int, int>,
|
||||
* }
|
||||
*
|
||||
* @phpstan-type TFontDataDesc array{
|
||||
* 'Ascent': int,
|
||||
* 'AvgWidth': int,
|
||||
* 'CapHeight': int,
|
||||
* 'Descent': int,
|
||||
* 'Flags': int,
|
||||
* 'FontBBox': string,
|
||||
* 'ItalicAngle': int,
|
||||
* 'Leading': int,
|
||||
* 'MaxWidth': int,
|
||||
* 'MissingWidth': int,
|
||||
* 'StemH': int,
|
||||
* 'StemV': int,
|
||||
* 'XHeight': int,
|
||||
* }
|
||||
*
|
||||
* @phpstan-type TFontDataEncTable array{
|
||||
* 'encodingID': int,
|
||||
* 'offset': int,
|
||||
* 'platformID': int,
|
||||
* }
|
||||
*
|
||||
* @phpstan-type TFontDataMode array{
|
||||
* 'bold': bool,
|
||||
* 'italic': bool,
|
||||
* 'linethrough': bool,
|
||||
* 'overline': bool,
|
||||
* 'underline': bool,
|
||||
* }
|
||||
*
|
||||
* @phpstan-type TFontDataTableItem array{
|
||||
* 'checkSum': int,
|
||||
* 'data': string,
|
||||
* 'length': int,
|
||||
* 'offset': int,
|
||||
* }
|
||||
*
|
||||
* @phpstan-type TFontData array{
|
||||
* 'Ascender': int,
|
||||
* 'Ascent': int,
|
||||
* 'AvgWidth': float,
|
||||
* 'CapHeight': int,
|
||||
* 'CharacterSet': string,
|
||||
* 'Descender': int,
|
||||
* 'Descent': int,
|
||||
* 'EncodingScheme': string,
|
||||
* 'FamilyName': string,
|
||||
* 'Flags': int,
|
||||
* 'FontBBox': array<int>,
|
||||
* 'FontName': string,
|
||||
* 'FullName': string,
|
||||
* 'IsFixedPitch': bool,
|
||||
* 'ItalicAngle': int,
|
||||
* 'Leading': int,
|
||||
* 'MaxWidth': int,
|
||||
* 'MissingWidth': int|null,
|
||||
* 'StdHW': int,
|
||||
* 'StdVW': int,
|
||||
* 'StemH': int,
|
||||
* 'StemV': int,
|
||||
* 'UnderlinePosition': int,
|
||||
* 'UnderlineThickness': int,
|
||||
* 'Version': string,
|
||||
* 'Weight': string,
|
||||
* 'XHeight': int,
|
||||
* 'bbox': string,
|
||||
* 'cbbox': array<int, array<int, int>>,
|
||||
* 'cidinfo': TFontDataCidInfo,
|
||||
* 'compress': bool,
|
||||
* 'ctg': string,
|
||||
* 'ctgdata': array<int, int>,
|
||||
* 'cw': array<int, int>,
|
||||
* 'cwu': array<int, int>,
|
||||
* 'datafile': string,
|
||||
* 'desc': TFontDataDesc,
|
||||
* 'diff': string,
|
||||
* 'diff_n': int,
|
||||
* 'diffid'?: int,
|
||||
* 'dir': string,
|
||||
* 'dw': int,
|
||||
* 'enc': string,
|
||||
* 'enc_map': array<int, string>,
|
||||
* 'encodingTables': array<int, TFontDataEncTable>,
|
||||
* 'encoding_id': int,
|
||||
* 'encrypted': string,
|
||||
* 'fakestyle': bool,
|
||||
* 'family': string,
|
||||
* 'file': string,
|
||||
* 'file_n': int,
|
||||
* 'file_name': string,
|
||||
* 'i': int,
|
||||
* 'ifile': string,
|
||||
* 'indexToLoc': array<int, int>,
|
||||
* 'input_file': string,
|
||||
* 'isUnicode': bool,
|
||||
* 'italicAngle': float,
|
||||
* 'key': string,
|
||||
* 'lenIV': int,
|
||||
* 'length1': int,
|
||||
* 'length2': int,
|
||||
* 'linked': bool,
|
||||
* 'mode': TFontDataMode,
|
||||
* 'n': int,
|
||||
* 'name': string,
|
||||
* 'numGlyphs': int,
|
||||
* 'numHMetrics': int,
|
||||
* 'originalsize': int,
|
||||
* 'pdfa': bool,
|
||||
* 'platform_id': int,
|
||||
* 'settype': string,
|
||||
* 'short_offset': bool,
|
||||
* 'size1': int,
|
||||
* 'size2': int,
|
||||
* 'style': string,
|
||||
* 'subset': bool,
|
||||
* 'subsetchars': array<int, bool>,
|
||||
* 'table': array<string, TFontDataTableItem>,
|
||||
* 'tot_num_glyphs': int,
|
||||
* 'type': string,
|
||||
* 'underlinePosition': int,
|
||||
* 'underlineThickness': int,
|
||||
* 'unicode': bool,
|
||||
* 'unitsPerEm': int,
|
||||
* 'up': int,
|
||||
* 'urk': float,
|
||||
* 'ut': int,
|
||||
* 'weight': string,
|
||||
* }
|
||||
*/
|
||||
abstract class Load
|
||||
{
|
||||
/**
|
||||
* File helper used to load font definition files.
|
||||
*/
|
||||
protected ObjFile $fileHelper;
|
||||
|
||||
/**
|
||||
* True when the file helper is created internally by this class.
|
||||
*/
|
||||
protected bool $ownsFileHelper = false;
|
||||
|
||||
/**
|
||||
* Valid Font types
|
||||
*
|
||||
* @var array<string, bool> Font types
|
||||
*/
|
||||
protected const FONTTYPES = [
|
||||
'Core' => true,
|
||||
'TrueType' => true,
|
||||
'TrueTypeUnicode' => true,
|
||||
'Type1' => true,
|
||||
'cidfont0' => true,
|
||||
];
|
||||
|
||||
/**
|
||||
* Font data
|
||||
*
|
||||
* @var TFontData
|
||||
*/
|
||||
protected array $data = [
|
||||
'Ascender' => 0,
|
||||
'Ascent' => 0,
|
||||
'AvgWidth' => 0.0,
|
||||
'CapHeight' => 0,
|
||||
'CharacterSet' => '',
|
||||
'Descender' => 0,
|
||||
'Descent' => 0,
|
||||
'EncodingScheme' => '',
|
||||
'FamilyName' => '',
|
||||
'Flags' => 0,
|
||||
'FontBBox' => [],
|
||||
'FontName' => '',
|
||||
'FullName' => '',
|
||||
'IsFixedPitch' => false,
|
||||
'ItalicAngle' => 0,
|
||||
'Leading' => 0,
|
||||
'MaxWidth' => 0,
|
||||
'MissingWidth' => 0,
|
||||
'StdHW' => 0,
|
||||
'StdVW' => 0,
|
||||
'StemH' => 0,
|
||||
'StemV' => 0,
|
||||
'UnderlinePosition' => 0,
|
||||
'UnderlineThickness' => 0,
|
||||
'Version' => '',
|
||||
'Weight' => '',
|
||||
'XHeight' => 0,
|
||||
'bbox' => '',
|
||||
'cbbox' => [],
|
||||
'cidinfo' => [
|
||||
'Ordering' => '',
|
||||
'Registry' => '',
|
||||
'Supplement' => 0,
|
||||
'uni2cid' => [],
|
||||
],
|
||||
'compress' => false,
|
||||
'ctg' => '',
|
||||
'ctgdata' => [],
|
||||
'cw' => [],
|
||||
'cwu' => [],
|
||||
'datafile' => '',
|
||||
'desc' => [
|
||||
'Ascent' => 0,
|
||||
'AvgWidth' => 0,
|
||||
'CapHeight' => 0,
|
||||
'Descent' => 0,
|
||||
'Flags' => 0,
|
||||
'FontBBox' => '',
|
||||
'ItalicAngle' => 0,
|
||||
'Leading' => 0,
|
||||
'MaxWidth' => 0,
|
||||
'MissingWidth' => 0,
|
||||
'StemH' => 0,
|
||||
'StemV' => 0,
|
||||
'XHeight' => 0,
|
||||
],
|
||||
'diff' => '',
|
||||
'diff_n' => 0,
|
||||
'dir' => '',
|
||||
'dw' => 0,
|
||||
'enc' => '',
|
||||
'enc_map' => [],
|
||||
'encodingTables' => [],
|
||||
'encoding_id' => 0,
|
||||
'encrypted' => '',
|
||||
'fakestyle' => false,
|
||||
'family' => '',
|
||||
'file' => '',
|
||||
'file_n' => 0,
|
||||
'file_name' => '',
|
||||
'i' => 0,
|
||||
'ifile' => '',
|
||||
'indexToLoc' => [],
|
||||
'input_file' => '',
|
||||
'isUnicode' => false,
|
||||
'italicAngle' => 0,
|
||||
'key' => '',
|
||||
'lenIV' => 0,
|
||||
'length1' => 0,
|
||||
'length2' => 0,
|
||||
'linked' => false,
|
||||
'mode' => [
|
||||
'bold' => false,
|
||||
'italic' => false,
|
||||
'linethrough' => false,
|
||||
'overline' => false,
|
||||
'underline' => false,
|
||||
],
|
||||
'n' => 0,
|
||||
'name' => '',
|
||||
'numGlyphs' => 0,
|
||||
'numHMetrics' => 0,
|
||||
'originalsize' => 0,
|
||||
'pdfa' => false,
|
||||
'platform_id' => 0,
|
||||
'settype' => '',
|
||||
'short_offset' => false,
|
||||
'size1' => 0,
|
||||
'size2' => 0,
|
||||
'style' => '',
|
||||
'subset' => false,
|
||||
'subsetchars' => [],
|
||||
'table' => [],
|
||||
'tot_num_glyphs' => 0,
|
||||
'type' => '',
|
||||
'underlinePosition' => 0,
|
||||
'underlineThickness' => 0,
|
||||
'unicode' => false,
|
||||
'unitsPerEm' => 0,
|
||||
'up' => 0,
|
||||
'urk' => 0.0,
|
||||
'ut' => 0,
|
||||
'weight' => '',
|
||||
];
|
||||
|
||||
/**
|
||||
* @param ObjFile|null $fileHelper Optional file helper for font loading.
|
||||
*/
|
||||
public function __construct(?ObjFile $fileHelper = null)
|
||||
{
|
||||
$this->ownsFileHelper = $fileHelper === null;
|
||||
$this->fileHelper = $fileHelper ?? new ObjFile(allowedPaths: $this->buildAllowedPaths());
|
||||
}
|
||||
|
||||
/**
|
||||
* Load the font data
|
||||
*
|
||||
* @throws FontException in case of error
|
||||
*/
|
||||
public function load(): void
|
||||
{
|
||||
$this->getFontInfo();
|
||||
$this->checkType();
|
||||
$this->setName();
|
||||
$this->setDefaultWidth();
|
||||
if ($this->data['fakestyle']) {
|
||||
$this->setArtificialStyles();
|
||||
}
|
||||
|
||||
$this->setFileData();
|
||||
}
|
||||
|
||||
/**
|
||||
* Load the font data
|
||||
*
|
||||
* @throws FontException in case of error
|
||||
*
|
||||
* @SuppressWarnings("PHPMD.CyclomaticComplexity")
|
||||
*/
|
||||
protected function getFontInfo(): void
|
||||
{
|
||||
$this->findFontFile();
|
||||
|
||||
if ($this->ownsFileHelper) {
|
||||
$this->fileHelper->setAllowedPaths($this->buildAllowedPaths());
|
||||
}
|
||||
|
||||
// read the font definition file
|
||||
$fdt = $this->fileHelper->getFileData($this->data['ifile']);
|
||||
if ($fdt === false) {
|
||||
throw new FontException('unable to read file: ' . $this->data['ifile']);
|
||||
}
|
||||
|
||||
/** @var array<string, mixed>|null $fdtdata */
|
||||
$fdtdata = \json_decode($fdt, true, 5, JSON_OBJECT_AS_ARRAY);
|
||||
if ($fdtdata === null) {
|
||||
throw new FontException('JSON decoding error [' . \json_last_error() . ']');
|
||||
}
|
||||
|
||||
if (!isset($fdtdata['type'])) {
|
||||
throw new FontException('The font definition file has a bad format: ' . $this->data['ifile']);
|
||||
}
|
||||
|
||||
$merged = \array_replace_recursive($this->data, $fdtdata);
|
||||
/** @var TFontData $merged */
|
||||
$this->data = $merged;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a list of font directories
|
||||
*
|
||||
* @return array<string> Font directories
|
||||
*/
|
||||
protected function findFontDirectories(): array
|
||||
{
|
||||
$dir = new Dir();
|
||||
$dirs = [];
|
||||
if (\defined('K_PATH_FONTS')) {
|
||||
$kpathfonts = (string) \constant('K_PATH_FONTS');
|
||||
if ($kpathfonts !== '') {
|
||||
$dirs[] = $kpathfonts;
|
||||
$glb = \glob($kpathfonts . DIRECTORY_SEPARATOR . '*', GLOB_ONLYDIR);
|
||||
if ($glb !== false) {
|
||||
$dirs = [...$dirs, ...$glb];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
$parent_font_dir = $dir->findParentDir('fonts', __DIR__);
|
||||
if ($parent_font_dir !== '' && $parent_font_dir !== '/') {
|
||||
$dirs[] = $parent_font_dir;
|
||||
$glb = \glob($parent_font_dir . DIRECTORY_SEPARATOR . '*', GLOB_ONLYDIR);
|
||||
if ($glb !== false) {
|
||||
$dirs = \array_merge($dirs, $glb);
|
||||
}
|
||||
}
|
||||
|
||||
return \array_unique($dirs);
|
||||
}
|
||||
|
||||
/**
|
||||
* Build trusted roots for local font definition loading.
|
||||
*
|
||||
* @return array<string>
|
||||
*/
|
||||
protected function buildAllowedPaths(): array
|
||||
{
|
||||
return FontPaths::buildAllowedPaths();
|
||||
}
|
||||
|
||||
/**
|
||||
* Load the font data
|
||||
*
|
||||
* @throws FontException in case of error
|
||||
*/
|
||||
protected function findFontFile(): void
|
||||
{
|
||||
if ($this->data['ifile'] !== '') {
|
||||
$this->data['dir'] = \dirname($this->data['ifile']);
|
||||
return;
|
||||
}
|
||||
|
||||
$this->data['ifile'] = \strtolower($this->data['key']) . '.json';
|
||||
|
||||
// find font definition file names
|
||||
$files = \array_unique([
|
||||
\strtolower($this->data['key']) . '.json',
|
||||
\strtolower($this->data['family']) . '.json',
|
||||
]);
|
||||
|
||||
// directories where to search for the font definition file
|
||||
$dirs = $this->findFontDirectories();
|
||||
|
||||
foreach ($files as $file) {
|
||||
foreach ($dirs as $dir) {
|
||||
if (!\is_readable($dir . DIRECTORY_SEPARATOR . $file)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$this->data['ifile'] = $dir . DIRECTORY_SEPARATOR . $file;
|
||||
$this->data['dir'] = $dir;
|
||||
break 2;
|
||||
}
|
||||
|
||||
// we have not found the version with style variations
|
||||
$this->data['fakestyle'] = true;
|
||||
}
|
||||
}
|
||||
|
||||
protected function setDefaultWidth(): void
|
||||
{
|
||||
if ($this->data['dw'] !== 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
if ($this->data['desc']['MissingWidth'] > 0) {
|
||||
$this->data['dw'] = $this->data['desc']['MissingWidth'];
|
||||
} elseif (isset($this->data['cw'][32]) && $this->data['cw'][32] !== 0) {
|
||||
$this->data['dw'] = $this->data['cw'][32];
|
||||
} else {
|
||||
$this->data['dw'] = 600;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Check Font Type
|
||||
*
|
||||
* @throws FontException on unknown font type
|
||||
*/
|
||||
protected function checkType(): void
|
||||
{
|
||||
if (isset(self::FONTTYPES[$this->data['type']])) {
|
||||
return;
|
||||
}
|
||||
|
||||
throw new FontException('Unknown font type: ' . $this->data['type']);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return void
|
||||
*
|
||||
* @throws FontException on using a CID0 font in a pdfa
|
||||
*/
|
||||
protected function setName(): void
|
||||
{
|
||||
if ($this->data['type'] === 'Core') {
|
||||
$this->data['name'] = Core::FONT[$this->data['key']] ?? $this->data['key'];
|
||||
$this->data['subset'] = false;
|
||||
} elseif ($this->data['type'] === 'Type1' || $this->data['type'] === 'TrueType') {
|
||||
$this->data['subset'] = false;
|
||||
} elseif ($this->data['type'] === 'TrueTypeUnicode') {
|
||||
$this->data['enc'] = 'Identity-H';
|
||||
} elseif ($this->data['type'] === 'cidfont0' && $this->data['pdfa']) {
|
||||
throw new FontException('CID0 fonts are not supported, all fonts must be embedded in PDF/A mode!');
|
||||
}
|
||||
|
||||
if ($this->data['name'] === '') {
|
||||
$this->data['name'] = $this->data['key'];
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Set artificial styles if the font variation file is missing
|
||||
*/
|
||||
protected function setArtificialStyles(): void
|
||||
{
|
||||
// artificial bold
|
||||
if ($this->data['mode']['bold']) {
|
||||
$this->data['name'] .= 'Bold';
|
||||
$this->data['desc']['StemV'] = $this->data['desc']['StemV'] === 0
|
||||
? 123
|
||||
: (int) \round($this->data['desc']['StemV'] * 1.75);
|
||||
}
|
||||
|
||||
// artificial italic
|
||||
if ($this->data['mode']['italic']) {
|
||||
$this->data['name'] .= 'Italic';
|
||||
if ($this->data['desc']['ItalicAngle'] !== 0) {
|
||||
$this->data['desc']['ItalicAngle'] -= 11;
|
||||
} else {
|
||||
$this->data['desc']['ItalicAngle'] = -11;
|
||||
}
|
||||
|
||||
if ($this->data['desc']['Flags'] !== 0) {
|
||||
$this->data['desc']['Flags'] |= 64; //bit 7
|
||||
} else {
|
||||
$this->data['desc']['Flags'] = 64;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public function setFileData(): void
|
||||
{
|
||||
if ($this->data['file'] === '') {
|
||||
return;
|
||||
}
|
||||
|
||||
if (\str_contains($this->data['type'], 'TrueType')) {
|
||||
$this->data['length1'] = $this->data['originalsize'];
|
||||
$this->data['length2'] = 0;
|
||||
} elseif ($this->data['type'] !== 'Core') {
|
||||
$this->data['length1'] = $this->data['size1'];
|
||||
$this->data['length2'] = $this->data['size2'];
|
||||
}
|
||||
}
|
||||
}
|
||||
+467
@@ -0,0 +1,467 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
/**
|
||||
* OutFont.php
|
||||
*
|
||||
* @since 2011-05-23
|
||||
* @category Library
|
||||
* @package PdfFont
|
||||
* @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-font
|
||||
*
|
||||
* This file is part of tc-lib-pdf-font software library.
|
||||
*/
|
||||
|
||||
namespace Com\Tecnick\Pdf\Font;
|
||||
|
||||
use Com\Tecnick\File\File as ObjFile;
|
||||
use Com\Tecnick\Pdf\Encrypt\Encrypt;
|
||||
use Com\Tecnick\Pdf\Encrypt\Exception as EncException;
|
||||
use Com\Tecnick\Pdf\Font\Exception as FontException;
|
||||
use Com\Tecnick\Unicode\Data\Identity;
|
||||
|
||||
/**
|
||||
* Com\Tecnick\Pdf\Font\OutFont
|
||||
*
|
||||
* @since 2011-05-23
|
||||
* @category Library
|
||||
* @package PdfFont
|
||||
* @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-font
|
||||
*
|
||||
* @phpstan-import-type TFontData from Load
|
||||
* @phpstan-import-type TFontDataCidInfo from Load
|
||||
* @phpstan-import-type TFontDataDesc from Load
|
||||
*/
|
||||
abstract class OutFont extends \Com\Tecnick\Pdf\Font\OutUtil
|
||||
{
|
||||
/**
|
||||
* Current PDF object number
|
||||
*/
|
||||
protected int $pon;
|
||||
|
||||
/**
|
||||
* Encrypt object
|
||||
*/
|
||||
protected Encrypt $enc;
|
||||
|
||||
/**
|
||||
* File helper used to load font files.
|
||||
*/
|
||||
protected ObjFile $fileHelper;
|
||||
|
||||
/**
|
||||
* Get the PDF output string for a CID-0 font.
|
||||
* A Type 0 CIDFont contains glyph descriptions based on the Adobe Type 1 font format
|
||||
*
|
||||
* @param TFontData $font Font to process
|
||||
*
|
||||
* @return string
|
||||
*
|
||||
* @throws EncException
|
||||
*/
|
||||
protected function getCid0(array $font): string
|
||||
{
|
||||
$fontcw = $font['cw'];
|
||||
$fontname = $font['name'];
|
||||
$fontenc = $font['enc'];
|
||||
$fontn = $font['n'];
|
||||
$fonti = $font['i'];
|
||||
$fontdw = $font['dw'];
|
||||
$fontdesc = $font['desc'];
|
||||
$fontcidinfo = $font['cidinfo'];
|
||||
$cidregistry = $fontcidinfo['Registry'];
|
||||
$cidordering = $fontcidinfo['Ordering'];
|
||||
$cidsupplement = $fontcidinfo['Supplement'];
|
||||
|
||||
$cidoffset = 0;
|
||||
if (!isset($fontcw[1])) {
|
||||
$cidoffset = 31;
|
||||
}
|
||||
|
||||
$this->uniToCid($font, $cidoffset);
|
||||
$name = $fontname;
|
||||
$longname = $name;
|
||||
if ($fontenc !== '') {
|
||||
$longname .= '-' . $fontenc;
|
||||
}
|
||||
|
||||
// obj 1
|
||||
$out =
|
||||
$fontn
|
||||
. ' 0 obj'
|
||||
. "\n"
|
||||
. '<</Type /Font'
|
||||
. ' /Subtype /Type0'
|
||||
. ' /BaseFont /'
|
||||
. $longname
|
||||
. ' /Name /F'
|
||||
. $fonti;
|
||||
if ($fontenc !== '') {
|
||||
$out .= ' /Encoding /' . $fontenc;
|
||||
}
|
||||
|
||||
$out .= ' /DescendantFonts [' . ($this->pon + 1) . ' 0 R] >>' . "\n" . 'endobj' . "\n";
|
||||
|
||||
// obj 2
|
||||
$out .= ++$this->pon . ' 0 obj' . "\n" . '<</Type /Font /Subtype /CIDFontType0 /BaseFont /' . $name;
|
||||
$cidinfo =
|
||||
'/Registry '
|
||||
. $this->enc->escapeDataString($cidregistry, $this->pon)
|
||||
. ' /Ordering '
|
||||
. $this->enc->escapeDataString($cidordering, $this->pon)
|
||||
. ' /Supplement '
|
||||
. $cidsupplement;
|
||||
$out .=
|
||||
' /CIDSystemInfo <<'
|
||||
. $cidinfo
|
||||
. '>>'
|
||||
. ' /FontDescriptor '
|
||||
. ($this->pon + 1)
|
||||
. ' 0 R'
|
||||
. ' /DW '
|
||||
. $fontdw
|
||||
. "\n"
|
||||
. $this->getCharWidths($font, $cidoffset)
|
||||
. ' >>'
|
||||
. "\n"
|
||||
. 'endobj'
|
||||
. "\n";
|
||||
|
||||
// obj 3
|
||||
$out .= ++$this->pon . ' 0 obj' . "\n" . '<</Type /FontDescriptor /FontName /' . $name;
|
||||
foreach ($fontdesc as $key => $val) {
|
||||
$out .= $this->getKeyValOut($key, $val);
|
||||
}
|
||||
|
||||
return $out . ('>>' . "\n" . 'endobj' . "\n");
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert Unicode to CID
|
||||
*
|
||||
* @param TFontData $font Font to process
|
||||
* @param int $cidoffset Offset for CID values
|
||||
*/
|
||||
protected function uniToCid(array &$font, int $cidoffset): void
|
||||
{
|
||||
// convert unicode to cid.
|
||||
$fontcidinfo = $font['cidinfo'];
|
||||
$uni2cidraw = $fontcidinfo['uni2cid'];
|
||||
$uni2cid = [];
|
||||
foreach ($uni2cidraw as $uni => $cid) {
|
||||
$uni2cid[(int) $uni] = (int) $cid;
|
||||
}
|
||||
|
||||
$fontcwraw = $font['cw'];
|
||||
$fontcw = [];
|
||||
foreach ($fontcwraw as $uni => $width) {
|
||||
$fontcw[(int) $uni] = (int) $width;
|
||||
}
|
||||
|
||||
$chw = [];
|
||||
foreach ($fontcw as $uni => $width) {
|
||||
if (isset($uni2cid[$uni])) {
|
||||
$chw[$uni2cid[$uni] + $cidoffset] = $width;
|
||||
} elseif ($uni < 256) {
|
||||
$chw[$uni] = $width;
|
||||
} // else unknown character
|
||||
}
|
||||
|
||||
foreach ($chw as $cid => $width) {
|
||||
$fontcw[$cid] = $width;
|
||||
}
|
||||
|
||||
$font['cw'] = $fontcw;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the PDF output string for a TrueTypeUnicode font.
|
||||
* Based on PDF Reference 1.3 (section 5)
|
||||
*
|
||||
* @param TFontData $font Font to process
|
||||
*
|
||||
* @return string
|
||||
*
|
||||
* @throws EncException
|
||||
* @throws FontException
|
||||
* @throws \RuntimeException
|
||||
*
|
||||
* @SuppressWarnings("PHPMD.ExcessiveMethodLength")
|
||||
* @SuppressWarnings("PHPMD.CyclomaticComplexity")
|
||||
* @SuppressWarnings("PHPMD.NPathComplexity")
|
||||
*/
|
||||
protected function getTrueTypeUnicode(array $font): string
|
||||
{
|
||||
$fontsubset = $font['subset'];
|
||||
$fonti = $font['i'];
|
||||
$fontn = $font['n'];
|
||||
$fontenc = $font['enc'];
|
||||
$fontnamebase = $font['name'];
|
||||
$fontdw = $font['dw'];
|
||||
$fontctg = $font['ctg'];
|
||||
$fontdir = $font['dir'];
|
||||
$fontfilen = $font['file_n'];
|
||||
$fontdesc = $font['desc'];
|
||||
$fontcidinfo = $font['cidinfo'];
|
||||
|
||||
$fontname = '';
|
||||
if ($fontsubset) {
|
||||
// change name for font subsetting
|
||||
$subtag = \sprintf('%06u', $fonti);
|
||||
$subtag = \strtr($subtag, '0123456789', 'ABCDEFGHIJ');
|
||||
$fontname .= $subtag . '+';
|
||||
}
|
||||
|
||||
$fontname .= $fontnamebase;
|
||||
|
||||
// Type0 Font
|
||||
// A composite font composed of other fonts, organized hierarchically
|
||||
|
||||
// obj 1
|
||||
$out =
|
||||
$fontn
|
||||
. ' 0 obj'
|
||||
. "\n"
|
||||
. '<< /Type /Font'
|
||||
. ' /Subtype /Type0'
|
||||
. ' /BaseFont /'
|
||||
. $fontname
|
||||
. ' /Name /F'
|
||||
. $fonti
|
||||
. ' /Encoding /'
|
||||
. $fontenc
|
||||
. ' /ToUnicode '
|
||||
. ($this->pon + 1)
|
||||
. ' 0 R'
|
||||
. ' /DescendantFonts ['
|
||||
. ($this->pon + 2)
|
||||
. ' 0 R]'
|
||||
. ' >>'
|
||||
. "\n"
|
||||
. 'endobj'
|
||||
. "\n";
|
||||
|
||||
// ToUnicode Object
|
||||
$out .= ++$this->pon . ' 0 obj' . "\n" . '<<';
|
||||
$cidhmap = Identity::CIDHMAP;
|
||||
if ($font['compress']) {
|
||||
$out .= ' /Filter /FlateDecode';
|
||||
$cidhmap = \gzcompress($cidhmap);
|
||||
if ($cidhmap === false) {
|
||||
throw new \RuntimeException('Unable to compress CIDHMAP');
|
||||
}
|
||||
}
|
||||
|
||||
$stream = $this->enc->encryptString($cidhmap, $this->pon); // ToUnicode map for Identity-H
|
||||
$out .=
|
||||
' /Length '
|
||||
. \strlen($stream)
|
||||
. ' >>'
|
||||
. ' stream'
|
||||
. "\n"
|
||||
. $stream
|
||||
. "\n"
|
||||
. 'endstream'
|
||||
. "\n"
|
||||
. 'endobj'
|
||||
. "\n";
|
||||
|
||||
// CIDFontType2
|
||||
// A CIDFont whose glyph descriptions are based on TrueType font technology
|
||||
$out .= ++$this->pon . ' 0 obj' . "\n" . '<< /Type /Font /Subtype /CIDFontType2 /BaseFont /' . $fontname;
|
||||
// A dictionary containing entries that define the character collection of the CIDFont.
|
||||
$cidRegistry = $fontcidinfo['Registry'] === '' ? 'Adobe' : $fontcidinfo['Registry'];
|
||||
$cidOrdering = $fontcidinfo['Ordering'] === '' ? 'Identity' : $fontcidinfo['Ordering'];
|
||||
$cidinfo =
|
||||
'/Registry '
|
||||
. $this->enc->escapeDataString($cidRegistry, $this->pon)
|
||||
. ' /Ordering '
|
||||
. $this->enc->escapeDataString($cidOrdering, $this->pon)
|
||||
. ' /Supplement '
|
||||
. $fontcidinfo['Supplement'];
|
||||
$out .=
|
||||
' /CIDSystemInfo << '
|
||||
. $cidinfo
|
||||
. ' >>'
|
||||
. ' /FontDescriptor '
|
||||
. ($this->pon + 1)
|
||||
. ' 0 R'
|
||||
. ' /DW '
|
||||
. $fontdw
|
||||
. "\n"
|
||||
. $this->getCharWidths($font, 0);
|
||||
if ($fontctg !== '') {
|
||||
$out .= "\n" . '/CIDToGIDMap ' . ($this->pon + 2) . ' 0 R';
|
||||
}
|
||||
|
||||
$out .= ' >>' . "\n" . 'endobj' . "\n";
|
||||
|
||||
// Font descriptor
|
||||
// A font descriptor describing the CIDFont default metrics other than its glyph widths
|
||||
$out .= ++$this->pon . ' 0 obj' . "\n" . '<< /Type /FontDescriptor /FontName /' . $fontname;
|
||||
foreach ($fontdesc as $key => $val) {
|
||||
$out .= $this->getKeyValOut($key, $val);
|
||||
}
|
||||
|
||||
if ($fontfilen > 0) {
|
||||
// A stream containing a TrueType font
|
||||
$out .= ' /FontFile2 ' . $fontfilen . ' 0 R';
|
||||
}
|
||||
|
||||
$out .= ' >>' . "\n" . 'endobj' . "\n";
|
||||
|
||||
if ($fontctg !== '') {
|
||||
$out .= ++$this->pon . ' 0 obj' . "\n";
|
||||
// Embed CIDToGIDMap
|
||||
// A specification of the mapping from CIDs to glyph indices
|
||||
// search and get CTG font file to embed
|
||||
$ctgfile = \strtolower($fontctg);
|
||||
// search and get ctg font file to embed
|
||||
$fontfile = $this->getFontFullPath($fontdir, $ctgfile);
|
||||
$content = $this->fileHelper->getLocalFileData($fontfile);
|
||||
if ($content === false) {
|
||||
throw new FontException('Unable to read font file: ' . $fontfile);
|
||||
}
|
||||
|
||||
$stream = $this->enc->encryptString($content, $this->pon);
|
||||
$out .= '<< /Length ' . \strlen($stream) . '';
|
||||
if (\str_ends_with($fontfile, '.z')) { // check file extension
|
||||
// Decompresses data encoded using the public-domain
|
||||
// zlib/deflate compression method, reproducing the
|
||||
// original text or binary data
|
||||
$out .= ' /Filter /FlateDecode';
|
||||
}
|
||||
|
||||
$out .= ' >> stream' . "\n" . $stream . "\n" . 'endstream' . "\n" . 'endobj' . "\n";
|
||||
}
|
||||
|
||||
return $out;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the PDF output string for a Core font.
|
||||
*
|
||||
* @param TFontData $font Font to process
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
protected function getCore(array $font): string
|
||||
{
|
||||
$fontn = $font['n'];
|
||||
$fontname = $font['name'];
|
||||
$fonti = $font['i'];
|
||||
$fontfamily = $font['family'];
|
||||
|
||||
$out =
|
||||
$fontn
|
||||
. ' 0 obj'
|
||||
. "\n"
|
||||
. '<</Type /Font'
|
||||
. ' /Subtype /Type1'
|
||||
. ' /BaseFont /'
|
||||
. $fontname
|
||||
. ' /Name /F'
|
||||
. $fonti;
|
||||
if ($fontfamily !== 'symbol' && $fontfamily !== 'zapfdingbats') {
|
||||
$out .= ' /Encoding /WinAnsiEncoding';
|
||||
}
|
||||
|
||||
return $out . (' >>' . "\n" . 'endobj' . "\n");
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the PDF output string for a TrueType font.
|
||||
*
|
||||
* @param TFontData $font Font to process
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
protected function getTrueType(array $font): string
|
||||
{
|
||||
$fontname = $font['name'];
|
||||
$fonttype = $font['type'];
|
||||
$fonti = $font['i'];
|
||||
$fontn = $font['n'];
|
||||
$fontdw = $font['dw'];
|
||||
$fontfile = $font['file'];
|
||||
$fontfilen = $font['file_n'];
|
||||
$fontenc = $font['enc'];
|
||||
$fontdesc = $font['desc'];
|
||||
$fontcw = $font['cw'];
|
||||
|
||||
// obj 1
|
||||
$out =
|
||||
$fontn
|
||||
. ' 0 obj'
|
||||
. "\n"
|
||||
. '<</Type /Font'
|
||||
. ' /Subtype /'
|
||||
. $fonttype
|
||||
. ' /BaseFont /'
|
||||
. $fontname
|
||||
. ' /Name /F'
|
||||
. $fonti
|
||||
. ' /FirstChar 32 /LastChar 255'
|
||||
. ' /Widths '
|
||||
. ($this->pon + 1)
|
||||
. ' 0 R'
|
||||
. ' /FontDescriptor '
|
||||
. ($this->pon + 2)
|
||||
. ' 0 R';
|
||||
if ($fontenc !== '') {
|
||||
if ($font['diff_n'] !== 0) {
|
||||
$out .= ' /Encoding ' . $font['diff_n'] . ' 0 R';
|
||||
} else {
|
||||
$out .= ' /Encoding /WinAnsiEncoding';
|
||||
}
|
||||
}
|
||||
|
||||
$out .= ' >>' . "\n" . 'endobj' . "\n";
|
||||
|
||||
// obj 2 - Widths
|
||||
$out .= ++$this->pon . ' 0 obj' . "\n" . '[';
|
||||
for ($idx = 32; $idx < 256; ++$idx) {
|
||||
if (isset($fontcw[$idx])) {
|
||||
$out .= (int) $fontcw[$idx] . ' ';
|
||||
} else {
|
||||
$out .= $fontdw . ' ';
|
||||
}
|
||||
}
|
||||
|
||||
$out .= ']' . "\n" . 'endobj' . "\n";
|
||||
|
||||
// obj 3 - Descriptor
|
||||
$out .= ++$this->pon . ' 0 obj' . "\n" . '<</Type /FontDescriptor /FontName /' . $fontname;
|
||||
foreach ($fontdesc as $fdk => $fdv) {
|
||||
$out .= $this->getKeyValOut($fdk, $fdv);
|
||||
}
|
||||
|
||||
if ($fontfile !== '') {
|
||||
$out .= ' /FontFile' . ($fonttype === 'Type1' ? '' : '2') . ' ' . $fontfilen . ' 0 R';
|
||||
}
|
||||
|
||||
return $out . ('>>' . "\n" . 'endobj' . "\n");
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the formatted key/value PDF string
|
||||
*
|
||||
* @param string $key Key name
|
||||
* @param mixed $val Value
|
||||
*/
|
||||
protected function getKeyValOut(string $key, mixed $val): string
|
||||
{
|
||||
if (\is_float($val)) {
|
||||
$val = \sprintf('%F', $val);
|
||||
}
|
||||
|
||||
return ' /' . $key . ' ' . (string) $val;
|
||||
}
|
||||
}
|
||||
+199
@@ -0,0 +1,199 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
/**
|
||||
* OutUtil.php
|
||||
*
|
||||
* @since 2011-05-23
|
||||
* @category Library
|
||||
* @package PdfFont
|
||||
* @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-font
|
||||
*
|
||||
* This file is part of tc-lib-pdf-font software library.
|
||||
*/
|
||||
|
||||
namespace Com\Tecnick\Pdf\Font;
|
||||
|
||||
use Com\Tecnick\File\Dir;
|
||||
use Com\Tecnick\Pdf\Font\Exception as FontException;
|
||||
|
||||
/**
|
||||
* Com\Tecnick\Pdf\Font\OutUtil
|
||||
*
|
||||
* @since 2011-05-23
|
||||
* @category Library
|
||||
* @package PdfFont
|
||||
* @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-font
|
||||
*
|
||||
* @phpstan-import-type TFontData from Load
|
||||
*/
|
||||
abstract class OutUtil
|
||||
{
|
||||
/**
|
||||
* Return font full path
|
||||
*
|
||||
* @param string $fontdir Original font directory
|
||||
* @param string $file Font file name.
|
||||
*
|
||||
* @return string Font full path or empty string
|
||||
*
|
||||
* @throws FontException
|
||||
*/
|
||||
protected function getFontFullPath(string $fontdir, string $file): string
|
||||
{
|
||||
$dirobj = new Dir();
|
||||
$kpathfonts = \defined('K_PATH_FONTS') ? (string) \constant('K_PATH_FONTS') : '';
|
||||
// directories where to search for the font definition file
|
||||
// ('.' searches the current working directory)
|
||||
$dirs = \array_unique([
|
||||
'.',
|
||||
$fontdir,
|
||||
$kpathfonts,
|
||||
$dirobj->findParentDir('fonts', __DIR__),
|
||||
]);
|
||||
foreach ($dirs as $dir) {
|
||||
if (\is_readable($dir . DIRECTORY_SEPARATOR . $file)) {
|
||||
return $dir . DIRECTORY_SEPARATOR . $file;
|
||||
}
|
||||
}
|
||||
|
||||
throw new FontException('Unable to locate the file: ' . $file);
|
||||
}
|
||||
|
||||
/**
|
||||
* Outputs font widths
|
||||
*
|
||||
* @param TFontData $font Font to process
|
||||
* @param int $cidoffset Offset for CID values
|
||||
*
|
||||
* @return string PDF command string for font widths
|
||||
*/
|
||||
protected function getCharWidths(array $font, int $cidoffset = 0): string
|
||||
{
|
||||
\ksort($font['cw']);
|
||||
$range = $this->getWidthRanges($font, $cidoffset);
|
||||
// output data
|
||||
$wdt = '';
|
||||
foreach ($range as $kdx => $wds) {
|
||||
if (\count(\array_count_values($wds)) === 1) {
|
||||
// interval mode is more compact
|
||||
$wdt .= ' ' . $kdx . ' ' . ($kdx + \count($wds) - 1) . ' ' . $wds[0];
|
||||
} else {
|
||||
// range mode
|
||||
$wdt .= ' ' . $kdx . ' [ ' . \implode(' ', $wds) . ' ]';
|
||||
}
|
||||
}
|
||||
|
||||
return '/W [' . $wdt . ' ]';
|
||||
}
|
||||
|
||||
/**
|
||||
* get width ranges of characters
|
||||
*
|
||||
* @param TFontData $font Font to process
|
||||
* @param int $cidoffset Offset for CID values
|
||||
*
|
||||
* @return array<int, array<int, int>>
|
||||
*/
|
||||
protected function getWidthRanges(array $font, int $cidoffset = 0): array
|
||||
{
|
||||
$range = [];
|
||||
$rangeid = 0;
|
||||
$prevcid = -2;
|
||||
$prevwidth = -1;
|
||||
$interval = false;
|
||||
// for each character
|
||||
foreach ($font['cw'] as $cid => $width) {
|
||||
$cid -= $cidoffset;
|
||||
if ($font['subset'] && !isset($font['subsetchars'][$cid])) {
|
||||
// ignore the unused characters (font subsetting)
|
||||
continue;
|
||||
}
|
||||
|
||||
if ($width !== $font['dw']) {
|
||||
if ($cid === ($prevcid + 1)) {
|
||||
// consecutive CID
|
||||
if ($width === $prevwidth) {
|
||||
if ($width === $range[$rangeid][0]) {
|
||||
$range[$rangeid][] = $width;
|
||||
} else {
|
||||
\array_pop($range[$rangeid]);
|
||||
// new range
|
||||
$rangeid = $prevcid;
|
||||
$range[$rangeid] = [];
|
||||
$range[$rangeid][] = $prevwidth;
|
||||
$range[$rangeid][] = $width;
|
||||
}
|
||||
|
||||
$interval = true;
|
||||
$range[$rangeid][-1] = -1;
|
||||
} else {
|
||||
if ($interval) {
|
||||
// new range
|
||||
$rangeid = $cid;
|
||||
$range[$rangeid] = [];
|
||||
$range[$rangeid][] = $width;
|
||||
} else {
|
||||
$range[$rangeid][] = $width;
|
||||
}
|
||||
|
||||
$interval = false;
|
||||
}
|
||||
} else {
|
||||
// new range
|
||||
$rangeid = $cid;
|
||||
$range[$rangeid] = [];
|
||||
$range[$rangeid][] = $width;
|
||||
$interval = false;
|
||||
}
|
||||
|
||||
$prevcid = $cid;
|
||||
$prevwidth = $width;
|
||||
}
|
||||
}
|
||||
|
||||
/** @var array<int, array<int, int>> $range */
|
||||
return $this->optimizeWidthRanges($range);
|
||||
}
|
||||
|
||||
/**
|
||||
* Optimize width ranges
|
||||
*
|
||||
* @param array<int, array<int, int>> $range Width Ranges
|
||||
*
|
||||
* @return array<int, array<int, int>>
|
||||
*/
|
||||
protected function optimizeWidthRanges(array $range): array
|
||||
{
|
||||
$prevk = -1;
|
||||
$nextk = -1;
|
||||
$prevint = false;
|
||||
foreach ($range as $kdx => $wds) {
|
||||
$cws = \count($wds);
|
||||
if ($kdx === $nextk && !$prevint && (!isset($wds[-1]) || $cws < 4)) {
|
||||
unset($range[$kdx][-1]);
|
||||
$range[$prevk] = [...$range[$prevk], ...$range[$kdx]];
|
||||
unset($range[$kdx]);
|
||||
} else {
|
||||
$prevk = $kdx;
|
||||
}
|
||||
|
||||
$prevint = false;
|
||||
$nextk = $kdx + $cws;
|
||||
if (isset($wds[-1])) {
|
||||
unset($range[$kdx][-1]);
|
||||
$prevint = $cws > 3;
|
||||
--$nextk;
|
||||
}
|
||||
}
|
||||
|
||||
return $range;
|
||||
}
|
||||
}
|
||||
+362
@@ -0,0 +1,362 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
/**
|
||||
* Output.php
|
||||
*
|
||||
* @since 2011-05-23
|
||||
* @category Library
|
||||
* @package PdfFont
|
||||
* @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-font
|
||||
*
|
||||
* This file is part of tc-lib-pdf-font software library.
|
||||
*/
|
||||
|
||||
namespace Com\Tecnick\Pdf\Font;
|
||||
|
||||
use Com\Tecnick\File\Exception as FileException;
|
||||
use Com\Tecnick\File\File as ObjFile;
|
||||
use Com\Tecnick\Pdf\Encrypt\Encrypt;
|
||||
use Com\Tecnick\Pdf\Font\Exception as FontException;
|
||||
|
||||
/**
|
||||
* Com\Tecnick\Pdf\Font\Output
|
||||
*
|
||||
* @since 2011-05-23
|
||||
* @category Library
|
||||
* @package PdfFont
|
||||
* @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-font
|
||||
*
|
||||
* @phpstan-import-type TFontData from Load
|
||||
*/
|
||||
class Output extends \Com\Tecnick\Pdf\Font\OutFont
|
||||
{
|
||||
/**
|
||||
* Namespace and schema-version prefix for subset cache keys.
|
||||
*
|
||||
* Bump the trailing version segment to invalidate previously cached
|
||||
* subsets whenever the subsetting algorithm or key format changes.
|
||||
*/
|
||||
protected const SUBSET_CACHE_KEY_PREFIX = 'tc-lib-pdf-font:subset:v2:';
|
||||
|
||||
/**
|
||||
* Array of character subsets for each font file
|
||||
*
|
||||
* @var array<string, array<int, bool>>
|
||||
*/
|
||||
protected array $subchars = [];
|
||||
|
||||
/**
|
||||
* PDF string block with the fonts definitions
|
||||
*/
|
||||
protected string $out = '';
|
||||
|
||||
/**
|
||||
* Initialize font data
|
||||
*
|
||||
* @param array<string, TFontData> $fonts Array of imported fonts data
|
||||
* @param int $pon Current PDF Object Number
|
||||
* @param Encrypt $encrypt Encrypt object
|
||||
* @param ObjFile $fileHelper File helper for font loading.
|
||||
* @param FontSubsetCacheInterface $subsetCache Optional cache for subset font programs.
|
||||
*
|
||||
* @throws FileException
|
||||
* @throws FontException
|
||||
*/
|
||||
public function __construct(
|
||||
protected array $fonts,
|
||||
int $pon,
|
||||
Encrypt $encrypt,
|
||||
?ObjFile $fileHelper = null,
|
||||
protected ?FontSubsetCacheInterface $subsetCache = null,
|
||||
) {
|
||||
$this->fileHelper = $fileHelper ?? new ObjFile(allowedPaths: $this->buildAllowedPaths());
|
||||
|
||||
$this->pon = $pon;
|
||||
$this->enc = $encrypt;
|
||||
|
||||
$this->out = $this->getEncodingDiffs();
|
||||
$this->out .= $this->getFontFiles();
|
||||
$this->out .= $this->getFontDefinitions();
|
||||
}
|
||||
|
||||
/**
|
||||
* Build trusted roots for local font file loading.
|
||||
*
|
||||
* @return array<string>
|
||||
*/
|
||||
private function buildAllowedPaths(): array
|
||||
{
|
||||
return FontPaths::buildAllowedPaths();
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns current PDF object number
|
||||
*/
|
||||
public function getObjectNumber(): int
|
||||
{
|
||||
return $this->pon;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the PDF fonts block
|
||||
*/
|
||||
public function getFontsBlock(): string
|
||||
{
|
||||
return $this->out;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the PDF output string for Font resources dictionary.
|
||||
*
|
||||
* @param array<string, TFontData|array{'i': int, 'n': int}> $data Font data.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
private function getOutFontResources(array $data): string
|
||||
{
|
||||
if ($data === []) {
|
||||
return '';
|
||||
}
|
||||
|
||||
$out = ' /Font <<';
|
||||
|
||||
foreach ($data as $font) {
|
||||
$out .= ' /F' . (int) $font['i'] . ' ' . (int) $font['n'] . ' 0 R';
|
||||
}
|
||||
|
||||
return $out . ' >>';
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the PDF output string for Font resources dictionary.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function getOutFontDict(): string
|
||||
{
|
||||
return $this->getOutFontResources($this->fonts);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the PDF output string for XOBject Font resources dictionary.
|
||||
*
|
||||
* @param array<string> $keys Array of font keys.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function getOutFontDictByKeys(array $keys): string
|
||||
{
|
||||
if ($keys === []) {
|
||||
return '';
|
||||
}
|
||||
|
||||
$data = [];
|
||||
foreach ($keys as $key) {
|
||||
$data[$key] = [
|
||||
'i' => $this->fonts[$key]['i'],
|
||||
'n' => $this->fonts[$key]['n'],
|
||||
];
|
||||
}
|
||||
|
||||
return $this->getOutFontResources($data);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the PDF output string for font encoding diffs
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
protected function getEncodingDiffs(): string
|
||||
{
|
||||
$out = '';
|
||||
$done = []; // store processed items to avoid duplication
|
||||
foreach ($this->fonts as $fkey => $font) {
|
||||
if ($font['diff'] !== '') {
|
||||
$dkey = \md5($font['diff']);
|
||||
if (!isset($done[$dkey])) {
|
||||
$out .=
|
||||
++$this->pon
|
||||
. ' 0 obj'
|
||||
. "\n"
|
||||
. '<< /Type /Encoding /BaseEncoding /WinAnsiEncoding /Differences ['
|
||||
. $font['diff']
|
||||
. '] >>'
|
||||
. "\n"
|
||||
. 'endobj'
|
||||
. "\n";
|
||||
$done[$dkey] = $this->pon;
|
||||
}
|
||||
|
||||
$this->fonts[$fkey]['diff_n'] = $done[$dkey];
|
||||
}
|
||||
|
||||
// extract the character subset
|
||||
if ($font['file'] !== '') {
|
||||
$file_key = \md5($font['file']);
|
||||
if (!isset($this->subchars[$file_key]) || $this->subchars[$file_key] === []) {
|
||||
$this->subchars[$file_key] = $font['subsetchars'];
|
||||
} else {
|
||||
foreach ($font['subsetchars'] as $cid => $enabled) {
|
||||
if (!$enabled) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$this->subchars[$file_key][(int) $cid] = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return $out;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the PDF output string for font files
|
||||
*
|
||||
* @return string
|
||||
*
|
||||
* @throws FileException
|
||||
* @throws FontException
|
||||
*/
|
||||
protected function getFontFiles(): string
|
||||
{
|
||||
$out = '';
|
||||
$done = []; // store processed items to avoid duplication
|
||||
foreach ($this->fonts as $fkey => $font) {
|
||||
if ($font['file'] === '') {
|
||||
continue;
|
||||
}
|
||||
|
||||
$dkey = \md5($font['file']);
|
||||
if (!isset($done[$dkey])) {
|
||||
$fontfile = $this->getFontFullPath($font['dir'], $font['file']);
|
||||
$font_data = $this->fileHelper->getLocalFileData($fontfile);
|
||||
if ($font_data === false) {
|
||||
throw new FontException('Unable to read font file: ' . $fontfile);
|
||||
}
|
||||
|
||||
if ($font['subset']) {
|
||||
$font_data = \gzuncompress($font_data);
|
||||
if ($font_data === false) {
|
||||
throw new FontException('Unable to uncompress font file: ' . $fontfile);
|
||||
}
|
||||
|
||||
$subchars = $this->subchars[$dkey];
|
||||
// Only derive the cache key when a cache is configured: subsetCacheKey()
|
||||
// hashes the whole (multi-MB) font program, which is pure waste otherwise.
|
||||
$cache = $this->subsetCache;
|
||||
$cacheKey = '';
|
||||
$subsetFont = null;
|
||||
if ($cache !== null) {
|
||||
$cacheKey = $this->subsetCacheKey($font_data, $font, $subchars);
|
||||
$subsetFont = $cache->get($cacheKey);
|
||||
}
|
||||
|
||||
if ($subsetFont === null) {
|
||||
$sub = new Subset($font_data, $font, $this->fileHelper, $subchars);
|
||||
$subsetFont = $sub->getSubsetFont();
|
||||
$cache?->set($cacheKey, $subsetFont);
|
||||
}
|
||||
|
||||
$font_data = $subsetFont;
|
||||
$font['length1'] = \strlen($font_data);
|
||||
$font_data = \gzcompress($font_data);
|
||||
if ($font_data === false) {
|
||||
throw new FontException('Unable to compress font file: ' . $fontfile);
|
||||
}
|
||||
}
|
||||
|
||||
++$this->pon;
|
||||
$stream = $this->enc->encryptString($font_data, $this->pon);
|
||||
$out .=
|
||||
$this->pon
|
||||
. ' 0 obj'
|
||||
. "\n"
|
||||
. '<<'
|
||||
. ' /Filter /FlateDecode'
|
||||
. ' /Length '
|
||||
. \strlen($stream)
|
||||
. ' /Length1 '
|
||||
. $font['length1'];
|
||||
if ($font['type'] === 'Type1') {
|
||||
// Length2/Length3 are only valid for Type1 FontFile streams,
|
||||
// not for TrueType (FontFile2) or CFF (FontFile3) programs.
|
||||
$out .= ' /Length2 ' . $font['length2'] . ' /Length3 0';
|
||||
}
|
||||
|
||||
$out .= ' >> stream' . "\n" . $stream . "\n" . 'endstream' . "\n" . 'endobj' . "\n";
|
||||
$done[$dkey] = $this->pon;
|
||||
}
|
||||
|
||||
$this->fonts[$fkey]['file_n'] = $done[$dkey];
|
||||
}
|
||||
|
||||
return $out;
|
||||
}
|
||||
|
||||
/**
|
||||
* Build the cache key identifying a subset font program.
|
||||
*
|
||||
* The subset output is fully determined by the uncompressed font program
|
||||
* bytes, the cmap-selection metrics that drive glyph mapping
|
||||
* (platform_id, encoding_id, type) and the requested subset characters,
|
||||
* so the key combines all of them. The version prefix allows invalidating
|
||||
* stale entries if the subset algorithm changes.
|
||||
*
|
||||
* The font program (potentially several MB) is fingerprinted with xxh128:
|
||||
* this is a content hash purely for cache addressing, not a security
|
||||
* primitive, so a fast non-cryptographic 128-bit hash is sufficient and
|
||||
* keeps cache-hit lookups cheap.
|
||||
*
|
||||
* @param string $font_data Uncompressed font program bytes.
|
||||
* @param TFontData $font Extracted font metrics.
|
||||
* @param array<int, bool> $subchars Subset characters (charcode => enabled).
|
||||
*/
|
||||
protected function subsetCacheKey(string $font_data, array $font, array $subchars): string
|
||||
{
|
||||
\ksort($subchars);
|
||||
|
||||
return (
|
||||
self::SUBSET_CACHE_KEY_PREFIX
|
||||
. \hash('xxh128', $font_data)
|
||||
. ':'
|
||||
. $font['platform_id']
|
||||
. ':'
|
||||
. $font['encoding_id']
|
||||
. ':'
|
||||
. $font['type']
|
||||
. ':'
|
||||
. \hash('xxh128', \implode(',', \array_keys(\array_filter($subchars))))
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the PDF output string for fonts
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
protected function getFontDefinitions(): string
|
||||
{
|
||||
$out = '';
|
||||
foreach ($this->fonts as $font) {
|
||||
$out .= match (\strtolower($font['type'])) {
|
||||
'core' => $this->getCore($font),
|
||||
'cidfont0' => $this->getCid0($font),
|
||||
'type1' => $this->getTrueType($font),
|
||||
'truetype' => $this->getTrueType($font),
|
||||
'truetypeunicode' => $this->getTrueTypeUnicode($font),
|
||||
default => throw new FontException('Unsupported font type: ' . $font['type']),
|
||||
};
|
||||
}
|
||||
|
||||
return $out;
|
||||
}
|
||||
}
|
||||
+942
@@ -0,0 +1,942 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
/**
|
||||
* Stack.php
|
||||
*
|
||||
* @since 2011-05-23
|
||||
* @category Library
|
||||
* @package PdfFont
|
||||
* @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-font
|
||||
*
|
||||
* This file is part of tc-lib-pdf-font software library.
|
||||
*/
|
||||
|
||||
namespace Com\Tecnick\Pdf\Font;
|
||||
|
||||
use Com\Tecnick\Pdf\Font\Exception as FontException;
|
||||
use Com\Tecnick\Unicode\Data\BidiClass;
|
||||
use Com\Tecnick\Unicode\Data\Type as UnicodeType;
|
||||
|
||||
/**
|
||||
* Com\Tecnick\Pdf\Font\Stack
|
||||
*
|
||||
* @since 2011-05-23
|
||||
* @category Library
|
||||
* @package PdfFont
|
||||
* @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-font
|
||||
*
|
||||
* @phpstan-import-type TFontData from Load
|
||||
*
|
||||
* @phpstan-type TTextSplit array{
|
||||
* 'pos': int,
|
||||
* 'ord': int,
|
||||
* 'spaces': int,
|
||||
* 'septype': string,
|
||||
* 'wordwidth': float,
|
||||
* 'totwidth': float,
|
||||
* 'totspacewidth': float,
|
||||
* }
|
||||
*
|
||||
* @phpstan-type TTextDims array{
|
||||
* 'chars': int,
|
||||
* 'spaces': int,
|
||||
* 'words': int,
|
||||
* 'totwidth': float,
|
||||
* 'totspacewidth': float,
|
||||
* 'split': array<int, TTextSplit>,
|
||||
* }
|
||||
*
|
||||
* @phpstan-type TBBox array{float, float, float, float}
|
||||
*
|
||||
* @phpstan-type TStackItem array{
|
||||
* 'key': string,
|
||||
* 'style': string,
|
||||
* 'size': float,
|
||||
* 'spacing': float,
|
||||
* 'stretching': float,
|
||||
* }
|
||||
*
|
||||
* @phpstan-type TFontMetric array{
|
||||
* 'ascent': float,
|
||||
* 'avgwidth': float,
|
||||
* 'capheight': float,
|
||||
* 'cbbox': array<int, TBBox>,
|
||||
* 'cratio': float,
|
||||
* 'cw': array<int, float>,
|
||||
* 'cwu': array<int, float>,
|
||||
* 'descent': float,
|
||||
* 'dw': float,
|
||||
* 'fbbox': array<int, float>,
|
||||
* 'height': float,
|
||||
* 'idx': int,
|
||||
* 'key': string,
|
||||
* 'maxwidth': float,
|
||||
* 'midpoint': float,
|
||||
* 'missingwidth': float,
|
||||
* 'out': string,
|
||||
* 'outraw': string,
|
||||
* 'size': float,
|
||||
* 'spacing': float,
|
||||
* 'stretching': float,
|
||||
* 'style': string,
|
||||
* 'type': string,
|
||||
* 'up': float,
|
||||
* 'usize': float,
|
||||
* 'ut': float,
|
||||
* 'xheight': float,
|
||||
* }
|
||||
*
|
||||
* @SuppressWarnings("PHPMD.ExcessiveClassComplexity")
|
||||
*/
|
||||
class Stack extends \Com\Tecnick\Pdf\Font\Buffer
|
||||
{
|
||||
/**
|
||||
* Default font size in points
|
||||
*/
|
||||
public const DEFAULT_SIZE = 10;
|
||||
|
||||
/**
|
||||
* Array (stack) containing fonts in order of insertion.
|
||||
* The last item is the current font.
|
||||
*
|
||||
* @var array<int, TStackItem>
|
||||
*/
|
||||
protected array $stack = [];
|
||||
|
||||
/**
|
||||
* Current font index
|
||||
*/
|
||||
protected int $index = -1;
|
||||
|
||||
/**
|
||||
* Array containing font metrics for each fontkey-size combination.
|
||||
*
|
||||
* @var array<string, TFontMetric>
|
||||
*/
|
||||
protected array $metric = [];
|
||||
|
||||
/**
|
||||
* Insert a font into the stack
|
||||
*
|
||||
* The definition file (and the font file itself when embedding) must be present either in the current directory
|
||||
* or in the one indicated by K_PATH_FONTS if the constant is defined.
|
||||
*
|
||||
* @param int $objnum Current PDF object number
|
||||
* @param string $font Font family, or comma separated list of font families
|
||||
* If it is a standard family name, it will override the corresponding font.
|
||||
* @param string $style Font style.
|
||||
* Possible values are (case-insensitive):
|
||||
* regular (default)
|
||||
* B: bold
|
||||
* I: italic
|
||||
* U: underline
|
||||
* D: strikeout (linethrough)
|
||||
* O: overline
|
||||
* @param ?float $size Font size in points (set to null to inherit the last font size).
|
||||
* @param ?float $spacing Extra spacing between characters.
|
||||
* @param ?float $stretching Horizontal character stretching ratio.
|
||||
* @param string $ifile The font definition file (or empty for autodetect).
|
||||
* By default, the name is built from the family and style, in lower case with no spaces.
|
||||
* @param ?bool $subset If true embed only a subset of the font (stores only the information related to
|
||||
* the used characters); If false embed full font; This option is valid only for
|
||||
* TrueTypeUnicode fonts and is disabled for PDF/A. If you want to enable users to
|
||||
* modify the document, set this parameter to false. If you subset the font, the person
|
||||
* who receives your PDF would need to have your same font in order to make changes to
|
||||
* your PDF. The file size of the PDF would also be smaller because you are embedding
|
||||
* only a subset.
|
||||
* Set this to null to use the default value.
|
||||
* NOTE: This option is computational and memory intensive.
|
||||
*
|
||||
* @return TFontMetric Font data
|
||||
*
|
||||
* @throws FontException in case of error
|
||||
*/
|
||||
public function insert(
|
||||
int &$objnum,
|
||||
string $font,
|
||||
string $style = '',
|
||||
?float $size = null,
|
||||
?float $spacing = null,
|
||||
?float $stretching = null,
|
||||
string $ifile = '',
|
||||
?bool $subset = null,
|
||||
): array {
|
||||
if ($subset === null) {
|
||||
$subset = $this->subset;
|
||||
}
|
||||
|
||||
$size = $this->getInputSize($size);
|
||||
$spacing = $this->getInputSpacing($spacing);
|
||||
$stretching = $this->getInputStretching($stretching);
|
||||
|
||||
// try to load the corresponding imported font
|
||||
/** @var ?FontException $err */
|
||||
$err = null;
|
||||
$keys = $this->getNormalizedFontKeys($font);
|
||||
$fontkey = '';
|
||||
foreach ($keys as $key) {
|
||||
try {
|
||||
$fontkey = $this->add($objnum, $key, $style, $ifile, $subset);
|
||||
$err = null;
|
||||
break;
|
||||
} catch (FontException $exc) {
|
||||
$err = $exc;
|
||||
}
|
||||
}
|
||||
|
||||
if ($err !== null) {
|
||||
throw new FontException($err->getMessage());
|
||||
}
|
||||
|
||||
// add this font in the stack
|
||||
$data = $this->getFont($fontkey);
|
||||
|
||||
$this->stack[++$this->index] = [
|
||||
'key' => $fontkey,
|
||||
'style' => $data['style'],
|
||||
'size' => $size,
|
||||
'spacing' => $spacing,
|
||||
'stretching' => $stretching,
|
||||
];
|
||||
|
||||
return $this->getFontMetric($this->index);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the current font data array.
|
||||
*
|
||||
* @return TFontMetric
|
||||
*
|
||||
* @throws FontException
|
||||
*/
|
||||
public function getCurrentFont(): array
|
||||
{
|
||||
return $this->getFontMetric($this->index);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a clone of the specified font with new parameters.
|
||||
*
|
||||
* @param int $objnum Current PDF object number.
|
||||
* @param ?int $idx Font index. Leave it null to use the current font.
|
||||
* @param ?string $style Font style.
|
||||
* Possible values are (case-insensitive):
|
||||
* regular (default)
|
||||
* B: bold
|
||||
* I: italic
|
||||
* U: underline
|
||||
* D: strikeout (linethrough)
|
||||
* O: overline
|
||||
* @param ?float $size Font size in points (set to null to inherit the last font size).
|
||||
* @param ?float $spacing Extra spacing between characters.
|
||||
* @param ?float $stretching Horizontal character stretching ratio.
|
||||
*
|
||||
* @return TFontMetric
|
||||
*
|
||||
* @throws FontException
|
||||
*/
|
||||
public function cloneFont(
|
||||
int &$objnum,
|
||||
?int $idx = null,
|
||||
?string $style = null,
|
||||
?float $size = null,
|
||||
?float $spacing = null,
|
||||
?float $stretching = null,
|
||||
): array {
|
||||
if ($idx === null) {
|
||||
$idx = $this->index;
|
||||
} elseif ($idx < 0 || $idx > $this->index) {
|
||||
throw new FontException('Invalid font index');
|
||||
}
|
||||
|
||||
$curfont = $this->getStackItem($idx);
|
||||
|
||||
if ($style === null || $style === $curfont['style']) {
|
||||
$size = $this->getInputSize($size);
|
||||
$spacing = $this->getInputSpacing($spacing);
|
||||
$stretching = $this->getInputStretching($stretching);
|
||||
|
||||
$this->stack[++$this->index] = [
|
||||
'key' => $curfont['key'],
|
||||
'style' => $curfont['style'],
|
||||
'size' => $size,
|
||||
'spacing' => $spacing,
|
||||
'stretching' => $stretching,
|
||||
];
|
||||
|
||||
return $this->getFontMetric($this->index);
|
||||
}
|
||||
|
||||
$data = $this->getFont($curfont['key']);
|
||||
|
||||
return $this->insert(
|
||||
$objnum,
|
||||
$data['family'],
|
||||
$style,
|
||||
$size,
|
||||
$spacing,
|
||||
$stretching,
|
||||
$this->getStyleFontFile($data, $style),
|
||||
$data['subset'],
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the font definition file to use to load a different style of an already loaded font.
|
||||
*
|
||||
* The 'ifile' entry of a loaded font is the definition file of its own style,
|
||||
* so it cannot be reused as is for a different style.
|
||||
* The definition file of the requested style is searched in the same directory of the source one;
|
||||
* if it is not there, an empty string is returned to trigger the standard autodetection,
|
||||
* that also provides the artificial style fallback when no styled definition file exists.
|
||||
*
|
||||
* @param TFontData $data Data of the source font.
|
||||
* @param string $style Requested font style.
|
||||
*
|
||||
* @return string The font definition file, or an empty string for autodetection.
|
||||
*/
|
||||
protected function getStyleFontFile(array $data, string $style): string
|
||||
{
|
||||
if ($data['dir'] === '') {
|
||||
return '';
|
||||
}
|
||||
|
||||
$style = \strtoupper($style);
|
||||
$suffix = (\str_contains($style, 'B') ? 'B' : '') . (\str_contains($style, 'I') ? 'I' : '');
|
||||
$ifile = $data['dir'] . DIRECTORY_SEPARATOR . \strtolower($data['family'] . $suffix) . '.json';
|
||||
|
||||
return \is_readable($ifile) ? $ifile : '';
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the current font key.
|
||||
*
|
||||
* @return string
|
||||
*
|
||||
* @throws FontException
|
||||
*/
|
||||
public function getCurrentFontKey(): string
|
||||
{
|
||||
return $this->getCurrentStackItem()['key'];
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the current font type (i.e.: Core, TrueType, TrueTypeUnicode, Type1).
|
||||
*
|
||||
* @return string
|
||||
*
|
||||
* @throws FontException
|
||||
*/
|
||||
public function getCurrentFontType(): string
|
||||
{
|
||||
return $this->getFont($this->getCurrentStackItem()['key'])['type'];
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns true if a current font is available on the stack.
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
public function hasCurrentFont(): bool
|
||||
{
|
||||
return $this->index >= 0 && $this->stack !== [];
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the number of fonts currently stored in the stack.
|
||||
*
|
||||
* @return int
|
||||
*/
|
||||
public function getStackSize(): int
|
||||
{
|
||||
return \count($this->stack);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the current font index in the stack.
|
||||
*
|
||||
* @return int
|
||||
*/
|
||||
public function getCurrentFontIndex(): int
|
||||
{
|
||||
return $this->index;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the PDF code to use the current font.
|
||||
*
|
||||
* @return string
|
||||
*
|
||||
* @throws FontException
|
||||
*/
|
||||
public function getOutCurrentFont(): string
|
||||
{
|
||||
return $this->getFontMetric($this->index)['out'];
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns true if the current font type is Core, TrueType or Type1.
|
||||
*
|
||||
* @return bool
|
||||
*
|
||||
* @throws FontException
|
||||
*/
|
||||
public function isCurrentByteFont(): bool
|
||||
{
|
||||
$currentFontType = $this->getCurrentFontType();
|
||||
return $currentFontType === 'Core' || $currentFontType === 'TrueType' || $currentFontType === 'Type1';
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns true if the current font type is TrueTypeUnicode or cidfont0.
|
||||
*
|
||||
* @return bool
|
||||
*
|
||||
* @throws FontException
|
||||
*/
|
||||
public function isCurrentUnicodeFont(): bool
|
||||
{
|
||||
$currentFontType = $this->getCurrentFontType();
|
||||
return $currentFontType === 'TrueTypeUnicode' || $currentFontType === 'cidfont0';
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove and return the last inserted font
|
||||
*
|
||||
* @return TFontMetric
|
||||
*
|
||||
* @throws FontException
|
||||
*/
|
||||
public function popLastFont(): array
|
||||
{
|
||||
if ($this->index < 0 || $this->stack === []) {
|
||||
throw new FontException('The font stack is empty');
|
||||
}
|
||||
|
||||
$font = $this->getFontMetric($this->index);
|
||||
\array_pop($this->stack);
|
||||
--$this->index;
|
||||
return $font;
|
||||
}
|
||||
|
||||
/**
|
||||
* Replace missing characters with selected substitutions
|
||||
*
|
||||
* @param array<int, int> $uniarr Array of character codepoints.
|
||||
* @param array<int, array<int>> $subs Array of possible character substitutions.
|
||||
* The key is the character to check (integer value),
|
||||
* the value is an array of possible substitutes.
|
||||
*
|
||||
* @return array<int, int> Array of character codepoints.
|
||||
*
|
||||
* @throws FontException
|
||||
*/
|
||||
public function replaceMissingChars(array $uniarr, array $subs = []): array
|
||||
{
|
||||
$font = $this->getFontMetric($this->index);
|
||||
foreach ($uniarr as $pos => $uni) {
|
||||
if (isset($font['cw'][$uni])) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$alts = $subs[$uni] ?? null;
|
||||
if ($alts === null) {
|
||||
continue;
|
||||
}
|
||||
|
||||
foreach ($alts as $alt) {
|
||||
if (!isset($font['cw'][$alt])) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$uniarr[$pos] = $alt;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return $uniarr;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns true if the specified Unicode value is defined in the current font
|
||||
*
|
||||
* @param int $ord Unicode character value to convert
|
||||
*
|
||||
* @return bool
|
||||
*
|
||||
* @throws FontException
|
||||
*/
|
||||
public function isCharDefined(int $ord): bool
|
||||
{
|
||||
$font = $this->getFontMetric($this->index);
|
||||
return isset($font['cw'][$ord]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the width of the specified character
|
||||
*
|
||||
* @param int $ord Unicode character value.
|
||||
*
|
||||
* @return float
|
||||
*
|
||||
* @throws FontException
|
||||
*/
|
||||
public function getCharWidth(int $ord): float
|
||||
{
|
||||
if ($ord === 173 || $ord === 8203) {
|
||||
// 173 = SHY character is not printed, as it is used for text hyphenation
|
||||
// 8203 = ZWSP character
|
||||
return 0;
|
||||
}
|
||||
|
||||
$font = $this->getFontMetric($this->index);
|
||||
if (isset($font['cwu'][$ord])) {
|
||||
return $font['cwu'][$ord];
|
||||
}
|
||||
|
||||
return $font['cw'][$ord] ?? $font['dw'];
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the length of the string specified using an array of codepoints.
|
||||
*
|
||||
* @param array<int, int> $uniarr Array of character codepoints.
|
||||
*
|
||||
* @return float
|
||||
*
|
||||
* @throws FontException
|
||||
*/
|
||||
public function getOrdArrWidth(array $uniarr): float
|
||||
{
|
||||
return $this->getOrdArrDims($uniarr)['totwidth'];
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns various dimensions of the string specified using an array of codepoints.
|
||||
*
|
||||
* @param array<int, int> $uniarr Array of character codepoints.
|
||||
*
|
||||
* @return TTextDims
|
||||
*
|
||||
* @throws FontException
|
||||
*/
|
||||
public function getOrdArrDims(array $uniarr): array
|
||||
{
|
||||
$chars = \count($uniarr); // total number of chars
|
||||
$spaces = 0; // total number of spaces
|
||||
$totwidth = 0; // total string width
|
||||
$totspacewidth = 0; // total space width
|
||||
$words = 0; // total number of words
|
||||
$curfont = $this->getFontMetric($this->index);
|
||||
$fact = $curfont['spacing'] * $curfont['stretching'];
|
||||
$fkey = $curfont['key'];
|
||||
$subset = false;
|
||||
if (
|
||||
isset($this->font[$fkey])
|
||||
&& \is_array($this->font[$fkey])
|
||||
&& \array_key_exists('subset', $this->font[$fkey])
|
||||
&& $this->font[$fkey]['subset'] === true
|
||||
) {
|
||||
$subset = true;
|
||||
}
|
||||
$uniarr[] = 8203; // add null at the end to ensure that the last word is processed
|
||||
$split = [];
|
||||
$prevtotwidth = 0.0;
|
||||
foreach ($uniarr as $idx => $ord) {
|
||||
if ($subset) {
|
||||
$this->addSubsetChar($fkey, $ord);
|
||||
}
|
||||
|
||||
// getType() resolves the code points that are not listed in the type table,
|
||||
// which only holds the ones whose bidirectional type is not L.
|
||||
$unitype = UnicodeType::getType($ord);
|
||||
$bidiClass = BidiClass::tryFrom($unitype);
|
||||
// Inline the width lookup using the already-resolved $curfont metric: calling
|
||||
// getCharWidth() here would re-resolve getFontMetric($this->index) per character.
|
||||
$chrwidth = match ($ord) {
|
||||
173, 8203 => 0.0, // 173 = SHY (hyphenation), 8203 = ZWSP: not printed
|
||||
default => $curfont['cwu'][$ord] ?? $curfont['cw'][$ord] ?? $curfont['dw'],
|
||||
};
|
||||
// Split on paragraph/segment separators (B, S), whitespace (WS) and boundary neutrals (BN).
|
||||
if (
|
||||
$bidiClass === BidiClass::B
|
||||
|| $bidiClass === BidiClass::S
|
||||
|| $bidiClass === BidiClass::WS
|
||||
|| $bidiClass === BidiClass::BN
|
||||
) {
|
||||
$currenttotwidth = $totwidth + ($fact * ($idx - 1));
|
||||
$split[$words] = [
|
||||
'pos' => $idx,
|
||||
'ord' => $ord,
|
||||
'spaces' => $spaces,
|
||||
'septype' => $unitype,
|
||||
'wordwidth' => $words > 0 ? $currenttotwidth - $prevtotwidth : 0,
|
||||
'totwidth' => $currenttotwidth,
|
||||
'totspacewidth' => $totspacewidth + ($fact * \max(0, $spaces - 1)),
|
||||
];
|
||||
$prevtotwidth = $currenttotwidth;
|
||||
$words++;
|
||||
if ($bidiClass === BidiClass::WS) {
|
||||
++$spaces;
|
||||
$totspacewidth += $chrwidth;
|
||||
}
|
||||
}
|
||||
$totwidth += $chrwidth;
|
||||
}
|
||||
$totwidth += $fact * \max(0, $chars - 1);
|
||||
$totspacewidth += $fact * \max(0, $spaces - 1);
|
||||
return [
|
||||
'chars' => $chars,
|
||||
'spaces' => $spaces,
|
||||
'words' => $words,
|
||||
'totwidth' => $totwidth,
|
||||
'totspacewidth' => $totspacewidth,
|
||||
'split' => $split,
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the glyph bounding box of the specified character in the current font in user units.
|
||||
*
|
||||
* @param int $ord Unicode character value.
|
||||
*
|
||||
* @return TBBox (xMin, yMin, xMax, yMax)
|
||||
*
|
||||
* @throws FontException
|
||||
*/
|
||||
public function getCharBBox(int $ord): array
|
||||
{
|
||||
$font = $this->getFontMetric($this->index);
|
||||
return $font['cbbox'][$ord] ?? [0.0, 0.0, 0.0, 0.0]; // glyph without outline
|
||||
}
|
||||
|
||||
/**
|
||||
* Replace a char if it is defined on the current font.
|
||||
*
|
||||
* @param int $oldchar Integer code (Unicode) of the character to replace.
|
||||
* @param int $newchar Integer code (Unicode) of the new character.
|
||||
*
|
||||
* @return int the replaced char or the old char in case the new char is not defined
|
||||
*
|
||||
* @throws FontException
|
||||
*/
|
||||
public function replaceChar(int $oldchar, int $newchar): int
|
||||
{
|
||||
if ($this->isCharDefined($newchar)) {
|
||||
// add the new char on the subset list
|
||||
$this->addSubsetChar($this->getFontMetric($this->index)['key'], $newchar);
|
||||
// return the new character
|
||||
return $newchar;
|
||||
}
|
||||
|
||||
// return the old char
|
||||
return $oldchar;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the font metrics associated to the input key.
|
||||
*
|
||||
* @param int $idx Font index in the stack.
|
||||
*
|
||||
* @return TFontMetric
|
||||
*
|
||||
* @throws FontException
|
||||
*/
|
||||
protected function getFontMetric(int $idx): array
|
||||
{
|
||||
$font = $this->getStackItem($idx);
|
||||
// Cheap, collision-free cache key from just the fields the metric depends on,
|
||||
// instead of md5(serialize($font)) which ran on every (mostly cache-hit) call.
|
||||
$mkey =
|
||||
$font['key']
|
||||
. '|'
|
||||
. $font['size']
|
||||
. '|'
|
||||
. $font['spacing']
|
||||
. '|'
|
||||
. $font['stretching']
|
||||
. '|'
|
||||
. $font['style'];
|
||||
if (isset($this->metric[$mkey])) {
|
||||
return $this->metric[$mkey];
|
||||
}
|
||||
|
||||
$fontkey = $font['key'];
|
||||
$fontsize = $font['size'];
|
||||
$fontspacing = $font['spacing'];
|
||||
$fontstretching = $font['stretching'];
|
||||
$fontstyle = $font['style'];
|
||||
|
||||
$usize = $fontsize / $this->kunit;
|
||||
$cratio = $fontsize / 1000;
|
||||
$wratio = $cratio * $fontstretching; // horizontal ratio
|
||||
$data = $this->getFont($fontkey);
|
||||
$desc = $data['desc'];
|
||||
// Build the glyph widths and bounding boxes already scaled to internal units in a
|
||||
// single pass, instead of first casting into intermediate arrays and then rescaling.
|
||||
$cw = [];
|
||||
foreach ($data['cw'] as $cid => $width) {
|
||||
$cw[(int) $cid] = (float) $width * $wratio;
|
||||
}
|
||||
|
||||
$cwu = [];
|
||||
foreach ($data['cwu'] as $codepoint => $width) {
|
||||
$cwu[(int) $codepoint] = (float) $width * $wratio;
|
||||
}
|
||||
|
||||
$cbbox = [];
|
||||
foreach ($data['cbbox'] as $cid => $val) {
|
||||
if (\count($val) !== 4) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$bbox = \array_values($val);
|
||||
$cbbox[(int) $cid] = [
|
||||
0 => (float) $bbox[0] * $wratio,
|
||||
1 => (float) $bbox[1] * $cratio,
|
||||
2 => (float) $bbox[2] * $wratio,
|
||||
3 => (float) $bbox[3] * $cratio,
|
||||
];
|
||||
}
|
||||
|
||||
$ascent = (float) $desc['Ascent'];
|
||||
$descent = (float) $desc['Descent'];
|
||||
$avgwidth = (float) $desc['AvgWidth'];
|
||||
$capheight = (float) $desc['CapHeight'];
|
||||
$maxwidth = (float) $desc['MaxWidth'];
|
||||
$missingwidth = (float) $desc['MissingWidth'];
|
||||
$xheight = (float) $desc['XHeight'];
|
||||
$fontbbox = $desc['FontBBox'];
|
||||
$dw = (float) $data['dw'];
|
||||
$up = (float) $data['up'];
|
||||
$ut = (float) $data['ut'];
|
||||
$fonttype = $data['type'];
|
||||
$outfont = \sprintf('/F%d %F Tf', (int) $data['i'], $fontsize); // PDF output string
|
||||
$tbox = \array_pad(\explode(' ', \substr($fontbbox, 1, -1)), 4, '0');
|
||||
// add this font in the stack with metrics in internal units
|
||||
$this->metric[$mkey] = [
|
||||
'ascent' => $ascent * $cratio,
|
||||
'avgwidth' => $avgwidth * $cratio * $fontstretching,
|
||||
'capheight' => $capheight * $cratio,
|
||||
'cbbox' => $cbbox,
|
||||
'cratio' => $cratio,
|
||||
'cw' => $cw,
|
||||
'cwu' => $cwu,
|
||||
'descent' => $descent * $cratio,
|
||||
'dw' => $dw * $cratio * $fontstretching,
|
||||
'fbbox' => [
|
||||
0 => (\is_numeric($tbox[0]) ? (float) $tbox[0] : 0.0) * $wratio, // left
|
||||
1 => (\is_numeric($tbox[1]) ? (float) $tbox[1] : 0.0) * $cratio, // bottom
|
||||
2 => (\is_numeric($tbox[2]) ? (float) $tbox[2] : 0.0) * $wratio, // right
|
||||
3 => (\is_numeric($tbox[3]) ? (float) $tbox[3] : 0.0) * $cratio, // top
|
||||
],
|
||||
'height' => ($ascent - $descent) * $cratio,
|
||||
'idx' => $idx,
|
||||
'key' => $fontkey,
|
||||
'maxwidth' => $maxwidth * $cratio * $fontstretching,
|
||||
'midpoint' => (($ascent + $descent) * $cratio) / 2,
|
||||
'missingwidth' => $missingwidth * $cratio * $fontstretching,
|
||||
'out' => 'BT ' . $outfont . ' ET' . "\r",
|
||||
'outraw' => $outfont,
|
||||
'size' => $fontsize,
|
||||
'spacing' => $fontspacing,
|
||||
'stretching' => $fontstretching,
|
||||
'style' => $fontstyle,
|
||||
'type' => $fonttype,
|
||||
'up' => $up * $cratio,
|
||||
'usize' => $usize,
|
||||
'ut' => $ut * $cratio,
|
||||
'xheight' => $xheight * $cratio,
|
||||
];
|
||||
return $this->metric[$mkey];
|
||||
}
|
||||
|
||||
/**
|
||||
* Normalize the input size (minimum 0)
|
||||
*
|
||||
* @param ?float $size Font size in points (set to null to inherit the last font size).
|
||||
*
|
||||
* @return float
|
||||
*
|
||||
* @throws FontException
|
||||
*/
|
||||
protected function getInputSize(?float $size = null): float
|
||||
{
|
||||
if ($size === null || $size < 0) {
|
||||
if ($this->index >= 0) {
|
||||
// inherit the size of the last inserted font
|
||||
return $this->getCurrentStackItem()['size'];
|
||||
}
|
||||
|
||||
return self::DEFAULT_SIZE;
|
||||
}
|
||||
|
||||
return \max(0, $size);
|
||||
}
|
||||
|
||||
/**
|
||||
* Normalize the input spacing (minimum 0)
|
||||
*
|
||||
* @param ?float $spacing Extra spacing between characters.
|
||||
*
|
||||
* @return float
|
||||
*
|
||||
* @throws FontException
|
||||
*/
|
||||
protected function getInputSpacing(?float $spacing = null): float
|
||||
{
|
||||
if ($spacing === null) {
|
||||
if ($this->index >= 0) {
|
||||
// inherit the size of the last inserted font
|
||||
return $this->getCurrentStackItem()['spacing'];
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
return $spacing;
|
||||
}
|
||||
|
||||
/**
|
||||
* Normalize the input stretching
|
||||
*
|
||||
* @param ?float $stretching Horizontal character stretching ratio.
|
||||
*
|
||||
* @return float
|
||||
*
|
||||
* @throws FontException
|
||||
*/
|
||||
protected function getInputStretching(?float $stretching = null): float
|
||||
{
|
||||
if ($stretching === null) {
|
||||
if ($this->index >= 0) {
|
||||
// inherit the size of the last inserted font
|
||||
return $this->getCurrentStackItem()['stretching'];
|
||||
}
|
||||
|
||||
return 1;
|
||||
}
|
||||
|
||||
return $stretching;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the stack item at the given index.
|
||||
*
|
||||
* @param int $idx Font index in the stack.
|
||||
*
|
||||
* @return TStackItem
|
||||
*
|
||||
* @throws FontException
|
||||
*/
|
||||
protected function getStackItem(int $idx): array
|
||||
{
|
||||
$item = $this->stack[$idx] ?? null;
|
||||
if ($item === null) {
|
||||
throw new FontException('Invalid font index');
|
||||
}
|
||||
|
||||
return $item;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the current stack item.
|
||||
*
|
||||
* @return TStackItem
|
||||
*
|
||||
* @throws FontException
|
||||
*/
|
||||
protected function getCurrentStackItem(): array
|
||||
{
|
||||
return $this->getStackItem($this->index);
|
||||
}
|
||||
|
||||
/**
|
||||
* Return normalized font keys
|
||||
*
|
||||
* @param string $fontfamily Property string containing comma-separated font family names
|
||||
*
|
||||
* @return array<string>
|
||||
*
|
||||
* @throws FontException
|
||||
*/
|
||||
protected function getNormalizedFontKeys(string $fontfamily): array
|
||||
{
|
||||
if ($fontfamily === '') {
|
||||
throw new FontException('Empty font family name');
|
||||
}
|
||||
|
||||
$keys = [];
|
||||
// remove spaces and symbols
|
||||
$fontfamily = \preg_replace('/[^a-z0-9_\,]/', '', \strtolower($fontfamily));
|
||||
if ($fontfamily === null) {
|
||||
throw new FontException('Invalid font family name');
|
||||
}
|
||||
|
||||
// extract all font names
|
||||
$fontslist = \preg_split('/[,]/', $fontfamily);
|
||||
if ($fontslist === false) {
|
||||
throw new FontException('Invalid font family name: ' . $fontfamily);
|
||||
}
|
||||
|
||||
// replacement patterns
|
||||
|
||||
$fontpattern = ['/regular$/', '/italic$/', '/oblique$/', '/bold([I]?)$/'];
|
||||
$fontreplacement = ['', 'I', 'I', 'B\\1'];
|
||||
|
||||
$keypattern = ['/^serif|^cursive|^fantasy|^timesnewroman/', '/^sansserif/', '/^monospace/'];
|
||||
$keyreplacement = ['times', 'helvetica', 'courier'];
|
||||
|
||||
// find first valid font name
|
||||
foreach ($fontslist as $font) {
|
||||
$font = \preg_replace($fontpattern, $fontreplacement, $font);
|
||||
if ($font === null) {
|
||||
throw new FontException('Invalid font family name: ' . $fontfamily);
|
||||
}
|
||||
|
||||
// replace common family names and core fonts
|
||||
$fontkey = \preg_replace($keypattern, $keyreplacement, $font);
|
||||
if ($fontkey === null) {
|
||||
throw new FontException('Invalid font family name: ' . $fontfamily);
|
||||
}
|
||||
|
||||
$keys[] = $fontkey;
|
||||
}
|
||||
|
||||
return $keys;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the normalized font family name or the current font name key.
|
||||
*
|
||||
* @param string $fontfamily Raw font family name.
|
||||
*
|
||||
* @return string
|
||||
*
|
||||
* @throws FontException
|
||||
*/
|
||||
public function getFontFamilyName(string $fontfamily): string
|
||||
{
|
||||
$fkeys = $this->getNormalizedFontKeys($fontfamily);
|
||||
foreach ($fkeys as $fkey) {
|
||||
if ($this->isValidKey($fkey)) {
|
||||
return $fkey;
|
||||
}
|
||||
|
||||
$pdfakey = 'pdfa' . $fkey;
|
||||
if ($this->isValidKey($pdfakey)) {
|
||||
return $pdfakey;
|
||||
}
|
||||
}
|
||||
|
||||
return $this->getCurrentFontKey();
|
||||
}
|
||||
}
|
||||
+580
@@ -0,0 +1,580 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
/**
|
||||
* Subset.php
|
||||
*
|
||||
* @since 2011-05-23
|
||||
* @category Library
|
||||
* @package PdfFont
|
||||
* @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-font
|
||||
*
|
||||
* This file is part of tc-lib-pdf-font software library.
|
||||
*/
|
||||
|
||||
namespace Com\Tecnick\Pdf\Font;
|
||||
|
||||
use Com\Tecnick\File\Byte;
|
||||
use Com\Tecnick\File\File as ObjFile;
|
||||
use Com\Tecnick\Pdf\Font\Exception as FontException;
|
||||
use Com\Tecnick\Pdf\Font\Import\TrueType;
|
||||
|
||||
/**
|
||||
* Com\Tecnick\Pdf\Font\Subset
|
||||
*
|
||||
* @since 2011-05-23
|
||||
* @category Library
|
||||
* @package PdfFont
|
||||
* @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-font
|
||||
*
|
||||
* @phpstan-import-type TFontData from Load
|
||||
*/
|
||||
class Subset
|
||||
{
|
||||
/**
|
||||
* array of table names to preserve (loca and glyf tables will be added later)
|
||||
* the cmap table is not needed and shall not be present,
|
||||
* since the mapping from character codes to glyph descriptions is provided separately
|
||||
*
|
||||
* @var array<string, bool>
|
||||
*/
|
||||
protected const TABLENAMES = [
|
||||
'head' => true,
|
||||
'hhea' => true,
|
||||
'hmtx' => true,
|
||||
'maxp' => true,
|
||||
'cvt ' => true,
|
||||
'fpgm' => true,
|
||||
'prep' => true,
|
||||
'glyf' => true,
|
||||
'loca' => true,
|
||||
];
|
||||
|
||||
/**
|
||||
* Content of the input font file
|
||||
*/
|
||||
protected string $font = '';
|
||||
|
||||
/**
|
||||
* Object used to read font bytes
|
||||
*/
|
||||
protected Byte $fbyte;
|
||||
|
||||
/**
|
||||
* Extracted font metrics
|
||||
*
|
||||
* @var TFontData
|
||||
*/
|
||||
protected array $fdt = [
|
||||
'Ascender' => 0,
|
||||
'Ascent' => 0,
|
||||
'AvgWidth' => 0.0,
|
||||
'CapHeight' => 0,
|
||||
'CharacterSet' => '',
|
||||
'Descender' => 0,
|
||||
'Descent' => 0,
|
||||
'EncodingScheme' => '',
|
||||
'FamilyName' => '',
|
||||
'Flags' => 0,
|
||||
'FontBBox' => [],
|
||||
'FontName' => '',
|
||||
'FullName' => '',
|
||||
'IsFixedPitch' => false,
|
||||
'ItalicAngle' => 0,
|
||||
'Leading' => 0,
|
||||
'MaxWidth' => 0,
|
||||
'MissingWidth' => 0,
|
||||
'StdHW' => 0,
|
||||
'StdVW' => 0,
|
||||
'StemH' => 0,
|
||||
'StemV' => 0,
|
||||
'UnderlinePosition' => 0,
|
||||
'UnderlineThickness' => 0,
|
||||
'Version' => '',
|
||||
'Weight' => '',
|
||||
'XHeight' => 0,
|
||||
'bbox' => '',
|
||||
'cbbox' => [],
|
||||
'cidinfo' => [
|
||||
'Ordering' => '',
|
||||
'Registry' => '',
|
||||
'Supplement' => 0,
|
||||
'uni2cid' => [],
|
||||
],
|
||||
'compress' => false,
|
||||
'ctg' => '',
|
||||
'ctgdata' => [],
|
||||
'cw' => [],
|
||||
'cwu' => [],
|
||||
'datafile' => '',
|
||||
'desc' => [
|
||||
'Ascent' => 0,
|
||||
'AvgWidth' => 0,
|
||||
'CapHeight' => 0,
|
||||
'Descent' => 0,
|
||||
'Flags' => 0,
|
||||
'FontBBox' => '',
|
||||
'ItalicAngle' => 0,
|
||||
'Leading' => 0,
|
||||
'MaxWidth' => 0,
|
||||
'MissingWidth' => 0,
|
||||
'StemH' => 0,
|
||||
'StemV' => 0,
|
||||
'XHeight' => 0,
|
||||
],
|
||||
'diff' => '',
|
||||
'diff_n' => 0,
|
||||
'dir' => '',
|
||||
'dw' => 0,
|
||||
'enc' => '',
|
||||
'enc_map' => [],
|
||||
'encodingTables' => [],
|
||||
'encoding_id' => 0,
|
||||
'encrypted' => '',
|
||||
'fakestyle' => false,
|
||||
'family' => '',
|
||||
'file' => '',
|
||||
'file_n' => 0,
|
||||
'file_name' => '',
|
||||
'i' => 0,
|
||||
'ifile' => '',
|
||||
'indexToLoc' => [],
|
||||
'input_file' => '',
|
||||
'isUnicode' => false,
|
||||
'italicAngle' => 0,
|
||||
'key' => '',
|
||||
'lenIV' => 0,
|
||||
'length1' => 0,
|
||||
'length2' => 0,
|
||||
'linked' => false,
|
||||
'mode' => [
|
||||
'bold' => false,
|
||||
'italic' => false,
|
||||
'linethrough' => false,
|
||||
'overline' => false,
|
||||
'underline' => false,
|
||||
],
|
||||
'n' => 0,
|
||||
'name' => '',
|
||||
'numGlyphs' => 0,
|
||||
'numHMetrics' => 0,
|
||||
'originalsize' => 0,
|
||||
'pdfa' => false,
|
||||
'platform_id' => 0,
|
||||
'settype' => '',
|
||||
'short_offset' => false,
|
||||
'size1' => 0,
|
||||
'size2' => 0,
|
||||
'style' => '',
|
||||
'subset' => false,
|
||||
'subsetchars' => [],
|
||||
'table' => [],
|
||||
'tot_num_glyphs' => 0,
|
||||
'type' => '',
|
||||
'underlinePosition' => 0,
|
||||
'underlineThickness' => 0,
|
||||
'unicode' => false,
|
||||
'unitsPerEm' => 0,
|
||||
'up' => 0,
|
||||
'urk' => 0.0,
|
||||
'ut' => 0,
|
||||
'weight' => '',
|
||||
];
|
||||
|
||||
/**
|
||||
* Array containing subset glyphs indexes of chars from cmap table
|
||||
*
|
||||
* @var array<int, bool>
|
||||
*/
|
||||
protected array $subglyphs = [];
|
||||
|
||||
/**
|
||||
* Subset font
|
||||
*/
|
||||
protected string $subfont = '';
|
||||
|
||||
/**
|
||||
* Pointer position on the original font data
|
||||
*/
|
||||
protected int $offset = 0;
|
||||
|
||||
/**
|
||||
* File helper used to load font definition files.
|
||||
*/
|
||||
protected ObjFile $fileHelper;
|
||||
|
||||
/**
|
||||
* Process TrueType font
|
||||
*
|
||||
* @param string $font Content of the input font file
|
||||
* @param TFontData $fdt Extracted font metrics
|
||||
* @param ObjFile $fileHelper Optional file helper for font loading.
|
||||
* @param array<int, bool> $subchars Array containing subset chars
|
||||
*
|
||||
* @throws FontException in case of error
|
||||
*/
|
||||
public function __construct(string $font, array $fdt, ObjFile $fileHelper, array $subchars = [])
|
||||
{
|
||||
$this->fileHelper = $fileHelper;
|
||||
$this->font = $font;
|
||||
$this->fbyte = new Byte($font);
|
||||
$trueType = new TrueType(
|
||||
font: $font,
|
||||
fdt: $fdt,
|
||||
fileHelper: $this->fileHelper,
|
||||
fbyte: $this->fbyte,
|
||||
subchars: $subchars,
|
||||
// Subsetting only needs the glyph program (loca/glyf); per-glyph bounding
|
||||
// boxes are never read here, so skip computing them.
|
||||
withCbbox: false,
|
||||
);
|
||||
$this->fdt = $trueType->getFontMetrics();
|
||||
$this->subglyphs = $trueType->getSubGlyphs();
|
||||
$this->addCompositeGlyphs();
|
||||
$this->addProcessedTables();
|
||||
$this->removeUnusedTables();
|
||||
$this->buildSubsetFont();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all the extracted font metrics
|
||||
*/
|
||||
public function getSubsetFont(): string
|
||||
{
|
||||
return $this->subfont;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the checksum of a TTF table.
|
||||
*
|
||||
* @param string $table Table to check
|
||||
* @param int $length Length of table in bytes
|
||||
*
|
||||
* @return int checksum
|
||||
*
|
||||
* @throws FontException
|
||||
*/
|
||||
protected function getTableChecksum(string $table, int $length): int
|
||||
{
|
||||
$sum = 0;
|
||||
$tlen = (int) floor(($length + 3) / 4);
|
||||
$offset = 0;
|
||||
for ($idx = 0; $idx < $tlen; ++$idx) {
|
||||
$chunk = \substr($table, $offset, 4);
|
||||
if (\strlen($chunk) < 4) {
|
||||
// OpenType checksums use zero-padding for trailing partial words.
|
||||
$chunk = \str_pad($chunk, 4, "\0", STR_PAD_RIGHT);
|
||||
}
|
||||
|
||||
$val = \unpack('Ni', $chunk);
|
||||
if ($val === false) {
|
||||
throw new FontException('Unable to unpack table data');
|
||||
}
|
||||
|
||||
$sum += $val['i'];
|
||||
$offset += 4;
|
||||
}
|
||||
|
||||
$sum = \unpack('Ni', \pack('N', $sum));
|
||||
if ($sum === false) {
|
||||
throw new FontException('Unable to unpack checksum');
|
||||
}
|
||||
|
||||
return $sum['i'];
|
||||
}
|
||||
|
||||
/**
|
||||
* Add composite glyphs
|
||||
*/
|
||||
protected function addCompositeGlyphs(): void
|
||||
{
|
||||
$new_sga = $this->subglyphs;
|
||||
while ($new_sga !== []) {
|
||||
$sga = \array_keys($new_sga);
|
||||
$new_sga = [];
|
||||
foreach ($sga as $key) {
|
||||
$new_sga = $this->findCompositeGlyphs($new_sga, $key);
|
||||
}
|
||||
|
||||
foreach ($new_sga as $gid => $enabled) {
|
||||
if (!$enabled) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$this->subglyphs[$gid] = true;
|
||||
}
|
||||
}
|
||||
|
||||
// sort glyphs by key
|
||||
\ksort($this->subglyphs);
|
||||
}
|
||||
|
||||
/**
|
||||
* Find composite glyphs
|
||||
*
|
||||
* @param array<int, bool> $new_sga
|
||||
* @param int $key
|
||||
*
|
||||
* @return array<int, bool>
|
||||
*/
|
||||
protected function findCompositeGlyphs(array $new_sga, int $key): array
|
||||
{
|
||||
if (isset($this->fdt['indexToLoc'][$key])) {
|
||||
/**
|
||||
* Glyph Header
|
||||
* - int16 numberOfContours Normal glyph if >= 0 or composite glyph if negative (should be -1)
|
||||
* - int16 xMin Minimum x for coordinate data.
|
||||
* - int16 yMin Minimum y for coordinate data.
|
||||
* - int16 xMax Maximum x for coordinate data.
|
||||
* - int16 yMax Maximum y for coordinate data.
|
||||
*/
|
||||
|
||||
$this->offset = $this->fdt['table']['glyf']['offset'] + $this->fdt['indexToLoc'][$key];
|
||||
$numberOfContours = $this->fbyte->getShort($this->offset);
|
||||
$this->offset += 2;
|
||||
if ($numberOfContours < 0) { // composite glyph
|
||||
/**
|
||||
* ComponentGlyph record
|
||||
* - uint16 flags Normal glyph if >= 0 or composite glyph if negative (should be -1)
|
||||
* - uint16 glyphIndex glyph index of component
|
||||
* - u/int8|u/int16 argument1 x-offset for component or point number; type depends on bits 0 and 1 in component flags
|
||||
* - u/int8|u/int16 argument2 y-offset for component or point number; type depends on bits 0 and 1 in component flags
|
||||
* - [transform data] optional transform data
|
||||
*/
|
||||
$this->offset += 8; // skip xMin, yMin, xMax, yMax
|
||||
do {
|
||||
$flags = $this->fbyte->getUShort($this->offset);
|
||||
$this->offset += 2;
|
||||
$glyphIndex = $this->fbyte->getUShort($this->offset);
|
||||
$this->offset += 2;
|
||||
if (!isset($this->subglyphs[$glyphIndex])) {
|
||||
// add missing glyphs
|
||||
$new_sga[$glyphIndex] = true;
|
||||
}
|
||||
|
||||
// skip some bytes by case
|
||||
// ARG_1_AND_2_ARE_WORDS (bit 0): [u]int32 if set and [u]int16 if not set
|
||||
if (($flags & 1) !== 0) {
|
||||
$this->offset += 4;
|
||||
} else {
|
||||
$this->offset += 2;
|
||||
}
|
||||
|
||||
if (($flags & 8) !== 0) {
|
||||
// WE_HAVE_A_SCALE (bit 3): Adds 1 * F2DOT14 field
|
||||
$this->offset += 2;
|
||||
} elseif (($flags & 64) !== 0) {
|
||||
// WE_HAVE_AN_X_AND_Y_SCALE (bit 6): Adds 2 * F2DOT14 fields
|
||||
$this->offset += 4;
|
||||
} elseif (($flags & 128) !== 0) {
|
||||
// WE_HAVE_A_TWO_BY_TWO (bit 7): Adds 4 * F2DOT14 fields
|
||||
$this->offset += 8;
|
||||
}
|
||||
} while ($flags & 32); // MORE_COMPONENTS (bit 5)
|
||||
}
|
||||
}
|
||||
|
||||
return $new_sga;
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove unused tables
|
||||
*/
|
||||
protected function removeUnusedTables(): void
|
||||
{
|
||||
// get the tables to preserve
|
||||
$this->offset = 12;
|
||||
$tabname = \array_keys($this->fdt['table']);
|
||||
foreach ($tabname as $tag) {
|
||||
if (!isset(self::TABLENAMES[$tag])) {
|
||||
// remove the table
|
||||
unset($this->fdt['table'][$tag]);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!isset($this->fdt['table'][$tag])) {
|
||||
$this->fdt['table'][$tag] = [
|
||||
'checkSum' => 0,
|
||||
'data' => '',
|
||||
'length' => 0,
|
||||
'offset' => 0,
|
||||
];
|
||||
}
|
||||
|
||||
$isSubsetTable = $tag === 'loca' || $tag === 'glyf';
|
||||
if (!$isSubsetTable) {
|
||||
$this->fdt['table'][$tag]['data'] = \substr(
|
||||
$this->font,
|
||||
$this->fdt['table'][$tag]['offset'],
|
||||
$this->fdt['table'][$tag]['length'],
|
||||
);
|
||||
if ($tag === 'head') {
|
||||
// set the checkSumAdjustment to 0
|
||||
$this->fdt['table'][$tag]['data'] =
|
||||
\substr($this->fdt['table'][$tag]['data'], 0, 8)
|
||||
. "\x0\x0\x0\x0"
|
||||
. \substr($this->fdt['table'][$tag]['data'], 12);
|
||||
}
|
||||
}
|
||||
|
||||
$pad = 4 - ((int) $this->fdt['table'][$tag]['length'] % 4);
|
||||
if ($pad !== 4) {
|
||||
// the length of a table must be a multiple of four bytes
|
||||
$this->fdt['table'][$tag]['length'] += (int) $pad;
|
||||
$this->fdt['table'][$tag]['data'] .= \str_repeat("\x0", max(0, $pad));
|
||||
}
|
||||
|
||||
$this->fdt['table'][$tag]['offset'] = $this->offset;
|
||||
$this->offset += $this->fdt['table'][$tag]['length'];
|
||||
|
||||
// check sum is not changed
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Add glyf and loca tables
|
||||
*
|
||||
* @SuppressWarnings("PHPMD.CyclomaticComplexity")
|
||||
* @SuppressWarnings("PHPMD.NPathComplexity")
|
||||
*/
|
||||
protected function addProcessedTables(): void
|
||||
{
|
||||
// build new glyf and loca tables
|
||||
$glyf = '';
|
||||
$loca = '';
|
||||
$this->offset = 0;
|
||||
$glyf_offset = $this->fdt['table']['glyf']['offset'];
|
||||
for ($i = 0; $i < $this->fdt['tot_num_glyphs']; ++$i) {
|
||||
$nextidx = $this->getNextLocaIndex($i + 1);
|
||||
if (isset($this->subglyphs[$i], $this->fdt['indexToLoc'][$i]) && $nextidx !== null) {
|
||||
$length = $this->fdt['indexToLoc'][$nextidx] - $this->fdt['indexToLoc'][$i];
|
||||
$glyf .= \substr($this->font, $glyf_offset + $this->fdt['indexToLoc'][$i], $length);
|
||||
} else {
|
||||
$length = 0;
|
||||
}
|
||||
|
||||
if ($this->fdt['short_offset']) {
|
||||
$loca .= \pack('n', \floor($this->offset / 2));
|
||||
} else {
|
||||
$loca .= \pack('N', $this->offset);
|
||||
}
|
||||
|
||||
$this->offset += $length;
|
||||
}
|
||||
|
||||
// add loca
|
||||
if (!isset($this->fdt['table']['loca'])) {
|
||||
$this->fdt['table']['loca'] = [
|
||||
'checkSum' => 0,
|
||||
'data' => '',
|
||||
'length' => 0,
|
||||
'offset' => 0,
|
||||
];
|
||||
}
|
||||
|
||||
$this->fdt['table']['loca']['data'] = $loca;
|
||||
$this->fdt['table']['loca']['length'] = \strlen($loca);
|
||||
$this->fdt['table']['loca']['offset'] = $this->offset;
|
||||
$pad = 4 - ($this->fdt['table']['loca']['length'] % 4);
|
||||
if ($pad !== 4) {
|
||||
// the length of a table must be a multiple of four bytes
|
||||
$this->fdt['table']['loca']['length'] += $pad;
|
||||
$this->fdt['table']['loca']['data'] .= \str_repeat("\x0", $pad);
|
||||
}
|
||||
|
||||
$this->fdt['table']['loca']['checkSum'] = $this->getTableChecksum(
|
||||
$this->fdt['table']['loca']['data'],
|
||||
$this->fdt['table']['loca']['length'],
|
||||
);
|
||||
|
||||
$this->offset += $this->fdt['table']['loca']['length'];
|
||||
|
||||
// add glyf
|
||||
if (!isset($this->fdt['table']['glyf'])) {
|
||||
$this->fdt['table']['glyf'] = [
|
||||
'checkSum' => 0,
|
||||
'data' => '',
|
||||
'length' => 0,
|
||||
'offset' => 0,
|
||||
];
|
||||
}
|
||||
|
||||
$this->fdt['table']['glyf']['data'] = $glyf;
|
||||
$this->fdt['table']['glyf']['length'] = \strlen($glyf);
|
||||
$this->fdt['table']['glyf']['offset'] = $this->offset;
|
||||
$pad = 4 - ($this->fdt['table']['glyf']['length'] % 4);
|
||||
if ($pad !== 4) {
|
||||
// the length of a table must be a multiple of four bytes
|
||||
$this->fdt['table']['glyf']['length'] += $pad;
|
||||
$this->fdt['table']['glyf']['data'] .= \str_repeat("\x0", $pad);
|
||||
}
|
||||
|
||||
$this->fdt['table']['glyf']['checkSum'] = $this->getTableChecksum(
|
||||
$this->fdt['table']['glyf']['data'],
|
||||
$this->fdt['table']['glyf']['length'],
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the first available loca index from $start, or null if none exists.
|
||||
*/
|
||||
protected function getNextLocaIndex(int $start): ?int
|
||||
{
|
||||
for ($idx = $start; $idx <= $this->fdt['tot_num_glyphs']; ++$idx) {
|
||||
if (isset($this->fdt['indexToLoc'][$idx])) {
|
||||
return $idx;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* build new subset font
|
||||
*
|
||||
* @throws FontException
|
||||
*/
|
||||
protected function buildSubsetFont(): void
|
||||
{
|
||||
$this->subfont = '';
|
||||
$this->subfont .= \pack('N', 0x1_0000); // sfnt version
|
||||
$numTables = \count($this->fdt['table']);
|
||||
$this->subfont .= \pack('n', $numTables); // numTables
|
||||
$entrySelector = \floor(\log($numTables, 2));
|
||||
$searchRange = (2 ** $entrySelector) * 16;
|
||||
$rangeShift = ($numTables * 16) - $searchRange;
|
||||
$this->subfont .= \pack('n', $searchRange); // searchRange
|
||||
$this->subfont .= \pack('n', $entrySelector); // entrySelector
|
||||
$this->subfont .= \pack('n', $rangeShift); // rangeShift
|
||||
// Table offsets stored in $this->fdt start after the 12-byte sfnt header.
|
||||
// The full output adds the table directory immediately after that header,
|
||||
// so both directory offsets and in-buffer table positions must include this base.
|
||||
$tableDataBaseOffset = $numTables * 16;
|
||||
$this->offset = $tableDataBaseOffset;
|
||||
foreach ($this->fdt['table'] as $tag => $data) {
|
||||
$this->subfont .= $tag; // tag
|
||||
$this->subfont .= \pack('N', $data['checkSum']); // checkSum
|
||||
$this->subfont .= \pack('N', $data['offset'] + $this->offset); // offset
|
||||
$this->subfont .= \pack('N', $data['length']); // length
|
||||
}
|
||||
|
||||
foreach ($this->fdt['table'] as $data) {
|
||||
$this->subfont .= $data['data'];
|
||||
}
|
||||
|
||||
// set checkSumAdjustment on head table
|
||||
$checkSumAdjustment = 0xB1B0_AFBA - $this->getTableChecksum($this->subfont, \strlen($this->subfont));
|
||||
$headAdjustmentPos = $tableDataBaseOffset + $this->fdt['table']['head']['offset'] + 8;
|
||||
$this->subfont =
|
||||
\substr($this->subfont, 0, $headAdjustmentPos)
|
||||
. \pack('N', $checkSumAdjustment)
|
||||
. \substr($this->subfont, $headAdjustmentPos + 4);
|
||||
}
|
||||
}
|
||||
File diff suppressed because one or more lines are too long
@@ -0,0 +1,251 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* BufferTest.php
|
||||
*
|
||||
* @since 2011-05-23
|
||||
* @category Library
|
||||
* @package PdfFont
|
||||
* @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-font
|
||||
*
|
||||
* This file is part of tc-lib-pdf-font software library.
|
||||
*/
|
||||
|
||||
namespace Test;
|
||||
|
||||
/**
|
||||
* Buffer Test
|
||||
*
|
||||
* @since 2011-05-23
|
||||
* @category Library
|
||||
* @package PdfFont
|
||||
* @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-font
|
||||
*
|
||||
* @SuppressWarnings("PHPMD.LongVariable")
|
||||
*/
|
||||
class BufferTest extends TestUtil
|
||||
{
|
||||
public function testSubsetModeDisabledByDefault(): void
|
||||
{
|
||||
$this->setupTest();
|
||||
$stack = new \Com\Tecnick\Pdf\Font\Stack(1);
|
||||
$this->assertFalse($stack->isSubsetMode());
|
||||
}
|
||||
|
||||
/** @throws \Com\Tecnick\Pdf\Font\Exception */
|
||||
public function testAddSubsetCharOnMissingFontThrows(): void
|
||||
{
|
||||
$this->bcExpectException(\Com\Tecnick\Pdf\Font\Exception::class);
|
||||
$this->setupTest();
|
||||
$stack = new \Com\Tecnick\Pdf\Font\Stack(1);
|
||||
$stack->addSubsetChar('missing', 65);
|
||||
}
|
||||
|
||||
/** @throws \Com\Tecnick\Pdf\Font\Exception */
|
||||
public function testStackMissingKey(): void
|
||||
{
|
||||
$this->bcExpectException(\Com\Tecnick\Pdf\Font\Exception::class);
|
||||
$this->setupTest();
|
||||
$stack = new \Com\Tecnick\Pdf\Font\Stack(1);
|
||||
$stack->getFont('missing');
|
||||
}
|
||||
|
||||
/** @throws \Com\Tecnick\Pdf\Font\Exception */
|
||||
public function testStackMissingFontName(): void
|
||||
{
|
||||
$this->bcExpectException(\Com\Tecnick\Pdf\Font\Exception::class);
|
||||
$this->setupTest();
|
||||
$stack = new \Com\Tecnick\Pdf\Font\Stack(1);
|
||||
$objnum = 1;
|
||||
$stack->add($objnum, '');
|
||||
}
|
||||
|
||||
/** @throws \Com\Tecnick\Pdf\Font\Exception */
|
||||
public function testStackIFileMissing(): void
|
||||
{
|
||||
$this->bcExpectException(\Com\Tecnick\Pdf\Font\Exception::class);
|
||||
$this->setupTest();
|
||||
$stack = new \Com\Tecnick\Pdf\Font\Stack(1);
|
||||
$objnum = 1;
|
||||
$stack->add($objnum, 'something', '', '/missing/nothere.json');
|
||||
}
|
||||
|
||||
/** @throws \Com\Tecnick\Pdf\Font\Exception */
|
||||
public function testStackIFileNotJson(): void
|
||||
{
|
||||
$this->bcExpectException(\Com\Tecnick\Pdf\Font\Exception::class);
|
||||
$this->setupTest();
|
||||
$stack = new \Com\Tecnick\Pdf\Font\Stack(1);
|
||||
$objnum = 1;
|
||||
$stack->add($objnum, 'something', '', __DIR__ . '/StackTest.php');
|
||||
}
|
||||
|
||||
/** @throws \Com\Tecnick\Pdf\Font\Exception */
|
||||
public function testStackIFileWrongFormat(): void
|
||||
{
|
||||
$this->bcExpectException(\Com\Tecnick\Pdf\Font\Exception::class);
|
||||
$this->setupTest();
|
||||
$stack = new \Com\Tecnick\Pdf\Font\Stack(1);
|
||||
$objnum = 1;
|
||||
\file_put_contents($this->getFontPath() . 'badformat.json', '{"bad":"format"}');
|
||||
$stack->add($objnum, 'something', '', $this->getFontPath() . 'badformat.json');
|
||||
}
|
||||
|
||||
/** @throws \Com\Tecnick\Pdf\Font\Exception */
|
||||
public function testLoadDeafultWidthA(): void
|
||||
{
|
||||
$this->setupTest();
|
||||
$stack = new \Com\Tecnick\Pdf\Font\Stack(1);
|
||||
$objnum = 1;
|
||||
\file_put_contents($this->getFontPath() . 'test.json', '{"type":"Type1","cw":{"0":100}}');
|
||||
$stack->add($objnum, 'test', '', $this->getFontPath() . 'test.json');
|
||||
$font = $stack->getFont('test');
|
||||
$this->assertEquals(600, $font['dw']);
|
||||
}
|
||||
|
||||
/** @throws \Com\Tecnick\Pdf\Font\Exception */
|
||||
public function testLoadDeafultWidthB(): void
|
||||
{
|
||||
$this->setupTest();
|
||||
$stack = new \Com\Tecnick\Pdf\Font\Stack(1);
|
||||
$objnum = 1;
|
||||
\file_put_contents($this->getFontPath() . 'test.json', '{"type":"Type1","cw":{"32":123}}');
|
||||
$stack->add($objnum, 'test', '', $this->getFontPath() . 'test.json');
|
||||
$font = $stack->getFont('test');
|
||||
$this->assertEquals(123, $font['dw']);
|
||||
}
|
||||
|
||||
/** @throws \Com\Tecnick\Pdf\Font\Exception */
|
||||
public function testLoadDeafultWidthC(): void
|
||||
{
|
||||
$this->setupTest();
|
||||
$stack = new \Com\Tecnick\Pdf\Font\Stack(1);
|
||||
$objnum = 1;
|
||||
\file_put_contents(
|
||||
$this->getFontPath() . 'test.json',
|
||||
'{"type":"Type1","desc":{"MissingWidth":234},"cw":{"0":600}}',
|
||||
);
|
||||
$stack->add($objnum, 'test', '', $this->getFontPath() . 'test.json');
|
||||
$font = $stack->getFont('test');
|
||||
$this->assertEquals(234, $font['dw']);
|
||||
}
|
||||
|
||||
/** @throws \Com\Tecnick\Pdf\Font\Exception */
|
||||
public function testLoadWrongType(): void
|
||||
{
|
||||
$this->bcExpectException(\Com\Tecnick\Pdf\Font\Exception::class);
|
||||
$this->setupTest();
|
||||
$stack = new \Com\Tecnick\Pdf\Font\Stack(1);
|
||||
$objnum = 1;
|
||||
\file_put_contents($this->getFontPath() . 'test.json', '{"type":"WRONG","cw":{"0":600}}');
|
||||
$stack->add($objnum, 'test', '', $this->getFontPath() . 'test.json');
|
||||
}
|
||||
|
||||
/** @throws \Com\Tecnick\Pdf\Font\Exception */
|
||||
public function testLoadCidOnPdfa(): void
|
||||
{
|
||||
$this->bcExpectException(\Com\Tecnick\Pdf\Font\Exception::class);
|
||||
$this->setupTest();
|
||||
$stack = new \Com\Tecnick\Pdf\Font\Stack(1, false, true, true);
|
||||
$objnum = 1;
|
||||
\file_put_contents($this->getFontPath() . 'test.json', '{"type":"cidfont0","cw":{"0":600}}');
|
||||
$stack->add($objnum, 'test', '', $this->getFontPath() . 'test.json', false);
|
||||
}
|
||||
|
||||
/** @throws \Com\Tecnick\Pdf\Font\Exception */
|
||||
public function testLoadArtificialStyles(): void
|
||||
{
|
||||
$this->setupTest();
|
||||
$stack = new \Com\Tecnick\Pdf\Font\Stack(1);
|
||||
$objnum = 1;
|
||||
\file_put_contents(
|
||||
$this->getFontPath() . 'test.json',
|
||||
'{"type":"Core","cw":{"0":600},"mode":{"bold":true,"italic":true}}',
|
||||
);
|
||||
$key = $stack->add($objnum, 'symbol', '', $this->getFontPath() . 'test.json');
|
||||
$this->assertNotEmpty($key);
|
||||
}
|
||||
|
||||
/**
|
||||
* @throws \Com\Tecnick\File\Exception
|
||||
* @throws \Com\Tecnick\Pdf\Font\Exception
|
||||
* @throws \RangeException
|
||||
*/
|
||||
public function testBuffer(): void
|
||||
{
|
||||
$this->setupTest();
|
||||
$indir = \dirname(__DIR__) . '/util/vendor/tecnickcom/tc-font-mirror/';
|
||||
|
||||
$objnum = 1;
|
||||
$stack = new \Com\Tecnick\Pdf\Font\Stack(1, false, true, false);
|
||||
|
||||
new \Com\Tecnick\Pdf\Font\Import($indir . 'pdfa/pfb/PDFASymbol.pfb', '', 'Type1', 'symbol');
|
||||
$stack->add($objnum, 'pdfasymbol');
|
||||
|
||||
new \Com\Tecnick\Pdf\Font\Import($indir . 'core/Helvetica.afm');
|
||||
$stack->add($objnum, 'helvetica');
|
||||
|
||||
new \Com\Tecnick\Pdf\Font\Import($indir . 'core/Helvetica-Bold.afm');
|
||||
$stack->add($objnum, 'helvetica', 'B');
|
||||
|
||||
new \Com\Tecnick\Pdf\Font\Import($indir . 'core/Helvetica-BoldOblique.afm');
|
||||
$stack->add($objnum, 'helveticaBI');
|
||||
|
||||
new \Com\Tecnick\Pdf\Font\Import($indir . 'core/Helvetica-Oblique.afm');
|
||||
$stack->add($objnum, 'helvetica', 'I');
|
||||
|
||||
new \Com\Tecnick\Pdf\Font\Import($indir . 'freefont/FreeSans.ttf');
|
||||
$stack->add($objnum, 'freesans', '');
|
||||
|
||||
new \Com\Tecnick\Pdf\Font\Import($indir . 'freefont/FreeSansBold.ttf');
|
||||
$stack->add($objnum, 'freesans', 'B');
|
||||
|
||||
new \Com\Tecnick\Pdf\Font\Import($indir . 'freefont/FreeSansOblique.ttf');
|
||||
$stack->add($objnum, 'freesans', 'I');
|
||||
|
||||
new \Com\Tecnick\Pdf\Font\Import($indir . 'freefont/FreeSansBoldOblique.ttf');
|
||||
$stack->add($objnum, 'freesans', 'BIUDO', '', true);
|
||||
|
||||
$fontkey = $stack->add($objnum, 'freesans', 'BI', '', true);
|
||||
$this->assertEquals('freesansBI', $fontkey);
|
||||
|
||||
$this->assertEquals(10, $objnum);
|
||||
$this->assertCount(9, $stack->getFonts());
|
||||
$this->assertCount(1, $stack->getEncDiffs());
|
||||
|
||||
$font = $stack->getFont('freesansB');
|
||||
$this->assertNotEmpty($font);
|
||||
$this->assertEquals('FreeSansBold', $font['name']);
|
||||
$this->assertEquals('TrueTypeUnicode', $font['type']);
|
||||
|
||||
new \Com\Tecnick\Pdf\Font\Import($indir . 'core/ZapfDingbats.afm');
|
||||
$stack->add($objnum, 'zapfdingbats', 'BIUDO');
|
||||
$font = $stack->getFont('zapfdingbats');
|
||||
$this->assertNotEmpty($font);
|
||||
}
|
||||
|
||||
/**
|
||||
* @throws \Com\Tecnick\File\Exception
|
||||
* @throws \Com\Tecnick\Pdf\Font\Exception
|
||||
* @throws \RangeException
|
||||
*/
|
||||
public function testBufferPdfa(): void
|
||||
{
|
||||
$this->setupTest();
|
||||
$indir = \dirname(__DIR__) . '/util/vendor/tecnickcom/tc-font-mirror/';
|
||||
|
||||
$objnum = 1;
|
||||
$stack = new \Com\Tecnick\Pdf\Font\Stack(1, true, false, true);
|
||||
|
||||
new \Com\Tecnick\Pdf\Font\Import($indir . 'pdfa/pfb/PDFAHelveticaBoldOblique.pfb');
|
||||
$stack->add($objnum, 'arial', 'BIUDO', '', true);
|
||||
$font = $stack->getFont('pdfahelveticaBI');
|
||||
$this->assertNotEmpty($font);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* FontTest.php
|
||||
*
|
||||
* @since 2011-05-23
|
||||
* @category Library
|
||||
* @package PdfFont
|
||||
* @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-font
|
||||
*
|
||||
* This file is part of tc-lib-pdf-font software library.
|
||||
*/
|
||||
|
||||
namespace Test;
|
||||
|
||||
/**
|
||||
* Font Test
|
||||
*
|
||||
* @since 2011-05-23
|
||||
* @category Library
|
||||
* @package PdfFont
|
||||
* @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-font
|
||||
*/
|
||||
class FontTest extends TestUtil
|
||||
{
|
||||
/** @throws \Com\Tecnick\Pdf\Font\Exception */
|
||||
public function testFontRejectsUnsafeInputDefinitionPath(): void
|
||||
{
|
||||
$this->bcExpectException(\Com\Tecnick\Pdf\Font\Exception::class);
|
||||
$this->setupTest();
|
||||
new \Com\Tecnick\Pdf\Font\Font(
|
||||
'helvetica',
|
||||
'',
|
||||
'../font.json',
|
||||
false,
|
||||
true,
|
||||
false,
|
||||
true,
|
||||
new \Com\Tecnick\File\File(),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,114 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* FontTypeTest.php
|
||||
*
|
||||
* @since 2026-07-17
|
||||
* @category Library
|
||||
* @package PdfFont
|
||||
* @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-font
|
||||
*
|
||||
* This file is part of tc-lib-pdf-font software library.
|
||||
*/
|
||||
|
||||
namespace Test;
|
||||
|
||||
use Com\Tecnick\Pdf\Font\Exception as FontException;
|
||||
use Com\Tecnick\Pdf\Font\FontType;
|
||||
use Com\Tecnick\Pdf\Font\Import;
|
||||
|
||||
/**
|
||||
* FontType enum test
|
||||
*
|
||||
* @since 2026-07-17
|
||||
* @category Library
|
||||
* @package PdfFont
|
||||
* @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-font
|
||||
*/
|
||||
class FontTypeTest extends TestUtil
|
||||
{
|
||||
public function testCaseBackingValues(): void
|
||||
{
|
||||
$this->assertSame('', FontType::Auto->value);
|
||||
$this->assertSame('Core', FontType::Core->value);
|
||||
$this->assertSame('TrueType', FontType::TrueType->value);
|
||||
$this->assertSame('TrueTypeUnicode', FontType::TrueTypeUnicode->value);
|
||||
$this->assertSame('Type1', FontType::Type1->value);
|
||||
$this->assertSame('CID0JP', FontType::Cid0Jp->value);
|
||||
$this->assertSame('CID0KR', FontType::Cid0Kr->value);
|
||||
$this->assertSame('CID0CS', FontType::Cid0Cs->value);
|
||||
$this->assertSame('CID0CT', FontType::Cid0Ct->value);
|
||||
}
|
||||
|
||||
/**
|
||||
* @throws FontException
|
||||
*/
|
||||
public function testFromLooseCanonical(): void
|
||||
{
|
||||
$this->assertSame(FontType::Auto, FontType::fromLoose(''));
|
||||
$this->assertSame(FontType::TrueTypeUnicode, FontType::fromLoose('TrueTypeUnicode'));
|
||||
$this->assertSame(FontType::Cid0Jp, FontType::fromLoose('CID0JP'));
|
||||
}
|
||||
|
||||
/**
|
||||
* @throws FontException
|
||||
*/
|
||||
public function testFromLoosePassesThroughEnumInstance(): void
|
||||
{
|
||||
$this->assertSame(FontType::Type1, FontType::fromLoose(FontType::Type1));
|
||||
}
|
||||
|
||||
/**
|
||||
* @throws FontException
|
||||
*/
|
||||
public function testFromLooseRoundTrip(): void
|
||||
{
|
||||
foreach (FontType::cases() as $case) {
|
||||
$this->assertSame($case, FontType::fromLoose($case->value));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Font type names are case sensitive, so a wrong-case value is unknown.
|
||||
*
|
||||
* @throws FontException
|
||||
*/
|
||||
public function testFromLooseIsCaseSensitive(): void
|
||||
{
|
||||
$this->bcExpectException(FontException::class);
|
||||
FontType::fromLoose('type1');
|
||||
}
|
||||
|
||||
/**
|
||||
* @throws FontException
|
||||
*/
|
||||
public function testFromLooseUnknownThrows(): void
|
||||
{
|
||||
$this->bcExpectException(FontException::class);
|
||||
FontType::fromLoose('OpenType');
|
||||
}
|
||||
|
||||
/**
|
||||
* The widened Import constructor accepts a FontType enum and resolves it the
|
||||
* same way as the equivalent legacy string.
|
||||
*
|
||||
* @throws FontException
|
||||
* @throws \Com\Tecnick\File\Exception
|
||||
* @throws \RangeException
|
||||
*/
|
||||
public function testImportAcceptsEnum(): void
|
||||
{
|
||||
$fin = \dirname(__DIR__) . '/util/vendor/tecnickcom/tc-font-mirror/core/Helvetica.afm';
|
||||
$outdir = \dirname(__DIR__) . '/target/tmptest/fonttype/';
|
||||
\system('rm -rf ' . $outdir . ' && mkdir -p ' . $outdir);
|
||||
|
||||
$import = new Import($fin, $outdir, FontType::Core);
|
||||
$this->assertNotSame('', $import->getFontName());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,271 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* CoreMetricsTest.php
|
||||
*
|
||||
* @since 2026-05-05
|
||||
* @category Library
|
||||
* @package PdfFont
|
||||
* @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-font
|
||||
*
|
||||
* This file is part of tc-lib-pdf-font software library.
|
||||
*/
|
||||
|
||||
namespace Test\Import;
|
||||
|
||||
use Com\Tecnick\Pdf\Font\Exception as FontException;
|
||||
use Com\Tecnick\Pdf\Font\Import\Core;
|
||||
use PHPUnit\Framework\Attributes\DataProvider;
|
||||
use PHPUnit\Framework\TestCase;
|
||||
|
||||
/**
|
||||
* Verifies that Import\Core correctly maps AFM widths to WinAnsi byte positions (cw)
|
||||
* and to Unicode codepoints (cwu) for Helvetica.
|
||||
*
|
||||
* @phpstan-import-type TFontData from \Com\Tecnick\Pdf\Font\Load
|
||||
*/
|
||||
class CoreMetricsTest extends TestCase
|
||||
{
|
||||
private const HELVETICA_AFM = __DIR__ . '/../../util/vendor/tecnickcom/tc-font-mirror/core/Helvetica.afm';
|
||||
|
||||
/** @var TFontData */
|
||||
private static array $fdtTemplate = [
|
||||
'Ascender' => 0,
|
||||
'Ascent' => 0,
|
||||
'AvgWidth' => 0.0,
|
||||
'CapHeight' => 0,
|
||||
'CharacterSet' => '',
|
||||
'Descender' => 0,
|
||||
'Descent' => 0,
|
||||
'EncodingScheme' => '',
|
||||
'FamilyName' => '',
|
||||
'Flags' => 0,
|
||||
'FontBBox' => [],
|
||||
'FontName' => '',
|
||||
'FullName' => '',
|
||||
'IsFixedPitch' => false,
|
||||
'ItalicAngle' => 0,
|
||||
'Leading' => 0,
|
||||
'MaxWidth' => 0,
|
||||
'MissingWidth' => 0,
|
||||
'StdHW' => 0,
|
||||
'StdVW' => 0,
|
||||
'StemH' => 0,
|
||||
'StemV' => 0,
|
||||
'UnderlinePosition' => 0,
|
||||
'UnderlineThickness' => 0,
|
||||
'Version' => '',
|
||||
'Weight' => '',
|
||||
'XHeight' => 0,
|
||||
'bbox' => '',
|
||||
'cbbox' => [],
|
||||
'cidinfo' => ['Ordering' => '', 'Registry' => '', 'Supplement' => 0, 'uni2cid' => []],
|
||||
'compress' => false,
|
||||
'ctg' => '',
|
||||
'ctgdata' => [],
|
||||
'cw' => [],
|
||||
'cwu' => [],
|
||||
'datafile' => '',
|
||||
'desc' => [
|
||||
'Ascent' => 0,
|
||||
'AvgWidth' => 0,
|
||||
'CapHeight' => 0,
|
||||
'Descent' => 0,
|
||||
'Flags' => 0,
|
||||
'FontBBox' => '',
|
||||
'ItalicAngle' => 0,
|
||||
'Leading' => 0,
|
||||
'MaxWidth' => 0,
|
||||
'MissingWidth' => 0,
|
||||
'StemH' => 0,
|
||||
'StemV' => 0,
|
||||
'XHeight' => 0,
|
||||
],
|
||||
'diff' => '',
|
||||
'diff_n' => 0,
|
||||
'dir' => '',
|
||||
'dw' => 0,
|
||||
'enc' => '',
|
||||
'enc_map' => [],
|
||||
'encodingTables' => [],
|
||||
'encoding_id' => 0,
|
||||
'encrypted' => '',
|
||||
'fakestyle' => false,
|
||||
'family' => '',
|
||||
'file' => '',
|
||||
'file_n' => 0,
|
||||
'file_name' => '',
|
||||
'i' => 0,
|
||||
'ifile' => '',
|
||||
'indexToLoc' => [],
|
||||
'input_file' => '',
|
||||
'isUnicode' => false,
|
||||
'italicAngle' => 0,
|
||||
'key' => '',
|
||||
'lenIV' => 0,
|
||||
'length1' => 0,
|
||||
'length2' => 0,
|
||||
'linked' => false,
|
||||
'mode' => [
|
||||
'bold' => false,
|
||||
'italic' => false,
|
||||
'linethrough' => false,
|
||||
'overline' => false,
|
||||
'underline' => false,
|
||||
],
|
||||
'n' => 0,
|
||||
'name' => '',
|
||||
'numGlyphs' => 0,
|
||||
'numHMetrics' => 0,
|
||||
'originalsize' => 0,
|
||||
'pdfa' => false,
|
||||
'platform_id' => 0,
|
||||
'settype' => '',
|
||||
'short_offset' => false,
|
||||
'size1' => 0,
|
||||
'size2' => 0,
|
||||
'style' => '',
|
||||
'subset' => false,
|
||||
'subsetchars' => [],
|
||||
'table' => [],
|
||||
'tot_num_glyphs' => 0,
|
||||
'type' => '',
|
||||
'underlinePosition' => 0,
|
||||
'underlineThickness' => 0,
|
||||
'unicode' => false,
|
||||
'unitsPerEm' => 0,
|
||||
'up' => 0,
|
||||
'urk' => 0.0,
|
||||
'ut' => 0,
|
||||
'weight' => '',
|
||||
];
|
||||
|
||||
/** @return array<string, array{int, int}> */
|
||||
public static function provideHelveticaWinAnsiWidths(): array
|
||||
{
|
||||
return [
|
||||
// [ winansi_cid, expected_width ]
|
||||
// Printable ASCII — unchanged by fix, sanity checks
|
||||
'space' => [0x20, 278],
|
||||
'A' => [0x41, 667],
|
||||
'hyphen' => [0x2D, 333],
|
||||
// WinAnsi 0x80–0x9F range (formerly wrong/missing)
|
||||
'Euro' => [0x80, 556],
|
||||
'quotesinglbase' => [0x82, 222],
|
||||
'florin' => [0x83, 556],
|
||||
'quotedblbase' => [0x84, 333],
|
||||
'ellipsis' => [0x85, 1000],
|
||||
'dagger' => [0x86, 556],
|
||||
'daggerdbl' => [0x87, 556],
|
||||
'circumflex' => [0x88, 333],
|
||||
'perthousand' => [0x89, 1000],
|
||||
'Scaron' => [0x8A, 667],
|
||||
'guilsinglleft' => [0x8B, 333],
|
||||
'OE' => [0x8C, 1000],
|
||||
'Zcaron' => [0x8E, 611],
|
||||
'quoteleft' => [0x91, 222],
|
||||
'quoteright' => [0x92, 222],
|
||||
'quotedblleft' => [0x93, 333],
|
||||
'quotedblright' => [0x94, 333],
|
||||
'bullet' => [0x95, 350],
|
||||
'endash' => [0x96, 556],
|
||||
'emdash' => [0x97, 1000],
|
||||
'tilde' => [0x98, 333],
|
||||
'trademark' => [0x99, 1000],
|
||||
'scaron' => [0x9A, 500],
|
||||
'guilsinglright' => [0x9B, 333],
|
||||
'oe' => [0x9C, 944],
|
||||
'zcaron' => [0x9E, 500],
|
||||
'Ydieresis' => [0x9F, 667],
|
||||
];
|
||||
}
|
||||
|
||||
/** @throws FontException */
|
||||
#[DataProvider('provideHelveticaWinAnsiWidths')]
|
||||
public function testHelveticaWinAnsiWidth(int $cid, int $expected): void
|
||||
{
|
||||
$fdt = $this->getHelveticaMetrics();
|
||||
$this->assertSame($expected, $fdt['cw'][$cid] ?? null, 'cw[0x' . \dechex($cid) . ']');
|
||||
}
|
||||
|
||||
/** @return array<string, array{int, int}> */
|
||||
public static function provideHelveticaUnicodeWidths(): array
|
||||
{
|
||||
return [
|
||||
// [ unicode_codepoint, expected_width ]
|
||||
'emdash' => [0x2014, 1000],
|
||||
'endash' => [0x2013, 556],
|
||||
'quoteleft' => [0x2018, 222],
|
||||
'quoteright' => [0x2019, 222],
|
||||
'quotedblleft' => [0x201C, 333],
|
||||
'quotedblright' => [0x201D, 333],
|
||||
'bullet' => [0x2022, 350],
|
||||
'ellipsis' => [0x2026, 1000],
|
||||
'trademark' => [0x2122, 1000],
|
||||
'Euro' => [0x20AC, 556],
|
||||
'OE' => [0x0152, 1000],
|
||||
'oe' => [0x0153, 944],
|
||||
'Scaron' => [0x0160, 667],
|
||||
'scaron' => [0x0161, 500],
|
||||
'Ydieresis' => [0x0178, 667],
|
||||
'Zcaron' => [0x017D, 611],
|
||||
'zcaron' => [0x017E, 500],
|
||||
// fi/fl are not WinAnsi-encoded but must appear in cwu
|
||||
'fi' => [0xFB01, 500],
|
||||
'fl' => [0xFB02, 500],
|
||||
];
|
||||
}
|
||||
|
||||
/** @throws FontException */
|
||||
#[DataProvider('provideHelveticaUnicodeWidths')]
|
||||
public function testHelveticaUnicodeWidth(int $codepoint, int $expected): void
|
||||
{
|
||||
$fdt = $this->getHelveticaMetrics();
|
||||
$this->assertArrayHasKey('cwu', $fdt);
|
||||
$this->assertSame(
|
||||
$expected,
|
||||
$fdt['cwu'][$codepoint] ?? null,
|
||||
'cwu[U+' . \strtoupper(\dechex($codepoint)) . ']',
|
||||
);
|
||||
}
|
||||
|
||||
/** @throws FontException */
|
||||
public function testGetFontMetricsHandlesAfmWithoutCharMetrics(): void
|
||||
{
|
||||
// an AFM with zero "C" lines must not trigger a DivisionByZeroError in setCharWidths
|
||||
$afm =
|
||||
"StartFontMetrics 4.1\n"
|
||||
. "FontName TestEmpty\n"
|
||||
. "FullName Test Empty\n"
|
||||
. "FontBBox 0 -200 1000 700\n"
|
||||
. "CapHeight 700\n"
|
||||
. "Ascender 700\n"
|
||||
. "Descender -200\n"
|
||||
. "StartCharMetrics 0\n"
|
||||
. "EndCharMetrics\n"
|
||||
. "EndFontMetrics\n";
|
||||
|
||||
$core = new Core($afm, self::$fdtTemplate, new \Com\Tecnick\File\File());
|
||||
$fdt = $core->getFontMetrics();
|
||||
|
||||
$this->assertSame(0, $fdt['AvgWidth']);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return TFontData
|
||||
*
|
||||
* @throws FontException
|
||||
*/
|
||||
private function getHelveticaMetrics(): array
|
||||
{
|
||||
$content = \file_get_contents(self::HELVETICA_AFM);
|
||||
$this->assertIsString($content);
|
||||
|
||||
$core = new Core($content, self::$fdtTemplate, new \Com\Tecnick\File\File());
|
||||
|
||||
return $core->getFontMetrics();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,162 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* ImportInternalsTest.php
|
||||
*
|
||||
* @since 2026-05-05
|
||||
* @category Library
|
||||
* @package PdfFont
|
||||
* @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-font
|
||||
*
|
||||
* This file is part of tc-lib-pdf-font software library.
|
||||
*/
|
||||
|
||||
namespace Test;
|
||||
|
||||
use Com\Tecnick\Pdf\Font\Import;
|
||||
|
||||
/**
|
||||
* Tests for protected methods of Import that cannot be reached through the
|
||||
* normal public constructor path in isolation.
|
||||
*
|
||||
* @since 2026-05-05
|
||||
* @category Library
|
||||
* @package PdfFont
|
||||
* @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-font
|
||||
*/
|
||||
class ImportInternalsTest extends TestUtil
|
||||
{
|
||||
private function buildImport(): Import
|
||||
{
|
||||
$class = new \ReflectionClass(Import::class);
|
||||
return $class->newInstanceWithoutConstructor();
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<int, mixed> $args
|
||||
*/
|
||||
private function callStringMethod(object $obj, string $method, array $args = []): string
|
||||
{
|
||||
$ref = new \ReflectionMethod($obj, $method);
|
||||
|
||||
if (!\is_string($ref->invokeArgs($obj, $args))) {
|
||||
$this->fail('Expected string return value.');
|
||||
}
|
||||
|
||||
return (string) $ref->invokeArgs($obj, $args);
|
||||
}
|
||||
|
||||
private function setFdt(object $obj, mixed $fdt): void
|
||||
{
|
||||
$prop = new \ReflectionProperty($obj, 'fdt');
|
||||
$prop->setValue($obj, $fdt);
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// updateCIDtoGIDmap
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
public function testUpdateCIDtoGIDmapSetsGlyphPairBytes(): void
|
||||
{
|
||||
$instance = $this->buildImport();
|
||||
// 65536 CID slots × 2 bytes = 131072 bytes
|
||||
$map = str_repeat("\x00", 131072);
|
||||
$result = $this->callStringMethod($instance, 'updateCIDtoGIDmap', [$map, 65, 42]);
|
||||
// gid 42 = 0x002A → high byte = 0x00, low byte = 0x2A
|
||||
$this->assertSame(0, ord($result[65 * 2]));
|
||||
$this->assertSame(42, ord($result[(65 * 2) + 1]));
|
||||
}
|
||||
|
||||
public function testUpdateCIDtoGIDmapIgnoresCidOutOfRange(): void
|
||||
{
|
||||
$instance = $this->buildImport();
|
||||
$map = str_repeat("\x00", 131072);
|
||||
$result = $this->callStringMethod($instance, 'updateCIDtoGIDmap', [$map, 0x10000, 5]);
|
||||
// CID 0x10000 is out of the 0..0xFFFF range → map unchanged
|
||||
$this->assertSame($map, $result);
|
||||
}
|
||||
|
||||
public function testUpdateCIDtoGIDmapIgnoresGidAbove0xffff(): void
|
||||
{
|
||||
$instance = $this->buildImport();
|
||||
$map = str_repeat("\x00", 131072);
|
||||
// gid = 0x1002A is outside the representable 16-bit range → entry left as 0 (notdef)
|
||||
$result = $this->callStringMethod($instance, 'updateCIDtoGIDmap', [$map, 0, 0x1002A]);
|
||||
$this->assertSame(0, ord($result[0]));
|
||||
$this->assertSame(0, ord($result[1]));
|
||||
}
|
||||
|
||||
public function testUpdateCIDtoGIDmapIgnoresNegativeGid(): void
|
||||
{
|
||||
$instance = $this->buildImport();
|
||||
$map = str_repeat("\x00", 131072);
|
||||
// gid < 0 → condition ($gid >= 0) is false → map unchanged
|
||||
$result = $this->callStringMethod($instance, 'updateCIDtoGIDmap', [$map, 10, -1]);
|
||||
$this->assertSame($map, $result);
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// getEncodingTable
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
public function testGetEncodingTableReturnsCp1252ForType1NonSymbolic(): void
|
||||
{
|
||||
$instance = $this->buildImport();
|
||||
$this->setFdt($instance, ['type' => 'Type1', 'Flags' => 32]);
|
||||
// Flags & 4 == 0 → non-symbolic Type1 → cp1252
|
||||
$result = $this->callStringMethod($instance, 'getEncodingTable', ['']);
|
||||
$this->assertSame('cp1252', $result);
|
||||
}
|
||||
|
||||
public function testGetEncodingTableReturnsEmptyForType1Symbolic(): void
|
||||
{
|
||||
$instance = $this->buildImport();
|
||||
$this->setFdt($instance, ['type' => 'Type1', 'Flags' => 4]);
|
||||
// Flags & 4 != 0 → symbolic → empty string
|
||||
$result = $this->callStringMethod($instance, 'getEncodingTable', ['']);
|
||||
$this->assertSame('', $result);
|
||||
}
|
||||
|
||||
public function testGetEncodingTableReturnsEmptyForTrueTypeUnicode(): void
|
||||
{
|
||||
$instance = $this->buildImport();
|
||||
$this->setFdt($instance, ['type' => 'TrueTypeUnicode', 'Flags' => 0]);
|
||||
$result = $this->callStringMethod($instance, 'getEncodingTable', ['']);
|
||||
$this->assertSame('', $result);
|
||||
}
|
||||
|
||||
public function testGetEncodingTablePassesThroughExplicitEncoding(): void
|
||||
{
|
||||
$instance = $this->buildImport();
|
||||
$this->setFdt($instance, ['type' => 'TrueType', 'Flags' => 0]);
|
||||
$result = $this->callStringMethod($instance, 'getEncodingTable', ['iso-8859-1']);
|
||||
$this->assertSame('iso-8859-1', $result);
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// findOutputPath
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
public function testFindOutputPathReturnsKPathFontsWhenDefined(): void
|
||||
{
|
||||
$this->setupTest();
|
||||
$instance = $this->buildImport();
|
||||
$result = $this->callStringMethod($instance, 'findOutputPath', ['']);
|
||||
$this->assertSame(constant('K_PATH_FONTS'), $result);
|
||||
}
|
||||
|
||||
public function testFindOutputPathReturnsProvidedWritablePath(): void
|
||||
{
|
||||
$outdir = dirname(__DIR__) . '/target/tmptest/internals/';
|
||||
system('mkdir -p ' . $outdir);
|
||||
$instance = $this->buildImport();
|
||||
$result = $this->callStringMethod($instance, 'findOutputPath', [$outdir]);
|
||||
$this->assertSame($outdir, $result);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,293 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* ImportTest.php
|
||||
*
|
||||
* @since 2011-05-23
|
||||
* @category Library
|
||||
* @package PdfFont
|
||||
* @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-font
|
||||
*
|
||||
* This file is part of tc-lib-pdf-font software library.
|
||||
*/
|
||||
|
||||
namespace Test;
|
||||
|
||||
use Com\Tecnick\File\Exception as FileException;
|
||||
use Com\Tecnick\Pdf\Font\Exception as FontException;
|
||||
use PHPUnit\Framework\Attributes\DataProvider;
|
||||
|
||||
/**
|
||||
* Import Test
|
||||
*
|
||||
* @since 2011-05-23
|
||||
* @category Library
|
||||
* @package PdfFont
|
||||
* @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-font
|
||||
*
|
||||
* @SuppressWarnings("PHPMD.LongVariable")
|
||||
*
|
||||
* @phpstan-import-type TFontData from \Com\Tecnick\Pdf\Font\Load
|
||||
*/
|
||||
class ImportTest extends TestUtil
|
||||
{
|
||||
private function expectFontException(): void
|
||||
{
|
||||
$this->bcExpectException(\Com\Tecnick\Pdf\Font\Exception::class);
|
||||
}
|
||||
|
||||
/**
|
||||
* @throws FileException
|
||||
* @throws FontException
|
||||
* @throws \RangeException
|
||||
*/
|
||||
public function testImportForbiddenProtocol(): void
|
||||
{
|
||||
$this->expectFontException();
|
||||
new \Com\Tecnick\Pdf\Font\Import('phar://test.txt');
|
||||
}
|
||||
|
||||
/**
|
||||
* @throws FileException
|
||||
* @throws FontException
|
||||
* @throws \RangeException
|
||||
*/
|
||||
public function testImportParentDir(): void
|
||||
{
|
||||
$this->expectFontException();
|
||||
new \Com\Tecnick\Pdf\Font\Import('/tmp/something/../test.txt');
|
||||
}
|
||||
|
||||
/**
|
||||
* @throws FileException
|
||||
* @throws FontException
|
||||
* @throws \RangeException
|
||||
*/
|
||||
public function testImportEmptyName(): void
|
||||
{
|
||||
$this->expectFontException();
|
||||
new \Com\Tecnick\Pdf\Font\Import('');
|
||||
}
|
||||
|
||||
/**
|
||||
* @throws FileException
|
||||
* @throws FontException
|
||||
* @throws \RangeException
|
||||
*/
|
||||
public function testImportExist(): void
|
||||
{
|
||||
$this->expectFontException();
|
||||
$fin = \dirname(__DIR__) . '/util/vendor/tecnickcom/tc-font-mirror/core/Helvetica.afm';
|
||||
$outdir = \dirname(__DIR__) . '/target/tmptest/';
|
||||
\system('rm -rf ' . $outdir . ' && mkdir -p ' . $outdir);
|
||||
new \Com\Tecnick\Pdf\Font\Import($fin, $outdir);
|
||||
new \Com\Tecnick\Pdf\Font\Import($fin, $outdir);
|
||||
}
|
||||
|
||||
/**
|
||||
* @throws FileException
|
||||
* @throws FontException
|
||||
* @throws \RangeException
|
||||
*/
|
||||
public function testImportWrongFile(): void
|
||||
{
|
||||
$this->expectFontException();
|
||||
new \Com\Tecnick\Pdf\Font\Import(\dirname(__DIR__) . '/util/vendor/tecnickcom/tc-font-mirror/core/Missing.afm');
|
||||
}
|
||||
|
||||
/**
|
||||
* @throws FileException
|
||||
* @throws FontException
|
||||
* @throws \RangeException
|
||||
*/
|
||||
public function testImportDefaultOutput(): void
|
||||
{
|
||||
$this->expectFontException();
|
||||
new \Com\Tecnick\Pdf\Font\Import(\dirname(__DIR__) . '/util/vendor/tecnickcom/tc-font-mirror/core/Missing.afm');
|
||||
}
|
||||
|
||||
/**
|
||||
* @throws FileException
|
||||
* @throws FontException
|
||||
* @throws \RangeException
|
||||
*/
|
||||
public function testImportUnsupportedType(): void
|
||||
{
|
||||
$this->expectFontException();
|
||||
$fin = \dirname(__DIR__) . '/util/vendor/tecnickcom/tc-font-mirror/core/Helvetica.afm';
|
||||
$outdir = \dirname(__DIR__) . '/target/tmptest/core/';
|
||||
\system('rm -rf ' . $outdir . ' && mkdir -p ' . $outdir);
|
||||
new \Com\Tecnick\Pdf\Font\Import($fin, $outdir, 'ERROR');
|
||||
}
|
||||
|
||||
/**
|
||||
* @throws FileException
|
||||
* @throws FontException
|
||||
* @throws \RangeException
|
||||
*/
|
||||
public function testImportUnsupportedOpenType(): void
|
||||
{
|
||||
$this->expectFontException();
|
||||
$outdir = \dirname(__DIR__) . '/target/tmptest/core/';
|
||||
\system('rm -rf ' . $outdir . ' && mkdir -p ' . $outdir);
|
||||
\file_put_contents($outdir . 'test.ttf', 'OTTO 1234');
|
||||
new \Com\Tecnick\Pdf\Font\Import($outdir . 'test.ttf', $outdir);
|
||||
}
|
||||
|
||||
/**
|
||||
* @throws FileException
|
||||
* @throws FontException
|
||||
* @throws \JsonException
|
||||
* @throws \RangeException
|
||||
*/
|
||||
#[DataProvider('importDataProvider')]
|
||||
public function testImport(
|
||||
string $fontdir,
|
||||
string $font,
|
||||
string $outname,
|
||||
string $type = '',
|
||||
string $encoding = '',
|
||||
): void {
|
||||
$indir = \dirname(__DIR__) . '/util/vendor/tecnickcom/tc-font-mirror/' . $fontdir . '/';
|
||||
$outdir = \dirname(__DIR__) . '/target/tmptest/' . $fontdir . '/';
|
||||
\system('rm -rf ' . \dirname(__DIR__) . '/target/tmptest/ && mkdir -p ' . $outdir);
|
||||
|
||||
$import = new \Com\Tecnick\Pdf\Font\Import($indir . $font, $outdir, $type, $encoding);
|
||||
$this->assertEquals($outname, $import->getFontName());
|
||||
|
||||
$file = \file_get_contents($outdir . $outname . '.json');
|
||||
$this->assertNotFalse($file);
|
||||
|
||||
/**
|
||||
* @var array{
|
||||
* type: mixed,
|
||||
* name: mixed,
|
||||
* up: mixed,
|
||||
* ut: mixed,
|
||||
* dw: mixed,
|
||||
* diff: mixed,
|
||||
* desc: array{
|
||||
* Flags: mixed,
|
||||
* FontBBox: mixed,
|
||||
* ItalicAngle: mixed,
|
||||
* Ascent: mixed,
|
||||
* Descent: mixed,
|
||||
* Leading: mixed,
|
||||
* CapHeight: mixed,
|
||||
* XHeight: mixed,
|
||||
* StemV: mixed,
|
||||
* StemH: mixed,
|
||||
* AvgWidth: mixed,
|
||||
* MaxWidth: mixed,
|
||||
* MissingWidth: mixed
|
||||
* }
|
||||
* } $json
|
||||
*/
|
||||
$json = \json_decode($file, true, 512, JSON_THROW_ON_ERROR);
|
||||
|
||||
$this->assertArrayHasKey('type', $json);
|
||||
$this->assertArrayHasKey('name', $json);
|
||||
$this->assertArrayHasKey('up', $json);
|
||||
$this->assertArrayHasKey('ut', $json);
|
||||
$this->assertArrayHasKey('dw', $json);
|
||||
$this->assertArrayHasKey('diff', $json);
|
||||
$this->assertArrayHasKey('desc', $json);
|
||||
$this->assertArrayHasKey('Flags', $json['desc']);
|
||||
|
||||
$metric = $import->getFontMetrics();
|
||||
|
||||
$this->assertEquals('[' . $metric['bbox'] . ']', $json['desc']['FontBBox']);
|
||||
$this->assertEqualsWithDelta($metric['italicAngle'], $json['desc']['ItalicAngle'], 0.001);
|
||||
$this->assertEquals($metric['Ascent'], $json['desc']['Ascent']);
|
||||
$this->assertEquals($metric['Descent'], $json['desc']['Descent']);
|
||||
$this->assertEquals($metric['Leading'], $json['desc']['Leading']);
|
||||
$this->assertEquals($metric['CapHeight'], $json['desc']['CapHeight']);
|
||||
$this->assertEquals($metric['XHeight'], $json['desc']['XHeight']);
|
||||
$this->assertEquals($metric['StemV'], $json['desc']['StemV']);
|
||||
$this->assertEquals($metric['StemH'], $json['desc']['StemH']);
|
||||
$this->assertEquals($metric['AvgWidth'], $json['desc']['AvgWidth']);
|
||||
$this->assertEquals($metric['MaxWidth'], $json['desc']['MaxWidth']);
|
||||
$this->assertEquals($metric['MissingWidth'], $json['desc']['MissingWidth']);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<array<string>>
|
||||
*/
|
||||
public static function importDataProvider(): array
|
||||
{
|
||||
return [
|
||||
['core', 'Courier.afm', 'courier'],
|
||||
['core', 'Courier-Bold.afm', 'courierb'],
|
||||
['core', 'Courier-BoldOblique.afm', 'courierbi'],
|
||||
['core', 'Courier-Oblique.afm', 'courieri'],
|
||||
['core', 'Helvetica.afm', 'helvetica'],
|
||||
['core', 'Helvetica-Bold.afm', 'helveticab'],
|
||||
['core', 'Helvetica-BoldOblique.afm', 'helveticabi'],
|
||||
['core', 'Helvetica-Oblique.afm', 'helveticai'],
|
||||
['core', 'Symbol.afm', 'symbol'],
|
||||
['core', 'Times.afm', 'times'],
|
||||
['core', 'Times-Bold.afm', 'timesb'],
|
||||
['core', 'Times-BoldItalic.afm', 'timesbi'],
|
||||
['core', 'Times-Italic.afm', 'timesi'],
|
||||
['core', 'ZapfDingbats.afm', 'zapfdingbats'],
|
||||
['pdfa/pfb', 'PDFACourierBoldOblique.pfb', 'pdfacourierbi', '', ''],
|
||||
['pdfa/pfb', 'PDFACourierBold.pfb', 'pdfacourierb', 'Type1', 'cp1252'],
|
||||
['pdfa/pfb', 'PDFACourierOblique.pfb', 'pdfacourieri', 'Type1', 'cp1252'],
|
||||
['pdfa/pfb', 'PDFACourier.pfb', 'pdfacourier', 'Type1', 'cp1252'],
|
||||
['pdfa/pfb', 'PDFAHelveticaBoldOblique.pfb', 'pdfahelveticabi', 'Type1', 'cp1252'],
|
||||
['pdfa/pfb', 'PDFAHelveticaBold.pfb', 'pdfahelveticab', 'Type1', 'cp1252'],
|
||||
['pdfa/pfb', 'PDFAHelveticaOblique.pfb', 'pdfahelveticai', 'Type1', 'cp1252'],
|
||||
['pdfa/pfb', 'PDFAHelvetica.pfb', 'pdfahelvetica', 'Type1', 'cp1252'],
|
||||
['pdfa/pfb', 'PDFASymbol.pfb', 'pdfasymbol', '', 'symbol'],
|
||||
['pdfa/pfb', 'PDFATimesBoldItalic.pfb', 'pdfatimesbi', 'Type1', 'cp1252'],
|
||||
['pdfa/pfb', 'PDFATimesBold.pfb', 'pdfatimesb', 'Type1', 'cp1252'],
|
||||
['pdfa/pfb', 'PDFATimesItalic.pfb', 'pdfatimesi', 'Type1', 'cp1252'],
|
||||
['pdfa/pfb', 'PDFATimes.pfb', 'pdfatimes', 'Type1', 'cp1252'],
|
||||
['pdfa/pfb', 'PDFAZapfDingbats.pfb', 'pdfazapfdingbats'],
|
||||
['freefont', 'FreeMonoBoldOblique.ttf', 'freemonobi'],
|
||||
['freefont', 'FreeMonoBold.ttf', 'freemonob'],
|
||||
['freefont', 'FreeMonoOblique.ttf', 'freemonoi'],
|
||||
['freefont', 'FreeMono.ttf', 'freemono'],
|
||||
['freefont', 'FreeSansBoldOblique.ttf', 'freesansbi'],
|
||||
['freefont', 'FreeSansBold.ttf', 'freesansb'],
|
||||
['freefont', 'FreeSansOblique.ttf', 'freesansi'],
|
||||
['freefont', 'FreeSans.ttf', 'freesans'],
|
||||
['freefont', 'FreeSerifBoldItalic.ttf', 'freeserifbi'],
|
||||
['freefont', 'FreeSerifBold.ttf', 'freeserifb'],
|
||||
['freefont', 'FreeSerifItalic.ttf', 'freeserifi'],
|
||||
['freefont', 'FreeSerif.ttf', 'freeserif'],
|
||||
['unifont', 'unifont.ttf', 'unifont'],
|
||||
['cid0', 'cid0cs.ttf', 'cid0cs', 'CID0CS'],
|
||||
['cid0', 'cid0ct.ttf', 'cid0ct', 'CID0CT'],
|
||||
['cid0', 'cid0jp.ttf', 'cid0jp', 'CID0JP'],
|
||||
['cid0', 'cid0kr.ttf', 'cid0kr', 'CID0KR'],
|
||||
['dejavu/ttf', 'DejaVuSans.ttf', 'dejavusans'],
|
||||
['dejavu/ttf', 'DejaVuSans-BoldOblique.ttf', 'dejavusansbi'],
|
||||
['dejavu/ttf', 'DejaVuSans-Bold.ttf', 'dejavusansb'],
|
||||
['dejavu/ttf', 'DejaVuSans-Oblique.ttf', 'dejavusansi'],
|
||||
['dejavu/ttf', 'DejaVuSansCondensed.ttf', 'dejavusanscondensed'],
|
||||
['dejavu/ttf', 'DejaVuSansCondensed-BoldOblique.ttf', 'dejavusanscondensedbi'],
|
||||
['dejavu/ttf', 'DejaVuSansCondensed-Bold.ttf', 'dejavusanscondensedb'],
|
||||
['dejavu/ttf', 'DejaVuSansCondensed-Oblique.ttf', 'dejavusanscondensedi'],
|
||||
['dejavu/ttf', 'DejaVuSansMono.ttf', 'dejavusansmono'],
|
||||
['dejavu/ttf', 'DejaVuSansMono-BoldOblique.ttf', 'dejavusansmonobi'],
|
||||
['dejavu/ttf', 'DejaVuSansMono-Bold.ttf', 'dejavusansmonob'],
|
||||
['dejavu/ttf', 'DejaVuSansMono-Oblique.ttf', 'dejavusansmonoi'],
|
||||
['dejavu/ttf', 'DejaVuSans-ExtraLight.ttf', 'dejavusansextralight'],
|
||||
['dejavu/ttf', 'DejaVuSerif.ttf', 'dejavuserif'],
|
||||
['dejavu/ttf', 'DejaVuSerif-BoldItalic.ttf', 'dejavuserifbi'],
|
||||
['dejavu/ttf', 'DejaVuSerif-Bold.ttf', 'dejavuserifb'],
|
||||
['dejavu/ttf', 'DejaVuSerif-Italic.ttf', 'dejavuserifi'],
|
||||
['dejavu/ttf', 'DejaVuSerifCondensed.ttf', 'dejavuserifcondensed'],
|
||||
['dejavu/ttf', 'DejaVuSerifCondensed-BoldItalic.ttf', 'dejavuserifcondensedbi'],
|
||||
['dejavu/ttf', 'DejaVuSerifCondensed-Bold.ttf', 'dejavuserifcondensedb'],
|
||||
['dejavu/ttf', 'DejaVuSerifCondensed-Italic.ttf', 'dejavuserifcondensedi'],
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* LoadTest.php
|
||||
*
|
||||
* @since 2026-05-21
|
||||
* @category Library
|
||||
* @package PdfFont
|
||||
* @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-font
|
||||
*
|
||||
* This file is part of tc-lib-pdf-font software library.
|
||||
*/
|
||||
|
||||
namespace Test;
|
||||
|
||||
/**
|
||||
* Load Test
|
||||
*
|
||||
* @since 2026-05-21
|
||||
* @category Library
|
||||
* @package PdfFont
|
||||
* @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-font
|
||||
*/
|
||||
class LoadTest extends TestUtil
|
||||
{
|
||||
/** @throws \Com\Tecnick\Pdf\Font\Exception */
|
||||
public function testLoadAppliesFallbackStylesForMissingVariantFiles(): void
|
||||
{
|
||||
$load = new LoadTestHarness('customfont', '');
|
||||
$load->setModeAndMetrics(true, true, 0, 0, 0);
|
||||
|
||||
$load->load();
|
||||
|
||||
$this->assertSame('customfontBoldItalic', $load->getNameValue());
|
||||
$this->assertSame(123, $load->getStemVValue());
|
||||
$this->assertSame(-11, $load->getItalicAngleValue());
|
||||
$this->assertSame(64, $load->getFlagsValue());
|
||||
}
|
||||
|
||||
public function testFindFontDirectoriesExcludesEmptyRootEntry(): void
|
||||
{
|
||||
$load = new LoadTestHarness('customfont', '');
|
||||
|
||||
$dirs = $load->exposeFontDirectories();
|
||||
|
||||
// An empty entry makes findFontFile() probe the filesystem root
|
||||
// (is_readable('' . DIRECTORY_SEPARATOR . $file) === is_readable('/<font>.json')),
|
||||
// which fails and emits a warning under open_basedir restrictions.
|
||||
// See https://github.com/tecnickcom/tc-lib-pdf/issues/238
|
||||
$this->assertNotContains('', $dirs);
|
||||
}
|
||||
|
||||
/** @throws \Com\Tecnick\Pdf\Font\Exception */
|
||||
public function testLoadUpdatesExistingBoldAndItalicMetrics(): void
|
||||
{
|
||||
$load = new LoadTestHarness('customfont', 'Custom');
|
||||
$load->setModeAndMetrics(true, true, 100, -20, 1);
|
||||
|
||||
$load->load();
|
||||
|
||||
$this->assertSame('CustomBoldItalic', $load->getNameValue());
|
||||
$this->assertSame(175, $load->getStemVValue());
|
||||
$this->assertSame(-31, $load->getItalicAngleValue());
|
||||
$this->assertSame(65, $load->getFlagsValue());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* LoadTestHarness.php
|
||||
*
|
||||
* @since 2026-05-21
|
||||
* @category Library
|
||||
* @package PdfFont
|
||||
* @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-font
|
||||
*
|
||||
* This file is part of tc-lib-pdf-font software library.
|
||||
*/
|
||||
|
||||
namespace Test;
|
||||
|
||||
class LoadTestHarness extends \Com\Tecnick\Pdf\Font\Load
|
||||
{
|
||||
public function __construct(string $key, string $name)
|
||||
{
|
||||
parent::__construct();
|
||||
$this->data['type'] = 'TrueType';
|
||||
$this->data['key'] = $key;
|
||||
$this->data['name'] = $name;
|
||||
$this->data['fakestyle'] = true;
|
||||
$this->data['cw'][32] = 500;
|
||||
}
|
||||
|
||||
public function setModeAndMetrics(bool $bold, bool $italic, int $stemv, int $italicAngle, int $flags): void
|
||||
{
|
||||
$this->data['mode']['bold'] = $bold;
|
||||
$this->data['mode']['italic'] = $italic;
|
||||
$this->data['mode']['linethrough'] = false;
|
||||
$this->data['mode']['overline'] = false;
|
||||
$this->data['mode']['underline'] = false;
|
||||
$this->data['desc']['StemV'] = $stemv;
|
||||
$this->data['desc']['ItalicAngle'] = $italicAngle;
|
||||
$this->data['desc']['Flags'] = $flags;
|
||||
$this->data['desc']['MissingWidth'] = 0;
|
||||
}
|
||||
|
||||
public function getNameValue(): string
|
||||
{
|
||||
return $this->data['name'];
|
||||
}
|
||||
|
||||
/**
|
||||
* Expose the resolved font search directories for testing.
|
||||
*
|
||||
* @return array<string>
|
||||
*/
|
||||
public function exposeFontDirectories(): array
|
||||
{
|
||||
return $this->findFontDirectories();
|
||||
}
|
||||
|
||||
public function getStemVValue(): int
|
||||
{
|
||||
return $this->data['desc']['StemV'];
|
||||
}
|
||||
|
||||
public function getItalicAngleValue(): int
|
||||
{
|
||||
return $this->data['desc']['ItalicAngle'];
|
||||
}
|
||||
|
||||
public function getFlagsValue(): int
|
||||
{
|
||||
return $this->data['desc']['Flags'];
|
||||
}
|
||||
|
||||
protected function getFontInfo(): void
|
||||
{
|
||||
// Keep the preloaded test data and skip filesystem reads.
|
||||
}
|
||||
|
||||
public function setFileData(): void
|
||||
{
|
||||
// Avoid dependency on actual font files for internal branch checks.
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,608 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* OutputTest.php
|
||||
*
|
||||
* @since 2011-05-23
|
||||
* @category Library
|
||||
* @package PdfFont
|
||||
* @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-font
|
||||
*
|
||||
* This file is part of tc-lib-pdf-font software library.
|
||||
*/
|
||||
|
||||
namespace Test;
|
||||
|
||||
use Com\Tecnick\File\Exception as FileException;
|
||||
use Com\Tecnick\Pdf\Encrypt\Encrypt;
|
||||
use Com\Tecnick\Pdf\Font\Exception as FontException;
|
||||
|
||||
/**
|
||||
* Output Test
|
||||
*
|
||||
* @since 2011-05-23
|
||||
* @category Library
|
||||
* @package PdfFont
|
||||
* @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-font
|
||||
*
|
||||
* @SuppressWarnings("PHPMD.LongVariable")
|
||||
*
|
||||
* @phpstan-import-type TFontData from \Com\Tecnick\Pdf\Font\Load
|
||||
*/
|
||||
class OutputTest extends TestUtil
|
||||
{
|
||||
/** @throws \ReflectionException */
|
||||
private function createEncrypt(): Encrypt
|
||||
{
|
||||
$reflector = new \ReflectionClass(Encrypt::class);
|
||||
$encrypt = $reflector->newInstanceWithoutConstructor();
|
||||
|
||||
\assert($encrypt instanceof Encrypt, 'Failed to create Encrypt instance');
|
||||
|
||||
return $encrypt;
|
||||
}
|
||||
|
||||
private function prepareTestEnvironment(): void
|
||||
{
|
||||
parent::setupTest();
|
||||
}
|
||||
|
||||
/**
|
||||
* @return TFontData
|
||||
*/
|
||||
private function getFontTemplate(): array
|
||||
{
|
||||
return [
|
||||
'Ascender' => 0,
|
||||
'Ascent' => 0,
|
||||
'AvgWidth' => 0.0,
|
||||
'CapHeight' => 0,
|
||||
'CharacterSet' => '',
|
||||
'Descender' => 0,
|
||||
'Descent' => 0,
|
||||
'EncodingScheme' => '',
|
||||
'FamilyName' => '',
|
||||
'Flags' => 0,
|
||||
'FontBBox' => [],
|
||||
'FontName' => '',
|
||||
'FullName' => '',
|
||||
'IsFixedPitch' => false,
|
||||
'ItalicAngle' => 0,
|
||||
'Leading' => 0,
|
||||
'MaxWidth' => 0,
|
||||
'MissingWidth' => 0,
|
||||
'StdHW' => 0,
|
||||
'StdVW' => 0,
|
||||
'StemH' => 0,
|
||||
'StemV' => 0,
|
||||
'UnderlinePosition' => 0,
|
||||
'UnderlineThickness' => 0,
|
||||
'Version' => '',
|
||||
'Weight' => '',
|
||||
'XHeight' => 0,
|
||||
'bbox' => '',
|
||||
'cbbox' => [],
|
||||
'cidinfo' => ['Ordering' => '', 'Registry' => '', 'Supplement' => 0, 'uni2cid' => []],
|
||||
'compress' => false,
|
||||
'ctg' => '',
|
||||
'ctgdata' => [],
|
||||
'cw' => [],
|
||||
'cwu' => [],
|
||||
'datafile' => '',
|
||||
'desc' => [
|
||||
'Ascent' => 0,
|
||||
'AvgWidth' => 0,
|
||||
'CapHeight' => 0,
|
||||
'Descent' => 0,
|
||||
'Flags' => 0,
|
||||
'FontBBox' => '',
|
||||
'ItalicAngle' => 0,
|
||||
'Leading' => 0,
|
||||
'MaxWidth' => 0,
|
||||
'MissingWidth' => 0,
|
||||
'StemH' => 0,
|
||||
'StemV' => 0,
|
||||
'XHeight' => 0,
|
||||
],
|
||||
'diff' => '',
|
||||
'diff_n' => 0,
|
||||
'dir' => '',
|
||||
'dw' => 0,
|
||||
'enc' => '',
|
||||
'enc_map' => [],
|
||||
'encodingTables' => [],
|
||||
'encoding_id' => 0,
|
||||
'encrypted' => '',
|
||||
'fakestyle' => false,
|
||||
'family' => '',
|
||||
'file' => '',
|
||||
'file_n' => 0,
|
||||
'file_name' => '',
|
||||
'i' => 0,
|
||||
'ifile' => '',
|
||||
'indexToLoc' => [],
|
||||
'input_file' => '',
|
||||
'isUnicode' => false,
|
||||
'italicAngle' => 0,
|
||||
'key' => '',
|
||||
'lenIV' => 0,
|
||||
'length1' => 0,
|
||||
'length2' => 0,
|
||||
'linked' => false,
|
||||
'mode' => [
|
||||
'bold' => false,
|
||||
'italic' => false,
|
||||
'linethrough' => false,
|
||||
'overline' => false,
|
||||
'underline' => false,
|
||||
],
|
||||
'n' => 0,
|
||||
'name' => '',
|
||||
'numGlyphs' => 0,
|
||||
'numHMetrics' => 0,
|
||||
'originalsize' => 0,
|
||||
'pdfa' => false,
|
||||
'platform_id' => 0,
|
||||
'settype' => '',
|
||||
'short_offset' => false,
|
||||
'size1' => 0,
|
||||
'size2' => 0,
|
||||
'style' => '',
|
||||
'subset' => false,
|
||||
'subsetchars' => [],
|
||||
'table' => [],
|
||||
'tot_num_glyphs' => 0,
|
||||
'type' => '',
|
||||
'underlinePosition' => 0,
|
||||
'underlineThickness' => 0,
|
||||
'unicode' => false,
|
||||
'unitsPerEm' => 0,
|
||||
'up' => 0,
|
||||
'urk' => 0.0,
|
||||
'ut' => 0,
|
||||
'weight' => '',
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* @throws FileException
|
||||
* @throws FontException
|
||||
* @throws \RangeException
|
||||
* @throws \ReflectionException
|
||||
*/
|
||||
public function testOutput(): void
|
||||
{
|
||||
$this->prepareTestEnvironment();
|
||||
$indir = \dirname(__DIR__) . '/util/vendor/tecnickcom/tc-font-mirror/';
|
||||
|
||||
$objnum = 1;
|
||||
$stack = new \Com\Tecnick\Pdf\Font\Stack(1);
|
||||
|
||||
new \Com\Tecnick\Pdf\Font\Import($indir . 'pdfa/pfb/PDFASymbol.pfb', '', 'Type1', 'symbol');
|
||||
$stack->add($objnum, 'pdfasymbol');
|
||||
|
||||
new \Com\Tecnick\Pdf\Font\Import($indir . 'core/Helvetica.afm');
|
||||
$stack->add($objnum, 'helvetica');
|
||||
|
||||
new \Com\Tecnick\Pdf\Font\Import($indir . 'core/Helvetica-Bold.afm');
|
||||
$stack->add($objnum, 'helvetica', 'B');
|
||||
|
||||
new \Com\Tecnick\Pdf\Font\Import($indir . 'core/Helvetica-BoldOblique.afm');
|
||||
$stack->add($objnum, 'helveticaBI');
|
||||
|
||||
new \Com\Tecnick\Pdf\Font\Import($indir . 'core/Helvetica-Oblique.afm');
|
||||
$stack->add($objnum, 'helvetica', 'I');
|
||||
|
||||
new \Com\Tecnick\Pdf\Font\Import($indir . 'freefont/FreeSans.ttf');
|
||||
$stack->add($objnum, 'freesans', '');
|
||||
|
||||
new \Com\Tecnick\Pdf\Font\Import($indir . 'freefont/FreeSansBold.ttf');
|
||||
$stack->add($objnum, 'freesans', 'B');
|
||||
|
||||
new \Com\Tecnick\Pdf\Font\Import($indir . 'freefont/FreeSansOblique.ttf');
|
||||
$stack->add($objnum, 'freesans', 'I');
|
||||
|
||||
new \Com\Tecnick\Pdf\Font\Import($indir . 'freefont/FreeSansBoldOblique.ttf');
|
||||
$stack->add($objnum, 'freesans', 'BIUDO', '', true);
|
||||
|
||||
new \Com\Tecnick\Pdf\Font\Import($indir . 'cid0/cid0jp.ttf', '', 'CID0JP');
|
||||
$stack->add($objnum, 'cid0jp');
|
||||
|
||||
$fonts = $stack->getFonts();
|
||||
$this->assertCount(10, $fonts);
|
||||
|
||||
$encrypt = $this->createEncrypt();
|
||||
$output = new \Com\Tecnick\Pdf\Font\Output($fonts, $objnum, $encrypt, null);
|
||||
|
||||
$this->assertEquals(37, $output->getObjectNumber());
|
||||
|
||||
$this->assertNotEmpty($output->getFontsBlock());
|
||||
|
||||
$this->assertNotEmpty($output->getOutFontDict());
|
||||
|
||||
$keys = [];
|
||||
foreach ($fonts as $font) {
|
||||
$keys[] = $font['key'];
|
||||
}
|
||||
|
||||
$this->assertNotEmpty($output->getOutFontDictByKeys($keys));
|
||||
}
|
||||
|
||||
/**
|
||||
* @throws FileException
|
||||
* @throws FontException
|
||||
* @throws \ReflectionException
|
||||
*/
|
||||
public function testOutputWithNoFontsReturnsEmptyStrings(): void
|
||||
{
|
||||
// Empty font array: constructor still runs without error; all output methods
|
||||
// return empty strings because there is nothing to iterate over.
|
||||
$encrypt = $this->createEncrypt();
|
||||
$output = new \Com\Tecnick\Pdf\Font\Output([], 1, $encrypt, null);
|
||||
|
||||
$this->assertSame('', $output->getFontsBlock());
|
||||
$this->assertSame('', $output->getOutFontDict());
|
||||
$this->assertSame('', $output->getOutFontDictByKeys([]));
|
||||
}
|
||||
|
||||
/**
|
||||
* @throws FileException
|
||||
* @throws FontException
|
||||
* @throws \ReflectionException
|
||||
*/
|
||||
public function testOutputGetFontDefinitionsThrowsOnUnknownFontType(): void
|
||||
{
|
||||
// A font entry with an unrecognised type triggers the default branch of the
|
||||
// match expression inside getFontDefinitions, which throws FontException.
|
||||
$this->bcExpectException(\Com\Tecnick\Pdf\Font\Exception::class);
|
||||
|
||||
$encrypt = $this->createEncrypt();
|
||||
|
||||
// Build a minimal font array with an unknown type so that getFontDefinitions
|
||||
// reaches the default throw branch.
|
||||
$fonts = ['unknown_key' => $this->getFontTemplate()];
|
||||
$fonts['unknown_key']['type'] = 'UnknownType';
|
||||
|
||||
new \Com\Tecnick\Pdf\Font\Output($fonts, 1, $encrypt, null);
|
||||
}
|
||||
|
||||
/**
|
||||
* @throws FileException
|
||||
* @throws FontException
|
||||
* @throws \RangeException
|
||||
* @throws \ReflectionException
|
||||
*/
|
||||
public function testSubsetTrueTypeUnicodeOutputUsesValidCidSystemInfoAndFontStream(): void
|
||||
{
|
||||
$this->prepareTestEnvironment();
|
||||
$indir = \dirname(__DIR__) . '/util/vendor/tecnickcom/tc-font-mirror/';
|
||||
|
||||
$objnum = 1;
|
||||
$stack = new \Com\Tecnick\Pdf\Font\Stack(1);
|
||||
new \Com\Tecnick\Pdf\Font\Import($indir . 'freefont/FreeSans.ttf');
|
||||
$stack->add($objnum, 'freesans', '', '', true);
|
||||
|
||||
// Ensure at least a few glyphs are included in the subset.
|
||||
foreach ([32, 65, 66, 67, 937, 960] as $ord) {
|
||||
$stack->addSubsetChar('freesans', $ord);
|
||||
}
|
||||
|
||||
$encrypt = $this->createEncrypt();
|
||||
$output = new \Com\Tecnick\Pdf\Font\Output($stack->getFonts(), $objnum, $encrypt, null);
|
||||
$out = $output->getFontsBlock();
|
||||
|
||||
$this->assertStringNotContainsString('/Registry () /Ordering ()', $out);
|
||||
$this->assertStringContainsString('/Registry (Adobe) /Ordering (Identity) /Supplement 0', $out);
|
||||
|
||||
$matches = [];
|
||||
\preg_match_all('/\\/Length1\\s+(\\d+)/', $out, $matches);
|
||||
$lengthMatches = $matches[1] ?? [];
|
||||
$lengths = \array_map('intval', $lengthMatches);
|
||||
$this->assertNotEmpty($lengths);
|
||||
$this->assertGreaterThan(1000, \max($lengths));
|
||||
}
|
||||
|
||||
/**
|
||||
* @throws FileException
|
||||
* @throws FontException
|
||||
* @throws \RangeException
|
||||
* @throws \ReflectionException
|
||||
*/
|
||||
public function testSubsetCharMergePreservesUnicodeKeys(): void
|
||||
{
|
||||
$this->prepareTestEnvironment();
|
||||
$indir = \dirname(__DIR__) . '/util/vendor/tecnickcom/tc-font-mirror/';
|
||||
|
||||
$objnum = 1;
|
||||
$stack = new \Com\Tecnick\Pdf\Font\Stack(1);
|
||||
new \Com\Tecnick\Pdf\Font\Import($indir . 'freefont/FreeSans.ttf');
|
||||
$stack->add($objnum, 'freesans', '', '', true);
|
||||
|
||||
$fonts = $stack->getFonts();
|
||||
if (!isset($fonts['freesans'])) {
|
||||
$this->fail('Expected freesans font data');
|
||||
}
|
||||
|
||||
$base = $fonts['freesans'];
|
||||
$base['key'] = 'freesans_dup';
|
||||
$base['i'] += 1000;
|
||||
$base['n'] += 1000;
|
||||
$base['subsetchars'] = [8776 => true, 9999 => false];
|
||||
$primary = $fonts['freesans'];
|
||||
$primary['subsetchars'] = [960 => true];
|
||||
|
||||
$fonts = \array_replace($fonts, [
|
||||
'freesans' => $primary,
|
||||
'freesans_dup' => $base,
|
||||
]);
|
||||
|
||||
$encrypt = $this->createEncrypt();
|
||||
$output = new \Com\Tecnick\Pdf\Font\Output($fonts, $objnum, $encrypt, null);
|
||||
|
||||
$ref = new \ReflectionClass($output);
|
||||
$prop = $ref->getProperty('subchars');
|
||||
/** @var array<int, array<int, bool>> $subchars */
|
||||
$subchars = $prop->getValue($output);
|
||||
|
||||
$this->assertIsArray($subchars);
|
||||
$this->assertNotEmpty($subchars);
|
||||
$first = \array_values($subchars)[0] ?? null;
|
||||
$this->assertIsArray($first);
|
||||
$this->assertArrayHasKey(960, $first);
|
||||
$this->assertArrayHasKey(8776, $first);
|
||||
$this->assertArrayNotHasKey(9999, $first);
|
||||
}
|
||||
|
||||
public function testUniToCidPreservesNumericCidKeys(): void
|
||||
{
|
||||
$outfont = new OutputTestOutFont();
|
||||
|
||||
$font = $this->getFontTemplate();
|
||||
$font['cidinfo'] = [
|
||||
'Ordering' => 'Identity',
|
||||
'Registry' => 'Adobe',
|
||||
'Supplement' => 0,
|
||||
'uni2cid' => [960 => 853, 8776 => 3283],
|
||||
];
|
||||
$font['cw'] = [32 => 250, 960 => 500, 8776 => 600];
|
||||
$font['i'] = 1;
|
||||
$font['n'] = 1;
|
||||
$font['name'] = 'test';
|
||||
$font['subset'] = true;
|
||||
|
||||
$outfont->runUniToCid($font, 0);
|
||||
|
||||
$this->assertArrayHasKey(853, $font['cw']);
|
||||
$this->assertArrayHasKey(3283, $font['cw']);
|
||||
$this->assertSame(500, $font['cw'][853] ?? null);
|
||||
$this->assertSame(600, $font['cw'][3283] ?? null);
|
||||
}
|
||||
|
||||
/** @throws \Com\Tecnick\Pdf\Font\Exception */
|
||||
public function testGetFontFullPathThrowsForMissingFile(): void
|
||||
{
|
||||
$this->setupTest();
|
||||
$outfont = new OutputTestOutFont();
|
||||
$this->bcExpectException(\Com\Tecnick\Pdf\Font\Exception::class);
|
||||
$outfont->runGetFontFullPath($this->getFontPath(), 'not-here.bin');
|
||||
}
|
||||
|
||||
/**
|
||||
* @throws FileException
|
||||
* @throws FontException
|
||||
* @throws \ReflectionException
|
||||
*/
|
||||
public function testOutputRejectsSubsetFromPlainFileData(): void
|
||||
{
|
||||
$this->prepareTestEnvironment();
|
||||
$this->bcExpectException(\Com\Tecnick\Pdf\Font\Exception::class);
|
||||
|
||||
$tmpfile = $this->getFontPath() . 'plain-font.bin';
|
||||
\file_put_contents($tmpfile, 'not-gzip-data');
|
||||
|
||||
$font = $this->getFontTemplate();
|
||||
$font['key'] = 'plain';
|
||||
$font['name'] = 'Plain';
|
||||
$font['i'] = 1;
|
||||
$font['n'] = 1;
|
||||
$font['file'] = 'plain-font.bin';
|
||||
$font['dir'] = $this->getFontPath();
|
||||
$font['subset'] = true;
|
||||
$font['subsetchars'] = [65 => true];
|
||||
|
||||
$encrypt = $this->createEncrypt();
|
||||
\set_error_handler(static fn(): bool => true);
|
||||
try {
|
||||
new \Com\Tecnick\Pdf\Font\Output(['plain' => $font], 1, $encrypt, null);
|
||||
} finally {
|
||||
\restore_error_handler();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @throws FileException
|
||||
* @throws FontException
|
||||
* @throws \ReflectionException
|
||||
*/
|
||||
public function testOutputBuildsTrueTypeDefinitionWithDefaultEncoding(): void
|
||||
{
|
||||
$font = $this->getFontTemplate();
|
||||
$font['key'] = 'truetypefont';
|
||||
$font['name'] = 'TrueTypeFont';
|
||||
$font['type'] = 'TrueType';
|
||||
$font['i'] = 1;
|
||||
$font['n'] = 1;
|
||||
$font['enc'] = 'cp1252';
|
||||
$font['dw'] = 600;
|
||||
$font['cw'] = [32 => 250, 65 => 700];
|
||||
|
||||
$encrypt = $this->createEncrypt();
|
||||
$output = new \Com\Tecnick\Pdf\Font\Output(['truetypefont' => $font], 1, $encrypt, null);
|
||||
$block = $output->getFontsBlock();
|
||||
|
||||
$this->assertStringContainsString('/Subtype /TrueType', $block);
|
||||
$this->assertStringContainsString('/Encoding /WinAnsiEncoding', $block);
|
||||
}
|
||||
|
||||
public function testGetKeyValOutFormatsFloatValues(): void
|
||||
{
|
||||
$outfont = new OutputTestOutFont();
|
||||
$out = $outfont->runGetKeyValOut('ItalicAngle', 12.5);
|
||||
$this->assertSame(' /ItalicAngle 12.500000', $out);
|
||||
}
|
||||
|
||||
/**
|
||||
* @throws FileException
|
||||
* @throws FontException
|
||||
* @throws \ReflectionException
|
||||
*/
|
||||
public function testOutputBuildsCidFont0WhenGlyphOneIsNotDefined(): void
|
||||
{
|
||||
$font = $this->getFontTemplate();
|
||||
$font['key'] = 'cidfont0';
|
||||
$font['name'] = 'CIDFont0Test';
|
||||
$font['type'] = 'CIDFont0';
|
||||
$font['i'] = 1;
|
||||
$font['n'] = 1;
|
||||
$font['enc'] = 'Identity-H';
|
||||
$font['dw'] = 600;
|
||||
$font['cw'] = [32 => 500, 65 => 700];
|
||||
$font['cidinfo'] = [
|
||||
'Registry' => 'Adobe',
|
||||
'Ordering' => 'Identity',
|
||||
'Supplement' => 0,
|
||||
'uni2cid' => [],
|
||||
];
|
||||
|
||||
$encrypt = $this->createEncrypt();
|
||||
$output = new \Com\Tecnick\Pdf\Font\Output(['cidfont0' => $font], 1, $encrypt, null);
|
||||
$block = $output->getFontsBlock();
|
||||
|
||||
$this->assertStringContainsString('/Subtype /Type0', $block);
|
||||
$this->assertStringContainsString('/Subtype /CIDFontType0', $block);
|
||||
}
|
||||
|
||||
/**
|
||||
* Build a subset-enabled FreeSans font stack for cache tests.
|
||||
*
|
||||
* @return array<string, TFontData>
|
||||
*
|
||||
* @throws FileException
|
||||
* @throws FontException
|
||||
* @throws \RangeException
|
||||
*/
|
||||
private function buildSubsetFonts(int $objnum): array
|
||||
{
|
||||
$this->prepareTestEnvironment();
|
||||
$indir = \dirname(__DIR__) . '/util/vendor/tecnickcom/tc-font-mirror/';
|
||||
|
||||
$stack = new \Com\Tecnick\Pdf\Font\Stack(1);
|
||||
new \Com\Tecnick\Pdf\Font\Import($indir . 'freefont/FreeSans.ttf');
|
||||
$stack->add($objnum, 'freesans', '', '', true);
|
||||
|
||||
foreach ([32, 65, 66, 67, 937, 960] as $ord) {
|
||||
$stack->addSubsetChar('freesans', $ord);
|
||||
}
|
||||
|
||||
return $stack->getFonts();
|
||||
}
|
||||
|
||||
/**
|
||||
* @throws FileException
|
||||
* @throws FontException
|
||||
* @throws \RangeException
|
||||
* @throws \ReflectionException
|
||||
*/
|
||||
public function testSubsetCacheStoresOnMissAndReusesOnHit(): void
|
||||
{
|
||||
$objnum = 1;
|
||||
$fonts = $this->buildSubsetFonts($objnum);
|
||||
$cache = new SpyFontSubsetCache();
|
||||
$encrypt = $this->createEncrypt();
|
||||
|
||||
$firstObj = new \Com\Tecnick\Pdf\Font\Output($fonts, $objnum, $encrypt, null, $cache);
|
||||
$first = $firstObj->getFontsBlock();
|
||||
|
||||
$secondObj = new \Com\Tecnick\Pdf\Font\Output($fonts, $objnum, $encrypt, null, $cache);
|
||||
$second = $secondObj->getFontsBlock();
|
||||
|
||||
$this->assertSame($first, $second);
|
||||
$this->assertCount(1, $cache->store, 'subset should be stored exactly once');
|
||||
|
||||
$storedKey = \array_key_first($cache->store);
|
||||
$this->assertIsString($storedKey);
|
||||
$this->assertSame([$storedKey], $cache->setCalls, 'subset should be computed and stored exactly once');
|
||||
$this->assertSame(
|
||||
[$storedKey, $storedKey],
|
||||
$cache->getCalls,
|
||||
'cache should be consulted on every pass (miss then hit) for the same key',
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* @throws FileException
|
||||
* @throws FontException
|
||||
* @throws \RangeException
|
||||
* @throws \ReflectionException
|
||||
*/
|
||||
public function testSubsetCacheHitProducesIdenticalOutputToNoCache(): void
|
||||
{
|
||||
$objnum = 1;
|
||||
$fonts = $this->buildSubsetFonts($objnum);
|
||||
$encrypt = $this->createEncrypt();
|
||||
|
||||
$noCacheObj = new \Com\Tecnick\Pdf\Font\Output($fonts, $objnum, $encrypt, null, null);
|
||||
$noCache = $noCacheObj->getFontsBlock();
|
||||
|
||||
$cache = new SpyFontSubsetCache();
|
||||
// First pass populates the cache (miss), second pass reads from it (hit).
|
||||
new \Com\Tecnick\Pdf\Font\Output($fonts, $objnum, $encrypt, null, $cache);
|
||||
$hitObj = new \Com\Tecnick\Pdf\Font\Output($fonts, $objnum, $encrypt, null, $cache);
|
||||
$hit = $hitObj->getFontsBlock();
|
||||
|
||||
$this->assertSame($noCache, $hit, 'a cache hit must reproduce the no-cache output byte-for-byte');
|
||||
}
|
||||
|
||||
/**
|
||||
* @throws FileException
|
||||
* @throws FontException
|
||||
* @throws \ReflectionException
|
||||
*/
|
||||
public function testSubsetCacheKeyIsStableAndDiscriminating(): void
|
||||
{
|
||||
$this->setupTest();
|
||||
$encrypt = $this->createEncrypt();
|
||||
$output = new OutputTestOutput([], 1, $encrypt, null);
|
||||
|
||||
$font = $this->getFontTemplate();
|
||||
$font['platform_id'] = 3;
|
||||
$font['encoding_id'] = 1;
|
||||
$font['type'] = 'TrueTypeUnicode';
|
||||
$data = 'FONT-PROGRAM-BYTES';
|
||||
|
||||
$keyA = $output->runSubsetCacheKey($data, $font, [65 => true, 66 => true]);
|
||||
|
||||
$keyOrder = $output->runSubsetCacheKey($data, $font, [66 => true, 65 => true]);
|
||||
$this->assertSame($keyA, $keyOrder, 'char insertion order must not change the key');
|
||||
|
||||
$keyDisabled = $output->runSubsetCacheKey($data, $font, [65 => true, 66 => true, 67 => false]);
|
||||
$this->assertSame($keyA, $keyDisabled, 'disabled chars must not change the key');
|
||||
|
||||
$keyChars = $output->runSubsetCacheKey($data, $font, [65 => true]);
|
||||
$this->assertNotSame($keyA, $keyChars, 'a different char set must change the key');
|
||||
|
||||
$keyBytes = $output->runSubsetCacheKey('OTHER-BYTES', $font, [65 => true, 66 => true]);
|
||||
$this->assertNotSame($keyA, $keyBytes, 'different font bytes must change the key');
|
||||
|
||||
$fontAlt = $font;
|
||||
$fontAlt['encoding_id'] = 10;
|
||||
$keyCmap = $output->runSubsetCacheKey($data, $fontAlt, [65 => true, 66 => true]);
|
||||
$this->assertNotSame($keyA, $keyCmap, 'different cmap selection metrics must change the key');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* OutputTestOutFont.php
|
||||
*
|
||||
* @since 2011-05-23
|
||||
* @category Library
|
||||
* @package PdfFont
|
||||
* @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-font
|
||||
*
|
||||
* This file is part of tc-lib-pdf-font software library.
|
||||
*/
|
||||
|
||||
namespace Test;
|
||||
|
||||
/**
|
||||
* @phpstan-import-type TFontData from \Com\Tecnick\Pdf\Font\Load
|
||||
*/
|
||||
class OutputTestOutFont extends \Com\Tecnick\Pdf\Font\OutFont
|
||||
{
|
||||
/**
|
||||
* @param TFontData $font
|
||||
*/
|
||||
public function runUniToCid(array &$font, int $cidoffset): void
|
||||
{
|
||||
$this->uniToCid($font, $cidoffset);
|
||||
}
|
||||
|
||||
/**
|
||||
* @throws \Com\Tecnick\Pdf\Font\Exception
|
||||
*/
|
||||
public function runGetFontFullPath(string $fontdir, string $file): string
|
||||
{
|
||||
return $this->getFontFullPath($fontdir, $file);
|
||||
}
|
||||
|
||||
public function runGetKeyValOut(string $key, mixed $val): string
|
||||
{
|
||||
return $this->getKeyValOut($key, $val);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* OutputTestOutput.php
|
||||
*
|
||||
* @since 2026-06-16
|
||||
* @category Library
|
||||
* @package PdfFont
|
||||
* @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-font
|
||||
*
|
||||
* This file is part of tc-lib-pdf-font software library.
|
||||
*/
|
||||
|
||||
namespace Test;
|
||||
|
||||
/**
|
||||
* Test helper exposing protected Output members.
|
||||
*
|
||||
* @phpstan-import-type TFontData from \Com\Tecnick\Pdf\Font\Load
|
||||
*/
|
||||
class OutputTestOutput extends \Com\Tecnick\Pdf\Font\Output
|
||||
{
|
||||
/**
|
||||
* @param TFontData $font Extracted font metrics.
|
||||
* @param array<int, bool> $subchars Subset characters (charcode => enabled).
|
||||
*/
|
||||
public function runSubsetCacheKey(string $font_data, array $font, array $subchars): string
|
||||
{
|
||||
return $this->subsetCacheKey($font_data, $font, $subchars);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* SpyFontSubsetCache.php
|
||||
*
|
||||
* @since 2026-06-16
|
||||
* @category Library
|
||||
* @package PdfFont
|
||||
* @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-font
|
||||
*
|
||||
* This file is part of tc-lib-pdf-font software library.
|
||||
*/
|
||||
|
||||
namespace Test;
|
||||
|
||||
use Com\Tecnick\Pdf\Font\FontSubsetCacheInterface;
|
||||
|
||||
/**
|
||||
* In-memory FontSubsetCacheInterface implementation that records access for
|
||||
* assertions in the test-suite.
|
||||
*/
|
||||
class SpyFontSubsetCache implements FontSubsetCacheInterface
|
||||
{
|
||||
/**
|
||||
* Stored subset font programs keyed by cache key.
|
||||
*
|
||||
* @var array<string, string>
|
||||
*/
|
||||
public array $store = [];
|
||||
|
||||
/**
|
||||
* Keys requested via get(), in call order.
|
||||
*
|
||||
* @var array<int, string>
|
||||
*/
|
||||
public array $getCalls = [];
|
||||
|
||||
/**
|
||||
* Keys written via set(), in call order.
|
||||
*
|
||||
* @var array<int, string>
|
||||
*/
|
||||
public array $setCalls = [];
|
||||
|
||||
public function get(string $key): ?string
|
||||
{
|
||||
$this->getCalls[] = $key;
|
||||
|
||||
return $this->store[$key] ?? null;
|
||||
}
|
||||
|
||||
public function set(string $key, string $subsetFont): void
|
||||
{
|
||||
$this->setCalls[] = $key;
|
||||
$this->store[$key] = $subsetFont;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,485 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* StackTest.php
|
||||
*
|
||||
* @since 2011-05-23
|
||||
* @category Library
|
||||
* @package PdfFont
|
||||
* @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-font
|
||||
*
|
||||
* This file is part of tc-lib-pdf-font software library.
|
||||
*/
|
||||
|
||||
namespace Test;
|
||||
|
||||
use Com\Tecnick\File\Exception as FileException;
|
||||
use Com\Tecnick\Pdf\Font\Exception as FontException;
|
||||
|
||||
/**
|
||||
* Buffer Test
|
||||
*
|
||||
* @since 2011-05-23
|
||||
* @category Library
|
||||
* @package PdfFont
|
||||
* @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-font
|
||||
*
|
||||
* @SuppressWarnings("PHPMD.LongVariable")
|
||||
*/
|
||||
class StackTest extends TestUtil
|
||||
{
|
||||
private function prepareTestEnvironment(): void
|
||||
{
|
||||
parent::setupTest();
|
||||
}
|
||||
|
||||
/**
|
||||
* @throws FileException
|
||||
* @throws FontException
|
||||
* @throws \RangeException
|
||||
*/
|
||||
public function testStack(): void
|
||||
{
|
||||
$this->prepareTestEnvironment();
|
||||
$indir = \dirname(__DIR__) . '/util/vendor/tecnickcom/tc-font-mirror/';
|
||||
|
||||
$objnum = 1;
|
||||
$stack = new \Com\Tecnick\Pdf\Font\Stack(0.75, true, true, true);
|
||||
|
||||
new \Com\Tecnick\Pdf\Font\Import($indir . 'freefont/FreeSans.ttf');
|
||||
$cfont = $stack->insert($objnum, 'freesans', '', 12, -0.1, 0.9, '', null);
|
||||
$this->assertNotEmpty($cfont);
|
||||
$this->assertNotEmpty($cfont['cbbox']);
|
||||
|
||||
$this->bcAssertEqualsWithDelta([0.162, 0.0, 7.0308, 8.748], $stack->getCharBBox(65), 0.0001);
|
||||
|
||||
new \Com\Tecnick\Pdf\Font\Import($indir . 'pdfa/pfb/PDFATimes.pfb');
|
||||
$afont = $stack->insert($objnum, 'times', '', 14, 0.3, 1.2, '', null);
|
||||
$this->assertNotEmpty($afont);
|
||||
|
||||
new \Com\Tecnick\Pdf\Font\Import($indir . 'pdfa/pfb/PDFAHelveticaBoldOblique.pfb');
|
||||
$bfont = $stack->insert($objnum, 'helvetica', 'BIUDO', null, null, null, '', null);
|
||||
$this->assertNotEmpty($bfont);
|
||||
|
||||
$this->assertEquals("BT /F3 14.000000 Tf ET\r", $bfont['out']);
|
||||
$this->assertEquals('pdfahelveticaBI', $bfont['key']);
|
||||
$this->assertEquals('Type1', $bfont['type']);
|
||||
$this->bcAssertEqualsWithDelta(14, $bfont['size'], 0.0001);
|
||||
$this->bcAssertEqualsWithDelta(0.3, $bfont['spacing'], 0.0001);
|
||||
$this->bcAssertEqualsWithDelta(1.2, $bfont['stretching'], 0.0001);
|
||||
$this->bcAssertEqualsWithDelta(18.6667, $bfont['usize'], 0.0001);
|
||||
$this->bcAssertEqualsWithDelta(0.014, $bfont['cratio'], 0.0001);
|
||||
$this->bcAssertEqualsWithDelta(-1.554, $bfont['up'], 0.0001);
|
||||
$this->bcAssertEqualsWithDelta(0.966, $bfont['ut'], 0.0001);
|
||||
$this->bcAssertEqualsWithDelta(4.6704, $bfont['dw'], 0.0001);
|
||||
$this->bcAssertEqualsWithDelta(13.342, $bfont['ascent'], 0.0001);
|
||||
$this->bcAssertEqualsWithDelta(-3.08, $bfont['descent'], 0.0001);
|
||||
$this->bcAssertEqualsWithDelta(16.422, $bfont['height'], 0.0001);
|
||||
$this->bcAssertEqualsWithDelta(5.131, $bfont['midpoint'], 0.0001);
|
||||
$this->bcAssertEqualsWithDelta(10.136, $bfont['capheight'], 0.0001);
|
||||
$this->bcAssertEqualsWithDelta(7.56, $bfont['xheight'], 0.0001);
|
||||
$this->bcAssertEqualsWithDelta(9.492, $bfont['avgwidth'], 0.0001);
|
||||
$this->bcAssertEqualsWithDelta(16.8, $bfont['maxwidth'], 0.0001);
|
||||
$this->bcAssertEqualsWithDelta(4.6704, $bfont['missingwidth'], 0.0001);
|
||||
$this->bcAssertEqualsWithDelta([-1.092, -3.08, 18.5976, 13.342], $bfont['fbbox'], 0.0001);
|
||||
|
||||
$fkey = $stack->getCurrentFontKey();
|
||||
$this->assertEquals('pdfahelveticaBI', $fkey);
|
||||
|
||||
$font = $stack->getCurrentFont();
|
||||
$this->assertEquals($bfont, $font);
|
||||
|
||||
$this->assertTrue($stack->isCharDefined(65));
|
||||
$this->assertFalse($stack->isCharDefined(300));
|
||||
|
||||
$this->assertEquals(75, $stack->replaceChar(65, 75));
|
||||
$this->assertEquals(65, $stack->replaceChar(65, 300));
|
||||
|
||||
$this->assertEquals([0, 0, 0, 0], $stack->getCharBBox(300));
|
||||
|
||||
$this->bcAssertEqualsWithDelta(12.1296, $stack->getCharWidth(65), 0.0001);
|
||||
$this->bcAssertEqualsWithDelta(0, $stack->getCharWidth(173), 0.0001);
|
||||
$this->bcAssertEqualsWithDelta(4.6704, $stack->getCharWidth(300), 0.0001);
|
||||
|
||||
$uniarr = [65, 173, 300];
|
||||
$this->bcAssertEqualsWithDelta(17.52, $stack->getOrdArrWidth($uniarr), 0.0001);
|
||||
|
||||
$subs = [
|
||||
65 => [400, 75],
|
||||
173 => [76, 300],
|
||||
300 => [400, 77],
|
||||
];
|
||||
$this->assertEquals([65, 173, 77], $stack->replaceMissingChars($uniarr, $subs));
|
||||
|
||||
$font = $stack->popLastFont();
|
||||
$this->assertEquals($bfont, $font);
|
||||
|
||||
$font = $stack->getCurrentFont();
|
||||
$this->assertEquals($afont, $font);
|
||||
|
||||
$fkey = $stack->getCurrentFontKey();
|
||||
$this->assertEquals('pdfatimes', $fkey);
|
||||
|
||||
$type = $stack->getCurrentFontType();
|
||||
$this->assertEquals('Type1', $type);
|
||||
|
||||
$ftype = $stack->isCurrentUnicodeFont();
|
||||
$this->assertFalse($ftype);
|
||||
|
||||
$ftype = $stack->isCurrentByteFont();
|
||||
$this->assertTrue($ftype);
|
||||
|
||||
$uniarr = [65, 173, 300, 32, 65, 173, 300, 32, 65, 173, 300];
|
||||
$widths = $stack->getOrdArrDims($uniarr);
|
||||
$this->assertEquals(11, $widths['chars']);
|
||||
$this->assertEquals(2, $widths['spaces']);
|
||||
$this->bcAssertEqualsWithDelta(60.9384, $widths['totwidth'], 0.0001);
|
||||
$this->bcAssertEqualsWithDelta(8.76, $widths['totspacewidth'], 0.0001);
|
||||
$this->assertEquals(6, $widths['words']);
|
||||
|
||||
$split = $widths['split'][5] ?? null;
|
||||
$this->assertIsArray($split);
|
||||
$this->assertEquals(11, $split['pos']);
|
||||
$this->assertEquals(8203, $split['ord']);
|
||||
$this->assertEquals('BN', $split['septype']);
|
||||
$this->bcAssertEqualsWithDelta(4.92, $split['wordwidth'], 0.0001);
|
||||
$this->assertEquals(2, $split['spaces']);
|
||||
$this->bcAssertEqualsWithDelta(60.9384, $split['totwidth'], 0.0001);
|
||||
$this->bcAssertEqualsWithDelta(8.76, $split['totspacewidth'], 0.0001);
|
||||
|
||||
$outfont = $stack->getOutCurrentFont();
|
||||
$this->assertEquals("BT /F2 14.000000 Tf ET\r", $outfont);
|
||||
|
||||
$font = $stack->cloneFont($objnum, null, null, 13, 0.3, 0.7);
|
||||
$this->assertEquals(13, $font['size']);
|
||||
$this->assertEquals(0.3, $font['spacing']);
|
||||
$this->assertEquals(0.7, $font['stretching']);
|
||||
|
||||
$font = $stack->cloneFont($objnum, 0, 'BI', 17, 0.7, 1.3);
|
||||
$this->assertEquals('BI', $font['style']);
|
||||
$this->assertEquals(17, $font['size']);
|
||||
$this->assertEquals(0.7, $font['spacing']);
|
||||
$this->assertEquals(1.3, $font['stretching']);
|
||||
|
||||
$fname = $stack->getFontFamilyName('unknown');
|
||||
$this->assertEquals('freesansBI', $fname);
|
||||
|
||||
new \Com\Tecnick\Pdf\Font\Import($indir . 'pdfa/pfb/PDFACourier.pfb');
|
||||
$bfont = $stack->insert($objnum, 'courier', '', null, null, null, '', null);
|
||||
$this->assertNotEmpty($bfont);
|
||||
|
||||
$fname = $stack->getFontFamilyName('freesans');
|
||||
$this->assertEquals('freesans', $fname);
|
||||
|
||||
$fname = $stack->getFontFamilyName('cursive');
|
||||
$this->assertEquals('pdfatimes', $fname);
|
||||
|
||||
$fname = $stack->getFontFamilyName('unknown');
|
||||
$this->assertEquals('pdfacourier', $fname);
|
||||
}
|
||||
|
||||
/** @throws FontException */
|
||||
public function testEmptyStack(): void
|
||||
{
|
||||
$this->bcExpectException(\Com\Tecnick\Pdf\Font\Exception::class);
|
||||
$this->prepareTestEnvironment();
|
||||
$stack = new \Com\Tecnick\Pdf\Font\Stack(1);
|
||||
$stack->popLastFont();
|
||||
}
|
||||
|
||||
/** @throws FontException */
|
||||
public function testStackMissingFont(): void
|
||||
{
|
||||
$this->bcExpectException(\Com\Tecnick\Pdf\Font\Exception::class);
|
||||
$this->prepareTestEnvironment();
|
||||
$stack = new \Com\Tecnick\Pdf\Font\Stack(1);
|
||||
$objnum = 1;
|
||||
$stack->insert($objnum, 'missing');
|
||||
}
|
||||
|
||||
/**
|
||||
* @throws FileException
|
||||
* @throws FontException
|
||||
* @throws \RangeException
|
||||
*/
|
||||
public function testHasCurrentFont(): void
|
||||
{
|
||||
$this->prepareTestEnvironment();
|
||||
$indir = \dirname(__DIR__) . '/util/vendor/tecnickcom/tc-font-mirror/';
|
||||
|
||||
$objnum = 1;
|
||||
$stack = new \Com\Tecnick\Pdf\Font\Stack(0.75, true, true, true);
|
||||
$this->assertFalse($stack->hasCurrentFont());
|
||||
$this->assertSame(0, $stack->getStackSize());
|
||||
$this->assertSame(-1, $stack->getCurrentFontIndex());
|
||||
|
||||
new \Com\Tecnick\Pdf\Font\Import($indir . 'freefont/FreeSans.ttf');
|
||||
$font = $stack->insert($objnum, 'freesans', '', 12);
|
||||
$this->assertTrue($stack->hasCurrentFont());
|
||||
$this->assertSame(1, $stack->getStackSize());
|
||||
$this->assertSame(0, $stack->getCurrentFontIndex());
|
||||
$this->assertSame($font['out'], $stack->getOutCurrentFont());
|
||||
|
||||
$stack->cloneFont($objnum, null, null, 13);
|
||||
$this->assertSame(2, $stack->getStackSize());
|
||||
$this->assertSame(1, $stack->getCurrentFontIndex());
|
||||
|
||||
$stack->popLastFont();
|
||||
$this->assertTrue($stack->hasCurrentFont());
|
||||
$this->assertSame(1, $stack->getStackSize());
|
||||
$this->assertSame(0, $stack->getCurrentFontIndex());
|
||||
|
||||
$stack->popLastFont();
|
||||
$this->assertFalse($stack->hasCurrentFont());
|
||||
$this->assertSame(0, $stack->getStackSize());
|
||||
$this->assertSame(-1, $stack->getCurrentFontIndex());
|
||||
}
|
||||
|
||||
/**
|
||||
* Only the paragraph and segment separators, the whitespace and the boundary neutrals
|
||||
* split words. The type table lists the code points whose bidirectional type is not L,
|
||||
* so the letters that are missing from it must not be taken as separators.
|
||||
*
|
||||
* @throws FileException
|
||||
* @throws FontException
|
||||
* @throws \RangeException
|
||||
*/
|
||||
public function testWordSplitOnSeparatorsOnly(): void
|
||||
{
|
||||
$this->prepareTestEnvironment();
|
||||
$indir = \dirname(__DIR__) . '/util/vendor/tecnickcom/tc-font-mirror/';
|
||||
$objnum = 1;
|
||||
|
||||
$stack = new \Com\Tecnick\Pdf\Font\Stack(0.75, true, true, true);
|
||||
new \Com\Tecnick\Pdf\Font\Import($indir . 'freefont/FreeSans.ttf');
|
||||
$stack->insert($objnum, 'freesans', '', 12, 0, 1, '', null);
|
||||
|
||||
// LATIN A, CJK UNIFIED IDEOGRAPH-4E00, HANGUL SYLLABLE GA and DEVANAGARI KA are
|
||||
// all of bidirectional type L: one word, closed by the trailing ZWSP.
|
||||
$widths = $stack->getOrdArrDims([0x41, 0x4E00, 0xAC00, 0x0915]);
|
||||
$this->assertEquals(4, $widths['chars']);
|
||||
$this->assertEquals(0, $widths['spaces']);
|
||||
$this->assertEquals(1, $widths['words']);
|
||||
|
||||
// The same letters around a space: two words plus the trailing ZWSP.
|
||||
$widths = $stack->getOrdArrDims([0x41, 0x4E00, 0x20, 0xAC00, 0x0915]);
|
||||
$this->assertEquals(1, $widths['spaces']);
|
||||
$this->assertEquals(2, $widths['words']);
|
||||
$split = $widths['split'][0] ?? null;
|
||||
$this->assertIsArray($split);
|
||||
$this->assertEquals('WS', $split['septype']);
|
||||
}
|
||||
|
||||
/**
|
||||
* @throws FileException
|
||||
* @throws FontException
|
||||
* @throws \RangeException
|
||||
*/
|
||||
public function testUnicodeOrdAddedToSubsetChars(): void
|
||||
{
|
||||
$this->prepareTestEnvironment();
|
||||
$indir = \dirname(__DIR__) . '/util/vendor/tecnickcom/tc-font-mirror/';
|
||||
$objnum = 1;
|
||||
|
||||
$stack = new \Com\Tecnick\Pdf\Font\Stack(0.75, true, true, true);
|
||||
new \Com\Tecnick\Pdf\Font\Import($indir . 'freefont/FreeSans.ttf');
|
||||
$stack->insert($objnum, 'freesans', '', 12, 0, 1, '', true);
|
||||
|
||||
// Use pi and almost-equal to ensure non-latin BMP code points are tracked.
|
||||
$stack->getOrdArrDims([960, 8776]);
|
||||
|
||||
$fonts = $stack->getFonts();
|
||||
$fkey = $stack->getCurrentFontKey();
|
||||
$currentFont = $fonts[$fkey] ?? null;
|
||||
$this->assertIsArray($currentFont);
|
||||
$this->assertArrayHasKey(960, $currentFont['subsetchars']);
|
||||
$this->assertArrayHasKey(8776, $currentFont['subsetchars']);
|
||||
}
|
||||
|
||||
/**
|
||||
* @throws FileException
|
||||
* @throws FontException
|
||||
* @throws \RangeException
|
||||
*/
|
||||
public function testFractionalFontSize(): void
|
||||
{
|
||||
$this->prepareTestEnvironment();
|
||||
$indir = \dirname(__DIR__) . '/util/vendor/tecnickcom/tc-font-mirror/';
|
||||
|
||||
$objnum = 1;
|
||||
$stack = new \Com\Tecnick\Pdf\Font\Stack(0.75, true, true, true);
|
||||
|
||||
new \Com\Tecnick\Pdf\Font\Import($indir . 'freefont/FreeSans.ttf');
|
||||
$font = $stack->insert($objnum, 'freesans', '', 10.5);
|
||||
|
||||
$this->bcAssertEqualsWithDelta(10.5, $font['size'], 0.0001);
|
||||
$this->assertEquals("BT /F1 10.500000 Tf ET\r", $font['out']);
|
||||
|
||||
$clone = $stack->cloneFont($objnum, null, null, 11.25);
|
||||
|
||||
$this->bcAssertEqualsWithDelta(11.25, $clone['size'], 0.0001);
|
||||
$this->assertEquals("BT /F1 11.250000 Tf ET\r", $clone['out']);
|
||||
}
|
||||
|
||||
/**
|
||||
* Cloning a font with a different style must load the definition file of the
|
||||
* requested style, not reuse the one of the source font (issue #19).
|
||||
*
|
||||
* @throws FileException
|
||||
* @throws FontException
|
||||
* @throws \RangeException
|
||||
*/
|
||||
public function testCloneFontLoadsStyledDefinitionFile(): void
|
||||
{
|
||||
$this->prepareTestEnvironment();
|
||||
$indir = \dirname(__DIR__) . '/util/vendor/tecnickcom/tc-font-mirror/';
|
||||
$objnum = 1;
|
||||
|
||||
$stack = new \Com\Tecnick\Pdf\Font\Stack(0.75, true, true, true);
|
||||
new \Com\Tecnick\Pdf\Font\Import($indir . 'freefont/FreeSans.ttf');
|
||||
new \Com\Tecnick\Pdf\Font\Import($indir . 'freefont/FreeSansBold.ttf');
|
||||
new \Com\Tecnick\Pdf\Font\Import($indir . 'freefont/FreeSansBoldOblique.ttf');
|
||||
|
||||
$regular = $stack->insert($objnum, 'freesans', '', 12);
|
||||
$this->assertEquals('freesans', $regular['key']);
|
||||
|
||||
// the bold style has never been loaded before: the clone must load it from
|
||||
// the bold definition file found in the same directory of the source font
|
||||
$clone = $stack->cloneFont($objnum, null, 'B', 12);
|
||||
$this->assertEquals('freesansB', $clone['key']);
|
||||
$this->assertEquals('B', $clone['style']);
|
||||
|
||||
$font = $stack->getFont('freesansB');
|
||||
$this->assertEquals('FreeSansBold', $font['name']);
|
||||
$this->assertEquals('freesansb.json', \basename($font['ifile']));
|
||||
$this->assertFalse($font['fakestyle']);
|
||||
|
||||
// the real bold glyphs are wider than the regular ones
|
||||
$regularWidth = $regular['cw'][65] ?? 0.0;
|
||||
$cloneWidth = $clone['cw'][65] ?? 0.0;
|
||||
$this->assertGreaterThan(0.0, $regularWidth);
|
||||
$this->assertGreaterThan($regularWidth, $cloneWidth);
|
||||
|
||||
// decoration-only style letters must be ignored when resolving the file
|
||||
$clone = $stack->cloneFont($objnum, 0, 'BIUDO', 14);
|
||||
$this->assertEquals('freesansBI', $clone['key']);
|
||||
$this->assertEquals('BIUDO', $clone['style']);
|
||||
|
||||
$font = $stack->getFont('freesansBI');
|
||||
$this->assertEquals('FreeSansBoldOblique', $font['name']);
|
||||
$this->assertEquals('freesansbi.json', \basename($font['ifile']));
|
||||
$this->assertFalse($font['fakestyle']);
|
||||
}
|
||||
|
||||
/**
|
||||
* Cloning a font with a different style whose definition file does not exist
|
||||
* must fall back to the autodetection with the artificial style emulation.
|
||||
*
|
||||
* @throws FileException
|
||||
* @throws FontException
|
||||
* @throws \RangeException
|
||||
*/
|
||||
public function testCloneFontFallsBackToArtificialStyleWhenStyledFileIsMissing(): void
|
||||
{
|
||||
$this->prepareTestEnvironment();
|
||||
$indir = \dirname(__DIR__) . '/util/vendor/tecnickcom/tc-font-mirror/';
|
||||
$objnum = 1;
|
||||
|
||||
$stack = new \Com\Tecnick\Pdf\Font\Stack(0.75, true, true, true);
|
||||
new \Com\Tecnick\Pdf\Font\Import($indir . 'freefont/FreeSans.ttf');
|
||||
|
||||
$regular = $stack->insert($objnum, 'freesans', '', 12);
|
||||
$clone = $stack->cloneFont($objnum, null, 'B', 12);
|
||||
$this->assertEquals('freesansB', $clone['key']);
|
||||
|
||||
$font = $stack->getFont('freesansB');
|
||||
$this->assertEquals('freesans.json', \basename($font['ifile']));
|
||||
$this->assertTrue($font['fakestyle']);
|
||||
$this->assertTrue($font['mode']['bold']);
|
||||
|
||||
// artificial bold reuses the regular glyph widths
|
||||
$regularWidth = $regular['cw'][65] ?? 0.0;
|
||||
$cloneWidth = $clone['cw'][65] ?? 0.0;
|
||||
$this->assertGreaterThan(0.0, $regularWidth);
|
||||
$this->bcAssertEqualsWithDelta($regularWidth, $cloneWidth, 0.0001);
|
||||
}
|
||||
|
||||
/**
|
||||
* @throws FileException
|
||||
* @throws FontException
|
||||
* @throws \RangeException
|
||||
*/
|
||||
public function testCloneFontRejectsOutOfRangeIndex(): void
|
||||
{
|
||||
$this->prepareTestEnvironment();
|
||||
$indir = \dirname(__DIR__) . '/util/vendor/tecnickcom/tc-font-mirror/';
|
||||
$objnum = 1;
|
||||
|
||||
$stack = new \Com\Tecnick\Pdf\Font\Stack(1);
|
||||
new \Com\Tecnick\Pdf\Font\Import($indir . 'core/Helvetica.afm');
|
||||
$stack->insert($objnum, 'helvetica');
|
||||
|
||||
$this->bcExpectException(\Com\Tecnick\Pdf\Font\Exception::class);
|
||||
$stack->cloneFont($objnum, 99);
|
||||
}
|
||||
|
||||
/**
|
||||
* @throws FileException
|
||||
* @throws FontException
|
||||
* @throws \RangeException
|
||||
*/
|
||||
public function testReplaceMissingCharsKeepsOriginalWhenNoSubstitutesProvided(): void
|
||||
{
|
||||
$this->prepareTestEnvironment();
|
||||
$indir = \dirname(__DIR__) . '/util/vendor/tecnickcom/tc-font-mirror/';
|
||||
$objnum = 1;
|
||||
|
||||
$stack = new \Com\Tecnick\Pdf\Font\Stack(1);
|
||||
new \Com\Tecnick\Pdf\Font\Import($indir . 'core/Helvetica.afm');
|
||||
$stack->insert($objnum, 'helvetica');
|
||||
|
||||
$this->assertSame([400], $stack->replaceMissingChars([400], []));
|
||||
}
|
||||
|
||||
/** @throws FontException */
|
||||
public function testGetFontFamilyNameRejectsEmptyString(): void
|
||||
{
|
||||
$this->prepareTestEnvironment();
|
||||
$stack = new \Com\Tecnick\Pdf\Font\Stack(1);
|
||||
|
||||
$this->bcExpectException(\Com\Tecnick\Pdf\Font\Exception::class);
|
||||
$stack->getFontFamilyName('');
|
||||
}
|
||||
|
||||
/** @throws FontException */
|
||||
public function testGetCharWidthFailsWithoutCurrentFont(): void
|
||||
{
|
||||
$this->prepareTestEnvironment();
|
||||
$stack = new \Com\Tecnick\Pdf\Font\Stack(1);
|
||||
|
||||
$this->bcExpectException(\Com\Tecnick\Pdf\Font\Exception::class);
|
||||
$stack->getCharWidth(65);
|
||||
}
|
||||
|
||||
/** @throws FontException */
|
||||
public function testMalformedCharBoxDataIsIgnored(): void
|
||||
{
|
||||
$this->prepareTestEnvironment();
|
||||
$objnum = 1;
|
||||
$stack = new \Com\Tecnick\Pdf\Font\Stack(1);
|
||||
|
||||
\file_put_contents(
|
||||
$this->getFontPath() . 'badbbox.json',
|
||||
'{"type":"Type1","desc":{"FontBBox":"[0 0 0 0]"},"cw":{"65":400},"cbbox":{"65":[1,2,3]}}',
|
||||
);
|
||||
|
||||
$stack->insert($objnum, 'badbbox', '', null, null, null, $this->getFontPath() . 'badbbox.json', null);
|
||||
$this->assertSame([0.0, 0.0, 0.0, 0.0], $stack->getCharBBox(65));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,138 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* StackUnicodeWidthTest.php
|
||||
*
|
||||
* @since 2026-05-05
|
||||
* @category Library
|
||||
* @package PdfFont
|
||||
* @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-font
|
||||
*
|
||||
* This file is part of tc-lib-pdf-font software library.
|
||||
*/
|
||||
|
||||
namespace Test;
|
||||
|
||||
use Com\Tecnick\File\Exception as FileException;
|
||||
use Com\Tecnick\Pdf\Font\Exception as FontException;
|
||||
use Com\Tecnick\Pdf\Font\Import;
|
||||
use Com\Tecnick\Pdf\Font\Stack;
|
||||
|
||||
/**
|
||||
* Verifies that Stack::getCharWidth() resolves widths for non-ASCII Unicode
|
||||
* codepoints via the cwu table populated during Core font import.
|
||||
*/
|
||||
class StackUnicodeWidthTest extends TestUtil
|
||||
{
|
||||
private const HELVETICA_AFM = __DIR__ . '/../util/vendor/tecnickcom/tc-font-mirror/core/Helvetica.afm';
|
||||
|
||||
private function prepareTestEnvironment(): void
|
||||
{
|
||||
parent::setupTest();
|
||||
}
|
||||
|
||||
private function fontPath(): string
|
||||
{
|
||||
return parent::getFontPath();
|
||||
}
|
||||
|
||||
/**
|
||||
* @throws FileException
|
||||
* @throws FontException
|
||||
* @throws \RangeException
|
||||
*/
|
||||
private function loadHelveticaStack(): Stack
|
||||
{
|
||||
$this->prepareTestEnvironment();
|
||||
new Import((string) \realpath(self::HELVETICA_AFM), $this->fontPath());
|
||||
$objnum = 1;
|
||||
$stack = new Stack(0.75, true, true, false);
|
||||
$stack->insert($objnum, 'helvetica', '', 10);
|
||||
return $stack;
|
||||
}
|
||||
|
||||
/**
|
||||
* @throws FileException
|
||||
* @throws FontException
|
||||
* @throws \RangeException
|
||||
*/
|
||||
public function testStackResolvesEmdashByUnicode(): void
|
||||
{
|
||||
$stack = $this->loadHelveticaStack();
|
||||
// em-dash U+2014 → AFM width 1000, at 10pt with stretching=1: 1000 * (10/1000) * 1 = 10.0
|
||||
$this->bcAssertEqualsWithDelta(10.0, $stack->getCharWidth(0x2014), 0.001);
|
||||
}
|
||||
|
||||
/**
|
||||
* @throws FileException
|
||||
* @throws FontException
|
||||
* @throws \RangeException
|
||||
*/
|
||||
public function testStackResolvesEndashByUnicode(): void
|
||||
{
|
||||
$stack = $this->loadHelveticaStack();
|
||||
// en-dash U+2013 → AFM width 556
|
||||
$this->bcAssertEqualsWithDelta(5.56, $stack->getCharWidth(0x2013), 0.001);
|
||||
}
|
||||
|
||||
/**
|
||||
* @throws FileException
|
||||
* @throws FontException
|
||||
* @throws \RangeException
|
||||
*/
|
||||
public function testStackResolvesBulletByUnicode(): void
|
||||
{
|
||||
$stack = $this->loadHelveticaStack();
|
||||
// bullet U+2022 → AFM width 350
|
||||
$this->bcAssertEqualsWithDelta(3.5, $stack->getCharWidth(0x2022), 0.001);
|
||||
}
|
||||
|
||||
/**
|
||||
* @throws FileException
|
||||
* @throws FontException
|
||||
* @throws \RangeException
|
||||
*/
|
||||
public function testStackResolvesEuroByUnicode(): void
|
||||
{
|
||||
$stack = $this->loadHelveticaStack();
|
||||
// Euro U+20AC → AFM width 556
|
||||
$this->bcAssertEqualsWithDelta(5.56, $stack->getCharWidth(0x20AC), 0.001);
|
||||
}
|
||||
|
||||
/**
|
||||
* @throws FileException
|
||||
* @throws FontException
|
||||
* @throws \RangeException
|
||||
*/
|
||||
public function testStackResolvesSpaceByCodepoint(): void
|
||||
{
|
||||
$stack = $this->loadHelveticaStack();
|
||||
// space U+0020 → AFM width 278 (sanity check, no regression)
|
||||
$this->bcAssertEqualsWithDelta(2.78, $stack->getCharWidth(0x20), 0.001);
|
||||
}
|
||||
|
||||
/**
|
||||
* @throws FileException
|
||||
* @throws FontException
|
||||
* @throws \RangeException
|
||||
*/
|
||||
public function testStackReturnZeroForShy(): void
|
||||
{
|
||||
$stack = $this->loadHelveticaStack();
|
||||
$this->assertSame(0.0, $stack->getCharWidth(0xAD));
|
||||
}
|
||||
|
||||
/**
|
||||
* @throws FileException
|
||||
* @throws FontException
|
||||
* @throws \RangeException
|
||||
*/
|
||||
public function testStackReturnZeroForZwsp(): void
|
||||
{
|
||||
$stack = $this->loadHelveticaStack();
|
||||
$this->assertSame(0.0, $stack->getCharWidth(0x200B));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,467 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* SubsetTest.php
|
||||
*
|
||||
* @since 2026-05-01
|
||||
* @category Library
|
||||
* @package PdfFont
|
||||
* @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-font
|
||||
*
|
||||
* This file is part of tc-lib-pdf-font software library.
|
||||
*/
|
||||
|
||||
namespace Test;
|
||||
|
||||
/**
|
||||
* Subset Test
|
||||
*
|
||||
* @since 2026-05-01
|
||||
* @category Library
|
||||
* @package PdfFont
|
||||
* @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-font
|
||||
*/
|
||||
class SubsetTest extends TestUtil
|
||||
{
|
||||
private function setProp(object $obj, string $name, mixed $value): void
|
||||
{
|
||||
$prop = new \ReflectionProperty($obj, $name);
|
||||
$prop->setValue($obj, $value);
|
||||
}
|
||||
|
||||
/** @return array<array-key, mixed> */
|
||||
private function getDefaultFdt(): array
|
||||
{
|
||||
$ref = new \ReflectionClass(\Com\Tecnick\Pdf\Font\Subset::class);
|
||||
$prop = $ref->getProperty('fdt');
|
||||
$instance = $ref->newInstanceWithoutConstructor();
|
||||
|
||||
return (static fn(mixed $value): array => \is_array($value) ? $value : [])($prop->getValue($instance));
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<array-key, mixed> $table
|
||||
*
|
||||
* @return array<array-key, mixed>
|
||||
*/
|
||||
private function getTableRecord(array $table, string $tag): array
|
||||
{
|
||||
if (!isset($table[$tag]) || !\is_array($table[$tag])) {
|
||||
$this->fail('Missing or invalid table record: ' . $tag);
|
||||
}
|
||||
|
||||
return $table[$tag];
|
||||
}
|
||||
|
||||
/** @param array<array-key, mixed> $table */
|
||||
private function getTableRecordString(array $table, string $tag, string $field): string
|
||||
{
|
||||
$record = $this->getTableRecord($table, $tag);
|
||||
if (!isset($record[$field]) || !\is_string($record[$field])) {
|
||||
$this->fail('Missing or invalid table string field: ' . $tag . '.' . $field);
|
||||
}
|
||||
|
||||
return $record[$field];
|
||||
}
|
||||
|
||||
/** @param array<array-key, mixed> $table */
|
||||
private function getTableRecordInt(array $table, string $tag, string $field): int
|
||||
{
|
||||
$record = $this->getTableRecord($table, $tag);
|
||||
if (!isset($record[$field]) || !\is_int($record[$field])) {
|
||||
$this->fail('Missing or invalid table int field: ' . $tag . '.' . $field);
|
||||
}
|
||||
|
||||
return $record[$field];
|
||||
}
|
||||
|
||||
/** @throws \Com\Tecnick\Pdf\Font\Exception */
|
||||
public function testTableChecksumPadsTrailingBytes(): void
|
||||
{
|
||||
$subset = new class() extends \Com\Tecnick\Pdf\Font\Subset {
|
||||
public function __construct() {}
|
||||
|
||||
/** @throws \Com\Tecnick\Pdf\Font\Exception */
|
||||
public function checksum(string $table, int $length): int
|
||||
{
|
||||
return $this->getTableChecksum($table, $length);
|
||||
}
|
||||
};
|
||||
|
||||
// 3-byte table must be zero-padded to a 4-byte word before summing.
|
||||
$this->assertSame(0x01020300, $subset->checksum("\x01\x02\x03", 3));
|
||||
}
|
||||
|
||||
/** @throws \Com\Tecnick\Pdf\Font\Exception */
|
||||
public function testTableChecksumHandlesMixedFullAndPartialWords(): void
|
||||
{
|
||||
$subset = new class() extends \Com\Tecnick\Pdf\Font\Subset {
|
||||
public function __construct() {}
|
||||
|
||||
/** @throws \Com\Tecnick\Pdf\Font\Exception */
|
||||
public function checksum(string $table, int $length): int
|
||||
{
|
||||
return $this->getTableChecksum($table, $length);
|
||||
}
|
||||
};
|
||||
|
||||
$table = "\x11\x22\x33\x44\x55\x66\x77";
|
||||
// 0x11223344 + 0x55667700, modulo 2^32
|
||||
$this->assertSame(0x6688AA44, $subset->checksum($table, 7));
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// removeUnusedTables
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
public function testRemoveUnusedTablesDropsUnknownTableTags(): void
|
||||
{
|
||||
// Build an anonymous subclass that exposes removeUnusedTables and lets us
|
||||
// inspect the resulting fdt without running the full constructor chain.
|
||||
$subset = new class() extends \Com\Tecnick\Pdf\Font\Subset {
|
||||
public function __construct() {}
|
||||
|
||||
public function run(): void
|
||||
{
|
||||
$this->removeUnusedTables();
|
||||
}
|
||||
|
||||
/** @return array<string, mixed> */
|
||||
public function getTable(): array
|
||||
{
|
||||
return $this->fdt['table'];
|
||||
}
|
||||
};
|
||||
|
||||
// A font binary with 8 bytes of head data (for substr to not be empty)
|
||||
$font = str_repeat("\x00", 64);
|
||||
$this->setProp($subset, 'font', $font);
|
||||
$this->setProp($subset, 'offset', 12);
|
||||
|
||||
// Provide two tables: 'head' (known → kept) and 'xxxx' (unknown → removed)
|
||||
$this->setProp($subset, 'fdt', array_merge($this->getDefaultFdt(), [
|
||||
'table' => [
|
||||
'head' => ['offset' => 0, 'length' => 8, 'checkSum' => 0, 'data' => ''],
|
||||
'xxxx' => ['offset' => 0, 'length' => 8, 'checkSum' => 0, 'data' => ''],
|
||||
],
|
||||
]));
|
||||
|
||||
$subset->run();
|
||||
|
||||
$table = $subset->getTable();
|
||||
$this->assertArrayHasKey('head', $table);
|
||||
$this->assertArrayNotHasKey('xxxx', $table);
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// addProcessedTables
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
public function testAddProcessedTablesBuildsLocaAndGlyfFromSubsetGlyphs(): void
|
||||
{
|
||||
$subset = new class() extends \Com\Tecnick\Pdf\Font\Subset {
|
||||
public function __construct() {}
|
||||
|
||||
public function run(): void
|
||||
{
|
||||
$this->addProcessedTables();
|
||||
}
|
||||
|
||||
/** @return array<string, mixed> */
|
||||
public function getTable(): array
|
||||
{
|
||||
return $this->fdt['table'];
|
||||
}
|
||||
};
|
||||
|
||||
// Font data: 12 bytes (glyf table at offset 0, 12 bytes of raw glyph data)
|
||||
$font = str_repeat("\xAB", 12);
|
||||
$this->setProp($subset, 'font', $font);
|
||||
$this->setProp($subset, 'offset', 0);
|
||||
|
||||
// subglyphs: only glyph 0 is in the subset
|
||||
$this->setProp($subset, 'subglyphs', [0 => true]);
|
||||
|
||||
// Inject the fdt state the method needs
|
||||
$this->setProp($subset, 'fdt', array_merge($this->getDefaultFdt(), [
|
||||
'tot_num_glyphs' => 2,
|
||||
'short_offset' => false, // long (Offset32) loca entries
|
||||
'indexToLoc' => [0 => 0, 1 => 8], // glyph 0 is 8 bytes
|
||||
'table' => [
|
||||
'glyf' => ['offset' => 0, 'length' => 12, 'checkSum' => 0, 'data' => ''],
|
||||
'loca' => ['offset' => 0, 'length' => 0, 'checkSum' => 0, 'data' => ''],
|
||||
],
|
||||
]));
|
||||
|
||||
$subset->run();
|
||||
|
||||
$table = $subset->getTable();
|
||||
|
||||
// loca must have been rebuilt
|
||||
$this->assertNotEmpty($this->getTableRecordString($table, 'loca', 'data'));
|
||||
// glyf must contain the extracted glyph bytes (8 bytes for glyph 0, padded to multiple of 4)
|
||||
$this->assertNotEmpty($this->getTableRecordString($table, 'glyf', 'data'));
|
||||
// The checksum must have been computed (non-zero for non-empty data)
|
||||
$this->assertNotSame(
|
||||
0,
|
||||
$this->getTableRecordInt($table, 'loca', 'checkSum') + $this->getTableRecordInt($table, 'glyf', 'checkSum'),
|
||||
);
|
||||
}
|
||||
|
||||
/** @throws \Com\Tecnick\Pdf\Font\Exception */
|
||||
public function testBuildSubsetFontKeepsTableDirectoryOffsetsIntact(): void
|
||||
{
|
||||
$subset = new class() extends \Com\Tecnick\Pdf\Font\Subset {
|
||||
public function __construct() {}
|
||||
|
||||
/** @throws \Com\Tecnick\Pdf\Font\Exception */
|
||||
public function run(): void
|
||||
{
|
||||
$this->buildSubsetFont();
|
||||
}
|
||||
|
||||
public function getSubFont(): string
|
||||
{
|
||||
return $this->subfont;
|
||||
}
|
||||
};
|
||||
|
||||
$this->setProp($subset, 'fdt', array_merge($this->getDefaultFdt(), [
|
||||
'table' => [
|
||||
// Offsets in fdt are relative to the 12-byte sfnt header.
|
||||
'head' => [
|
||||
'checkSum' => 0,
|
||||
'data' => str_repeat("\x00", 12),
|
||||
'length' => 12,
|
||||
'offset' => 12,
|
||||
],
|
||||
],
|
||||
]));
|
||||
|
||||
$subset->run();
|
||||
$subfont = $subset->getSubFont();
|
||||
|
||||
// With a single table, the table directory offset must point to byte 28
|
||||
// (12-byte sfnt header + 16-byte table record).
|
||||
$offset = \unpack('N', \substr($subfont, 20, 4));
|
||||
$this->assertIsArray($offset);
|
||||
$this->assertSame(28, $offset[1]);
|
||||
}
|
||||
|
||||
public function testAddProcessedTablesUsesNextAvailableLocaIndexWhenImmediateIsMissing(): void
|
||||
{
|
||||
$subset = new class() extends \Com\Tecnick\Pdf\Font\Subset {
|
||||
public function __construct() {}
|
||||
|
||||
public function run(): void
|
||||
{
|
||||
$this->addProcessedTables();
|
||||
}
|
||||
|
||||
/** @return array<string, mixed> */
|
||||
public function getTable(): array
|
||||
{
|
||||
return $this->fdt['table'];
|
||||
}
|
||||
};
|
||||
|
||||
// 8 bytes for glyph 0 followed by 8 bytes for glyph 1.
|
||||
$font = str_repeat("\xAB", 16);
|
||||
$this->setProp($subset, 'font', $font);
|
||||
$this->setProp($subset, 'offset', 0);
|
||||
$this->setProp($subset, 'subglyphs', [0 => true]);
|
||||
|
||||
// Simulate parser output where index 1 was removed as duplicate-empty marker.
|
||||
// Glyph 0 must still use index 2 as the closing boundary.
|
||||
$this->setProp($subset, 'fdt', array_merge($this->getDefaultFdt(), [
|
||||
'tot_num_glyphs' => 3,
|
||||
'short_offset' => false,
|
||||
'indexToLoc' => [0 => 0, 2 => 8, 3 => 16],
|
||||
'table' => [
|
||||
'glyf' => ['offset' => 0, 'length' => 16, 'checkSum' => 0, 'data' => ''],
|
||||
'loca' => ['offset' => 0, 'length' => 0, 'checkSum' => 0, 'data' => ''],
|
||||
],
|
||||
]));
|
||||
|
||||
$subset->run();
|
||||
$table = $subset->getTable();
|
||||
|
||||
// Glyph 0 must not be dropped just because index 1 is missing.
|
||||
$this->assertNotEmpty($this->getTableRecordString($table, 'glyf', 'data'));
|
||||
}
|
||||
|
||||
public function testAddCompositeGlyphsPreservesNumericGlyphIndexes(): void
|
||||
{
|
||||
$subset = new class() extends \Com\Tecnick\Pdf\Font\Subset {
|
||||
private bool $added = false;
|
||||
|
||||
public function __construct() {}
|
||||
|
||||
public function run(): void
|
||||
{
|
||||
$this->addCompositeGlyphs();
|
||||
}
|
||||
|
||||
/** @return array<int, bool> */
|
||||
public function getSubglyphs(): array
|
||||
{
|
||||
return $this->subglyphs;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<int, bool> $new_sga
|
||||
* @param int $key
|
||||
*
|
||||
* @return array<int, bool>
|
||||
*/
|
||||
protected function findCompositeGlyphs(array $new_sga, int $key): array
|
||||
{
|
||||
if (!$this->added) {
|
||||
$this->added = true;
|
||||
$new_sga[3283] = true;
|
||||
}
|
||||
|
||||
return $new_sga;
|
||||
}
|
||||
};
|
||||
|
||||
$this->setProp($subset, 'subglyphs', [853 => true]);
|
||||
|
||||
$subset->run();
|
||||
$subglyphs = $subset->getSubglyphs();
|
||||
|
||||
$this->assertArrayHasKey(853, $subglyphs);
|
||||
$this->assertArrayHasKey(3283, $subglyphs);
|
||||
}
|
||||
|
||||
public function testAddCompositeGlyphsSkipsDisabledDerivedGlyphs(): void
|
||||
{
|
||||
$subset = new class() extends \Com\Tecnick\Pdf\Font\Subset {
|
||||
private bool $first = true;
|
||||
|
||||
public function __construct() {}
|
||||
|
||||
public function run(): void
|
||||
{
|
||||
$this->addCompositeGlyphs();
|
||||
}
|
||||
|
||||
/** @return array<int, bool> */
|
||||
public function getSubglyphs(): array
|
||||
{
|
||||
return $this->subglyphs;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<int, bool> $new_sga
|
||||
* @param int $key
|
||||
*
|
||||
* @return array<int, bool>
|
||||
*/
|
||||
protected function findCompositeGlyphs(array $new_sga, int $key): array
|
||||
{
|
||||
if ($this->first) {
|
||||
$this->first = false;
|
||||
$new_sga[400] = false;
|
||||
$new_sga[401] = true;
|
||||
}
|
||||
|
||||
return $new_sga;
|
||||
}
|
||||
};
|
||||
|
||||
$this->setProp($subset, 'subglyphs', [100 => true]);
|
||||
$subset->run();
|
||||
|
||||
$subglyphs = $subset->getSubglyphs();
|
||||
$this->assertArrayHasKey(100, $subglyphs);
|
||||
$this->assertArrayHasKey(401, $subglyphs);
|
||||
$this->assertArrayNotHasKey(400, $subglyphs);
|
||||
}
|
||||
|
||||
public function testFindCompositeGlyphsParsesScaleAndTwoByTwoComponents(): void
|
||||
{
|
||||
$subset = new class() extends \Com\Tecnick\Pdf\Font\Subset {
|
||||
public function __construct() {}
|
||||
|
||||
/**
|
||||
* @param array<int, bool> $newSga
|
||||
*
|
||||
* @return array<int, bool>
|
||||
*/
|
||||
public function runFindCompositeGlyphs(array $newSga, int $key): array
|
||||
{
|
||||
return $this->findCompositeGlyphs($newSga, $key);
|
||||
}
|
||||
};
|
||||
|
||||
// Glyph header: numberOfContours = -1 (composite), 8 bytes bbox.
|
||||
// Component 1: MORE_COMPONENTS + WE_HAVE_AN_X_AND_Y_SCALE, glyph 5.
|
||||
// Component 2: WE_HAVE_A_TWO_BY_TWO, glyph 6.
|
||||
$font =
|
||||
"\xFF\xFF\x00\x00\x00\x00\x00\x00\x00\x00"
|
||||
. "\x00\x60\x00\x05\x00\x00\x00\x00\x00\x00"
|
||||
. "\x00\x80\x00\x06\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00";
|
||||
|
||||
$this->setProp($subset, 'font', $font);
|
||||
$this->setProp($subset, 'fbyte', new \Com\Tecnick\File\Byte($font));
|
||||
$this->setProp($subset, 'subglyphs', []);
|
||||
$this->setProp($subset, 'fdt', \array_replace_recursive($this->getDefaultFdt(), [
|
||||
'indexToLoc' => [0 => 0],
|
||||
'table' => [
|
||||
'glyf' => ['offset' => 0, 'length' => \strlen($font), 'checkSum' => 0, 'data' => ''],
|
||||
],
|
||||
]));
|
||||
|
||||
$newSga = $subset->runFindCompositeGlyphs([], 0);
|
||||
$this->assertArrayHasKey(5, $newSga);
|
||||
$this->assertArrayHasKey(6, $newSga);
|
||||
}
|
||||
|
||||
public function testAddProcessedTablesCreatesShortLocaAndPadsTables(): void
|
||||
{
|
||||
$subset = new class() extends \Com\Tecnick\Pdf\Font\Subset {
|
||||
public function __construct() {}
|
||||
|
||||
public function run(): void
|
||||
{
|
||||
$this->addProcessedTables();
|
||||
}
|
||||
|
||||
/** @return array<string, mixed> */
|
||||
public function getTable(): array
|
||||
{
|
||||
return $this->fdt['table'];
|
||||
}
|
||||
};
|
||||
|
||||
// One glyph with 3 bytes to force padding in both loca and glyf tables.
|
||||
$font = "\xAA\xBB\xCC";
|
||||
$this->setProp($subset, 'font', $font);
|
||||
$this->setProp($subset, 'offset', 0);
|
||||
$this->setProp($subset, 'subglyphs', [0 => true]);
|
||||
$this->setProp($subset, 'fdt', \array_replace_recursive($this->getDefaultFdt(), [
|
||||
'tot_num_glyphs' => 1,
|
||||
'short_offset' => true,
|
||||
'indexToLoc' => [0 => 0, 1 => 3],
|
||||
'table' => [
|
||||
'glyf' => ['offset' => 0, 'length' => 3, 'checkSum' => 0, 'data' => ''],
|
||||
],
|
||||
]));
|
||||
|
||||
$subset->run();
|
||||
$table = $subset->getTable();
|
||||
|
||||
$this->assertArrayHasKey('loca', $table);
|
||||
$this->assertSame(4, $this->getTableRecordInt($table, 'loca', 'length'));
|
||||
$this->assertSame(4, $this->getTableRecordInt($table, 'glyf', 'length'));
|
||||
$this->assertSame(0, \strlen($this->getTableRecordString($table, 'loca', 'data')) % 4);
|
||||
$this->assertSame(0, \strlen($this->getTableRecordString($table, 'glyf', 'data')) % 4);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* TestUtil.php
|
||||
*
|
||||
* @since 2020-12-19
|
||||
* @category Library
|
||||
* @package PdfFont
|
||||
* @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-font
|
||||
*
|
||||
* This file is part of tc-lib-color software library.
|
||||
*/
|
||||
|
||||
namespace Test;
|
||||
|
||||
use PHPUnit\Framework\TestCase;
|
||||
|
||||
/**
|
||||
* Web Color class test
|
||||
*
|
||||
* @since 2020-12-19
|
||||
* @category Library
|
||||
* @package PdfFont
|
||||
* @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-font
|
||||
*
|
||||
* @preserveGlobalState disabled
|
||||
* @runTestsInSeparateProcesses
|
||||
*/
|
||||
class TestUtil extends TestCase
|
||||
{
|
||||
protected function setupTest(): void
|
||||
{
|
||||
if (!\defined('K_PATH_FONTS')) {
|
||||
\define('K_PATH_FONTS', \dirname(__DIR__) . '/target/tmptest/');
|
||||
}
|
||||
|
||||
$fontPath = (string) \constant('K_PATH_FONTS');
|
||||
\system('rm -rf ' . $fontPath . ' && mkdir -p ' . $fontPath);
|
||||
}
|
||||
|
||||
protected function getFontPath(): string
|
||||
{
|
||||
if (\defined('K_PATH_FONTS')) {
|
||||
return (string) \constant('K_PATH_FONTS');
|
||||
}
|
||||
|
||||
return '';
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
}
|
||||
+1439
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,569 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* TypeOneInternalsTest.php
|
||||
*
|
||||
* @since 2026-05-05
|
||||
* @category Library
|
||||
* @package PdfFont
|
||||
* @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-font
|
||||
*
|
||||
* This file is part of tc-lib-pdf-font software library.
|
||||
*/
|
||||
|
||||
namespace Test;
|
||||
|
||||
use Com\Tecnick\Pdf\Font\Exception as FontException;
|
||||
use Com\Tecnick\Pdf\Font\Import\TypeOne;
|
||||
|
||||
/**
|
||||
* Tests for protected methods of Import\TypeOne exercised via reflection.
|
||||
*
|
||||
* @since 2026-05-05
|
||||
* @category Library
|
||||
* @package PdfFont
|
||||
* @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-font
|
||||
*
|
||||
* @phpstan-import-type TFontData from \Com\Tecnick\Pdf\Font\Load
|
||||
*/
|
||||
class TypeOneInternalsTest extends TestUtil
|
||||
{
|
||||
/** @var TFontData */
|
||||
private static array $fdtDefaults = [
|
||||
'Ascender' => 0,
|
||||
'Ascent' => 700,
|
||||
'AvgWidth' => 0.0,
|
||||
'CapHeight' => 680,
|
||||
'CharacterSet' => '',
|
||||
'Descender' => -200,
|
||||
'Descent' => -200,
|
||||
'EncodingScheme' => '',
|
||||
'FamilyName' => '',
|
||||
'Flags' => 0,
|
||||
'FontBBox' => [],
|
||||
'FontName' => '',
|
||||
'FullName' => '',
|
||||
'IsFixedPitch' => false,
|
||||
'ItalicAngle' => 0,
|
||||
'Leading' => 0,
|
||||
'MaxWidth' => 0,
|
||||
'MissingWidth' => 0,
|
||||
'StdHW' => 0,
|
||||
'StdVW' => 0,
|
||||
'StemH' => 0,
|
||||
'StemV' => 0,
|
||||
'UnderlinePosition' => 0,
|
||||
'UnderlineThickness' => 0,
|
||||
'Version' => '',
|
||||
'Weight' => '',
|
||||
'XHeight' => 0,
|
||||
'bbox' => '',
|
||||
'cbbox' => [],
|
||||
'cidinfo' => ['Ordering' => '', 'Registry' => '', 'Supplement' => 0, 'uni2cid' => []],
|
||||
'compress' => false,
|
||||
'ctg' => '',
|
||||
'ctgdata' => [],
|
||||
'cw' => [],
|
||||
'cwu' => [],
|
||||
'datafile' => '',
|
||||
'desc' => [
|
||||
'Ascent' => 0,
|
||||
'AvgWidth' => 0,
|
||||
'CapHeight' => 0,
|
||||
'Descent' => 0,
|
||||
'Flags' => 0,
|
||||
'FontBBox' => '',
|
||||
'ItalicAngle' => 0,
|
||||
'Leading' => 0,
|
||||
'MaxWidth' => 0,
|
||||
'MissingWidth' => 0,
|
||||
'StemH' => 0,
|
||||
'StemV' => 0,
|
||||
'XHeight' => 0,
|
||||
],
|
||||
'diff' => '',
|
||||
'diff_n' => 0,
|
||||
'dir' => '',
|
||||
'dw' => 0,
|
||||
'enc' => '',
|
||||
'enc_map' => [],
|
||||
'encodingTables' => [],
|
||||
'encoding_id' => 0,
|
||||
'encrypted' => '',
|
||||
'fakestyle' => false,
|
||||
'family' => '',
|
||||
'file' => '',
|
||||
'file_n' => 0,
|
||||
'file_name' => '',
|
||||
'i' => 0,
|
||||
'ifile' => '',
|
||||
'indexToLoc' => [],
|
||||
'input_file' => '',
|
||||
'isUnicode' => false,
|
||||
'italicAngle' => 0,
|
||||
'key' => '',
|
||||
'lenIV' => 4,
|
||||
'length1' => 0,
|
||||
'length2' => 0,
|
||||
'linked' => false,
|
||||
'mode' => [
|
||||
'bold' => false,
|
||||
'italic' => false,
|
||||
'linethrough' => false,
|
||||
'overline' => false,
|
||||
'underline' => false,
|
||||
],
|
||||
'n' => 0,
|
||||
'name' => '',
|
||||
'numGlyphs' => 0,
|
||||
'numHMetrics' => 0,
|
||||
'originalsize' => 0,
|
||||
'pdfa' => false,
|
||||
'platform_id' => 0,
|
||||
'settype' => '',
|
||||
'short_offset' => false,
|
||||
'size1' => 0,
|
||||
'size2' => 0,
|
||||
'style' => '',
|
||||
'subset' => false,
|
||||
'subsetchars' => [],
|
||||
'table' => [],
|
||||
'tot_num_glyphs' => 0,
|
||||
'type' => 'Type1',
|
||||
'underlinePosition' => 0,
|
||||
'underlineThickness' => 0,
|
||||
'unicode' => false,
|
||||
'unitsPerEm' => 0,
|
||||
'up' => 0,
|
||||
'urk' => 1.0,
|
||||
'ut' => 0,
|
||||
'weight' => 'normal',
|
||||
];
|
||||
|
||||
private function buildTypeOne(): TypeOne
|
||||
{
|
||||
$class = new \ReflectionClass(TypeOne::class);
|
||||
$instance = $class->newInstanceWithoutConstructor();
|
||||
$this->setProp($instance, 'fdt', self::$fdtDefaults);
|
||||
$this->setProp($instance, 'font', '');
|
||||
return $instance;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<int, mixed> $args
|
||||
*/
|
||||
private function callMethod(object $obj, string $method, array $args = []): mixed
|
||||
{
|
||||
$ref = new \ReflectionMethod($obj, $method);
|
||||
return $ref->invokeArgs($obj, $args);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<int, mixed> $args
|
||||
*/
|
||||
private function callIntMethod(object $obj, string $method, array $args = []): int
|
||||
{
|
||||
return $this->expectInt($this->callMethod($obj, $method, $args), 'Expected int result.');
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<int, mixed> $args
|
||||
*
|
||||
* @return array<int, array<int, string>>
|
||||
*/
|
||||
private function callArrayMethod(object $obj, string $method, array $args = []): array
|
||||
{
|
||||
return $this->expectIntStringMatrix($this->callMethod($obj, $method, $args), 'Expected array result.');
|
||||
}
|
||||
|
||||
private function setProp(object $obj, string $name, mixed $value): void
|
||||
{
|
||||
$prop = new \ReflectionProperty($obj, $name);
|
||||
$prop->setValue($obj, $value);
|
||||
}
|
||||
|
||||
/** @return array<string, mixed> */
|
||||
private function getFontData(object $obj): array
|
||||
{
|
||||
$prop = new \ReflectionProperty($obj, 'fdt');
|
||||
return $this->expectFontData($prop->getValue($obj));
|
||||
}
|
||||
|
||||
/** @param array<string, mixed> $fontData */
|
||||
private function getFontIntValue(array $fontData, string $key): int
|
||||
{
|
||||
if (!isset($fontData[$key]) || !\is_int($fontData[$key])) {
|
||||
$this->fail('Expected int font field: ' . $key);
|
||||
}
|
||||
|
||||
return $fontData[$key];
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $fontData
|
||||
*
|
||||
* @return array<int, string>
|
||||
*/
|
||||
private function getFontStringMap(array $fontData, string $key): array
|
||||
{
|
||||
if (!isset($fontData[$key]) || !\is_array($fontData[$key])) {
|
||||
$this->fail('Expected array font field: ' . $key);
|
||||
}
|
||||
|
||||
/** @var array<int, string> $value */
|
||||
$value = $fontData[$key];
|
||||
return $value;
|
||||
}
|
||||
|
||||
private function expectInt(mixed $value, string $message): int
|
||||
{
|
||||
if (!\is_int($value)) {
|
||||
$this->fail($message);
|
||||
}
|
||||
|
||||
return $value;
|
||||
}
|
||||
|
||||
/** @return array<int, array<int, string>> */
|
||||
private function expectIntStringMatrix(mixed $value, string $message): array
|
||||
{
|
||||
if (!\is_array($value)) {
|
||||
$this->fail($message);
|
||||
}
|
||||
|
||||
/** @var array<int, array<int, string>> $value */
|
||||
return $value;
|
||||
}
|
||||
|
||||
/** @return array<string, mixed> */
|
||||
private function expectFontData(mixed $value): array
|
||||
{
|
||||
if (!\is_array($value)) {
|
||||
$this->fail('Expected font data array.');
|
||||
}
|
||||
|
||||
/** @var array<string, mixed> $value */
|
||||
return $value;
|
||||
}
|
||||
|
||||
/** @param array<string, mixed> $fontData */
|
||||
private function getFontStringValue(array $fontData, string $key): string
|
||||
{
|
||||
if (!isset($fontData[$key]) || !\is_string($fontData[$key])) {
|
||||
$this->fail('Expected string font field: ' . $key);
|
||||
}
|
||||
|
||||
return $fontData[$key];
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// extractFontInfo
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
public function testExtractFontInfoParsesWeight(): void
|
||||
{
|
||||
$instance = $this->buildTypeOne();
|
||||
$this->setProp(
|
||||
$instance,
|
||||
'font',
|
||||
"/FontName /Helvetica-Bold def\n/FontBBox {0 -200 1000 700} def\n/Weight (Bold) def",
|
||||
);
|
||||
|
||||
$this->callMethod($instance, 'extractFontInfo');
|
||||
$fdt = $this->getFontData($instance);
|
||||
|
||||
// the parsed /Weight must survive (it previously was hard-coded to 'Book',
|
||||
// which disabled the bold StemV heuristic in extractStem)
|
||||
$this->assertSame('bold', $this->getFontStringValue($fdt, 'weight'));
|
||||
}
|
||||
|
||||
public function testExtractFontInfoDefaultsWeightToBook(): void
|
||||
{
|
||||
$instance = $this->buildTypeOne();
|
||||
$this->setProp($instance, 'font', "/FontName /Helvetica def\n/FontBBox {0 -200 1000 700} def");
|
||||
|
||||
$this->callMethod($instance, 'extractFontInfo');
|
||||
$fdt = $this->getFontData($instance);
|
||||
|
||||
$this->assertSame('Book', $this->getFontStringValue($fdt, 'weight'));
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// extractStem
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
public function testExtractStemReadsStdVwAndStdHw(): void
|
||||
{
|
||||
$instance = $this->buildTypeOne();
|
||||
$eplain = '/StdVW [85] def /StdHW [40] def /CapHeight [690] def';
|
||||
$this->callMethod($instance, 'extractStem', [$eplain]);
|
||||
$fdt = $this->getFontData($instance);
|
||||
|
||||
$this->assertSame(85, $this->getFontIntValue($fdt, 'StemV'));
|
||||
$this->assertSame(40, $this->getFontIntValue($fdt, 'StemH'));
|
||||
$this->assertSame(690, $this->getFontIntValue($fdt, 'CapHeight'));
|
||||
}
|
||||
|
||||
public function testExtractStemUsesBoldDefaultWhenStdVwAbsent(): void
|
||||
{
|
||||
$instance = $this->buildTypeOne();
|
||||
$fdt = self::$fdtDefaults;
|
||||
$fdt['weight'] = 'bold';
|
||||
$this->setProp($instance, 'fdt', $fdt);
|
||||
|
||||
$this->callMethod($instance, 'extractStem', ['']);
|
||||
$fdt = $this->getFontData($instance);
|
||||
|
||||
$this->assertSame(123, $this->getFontIntValue($fdt, 'StemV'));
|
||||
$this->assertSame(30, $this->getFontIntValue($fdt, 'StemH'));
|
||||
}
|
||||
|
||||
public function testExtractStemUsesDefaultsWhenNoMatchingKeys(): void
|
||||
{
|
||||
$instance = $this->buildTypeOne();
|
||||
$this->callMethod($instance, 'extractStem', ['']);
|
||||
$fdt = $this->getFontData($instance);
|
||||
|
||||
$this->assertSame(70, $this->getFontIntValue($fdt, 'StemV'));
|
||||
$this->assertSame(30, $this->getFontIntValue($fdt, 'StemH'));
|
||||
// CapHeight falls back to Ascent (700)
|
||||
$this->assertSame(700, $this->getFontIntValue($fdt, 'CapHeight'));
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// getRandomBytes
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
public function testGetRandomBytesDefaultsToFourWhenMissing(): void
|
||||
{
|
||||
$instance = $this->buildTypeOne();
|
||||
$this->callMethod($instance, 'getRandomBytes', ['no lenIV here']);
|
||||
$fdt = $this->getFontData($instance);
|
||||
$this->assertSame(4, $this->getFontIntValue($fdt, 'lenIV'));
|
||||
}
|
||||
|
||||
public function testGetRandomBytesParsesExplicitLenIV(): void
|
||||
{
|
||||
$instance = $this->buildTypeOne();
|
||||
$this->callMethod($instance, 'getRandomBytes', ['/lenIV 8 def']);
|
||||
$fdt = $this->getFontData($instance);
|
||||
$this->assertSame(8, $this->getFontIntValue($fdt, 'lenIV'));
|
||||
}
|
||||
|
||||
public function testGetRandomBytesParsesLenIVZero(): void
|
||||
{
|
||||
$instance = $this->buildTypeOne();
|
||||
$this->callMethod($instance, 'getRandomBytes', ['/lenIV 0 def']);
|
||||
$fdt = $this->getFontData($instance);
|
||||
$this->assertSame(0, $this->getFontIntValue($fdt, 'lenIV'));
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// getCharstringData
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
public function testGetCharstringDataReturnsEmptyMatchesWhenNoneFound(): void
|
||||
{
|
||||
$instance = $this->buildTypeOne();
|
||||
$fdt = self::$fdtDefaults;
|
||||
$fdt['enc'] = '';
|
||||
$this->setProp($instance, 'fdt', $fdt);
|
||||
|
||||
$eplain = '/CharStrings 0 dict dup begin end';
|
||||
$result = $this->callArrayMethod($instance, 'getCharstringData', [$eplain]);
|
||||
$this->assertIsArray($result);
|
||||
$this->assertCount(0, $result);
|
||||
}
|
||||
|
||||
public function testGetCharstringDataReturnsEmptyWhenEncNotInMap(): void
|
||||
{
|
||||
$instance = $this->buildTypeOne();
|
||||
$fdt = self::$fdtDefaults;
|
||||
$fdt['enc'] = 'nonexistent_encoding';
|
||||
$this->setProp($instance, 'fdt', $fdt);
|
||||
|
||||
$eplain = '/CharStrings 0 dict dup begin end';
|
||||
$result = $this->callArrayMethod($instance, 'getCharstringData', [$eplain]);
|
||||
$this->assertIsArray($result);
|
||||
}
|
||||
|
||||
public function testGetCharstringDataPopulatesEncMapForKnownEncoding(): void
|
||||
{
|
||||
$instance = $this->buildTypeOne();
|
||||
$fdt = self::$fdtDefaults;
|
||||
$fdt['enc'] = 'cp1252';
|
||||
$this->setProp($instance, 'fdt', $fdt);
|
||||
|
||||
$eplain = '/CharStrings 0 dict dup begin end';
|
||||
$this->callMethod($instance, 'getCharstringData', [$eplain]);
|
||||
$fdt = $this->getFontData($instance);
|
||||
|
||||
$this->assertNotEmpty($this->getFontStringMap($fdt, 'enc_map'));
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// getCid
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
public function testGetCidReturnsImapValueWhenCharNameFound(): void
|
||||
{
|
||||
$instance = $this->buildTypeOne();
|
||||
$imap = ['A' => 65, 'B' => 66];
|
||||
$val = [0 => '', 1 => 'A', 2 => ''];
|
||||
$result = $this->callIntMethod($instance, 'getCid', [$imap, $val]);
|
||||
$this->assertSame(65, $result);
|
||||
}
|
||||
|
||||
public function testGetCidReturnsZeroWhenEncMapEmpty(): void
|
||||
{
|
||||
$instance = $this->buildTypeOne();
|
||||
$fdt = self::$fdtDefaults;
|
||||
$fdt['enc_map'] = [];
|
||||
$this->setProp($instance, 'fdt', $fdt);
|
||||
|
||||
$imap = [];
|
||||
$val = [0 => '', 1 => 'Z', 2 => ''];
|
||||
$result = $this->callIntMethod($instance, 'getCid', [$imap, $val]);
|
||||
$this->assertSame(0, $result);
|
||||
}
|
||||
|
||||
public function testGetCidReturnsZeroWhenCharNotFoundInEncMap(): void
|
||||
{
|
||||
$instance = $this->buildTypeOne();
|
||||
$fdt = self::$fdtDefaults;
|
||||
$fdt['enc_map'] = ['a' => 97];
|
||||
$this->setProp($instance, 'fdt', $fdt);
|
||||
|
||||
$imap = [];
|
||||
$val = [0 => '', 1 => 'missing', 2 => ''];
|
||||
$result = $this->callIntMethod($instance, 'getCid', [$imap, $val]);
|
||||
$this->assertSame(0, $result);
|
||||
}
|
||||
|
||||
public function testGetCidClampsLargeCidToThousand(): void
|
||||
{
|
||||
$instance = $this->buildTypeOne();
|
||||
// Build enc_map where the glyph name resolves to a CID > 1000
|
||||
$encMap = [];
|
||||
$encMap[1001] = 'BigChar';
|
||||
$fdt = self::$fdtDefaults;
|
||||
$fdt['enc_map'] = $encMap;
|
||||
$this->setProp($instance, 'fdt', $fdt);
|
||||
|
||||
$imap = [];
|
||||
$val = [0 => '', 1 => 'BigChar', 2 => ''];
|
||||
$result = $this->callIntMethod($instance, 'getCid', [$imap, $val]);
|
||||
$this->assertSame(1000, $result);
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// decodeNumber
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
public function testDecodeNumberHandlesByte32To246(): void
|
||||
{
|
||||
$instance = $this->buildTypeOne();
|
||||
// ccom[0] = 139 → decoded value = 139 - 139 = 0
|
||||
$ccom = [139];
|
||||
/** @var array<int, int> $cdec */
|
||||
$cdec = [];
|
||||
/** @var array<int, int> $cwidths */
|
||||
$cwidths = [];
|
||||
$cck = 0;
|
||||
$cid = 0;
|
||||
$newIdx = $this->callIntMethod($instance, 'decodeNumber', [0, &$cck, &$cid, &$ccom, &$cdec, &$cwidths]);
|
||||
/** @var array<int, int> $cdec */
|
||||
$this->assertSame(1, $newIdx);
|
||||
$this->assertSame(0, $cdec[0] ?? null);
|
||||
}
|
||||
|
||||
public function testDecodeNumberHandlesBytes247To250(): void
|
||||
{
|
||||
$instance = $this->buildTypeOne();
|
||||
// ccom[0] = 247, ccom[1] = 0 → value = (247-247)*256 + 0 + 108 = 108
|
||||
$ccom = [247, 0];
|
||||
/** @var array<int, int> $cdec */
|
||||
$cdec = [];
|
||||
/** @var array<int, int> $cwidths */
|
||||
$cwidths = [];
|
||||
$cck = 0;
|
||||
$cid = 0;
|
||||
$newIdx = $this->callIntMethod($instance, 'decodeNumber', [0, &$cck, &$cid, &$ccom, &$cdec, &$cwidths]);
|
||||
/** @var array<int, int> $cdec */
|
||||
$this->assertSame(2, $newIdx);
|
||||
$this->assertSame(108, $cdec[0] ?? null);
|
||||
}
|
||||
|
||||
public function testDecodeNumberHandlesBytes251To254(): void
|
||||
{
|
||||
$instance = $this->buildTypeOne();
|
||||
// ccom[0] = 251, ccom[1] = 0 → value = -(251-251)*256 - 0 - 108 = -108
|
||||
$ccom = [251, 0];
|
||||
/** @var array<int, int> $cdec */
|
||||
$cdec = [];
|
||||
/** @var array<int, int> $cwidths */
|
||||
$cwidths = [];
|
||||
$cck = 0;
|
||||
$cid = 0;
|
||||
$newIdx = $this->callIntMethod($instance, 'decodeNumber', [0, &$cck, &$cid, &$ccom, &$cdec, &$cwidths]);
|
||||
/** @var array<int, int> $cdec */
|
||||
$this->assertSame(2, $newIdx);
|
||||
$this->assertSame(-108, $cdec[0] ?? null);
|
||||
}
|
||||
|
||||
public function testDecodeNumberHandlesByte255FourByteInt(): void
|
||||
{
|
||||
$instance = $this->buildTypeOne();
|
||||
// ccom[0]=255, ccom[1..4] = big-endian int 500 = 0x000001F4
|
||||
$ccom = [255, 0, 0, 1, 0xF4];
|
||||
/** @var array<int, int> $cdec */
|
||||
$cdec = [];
|
||||
/** @var array<int, int> $cwidths */
|
||||
$cwidths = [];
|
||||
$cck = 0;
|
||||
$cid = 0;
|
||||
$newIdx = $this->callIntMethod($instance, 'decodeNumber', [0, &$cck, &$cid, &$ccom, &$cdec, &$cwidths]);
|
||||
/** @var array<int, int> $cdec */
|
||||
$this->assertSame(5, $newIdx);
|
||||
// The 4-byte sequence packs as little-endian 'l' → 0x000001F4 LE = 0xF4010000 BE
|
||||
// unpack('li', "\x00\x00\x01\xF4") depends on system endianness; just assert it returned an int.
|
||||
$this->assertIsInt($cdec[0] ?? null);
|
||||
}
|
||||
|
||||
public function testDecodeNumberHsbwCommandUpdatesWidth(): void
|
||||
{
|
||||
$instance = $this->buildTypeOne();
|
||||
// Build a 2-element decode stack: cdec[0]=width(300), cdec[1]=13 (hsbw)
|
||||
// When ccom[$idx]=value<32 and cck>0 and the value==13 → hsbw: cwidths[$cid] = cdec[$cck-1]
|
||||
$ccom = [13]; // hsbw opcode (value < 32)
|
||||
/** @var array<int, int> $cdec */
|
||||
$cdec = [0 => 300];
|
||||
/** @var array<int, int> $cwidths */
|
||||
$cwidths = [];
|
||||
$cck = 1; // stack has one element already
|
||||
$cid = 7;
|
||||
$this->callMethod($instance, 'decodeNumber', [0, &$cck, &$cid, &$ccom, &$cdec, &$cwidths]);
|
||||
/** @var array<int, int> $cwidths */
|
||||
$this->assertArrayHasKey(7, $cwidths);
|
||||
$this->assertSame(300, $cwidths[7] ?? null);
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// storeFontData – error paths
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
public function testStoreFontDataThrowsOnInvalidMarker(): void
|
||||
{
|
||||
$instance = $this->buildTypeOne();
|
||||
// First byte not 128 → invalid binary Type1
|
||||
$this->setProp($instance, 'font', "\x00\x00\x00\x00\x00\x00");
|
||||
$this->bcExpectException(FontException::class);
|
||||
$this->callMethod($instance, 'storeFontData', []);
|
||||
}
|
||||
}
|
||||
+191
@@ -0,0 +1,191 @@
|
||||
# makefile
|
||||
#
|
||||
# @since 2015-05-14
|
||||
# @category Library
|
||||
# @package PdfFont
|
||||
# @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-font
|
||||
#
|
||||
# This file is part of tc-lib-pdf-font software library.
|
||||
#
|
||||
# Download and convert fonts for tc-lib-pdf-font.
|
||||
# ----------------------------------------------------------------------------------------------------------------------
|
||||
|
||||
# Folder containing the font to install (package)
|
||||
PKGFONTDIR=.
|
||||
|
||||
# License name of the font to be packaged
|
||||
PKGFONTLICENSE=.
|
||||
|
||||
# Project owner
|
||||
OWNER=tecnickcom
|
||||
|
||||
# Project vendor
|
||||
VENDOR=${OWNER}
|
||||
|
||||
# Project name
|
||||
PROJECT=tc-lib-pdf-font-data-$(PKGFONTDIR)
|
||||
|
||||
# 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
|
||||
FONTPATH=${PHPHOME}/Pdf/Font/fonts/$(PKGFONTDIR)/
|
||||
|
||||
# Default installation path for documentation
|
||||
DOCPATH=${DATADIR}/doc/$(PKGNAME)/
|
||||
|
||||
# Installation path for the code
|
||||
PATHINSTFONT=$(DESTDIR)/$(FONTPATH)
|
||||
|
||||
# Installation path for documentation
|
||||
PATHINSTDOC=$(DESTDIR)/$(DOCPATH)
|
||||
|
||||
# Current directory
|
||||
CURRENTDIR=$(CURDIR)/
|
||||
|
||||
# RPM Packaging path (where RPMs will be stored)
|
||||
PATHRPMPKG=$(CURRENTDIR)/../target/RPM_FONTS/$(PKGFONTDIR)
|
||||
|
||||
# DEB Packaging path (where DEBs will be stored)
|
||||
PATHDEBPKG=$(CURRENTDIR)/../target/DEB_FONTS/$(PKGFONTDIR)
|
||||
|
||||
# BZ2 Packaging path (where BZ2s will be stored)
|
||||
PATHBZ2PKG=$(CURRENTDIR)/../target/BZ2_FONTS/$(PKGFONTDIR)
|
||||
|
||||
|
||||
# Composer executable (disable APC to as a work-around of a bug)
|
||||
COMPOSER=$(shell which php) -d "apc.enable_cli=0" $(shell which composer)
|
||||
|
||||
# sed argument for in-place substitutions
|
||||
SEDINPLACE=-i
|
||||
ifeq ($(shell uname -s),Darwin)
|
||||
SEDINPLACE=-i ''
|
||||
endif
|
||||
|
||||
# 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 ""
|
||||
|
||||
# alias for help target
|
||||
.PHONY: all
|
||||
all: help
|
||||
|
||||
## delete the vendor and target directory
|
||||
.PHONY: clean
|
||||
clean:
|
||||
rm -rf ./vendor/
|
||||
rm -rf ../target/fonts
|
||||
|
||||
## Download all dependencies
|
||||
.PHONY: deps
|
||||
deps:
|
||||
($(COMPOSER) install --no-dev --no-interaction)
|
||||
|
||||
## Clean and download the composer dependencies (all TTF font files)
|
||||
.PHONY: build
|
||||
build: deps
|
||||
./bulk_convert.php
|
||||
|
||||
## Update composer dependencies
|
||||
.PHONY: update
|
||||
update:
|
||||
($(COMPOSER) update --no-interaction)
|
||||
|
||||
## Install this application
|
||||
.PHONY: install
|
||||
install: uninstall
|
||||
mkdir -p "$(PATHINSTFONT)"
|
||||
cp -rf "../target/fonts/$(PKGFONTDIR)/"*".json" "$(PATHINSTFONT)"
|
||||
cp -rf "../target/fonts/$(PKGFONTDIR)/"*".z" "$(PATHINSTFONT)" | true
|
||||
find "$(PATHINSTFONT)" -type d -exec chmod 755 {} \;
|
||||
find "$(PATHINSTFONT)" -type f -exec chmod 644 {} \;
|
||||
mkdir -p "$(PATHINSTDOC)"
|
||||
cp -f "../target/fonts/$(PKGFONTDIR)/LICENSE" "$(PATHINSTDOC)"
|
||||
cp -f "../target/fonts/$(PKGFONTDIR)/README" "$(PATHINSTDOC)"
|
||||
cp -f ../VERSION "$(PATHINSTDOC)"
|
||||
cp -f ../RELEASE "$(PATHINSTDOC)"
|
||||
chmod -R 644 "$(PATHINSTDOC)"*
|
||||
|
||||
## Remove all installed files
|
||||
.PHONY: uninstall
|
||||
uninstall:
|
||||
rm -rf "$(PATHINSTFONT)"
|
||||
|
||||
# --- PACKAGING ---
|
||||
|
||||
## 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)"
|
||||
rpmbuild --define \
|
||||
"_topdir $(PATHRPMPKG)" \
|
||||
--define "_vendor $(VENDOR)" \
|
||||
--define "_owner $(OWNER)" \
|
||||
--define "_project $(PROJECT)" \
|
||||
--define "_package $(PKGNAME)" \
|
||||
--define "_version $(VERSION)" \
|
||||
--define "_release $(RELEASE)" \
|
||||
--define "_current_directory $(CURRENTDIR)" \
|
||||
--define "_fontpath /$(FONTPATH)" \
|
||||
--define "_docpath /$(DOCPATH)" \
|
||||
--define "_fontdir $(PKGFONTDIR)" \
|
||||
--define "_license $(PKGFONTLICENSE)" \
|
||||
-bb ../resources/rpm/fonts.spec
|
||||
|
||||
## Build the DEB package for Debian-like Linux distributions
|
||||
.PHONY: deb
|
||||
deb:
|
||||
echo "resources/fonts/control/$(DEBCOPYRIGHT)"
|
||||
rm -rf "$(PATHDEBPKG)"
|
||||
make install DESTDIR="$(PATHDEBPKG)/$(PKGNAME)-$(VERSION)" PKGFONTDIR="$(PKGFONTDIR)"
|
||||
tar -zcvf "$(PATHDEBPKG)/$(PKGNAME)_$(VERSION).orig.tar.gz" -C "$(PATHDEBPKG)/" "$(PKGNAME)-$(VERSION)"
|
||||
cp -rf ../resources/fonts/debian "$(PATHDEBPKG)/$(PKGNAME)-$(VERSION)/debian"
|
||||
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)/" {} \;
|
||||
find "$(PATHDEBPKG)/$(PKGNAME)-$(VERSION)/debian/" -type f -exec sed $(SEDINPLACE) "s/~#FONT#~/$(PKGFONTDIR)/" {} \;
|
||||
find "$(PATHDEBPKG)/$(PKGNAME)-$(VERSION)/debian/" -type f -exec sed $(SEDINPLACE) "s/~#LICENSE#~/$(PKGFONTLICENSE)/" {} \;
|
||||
echo "$(FONTPATH)" > "$(PATHDEBPKG)/$(PKGNAME)-$(VERSION)/debian/$(PKGNAME).dirs"
|
||||
echo "$(FONTPATH)* $(FONTPATH)" > "$(PATHDEBPKG)/$(PKGNAME)-$(VERSION)/debian/install"
|
||||
echo "$(DOCPATH)" >> "$(PATHDEBPKG)/$(PKGNAME)-$(VERSION)/debian/$(PKGNAME).dirs"
|
||||
echo "$(DOCPATH)* $(DOCPATH)" >> "$(PATHDEBPKG)/$(PKGNAME)-$(VERSION)/debian/install"
|
||||
echo "new-package-should-close-itp-bug" > "$(PATHDEBPKG)/$(PKGNAME)-$(VERSION)/debian/$(PKGNAME).lintian-overrides"
|
||||
echo "extra-license-file $(DOCPATH)LICENSE.gz" >> "$(PATHDEBPKG)/$(PKGNAME)-$(VERSION)/debian/$(PKGNAME).lintian-overrides"
|
||||
cd "$(PATHDEBPKG)/$(PKGNAME)-$(VERSION)" && debuild -us -uc
|
||||
|
||||
## Build a compressed bz2 archive
|
||||
.PHONY: bz2
|
||||
bz2:
|
||||
rm -rf "$(PATHBZ2PKG)"
|
||||
make install DESTDIR="$(PATHBZ2PKG)" PKGFONTDIR="$(PKGFONTDIR)"
|
||||
tar -jcvf "$(PATHBZ2PKG)/$(PKGNAME)-$(VERSION)-$(RELEASE).tbz2" -C "$(PATHBZ2PKG)" "$(DATADIR)"
|
||||
@@ -0,0 +1,197 @@
|
||||
#!/usr/bin/env php
|
||||
<?php
|
||||
/**
|
||||
* bulk_convert.php
|
||||
*
|
||||
* @since 2015-11-30
|
||||
* @category Library
|
||||
* @package PdfFont
|
||||
* @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-font
|
||||
*
|
||||
* This file is part of tc-lib-pdf-font software library.
|
||||
*
|
||||
* Command-line tool to convert fonts data for the tc-lib-pdf-font library in bulk.
|
||||
*/
|
||||
|
||||
if (\php_sapi_name() != 'cli') {
|
||||
\fwrite(STDERR, 'You need to run this command from console.'."\n");
|
||||
exit(1);
|
||||
}
|
||||
|
||||
/**
|
||||
* Display help guide for this command.
|
||||
*/
|
||||
function showHelp()
|
||||
{
|
||||
$help = <<<EOD
|
||||
|
||||
bulk_convert - Command-line tool to convert fonts data for the tc-lib-pdf-font library.
|
||||
|
||||
Usage:
|
||||
bulk_convert.php [ options ]
|
||||
|
||||
Options:
|
||||
|
||||
-o, --outpath
|
||||
Output path for generated font files (must be writeable by the
|
||||
web server). Leave empty for default font folder.
|
||||
|
||||
-h, --help
|
||||
Display this help and exit.
|
||||
|
||||
EOD;
|
||||
\fwrite(STDOUT, $help);
|
||||
exit(0);
|
||||
}
|
||||
|
||||
// initialize the array of options
|
||||
$options = array('outpath' => \dirname(__DIR__).'/target/fonts/');
|
||||
|
||||
// short input options
|
||||
$sopt = 'o:';
|
||||
|
||||
// long input options
|
||||
$lopt = array('outpath:');
|
||||
|
||||
// parse input options
|
||||
$inopt = \getopt($sopt, $lopt);
|
||||
|
||||
// import options (with some sanitization)
|
||||
foreach ($inopt as $opt => $val) {
|
||||
switch ($opt) {
|
||||
case 'o':
|
||||
case 'outpath':
|
||||
$options['outpath'] = \realpath($val);
|
||||
if (\substr($options['outpath'], -1) != '/') {
|
||||
$options['outpath'] .= '/';
|
||||
}
|
||||
break;
|
||||
case 'h':
|
||||
case 'help':
|
||||
default:
|
||||
showHelp();
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// check input values
|
||||
if (!is_dir($options['outpath'])) {
|
||||
\mkdir($options['outpath'], 0755, true);
|
||||
}
|
||||
if (!\is_writable($options['outpath'])) {
|
||||
\fwrite(STDERR, 'ERROR: Can\'t write to '.$options['outpath']."\n\n");
|
||||
exit(2);
|
||||
}
|
||||
|
||||
$ttfdir = __DIR__.'/vendor/tecnickcom/tc-font-mirror/';
|
||||
if (!is_dir($ttfdir)) {
|
||||
\fwrite(STDERR, 'ERROR: The '.$ttfdir.' directory is empty, please execute \'make build\' before this command.'."\n\n");
|
||||
exit(3);
|
||||
}
|
||||
|
||||
\fwrite(STDOUT, "\n".'>>> Converting fonts:'."\n".'*** Output directory set to '.$options['outpath']."\n");
|
||||
|
||||
// count conversions
|
||||
$convert_errors = 0;
|
||||
$convert_success = 0;
|
||||
|
||||
require_once (\dirname(__DIR__).'/vendor/autoload.php');
|
||||
|
||||
$fontdir = \array_diff(\scandir($ttfdir), array('.', '..', '.git'));
|
||||
|
||||
// URL of websites containing the font sources
|
||||
$font_url = array(
|
||||
'cid0' => 'http://unifoundry.com/unifont.html',
|
||||
'core' => 'https://partners.adobe.com/public/developer/en/pdf/Core14_AFMs.zip',
|
||||
'dejavu' => 'http://sourceforge.net/projects/dejavu/files/dejavu/2.35/dejavu-fonts-ttf-2.35.zip',
|
||||
'freefont' => 'https://ftp.gnu.org/gnu/freefont/freefont-ttf-20120503.zip',
|
||||
'pdfa' => 'https://github.com/tecnickcom/tc-font-pdfa',
|
||||
'unifont' => 'http://unifoundry.com/unifont.html',
|
||||
);
|
||||
|
||||
foreach ($fontdir as $dir) {
|
||||
$indir = $ttfdir.$dir;
|
||||
if (!is_dir($indir)) {
|
||||
continue;
|
||||
}
|
||||
// search font files in sub directories
|
||||
$all_files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($indir));
|
||||
$fonts = \iterator_to_array(new RegexIterator($all_files, '/\.ttf$/'));
|
||||
$fonts = \array_merge($fonts, \iterator_to_array(new RegexIterator($all_files, '/\.pfb$/')));
|
||||
$fonts = \array_merge($fonts, \iterator_to_array(new RegexIterator($all_files, '/\.otf$/')));
|
||||
if (empty($fonts)) {
|
||||
$fonts = \iterator_to_array(new RegexIterator($all_files, '/\.afm$/'));
|
||||
}
|
||||
if (empty($fonts)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// build output path directory
|
||||
$outdir = $options['outpath'].$dir.'/';
|
||||
if (!is_dir($outdir)) {
|
||||
\mkdir($outdir, 0755, true);
|
||||
}
|
||||
\copy($indir.'/LICENSE', $outdir.'LICENSE');
|
||||
|
||||
// generate a README file
|
||||
$readme = '# '.$dir.' font files for tc-lib-pdf-font'."\n\n"
|
||||
.'This folder contains font files and/or font data extracted from:'."\n"
|
||||
.$font_url[$dir]."\n"
|
||||
.'using the "bulk_convert.php" utility in https://github.com/tecnickcom/tc-lib-pdf-font'."\n\n"
|
||||
.'The original files (if present) have been renamed and compressed using the ZLIB data format (.z files).'."\n"
|
||||
.'The font files are subject to the conditions stated in the LICENSE file.'."\n"
|
||||
.'For further information please consult the original documentation at the link above.'."\n";
|
||||
\file_put_contents($outdir.'README', $readme);
|
||||
|
||||
foreach ($fonts as $font) {
|
||||
if (\substr($font, -4) == '.otf') {
|
||||
// OTF fonts are not yet supported but we can try to convert them to TTF using FontForge
|
||||
\system('fontforge -script otf2ttf.ff '.\escapeshellcmd($font), $err);
|
||||
if ($err != 0) {
|
||||
\fwrite(STDERR, "\033[31m".'Unable to convert: '.$font."\033[m");
|
||||
continue;
|
||||
}
|
||||
$font = \substr($font, 0, -4).'.ttf';
|
||||
}
|
||||
|
||||
$type = '';
|
||||
$encoding = '';
|
||||
if ($dir == 'cid0') {
|
||||
$type = \strtoupper(\basename($font, '.ttf'));
|
||||
} elseif (($dir == 'core') || ($dir == 'pdfa')) {
|
||||
if (\strpos($font, 'Symbol') !== false) {
|
||||
$encoding = 'symbol';
|
||||
} elseif (\strpos($font, 'ZapfDingbats') === false) {
|
||||
$encoding = 'cp1252';
|
||||
}
|
||||
}
|
||||
try {
|
||||
$import = new \Com\Tecnick\Pdf\Font\Import(
|
||||
\realpath($font),
|
||||
$outdir,
|
||||
$type,
|
||||
$encoding
|
||||
);
|
||||
$fontname = $import->getFontName();
|
||||
\fwrite(STDOUT, "\033[32m".'+++ OK : '.$font.' added as '.$fontname."\033[m\n");
|
||||
++$convert_success;
|
||||
} catch (\Exception $exc) {
|
||||
++$convert_errors;
|
||||
\fwrite(STDERR, "\033[31m".'--- ERROR: can\'t add '.$font."\n ".$exc->getMessage()."\033[m\n");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
$endmsg = '>>> PROCESS COMPLETED: '.$convert_success.' CONVERTED FONT(S), '.$convert_errors.' ERROR(S)!'."\n\n";
|
||||
|
||||
if ($convert_errors > 0) {
|
||||
\fwrite(STDERR, "\033[31m".$endmsg.'ERROR'."\033[m");
|
||||
exit(4);
|
||||
}
|
||||
|
||||
\fwrite(STDOUT, "\033[32m".$endmsg."\033[m");
|
||||
exit(0);
|
||||
|
||||
@@ -0,0 +1,62 @@
|
||||
{
|
||||
"name": "tecnickcom/tc-lib-pdf-font",
|
||||
"description": "Import TTF font files to be converted for tc-lib-pdf",
|
||||
"type": "library",
|
||||
"homepage": "http://www.tecnick.com",
|
||||
"keywords": [
|
||||
"tc-lib-pdf-font-data",
|
||||
"PDF",
|
||||
"font",
|
||||
"TTF",
|
||||
"AFM",
|
||||
"PFB",
|
||||
"import"
|
||||
],
|
||||
"authors": [
|
||||
{
|
||||
"name": "Nicola Asuni",
|
||||
"email": "info@tecnick.com",
|
||||
"role": "lead"
|
||||
}
|
||||
],
|
||||
"require": {
|
||||
"tecnickcom/tc-font-mirror": "^2.2"
|
||||
},
|
||||
"minimum-stability": "dev",
|
||||
"prefer-stable": true,
|
||||
"config": {
|
||||
"allow-plugins": {
|
||||
"dealerdirect/phpcodesniffer-composer-installer": true
|
||||
}
|
||||
},
|
||||
"require-dev": {},
|
||||
"repositories": [
|
||||
{
|
||||
"type": "package",
|
||||
"package": {
|
||||
"name": "tecnickcom/tc-font-mirror",
|
||||
"version": "2.2.0",
|
||||
"dist": {
|
||||
"type": "zip",
|
||||
"url": "https://github.com/tecnickcom/tc-font-mirror/archive/refs/tags/2.2.0.zip",
|
||||
"reference": "main"
|
||||
},
|
||||
"autoload": {
|
||||
"classmap": [
|
||||
"."
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
],
|
||||
"support": {
|
||||
"issues": "https://github.com/tecnickcom/tc-lib-pdf-font/issues",
|
||||
"source": "https://github.com/tecnickcom/tc-lib-pdf-font"
|
||||
},
|
||||
"scripts": {
|
||||
"test": "XDEBUG_MODE=coverage ./vendor/bin/phpunit --stderr test",
|
||||
"cs-check": "./vendor/bin/phpcs --standard=phpcs.xml",
|
||||
"cs-fix": "./vendor/bin/phpcbf --ignore=\"./vendor/\" --standard=psr12 src test",
|
||||
"analyse": "./vendor/phpstan.phar analyse"
|
||||
}
|
||||
}
|
||||
+306
@@ -0,0 +1,306 @@
|
||||
#!/usr/bin/env php
|
||||
<?php
|
||||
/**
|
||||
* convert.php
|
||||
*
|
||||
* @since 2011-05-23
|
||||
* @category Library
|
||||
* @package PdfFont
|
||||
* @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-font
|
||||
*
|
||||
* This file is part of tc-lib-pdf-font software library.
|
||||
*
|
||||
* Command-line tool to convert fonts data for the tc-lib-pdf-font library.
|
||||
*/
|
||||
|
||||
if (\php_sapi_name() != 'cli') {
|
||||
\fwrite(STDERR, 'You need to run this command from console.'."\n");
|
||||
exit(1);
|
||||
}
|
||||
|
||||
/**
|
||||
* Display help guide for this command.
|
||||
*/
|
||||
function showHelp()
|
||||
{
|
||||
$help = <<<EOD
|
||||
|
||||
convert - Command-line tool to convert fonts data for the tc-lib-pdf-font library.
|
||||
|
||||
Usage:
|
||||
convert.php [ options ] -i fontfile[,fontfile]...
|
||||
|
||||
Options:
|
||||
|
||||
-o, --outpath
|
||||
Output path for generated font files (must be writeable by the
|
||||
web server). Leave empty for default font folder.
|
||||
|
||||
-t, --type
|
||||
Font type. Leave empty for autodetect mode.
|
||||
Valid values are:
|
||||
Core
|
||||
TrueTypeUnicode
|
||||
TrueType
|
||||
Type1
|
||||
CID0JP = CID-0 Japanese
|
||||
CID0KR = CID-0 Korean
|
||||
CID0CS = CID-0 Chinese Simplified
|
||||
CID0CT = CID-0 Chinese Traditional
|
||||
|
||||
-e, --encoding
|
||||
Name of the encoding table to use.
|
||||
Leave empty for default mode.
|
||||
Omit this parameter for TrueTypeUnicode and symbolic fonts
|
||||
like Symbol or ZapfDingBats.
|
||||
|
||||
-f, --flags
|
||||
Unsigned 32-bit integer containing flags specifying various
|
||||
characteristics of the font (see PDF32000:2008 - 9.8.2 Font
|
||||
Descriptor Flags):
|
||||
+1 for fixed font;
|
||||
+4 for symbol;
|
||||
+32 for non-symbol;
|
||||
+64 for italic.
|
||||
Fixed and Italic mode are generally autodetected so you have
|
||||
to set it to:
|
||||
4 = symbolic font;
|
||||
32 = non-symbolic font (default).
|
||||
|
||||
-p, --platform_id
|
||||
Platform ID for CMAP table to extract (when building a Unicode
|
||||
font for Windows this value should be 3, for Macintosh should
|
||||
be 1).
|
||||
|
||||
-n, --encoding_id
|
||||
Encoding ID for CMAP table to extract (when building a Unicode
|
||||
font for Windows this value should be 1, for Macintosh should
|
||||
be 0).
|
||||
When Platform ID is 3, legal values for Encoding ID are:
|
||||
0 = Symbol,
|
||||
1 = Unicode,
|
||||
2 = ShiftJIS,
|
||||
3 = PRC,
|
||||
4 = Big5,
|
||||
5 = Wansung,
|
||||
6 = Johab,
|
||||
7 = Reserved,
|
||||
8 = Reserved,
|
||||
9 = Reserved,
|
||||
10 = UCS-4.
|
||||
|
||||
-l, --linked
|
||||
Link to system font instead of copying the font data (not
|
||||
transportable).
|
||||
Note: this feature is unsupported by Type1 fonts.
|
||||
|
||||
-i, --fonts
|
||||
Comma-separated list of input font files.
|
||||
|
||||
-h, --help
|
||||
Display this help and exit.
|
||||
|
||||
Examples:
|
||||
|
||||
./convert.php --outpath=/tmp/ --type=Type1 --encoding=cp1252 --flags=97 --encoding_id=1 \
|
||||
--fonts=/tmp/pdfa/pdfacourieri.pfb,/tmp/pdfa/pdfacourierbi.pfb
|
||||
|
||||
./convert.php --outpath=/tmp/ --type=TrueTypeUnicode --flags=32 --encoding_id=1 \
|
||||
--fonts=/tmp/freefont-20120503/FreeSans.ttf
|
||||
|
||||
./convert.php --outpath=/tmp/ --type=TrueTypeUnicode --flags=97 --encoding_id=1 \
|
||||
--fonts=/tmp/dejavu-fonts-ttf-2.35/ttf/DejaVuSansMono-BoldOblique.ttf
|
||||
|
||||
|
||||
EOD;
|
||||
\fwrite(STDOUT, $help);
|
||||
exit(0);
|
||||
}
|
||||
|
||||
// remove the name of the executing script
|
||||
\array_shift($argv);
|
||||
|
||||
// no options chosen, display help
|
||||
if (empty($argv)) {
|
||||
showHelp();
|
||||
}
|
||||
|
||||
// initialize the array of options
|
||||
$options = array(
|
||||
'outpath' => \dirname(__DIR__) . '/target/fonts/',
|
||||
'type' => '',
|
||||
'encoding' => '',
|
||||
'flags' => 32,
|
||||
'platform_id' => 3,
|
||||
'encoding_id' => 1,
|
||||
'linked' => false
|
||||
);
|
||||
|
||||
// short input options
|
||||
$sopt = 't:e:f:o:p:n:li:h';
|
||||
|
||||
// long input options
|
||||
$lopt = array(
|
||||
'outpath:',
|
||||
'type:',
|
||||
'encoding:',
|
||||
'flags:',
|
||||
'platform_id:',
|
||||
'encoding_id:',
|
||||
'linked',
|
||||
'fonts:',
|
||||
'help'
|
||||
);
|
||||
|
||||
// parse input options
|
||||
$inopt = \getopt($sopt, $lopt);
|
||||
|
||||
// import options (with some sanitization)
|
||||
foreach ($inopt as $opt => $val) {
|
||||
switch ($opt) {
|
||||
case 'o':
|
||||
case 'outpath':
|
||||
// Keep the raw value when the directory does not exist yet:
|
||||
// realpath() returns false for a missing path and would
|
||||
// otherwise collapse the output path to '/'. The directory is
|
||||
// created and the path normalized further below.
|
||||
$resolved = \realpath($val);
|
||||
$options['outpath'] = ($resolved !== false) ? $resolved : $val;
|
||||
if (\substr($options['outpath'], -1) != '/') {
|
||||
$options['outpath'] .= '/';
|
||||
}
|
||||
break;
|
||||
case 't':
|
||||
case 'type':
|
||||
if (\in_array($val, array('TrueTypeUnicode', 'TrueType', 'Type1', 'CID0JP', 'CID0KR', 'CID0CS', 'CID0CT'))) {
|
||||
$options['type'] = $val;
|
||||
}
|
||||
break;
|
||||
case 'e':
|
||||
case 'encoding':
|
||||
$options['encoding'] = $val;
|
||||
break;
|
||||
case 'f':
|
||||
case 'flags':
|
||||
$options['flags'] = \intval($val);
|
||||
break;
|
||||
case 'p':
|
||||
case 'platform_id':
|
||||
$options['platform_id'] = \min(\max(1, \intval($val)), 3);
|
||||
break;
|
||||
case 'n':
|
||||
case 'encoding_id':
|
||||
$options['encoding_id'] = \min(\max(0, \intval($val)), 10);
|
||||
break;
|
||||
case 'l':
|
||||
case 'linked':
|
||||
$options['linked'] = true;
|
||||
break;
|
||||
case 'i':
|
||||
case 'fonts':
|
||||
$options['fonts'] = \explode(',', $val);
|
||||
break;
|
||||
case 'h':
|
||||
case 'help':
|
||||
default:
|
||||
showHelp();
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// check input values
|
||||
|
||||
if (!is_dir($options['outpath'])) {
|
||||
\mkdir($options['outpath'], 0755, true);
|
||||
}
|
||||
|
||||
if (!is_dir($options['outpath']) || !\is_writable($options['outpath'])) {
|
||||
\fwrite(STDERR, 'ERROR: Can\'t write to '.$options['outpath']."\n\n");
|
||||
exit(2);
|
||||
}
|
||||
|
||||
// the directory now exists: normalize to an absolute path with trailing slash
|
||||
$options['outpath'] = \realpath($options['outpath']) . '/';
|
||||
|
||||
if (empty($options['fonts'])) {
|
||||
\fwrite(STDERR, 'ERROR: missing input fonts (try --help for usage)'."\n\n");
|
||||
exit(3);
|
||||
}
|
||||
|
||||
\fwrite(STDOUT, "\n".'>>> Converting fonts:'."\n".'*** Output directory set to '.$options['outpath']."\n");
|
||||
|
||||
// count conversions
|
||||
$convert_errors = 0;
|
||||
$convert_success = 0;
|
||||
|
||||
// Locate the Composer autoloader, supporting both a standalone checkout
|
||||
// (vendor inside the project root) and installation as a dependency
|
||||
// (autoloader at the top level of the host project).
|
||||
$autoloadFound = false;
|
||||
foreach (
|
||||
array(
|
||||
\dirname(__DIR__) . '/vendor/autoload.php', // standalone repository checkout
|
||||
\dirname(__DIR__, 4) . '/vendor/autoload.php', // installed under <project>/vendor/tecnickcom/tc-lib-pdf-font
|
||||
) as $autoloadFile
|
||||
) {
|
||||
if (\is_file($autoloadFile)) {
|
||||
require_once $autoloadFile;
|
||||
$autoloadFound = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (!$autoloadFound) {
|
||||
\fwrite(STDERR, 'ERROR: Composer autoloader not found. Run "composer install" first.'."\n\n");
|
||||
exit(5);
|
||||
}
|
||||
|
||||
foreach ($options['fonts'] as $font) {
|
||||
try {
|
||||
$fontFile = realpath($font);
|
||||
if ($fontFile === false) {
|
||||
throw new \Exception('Invalid font file path: ' . $font);
|
||||
}
|
||||
|
||||
$allowedPaths = \array_values(\array_unique(\array_filter(array_map(
|
||||
static fn (string $path): string => rtrim($path, '/\\'),
|
||||
\array_merge(
|
||||
\Com\Tecnick\Pdf\Font\FontPaths::buildAllowedPaths(),
|
||||
[\dirname($fontFile), $options['outpath']]
|
||||
)
|
||||
))));
|
||||
|
||||
$fileHelper = new \Com\Tecnick\File\File(allowedPaths: $allowedPaths);
|
||||
|
||||
$import = new \Com\Tecnick\Pdf\Font\Import(
|
||||
$fontFile,
|
||||
$options['outpath'],
|
||||
$options['type'],
|
||||
$options['encoding'],
|
||||
$options['flags'],
|
||||
$options['platform_id'],
|
||||
$options['encoding_id'],
|
||||
$options['linked'],
|
||||
$fileHelper
|
||||
);
|
||||
$fontname = $import->getFontName();
|
||||
\fwrite(STDOUT, "\033[32m".'+++ OK : '.$font.' added as '.$fontname."\033[m\n");
|
||||
++$convert_success;
|
||||
} catch (\Exception $exc) {
|
||||
++$convert_errors;
|
||||
\fwrite(STDERR, "\033[31m".'--- ERROR: can\'t add '.$font."\n ".$exc->getMessage()."\033[m\n");
|
||||
}
|
||||
}
|
||||
|
||||
$endmsg = '>>> PROCESS COMPLETED: '.$convert_success.' CONVERTED FONT(S), '.$convert_errors.' ERROR(S)!'."\n\n";
|
||||
|
||||
if ($convert_errors > 0) {
|
||||
\fwrite(STDERR, "\033[31m".$endmsg.'ERROR'."\033[m");
|
||||
exit(4);
|
||||
}
|
||||
|
||||
\fwrite(STDOUT, "\033[32m".$endmsg."\033[m");
|
||||
exit(0);
|
||||
@@ -0,0 +1,46 @@
|
||||
#!/usr/bin/env fontforge
|
||||
|
||||
# FontForge script used to convert Noto CJK OTF fonts into TTF format
|
||||
# FROM: https://gist.github.com/mojavelinux/c74162d44ca77d1a7c25
|
||||
|
||||
# PDF Flags
|
||||
# * 0x90 - Neither OpenType or Apple
|
||||
# * 0x800 - Generate old-style 'kern' table
|
||||
# * 0x08 - Exclude TrueType instructions
|
||||
genflags = 0x90 + 0x08 + 0x800
|
||||
|
||||
src_file = $1
|
||||
dst_file = $1:r + ".ttf"
|
||||
|
||||
Open(src_file)
|
||||
CIDFlatten()
|
||||
SelectAll()
|
||||
ClearInstrs()
|
||||
SelectNone()
|
||||
|
||||
# Remove glyphs we'll later truncate to get under glyph limit
|
||||
SelectMore(0u1f190,0u1f199)
|
||||
Clear()
|
||||
SelectNone()
|
||||
|
||||
Generate(dst_file, "", genflags)
|
||||
Close()
|
||||
|
||||
Open(dst_file)
|
||||
|
||||
# Add missing space glyph
|
||||
Select(0u00a0)
|
||||
Copy()
|
||||
Select(0u0020)
|
||||
Paste()
|
||||
SetWidth(0)
|
||||
SelectNone()
|
||||
|
||||
# select lesser range of glyphs
|
||||
#SelectMore(0u0020,0uffee)
|
||||
#SelectInvert()
|
||||
#Clear()
|
||||
#SelectNone()
|
||||
|
||||
Generate(dst_file, "", genflags)
|
||||
Close()
|
||||
Reference in New Issue
Block a user