Skip to content

Commit b465e51

Browse files
jakejackson1claude
andcommitted
Keep a PDF/A-1b document to what PDF/A-1 allows of fonts, SVG opacity, shadow blur and annotation colours (#346)
veraPDF rejected PDF/A-1b documents on five rules: - 6.3.5-3: a CID font subset now carries a CIDSet naming each CID its CIDToGIDMap maps, and .notdef. Written only under PDF/A-1. - 6.3.7-3: a font subset written as a symbolic TrueType font leaves out its format 6 (1,0) cmap subtable under PDF/A-1, keeping the (3,0) one. - 6.4-5/6.4-6: SVG opacity, fill-opacity and stroke-opacity go through Mpdf::allowedAlpha(), as SetAlpha() does, so they paint opaque where transparency is not allowed. - 6.4-1: a blurred box-shadow fades out through a soft mask, so without transparency it is drawn unblurred, with its edge at the blur's midpoint. - 6.5.3-3: an annotation carries no /C under PDF/A-1 with a CMYK output intent; its appearance still has the colour. PdfaConformanceTest now validates its documents at 1-B too. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
1 parent c93b66a commit b465e51

8 files changed

Lines changed: 435 additions & 36 deletions

File tree

‎src/Fonts/FontSubsetter.php‎

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -403,22 +403,23 @@ private function buildSubset(array $subset, $useOTL)
403403
* @param int $TTCfontID Which font of a TrueType Collection, or 0 for a plain font
404404
* @param bool $debug Whether to check the font's own tables as they are read
405405
* @param int $useOTL Whether the document laid the font out with its OTL tables
406+
* @param bool $oneCmapSubtable Whether the cmap may hold only its (3,0) subtable, as PDF/A-1 requires
406407
*
407408
* @return string The font program to embed
408409
*
409410
* @throws \Mpdf\Exception\FontException Where the font carries no Unicode cmap to read, or subsets
410411
* into more segments than the format 4 subtable's length
411412
* field can state
412413
*/
413-
public function makeSubsetSIP($file, array $subset, $TTCfontID = 0, $debug = false, $useOTL = 0)
414+
public function makeSubsetSIP($file, array $subset, $TTCfontID = 0, $debug = false, $useOTL = 0, $oneCmapSubtable = false)
414415
{
415416
$this->open($file);
416417

417418
// Closed however the build ends: see makeSubset
418419
try {
419420
$this->readTableDirectory($TTCfontID, $debug);
420421

421-
return $this->buildSubsetSIP($subset, $TTCfontID, $useOTL);
422+
return $this->buildSubsetSIP($subset, $TTCfontID, $useOTL, $oneCmapSubtable);
422423
} finally {
423424
$this->reader->close();
424425
}
@@ -427,7 +428,7 @@ public function makeSubsetSIP($file, array $subset, $TTCfontID = 0, $debug = fal
427428
/**
428429
* @return string See makeSubsetSIP
429430
*/
430-
private function buildSubsetSIP(array $subset, $TTCfontID, $useOTL)
431+
private function buildSubsetSIP(array $subset, $TTCfontID, $useOTL, $oneCmapSubtable)
431432
{
432433
list($indexToLocFormat, $numberOfHMetrics, $numGlyphs) = $this->readHeaders();
433434

@@ -558,11 +559,12 @@ private function buildSubsetSIP(array $subset, $TTCfontID, $useOTL)
558559
// cmap - Character to glyph mapping
559560
$format6Length = 10 + 2 * count($subset);
560561

561-
if ($format6Length > 0xFFFF) {
562+
if ($format6Length > 0xFFFF || $oneCmapSubtable) {
562563
// A format 6 subtable states its length in a uint16, so past 32,762 characters it cannot be
563564
// written. It maps the same codes to the same glyphs as the format 4 subtable, and a reader
564565
// looks a symbolic TrueType font's codes up in (3,0) before (1,0) (ISO 32000-1, 9.6.6.4),
565-
// so leave (1,0) out rather than refuse a font the format 4 subtable maps whole.
566+
// so leave (1,0) out rather than refuse a font the format 4 subtable maps whole, or one
567+
// PDF/A-1 allows a single subtable.
566568
$cmapstr = TableWriter::uint16s([0, 1, 3, 0]) . TableWriter::uint32(12) . $cmapstr4;
567569
} else {
568570
$cmapstr = TableWriter::uint16s([0, 2, 1, 0]) . TableWriter::uint32(20)

‎src/Image/Svg.php‎

Lines changed: 21 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1512,9 +1512,7 @@ function svgStyle($critere_style, $attribs, $element)
15121512
} elseif ($critere_style['fill-opacity'] < 0) {
15131513
$opacity = 0;
15141514
}
1515-
$gs = $this->mpdf->AddExtGState(['ca' => $opacity, 'BM' => '/Normal']);
1516-
$this->mpdf->extgstates[$gs]['fo'] = true;
1517-
$path_style .= sprintf(' /GS%d gs ', $gs);
1515+
$path_style .= $this->opacityState(['ca' => $opacity]);
15181516
}
15191517

15201518
if (isset($critere_style['stroke-opacity'])) {
@@ -1528,9 +1526,7 @@ function svgStyle($critere_style, $attribs, $element)
15281526
} elseif ($critere_style['stroke-opacity'] < 0) {
15291527
$opacity = 0;
15301528
}
1531-
$gs = $this->mpdf->AddExtGState(['CA' => $opacity, 'BM' => '/Normal']);
1532-
$this->mpdf->extgstates[$gs]['fo'] = true;
1533-
$path_style .= sprintf(' /GS%d gs ', $gs);
1529+
$path_style .= $this->opacityState(['CA' => $opacity]);
15341530
}
15351531

15361532
switch ($style) {
@@ -2436,9 +2432,7 @@ function svgText()
24362432
}
24372433
}
24382434

2439-
$gs = $this->mpdf->AddExtGState(['ca' => $fopacity, 'CA' => $sopacity, 'BM' => '/Normal']);
2440-
$this->mpdf->extgstates[$gs]['fo'] = true;
2441-
$opacitystr = sprintf(' /GS%d gs ', $gs);
2435+
$opacitystr = $this->opacityState(['ca' => $fopacity, 'CA' => $sopacity]);
24422436

24432437
$fillstr = '';
24442438
if (isset($current_style['fill']) && $current_style['fill'] != 'none') {
@@ -2612,9 +2606,7 @@ function svgText()
26122606
}
26132607
}
26142608

2615-
$gs = $this->mpdf->AddExtGState(['ca' => $fopacity, 'CA' => $sopacity, 'BM' => '/Normal']);
2616-
$this->mpdf->extgstates[$gs]['fo'] = true;
2617-
$opacitystr = sprintf(' /GS%d gs ', $gs);
2609+
$opacitystr = $this->opacityState(['ca' => $fopacity, 'CA' => $sopacity]);
26182610

26192611
$fillstr = '';
26202612

@@ -4186,6 +4178,23 @@ function xml_svg2pdf_end($parser, $name)
41864178
}
41874179
}
41884180

4181+
/**
4182+
* The operator that sets the fill (ca) and stroke (CA) opacities given, painting opaque where the document does
4183+
* not allow transparency
4184+
*
4185+
* @param float[] $alphas
4186+
*
4187+
* @return string
4188+
*/
4189+
private function opacityState(array $alphas)
4190+
{
4191+
$alphas = array_map([$this->mpdf, 'allowedAlpha'], $alphas);
4192+
$gs = $this->mpdf->AddExtGState($alphas + ['BM' => '/Normal']);
4193+
$this->mpdf->extgstates[$gs]['fo'] = true;
4194+
4195+
return sprintf(' /GS%d gs ', $gs);
4196+
}
4197+
41894198
private function computeBezierBoundingBox($start, $c)
41904199
{
41914200
$P0 = [$start[0], $start[1]];

‎src/Mpdf.php‎

Lines changed: 47 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -2025,17 +2025,53 @@ public function pdfaConformance()
20252025
*/
20262026
public function transparencyAllowed()
20272027
{
2028-
if ($this->PDFX) {
2029-
return false;
2030-
}
2028+
return !$this->PDFX && $this->pdfaPart() !== '1';
2029+
}
20312030

2031+
/**
2032+
* The PDF/A part the document conforms to, or null when it is not PDF/A
2033+
*
2034+
* @return string|null
2035+
*/
2036+
public function pdfaPart()
2037+
{
20322038
if (!$this->PDFA) {
2033-
return true;
2039+
return null;
20342040
}
20352041

20362042
list($part) = $this->pdfaConformance();
20372043

2038-
return $part !== '1';
2044+
return $part;
2045+
}
2046+
2047+
/**
2048+
* The alpha the document may paint with: the one given, or opaque where transparency is not allowed
2049+
*
2050+
* @param float $alpha from 0 (transparent) to 1 (opaque)
2051+
*
2052+
* @return float
2053+
*/
2054+
public function allowedAlpha($alpha)
2055+
{
2056+
if ($alpha == 1 || $this->transparencyAllowed()) {
2057+
return $alpha;
2058+
}
2059+
2060+
$this->pdfaxWarning('Image opacity must be 100% (Opacity changed to 100%)');
2061+
2062+
return 1;
2063+
}
2064+
2065+
/**
2066+
* Records what a PDF/A or PDF/X document had to change, unless it was asked to make such changes silently
2067+
*
2068+
* @param string $message
2069+
*/
2070+
private function pdfaxWarning($message)
2071+
{
2072+
if (($this->PDFA && !$this->PDFAauto) || ($this->PDFX && !$this->PDFXauto)) {
2073+
$this->PDFAXwarnings[] = $message;
2074+
}
20392075
}
20402076

20412077
/**
@@ -2057,12 +2093,7 @@ function SetAlpha($alpha, $bm = 'Normal', $return = false, $mode = 'B')
20572093
// HardLight, SoftLight, Difference, Exclusion, Hue, Saturation, Color, Luminosity
20582094
// set alpha for stroking (CA) and non-stroking (ca) operations
20592095
// mode determines F (fill) S (stroke) B (both)
2060-
if (!$this->transparencyAllowed() && $alpha != 1) {
2061-
if (($this->PDFA && !$this->PDFAauto) || ($this->PDFX && !$this->PDFXauto)) {
2062-
$this->PDFAXwarnings[] = "Image opacity must be 100% (Opacity changed to 100%)";
2063-
}
2064-
$alpha = 1;
2065-
}
2096+
$alpha = $this->allowedAlpha($alpha);
20662097
$a = ['BM' => '/' . $bm];
20672098
if ($mode == 'F' || $mode == 'B') {
20682099
$a['ca'] = $alpha; // mPDF 5.7.2
@@ -17704,6 +17735,11 @@ function PaintDivBB($divider = '', $blockstate = 0, $blvl = 0)
1770417735
$shadow .= 'W n' . "\n";
1770517736

1770617737
$sh['blur'] = abs($sh['blur']); // cannot have negative blur value
17738+
// A blur fades out through a soft mask, so without transparency the shadow keeps the hard edge at the blur's midpoint
17739+
if ($sh['blur'] && !$this->transparencyAllowed()) {
17740+
$this->pdfaxWarning('A box-shadow cannot be blurred without transparency (Shadow drawn without blur)');
17741+
$sh['blur'] = 0;
17742+
}
1770717743
// Ensure spread/blur do not make effective shadow width/height < 0
1770817744
// Could do more complex things but this just adjusts spread value
1770917745
if (-$sh['spread'] + $sh['blur'] / 2 > min($w / 2, $h / 2)) {

‎src/Writer/FontWriter.php‎

Lines changed: 30 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -211,7 +211,7 @@ public function writeFonts()
211211

212212
$subset = $font['subsets'][$sfid];
213213
unset($subset[0]);
214-
$ttfontstream = $subsetter->makeSubsetSIP($font['ttffile'], $subset, $font['TTCfontID'], $this->mpdf->debugfonts, $font['useOTL']); // mPDF 5.7.1
214+
$ttfontstream = $subsetter->makeSubsetSIP($font['ttffile'], $subset, $font['TTCfontID'], $this->mpdf->debugfonts, $font['useOTL'], $this->mpdf->pdfaPart() === '1'); // mPDF 5.7.1
215215
$ttfontsize = strlen($ttfontstream);
216216
$fontstream = gzcompress($ttfontstream);
217217
$widthstring = '';
@@ -416,6 +416,12 @@ public function writeFonts()
416416
$this->writer->write(' /Style << /Panose ' . $this->writer->hexString($font['panose']) . ' >>');
417417
}
418418

419+
// PDF/A-1 requires a CIDSet of a subset, written after the font file
420+
$cidSet = $asSubset && $this->mpdf->pdfaPart() === '1';
421+
if ($cidSet) {
422+
$this->writer->write('/CIDSet ' . ($this->mpdf->n + 3) . ' 0 R');
423+
}
424+
419425
if ($asSubset) {
420426
$this->writer->write('/FontFile2 ' . ($this->mpdf->n + 2) . ' 0 R');
421427
} elseif ($font['fontkey']) {
@@ -470,12 +476,35 @@ public function writeFonts()
470476
$this->writer->write('endobj');
471477
unset($subsetter);
472478
}
479+
480+
if ($cidSet) {
481+
$this->writeCidSet(array_keys($codeToGlyph));
482+
}
473483
} else {
474484
throw new \Mpdf\MpdfException(sprintf('Unsupported font type: %s (%s)', $type, $name));
475485
}
476486
}
477487
}
478488

489+
/**
490+
* Writes a CIDSet stream: one bit per CID from 0, the high bit of the first byte first, set for each CID the
491+
* font program has a glyph for. CID 0 is always there, as .notdef.
492+
*
493+
* @param int[] $cids
494+
*/
495+
private function writeCidSet(array $cids)
496+
{
497+
$bits = str_repeat("\x00", (max($cids) >> 3) + 1);
498+
foreach (array_merge([0], $cids) as $cid) {
499+
$bits[$cid >> 3] = chr(ord($bits[$cid >> 3]) | (0x80 >> ($cid & 7)));
500+
}
501+
502+
$this->writer->object();
503+
$this->writer->write('<</Length ' . $this->writer->streamLength($bits) . '>>');
504+
$this->writer->stream($bits);
505+
$this->writer->write('endobj');
506+
}
507+
479508
/**
480509
* How much of a font the document drew, counted the way the font's own character count is.
481510
*

‎src/Writer/MetadataWriter.php‎

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -745,7 +745,10 @@ public function writeAnnotations() // _putannots
745745
}
746746

747747
$fill = $this->annotationFill($pl['opt']);
748-
$annot .= ' /C [' . preg_replace('/ (rg|g|k)$/', '', $fill) . ']';
748+
// PDF/A-1 allows /C only with an RGB output intent; the appearance still carries the colour
749+
if ($this->mpdf->pdfaPart() !== '1' || $this->mpdf->restrictColorSpace !== 3) {
750+
$annot .= ' /C [' . preg_replace('/ (rg|g|k)$/', '', $fill) . ']';
751+
}
749752

750753
// Kept apart, as a popup reuses $w and $h for its own size
751754
$appearanceWidth = $w;
@@ -776,7 +779,7 @@ public function writeAnnotations() // _putannots
776779

777780
if (!$fileAttachment) {
778781
// Subj is PDF 1.5 spec, after PDF/X-1a (PDF 1.3) and PDF/A-1 (PDF 1.4)
779-
if (isset($pl['opt']['subj']) && !$this->mpdf->PDFX && (!$this->mpdf->PDFA || $this->mpdf->pdfaConformance()[0] !== '1')) {
782+
if (isset($pl['opt']['subj']) && !$this->mpdf->PDFX && $this->mpdf->pdfaPart() !== '1') {
780783
$annot .= ' /Subj ' . $this->writer->utf16BigEndianTextString($pl['opt']['subj']);
781784
}
782785
if ($this->writesPopup($pl)) {

‎tests/Mpdf/Fonts/FontSubsetterCmapTest.php‎

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -116,6 +116,33 @@ public function format6Provider()
116116
];
117117
}
118118

119+
/**
120+
* PDF/A-1 allows a symbolic TrueType font one cmap subtable, so makeSubsetSIP can be asked to leave out the
121+
* format 6 one under (1,0) and keep the format 4 one readers look up first
122+
*
123+
* @dataProvider oneCmapSubtableProvider
124+
*/
125+
public function testMakeSubsetSipWritesOneSubtableWhenAsked($oneCmapSubtable, array $encodings)
126+
{
127+
$file = $this->file('angerthas');
128+
$program = $this->subsetter()->makeSubsetSIP($file, $this->pangram('angerthas'), 0, false, false, $oneCmapSubtable);
129+
130+
$this->assertSame($encodings, array_keys($this->encodingRecords($this->table($program, 'cmap'))));
131+
}
132+
133+
/**
134+
* Whether one subtable is asked for, and the encodings the cmap then lists
135+
*
136+
* @return mixed[][]
137+
*/
138+
public function oneCmapSubtableProvider()
139+
{
140+
return [
141+
'both subtables' => [false, ['1,0', '3,0']],
142+
'one subtable' => [true, ['3,0']],
143+
];
144+
}
145+
119146
/**
120147
* The three builders share one format 4 subtable, so its bytes are pinned here directly rather
121148
* than only through the golden masters' hashes of whole programs.

0 commit comments

Comments
 (0)