Yii-PDF Extension ¶
Small Yii extension, that wraps a few PHP libraries (mPDF and HTML2PDF so far) to convert HTML to PDF
Resources ¶
- Extension's GitHub repository
- mPDF - is a PHP class to generate PDF files from HTML with Unicode/UTF-8 and CJK support
- HTML2PDF - is a PHP class using FPDF for the PHP4 release, and TCPDF for the PHP5 release. It can convert valid HTML and xHTML to PDF
Requirements ¶
- Yii 1.1.9 or above
- mPDF version 5.3 (has been released 2011-07-21) or above
- HTML2PDF version 4.03 (has been released 2011-05-27) or above
Official documentation and examples ¶
Installation ¶
- Download and extract extension to the directory
protected/extensions/yii-pdf
- Download and extract library (mPDF and/or HTML2PDF)
to own directory in catalog
protected/vendors
or set new value for'librarySourcePath'
parameter in'params'
array - Array
'defaultParams'
- this is an array of constructor's default params of selected library. If you want to change default params - you can set them in config file (like shown below). If you do so - you must keep the order of array items! - In your
protected/config/main.php
, add the following:
//...
'components'=>array(
//...
'ePdf' => array(
'class' => 'ext.yii-pdf.EYiiPdf',
'params' => array(
'mpdf' => array(
'librarySourcePath' => 'application.vendors.mpdf.*',
'constants' => array(
'_MPDF_TEMP_PATH' => Yii::getPathOfAlias('application.runtime'),
),
'class'=>'mpdf', // the literal class filename to be loaded from the vendors folder
/*'defaultParams' => array( // More info: http://mpdf1.com/manual/index.php?tid=184
'mode' => '', // This parameter specifies the mode of the new document.
'format' => 'A4', // format A4, A5, ...
'default_font_size' => 0, // Sets the default document font size in points (pt)
'default_font' => '', // Sets the default font-family for the new document.
'mgl' => 15, // margin_left. Sets the page margins for the new document.
'mgr' => 15, // margin_right
'mgt' => 16, // margin_top
'mgb' => 16, // margin_bottom
'mgh' => 9, // margin_header
'mgf' => 9, // margin_footer
'orientation' => 'P', // landscape or portrait orientation
)*/
),
'HTML2PDF' => array(
'librarySourcePath' => 'application.vendors.html2pdf.*',
'classFile' => 'html2pdf.class.php', // For adding to Yii::$classMap
/*'defaultParams' => array( // More info: http://wiki.spipu.net/doku.php?id=html2pdf:en:v4:accueil
'orientation' => 'P', // landscape or portrait orientation
'format' => 'A4', // format A4, A5, ...
'language' => 'en', // language: fr, en, it ...
'unicode' => true, // TRUE means clustering the input text IS unicode (default = true)
'encoding' => 'UTF-8', // charset encoding; Default is UTF-8
'marges' => array(5, 5, 5, 8), // margins by default, in order (left, top, right, bottom)
)*/
)
),
),
//...
)
//...
Usage ¶
...
public function actionIndex()
{
# mPDF
$mPDF1 = Yii::app()->ePdf->mpdf();
# You can easily override default constructor's params
$mPDF1 = Yii::app()->ePdf->mpdf('', 'A5');
# render (full page)
$mPDF1->WriteHTML($this->render('index', array(), true));
# Load a stylesheet
$stylesheet = file_get_contents(Yii::getPathOfAlias('webroot.css') . '/main.css');
$mPDF1->WriteHTML($stylesheet, 1);
# renderPartial (only 'view' of current controller)
$mPDF1->WriteHTML($this->renderPartial('index', array(), true));
# Renders image
$mPDF1->WriteHTML(CHtml::image(Yii::getPathOfAlias('webroot.css') . '/bg.gif' ));
# Outputs ready PDF
$mPDF1->Output();
////////////////////////////////////////////////////////////////////////////////////
# HTML2PDF has very similar syntax
$html2pdf = Yii::app()->ePdf->HTML2PDF();
$html2pdf->WriteHTML($this->renderPartial('index', array(), true));
$html2pdf->Output();
////////////////////////////////////////////////////////////////////////////////////
# Example from HTML2PDF wiki: Send PDF by email
$content_PDF = $html2pdf->Output('', EYiiPdf::OUTPUT_TO_STRING);
require_once(dirname(__FILE__).'/pjmail/pjmail.class.php');
$mail = new PJmail();
$mail->setAllFrom('webmaster@my_site.net', "My personal site");
$mail->addrecipient('mail_user@my_site.net');
$mail->addsubject("Example sending PDF");
$mail->text = "This is an example of sending a PDF file";
$mail->addbinattachement("my_document.pdf", $content_PDF);
$res = $mail->sendmail();
}
...
License ¶
- mPDF has GNU General Public License version 2
- HTML2PDF has GNU Library or Lesser General Public License (LGPL)
- This extension was released under the New BSD License
Change Log ¶
- Version 0.3.2 (2013-04-05)
func_get_args() is using through a variable now (for PHP < 5.3.0)
- Version 0.3 (2012-07-07)
Fixed default constructor's params [thanks to zitter]
- Version 0.2a (2012-02-05)
Fixed method name (mpdf - now it's lower-case) for some case-sensitive *nix OS filesystems (it may cause for some errors) [thanks to Hylke]
- Version 0.2 (2012-01-24)
- Installation readme for mPDF part is updated (thanks to somethingkindawierd for noticed)
- Version 0.2 (2012-01-18)
- Parameter
'defaultParams'
is not required anymore (will be used constructor's default params of selected library) - Added a few helper constants for
Output()
method (detailed info located in extension's class)
class EYiiPdf extends CApplicationComponent
{
...
const OUTPUT_TO_BROWSER = "I";
const OUTPUT_TO_DOWNLOAD = "D";
const OUTPUT_TO_FILE = "F";
const OUTPUT_TO_STRING = "S";
...
}
#Example (make sure that target directory is writable)
$html2pdf->Output('/path/to/file.pdf', EYiiPdf::OUTPUT_TO_FILE);
- Version 0.1 (2012-01-16)
- Initial release
Looks awesome!
It seems to me you've forgot to mention where to put your extension code in the installation instructions.
Description updated
Thanks
Thanks for this cool extension !
Minor adjust to use with PHP versions prior to 5.3
Replace
public function mpdf() { $this->initLibrary(__FUNCTION__, func_get_args()); return $this->_mpdf; }
With
public function mpdf() { $params = func_get_args(); $this->initLibrary(__FUNCTION__, $params); return $this->_mpdf; }
Do the same for the HTML2PDF() function just bellow the mpdf() function.
Great - works also with Yii 1.1.8
Thanks for the great extension. And thanks also for letting me know about mPDF and HTML2PDF — I thought the world was spinning around TCPDF and Zend_Pdf :)
Just FYI, I tested it on a not-so-basic view (with relative divs, photos, and UTF8) on Yii 1.1.8 and it works like a charm. I tried it also on 1.1.9.
Well I may have now to test with HTML2PDF and TCPDF before maybe digging into mPDF options, in order to compare the three as per size and performance.
Edit: Maybe someone would be interested on a display-or-generate snippet:
public function actionPdf($id) { (… code to generate / retrieve the file name depending on $id …) $fileName = 'someName'; // without the extension, I add it later. The idea is to get the fileName from the db for instance or generate it dynamically $file = Yii::getPathOfAlias('webroot') . '/targetPath/' . $fileName . '.pdf'; if(!file_exists($file)) { $mPDF1 = Yii::app()->ePdf->mpdf(); $stylesheet = file_get_contents(Yii::getPathOfAlias('webroot.css') . '/screen.css'); $mPDF1->WriteHTML($stylesheet, 1); $stylesheet = file_get_contents(Yii::getPathOfAlias('webroot.css') . '/custom.css'); $mPDF1->WriteHTML($stylesheet, 1); $mPDF1->WriteHTML($this->renderPartial('view', array('model' => $this->loadModel($id)), true)); $mPDF1->Output($file, EYiiPdf::OUTPUT_TO_FILE); } header('Content-Type: application/pdf'); readfile($file); }
Landscape Orientation
I've tried setting orientation to 'L', but the generated pdf file still remains portrait. The only way I could do it was to manually set the variables as follows. Anyone manage to get landscape orientation working or is this a known bug in mpdf.php?
Code example produces landscape 11.69 x 8.26 inch:
$pdf = Yii::app()->ePdf->mpdf('', 'A4', '','','','','','','','','P'); $pdf->writeHTMLfooter=false; $pdf->writeHTMLheader=false; $pdf->DeflMargin=5; $pdf->DefrMargin=5; $pdf->tMargin=5; $pdf->bMargin=5; $pdf->w=297; //manually set width $pdf->h=209.8; //manually set height
RE: Landscape Orientation
MrLe, try to do like this:
$mpdf = Yii::app()->ePdf->mpdf(); // keep default params or set them after constructor $mpdf->_setPageSize('A4', 'L');
RE: Landscape Orientation
borales, thanks for your reply. Tried out your suggestion but got error: "Fatal error: Cannot pass parameter 2 by reference" ie. _setPageSize('A4', 'L')
$pdf = Yii::app()->ePdf->mpdf(); $pdf->_setPageSize('A4', 'L');
Hi
Thanks for your extension.
Can I use it to convert images/documents(doc,ppt,etc) to pdf file ?
Thanks
Small change for me
I've changed
# Merging params arrays (preserving params' indexes) if(isset($this->params[$library_name]['defaultParams'])) echo "settato!"; $args = isset($this->params[$library_name]['defaultParams']) ? $constructorClassArgs + array_values($this->params[$library_name]['defaultParams']) : array();
to
# Merging params arrays (preserving params' indexes) if(isset($this->params[$library_name]['defaultParams'])) echo "settato!"; $args = isset($this->params[$library_name]['defaultParams']) ? $constructorClassArgs + array_values($this->params[$library_name]['defaultParams']) : $constructorClassArgs; // <-- Note here
to make it work with parameters passed on constructor.
RE: Small change for me
zitter, thanks. I will fix this asap.
Great One
How could I give a page break?
Page breaks
@shibly27 Try http://www.minte9.com/kb/force-page-breaks-while-converting-html-to-pdf-programming-css-i16
You must set parameters first
i have edit my EYiiPdf.php like this:
public function mPDF() { $params = func_get_args(); $this->initLibrary(__FUNCTION__, $params); return $this->_mPDF; } /** * @return HTML2PDF */ public function HTML2PDF() { $params = func_get_args(); $this->initLibrary(__FUNCTION__, $params); return $this->_HTML2PDF; }
but i still get error "You must set parameters first "
Invalid argument supplied for foreach()
I have some report to export to pdf.
If the report only need 1 page, it can render the pdf. but if my data make the report more then 1 page. i get this error..
Please help me to fix this...
If i use Html2PDF how to include the css in it..
To the Point..
Just exactly what I need for.. Thank you!
Landscape Orientation
Just in case anyone was wondering, I was able to get the landscape orientation to work by using this method of declaring the class
$pdf = Yii::app()->ePdf->mpdf('', 'A4-L', '','','','','','','','','L');
Thanks !
Thanks for this awesome extension !
For some reason, with mPDF, I cannot get my CSS to be used in the PDF. I don't get any "file not found" error so I am guessing my path is correct, but still the CSS is not used. Any suggestions ?
Thanks,
Jonathan
Re
staticblue, can you show your code with CSS part here?
here is my current code :
# mPDF $mPDF1 = Yii::app()->ePdf->mpdf(); # Load a stylesheet $stylesheet = file_get_contents(Yii::getPathOfAlias('webroot.css') . '/screen.css'); $mPDF1->WriteHTML($stylesheet, 1); $mPDF1->WriteHTML($this->renderPartial('view', array( 'model' => $model, 'items' => $items, 'order' => $order, ), true)); $mPDF1->Output();
It definitely finds my screen.css, but doesn't seem to apply any of the styles ?
Re
staticblue, are you sure your CSS rules are applied correctly in the given scope? Try to render a whole page (renderPartial -> render).
Hi
Hi Borales,
Thanks for your answer. What do you mean by "applied correctly in the given scope" ?
I tried doing render instead of renderPartial, but this gives me a blank (empty) PDF ... any ideas ?
Jonathan
pdf & extension bootstrapp
Hello,
Thank you for the extension.
I am trying to use this extension with the extension bootstrap :
http://www.yiiframework.com/extension/bootstrap/
but it doesn't work.I got this error :
> TbInput: Failed to initialize widget! Model is not se
anyboody try to mix the 2 extensions?
Nath
@nath-0
Model is not set
is a base Yii error, which means that... model is not set. Without even looking into your code I'm 99% sure, that problem is in your own code, not in PDF or Bootstrap extension.Double check and then even triple check your code. Dumb variable your passing to
Tbinput
as model and make yourself 1000% sure, that it is a validCActiveModel
or descent class.Out put file is corrupted
hi
i hav used this code for generating pdf
# HTML2PDF has very similar syntax $html2pdf = Yii::app()->ePdf->HTML2PDF(); $html2pdf->WriteHTML($this->renderPartial('bookingpdf', array(), true)); $html2pdf->Output( 'etc.pdf' , EYiiPdf::OUTPUT_TO_DOWNLOAD );
in the config.php use this
'HTML2PDF' => array( 'librarySourcePath' => 'application.vendors.html2pdf.*', 'classFile' => 'html2pdf.class.php', // For adding to Yii::$classMap 'defaultParams' => array( // More info: http://wiki.spipu.net/doku.php?id=html2pdf:en:v4:accueil 'orientation' => 'P', // landscape or portrait orientation 'format' => 'A4', // format A4, A5, ... 'language' => 'en', // language: fr, en, it ... 'unicode' => true, // TRUE means clustering the input text IS unicode (default = true) 'encoding' => 'UTF-8', // charset encoding; Default is UTF-8 'marges' => array(5, 5, 5, 8), // margins by default, in order (left, top, right, bottom) ) )
and in bookingpdf.php
i used
but when i try to open the downloaded file , it gives a error that file is corrupted or not pdf..
what should i do now ..
Please Help
Built in browser pdf viewers
I was having similar problems viewing pdfs created by this software at first, but I think it was because I was trying to open it in my browser using its pdf viewer. I was able to get it to work if I downloaded it and used Adobe Acrobat Reader. Not sure if this will solve your problem I try using your code.
preg_replace(): The /e modifier is deprecated, use preg_replace_callback instead
preg_replace() has been used on line 79 & 80 but now in php5.5 it have been deprecated with preg_replace_callback(), what would be solution of this problem.
75 if(!function_exists('strcode2utf')){ 76 function strcode2utf($str,$lo=true) { 77 //converts all the &#nnn; and &#xhhh; in a string to Unicode 78 if ($lo) { $lo = 1; } else { $lo = 0; } 79 $str = preg_replace('/\&\#([0-9]+)\;/me', "code2utf('\\1',{$lo})",$str); 80 $str = preg_replace('/\&\#x([0-9a-fA-F]+)\;/me', "codeHex2utf('\\1',{$lo})",$str); 81 return $str; 82 } 83 }
To: onkar lal
Is this in my extension? I couldn't find it
You can submit an issue tracker here https://github.com/Borales/yii-pdf
Hi,
Nice and easy to install.Thanks a lot Brother for this extension.
Pdf is not defined
I am a fool, I was wrong data defining
I add yii-pdf
-protected
--extensions
---yii-pdf
----EYiiPdf.php
and I have:
'ePdf' => array( 'class' => 'ext.yii-pdf.EYiiPdf',
which can be the error?_
to nkdos
Do you call it with Yii::app()->pdf or Yii::app()->ePdf?
Double data shown
Hello. Thank you for the extension. But when I tried to display the content, it displays twice. Here is my code :
Controller
$model = $this->loadModel($id); $html2pdf = Yii::app()->ePdf->HTML2PDF(); $html2pdf->writeHTML($this->renderPartial('print', compact('model'),false)); $html2pdf->output('etc2.pdf',EYiiPdf::OUTPUT_TO_BROWSER);
View
Please help, thank you.
to C.S.Putera
... $html2pdf->writeHTML($this->renderPartial('print', compact('model'), false)); ...
C.S.Putera, do you have a reason for using the third param as
false
in above code?Try to change line in your code to this:
... $html2pdf->writeHTML($this->renderPartial('print', compact('model'), true)); ...
It will return output text to
writeHTML
method.And your problem should be gone.
Double data shown
Thank you for the fast response. Yes, I have tried to set the third param to true and still shown double. What I mean by double is that, the pdf shown contain : "Hello WorldHello World" instead of "HelloWorld" only
to C.S.Putera
C.S.Putera, can you show your complete controller-action code?
Seems that you are the only with such problem.. I can't reproduce it.
Double data shown
Yes, this is my full controller action code :
public function actionPrint($id) { $model = $this->loadModel($id); $html2pdf = Yii::app()->ePdf->HTML2PDF(); $html2pdf->writeHTML($this->renderPartial('print', compact('model'),true)); $html2pdf->output('etc.pdf',EYiiPdf::OUTPUT_TO_BROWSER); }
Thank you
Double data shown ( solved )
Updated
Hello. Found the reason why it shows double. This was my view :
I did not use td inside the table. After I added the td then it works perfect. Thank you so much for the extension and the support. Cheers!
to C.S.Putera
C.S.Putera, lets try to do some trick.
Change this line:
$html2pdf->writeHTML($this->renderPartial('print', compact('model'),true));
To this:
$html2pdf->writeHTML('<table><tr>Hello World</tr></table>');
If it will be no error - then you have some layout confilcts (I suppose).
Content Moved To Next Page
Hello. I found that if there is my content ( say last section of the page ) which is long and got separated into the next page, then all the content above also moved to the next page, leaving the first page blank. Here is the link when the section content is short :
OK
And if the section got long, it moved down. This is the screenshot :
NOT OK
Here is my view :
print.php
Do I do something wrong ? All I did is just adding the last content of that page with long lorem ipsum text and everything moved down to the next page. Please help, thank you so much
C.S.Putera
C.S.Putera, I think this is a mPDF (or HTML2PDF) problem, you should visit its official documentation site and check it there.
My extension is just a "bridge" between Yii and vendor libs.
Include font issue
Hi,When I tried to generate pdf,I got this error!
TCPDF ERROR: Could not include font definition file: verdana
How I can fix this issue?
Need to change mPDF download link
Need to change mPDF download link.
list indent for texteditor list
hello yiiers,
To Add Header/Footer :
$mPDF1->SetHtmlHeader("Your header text here"); $mPDF1->SetHtmlFooter(("Your footer text here");
if someone has try to add texteditor text in pdf and list indent not working then i have found solution using str_replace,
$notes = str_replace('<ol style="margin-left: 40px;">', '<div style="margin-left: 40px;"><ol style="margin-left: 40px;">', $model->notes); echo $notes = str_replace('</ol>',"</ol></div>",$notes);
Also one if you have got float:left issue then user mpdf not a HTMLtoPDF.
if you got solution do thumns up.
Thanks.
Exception
Property "CWebUser.ePdf" is not defined.
I got the above error.. :(
@Sachy
I am pretty sure you misplaced the component configuration in your config file.
Some records are missing
Hi, thank you for the great extension.
I have a small problem: Not all records are shown...what could be the problem?
For a table with 50 (more or less) records, everything is ok...
But eg. for a table with 313 records, only 260 are shown...
Re: Some records are missing
I got it working...I was missing:
$model->unsetAttributes();
Footer
$mPDF1->SetHtmlHeader("Your header text here"); $mPDF1->SetHtmlFooter(("Your footer text here");
This is not working in my app.
Used this instead in view/html page
<page_footer> 'Footer here' </page_footer> For page number <page_footer> [[page_cu]]/[[page_nb]] </page_footer> General Example <page> <page_footer> [[page_cu]]/[[page_nb]] </page_footer> </page>
this is working fine
Any update on how to use this plugin in php 7.4? I am having this error.
PHP Fatal error: Trait 'Mpdf\\Strict' not found in `vendors/mpdf/src/Mpdf.php on line 39`
If you have any questions, please ask in the forum instead.
Signup or Login in order to comment.