]> CyberLeo.Net >> Repos - Github/sugarcrm.git/blob - include/Sugarpdf/Sugarpdf.php
Release 6.2.0
[Github/sugarcrm.git] / include / Sugarpdf / Sugarpdf.php
1 <?php
2 if(!defined('sugarEntry') || !sugarEntry) die('Not A Valid Entry Point');
3 /*********************************************************************************
4  * SugarCRM Community Edition is a customer relationship management program developed by
5  * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
6  * 
7  * This program is free software; you can redistribute it and/or modify it under
8  * the terms of the GNU Affero General Public License version 3 as published by the
9  * Free Software Foundation with the addition of the following permission added
10  * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
11  * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
12  * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
13  * 
14  * This program is distributed in the hope that it will be useful, but WITHOUT
15  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
16  * FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more
17  * details.
18  * 
19  * You should have received a copy of the GNU Affero General Public License along with
20  * this program; if not, see http://www.gnu.org/licenses or write to the Free
21  * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
22  * 02110-1301 USA.
23  * 
24  * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
25  * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
26  * 
27  * The interactive user interfaces in modified source and object code versions
28  * of this program must display Appropriate Legal Notices, as required under
29  * Section 5 of the GNU Affero General Public License version 3.
30  * 
31  * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
32  * these Appropriate Legal Notices must retain the display of the "Powered by
33  * SugarCRM" logo. If the display of the logo is not reasonably feasible for
34  * technical reasons, the Appropriate Legal Notices must display the words
35  * "Powered by SugarCRM".
36  ********************************************************************************/
37
38
39
40 if(file_exists('custom/include/Sugarpdf/sugarpdf_config.php')){
41     require_once('custom/include/Sugarpdf/sugarpdf_config.php');
42 } else {
43     require_once('include/Sugarpdf/sugarpdf_config.php');
44 }
45
46 require_once('include/tcpdf/tcpdf.php');
47 require_once('include/Sugarpdf/SugarpdfHelper.php');
48
49 class Sugarpdf extends TCPDF
50 {
51
52     /**
53      * This array is meant to hold an objects/data that we would like to pass between
54      * the controller and the view.  The bean will automatically be set for us, but this
55      * is meant to hold anything else.
56      */
57     var $sugarpdf_object_map = array();
58     /**
59      * The name of the current module.
60      */
61     var $module = '';
62     /**
63      * The name of the current action.
64      */
65     var $action = '';
66     /**
67      */
68     var $bean = null;
69      /**
70      * Any errors that occured this can either be set by the view or the controller or the model
71      */
72     var $errors = array();
73     /**
74      * Use to set the filename of the output pdf file.
75      */
76     var $fileName = PDF_FILENAME;
77     /**
78      * Use for the ACL access.
79      */
80     var $aclAction = PDF_ACL_ACCESS;
81     /**
82      * Constructor which will peform the setup.
83      */
84     
85    
86     function __construct($bean = null, $sugarpdf_object_map = array(),$orientation=PDF_PAGE_ORIENTATION, $unit=PDF_UNIT, $format=PDF_PAGE_FORMAT, $unicode=true, $encoding='UTF-8', $diskcache=false){
87         global $locale;
88       //  $encoding = $locale->getExportCharset();
89         if(empty($encoding)){
90             $encoding = "UTF-8";
91         }
92         parent::__construct($orientation,$unit,$format,$unicode,$encoding,$diskcache);
93         $this->module = $GLOBALS['module'];
94         $this->bean = &$bean;
95         $this->sugarpdf_object_map = $sugarpdf_object_map;
96         if(!empty($_REQUEST["sugarpdf"])){
97             $this->action = $_REQUEST["sugarpdf"];
98         }
99     }
100
101     /**
102      * This method will be called from the controller and is not meant to be overridden.
103      */
104     function process(){
105         $this->preDisplay();
106         $this->display();
107
108     }
109
110     /**
111      * This method will display the errors on the page.
112      */
113     function displayErrors(){
114         foreach($this->errors as $error) {
115             echo '<span class="error">' . $error . '</span><br>';
116         }
117     }
118
119     /**
120      * [OVERRIDE] - This method is meant to overidden in a subclass. The purpose of this method is
121      * to allow a view to do some preprocessing before the display method is called. This becomes
122      * useful when you have a view defined at the application level and then within a module
123      * have a sub-view that extends from this application level view.  The application level
124      * view can do the setup in preDisplay() that is common to itself and any subviews
125      * and then the subview can just override display(). If it so desires, can also override
126      * preDisplay().
127      */
128     function preDisplay(){
129         // set document information
130         $this->SetCreator(PDF_CREATOR);
131         $this->SetAuthor(PDF_AUTHOR);
132         $this->SetTitle(PDF_TITLE);
133         $this->SetSubject(PDF_SUBJECT);
134         $this->SetKeywords(PDF_KEYWORDS);
135         
136         // set other properties
137         $compression=false;
138         if(PDF_COMPRESSION == "on"){
139             $compression=true;
140         }
141         $this->SetCompression($compression);
142         $protection=array();
143         if(PDF_PROTECTION != ""){
144             $protection=explode(",",PDF_PROTECTION);
145         }
146
147         $this->SetProtection($protection,blowfishDecode(blowfishGetKey('sugarpdf_pdf_user_password'), PDF_USER_PASSWORD),blowfishDecode(blowfishGetKey('sugarpdf_pdf_owner_password'), PDF_OWNER_PASSWORD));
148         $this->setCellHeightRatio(K_CELL_HEIGHT_RATIO);
149         $this->setJPEGQuality(intval(PDF_JPEG_QUALITY));
150         $this->setPDFVersion(PDF_PDF_VERSION);
151         
152         // set default header data
153         $this->setHeaderData(PDF_HEADER_LOGO, PDF_HEADER_LOGO_WIDTH, PDF_HEADER_TITLE, PDF_HEADER_STRING);
154         
155         // set header and footer fonts
156         $this->setHeaderFont(Array(PDF_FONT_NAME_MAIN, '', PDF_FONT_SIZE_MAIN));
157         $this->setFooterFont(Array(PDF_FONT_NAME_DATA, '', PDF_FONT_SIZE_DATA));
158         
159         //set margins
160         $this->SetMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP, PDF_MARGIN_RIGHT);
161         $this->setHeaderMargin(PDF_MARGIN_HEADER);
162         $this->setFooterMargin(PDF_MARGIN_FOOTER);
163         
164         //set auto page breaks
165         $this->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);
166         
167         //set image scale factor
168         $this->setImageScale(PDF_IMAGE_SCALE_RATIO); 
169         
170         //set some language-dependent strings
171         //$this->setLanguageArray($l); 
172         
173         // ---------------------------------------------------------        
174         
175     }
176
177     /**
178      * [OVERRIDE] - This method is meant to overidden in a subclass.
179      */
180     function display(){
181         $this->AddPage();
182         $this->SetFont(PDF_FONT_NAME_MAIN,'B',16);
183         $this->MultiCell(0,0,'Tcpdf class for this module and action has not been implemented.',0,'C');
184         $this->Info();
185
186
187     }
188     
189     /**
190      * [OVERRIDE]
191      * This method override the regular Header() method to enable the custom image directory in addition to the OOB image directory.
192      * This method is used to render the page header.
193      * It is automatically called by AddPage().
194      * @access public
195     * @see include/tcpdf/TCPDF#Header()
196      */
197     public function Header() {
198         $ormargins = $this->getOriginalMargins();
199         $headerfont = $this->getHeaderFont();
200         $headerdata = $this->getHeaderData();
201         
202         if (($headerdata['logo']) AND ($headerdata['logo'] != K_BLANK_IMAGE)) {
203             
204             // START SUGARPDF
205             $logo = K_PATH_CUSTOM_IMAGES.$headerdata['logo'];
206             $imsize = @getimagesize($logo);
207             if ($imsize === FALSE) {
208                 // encode spaces on filename
209                 $logo = str_replace(' ', '%20', $logo);
210                 $imsize = @getimagesize($logo);
211                 if ($imsize === FALSE) {
212                     $logo = K_PATH_IMAGES.$headerdata['logo'];
213                 }
214             }
215             // END SUGARPDF
216             
217             $this->Image($logo, $this->GetX(), $this->getHeaderMargin(), $headerdata['logo_width']);
218             $imgy = $this->getImageRBY();
219         } else {
220             $imgy = $this->GetY();
221         }
222         $cell_height = round(($this->getCellHeightRatio() * $headerfont[2]) / $this->getScaleFactor(), 2);
223         // set starting margin for text data cell
224         if ($this->getRTL()) {
225             $header_x = $ormargins['right'] + ($headerdata['logo_width'] * 1.1);
226         } else {
227             $header_x = $ormargins['left'] + ($headerdata['logo_width'] * 1.1);
228         }
229         $this->SetTextColor(0, 0, 0);
230         // header title
231         $this->SetFont($headerfont[0], 'B', $headerfont[2] + 1);
232         $this->SetX($header_x);         
233         $this->Cell(0, $cell_height, $headerdata['title'], 0, 1, '', 0, '', 0);
234         // header string
235         $this->SetFont($headerfont[0], $headerfont[1], $headerfont[2]);
236         $this->SetX($header_x);
237         $this->MultiCell(0, $cell_height, $headerdata['string'], 0, '', 0, 1, '', '', true, 0, false);
238         // print an ending header line
239         $this->SetLineStyle(array('width' => 0.85 / $this->getScaleFactor(), 'cap' => 'butt', 'join' => 'miter', 'dash' => 0, 'color' => array(0, 0, 0)));
240         $this->SetY((2.835 / $this->getScaleFactor()) + max($imgy, $this->GetY()));
241         if ($this->getRTL()) {
242             $this->SetX($ormargins['right']);
243         } else {
244             $this->SetX($ormargins['left']);
245         }
246         $this->Cell(0, 0, '', 'T', 0, 'C');
247     }
248     
249     /**
250     * [OVERRIDE] SetFont method in TCPDF Library
251     * This method override the regular SetFont() method to enable the custom font directory in addition to the OOB font directory.
252     * 
253     * @param string $family Family font. It can be either a name defined by AddFont() or one of the standard Type1 families (case insensitive):<ul><li>times (Times-Roman)</li><li>timesb (Times-Bold)</li><li>timesi (Times-Italic)</li><li>timesbi (Times-BoldItalic)</li><li>helvetica (Helvetica)</li><li>helveticab (Helvetica-Bold)</li><li>helveticai (Helvetica-Oblique)</li><li>helveticabi (Helvetica-BoldOblique)</li><li>courier (Courier)</li><li>courierb (Courier-Bold)</li><li>courieri (Courier-Oblique)</li><li>courierbi (Courier-BoldOblique)</li><li>symbol (Symbol)</li><li>zapfdingbats (ZapfDingbats)</li></ul> It is also possible to pass an empty string. In that case, the current family is retained.
254     * @param string $style Font style. Possible values are (case insensitive):<ul><li>empty string: regular</li><li>B: bold</li><li>I: italic</li><li>U: underline</li><li>D: line trough</li></ul> or any combination. The default value is regular. Bold and italic styles do not apply to Symbol and ZapfDingbats basic fonts or other fonts when not defined.
255     * @param float $size Font size in points. The default value is the current size. If no size has been specified since the beginning of the document, the value taken is 12
256     * @param string $fontfile The font definition file. By default, the name is built from the family and style, in lower case with no spaces.
257     * @access public
258     * @see include/tcpdf/TCPDF#SetFont()
259     */
260     public function SetFont($family, $style='', $size=0, $fontfile='') {
261         
262         if(empty($fontfile) && defined('K_PATH_CUSTOM_FONTS')){
263             // This will force addFont to search the custom directory for font before the OOB directory
264             $fontfile = K_PATH_CUSTOM_FONTS."phantomFile.phantom";
265         }
266         parent::SetFont($family, $style, $size, $fontfile);
267     }
268
269     function Info(){
270         
271         $this->SetFont(PDF_FONT_NAME_MAIN,'',12);
272         $this->MultiCell(0,0,'---',0,'L');
273         $this->MultiCell(0,0,'Class: '.get_class($this),0,'L');
274         $this->MultiCell(0,0,'Extends: '.get_parent_class($this),0,'L');
275         $this->MultiCell(0,0,'---',0,'L');
276         $this->MultiCell(0,0,'Module: '.$this->module,0,'L');
277         $this->MultiCell(0,0,'Tcpdf Action: '.$this->action,0,'L');
278         $this->MultiCell(0,0,'Bean ID: '.$this->bean->getFieldValue('id'),0,'L');
279         $this->SetFont(PDF_FONT_NAME_MAIN,'',12);
280         $this->MultiCell(0,0,'---',0,'L');
281
282     }
283     
284     /**
285      * [OVERRIDE] Cell method in tcpdf library.
286      * Handle charset conversion and HTML entity decode.
287      * This method override the regular Cell() method to apply the prepare_string() function to
288      * the string to print in the PDF.
289      * The cell method is used by all the methods which print text (Write, MultiCell).
290      * @see include/tcpdf/TCPDF#Cell()
291      */
292     public function Cell($w, $h=0, $txt='', $border=0, $ln=0, $align='', $fill=0, $link='', $stretch=0) {
293         parent::Cell($w, $h, prepare_string($txt), $border, $ln, $align, $fill, $link, $stretch);
294     }
295     
296     /**
297      * This Ln1() method will always print a line break of one line height.
298      * The regular Ln() method print a line break which has the height of the last printed cell.
299      */
300     public function Ln1() {
301         parent::Ln($this->FontSize * $this->cell_height_ratio + 2 * $this->cMargin, false);
302     }
303     
304     
305     /**
306      * This method allow printing a table using the MultiCell method with a formatted options array in parameter
307      * Options : 
308      * header options override the regular options for the header's cells - $options['header']
309      * cell options override the regular options for the specific cell - Array[line number (0 to x)][cell header]['options']
310      * @param $item Array[line number (0 to x)][cell header] = Cell content OR 
311      *              Array[line number (0 to x)][cell header]['value'] = Cell content AND 
312      *              Array[line number (0 to x)][cell header]['options'] = Array[cell properties] = values
313      * @param $options Array which can contain : width (array 'column name'=>'width value + % OR nothing'), isheader (bool), header (array), fill (string: HTML color), ishtml (bool) default: false, border (0: no border (defaul), 1: frame or all of the following characters: L ,T ,R ,B), align (L: left align, C: center, R: right align, J: justification)
314      * @see MultiCell()
315      */
316     public function writeCellTable($item, $options=NULL){
317         // Save initial font values
318         $fontFamily = $this->getFontFamily();
319         $fontSize = $this->getFontSizePt();
320         $fontStyle = $this->getFontStyle();
321         $this->SetTextColor(0, 0, 0);
322         
323         $options = $this->initOptionsForWriteCellTable($options, $item);
324         
325         // HEADER
326         if(!isset($options['isheader']) || $options['isheader'] == true){
327             $headerOptions = $options;
328             if(!empty($options['header']) && is_array($options['header'])){
329                 $headerOptions = $this->initOptionsForWriteCellTable($options['header'], $item);
330             }
331             foreach($item[0] as $k => $v){
332                 $header[$k]=$k;
333             }
334             $h = $this->getLineHeightFromArray($header, $options["width"]);
335             foreach($header as $v){
336                 $this->MultiCell($options["width"][$v],$h,$v,$headerOptions['border'],$headerOptions['align'],$headerOptions['fillstate'],0,'','',true,0,$headerOptions['ishtml']);
337             }
338             $this->SetFillColorArray($this->convertHTMLColorToDec($options['fill']));
339             $this->Ln();
340         }
341         
342         // MAIN
343         // default font
344         $this->SetFont($fontFamily,$fontStyle,$fontSize);
345         $this->SetTextColor(0, 0, 0);
346         $even=true;
347         // LINES
348         foreach($item as $k=>$line){
349             $even=!$even;
350             $h = $this->getLineHeightFromArray($line, $options["width"]);
351             //CELLS
352             foreach($line as $kk=>$cell){
353                 $cellOptions = $options;
354                 $value = $cell;
355                 
356                 if(is_array($cell)){
357                     $value = $cell['value'];
358                     if(!empty($cell['options']) && is_array($cell['options'])){
359                         $cellOptions = $this->initOptionsForWriteCellTable($cell['options'], $item);
360                     }
361                 }
362                 
363                 if($even && !empty($options['evencolor'])){
364                     $this->SetFillColorArray($this->convertHTMLColorToDec($options['evencolor']));
365                     $cellOptions['fillstate']=1;
366                 }else if(!$even && !empty($options['oddcolor'])){
367                     $this->SetFillColorArray($this->convertHTMLColorToDec($options['oddcolor']));
368                     $cellOptions['fillstate']=1;
369                 }
370                 
371                 $this->MultiCell($options["width"][$kk],$h,$value,$cellOptions['border'],$cellOptions['align'],$cellOptions['fillstate'],0,'','',true,0,$cellOptions['ishtml']);
372                 
373                 $this->SetFillColorArray($this->convertHTMLColorToDec($options['fill']));
374             }
375             $this->Ln();
376         }
377         $this->SetFont($fontFamily,$fontStyle,$fontSize);
378         $this->SetTextColor(0, 0, 0);
379     }
380     
381     /**
382      * This method allow printing a table using the writeHTML method with a formatted array in parameter
383      * This method can also return the table as HTML code
384      * @param $item Array[line number (0 to x)][cell header] = Cell content OR 
385      *              Array[line number (0 to x)][cell header]['value'] = Cell content AND 
386      *              Array[line number (0 to x)][cell header]['options'] = Array[cell properties] = values
387      * @param $returnHtml (bool) Return the table as HTML code instead of printing the HTML table
388      * @param $options Array which can contain : table (array of "HTML proprty"=>"value"),td (array of "HTML proprty"=>"value"), tr (array of "HTML proprty"=>"value"), isheader(bool), header (array of "HTML proprty"=>"value"), width (array 'column name'=>'width value + unit OR nothing')
389      * @return the HTML code if $returnHtml set to true
390      */
391     public function writeHTMLTable($item, $returnHtml=false, $options=NULL){
392         //TODO ISSUE - width in % for the td have to be multiply by the number of column.
393         //     ex: for a width of 20% in a table of 6 columns the width will have to be 120% (20*6).
394         $html="";
395         $line="";
396         if(!empty($options)){
397             foreach($options as $k=>$v){
398                 $tmp[strtolower($k)]=$v;
399             }
400             $options=$tmp;
401         }else{
402             $options=array();
403         }
404         if(!isset($options["isheader"]) || $options["isheader"] == true){
405             if(!empty($options["header"])){
406                 foreach($options["header"] as $k=>$v){
407                     $tmp[strtolower($k)]=$v;
408                 }
409                 $options["header"]=$tmp;
410             }else{
411                 $options["header"]=array("tr"=>array("bgcolor"=>"#DCDCDC"),"td"=>array());
412             }
413             
414             foreach($item[0] as $k => $v){
415                 if(!empty($options["width"]))$options["header"]["td"]["width"]=$options["width"][$k];
416                 $line.=$this->wrap("td", $k, $options["header"]);
417             }
418             $html.=$this->wrap("tr", $line, $options["header"]);
419         }
420         foreach ($item as $k=>$v){
421             $line="";
422             foreach($v as $kk => $vv){
423                 if(!empty($options["width"]) && isset($options["width"][$kk]))$options["td"]["width"]=$options["width"][$kk];
424                 $line.=$this->wrap("td", $vv, $options);
425             }
426             $html.=$this->wrap("tr", $line, $options);
427         }
428         $html=$this->wrap("table", $html, $options);
429         if($returnHtml){
430             return $html;
431         }else{
432             $this->writeHTML($html);
433         }
434     }
435     
436     /**
437      * return the HTML code of the value wrap with the tag $tag. This method handle options (general and specific)
438      * @param $tag
439      * @param $value
440      * @param $options
441      * @return the HTML wrapped code
442      */
443     private function wrap($tag, $value, $options){
444         if(empty($options[$tag])){
445             $options[$tag] = array();
446         }
447         if(is_array($value)){
448             if(isset($value["options"])){
449                 // The options of a specific entity overwrite the general options 
450                 $options[$tag] = $value["options"];
451             }
452             if(isset($value["value"])){
453                 $value = $value["value"];
454             }else{
455                 $value = "";
456             }
457         }
458         return wrapTag($tag, $value, $options[$tag]);
459     }
460     
461     /**
462      * Return the heigth of a line depending of the width, the font and the content
463      * @param $line Array containing the data of all the cells of the line
464      * @param $width Array containing the width of all the cells of the line
465      * @return The heigth of the line
466      */
467     private function getLineHeightFromArray($line, $width){
468         $h=0;
469         foreach($line as $kk=>$cell){
470             $cellValue = $cell;
471             if(is_array($cellValue)){
472                 $tmp = $cellValue['value'];
473                 $cellValue = $tmp;
474             }
475             if($h<$this->getNumLines($cellValue, $width[$kk])){
476                 $h=$this->getNumLines($cellValue, $width[$kk]);
477             }
478         }
479         return $h * $this->FontSize * $this->cell_height_ratio + 2 * $this->cMargin;
480     }
481     
482     /**
483      * Private method for writeCellTable which format and initialize the options array.
484      * @param $options array
485      * @param $item array
486      * @return $options array
487      */
488     private function initOptionsForWriteCellTable($options, $item){
489        if(!empty($options)){
490             foreach($options as $k=>$v){
491                 $tmp[strtolower($k)]=$v;
492             }
493             $options=$tmp;
494         }else{
495             $options=array();
496         }
497         // set to default if empty
498         if(empty($options["width"]) || !is_array($options["width"])){
499             $colNum = count($item[0]);
500             $defaultWidth = $this->getRemainingWidth()/$colNum;
501             foreach($item[0] as $k => $v){
502                 $options["width"][$k]=$defaultWidth;
503             }
504         }else{
505             foreach($options["width"] as $k => $v){
506                 $options["width"][$k] = $this->getHTMLUnitToUnits($v, $this->getRemainingWidth());
507             }
508             
509         }
510         
511         if(empty($options["border"])){
512             $options["border"]=0;
513         }
514         
515         if(empty($options["align"])){
516             $options["align"]="L";
517         }
518         
519         if(empty($options['ishtml'])){
520             $options['ishtml'] = false;
521         }
522         if(empty($options['border'])){
523             $options['border'] = 0;
524         }
525         
526         if(!empty($options['fill'])){
527             $this->SetFillColorArray($this->convertHTMLColorToDec($options['fill']));
528             $options['fillstate']=1;
529         }else{
530             $options['fill']="#FFFFFF";//white
531             $options['fillstate']=0;
532         }
533         
534         if(!empty($options['fontfamily'])){
535             $fontFamily = $options['fontfamily'];
536         }else{
537             $fontFamily = $this->getFontFamily();
538         }
539         if(!empty($options['fontsize'])){
540             $fontSize = $options['fontsize'];
541         }else{
542             $fontSize = $this->getFontSizePt();
543         }
544         if(!empty($options['fontstyle'])){
545             $fontStyle = $options['fontstyle'];
546         }else{
547             $fontStyle = $this->getFontStyle();
548         }
549         if(!empty($options['textcolor'])){
550             $this->SetTextColorArray($this->convertHTMLColorToDec($options['textcolor']));
551         }else{
552             $this->SetTextColor(0, 0, 0);//black
553         }
554
555         $this->SetFont($fontFamily, $fontStyle, $fontSize);
556         
557         return $options;
558     }
559     
560     /**
561     * This is method is fix for a better handling of the count. This method now handle the line break
562     * between words.
563     * This method returns the estimated number of lines required to print the text.
564     * @param string $txt text to print
565     * @param float $w width of cell. If 0, they extend up to the right margin of the page.
566     * @return int Return the estimated number of lines.
567     * @access public
568     * @since 4.5.011
569     * @OVERRIDE
570     */
571     public function getNumLines($txt, $w=0) {
572         $lines = 0;
573         if (empty($w) OR ($w <= 0)) {
574             if ($this->rtl) {
575                 $w = $this->x - $this->lMargin;
576             } else {
577                 $w = $this->w - $this->rMargin - $this->x;
578             }
579         }
580         // max column width
581         $wmax = $w - (2 * $this->cMargin);
582         // remove carriage returns
583         $txt = str_replace("\r", '', $txt);
584         // divide text in blocks
585         $txtblocks = explode("\n", $txt);
586         // for each block;
587         foreach ($txtblocks as $block) {
588             // estimate the number of lines
589             if(empty($block)){
590                 $lines++;
591             // If the block is in more than one line
592             }else if(ceil($this->GetStringWidth($block) / $wmax)>1){
593                 //devide in words
594                 $words = explode(" ", $block);
595                 //TODO explode with space is not the best things to do...
596                 $wordBlock = "";
597                 $first=true;
598                 $lastNum = 0;
599                 $run = false;
600                 
601                 for($i=0; $i<count($words); $i++){
602                     if($first){
603                         $wordBlock = $words[$i];
604                     }else{
605                         $wordBlock .= " ".$words[$i];
606                     }
607                     if(ceil($this->GetStringWidth($wordBlock) / $wmax)>1){
608                         if($first){
609                             $lastNum = ceil($this->GetStringWidth($wordBlock) / $wmax);
610                             $run = true;
611                             $first = false;
612                         }else{
613                             if($run && $lastNum == ceil($this->GetStringWidth($wordBlock) / $wmax)){
614                                 // save the number of line if it is the last loop
615                                 if($i+1 == count($words)){
616                                     $lines += ceil($this->GetStringWidth($wordBlock) / $wmax);
617                                 }
618                                 continue;
619                             }else{
620                                 $first = true;
621                                 $lines += ceil($this->GetStringWidth( substr($wordBlock, 0, (strlen($wordBlock) - strlen(" ".$words[$i]))) ) / $wmax);
622                                 $i--;
623                                 $lastNum = 0;
624                                 $run = false;
625                             }
626                         }
627
628                     }else{
629                         $first = false;
630                     }
631                     // save the number of line if it is the last loop
632                     if($i+1 == count($words)){
633                         $lines += ceil($this->GetStringWidth($wordBlock) / $wmax);
634                     }
635                 }
636                 
637             }else{
638                 $lines++;
639             }
640         }
641         return $lines;
642     }
643     
644     /**
645      * Disable zlib output compression if we are downloading the PDF.
646      *
647      * @see TCPDF::Output()
648      */
649     public function Output($name='doc.pdf', $dest='I') 
650     {
651         if ( $dest == 'I' || $dest == 'D') {
652             ini_set('zlib.output_compression', 'Off');
653         }
654         
655         return parent::Output($name,$dest);
656     }
657 }
658