nishan
nishan

Reputation: 51

How to render pdf from HTML using CakePdf? I followed the instructions given in github but getting an error 'Failed to load PDF document'?

I installed the plugins of CakePdf using composer. So in my vendor folder I have CakePdf plugin & other dependencies.

I downloaded wkhtmltopdf and installed it in a directory. The directory is C:\Program Files\wkhtmltopdf\bin\wkhtmltopdf.exe

Next by running the command ./bin/cake plugin load CakePdf -b I added the plugin in src/application.php

$this->addPlugin('CakePdf', ['bootstrap' => true]);

Then I wrote the below line in config/routes.php just before Router::scope

Router::extensions(['pdf']);

And in config/bootstrap.php

Configure::write('CakePdf', [
    'engine' => [
        'className' => 'CakePdf.WkHtmlToPdf',
        'binary' => 'C:\Program Files\wkhtmltopdf\bin\wkhtmltopdf.exe',
        'options' => [
            'print-media-type' => false,
            'outline' => true,
            'dpi' => 96
        ],
    ],
]);

Now in my abc controller view action I wrote

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

I have also created view.ctp inside src/Templates/abc/pdf/view.ctp and a default.pdf layout inside src/Templates/Layout/pdf/default.ctp .

Now when I go to localhost/abc/view/1.pdf, I get an error saying Failed to load PDF document!

Failed to load the PDF document

I would really like to know what could have went wrong and how I can fix it to work?

Upvotes: 0

Views: 1685

Answers (1)

kuvukala
kuvukala

Reputation: 66

In my case I had AdminLTE layout and template files set up in AppController's beforeRender method so it was overriding my layout and template just before providing the view.

I altered beforeRender method of AppController class to something like this:

    public function beforeRender(Event $event)
    {
        switch ($this->request->params['_ext']) {
          case 'pdf':
            break;
          default:
            $this->viewBuilder()->setTheme('AdminLTE');
            $this->viewBuilder()->setClassName('AdminLTE.AdminLTE');
            break;
        }
    }

and CakePdf plugin started to generate PDF's like it should.

Upvotes: 1

Related Questions