how can I save PdfModel to file in Zend Framework

2019-08-13 19:01发布

问题:

I use ZF2 and DOMPDFModule\View\Model\PdfModel to generate pdf. When it is shown as a view everything is fine, but I cannot find out how to save it to file (in the code, without asking user about download). I have code like this:

use DOMPDFModule\View\Model\PdfModel;

$viewModel = new PdfModel($variables);
$viewModel->setTemplate('pos/stocklist/' . $type);
$viewModel->setOption('paperSize', 'a4');
$viewModel->setOption('paperOrientation', 'portrait');
$viewModel->setOption('fileName', 'stock.pdf');

I tried to do it in this way, but render method does not exist:

$output = $viewModel->render();
$handle = fopen($file_path.DIRECTORY_SEPARATOR.$file_name , 'w');
fwrite( $handle,$output );
fclose( $handle );

Appreciate your help.

回答1:

An example at the project's github README page shows the $viewModel being returned from the controller action. Also, the filename option which you've already specified should force the file to be downloaded rather than displayed within the browser.

The author has implemented a view strategy/renderer which creates the actual dompdf object and automatically renders the view model for you, similar to the existing zf2 behavior, so you don't have to short-circuit the MVC lifecycle.