Since dompdf can't handle Unicode, decode it to ISO-8859-1
[project/print.git] / print_pdf / print_pdf.pages.inc
1 <?php
2 // $Id$
3
4 /**
5 * @file
6 * Generates the PDF versions of the pages
7 *
8 * This file is included by the print_pdf module and includes the
9 * functions that interface with the PDF generation packages.
10 */
11
12 require_once(DRUPAL_ROOT .'/'. drupal_get_path('module', 'print') .'/print.pages.inc');
13
14 /**
15 * Generate a PDF version of the printer-friendly page
16 *
17 * @see print_controller()
18 * @see _print_get_template()
19 * @see _print_pdf_dompdf()
20 * @see _print_pdf_tcpdf()
21 */
22 function print_pdf_controller() {
23 global $base_url;
24
25 $args = func_get_args();
26 // Remove the printpdf/ prefix
27 $path = implode('/', $args);
28 $cid = isset($_GET['comment']) ? (int)$_GET['comment'] : NULL;
29
30 $print_pdf_pdf_tool = variable_get('print_pdf_pdf_tool', PRINT_PDF_PDF_TOOL_DEFAULT);
31
32 $print = print_controller($path, $cid);
33 if ($print === FALSE) {
34 return;
35 }
36
37 // Img elements must be set to absolute
38 $pattern = '!<(img\s[^>]*?)>!is';
39 $print['content'] = preg_replace_callback($pattern, '_print_rewrite_urls', $print['content']);
40 $print['logo'] = preg_replace_callback($pattern, '_print_rewrite_urls', $print['logo']);
41 $print['footer_message'] = preg_replace_callback($pattern, '_print_rewrite_urls', $print['footer_message']);
42 // And converted from private to public paths
43 $file_downloads = variable_get('file_downloads', FILE_DOWNLOADS_PUBLIC);
44 if ($file_downloads == FILE_DOWNLOADS_PRIVATE) {
45 $pattern = "!(<img\s[^>]*?src\s*?=\s*?['\"]?${base_url}/)system/files(/[^>]*?>)!is";
46 $replacement = '$1'. file_directory_path() .'$2';
47 $print['content'] = preg_replace($pattern, $replacement, $print['content']);
48 $print['logo'] = preg_replace($pattern, $replacement, $print['logo']);
49 $print['footer_message'] = preg_replace($pattern, $replacement, $print['footer_message']);
50 }
51
52 $node = $print['node'];
53 ob_start();
54 include_once(DRUPAL_ROOT .'/'. _print_get_template('pdf', $print['type']));
55 $html = ob_get_contents();
56 ob_end_clean();
57
58 if (basename($print_pdf_pdf_tool) == 'dompdf_config.inc.php') {
59 _print_pdf_dompdf($print, $html, $path .'.pdf');
60 }
61 elseif (basename($print_pdf_pdf_tool) == 'tcpdf.php') {
62 _print_pdf_tcpdf($print, $html, $path .'.pdf');
63 }
64 else {
65 return drupal_not_found();
66 }
67 }
68
69 /**
70 * Generate the PDF file using the dompdf library
71 *
72 * @param $print
73 * array containing the configured data
74 * @param $html
75 * contents of the post-processed template already with the node data
76 * @param $filename
77 * name of the PDF file to be generated
78 * @see print_pdf_controller()
79 */
80 function _print_pdf_dompdf($print, $html, $filename) {
81 $print_pdf_pdf_tool = variable_get('print_pdf_pdf_tool', PRINT_PDF_PDF_TOOL_DEFAULT);
82 $print_pdf_paper_size = variable_get('print_pdf_paper_size', PRINT_PDF_PAPER_SIZE_DEFAULT);
83 $print_pdf_page_orientation = variable_get('print_pdf_page_orientation', PRINT_PDF_PAGE_ORIENTATION_DEFAULT);
84 $print_pdf_content_disposition = variable_get('print_pdf_content_disposition', PRINT_PDF_CONTENT_DISPOSITION_DEFAULT);
85 require_once(DRUPAL_ROOT .'/'. $print_pdf_pdf_tool);
86
87 // dompdf seems to have problems with something in system.css so let's not use it
88 $html = preg_replace('!<link.*?modules/system/system.css.*?/>!', '', $html);
89
90 $url_array = parse_url($print['url']);
91
92 $protocol = $url_array['scheme'] .'://';
93 $host = $url_array['host'];
94 $path = dirname($url_array['path']) .'/';
95
96 $dompdf = new DOMPDF();
97 $dompdf->set_base_path($path);
98 $dompdf->set_host($host);
99 $dompdf->set_paper(drupal_strtolower($print_pdf_paper_size), $print_pdf_page_orientation);
100 $dompdf->set_protocol($protocol);
101
102 $html = theme('print_pdf_dompdf_footer', $html);
103
104 $dompdf->load_html(utf8_decode($html));
105
106 $dompdf->render();
107 $dompdf->stream($filename, array('Attachment' => ($print_pdf_content_disposition == 2)));
108 }
109
110 /**
111 * Generate the PDF file using the TCPDF library
112 *
113 * @param $print
114 * array containing the configured data
115 * @param $html
116 * contents of the post-processed template already with the node data
117 * @param $filename
118 * name of the PDF file to be generated
119 * @see print_pdf_controller()
120 */
121 function _print_pdf_tcpdf($print, $html, $filename) {
122 global $base_url;
123 $print_pdf_pdf_tool = variable_get('print_pdf_pdf_tool', PRINT_PDF_PDF_TOOL_DEFAULT);
124 $print_pdf_paper_size = variable_get('print_pdf_paper_size', PRINT_PDF_PAPER_SIZE_DEFAULT);
125 $print_pdf_page_orientation = variable_get('print_pdf_page_orientation', PRINT_PDF_PAGE_ORIENTATION_DEFAULT);
126 $print_pdf_content_disposition = variable_get('print_pdf_content_disposition', PRINT_PDF_CONTENT_DISPOSITION_DEFAULT);
127
128 $pdf_tool_path = realpath(dirname($print_pdf_pdf_tool));
129
130 define('K_TCPDF_EXTERNAL_CONFIG', TRUE);
131 define('K_PATH_MAIN', dirname($_SERVER['SCRIPT_FILENAME']));
132 define('K_PATH_URL', $base_url);
133 define('K_PATH_FONTS', $pdf_tool_path .'/fonts/');
134 define('K_PATH_CACHE', $pdf_tool_path .'/cache/');
135 define('K_PATH_IMAGES', '');
136 define('K_BLANK_IMAGE', $pdf_tool_path .'/images/_blank.png');
137 define('K_CELL_HEIGHT_RATIO', 1.25);
138 define('K_SMALL_RATIO', 2/3);
139
140 require_once(DRUPAL_ROOT .'/'. $print_pdf_pdf_tool);
141 if (strpos(PDF_PRODUCER, 'PHP4') === FALSE) {
142 require_once(DRUPAL_ROOT .'/'. drupal_get_path('module', 'print_pdf') .'/print_pdf.class.inc');
143 }
144 else {
145 drupal_set_message(t("The PHP4 version of TCPDF is not supported. Please upgrade it."), 'error', FALSE);
146 drupal_goto($_GET['q']);
147 }
148
149 $font = Array(
150 variable_get('print_pdf_font_family', PRINT_PDF_FONT_FAMILY_DEFAULT),
151 '',
152 variable_get('print_pdf_font_size', PRINT_PDF_FONT_SIZE_DEFAULT),
153 );
154 $orientation = drupal_strtoupper($print_pdf_page_orientation[0]);
155
156 // create new PDF document
157 $pdf = new PrintTCPDF($orientation , 'mm', $print_pdf_paper_size, TRUE);
158
159 // set document information
160 $pdf->SetAuthor(strip_tags($print['submitted']));
161 $pdf->SetCreator(variable_get('site_name', 'Drupal'));
162 $pdf->SetTitle($print['title']);
163 $keys = implode(' ', explode("\n", trim(strip_tags($print['taxonomy']))));
164 $pdf->SetKeywords($keys);
165 $pdf->setPDFVersion('1.6');
166
167 $pdf = theme('print_pdf_tcpdf_header', $pdf, $html, $font);
168 $pdf = theme('print_pdf_tcpdf_footer', $pdf, $html, $font);
169 $pdf = theme('print_pdf_tcpdf_page', $pdf);
170
171 //initialize document
172 $pdf->AliasNbPages();
173
174 // add a page
175 $pdf->AddPage();
176
177 $pdf = theme('print_pdf_tcpdf_content', $pdf, $html, $font);
178
179 // reset pointer to the last page
180 $pdf->lastPage();
181
182 //Close and output PDF document
183 $output_dest = ($print_pdf_content_disposition == 2) ? 'D' : 'I';
184 $pdf->Output($filename, $output_dest);
185 }
186
187 /**
188 * Format the dompdf footer contents
189 *
190 * @param $html
191 * contents of the body of the HTML from the original node
192 * @see theme_print_pdf_tcpdf_footer()
193 */
194 function theme_print_pdf_dompdf_footer(&$html) {
195 preg_match('!<div class="print-footer">(.*?)</div>!si', $html, $tpl_footer);
196 $html = str_replace($tpl_footer[0], '', $html);
197
198 $text = '<script type="text/php">
199 if (isset($pdf)) {
200 $font = Font_Metrics::get_font("verdana");;
201 $size = 10;
202 $color = array(0,0,0);
203 $text_height = Font_Metrics::get_font_height($font, $size);
204
205 $w = $pdf->get_width();
206 $h = $pdf->get_height();
207
208 $footer = $pdf->open_object();
209
210 // Draw a line along the bottom
211 $y = $h - 25;
212 $pdf->line(15, $y, $w - 15, $y, $color, 1);
213
214 $y += $text_height / 2;
215 $pdf->page_text(15, $y, \''. addslashes(strip_tags($tpl_footer[1])) .'\', $font, $size, $color);
216
217 $pdf->close_object();
218 $pdf->add_object($footer, "all");
219
220 // Center the text
221 $width = Font_Metrics::get_text_width("Page 1 of 2", $font, $size);
222 $pagenumtxt = t("Page !n of !total", array("!n" => "{PAGE_NUM}", "!total" => "{PAGE_COUNT}"));
223 $pdf->page_text($w - 15 - $width, $y, $pagenumtxt, $font, $size, $color);
224 }
225 </script>';
226
227 return str_replace("<body>", "<body>" . $text, $html);
228 }
229
230 /**
231 * Format the TCPDF header
232 *
233 * @param $pdf
234 * current TCPDF object
235 * @param $html
236 * contents of the body of the HTML from the original node
237 * @param $font
238 * array with the font definition (font name, styles and size)
239 * @see theme_print_pdf_tcpdf_header()
240 */
241 function theme_print_pdf_tcpdf_header(&$pdf, &$html, $font) {
242 preg_match('!<div class="print-logo">(.*?)</div>!si', $html, $tpl_logo);
243 preg_match('!<h1 class="print-title">(.*?)</h1>!si', $html, $tpl_title);
244 preg_match('!<div class="print-site_name">(.*?)</div>!si', $html, $tpl_site_name);
245
246 $ratio = 0;
247 $logo = '';
248 $logo_ret = preg_match('!src\s*=\s*(\'.*?\'|".*?"|[^\s]*)!i', $tpl_logo[1], $matches);
249 if ($logo_ret) {
250 $logo = trim($matches[1], '\'"');
251 $size = getimagesize($logo);
252 $ratio = $size[0] / $size[1];
253 }
254
255 // set header font
256 $pdf->setHeaderFont($font);
257 // set header margin
258 $pdf->SetHeaderMargin(5);
259 // set header data
260 $pdf->SetHeaderData($logo, 10 * $ratio, $tpl_title[1], strip_tags($tpl_site_name[1]));
261
262 return $pdf;
263 }
264
265 /**
266 * Format the TCPDF page settings (margins, etc)
267 *
268 * @param $pdf
269 * current TCPDF object
270 * @see theme_print_pdf_tcpdf_page()
271 */
272 function theme_print_pdf_tcpdf_page(&$pdf) {
273 // set margins
274 $pdf->SetMargins(15, 20, 15);
275 // set auto page breaks
276 $pdf->SetAutoPageBreak(TRUE, 15);
277 // set image scale factor
278 $pdf->setImageScale(4);
279 // set image compression quality
280 $pdf->setJPEGQuality(100);
281
282 return $pdf;
283 }
284
285 /**
286 * Format the TCPDF page content
287 *
288 * @param $pdf
289 * current TCPDF object
290 * @param $html
291 * contents of the body of the HTML from the original node
292 * @param $font
293 * array with the font definition (font name, styles and size)
294 * @see theme_print_pdf_tcpdf_content()
295 */
296 function theme_print_pdf_tcpdf_content(&$pdf, &$html, $font) {
297 // set content font
298 $pdf->setFont($font[0], $font[1], $font[2]);
299
300 preg_match('!<body.*?>(.*)</body>!sim', $html, $matches);
301 $pattern = '!(?:<div class="print-(?:logo|site_name|breadcrumb|footer)">.*?</div>|<hr class="print-hr" />)!si';
302 $matches[1] = preg_replace($pattern, '', $matches[1]);
303
304
305 // Since TCPDF's writeHTML is so bad with <p>, do everything possible to make it look nice
306 $matches[1] = preg_replace('!(<p\s*/>|</p>)!i', '<br />', $matches[1]);
307 $matches[1] = str_replace(array('<div', 'div>'), array('<span', 'span><br />'), $matches[1]);
308
309 $pdf->writeHTML($matches[1]);
310
311 return $pdf;
312 }
313
314 /**
315 * Format the TCPDF footer contents
316 *
317 * @param $pdf
318 * current TCPDF object
319 * @param $html
320 * contents of the body of the HTML from the original node
321 * @param $font
322 * array with the font definition (font name, styles and size)
323 * @see theme_print_pdf_tcpdf_footer()
324 */
325 function theme_print_pdf_tcpdf_footer(&$pdf, &$html, $font) {
326 preg_match('!<div class="print-footer">(.*?)</div>!si', $html, $tpl_footer);
327 $footer = trim(preg_replace('!</?div[^>]*?>!i', '', $tpl_footer[1]));
328
329 // set footer font
330 $font[2] *= 0.8;
331 $pdf->setFooterFont($font);
332 // set footer margin
333 $pdf->SetFooterMargin(10);
334 // set footer data
335 $pdf->SetFooterData($footer);
336
337 return $pdf;
338 }
339
340 /**
341 * Format the TCPDF footer layout
342 *
343 * @param $pdf
344 * current TCPDF object
345 * @see theme_print_pdf_tcpdf_footer2()
346 */
347 function theme_print_pdf_tcpdf_footer2(&$pdf) {
348 //Position at 1.5 cm from bottom
349 $pdf->writeHTMLCell(0, 15, 15, 0, $pdf->footer, 0, 0, 0, TRUE, '');
350
351 $ormargins = $pdf->getOriginalMargins();
352 $pagenumtxt = t('Page !n of !total', array('!n' => $pdf->PageNo(), '!total' => $pdf->getAliasNbPages()));
353 //Print page number
354 if ($pdf->getRTL()) {
355 $pdf->SetX($ormargins['right']);
356 $pdf->Cell(0, 10, $pagenumtxt, 'T', 0, 'L');
357 }
358 else {
359 $pdf->SetX($ormargins['left']);
360 $pdf->Cell(0, 10, $pagenumtxt, 'T', 0, 'R');
361 }
362
363 return $pdf;
364 }