Feature: Labelprint für Kistenetiketten hinzugefügt

This commit is contained in:
2025-10-27 12:14:44 +01:00
parent 43bc416554
commit 14bae6c9ef
1068 changed files with 229014 additions and 1807 deletions

View File

@@ -0,0 +1,20 @@
# Ref: https://EditorConfig.org
# top-most EditorConfig file
root = true
# Unix-style end of lines and a blank line at the end of the file
[*]
indent_style = tab
end_of_line = lf
charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = true
[*.php]
indent_style = space
indent_size = 4
[*.{js,json,scss,css,yml,vue}]
indent_style = space
indent_size = 2

View File

@@ -0,0 +1 @@
custom: ['https://www.paypal.com/donate/?hosted_button_id=NZUEC5XS8MFBJ']

View File

@@ -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.

View File

@@ -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.

View File

@@ -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.

View File

@@ -0,0 +1,58 @@
name: check
env:
XDEBUG_MODE: coverage
permissions:
contents: read
on:
push:
branches:
- 'main'
pull_request:
types: [opened, synchronize, reopened]
branches:
- main
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.1", "8.2", "8.3", "8.4"]
experimental: [false]
os: [ubuntu-latest]
coverage-extension: [pcov]
steps:
- uses: actions/checkout@v4
- 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@v4
with:
path: ~/.composer/cache/
key: composer-cache
- name: Install dependencies
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@v5
with:
flags: php-${{ matrix.php-version }}-${{ matrix.os }}
name: php-${{ matrix.php-version }}-${{ matrix.os }}

View File

@@ -0,0 +1,23 @@
**/*.bak
**/*.tmp
**/.#*
**/.DS_Store
**/._*
**/.idea
**/.vagrant
**/auth.json
**/nbproject
**/temp.php
**/test.php
.phpdoc
.phpunit.cache
.phpunit.result.cache
composer.lock
ecs.php
phpunit.xml
rector.php
resources/util/vendor
src/fonts
target
target/fonts
vendor

View File

@@ -0,0 +1 @@
* @nicolaasuni

View File

@@ -0,0 +1,128 @@
# Contributor Covenant Code of Conduct
## Our Pledge
We as members, contributors, and leaders pledge to make participation in our
community a harassment-free experience for everyone, regardless of age, body
size, visible or invisible disability, ethnicity, sex characteristics, gender
identity and expression, level of experience, education, socio-economic status,
nationality, personal appearance, race, religion, or sexual identity
and orientation.
We pledge to act and interact in ways that contribute to an open, welcoming,
diverse, inclusive, and healthy community.
## Our Standards
Examples of behavior that contributes to a positive environment for our
community include:
* Demonstrating empathy and kindness toward other people
* Being respectful of differing opinions, viewpoints, and experiences
* Giving and gracefully accepting constructive feedback
* Accepting responsibility and apologizing to those affected by our mistakes,
and learning from the experience
* Focusing on what is best not just for us as individuals, but for the
overall community
Examples of unacceptable behavior include:
* The use of sexualized language or imagery, and sexual attention or
advances of any kind
* Trolling, insulting or derogatory comments, and personal or political attacks
* Public or private harassment
* Publishing others' private information, such as a physical or email
address, without their explicit permission
* Other conduct which could reasonably be considered inappropriate in a
professional setting
## Enforcement Responsibilities
Community leaders are responsible for clarifying and enforcing our standards of
acceptable behavior and will take appropriate and fair corrective action in
response to any behavior that they deem inappropriate, threatening, offensive,
or harmful.
Community leaders have the right and responsibility to remove, edit, or reject
comments, commits, code, wiki edits, issues, and other contributions that are
not aligned to this Code of Conduct, and will communicate reasons for moderation
decisions when appropriate.
## Scope
This Code of Conduct applies within all community spaces, and also applies when
an individual is officially representing the community in public spaces.
Examples of representing our community include using an official e-mail address,
posting via an official social media account, or acting as an appointed
representative at an online or offline event.
## Enforcement
Instances of abusive, harassing, or otherwise unacceptable behavior may be
reported to the community leaders responsible for enforcement at
.
All complaints will be reviewed and investigated promptly and fairly.
All community leaders are obligated to respect the privacy and security of the
reporter of any incident.
## Enforcement Guidelines
Community leaders will follow these Community Impact Guidelines in determining
the consequences for any action they deem in violation of this Code of Conduct:
### 1. Correction
**Community Impact**: Use of inappropriate language or other behavior deemed
unprofessional or unwelcome in the community.
**Consequence**: A private, written warning from community leaders, providing
clarity around the nature of the violation and an explanation of why the
behavior was inappropriate. A public apology may be requested.
### 2. Warning
**Community Impact**: A violation through a single incident or series
of actions.
**Consequence**: A warning with consequences for continued behavior. No
interaction with the people involved, including unsolicited interaction with
those enforcing the Code of Conduct, for a specified period of time. This
includes avoiding interactions in community spaces as well as external channels
like social media. Violating these terms may lead to a temporary or
permanent ban.
### 3. Temporary Ban
**Community Impact**: A serious violation of community standards, including
sustained inappropriate behavior.
**Consequence**: A temporary ban from any sort of interaction or public
communication with the community for a specified period of time. No public or
private interaction with the people involved, including unsolicited interaction
with those enforcing the Code of Conduct, is allowed during this period.
Violating these terms may lead to a permanent ban.
### 4. Permanent Ban
**Community Impact**: Demonstrating a pattern of violation of community
standards, including sustained inappropriate behavior, harassment of an
individual, or aggression toward or disparagement of classes of individuals.
**Consequence**: A permanent ban from any sort of public interaction within
the community.
## Attribution
This Code of Conduct is adapted from the [Contributor Covenant][homepage],
version 2.0, available at
https://www.contributor-covenant.org/version/2/0/code_of_conduct.html.
Community Impact Guidelines were inspired by [Mozilla's code of conduct
enforcement ladder](https://github.com/mozilla/diversity).
[homepage]: https://www.contributor-covenant.org
For answers to common questions about this code of conduct, see the FAQ at
https://www.contributor-covenant.org/faq. Translations are available at
https://www.contributor-covenant.org/translations.

View File

@@ -0,0 +1,26 @@
# How to Contribute
## Reporting a bug
* **Do not open up a GitHub issue if the bug is a security vulnerability**, and instead to refer to our [Security policy](SECURITY.md).
* Ensure the bug was not already reported by searching on GitHub Issues.
* If you're unable to find an open issue addressing the problem, open a new one. Be sure to include a **title and clear description**, as much relevant information as possible, and a **code sample** or an **executable test case** demonstrating the expected behavior that is not occurring.
## Submitting a bug fix
* Open a new GitHub pull request with the patch.
* Ensure the PR description clearly describes the problem and solution. Include the relevant issue number if applicable.
* Ensure the new code is following the existing conventions and the unit test coverage is 100%.
* Before submitting, please run the following command locally to ensure the code is passing the automatic checks: `make buildall`.
## Add a new feature or change an existing one
* Before writing any code please suggest the change by opening a new Feature Request on Issues.

View File

@@ -0,0 +1,862 @@
**********************************************************************
* LICENSE
*
* SOFTWARE : tc-lib-pdf-font
* AUTHOR : Nicola Asuni <info@tecnick.com>
* COPYRIGHT : 2011-2025 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. <http://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. <http://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 <http://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
<http://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
<http://www.gnu.org/philosophy/why-not-lgpl.html>.
**********************************************************************
**********************************************************************

View File

@@ -0,0 +1,313 @@
# makefile
#
# @since 2015-05-14
# @category Library
# @package PdfFont
# @author Nicola Asuni <info@tecnick.com>
# @copyright 2011-2024 Nicola Asuni - Tecnick.com LTD
# @license http://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=$(dir $(realpath $(firstword $(MAKEFILE_LIST))))
# Target directory
TARGETDIR=$(CURRENTDIR)target
# RPM Packaging path (where RPMs will be stored)
PATHRPMPKG=$(TARGETDIR)/RPM
# DEB Packaging path (where DEBs will be stored)
PATHDEBPKG=$(TARGETDIR)/DEB
# BZ2 Packaging path (where BZ2s will be stored)
PATHBZ2PKG=$(TARGETDIR)/BZ2
# 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
# --- MAKE TARGETS ---
# Display general help about this command
.PHONY: help
help:
@echo ""
@echo "$(PROJECT) Makefile."
@echo "The following commands are available:"
@echo ""
@echo " make buildall : Build and test everything from scratch"
@echo " make bz2 : Package the library in a compressed bz2 archive"
@echo " make clean : Delete the vendor and target directories"
@echo " make codefix : Fix code style violations"
@echo " make deb : Build a DEB package for Debian-like Linux distributions"
@echo " make deps : Download all dependencies"
@echo " make doc : Generate source code documentation"
@echo " make lint : Test source code for coding standard violations"
@echo " make qa : Run all tests and reports"
@echo " make report : Generate various reports"
@echo " make rpm : Build an RPM package for RedHat-like Linux distributions"
@echo " make server : Start the development server"
@echo " make test : Run unit tests"
@echo " make versionup: Increase the version patch number"
@echo ""
@echo " make fonts : Import and convert fonts"
@echo " make rpm_fonts: Build fonts RPM packages"
@echo " make deb_fonts: Build fonts DEB packages"
@echo " make bz2_fonts: Build fonts tar bz2 (tbz2) compressed archives"
@echo ""
@echo "To test and build everything from scratch:"
@echo "make buildall"
@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 codefix 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
# Fix code style violations
.PHONY: codefix
codefix:
./vendor/bin/phpcbf --ignore="./vendor/" --standard=psr12 src test
# 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 -exec sed -i "s/~#DATE#~/`date -R`/" {} \;
find $(PATHDEBPKG)/$(PKGNAME)-$(VERSION)/debian/ -type f -exec sed -i "s/~#VENDOR#~/$(VENDOR)/" {} \;
find $(PATHDEBPKG)/$(PKGNAME)-$(VERSION)/debian/ -type f -exec sed -i "s/~#PROJECT#~/$(PROJECT)/" {} \;
find $(PATHDEBPKG)/$(PKGNAME)-$(VERSION)/debian/ -type f -exec sed -i "s/~#PKGNAME#~/$(PKGNAME)/" {} \;
find $(PATHDEBPKG)/$(PKGNAME)-$(VERSION)/debian/ -type f -exec sed -i "s/~#VERSION#~/$(VERSION)/" {} \;
find $(PATHDEBPKG)/$(PKGNAME)-$(VERSION)/debian/ -type f -exec sed -i "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/* $(TARGETDIR)/fonts
($(COMPOSER) install -vvv --no-interaction)
curl --silent --show-error --fail --location --output ./vendor/phpstan.phar https://github.com/phpstan/phpstan/releases/download/2.1.2/phpstan.phar \
&& chmod +x ./vendor/phpstan.phar
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
# Test source code for coding standard violations
.PHONY: lint
lint:
./vendor/bin/phpcs --ignore="./vendor/" --standard=phpcs.xml src test
./vendor/bin/phpmd src text codesize,unusedcode,naming,design --exclude vendor
./vendor/bin/phpmd test text unusedcode,naming,design --exclude vendor
php -r 'exit((int)version_compare(PHP_MAJOR_VERSION, "7", ">"));' || ./vendor/phpstan.phar analyse
# 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:
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 "_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:
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} ; \
)

View File

@@ -0,0 +1,105 @@
# tc-lib-pdf-font
*PHP library containing PDF font methods and utilities*
[![Latest Stable Version](https://poser.pugx.org/tecnickcom/tc-lib-pdf-font/version)](https://packagist.org/packages/tecnickcom/tc-lib-pdf-font)
![Build](https://github.com/tecnickcom/tc-lib-pdf-font/actions/workflows/check.yml/badge.svg)
[![Coverage](https://codecov.io/gh/tecnickcom/tc-lib-pdf-font/graph/badge.svg?token=wGN6UnOAFo)](https://codecov.io/gh/tecnickcom/tc-lib-pdf-font)
[![License](https://poser.pugx.org/tecnickcom/tc-lib-pdf-font/license)](https://packagist.org/packages/tecnickcom/tc-lib-pdf-font)
[![Downloads](https://poser.pugx.org/tecnickcom/tc-lib-pdf-font/downloads)](https://packagist.org/packages/tecnickcom/tc-lib-pdf-font)
[![Donate via PayPal](https://img.shields.io/badge/donate-paypal-87ceeb.svg)](https://www.paypal.com/donate/?hosted_button_id=NZUEC5XS8MFBJ)
*Please consider supporting this project by making a donation via [PayPal](https://www.paypal.com/donate/?hosted_button_id=NZUEC5XS8MFBJ)*
* **category** Library
* **package** \Com\Tecnick\Pdf\Font
* **author** Nicola Asuni <info@tecnick.com>
* **copyright** 2011-2025 Nicola Asuni - Tecnick.com LTD
* **license** http://www.gnu.org/copyleft/lesser.html GNU-LGPL v3 (see LICENSE.TXT)
* **link** https://github.com/tecnickcom/tc-lib-pdf-font
* **SRC DOC** https://tcpdf.org/docs/srcdoc/tc-lib-pdf-font
## Description
PHP library containing PDF font methods and utilities.
The initial source code has been derived from [TCPDF](<http://www.tcpdf.org>).
## Getting started
First, you need to install all development dependencies using [Composer](https://getcomposer.org/):
```bash
$ curl -sS https://getcomposer.org/installer | php
$ mv composer.phar /usr/local/bin/composer
```
This project include a Makefile that allows you to test and build the project with simple commands.
To see all available options:
```bash
make help
```
To install all the development dependencies:
```bash
make deps
```
## Running all tests
Before committing the code, please check if it passes all tests using
```bash
make qa
```
All artifacts are generated in the target directory.
To generate the default fonts you can use the command:
```bash
make fonts
```
The files are generated inside the `target/fonts` folder.
Please check the `util/convert.php` and `util/bulk_convert.php` to manually convert fonts.
## Installation
Create a composer.json in your projects root-directory:
```json
{
"require": {
"tecnickcom/tc-lib-pdf-font": "^2.0"
}
}
```
Or add to an existing project with:
```bash
composer require tecnickcom/tc-lib-pdf-font ^2.0
```
## Font conversion
To import fonts in bulk, please check the convert program in resources/cli.
## Packaging
This library is mainly intended to be used and included in other PHP projects using Composer.
However, since some production environments dictates the installation of any application as RPM or DEB packages,
this library includes make targets for building these packages (`make rpm` and `make deb`).
The packages are generated under the `target` directory.
When this library is installed using an RPM or DEB package, you can use it your code by including the autoloader:
```
require_once ('/usr/share/php/Com/Tecnick/Pdf/Font/autoload.php');
```
## Developer(s) Contact
* Nicola Asuni <info@tecnick.com>

View File

@@ -0,0 +1 @@
0

View File

@@ -0,0 +1,5 @@
# Security Policy
## Reporting a Vulnerability
Please report (suspected) security vulnerabilities to info@tecnick.com.

View File

@@ -0,0 +1 @@
2.6.12

View File

@@ -0,0 +1,46 @@
{
"name": "tecnickcom/tc-lib-pdf-font",
"description": "PHP library containing PDF page formats and definitions",
"type": "library",
"homepage": "http://www.tecnick.com",
"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"
}
],
"require": {
"php": ">=8.1",
"ext-json": "*",
"ext-pcre": "*",
"ext-zlib": "*",
"tecnickcom/tc-lib-file": "^2.2",
"tecnickcom/tc-lib-unicode-data": "^2.0",
"tecnickcom/tc-lib-pdf-encrypt": "^2.1"
},
"require-dev": {
"pdepend/pdepend": "2.16.2",
"phpmd/phpmd": "2.15.0",
"phpunit/phpunit": "12.2.0 || 11.5.7 || 10.5.40",
"squizlabs/php_codesniffer": "3.13.0"
},
"autoload": {
"psr-4": {
"Com\\Tecnick\\Pdf\\Font\\": "src"
}
},
"autoload-dev": {
"psr-4": { "Test\\": "test" }
}
}

View File

@@ -0,0 +1,15 @@
{
"source-providers": [
{
"in": "src as source",
"exclude": "vendor",
"name": "/\\.(php)$/"
}
],
"plugins": [
],
"analysers": [
],
"services": [
]
}

View File

@@ -0,0 +1,7 @@
<?xml version="1.0"?>
<ruleset name="backward-compatibility">
<description>PSR-12 for PHP less than 7.1</description>
<rule ref="PSR12">
<exclude name="PSR12.Properties.ConstantVisibility"/>
</rule>
</ruleset>

View File

@@ -0,0 +1,10 @@
parameters:
level: 6
paths:
- src
- test
excludePaths:
- vendor
ignoreErrors:
reportUnmatchedIgnoredErrors: false
treatPhpDocTypesAsCertain: false

View File

@@ -0,0 +1,31 @@
<?xml version="1.0" encoding="UTF-8"?>
<phpunit backupGlobals="false"
bootstrap="vendor/autoload.php"
colors="true"
displayDetailsOnTestsThatTriggerDeprecations="true"
displayDetailsOnTestsThatTriggerErrors="true"
displayDetailsOnTestsThatTriggerNotices="true"
displayDetailsOnTestsThatTriggerWarnings="true"
displayDetailsOnPhpunitDeprecations="true"
processIsolation="false"
stopOnFailure="false">
<testsuites>
<testsuite name="tc-lib-pdf-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>

View File

@@ -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-2024 Nicola Asuni - Tecnick.com LTD
* @license http://www.gnu.org/copyleft/lesser.html GNU-LGPL v3 (see LICENSE.TXT)
* @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;
}
}
);

View 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#~

View File

@@ -0,0 +1 @@
10

View File

@@ -0,0 +1,15 @@
Source: ~#PKGNAME#~
Maintainer: Nicola Asuni <info@tecnick.com>
Section: php
Priority: optional
Build-Depends: debhelper (>= 9)
Standards-Version: 3.9.7
Homepage: https://github.com/~#VENDOR#~/~#PROJECT#~
Vcs-Git: https://github.com/~#VENDOR#~/~#PROJECT#~.git
Package: ~#PKGNAME#~
Provides: php-~#PROJECT#~
Architecture: all
Depends: php (>= 8.1.0), php-json, php-zip, php-tecnickcom-tc-lib-file (<< 3.0.0), php-tecnickcom-tc-lib-file (>= 2.2.2), php-tecnickcom-tc-lib-unicode-data (<< 3.0.0), php-tecnickcom-tc-lib-unicode-data (>= 2.0.24), php-tecnickcom-tc-lib-pdf-encrypt (<< 3.0.0), php-tecnickcom-tc-lib-pdf-encrypt (>= 2.1.16), php-tecnickcom-tc-lib-pdf-font-core (<< 2.0.0), php-tecnickcom-tc-lib-pdf-font-data-core (>= 1.8.7), ${misc:Depends}
Description: PHP PDF Fonts Library
PHP library containing PDF font methods and utilities.

View File

@@ -0,0 +1,20 @@
Format: http://www.debian.org/doc/packaging-manuals/copyright-format/1.0/
Upstream-Name: ~#PROJECT#~
Source: https://github.com/~#VENDOR#~/~#PROJECT#~
Files: *
Copyright: Copyright 2001-2024 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 <http://www.gnu.org/licenses/> or
/usr/share/common-licenses/LGPL-3

View File

@@ -0,0 +1,3 @@
#!/usr/bin/make -f
%:
dh $@

View File

@@ -0,0 +1 @@
3.0 (quilt)

View 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#~

View File

@@ -0,0 +1 @@
10

View File

@@ -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.

View File

@@ -0,0 +1,14 @@
Format: http://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

View File

@@ -0,0 +1,3 @@
#!/usr/bin/make -f
%:
dh $@

View File

@@ -0,0 +1 @@
3.0 (quilt)

View File

@@ -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 2024 Nicola Asuni <info@tecnick.com> 1.0.0-1
- Initial Commit

View File

@@ -0,0 +1,57 @@
# 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
Group: Development/Libraries
License: LGPL-3.0+
URL: https://github.com/%{gh_owner}/%{gh_project}
BuildRoot: %{_tmppath}/%{name}-%{version}-%{release}-%(%{__id_u} -n)
BuildArch: noarch
Requires: php(language) >= 8.1.0
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) >= 2.2.2
Requires: php-composer(%{c_vendor}/tc-lib-unicode-data) < 3.0.0
Requires: php-composer(%{c_vendor}/tc-lib-unicode-data) >= 2.0.24
Requires: php-composer(%{c_vendor}/tc-lib-pdf-encrypt) < 3.0.0
Requires: php-composer(%{c_vendor}/tc-lib-pdf-encrypt) >= 2.1.16
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
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 $RPM_BUILD_ROOT
(cd %{_current_directory} && make install DESTDIR=$RPM_BUILD_ROOT)
%clean
rm -rf $RPM_BUILD_ROOT
#(cd %{_current_directory} && make clean)
%files
%attr(-,root,root) %{_libpath}
%attr(-,root,root) %{_docpath}
%docdir %{_docpath}
#%config(noreplace) %{_configpath}*
%changelog
* Mon Aug 10 2024 Nicola Asuni <info@tecnick.com> 1.0.0-1
- Initial Commit

View File

@@ -0,0 +1,298 @@
<?php
/**
* Buffer.php
*
* @since 2011-05-23
* @category Library
* @package PdfFont
* @author Nicola Asuni <info@tecnick.com>
* @copyright 2011-2024 Nicola Asuni - Tecnick.com LTD
* @license http://www.gnu.org/copyleft/lesser.html GNU-LGPL v3 (see LICENSE.TXT)
* @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\Buffer
*
* @since 2011-05-23
* @category Library
* @package PdfFont
* @author Nicola Asuni <info@tecnick.com>
* @copyright 2011-2024 Nicola Asuni - Tecnick.com LTD
* @license http://www.gnu.org/copyleft/lesser.html GNU-LGPL v3 (see LICENSE.TXT)
* @link https://github.com/tecnickcom/tc-lib-pdf-font
*
* @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;
/**
* 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 = [];
/**
* Initialize fonts buffer
*
* @param float $kunit Unit of measure conversion ratio.
* @param bool $subset If true embedd only a subset of the fonts
* (stores only the information related to
* the used characters); If false embedd
* full font; This option is valid only for
* TrueTypeUnicode fonts and it 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 otherwhise.
* @param bool $pdfa True if we are in PDF/A mode.
*
* @return string Font key
*/
public function __construct(
protected float $kunit,
protected bool $subset = false,
protected bool $unicode = true,
protected bool $pdfa = false
) {
}
/**
* 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
*/
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 it 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
) {
if ($subset === null) {
$subset = $this->subset;
}
$fobj = new Font($font, $style, $ifile, $subset, $this->unicode, $this->pdfa);
$key = $fobj->getFontkey();
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;
return $key;
}
/**
* Set font file and subset
*
* @param string $key Font key
*/
protected function setFontFile(string $key): void
{
if (empty($this->font[$key]['file'])) {
return;
}
$file = $this->font[$key]['file'];
if (! isset($this->file[$file])) {
$this->file[$file] = [
'dir' => '',
'keys' => [],
'length1' => 0,
'length2' => 0,
'subset' => false,
];
}
if (! in_array($key, $this->file[$file]['keys'])) {
$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'];
$this->file[$file]['subset'] = ($this->file[$file]['subset'] && $this->font[$key]['subset']);
}
/**
* Set font diff
*
* @param string $key Font key
*/
protected function setFontDiff(string $key): void
{
if (empty($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;
}
}

View File

@@ -0,0 +1,60 @@
<?php
/**
* Core.php
*
* @since 2011-05-23
* @category Library
* @package PdfFont
* @author Nicola Asuni <info@tecnick.com>
* @copyright 2011-2024 Nicola Asuni - Tecnick.com LTD
* @license http://www.gnu.org/copyleft/lesser.html GNU-LGPL v3 (see LICENSE.TXT)
* @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-2024 Nicola Asuni - Tecnick.com LTD
* @license http://www.gnu.org/copyleft/lesser.html GNU-LGPL v3 (see LICENSE.TXT)
* @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',
];
}

View File

@@ -0,0 +1,34 @@
<?php
/**
* Exception.php
*
* @since 2011-05-23
* @category Library
* @package PdfFont
* @author Nicola Asuni <info@tecnick.com>
* @copyright 2011-2024 Nicola Asuni - Tecnick.com LTD
* @license http://www.gnu.org/copyleft/lesser.html GNU-LGPL v3 (see LICENSE.TXT)
* @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-2024 Nicola Asuni - Tecnick.com LTD
* @license http://www.gnu.org/copyleft/lesser.html GNU-LGPL v3 (see LICENSE.TXT)
* @link https://github.com/tecnickcom/tc-lib-pdf-font
*/
class Exception extends \Exception
{
}

View File

@@ -0,0 +1,207 @@
<?php
/**
* Font.php
*
* @since 2011-05-23
* @category Library
* @package PdfFont
* @author Nicola Asuni <info@tecnick.com>
* @copyright 2011-2024 Nicola Asuni - Tecnick.com LTD
* @license http://www.gnu.org/copyleft/lesser.html GNU-LGPL v3 (see LICENSE.TXT)
* @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\File\File;
/**
* Com\Tecnick\Pdf\Font\Font
*
* @since 2011-05-23
* @category Library
* @package PdfFont
* @author Nicola Asuni <info@tecnick.com>
* @copyright 2011-2024 Nicola Asuni - Tecnick.com LTD
* @license http://www.gnu.org/copyleft/lesser.html GNU-LGPL v3 (see LICENSE.TXT)
* @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 embedd only a subset of the font
* (stores only the information related to
* the used characters); If false embedd
* full font; This option is valid only for
* TrueTypeUnicode fonts and it 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 if we are in Unicode mode, False otherwhise.
* @param bool $pdfa True if we are in PDF/A mode.
* @param bool $compress Set to false to disable stream compression.
*
* @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
) {
if ($font === '') {
throw new FontException('empty font family name');
}
if (FILE::hasDoubleDots($ifile) || FILE::hasForbiddenProtocol($ifile)) {
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, 255, 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'] = (string) $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;
}
}

View File

@@ -0,0 +1,598 @@
<?php
/**
* Import.php
*
* @since 2011-05-23
* @category Library
* @package PdfFont
* @author Nicola Asuni <info@tecnick.com>
* @copyright 2011-2024 Nicola Asuni - Tecnick.com LTD
* @license http://www.gnu.org/copyleft/lesser.html GNU-LGPL v3 (see LICENSE.TXT)
* @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\File;
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-2024 Nicola Asuni - Tecnick.com LTD
* @license http://www.gnu.org/copyleft/lesser.html GNU-LGPL v3 (see LICENSE.TXT)
* @link https://github.com/tecnickcom/tc-lib-pdf-font
*
* @phpstan-import-type TFontData from Load
*
* @SuppressWarnings("PHPMD.ExcessiveClassComplexity")
*/
class Import
{
/**
* 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' => [],
'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 $type Font type. 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.
*
* @throws FontException in case of error
*/
public function __construct(
string $file,
string $output_path = '',
string $type = '',
string $encoding = '',
int $flags = 32,
int $platform_id = 3,
int $encoding_id = 1,
bool $linked = false
) {
if (FILE::hasDoubleDots($file) || FILE::hasForbiddenProtocol($file)) {
throw new FontException('Invalid font file name: ' . $file);
}
$this->fdt['input_file'] = $file;
$this->fdt['file_name'] = $this->makeFontName($file);
if (empty($this->fdt['file_name'])) {
throw new FontException('the font name is empty');
}
$this->fdt['dir'] = $this->findOutputPath($output_path);
$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 = @file_get_contents($file)) === false) {
throw new FontException('unable to read the input font file: ' . $file);
}
$this->font = $font;
$this->fbyte = new Byte($this->font);
$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($this->font, $this->fdt),
'Type1' => new TypeOne($this->font, $this->fdt),
default => new TrueType($this->font, $this->fdt, $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;
}
}
/**
* Save the eported metadata font file
*
* @SuppressWarnings("PHPMD.CyclomaticComplexity")
* @SuppressWarnings("PHPMD.NPathComplexity")
*/
protected function saveFontData(): void
{
$pfile = '{"type":"' . $this->fdt['type'] . '"'
. ',"name":"' . $this->fdt['name'] . '"'
. ',"up":' . $this->fdt['underlinePosition']
. ',"ut":' . $this->fdt['underlineThickness']
. ',"dw":' . (($this->fdt['MissingWidth'] > 0) ? $this->fdt['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('', 131072, "\x00"); // (256 * 256 * 2) = 131072
foreach ($this->fdt['ctgdata'] as $cid => $gid) {
$cidtogidmap = $this->updateCIDtoGIDmap($cidtogidmap, (int) $cid, (int) $gid);
}
// store compressed CIDToGIDMap
$file = new File();
$fpt = $file->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":' . $this->fdt['MissingWidth']
. '}';
if (! empty($this->fdt['cbbox'])) {
$ccboxstr = '';
foreach ($this->fdt['cbbox'] as $cid => $bbox) {
$ccboxstr .= ',"' . $cid . '":[' . $bbox[0] . ',' . $bbox[1] . ',' . $bbox[2] . ',' . $bbox[3] . ']';
}
$pfile .= ',"cbbox":{' . substr($ccboxstr, 1) . '}';
}
if (! empty($this->fdt['cw'])) {
$cwstr = '';
foreach ($this->fdt['cw'] as $cid => $width) {
$cwstr .= ',"' . $cid . '":' . $width;
}
$pfile .= ',"cw":{' . substr($cwstr, 1) . '}';
}
$pfile .= '}' . "\n";
// store file
$file = new File();
$fpt = $file->fopenLocal($this->fdt['datafile'], 'wb');
fwrite($fpt, $pfile);
fclose($fpt);
}
/**
* Make the output font name
*
* @param string $font_file Input font file
*/
protected function makeFontName(string $font_file): string
{
$font_path_parts = pathinfo($font_file);
if (empty($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 !== ''
&& (strpos($output_path, '://') === false)
&& !FILE::hasDoubleDots($output_path)
&& is_writable($output_path)
) {
return $output_path;
}
if (defined('K_PATH_FONTS') && is_writable(K_PATH_FONTS)) {
return K_PATH_FONTS;
}
$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.
*/
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) == 0x10000) {
return 'TrueTypeUnicode';
}
return 'Type1';
}
if (str_starts_with($font_type, 'CID0')) {
return 'cidfont0';
}
if (in_array($font_type, ['Core', 'Type1', 'TrueType', 'TrueTypeUnicode'])) {
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.
*/
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'))
&& (! empty($this->fdt['enc'])
&& (is_string($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) {
if ($enc_target[$idx] != $enc_ref[$idx]) {
if ($idx != $last + 1) {
$diff .= $idx . ' ';
}
$last = $idx;
$diff .= '/' . $enc_target[$idx] . ' ';
}
}
}
return $diff;
}
/**
* Update the CIDToGIDMap string with a new value
*
* @param string $map CIDToGIDMap.
* @param int $cid CID value.
* @param int $gid GID value.
*/
protected function updateCIDtoGIDmap(string $map, int $cid, int $gid): string
{
if (($cid >= 0) && ($cid <= 0xFFFF) && ($gid >= 0)) {
if ($gid > 0xFFFF) {
$gid -= 0x10000;
}
$map[($cid * 2)] = chr($gid >> 8);
$map[(($cid * 2) + 1)] = chr($gid & 0xFF);
}
return $map;
}
}

View File

@@ -0,0 +1,227 @@
<?php
/**
* Core.php
*
* @since 2011-05-23
* @category Library
* @package PdfFont
* @author Nicola Asuni <info@tecnick.com>
* @copyright 2011-2024 Nicola Asuni - Tecnick.com LTD
* @license http://www.gnu.org/copyleft/lesser.html GNU-LGPL v3 (see LICENSE.TXT)
* @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;
use Com\Tecnick\Pdf\Font\Exception as FontException;
/**
* Com\Tecnick\Pdf\Font\Import\Core
*
* @since 2011-05-23
* @category Library
* @package PdfFont
* @author Nicola Asuni <info@tecnick.com>
* @copyright 2011-2024 Nicola Asuni - Tecnick.com LTD
* @license http://www.gnu.org/copyleft/lesser.html GNU-LGPL v3 (see LICENSE.TXT)
* @link https://github.com/tecnickcom/tc-lib-pdf-font
*
* @phpstan-import-type TFontData from \Com\Tecnick\Pdf\Font\Load
*/
class Core
{
/**
* @param string $font Content of the input font file
* @param TFontData $fdt Extracted font metrics
*
* @throws FontException in case of error
*/
public function __construct(
protected string $font,
protected array $fdt
) {
$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 (! empty($cwidths[32])) {
$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'];
}
}
$this->fdt['AvgWidth'] = (int) round($this->fdt['AvgWidth'] / count($cwidths));
}
/**
* Extract Metrics
*/
protected function extractMetrics(): void
{
$cwd = [];
$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->setCharWidths($cwd);
}
/**
* Extract Metrics
*
* @param array<int, string> $col Array containing row elements to process
* @param array<int, int> $cwd Array contianing 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':
$cid = (int) $col[1];
if ($cid >= 0) {
$cwd[$cid] = (int) $col[4];
if (! empty($col[14])) {
$this->fdt['cbbox'][$cid] = [(int) $col[10], (int) $col[11], (int) $col[12], (int) $col[13]];
}
}
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
*/
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']);
if (empty($this->fdt['XHeight'])) {
$this->fdt['XHeight'] = 0;
}
}
protected function setMissingValues(): void
{
$this->fdt['Descender'] = $this->fdt['FontBBox'][1];
$this->fdt['Ascender'] = $this->fdt['FontBBox'][3];
if (empty($this->fdt['CapHeight'])) {
$this->fdt['CapHeight'] = $this->fdt['Ascender'];
}
}
/**
* Process Core font
*/
protected function process(): void
{
$this->extractMetrics();
$this->setFlags();
$this->setMissingValues();
$this->remapValues();
}
}

View File

@@ -0,0 +1,811 @@
<?php
/**
* TrueType.php
*
* @since 2011-05-23
* @category Library
* @package PdfFont
* @author Nicola Asuni <info@tecnick.com>
* @copyright 2011-2024 Nicola Asuni - Tecnick.com LTD
* @license http://www.gnu.org/copyleft/lesser.html GNU-LGPL v3 (see LICENSE.TXT)
* @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\Byte;
use Com\Tecnick\File\File;
use Com\Tecnick\Pdf\Font\Exception as FontException;
use Com\Tecnick\Unicode\Data\Encoding;
/**
* Com\Tecnick\Pdf\Font\Import\TrueType
*
* @since 2011-05-23
* @category Library
* @package PdfFont
* @author Nicola Asuni <info@tecnick.com>
* @copyright 2011-2024 Nicola Asuni - Tecnick.com LTD
* @license http://www.gnu.org/copyleft/lesser.html GNU-LGPL v3 (see LICENSE.TXT)
* @link https://github.com/tecnickcom/tc-lib-pdf-font
*
* @phpstan-import-type TFontData from \Com\Tecnick\Pdf\Font\Load
*
* @SuppressWarnings("PHPMD.ExcessiveClassComplexity")
* @SuppressWarnings("PHPMD.ExcessiveClassLength")
*/
class TrueType
{
/**
* Array containing subset chars
*
* @var array<int, bool>
*/
protected array $subchars = [];
/**
* Array containing subset glyphs indexes of chars from cmap table
*
* @var array<int, bool>
*/
protected array $subglyphs = [
0 => true,
];
/**
* Pointer position on the original font data
*/
protected int $offset = 0;
/**
* Process TrueType font
*
* @param string $font Content of the input font file
* @param TFontData $fdt Extracted font metrics
* @param Byte $fbyte Object used to read font bytes
* @param array<int, bool> $subchars Array containing subset chars
*
* @throws FontException in case of error
*/
public function __construct(
protected string $font,
protected array $fdt,
protected Byte $fbyte,
array $subchars = []
) {
ksort($subchars);
$this->subchars = $subchars;
$this->process();
}
/**
* Get all the extracted font metrics
*
* @return TFontData
*/
public function getFontMetrics(): array
{
return $this->fdt;
}
/**
* Get glyphs in the subset
*
* @return array<int, bool>
*/
public function getSubGlyphs(): array
{
return $this->subglyphs;
}
/**
* Process TrueType font
*/
protected function process(): void
{
$this->isValidType();
$this->setFontFile();
$this->getTables();
$this->checkMagickNumber();
$this->offset += 2; // skip flags
$this->getBbox();
$this->getIndexToLoc();
$this->getEncodingTables();
$this->getOS2Metrics();
$this->getFontName();
$this->getPostData();
$this->getHheaData();
$this->getMaxpData();
$this->getCIDToGIDMap();
$this->getHeights();
$this->getWidths();
}
/**
* Check if the font is a valid type
*
* @throws FontException if the font is invalid
*/
protected function isValidType(): void
{
if ($this->fbyte->getULong($this->offset) != 0x10000) {
throw new FontException('sfnt version must be 0x00010000 for TrueType version 1.0.');
}
$this->offset += 4;
}
/**
* Copy or link the original font file
*/
protected function setFontFile(): void
{
if (! empty($this->fdt['desc']['MaxWidth'])) {
// subsetting mode
$this->fdt['Flags'] = $this->fdt['desc']['Flags'];
return;
}
if ($this->fdt['type'] == 'cidfont0') {
return;
}
if ($this->fdt['linked']) {
// creates a symbolic link to the existing font
symlink($this->fdt['input_file'], $this->fdt['dir'] . $this->fdt['file_name']);
return;
}
// store compressed font
$this->fdt['file'] = $this->fdt['file_name'] . '.z';
$file = new File();
$fpt = $file->fopenLocal($this->fdt['dir'] . $this->fdt['file'], 'wb');
$cmpr = gzcompress($this->font);
if ($cmpr === false) {
throw new FontException('Error compressing font file.');
}
fwrite($fpt, $cmpr);
fclose($fpt);
}
/**
* Get the font tables
*/
protected function getTables(): void
{
// get number of tables
$numTables = $this->fbyte->getUShort($this->offset);
$this->offset += 2;
// skip searchRange, entrySelector and rangeShift
$this->offset += 6;
// tables array
$this->fdt['table'] = [];
// ---------- get tables ----------
for ($idx = 0; $idx < $numTables; ++$idx) {
// get table info
$tag = substr($this->font, $this->offset, 4);
$this->offset += 4;
$this->fdt['table'][$tag] = [
'checkSum' => 0,
'data' => '',
'length' => 0,
'offset' => 0,
];
$this->fdt['table'][$tag]['checkSum'] = $this->fbyte->getULong($this->offset);
$this->offset += 4;
$this->fdt['table'][$tag]['offset'] = $this->fbyte->getULong($this->offset);
$this->offset += 4;
$this->fdt['table'][$tag]['length'] = $this->fbyte->getULong($this->offset);
$this->offset += 4;
}
}
/**
* Check if the font is a valid type
*
* @throws FontException if the font is invalid
*/
protected function checkMagickNumber(): void
{
$this->offset = ($this->fdt['table']['head']['offset'] + 12);
if ($this->fbyte->getULong($this->offset) != 0x5F0F3CF5) {
// magicNumber must be 0x5F0F3CF5
throw new FontException('magicNumber must be 0x5F0F3CF5');
}
$this->offset += 4;
}
/**
* Get BBox, units and flags
*/
protected function getBbox(): void
{
$this->fdt['unitsPerEm'] = $this->fbyte->getUShort($this->offset);
$this->offset += 2;
// units ratio constant
$this->fdt['urk'] = (1000 / $this->fdt['unitsPerEm']);
$this->offset += 16; // skip created, modified
$xMin = (int) round($this->fbyte->getFWord($this->offset) * $this->fdt['urk']);
$this->offset += 2;
$yMin = (int) round($this->fbyte->getFWord($this->offset) * $this->fdt['urk']);
$this->offset += 2;
$xMax = (int) round($this->fbyte->getFWord($this->offset) * $this->fdt['urk']);
$this->offset += 2;
$yMax = (int) round($this->fbyte->getFWord($this->offset) * $this->fdt['urk']);
$this->offset += 2;
$this->fdt['bbox'] = $xMin . ' ' . $yMin . ' ' . $xMax . ' ' . $yMax;
$macStyle = $this->fbyte->getUShort($this->offset);
$this->offset += 2;
// PDF font flags
if (($macStyle & 2) == 2) {
// italic flag
$this->fdt['Flags'] |= 64;
}
}
/**
* Get index to loc map
*/
protected function getIndexToLoc(): void
{
// get offset mode (indexToLocFormat : 0 = short, 1 = long)
$this->offset = ($this->fdt['table']['head']['offset'] + 50);
$this->fdt['short_offset'] = ($this->fbyte->getShort($this->offset) == 0);
$this->offset += 2;
// get the offsets to the locations of the glyphs in the font, relative to the beginning of the glyphData table
$this->fdt['indexToLoc'] = [];
$this->offset = $this->fdt['table']['loca']['offset'];
if ($this->fdt['short_offset']) {
// short version
$this->fdt['tot_num_glyphs'] = (int) floor($this->fdt['table']['loca']['length'] / 2); // numGlyphs + 1
for ($idx = 0; $idx < $this->fdt['tot_num_glyphs']; ++$idx) {
$this->fdt['indexToLoc'][$idx] = $this->fbyte->getUShort($this->offset) * 2;
if (
isset($this->fdt['indexToLoc'][($idx - 1)])
&& ($this->fdt['indexToLoc'][$idx] === $this->fdt['indexToLoc'][($idx - 1)])
) {
// the last glyph didn't have an outline
unset($this->fdt['indexToLoc'][($idx - 1)]);
}
$this->offset += 2;
}
} else {
// long version
$this->fdt['tot_num_glyphs'] = (int) floor($this->fdt['table']['loca']['length'] / 4); // numGlyphs + 1
for ($idx = 0; $idx < $this->fdt['tot_num_glyphs']; ++$idx) {
$this->fdt['indexToLoc'][$idx] = $this->fbyte->getULong($this->offset);
if (
isset($this->fdt['indexToLoc'][($idx - 1)])
&& ($this->fdt['indexToLoc'][$idx] === $this->fdt['indexToLoc'][($idx - 1)])
) {
// the last glyph didn't have an outline
unset($this->fdt['indexToLoc'][($idx - 1)]);
}
$this->offset += 4;
}
}
}
protected function getEncodingTables(): void
{
// get glyphs indexes of chars from cmap table
$this->offset = $this->fdt['table']['cmap']['offset'] + 2;
$numEncodingTables = $this->fbyte->getUShort($this->offset);
$this->offset += 2;
$this->fdt['encodingTables'] = [];
for ($idx = 0; $idx < $numEncodingTables; ++$idx) {
$this->fdt['encodingTables'][$idx]['platformID'] = $this->fbyte->getUShort($this->offset);
$this->offset += 2;
$this->fdt['encodingTables'][$idx]['encodingID'] = $this->fbyte->getUShort($this->offset);
$this->offset += 2;
$this->fdt['encodingTables'][$idx]['offset'] = $this->fbyte->getULong($this->offset);
$this->offset += 4;
}
}
/**
* Get encoding tables
*/
protected function getOS2Metrics(): void
{
$this->offset = $this->fdt['table']['OS/2']['offset'];
$this->offset += 2; // skip version
// xAvgCharWidth
$this->fdt['AvgWidth'] = (int) round($this->fbyte->getFWord($this->offset) * $this->fdt['urk']);
$this->offset += 2;
// usWeightClass
$usWeightClass = round($this->fbyte->getUFWord($this->offset) * $this->fdt['urk']);
// estimate StemV and StemH (400 = usWeightClass for Normal - Regular font)
$this->fdt['StemV'] = (int) round((70 * $usWeightClass) / 400);
$this->fdt['StemH'] = (int) round((30 * $usWeightClass) / 400);
$this->offset += 2;
$this->offset += 2; // usWidthClass
$fsType = $this->fbyte->getShort($this->offset);
$this->offset += 2;
if ($fsType == 2) {
throw new FontException(
'This Font cannot be modified, embedded or exchanged in any manner'
. ' without first obtaining permission of the legal owner.'
);
}
}
protected function getFontName(): void
{
$this->fdt['name'] = '';
$this->offset = $this->fdt['table']['name']['offset'];
$this->offset += 2; // skip Format selector (=0).
// Number of NameRecords that follow n.
$numNameRecords = $this->fbyte->getUShort($this->offset);
$this->offset += 2;
// Offset to start of string storage (from start of table).
$stringStorageOffset = $this->fbyte->getUShort($this->offset);
$this->offset += 2;
for ($idx = 0; $idx < $numNameRecords; ++$idx) {
$this->offset += 6; // skip Platform ID, Platform-specific encoding ID, Language ID.
// Name ID.
$nameID = $this->fbyte->getUShort($this->offset);
$this->offset += 2;
if ($nameID == 6) {
// String length (in bytes).
$stringLength = $this->fbyte->getUShort($this->offset);
$this->offset += 2;
// String offset from start of storage area (in bytes).
$stringOffset = $this->fbyte->getUShort($this->offset);
$this->offset += 2;
$this->offset = ($this->fdt['table']['name']['offset'] + $stringStorageOffset + $stringOffset);
$this->fdt['name'] = substr($this->font, $this->offset, $stringLength);
$name = preg_replace('/[^a-zA-Z0-9_\-]/', '', $this->fdt['name']);
if (($name === null) || ($name === '')) {
throw new FontException('Error getting font name.');
}
$this->fdt['name'] = $name;
break;
} else {
$this->offset += 4; // skip String length, String offset
}
}
}
protected function getPostData(): void
{
$this->offset = $this->fdt['table']['post']['offset'];
$this->offset += 4; // skip Format Type
$this->fdt['italicAngle'] = $this->fbyte->getFixed($this->offset);
$this->offset += 4;
$this->fdt['underlinePosition'] = (int) round($this->fbyte->getFWord($this->offset) * $this->fdt['urk']);
$this->offset += 2;
$this->fdt['underlineThickness'] = (int) round($this->fbyte->getFWord($this->offset) * $this->fdt['urk']);
$this->offset += 2;
$isFixedPitch = ($this->fbyte->getULong($this->offset) != 0);
$this->offset += 2;
if ($isFixedPitch) {
$this->fdt['Flags'] |= 1;
}
}
protected function getHheaData(): void
{
// ---------- get hhea data ----------
$this->offset = $this->fdt['table']['hhea']['offset'];
$this->offset += 4; // skip Table version number
// Ascender
$this->fdt['Ascent'] = (int) round($this->fbyte->getFWord($this->offset) * $this->fdt['urk']);
$this->offset += 2;
// Descender
$this->fdt['Descent'] = (int) round($this->fbyte->getFWord($this->offset) * $this->fdt['urk']);
$this->offset += 2;
// LineGap
$this->fdt['Leading'] = (int) round($this->fbyte->getFWord($this->offset) * $this->fdt['urk']);
$this->offset += 2;
// advanceWidthMax
$this->fdt['MaxWidth'] = (int) round($this->fbyte->getUFWord($this->offset) * $this->fdt['urk']);
$this->offset += 2;
$this->offset += 22; // skip some values
// get the number of hMetric entries in hmtx table
$this->fdt['numHMetrics'] = $this->fbyte->getUShort($this->offset);
}
protected function getMaxpData(): void
{
$this->offset = $this->fdt['table']['maxp']['offset'];
$this->offset += 4; // skip Table version number
// get the the number of glyphs in the font.
$this->fdt['numGlyphs'] = $this->fbyte->getUShort($this->offset);
}
/**
* Get font heights
*/
protected function getHeights(): void
{
// get xHeight (height of x)
$this->fdt['XHeight'] = ($this->fdt['Ascent'] + $this->fdt['Descent']);
if (! empty($this->fdt['ctgdata'][120])) {
$this->offset = (
$this->fdt['table']['glyf']['offset']
+ $this->fdt['indexToLoc'][$this->fdt['ctgdata'][120]]
+ 4
);
$yMin = $this->fbyte->getFWord($this->offset);
$this->offset += 4;
$yMax = $this->fbyte->getFWord($this->offset);
$this->offset += 2;
$this->fdt['XHeight'] = (int) round(($yMax - $yMin) * $this->fdt['urk']);
}
// get CapHeight (height of H)
$this->fdt['CapHeight'] = (int) $this->fdt['Ascent'];
if (! empty($this->fdt['ctgdata'][72])) {
$this->offset = (
$this->fdt['table']['glyf']['offset']
+ $this->fdt['indexToLoc'][$this->fdt['ctgdata'][72]]
+ 4
);
$yMin = $this->fbyte->getFWord($this->offset);
$this->offset += 4;
$yMax = $this->fbyte->getFWord($this->offset);
$this->offset += 2;
$this->fdt['CapHeight'] = (int) round(($yMax - $yMin) * $this->fdt['urk']);
}
}
/**
* Get font widths
*/
protected function getWidths(): void
{
// create widths array
$chw = [];
$this->offset = $this->fdt['table']['hmtx']['offset'];
for ($i = 0; $i < $this->fdt['numHMetrics']; ++$i) {
$chw[$i] = round($this->fbyte->getUFWord($this->offset) * $this->fdt['urk']);
$this->offset += 4; // skip lsb
}
if ($this->fdt['numHMetrics'] < $this->fdt['numGlyphs']) {
// fill missing widths with the last value
$chw = array_pad($chw, $this->fdt['numGlyphs'], $chw[($this->fdt['numHMetrics'] - 1)]);
}
$this->fdt['MissingWidth'] = $chw[0];
$this->fdt['cw'] = [];
$this->fdt['cbbox'] = [];
for ($cid = 0; $cid <= 65535; ++$cid) {
if (isset($this->fdt['ctgdata'][$cid])) {
if (isset($chw[$this->fdt['ctgdata'][$cid]])) {
$this->fdt['cw'][$cid] = $chw[$this->fdt['ctgdata'][$cid]];
}
if (isset($this->fdt['indexToLoc'][$this->fdt['ctgdata'][$cid]])) {
$this->offset = (
$this->fdt['table']['glyf']['offset']
+ $this->fdt['indexToLoc'][$this->fdt['ctgdata'][$cid]]
);
$xMin = (int) round($this->fbyte->getFWord($this->offset + 2) * $this->fdt['urk']);
$yMin = (int) round($this->fbyte->getFWord($this->offset + 4) * $this->fdt['urk']);
$xMax = (int) round($this->fbyte->getFWord($this->offset + 6) * $this->fdt['urk']);
$yMax = (int) round($this->fbyte->getFWord($this->offset + 8) * $this->fdt['urk']);
$this->fdt['cbbox'][$cid] = [$xMin, $yMin, $xMax, $yMax];
}
}
}
}
/**
* Add CTG entry
*/
protected function addCtgItem(int $cid, int $gid): void
{
$this->fdt['ctgdata'][$cid] = $gid;
if (isset($this->subchars[$cid])) {
$this->subglyphs[$gid] = true;
}
}
/**
* Process the CID To GID Map.
*
* @SuppressWarnings("PHPMD.CyclomaticComplexity")
*/
protected function getCIDToGIDMap(): void
{
$this->fdt['ctgdata'] = [];
foreach ($this->fdt['encodingTables'] as $enctable) {
// get only specified Platform ID and Encoding ID
if (
($enctable['platformID'] == $this->fdt['platform_id'])
&& ($enctable['encodingID'] == $this->fdt['encoding_id'])
) {
$this->offset = ($this->fdt['table']['cmap']['offset'] + $enctable['offset']);
$format = $this->fbyte->getUShort($this->offset);
$this->offset += 2;
match ($format) {
0 => $this->processFormat0(),
2 => $this->processFormat2(),
4 => $this->processFormat4(),
6 => $this->processFormat6(),
8 => $this->processFormat8(),
10 => $this->processFormat10(),
12 => $this->processFormat12(),
13 => $this->processFormat13(),
14 => $this->processFormat14(),
default => throw new FontException('Unsupported cmap format: ' . $format),
};
}
}
if (! isset($this->fdt['ctgdata'][0])) {
$this->fdt['ctgdata'][0] = 0;
}
if ($this->fdt['type'] != 'TrueTypeUnicode') {
return;
}
if (count($this->fdt['ctgdata']) != 256) {
return;
}
$this->fdt['type'] = 'TrueType';
}
/**
* Process Format 0: Byte encoding table
*/
protected function processFormat0(): void
{
$this->offset += 4; // skip length and version/language
for ($chr = 0; $chr < 256; ++$chr) {
$gid = $this->fbyte->getByte($this->offset);
$this->addCtgItem($chr, $gid);
++$this->offset;
}
}
/**
* Process Format 2: High-byte mapping through table
*/
protected function processFormat2(): void
{
$this->offset += 4; // skip length and version/language
$numSubHeaders = 0;
for ($chr = 0; $chr < 256; ++$chr) {
// Array that maps high bytes to subHeaders: value is subHeader index * 8.
$subHeaderKeys[$chr] = ($this->fbyte->getUShort($this->offset) / 8);
$this->offset += 2;
if ($numSubHeaders < $subHeaderKeys[$chr]) {
$numSubHeaders = $subHeaderKeys[$chr];
}
}
// the number of subHeaders is equal to the max of subHeaderKeys + 1
++$numSubHeaders;
// read subHeader structures
$subHeaders = [];
$numGlyphIndexArray = 0;
for ($ish = 0; $ish < $numSubHeaders; ++$ish) {
$subHeaders[$ish]['firstCode'] = $this->fbyte->getUShort($this->offset);
$this->offset += 2;
$subHeaders[$ish]['entryCount'] = $this->fbyte->getUShort($this->offset);
$this->offset += 2;
$subHeaders[$ish]['idDelta'] = $this->fbyte->getUShort($this->offset);
$this->offset += 2;
$subHeaders[$ish]['idRangeOffset'] = $this->fbyte->getUShort($this->offset);
$this->offset += 2;
$subHeaders[$ish]['idRangeOffset'] -= (2 + (($numSubHeaders - $ish - 1) * 8));
$subHeaders[$ish]['idRangeOffset'] /= 2;
$numGlyphIndexArray += $subHeaders[$ish]['entryCount'];
}
$glyphIndexArray = [
0 => 0,
];
for ($gid = 0; $gid < $numGlyphIndexArray; ++$gid) {
$glyphIndexArray[$gid] = $this->fbyte->getUShort($this->offset);
$this->offset += 2;
}
for ($chr = 0; $chr < 256; ++$chr) {
$shk = $subHeaderKeys[$chr];
if ($shk == 0) {
// one byte code
$cdx = $chr;
$gid = $glyphIndexArray[0];
$this->addCtgItem($cdx, $gid);
} else {
// two bytes code
$start_byte = $subHeaders[$shk]['firstCode'];
$end_byte = $start_byte + $subHeaders[$shk]['entryCount'];
for ($jdx = $start_byte; $jdx < $end_byte; ++$jdx) {
// combine high and low bytes
$cdx = (($chr << 8) + $jdx);
$idRangeOffset = ($subHeaders[$shk]['idRangeOffset'] + $jdx - $subHeaders[$shk]['firstCode']);
$gid = max(0, (($glyphIndexArray[$idRangeOffset] + $subHeaders[$shk]['idDelta']) % 65536));
$this->addCtgItem($cdx, $gid);
}
}
}
}
/**
* Process Format 4: Segment mapping to delta values
*/
protected function processFormat4(): void
{
$length = $this->fbyte->getUShort($this->offset);
$this->offset += 2;
$this->offset += 2; // skip version/language
$segCount = floor($this->fbyte->getUShort($this->offset) / 2);
$this->offset += 2;
$this->offset += 6; // skip searchRange, entrySelector, rangeShift
$endCount = []; // array of end character codes for each segment
for ($kdx = 0; $kdx < $segCount; ++$kdx) {
$endCount[$kdx] = $this->fbyte->getUShort($this->offset);
$this->offset += 2;
}
$this->offset += 2; // skip reservedPad
$startCount = []; // array of start character codes for each segment
for ($kdx = 0; $kdx < $segCount; ++$kdx) {
$startCount[$kdx] = $this->fbyte->getUShort($this->offset);
$this->offset += 2;
}
$idDelta = []; // delta for all character codes in segment
for ($kdx = 0; $kdx < $segCount; ++$kdx) {
$idDelta[$kdx] = $this->fbyte->getUShort($this->offset);
$this->offset += 2;
}
$idRangeOffset = []; // Offsets into glyphIdArray or 0
for ($kdx = 0; $kdx < $segCount; ++$kdx) {
$idRangeOffset[$kdx] = $this->fbyte->getUShort($this->offset);
$this->offset += 2;
}
$gidlen = (floor($length / 2) - 8 - (4 * $segCount));
$glyphIdArray = []; // glyph index array
for ($kdx = 0; $kdx < $gidlen; ++$kdx) {
$glyphIdArray[$kdx] = $this->fbyte->getUShort($this->offset);
$this->offset += 2;
}
for ($kdx = 0; $kdx < $segCount; ++$kdx) {
for ($chr = $startCount[$kdx]; $chr <= $endCount[$kdx]; ++$chr) {
if ($idRangeOffset[$kdx] == 0) {
$gid = max(0, (($idDelta[$kdx] + $chr) % 65536));
} else {
$gid = (floor($idRangeOffset[$kdx] / 2) + ($chr - $startCount[$kdx]) - ($segCount - $kdx));
$gid = max(0, (($glyphIdArray[$gid] + $idDelta[$kdx]) % 65536));
}
$this->addCtgItem($chr, $gid);
}
}
}
/**
* Process Format 6: Trimmed table mapping
*/
protected function processFormat6(): void
{
$this->offset += 4; // skip length and version/language
$firstCode = $this->fbyte->getUShort($this->offset);
$this->offset += 2;
$entryCount = $this->fbyte->getUShort($this->offset);
$this->offset += 2;
for ($kdx = 0; $kdx < $entryCount; ++$kdx) {
$chr = ($kdx + $firstCode);
$gid = $this->fbyte->getUShort($this->offset);
$this->offset += 2;
$this->addCtgItem($chr, $gid);
}
}
/**
* Process Format 8: Mixed 16-bit and 32-bit coverage
*/
protected function processFormat8(): void
{
$this->offset += 10; // skip reserved, length and version/language
for ($kdx = 0; $kdx < 8192; ++$kdx) {
$is32[$kdx] = $this->fbyte->getByte($this->offset);
++$this->offset;
}
$nGroups = $this->fbyte->getULong($this->offset);
$this->offset += 4;
for ($idx = 0; $idx < $nGroups; ++$idx) {
$startCharCode = $this->fbyte->getULong($this->offset);
$this->offset += 4;
$endCharCode = $this->fbyte->getULong($this->offset);
$this->offset += 4;
$startGlyphID = $this->fbyte->getULong($this->offset);
$this->offset += 4;
for ($cpw = $startCharCode; $cpw <= $endCharCode; ++$cpw) {
$is32idx = floor($cpw / 8);
if ((isset($is32[$is32idx])) && (($is32[$is32idx] & (1 << (7 - ($cpw % 8)))) == 0)) {
$chr = $cpw;
} else {
// 32 bit format
// convert to decimal (http://www.unicode.org/faq//utf_bom.html#utf16-4)
//LEAD_OFFSET = (0xD800 - (0x10000 >> 10)) = 55232
//SURROGATE_OFFSET = (0x10000 - (0xD800 << 10) - 0xDC00) = -56613888
$chr = (((55232 + ($cpw >> 10)) << 10) + (0xDC00 + ($cpw & 0x3FF)) - 56_613_888);
}
$this->addCtgItem($chr, $startGlyphID);
$this->fdt['ctgdata'][$chr] = 0; // overwrite
++$startGlyphID;
}
}
}
/**
* Process Format 10: Trimmed array
*/
protected function processFormat10(): void
{
$this->offset += 10; // skip reserved, length and version/language
$startCharCode = $this->fbyte->getULong($this->offset);
$this->offset += 4;
$numChars = $this->fbyte->getULong($this->offset);
$this->offset += 4;
for ($kdx = 0; $kdx < $numChars; ++$kdx) {
$chr = ($kdx + $startCharCode);
$gid = $this->fbyte->getUShort($this->offset);
$this->addCtgItem($chr, $gid);
$this->offset += 2;
}
}
/**
* Process Format 12: Segmented coverage
*/
protected function processFormat12(): void
{
$this->offset += 10; // skip length and version/language
$nGroups = $this->fbyte->getULong($this->offset);
$this->offset += 4;
for ($kdx = 0; $kdx < $nGroups; ++$kdx) {
$startCharCode = $this->fbyte->getULong($this->offset);
$this->offset += 4;
$endCharCode = $this->fbyte->getULong($this->offset);
$this->offset += 4;
$startGlyphCode = $this->fbyte->getULong($this->offset);
$this->offset += 4;
for ($chr = $startCharCode; $chr <= $endCharCode; ++$chr) {
$this->addCtgItem($chr, $startGlyphCode);
++$startGlyphCode;
}
}
}
/**
* Process Format 13: Many-to-one range mappings
*
* @TODO: TO BE IMPLEMENTED
*/
protected function processFormat13(): void
{
}
/**
* Process Format 14: Unicode Variation Sequences
*
* @TODO: TO BE IMPLEMENTED
*/
protected function processFormat14(): void
{
}
}

View File

@@ -0,0 +1,360 @@
<?php
/**
* TypeOne.php
*
* @since 2011-05-23
* @category Library
* @package PdfFont
* @author Nicola Asuni <info@tecnick.com>
* @copyright 2011-2024 Nicola Asuni - Tecnick.com LTD
* @license http://www.gnu.org/copyleft/lesser.html GNU-LGPL v3 (see LICENSE.TXT)
* @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;
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-2024 Nicola Asuni - Tecnick.com LTD
* @license http://www.gnu.org/copyleft/lesser.html GNU-LGPL v3 (see LICENSE.TXT)
* @link https://github.com/tecnickcom/tc-lib-pdf-font
*
* @SuppressWarnings("PHPMD.ExcessiveClassComplexity")
*/
class TypeOne extends \Com\Tecnick\Pdf\Font\Import\Core
{
/**
* Store font data
*/
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'];
$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'];
$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';
$file = new File();
$fpt = $file->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
*/
protected function extractFontInfo(): void
{
if (preg_match('#/FontName[\s]*+\/([^\s]*+)#', $this->font, $matches) !== 1) {
preg_match('#/FullName[\s]*+\(([^\)]*+)#', $this->font, $matches);
}
$name = preg_replace('/[^a-zA-Z0-9_\-]/', '', $matches[1]);
if ($name === null) {
throw new FontException('Unable to extract font name');
}
$this->fdt['name'] = $name;
preg_match('#/FontBBox[\s]*+{([^}]*+)#', $this->font, $matches);
$rawbvl = explode(' ', trim($matches[1]));
$bvl = [(int) $rawbvl[0], (int) $rawbvl[1], (int) $rawbvl[2], (int) $rawbvl[3]];
$this->fdt['bbox'] = implode(' ', $bvl);
$this->fdt['Ascent'] = $bvl[3];
$this->fdt['Descent'] = $bvl[1];
preg_match('#/ItalicAngle[\s]*+([0-9\+\-]*+)#', $this->font, $matches);
$this->fdt['italicAngle'] = (int) $matches[1];
if ($this->fdt['italicAngle'] != 0) {
$this->fdt['Flags'] |= 64;
}
preg_match('#/UnderlinePosition[\s]*+([0-9\+\-]*+)#', $this->font, $matches);
$this->fdt['underlinePosition'] = (int) $matches[1];
preg_match('#/UnderlineThickness[\s]*+([0-9\+\-]*+)#', $this->font, $matches);
$this->fdt['underlineThickness'] = (int) $matches[1];
preg_match('#/isFixedPitch[\s]*+([^\s]*+)#', $this->font, $matches);
if ($matches[1] == 'true') {
$this->fdt['Flags'] = (((int) $this->fdt['Flags']) | 1);
}
preg_match('#/Weight[\s]*+\(([^\)]*+)#', $this->font, $matches);
if (! empty($matches[1])) {
$this->fdt['weight'] = strtolower($matches[1]);
}
$this->fdt['weight'] = 'Book';
$this->fdt['Leading'] = 0;
}
/**
* Extract Font information
*
* @return array<string, int>
*/
protected function getInternalMap(): array
{
$imap = [];
if (preg_match_all('#dup[\s]([0-9]+)[\s]*+/([^\s]*+)[\s]put#sU', $this->font, $fmap, PREG_SET_ORDER) > 0) {
foreach ($fmap as $val) {
$imap[$val[2]] = (int) $val[1];
}
}
return $imap;
}
/**
* Decrypt eexec encrypted part
*/
protected function getEplain(): string
{
$csr = 55665; // eexec encryption constant
$cc1 = 52845;
$cc2 = 22719;
$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) % 65536);
}
return $eplain;
}
/**
* Extract eexec info
*
* @return array<int, array<int, string>>
*/
protected function extractEplainInfo(): array
{
$eplain = $this->getEplain();
if (preg_match('#/ForceBold[\s]*+([^\s]*+)#', $eplain, $matches) > 0 && $matches[1] == 'true') {
$this->fdt['Flags'] |= 0x40000;
}
$this->extractStem($eplain);
if (preg_match('#/BlueValues[\s]*+\[([^\]]*+)#', $eplain, $matches) > 0) {
$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
{
if (preg_match('#/StdVW[\s]*+\[([^\]]*+)#', $eplain, $matches) > 0) {
$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) > 0 ? (int) $matches[1] : 30;
if (preg_match('#/Cap[X]?Height[\s]*+\[([^\]]*+)#', $eplain, $matches) > 0) {
$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;
if (preg_match('#/lenIV[\s]*+([\d]*+)#', $eplain, $matches) > 0) {
$this->fdt['lenIV'] = (int) $matches[1];
}
}
/**
* @return array<int, array<int, string>>
*/
protected function getCharstringData(string $eplain): array
{
$this->fdt['enc_map'] = [];
$eplain = substr($eplain, (strpos($eplain, '/CharStrings') + 1));
preg_match_all('#/([A-Za-z0-9\.]*+)[\s][0-9]+[\s]RD[\s](.*)[\s]ND#sU', $eplain, $matches, PREG_SET_ORDER);
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]];
}
if ($this->fdt['enc_map'] === false) {
return 0;
}
$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
*/
protected function decodeNumber(
int $idx,
int &$cck,
int &$cid,
array &$ccom,
array &$cdec,
array &$cwidths
): int {
if ($ccom[$idx] == 255) {
$sval = chr($ccom[($idx + 1)]) . chr($ccom[($idx + 2)]) . chr($ccom[($idx + 3)]) . chr($ccom[($idx + 4)]);
$vsval = unpack('li', $sval);
if (($vsval === false) || (!is_numeric($vsval['i']))) {
throw new FontException('Unable to unpack number');
}
$cdec[$cck] = (int) $vsval['i'];
return ($idx + 5);
}
if ($ccom[$idx] >= 251) {
$cdec[$cck] = ((-($ccom[$idx] - 251) * 256) - $ccom[($idx + 1)] - 108);
return ($idx + 2);
}
if ($ccom[$idx] >= 247) {
$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
*/
protected function process(): void
{
$this->storeFontData();
$this->extractFontInfo();
$imap = $this->getInternalMap();
$matches = $this->extractEplainInfo();
$cwidths = [];
$cc1 = 52845;
$cc2 = 22719;
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) % 65536);
}
// 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);
}
}

View File

@@ -0,0 +1,506 @@
<?php
/**
* Load.php
*
* @since 2011-05-23
* @category Library
* @package PdfFont
* @author Nicola Asuni <info@tecnick.com>
* @copyright 2011-2024 Nicola Asuni - Tecnick.com LTD
* @license http://www.gnu.org/copyleft/lesser.html GNU-LGPL v3 (see LICENSE.TXT)
* @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\Load
*
* @since 2011-05-23
* @category Library
* @package PdfFont
* @author Nicola Asuni <info@tecnick.com>
* @copyright 2011-2024 Nicola Asuni - Tecnick.com LTD
* @license http://www.gnu.org/copyleft/lesser.html GNU-LGPL v3 (see LICENSE.TXT)
* @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,
* '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>,
* 'datafile': string,
* 'desc': TFontDataDesc,
* 'diff': string,
* 'diff_n': 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
{
/**
* 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' => [],
'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' => '',
];
/**
* 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();
// read the font definition file
if (! @is_readable($this->data['ifile'])) {
throw new FontException('unable to read file: ' . $this->data['ifile']);
}
$fdt = @file_get_contents($this->data['ifile']);
if ($fdt === false) {
throw new FontException('unable to read file: ' . $this->data['ifile']);
}
$fdtdata = @json_decode($fdt, true, 5, JSON_OBJECT_AS_ARRAY);
if ($fdtdata === null) {
throw new FontException('JSON decoding error [' . json_last_error() . ']');
}
if (! is_array($fdtdata) || (! isset($fdtdata['type']))) {
throw new FontException('fhe font definition file has a bad format: ' . $this->data['ifile']);
}
$this->data = array_replace_recursive($this->data, $fdtdata);
}
/**
* Returns a list of font directories
*
* @return array<string> Font directories
*/
protected function findFontDirectories(): array
{
$dir = new Dir();
$dirs = [''];
if (defined('K_PATH_FONTS')) {
$dirs[] = K_PATH_FONTS;
$glb = glob(K_PATH_FONTS . 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);
}
/**
* Load the font data
*
* @throws FontException in case of error
*/
protected function findFontFile(): void
{
if (! empty($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)) {
$this->data['ifile'] = $dir . DIRECTORY_SEPARATOR . $file;
$this->data['dir'] = $dir;
break 2;
}
}
// we haven't found the version with style variations
$this->data['fakestyle'] = true;
}
}
protected function setDefaultWidth(): void
{
if (! empty($this->data['dw'])) {
return;
}
if ($this->data['desc']['MissingWidth'] > 0) {
$this->data['dw'] = $this->data['desc']['MissingWidth'];
} elseif (! empty($this->data['cw'][32])) {
$this->data['dw'] = $this->data['cw'][32];
} else {
$this->data['dw'] = 600;
}
}
/**
* Check Font Type
*/
protected function checkType(): void
{
if (isset(self::FONTTYPES[$this->data['type']])) {
return;
}
throw new FontException('Unknow font type: ' . $this->data['type']);
}
protected function setName(): void
{
if ($this->data['type'] == 'Core') {
$this->data['name'] = (string) Core::FONT[$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 (empty($this->data['name'])) {
$this->data['name'] = (string) $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'] = empty($this->data['desc']['StemV'])
? 123 : (int) round($this->data['desc']['StemV'] * 1.75);
}
// artificial italic
if ($this->data['mode']['italic']) {
$this->data['name'] .= 'Italic';
if (! empty($this->data['desc']['ItalicAngle'])) {
$this->data['desc']['ItalicAngle'] -= 11;
} else {
$this->data['desc']['ItalicAngle'] = -11;
}
if (! empty($this->data['desc']['Flags'])) {
$this->data['desc']['Flags'] |= 64; //bit 7
} else {
$this->data['desc']['Flags'] = 64;
}
}
}
public function setFileData(): void
{
if (empty($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'];
}
}
}

View File

@@ -0,0 +1,411 @@
<?php
/**
* OutFont.php
*
* @since 2011-05-23
* @category Library
* @package PdfFont
* @author Nicola Asuni <info@tecnick.com>
* @copyright 2011-2024 Nicola Asuni - Tecnick.com LTD
* @license http://www.gnu.org/copyleft/lesser.html GNU-LGPL v3 (see LICENSE.TXT)
* @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\Encrypt\Encrypt;
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-2024 Nicola Asuni - Tecnick.com LTD
* @license http://www.gnu.org/copyleft/lesser.html GNU-LGPL v3 (see LICENSE.TXT)
* @link https://github.com/tecnickcom/tc-lib-pdf-font
*
* @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;
/**
* 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 array{
* 'cidinfo': TFontDataCidInfo,
* 'cw': array<int, int>,
* 'desc': TFontDataDesc,
* 'dw': int,
* 'enc': string,
* 'i': int,
* 'n': int,
* 'name': string,
* 'subset': bool,
* 'subsetchars': array<int, bool>,
* } $font Font to process
*
* return string
*/
protected function getCid0(array $font): string
{
$cidoffset = 0;
if (! isset($font['cw'][1])) {
$cidoffset = 31;
}
$this->uniToCid($font, $cidoffset);
$name = $font['name'];
$longname = $name;
if (! empty($font['enc'])) {
$longname .= '-' . $font['enc'];
}
// obj 1
$out = $font['n'] . ' 0 obj' . "\n"
. '<</Type /Font'
. ' /Subtype /Type0'
. ' /BaseFont /' . $longname
. ' /Name /F' . $font['i'];
if (! empty($font['enc'])) {
$out .= ' /Encoding /' . $font['enc'];
}
$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($font['cidinfo']['Registry'], $this->pon)
. ' /Ordering ' . $this->enc->escapeDataString($font['cidinfo']['Ordering'], $this->pon)
. ' /Supplement ' . $font['cidinfo']['Supplement'];
$out .= ' /CIDSystemInfo <<' . $cidinfo . '>>'
. ' /FontDescriptor ' . ($this->pon + 1) . ' 0 R'
. ' /DW ' . $font['dw'] . "\n"
. $this->getCharWidths($font, $cidoffset)
. ' >>' . "\n"
. 'endobj' . "\n";
// obj 3
$out .= (++$this->pon) . ' 0 obj' . "\n"
. '<</Type /FontDescriptor /FontName /' . $name;
foreach ($font['desc'] as $key => $val) {
if ($key !== 'Style') { // @phpstan-ignore-line
$out .= $this->getKeyValOut($key, $val);
}
}
return $out . ('>>' . "\n"
. 'endobj' . "\n");
}
/**
* Convert Unicode to CID
*
* @param array{
* 'cidinfo': TFontDataCidInfo,
* 'cw': array<int, int>,
* 'desc': TFontDataDesc,
* 'dw': int,
* 'enc': string,
* 'i': int,
* 'n': int,
* 'name': string,
* 'subset': bool,
* 'subsetchars': array<int, bool>,
* } $font Font to process
* @param int $cidoffset Offset for CID values
*/
protected function uniToCid(array &$font, int $cidoffset): void
{
// convert unicode to cid.
$uni2cid = $font['cidinfo']['uni2cid'];
$chw = [];
foreach ($font['cw'] as $uni => $width) {
if (isset($uni2cid[$uni])) {
$chw[($uni2cid[$uni] + $cidoffset)] = $width;
} elseif ($uni < 256) {
$chw[$uni] = $width;
} // else unknown character
}
$font['cw'] = array_merge($font['cw'], $chw);
}
/**
* Get the PDF output string for a TrueTypeUnicode font.
* Based on PDF Reference 1.3 (section 5)
*
* @param array{
* 'cidinfo': TFontDataCidInfo,
* 'compress': bool,
* 'ctg': string,
* 'cw': array<int, int>,
* 'desc': TFontDataDesc,
* 'dir': string,
* 'dw': int,
* 'enc': string,
* 'file_n': int,
* 'i': int,
* 'n': int,
* 'name': string,
* 'subset': bool,
* 'subsetchars': array<int, bool>,
* } $font Font to process
*
* return string
*
* @SuppressWarnings("PHPMD.ExcessiveMethodLength")
* @SuppressWarnings("PHPMD.CyclomaticComplexity")
* @SuppressWarnings("PHPMD.NPathComplexity")
*/
protected function getTrueTypeUnicode(array $font): string
{
$fontname = '';
if ($font['subset']) {
// change name for font subsetting
$subtag = sprintf('%06u', $font['i']);
$subtag = strtr($subtag, '0123456789', 'ABCDEFGHIJ');
$fontname .= $subtag . '+';
}
$fontname .= $font['name'];
// Type0 Font
// A composite font composed of other fonts, organized hierarchically
// obj 1
$out = $font['n'] . ' 0 obj' . "\n"
. '<< /Type /Font'
. ' /Subtype /Type0'
. ' /BaseFont /' . $fontname
. ' /Name /F' . $font['i']
. ' /Encoding /' . $font['enc']
. ' /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.
$cidinfo = '/Registry ' . $this->enc->escapeDataString($font['cidinfo']['Registry'], $this->pon)
. ' /Ordering ' . $this->enc->escapeDataString($font['cidinfo']['Ordering'], $this->pon)
. ' /Supplement ' . $font['cidinfo']['Supplement'];
$out .= ' /CIDSystemInfo << ' . $cidinfo . ' >>'
. ' /FontDescriptor ' . ($this->pon + 1) . ' 0 R'
. ' /DW ' . $font['dw'] . "\n"
. $this->getCharWidths($font, 0);
if (! empty($font['ctg'])) {
$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 ($font['desc'] as $key => $val) {
$out .= $this->getKeyValOut($key, $val);
}
if (! empty($font['file_n'])) {
// A stream containing a TrueType font
$out .= ' /FontFile2 ' . $font['file_n'] . ' 0 R';
}
$out .= ' >>' . "\n"
. 'endobj' . "\n";
if (! empty($font['ctg'])) {
$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 embedd
$ctgfile = strtolower($font['ctg']);
// search and get ctg font file to embedd
$fontfile = $this->getFontFullPath($font['dir'], $ctgfile);
$content = file_get_contents($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 array{
* 'family': string,
* 'i': int,
* 'n': int,
* 'name': string,
* } $font Font to process
*
* return string
*/
protected function getCore(array $font): string
{
$out = $font['n'] . ' 0 obj' . "\n"
. '<</Type /Font'
. ' /Subtype /Type1'
. ' /BaseFont /' . $font['name']
. ' /Name /F' . $font['i'];
if (($font['family'] != 'symbol') && ($font['family'] != 'zapfdingbats')) {
$out .= ' /Encoding /WinAnsiEncoding';
}
return $out . (' >>' . "\n"
. 'endobj' . "\n");
}
/**
* Get the PDF output string for a Core font.
*
* @param array{
* 'cw': array<int, int>,
* 'desc': TFontDataDesc,
* 'diff_n': int,
* 'dw': int,
* 'enc': string,
* 'file': string,
* 'file_n': int,
* 'i': int,
* 'n': int,
* 'name': string,
* 'type': string,
* } $font Font to process
*
* return string
*/
protected function getTrueType(array $font): string
{
// obj 1
$out = $font['n'] . ' 0 obj' . "\n"
. '<</Type /Font'
. ' /Subtype /' . $font['type']
. ' /BaseFont /' . $font['name']
. ' /Name /F' . $font['i']
. ' /FirstChar 32 /LastChar 255'
. ' /Widths ' . ($this->pon + 1) . ' 0 R'
. ' /FontDescriptor ' . ($this->pon + 2) . ' 0 R';
if (! empty($font['enc'])) {
if (isset($font['diff_n']) && $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($font['cw'][$idx])) {
$out .= $font['cw'][$idx] . ' ';
} else {
$out .= $font['dw'] . ' ';
}
}
$out .= ']' . "\n"
. 'endobj' . "\n";
// obj 3 - Descriptor
$out .= (++$this->pon) . ' 0 obj' . "\n"
. '<</Type /FontDescriptor /FontName /' . $font['name'];
foreach ($font['desc'] as $fdk => $fdv) {
$out .= $this->getKeyValOut($fdk, $fdv);
}
if (! empty($font['file'])) {
$out .= ' /FontFile' . ($font['type'] == 'Type1' ? '' : '2') . ' ' . $font['file_n'] . ' 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 . ' ' . $val . '';
}
}

View File

@@ -0,0 +1,197 @@
<?php
/**
* OutUtil.php
*
* @since 2011-05-23
* @category Library
* @package PdfFont
* @author Nicola Asuni <info@tecnick.com>
* @copyright 2011-2024 Nicola Asuni - Tecnick.com LTD
* @license http://www.gnu.org/copyleft/lesser.html GNU-LGPL v3 (see LICENSE.TXT)
* @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-2024 Nicola Asuni - Tecnick.com LTD
* @license http://www.gnu.org/copyleft/lesser.html GNU-LGPL v3 (see LICENSE.TXT)
* @link https://github.com/tecnickcom/tc-lib-pdf-font
*/
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
*/
protected function getFontFullPath(string $fontdir, string $file): string
{
$dirobj = new Dir();
// directories where to search for the font definition file
$dirs = array_unique(
['', $fontdir, (defined('K_PATH_FONTS') ? K_PATH_FONTS : ''), $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 array{
* 'cw': array<int, int>,
* 'dw': int,
* 'subset': bool,
* 'subsetchars': array<int, bool>,
* } $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 array{
* 'cw': array<int, int>,
* 'dw': int,
* 'subset': bool,
* 'subsetchars': array<int, bool>,
* } $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;
}
}
return $this->optimizeWidthRanges($range);
}
/**
* Optimize width ranges
*
* @param array<int, array<int, int>> $range Widht 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;
}
}

View File

@@ -0,0 +1,258 @@
<?php
/**
* Output.php
*
* @since 2011-05-23
* @category Library
* @package PdfFont
* @author Nicola Asuni <info@tecnick.com>
* @copyright 2011-2024 Nicola Asuni - Tecnick.com LTD
* @license http://www.gnu.org/copyleft/lesser.html GNU-LGPL v3 (see LICENSE.TXT)
* @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\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-2024 Nicola Asuni - Tecnick.com LTD
* @license http://www.gnu.org/copyleft/lesser.html GNU-LGPL v3 (see LICENSE.TXT)
* @link https://github.com/tecnickcom/tc-lib-pdf-font
*
* @phpstan-import-type TFontData from Load
*/
class Output extends \Com\Tecnick\Pdf\Font\OutFont
{
/**
* 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
*/
public function __construct(
protected array $fonts,
int $pon,
Encrypt $encrypt
) {
$this->pon = $pon;
$this->enc = $encrypt;
$this->out = $this->getEncodingDiffs();
$this->out .= $this->getFontFiles();
$this->out .= $this->getFontDefinitions();
}
/**
* 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, array{'i': int, 'n': int}> $data Font data.
*
* @return string
*/
private function getOutFontResources(array $data): string
{
if (empty($data)) {
return '';
}
$out = ' /Font <<';
foreach ($data as $font) {
$out .= ' /F' . $font['i'] . ' ' . $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 (empty($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 (! empty($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 (! empty($font['file'])) {
$file_key = md5($font['file']);
if (empty($this->subchars[$file_key])) {
$this->subchars[$file_key] = $font['subsetchars'];
} else {
$this->subchars[$file_key] = array_merge($this->subchars[$file_key], $font['subsetchars']);
}
}
}
return $out;
}
/**
* Get the PDF output string for font files
*
* return string
*/
protected function getFontFiles(): string
{
$out = '';
$done = []; // store processed items to avoid duplication
foreach ($this->fonts as $fkey => $font) {
if (! empty($font['file'])) {
$dkey = md5($font['file']);
if (! isset($done[$dkey])) {
$fontfile = $this->getFontFullPath($font['dir'], $font['file']);
$font_data = file_get_contents($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);
}
$sub = new Subset($font_data, $font, $this->subchars[md5($font['file'])]);
$font_data = $sub->getSubsetFont();
$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'];
$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;
}
/**
* 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;
}
}

View File

@@ -0,0 +1,758 @@
<?php
/**
* Stack.php
*
* @since 2011-05-23
* @category Library
* @package PdfFont
* @author Nicola Asuni <info@tecnick.com>
* @copyright 2011-2024 Nicola Asuni - Tecnick.com LTD
* @license http://www.gnu.org/copyleft/lesser.html GNU-LGPL v3 (see LICENSE.TXT)
* @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\Unicode\Data\Type as UnicodeType;
use Com\Tecnick\Pdf\Font\Exception as FontException;
/**
* Com\Tecnick\Pdf\Font\Stack
*
* @since 2011-05-23
* @category Library
* @package PdfFont
* @author Nicola Asuni <info@tecnick.com>
* @copyright 2011-2024 Nicola Asuni - Tecnick.com LTD
* @license http://www.gnu.org/copyleft/lesser.html GNU-LGPL v3 (see LICENSE.TXT)
* @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>,
* '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 ?int $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 embedd only a subset of the font
* (stores only the information related to
* the used characters); If false embedd
* full font; This option is valid only for
* TrueTypeUnicode fonts and it 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 = '',
?int $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
$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 instanceof \Com\Tecnick\Pdf\Font\Exception) {
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
*/
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 ?int $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
*/
public function cloneFont(
int &$objnum,
?int $idx = null,
?string $style = null,
?int $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->stack[$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,
$data['ifile'],
$data['subset'],
);
}
/**
* Returns the current font key.
*
* @return string
*/
public function getCurrentFontKey(): string
{
return $this->stack[$this->index]['key'];
}
/**
* Returns the current font type (i.e.: Core, TrueType, TrueTypeUnicode, Type1).
*
* @return string
*/
public function getCurrentFontType(): string
{
return $this->getFont($this->stack[$this->index]['key'])['type'];
}
/**
* Returns the PDF code to use the current font.
*
* @return string
*/
public function getOutCurrentFont(): string
{
return $this->getFontMetric($this->index)['out'];
}
/**
* Returns true if the current font type is Core, TrueType or Type1.
*
* @return bool
*/
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
*/
public function isCurrentUnicodeFont(): bool
{
$currentFontType = $this->getCurrentFontType();
return (($currentFontType == 'TrueTypeUnicode') || ($currentFontType == 'cidfont0'));
}
/**
* Remove and return the last inserted font
*
* @return TFontMetric
*/
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.
*/
public function replaceMissingChars(array $uniarr, array $subs = []): array
{
$font = $this->getFontMetric($this->index);
foreach ($uniarr as $pos => $uni) {
if (isset($font['cw'][$uni])) {
continue;
}
if (! isset($subs[$uni])) {
continue;
}
foreach ($subs[$uni] as $alt) {
if (isset($font['cw'][$alt])) {
$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
*/
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
*/
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);
return $font['cw'][$ord] ?? $font['dw'];
}
/**
* Returns the lenght of the string specified using an array of codepoints.
*
* @param array<int, int> $uniarr Array of character codepoints.
*
* @return float
*/
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
*/
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
$fact = ($this->stack[$this->index]['spacing'] * $this->stack[$this->index]['stretching']);
$uniarr[] = 8203; // add null at the end to ensure that the last word is processed
$split = [];
foreach ($uniarr as $idx => $ord) {
$unitype = UnicodeType::UNI[$ord];
$chrwidth = $this->getCharWidth($ord);
// 'B' Paragraph Separator
// 'S' Segment Separator
// 'WS' Whitespace
// 'BN' Boundary Neutral
if (($unitype == 'B') || ($unitype == 'S') || ($unitype == 'WS') || ($unitype == 'BN')) {
$split[$words] = [
'pos' => $idx,
'ord' => $ord,
'spaces' => $spaces,
'septype' => $unitype,
'wordwidth' => 0,
'totwidth' => ($totwidth + ($fact * ($idx - 1))),
'totspacewidth' => ($totspacewidth + ($fact * ($spaces - 1))),
];
if ($words > 0) {
$split[$words]['wordwidth'] = ($split[$words]['totwidth'] - $split[($words - 1)]['totwidth']);
}
$words++;
if ($unitype == 'WS') {
++$spaces;
$totspacewidth += $chrwidth;
}
}
$totwidth += $chrwidth;
}
$totwidth += ($fact * ($chars - 1));
$totspacewidth += ($fact * ($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)
*/
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 i not defined
*/
public function replaceChar(int $oldchar, int $newchar): int
{
if ($this->isCharDefined($newchar)) {
// add the new char on the subset list
$this->addSubsetChar($this->stack[$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
*/
protected function getFontMetric(int $idx): array
{
$font = $this->stack[$idx];
$mkey = md5(serialize($font));
if (! empty($this->metric[$mkey])) {
return $this->metric[$mkey];
}
$size = $font['size'];
$usize = ((float) $size / $this->kunit);
$cratio = ((float) $size / 1000);
$wratio = ($cratio * $font['stretching']); // horizontal ratio
$data = $this->getFont($font['key']);
$outfont = sprintf('/F%d %F Tf', $data['i'], $font['size']); // PDF output string
// add this font in the stack wit metrics in internal units
$this->metric[$mkey] = [
'ascent' => ((float) $data['desc']['Ascent'] * $cratio),
'avgwidth' => ((float) $data['desc']['AvgWidth'] * $cratio * $font['stretching']),
'capheight' => ((float) $data['desc']['CapHeight'] * $cratio),
'cbbox' => [],
'cratio' => $cratio,
'cw' => [],
'descent' => ((float) $data['desc']['Descent'] * $cratio),
'dw' => ((float) $data['dw'] * $cratio * $font['stretching']),
'fbbox' => [],
'height' => ((float) ($data['desc']['Ascent'] - $data['desc']['Descent']) * $cratio),
'idx' => $idx,
'key' => $font['key'],
'maxwidth' => ((float) $data['desc']['MaxWidth'] * $cratio * $font['stretching']),
'midpoint' => ((float) ($data['desc']['Ascent'] + $data['desc']['Descent']) * $cratio / 2),
'missingwidth' => ((float) $data['desc']['MissingWidth'] * $cratio * $font['stretching']),
'out' => 'BT ' . $outfont . ' ET' . "\r",
'outraw' => $outfont,
'size' => $size,
'spacing' => $font['spacing'],
'stretching' => $font['stretching'],
'style' => $font['style'],
'type' => $data['type'],
'up' => ((float) $data['up'] * $cratio),
'usize' => $usize,
'ut' => ((float) $data['ut'] * $cratio),
'xheight' => ((float) $data['desc']['XHeight'] * $cratio),
];
$tbox = explode(' ', substr($data['desc']['FontBBox'], 1, -1));
$this->metric[$mkey]['fbbox'] = [
// left
((float) $tbox[0] * $wratio),
// bottom
((float) $tbox[1] * $cratio),
// right
((float) $tbox[2] * $wratio),
// top
((float) $tbox[3] * $cratio),
];
//left, bottom, right, and top edges
foreach ($data['cw'] as $cid => $width) {
$this->metric[$mkey]['cw'][(int) $cid] = ((float) $width * $wratio);
}
if (is_array($data['cbbox'])) {
foreach ($data['cbbox'] as $cid => $val) {
if (! is_array($val)) {
continue;
}
if (count($val) != 4) {
continue;
}
$this->metric[$mkey]['cbbox'][(int) $cid] = [
// left
((float) $val[0] * $wratio),
// bottom
((float) $val[1] * $cratio),
// right
((float) $val[2] * $wratio),
// top
((float) $val[3] * $cratio),
];
}
}
return $this->metric[$mkey];
}
/**
* Normalize the input size
*
* @param ?int $size Font size in points (set to null to inherit the last font size).
*
* @return float
*/
protected function getInputSize(?int $size = null): float
{
if (($size === null) || ($size < 0)) {
if ($this->index >= 0) {
// inherit the size of the last inserted font
return $this->stack[$this->index]['size'] ?? 0;
}
return self::DEFAULT_SIZE;
}
return max(0, (float) $size);
}
/**
* Normalize the input spacing
*
* @param ?float $spacing Extra spacing between characters.
*
* @return float
*/
protected function getInputSpacing(?float $spacing = null): float
{
if ($spacing === null) {
if ($this->index >= 0) {
// inherit the size of the last inserted font
return $this->stack[$this->index]['spacing'] ?? 0;
}
return 0;
}
return ($spacing);
}
/**
* Normalize the input stretching
*
* @param ?float $stretching Horizontal character stretching ratio.
*
* @return float
*/
protected function getInputStretching(?float $stretching = null): float
{
if ($stretching === null) {
if ($this->index >= 0) {
// inherit the size of the last inserted font
return $this->stack[$this->index]['stretching'] ?? 0;
}
return 1;
}
return ($stretching);
}
/**
* Return normalized font keys
*
* @param string $fontfamily Property string containing comma-separated font family names
*
* @return array<string>
*/
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) || (! is_string($fontfamily))) {
throw new FontException('Invalid font family name: ' . $fontfamily);
}
// 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 nomalized font family name or the current font name (key.
*
* @param string $fontfamily Raw font family name.
*
* @return string
*/
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();
}
}

View File

@@ -0,0 +1,498 @@
<?php
/**
* Subset.php
*
* @since 2011-05-23
* @category Library
* @package PdfFont
* @author Nicola Asuni <info@tecnick.com>
* @copyright 2011-2024 Nicola Asuni - Tecnick.com LTD
* @license http://www.gnu.org/copyleft/lesser.html GNU-LGPL v3 (see LICENSE.TXT)
* @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\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-2024 Nicola Asuni - Tecnick.com LTD
* @license http://www.gnu.org/copyleft/lesser.html GNU-LGPL v3 (see LICENSE.TXT)
* @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' => [],
'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;
/**
* Process TrueType font
*
* @param string $font Content of the input font file
* @param TFontData $fdt Extracted font metrics
* @param array<int, bool> $subchars Array containing subset chars
*
* @throws FontException in case of error
*/
public function __construct(string $font, array $fdt, array $subchars = [])
{
$this->fbyte = new Byte($font);
$trueType = new TrueType($font, $fdt, $this->fbyte, $subchars);
$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;
}
/**
* Returs the checksum of a TTF table.
*
* @param string $table Table to check
* @param int $length Length of table in bytes
*
* @return int checksum
*/
protected function getTableChecksum(string $table, int $length): int
{
$sum = 0;
$tlen = ($length / 4);
$offset = 0;
for ($idx = 0; $idx < $tlen; ++$idx) {
$val = unpack('Ni', substr($table, $offset, 4));
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);
}
$this->subglyphs = [...$this->subglyphs, ...$new_sga];
}
// sort glyphs by key (and remove duplicates)
ksort($this->subglyphs);
}
/**
* Add composite glyphs
*
* @param array<int, bool> $new_sga
*
* @return array<int, bool>
*/
protected function findCompositeGlyphs(array $new_sga, int $key): array
{
if (isset($this->fdt['indexToLoc'][$key])) {
$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
$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
if (($flags & 1) !== 0) {
$this->offset += 4;
} else {
$this->offset += 2;
}
if (($flags & 8) !== 0) {
$this->offset += 2;
} elseif (($flags & 64) !== 0) {
$this->offset += 4;
} elseif (($flags & 128) !== 0) {
$this->offset += 8;
}
} while ($flags & 32);
}
}
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 (empty($this->fdt['table'][$tag])) {
$this->fdt['table'][$tag] = [
'checkSum' => 0,
'data' => '',
'length' => 0,
'offset' => 0,
];
}
$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", $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) {
if (
isset($this->subglyphs[$i])
&& isset($this->fdt['indexToLoc'][$i])
&& isset($this->fdt['indexToLoc'][($i + 1)])
) {
$length = ($this->fdt['indexToLoc'][($i + 1)] - $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 (empty($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 (empty($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']
);
}
/**
* build new subset font
*/
protected function buildSubsetFont(): void
{
$this->subfont = '';
$this->subfont .= pack('N', 0x10000); // 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
$this->offset = ($numTables * 16);
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 = (0xB1B0AFBA - $this->getTableChecksum($this->subfont, strlen($this->subfont)));
$this->subfont = substr($this->subfont, 0, $this->fdt['table']['head']['offset'] + 8)
. pack('N', $checkSumAdjustment)
. substr($this->subfont, $this->fdt['table']['head']['offset'] + 12);
}
}

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,214 @@
<?php
/**
* BufferTest.php
*
* @since 2011-05-23
* @category Library
* @package PdfFont
* @author Nicola Asuni <info@tecnick.com>
* @copyright 2011-2024 Nicola Asuni - Tecnick.com LTD
* @license http://www.gnu.org/copyleft/lesser.html GNU-LGPL v3 (see LICENSE.TXT)
* @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-2024 Nicola Asuni - Tecnick.com LTD
* @license http://www.gnu.org/copyleft/lesser.html GNU-LGPL v3 (see LICENSE.TXT)
* @link https://github.com/tecnickcom/tc-lib-pdf-font
*
* @SuppressWarnings("PHPMD.LongVariable")
*/
class BufferTest extends TestUtil
{
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');
}
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, '');
}
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');
}
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');
}
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');
}
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']);
}
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']);
}
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']);
}
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');
}
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);
}
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);
}
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);
}
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);
}
}

View File

@@ -0,0 +1,215 @@
<?php
/**
* ImportTest.php
*
* @since 2011-05-23
* @category Library
* @package PdfFont
* @author Nicola Asuni <info@tecnick.com>
* @copyright 2011-2024 Nicola Asuni - Tecnick.com LTD
* @license http://www.gnu.org/copyleft/lesser.html GNU-LGPL v3 (see LICENSE.TXT)
* @link https://github.com/tecnickcom/tc-lib-pdf-font
*
* This file is part of tc-lib-pdf-font software library.
*/
namespace Test;
use PHPUnit\Framework\Attributes\DataProvider;
/**
* Import Test
*
* @since 2011-05-23
* @category Library
* @package PdfFont
* @author Nicola Asuni <info@tecnick.com>
* @copyright 2011-2024 Nicola Asuni - Tecnick.com LTD
* @license http://www.gnu.org/copyleft/lesser.html GNU-LGPL v3 (see LICENSE.TXT)
* @link https://github.com/tecnickcom/tc-lib-pdf-font
*
* @SuppressWarnings("PHPMD.LongVariable")
*/
class ImportTest extends TestUtil
{
public function testImportForbiddenProtocol(): void
{
$this->bcExpectException('\\' . \Com\Tecnick\Pdf\Font\Exception::class);
new \Com\Tecnick\Pdf\Font\Import('phar://test.txt');
}
public function testImportParentDir(): void
{
$this->bcExpectException('\\' . \Com\Tecnick\Pdf\Font\Exception::class);
new \Com\Tecnick\Pdf\Font\Import('/tmp/something/../test.txt');
}
public function testImportEmptyName(): void
{
$this->bcExpectException('\\' . \Com\Tecnick\Pdf\Font\Exception::class);
new \Com\Tecnick\Pdf\Font\Import('');
}
public function testImportExist(): void
{
$this->bcExpectException('\\' . \Com\Tecnick\Pdf\Font\Exception::class);
$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);
}
public function testImportWrongFile(): void
{
$this->bcExpectException('\\' . \Com\Tecnick\Pdf\Font\Exception::class);
new \Com\Tecnick\Pdf\Font\Import(dirname(__DIR__) . '/util/vendor/tecnickcom/tc-font-mirror/core/Missing.afm');
}
public function testImportDefaultOutput(): void
{
$this->bcExpectException('\\' . \Com\Tecnick\Pdf\Font\Exception::class);
new \Com\Tecnick\Pdf\Font\Import(dirname(__DIR__) . '/util/vendor/tecnickcom/tc-font-mirror/core/Missing.afm');
}
public function testImportUnsupportedType(): void
{
$this->bcExpectException('\\' . \Com\Tecnick\Pdf\Font\Exception::class);
$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');
}
public function testImportUnsupportedOpenType(): void
{
$this->bcExpectException('\\' . \Com\Tecnick\Pdf\Font\Exception::class);
$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);
}
#[DataProvider('importDataProvider')]
public function testImport(
string $fontdir,
string $font,
mixed $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);
$json = json_decode($file, true, 512, JSON_THROW_ON_ERROR);
$this->assertNotNull($json);
$this->assertIsArray($json);
$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->assertEquals($metric['italicAngle'], $json['desc']['ItalicAngle']);
$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'],
];
}
}

View File

@@ -0,0 +1,91 @@
<?php
/**
* OutputTest.php
*
* @since 2011-05-23
* @category Library
* @package PdfFont
* @author Nicola Asuni <info@tecnick.com>
* @copyright 2011-2024 Nicola Asuni - Tecnick.com LTD
* @license http://www.gnu.org/copyleft/lesser.html GNU-LGPL v3 (see LICENSE.TXT)
* @link https://github.com/tecnickcom/tc-lib-pdf-font
*
* This file is part of tc-lib-pdf-font software library.
*/
namespace Test;
/**
* Output Test
*
* @since 2011-05-23
* @category Library
* @package PdfFont
* @author Nicola Asuni <info@tecnick.com>
* @copyright 2011-2024 Nicola Asuni - Tecnick.com LTD
* @license http://www.gnu.org/copyleft/lesser.html GNU-LGPL v3 (see LICENSE.TXT)
* @link https://github.com/tecnickcom/tc-lib-pdf-font
*
* @SuppressWarnings("PHPMD.LongVariable")
*/
class OutputTest extends TestUtil
{
public function testOutput(): void
{
$this->setupTest();
$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 = new \Com\Tecnick\Pdf\Encrypt\Encrypt();
$output = new \Com\Tecnick\Pdf\Font\Output($fonts, $objnum, $encrypt);
$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));
}
}

View File

@@ -0,0 +1,188 @@
<?php
/**
* StackTest.php
*
* @since 2011-05-23
* @category Library
* @package PdfFont
* @author Nicola Asuni <info@tecnick.com>
* @copyright 2011-2024 Nicola Asuni - Tecnick.com LTD
* @license http://www.gnu.org/copyleft/lesser.html GNU-LGPL v3 (see LICENSE.TXT)
* @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-2024 Nicola Asuni - Tecnick.com LTD
* @license http://www.gnu.org/copyleft/lesser.html GNU-LGPL v3 (see LICENSE.TXT)
* @link https://github.com/tecnickcom/tc-lib-pdf-font
*
* @SuppressWarnings("PHPMD.LongVariable")
*/
class StackTest extends TestUtil
{
public function testStack(): void
{
$this->setupTest();
$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']);
$this->assertEquals(11, $widths['split'][5]['pos']);
$this->assertEquals(8203, $widths['split'][5]['ord']);
$this->assertEquals('BN', $widths['split'][5]['septype']);
$this->bcAssertEqualsWithDelta(4.92, $widths['split'][5]['wordwidth'], 0.0001);
$this->assertEquals(2, $widths['split'][5]['spaces']);
$this->bcAssertEqualsWithDelta(60.9384, $widths['split'][5]['totwidth'], 0.0001);
$this->bcAssertEqualsWithDelta(8.76, $widths['split'][5]['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);
}
public function testEmptyStack(): void
{
$this->bcExpectException('\\' . \Com\Tecnick\Pdf\Font\Exception::class);
$this->setupTest();
$stack = new \Com\Tecnick\Pdf\Font\Stack(1);
$stack->popLastFont();
}
public function testStackMissingFont(): void
{
$this->bcExpectException('\\' . \Com\Tecnick\Pdf\Font\Exception::class);
$this->setupTest();
$stack = new \Com\Tecnick\Pdf\Font\Stack(1);
$objnum = 1;
$stack->insert($objnum, 'missing');
}
}

View File

@@ -0,0 +1,71 @@
<?php
/**
* TestUtil.php
*
* @since 2020-12-19
* @category Library
* @package PdfFont
* @author Nicola Asuni <info@tecnick.com>
* @copyright 2015-2024 Nicola Asuni - Tecnick.com LTD
* @license http://www.gnu.org/copyleft/lesser.html GNU-LGPL v3 (see LICENSE.TXT)
* @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-2024 Nicola Asuni - Tecnick.com LTD
* @license http://www.gnu.org/copyleft/lesser.html GNU-LGPL v3 (see LICENSE.TXT)
* @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/');
}
system('rm -rf ' . K_PATH_FONTS . ' && mkdir -p ' . K_PATH_FONTS);
}
protected function getFontPath(): string
{
if (defined('K_PATH_FONTS')) {
return 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($exception): void
{
parent::expectException($exception);
}
}

View File

@@ -0,0 +1,187 @@
# makefile
#
# @since 2015-05-14
# @category Library
# @package PdfFont
# @author Nicola Asuni <info@tecnick.com>
# @copyright 2011-2024 Nicola Asuni - Tecnick.com LTD
# @license http://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=$(dir $(realpath $(firstword $(MAKEFILE_LIST))))
# 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)
# --- MAKE TARGETS ---
# Display general help about this command
.PHONY: help
help:
@echo ""
@echo "${PROJECT} Makefile."
@echo "The following commands are available:"
@echo ""
@echo " make clean : Delete the vendor and target directory"
@echo " make build : Clean and download the composer dependencies"
@echo " make update : Update composer dependencies"
@echo " make install : Install this library"
@echo " make uninstall : Remove all installed files"
@echo " make rpm : Build an RPM package"
@echo " make deb : Build a DEB package"
@echo " make bz2 : Build a tar bz2 (tbz2) compressed archive"
@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
.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:
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 -i "s/~#DATE#~/`date -R`/" {} \;
find $(PATHDEBPKG)/$(PKGNAME)-$(VERSION)/debian/ -type f -exec sed -i "s/~#VENDOR#~/$(VENDOR)/" {} \;
find $(PATHDEBPKG)/$(PKGNAME)-$(VERSION)/debian/ -type f -exec sed -i "s/~#PROJECT#~/$(PROJECT)/" {} \;
find $(PATHDEBPKG)/$(PKGNAME)-$(VERSION)/debian/ -type f -exec sed -i "s/~#PKGNAME#~/$(PKGNAME)/" {} \;
find $(PATHDEBPKG)/$(PKGNAME)-$(VERSION)/debian/ -type f -exec sed -i "s/~#VERSION#~/$(VERSION)/" {} \;
find $(PATHDEBPKG)/$(PKGNAME)-$(VERSION)/debian/ -type f -exec sed -i "s/~#RELEASE#~/$(RELEASE)/" {} \;
find $(PATHDEBPKG)/$(PKGNAME)-$(VERSION)/debian/ -type f -exec sed -i "s/~#FONT#~/$(PKGFONTDIR)/" {} \;
find $(PATHDEBPKG)/$(PKGNAME)-$(VERSION)/debian/ -type f -exec sed -i "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)

View File

@@ -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-2024 Nicola Asuni - Tecnick.com LTD
* @license http://www.gnu.org/copyleft/lesser.html GNU-LGPL v3 (see LICENSE.TXT)
* @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-font-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);

View File

@@ -0,0 +1,45 @@
{
"name": "tecnickcom/tc-lib-pdf-font",
"description": "Import TTF font files to be converted for tc-lib-pdf-font",
"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.1"
},
"require-dev": {},
"repositories": [
{
"type": "package",
"package": {
"name": "tecnickcom/tc-font-mirror",
"version": "2.1.0",
"dist": {
"type": "zip",
"url": "https://github.com/tecnickcom/tc-font-mirror/archive/refs/tags/2.1.0.zip",
"reference": "main"
},
"autoload": {
"classmap": [
"."
]
}
}
}
]
}

View File

@@ -0,0 +1,258 @@
#!/usr/bin/env php
<?php
/**
* convert.php
*
* @since 2011-05-23
* @category Library
* @package PdfFont
* @author Nicola Asuni <info@tecnick.com>
* @copyright 2011-2024 Nicola Asuni - Tecnick.com LTD
* @license http://www.gnu.org/copyleft/lesser.html GNU-LGPL v3 (see LICENSE.TXT)
* @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' => './',
'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':
$options['outpath'] = realpath($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']) || !is_writable($options['outpath'])) {
fwrite(STDERR, 'ERROR: Can\'t write to '.$options['outpath']."\n\n");
exit(2);
}
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;
require_once (dirname(dirname(__DIR__)).'/vendor/autoload.php');
foreach ($options['fonts'] as $font) {
try {
$import = new \Com\Tecnick\Pdf\Font\Import(
realpath($font),
$options['outpath'],
$options['type'],
$options['encoding'],
$options['flags'],
$options['platform_id'],
$options['encoding_id'],
$options['linked']
);
$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);

View File

@@ -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()