This file provides guidance to coding agents when working with code in this repository.
mPDF is a PHP library that generates PDF files from UTF-8 encoded HTML. It descends from FPDF and
HTML2FPDF. Published as mpdf/mpdf on Packagist, licensed GPL-2.0-only. Docs live at
https://mpdf.github.io (the mpdf/mpdf.github.io repo, not this one).
The default branch is development, not master. PRs go there except for backports.
composer install # also chmods ./tmp to 0777 via post-install-cmd
composer test # PHPUnit; snapshot group excluded by default
composer test -- --group=snapshot # snapshot tests only (needs ext-imagick + ghostscript)
composer coverage # --coverage-text, needs xdebug
composer cs # phpcs, PSR-2-with-tabs ruleset over src utils tests
composer cs:fix # phpcbf
vendor/bin/phpstan # level 2 over src/, uses phpstan-baseline.neonPHPStan is not in require-dev — CI installs phpstan/phpstan:^2.0 on the fly. Install it
yourself before running static analysis locally, do not commit the change.
Running a single test or a subset:
vendor/bin/phpunit tests/Issues/Issue2181Test.php
vendor/bin/phpunit --filter testSomeMethod tests/Mpdf/MpdfTest.php
vendor/bin/phpunit tests/Mpdf/Css- PHP 5.6 is the floor (
^5.6 || ^7.0 || ~8.0–8.5), and CI runs all 12 versions on Ubuntu and Windows.src/contains no??, no arrow functions, no typed properties, no return types — keep it that way. Useisset()/ternaries,list()destructuring, and docblock@var/@paramtypes. - Indentation is tabs, 4-wide (
ruleset.xml= PSR-2 withDisallowSpaceIndentand tabScopeIndent). Space indentation failscomposer cs. - The
Stricttrait (src/Strict.php, used byMpdf,Tag, and most services) makes reading or writing an undeclared property throwMpdfException. Declare a property before assigning to it. - Every PR should add a
CHANGELOG.mdentry under the currentmPDF 8.3.xsection (New features / Bugfixes), and a test where possible. - Where applicable, docs should also be updated with more significant code changes and proposed as a separate PR in their own repository.
- Create a separate aptly named branch for the work.
- Commit changes in small self-contained chunks.
- Do not use excessive comments, comment in code only when absolutely necessary.
- Commit messages themselves have to fit to a single line.
- Always acknowledge used model in the third line of the commit message when AI was used.
src/Mpdf.php is ~27.5k lines and holds nearly all rendering state as public properties. It is not
being decomposed by class extraction so much as by service extraction.
Mpdf::__construct() builds config (initConfig() merging Config/ConfigVariables.php +
Config/FontVariables.php with the user's $config array), then calls
ServiceFactory::getServices(). That returns an array keyed by property name; the constructor loops
and does $this->{$key} = $service, recording the names in $this->services. So collaborators like
$this->cssManager, $this->otl, $this->writer, $this->colorConverter appear as properties with
no constructor parameter — grep ServiceFactory to find where any of them is built.
An optional second constructor argument, a Mpdf\Container\ContainerInterface, lets callers override
httpClient, localContentLoader, and assetFetcher. This is the only supported extension seam for
services; ServiceFactory checks $container->has(...) for exactly those keys.
WriteHTML($html, $mode, $init, $close)(~line 13182) is the entry point.$modecomes fromHTMLParserMode—DEFAULT_MODE(whole document),HEADER_CSS(stylesheet only),HTML_BODY, plus two@internalmodes for non-writing parses and header buffering.- Charset detection (
ReadCharset),purify_utf8, meta tags,<base href>. CssManager::readCss()strips stylesheets out of the HTML and parses them.CssManageris a thin facade overCss\CssParser(parse) andCss\CssMerger(cascade/specificity), recently refactored — note that call sites inMpdf.phpstill use the old casing (ReadCSS,MergeCSS), which works only because PHP method names are case-insensitive. Parsed rules live in the public$CSS/$cascadeCSS/$tablecascadeCSSarrays;mergeCss($inherit, $tag, $attr)resolves the cascade for one element.- The HTML is tokenized and each tag dispatches through
Tag::OpenTag()/CloseTag(), which resolve a handler class via the static map inTag::getTagClassName()→src/Tag/*.php(one class per HTML element, e.g.Tag\Div,Tag\Table, plus mPDF-specific ones likeTag\Barcode,Tag\DotTab,Tag\PageHeader,Tag\IndexEntry). Adding element support means adding a class insrc/Tag/and, if the class name differs from the uppercased tag, an entry in that map. - Text accumulates in
$this->textbuffer, then flows through line-breaking, justification, andsrc/Otl.php(~6.2k lines) for OpenType layout: GSUB/GPOS, bidi, and the complex-script shapers insrc/Shaper/(Indic, Myanmar, Sea). src/Writer/*emit the actual PDF objects — one writer per concern (FontWriter,ImageWriter,PageWriter,MetadataWriter,BookmarkWriter, …), all coordinating throughBaseWriter, which appends toBuffer(an array-backed buffer, for memory).Output()/OutputFile()/OutputHttpInline()/OutputBinaryData()finish the document;Output\Destinationholds the destination constants.
Fonts\FontFileFinder locates TTFs under the configured fontDir; TTFontFile parses them;
Fonts\MetricsGenerator produces metrics, and Fonts\FontCache (wrapping Cache) persists parsed
font data under <tempDir>/mpdf/ttfontdata. Font families and their file mappings are declared in
Config/FontVariables.php; bundled fonts live in ttfonts/ and data/font/. Subsetting is on by
default. Language\LanguageToFont + Language\ScriptToLanguage drive autoLangToFont /
autoScriptToLang.
src/Image/—ImageProcessorplus decoders for BMP, WMF, SVG (Image\Svgis a full SVG renderer), withsrc/Gif/for GIF.ImageTypeGuessersniffs formats.src/Barcode/— one class per symbology behindBarcodeInterface/AbstractBarcode; 2D QR codes come from the optionalmpdf/qrcodepackage.src/Color/—ColorConverteris the single entry point;ColorSpaceRestrictorenforces PDF/A and PDF/X colorspace rules.src/Conversion/DecTo*— list numbering systems (roman, alpha, greek, hebrew, CJK, other).src/FpdiTrait.php+setasign/fpdi— importing pages from existing PDFs.src/Pdf/Protection.php— encryption and permissions.data/— runtime data files loaded withrequire:upperCase.php,entity_substitutions.php,CJKdata.php, collation tables, hyphenationpatterns/, ICC profiles,mpdf.css(the default stylesheet).utils/— standalone CLI/browser scripts for inspecting fonts and images; not part of the distributed package (export-ignore).
Three suites, all under tests/ with PSR-4 roots Mpdf\ → tests/Mpdf, Issues\ → tests/Issues,
Snapshots\ → tests/Snapshots.
tests/Mpdf/— unit tests per class, mirroringsrc/. Most extendMpdf\BaseMpdfTest, which constructsnew Mpdf(['mode' => 'c'])inset_up()and callscleanup()intear_down().tests/Issues/IssueNNNNTest.php— regression tests named after the GitHub issue number. This is the conventional home for a bugfix test.tests/Snapshots/— subclasses ofSnapshots\SnapshotimplementinggetId()andgeneratePdf()(which sets$this->mpdf; do not callOutput*()in it). The base class renders the PDF, converts both it andtests/data/snapshots/<id>.pdfto PNGs via Imagick, and compares page by page withMETRIC_ABSOLUTEERRORMETRICagainstgetComparisonFuzzyLimit(). Failures dump diff images and the generated PDF into<tempDir>/artifacts/.
Snapshot tests carry @group snapshot and are excluded by phpunit.xml, because they need
ext-imagick, ghostscript, and an ImageMagick policy that permits PDF reads. They run in their own
CI workflow on PHP 8.5. Committed baseline PDFs — not images — are the fixtures, since Imagick
versions rasterize differently.
Test base classes use Yoast\PHPUnitPolyfills\TestCases\TestCase, hence the snake_case
set_up()/tear_down() hooks, which keep the suite runnable from PHPUnit 5 through 9.
tests/bootstrap.php instantiates an Mpdf once so its constants are defined for every test.
Five GitHub Actions workflows on pull_request and pushes to development/master/test:
tests.yml (12 PHP versions × Ubuntu/Windows), cs.yml (PHP 7.4), static-analysis.yml (PHP 8.2),
snapshots.yml (PHP 8.5 + imagick), coverage.yml (PHP 7.4 + xdebug, development only).
composer.lockis gitignored — the library is tested against floating dependencies.tmp/is the default temp dir and must be writable; mPDF cleans up old files there, so a dedicated path is recommended for real use (tempDirconfig).- Fetching remote assets is unreliable under single-threaded servers such as
php -S.