Overview
tc-lib-color provides parsing, conversion, and formatting of color values for web and PDF rendering pipelines.
One normalization layer covers RGB, CMYK, HSL, grayscale, Lab, and spot colors, in both their CSS and their PDF representations. Conversions written ad hoc in three places tend to round differently in all three; here they do not.
Repository and API Docs
- GitHub: https://github.com/tecnickcom/tc-lib-color
- API docs: https://tcpdf.org/docs/srcdoc/tc-lib-color
- Packagist: https://packagist.org/packages/tecnickcom/tc-lib-color
Project Metadata
| Item | Value |
|---|---|
| Namespace | \Com\Tecnick\Color |
| License | GNU LGPL v3 |
Installation
composer require tecnickcom/tc-lib-color
Where It Fits
Use this package whenever rendering needs explicit color conversions and repeatable output across digital and print contexts.
It is a direct dependency of tecnickcom/tc-lib-pdf and is used internally for all color operations during PDF composition.
Color Models
| Model | Class |
|---|---|
| RGB / RGBA | \Com\Tecnick\Color\Model\Rgb |
| HSL / HSLA | \Com\Tecnick\Color\Model\Hsl |
| CMYK | \Com\Tecnick\Color\Model\Cmyk |
| CIE Lab | \Com\Tecnick\Color\Model\Lab |
| Grayscale | \Com\Tecnick\Color\Model\Gray |
Each page gives the components, the ranges and the output of every accessor; Colour Models puts the five side by side and Conversions covers moving between them.
Spot colors (Separation) are handled by \Com\Tecnick\Color\Spot, with DeviceCMYK and Lab alternate color spaces for PDF output.
Integration Helpers
- CSS output that parses back to the same color
- PDF and Acrobat JavaScript color output
- Cross-model conversion helpers on all color models
- Named web color lookup (CSS Color Module Level 4 names) and nearest-color matching in sRGB or CIE Lab
Main Classes
| Class | Purpose |
|---|---|
\Com\Tecnick\Color\Web | Named web colors, hex parsing, nearest-color lookup |
\Com\Tecnick\Color\Pdf | PDF color operators, spot color objects, JS color strings |
\Com\Tecnick\Color\Css | CSS color string parsing and normalization |
\Com\Tecnick\Color\Spot | Spot color registry and PDF spot color resource generation |
\Com\Tecnick\Color\ComponentNormalizer | Scaling of parsed component values into the [0..1] range |
Pdf extends Spot extends Web extends Css, so a single object provides the parser, the spot registry and the PDF writer. Each role also has its own interface to type against:
| Interface | Role |
|---|---|
\Com\Tecnick\Color\ColorParserInterface | Color string parsing and named color lookup |
\Com\Tecnick\Color\SpotRegistryInterface | Spot color registration and PDF spot resource output |
\Com\Tecnick\Color\PdfColorWriterInterface | PDF and Acrobat JavaScript color output |
\Com\Tecnick\Color\ExceptionInterface | Common interface of the library exceptions |
Web::getColorObj(), Spot::getSpotColor(), Pdf::getPdfColor() and Pdf::getColorObject() can be overridden, along with the protected parser methods on Css and Spot::resolveSpotColorData(). Every other public method is final.
Supported Color Notations
getColorObj() accepts hexadecimal codes in four lengths, the 150 named colors, seven color functions (g(), rgb(), rgba(), hsl(), hsla(), cmyk(), cmyka(), lab()) and the Acrobat JavaScript array forms. Components are separated either by commas or by spaces, not by a mixture of the two; out-of-range components are clamped and hues wrap, as CSS Color Level 4 requires.
Colour Notations has every form with its parsed result, the angle units, the alpha syntax and what transparent resolves to.
Typed Enums
\Com\Tecnick\Color\ColorModelType is a backed enum listing the supported color models (GRAY, RGB, HSL, CMYK, LAB). Its backing value is the canonical model string returned by the model objects, so it can be used interchangeably with the plain string wherever a model type is accepted. Model::create() builds a model object from an enum case and a component array.
Exceptions
\Com\Tecnick\Color\Exception (a \Exception) signals invalid input. \Com\Tecnick\Color\UnknownComponentException (a \LogicException) signals a component name a model does not define, and is not swallowed by the lenient accessors tryGetColorObj() and getColorObject(). Both implement \Com\Tecnick\Color\ExceptionInterface, so a single catch covers them.
Errors lists every message with the call that raises it, and the inputs that clamp instead of raising.
Version 3.0 Changes
Release 3.0 is a breaking change:
Rgb::getCssColor()emitsrgb(255,0,0)andGray::getCssColor()emitsg(128)instead of percentage forms; alpha is capped at four decimals.- The PDF color getters take a trailing
bool $allowSpot = trueargument, and most public methods ofWeb,SpotandPdfarefinal. Model::__construct()is removed from the abstract base: each model validates its own components and raisesUnknownComponentException.- Malformed numbers and mixed comma/space separators are rejected; out-of-range components clamp and hues wrap.
Css::normalizeValue()is concrete and delegates scaling to theComponentNormalizercollaborator.- New API: the role interfaces,
Model::withInvertedColor(),Web::getClosestWebColorByDeltaE(), CSS angle units, slash-alpha and percentage alpha. addSpotLabColor()clamps its range to[-128..127], the spot color accessors return copies, and a spot resource with no PDF object raises instead of being emitted.
How Integration Works
- Instantiate
WeborPdfdepending on target output context. - Parse input color strings (hex, CSS, named, spot) into a color model object.
- Use model output methods to produce CSS strings, PDF operators, or normalized arrays.
- For PDF output, use
Pdf::getPdfColor()to emit the correct PDF color operator.
<?php
require_once __DIR__ . '/vendor/autoload.php';
$pdf = new \Com\Tecnick\Color\Pdf();
$color = $pdf->getColorObject('#336699');
echo $color->getCssColor(); // rgb(51,102,153)
echo $pdf->getPdfFillColor('#336699');
Pdf extends the spot registry, which extends the web parser, so one object covers every step. The reference pages carry the worked examples:
| Task | Page |
|---|---|
| Write a color string the parser accepts | Colour Notations |
| Pick a model and read its components | Colour Models |
| Move a color between models | Conversions |
| Look up or name a color | Web Colours, Nearest Colour |
| Register an ink and emit its resources | Spot Colours |
| Write color into a PDF | PDF Output |
| Handle bad input | Errors |
Behavior Worth Knowing
- Spot colors are registered only when you add them explicitly. The color getters do not register one as a side effect, so the spot resources a document emits match the ones it actually uses.
- Spot color names are escaped when written to PDF, and the CSS parser recognizes the standard spot color names.
- Spot colors take a
DeviceCMYKor a Lab alternate color space in PDF output. - HSL saturation and lightness are always parsed as percentages, as the CSS specification requires.
Integration Notes
Parse color notation once, at the edge of your application, and pass typed model objects inward. Strings that reach the rendering layer get reparsed, sometimes under different assumptions.
RGB and CMYK cover different gamuts, so a screen preview and a press sheet agree across most of the range and differ at the saturated end. Conversions has the conversion matrix and the round-trip measurements.
Lab is the device-independent option, and it is what ISO 19005 prefers. A DeviceCMYK color in a PDF/A document is only valid when the output intent is a CMYK profile, and tc-lib-pdf reports the mismatch through getWarnings(); see /docs/standards/.
Requirements
- PHP 8.2 or later
- Extension:
pcre - Composer
Development and Packaging
- QA and local checks:
make deps,make help,make qa - Coverage report:
make qa-coverage - Local example server:
make server - Packaging:
make rpm,make deb
Support and Contribution
- Sponsor: https://github.com/sponsors/tecnickcom
- Contribution guide: https://github.com/tecnickcom/tc-lib-color/blob/main/CONTRIBUTING.md
- Security policy: https://github.com/tecnickcom/tc-lib-color/blob/main/SECURITY.md