pdf.lib.php 24 KB

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