pdf.lib.php 25 KB

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