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