Skip to content

Commit fc11cbb

Browse files
jakejackson1claude
andcommitted
Read the alpha of #rgba and #rrggbbaa, and clamp colour channels instead of wrapping them
`#f008` was read from the wrong digits and `#rrggbbaa` lost its alpha. A channel outside its range was masked into a byte, so rgb(255.5, 0, 0) drew black and rgb(300, 0, 0) dark red. Read both hex forms with their alpha, let the background shorthand take an eight-digit colour, clamp channels, alphas and hsl() saturation and lightness to their range, and add rebeccapurple. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 4402e6c commit fc11cbb

8 files changed

Lines changed: 226 additions & 12 deletions

File tree

‎CHANGELOG-GRAVITYPDF.md‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -141,6 +141,10 @@ Bugfixes
141141
* `vw`, `vh`, `vmin`, `vmax`, `Q` and `ch` were read as pixels, `+5mm` and `1e+1mm` as 0, and `1,5mm` as 1mm. The units are now resolved against the page and the font size, the numbers are read, and `1,5mm` is dropped. [#552] [#565]
142142
* `line-height: 0` gave lines a normal height. Lines now have no height, as in a browser. A line height well below the font size, such as `0.5` or `1mm`, was stretched down to the baseline; it is now kept. A negative `line-height`, which shrank lines to odd heights, is now ignored. [#552] [#567]
143143
* The rule after an `@supports`, `@layer`, `@keyframes`, `@container` or other block at-rule was lost, and so were the rules inside `@supports` and `@layer`. The rule after `@charset`, `@namespace` or `@import` was lost too. `@supports` and `@layer` blocks are now unwrapped as `@media` blocks are, except `@supports not`, and other at-rules are removed whole. [#524] [#566]
144+
* Some colour values were read wrongly. [#552] [#570]
145+
* `#rgba` was read from the wrong digits: `#f008` drew `rgb(240, 8, 0)`. `#rrggbbaa` dropped its alpha. Both are now read with their alpha.
146+
* A channel outside its range wrapped instead of being clamped: `rgb(255.5, 0, 0)` drew black and `rgb(300, 0, 0)` dark red. Channels, alphas, and `hsl()` saturation and lightness are now clamped, as CSS does.
147+
* `rebeccapurple` was missing. mPDF's `violetred`, which is not a CSS colour, is kept.
144148
* A percentage `width`, `min-width` or `max-width` on an image in a table cell was resolved against the block around the table, not the cell. In a 60mm cell, `max-width: 20%` came out as 36mm. [#223] [#505]
145149
* An `@page :left` or `@page :right` rule was ignored unless the style sheet also had a plain `@page` rule. With one, the margins of a `:right` rule were applied to left pages too. [#555] [#556]
146150
* When a later `WriteHTML()` call turned the document right to left, the text on the page already started was set between the swapped side margins. That page now keeps its margins, and the swap starts with the next page. [#554] [#558]
@@ -751,4 +755,5 @@ These changes do not change output.
751755
[#568]: https://github.com/GravityPDF/mpdf/pull/568
752756
[#567]: https://github.com/GravityPDF/mpdf/pull/567
753757
[#566]: https://github.com/GravityPDF/mpdf/pull/566
758+
[#570]: https://github.com/GravityPDF/mpdf/pull/570
754759
[#615]: https://github.com/GravityPDF/mpdf/pull/615

‎src/Color/ColorConverter.php‎

Lines changed: 49 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -292,7 +292,7 @@ private function convertPlain($color, array &$PDFAXwarnings = [])
292292
$c = false;
293293

294294
if (preg_match('/^[\d]+$/', $color)) {
295-
$c = [static::MODE_GRAYSCALE, $color]; // i.e. integer only
295+
$c = [static::MODE_GRAYSCALE, $this->clamp($color, 255)]; // i.e. integer only
296296
} elseif (strpos($color, '#') === 0) { // case of #nnnnnn or #nnn
297297
$c = $this->processHashColor($color);
298298
} elseif (preg_match('/(rgba|rgb|device-cmyka|cmyka|device-cmyk|cmyk|hsla|hsl|spot)\((.*?)\)/', $color, $m)) {
@@ -340,16 +340,20 @@ private function processHashColor($color)
340340
// in case of Background: #CCC url() x-repeat etc.
341341
$cor = preg_replace('/\s+.*/', '', $color);
342342

343-
// Turn #RGB into #RRGGBB
344-
if (strlen($cor) === 4) {
345-
$cor = '#' . $cor[1] . $cor[1] . $cor[2] . $cor[2] . $cor[3] . $cor[3];
343+
// Turn #RGB into #RRGGBB, and #RGBA into #RRGGBBAA
344+
if (strlen($cor) === 4 || strlen($cor) === 5) {
345+
$cor = '#' . preg_replace('/./', '$0$0', substr($cor, 1));
346346
}
347347

348348
$r = self::safeHexDec(substr($cor, 1, 2));
349349
$g = self::safeHexDec(substr($cor, 3, 2));
350350
$b = self::safeHexDec(substr($cor, 5, 2));
351351

352-
return [3, $r, $g, $b];
352+
if (strlen($cor) === 9) {
353+
return [static::MODE_RGBA, $r, $g, $b, self::safeHexDec(substr($cor, 7, 2)) * 100 / 255];
354+
}
355+
356+
return [static::MODE_RGB, $r, $g, $b];
353357
}
354358

355359
/**
@@ -367,24 +371,30 @@ private function processModeColor($mode, array $cores)
367371
// rgb() and rgba() are the same function, as are hsl() and hsla(): a fourth argument is the alpha
368372
case 'hsl':
369373
case 'hsla':
370-
list($cores[0], $cores[1], $cores[2]) = $this->colorModeConverter->hsl2rgb($this->hueTurns($cores[0]), $cores[1], $cores[2]);
374+
list($cores[0], $cores[1], $cores[2]) = $this->colorModeConverter->hsl2rgb(
375+
$this->hueTurns($cores[0]),
376+
$this->clamp($cores[1], 1),
377+
$this->clamp($cores[2], 1)
378+
);
371379
// no break
372380

373381
case 'rgb':
374382
case 'rgba':
383+
$rgb = $this->clampEach(array_slice($cores, 0, 3), 255);
384+
375385
if (isset($cores[3])) {
376-
return [static::MODE_RGBA, $cores[0], $cores[1], $cores[2], $cores[3] * 100];
386+
return array_merge([static::MODE_RGBA], $rgb, [$this->clamp($cores[3], 1) * 100]);
377387
}
378388

379-
return [static::MODE_RGB, $cores[0], $cores[1], $cores[2]];
389+
return array_merge([static::MODE_RGB], $rgb);
380390

381391
case 'cmyk':
382392
case 'device-cmyk':
383-
return [static::MODE_CMYK, $cores[0], $cores[1], $cores[2], $cores[3]];
393+
return array_merge([static::MODE_CMYK], $this->clampEach(array_slice($cores, 0, 4), 100));
384394

385395
case 'cmyka':
386396
case 'device-cmyka':
387-
return [static::MODE_CMYKA, $cores[0], $cores[1], $cores[2], $cores[3], $cores[4] * 100];
397+
return array_merge([static::MODE_CMYKA], $this->clampEach(array_slice($cores, 0, 4), 100), [$this->clamp($cores[4], 1) * 100]);
388398

389399
case 'spot':
390400
$name = strtoupper(trim($cores[0]));
@@ -453,6 +463,35 @@ private function convertPercentCoreValues($mode, array $cores)
453463
return $cores;
454464
}
455465

466+
/**
467+
* CSS clamps a value outside its range to the nearest end, where packing it into a byte would wrap it
468+
*
469+
* @param string|float $value
470+
* @param float $max
471+
*
472+
* @return float
473+
*/
474+
private function clamp($value, $max)
475+
{
476+
return max(0, min($max, (float) $value));
477+
}
478+
479+
/**
480+
* @param array $values
481+
* @param float $max
482+
*
483+
* @return float[] Each value clamped to the range from 0 to $max
484+
*/
485+
private function clampEach(array $values, $max)
486+
{
487+
$clamped = [];
488+
foreach ($values as $value) {
489+
$clamped[] = $this->clamp($value, $max);
490+
}
491+
492+
return $clamped;
493+
}
494+
456495
/**
457496
* @param string|float $hue A number of degrees, or an angle in deg, grad, rad or turn
458497
*

‎src/Color/NamedColors.php‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -125,6 +125,7 @@ class NamedColors
125125
'plum' => '#dda0dd',
126126
'powderblue' => '#b0e0e6',
127127
'purple' => '#800080',
128+
'rebeccapurple' => '#663399',
128129
'red' => '#ff0000',
129130
'rosybrown' => '#bc8f8f',
130131
'royalblue' => '#4169e1',

‎src/Css/NormalizeProperties.php‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -477,7 +477,7 @@ protected function parseCssBackground($s)
477477

478478
if (preg_match('/url\(/i', $s)) {
479479
// If color, set and strip it off
480-
if (preg_match('/^\s*(#[0-9a-fA-F]{3,6}|(rgba|rgb|device-cmyka|cmyka|device-cmyk|cmyk|hsla|hsl|spot)\(.*?\)|[a-zA-Z]{3,})\s+(url\(.*)/i', $s, $m)) {
480+
if (preg_match('/^\s*(#[0-9a-fA-F]{3,8}|(rgba|rgb|device-cmyka|cmyka|device-cmyk|cmyk|hsla|hsl|spot)\(.*?\)|[a-zA-Z]{3,})\s+(url\(.*)/i', $s, $m)) {
481481
$background['c'] = strtolower($m[1]);
482482
$s = $m[3];
483483
}
@@ -502,7 +502,7 @@ protected function parseCssBackground($s)
502502
return $background;
503503
}
504504

505-
if (preg_match('/^\s*(#[0-9a-fA-F]{3,6}|(rgba|rgb|device-cmyka|cmyka|device-cmyk|cmyk|hsla|hsl|spot)\(.*?\)|[a-zA-Z]{3,})/i', $s, $m)) {
505+
if (preg_match('/^\s*(#[0-9a-fA-F]{3,8}|(rgba|rgb|device-cmyka|cmyka|device-cmyk|cmyk|hsla|hsl|spot)\(.*?\)|[a-zA-Z]{3,})/i', $s, $m)) {
506506
$background['c'] = strtolower($m[1]);
507507
}
508508

‎tests/Mpdf/Color/ColorConverterTest.php‎

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -150,6 +150,53 @@ public function modernSyntaxProvider()
150150
];
151151
}
152152

153+
/**
154+
* Hex colours with an alpha digit or pair, channels and alphas outside their range clamped to it rather than
155+
* wrapped, and rebeccapurple beside the named colour mPDF already knew
156+
*
157+
* @dataProvider colorValuesProvider
158+
*
159+
* @param string $input
160+
* @param string $output
161+
*/
162+
public function testConvertColorValues($input, $output)
163+
{
164+
$converter = new ColorConverter($this->mpdf, new ColorModeConverter(), $this->restrictor);
165+
166+
$this->assertSame($output, $converter->convert($input));
167+
}
168+
169+
/**
170+
* Each colour, and its binary string: the mode, then the channels, then the alpha as a percentage
171+
*
172+
* @return string[][]
173+
*/
174+
public function colorValuesProvider()
175+
{
176+
return [
177+
['#f008', "5\xff\x00\x005\x00"],
178+
['#F00F', "5\xff\x00\x00d\x00"],
179+
['#ff000080', "5\xff\x00\x002\x00"],
180+
['#ff0000ff', "5\xff\x00\x00d\x00"],
181+
['#ff000000', "5\xff\x00\x00\x00\x00"],
182+
183+
['rgb(255.5, 0, 0)', "3\xff\x00\x00\x00\x00"],
184+
['rgb(300, -20, 127.6)', "3\xff\x00\x80\x00\x00"],
185+
['rgb(150%, 0%, 0%)', "3\xff\x00\x00\x00\x00"],
186+
['rgba(0, 0, 255, 1.5)', "5\x00\x00\xffd\x00"],
187+
['rgba(0, 0, 255, -1)', "5\x00\x00\xff\x00\x00"],
188+
['rgba(0, 0, 255, 150%)', "5\x00\x00\xffd\x00"],
189+
['hsl(120, 150%, 50%)', "3\x00\xff\x00\x00\x00"],
190+
['hsl(120, 100%, 150%)', "3\xff\xff\xff\x00\x00"],
191+
['cmyk(150, 0, -5, 100)', "4d\x00\x00d\x00"],
192+
['cmyka(0, 0, 0, 100, 2)', "6\x00\x00\x00dd"],
193+
['300', "1\xff\x00\x00\x00\x00"],
194+
195+
['rebeccapurple', "3f3\x99\x00\x00"],
196+
['violetred', "3\xd0\x20\x90\x00\x00"],
197+
];
198+
}
199+
153200
public function testConvertUnknownSpotColor()
154201
{
155202
$this->expectException(\Mpdf\MpdfException::class);

‎tests/Mpdf/ColorValueTest.php‎

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
<?php
2+
3+
namespace Mpdf;
4+
5+
/**
6+
* Colour values mPDF read wrongly: hex colours with an alpha, channels outside their range, and rebeccapurple
7+
*/
8+
class ColorValueTest extends \Yoast\PHPUnitPolyfills\TestCases\TestCase
9+
{
10+
11+
use PageStreams;
12+
13+
/**
14+
* @dataProvider colorsProvider
15+
*
16+
* @param string $css Declarations for a paragraph
17+
* @param string[] $drawn Operators and opacities the document must contain
18+
* @param string[] $notDrawn Ones it must not
19+
*/
20+
public function testDrawsTheColour($css, array $drawn, array $notDrawn = [])
21+
{
22+
$pdf = $this->assertDrawsSilently(function (Mpdf $mpdf) use ($css) {
23+
$mpdf->WriteHTML('<p style="' . $css . '">Text</p>');
24+
});
25+
26+
foreach ($drawn as $needle) {
27+
$this->assertStringContainsString($needle, $pdf);
28+
}
29+
30+
foreach ($notDrawn as $needle) {
31+
$this->assertStringNotContainsString($needle, $pdf);
32+
}
33+
}
34+
35+
/**
36+
* Each case: the declarations, what they must draw, and what they must not
37+
*
38+
* @return array[]
39+
*/
40+
public function colorsProvider()
41+
{
42+
return [
43+
'#rgba in the background shorthand' => ['background: #f008', ['1.000 0.000 0.000 rg', '/ca 0.53']],
44+
'#rrggbbaa in the background shorthand' => ['background: #0000ff80', ['0.000 0.000 1.000 rg', '/ca 0.5']],
45+
'#rrggbbaa in background-color' => ['background-color: #0000ff80', ['0.000 0.000 1.000 rg', '/ca 0.5']],
46+
'a fractional channel' => ['color: rgb(255.5, 0, 0)', ['1.000 0.000 0.000 rg']],
47+
'channels past each end' => ['color: rgb(300, -20, 0)', ['1.000 0.000 0.000 rg']],
48+
'an alpha above 1' => ['background-color: rgba(0, 0, 255, 1.5)', ['0.000 0.000 1.000 rg'], ['/ca 1.']],
49+
'rebeccapurple' => ['color: rebeccapurple', ['0.400 0.200 0.600 rg']],
50+
];
51+
}
52+
53+
}
Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
<?php
2+
3+
namespace Snapshots;
4+
5+
/**
6+
* Hex colours with an alpha, channels and alphas outside their range, and rebeccapurple
7+
*
8+
* @group snapshot
9+
*/
10+
class ColorValueSnapshotTest extends Snapshot
11+
{
12+
13+
/**
14+
* The fixture's name
15+
*
16+
* @return string
17+
*/
18+
public function getId()
19+
{
20+
return 'color-value';
21+
}
22+
23+
/**
24+
* One case per value, under a caption saying what should be seen
25+
*/
26+
public function generatePdf()
27+
{
28+
ob_start();
29+
?>
30+
<style>
31+
body { font-size: 9pt; }
32+
h1 { font-size: 15pt; margin: 0 0 2mm 0; }
33+
h2 { margin: 4mm 0 1mm 0; font-size: 10pt; }
34+
p.caption { margin: 0 0 2mm 0; font-size: 8pt; color: #606060; }
35+
p.text { font-size: 12pt; margin: 0 0 2mm 0; }
36+
div.halves { background: linear-gradient(to right, #000000 50%, #ffffff 50%); border: 0.2mm solid #999999; padding: 3mm 0; margin-bottom: 2mm; }
37+
div.band { height: 6mm; }
38+
</style>
39+
40+
<h1>Colour values</h1>
41+
42+
<h2>Hex colours with an alpha</h2>
43+
<p class="caption">background: #f008, red at 53% opacity, across a block that is black on the left and white on the right: dark red on the left, pink on the right.</p>
44+
<div class="halves"><div class="band" style="background: #f008"></div></div>
45+
46+
<p class="caption">background: #0000ff80, blue at 50% opacity: dark blue on the left, light blue on the right.</p>
47+
<div class="halves"><div class="band" style="background: #0000ff80"></div></div>
48+
49+
<h2>Channels outside their range</h2>
50+
<p class="caption">rgb(255.5, 0, 0) and rgb(300, -20, 0) are clamped to red. Both lines are red.</p>
51+
<p class="text" style="color: rgb(255.5, 0, 0)">rgb(255.5, 0, 0) is red</p>
52+
<p class="text" style="color: rgb(300, -20, 0)">rgb(300, -20, 0) is red</p>
53+
54+
<p class="caption">rgba(0, 0, 255, 1.5), an alpha above 1, is clamped to 1: opaque blue across both halves.</p>
55+
<div class="halves"><div class="band" style="background-color: rgba(0, 0, 255, 1.5)"></div></div>
56+
57+
<h2>Named colours</h2>
58+
<p class="caption">rebeccapurple is purple, and violetred, which mPDF has long accepted, is still pink.</p>
59+
<p class="text" style="color: rebeccapurple">rebeccapurple</p>
60+
<p class="text" style="color: violetred">violetred</p>
61+
<?php
62+
$html = ob_get_clean();
63+
64+
$this->mpdf = $this->createMpdf();
65+
66+
$this->mpdf->WriteHTML($html);
67+
}
68+
69+
}
35.7 KB
Binary file not shown.

0 commit comments

Comments
 (0)