Snappy Documentation

repository·master·Indexed 26 days ago

https://github.com/knplabs/snappy

A PHP library that acts as a wrapper around the wkhtmltopdf and wkhtmltoimage binaries. It enables developers to generate PDFs, snapshots, or thumbnails from URLs or HTML content, featuring support for custom options, headers, footers, and Table of Contents.

Tokens
4.1K
Snippets
12
Records
23
Agent score
89%

What's inside Snappy

  1. Resolve relative links and media URLs in PDF

    master

    When converting HTML files that use relative links or media URLs, you must either:

    1. Convert all links/URLs to absolute paths.
    2. Use the <base> HTML tag to specify the base URL for the document.
  2. Debug Snappy commands and execution

    master
    To inspect the exact commands Snappy is executing, including environment variables, timeouts, stdout, and stderr, install a PSR-3 compliant logging library and call the setLogger() method on your generator instance.
  3. Install wkhtmltopdf binaries via Composer

    master

    If you do not have wkhtmltopdf installed on your system, you can install static binaries as Composer dependencies. Note that these are extracted from Debian 7 packages and may not be compatible with non-Debian Linux distributions.

    # For i386 systems
    composer require h4cc/wkhtmltopdf-i386 0.12.x
    composer require h4cc/wkhtmltoimage-i386 0.12.x
    
    # For 64-bit systems
    composer require h4cc/wkhtmltopdf-amd64 0.12.x
    composer require h4cc/wkhtmltoimage-amd64 0.12.x
  4. Fix broken tables and page breaks in PDF

    master

    To prevent tables from breaking incorrectly across pages, use proper <thead> and <tbody> tags and apply the following CSS:

    table { page-break-inside:auto; }
    tr    { page-break-inside:avoid; page-break-after:auto; }
    thead { display:table-header-group; }
    tfoot { display:table-footer-group; }

    To manually force a page break, use the CSS page-break-after: always; on a container element:

    <style type="text/css">
        .page {
            overflow: hidden;
            page-break-after: always;
        }
    </style>
    
    <div class="page">
       new page
    </div>
  5. Add headers and footers to every page

    master

    To add a header or footer to every page, provide either a valid file path or an HTML string via the header-html or footer-html options.

    Important requirements:

    1. The HTML content for headers/footers must start with a valid doctype and include <html>, <head>, and <body> tags.
    2. If providing a file path for a footer, ensure it has an .html extension to avoid 'unknown error' exit codes.
    3. This feature may not work with wkhtmltopdf versions compiled against unpatched Qt (common in Linux distributions). Use the official version from wkhtmltopdf.org for best results.
    <?php
    require __DIR__ . '/vendor/autoload.php';
    
    $header = <<<HTML
    <!DOCTYPE html>
    <html
      <head><style type="text/css">p { color: #FF0000; }</style></head>
      <body><p>Lorem ipsum</p></body>
    </html>
    HTML;
    
    $footer = <<<HTML
    <!DOCTYPE html>
    <html
      <head><style type="text/css">p { color: #0000FF; }</style></head>
      <body><p>Lorem ipsum</p></body>
    </html>
    HTML;
    
    // Use a temporary file with .html extension for the footer path
    $footerPath = tempnam('/tmp', 'footer') . '.html';
    file_put_contents($footerPath, $footer);
    
    $pdf = new \Knp\Snappy\Pdf(__DIR__ . '/vendor/bin/wkhtmltopdf-amd64');
    $pdf->generateFromHtml('', '/tmp/out/test.pdf', ['header-html' => $header, 'footer-html' => $footerPath], true);
  6. Resolve 'cannot connect to X server' errors

    master
    If you encounter wkhtmltopdf: cannot connect to X server, ensure you are using wkhtmltopdf >= 0.12.2, which no longer requires an X server or emulation. If you cannot update, you may need to use xvfb to provide a virtual X server.
  7. Fix character encoding and accent rendering

    master

    To ensure accented characters and UTF-8 symbols render correctly:

    1. Include <meta charset="UTF-8" /> in your HTML document.
    2. Pass the encoding option as utf-8 to the generator.

    If accents in options (like footer-right) are being mangled (e.g., 'Página' becoming 'Página'), set the server locale using setlocale(LC_CTYPE, 'your_locale.UTF-8'). Ensure the locale is actually installed on your server by running locale -a.

  8. Handle ContentNotFoundError and other wkhtmltopdf errors

    master
    When wkhtmltopdf returns an error code (such as 1 for ContentNotFoundError), the generate method will throw a RuntimeException. You should catch this exception and check the error code to handle the failure appropriately.
  9. Generate a single PDF from multiple sources

    master

    You can generate a single PDF from multiple URLs or multiple HTML strings by passing an array of inputs to the generate() or generateFromHtml() methods instead of a single string.

    <?php
    
    $pdf = new \Knp\Snappy\Pdf(__DIR__ . '/vendor/bin/wkhtmltopdf-amd64');
    $pdf->generate(['https://google.com', 'https://google.jp'], '/tmp/out/test.pdf');
    // or
    $pdf->generateFromHtml(['<html><body>Doc 1</body></html>', '<html><body>Doc 2</body></html>'], '/tmp/out/test.pdf');
  10. Merge multiple URLs into a single PDF

    master

    Pass an array of URLs to getOutput() to combine them into one continuous PDF document.

    $snappy = new Pdf('/usr/local/bin/wkhtmltopdf');
    header('Content-Type: application/pdf');
    header('Content-Disposition: attachment; filename="file.pdf"');
    echo $snappy->getOutput(array('http://www.github.com','http://www.knplabs.com','http://www.php.net'));
  11. Generate a PDF with a Table of Contents and custom XSL stylesheet

    master

    To create a PDF with a Table of Contents (TOC) using a custom XSL stylesheet, enable the toc option and provide the path to your .xsl file via xsl-style-sheet.

    <?php
    $snappy = new Pdf('/path/to/binary');
    
    $snappy->setOption('toc', true);
    $snappy->setOption('xsl-style-sheet', 'http://path/to/stylesheet.xsl'); // or local file
    
    $snappy->generateFromHtml('<p>Some content</p>', 'test.pdf');