Initial commit

This commit is contained in:
2026-09-07 22:04:36 +00:00
commit d1334bf406
2334 changed files with 646393 additions and 0 deletions
+849
View File
@@ -0,0 +1,849 @@
<?php
declare(strict_types=1);
/**
* Base.php
*
* @since 2011-05-23
* @category Library
* @package PdfGraph
* @author Nicola Asuni <info@tecnick.com>
* @copyright 2011-2026 Nicola Asuni - Tecnick.com LTD
* @license https://www.gnu.org/copyleft/lesser.html GNU-LGPL v3 (see LICENSE)
* @link https://github.com/tecnickcom/tc-lib-pdf-graph
*
* This file is part of tc-lib-pdf-graph software library.
*/
namespace Com\Tecnick\Pdf\Graph;
use Com\Tecnick\Color\Pdf as PdfColor;
use Com\Tecnick\Pdf\Encrypt\Encrypt;
/**
* Com\Tecnick\Pdf\Graph\Base
*
* @since 2011-05-23
* @category Library
* @package PdfGraph
* @author Nicola Asuni <info@tecnick.com>
* @copyright 2011-2026 Nicola Asuni - Tecnick.com LTD
* @license https://www.gnu.org/copyleft/lesser.html GNU-LGPL v3 (see LICENSE)
* @link https://github.com/tecnickcom/tc-lib-pdf-graph
*
* @phpstan-type TTMatrix array{
* float,
* float,
* float,
* float,
* float,
* float,
* }
*
* @phpstan-type StyleData array{
* 'lineWidth': float,
* 'lineCap': string,
* 'lineJoin': string,
* 'miterLimit': float,
* 'dashArray': array<int>,
* 'dashPhase': float,
* 'lineColor': string,
* 'fillColor': string,
* }
*
* @phpstan-type StyleDataOpt array{
* 'lineWidth'?: float,
* 'lineCap'?: string,
* 'lineJoin'?: string,
* 'miterLimit'?: float,
* 'dashArray'?: array<int>,
* 'dashPhase'?: float,
* 'lineColor'?: string,
* 'fillColor'?: string,
* }
*
* @phpstan-type GradientData array{
* 'antialias': bool,
* 'background': ?\Com\Tecnick\Color\Model,
* 'colors': array<int, array{
* 'color': string,
* 'exponent'?: float,
* 'opacity'?: float,
* 'offset'?: float,
* }>,
* 'colspace': string,
* 'coords': array<float>,
* 'id': int,
* 'pattern': int,
* 'stream': string,
* 'transparency': bool,
* 'type': int,
* }
*
* @SuppressWarnings("PHPMD.ExcessiveClassComplexity")
*/
abstract class Base
{
/**
* Pi constant
* We use this instead of M_PI because HHVM has a different value.
*
* @var float
*/
public const MPI = 3.141_592_653_589_793_238_462_643_383_279_502_884_197_169_399_375_10;
/**
* Identity matrix for transformations.
*
* @var TTMatrix
*/
public const IDMATRIX = [1.0, 0.0, 0.0, 1.0, 0.0, 0.0];
/**
* PDF graphics state save operator.
*
* @var string
*/
protected const GSAVE = 'q' . "\n";
/**
* PDF graphics state restore operator.
*
* @var string
*/
protected const GRESTORE = 'Q' . "\n";
/**
* Current PDF object number
*/
protected int $pon = 0;
/**
* Current page height
*/
protected float $pageh = 0;
/**
* Current page width
*/
protected float $pagew = 0;
/**
* Unit of measure conversion ratio
*/
protected float $kunit = 1.0;
/**
* Stack index.
*/
protected int $styleid = -1;
/**
* Stack containing style data.
*
* @var array<StyleDataOpt>
*/
protected array $style = [];
/**
* Array of transparency objects and parameters.
*
* @var array<int, array{
* 'n': int,
* 'name': string,
* 'parms': array<string, int|float|bool|string>,
* }>
*/
protected array $extgstates = [];
/**
* Array of gradients
*
* @var array<int, GradientData>
*/
protected array $gradients = [];
/**
* Bookkeeping for the luminosity soft-mask patterns generated for
* transparent gradients, keyed by the transparency pattern index used as
* the resource name (/p{key}) inside the soft-mask form XObject.
*
* These are internal helper objects, referenced only from within the
* soft-mask XObject, and are deliberately kept out of $gradients so they
* are not advertised in the page-level gradient resource dictionary.
*
* @var array<int, array{'id': int, 'pattern': int}>
*/
protected array $gradientMasks = [];
/**
* Initialize
*
* @param float $kunit Unit of measure conversion ratio.
* @param float $pagew Page width.
* @param float $pageh Page height.
* @param PdfColor $pdfColor Color object.
* @param Encrypt $encrypt Encrypt object.
* @param bool $pdfa True if we are in PDF/A mode.
* @param bool $compress Set to false to disable stream compression.
*/
public function __construct(
float $kunit,
float $pagew,
float $pageh,
/**
* Color object
*/
protected PdfColor $pdfColor,
/**
* Encrypt object
*/
protected Encrypt $encrypt,
protected bool $pdfa = false,
protected bool $compress = true,
) {
$this->setKUnit($kunit);
$this->setPageWidth($pagew);
$this->setPageHeight($pageh);
$this->initStyle();
}
/**
* Initialize default style
*/
public function initStyle(): void
{
$this->style[++$this->styleid] = $this->getDefaultStyle();
}
/**
* Returns the default style.
*
* @param StyleDataOpt $style Style parameters to merge to the default ones.
*
* @return StyleData
*/
public function getDefaultStyle(array $style = []): array
{
return [
// line thickness in user units
'lineWidth' => $style['lineWidth'] ?? (1.0 / $this->kunit),
// shape of the endpoints for any open path that is stroked
'lineCap' => $style['lineCap'] ?? 'butt',
// shape of joints between connected segments of a stroked path
'lineJoin' => $style['lineJoin'] ?? 'miter',
// maximum length of mitered line joins for stroked paths
'miterLimit' => $style['miterLimit'] ?? (10.0 / $this->kunit),
// lengths of alternating dashes and gaps
'dashArray' => $style['dashArray'] ?? [],
// distance at which to start the dash
'dashPhase' => $style['dashPhase'] ?? 0.0,
// line (drawing) color
'lineColor' => $style['lineColor'] ?? 'black',
// background (filling) color
'fillColor' => $style['fillColor'] ?? 'black',
];
}
/**
* Returns current PDF object number
*/
public function getObjectNumber(): int
{
return $this->pon;
}
/**
* Set page height and returns previous value.
*
* @param float $pageh Page height.
*
* @return float previous page height value.
*/
public function setPageHeight(float $pageh): float
{
$ret = $this->pageh;
$this->pageh = $pageh;
return $ret;
}
/**
* Set page width and returns previous value.
*
* @param float $pagew Page width.
*
* @return float previous page width value.
*/
public function setPageWidth(float $pagew): float
{
$ret = $this->pagew;
$this->pagew = $pagew;
return $ret;
}
/**
* Set unit of measure conversion ratio.
*
* @param float $kunit Unit of measure conversion ratio.
*/
public function setKUnit(float $kunit): static
{
$this->kunit = $kunit;
return $this;
}
/**
* Get the PDF output string for ExtGState
*
* @param int $pon Current PDF Object Number
*
* @return string PDF command
*/
public function getOutExtGState(int $pon): string
{
$this->pon = $pon;
$out = '';
foreach ($this->extgstates as $idx => $ext) {
$this->extgstates[$idx]['n'] = ++$this->pon;
$out .= $this->pon . ' 0 obj' . "\n" . '<< /Type /ExtGState';
foreach ($ext['parms'] as $key => $val) {
$val = match (true) {
\is_numeric($val) => \sprintf('%F', $val),
$val === true => 'true',
$val === false => 'false',
default => $val,
};
$out .= ' /' . $key . ' ' . $val;
}
$out .= ' >>' . "\n" . 'endobj' . "\n";
}
return $out;
}
/**
* Returns the last extgstate ID to be used with XObjects.
*
* @return ?int
*/
public function getLastExtGStateID(): ?int
{
return \array_key_last($this->extgstates);
}
/**
* Returns the resource names of the registered ExtGState objects that carry
* actual (non-trivial) transparency: a fill or stroke alpha below 1, a blend
* mode other than Normal, or a soft mask.
*
* The returned names match the tokens used by the `gs` operator in content
* streams (for example "GS3"), so callers can detect whether a given content
* stream actually triggers transparency (as opposed to merely resetting the
* graphics state back to fully opaque).
*
* @return array<int, string> List of ExtGState resource names.
*/
public function getTransparencyExtGStateNames(): array
{
$names = [];
foreach ($this->extgstates as $key => $ext) {
if (!self::extGStateHasTransparency($ext['parms'])) {
continue;
}
$names[] = $ext['name'] !== '' ? $ext['name'] : 'GS' . $key;
}
return $names;
}
/**
* Whether the given ExtGState parameters describe actual transparency:
* a constant alpha below 1, a non-Normal blend mode, or a soft mask.
*
* @param array<string, int|float|bool|string> $parms ExtGState parameters.
*/
private static function extGStateHasTransparency(array $parms): bool
{
$belowOne = static fn(string $key): bool => (
isset($parms[$key])
&& \is_numeric($parms[$key])
&& (float) $parms[$key] < 1.0
);
if ($belowOne('ca') || $belowOne('CA')) {
return true;
}
$blend = isset($parms['BM']) ? \ltrim((string) $parms['BM'], '/') : 'Normal';
if ($blend !== '' && $blend !== 'Normal') {
return true;
}
$smask = isset($parms['SMask']) ? \ltrim((string) $parms['SMask'], '/') : 'None';
return $smask !== '' && $smask !== 'None';
}
/**
* Get the PDF output string for ExtGState Resource Dictionary.
*
* @param array<int, array{'name': string, 'n': int, 'parms'?: array<string, int|float|bool|string>}> $data extgstates data.
*
* @return string PDF command
*/
private function getOutExtGStateResDict(array $data): string
{
if ($this->pdfa || $this->extgstates === []) {
return '';
}
$out = ' /ExtGState <<';
foreach ($data as $key => $ext) {
$out .= $ext['name'] !== '' ? ' /' . $ext['name'] : ' /GS' . $key;
$out .= ' ' . $ext['n'] . ' 0 R';
}
return $out . (' >>' . "\n");
}
/**
* Get the PDF output string for ExtGState Resource Dictionary
*
* @return string PDF command
*/
public function getOutExtGStateResources(): string
{
return $this->getOutExtGStateResDict($this->extgstates);
}
/**
* Get the PDF output string for ExtGState Resource Dictionary for XObjects.
*
* @param array<int> $keys Array of extgstates keys.
*
* @return string PDF command
*/
public function getOutExtGStateResourcesByKeys(array $keys): string
{
if ($keys === []) {
return '';
}
$data = [];
foreach ($keys as $key) {
$ext = $this->extgstates[$key] ?? null;
if (!\is_array($ext)) {
continue;
}
$data[$key] = [
'name' => $ext['name'],
'n' => $ext['n'],
];
}
return $this->getOutExtGStateResDict($data);
}
/**
* Get the PDF output string for Gradients Resource Dictionary.
*
* @param array<int, array{'id': int, 'pattern': int, 'antialias'?: bool, 'background'?: ?\Com\Tecnick\Color\Model, 'colors'?: array<int, array{'color': string, 'exponent'?: float, 'opacity'?: float, 'offset'?: float}>, 'colspace'?: string, 'coords'?: array<float>, 'stream'?: string, 'transparency'?: bool, 'type'?: int}> $data gradients data.
*
* @return string PDF command
*/
private function getOutGradientResDict(array $data): string
{
if ($this->pdfa || $data === []) {
return '';
}
$grp = '';
$grs = '';
foreach ($data as $idx => $grad) {
// gradient patterns
$grp .= ' /p' . $idx . ' ' . $grad['pattern'] . ' 0 R';
// gradient shadings
$grs .= ' /Sh' . $idx . ' ' . $grad['id'] . ' 0 R';
}
return ' /Pattern <<' . $grp . ' >>' . "\n" . ' /Shading <<' . $grs . ' >>' . "\n";
}
/**
* Get the PDF output string for Gradients Resource Dictionary
*
* @return string PDF command
*/
public function getOutGradientResources(): string
{
return $this->getOutGradientResDict($this->gradients);
}
/**
* Returns the PDF command to output gradient resources.
*
* @param array<int> $keys Array of gradient keys.
*
* @return string PDF command
*/
public function getOutGradientResourcesByKeys(array $keys): string
{
if ($keys === []) {
return '';
}
$data = [];
foreach ($keys as $key) {
$grad = $this->gradients[$key] ?? null;
if (!\is_array($grad)) {
continue;
}
$data[$key] = [
'id' => $grad['id'],
'pattern' => $grad['pattern'],
];
}
return $this->getOutGradientResDict($data);
}
/**
* Get the PDF output string for gradient colors and transparency
*
* @param GradientData $grad Array of gradient colors
* @param string $type Type of output: 'color' or 'opacity'
*
* @return string PDF command
*
* @throws \Com\Tecnick\Pdf\Encrypt\Exception
*
* @SuppressWarnings("PHPMD.CyclomaticComplexity")
*/
protected function getOutGradientCols(array $grad, string $type): string
{
if ($type === 'opacity' && !$grad['transparency']) {
return '';
}
$out = '';
if ($grad['type'] === 2 || $grad['type'] === 3) {
$num_cols = \count($grad['colors']);
$lastcols = $num_cols - 1;
$funct = []; // color and transparency objects
$bounds = [];
$encode = [];
for ($idx = 1; $idx < $num_cols; ++$idx) {
$prevcol = $grad['colors'][$idx - 1] ?? null;
$nextcol = $grad['colors'][$idx] ?? null;
if (!\is_array($prevcol) || !\is_array($nextcol)) {
continue;
}
$col0 = $prevcol[$type] ?? null;
$col1 = $nextcol[$type] ?? null;
if ($type !== 'color') {
if (!\is_numeric($col0) || !\is_numeric($col1)) {
continue;
}
$col0 = \sprintf('%F', (float) $col0);
$col1 = \sprintf('%F', (float) $col1);
} else {
if (!\is_string($col0) || !\is_string($col1)) {
continue;
}
$model0 = $this->pdfColor->getColorObject($col0);
$model1 = $this->pdfColor->getColorObject($col1);
if (!$model0 instanceof \Com\Tecnick\Color\Model) {
continue;
}
if (!$model1 instanceof \Com\Tecnick\Color\Model) {
continue;
}
$col0 = $model0->getComponentsString();
$col1 = $model1->getComponentsString();
}
$encode[] = '0 1';
$offset = $nextcol['offset'] ?? null;
if ($idx < $lastcols && \is_float($offset)) {
$bounds[] = \sprintf('%F ', $offset);
}
$out .=
++$this->pon
. ' 0 obj'
. "\n"
. '<<'
. ' /FunctionType 2'
. ' /Domain [0 1]'
. ' /C0 ['
. $col0
. ']'
. ' /C1 ['
. $col1
. ']';
$exponent = $nextcol['exponent'] ?? null;
if (\is_float($exponent)) {
$out .= ' /N ' . $exponent;
}
$out .= ' >>' . "\n" . 'endobj' . "\n";
$funct[] = $this->pon . ' 0 R';
}
$out .=
++$this->pon
. ' 0 obj'
. "\n"
. '<<'
. ' /FunctionType 3'
. ' /Domain [0 1]'
. ' /Functions ['
. \implode(' ', $funct)
. ']'
. ' /Bounds ['
. \implode(' ', $bounds)
. ']'
. ' /Encode ['
. \implode(' ', $encode)
. ']'
. ' >>'
. "\n"
. 'endobj'
. "\n";
}
return $out . $this->getOutPatternObj($grad, $this->pon);
}
/**
* Get the PDF output string for the pattern and shading object
*
* @param GradientData $grad Array of gradient colors
* @param int $objref Reference object number
*
* @return string PDF command
*
* @throws \Com\Tecnick\Pdf\Encrypt\Exception
*/
protected function getOutPatternObj(array $grad, int $objref): string
{
// set shading object
if ($grad['transparency']) {
$grad['colspace'] = 'DeviceGray';
}
$oid = ++$this->pon;
$coords = $grad['coords'];
$out = $oid . ' 0 obj' . "\n" . '<< /ShadingType ' . $grad['type'] . ' /ColorSpace /' . $grad['colspace'];
if ($grad['background'] !== null) {
$out .= ' /Background [' . $grad['background']->getComponentsString() . ']';
}
if ($grad['antialias']) {
$out .= ' /AntiAlias true';
}
if ($grad['type'] === 2) {
$out .= \sprintf(
' /Coords [%F %F %F %F] /Domain [0 1] /Function %d 0 R /Extend [true true] >>' . "\n",
$coords[0] ?? 0.0,
$coords[1] ?? 0.0,
$coords[2] ?? 0.0,
$coords[3] ?? 0.0,
$objref,
);
} elseif ($grad['type'] === 3) {
// x0, y0, r0, x1, y1, r1
// the radius of the inner circle is 0
$out .= \sprintf(
' /Coords [%F %F 0 %F %F %F] /Domain [0 1] /Function %d 0 R /Extend [true true] >>' . "\n",
$coords[0] ?? 0.0,
$coords[1] ?? 0.0,
$coords[2] ?? 0.0,
$coords[3] ?? 0.0,
$coords[4] ?? 0.0,
$objref,
);
} elseif ($grad['type'] === 6) {
$stream = $this->encrypt->encryptString($grad['stream'], $this->pon);
$out .=
' /BitsPerCoordinate 16 /BitsPerComponent 8/Decode[0 1 0 1 0 1 0 1 0 1] /BitsPerFlag 8 /Length '
. \strlen($stream)
. ' >>'
. "\n"
. ' stream'
. "\n"
. $stream
. "\n"
. 'endstream'
. "\n";
}
$out .= 'endobj' . "\n";
// pattern object
$out .=
++$this->pon
. ' 0 obj'
. "\n"
. '<<'
. ' /Type /Pattern'
. ' /PatternType 2'
. ' /Shading '
. $oid
. ' 0 R'
. ' >>'
. "\n"
. 'endobj'
. "\n";
return $out;
}
/**
* Get the PDF output string for gradient shaders
*
* @param int $pon Current PDF Object Number
*
* @return string PDF command
*
* @throws \Com\Tecnick\Pdf\Encrypt\Exception
*/
public function getOutGradientShaders(int $pon): string
{
$this->pon = $pon;
if ($this->pdfa || $this->gradients === []) {
return '';
}
$idt = \count($this->gradients); // index for transparency gradients
$out = '';
foreach ($this->gradients as $idx => $grad) {
$gcol = $this->getOutGradientCols($grad, 'color');
if ($gcol !== '') {
$out .= $gcol;
$this->gradients[$idx]['id'] = $this->pon - 1;
$this->gradients[$idx]['pattern'] = $this->pon;
}
$gopa = $this->getOutGradientCols($grad, 'opacity');
$idgs = $idx + $idt;
if ($gopa !== '') {
$out .= $gopa;
$this->gradientMasks[$idgs] = [
'id' => $this->pon - 1,
'pattern' => $this->pon,
];
}
if ($grad['transparency']) {
$mask = $this->gradientMasks[$idgs] ?? null;
if ($mask === null) {
// no transparency pattern was generated: skip without emitting a partial object
continue;
}
$oid = ++$this->pon;
$pwidth = $this->pagew * $this->kunit;
$pheight = $this->pageh * $this->kunit;
$rect = \sprintf('%F %F', $pwidth, $pheight);
$out .= $oid . ' 0 obj' . "\n" . '<< /Type /XObject /Subtype /Form /FormType 1';
$stream = 'q /a0 gs /Pattern cs /p' . $idgs . ' scn 0 0 ' . $pwidth . ' ' . $pheight . ' re f Q';
if ($this->compress) {
$cmpstream = \gzcompress($stream);
if ($cmpstream !== false) {
$stream = $cmpstream;
$out .= ' /Filter /FlateDecode';
}
}
$stream = $this->encrypt->encryptString($stream, $oid);
$out .=
' /Length '
. \strlen($stream)
. ' /BBox [0 0 '
. $rect
. ']'
. ' /Group << /Type /Group /S /Transparency /CS /DeviceGray >>'
. ' /Resources <<'
. ' /ExtGState << /a0 << /ca 1 /CA 1 >> >>'
. ' /Pattern << /p'
. $idgs
. ' '
. $mask['pattern']
. ' 0 R >>'
. ' >>'
. ' >>'
. "\n"
. ' stream'
. "\n"
. $stream
. "\n"
. 'endstream'
. "\n"
. 'endobj'
. "\n";
// SMask
$objsm = ++$this->pon;
$out .=
$objsm
. ' 0 obj'
. "\n"
. '<<'
. ' /Type /Mask'
. ' /S /Luminosity'
. ' /G '
. $oid
. ' 0 R'
. ' >>'
. "\n"
. 'endobj'
. "\n";
// ExtGState
$objext = ++$this->pon;
$out .=
$objext
. ' 0 obj'
. "\n"
. '<<'
. ' /Type /ExtGState'
. ' /SMask '
. $objsm
. ' 0 R'
. ' /AIS false'
. ' >>'
. "\n"
. 'endobj'
. "\n";
$this->extgstates[] = [
'n' => $objext,
'name' => 'TGS' . $idx,
// Record the soft mask so this entry is recognised as carrying
// actual transparency (see getTransparencyExtGStateNames()).
'parms' => [
'SMask' => $objsm . ' 0 R',
],
];
}
}
return $out;
}
}
+90
View File
@@ -0,0 +1,90 @@
<?php
declare(strict_types=1);
/**
* BlendMode.php
*
* @since 2026-07-17
* @category Library
* @package PdfGraph
* @author Nicola Asuni <info@tecnick.com>
* @copyright 2011-2026 Nicola Asuni - Tecnick.com LTD
* @license https://www.gnu.org/copyleft/lesser.html GNU-LGPL v3 (see LICENSE)
* @link https://github.com/tecnickcom/tc-lib-pdf-graph
*
* This file is part of tc-lib-pdf-graph software library.
*/
namespace Com\Tecnick\Pdf\Graph;
/**
* Com\Tecnick\Pdf\Graph\BlendMode
*
* Backed enum for the PDF blend modes (PDF 32000-1:2008 - 11.3.5). The backing
* value of each case is the canonical /BM name validated by Gradient::getAlpha().
*
* @since 2026-07-17
* @category Library
* @package PdfGraph
* @author Nicola Asuni <info@tecnick.com>
* @copyright 2011-2026 Nicola Asuni - Tecnick.com LTD
* @license https://www.gnu.org/copyleft/lesser.html GNU-LGPL v3 (see LICENSE)
* @link https://github.com/tecnickcom/tc-lib-pdf-graph
*/
enum BlendMode: string
{
case Normal = 'Normal';
case Multiply = 'Multiply';
case Screen = 'Screen';
case Overlay = 'Overlay';
case Darken = 'Darken';
case Lighten = 'Lighten';
case ColorDodge = 'ColorDodge';
case ColorBurn = 'ColorBurn';
case HardLight = 'HardLight';
case SoftLight = 'SoftLight';
case Difference = 'Difference';
case Exclusion = 'Exclusion';
case Hue = 'Hue';
case Saturation = 'Saturation';
case Color = 'Color';
case Luminosity = 'Luminosity';
/**
* Resolve a loose blend mode value to the matching enum case.
*
* Accepts an enum instance (returned unchanged) or a string (with an
* optional leading '/' stripped, as PDF /BM names carry). Unknown values
* fall back to Normal, matching Gradient::getAlpha().
*
* @param string|self $value Blend mode name or enum case.
*/
public static function fromLoose(string|self $value): self
{
if ($value instanceof self) {
return $value;
}
if ($value !== '' && $value[0] === '/') {
$value = \substr($value, 1);
}
return self::tryFrom($value) ?? self::Normal;
}
}
+799
View File
@@ -0,0 +1,799 @@
<?php
declare(strict_types=1);
/**
* Draw.php
*
* @since 2011-05-23
* @category Library
* @package PdfGraph
* @author Nicola Asuni <info@tecnick.com>
* @copyright 2011-2026 Nicola Asuni - Tecnick.com LTD
* @license https://www.gnu.org/copyleft/lesser.html GNU-LGPL v3 (see LICENSE)
* @link https://github.com/tecnickcom/tc-lib-pdf-graph
*
* This file is part of tc-lib-pdf-graph software library.
*/
namespace Com\Tecnick\Pdf\Graph;
use Com\Tecnick\Pdf\Graph\Exception as GraphException;
/**
* Com\Tecnick\Pdf\Graph\Draw
*
* @since 2011-05-23
* @category Library
* @package PdfGraph
* @author Nicola Asuni <info@tecnick.com>
* @copyright 2011-2026 Nicola Asuni - Tecnick.com LTD
* @license https://www.gnu.org/copyleft/lesser.html GNU-LGPL v3 (see LICENSE)
* @link https://github.com/tecnickcom/tc-lib-pdf-graph
*
* @phpstan-import-type StyleDataOpt from \Com\Tecnick\Pdf\Graph\Base
*
* @SuppressWarnings("PHPMD.ExcessiveClassComplexity")
*/
class Draw extends \Com\Tecnick\Pdf\Graph\Gradient
{
/**
* Draws a line between two points.
*
* @param float $posx1 Abscissa of first point.
* @param float $posy1 Ordinate of first point.
* @param float $posx2 Abscissa of second point.
* @param float $posy2 Ordinate of second point.
* @param StyleDataOpt $style Line style to apply.
*
* @return string PDF command
*/
public function getLine(float $posx1, float $posy1, float $posx2, float $posy2, array $style = []): string
{
return (
$this->getStyleCmd($style)
. $this->getRawPoint($posx1, $posy1)
. $this->getRawLine($posx2, $posy2)
. $this->getPathPaintOp('S')
);
}
/**
* Draws a Bezier curve.
* The Bezier curve is a tangent to the line between the control points at either end of the curve.
*
* @param float $posx0 Abscissa of start point.
* @param float $posy0 Ordinate of start point.
* @param float $posx1 Abscissa of control point 1.
* @param float $posy1 Ordinate of control point 1.
* @param float $posx2 Abscissa of control point 2.
* @param float $posy2 Ordinate of control point 2.
* @param float $posx3 Abscissa of end point.
* @param float $posy3 Ordinate of end point.
* @param string|PathPaintOp $mode Mode of rendering. @see getPathPaintOp()
* @param StyleDataOpt $style Style.
*
* @return string PDF command
*
* @SuppressWarnings("PHPMD.ExcessiveParameterList")
*/
public function getCurve(
float $posx0,
float $posy0,
float $posx1,
float $posy1,
float $posx2,
float $posy2,
float $posx3,
float $posy3,
string|PathPaintOp $mode = 'S',
array $style = [],
): string {
return (
$this->getStyleCmd($style)
. $this->getRawPoint($posx0, $posy0)
. $this->getRawCurve($posx1, $posy1, $posx2, $posy2, $posx3, $posy3)
. $this->getPathPaintOp($mode)
);
}
/**
* Draws a poly-Bezier curve.
* Each Bezier curve segment is a tangent to the line between the control points at either end of the curve.
*
* @param float $posx0 Abscissa of start point.
* @param float $posy0 Ordinate of start point.
* @param array<array<float>> $segments An array of bezier descriptions. Format: array(x1, y1, x2, y2, x3, y3).
* @param string|PathPaintOp $mode Mode of rendering. @see getPathPaintOp()
* @param StyleDataOpt $style Style.
*
* @return string PDF command
*/
public function getPolycurve(
float $posx0,
float $posy0,
array $segments,
string|PathPaintOp $mode = 'S',
array $style = [],
): string {
$out = $this->getStyleCmd($style) . $this->getRawPoint($posx0, $posy0);
foreach ($segments as $segment) {
if (!isset($segment[0], $segment[1], $segment[2], $segment[3], $segment[4], $segment[5])) {
continue;
}
$posx1 = $segment[0];
$posy1 = $segment[1];
$posx2 = $segment[2];
$posy2 = $segment[3];
$posx3 = $segment[4];
$posy3 = $segment[5];
$out .= $this->getRawCurve($posx1, $posy1, $posx2, $posy2, $posx3, $posy3);
}
return $out . $this->getPathPaintOp($mode);
}
/**
* Draws an ellipse.
* An ellipse is formed from n Bezier curves.
*
* @param float $posx Abscissa of center point.
* @param float $posy Ordinate of center point.
* @param float $hrad Horizontal radius.
* @param float $vrad Vertical radius.
* @param float $angle Angle oriented (anti-clockwise). Default value: 0.
* @param float $angs Angle in degrees at which starting drawing.
* @param float $angf Angle in degrees at which stop drawing.
* @param string|PathPaintOp $mode Mode of rendering. @see getPathPaintOp()
* @param StyleDataOpt $style Style.
* @param int $ncv Number of curves used to draw a 90 degrees portion of ellipse.
*
* @return string PDF command
*
* @SuppressWarnings("PHPMD.ExcessiveParameterList")
*/
public function getEllipse(
float $posx,
float $posy,
float $hrad,
float $vrad = 0,
float $angle = 0,
float $angs = 0,
float $angf = 360,
string|PathPaintOp $mode = 'S',
array $style = [],
int $ncv = 2,
): string {
if ($vrad === 0.0) {
$vrad = $hrad;
}
return (
$this->getStyleCmd($style)
. $this->getRawEllipticalArc(
$posx,
$posy,
$hrad,
$vrad,
$angle,
$angs,
$angf,
false,
$ncv,
true,
true,
false,
)
. $this->getPathPaintOp($mode)
);
}
/**
* Draws a circle.
* A circle is formed from n Bezier curves.
*
* @param float $posx Abscissa of center point.
* @param float $posy Ordinate of center point.
* @param float $rad Radius.
* @param float $angs Angle in degrees at which starting drawing.
* @param float $angf Angle in degrees at which stop drawing.
* @param string|PathPaintOp $mode Mode of rendering. @see getPathPaintOp()
* @param StyleDataOpt $style Style.
* @param int $ncv Number of curves used to draw a 90 degrees portion of ellipse.
*
* @return string PDF command
*/
public function getCircle(
float $posx,
float $posy,
float $rad,
float $angs = 0,
float $angf = 360,
string|PathPaintOp $mode = 'S',
array $style = [],
int $ncv = 2,
): string {
return $this->getEllipse($posx, $posy, $rad, $rad, 0, $angs, $angf, $mode, $style, $ncv);
}
/**
* Draws a circle pie sector.
*
* @param float $posx Abscissa of center point.
* @param float $posy Ordinate of center point.
* @param float $rad Radius.
* @param float $angs Angle in degrees at which starting drawing.
* @param float $angf Angle in degrees at which stop drawing.
* @param string|PathPaintOp $mode Mode of rendering. @see getPathPaintOp()
* @param StyleDataOpt $style Style.
* @param int $ncv Number of curves used to draw a 90 degrees portion of ellipse.
*
* @return string PDF command
*/
public function getPieSector(
float $posx,
float $posy,
float $rad,
float $angs = 0,
float $angf = 360,
string|PathPaintOp $mode = 'FD',
array $style = [],
int $ncv = 2,
): string {
return (
$this->getStyleCmd($style)
. $this->getRawEllipticalArc($posx, $posy, $rad, $rad, 0, $angs, $angf, true, $ncv, true, true, false)
. $this->getPathPaintOp($mode)
);
}
/**
* Draws a basic polygon.
*
* @param array<float> $points Points - array containing 4 points for each segment: (x0, y0, x1, y1, x2, y2, ...)
* @param string|PathPaintOp $mode Mode of rendering. @see getPathPaintOp()
* @param StyleDataOpt $style Style.
*
* @return string PDF command
*/
public function getBasicPolygon(array $points, string|PathPaintOp $mode = 'S', array $style = []): string
{
$nco = \count($points); // number of coordinates
if ($nco < 4 || ($points[0] ?? null) === null || ($points[1] ?? null) === null) {
return ''; // need at least 2 points (4 coordinates)
}
$out = $this->getStyleCmd($style) . $this->getRawPoint($points[0], $points[1]);
for ($idx = 2; $idx < $nco; $idx += 2) {
if (($points[$idx] ?? null) === null || ($points[$idx + 1] ?? null) === null) {
continue;
}
$posx = $points[$idx] ?? 0.0;
$posy = $points[$idx + 1] ?? 0.0;
$out .= $this->getRawLine($posx, $posy);
}
return $out . $this->getPathPaintOp($mode);
}
/**
* Returns the polygon default style command and initialize the first segment style if missing.
*
* @param array<StyleDataOpt> $styles Array of styles -
* one style entry for each polygon segment and/or one global "all" entry.
*
* @return string PDF command
*/
protected function getDefaultSegStyle(array $styles = []): string
{
$out = '';
$styleAll = $styles['all'] ?? [];
if ($styleAll !== []) {
$out .= $this->getStyleCmd($styleAll);
}
return $out;
}
/**
* Draws a polygon with a different style for each segment.
*
* @param array<float> $points Points - array with values (x0, y0, x1, y1,..., x(n-1), y(n-1))
* @param string|PathPaintOp $mode Mode of rendering. @see getPathPaintOp()
* @param array<StyleDataOpt> $styles Array of styles -
* one style entry for each polygon segment and/or one global "all" entry.
*
* @return string PDF command
*
* @SuppressWarnings("PHPMD.CyclomaticComplexity")
* @SuppressWarnings("PHPMD.NPathComplexity")
*/
public function getPolygon(array $points, string|PathPaintOp $mode = 'S', array $styles = []): string
{
if ($mode instanceof PathPaintOp) {
$mode = $mode->value;
}
$nco = \count($points); // number of points
if ($nco < 6 || ($points[0] ?? null) === null || ($points[1] ?? null) === null) {
return ''; // we need at least 3 points
}
$nseg = (int) ($nco / 2); // number of segments (including the closing one)
$out = $this->getDefaultSegStyle($styles);
$lastx = $points[$nco - 2] ?? null;
$lasty = $points[$nco - 1] ?? null;
if (
$this->isClosingMode($mode)
&& $lastx !== null
&& $lasty !== null
&& ($lastx !== $points[0] || $lasty !== $points[1])
) {
// close polygon by adding the first point (x, y) at the end
$points[$nco++] = $points[0];
$points[$nco++] = $points[1];
$style0 = $styles[0] ?? [];
if ($style0 !== []) {
// copy style for the last segment
$styles[$nseg - 1] = $style0;
}
}
// paint the filling
if ($this->isFillingMode($mode)) {
$out .= $this->getBasicPolygon($points, $this->getModeWithoutStroke($mode));
if ($this->isClippingMode($mode)) {
return $out;
}
}
if (!$this->isStrokingMode($mode)) {
return $out;
}
// When the outline is uniformly styled (no per-segment style overrides),
// stroke it as a single continuous path so that adjacent edges are joined
// at the vertices (miter/round/bevel) instead of being drawn as
// independent, butt-capped segments that would leave the corners open.
$hasSegmentStyles = false;
foreach ($styles as $skey => $sval) {
if (!\is_int($skey) || $sval === []) {
continue;
}
$hasSegmentStyles = true;
break;
}
if (!$hasSegmentStyles) {
$closed = $points[0] === ($points[$nco - 2] ?? null) && $points[1] === ($points[$nco - 1] ?? null);
return $out . $this->getBasicPolygon($points, $closed ? 's' : 'S');
}
$nco -= 3;
// paint the outline
for ($idx = 0; $idx < $nco; $idx += 2) {
$segid = (int) ($idx / 2);
$styles[$segid] ??= [];
if (
($points[$idx] ?? null) === null
|| ($points[$idx + 1] ?? null) === null
|| ($points[$idx + 2] ?? null) === null
|| ($points[$idx + 3] ?? null) === null
) {
continue;
}
$posx1 = $points[$idx] ?? 0.0;
$posy1 = $points[$idx + 1] ?? 0.0;
$posx2 = $points[$idx + 2] ?? 0.0;
$posy2 = $points[$idx + 3] ?? 0.0;
$segstyle = $styles[$segid] ?? [];
$out .= $this->getLine($posx1, $posy1, $posx2, $posy2, $segstyle);
}
return $out;
}
/**
* Draws a regular polygon.
*
* @param float $posx Abscissa of center point.
* @param float $posy Ordinate of center point.
* @param float $radius Radius of inscribed circle.
* @param int $sides Number of sides.
* @param float $angle Angle of the orientation (anti-clockwise).
* @param string|PathPaintOp $mode Mode of rendering. @see getPathPaintOp()
* @param array<StyleDataOpt> $styles Array of styles -
* one style entry for each polygon segment and/or one global "all" entry.
* @param string|PathPaintOp $cirmode Mode of rendering of the inscribed circle (if any). @see getPathPaintOp()
* @param StyleDataOpt $cirstyle Style of inscribed circle.
*
* @return string PDF command
*/
public function getRegularPolygon(
float $posx,
float $posy,
float $radius,
int $sides,
float $angle = 0,
string|PathPaintOp $mode = 'S',
array $styles = [],
string|PathPaintOp $cirmode = '',
array $cirstyle = [],
): string {
if ($sides < 3) { // triangle is the minimum polygon
return '';
}
$out = '';
if ($cirmode !== '') {
$out .= $this->getCircle($posx, $posy, $radius, 0, 360, $cirmode, $cirstyle);
}
$points = [];
for ($idx = 0; $idx < $sides; ++$idx) {
$angrad = $this->degToRad($angle + (($idx * 360) / $sides));
$points[] = $posx + ($radius * \sin($angrad));
$points[] = $posy + ($radius * \cos($angrad));
}
return $out . $this->getPolygon($points, $mode, $styles);
}
/**
* Draws a star polygon.
*
* @param float $posx Abscissa of center point.
* @param float $posy Ordinate of center point.
* @param float $radius Radius of inscribed circle.
* @param int $nvert Number of vertices.
* @param int $ngaps Number of gaps (if ($ngaps % $nvert = 1) then is a regular polygon).
* @param float $angle Angle oriented (anti-clockwise).
* @param string|PathPaintOp $mode Mode of rendering. @see getPathPaintOp()
* @param array<StyleDataOpt> $styles Array of styles -
* one style entry for each polygon segment and/or one global "all" entry.
* @param string|PathPaintOp $cirmode Mode of rendering of the inscribed circle (if any). @see getPathPaintOp()
* @param StyleDataOpt $cirstyle Style of inscribed circle.
*
* @return string PDF command
*
* @SuppressWarnings("PHPMD.ExcessiveParameterList")
*/
public function getStarPolygon(
float $posx,
float $posy,
float $radius,
int $nvert,
int $ngaps,
float $angle = 0,
string|PathPaintOp $mode = 'S',
array $styles = [],
string|PathPaintOp $cirmode = '',
array $cirstyle = [],
): string {
if ($nvert < 2) {
return '';
}
$out = '';
if ($cirmode !== '') {
$out .= $this->getCircle($posx, $posy, $radius, 0, 360, $cirmode, $cirstyle);
}
$points = [];
$visited = [];
$idx = 0;
while ($idx >= 0 && !isset($visited[$idx])) {
$visited[$idx] = true;
$angrad = $this->degToRad($angle + (($idx * 360) / $nvert));
$points[] = $posx + ($radius * \sin($angrad));
$points[] = $posy + ($radius * \cos($angrad));
$idx = ($idx + $ngaps) % $nvert;
}
if (\count($points) < 6) {
return $out;
}
return $out . $this->getPolygon($points, $mode, $styles);
}
/**
* Draws a rectangle with a different style for each segment.
*
* @param float $posx Abscissa of upper-left corner.
* @param float $posy Ordinate of upper-left corner.
* @param float $width Width.
* @param float $height Height.
* @param string|PathPaintOp $mode Mode of rendering. @see getPathPaintOp()
* @param array<StyleDataOpt> $styles Array of styles -
* one style entry for each side (T,R,B,L) and/or one global "all" entry.
*
* @return string PDF command
*/
public function getRect(
float $posx,
float $posy,
float $width,
float $height,
string|PathPaintOp $mode = 'S',
array $styles = [],
): string {
$points = [
$posx,
$posy,
$posx + $width,
$posy,
$posx + $width,
$posy + $height,
$posx,
$posy + $height,
$posx,
$posy,
];
return $this->getPolygon($points, $mode, $styles);
}
/**
* Draws a rounded rectangle.
*
* @param float $posx Abscissa of upper-left corner.
* @param float $posy Ordinate of upper-left corner.
* @param float $width Width.
* @param float $height Height.
* @param float $hrad X-axis radius of the ellipse used to round off the corners of the rectangle.
* @param float $vrad Y-axis radius of the ellipse used to round off the corners of the rectangle.
* @param string $corner Round corners to draw: 0 (square i-corner) or 1 (rounded i-corner) in i-position.
* Positions are in the following order: top right, bottom right, bottom left and
* top left.
* @param string|PathPaintOp $mode Mode of rendering. @see getPathPaintOp()
* @param StyleDataOpt $style Style.
*
* @return string PDF command
*
* @SuppressWarnings("PHPMD.CyclomaticComplexity")
* @SuppressWarnings("PHPMD.NPathComplexity")
*/
public function getRoundedRect(
float $posx,
float $posy,
float $width,
float $height,
float $hrad,
float $vrad,
string $corner = '1111',
string|PathPaintOp $mode = 'S',
array $style = [],
): string {
if ($corner === '0000' || $hrad === 0.0 && $vrad === 0.0) {
// basic rectangle with straight corners
return $this->getBasicRect($posx, $posy, $width, $height, $mode, $style);
}
$out = $this->getStyleCmd($style);
$out .= $corner[3] !== '0' ? $this->getRawPoint($posx + $hrad, $posy) : $this->getRawPoint($posx, $posy);
$posxc = $posx + $width - $hrad;
$posyc = $posy + $vrad;
$out .= $this->getRawLine($posxc, $posy);
$arc = (4 / 3) * (\sqrt(2) - 1);
$harc = $hrad * $arc;
$varc = $vrad * $arc;
$out .= $corner[0] !== '0'
? $this->getRawCurve($posxc + $harc, $posyc - $vrad, $posxc + $hrad, $posyc - $varc, $posxc + $hrad, $posyc)
: $this->getRawLine($posx + $width, $posy);
$posxc = $posx + $width - $hrad;
$posyc = $posy + $height - $vrad;
$out .= $this->getRawLine($posx + $width, $posyc);
$out .= $corner[1] !== '0'
? $this->getRawCurve($posxc + $hrad, $posyc + $varc, $posxc + $harc, $posyc + $vrad, $posxc, $posyc + $vrad)
: $this->getRawLine($posx + $width, $posy + $height);
$posxc = $posx + $hrad;
$posyc = $posy + $height - $vrad;
$out .= $this->getRawLine($posxc, $posy + $height);
$out .= $corner[2] !== '0'
? $this->getRawCurve($posxc - $harc, $posyc + $vrad, $posxc - $hrad, $posyc + $varc, $posxc - $hrad, $posyc)
: $this->getRawLine($posx, $posy + $height);
$posxc = $posx + $hrad;
$posyc = $posy + $vrad;
$out .= $this->getRawLine($posx, $posyc);
$out .= $corner[3] !== '0'
? $this->getRawCurve($posxc - $hrad, $posyc - $varc, $posxc - $harc, $posyc - $vrad, $posxc, $posyc - $vrad)
: $this->getRawLine($posx, $posy);
return $out . $this->getPathPaintOp($mode);
}
/**
* Draws an arrow.
*
* @param float $posx0 Abscissa of first point.
* @param float $posy0 Ordinate of first point.
* @param float $posx1 Abscissa of second point (head side).
* @param float $posy1 Ordinate of second point (head side)
* @param int $headmode Arrow head mode:
* 0 = draw only
* head arms; 1 =
* draw closed head
* without filling;
* 2 = closed and
* filled head; 3 =
* filled head.
* @param float $armsize Length of head arms.
* @param int $armangle Angle between an head arm and the arrow shaft.
* @param StyleDataOpt $style Line style to apply.
*
* @return string PDF command
*/
public function getArrow(
float $posx0,
float $posy0,
float $posx1,
float $posy1,
int $headmode = 0,
float $armsize = 5,
int $armangle = 15,
array $style = [],
): string {
// getting arrow direction angle; 0 deg angle is when both arms go along X axis; angle grows clockwise.
$dir_angle = \atan2($posy0 - $posy1, $posx0 - $posx1);
if ($dir_angle < 0) {
$dir_angle += 2 * self::MPI;
}
$armangle = $this->degToRad($armangle);
$sx1 = $posx1;
$sy1 = $posy1;
if ($headmode > 0) {
// calculate the stopping point for the arrow shaft
$linewidth = $style['lineWidth'] ?? (float) $this->getLastStyleProperty('lineWidth', 0);
$sx1 = $posx1 + (($armsize - $linewidth) * \cos($dir_angle));
$sy1 = $posy1 + (($armsize - $linewidth) * \sin($dir_angle));
}
$out = $this->getStyleCmd($style);
// main arrow line / shaft
$out .= $this->getLine($posx0, $posy0, $sx1, $sy1);
// left arrowhead arm tip
$hxl = $posx1 + ($armsize * \cos($dir_angle + $armangle));
$hyl = $posy1 + ($armsize * \sin($dir_angle + $armangle));
// right arrowhead arm tip
$hxr = $posx1 + ($armsize * \cos($dir_angle - $armangle));
$hyr = $posy1 + ($armsize * \sin($dir_angle - $armangle));
$modemap = [
0 => 'S',
1 => 's',
2 => 'b',
3 => 'f',
];
$points = [$hxl, $hyl, $posx1, $posy1, $hxr, $hyr];
// The style was already emitted above and persists in the graphics
// state, so the arrowhead does not need to repeat it.
return $out . $this->getBasicPolygon($points, $modemap[$headmode] ?? 'S');
}
/**
* Get a registration mark.
*
* @param float $posx Abscissa of center point.
* @param float $posy Ordinate of center point.
* @param float $rad Radius.
* @param bool $double If true prints two concentric crop marks.
* @param string $color Color.
*
* @return string PDF command
*
* @throws \Com\Tecnick\Pdf\Graph\Exception
*/
public function getRegistrationMark(
float $posx,
float $posy,
float $rad,
bool $double = false,
string $color = 'all',
): string {
$style = [
'lineWidth' => \max(0.5 / $this->kunit, $rad / 30),
'lineCap' => 'butt',
'lineJoin' => 'miter',
'miterLimit' => 10.0 / $this->kunit,
'dashArray' => [],
'dashPhase' => 0,
'lineColor' => $color,
'fillColor' => $color,
];
$colobj = $this->pdfColor->getColorObject($color);
if (!$colobj instanceof \Com\Tecnick\Color\Model) {
throw new GraphException('Unknown color: ' . $color);
}
$out =
$colobj->getPdfColor()
. $this->getPieSector($posx, $posy, $rad, 90, 180, 'F')
. $this->getPieSector($posx, $posy, $rad, 270, 360, 'F')
. $this->getCircle($posx, $posy, $rad, 0, 360, 'S', [], 8);
if ($double) {
$radi = $rad * 0.5;
$out .=
$colobj->invertColor()->getPdfColor()
. $this->getPieSector($posx, $posy, $radi, 90, 180, 'F')
. $this->getPieSector($posx, $posy, $radi, 270, 360, 'F')
. $this->getCircle($posx, $posy, $radi, 0, 360, 'S', [], 8)
. $colobj->getPdfColor()
. $this->getPieSector($posx, $posy, $radi, 0, 90, 'F')
. $this->getPieSector($posx, $posy, $radi, 180, 270, 'F')
. $this->getCircle($posx, $posy, $radi, 0, 360, 'S', [], 8);
}
return $this->getStartTransform() . $this->getStyleCmd($style) . $out . $this->getStopTransform();
}
/**
* Get a CMYK registration mark.
*
* @param float $posx Abscissa of center point.
* @param float $posy Ordinate of center point.
* @param float $rad Radius.
*
* @return string PDF command
*/
public function getCmykRegistrationMark(float $posx, float $posy, float $rad): string
{
// internal radius
$radi = $rad * 0.6;
// external radius
$rade = $rad * 1.3;
// line style for external circle
$style = [
'lineWidth' => \max(0.5 / $this->kunit, $rad / 30),
'lineCap' => 'butt',
'lineJoin' => 'miter',
'miterLimit' => 10.0 / $this->kunit,
'dashArray' => [],
'dashPhase' => 0,
'lineColor' => 'All',
'fillColor' => '',
];
$cyan = $this->pdfColor->getColorObject('Cyan');
$magenta = $this->pdfColor->getColorObject('Magenta');
$yellow = $this->pdfColor->getColorObject('Yellow');
$key = $this->pdfColor->getColorObject('Key');
return (
$this->getStartTransform()
. ($cyan instanceof \Com\Tecnick\Color\Model ? $cyan->getPdfColor() : '')
. $this->getPieSector($posx, $posy, $radi, 270, 360, 'F')
. ($magenta instanceof \Com\Tecnick\Color\Model ? $magenta->getPdfColor() : '')
. $this->getPieSector($posx, $posy, $radi, 0, 90, 'F')
. ($yellow instanceof \Com\Tecnick\Color\Model ? $yellow->getPdfColor() : '')
. $this->getPieSector($posx, $posy, $radi, 90, 180, 'F')
. ($key instanceof \Com\Tecnick\Color\Model ? $key->getPdfColor() : '')
. $this->getPieSector($posx, $posy, $radi, 180, 270, 'F')
. $this->getStyleCmd($style)
. $this->getCircle($posx, $posy, $rad, 0, 360, 'S', [], 8)
. $this->getLine($posx, $posy - $rade, $posx, $posy - $radi)
. $this->getLine($posx, $posy + $radi, $posx, $posy + $rade)
. $this->getLine($posx - $rade, $posy, $posx - $radi, $posy)
. $this->getLine($posx + $radi, $posy, $posx + $rade, $posy)
. $this->getStopTransform()
);
}
}
+34
View File
@@ -0,0 +1,34 @@
<?php
declare(strict_types=1);
/**
* Exception.php
*
* @since 2011-05-23
* @category Library
* @package PdfGraph
* @author Nicola Asuni <info@tecnick.com>
* @copyright 2011-2026 Nicola Asuni - Tecnick.com LTD
* @license https://www.gnu.org/copyleft/lesser.html GNU-LGPL v3 (see LICENSE)
* @link https://github.com/tecnickcom/tc-lib-pdf-graph
*
* This file is part of tc-lib-pdf-graph software library.
*/
namespace Com\Tecnick\Pdf\Graph;
/**
* Com\Tecnick\Pdf\Graph\Exception
*
* Custom Exception class
*
* @since 2011-05-23
* @category Library
* @package PdfGraph
* @author Nicola Asuni <info@tecnick.com>
* @copyright 2011-2026 Nicola Asuni - Tecnick.com LTD
* @license https://www.gnu.org/copyleft/lesser.html GNU-LGPL v3 (see LICENSE)
* @link https://github.com/tecnickcom/tc-lib-pdf-graph
*/
class Exception extends \Exception {}
+930
View File
@@ -0,0 +1,930 @@
<?php
declare(strict_types=1);
/**
* Gradient.php
*
* @since 2011-05-23
* @category Library
* @package PdfGraph
* @author Nicola Asuni <info@tecnick.com>
* @copyright 2011-2026 Nicola Asuni - Tecnick.com LTD
* @license https://www.gnu.org/copyleft/lesser.html GNU-LGPL v3 (see LICENSE)
* @link https://github.com/tecnickcom/tc-lib-pdf-graph
*
* This file is part of tc-lib-pdf-graph software library.
*/
namespace Com\Tecnick\Pdf\Graph;
use Com\Tecnick\Color\ColorModelType;
use Com\Tecnick\Pdf\Graph\Exception as GraphException;
/**
* Com\Tecnick\Pdf\Graph\Gradient
*
* @since 2011-05-23
* @category Library
* @package PdfGraph
* @author Nicola Asuni <info@tecnick.com>
* @copyright 2011-2026 Nicola Asuni - Tecnick.com LTD
* @license https://www.gnu.org/copyleft/lesser.html GNU-LGPL v3 (see LICENSE)
* @link https://github.com/tecnickcom/tc-lib-pdf-graph
*
* @phpstan-import-type GradientData from \Com\Tecnick\Pdf\Graph\Base
* @phpstan-import-type StyleDataOpt from \Com\Tecnick\Pdf\Graph\Base
*
* @SuppressWarnings("PHPMD.ExcessiveClassComplexity")
*/
abstract class Gradient extends \Com\Tecnick\Pdf\Graph\Raw
{
/**
* Returns the gradients array
*
* @return array<int, GradientData>
*/
public function getGradientsArray(): array
{
return $this->gradients;
}
/**
* Draws a basic rectangle
*
* @param float $posx Abscissa of upper-left corner.
* @param float $posy Ordinate of upper-left corner.
* @param float $width Width.
* @param float $height Height.
* @param string|PathPaintOp $mode Mode of rendering (or PathPaintOp enum case). @see getPathPaintOp()
* @param StyleDataOpt $style Style.
*
* @return string PDF command
*/
public function getBasicRect(
float $posx,
float $posy,
float $width,
float $height,
string|PathPaintOp $mode = 'S',
array $style = [],
): string {
return $this->getStyleCmd($style) . $this->getRawRect($posx, $posy, $width, $height, $mode);
}
/**
* Get a linear colour gradient command.
*
* @param float $posx Abscissa of the top left corner of the rectangle.
* @param float $posy Ordinate of the top left corner of the rectangle.
* @param float $width Width of the rectangle.
* @param float $height Height of the rectangle.
* @param string $colorstart Starting color.
* @param string $colorend Ending color.
* @param array<float> $coords Gradient vector (x1, y1, x2, y2).
*
* @return string PDF command
*
* @throws \Com\Tecnick\Pdf\Graph\Exception
*/
public function getLinearGradient(
float $posx,
float $posy,
float $width,
float $height,
string $colorstart,
string $colorend,
array $coords = [0, 0, 1, 0],
): string {
return (
$this->getStartTransform()
. $this->getClippingRect($posx, $posy, $width, $height)
. $this->getGradientTransform($posx, $posy, $width, $height)
. $this->getGradient(
2,
$coords,
[
[
'color' => $colorstart,
'exponent' => 1.0,
'offset' => 0.0,
'opacity' => 1.0,
],
[
'color' => $colorend,
'exponent' => 1.0,
'offset' => 1.0,
'opacity' => 1.0,
],
],
'',
false,
)
. $this->getStopTransform()
);
}
/**
* Get a radial colour gradient command.
*
* @param float $posx Abscissa of the top left corner of the rectangle.
* @param float $posy Ordinate of the top left corner of the rectangle.
* @param float $width Width of the rectangle.
* @param float $height Height of the rectangle.
* @param string $colorstart Starting color.
* @param string $colorend Ending color.
* @param array<float> $coords Array of the form (fx, fy, cx, cy, r) where
* (fx, fy) is the starting point of the
* gradient with $colorstart (which should be
* inside the circle), (cx, cy) is the center of the
* circle with $colorend, and r is the radius
* of the circle.
*
* @return string PDF command
*
* @throws \Com\Tecnick\Pdf\Graph\Exception
*/
public function getRadialGradient(
float $posx,
float $posy,
float $width,
float $height,
string $colorstart,
string $colorend,
array $coords = [0.5, 0.5, 0.5, 0.5, 1],
): string {
return (
$this->getStartTransform()
. $this->getClippingRect($posx, $posy, $width, $height)
. $this->getGradientTransform($posx, $posy, $width, $height)
. $this->getGradient(
3,
$coords,
[
[
'color' => $colorstart,
'exponent' => 1.0,
'offset' => 0.0,
'opacity' => 1.0,
],
[
'color' => $colorend,
'exponent' => 1.0,
'offset' => 1.0,
'opacity' => 1.0,
],
],
'',
false,
)
. $this->getStopTransform()
);
}
/**
* Rectangular clipping area.
*
* @param float $posx Abscissa of the top left corner of the rectangle.
* @param float $posy Ordinate of the top left corner of the rectangle.
* @param float $width Width of the rectangle.
* @param float $height Height of the rectangle.
* @param bool $eoclip If true, set clipping path using even-odd rule.
*/
public function getClippingRect(float $posx, float $posy, float $width, float $height, bool $eoclip = false): string
{
$mode = $eoclip ? 'CEO' : 'CNZ';
return $this->getRawRect($posx, $posy, $width, $height, $mode);
}
/**
* Returns the transformation command that maps a gradient onto a rectangular area.
*
* @param float $posx Abscissa of the top left corner of the rectangle.
* @param float $posy Ordinate of the top left corner of the rectangle.
* @param float $width Width of the rectangle.
* @param float $height Height of the rectangle.
*/
public function getGradientTransform(float $posx, float $posy, float $width, float $height): string
{
$ctm = [
$width * $this->kunit,
0,
0,
$height * $this->kunit,
$posx * $this->kunit,
($this->pageh - ($posy + $height)) * $this->kunit,
];
return $this->getTransformation($ctm);
}
/**
* Get a color gradient PDF command.
*
* @param int $type Type of gradient (Not all types are currently supported):
* 1 = Function-based shading; 2 = Axial shading; 3 = Radial
* shading; 4 = Free-form Gouraud-shaded triangle mesh; 5 =
* Lattice-form Gouraud-shaded triangle mesh; 6 = Coons
* patch mesh; 7 Tensor-product patch mesh
* @param array<float> $coords Array of coordinates.
* @param array<int, array{
* 'color': string,
* 'exponent'?: float,
* 'opacity'?: float,
* 'offset'?: float,
* }> $stops Array gradient color components:
* color = color; offset = (0 to 1)
* represents a location along the
* gradient vector; exponent =
* exponent of the exponential
* interpolation function (default
* = 1).
* @param string $bgcolor Background color
* @param bool $antialias Flag indicating whether to filter the
* shading function to prevent aliasing artifacts.
*
* @return string PDF command
*
* @throws \Com\Tecnick\Pdf\Graph\Exception
*/
public function getGradient(
int $type,
array $coords,
array $stops,
string $bgcolor,
bool $antialias = false,
): string {
if ($this->pdfa) {
return '';
}
if (!isset($stops[0]['color'])) {
throw new GraphException('Invalid gradient stops');
}
$model = $this->pdfColor->getColorObject($stops[0]['color']);
if (!$model instanceof \Com\Tecnick\Color\Model) {
throw new GraphException('Invalid color');
}
$colspace = match ($model->getTypeEnum()) {
ColorModelType::Cmyk => 'DeviceCMYK',
ColorModelType::Gray => 'DeviceGray',
default => 'DeviceRGB',
};
$ngr = 1 + \count($this->gradients);
$this->gradients[$ngr] = $this->getGradientStops([
'antialias' => $antialias,
'background' => $this->pdfColor->getColorObject($bgcolor),
'colors' => [],
'colspace' => $colspace,
'coords' => $coords,
'id' => 0,
'pattern' => 0,
'stream' => '',
'transparency' => false,
'type' => $type,
], $stops);
$out = '';
if ($this->gradients[$ngr]['transparency']) {
// paint luminosity gradient
$out .= '/TGS' . $ngr . ' gs' . "\n";
}
// paint the gradient
$out .= '/Sh' . $ngr . ' sh' . "\n";
return $out;
}
/**
* Returns the last gradient ID to be used with XObjects.
*
* @return ?int
*/
public function getLastGradientID(): ?int
{
return \array_key_last($this->gradients);
}
/**
* Process the gradient stops.
*
* @param GradientData $grad Array containing gradient info
* @param array<int, array{
* 'color': string,
* 'exponent'?: float,
* 'opacity'?: float,
* 'offset'?: float,
* }> $stops Array gradient color components:
* color = color;
* offset = (0 to 1) represents a location along the gradient vector;
* exponent = exponent of the exponential interpolation function (default = 1).
*
* @return GradientData Gradient array.
*/
protected function getGradientStops(array $grad, array $stops): array
{
$num_stops = \count($stops);
$last_stop_id = $num_stops - 1;
foreach ($stops as $key => $stop) {
$grad['colors'][$key] = ['color' => $stop['color']];
$grad['colors'][$key]['exponent'] = 1.0;
if (array_key_exists('exponent', $stop)) {
// exponent for the interpolation function
$grad['colors'][$key]['exponent'] = $stop['exponent'];
}
$grad['colors'][$key]['opacity'] = 1.0;
if (array_key_exists('opacity', $stop)) {
$grad['colors'][$key]['opacity'] = $stop['opacity'];
$grad['transparency'] = $grad['transparency'] || $stop['opacity'] < 1.0;
}
// offset represents a location along the gradient vector
$offset = array_key_exists('offset', $stop) ? $stop['offset'] : null;
if ($offset === null && $key === 0) {
$offset = 0.0;
} elseif ($offset === null && $key === $last_stop_id) {
$offset = 1.0;
} elseif ($offset === null && $key > 0 && array_key_exists('offset', $grad['colors'][$key - 1] ?? [])) {
$prevoffset = $grad['colors'][$key - 1]['offset'] ?? 0.0;
$offsetstep = (1.0 - $prevoffset) / ($num_stops - $key);
$offset = $prevoffset + $offsetstep;
}
if ($offset !== null) {
$grad['colors'][$key]['offset'] = $offset;
}
}
return $grad;
}
/**
* Paints a coons patch mesh.
*
* @param float $posx Abscissa of the top left corner of the rectangle.
* @param float $posy Ordinate of the top left corner of the rectangle.
* @param float $width Width of the rectangle.
* @param float $height Height of the rectangle.
* @param string $colll Lower-Left corner color.
* @param string $collr Lower-Right corner color.
* @param string $colur Upper-Right corner color.
* @param string $colul Upper-Left corner color.
* @param array<float> $coords Coordinates
* @param float $coords_min Minimum value used by the coordinates.
* If a coordinate's value is smaller
* than this it will be cut to
* coords_min.
* @param float $coords_max Maximum value used by the coordinates.
* If a coordinate's value is greater
* than this it will be cut to
* coords_max.
* @param bool $antialias Flag indicating whether to filter the
* shading function to prevent aliasing artifacts.
*
* @return string PDF command
*
* @SuppressWarnings("PHPMD.ExcessiveParameterList")
* @SuppressWarnings("PHPMD.ExcessiveMethodLength")
*
* @throws \Com\Tecnick\Pdf\Graph\Exception
*/
public function getCoonsPatchMeshWithCoords(
float $posx,
float $posy,
float $width,
float $height,
string $colll = 'yellow',
string $collr = 'blue',
string $colur = 'green',
string $colul = 'red',
array $coords = [
0.00,
0.00,
0.33,
0.00,
0.67,
0.00,
1.00,
0.00,
1.00,
0.33,
1.00,
0.67,
1.00,
1.00,
0.67,
1.00,
0.33,
1.00,
0.00,
1.00,
0.00,
0.67,
0.00,
0.33,
],
float $coords_min = 0.0,
float $coords_max = 1.0,
bool $antialias = false,
): string {
if ($this->pdfa) {
return '';
}
// simple array -> convert to multi patch array
$patch_array = [
0 => [
'f' => 0,
'points' => $coords,
'colors' => [
0 => [
'red' => 1,
'green' => 1,
'blue' => 0,
'alpha' => 1,
],
1 => [
'red' => 0,
'green' => 0,
'blue' => 1,
'alpha' => 1,
],
2 => [
'red' => 0,
'green' => 1,
'blue' => 0,
'alpha' => 1,
],
3 => [
'red' => 1,
'green' => 0,
'blue' => 0,
'alpha' => 1,
],
],
],
];
$colllobj = $this->pdfColor->getColorObject($colll);
if (!$colllobj instanceof \Com\Tecnick\Color\Model) {
throw new GraphException('Invalid Lower-Left corner color');
}
$patch_array[0]['colors'][0] = $colllobj->toRgbArray();
$collrobj = $this->pdfColor->getColorObject($collr);
if (!$collrobj instanceof \Com\Tecnick\Color\Model) {
throw new GraphException('Invalid Lower-Right corner color');
}
$patch_array[0]['colors'][1] = $collrobj->toRgbArray();
$colurobj = $this->pdfColor->getColorObject($colur);
if (!$colurobj instanceof \Com\Tecnick\Color\Model) {
throw new GraphException('Invalid Upper-Right corner color');
}
$patch_array[0]['colors'][2] = $colurobj->toRgbArray();
$colulobj = $this->pdfColor->getColorObject($colul);
if (!$colulobj instanceof \Com\Tecnick\Color\Model) {
throw new GraphException('Invalid Upper-Left corner color');
}
$patch_array[0]['colors'][3] = $colulobj->toRgbArray();
return $this->getCoonsPatchMesh(
$posx,
$posy,
$width,
$height,
$patch_array,
$coords_min,
$coords_max,
$antialias,
);
}
/**
* Paints a coons patch mesh.
*
* @param float $posx Abscissa of the top left corner of the rectangle.
* @param float $posy Ordinate of the top left corner of the rectangle.
* @param float $width Width of the rectangle.
* @param float $height Height of the rectangle.
* @param array<array{
* 'f': int,
* 'points': array<float>,
* 'colors': array<int, array<string, float>>,
* }> $patch_array For one patch mesh:
* array(float x1,
* float y1, ....
* float x12, float
* y12): 12 pairs of
* coordinates
* (normally from 0 to
* 1) which specify
* the Bezier control
* points that define
* the patch. First
* pair is the lower
* left edge point,
* next is its right
* control point
* (control point 2).
* Then the other
* points are defined
* in the order:
* control point 1,
* edge point, control
* point 2 going
* counter-clockwise
* around the patch.
* Last (x12, y12) is
* the first edge
* point's left
* control point
* (control point 1).
* For two or more
* patch meshes:
* array[number of
* patches] - arrays
* with the following
* keys for each
* patch: f: where to
* put that patch (0 =
* first patch, 1, 2,
* 3 = right, top and
* left) points: 12
* pairs of
* coordinates of the
* Bezier control
* points as above for
* the first patch, 8
* pairs of
* coordinates for the
* following patches,
* ignoring the
* coordinates already
* defined by the
* precedent patch
* colors: must be 4
* colors for the
* first patch, 2
* colors for the
* following patches
* @param float $coords_min Minimum value used by the coordinates.
* If a coordinate's value is smaller
* than this it will be cut to
* coords_min.
* @param float $coords_max Maximum value used by the coordinates.
* If a coordinate's value is greater
* than this it will be cut to
* coords_max.
* @param bool $antialias Flag indicating whether to filter the
* shading function to prevent aliasing artifacts.
*
* @return string PDF command
*
* @SuppressWarnings("PHPMD.ExcessiveParameterList")
* @SuppressWarnings("PHPMD.ExcessiveMethodLength")
* @SuppressWarnings("PHPMD.CyclomaticComplexity")
*
* @throws \Com\Tecnick\Pdf\Graph\Exception
*/
public function getCoonsPatchMesh(
float $posx,
float $posy,
float $width,
float $height,
array $patch_array = [],
float $coords_min = 0.0,
float $coords_max = 1.0,
bool $antialias = false,
): string {
if ($this->pdfa) {
return '';
}
if ($coords_max <= $coords_min) {
throw new GraphException('coords_max must be greater than coords_min');
}
$ngr = 1 + \count($this->gradients);
$this->gradients[$ngr] = [
'antialias' => $antialias,
'colors' => [],
'background' => null,
'colspace' => 'DeviceRGB',
'coords' => [],
'id' => 0,
'pattern' => 0,
'stream' => '',
'transparency' => false,
'type' => 6, //coons patch mesh
];
$bpcd = 65_535; // 16 bits per coordinate
foreach ($patch_array as $par) {
$this->gradients[$ngr]['stream'] .= \chr($par['f'] & 0xFF); // start with the edge flag as 8 bit
foreach ($par['points'] as $point) {
// each point as 16 bit
$point = \floor(\max(0, \min($bpcd, (($point - $coords_min) / ($coords_max - $coords_min)) * $bpcd)));
$this->gradients[$ngr]['stream'] .=
\chr((int) \floor($point / 256) & 0xFF) . \chr((int) \floor($point % 256) & 0xFF);
}
foreach ($par['colors'] as $color) {
// each color component as 8 bit
$red = $color['red'] ?? 0.0;
$green = $color['green'] ?? 0.0;
$blue = $color['blue'] ?? 0.0;
$this->gradients[$ngr]['stream'] .=
\chr((int) \floor($red * 255) & 0xFF)
. \chr((int) \floor($green * 255) & 0xFF)
. \chr((int) \floor($blue * 255) & 0xFF);
}
}
return (
$this->getStartTransform()
. $this->getClippingRect($posx, $posy, $width, $height)
. $this->getGradientTransform($posx, $posy, $width, $height)
. '/Sh'
. $ngr
. ' sh'
. "\n"
. $this->getStopTransform()
);
}
/**
* Paints registration bars with color transitions
*
* @param float $posx Abscissa of the top left corner of the rectangle.
* @param float $posy Ordinate of the top left corner of the rectangle.
* @param float $width Width of the rectangle.
* @param float $height Height of the rectangle.
* @param bool $vertical If true prints bar vertically, otherwise horizontally.
* @param array<int, array<string>> $colors Array of colors to print,
* each entry is a color
* string or an array of two
* transition colors;
*
* @return string PDF command
*
* @SuppressWarnings("PHPMD.CyclomaticComplexity")
*
* @throws \Com\Tecnick\Pdf\Graph\Exception
*/
public function getColorRegistrationBar(
float $posx,
float $posy,
float $width,
float $height,
bool $vertical = false,
array $colors = [
// GRAY : black to white
['g(0%)', 'g(100%)'],
// RGB : red to white
['rgb(100%,0%,0%)', 'rgb(100%,100%,100%)'],
// RGB : green to white
['rgb(0%,100%,0%)', 'rgb(100%,100%,100%)'],
// RGB : blue to white
['rgb(0%,0%,100%)', 'rgb(100%,100%,100%)'],
// CMYK : cyan to white
['cmyk(100%,0%,0%,0%)', 'cmyk(0%,0%,0%,0%)'],
// CMYK : magenta to white
['cmyk(0%,100%,0%,0%)', 'cmyk(0%,0%,0%,0%)'],
// CMYK : yellow to white
['cmyk(0%,0%,100%,0%)', 'cmyk(0%,0%,0%,0%)'],
// CMYK : black to white
['cmyk(0%,0%,0%,100%)', 'cmyk(0%,0%,0%,0%)'],
],
): string {
$numbars = \count($colors);
if ($numbars <= 0) {
return '';
}
// set bar measures
// default (non-vertical)
$coords = [0, 0, 1, 0];
$wbr = $width;
$hbr = $height / $numbars;
$xdt = 0.0;
$ydt = $hbr;
if ($vertical) {
$coords = [0, 1, 0, 0]; // coordinates for gradient transition
$wbr = $width / $numbars; // bar width
$hbr = $height; // bar height
$xdt = $wbr; // delta x
$ydt = 0.0; // delta y
}
$xbr = $posx;
$ybr = $posy;
$out = '';
foreach ($colors as $color) {
if ($color !== [] && isset($color[0]) && $color[0] !== '') {
if (!isset($color[1])) {
$color[1] = $color[0];
}
if ($color[0] === $color[1] || $this->pdfa) {
// colored rectangle
$out .= $this->getStartTransform();
$colobj = $this->pdfColor->getColorObject($color[0]);
if ($colobj instanceof \Com\Tecnick\Color\Model) {
$out .= $colobj->getPdfColor();
}
$out .= $this->getBasicRect($xbr, $ybr, $wbr, $hbr, 'F') . $this->getStopTransform();
} else {
// color gradient
$out .= $this->getLinearGradient($xbr, $ybr, $wbr, $hbr, $color[0], $color[1], $coords);
}
}
$xbr += $xdt;
$ybr += $ydt;
}
return $out;
}
/**
* Get a crop-mark.
*
* @param float $posx Abscissa of the crop-mark center.
* @param float $posy Ordinate of the crop-mark center.
* @param float $width Width of the crop-mark.
* @param float $height Height of the crop-mark.
* @param string $type Type of crop mark - one symbol per type:
* T = TOP, B = BOTTOM, L = LEFT, R = RIGHT
* @param StyleDataOpt $style Line style to apply.
*
* @return string PDF command
*/
public function getCropMark(
float $posx,
float $posy,
float $width,
float $height,
string $type = 'TBLR',
array $style = [],
): string {
$crops = \array_unique(\str_split(\strtoupper($type), 1));
$space_ratio = 4;
$dhw = $width / $space_ratio; // horizontal space to leave before the intersection point
$dvh = $height / $space_ratio; // vertical space to leave before the intersection point
$out = '';
foreach ($crops as $crop) {
$draw = true;
$posx1 = $posx;
$posy1 = $posy;
$posx2 = $posx;
$posy2 = $posy;
switch ($crop) {
case 'T':
$posx1 = $posx;
$posy1 = $posy - $height;
$posx2 = $posx;
$posy2 = $posy - $dvh;
break;
case 'B':
$posx1 = $posx;
$posy1 = $posy + $dvh;
$posx2 = $posx;
$posy2 = $posy + $height;
break;
case 'L':
$posx1 = $posx - $width;
$posy1 = $posy;
$posx2 = $posx - $dhw;
$posy2 = $posy;
break;
case 'R':
$posx1 = $posx + $dhw;
$posy1 = $posy;
$posx2 = $posx + $width;
$posy2 = $posy;
break;
default:
$draw = false;
break;
}
if (!$draw) {
continue;
}
$out .= $this->getRawPoint($posx1, $posy1) . $this->getRawLine($posx2, $posy2) . $this->getPathPaintOp('S');
}
if ($out === '') {
return '';
}
return $this->getStartTransform() . $this->getStyleCmd($style) . $out . $this->getStopTransform();
}
/**
* Get overprint mode for stroking (OP) and non-stroking (op) painting operations.
* (Check the "Entries in a Graphics State Parameter Dictionary" on PDF 32000-1:2008).
*
* @param bool $stroking If true apply overprint for stroking operations.
* @param bool|null $nonstroking If true apply overprint for painting operations other than stroking.
* @param int $mode Overprint mode:
* 0 = each source
* colour
* component value
* replaces the
* value
* previously
* painted for the
* corresponding
* device
* colorant; 1 = a
* tint value of
* 0.0 for a
* source colour
* component shall
* leave the
* corresponding
* component of
* the previously
* painted colour
* unchanged.
*
* @return string PDF command
*/
public function getOverprint(bool $stroking = true, ?bool $nonstroking = null, int $mode = 0): string
{
if ($nonstroking === null) {
$nonstroking = $stroking;
}
return $this->getExtGState([
'OP' => $stroking,
'op' => $nonstroking,
'OPM' => \max(0, \min(1, $mode)),
]);
}
/**
* Set alpha for stroking (CA) and non-stroking (ca) operations.
*
* @param float $stroking Alpha value for stroking operations:
* real value from 0 (transparent) to 1 (opaque).
* @param string|BlendMode $bmv Blend mode (or BlendMode enum case), one of the following:
* Normal, Multiply, Screen,
* Overlay, Darken, Lighten,
* ColorDodge, ColorBurn, HardLight,
* SoftLight, Difference, Exclusion,
* Hue, Saturation, Color,
* Luminosity.
* @param float|string $nonstroking Alpha value for non-stroking operations:
* real value from 0 (transparent) to 1
* (opaque).
* @param bool $ais Alpha-Is-Shape flag: if true the soft-mask
* alpha values are interpreted as shape
* (passed through to the /AIS ExtGState key).
*
* @return string PDF command
*/
public function getAlpha(
float $stroking = 1,
string|BlendMode $bmv = 'Normal',
float|string $nonstroking = '',
bool $ais = false,
): string {
if ($nonstroking === '') {
$nonstroking = $stroking;
}
$bmv = BlendMode::fromLoose($bmv)->value;
if (\is_string($nonstroking)) {
$nonstroking = \is_numeric($nonstroking) ? (float) $nonstroking : $stroking;
}
return $this->getExtGState([
'CA' => $stroking,
'ca' => $nonstroking,
'BM' => '/' . $bmv,
'AIS' => $ais,
]);
}
}
+100
View File
@@ -0,0 +1,100 @@
<?php
declare(strict_types=1);
/**
* PathPaintOp.php
*
* @since 2026-07-17
* @category Library
* @package PdfGraph
* @author Nicola Asuni <info@tecnick.com>
* @copyright 2011-2026 Nicola Asuni - Tecnick.com LTD
* @license https://www.gnu.org/copyleft/lesser.html GNU-LGPL v3 (see LICENSE)
* @link https://github.com/tecnickcom/tc-lib-pdf-graph
*
* This file is part of tc-lib-pdf-graph software library.
*/
namespace Com\Tecnick\Pdf\Graph;
/**
* Com\Tecnick\Pdf\Graph\PathPaintOp
*
* Backed enum for the PDF path-painting operators (PDF 32000-1:2008 - 8.5.3).
* The backing value of each case is the canonical operator produced by
* Style::getPathPaintOp(); its many input aliases collapse onto these cases via
* fromLoose().
*
* @since 2026-07-17
* @category Library
* @package PdfGraph
* @author Nicola Asuni <info@tecnick.com>
* @copyright 2011-2026 Nicola Asuni - Tecnick.com LTD
* @license https://www.gnu.org/copyleft/lesser.html GNU-LGPL v3 (see LICENSE)
* @link https://github.com/tecnickcom/tc-lib-pdf-graph
*/
enum PathPaintOp: string
{
case Stroke = 'S';
case CloseStroke = 's';
case Fill = 'f';
case CloseFill = 'h f';
case FillEvenOdd = 'f*';
case CloseFillEvenOdd = 'h f*';
case FillStroke = 'B';
case FillStrokeEvenOdd = 'B*';
case CloseFillStroke = 'b';
case CloseFillStrokeEvenOdd = 'b*';
case Clip = 'W n';
case ClipEvenOdd = 'W* n';
case Close = 'h';
case NoOp = 'n';
/**
* Resolve a loose path paint mode to the matching canonical operator case.
*
* Accepts an enum instance (returned unchanged) or any of the input aliases
* accepted by Style::getPathPaintOp() (case sensitive). Unknown values fall
* back to Stroke, matching the default of Style::getPathPaintOp().
*
* @param string|self $value Path paint mode or enum case.
*/
public static function fromLoose(string|self $value): self
{
if ($value instanceof self) {
return $value;
}
return match ($value) {
'S', 'D' => self::Stroke,
's', 'h S', 'd' => self::CloseStroke,
'f', 'F' => self::Fill,
'h f' => self::CloseFill,
'f*', 'F*' => self::FillEvenOdd,
'h f*' => self::CloseFillEvenOdd,
'B', 'FD', 'DF' => self::FillStroke,
'B*', 'F*D', 'DF*' => self::FillStrokeEvenOdd,
'b', 'h B', 'fd', 'df' => self::CloseFillStroke,
'b*', 'h B*', 'f*d', 'df*' => self::CloseFillStrokeEvenOdd,
'W n', 'CNZ' => self::Clip,
'W* n', 'CEO' => self::ClipEvenOdd,
'h' => self::Close,
'n' => self::NoOp,
default => self::Stroke,
};
}
}
+422
View File
@@ -0,0 +1,422 @@
<?php
declare(strict_types=1);
/**
* Raw.php
*
* @since 2011-05-23
* @category Library
* @package PdfGraph
* @author Nicola Asuni <info@tecnick.com>
* @copyright 2011-2026 Nicola Asuni - Tecnick.com LTD
* @license https://www.gnu.org/copyleft/lesser.html GNU-LGPL v3 (see LICENSE)
* @link https://github.com/tecnickcom/tc-lib-pdf-graph
*
* This file is part of tc-lib-pdf-graph software library.
*/
namespace Com\Tecnick\Pdf\Graph;
/**
* Com\Tecnick\Pdf\Graph\Raw
*
* @since 2011-05-23
* @category Library
* @package PdfGraph
* @author Nicola Asuni <info@tecnick.com>
* @copyright 2011-2026 Nicola Asuni - Tecnick.com LTD
* @license https://www.gnu.org/copyleft/lesser.html GNU-LGPL v3 (see LICENSE)
* @link https://github.com/tecnickcom/tc-lib-pdf-graph
*/
abstract class Raw extends \Com\Tecnick\Pdf\Graph\Transform
{
/**
* Begin a new subpath by moving the current point to the specified coordinates,
* omitting any connecting line segment.
*
* @param float $posx Abscissa of point.
* @param float $posy Ordinate of point.
*
* @return string PDF command
*/
public function getRawPoint(float $posx, float $posy): string
{
return \sprintf('%F %F m' . "\n", $posx * $this->kunit, ($this->pageh - $posy) * $this->kunit);
}
/**
* Append a straight line segment from the current point to the specified one.
* The new current point shall be the one specified.
*
* @param float $posx Abscissa of end point.
* @param float $posy Ordinate of end point.
*
* @return string PDF command
*/
public function getRawLine(float $posx, float $posy): string
{
return \sprintf('%F %F l' . "\n", $posx * $this->kunit, ($this->pageh - $posy) * $this->kunit);
}
/**
* Append a rectangle to the current path as a complete subpath,
* with lower-left corner in the specified point and dimensions width and height in user units.
*
* @param float $posx Abscissa of upper-left corner.
* @param float $posy Ordinate of upper-left corner.
* @param float $width Width.
* @param float $height Height.
* @param string|PathPaintOp $mode Mode of rendering (or PathPaintOp enum case). @see getPathPaintOp()
*
* @return string PDF command
*/
public function getRawRect(
float $posx,
float $posy,
float $width,
float $height,
string|PathPaintOp $mode = '',
): string {
return \sprintf(
'%F %F %F %F re' . "\n" . $this->getPathPaintOp($mode, ''),
$posx * $this->kunit,
($this->pageh - $posy) * $this->kunit,
$width * $this->kunit,
-$height * $this->kunit,
);
}
/**
* Append a cubic Bezier curve to the current path.
* The curve shall extend from the current point to the point (posx3, posy3),
* using (posx1, posy1) and (posx2, posy2) as the Bezier control points.
* The new current point shall be (posx3, posy3).
*
* @param float $posx1 Abscissa of control point 1.
* @param float $posy1 Ordinate of control point 1.
* @param float $posx2 Abscissa of control point 2.
* @param float $posy2 Ordinate of control point 2.
* @param float $posx3 Abscissa of end point.
* @param float $posy3 Ordinate of end point.
*
* @return string PDF command
*/
public function getRawCurve(
float $posx1,
float $posy1,
float $posx2,
float $posy2,
float $posx3,
float $posy3,
): string {
return \sprintf(
'%F %F %F %F %F %F c' . "\n",
$posx1 * $this->kunit,
($this->pageh - $posy1) * $this->kunit,
$posx2 * $this->kunit,
($this->pageh - $posy2) * $this->kunit,
$posx3 * $this->kunit,
($this->pageh - $posy3) * $this->kunit,
);
}
/**
* Append a cubic Bezier curve to the current path.
* The curve shall extend from the current point to the point (posx3, posy3),
* using the current point and (posx2, posy2) as the Bezier control points.
* The new current point shall be (posx3, posy3).
*
* @param float $posx2 Abscissa of control point 2.
* @param float $posy2 Ordinate of control point 2.
* @param float $posx3 Abscissa of end point.
* @param float $posy3 Ordinate of end point.
*
* @return string PDF command
*/
public function getRawCurveV(float $posx2, float $posy2, float $posx3, float $posy3): string
{
return \sprintf(
'%F %F %F %F v' . "\n",
$posx2 * $this->kunit,
($this->pageh - $posy2) * $this->kunit,
$posx3 * $this->kunit,
($this->pageh - $posy3) * $this->kunit,
);
}
/**
* Append a cubic Bezier curve to the current path.
* The curve shall extend from the current point to the point (posx3, posy3),
* using (posx1, posy1) and (posx3, posy3) as the Bezier control points.
* The new current point shall be (posx3, posy3).
*
* @param float $posx1 Abscissa of control point 1.
* @param float $posy1 Ordinate of control point 1.
* @param float $posx3 Abscissa of end point.
* @param float $posy3 Ordinate of end point.
*
* @return string PDF command
*/
public function getRawCurveY(float $posx1, float $posy1, float $posx3, float $posy3): string
{
return \sprintf(
'%F %F %F %F y' . "\n",
$posx1 * $this->kunit,
($this->pageh - $posy1) * $this->kunit,
$posx3 * $this->kunit,
($this->pageh - $posy3) * $this->kunit,
);
}
/**
* Initialize angles for the elliptical arc.
*
* @param float $ags Angle in degrees at which starting drawing.
* @param float $agf Angle in degrees at which stop drawing.
* @param float $rdv Vertical radius (if = 0 then it is a circle).
* @param float $rdh Horizontal radius.
* @param bool $ccw If true draws in counter-clockwise direction.
* @param bool $svg If true the angles are in svg mode (already calculated).
*/
protected function setRawEllipticalArcAngles(
float &$ags,
float &$agf,
float $rdv,
float $rdh,
bool $ccw,
bool $svg,
): void {
$ags = $this->degToRad($ags);
$agf = $this->degToRad($agf);
if (!$svg) {
$ags = \atan2(\sin($ags) / $rdv, \cos($ags) / $rdh);
$agf = \atan2(\sin($agf) / $rdv, \cos($agf) / $rdh);
}
if ($ags < 0) {
$ags += 2 * self::MPI;
}
if ($agf < 0) {
$agf += 2 * self::MPI;
}
if ($ccw && $ags > $agf) {
// reverse rotation
$ags -= 2 * self::MPI;
} elseif (!$ccw && $ags < $agf) {
// reverse rotation
$agf -= 2 * self::MPI;
}
}
/**
* Append an elliptical arc to the current path.
* An ellipse is formed from n Bezier curves.
*
* @param float $posxc Abscissa of center point.
* @param float $posyc Ordinate of center point.
* @param float $rdh Horizontal radius.
* @param float $rdv Vertical radius (if = 0 then it is a circle).
* @param float $posxang Angle between the X-axis and the major axis of the ellipse.
* @param float $angs Angle in degrees at which starting drawing.
* @param float $angf Angle in degrees at which stop drawing.
* @param bool $pie If true do not mark the border point (used to draw pie sectors).
* @param float $ncv Number of curves used to draw a 90 degrees portion of ellipse.
* @param bool $startpoint If true output a starting point.
* @param bool $ccw If true draws in counter-clockwise direction.
* @param bool $svg If true the angles are in svg mode (already calculated).
* @param array<float> $bbox If provided, it will be filled with the bounding box coordinates
* (x min, y min, x max, y max). The box is derived from the Bezier
* control points, so (by the convex-hull property) it is guaranteed
* to contain the arc but may be slightly larger than its tight bounds.
*
* @return string PDF command
*
* @SuppressWarnings("PHPMD.ExcessiveParameterList")
* @SuppressWarnings("PHPMD.ExcessiveMethodLength")
*/
public function getRawEllipticalArc(
float $posxc,
float $posyc,
float $rdh,
float $rdv,
float $posxang = 0.0,
float $angs = 0.0,
float $angf = 360.0,
bool $pie = false,
float $ncv = 2,
bool $startpoint = true,
bool $ccw = true,
bool $svg = false,
array &$bbox = [],
): string {
$out = '';
if ($rdh <= 0 || $rdv < 0) {
return '';
}
if ($rdv === 0.0) {
// a zero vertical radius means a circle: use the horizontal radius
// (also avoids a division by zero when computing the arc angles)
$rdv = $rdh;
}
$bbox = [PHP_INT_MAX, PHP_INT_MAX, PHP_INT_MIN, PHP_INT_MIN];
if ($pie) {
$out .= $this->getRawPoint($posxc, $posyc); // center of the arc
}
$posxang = $this->degToRad($posxang);
$ags = $angs;
$agf = $angf;
$this->setRawEllipticalArcAngles($ags, $agf, $rdv, $rdh, $ccw, $svg);
$total_angle = $agf - $ags;
$ncv = \max(2, $ncv);
$ncv *= (2 * \abs($total_angle)) / self::MPI; // total arcs to draw
$ncv = (int) (\round($ncv) + 1);
$arcang = $total_angle / $ncv; // angle of each arc
$pageh = $this->pageh;
$posx0 = $posxc; // X center point in PDF coordinates
$posy0 = $pageh - $posyc; // Y center point in PDF coordinates
$ang = $ags; // starting angle
$alpha = \sin($arcang) * ((\sqrt(4 + (3 * (\tan($arcang / 2) ** 2))) - 1) / 3);
$cos_xang = \cos($posxang);
$sin_xang = \sin($posxang);
// first arc point and its Bezier control point
[$px1, $py1, $qx1, $qy1] = $this->getRawEllipticalArcPoint(
$posx0,
$posy0,
$rdh,
$rdv,
$cos_xang,
$sin_xang,
$alpha,
$ang,
);
if ($pie) {
$out .= $this->getRawLine($px1, $pageh - $py1); // line from center to arc starting point
} elseif ($startpoint) {
$out .= $this->getRawPoint($px1, $pageh - $py1); // arc starting point
}
// draw arcs
for ($idx = 1; $idx <= $ncv; ++$idx) {
$ang = $ags + ($idx * $arcang); // starting angle
if ($idx === $ncv) {
$ang = $agf;
}
// second arc point and its Bezier control point
[$px2, $py2, $qx2, $qy2] = $this->getRawEllipticalArcPoint(
$posx0,
$posy0,
$rdh,
$rdv,
$cos_xang,
$sin_xang,
$alpha,
$ang,
);
// draw arc
$cx1 = $px1 + $qx1;
$cy1 = $pageh - ($py1 + $qy1);
$cx2 = $px2 - $qx2;
$cy2 = $pageh - ($py2 - $qy2);
$cx3 = $px2;
$cy3 = $pageh - $py2;
$out .= $this->getRawCurve($cx1, $cy1, $cx2, $cy2, $cx3, $cy3);
// get bounding box coordinates
$bbox = [
\min($bbox[0], $cx1, $cx2, $cx3),
\min($bbox[1], $cy1, $cy2, $cy3),
\max($bbox[2], $cx1, $cx2, $cx3),
\max($bbox[3], $cy1, $cy2, $cy3),
];
// move to next point
$px1 = $px2;
$py1 = $py2;
$qx1 = $qx2;
$qy1 = $qy2;
}
if ($pie) {
$out .= $this->getRawLine($posxc, $posyc);
// get bounding box coordinates
$bbox = [
\min($bbox[0], $posxc),
\min($bbox[1], $posyc),
\max($bbox[2], $posxc),
\max($bbox[3], $posyc),
];
}
return $out;
}
/**
* Computes an elliptical arc point and its Bezier control-point offset.
*
* @param float $posx0 X center point in PDF coordinates.
* @param float $posy0 Y center point in PDF coordinates.
* @param float $rdh Horizontal radius.
* @param float $rdv Vertical radius.
* @param float $cosXang Cosine of the ellipse orientation angle.
* @param float $sinXang Sine of the ellipse orientation angle.
* @param float $alpha Bezier control-point scaling factor.
* @param float $ang Arc angle in radians.
*
* @return array{float, float, float, float} Point and control-point offset: [px, py, qx, qy].
*
* @SuppressWarnings("PHPMD.ExcessiveParameterList")
*/
private function getRawEllipticalArcPoint(
float $posx0,
float $posy0,
float $rdh,
float $rdv,
float $cosXang,
float $sinXang,
float $alpha,
float $ang,
): array {
$cosAng = \cos($ang);
$sinAng = \sin($ang);
return [
$posx0 + ($rdh * $cosXang * $cosAng) - ($rdv * $sinXang * $sinAng),
$posy0 + ($rdh * $sinXang * $cosAng) + ($rdv * $cosXang * $sinAng),
$alpha * ((-$rdh * $cosXang * $sinAng) - ($rdv * $sinXang * $cosAng)),
$alpha * ((-$rdh * $sinXang * $sinAng) + ($rdv * $cosXang * $cosAng)),
];
}
/**
* Returns the angle in radians between two vectors with the same origin point.
* Angles are counted counter-clock wise.
*
* @param float $posx1 X coordinate of first vector point.
* @param float $posy1 Y coordinate of first vector point.
* @param float $posx2 X coordinate of second vector point.
* @param float $posy2 Y coordinate of second vector point.
*
* @return float Angle in radians
*/
public function getVectorsAngle(float $posx1, float $posy1, float $posx2, float $posy2): float
{
$dprod = ($posx1 * $posx2) + ($posy1 * $posy2);
$dist1 = \sqrt(($posx1 * $posx1) + ($posy1 * $posy1));
$dist2 = \sqrt(($posx2 * $posx2) + ($posy2 * $posy2));
$distprod = $dist1 * $dist2;
if ($distprod === 0.0) {
return 0;
}
$angle = \acos(\min(1, \max(-1, $dprod / $distprod)));
if ((($posx1 * $posy2) - ($posx2 * $posy1)) < 0) {
$angle *= -1;
}
return $angle;
}
}
+594
View File
@@ -0,0 +1,594 @@
<?php
declare(strict_types=1);
/**
* Style.php
*
* @since 2011-05-23
* @category Library
* @package PdfGraph
* @author Nicola Asuni <info@tecnick.com>
* @copyright 2011-2026 Nicola Asuni - Tecnick.com LTD
* @license https://www.gnu.org/copyleft/lesser.html GNU-LGPL v3 (see LICENSE)
* @link https://github.com/tecnickcom/tc-lib-pdf-graph
*
* This file is part of tc-lib-pdf-graph software library.
*/
namespace Com\Tecnick\Pdf\Graph;
use Com\Tecnick\Pdf\Graph\Exception as GraphException;
/**
* Com\Tecnick\Pdf\Graph\Style
*
* @since 2011-05-23
* @category Library
* @package PdfGraph
* @author Nicola Asuni <info@tecnick.com>
* @copyright 2011-2026 Nicola Asuni - Tecnick.com LTD
* @license https://www.gnu.org/copyleft/lesser.html GNU-LGPL v3 (see LICENSE)
* @link https://github.com/tecnickcom/tc-lib-pdf-graph
*
* @phpstan-import-type StyleDataOpt from \Com\Tecnick\Pdf\Graph\Base
*
* @SuppressWarnings("PHPMD.ExcessiveClassComplexity")
*/
abstract class Style extends \Com\Tecnick\Pdf\Graph\Base
{
/**
* Array of restore points (style ID).
*
* @var array<int>
*/
protected array $stylemark = [0];
/**
* Map values for lineCap.
*
* @var array<int|string, int>
*/
protected const LINECAPMAP = [
0 => 0,
1 => 1,
2 => 2,
'butt' => 0,
'round' => 1,
'square' => 2,
];
/**
* Map values for lineJoin.
*
* @var array<int|string, int>
*/
protected const LINEJOINMAP = [
0 => 0,
1 => 1,
2 => 2,
'miter' => 0,
'round' => 1,
'bevel' => 2,
];
/**
* Map path paint operators.
*
* @var array<string, string>
*/
protected const PPOPMAP = [
'S' => 'S',
'D' => 'S',
's' => 's',
'h S' => 's',
'd' => 's',
'f' => 'f',
'F' => 'f',
'h f' => 'h f',
'f*' => 'f*',
'F*' => 'f*',
'h f*' => 'h f*',
'B' => 'B',
'FD' => 'B',
'DF' => 'B',
'B*' => 'B*',
'F*D' => 'B*',
'DF*' => 'B*',
'b' => 'b',
'h B' => 'b',
'fd' => 'b',
'df' => 'b',
'b*' => 'b*',
'h B*' => 'b*',
'f*d' => 'b*',
'df*' => 'b*',
'W n' => 'W n',
'CNZ' => 'W n',
'W* n' => 'W* n',
'CEO' => 'W* n',
'h' => 'h',
'n' => 'n',
];
/**
* Filling modes.
*
* @var array<string, bool>
*/
protected const MODEFILLING = [
'f' => true,
'f*' => true,
'B' => true,
'B*' => true,
'b' => true,
'b*' => true,
];
/**
* Stroking Modes.
*
* @var array<string, bool>
*/
protected const MODESTROKING = [
'S' => true,
's' => true,
'B' => true,
'B*' => true,
'b' => true,
'b*' => true,
];
/**
* Closing Modes.
*
* @var array<string, bool>
*/
protected const MODECLOSING = [
'b' => true,
'b*' => true,
's' => true,
];
/**
* Clipping Modes.
*
* @var array<string, bool>
*/
protected const MODECLIPPING = [
'CEO' => true,
'CNZ' => true,
'W n' => true,
'W* n' => true,
];
/**
* Map of equivalent modes without close.
*
* @var array<string, string>
*/
protected const MODETONOCLOSE = [
's' => 'S',
'b' => 'B',
'b*' => 'B*',
];
/**
* Map of equivalent modes without fill.
*
* @var array<string, string>
*/
protected const MODETONOFILL = [
'f' => '',
'f*' => '',
'B' => 'S',
'B*' => 'S',
'b' => 's',
'b*' => 's',
];
/**
* Map of equivalent modes without STROKE.
*
* @var array<string, string>
*/
protected const MODETONOSTROKE = [
'S' => '',
's' => 'h',
'B' => 'f',
'B*' => 'f*',
'b' => 'h f',
'b*' => 'h f*',
];
/**
* Add a new style
*
* @param StyleDataOpt $style Style to add.
* @param bool $inheritlast If true inherit missing values from the last style.
*
* @return string PDF style string
*/
public function add(array $style = [], bool $inheritlast = false): string
{
if ($inheritlast) {
$style = \array_merge($this->getCurrentStyleArray(), $style);
}
$this->style[++$this->styleid] = $style;
return $this->getStyle();
}
/**
* Remove and return last style.
*
* @return string PDF style string.
*
* @throws \Com\Tecnick\Pdf\Graph\Exception
*/
public function pop(): string
{
if ($this->styleid <= 0) {
throw new GraphException('The style stack is empty');
}
$style = $this->getStyle();
unset($this->style[$this->styleid]);
--$this->styleid;
return $style;
}
/**
* Save the current style ID to be restored later.
*/
public function saveStyleStatus(): void
{
$this->stylemark[] = $this->styleid;
}
/**
* Restore the saved style status.
*/
public function restoreStyleStatus(): void
{
$styleid = \array_pop($this->stylemark);
if ($styleid === null) {
$styleid = 0;
}
$this->styleid = $styleid;
$this->style = \array_slice($this->style, 0, $this->styleid + 1, true);
}
/**
* Returns the last style array.
*
* @return StyleDataOpt
*/
public function getCurrentStyleArray(): array
{
if (isset($this->style[$this->styleid])) {
return $this->style[$this->styleid];
}
return $this->getDefaultStyle();
}
/**
* Returns the last set value of the specified property.
*
* @param string $property Property to search.
* @param int|float|bool|string|null $default Default value to return in case the property is not found.
*
* @return int|float|bool|string|null Property value or $default in case the property is not found.
*/
public function getLastStyleProperty(
string $property,
int|float|bool|string|null $default = null,
): int|float|bool|string|null {
for ($idx = $this->styleid; $idx >= 0; --$idx) {
if (
array_key_exists($property, $this->style[$idx] ?? [])
&& ($this->style[$idx][$property] ?? null) !== null
&& !\is_array($this->style[$idx][$property])
) {
return $this->style[$idx][$property];
}
}
return $default;
}
/**
* Returns the value of the specified item from the last inserted style.
*
* @param string $item Item to search.
*
* @throws \Com\Tecnick\Pdf\Graph\Exception
*/
public function getCurrentStyleItem(string $item): mixed
{
$style = $this->getCurrentStyleArray();
if (!\array_key_exists($item, $style)) {
throw new GraphException('The ' . $item . ' value is not set in the current style');
}
return $style[$item];
}
/**
* Returns the PDF string of the last style added.
*/
public function getStyle(): string
{
return $this->getStyleCmd($this->getCurrentStyleArray());
}
/**
* Returns the PDF string of the specified style.
*
* @param StyleDataOpt $style Style to represent.
*/
public function getStyleCmd(array $style = []): string
{
$out = '';
if (array_key_exists('lineWidth', $style)) {
$out .= \sprintf('%F w' . "\n", $style['lineWidth'] * $this->kunit);
}
$out .= $this->getLineModeCmd($style);
if (array_key_exists('lineColor', $style)) {
$out .= $this->pdfColor->getPdfColor($style['lineColor'], true);
}
if (array_key_exists('fillColor', $style)) {
$out .= $this->pdfColor->getPdfColor($style['fillColor'], false);
}
return $out;
}
/**
* Returns the PDF string of the specified line style.
*
* @param StyleDataOpt $style Style to represent.
*
* @SuppressWarnings("PHPMD.CyclomaticComplexity")
*/
protected function getLineModeCmd(array $style = []): string
{
$out = '';
if (array_key_exists('lineCap', $style)) {
$lineCap = $style['lineCap'];
if (isset(self::LINECAPMAP[$lineCap])) {
$out .= self::LINECAPMAP[$lineCap] . ' J' . "\n";
}
}
if (array_key_exists('lineJoin', $style)) {
$lineJoin = $style['lineJoin'];
if (isset(self::LINEJOINMAP[$lineJoin])) {
$out .= self::LINEJOINMAP[$lineJoin] . ' j' . "\n";
}
}
if (array_key_exists('miterLimit', $style)) {
$out .= \sprintf('%F M' . "\n", $style['miterLimit'] * $this->kunit);
}
if (array_key_exists('dashArray', $style)) {
$dash = [];
foreach ($style['dashArray'] as $val) {
$dash[] = \sprintf('%F', (float) $val * $this->kunit);
}
if (!array_key_exists('dashPhase', $style)) {
$style['dashPhase'] = 0;
}
$out .= \sprintf('[%s] %F d' . "\n", \implode(' ', $dash), $style['dashPhase']);
}
return $out;
}
/**
* Get the Path-Painting Operators.
*
* @param string|PathPaintOp $mode Mode of rendering (or PathPaintOp enum case). Possible values are:
* - S or D: Stroke the path. - s or d:
* Close and stroke the path. - f or F:
* Fill the path, using the nonzero
* winding number rule to determine the
* region to fill. - f* or F*: Fill the
* path, using the even-odd rule to
* determine the region to fill. - B or FD
* or DF: Fill and then stroke the path,
* using the nonzero winding number rule
* to determine the region to fill. - B*
* or F*D or DF*: Fill and then stroke the
* path, using the even-odd rule to
* determine the region to fill. - b or fd
* or df: Close, fill, and then stroke the
* path, using the nonzero winding number
* rule to determine the region to fill. -
* b* or f*d or df*: Close, fill, and then
* stroke the path, using the even-odd
* rule to determine the region to fill. -
* CNZ: Clipping mode using the nonzero
* winding number rule to determine which
* regions lie inside the clipping path. -
* CEO: Clipping mode using the even-odd
* rule to determine which regions lie
* inside the clipping path - n: End
* the path object without filling or
* stroking it.
* @param string|PathPaintOp $default Default style (or PathPaintOp enum case)
*/
public function getPathPaintOp(string|PathPaintOp $mode, string|PathPaintOp $default = 'S'): string
{
if ($mode instanceof PathPaintOp) {
$mode = $mode->value;
}
if ($default instanceof PathPaintOp) {
$default = $default->value;
}
if ($mode === '' || !isset(self::PPOPMAP[$mode])) {
return isset(self::PPOPMAP[$default]) ? self::PPOPMAP[$default] . "\n" : '';
}
return self::PPOPMAP[$mode] . "\n";
}
/**
* Returns true if the specified path paint operator includes the filling option.
*
* @param string $mode Path paint operator (mode of rendering).
*/
public function isFillingMode(string $mode): bool
{
return (
isset(self::PPOPMAP[$mode])
&& (array_key_exists(self::PPOPMAP[$mode], self::MODEFILLING) || $this->isClippingMode($mode))
);
}
/**
* Returns true if the specified mode includes the stroking option.
*
* @param string $mode Path paint operator (mode of rendering).
*/
public function isStrokingMode(string $mode): bool
{
if (!isset(self::PPOPMAP[$mode])) {
return false;
}
$paintMode = self::PPOPMAP[$mode];
return array_key_exists($paintMode, self::MODESTROKING);
}
/**
* Returns true if the specified mode includes "closing the path" option.
*
* @param string $mode Path paint operator (mode of rendering).
*/
public function isClosingMode(string $mode): bool
{
return (
isset(self::PPOPMAP[$mode])
&& (array_key_exists(self::PPOPMAP[$mode], self::MODECLOSING) || $this->isClippingMode($mode))
);
}
/**
* Returns true if the specified mode is of clipping type.
*
* @param string $mode Path paint operator (mode of rendering).
*/
public function isClippingMode(string $mode): bool
{
if (!isset(self::PPOPMAP[$mode])) {
return false;
}
$paintMode = self::PPOPMAP[$mode];
return array_key_exists($paintMode, self::MODECLIPPING);
}
/**
* Remove the Close option from the specified Path paint operator.
*
* @param string $mode Path paint operator (mode of rendering).
*/
public function getModeWithoutClose(string $mode): string
{
if (!isset(self::PPOPMAP[$mode])) {
return $mode;
}
$paintMode = self::PPOPMAP[$mode];
if (isset(self::MODETONOCLOSE[$paintMode])) {
return self::MODETONOCLOSE[$paintMode];
}
return $mode;
}
/**
* Remove the Fill option from the specified Path paint operator.
*
* @param string $mode Path paint operator (mode of rendering).
*/
public function getModeWithoutFill(string $mode): string
{
if (!isset(self::PPOPMAP[$mode])) {
return $mode;
}
$paintMode = self::PPOPMAP[$mode];
if (isset(self::MODETONOFILL[$paintMode])) {
return self::MODETONOFILL[$paintMode];
}
return $mode;
}
/**
* Remove the Stroke option from the specified Path paint operator.
*
* @param string $mode Path paint operator (mode of rendering).
*/
public function getModeWithoutStroke(string $mode): string
{
if (!isset(self::PPOPMAP[$mode])) {
return $mode;
}
$paintMode = self::PPOPMAP[$mode];
if (isset(self::MODETONOSTROKE[$paintMode])) {
return self::MODETONOSTROKE[$paintMode];
}
return $mode;
}
/**
* Add transparency parameters to the current extgstate.
*
* @param array<string, int|float|bool|string> $parms parameters.
*
* @return string PDF command.
*/
public function getExtGState(array $parms): string
{
if ($this->pdfa) {
return '';
}
$gsx = \count($this->extgstates) + 1;
// check if this ExtGState already exist
foreach ($this->extgstates as $idx => $ext) {
if ($ext['parms'] !== $parms) {
continue;
}
$gsx = $idx;
break;
}
if (($this->extgstates[$gsx] ?? []) === []) {
$this->extgstates[$gsx] = [
'n' => 0,
'name' => '',
'parms' => $parms,
];
}
return '/GS' . $gsx . ' gs' . "\n";
}
}
+394
View File
@@ -0,0 +1,394 @@
<?php
declare(strict_types=1);
/**
* Transform.php
*
* @since 2011-05-23
* @category Library
* @package PdfGraph
* @author Nicola Asuni <info@tecnick.com>
* @copyright 2011-2026 Nicola Asuni - Tecnick.com LTD
* @license https://www.gnu.org/copyleft/lesser.html GNU-LGPL v3 (see LICENSE)
* @link https://github.com/tecnickcom/tc-lib-pdf-graph
*
* This file is part of tc-lib-pdf-graph software library.
*/
namespace Com\Tecnick\Pdf\Graph;
use Com\Tecnick\Pdf\Graph\Exception as GraphException;
/**
* Com\Tecnick\Pdf\Graph\Transform
*
* @since 2011-05-23
* @category Library
* @package PdfGraph
* @author Nicola Asuni <info@tecnick.com>
* @copyright 2011-2026 Nicola Asuni - Tecnick.com LTD
* @license https://www.gnu.org/copyleft/lesser.html GNU-LGPL v3 (see LICENSE)
* @link https://github.com/tecnickcom/tc-lib-pdf-graph
*
* @phpstan-import-type TTMatrix from \Com\Tecnick\Pdf\Graph\Base
*/
abstract class Transform extends \Com\Tecnick\Pdf\Graph\Style
{
/**
* Current ID for transformation matrix.
*/
protected int $ctmid = -1;
/**
* Array (stack) of Current Transformation Matrix (CTM),
* which maps user space coordinates used within a PDF content stream into output device coordinates.
*
* @var array<int, array<int, TTMatrix>>
*/
protected array $ctm = [];
/**
* Returns the transformation stack.
*
* @return array<int, array<int, TTMatrix>>
*/
public function getTransformStack(): array
{
return $this->ctm;
}
/**
* Returns the transformation stack index.
*/
public function getTransformIndex(): int
{
return $this->ctmid;
}
/**
* Starts a 2D transformation saving current graphic state.
* This function must be called before calling transformation methods
*/
public function getStartTransform(): string
{
$this->saveStyleStatus();
$this->ctm[++$this->ctmid] = [];
return Base::GSAVE;
}
/**
* Stops a 2D transformation restoring previous graphic state.
* This function must be called after calling transformation methods.
*/
public function getStopTransform(): string
{
if (($this->ctm[$this->ctmid] ?? null) === null) {
return '';
}
unset($this->ctm[$this->ctmid]);
--$this->ctmid;
$this->restoreStyleStatus();
return Base::GRESTORE;
}
/**
* Get the transformation matrix (CTM) PDF string
*
* @param TTMatrix $ctm Transformation matrix array.
*/
public function getTransformation(array $ctm): string
{
$this->ctm[$this->ctmid][] = $ctm;
return \sprintf('%F %F %F %F %F %F cm' . "\n", $ctm[0], $ctm[1], $ctm[2], $ctm[3], $ctm[4], $ctm[5]);
}
/**
* Vertical and horizontal non-proportional Scaling.
*
* @param float $skx Horizontal scaling factor.
* @param float $sky vertical scaling factor.
* @param float $posx Abscissa of the scaling center.
* @param float $posy Ordinate of the scaling center.
*
* @return string Transformation string
*
* @throws \Com\Tecnick\Pdf\Graph\Exception
*/
public function getScaling(float $skx, float $sky, float $posx, float $posy): string
{
if ($skx === 0.0 || $sky === 0.0) {
throw new GraphException('Scaling factors must be different than zero');
}
$posy = ($this->pageh - $posy) * $this->kunit;
$posx *= $this->kunit;
$ctm = [$skx, 0, 0, $sky, $posx * (1 - $skx), $posy * (1 - $sky)];
return $this->getTransformation($ctm);
}
/**
* Horizontal Scaling.
*
* @param float $skx Horizontal scaling factor.
* @param float $posx Abscissa of the scaling center.
* @param float $posy Ordinate of the scaling center.
*
* @return string Transformation string
*
* @throws \Com\Tecnick\Pdf\Graph\Exception
*/
public function getHorizScaling(float $skx, float $posx, float $posy): string
{
return $this->getScaling($skx, 1, $posx, $posy);
}
/**
* Vertical Scaling.
*
* @param float $sky vertical scaling factor.
* @param float $posx Abscissa of the scaling center.
* @param float $posy Ordinate of the scaling center.
*
* @return string Transformation string
*
* @throws \Com\Tecnick\Pdf\Graph\Exception
*/
public function getVertScaling(float $sky, float $posx, float $posy): string
{
return $this->getScaling(1, $sky, $posx, $posy);
}
/**
* Vertical and horizontal proportional Scaling.
*
* @param float $skf Scaling factor.
* @param float $posx Abscissa of the scaling center.
* @param float $posy Ordinate of the scaling center.
*
* @return string Transformation string
*
* @throws \Com\Tecnick\Pdf\Graph\Exception
*/
public function getPropScaling(float $skf, float $posx, float $posy): string
{
return $this->getScaling($skf, $skf, $posx, $posy);
}
/**
* Rotation.
*
* @param float $angle Angle in degrees for counter-clockwise rotation.
* @param float $posx Abscissa of the rotation center.
* @param float $posy Ordinate of the rotation center.
*
* @return string Transformation string
*/
public function getRotation(float $angle, float $posx, float $posy): string
{
$posy = ($this->pageh - $posy) * $this->kunit;
$posx *= $this->kunit;
$ctm = [];
$ctm[0] = \cos($this->degToRad($angle));
$ctm[1] = \sin($this->degToRad($angle));
$ctm[2] = -$ctm[1];
$ctm[3] = $ctm[0];
$ctm[4] = $posx + ($ctm[1] * $posy) - ($ctm[0] * $posx);
$ctm[5] = $posy - ($ctm[0] * $posy) - ($ctm[1] * $posx);
return $this->getTransformation($ctm);
}
/**
* Horizontal Mirroring.
*
* @param float $posx Abscissa of the mirroring line.
*
* @return string Transformation string
*
* @throws \Com\Tecnick\Pdf\Graph\Exception
*/
public function getHorizMirroring(float $posx): string
{
return $this->getScaling(-1, 1, $posx, 0);
}
/**
* Vertical Mirroring.
*
* @param float $posy Ordinate of the mirroring line.
*
* @return string Transformation string
*
* @throws \Com\Tecnick\Pdf\Graph\Exception
*/
public function getVertMirroring(float $posy): string
{
return $this->getScaling(1, -1, 0, $posy);
}
/**
* Point reflection mirroring.
*
* @param float $posx Abscissa of the mirroring point.
* @param float $posy Ordinate of the mirroring point.
*
* @return string Transformation string
*
* @throws \Com\Tecnick\Pdf\Graph\Exception
*/
public function getPointMirroring(float $posx, float $posy): string
{
return $this->getScaling(-1, -1, $posx, $posy);
}
/**
* Reflection against a straight line through point (x, y) with the gradient angle (angle).
*
* @param float $ang Gradient angle in degrees of the straight line.
* @param float $posx Abscissa of the mirroring point.
* @param float $posy Ordinate of the mirroring point.
*
* @return string Transformation string
*
* @throws \Com\Tecnick\Pdf\Graph\Exception
*/
public function getReflection(float $ang, float $posx, float $posy): string
{
return $this->getScaling(-1, 1, $posx, $posy) . $this->getRotation(-2 * ($ang - 90), $posx, $posy);
}
/**
* Translate graphic object horizontally and vertically.
*
* @param float $trx Movement to the right.
* @param float $try Movement to the bottom.
*
* @return string Transformation string
*/
public function getTranslation(float $trx, float $try): string
{
//calculate elements of transformation matrix
$ctm = [1, 0, 0, 1, $trx * $this->kunit, -$try * $this->kunit];
return $this->getTransformation($ctm);
}
/**
* Translate graphic object horizontally.
*
* @param float $trx Movement to the right.
*
* @return string Transformation string
*/
public function getHorizTranslation(float $trx): string
{
return $this->getTranslation($trx, 0);
}
/**
* Translate graphic object vertically.
*
* @param float $try Movement to the bottom.
*
* @return string Transformation string
*/
public function getVertTranslation(float $try): string
{
return $this->getTranslation(0, $try);
}
/**
* Skew.
*
* @param float $angx Angle in degrees between -90 (skew to the left) and 90 (skew to the right)
* @param float $angy Angle in degrees between -90 (skew to the bottom) and 90 (skew to the top)
* @param float $posx Abscissa of the skewing center.
* @param float $posy Ordinate of the skewing center.
*
* @return string Transformation string
*
* @throws \Com\Tecnick\Pdf\Graph\Exception
*/
public function getSkewing(float $angx, float $angy, float $posx, float $posy): string
{
if ($angx <= -90 || $angx >= 90 || $angy <= -90 || $angy >= 90) {
throw new GraphException('Angle values must be between -90 and +90 degrees.');
}
$posy = ($this->pageh - $posy) * $this->kunit;
$posx *= $this->kunit;
$ctm = [];
$ctm[0] = 1;
$ctm[1] = \tan($this->degToRad($angy));
$ctm[2] = \tan($this->degToRad($angx));
$ctm[3] = 1;
$ctm[4] = -$ctm[2] * $posy;
$ctm[5] = -$ctm[1] * $posx;
return $this->getTransformation($ctm);
}
/**
* Skew horizontally.
*
* @param float $angx Angle in degrees between -90 (skew to the left) and 90 (skew to the right)
* @param float $posx Abscissa of the skewing center.
* @param float $posy Ordinate of the skewing center.
*
* @return string Transformation string
*
* @throws \Com\Tecnick\Pdf\Graph\Exception
*/
public function getHorizSkewing(float $angx, float $posx, float $posy): string
{
return $this->getSkewing($angx, 0, $posx, $posy);
}
/**
* Skew vertically.
*
* @param float $angy Angle in degrees between -90 (skew to the bottom) and 90 (skew to the top)
* @param float $posx Abscissa of the skewing center.
* @param float $posy Ordinate of the skewing center.
*
* @return string Transformation string
*
* @throws \Com\Tecnick\Pdf\Graph\Exception
*/
public function getVertSkewing(float $angy, float $posx, float $posy): string
{
return $this->getSkewing(0, $angy, $posx, $posy);
}
/**
* Get the product of two Transformation Matrix.
*
* @param TTMatrix $tma First Transformation Matrix.
* @param TTMatrix $tmb Second Transformation Matrix.
*
* @return TTMatrix CTM Transformation Matrix.
*/
public function getCtmProduct(array $tma, array $tmb): array
{
return [
($tma[0] * $tmb[0]) + ($tma[2] * $tmb[1]),
($tma[1] * $tmb[0]) + ($tma[3] * $tmb[1]),
($tma[0] * $tmb[2]) + ($tma[2] * $tmb[3]),
($tma[1] * $tmb[2]) + ($tma[3] * $tmb[3]),
($tma[0] * $tmb[4]) + ($tma[2] * $tmb[5]) + $tma[4],
($tma[1] * $tmb[4]) + ($tma[3] * $tmb[5]) + $tma[5],
];
}
/**
* Converts the number in degrees to the radian equivalent.
* We use this instead of the deg2rad() function to avoid precision problems with hhvm.
*
* @param float $deg Angular value in degrees.
*
* @return float Angle in radians
*/
public function degToRad(float $deg): float
{
return ($deg * self::MPI) / 180;
}
}