Merge commit '227e59a6a8437' into 4.5-missing-prs
[civicrm-core.git] / CRM / Utils / PDF / Utils.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.5 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2014 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
9 | |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
13 | |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
18 | |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
26 */
27
28 /**
29 *
30 * @package CRM
31 * @copyright CiviCRM LLC (c) 2004-2014
32 * $Id$
33 *
34 */
35 class CRM_Utils_PDF_Utils {
36
37 /**
38 * @param $text
39 * @param string $fileName
40 * @param bool $output
41 * @param null $pdfFormat
42 *
43 * @return string|void
44 */
45 static function html2pdf(&$text, $fileName = 'civicrm.pdf', $output = FALSE, $pdfFormat = NULL) {
46 if (is_array($text)) {
47 $pages = &$text;
48 }
49 else {
50 $pages = array($text);
51 }
52 // Get PDF Page Format
53 $format = CRM_Core_BAO_PdfFormat::getDefaultValues();
54 if (is_array($pdfFormat)) {
55 // PDF Page Format parameters passed in
56 $format = array_merge($format, $pdfFormat);
57 }
58 else {
59 // PDF Page Format ID passed in
60 $format = CRM_Core_BAO_PdfFormat::getById($pdfFormat);
61 }
62 $paperSize = CRM_Core_BAO_PaperSize::getByName($format['paper_size']);
63 $paper_width = self::convertMetric($paperSize['width'], $paperSize['metric'], 'pt');
64 $paper_height = self::convertMetric($paperSize['height'], $paperSize['metric'], 'pt');
65 // dompdf requires dimensions in points
66 $paper_size = array(0, 0, $paper_width, $paper_height);
67 $orientation = CRM_Core_BAO_PdfFormat::getValue('orientation', $format);
68 $metric = CRM_Core_BAO_PdfFormat::getValue('metric', $format);
69 $t = CRM_Core_BAO_PdfFormat::getValue('margin_top', $format);
70 $r = CRM_Core_BAO_PdfFormat::getValue('margin_right', $format);
71 $b = CRM_Core_BAO_PdfFormat::getValue('margin_bottom', $format);
72 $l = CRM_Core_BAO_PdfFormat::getValue('margin_left', $format);
73
74 $stationery_path_partial = CRM_Core_BAO_PdfFormat::getValue('stationery', $format);
75
76 $stationery_path = NULL;
77 if (strlen($stationery_path_partial)) {
78 $doc_root = $_SERVER['DOCUMENT_ROOT'];
79 $stationery_path = $doc_root . "/" . $stationery_path_partial;
80 }
81
82 $margins = array($metric,$t,$r,$b,$l);
83
84 $config = CRM_Core_Config::singleton();
85 $html = "
86 <html>
87 <head>
88 <meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\"/>
89 <style>@page { margin: {$t}{$metric} {$r}{$metric} {$b}{$metric} {$l}{$metric}; }</style>
90 <style type=\"text/css\">@import url({$config->userFrameworkResourceURL}css/print.css);</style>
91 </head>
92 <body>
93 <div id=\"crm-container\">\n";
94
95 // Strip <html>, <header>, and <body> tags from each page
96 $htmlElementstoStrip = array(
97 '@<head[^>]*?>.*?</head>@siu',
98 '@<script[^>]*?>.*?</script>@siu',
99 '@<body>@siu',
100 '@</body>@siu',
101 '@<html[^>]*?>@siu',
102 '@</html>@siu',
103 '@<!DOCTYPE[^>]*?>@siu',
104 );
105 $htmlElementsInstead = array('', '', '', '', '', '');
106 foreach ($pages as & $page) {
107 $page = preg_replace($htmlElementstoStrip,
108 $htmlElementsInstead,
109 $page
110 );
111 }
112 // Glue the pages together
113 $html .= implode("\n<div style=\"page-break-after: always\"></div>\n", $pages);
114 $html .= "
115 </div>
116 </body>
117 </html>";
118 if ($config->wkhtmltopdfPath) {
119 return self::_html2pdf_wkhtmltopdf($paper_size, $orientation, $margins, $html, $output, $fileName);
120 }
121 else {
122 return self::_html2pdf_dompdf($paper_size, $orientation, $html, $output, $fileName);
123 //return self::_html2pdf_tcpdf($paper_size, $orientation, $margins, $html, $output, $fileName, $stationery_path);
124 }
125 }
126
127 static function _html2pdf_tcpdf($paper_size, $orientation, $margins, $html, $output, $fileName, $stationery_path) {
128 // Documentation on the TCPDF library can be found at: http://www.tcpdf.org
129 // This function also uses the FPDI library documented at: http://www.setasign.com/products/fpdi/about/
130 // Syntax borrowed from https://github.com/jake-mw/CDNTaxReceipts/blob/master/cdntaxreceipts.functions.inc
131 require_once 'tcpdf/tcpdf.php';
132 require_once('FPDI/fpdi.php'); // This library is only in the 'packages' area as of version 4.5
133
134 $paper_size_arr = array( $paper_size[2], $paper_size[3]);
135
136 $pdf = new TCPDF($orientation, 'pt', $paper_size_arr);
137 $pdf->Open();
138
139 if (is_readable($stationery_path)){
140 $pdf->SetStationery( $stationery_path );
141 }
142
143 $pdf->SetAuthor('');
144 $pdf->SetKeywords('CiviCRM.org');
145 $pdf->setPageUnit( $margins[0] ) ;
146 $pdf->SetMargins($margins[4], $margins[1], $margins[2], true);
147
148 $pdf->setJPEGQuality('100');
149 $pdf->SetAutoPageBreak(true, $margins[3]);
150
151 $pdf->AddPage();
152
153 $ln = true ;
154 $fill = false ;
155 $reset_parm = false;
156 $cell = false;
157 $align = '' ;
158
159 // output the HTML content
160 $pdf->writeHTML($html, $ln, $fill, $reset_parm, $cell, $align);
161
162 // reset pointer to the last page
163 $pdf->lastPage();
164
165 // close and output the PDF
166 $pdf->Close();
167 $pdf_file = 'CiviLetter'.'.pdf';
168 $pdf->Output($pdf_file, 'D');
169 CRM_Utils_System::civiExit(1);
170 }
171
172 /**
173 * @param $paper_size
174 * @param $orientation
175 * @param $html
176 * @param $output
177 * @param $fileName
178 *
179 * @return string
180 */
181 static function _html2pdf_dompdf($paper_size, $orientation, $html, $output, $fileName) {
182 // CRM-12165 - Remote file support required for image handling.
183 define("DOMPDF_ENABLE_REMOTE", true);
184 define('DOMPDF_ENABLE_AUTOLOAD', false);
185 require_once 'packages/vendor/dompdf/dompdf/dompdf_config.inc.php';
186
187 $dompdf = new DOMPDF();
188 $dompdf->set_paper($paper_size, $orientation);
189 $dompdf->load_html($html);
190 $dompdf->render();
191
192 if ($output) {
193 return $dompdf->output();
194 }
195 else {
196 $dompdf->stream($fileName);
197 }
198 }
199
200 /**
201 * @param $paper_size
202 * @param $orientation
203 * @param $margins
204 * @param $html
205 * @param $output
206 * @param $fileName
207 */
208 static function _html2pdf_wkhtmltopdf($paper_size, $orientation, $margins, $html, $output, $fileName) {
209 require_once 'packages/snappy/src/autoload.php';
210 $config = CRM_Core_Config::singleton();
211 $snappy = new Knp\Snappy\Pdf($config->wkhtmltopdfPath);
212 $snappy->setOption("page-width", $paper_size[2] . "pt");
213 $snappy->setOption("page-height", $paper_size[3] . "pt");
214 $snappy->setOption("orientation", $orientation);
215 $snappy->setOption("margin-top", $margins[1] . $margins[0]);
216 $snappy->setOption("margin-right", $margins[2] . $margins[0]);
217 $snappy->setOption("margin-bottom", $margins[3] . $margins[0]);
218 $snappy->setOption("margin-left", $margins[4] . $margins[0]);
219 $pdf = $snappy->getOutputFromHtml($html);
220 if ($output) {
221 return $pdf;
222 }
223 else {
224 header('Content-Type: application/pdf');
225 header('Content-Disposition: attachment; filename="' . $fileName . '"');
226 echo $pdf;
227 }
228 }
229
230 /*
231 * function to convert value from one metric to another
232 */
233 /**
234 * @param $value
235 * @param $from
236 * @param $to
237 * @param null $precision
238 *
239 * @return float|int
240 */
241 static function convertMetric($value, $from, $to, $precision = NULL) {
242 switch ($from . $to) {
243 case 'incm':
244 $value *= 2.54;
245 break;
246
247 case 'inmm':
248 $value *= 25.4;
249 break;
250
251 case 'inpt':
252 $value *= 72;
253 break;
254
255 case 'cmin':
256 $value /= 2.54;
257 break;
258
259 case 'cmmm':
260 $value *= 10;
261 break;
262
263 case 'cmpt':
264 $value *= 72 / 2.54;
265 break;
266
267 case 'mmin':
268 $value /= 25.4;
269 break;
270
271 case 'mmcm':
272 $value /= 10;
273 break;
274
275 case 'mmpt':
276 $value *= 72 / 25.4;
277 break;
278
279 case 'ptin':
280 $value /= 72;
281 break;
282
283 case 'ptcm':
284 $value *= 2.54 / 72;
285 break;
286
287 case 'ptmm':
288 $value *= 25.4 / 72;
289 break;
290 }
291 if (!is_null($precision)) {
292 $value = round($value, $precision);
293 }
294 return $value;
295 }
296
297 /**
298 * @param $fileName
299 * @param $searchPath
300 * @param $values
301 * @param int $numPages
302 * @param bool $echo
303 * @param string $output
304 * @param string $creator
305 * @param string $author
306 * @param string $title
307 */
308 static function &pdflib($fileName,
309 $searchPath,
310 &$values,
311 $numPages = 1,
312 $echo = TRUE,
313 $output = 'College_Match_App',
314 $creator = 'CiviCRM',
315 $author = 'http://www.civicrm.org/',
316 $title = '2006 College Match Scholarship Application'
317 ) {
318 try {
319 $pdf = new PDFlib();
320 $pdf->set_parameter("compatibility", "1.6");
321 $pdf->set_parameter("licensefile", "/home/paras/bin/license/pdflib.txt");
322
323 if ($pdf->begin_document('', '') == 0) {
324 CRM_Core_Error::statusBounce("PDFlib Error: " . $pdf->get_errmsg());
325 }
326
327 $config = CRM_Core_Config::singleton();
328 $pdf->set_parameter('resourcefile', $config->templateDir . '/Quest/pdf/pdflib.upr');
329 $pdf->set_parameter('textformat', 'utf8');
330
331 /* Set the search path for fonts and PDF files */
332
333 $pdf->set_parameter('SearchPath', $searchPath);
334
335 /* This line is required to avoid problems on Japanese systems */
336
337 $pdf->set_parameter('hypertextencoding', 'winansi');
338
339 $pdf->set_info('Creator', $creator);
340 $pdf->set_info('Author', $author);
341 $pdf->set_info('Title', $title);
342
343 $blockContainer = $pdf->open_pdi($fileName, '', 0);
344 if ($blockContainer == 0) {
345 CRM_Core_Error::statusBounce('PDFlib Error: ' . $pdf->get_errmsg());
346 }
347
348 for ($i = 1; $i <= $numPages; $i++) {
349 $page = $pdf->open_pdi_page($blockContainer, $i, '');
350 if ($page == 0) {
351 CRM_Core_Error::statusBounce('PDFlib Error: ' . $pdf->get_errmsg());
352 }
353
354 /* dummy page size */
355 $pdf->begin_page_ext(20, 20, '');
356
357 /* This will adjust the page size to the block container's size. */
358
359 $pdf->fit_pdi_page($page, 0, 0, 'adjustpage');
360
361
362 $status = array();
363 /* Fill all text blocks with dynamic data */
364
365 foreach ($values as $key => $value) {
366 if (is_array($value)) {
367 continue;
368 }
369
370 // pdflib does like the forward slash character, hence convert
371 $value = str_replace('/', '_', $value);
372
373 $res = $pdf->fill_textblock($page,
374 $key,
375 $value,
376 'embedding encoding=winansi'
377 );
378
379 /**
380 if ( $res == 0 ) {
381 CRM_Core_Error::debug( "$key, $value: $res", $pdf->get_errmsg( ) );
382 } else {
383 CRM_Core_Error::debug( "SUCCESS: $key, $value", null );
384 }
385 **/
386 }
387
388 $pdf->end_page_ext('');
389 $pdf->close_pdi_page($page);
390 }
391
392 $pdf->end_document('');
393 $pdf->close_pdi($blockContainer);
394
395 $buf = $pdf->get_buffer();
396 $len = strlen($buf);
397
398 if ($echo) {
399 header('Content-type: application/pdf');
400 header("Content-Length: $len");
401 header("Content-Disposition: inline; filename={$output}.pdf");
402 echo $buf;
403 CRM_Utils_System::civiExit();
404 }
405 else {
406 return $buf;
407 }
408 }
409 catch(PDFlibException$excp) {
410 CRM_Core_Error::statusBounce('PDFlib Error: Exception' .
411 "[" . $excp->get_errnum() . "] " . $excp->get_apiname() . ": " .
412 $excp->get_errmsg()
413 );
414 }
415 catch(Exception$excp) {
416 CRM_Core_Error::statusBounce("PDFlib Error: " . $excp->get_errmsg());
417 }
418 }
419 }
420