Skip to content

HTML Renderer

A classe HtmlRenderer é o ponto de entrada principal para todas as operações de HTML para PDF. Ela fornece uma API fluente para carregar conteúdo, configurar a saída e renderizar documentos PDF.

Método de Fábrica

Crie uma instância do renderer com o método estático create().

php
use Yeeefang\TcpdfNext\Artisan\HtmlRenderer;

// Default configuration (auto-detects Chrome)
$renderer = HtmlRenderer::create();

// With a custom Chrome binary path
$renderer = HtmlRenderer::create(
    chromePath: '/usr/bin/google-chrome',
);

// With a custom temporary directory
$renderer = HtmlRenderer::create(
    chromePath: '/usr/bin/chromium',
    tempDir: '/tmp/artisan-render',
);

Carregando Conteúdo

A Partir de uma String

Passe HTML bruto diretamente com loadHtml(). A string pode ser um documento HTML completo ou um fragmento.

php
$renderer->loadHtml('<h1>Hello, World!</h1>');

Quando você passa um fragmento, o Artisan o encapsula automaticamente em um documento <!DOCTYPE html> mínimo.

A Partir de um Arquivo Local

Carregue um arquivo .html do disco com loadFile(). Caminhos relativos para folhas de estilo, imagens e scripts dentro do arquivo são resolvidos a partir do diretório do arquivo.

php
$renderer->loadFile('/templates/quarterly-report.html');

A Partir de uma URL

Busque e renderize uma URL ativa com loadUrl(). A página é carregada dentro do Chrome headless, então o JavaScript executa e chamadas AJAX são resolvidas antes da renderização.

php
$renderer->loadUrl('https://reports.example.com/q4-2026');

Você pode definir um timeout de navegação para evitar travamentos em páginas lentas:

php
$renderer->loadUrl('https://example.com/dashboard', timeoutMs: 30000);

Métodos de Saída

Salvar em Arquivo

php
$renderer->save('/output/report.pdf');

Obter como String

Recupere os bytes brutos do PDF para processamento adicional (ex: armazenar em banco de dados, anexar a um email).

php
$pdfContent = $renderer->toString();

// Example: store in database
DB::table('documents')->insert([
    'name'    => 'report.pdf',
    'content' => $pdfContent,
]);

Enviar para o Navegador

Transmita o PDF diretamente para a resposta HTTP com os cabeçalhos apropriados.

php
// Inline display (browser PDF viewer)
$renderer->output('report.pdf', 'inline');

// Force download
$renderer->output('report.pdf', 'download');

Exemplo Completo: Fatura

php
use Yeeefang\TcpdfNext\Artisan\HtmlRenderer;

$html = <<<'HTML'
<!DOCTYPE html>
<html>
<head>
    <style>
        body { font-family: 'Inter', sans-serif; margin: 20mm; }
        .header { display: flex; justify-content: space-between; align-items: flex-start; }
        .company { font-size: 24px; font-weight: 700; color: #1a237e; }
        .meta { text-align: right; color: #666; font-size: 13px; }
        .grid { display: grid; grid-template-columns: 1fr 1fr; gap: 20px; margin: 30px 0; }
        .grid section { padding: 15px; background: #f8f9fa; border-radius: 6px; }
        table { width: 100%; border-collapse: collapse; margin-top: 20px; }
        th { background: #1a237e; color: white; padding: 10px 12px; text-align: left; }
        td { border-bottom: 1px solid #e0e0e0; padding: 10px 12px; }
        tr:nth-child(even) { background: #fafafa; }
        .total { font-weight: 700; font-size: 18px; text-align: right; margin-top: 20px; }
    </style>
</head>
<body>
    <div class="header">
        <div class="company">Acme Corporation</div>
        <div class="meta">
            Invoice #2026-001<br>
            Date: 2026-02-16<br>
            Due: 2026-03-16
        </div>
    </div>
    <div class="grid">
        <section>
            <strong>Bill To</strong><br>
            Jane Smith<br>
            456 Oak Avenue<br>
            Springfield, IL 62704
        </section>
        <section>
            <strong>Ship To</strong><br>
            Jane Smith<br>
            789 Elm Street<br>
            Springfield, IL 62704
        </section>
    </div>
    <table>
        <thead>
            <tr>
                <th>Item</th>
                <th>Qty</th>
                <th>Unit Price</th>
                <th>Amount</th>
            </tr>
        </thead>
        <tbody>
            <tr><td>Web Development</td><td>40 hrs</td><td>$150.00</td><td>$6,000.00</td></tr>
            <tr><td>UI/UX Design</td><td>20 hrs</td><td>$125.00</td><td>$2,500.00</td></tr>
            <tr><td>Annual Hosting</td><td>1</td><td>$1,200.00</td><td>$1,200.00</td></tr>
        </tbody>
    </table>
    <div class="total">Total: $9,700.00</div>
</body>
</html>
HTML;

HtmlRenderer::create()
    ->loadHtml($html)
    ->save('/invoices/2026-001.pdf');

Encadeamento de Métodos

Todo setter no HtmlRenderer retorna $this, habilitando um padrão fluente de builder.

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

HtmlRenderer::create()
    ->loadFile('/templates/report.html')
    ->withOptions(
        RenderOptions::create()
            ->setPageSize('A4')
            ->setLandscape(false)
            ->setMargins(top: 15, right: 10, bottom: 15, left: 10)
            ->setPrintBackground(true)
    )
    ->withStyleInjector(
        StyleInjector::create()
            ->addCss('body { font-size: 12pt; }')
    )
    ->save('/output/styled-report.pdf');

Tratamento de Erros

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

try {
    HtmlRenderer::create()
        ->loadUrl('https://example.com/slow-report')
        ->save('/output/report.pdf');
} catch (ChromeNotFoundException $e) {
    // Chrome binary not found -- check CHROME_PATH
    logger()->error('Chrome not installed: ' . $e->getMessage());
} catch (TimeoutException $e) {
    // Page took too long to load or render
    logger()->warning('Render timed out: ' . $e->getMessage());
} catch (RenderException $e) {
    // Any other rendering failure
    logger()->error('Render failed: ' . $e->getMessage());
}

Próximos Passos

Distribuído sob a licença LGPL-3.0-or-later.