PHP code example of mvlabs / mvlabs-snappy

1. Go to this page and download the library: Download mvlabs/mvlabs-snappy library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

mvlabs / mvlabs-snappy example snippets


    
    return [
        'modules' => [
            // ...
            'MvlabsSnappy',
        ],
        // ...
    ];
    


return [
    'mvlabs-snappy' => [
        'pdf' => [
           'binary'  => '/usr/local/bin/wkhtmltopdf',
           'options' => [], // Type wkhtmltopdf -H to see the list of options
        ],
        'image' => [
            'binary'  => '/usr/local/bin/wkhtmltoimage',
            'options' => [], // Type wkhtmltoimage -H to see the list of options
         ]
     ]
];


class IndexController extends AbstractActionController
{
    /**
     * @var Knp\Snappy\Pdf;
     */
    protected $mvlabsSnappyPdf;

    /**
     * @var Laminas\View\Renderer\RendererInterface
     */
    protected $renderer;

    public function __construct(Pdf $mvlabsSnappyPdf, RendererInterface $renderer)
    {
        $this->mvlabsSnappyPdf = $mvlabsSnappyPdf;
        $this->renderer = $renderer;
    }

    public function testPdfAction()
    {
        $now = new \DateTime();

        $layoutViewModel = $this->layout();
        $layoutViewModel->setTemplate('layout/pdf-layout');

        $viewModel = new ViewModel([
            'vars' => $vars,
        ]);

        $viewModel->setTemplate('myModule/myController/pdf-template');

        $layoutViewModel->setVariables([
            'content' => $this->renderer->render($viewModel),
        ]);

        $htmlOutput = $this->renderer->render($layoutViewModel);

        $output = $this->mvlabsSnappyPdf->getOutputFromHtml($htmlOutput);

        $response = $this->getResponse();
        $headers  = $response->getHeaders();
        $headers->addHeaderLine('Content-Type', 'application/pdf');
        $headers->addHeaderLine('Content-Disposition', "attachment; filename=\"export-" . $now->format('d-m-Y H:i:s') . ".pdf\"");

        $response->setContent($output);

        return $response;
    }
}