pdfable 10

A Yii extension to create PDFs with PHPWkHtmlToPdf/wkhtmltopdf

mikehaertl/pdfable

Written in PHP by 2 contributors

Contribute

Need Support?


we offer maintenance, support and development services for all our open source projects.

Contact Us

PDFable

PDFable is a Yii extension to create PDFs from web pages with PHPWkHtmlToPdf (included).

Requirements

PDFable requires the wkhtmltopdf binary to be installed on your system.

Installation

Download the package file and unzip it to the extensions directory. Note, that you may want to rename the directory from pdfable-x.y.z to pdfable.

Example module

To try out the extension, you can configure the pdfable example module in your main.php:

<?php
    'modules'=>array(
        'pdfable'=>array(
            'class'=>'ext.pdfable.pdfable.PdfableModule',
            // Optional: Set path to wkthmltopdf binary
            //'bin' => '/usr/bin/wkhtmltopdf',
        ),

The module should then be available from http://localhost/index.php?r=pdfable/demo or whatever you use as hostname. I recommend to have a look at this example module's code.

Basic configuration

PDFable comes as a controller behavior which gets attached through behaviors:

<?php
class MyController extends Controller
{
    public function behaviors()
    {
        return array(
            'pdfable'=>array(
                'class' => 'ext.pdfable.Pdfable',
            ),
        );
    }

Basic use

To render single page PDFs from a view file you just call renderPdf() instead of render(). This will convert the view file to a PDF and display it inline in the browser:

    public function actionPdfDemo()
    {
        // Render this view as PDF and display inline in the browser:
        $this->renderPdf('pdfDemo');
    }

Just as with render() you can of course also render more complex views with custom data. And if you want to open a download dialog, you can also pass the download filename as 4th argument:

<?php
    public function actionInvoice($id)
    {
        $invoice=Invoice::model()->findByPk($id);

        $this->renderPdf('invoice',array(
            'invoice' => $invoice,
        ), array(), 'invoice_'.$invoice->id.'.pdf');
    }

The third parameter allows you to pass additional PDF page options to wkhtmltopdf. See advanced configuration below.

Advanced use

Multi-Page PDFs

PDFs with more than one page (=view) are also possible. Here you would use the createPdf() method. It returns a PdfFile object.

<?php
    public function actionPortfolio($id)
    {
        $portfolio = Portfolio::model()->findByPk($id);

        $pdf = $this->createPdf();
        $pdf->renderPage('intro');
        $pdf->renderPage('portfolio',array(
            'portfolio' => $portfolio,
        ));
        $pdf->send('portfolio_'.$id.'.pdf');
    }

Use from console commands

You can also create PDFs from console commands through the low-level PdfFile class. The following example is taken from the example module:

    public function actionIndex($filename)
    {
        $pdf = new PdfFile;

        // We have to set some paths ...
        $pdf->baseViewPath  = Yii::getPathOfAlias('ext.pdfable.pdfable.views');
        $pdf->layoutPath    = Yii::getPathOfAlias('ext.pdfable.pdfable.views.layouts');
        $pdf->viewPath      = Yii::getPathOfAlias('ext.pdfable.pdfable.views.demo');

        // ... and supply our custom CSS file
        $pdf->setOptions(array(
            'user-style-sheet'  => Yii::getPathOfAlias('ext.pdfable.pdfable.assets.css.pdf').'.css',
        ));

        $pdf->renderPage('invoice');
        $pdf->renderPage('page1');
        $pdf->renderPage('page2');

        $pdf->saveAs($filename);
    }

If you want to try the example command you can add it to the commandMap in your console.php:

<?php
    'commandMap' => array(
        'demopdf' => array(
            'class' => 'ext.pdfable.pdfable.commands.DemopdfCommand',
        ),
    ),

You then can create an example PDF with ./yiic demopdf --filename=/tmp/demo.pdf.

Advanced configuration

It's recommended to have a look at the PHPWkHtmlToPdf documentation. All the options described there are also available with PDFable.

Default page options

You can set default PDF options for the document and each page in the behaviors() method:

<?php
   public function behaviors()
   {
       return array(
           'pdfable' => array(
               'class' => 'ext.pdfable.Pdfable',

               // Global PDF options (see wkhtmltopdf -H for details)
               'pdfOptions' => array(
                   'bin'   => '/usr/bin/wkhtmltopdf',  // path to executable (default)
                   'dpi'   => 600,
               ),

               // Default PDF page options (see wkhtmltopdf -H for details)
               'pdfPageOptions' => array(
                   'page-size'         => 'A5',

                   // You probably always need this, because CSS files from <link>
                   // tags in your document are ignored
                   'user-style-sheet'  => Yii::getPathOfAlias('webroot').'/css/pdf.css',
               ),

               // Use other tmp directory instead of application.runtime
               'tmpAlias' => 'application.var.tmp',
           ),
       );
   }

Override hardcoded page defaults

The behavior uses some hardcoded defaults for document and page options (see PdfFile). Your configuration above will always be merged with these defaults. If you don't like this and want complete freedom instead, then configure the behavior like this:

<?php
   public function behaviors()
   {
       return array(
           'pdfable' => array(
               'class' => 'ext.pdfable.Pdfable',

               'defaultPdfOptions' => array(
                   ...
                   // default PDF options here
                   // could also be an empty array to disable all defaults
                   ...
               ),

               'defaultPdfPageOptions' => array(
                   ...
                   // default PDF page options here
                   // could also be an empty array to disable all defaults
                   ...
               ),
           ),
       );
   }

Custom page options

You can supply custom wkhtmltopdf page options along as third parameter to renderPdf(). The format is the same as for addPage() in PHPWkHtmlToPdf.





43 other PHP projects


phpwkhtmltopdfPHP 716

A slim PHP wrapper around wkhtmltopdf with an easy to use and clean OOP interface

php-pdftkPHP 213

A PDF conversion and form utility based on pdftk

yii2-localeurlsPHP 189

Automatic locale/language management for URLs

YiiRedisPHP 131

A set of wrappers for different data types in redis

yiipasswordPHP 81

Password strategies for Yii

yii2-dockerizedPHP 64

A template for docker based Yii 2 applications

YiiSolrPHP 50

A wrapper for the pecl solr library that provides common Yii constructs, such as models, data providers etc

php-shellcommandPHP 48

A simple object oriented interface to execute shell commands in PHP

Yii-Docs-GeneratorPHP 47

Generates HTML documentation for Yii applications

YiiGitPHP 36

A git wrapper for Yii, allows access to all git commands programatically

YiiElasticSearchPHP 32

Elastic Search client for Yii

YiiCurlPHP 30

A curl library for Yii

YiiStateMachinePHP 28

A state machine behavior for Yii

yii2-streamlogPHP 19

A Yii 2 log target for streams in URL format

oauth2yiiPHP 18

An OAuth2 client / server extension for the Yii framework

packagecompressorPHP 16

A Javascript/CSS compressor based on Yii's package system

restyiiPHP 16

A RESTful extension for Yii.

localeurlsPHP 12

Automatic locale/language management for URLs

php-excel-readerPHP 12

It reads the binary format of XLS files directly and can return values and formats from any cell. This project is the fork of http://code.google.com/p/php-excel-reader/ that, apparently, is no longer maintained.

yii-api-vimPHP 8

Yii API manual plugin for VIM

yii2-bs3activeformPHP 7

A Bootstrap 3 enhanced ActiveForm for Yii 2

yii2-excel-messagePHP 7

Translate messages via Excel files

xcrudcontrollerPHP 7

A base class to quickly build customized CRUD interfaces.

handlebarsphpPHP 6

Transpiles handlebars templates into native PHP templates

Yii-Package-ManagerPHP 6

A package manager for Yii

php-tmpfilePHP 6

A convenience class for temporary files

yii2-apidoc-vimPHP 5

Yii2 apidoc as Vim helpfiles

php-orientdbPHP 5

A fast PHP driver for the OrientDB binary protocol.

translatablePHP 4

Transparent attribute translation for ActiveRecords

YiiUsersPHP 4

User management for Yii

Yii-Resource-ManagerPHP 3

Helpers to allow Yii to interact with resources (files) of different types

flushablePHP 3

Yii dependency that allows to flush records from the cache

bs3activeformPHP 2

A lightweight utility to render Bootstrap 3 forms in Yii

YiiEmailerPHP 2

Emailing functions for Yii

AccessRestrictablePHP 2

A Yii ActiveRecordBehavior that automatically applies conditions for access restriction to every query.

YiiLinkablePHP 1

A simple extension for Yii allowing easy and consistent access to model URLs and appropriate anchor text.

defaultpersisterPHP 1

Yii extension to save and restore model values in user session.

hybridauthmanagerPHP 1

An AuthManager for Yii that stores the hierarchy in a flat PHP file and the assignments in DB

YiiYaaPHP 1

YAA is an additional abstraction layer for Yii that aggregates a number of child models into a clean single model that is easy to cache

YiiAbstractArrayModelPHP

Work with PHP files in Active Record way

twittonioPHP

simple useless twitter client

yii2-base-appPHP

An alternative Yii2 application template for purists

xreturnablePHP

Yii extension to create URLs that allow to return to a page by storing its GET Parameters on a stack.