Merge pull request #19497 from eileenmcnaughton/534
[civicrm-core.git] / CRM / Utils / PDF / Utils.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
5 | |
6 | This work is published under the GNU AGPLv3 license with some |
7 | permitted exceptions and without any warranty. For full license |
8 | and copyright information, see https://civicrm.org/licensing |
9 +--------------------------------------------------------------------+
10 */
11
12
13 use Dompdf\Dompdf;
14 use Dompdf\Options;
15
16 /**
17 *
18 * @package CRM
19 * @copyright CiviCRM LLC https://civicrm.org/licensing
20 */
21 class CRM_Utils_PDF_Utils {
22
23 /**
24 * @param array $text
25 * List of HTML snippets.
26 * @param string $fileName
27 * The logical filename to display.
28 * Ex: "HelloWorld.pdf".
29 * @param bool $output
30 * FALSE to display PDF. TRUE to return as string.
31 * @param null $pdfFormat
32 * Unclear. Possibly PdfFormat or formValues.
33 *
34 * @return string|void
35 */
36 public static function html2pdf($text, $fileName = 'civicrm.pdf', $output = FALSE, $pdfFormat = NULL) {
37 if (is_array($text)) {
38 $pages = &$text;
39 }
40 else {
41 $pages = [$text];
42 }
43 // Get PDF Page Format
44 $format = CRM_Core_BAO_PdfFormat::getDefaultValues();
45 if (is_array($pdfFormat)) {
46 // PDF Page Format parameters passed in
47 $format = array_merge($format, $pdfFormat);
48 }
49 elseif (!empty($pdfFormat)) {
50 // PDF Page Format ID passed in
51 $format = CRM_Core_BAO_PdfFormat::getById($pdfFormat);
52 }
53 $paperSize = CRM_Core_BAO_PaperSize::getByName($format['paper_size']);
54 $paper_width = self::convertMetric($paperSize['width'], $paperSize['metric'], 'pt');
55 $paper_height = self::convertMetric($paperSize['height'], $paperSize['metric'], 'pt');
56 // dompdf requires dimensions in points
57 $paper_size = [0, 0, $paper_width, $paper_height];
58 $orientation = CRM_Core_BAO_PdfFormat::getValue('orientation', $format);
59 $metric = CRM_Core_BAO_PdfFormat::getValue('metric', $format);
60 $t = CRM_Core_BAO_PdfFormat::getValue('margin_top', $format);
61 $r = CRM_Core_BAO_PdfFormat::getValue('margin_right', $format);
62 $b = CRM_Core_BAO_PdfFormat::getValue('margin_bottom', $format);
63 $l = CRM_Core_BAO_PdfFormat::getValue('margin_left', $format);
64
65 $margins = [$metric, $t, $r, $b, $l];
66
67 // Add a special region for the HTML header of PDF files:
68 $pdfHeaderRegion = CRM_Core_Region::instance('export-document-header', FALSE);
69 $htmlHeader = ($pdfHeaderRegion) ? $pdfHeaderRegion->render('', FALSE) : '';
70
71 $html = "
72 <html>
73 <head>
74 <meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\"/>
75 <style>@page { margin: {$t}{$metric} {$r}{$metric} {$b}{$metric} {$l}{$metric}; }</style>
76 <style type=\"text/css\">@import url(" . CRM_Core_Config::singleton()->userFrameworkResourceURL . "css/print.css);</style>
77 {$htmlHeader}
78 </head>
79 <body>
80 <div id=\"crm-container\">\n";
81
82 // Strip <html>, <header>, and <body> tags from each page
83
84 $htmlElementstoStrip = [
85 '<head[^>]*?>.*?</head>',
86 '<script[^>]*?>.*?</script>',
87 '<body>',
88 '</body>',
89 '<html[^>]*?>',
90 '</html>',
91 '<!DOCTYPE[^>]*?>',
92 ];
93 foreach ($pages as & $page) {
94 foreach ($htmlElementstoStrip as $pattern) {
95 $page = mb_eregi_replace($pattern, '', $page);
96 }
97 }
98 // Glue the pages together
99 $html .= implode("\n<div style=\"page-break-after: always\"></div>\n", $pages);
100 $html .= "
101 </div>
102 </body>
103 </html>";
104 if (CRM_Core_Config::singleton()->wkhtmltopdfPath) {
105 return self::_html2pdf_wkhtmltopdf($paper_size, $orientation, $margins, $html, $output, $fileName);
106 }
107 else {
108 return self::_html2pdf_dompdf($paper_size, $orientation, $html, $output, $fileName);
109 }
110 }
111
112 /**
113 * Convert html to tcpdf.
114 *
115 * @deprecated
116 * @param $paper_size
117 * @param $orientation
118 * @param $margins
119 * @param $html
120 * @param $output
121 * @param $fileName
122 * @param $stationery_path
123 */
124 public static function _html2pdf_tcpdf($paper_size, $orientation, $margins, $html, $output, $fileName, $stationery_path) {
125 CRM_Core_Error::deprecatedFunctionWarning('CRM_Utils_PDF::_html2pdf_dompdf');
126 return self::_html2pdf_dompdf($paper_size, $orientation, $margins, $html, $output, $fileName);
127 // Documentation on the TCPDF library can be found at: http://www.tcpdf.org
128 // This function also uses the FPDI library documented at: http://www.setasign.com/products/fpdi/about/
129 // Syntax borrowed from https://github.com/jake-mw/CDNTaxReceipts/blob/master/cdntaxreceipts.functions.inc
130 require_once 'tcpdf/tcpdf.php';
131 // This library is only in the 'packages' area as of version 4.5
132 require_once 'FPDI/fpdi.php';
133
134 $paper_size_arr = [$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();
170 }
171
172 /**
173 * @param $paper_size
174 * @param $orientation
175 * @param $html
176 * @param $output
177 * @param string $fileName
178 *
179 * @return string
180 */
181 public static function _html2pdf_dompdf($paper_size, $orientation, $html, $output, $fileName) {
182 // CRM-12165 - Remote file support required for image handling.
183 $options = new Options();
184 $options->set('isRemoteEnabled', TRUE);
185
186 $dompdf = new DOMPDF($options);
187 $dompdf->set_paper($paper_size, $orientation);
188 $dompdf->load_html($html);
189 $dompdf->render();
190
191 if ($output) {
192 return $dompdf->output();
193 }
194 // CRM-19183 remove .pdf extension from filename
195 $fileName = basename($fileName, ".pdf");
196 if (CIVICRM_UF === 'UnitTests' && headers_sent()) {
197 // Streaming content will 'die' in unit tests unless ob_start()
198 // has been called.
199 throw new CRM_Core_Exception_PrematureExitException('_html2pdf_dompdf called', [
200 'html' => $html,
201 'fileName' => $fileName,
202 ]);
203 }
204 $dompdf->stream($fileName);
205 }
206
207 /**
208 * @param $paper_size
209 * @param $orientation
210 * @param $margins
211 * @param $html
212 * @param $output
213 * @param string $fileName
214 */
215 public static function _html2pdf_wkhtmltopdf($paper_size, $orientation, $margins, $html, $output, $fileName) {
216 $config = CRM_Core_Config::singleton();
217 // if the path doesn't exist fall back on the current backup which is DOMPDF.
218 if (!file_exists($config->wkhtmltopdfPath)) {
219 return self::_html2pdf_dompdf($paper_size, $orientation, $html, $output, $fileName);
220 }
221 require_once 'snappy/src/autoload.php';
222 $snappy = new Knp\Snappy\Pdf($config->wkhtmltopdfPath);
223 $snappy->setOption("page-width", $paper_size[2] . "pt");
224 $snappy->setOption("page-height", $paper_size[3] . "pt");
225 $snappy->setOption("orientation", $orientation);
226 $snappy->setOption("margin-top", $margins[1] . $margins[0]);
227 $snappy->setOption("margin-right", $margins[2] . $margins[0]);
228 $snappy->setOption("margin-bottom", $margins[3] . $margins[0]);
229 $snappy->setOption("margin-left", $margins[4] . $margins[0]);
230 $pdf = $snappy->getOutputFromHtml($html);
231 if ($output) {
232 return $pdf;
233 }
234 else {
235 CRM_Utils_System::setHttpHeader('Content-Type', 'application/pdf');
236 CRM_Utils_System::setHttpHeader('Content-Disposition', 'attachment; filename="' . $fileName . '"');
237 echo $pdf;
238 }
239 }
240
241 /**
242 * convert value from one metric to another.
243 *
244 * @param $value
245 * @param $from
246 * @param $to
247 * @param null $precision
248 *
249 * @return float|int
250 */
251 public static function convertMetric($value, $from, $to, $precision = NULL) {
252 switch ($from . $to) {
253 case 'incm':
254 $value *= 2.54;
255 break;
256
257 case 'inmm':
258 $value *= 25.4;
259 break;
260
261 case 'inpt':
262 $value *= 72;
263 break;
264
265 case 'cmin':
266 $value /= 2.54;
267 break;
268
269 case 'cmmm':
270 $value *= 10;
271 break;
272
273 case 'cmpt':
274 $value *= 72 / 2.54;
275 break;
276
277 case 'mmin':
278 $value /= 25.4;
279 break;
280
281 case 'mmcm':
282 $value /= 10;
283 break;
284
285 case 'mmpt':
286 $value *= 72 / 25.4;
287 break;
288
289 case 'ptin':
290 $value /= 72;
291 break;
292
293 case 'ptcm':
294 $value *= 2.54 / 72;
295 break;
296
297 case 'ptmm':
298 $value *= 25.4 / 72;
299 break;
300 }
301 if (!is_null($precision)) {
302 $value = round($value, $precision);
303 }
304 return $value;
305 }
306
307 }