CakePdf Documentation

repository·master·Indexed 18 days ago

https://github.com/friendsofcake/cakepdf

A CakePHP plugin providing a unified interface for converting HTML to PDF. It supports multiple rendering engines including DomPdf, Mpdf, TcLibPdf, WeasyPrint, and WkHtmlToPdf, and offers features for PDF encryption via crypto engines like Pdftk, caching, and automatic rendering through PdfView.

Tokens
7.4K
Snippets
28
Records
35
Agent score
63%

What's inside CakePdf

  1. Render PDFs in the browser with PdfView

    master

    To automatically render PDFs for browser viewing or download:

    1. Templates: Place PDF templates in a pdf subdirectory of your controller templates (e.g., templates/Invoices/pdf/view.php). Place layouts in templates/layout/pdf/default.php.
    2. Controller Setup: Register PdfView in your controller's initialize() method:
      $this->addViewClasses([\CakePdf\View\PdfView::class]);
    3. Accessing: Access the PDF via URL extension (e.g., http://localhost/invoices/view/1.pdf) or by setting the Accept header to application/pdf.
    4. Forced Download: To force a download instead of in-browser viewing, set download => true and optionally a filename in the pdfConfig.
    use CakePdf\View\PdfView;
    
    class InvoicesController extends AppController
    {
        public function initialize(): void
        {
            parent::initialize();
            $this->addViewClasses([PdfView::class]);
        }
    
        public function view($id = null): void
        {
            $invoice = $this->Invoice->get($id);
            $this->viewBuilder()->setOption(
                'pdfConfig',
                [
                    'orientation' => 'portrait',
                    'filename' => 'Invoice_' . $id,
                ]
            );
            $this->set('invoice', $invoice);
        }
    }
  2. Install CakePdf and PDF engines

    master

    Install the CakePdf plugin via Composer:

    composer require friendsofcake/cakepdf

    CakePdf does not include PDF engines. You must install the engine you intend to use separately. Common engines include:

    • DomPdf: composer require dompdf/dompdf
    • Mpdf: composer require mpdf/mpdf
    • TcLibPdf: composer require tecnickcom/tc-lib-pdf (Recommended successor to Tcpdf)
    • Tcpdf: composer require tecnickcom/tcpdf (Deprecated)
    • WeasyPrint: Install via system package manager (Recommended if you have server privileges).
    • WkHtmlToPdf: Requires system binaries.
  3. Ensure CSS and images load in PDFs

    master

    PDF engines often struggle with relative paths. To ensure assets load correctly:

    1. Use Absolute URLs: Use the fullBase option with CakePHP's HtmlHelper:
      echo $this->Html->image('logo.png', ['fullBase' => true]);
      echo $this->Html->css('bootstrap.css', ['fullBase' => true]);
    2. Use File System Paths: Alternatively, use absolute filesystem paths:
      <img src="<?= WWW_ROOT ?>img/logo.png" />
    3. WkHtmlToPdf Local Access: If using wkhtmltopdf with local filesystem paths, you must enable local file access in the engine config:
      'options' => ['enable-local-file-access' => true]
    echo $this->Html->image('logo.png', ['fullBase' => true]);
    echo $this->Html->css('bootstrap.css', ['fullBase' => true]);
  4. Set up CakePdf plugin and PDF routes

    master

    First, load the plugin using the CakePHP console:

    ./bin/cake plugin load CakePdf

    To use the PdfView functionality (which allows rendering PDFs via URL extensions like .pdf), register the pdf extension in your config/routes.php:

    $routes->scope('/', function (\Cake\Routing\RouteBuilder $routes) {
        $routes->setExtensions(['pdf']);
        // ...
    });
  5. Encrypt PDF documents

    master

    To encrypt PDFs, you must first select a crypto engine (e.g., Pdftk) in your bootstrap:

    Configure::write('CakePdf.crypto', 'CakePdf.Pdftk');

    Then, in your pdfConfig, use the following options:

    • protect: Set to true to enable encryption.
    • userPassword: (Optional) Password to open the file.
    • ownerPassword: (Optional) Password to unlock permissions.
    • permissions: (Optional) An array of allowed permissions. If not set, all permissions are denied by default.

    Available Permissions: print, degraded_print, modify, assembly, copy_contents, screen_readers, annotate, fill_in.

  6. Configure TcLibPdf font setup

    master

    The tecnickcom/tc-lib-pdf engine does not bundle fonts. It requires font files in *.json format located in a directory defined by the K_PATH_FONTS constant. Define this constant in your application bootstrap before rendering any PDFs:

    // Example: Define the absolute path to your fonts directory
    define('K_PATH_FONTS', '/absolute/path/to/your/fonts');

    The directory must contain core fonts like helvetica.json.

    define('K_PATH_FONTS', '/absolute/path/to/your/fonts');
  7. Force PDF download with filename configuration

    master

    You can trigger a forced browser download by setting the download or filename keys within your pdfConfig.

    • If pdfConfig.download is set, the response will include download headers.
    • If pdfConfig.filename is provided, that specific name will be used.
    • If no filename is provided but a download is requested, PdfView generates one based on the template path and the first passed parameter in the request.

    Use getFilename() to retrieve the calculated filename.

    // Example configuration for forced download
    $this->viewBuilder()->setOption('pdfConfig', [
        'download' => true,
        'filename' => 'report_2023.pdf'
    ]);
  8. Configure CakePdf engine and options

    master

    Configure CakePdf globally using Configure::write('CakePdf', $config); or locally in a controller via the view builder's pdfConfig option. At minimum, you must define the engine.

    Global Configuration Example:

    Configure::write('CakePdf', [
        'engine' => 'CakePdf.WeasyPrint',
        'download' => true,
    ]);

    Controller-level Configuration Example:

    $this->viewBuilder()->setOption(
        'pdfConfig',
        [
            'orientation' => 'portrait',
            'filename' => 'Invoice_' . $id,
        ]
    );

    Engine Configuration (Advanced): You can pass an array to engine to configure specific engine properties like binary, cwd, or engine-specific options (e.g., dpi for WeasyPrint or unit/margins for TcLibPdf).

  9. Configure font paths for TcLibPdfEngine

    master

    The TcLibPdfEngine uses the tecnickcom/tc-lib-pdf library, which does not ship with built-in fonts. To use standard PDF core fonts (Helvetica, Times, Courier, Symbol, ZapfDingbats) or custom fonts, you must provide generated *.json font files.

    You must define the K_PATH_FONTS constant during your application bootstrap to point to the directory containing these files.

    // Define this during bootstrap
    define('K_PATH_FONTS', '/path/to/generated/fonts');
  10. Generate PDF data for attachments or storage

    master

    To generate raw PDF data (e.g., for email attachments) without using the view layer automatically:

    1. Templates: Use templates/pdf/filename.php for views and templates/layout/pdf/default.php for layouts.
    2. Implementation: Use the CakePdf class to output the string or write to a file.
    $CakePdf = new \CakePdf\Pdf\CakePdf();
    $CakePdf->template('newsletter', 'default');
    $CakePdf->viewVars(['key' => 'value']);
    
    // Get the PDF string
    $pdf = $CakePdf->output();
    
    // Or write it to a file directly
    $pdf = $CakePdf->write(APP . 'files' . DS . 'newsletter.pdf');
    $CakePdf = new \CakePdf\Pdf\CakePdf();
    $CakePdf->template('newsletter', 'default');
    $CakePdf->viewVars(['key' => 'value']);
    // Get the PDF string returned
    $pdf = $CakePdf->output();
    // Or write it to file directly
    $pdf = $CakePdf->write(APP . 'files' . DS . 'newsletter.pdf');
  11. Configure DomPdfEngine options

    master

    When using the DomPdfEngine, you can pass configuration options to the underlying dompdf/dompdf library via the options key in your CakePdf configuration.

    By default, the engine uses the following settings if not explicitly provided:

    • fontCache: Set to TMP (the CakePHP temporary directory).
    • tempDir: Set to TMP (the CakePHP temporary directory).

    You can override these or provide other Dompdf-specific options by passing an array under the options key in your engine configuration.

    // Example configuration structure
    'CakePdf' => [
        'engine' => 'DomPdf',
        'options' => [
            'options' => [
                'fontCache' => '/custom/path/to/fonts',
                'tempDir' => '/custom/path/to/temp',
                // Other Dompdf options can be passed here
            ]
        ]
    ]