Corrected TeX ligatures for pdf letters
[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
22 class CRM_Utils_PDF_Utils {
23
24 public static function enqueuePDF($pdf) {
25
26 $fname = time().'_lp.pdf';
27 file_put_contents('/tmp/'.$fname, $pdf);
28 header('Location: /civicrm/lp-setup?file='.$fname);
29 exit;
30
31 }
32
33 public static function latex2pdf(&$text, $fileName = 'civicrm.pdf', $output = FALSE, $pdfFormat = NULL) {
34 /* FIXME: get $paper_size, $orientation, $margins */
35
36 if (is_array($text)) {
37 $pages = &$text;
38 }
39 else {
40 $pages = array($text);
41 }
42
43 $head='\documentclass[12pt]{letter}
44 \usepackage{url}
45 \usepackage{ucs}
46 \usepackage{array}
47 \usepackage{graphicx}
48 \usepackage[T1]{fontenc}
49 \usepackage{fullpage}
50 \usepackage{fontspec,xunicode}
51 %% VERY IMPORTANT. Configures supported languages and fonts to use for each one.
52 \usepackage[Latin, Hebrew, Arabics, CJK, Diacritics]{ucharclasses}
53 \newfontfamily{\normalfont}[Ligatures=TeX]{FreeSerif}
54 \newfontfamily{\cjkfont}{WenQuanYi Zen Hei}
55 \setDefaultTransitions{\normalfont}{}
56 \setTransitionsForLatin{\normalfont}{}
57 \setTransitionsForArabics{\normalfont}{}
58 \setTransitionsForCJK{\cjkfont}{}
59 \setTransitionsForDiacritics{\normalfont}{}
60 \setTransitionTo{Hebrew}{\normalfont}
61 \setmainfont{FreeSerif}
62
63 \newcommand{\fsfclosing}[1]{\par\nobreak\vspace{\parskip}
64 \stopbreaks
65 \noindent
66 \ifx\@empty\fromaddress\else
67 \hspace*{\longindentation}\fi
68 \parbox{\indentedwidth}{\raggedright
69 \ignorespaces #1\\\\[1\medskipamount]
70 \hspace*{-0.25in}\includegraphics[scale=1.0]{/var/www/drupal-7.27/sites/all/modules/civicrm/sigjohns.pdf}
71 \\\\
72
73 \ifx\@empty\fromsig
74 \fromname
75 \else \fromsig \fi\strut}
76 \par}
77 \medskipamount=\parskip
78
79 \pagestyle{empty}
80 \tolerance=8000
81 \address{\vspace{0.05in}}
82 \signature{John Sullivan \\\\ Executive Director}
83 \usepackage[
84 top = 1.5in,
85 bottom = 1.25in,
86 left = 1.0in,
87 right = 1.0in]{geometry}
88 \begin{document}
89 ';
90 $footer='
91 \end{document}';
92
93 $latex = $head;
94 foreach ($pages as $page) {
95 $latex.=$page;
96 }
97 $latex.=$footer;
98
99 $descriptorspec = array(
100 0 => array("pipe", "r"),
101 1 => array("pipe", "w")
102 );
103
104
105
106 $process = proc_open("/usr/local/bin/pdflatex_wrapper.sh", $descriptorspec, $pipes);
107
108
109 if (is_resource($process)) {
110 fwrite($pipes[0], $latex);
111 fclose($pipes[0]);
112
113 $pdf = stream_get_contents($pipes[1]);
114 fclose($pipes[1]);
115 } else {
116 CRM_Core_Error::debug_log_message("ERROR creating PDF. Check /tmp/pdflatex_*");
117 }
118
119 if ($output) {
120 return $pdf;
121 }
122 else {
123 header('Content-Type: application/pdf');
124 header('Content-Disposition: attachment; filename="' . $fileName . '"');
125 echo $pdf;
126 // quidam: comment previous line and uncomment next one during printing
127 //CRM_Utils_PDF_Utils::enqueuePDF($pdf);
128
129 }
130 }
131
132 /**
133 * @param array $text
134 * List of HTML snippets.
135 * @param string $fileName
136 * The logical filename to display.
137 * Ex: "HelloWorld.pdf".
138 * @param bool $output
139 * FALSE to display PDF. TRUE to return as string.
140 * @param null $pdfFormat
141 * Unclear. Possibly PdfFormat or formValues.
142 *
143 * @return string|void
144 */
145 public static function html2pdf($text, $fileName = 'civicrm.pdf', $output = FALSE, $pdfFormat = NULL) {
146 if (is_array($text)) {
147 $pages = &$text;
148 }
149 else {
150 $pages = [$text];
151 }
152 // Get PDF Page Format
153 $format = CRM_Core_BAO_PdfFormat::getDefaultValues();
154 if (is_array($pdfFormat)) {
155 // PDF Page Format parameters passed in
156 $format = array_merge($format, $pdfFormat);
157 }
158 elseif (!empty($pdfFormat)) {
159 // PDF Page Format ID passed in
160 $format = CRM_Core_BAO_PdfFormat::getById($pdfFormat);
161 }
162 $paperSize = CRM_Core_BAO_PaperSize::getByName($format['paper_size']);
163 $paper_width = self::convertMetric($paperSize['width'], $paperSize['metric'], 'pt');
164 $paper_height = self::convertMetric($paperSize['height'], $paperSize['metric'], 'pt');
165 // dompdf requires dimensions in points
166 $paper_size = [0, 0, $paper_width, $paper_height];
167 $orientation = CRM_Core_BAO_PdfFormat::getValue('orientation', $format);
168 $metric = CRM_Core_BAO_PdfFormat::getValue('metric', $format);
169 $t = CRM_Core_BAO_PdfFormat::getValue('margin_top', $format);
170 $r = CRM_Core_BAO_PdfFormat::getValue('margin_right', $format);
171 $b = CRM_Core_BAO_PdfFormat::getValue('margin_bottom', $format);
172 $l = CRM_Core_BAO_PdfFormat::getValue('margin_left', $format);
173
174 $margins = [$metric, $t, $r, $b, $l];
175
176 // Add a special region for the HTML header of PDF files:
177 $pdfHeaderRegion = CRM_Core_Region::instance('export-document-header', FALSE);
178 $htmlHeader = ($pdfHeaderRegion) ? $pdfHeaderRegion->render('', FALSE) : '';
179
180 $html = "
181 <html>
182 <head>
183 <meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\"/>
184 <style>@page { margin: {$t}{$metric} {$r}{$metric} {$b}{$metric} {$l}{$metric}; }</style>
185 <style type=\"text/css\">@import url(" . CRM_Core_Config::singleton()->userFrameworkResourceURL . "css/print.css);</style>
186 {$htmlHeader}
187 </head>
188 <body>
189 <div id=\"crm-container\">\n";
190
191 // Strip <html>, <header>, and <body> tags from each page
192
193 $htmlElementstoStrip = [
194 '<head[^>]*?>.*?</head>',
195 '<script[^>]*?>.*?</script>',
196 '<body>',
197 '</body>',
198 '<html[^>]*?>',
199 '</html>',
200 '<!DOCTYPE[^>]*?>',
201 ];
202 foreach ($pages as & $page) {
203 foreach ($htmlElementstoStrip as $pattern) {
204 $page = mb_eregi_replace($pattern, '', $page);
205 }
206 }
207 // Glue the pages together
208 $html .= implode("\n<div style=\"page-break-after: always\"></div>\n", $pages);
209 $html .= "
210 </div>
211 </body>
212 </html>";
213 if (CRM_Core_Config::singleton()->wkhtmltopdfPath) {
214 return self::_html2pdf_wkhtmltopdf($paper_size, $orientation, $margins, $html, $output, $fileName);
215 }
216 else {
217 return self::_html2pdf_dompdf($paper_size, $orientation, $html, $output, $fileName);
218 }
219 }
220
221 /**
222 * Convert html to tcpdf.
223 *
224 * @deprecated
225 * @param $paper_size
226 * @param $orientation
227 * @param $margins
228 * @param $html
229 * @param $output
230 * @param $fileName
231 * @param $stationery_path
232 */
233 public static function _html2pdf_tcpdf($paper_size, $orientation, $margins, $html, $output, $fileName, $stationery_path) {
234 CRM_Core_Error::deprecatedFunctionWarning('CRM_Utils_PDF::_html2pdf_dompdf');
235 return self::_html2pdf_dompdf($paper_size, $orientation, $margins, $html, $output, $fileName);
236 // Documentation on the TCPDF library can be found at: http://www.tcpdf.org
237 // This function also uses the FPDI library documented at: http://www.setasign.com/products/fpdi/about/
238 // Syntax borrowed from https://github.com/jake-mw/CDNTaxReceipts/blob/master/cdntaxreceipts.functions.inc
239 require_once 'tcpdf/tcpdf.php';
240 // This library is only in the 'packages' area as of version 4.5
241 require_once 'FPDI/fpdi.php';
242
243 $paper_size_arr = [$paper_size[2], $paper_size[3]];
244
245 $pdf = new TCPDF($orientation, 'pt', $paper_size_arr);
246 $pdf->Open();
247
248 if (is_readable($stationery_path)) {
249 $pdf->SetStationery($stationery_path);
250 }
251
252 $pdf->SetAuthor('');
253 $pdf->SetKeywords('CiviCRM.org');
254 $pdf->setPageUnit($margins[0]);
255 $pdf->SetMargins($margins[4], $margins[1], $margins[2], TRUE);
256
257 $pdf->setJPEGQuality('100');
258 $pdf->SetAutoPageBreak(TRUE, $margins[3]);
259
260 $pdf->AddPage();
261
262 $ln = TRUE;
263 $fill = FALSE;
264 $reset_parm = FALSE;
265 $cell = FALSE;
266 $align = '';
267
268 // output the HTML content
269 $pdf->writeHTML($html, $ln, $fill, $reset_parm, $cell, $align);
270
271 // reset pointer to the last page
272 $pdf->lastPage();
273
274 // close and output the PDF
275 $pdf->Close();
276 $pdf_file = 'CiviLetter' . '.pdf';
277 $pdf->Output($pdf_file, 'D');
278 CRM_Utils_System::civiExit();
279 }
280
281 /**
282 * @param $paper_size
283 * @param $orientation
284 * @param $html
285 * @param $output
286 * @param string $fileName
287 *
288 * @return string
289 */
290 public static function _html2pdf_dompdf($paper_size, $orientation, $html, $output, $fileName) {
291 // CRM-12165 - Remote file support required for image handling.
292 $options = new Options();
293 $options->set('isRemoteEnabled', TRUE);
294
295 $dompdf = new DOMPDF($options);
296 $dompdf->set_paper($paper_size, $orientation);
297 $dompdf->load_html($html);
298 $dompdf->render();
299
300 if ($output) {
301 return $dompdf->output();
302 }
303 // CRM-19183 remove .pdf extension from filename
304 $fileName = basename($fileName, ".pdf");
305 if (CIVICRM_UF === 'UnitTests' && headers_sent()) {
306 // Streaming content will 'die' in unit tests unless ob_start()
307 // has been called.
308 throw new CRM_Core_Exception_PrematureExitException('_html2pdf_dompdf called', [
309 'html' => $html,
310 'fileName' => $fileName,
311 ]);
312 }
313 $dompdf->stream($fileName);
314 }
315
316 /**
317 * @param $paper_size
318 * @param $orientation
319 * @param $margins
320 * @param $html
321 * @param $output
322 * @param string $fileName
323 */
324 public static function _html2pdf_wkhtmltopdf($paper_size, $orientation, $margins, $html, $output, $fileName) {
325 $config = CRM_Core_Config::singleton();
326 // if the path doesn't exist fall back on the current backup which is DOMPDF.
327 if (!file_exists($config->wkhtmltopdfPath)) {
328 return self::_html2pdf_dompdf($paper_size, $orientation, $html, $output, $fileName);
329 }
330 require_once 'snappy/src/autoload.php';
331 $snappy = new Knp\Snappy\Pdf($config->wkhtmltopdfPath);
332 $snappy->setOption("page-width", $paper_size[2] . "pt");
333 $snappy->setOption("page-height", $paper_size[3] . "pt");
334 $snappy->setOption("orientation", $orientation);
335 $snappy->setOption("margin-top", $margins[1] . $margins[0]);
336 $snappy->setOption("margin-right", $margins[2] . $margins[0]);
337 $snappy->setOption("margin-bottom", $margins[3] . $margins[0]);
338 $snappy->setOption("margin-left", $margins[4] . $margins[0]);
339 $html = preg_replace('/{ }/', ' ', $html);
340 $pdf = $snappy->getOutputFromHtml($html);
341 if ($output) {
342 return $pdf;
343 }
344 else {
345 CRM_Utils_System::setHttpHeader('Content-Type', 'application/pdf');
346 CRM_Utils_System::setHttpHeader('Content-Disposition', 'attachment; filename="' . $fileName . '"');
347 echo $pdf;
348 // quidam: comment previous line and uncomment next one during printing
349 //CRM_Utils_PDF_Utils::enqueuePDF($pdf);
350
351 }
352 }
353
354 /**
355 * convert value from one metric to another.
356 *
357 * @param $value
358 * @param $from
359 * @param $to
360 * @param null $precision
361 *
362 * @return float|int
363 */
364 public static function convertMetric($value, $from, $to, $precision = NULL) {
365 switch ($from . $to) {
366 case 'incm':
367 $value *= 2.54;
368 break;
369
370 case 'inmm':
371 $value *= 25.4;
372 break;
373
374 case 'inpt':
375 $value *= 72;
376 break;
377
378 case 'cmin':
379 $value /= 2.54;
380 break;
381
382 case 'cmmm':
383 $value *= 10;
384 break;
385
386 case 'cmpt':
387 $value *= 72 / 2.54;
388 break;
389
390 case 'mmin':
391 $value /= 25.4;
392 break;
393
394 case 'mmcm':
395 $value /= 10;
396 break;
397
398 case 'mmpt':
399 $value *= 72 / 25.4;
400 break;
401
402 case 'ptin':
403 $value /= 72;
404 break;
405
406 case 'ptcm':
407 $value *= 2.54 / 72;
408 break;
409
410 case 'ptmm':
411 $value *= 25.4 / 72;
412 break;
413 }
414 if (!is_null($precision)) {
415 $value = round($value, $precision);
416 }
417 return $value;
418 }
419
420 }