Merge pull request #3543 from eileenmcnaughton/CRM-14850
[civicrm-core.git] / CRM / Utils / PDF / Utils.php
CommitLineData
6a488035
TO
1<?php
2/*
3 +--------------------------------------------------------------------+
06b69b18 4 | CiviCRM version 4.5 |
6a488035 5 +--------------------------------------------------------------------+
06b69b18 6 | Copyright CiviCRM LLC (c) 2004-2014 |
6a488035
TO
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
06b69b18 31 * @copyright CiviCRM LLC (c) 2004-2014
6a488035
TO
32 * $Id$
33 *
34 */
35class CRM_Utils_PDF_Utils {
36
5bc392e6
EM
37 /**
38 * @param $text
39 * @param string $fileName
40 * @param bool $output
41 * @param null $pdfFormat
42 *
43 * @return string|void
44 */
6a488035
TO
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 $margins = array($metric,$t,$r,$b,$l);
74
75 $config = CRM_Core_Config::singleton();
76 $html = "
77<html>
78 <head>
79 <meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\"/>
80 <style>@page { margin: {$t}{$metric} {$r}{$metric} {$b}{$metric} {$l}{$metric}; }</style>
81 <style type=\"text/css\">@import url({$config->userFrameworkResourceURL}css/print.css);</style>
82 </head>
83 <body>
84 <div id=\"crm-container\">\n";
85
86 // Strip <html>, <header>, and <body> tags from each page
87 $htmlElementstoStrip = array(
88 '@<head[^>]*?>.*?</head>@siu',
89 '@<body>@siu',
90 '@</body>@siu',
91 '@<html[^>]*?>@siu',
92 '@</html>@siu',
93 '@<!DOCTYPE[^>]*?>@siu',
94 );
95 $htmlElementsInstead = array('', '', '', '', '', '');
96 foreach ($pages as & $page) {
97 $page = preg_replace($htmlElementstoStrip,
98 $htmlElementsInstead,
99 $page
100 );
101 }
102 // Glue the pages together
103 $html .= implode("\n<div style=\"page-break-after: always\"></div>\n", $pages);
104 $html .= "
105 </div>
106 </body>
107</html>";
108 if ($config->wkhtmltopdfPath) {
109 return self::_html2pdf_wkhtmltopdf($paper_size, $orientation, $margins, $html, $output, $fileName);
110 }
111 else {
112 return self::_html2pdf_dompdf($paper_size, $orientation, $html, $output, $fileName);
113 }
114 }
115
5bc392e6
EM
116 /**
117 * @param $paper_size
118 * @param $orientation
119 * @param $html
120 * @param $output
121 * @param $fileName
122 *
123 * @return string
124 */
6a488035
TO
125 static function _html2pdf_dompdf($paper_size, $orientation, $html, $output, $fileName) {
126 require_once 'packages/dompdf/dompdf_config.inc.php';
127 spl_autoload_register('DOMPDF_autoload');
128 $dompdf = new DOMPDF();
129 $dompdf->set_paper($paper_size, $orientation);
130 $dompdf->load_html($html);
131 $dompdf->render();
132
133 if ($output) {
134 return $dompdf->output();
135 }
136 else {
137 $dompdf->stream($fileName);
138 }
139 }
140
5bc392e6
EM
141 /**
142 * @param $paper_size
143 * @param $orientation
144 * @param $margins
145 * @param $html
146 * @param $output
147 * @param $fileName
148 */
6a488035
TO
149 static function _html2pdf_wkhtmltopdf($paper_size, $orientation, $margins, $html, $output, $fileName) {
150 require_once 'packages/snappy/src/autoload.php';
151 $config = CRM_Core_Config::singleton();
152 $snappy = new Knp\Snappy\Pdf($config->wkhtmltopdfPath);
153 $snappy->setOption("page-width", $paper_size[2] . "pt");
154 $snappy->setOption("page-height", $paper_size[3] . "pt");
155 $snappy->setOption("orientation", $orientation);
156 $snappy->setOption("margin-top", $margins[1] . $margins[0]);
157 $snappy->setOption("margin-right", $margins[2] . $margins[0]);
158 $snappy->setOption("margin-bottom", $margins[3] . $margins[0]);
159 $snappy->setOption("margin-left", $margins[4] . $margins[0]);
160 $pdf = $snappy->getOutputFromHtml($html);
161 if ($output) {
162 return $pdf;
163 }
164 else {
165 header('Content-Type: application/pdf');
166 header('Content-Disposition: attachment; filename="' . $fileName . '"');
167 echo $pdf;
168 }
169 }
170
171 /*
172 * function to convert value from one metric to another
173 */
5bc392e6
EM
174 /**
175 * @param $value
176 * @param $from
177 * @param $to
178 * @param null $precision
179 *
180 * @return float|int
181 */
6a488035
TO
182 static function convertMetric($value, $from, $to, $precision = NULL) {
183 switch ($from . $to) {
184 case 'incm':
185 $value *= 2.54;
186 break;
187
188 case 'inmm':
189 $value *= 25.4;
190 break;
191
192 case 'inpt':
193 $value *= 72;
194 break;
195
196 case 'cmin':
197 $value /= 2.54;
198 break;
199
200 case 'cmmm':
201 $value *= 10;
202 break;
203
204 case 'cmpt':
205 $value *= 72 / 2.54;
206 break;
207
208 case 'mmin':
209 $value /= 25.4;
210 break;
211
212 case 'mmcm':
213 $value /= 10;
214 break;
215
216 case 'mmpt':
217 $value *= 72 / 25.4;
218 break;
219
220 case 'ptin':
221 $value /= 72;
222 break;
223
224 case 'ptcm':
225 $value *= 2.54 / 72;
226 break;
227
228 case 'ptmm':
229 $value *= 25.4 / 72;
230 break;
231 }
232 if (!is_null($precision)) {
233 $value = round($value, $precision);
234 }
235 return $value;
236 }
237
5bc392e6
EM
238 /**
239 * @param $fileName
240 * @param $searchPath
241 * @param $values
242 * @param int $numPages
243 * @param bool $echo
244 * @param string $output
245 * @param string $creator
246 * @param string $author
247 * @param string $title
248 */
6a488035
TO
249 static function &pdflib($fileName,
250 $searchPath,
251 &$values,
252 $numPages = 1,
253 $echo = TRUE,
254 $output = 'College_Match_App',
255 $creator = 'CiviCRM',
256 $author = 'http://www.civicrm.org/',
257 $title = '2006 College Match Scholarship Application'
258 ) {
259 try {
260 $pdf = new PDFlib();
261 $pdf->set_parameter("compatibility", "1.6");
262 $pdf->set_parameter("licensefile", "/home/paras/bin/license/pdflib.txt");
263
264 if ($pdf->begin_document('', '') == 0) {
265 CRM_Core_Error::statusBounce("PDFlib Error: " . $pdf->get_errmsg());
266 }
267
268 $config = CRM_Core_Config::singleton();
269 $pdf->set_parameter('resourcefile', $config->templateDir . '/Quest/pdf/pdflib.upr');
270 $pdf->set_parameter('textformat', 'utf8');
271
272 /* Set the search path for fonts and PDF files */
273
274 $pdf->set_parameter('SearchPath', $searchPath);
275
276 /* This line is required to avoid problems on Japanese systems */
277
278 $pdf->set_parameter('hypertextencoding', 'winansi');
279
280 $pdf->set_info('Creator', $creator);
281 $pdf->set_info('Author', $author);
282 $pdf->set_info('Title', $title);
283
284 $blockContainer = $pdf->open_pdi($fileName, '', 0);
285 if ($blockContainer == 0) {
286 CRM_Core_Error::statusBounce('PDFlib Error: ' . $pdf->get_errmsg());
287 }
288
289 for ($i = 1; $i <= $numPages; $i++) {
290 $page = $pdf->open_pdi_page($blockContainer, $i, '');
291 if ($page == 0) {
292 CRM_Core_Error::statusBounce('PDFlib Error: ' . $pdf->get_errmsg());
293 }
294
295 /* dummy page size */
296 $pdf->begin_page_ext(20, 20, '');
297
298 /* This will adjust the page size to the block container's size. */
299
300 $pdf->fit_pdi_page($page, 0, 0, 'adjustpage');
301
302
303 $status = array();
304 /* Fill all text blocks with dynamic data */
305
306 foreach ($values as $key => $value) {
307 if (is_array($value)) {
308 continue;
309 }
310
311 // pdflib does like the forward slash character, hence convert
312 $value = str_replace('/', '_', $value);
313
314 $res = $pdf->fill_textblock($page,
315 $key,
316 $value,
317 'embedding encoding=winansi'
318 );
319
320 /**
321 if ( $res == 0 ) {
322 CRM_Core_Error::debug( "$key, $value: $res", $pdf->get_errmsg( ) );
323 } else {
324 CRM_Core_Error::debug( "SUCCESS: $key, $value", null );
325 }
326 **/
327 }
328
329 $pdf->end_page_ext('');
330 $pdf->close_pdi_page($page);
331 }
332
333 $pdf->end_document('');
334 $pdf->close_pdi($blockContainer);
335
336 $buf = $pdf->get_buffer();
337 $len = strlen($buf);
338
339 if ($echo) {
340 header('Content-type: application/pdf');
341 header("Content-Length: $len");
342 header("Content-Disposition: inline; filename={$output}.pdf");
343 echo $buf;
344 CRM_Utils_System::civiExit();
345 }
346 else {
347 return $buf;
348 }
349 }
350 catch(PDFlibException$excp) {
351 CRM_Core_Error::statusBounce('PDFlib Error: Exception' .
352 "[" . $excp->get_errnum() . "] " . $excp->get_apiname() . ": " .
353 $excp->get_errmsg()
354 );
355 }
356 catch(Exception$excp) {
357 CRM_Core_Error::statusBounce("PDFlib Error: " . $excp->get_errmsg());
358 }
359 }
360}
361