Skip to content

Commit eaf8d98

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 f92feed commit eaf8d98

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
@@ -126,6 +126,10 @@ Bugfixes
126126
* A percentage alpha, as in `rgba(255, 0, 0, 50%)`, gave an opacity above 1, which viewers draw opaque.
127127
* A fourth argument to `rgb()` or `hsl()` is read as the alpha instead of being dropped.
128128
* `border-color: rgb(255, 0, 0)` or `cmyk(0, 100, 0, 0)`, with spaces after the commas, drew black.
129+
* Some colour values were read wrongly. [#552] [#570]
130+
* `#rgba` was read from the wrong digits: `#f008` drew `rgb(240, 8, 0)`. `#rrggbbaa` dropped its alpha. Both are now read with their alpha.
131+
* 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.
132+
* `rebeccapurple` was missing. mPDF's `violetred`, which is not a CSS colour, is kept.
129133
* 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]
130134
* Balancing columns raised a warning and drew a block's closing background past the last column. [#475] [#488]
131135
* Inside `<columns>`, a block with an `rgba()` or `cmyka()` background was painted fully opaque. [#482] [#498]
@@ -703,3 +707,4 @@ These changes do not change output.
703707
[#549]: https://github.com/GravityPDF/mpdf/pull/549
704708
[#552]: https://github.com/GravityPDF/mpdf/issues/552
705709
[#563]: https://github.com/GravityPDF/mpdf/pull/563
710+
[#570]: https://github.com/GravityPDF/mpdf/pull/570

‎src/Color/ColorConverter.php‎

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

278278
if (preg_match('/^[\d]+$/', $color)) {
279-
$c = [static::MODE_GRAYSCALE, $color]; // i.e. integer only
279+
$c = [static::MODE_GRAYSCALE, $this->clamp($color, 255)]; // i.e. integer only
280280
} elseif (strpos($color, '#') === 0) { // case of #nnnnnn or #nnn
281281
$c = $this->processHashColor($color);
282282
} elseif (preg_match('/(rgba|rgb|device-cmyka|cmyka|device-cmyk|cmyk|hsla|hsl|spot)\((.*?)\)/', $color, $m)) {
@@ -324,16 +324,20 @@ private function processHashColor($color)
324324
// in case of Background: #CCC url() x-repeat etc.
325325
$cor = preg_replace('/\s+.*/', '', $color);
326326

327-
// Turn #RGB into #RRGGBB
328-
if (strlen($cor) === 4) {
329-
$cor = '#' . $cor[1] . $cor[1] . $cor[2] . $cor[2] . $cor[3] . $cor[3];
327+
// Turn #RGB into #RRGGBB, and #RGBA into #RRGGBBAA
328+
if (strlen($cor) === 4 || strlen($cor) === 5) {
329+
$cor = '#' . preg_replace('/./', '$0$0', substr($cor, 1));
330330
}
331331

332332
$r = self::safeHexDec(substr($cor, 1, 2));
333333
$g = self::safeHexDec(substr($cor, 3, 2));
334334
$b = self::safeHexDec(substr($cor, 5, 2));
335335

336-
return [3, $r, $g, $b];
336+
if (strlen($cor) === 9) {
337+
return [static::MODE_RGBA, $r, $g, $b, self::safeHexDec(substr($cor, 7, 2)) * 100 / 255];
338+
}
339+
340+
return [static::MODE_RGB, $r, $g, $b];
337341
}
338342

339343
/**
@@ -351,24 +355,30 @@ private function processModeColor($mode, array $cores)
351355
// rgb() and rgba() are the same function, as are hsl() and hsla(): a fourth argument is the alpha
352356
case 'hsl':
353357
case 'hsla':
354-
list($cores[0], $cores[1], $cores[2]) = $this->colorModeConverter->hsl2rgb($this->hueTurns($cores[0]), $cores[1], $cores[2]);
358+
list($cores[0], $cores[1], $cores[2]) = $this->colorModeConverter->hsl2rgb(
359+
$this->hueTurns($cores[0]),
360+
$this->clamp($cores[1], 1),
361+
$this->clamp($cores[2], 1)
362+
);
355363
// no break
356364

357365
case 'rgb':
358366
case 'rgba':
367+
$rgb = $this->clampEach(array_slice($cores, 0, 3), 255);
368+
359369
if (isset($cores[3])) {
360-
return [static::MODE_RGBA, $cores[0], $cores[1], $cores[2], $cores[3] * 100];
370+
return array_merge([static::MODE_RGBA], $rgb, [$this->clamp($cores[3], 1) * 100]);
361371
}
362372

363-
return [static::MODE_RGB, $cores[0], $cores[1], $cores[2]];
373+
return array_merge([static::MODE_RGB], $rgb);
364374

365375
case 'cmyk':
366376
case 'device-cmyk':
367-
return [static::MODE_CMYK, $cores[0], $cores[1], $cores[2], $cores[3]];
377+
return array_merge([static::MODE_CMYK], $this->clampEach(array_slice($cores, 0, 4), 100));
368378

369379
case 'cmyka':
370380
case 'device-cmyka':
371-
return [static::MODE_CMYKA, $cores[0], $cores[1], $cores[2], $cores[3], $cores[4] * 100];
381+
return array_merge([static::MODE_CMYKA], $this->clampEach(array_slice($cores, 0, 4), 100), [$this->clamp($cores[4], 1) * 100]);
372382

373383
case 'spot':
374384
$name = strtoupper(trim($cores[0]));
@@ -437,6 +447,35 @@ private function convertPercentCoreValues($mode, array $cores)
437447
return $cores;
438448
}
439449

450+
/**
451+
* CSS clamps a value outside its range to the nearest end, where packing it into a byte would wrap it
452+
*
453+
* @param string|float $value
454+
* @param float $max
455+
*
456+
* @return float
457+
*/
458+
private function clamp($value, $max)
459+
{
460+
return max(0, min($max, (float) $value));
461+
}
462+
463+
/**
464+
* @param array $values
465+
* @param float $max
466+
*
467+
* @return float[] Each value clamped to the range from 0 to $max
468+
*/
469+
private function clampEach(array $values, $max)
470+
{
471+
$clamped = [];
472+
foreach ($values as $value) {
473+
$clamped[] = $this->clamp($value, $max);
474+
}
475+
476+
return $clamped;
477+
}
478+
440479
/**
441480
* @param string|float $hue A number of degrees, or an angle in deg, grad, rad or turn
442481
*

‎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
@@ -430,7 +430,7 @@ protected function parseCssBackground($s)
430430

431431
if (preg_match('/url\(/i', $s)) {
432432
// If color, set and strip it off
433-
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)) {
433+
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)) {
434434
$background['c'] = strtolower($m[1]);
435435
$s = $m[3];
436436
}
@@ -455,7 +455,7 @@ protected function parseCssBackground($s)
455455
return $background;
456456
}
457457

458-
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)) {
458+
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)) {
459459
$background['c'] = strtolower($m[1]);
460460
}
461461

‎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)