Skip to content

Commit 0942dc5

Browse files
jakejackson1claude
andcommitted
Match @media and @import media queries against the print medium and the page size
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 10bf3ae commit 0942dc5

11 files changed

Lines changed: 737 additions & 25 deletions

‎CHANGELOG-GRAVITYPDF.md‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -123,6 +123,8 @@ Bugfixes
123123
* Descendant rules naming a table, row or cell, such as `td img` or `td span`, matched nothing inside the cell. [#223] [#507]
124124
* A descendant rule with a part mPDF cannot parse was cut short at that part and applied to the element before it. Such rules are now dropped. [#519]
125125
* 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]
126+
* `@media` was matched by looking for the word `print`, so `@media not print` applied, `orientation` was ignored and `min-width` never matched. Media queries are now evaluated for the print medium against the page current when the stylesheet is read: media types with `not` and `only`; `and`, `or` and `not` conditions; and `width`, `height` and `orientation`, with `min-`/`max-` prefixes and range syntax such as `(width >= 600px)`. An A4 page is about 794px wide, so `@media (min-width: 768px)` rules now apply to it. [#552] [#575]
127+
* `@import` ignored its media list, and did not load a URL that does not end in `.css`, such as a Google Fonts stylesheet. [#552] [#575]
126128
* 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]
127129
* Balancing columns raised a warning and drew a block's closing background past the last column. [#475] [#488]
128130
* Inside `<columns>`, a block with an `rgba()` or `cmyka()` background was painted fully opaque. [#482] [#498]
@@ -699,4 +701,6 @@ These changes do not change output.
699701
[#519]: https://github.com/GravityPDF/mpdf/pull/519
700702
[#524]: https://github.com/GravityPDF/mpdf/issues/524
701703
[#549]: https://github.com/GravityPDF/mpdf/pull/549
704+
[#552]: https://github.com/GravityPDF/mpdf/issues/552
702705
[#566]: https://github.com/GravityPDF/mpdf/pull/566
706+
[#575]: https://github.com/GravityPDF/mpdf/pull/575

‎src/Css/CssLoader.php‎

Lines changed: 38 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -27,11 +27,17 @@ class CssLoader
2727
*/
2828
private $cache;
2929

30-
public function __construct(Mpdf $mpdf, AssetFetcher $assetFetcher, Cache $cache)
30+
/**
31+
* @var MediaQueryProcessor
32+
*/
33+
private $mediaQueryProcessor;
34+
35+
public function __construct(Mpdf $mpdf, AssetFetcher $assetFetcher, Cache $cache, MediaQueryProcessor $mediaQueryProcessor)
3136
{
3237
$this->mpdf = $mpdf;
3338
$this->assetFetcher = $assetFetcher;
3439
$this->cache = $cache;
40+
$this->mediaQueryProcessor = $mediaQueryProcessor;
3541
}
3642

3743
/**
@@ -67,8 +73,7 @@ public function loadStylesheet($path)
6773
* Finds all external CSS file references including:
6874
* - <link rel="stylesheet" href="...">
6975
* - <link href="..." rel="stylesheet">
70-
* - @import url(...)
71-
* - @import "..."
76+
* - @import url(...) and @import "..." in <style> blocks, whose media query list matches
7277
*
7378
* @param string $html HTML content to scan
7479
* @return array Array of CSS file URLs
@@ -87,17 +92,35 @@ public function extractExternalStylesheetUrls($html)
8792
$cssUrls = array_merge($cssUrls, $cxt[1]);
8893
}
8994

90-
// @import url(...)
91-
if (preg_match_all('/@import url\([\'\"]{0,1}(\S*?\.css(\?[^\s\'\"]+)?)[\'\"]{0,1}\)\;?/si', $html, $cxt)) {
92-
$cssUrls = array_merge($cssUrls, $cxt[1]);
93-
}
95+
preg_match_all('/<style.*?>(.*?)<\/style>/si', $html, $styles);
9496

95-
// @import "..."
96-
if (preg_match_all('/@import (?!url)[\'\"]{0,1}(\S*?\.css(\?[^\s\'\"]+)?)[\'\"]{0,1}\;?/si', $html, $cxt)) {
97-
$cssUrls = array_merge($cssUrls, $cxt[1]);
97+
return array_merge($cssUrls, $this->extractImportUrls(implode(' ', $styles[1])));
98+
}
99+
100+
/**
101+
* The URLs the @import rules in $css load, less those whose media query list does not match
102+
*
103+
* A layer() before the media query list is ignored. A supports() condition is taken to pass, as the rules in an
104+
* @supports block are unwrapped, so one that starts with not fails.
105+
*
106+
* @param string $css
107+
* @return string[]
108+
*/
109+
private function extractImportUrls($css)
110+
{
111+
$url = '(?|url\(\s*"([^"]*)"\s*\)|url\(\s*\'([^\']*)\'\s*\)|url\(\s*([^\s"\')]*)\s*\)|"([^"]*)"|\'([^\']*)\')';
112+
$layer = '(?:\s*layer(?:\([^)]*\))?)?';
113+
$supports = '(?:\s*supports\(\s*(not\b)?(?:[^()]|\([^()]*\))*\))?';
114+
preg_match_all('/@import\s*' . $url . $layer . $supports . '([^;{}]*)/i', $css, $imports, PREG_SET_ORDER);
115+
116+
$urls = [];
117+
foreach ($imports as $import) {
118+
if ($import[1] !== '' && $import[2] === '' && $this->mediaQueryProcessor->matches($import[3])) {
119+
$urls[] = $import[1];
120+
}
98121
}
99122

100-
return $cssUrls;
123+
return $urls;
101124
}
102125

103126
/**
@@ -115,12 +138,10 @@ public function processExternalCssImports($stylesheetCss, $path, &$externalCss,
115138
$css = '';
116139

117140
$cssBasePath = preg_replace('/\/[^\/]*$/', '', $path) . '/';
118-
if (preg_match_all('/@import url\([\'\"]{0,1}(.*?\.css(\?\S+)?)[\'\"]{0,1}\)/si', $stylesheetCss, $cxtem)) {
119-
foreach ($cxtem[1] as $cxtembedded) {
120-
// path is relative to original stylesheet!!
121-
$externalCss[] = Path::relativeToAbsolutePath($cxtembedded, $cssBasePath);
122-
$externalCssCount++;
123-
}
141+
foreach ($this->extractImportUrls($stylesheetCss) as $cxtembedded) {
142+
// path is relative to original stylesheet!!
143+
$externalCss[] = Path::relativeToAbsolutePath($cxtembedded, $cssBasePath);
144+
$externalCssCount++;
124145
}
125146

126147
$css .= ' ' . $this->resolveBackgroundUrls($stylesheetCss, $cssBasePath);

‎src/Css/CssParser.php‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -117,8 +117,8 @@ public function __construct(
117117
) {
118118
$this->mpdf = $mpdf;
119119
$this->normalizeProperties = new NormalizeProperties($mpdf, $sizeConverter, $colorConverter);
120-
$this->cssLoader = new CssLoader($mpdf, $assetFetcher, $cache);
121-
$this->mediaQueryProcessor = new MediaQueryProcessor($mpdf);
120+
$this->mediaQueryProcessor = new MediaQueryProcessor($mpdf, $sizeConverter);
121+
$this->cssLoader = new CssLoader($mpdf, $assetFetcher, $cache, $this->mediaQueryProcessor);
122122
$this->atRuleProcessor = new AtRuleProcessor($this->mediaQueryProcessor);
123123
$this->commentParser = new CommentParser();
124124
$this->inlineStyleParser = new InlineStyleParser($this->normalizeProperties);

0 commit comments

Comments
 (0)