How to get CakePdf to work in CakePHP 3.x? - cakephp

I have installed CakePdf plugin in app/plugins folder and followed all the documentation possbile, thus my settings are as following:
// config/bootstrap.php
Plugin::load('CakePdf', ['bootstrap' => true, 'routes' => true]);
Configure::write('CakePdf', [
'engine' => 'CakePdf.WkHtmlToPdf',
'binary' => '/wkhtmltopdf/bin/wkhtmltopdf',
'margin' => [
'bottom' => 15,
'left' => 50,
'right' => 30,
'top' => 45
],
'orientation' => 'landscape',
'download' => true
]);
// config/routes.php
Router::extensions(['pdf']);
// controller/AppController.php
public function initialize()
{
parent::initialize();
$this->loadComponent('RequestHandler');
$this->loadComponent('Flash');
$this->loadComponent('Auth', [
'authenticate' => ['Form' => ['fields' => ['username' => 'email', 'password' => 'password']]],
'loginAction' => ['controller' => 'Users', 'action' => 'login'],
'loginRedirect' => ['controller' => 'Users', 'action' => 'index'],
'logoutRedirect' => ['controller' => 'Users', 'action' => 'login'],
'authorize' => 'Controller'
]);
}
Here is how a sample agendaPdf action looks like:
function agendaPdf(){
$agenda = 'sample agenda';
$this->viewBuilder()->options([
'pdfConfig' => [
'orientation' => 'portrait',
'filename' => 'agenda_123'
]
]);
$this->set('agenda', $agenda);
}
I have PDF layouts done, as well as a PDF folder inside the templates folder for the model's actions, however, if I go to app/users/agendapdf.pdf, I am given the following messages:
The action agendapdf.pdf is not defined in UsersController
Error: Create UsersController::agendapdf.pdf() in file: src/Controller/UsersController.php.
I would really like to know what could have went wrong and how I can fix it to work.

CakePdf does not include any of the supported PDF engines, so i tried wkhtmltopdf( Refered Link).
Step by Step process:
1. Install wkhtmltopdf binary file in your local or server system (Ubuntu, Window, Mac) - Download link : [wkhtmltopdf][2]
2. Check the installed location of wkhtmltopdf binary file - (i am using ubuntu so installed location is /usr/local/bin)
3. configure the wkhtmltopdf with cakephp:
- in : config/bootstrap.php like below:
Plugin::load('CakePdf', ['bootstrap' => true, 'routes' => true]);
Configure::write('CakePdf', [
'engine' => 'CakePdf.WkHtmlToPdf',
'margin' => [
'bottom' => 15,
'left' => 50,
'right' => 30,
'top' => 45
],
'orientation' => 'landscape',
'download' => true
]);
- Create a folder name "pdf" under your working template view folder:
* for ex: src/template/(working view folder)/pdf (src/template/budget/pdf)
- Create a file name "view.ctp" under newly created pdf folder under working directory:
* for ex: src/template/(working view folder)/pdf/view.ctp (src/template/budget/pdf/view.ctp)
- use below code in working controller - action(view - method)
$this->viewBuilder()->options([
'pdfConfig' => [
'orientation' => 'portrait',
'filename' => 'Invoice_' . $id
]
]);
* for ex:
public function view($id = null)
{
$budget = $this->budget->get($id);
$this->viewBuilder()->options([
'pdfConfig' => [
'orientation' => 'portrait',
'filename' => 'Invoice_' . $id
]
]);
$this->set('budget', $budget);
}
- Hit the controller and action to download as PDF.
* for ex: http://localhost:8765/projects/view/1.pdf
- if you are facing "wkhtmltopdf binary is not found or not executable" error. copy your wkhtmltopdf file from "/usr/local/bin" to "/usr/bin"
* cd /usr/local/bin
* sudo cp wkhtmltoimage /usr/bin/wkhtmltoimage
* sudo cp wkhtmltopdf /usr/bin/wkhtmltopdf

Related

CakePdf on a php5.6 server

The site is on a php5.6 server - shared hosting so installation is done manually using github and php-download.com.
We've chosen to use mpdf and I can create test files by calling it directly.
Our cake site is v3.x.
I've added the pdf extension to routes.php
I've added this to bootstrap.php
Plugin::load('CakePdf',['bootstrap' => true]);
Configure::write('CakePdf', [
'engine' => 'CakePdf.MpdfEngine',
'margin' => [
'bottom' => 15,
'left' => 50,
'right' => 30,
'top' => 45
],
'orientation' => 'portrait',
'download' => true
]);
In my "forms" controller I have 2 functions - they both throw errors on the homepage.
//before the class
use CakePdf\Pdf\CakePdf;
//in the class
function test(){
$this->viewBuilder()->setClassName('CakePdf.Pdf');
$this->viewBuilder()->setLayout('default');
$this->viewBuilder()->options([
'pdfConfig' => [
'engine' => 'CakePdf.MpdfEngine',
'download' => true,
'title' => 'My Form',
'filename' => 'Form1.pdf'
]
]);
}
function test1(){
$pdf_path = WWW_ROOT . 'tmp/tests/'.date('Y-m-d') . DS . 'test1.pdf';
//$CakePdf = new CakePdf();
$CakePdf = new \CakePdf\Pdf\CakePdf\CakePdf();
debug($CakePdf);
exit;
$CakePdf->template('test', 'pdf/default');
$pdf = $CakePdf->output();
$pdf = $CakePdf->write($pdf_path);
}
My error log for /forms/test1 is probably the most useful - in particular the bit where there's the extra 'CakePdf' in the first line
2020-10-12 16:30:12 Error: [Cake\Error\FatalErrorException] Class 'CakePdf\Pdf\CakePdf\CakePdf' not found in /var/www/www.mysite.com/public_html/src/Controller/FormsController.php on line 343
Request URL: /forms/test1.pdf
Stack Trace:
#0 /var/www/www.mysite.com/public_html/vendor/cakephp/cakephp/src/Error/BaseErrorHandler.php(105): Cake\Error\BaseErrorHandler->handleFatalError(1, 'Class 'CakePdf\\...', '/var/www/www.my...', 343)
#1 [internal function]: Cake\Error\BaseErrorHandler->Cake\Error\{closure}()
#2 {main}

CakePHP - CakeDC Plugin Permission Not Working

I have been using the following plugin (https://github.com/CakeDC/users) for CakePHP, but I can't figure out how to get the permissions working for it. I have followed all instructions, but it seems authorize does not get used at all. Wondering if anyone has any tips on how to make it work. Here is my setup:
bootstrap.php
Configure::write('Users.config', ['users']);
Plugin::load('CakeDC/Users', ['routes' => true, 'bootstrap' => true]);
AppController.php initialize function
$this->loadComponent('CakeDC/Users.UsersAuth');
config/users.php
$config = [
'Auth' => [
'authError' => 'Did you really think you are allowed to see that?'
]
];
return $config;
config/permissions.php
return [
'Users.SimpleRbac.permissions' => [
[
'role' => '*',
'controller' => 'Pages',
'action' => ['display'],
'allowed' => true
], [
'role' => '*',
'controller' => 'Taxes',
'action' => ['*'],
'allowed' => true
], [
'role' => '*',
'prefix' => 'v1',
'controller' => '*',
'action' => '*',
'allowed' => true
]
]
];
return $config;
Frankly it seems a CakePHP configuration issue, but I am not able to find where that problem is coming from. I say that because even though debug shows the correct file loaded to authorize, it does not get called.
Please ensure you are returning the $config variable in the users.php file and you are initializing the plugin correctly as indicated here https://github.com/CakeDC/users/blob/master/Docs/Documentation/Configuration.md
Configure::write('Users.config', ['users']);
Plugin::load('CakeDC/Users', ['routes' => true, 'bootstrap' => true]);
I've created a test environment here with your provided Auth configuration and it works correctly https://ide.c9.io/steinkel/users-so-42523209
https://nimbus.everhelper.me/client/notes/share/790695/girguwv9x7rttdvu5c4x
Thanks,

CakePHP 3: Upload multiple files and save file names in associated model?

I need to create the upload process where the user can upload multiple files at once, using the file field with html5 multiple attr. Name of the file must be saved in the associated model.
I can run successfully upload one file and save the file name in the photos table, across the field:
echo $this->Form->file('photos.name');
But if I want to enable upload more photos with
echo $this->Form->input('title'); // post title
echo $this->Form->input('maintext'); // post main text,
... etc
echo $this->Form->file('photos[].name',['multiple'=>true]);
I get into the problem, and try to understand where I make mistakes, but without success.
PostsController:
public function add()
{
$post = $this->Posts->newEntity();
if ($this->request->is('post')) {
$post = $this->Posts->patchEntity($post, $this->request->data);
if ($this->Posts->save($post)) {
$this->Flash->success(__('The post has been saved.'));
return $this->redirect(['action' => 'index']);
} else {
$this->Flash->error(__('The post could not be saved. Please, try again.'));
}
}
$this->set(compact('post'));
$this->set('_serialize', ['post']);
}
PostsTable:
$this->addBehavior('Upload');
$this->hasMany('Photos', [
'foreignKey' => 'post_id'
]);
UploadBehavior
All standard callbacks where I currently perform debug $data / $entity, but only in beforeMarshal i use:
$data = Hash::get($data,'name');
debug($data);
// debug output
[
'name' => 'HPIM3869.JPG',
'type' => 'image/jpeg',
'tmp_name' => 'C:\xampp\tmp\phpF02D.tmp',
'error' => (int) 0,
'size' => (int) 1295448
],
...
In beforeSave and afterSave
My form is OK, the data properly come in before Marshal method, if I upload 3 files, I also see the same number of debug outputs, but in beforSave and afterSave debug only show the first file like this:
debug($entity);
object(App\Model\Entity\Photos) {
'name' => [
'name' => 'HPIM3435.JPG',
'type' => 'image/jpeg',
'tmp_name' => 'C:\xampp\tmp\php5839.tmp',
'error' => (int) 0,
'size' => (int) 1517410
],
'post_id' => (int) 469,
'created' => object(Cake\I18n\Time) {
'time' => '2015-10-07T09:22:44+0200',
'timezone' => 'Europe/Berlin',
'fixedNowTime' => false
},
'modified' => object(Cake\I18n\Time) {
'time' => '2015-10-07T09:22:44+0200',
'timezone' => 'Europe/Berlin',
'fixedNowTime' => false
},
'[new]' => true,
'[accessible]' => [
'*' => true
],
'[dirty]' => [
'name' => true,
'post_id' => true,
'created' => true,
'modified' => true
],
'[original]' => [],
'[virtual]' => [],
'[errors]' => [],
'[repository]' => 'Photos'
}
Edit:
In the purpose of the test, I create such a form:
echo $this->Form->input('name',['value'=>'zzz']);
echo $this->Form->input('photos.0.name',['value'=>'zzz']);
echo $this->Form->input('photos.1.name',['value'=>'hhh']);
echo $this->Form->input('photos.2.name',['value'=>'fff']);
Also it only be saved the first result.
I need help to understand how to save multiple form data. Where I go wrong?
I think your field should be like this
echo $this->Form->file('photos.name.',['multiple'=>true]); //note dot notation at end of name. It will generate input name as array

croogo error plugin search

I download a search plugin from http://www.cakedc.com/downloads. and I used cakephp/croogo 1.4.3.
I renamed the search plugin 'Search' and I download in app/Plugin/.
in my controller:
public $name = 'MovementsRouts';
public $components = array('Search.Prg');
public $presetVars = array(
array('field' => 'name', 'type' => 'value'),
array('field' => 'status', 'type' => 'value'),
);
public function admin_index_route() {
$this->set('title_for_layout', __('Movement Taxi route'));
$this->MovementsRout->recursive = 0;
$this->Prg->commonProcess();
$this->paginate = array(
'MovementsRout' => array(
'conditions' => $this->MovementsRout->parseCriteria($this->passedArgs),
//'conditions' => array('MovementsRout.type_mvt ='=>'route_taxi'),
//'fields'=>array('id','description','title','support_count','oppose_count','user_id','created'),
'limit' => 5,
//'paramType' => 'querystring'
));
$this->set('movementsRouts', $this->paginate());
}
in my model:public
$name = 'MovementsRouts';
public $components = array('Search.Prg');
public $presetVars = array(
array('field' => 'name', 'type' => 'value'),
array('field' => 'status', 'type' => 'value'),
);
in my view index_route.ctp:
<div><?php
echo $this->Form->create('MovementsRout', array(
'url' => array_merge(array('action' => 'index'), $this->params['pass'])
));
echo $this->Form->input('name', array('div' => false, 'empty' => true)); // empty creates blank option.
echo $this->Form->input('status', array('label' => 'Status', 'options' => $statuses));
echo $this->Form->submit(__('Search', true), array('div' => false));
echo $this->Form->end();
?>
</div>
and I add in config/bootstrap:
CakePlugin::load('Search');
ERROR DISPLAY : Fatal error: Class 'Hash' not found in C:\xampp\htdocs\wfs\app\Plugin\Search\Controller\Component\PrgComponent.php on line 85
IN line 85 in app\Plugin\Search\Controller\Component\PrgComponent.php:
$this->_defaults = **Hash**::merge($this->_defaults, array(
'commonProcess' => (array)Configure::read('Search.Prg.commonProcess'),
'presetForm' => (array)Configure::read('Search.Prg.presetForm'),
), $settings);
}
What is the problem?
There's a mismatch between the cakephp version that Croogo bundles and what the Search plugin expects. To use Search plugin in Croogo 1.4.3, you need to find out which CakePHP version it's using, and download the correct version of Search plugin for that specific version of CakePHP.
Croogo 1.4.3 is really old, 14 releases behind the current stable. A lot has been improved and version 1.5.x already supports the Search plugin by default. I suggest you upgrade to the latest stable.

Trouble Generating PDF with CakePHP and CakePdf

I am trying to use CakePdf to generate a pdf file within CakePHP. I have a function in the CourseGradesController called viewReport. I want viewReport to allow you to select a student from a select field, and then upon submitting the form, it will generate a PDF with the appropriate data. If I put the data into a table and do not try to make a PDF, the page will display correctly, so I don't think that is the problem. In bootstrap.php, I have
CakePlugin::load('CakePdf', array('bootstrap' => true, 'routes' => true));
Configure::write('CakePdf', array(
'engine' => 'CakePdf.WkHtmlToPdf',
'options' => array(
'print-media-type' => false,
'outline' => true,
'dpi' => 96
),
'margin' => array(
'bottom' => 15,
'left' => 50,
'right' => 30,
'top' => 45
),
'binary' => '/var/www/cakephp/app/Plugin/CakePdf/Vendor/WkHtmlToPdf',
'orientation' => 'landscape',
'download' => false
));
I have the WkHtmlToPdf folder moved into /var/www/cakephp/app/Plugin/CakePdf/Vendor/WkHtmlToPdf, so the lib and include folders are in that directory.
In the viewReport function of CourseGradesController, I have
function viewReport($id = null)
{
$this->CourseGrade->id = $id;
if (!$this->CourseGrade->exists())
{
throw new NotFoundException(__('Invalid invoice'));
}
$this->pdfConfig = array(
'orientation' => 'portrait',
'filename' => 'Invoice_' . $id
);
$this->set('invoice', $this->CourseGrade->read(null, $id));
...
}
If I navigate to /courseGrades/viewReport, I get the error "Error: The requested address '/cakephp/courseGrades/viewReport' was not found on this server."
If I naviate to /courseGrades/viewReport/1.pdf, then I just see a completely blank screen.
I would strongly recommend the use of this plugin for this kind of work.
https://github.com/ceeram/CakePdf

Resources