CakePdf on a php5.6 server - cakephp

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}

Related

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

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

CakePdf & Cakephp 3.1.6

I can´t get CakePdf to work, If I would get an error, I could work with it. But nothing really shows up.
CakePhp: 3.1.6
CakePdf: current Version
I added an InvoicesController with this code
<?php
namespace App\Controller;
class InvoicesController extends AppController
{
// In your Invoices controller you could set additional configs, or override the global ones:
public function view($id)
{
$this->pdfConfig = array(
'orientation' => 'landscape',
'download' => true,
'filename' => 'invoucne.pdf'
);
}
}
?>
Also added this to my bootstrap.php
use Cake\Event\EventManager;
EventManager::instance()
->on(
'Controller.initialize',
function (Cake\Event\Event $event) {
$controller = $event->subject();
if ($controller->components()->has('RequestHandler')) {
$controller->RequestHandler->config('viewClassMap.pdf', 'CakePdf.Pdf');
}
}
);
Plugin::load('CakePdf', ['bootstrap' => true, 'routes' => true]);
Configure::write('CakePdf', [
'engine' => 'CakePdf.dompdf',
'margin' => [
'bottom' => 15,
'left' => 50,
'right' => 30,
'top' => 45
],
'orientation' => 'landscape',
'download' => true
]);
This to my routes.php
Router::extensions(['pdf']);
Also I go my default.ctp in the src/Template/Layout/pdf
<h2>Rendered with default layout</h2>
<?php echo $this->fetch('content'); ?>
And my views in my Template/Invoices/pdf
<html>
<body>
<h1>test</h1>
</body>
</html>
My url looks like:
http://localhost/caketest/invoices/view/1.pdf
I installed it with composer and my plugins lie in vendor/dompdf and vendor/friendsofcake/cakepdf
I had this problem before the solution is to put
Router::extensions(['pdf']);
before
Router::scope('/', function ($routes) { //some code}
not after it

MeioUpload isn't creating thumbnails in cakephp 2.4

I'm using meioupload and everything works well till I try to make thumbnails. Then I can see only kind of phpThumb error message which says
"C:/wamp/cakephp/vendors/phpTmub/img/uploads/product/filename/image.png" does not exist
I'm new with cakePHP so I never faced this problem before. Does anyone know what should I do?
here is my model code:
var $actsAs = array(
'MeioUpload' => array(
'filename' => array(
'create_directory' => true,
'allowed_mime' => array('image/jpeg', 'image/pjpeg', 'image/png'),
'allowed_ext' => array('.jpg', '.jpeg', '.png'),
'zoomCrop' => true,
'thumbsizes' => array(
'normal' => array('width' => 400, 'height' => 300),
'small' => array('width' => 80, 'height' => 80,'maxDimension' => '', 'thumbnailQuality' => 100, 'zoomCrop' => true),
),
'default' => 'default.jpg'
)
));
UPDATE:
I found special phpThumb for cakePHP 2.0 so the Path changed into this:
"C:/wamp/cakephp/img/uploads/product/filename/image.png"
and if I open default image in my browser th path is like:
localhost:8080/cakephp/img/uploads/product/filename/image.png
Thanks
I solved the problem, maybe not very elegant, but it works!
For the first time, as I said, I downloaded special version of phpThumb for cakePHP.
Here is link: https://github.com/simkimsia/phpThumb-for-cakephp-2.0
After there was my problem with the path because my images was in folder: C:\wamp\www\cakephp\app\webroot\img\uploads\product\filename\image.png
So I had to find this part of code(begins on line 1078):
if ($this->useCake) {
if ($this->config_document_root != null) {
$AbsoluteFilename = $this->config_document_root.DIRECTORY_SEPARATOR.$filename;
} else {
$AbsoluteFilename = WWW_ROOT.DIRECTORY_SEPARATOR.$filename;
}
}
And edit a the path to fit into my folder:
$AbsoluteFilename = $this->config_document_root.DIRECTORY_SEPARATOR.'cakephp'.DIRECTORY_SEPARATOR.'app'.DIRECTORY_SEPARATOR.'webroot'.DIRECTORY_SEPARATOR.$filename;
$AbsoluteFilename = WWW_ROOT.DIRECTORY_SEPARATOR.'cakephp'.DIRECTORY_SEPARATOR.'app'.DIRECTORY_SEPARATOR.'webroot'.DIRECTORY_SEPARATOR.$filename;
and now its working perfectly...
after try many things.. and finally read the answer of Jan Omacka, i only have to edit phpthumb.class.php, line 223 in the constructor function phpThumb()
First
// public: constructor
function phpThumb() {
.....
//comment line
//$this->config_document_root = (!empty($_SERVER['DOCUMENT_ROOT']) ? $_SERVER['DOCUMENT_ROOT'] : $this->config_document_root);
.....
}
//and put the constant CakePHP Var WWW_ROOT (Full path to the webroot.)
$this->config_document_root = WWW_ROOT;
//and if this don't work.. put your real path in linux, or windows
//$this->config_document_root = '/srv/www/htdocs/sic/app/webroot/';
In my case inside webroot, have a folder with estructure 'Usuarios/ID_Prestamo/IDUsuario/', all works great uploading the picture but thumbs not.. so after download the last version of phpThumb, i saw that show an error of File does not exist (URL misformat, for original JPG File), after that download the special versión for CakePhp and change the lines as mentioned.. and all works... I use OpenSuse Linux, Apache2, with Cake 2.4.2
Notes: I verified that if not have zoomCrop it not works, this is my structure
'dir' => 'galeria/', //main folder webroot/galeria/
'createDirectory' => true,
'maxSize'=>'5 Mb',
'allowedExt' => array('.jpg','.jpeg','.png'),
'zoomCrop' => true,
'thumbsizes' => array(
'small' => array('width'=>165, 'height'=>115),
'medium' => array('width'=>800, 'height'=>600)
),

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

How Can I Read the DB Configuration Settings From a Cake Shell?

I would like to write a cake shell to do a nightly backup of my database using mysqldump. I could do this as a shell script, but if I can cram it into a CakePHP shell, then I will get the added benefit of it working across both the development and live server, if I can get it to automagically read my database config settings. I will cron the cake shell and have some peace-of-mind knowing that I have frequent backups of my DB.
In my shell I'm trying to build up a string which starts with "mysqldump --user=" and I'd like to get the username from app/config/database.php. How can I get at the data in database.php?
In cake 2.1 the format has changed to:
App::uses('ConnectionManager', 'Model');
$dataSource = ConnectionManager::getDataSource('default');
$username = $dataSource->config['login'];
The following snippet should do the trick:
App::import('Core', 'ConnectionManager');
$dataSource = ConnectionManager::getDataSource('default');
$username = $dataSource->config['login'];
In CakePHP 3.x the format has changed to -
use Cake\Datasource\ConnectionManager;
$source = ConnectionManager::get('default');
debug($source); #Debugging the result
Result :
object(Cake\Database\Connection) {
'config' => [
'password' => '*****',
'username' => '*****',
'host' => '*****',
'database' => '*****',
'driver' => 'Cake\Database\Driver\Mysql',
'persistent' => false,
'encoding' => 'utf8',
'timezone' => 'UTC',
'cacheMetadata' => true,
'quoteIdentifiers' => false,
'log' => false,
'url' => null,
'name' => 'remote'
],
'driver' => object(Cake\Database\Driver\Mysql) {
'connected' => false
},
'transactionLevel' => (int) 0,
'transactionStarted' => false,
'useSavePoints' => false,
'logQueries' => false,
'logger' => null
}
Get the Result :
debug($source->config()); #Accessing the result
Result :
[
'driver' => 'Cake\Database\Driver\Mysql',
'persistent' => false,
'host' => 'localhost',
'username' => 'username',
'password' => 'password',
'database' => 'database',
'encoding' => 'utf8',
'timezone' => 'UTC',
'cacheMetadata' => true,
'quoteIdentifiers' => false,
'log' => false,
'url' => null,
'name' => 'remote'
]
Just for sharing.
For any cakephp project, if using php as cronjob or command line to do large data processing I would build a standalone php script without cakephp, the reason for doing this because cakephp is slow (e.g. read & process 100K records).
To make my life simple I put all my standalone scripts under app/Vendor/myscripts/ (e.g: app/Vendor/myscripts/process.php)
below also the basic code to make sure you use the same database settings in standalone script with cakephp (tested with MySQL)
require_once '/XYZ/app/Config/database.php';
$database = new DATABASE_CONFIG;
try{
$dblink = new PDO('mysql:host='.$database->default['host'].';dbname='.$database->default['database'], $database->default['login'], $database->default['password'], array(PDO::ATTR_PERSISTENT => false));
$dblink->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$dblink->exec('SET CHARACTER SET '.$database->default['encoding']);
} catch (Exception $e) {
die('DB Error'. $e->getMessage());
}
Example in controller, Change multi DB for DataSources in CakePHP 2.5.x
App::uses('AppController', 'Controller');
class DemoController extends AppController {
public $uses = array('AppModel', 'GVA21', 'GVA01', 'GVA14', 'GVA24' );
public function test_dbs(){
$this->autoRender=false;
// Load ConnectManager
App::uses('ConnectionManager', 'Model');
// DataSource ['default']
$MDM = $this->GVA14->find('count');
echo "MDM.GVA14\n<br>";
debug($MDM);
// Get DataSource Config DB ['default'] and ['SRL']
$confDeafult = ConnectionManager::$config->default;
$confSrl = ConnectionManager::$config->SRL;
// Change DataSource ['SRL']
ConnectionManager::drop('default');
ConnectionManager::create('default',$confSrl); //<== Is permanet change Find All models Down
// $this->GVA01->setDataSource('SRL'); //<== Is temp change Find model
echo "SRL.GVA14\n<br>";
$SRL = $this->GVA14->find('count');
debug($SRL);
$SRL = $this->GVA01->find('count');
echo "SRL.GVA01\n<br>";
debug($SRL);
$SRL = $this->GVA21->find('count');
echo "SRL.GVA21\n<br>";
debug($SRL);
// Change to DataSource ['default']
debug(ConnectionManager::drop('default'));
ConnectionManager::create('default',$confDeafult); //<== Is permanet change Find All models Down
//$this->GVA01->setDataSource('default'); //<== Is temp change Find model
$MDM = $this->GVA01->find('count');
echo "MDM.GVA01\n<br>";
debug($MDM);
$MDM = $this->GVA21->find('count');
echo "MDM.GVA21\n<br>";
debug($MDM);
////FIN
exit('FIN');
}

Resources