Skip to content

Advanced Features

Beyond basic HTML-to-PDF rendering, the Artisan package provides utilities for merging documents, injecting global styles, capturing screenshots, and fine-tuning Chrome behavior.

PDF Merging

The PdfMerger class combines multiple HTML sources into a single PDF document. Each source is rendered as a separate section, and the results are concatenated in order.

php
use Yeeefang\TcpdfNext\Artisan\PdfMerger;
use Yeeefang\TcpdfNext\Artisan\RenderOptions;

$merger = PdfMerger::create();

$merger
    ->addHtml('<h1>Cover Page</h1><p>Annual Report 2026</p>')
    ->addFile('/templates/chapter-1.html')
    ->addFile('/templates/chapter-2.html')
    ->addUrl('https://charts.example.com/annual-summary')
    ->addHtml('<h1>Appendix</h1><p>Supporting data tables.</p>');

$merger->save('/reports/annual-2026.pdf');

Per-Section Options

Each section can have its own RenderOptions. For example, a cover page in landscape and chapters in portrait.

php
$coverOptions = RenderOptions::create()
    ->setPageSize('A4')
    ->setLandscape(true)
    ->setPrintBackground(true);

$chapterOptions = RenderOptions::create()
    ->setPageSize('A4')
    ->setLandscape(false)
    ->setDisplayHeaderFooter(true)
    ->setFooterTemplate('
        <div style="font-size: 8px; text-align: center; width: 100%; color: #888;">
            Page <span class="pageNumber"></span>
        </div>
    ');

PdfMerger::create()
    ->addHtml('<h1>Cover</h1>', options: $coverOptions)
    ->addFile('/templates/chapter-1.html', options: $chapterOptions)
    ->addFile('/templates/chapter-2.html', options: $chapterOptions)
    ->save('/reports/merged.pdf');

CSS Injection

The StyleInjector class prepends CSS rules to the rendered page. This is useful for applying a global brand stylesheet to templates you do not control.

php
use Yeeefang\TcpdfNext\Artisan\HtmlRenderer;
use Yeeefang\TcpdfNext\Artisan\StyleInjector;

$injector = StyleInjector::create()
    ->addCss('
        body {
            font-family: "Inter", "Noto Sans TC", sans-serif;
            font-size: 11pt;
            line-height: 1.6;
            color: #333;
        }
        h1 { color: #1a237e; }
    ')
    ->addCssFile('/styles/brand.css');

HtmlRenderer::create()
    ->loadFile('/templates/report.html')
    ->withStyleInjector($injector)
    ->save('/output/branded-report.pdf');

Multiple Style Layers

Styles are injected in the order they are added. Later rules override earlier ones, following standard CSS specificity.

php
$injector = StyleInjector::create()
    ->addCssFile('/styles/reset.css')
    ->addCssFile('/styles/brand.css')
    ->addCss('table { page-break-inside: avoid; }');  // overrides

Screenshots

The ScreenshotCapture class renders HTML to image formats instead of PDF. Useful for generating thumbnails, social media previews, or visual regression testing.

php
use Yeeefang\TcpdfNext\Artisan\ScreenshotCapture;

// Full page screenshot as PNG
ScreenshotCapture::create()
    ->loadHtml('<h1>Preview</h1><p>This will be a PNG image.</p>')
    ->fullPage(true)
    ->format('png')
    ->save('/output/preview.png');

JPEG with Quality

php
ScreenshotCapture::create()
    ->loadUrl('https://example.com/dashboard')
    ->format('jpeg')
    ->quality(85)
    ->save('/output/dashboard.jpg');

Viewport Configuration

php
ScreenshotCapture::create()
    ->loadFile('/templates/email.html')
    ->viewport(width: 1200, height: 800)
    ->deviceScaleFactor(2)  // retina
    ->fullPage(false)
    ->save('/output/email-preview.png');

Chrome Configuration

Custom Binary Path

Artisan auto-detects Chrome on common OS paths. Override with chromePath.

php
use Yeeefang\TcpdfNext\Artisan\HtmlRenderer;

$renderer = HtmlRenderer::create(
    chromePath: '/opt/google/chrome/chrome',
);

Or set the CHROME_PATH environment variable globally.

Headless Mode Flags

Artisan passes --headless=new by default (Chrome 112+). You can add extra flags for specific environments.

php
$renderer = HtmlRenderer::create(
    chromeFlags: [
        '--no-sandbox',            // required in Docker
        '--disable-gpu',           // recommended in Docker
        '--disable-dev-shm-usage', // avoid /dev/shm issues
        '--font-render-hinting=none',
    ],
);

Connection Pooling

For high-throughput scenarios, reuse a single Chrome instance across multiple renders. This eliminates the startup cost (approximately 300--500 ms) for each subsequent render.

php
use Yeeefang\TcpdfNext\Artisan\ChromeBridge;
use Yeeefang\TcpdfNext\Artisan\HtmlRenderer;

// Create a persistent bridge
$bridge = ChromeBridge::create(chromePath: '/usr/bin/chromium');

// Reuse across multiple renders
foreach ($reports as $report) {
    HtmlRenderer::createWithBridge($bridge)
        ->loadHtml($report->html)
        ->save("/output/{$report->id}.pdf");
}

// Explicitly close when done
$bridge->close();

Error Handling

All Artisan exceptions extend Yeeefang\TcpdfNext\Artisan\Exceptions\ArtisanException.

php
use Yeeefang\TcpdfNext\Artisan\Exceptions\RenderException;
use Yeeefang\TcpdfNext\Artisan\Exceptions\ChromeNotFoundException;
use Yeeefang\TcpdfNext\Artisan\Exceptions\TimeoutException;

try {
    HtmlRenderer::create()->loadUrl($url)->save($path);
} catch (ChromeNotFoundException $e) {
    // Install Chrome or set CHROME_PATH
} catch (TimeoutException $e) {
    // Increase timeout or check network
} catch (RenderException $e) {
    // Inspect $e->getMessage() for details
}
ExceptionCommon Cause
ChromeNotFoundExceptionChrome not installed, CHROME_PATH incorrect
TimeoutExceptionSlow page, unresolved JS promises, network issues
RenderExceptionInvalid HTML, Chrome crash, disk write failure

Performance Tips

  1. Reuse Chrome instances -- Use ChromeBridge for batch operations.
  2. Minimize JavaScript -- The less JS Chrome must execute, the faster the render.
  3. Inline critical CSS -- Avoid external stylesheet fetches when possible.
  4. Set a tight timeout -- Fail fast on broken pages rather than blocking the queue.
  5. Use setPrintBackground(false) -- Skip background rendering when you do not need it.

Next Steps

  • Render Options -- Page size, margins, and header/footer templates.
  • Docker Setup -- Running Artisan in containerized environments.
  • Overview -- Package summary and installation.

Released under the LGPL-3.0-or-later License.