Using CakePdf data not showing - cakephp

I am in a problem with CakePDF. I am using CakePHP 2.3.6. I setup everything alright, bootstrap & core files are ok.
Now, I want to generate many pdf files and download them. Downloading is ok, but when I download the files, I see that the generated pdf files say that Undefined $data, where I send $data to the view file.
Here is my Controller code:
App::uses('CakePdf', 'CakePdf.pdf');
// ...
public function createPdf($id) {
$data = $this->DBTable->find('all', array(
'conditions' => array(
'DBTable.id' => $id
)
));
$CakePdf = new CakePdf();
$path = APP . DS . 'pdf' . DS;
foreach($data as $key => $var) {
$CakePdf->template('create', 'default');
$this->set('var', $var);
$this->pdfConfig = array(
'orientation' => 'portrait',
'filename' => $var['id'] . ".pdf"
);
$CakePdf->write($path . $var['id'] . ".pdf");
}
}
Here, I am downloading the files some other way, not related to this problem, because downloading is ok. When I run this, all files are downloaded, and when I see the files, they say "Udefined var", looks like they didn't receive and variable called "$var".
I put the view file & the layout exactly where ceeram said.
What should I do now ? Please help me.

At last I got a solution to this. In the Controller function :
$data=$this->ModelName->find('all');
$CakePdf=new CakePdf();
$CakePdf->template('view_file','default');
$this->pdfConfig=array('orientation'=>'portrait','filename'=>$data['name']);
$CakePdf->viewVars(array('data'=>$data));
$CakePdf->write($path.$data['name'].".pdf");
Here, we have to store view_file.ctp in View/Pdf/, and default in View/Layouts/pdf/, where view_file.ctp is the view file which we want to convert in pdf, and default is the layout for this specific view file.
Here, viewVars() function passes the data to the view file, just like :
$this->set->('data',$data);
Let me know if anything is not clear here.
Thanks.

Related

Cake PHP file Downloading using Media view

Hi I uploaded files and stored in app/views/xxx/yyy.
Now i would like to download the files
If the file is PDF it is opened in new Tab and rest of them are downloaded, I need all files to be opened in new tab.
Here is my Code :
$this->view = 'Media';
$params = array(
'id' => $fileName,
'name' => $fileNameWOExtn,
'download' => false,
'extension' => $fileExtn, // must be lower case
'path' => APP . 'views' . DS .'static' . DS. $url .DS // don't forget terminal 'DS'
);
LogUtil::$logger->debug('Media View Params : '. var_export($params, true));
$this->set($params);
Not every file can be opened in the browser. A lot of file type encodings are proprietary and require their specific program to read and interpret them. PDFs, plain text files, some images, etc (with some exceptions) are the only types that browsers can recognize.
What types are files are you trying to render?

Is there a way to set serverside code to clientside scripts with CakePHP

I have a couple of js files in my CakePHP project that need a path for ajax calls. I generate the paths on the server and want to pass them to the javascript in a generic way. I don't want to add them as a parameter to the function since they are static. Now I'm doing it like this:
<?php
$categories = Router::url(array('controller' => 'categories', 'action' => 'getChildCategories'));
$brands = Router::url(array('controller' => 'brands', 'action' => 'autoComplete'));
// first add the variables
echo $this->Html->scriptBlock(
'var CATEGORIE_GETSUBCATEGORY = "' . $categories . '";
var BRAND_AUTOCOMPLETE = "' . $brands . '";',
array('inline' => false)
);
// then include the file that uses them
echo $this->Html->script('add');
?>
Is there a better way to do this without passing them as parameters?
There's nothing wrong at all with the way you're currently doing it. Any performance gains to be had are negligible and I don't think there is a definitively more elegant way of doing it.

Cakephp 2.3.x Sending Files and forcing the download of a mp4 file

I'm using cakephp 2.3.1
I want to force download a mp4 file per http://book.cakephp.org/2.0/en/controllers/request-response.html#cake-response-file
In my 'view' I have the following code which is correctly searching for the filename, and finding the file name, and displaying the download link:
<?php $filename = APP . 'webroot/files/' . $dance['Dance']['id'] . '.mp4';
if (file_exists($filename)) {
echo $this->Html->link('DOWNLOAD', array('controller' => 'dances', 'action' => 'sendFile', $dance['Dance']['id']));
} else {
echo 'Coming soon: available April 16th';
}
?>
When the user clicks on the link I want to force the download of the mp4 file. In my controller I have the following code that doesn't work:
public function sendFile($id) {
$file = $this->Attachment->getFile($id); //Note: I do not understand the 'Attachment' and the 'getFile($id)'
$this->response->file($file['webroot/files/'], array('download' => true, 'name' => 'Dance'));
//Return reponse object to prevent controller from trying to render a view
return $this->response;
}
I don't understand 'Attachment' and the 'getFile()'
I'm getting the following error:
Error: Call to a member function getFile() on a non-object
What am I doing wrong and is there any other documentation I can be looking at to understand this better?
The line you don't understand is simply part of the example - it assumes the application has a model called Attachment and that it has a method called getFile. Since you don't have an Attachment model (or at least it isn't visible to the controller) you get a "call to member function on a non-object" error. That's not important though: all you need to worry about is providing a full system path to this->response->file(). In your example, you can probably get that by changing that line to:
$this->response->file(WWW_ROOT.'files/'. $id .'.mp4', array('download' => true, 'name' => 'Dance'));
You can get rid of the $this->Attachment->getFile line as it is irrelevant in your case.
Let me know if that helped!
public function downloadfile($id= null) {
$this->response->file(APP.'webroot\files\syllabus'.DS.$id,array('download'=> true, 'name'=>'Syllubus'));
return $this->response;
}
<?php echo $this->Html->link('Syllabus',
array('controller' => 'coursesubjects',
'action'=>'downloadfile',
$courseSubject['CourseSubject']['subject_syllabus']));
?>

CakePHP 2 : Implement CakePDF plugin by Ceeram

I'm trying to implement the CakePDF plugin designed by Ceeram.
I'm using CakePHP 2 and I work locally using wamp on windows vista. I followed everything from the readme file but I got stucked at some point.
What I'd firstly like to do is converting an HTML link to a PDF using the WkHtmlToPdf engine. I see many people having issues to make it work so I'm gonna detail all the way through in the following different steps.
STEP 1: CakePdf plugin by Ceeram
I downloaded the plugin at https://github.com/ceeram/CakePdf
I extracted the contained folder into app/Plugin/CakePdf
STEP 2: Bootstrap
I added the following lines - app/Config/bootstrap.php :
CakePlugin::load('CakePdf', array('bootstrap' => true, 'routes' => true));
Configure::write('CakePdf', array(
'engine' => 'CakePdf.WkHtmlToPdf'
),
'orientation' => 'portrait',
'download' => true
));
STEP 3: Controller
I've created my controller "InvoicesController.php" - app/Controller/InvoicesController.php:
class InvoicesController extends AppController {
public $components = array('RequestHandler');
public function view($id = null) {
$this->Invoice->id = $id;
if (!$this->Invoice->exists()) {
throw new NotFoundException(__('Invalid invoice'));
}
$this->pdfConfig = array(
'orientation' => 'portrait',
'filename' => 'Invoice_' . $id
);
$this->set('invoice', $this->Invoice->read(null, $id));
}
}
STEP 4: View
I've created a pdf folder in my view folder and created view.ctp in app/View/Invoices/pdf/view.ctp.
STEP 5: Layout
I've created a pdf folder in my layout folder and created app/View/Layouts/pdf/default.ctp
That's about it. In my view I couldn't make a PDF file from an URL.
Although I have to mention I'm new in OOP and CakePHP so I would be very grateful if you could show me how to have this done. I'm sure it will help others because there many newbies like me who want to do this but because it's all meant for advanced programmers we cannot figure out how to put the pieces together.
Thank you very much for your understanding and your help!
[THIS POST IS MODIFIED EACH TIME THERE IS A NEW ANSWER WHICH IMPROVES IT]
You need to add RequestHandler component, and browse to localhost/invoices/view/1.pdf
Looks like i had forgotten to mention to add RequestHandler component in the readme.
Also for WkHtmlToPdf you need to tell it where it can find it, and since you are on windows the default location surely wont work for you. You can set the location with Configure::write('CakePdf.binary', 'C:\Program Files\wkhtmltopdf\wkhtmltopdf.exe') after having installed it on windows
You are missing this code in app/config/routers.php
Router::parseExtensions();
Router::setExtensions(array('json', 'xml', 'rss', 'pdf'));
details available on:
http://www.dereuromark.de/2014/04/08/generating-pdfs-with-cakephp/

Problem when trying to upload zip/rar files with the milesjohnson's upload plugin

I'm new to cakephp and I have found this milesjohnson's upload plugin ,
and I kind of like it, mostly because it gives me the chance of renaming the file once uploaded.Unfortunately, I can't get it to upload any zip/rar files.
This is the action where I upload the file:
function add() {
if (!empty($this->data)) {
if ($data = $this->Uploader->upload('link_referencia', array('name' => date("dmYhis")))) {
debug($data);
$this->data['Publicacione']['link_referencia']=$data['name'];
}
$this->Publicacione->create();
if ($this->Publicacione->save($this->data)) {
$this->Session->setFlash(__('The publicacione has been saved', true));
//$this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(__('The publicacione could not be saved. Please, try again.', true));
}
}
$users = $this->Publicacione->User->find('list');
$this->set(compact('users'));
}
And this is the error I get everytime I attempt to upload any zip/rar file :
EDIT
Full insert query:
INSERT INTO `publicaciones` (`vigencia`, `tipo`, `titulo`, `descripcion`, `fecha_publicacion`, `fecha_caducidad`, `link_referencia`, `modified`, `created`) VALUES (1, 'c', 'there\'s nothing you can\'t do', '
fsdfsdfsdf
', '2011-06-07', '2011-06-30', Array, '2011-06-07 16:47:23', '2011-06-07 16:47:23')
Does anyone have any ideas on what the problem might be?
Thanks in advance.
i think there is nothing with the code what you have written but you should look at in to the plugin and find out whether it gives permission you to upload zip or not.
there will be conditions in your pluggin that you can upload only some kind of files like jpg,png,txt something like that.
I hope that helps you.
Regards,
Archit
Are you totally sure your File input on the form has type=>file specified, and same for your form?
Also I would look at other uploaders - MeioUpload can allow renaming and so on and is a bit more up to date. There is also the Cuploadify plugin (uploadify for cake) you can find on github.
Make sure your form is set to multipart/form-data like so:
<?php echo $this->Form->create('File', array('enctype' => 'multipart/form-data')); ?>
The following code will upload a file:
if ($this->request->is('post')) {
if ( $this->data['File']['file']['error'] <= 0 && $this->data['File']['file']['size'] <= 8388608 ) { // Check for no errors and that File size is around 8mb.
$folder = new Folder (ROOT . DS . 'app' . DS . 'filestorage' . DS, true); // create folder in /app/filestorage/
$path = $folder->path . $this->data['File']['file']['name']; // Set path to newly created folder + uploaded file name.
$tmpUrl = new File ( $this->data['File']['file']['tmp_name'] ); // Create temporary file object
if ($tmpUrl->copy($path , true) ) { // If copying file to path is successful,
$this->Session->setFlash(__('File uploaded succesfully!'));
}
}

Resources