pdf.lib.php 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534
  1. <?php
  2. /* See license terms in /license.txt */
  3. /**
  4. * @package chamilo.library
  5. */
  6. /**
  7. * Code
  8. */
  9. define('_MPDF_PATH', api_get_path(LIBRARY_PATH).'mpdf/');
  10. require_once _MPDF_PATH.'mpdf.php';
  11. /**
  12. * Class
  13. * @package chamilo.library
  14. */
  15. class PDF {
  16. var $pdf;
  17. var $custom_header = '';
  18. var $custom_footer = '';
  19. /**
  20. * Creates the mPDF object
  21. * @param string format A4 A4-L see http://mpdf1.com/manual/index.php?tid=184&searchstring=format
  22. * @param string orientation "P" = Portrait "L" = Landscape
  23. */
  24. public function __construct($page_format ='A4', $orientation = 'P', $params = array()) {
  25. /* More info @ http://mpdf1.com/manual/index.php?tid=184&searchstring=mPDF
  26. * mPDF ([ string $mode [, mixed $format [, float $default_font_size [, string $default_font [, float $margin_left , float $margin_right , float $margin_top , float $margin_bottom , float $margin_header , float $margin_footer [, string $orientation ]]]]]])
  27. */
  28. if (!in_array($orientation, array('P','L'))) {
  29. $orientation = 'P';
  30. }
  31. //$this->pdf = $pdf = new mPDF('UTF-8', $page_format, '', '', 30, 20, 27, 25, 16, 13, $orientation);
  32. //left, right, top, bottom, margin_header, margin footer
  33. $params['left'] = isset($params['left']) ? $params['left'] : 15;
  34. $params['right'] = isset($params['right']) ? $params['right'] : 15;
  35. $params['top'] = isset($params['top']) ? $params['top'] : 20;
  36. $params['bottom'] = isset($params['bottom']) ? $params['bottom'] : 15;
  37. $this->pdf = $pdf = new mPDF('UTF-8', $page_format, '', '', $params['left'], $params['right'], $params['top'], $params['bottom'], 8, 8, $orientation);
  38. }
  39. /**
  40. * Converts HTML files to PDF
  41. * @param mixed could be an html file path or an array with paths example: /var/www/myfile.html or array('/myfile.html','myotherfile.html') or even an indexed array with both 'title' and 'path' indexes for each element like array(0=>array('title'=>'Hello','path'=>'file.html'),1=>array('title'=>'Bye','path'=>'file2.html'));
  42. * @param string pdf name
  43. * @param string course code (if you are using html that are located in the document tool you must provide this)
  44. * @return void
  45. */
  46. public function html_to_pdf($html_file_array, $pdf_name = '', $course_code = null, $print_title = false) {
  47. if (empty($html_file_array)) {
  48. return false;
  49. }
  50. if (is_array($html_file_array)) {
  51. if (count($html_file_array) == 0)
  52. return false;
  53. } else {
  54. if (!file_exists($html_file_array)) {
  55. return false;
  56. }
  57. //Converting the string into an array
  58. $html_file_array = array($html_file_array);
  59. }
  60. $course_data = array();
  61. if (!empty($course_code)) {
  62. $course_data = api_get_course_info($course_code);
  63. }
  64. //clean styles and javascript document
  65. $clean_search = array (
  66. '@<script[^>]*?>.*?</script>@si',
  67. '@<style[^>]*?>.*?</style>@si'
  68. );
  69. //Formatting the pdf
  70. self::format_pdf($course_data);
  71. $counter = 1;
  72. foreach ($html_file_array as $file) {
  73. //Add a page break per file
  74. $page_break = '<pagebreak>';
  75. if ($counter == count($html_file_array)) {
  76. $page_break = '';
  77. }
  78. $counter++;
  79. $html_title = '';
  80. //if the array provided contained subarrays with 'title' entry,
  81. // then print the title in the PDF
  82. if (is_array($file) && isset($file['title'])) {
  83. $html_title = $file['title'];
  84. $file = $file['path'];
  85. } else {
  86. //we suppose we've only been sent a file path
  87. $html_title = basename($file);
  88. }
  89. if (empty($file) && !empty($html_title)) {
  90. //this is a chapter, print title & skip the rest
  91. if ($print_title) {
  92. $this->pdf->WriteHTML('<html><body><h3>'.$html_title.'</h3></body></html>'.$page_break, 2);
  93. }
  94. continue;
  95. }
  96. if (!file_exists($file)) {
  97. //the file doesn't exist, skip
  98. continue;
  99. }
  100. //it's not a chapter but the file exists, print its title
  101. if ($print_title) {
  102. $this->pdf->WriteHTML('<html><body><h3>'.$html_title.'</h3></body></html>',2);
  103. }
  104. $file_info = pathinfo($file);
  105. $extension = $file_info['extension'];
  106. if (in_array($extension, array('html', 'htm'))) {
  107. $filename = $file_info['basename'];
  108. $filename = str_replace('_',' ',$filename);
  109. if ($extension == 'html') {
  110. $filename = basename($filename,'.html');
  111. } elseif($extension == 'htm'){
  112. $filename = basename($filename,'.htm');
  113. }
  114. $document_html = @file_get_contents($file);
  115. $document_html = preg_replace($clean_search, '', $document_html);
  116. //absolute path for frames.css //TODO: necessary?
  117. $absolute_css_path = api_get_path(WEB_CODE_PATH).'css/'.api_get_setting('stylesheets').'/frames.css';
  118. $document_html = str_replace('href="./css/frames.css"', $absolute_css_path, $document_html);
  119. //$document_html=str_replace('<link rel="stylesheet" http://my.chamilo.net/main/css/chamilo/frames.css type="text/css" />','', $document_html);
  120. if (!empty($course_data['path'])) {
  121. $document_html= str_replace('../','',$document_html);
  122. //$document_path = api_get_path(WEB_COURSE_PATH).$course_data['path'].'/document/';
  123. $document_path = api_get_path(SYS_COURSE_PATH).$course_data['path'].'/document/';
  124. $doc = new DOMDocument();
  125. $result = @$doc->loadHTML($document_html);
  126. //Fixing only images @todo do the same thing with other elements
  127. $elements = $doc->getElementsByTagName('img');
  128. if (!empty($elements)) {
  129. foreach ($elements as $item) {
  130. $old_src = $item->getAttribute('src');
  131. if (strpos($old_src, 'http') === false) {
  132. if (strpos($old_src, '/main/default_course_document') === false) {
  133. $old_src_fixed = str_replace('/courses/'.$course_data['path'].'/document/', '', $old_src);
  134. $old_src_fixed = str_replace('courses/'.$course_data['path'].'/document/', '', $old_src_fixed);
  135. $new_path = $document_path.$old_src_fixed;
  136. $document_html= str_replace($old_src, $new_path, $document_html);
  137. }
  138. }
  139. }
  140. }
  141. }
  142. api_set_encoding_html($document_html, 'UTF-8'); // The library mPDF expects UTF-8 encoded input data.
  143. $title = api_get_title_html($document_html, 'UTF-8', 'UTF-8'); // TODO: Maybe it is better idea the title to be passed through
  144. // $_GET[] too, as it is done with file name.
  145. // At the moment the title is retrieved from the html document itself.
  146. if (empty($title)) {
  147. $title = $filename; // Here file name is expected to contain ASCII symbols only.
  148. }
  149. if (!empty($document_html)) {
  150. $this->pdf->WriteHTML($document_html.$page_break, 2);
  151. }
  152. } elseif (in_array($extension, array('jpg','jpeg','png','gif'))) {
  153. //Images
  154. $image = Display::img($file);
  155. $this->pdf->WriteHTML('<html><body>'.$image.'</body></html>'.$page_break,2);
  156. }
  157. }
  158. if (empty($pdf_name)) {
  159. $output_file = 'pdf_'.date('Y-m-d-his').'.pdf';
  160. } else {
  161. $pdf_name = replace_dangerous_char($pdf_name);
  162. $output_file = $pdf_name.'.pdf';
  163. }
  164. $result = $this->pdf->Output($output_file, 'D'); /// F to save the pdf in a file
  165. exit;
  166. }
  167. /**
  168. * Converts an html string to PDF
  169. * @param string valid html
  170. * @param string CSS content of a CSS file
  171. * @param string pdf name
  172. * @param string course code (if you are using html that are located in the document tool you must provide this)
  173. * @return string Web path
  174. */
  175. public function content_to_pdf($document_html, $css = '', $pdf_name = '', $course_code = null) {
  176. if (empty($document_html)) {
  177. return false;
  178. }
  179. //clean styles and javascript document
  180. $clean_search = array (
  181. '@<script[^>]*?>.*?</script>@si',
  182. '@<style[^>]*?>.*?</style>@siU'
  183. );
  184. //Formatting the pdf
  185. $course_data = api_get_course_info($course_code);
  186. self::format_pdf($course_data);
  187. $document_html = preg_replace($clean_search, '', $document_html);
  188. //absolute path for frames.css //TODO: necessary?
  189. $absolute_css_path = api_get_path(WEB_CODE_PATH).'css/'.api_get_setting('stylesheets').'/frames.css';
  190. $document_html = str_replace('href="./css/frames.css"','href="'.$absolute_css_path.'"', $document_html);
  191. //$document_html=str_replace('<link rel="stylesheet" http://my.chamilo.net/main/css/chamilo/frames.css type="text/css" />','', $document_html);
  192. $document_html= str_replace('../../','',$document_html);
  193. $document_html= str_replace('../','',$document_html);
  194. $document_html= str_replace('courses/'.$course_code.'/document/','',$document_html);
  195. if (!empty($course_data['path'])) {
  196. $document_path = api_get_path(SYS_COURSE_PATH).$course_data['path'].'/document/';
  197. $doc = new DOMDocument();
  198. $result = @$doc->loadHTML($document_html);
  199. //Fixing only images @todo do the same thing with other elements
  200. $elements = $doc->getElementsByTagName('img');
  201. if (!empty($elements)) {
  202. foreach ($elements as $item) {
  203. $old_src = $item->getAttribute('src');
  204. //$old_src= str_replace('../','',$old_src);
  205. if (strpos($old_src, 'http') === false) {
  206. if (strpos($old_src, '/main/default_course_document') === false) {
  207. if (strpos($old_src, '/main/inc/lib/') === false) {
  208. $old_src_fixed = str_replace('/courses/'.$course_data['path'].'/document/', '', $old_src);
  209. $old_src_fixed = str_replace('courses/'.$course_data['path'].'/document/', '', $old_src_fixed);
  210. $new_path = $document_path.$old_src_fixed;
  211. $document_html= str_replace($old_src, $new_path, $document_html);
  212. }
  213. }
  214. }
  215. }
  216. }
  217. }
  218. //replace relative path by absolute path for resources
  219. //$document_html= str_replace('src="/chamilo/main/default_course_document/', 'temp_template_path', $document_html);// before save src templates not apply
  220. //$document_html= str_replace('src="/', 'temp_template_path', $document_html);// before save src templates not apply
  221. //$document_html= str_replace('src="/chamilo/main/default_course_document/', 'temp_template_path', $document_html);// before save src templates not apply
  222. //$src_http_www= 'src="'.api_get_path(WEB_COURSE_PATH).$course_data['path'].'/document/';
  223. //$document_html= str_replace('src="',$src_http_www, $document_html);
  224. //$document_html= str_replace('temp_template_path', 'src="/main/default_course_document/', $document_html);// restore src templates
  225. api_set_encoding_html($document_html, 'UTF-8'); // The library mPDF expects UTF-8 encoded input data.
  226. $title = api_get_title_html($document_html, 'UTF-8', 'UTF-8'); // TODO: Maybe it is better idea the title to be passed through
  227. // $_GET[] too, as it is done with file name.
  228. // At the moment the title is retrieved from the html document itself.
  229. /* if (empty($title)) {
  230. $title = $filename; // Here file name is expected to contain ASCII symbols only.
  231. }*/
  232. if (!empty($css)) {
  233. $this->pdf->WriteHTML($css, 1);
  234. }
  235. $this->pdf->WriteHTML($document_html,2);
  236. if (empty($pdf_name)) {
  237. $output_file = 'pdf_'.date('Y-m-d-his').'.pdf';
  238. } else {
  239. $pdf_name = replace_dangerous_char($pdf_name);
  240. $output_file = $pdf_name.'.pdf';
  241. }
  242. $result = $this->pdf->Output($output_file, 'D'); // F to save the pdf in a file
  243. exit;
  244. }
  245. /**
  246. * Gets the watermark from the platform or a course
  247. * @param string course code (optional)
  248. * @param mixed web path of the watermark image, false if there is nothing to return
  249. */
  250. public static function get_watermark($course_code = null) {
  251. $web_path = false;
  252. if (!empty($course_code) && api_get_setting('pdf_export_watermark_by_course') == 'true') {
  253. $course_info = api_get_course_info($course_code);
  254. $store_path = api_get_path(SYS_COURSE_PATH).$course_info['path'].'/'.api_get_current_access_url_id().'_pdf_watermark.png'; // course path
  255. if (file_exists($store_path)) {
  256. $web_path = api_get_path(WEB_COURSE_PATH).$course_info['path'].'/'.api_get_current_access_url_id().'_pdf_watermark.png';
  257. }
  258. } else {
  259. $store_path = api_get_path(SYS_CODE_PATH).'default_course_document/images/'.api_get_current_access_url_id().'_pdf_watermark.png'; // course path
  260. if (file_exists($store_path))
  261. $web_path = api_get_path(WEB_CODE_PATH).'default_course_document/images/'.api_get_current_access_url_id().'_pdf_watermark.png';
  262. }
  263. return $web_path;
  264. }
  265. /**
  266. * Deletes the watermark from the Platform or Course
  267. * @param string course code (optional)
  268. * @param mixed web path of the watermark image, false if there is nothing to return
  269. */
  270. public function delete_watermark($course_code = null) {
  271. if (!empty($course_code) && api_get_setting('pdf_export_watermark_by_course') == 'true') {
  272. $course_info = api_get_course_info($course_code);
  273. $store_path = api_get_path(SYS_COURSE_PATH).$course_info['path'].'/'.api_get_current_access_url_id().'_pdf_watermark.png'; // course path
  274. } else {
  275. $store_path = api_get_path(SYS_CODE_PATH).'default_course_document/'.api_get_current_access_url_id().'_pdf_watermark.png'; // course path
  276. }
  277. if (file_exists($store_path)) {
  278. @unlink($store_path);
  279. return true;
  280. }
  281. return false;
  282. }
  283. /**
  284. * Uploads the pdf watermark in the main/default_course_document directory or in the course directory
  285. * @param string filename
  286. * @param string path of the file
  287. * @param string course code
  288. * @return mixed web path of the file if sucess, false otherwise
  289. */
  290. public function upload_watermark($filename, $source_file, $course_code = null) {
  291. if (!empty($course_code) && api_get_setting('pdf_export_watermark_by_course') == 'true') {
  292. $course_info = api_get_course_info($course_code);
  293. $store_path = api_get_path(SYS_COURSE_PATH).$course_info['path']; // course path
  294. $web_path = api_get_path(WEB_COURSE_PATH).$course_info['path'].'/pdf_watermark.png';
  295. } else {
  296. $store_path = api_get_path(SYS_CODE_PATH).'default_course_document/images'; // course path
  297. $web_path = api_get_path(WEB_CODE_PATH).'default_course_document/images/'.api_get_current_access_url_id().'_pdf_watermark.png';
  298. }
  299. $course_image = $store_path.'/'.api_get_current_access_url_id().'_pdf_watermark.png';
  300. $extension = strtolower(substr(strrchr($filename, '.'), 1));
  301. $result = false;
  302. if (file_exists($course_image)) {
  303. @unlink($course_image);
  304. }
  305. $my_image = new Image($source_file);
  306. $result = $my_image->send_image($course_image, -1, 'png');
  307. if ($result) {
  308. $result = $web_path;
  309. }
  310. return $result;
  311. }
  312. /**
  313. * Returns the default header
  314. */
  315. public function get_header($course_code = null) {
  316. /*$header = api_get_setting('pdf_export_watermark_text');
  317. if (!empty($course_code) && api_get_setting('pdf_export_watermark_by_course') == 'true') {
  318. $header = api_get_course_setting('pdf_export_watermark_text');
  319. }
  320. return $header;*/
  321. }
  322. public function set_footer() {
  323. $this->pdf->defaultfooterfontsize = 12; // in pts
  324. $this->pdf->defaultfooterfontstyle = B; // blank, B, I, or BI
  325. $this->pdf->defaultfooterline = 1; // 1 to include line below header/above footer
  326. $platform_name = api_get_setting('Institution');
  327. $left_content = $platform_name;
  328. $center_content = '';
  329. $right_content = '{PAGENO} / {nb}';
  330. //@todo remove this and use a simpler way
  331. $footer = array (
  332. 'odd' => array (
  333. 'L' => array (
  334. 'content' => $left_content, 'font-size' => 10,'font-style' => 'B','font-family' => 'serif','color'=>'#000000'),
  335. 'C' => array (
  336. 'content' => $center_content,'font-size' => 10,'font-style' => 'B','font-family' => 'serif','color'=>'#000000'),
  337. 'R' => array (
  338. 'content' => $right_content, 'font-size' => 10,'font-style' => 'B','font-family' => 'serif','color'=>'#000000'),
  339. 'line' => 1,
  340. ),
  341. 'even' => array (
  342. 'L' => array (
  343. 'content' => $left_content, 'font-size' => 10,'font-style' => 'B','font-family' => 'serif','color'=>'#000000'),
  344. 'C' => array (
  345. 'content' => $center_content,'font-size' => 10,'font-style' => 'B','font-family' => 'serif','color'=>'#000000'),
  346. 'R' => array (
  347. 'content' => $right_content, 'font-size' => 10,'font-style' => 'B','font-family' => 'serif','color'=>'#000000'),
  348. 'line' => 1,
  349. ),
  350. );
  351. // defines footer for Odd and Even Pages - placed at Outer margin see http://mpdf1.com/manual/index.php?tid=151&searchstring=setfooter
  352. $this->pdf->SetFooter($footer);
  353. }
  354. public function set_header($course_data) {
  355. $this->pdf->defaultheaderfontsize = 10; // in pts
  356. $this->pdf->defaultheaderfontstyle = BI; // blank, B, I, or BI
  357. $this->pdf->defaultheaderline = 1; // 1 to include line below header/above footer
  358. if (!empty($course_data['code'])) {
  359. $teacher_list = CourseManager::get_teacher_list_from_course_code($course_data['code']);
  360. $teachers = '';
  361. if (!empty($teacher_list)) {
  362. foreach ($teacher_list as $teacher) {
  363. //$teachers[]= api_get_person_name($teacher['firstname'], $teacher['lastname']);
  364. $teachers[]= $teacher['firstname'].' '.$teacher['lastname'];
  365. }
  366. if (count($teachers) > 1) {
  367. $teachers = get_lang('Teachers').': '.implode(', ', $teachers);
  368. } else {
  369. $teachers = get_lang('Teacher').': '.implode('', $teachers);
  370. }
  371. //do not show the teacher list see BT#4080 only the current teacher name
  372. $user_info = api_get_user_info();
  373. $teachers = $user_info['complete_name'];
  374. }
  375. $left_content = '';
  376. $center_content = '';
  377. $right_content = $teachers;
  378. $header = array (
  379. 'odd' => array (
  380. 'L' => array (
  381. 'content' => $left_content, 'font-size' => 10,'font-style' => 'B','font-family' => 'serif','color'=>'#000000'),
  382. 'C' => array (
  383. 'content' => $center_content,'font-size' => 10,'font-style' => 'B','font-family' => 'serif','color'=>'#000000'),
  384. 'R' => array (
  385. 'content' => $right_content, 'font-size' => 10,'font-style' => 'B','font-family' => 'serif','color'=>'#000000'),
  386. 'line' => 1,
  387. ),
  388. 'even' => array (
  389. 'L' => array (
  390. 'content' => $left_content, 'font-size' => 10,'font-style' => 'B','font-family' => 'serif','color'=>'#000000'),
  391. 'C' => array (
  392. 'content' => $center_content,'font-size' => 10,'font-style' => 'B','font-family' => 'serif','color'=>'#000000'),
  393. 'R' => array (
  394. 'content' => $right_content, 'font-size' => 10,'font-style' => 'B','font-family' => 'serif','color'=>'#000000'),
  395. 'line' => 1,
  396. ),
  397. );
  398. $this->pdf->SetHeader($header);// ('{DATE j-m-Y}|{PAGENO}/{nb}|'.$title);
  399. }
  400. }
  401. public function set_custom_header($header) {
  402. $this->custom_header = $header;
  403. }
  404. public function set_custom_footer($footer) {
  405. $this->custom_footer = $footer;
  406. }
  407. public function format_pdf($course_data) {
  408. $course_code = null;
  409. if (!empty( $course_data)) {
  410. $course_code = $course_data['code'];
  411. }
  412. /*$pdf->SetAuthor('Documents Chamilo');
  413. $pdf->SetTitle('title');
  414. $pdf->SetSubject('Exported from Chamilo Documents');
  415. $pdf->SetKeywords('Chamilo Documents');
  416. */
  417. $this->pdf->directionality = api_get_text_direction(); // TODO: To be read from the html document.
  418. $this->pdf->useOnlyCoreFonts = true;
  419. $this->pdf->mirrorMargins = 1; // Use different Odd/Even headers and footers and mirror margins
  420. //Adding watermark
  421. if (api_get_setting('pdf_export_watermark_enable') == 'true') {
  422. $watermark_file = self::get_watermark($course_code);
  423. if ($watermark_file) {
  424. //http://mpdf1.com/manual/index.php?tid=269&searchstring=watermark
  425. $this->pdf->SetWatermarkImage($watermark_file);
  426. $this->pdf->showWatermarkImage = true;
  427. } else {
  428. $watermark_file = self::get_watermark(null);
  429. if ($watermark_file) {
  430. $this->pdf->SetWatermarkImage($watermark_file);
  431. $this->pdf->showWatermarkImage = true;
  432. }
  433. }
  434. if ($course_code) {
  435. $watermark_text = api_get_course_setting('pdf_export_watermark_text');
  436. if (empty($watermark_text)) {
  437. $watermark_text = api_get_setting('pdf_export_watermark_text');
  438. }
  439. } else {
  440. $watermark_text = api_get_setting('pdf_export_watermark_text');
  441. }
  442. if (!empty($watermark_text)) {
  443. $this->pdf->SetWatermarkText(strcode2utf($watermark_text),0.1);
  444. $this->pdf->showWatermarkText = true;
  445. }
  446. }
  447. if (empty($this->custom_header)) {
  448. self::set_header($course_data);
  449. } else {
  450. $this->pdf->SetHTMLHeader($this->custom_header,'E');
  451. $this->pdf->SetHTMLHeader($this->custom_header,'O');
  452. }
  453. if (empty($this->custom_footer)) {
  454. self::set_footer();
  455. } else {
  456. $this->pdf->SetHTMLFooter($this->custom_footer);
  457. }
  458. }
  459. }