KnpSnappyBundle

repository·master·Indexed 23 days ago

https://github.com/knplabs/knpsnappybundle

A Symfony bundle providing a wrapper around the wkhtmltopdf utility to generate PDF documents and images from HTML content or URLs using the WebKit engine. It includes services for PDF and image generation (knp_snappy.pdf and knp_snappy.image) and provides specialized Symfony response objects like PdfResponse and JpegResponse for returning generated files directly from controllers.

Tokens
2.1K
Snippets
6
Records
10
Agent score
78%

What's inside KnpSnappyBundle

  1. Install KnpSnappyBundle

    master

    Install the bundle using Composer. If your Symfony project does not use Flex, you must manually register the bundle in your kernel configuration.

    composer require knplabs/knp-snappy-bundle
    // config/bundles.php
    <?php
    
    return [
        //...
        Knp\Bundle\SnappyBundle\KnpSnappyBundle::class => ['all' => true],
        //...
    ];
  2. Configure KnpSnappyBundle binaries and options

    master

    Use the knp_snappy configuration key to define the paths to the wkhtmltopdf and wkhtmltoimage binaries, enable/disable services, and pass specific options to the underlying tools.

    Note for Windows users: Use escaped double quotes for binary paths, e.g., "C:\\Program Files\\wkhtmltopdf\\bin\\wkhtmltopdf.exe".

    # config/packages/knp_snappy.yaml
    knp_snappy:
        pdf:
            enabled:    true
            binary:     /usr/local/bin/wkhtmltopdf
            options:    []
        image:
            enabled:    true
            binary:     /usr/local/bin/wkhtmltoimage
            options:    []
  3. Configure temporary folder and process timeout

    master

    You can customize the global settings for the bundle in config/packages/knp_snappy.yaml:

    • temporary_folder: The directory used for temporary files (defaults to sys_get_temp_dir()).
    • process_timeout: The timeout in seconds for the generation processes.
    # config/packages/knp_snappy.yaml
    knp_snappy:
        temporary_folder: "%kernel.cache_dir%/snappy"
        process_timeout: 20 # In seconds
  4. Return an image or PDF as a Symfony Response

    master

    To return a generated file directly as a web response from a controller, use getOutputFromHtml() in combination with JpegResponse or PdfResponse.

    use Knpundle\
    SnappyBundle\Snappy\Response\JpegResponse;
    use Knp\Bundle\SnappyBundle\Snappy\Response\PdfResponse;
    use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
    
    class SomeController extends AbstractController
    {
        public function imageAction(\Knp\Snappy\Image $knpSnappyImage)
        {
            $html = $this->renderView('MyBundle:Foo:bar.html.twig', ['some' => $vars]);
    
            return new JpegResponse(
                $knpSnappyImage->getOutputFromHtml($html),
                'image.jpg'
            );
        }
    
        public function pdfAction(\Knp\Snappy\Pdf $knpSnappyPdf)
        {
            $html = $this->renderView('MyBundle:Foo:bar.html.twig', ['some' => $vars]);
    
            return new PdfResponse(
                $knpSnappyPdf->getOutputFromHtml($html),
                'file.pdf'
            );
        }
    }
  5. Handle relative URLs in PDF generation

    master

    When generating a PDF from a URL, ensure that any internal links (like CSS or image files) use absolute URLs. You can use Symfony's generateUrl() with the third parameter set to true to ensure absolute paths are used.

    use Knpundle\\
    SnappyBundle\Snappy\Response\PdfResponse;
    use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
    
    class SomeController extends AbstractController
    {
        public function pdfAction(\Knp\Snappy\Pdf $knpSnappyPdf)
        {
            // use absolute path!
            $pageUrl = $this->generateUrl('homepage', array(), true);
    
            return new PdfResponse(
                $knpSnappyPdf->getOutput($pageUrl),
                'file.pdf'
            );
        }
    }
  6. Generate a PDF from Twig HTML content

    master

    Use the generateFromHtml() method on the Knp\Snappy\Pdf service to convert a rendered Twig view directly into a PDF file.

    // @var \Knp\Snappy\Pdf $knpSnappyPdf
    $knpSnappyPdf->generateFromHtml(
        $this->renderView(
            'MyBundle:Foo:bar.html.twig',
            ['some' => $vars]
        ),
        '/path/to/the/file.pdf'
    );
  7. Configure KnpSnappyBundle settings

    master

    The knp_snappy configuration key allows you to define global settings and specific configurations for PDF and Image generation.

    Global Settings

    • temporary_folder: Path to the folder used for temporary files.
    • process_timeout: The generator process timeout in seconds (minimum value is 1).

    PDF Configuration (pdf)

    • enabled: Boolean to enable/disable PDF generation (defaults to true).
    • binary: Path to the wkhtmltopdf binary (defaults to wkhtmltopdf).
    • options: An associative array of options passed to the binary. Note that underscores in keys are automatically converted to hyphens (e.g., lowez_quality becomes lowez-quality).
    • env: An associative array of environment variables to be passed to the process.

    Image Configuration (image)

    • enabled: Boolean to enable/disable image generation (defaults to true).
    • binary: Path to the wkhtmltoimage binary (defaults to wkhtmltoimage).
    • options: An associative array of options passed to the binary. Note that underscores in keys are automatically converted to hyphens.
    • env: An associative array of environment variables to be passed to the process.
  8. Instantiate a SnappyResponse

    master

    The SnappyResponse class is a specialized Symfony HttpFoundation Response used to return generated files (like PDFs or images) from a controller. It automatically handles setting the Content-Type and Content-Disposition headers.

    Constructor Parameters

    ParameterTypeDescription
    $contentmixedThe raw binary content of the generated file.
    $fileNamestringThe name of the file to be suggested in the headers.
    $contentTypestringThe MIME type of the content (e.g., application/pdf).
    $contentDispositionstringHow the browser should handle the file. Must be either inline or attachment.
    $statusintHTTP status code (defaults to 200).
    $headersarrayAdditional HTTP headers.
    $fileNameFallBackstringA fallback filename if the primary one is unavailable.
  9. Create a PdfResponse object

    master

    The PdfResponse class is used to wrap PDF content into a Symfony-compatible response object. This allows you to return a PDF directly from a controller.

    Constructor parameters:

    • $content (mixed): The raw PDF content.
    • $fileName (string): The name of the file (defaults to 'output.pdf').
    • $contentType (string): The MIME type (defaults to 'application/pdf').
    • $contentDisposition (string): How the browser should handle the file (e.g., 'attachment' to download, or 'inline' to display in-browser). Defaults to 'attachment'.
    • $status (int): HTTP status code. Defaults to 200.
    • $headers (array): Additional HTTP headers.
    • $fileNameFallBack (string): Fallback filename.