pdf.lib.php 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846
  1. <?php
  2. /* See license terms in /license.txt */
  3. use Chamilo\CoreBundle\Component\Utils\ChamiloApi;
  4. /**
  5. * Class PDF
  6. * @package chamilo.library
  7. *
  8. */
  9. class PDF
  10. {
  11. public $pdf;
  12. public $custom_header = array();
  13. public $custom_footer = array();
  14. public $params = array();
  15. public $template;
  16. /**
  17. * Creates the mPDF object
  18. * @param string $pageFormat format A4 A4-L see http://mpdf1.com/manual/index.php?tid=184&searchstring=format
  19. * @param string $orientation orientation "P" = Portrait "L" = Landscape
  20. * @param array $params
  21. * @param Template $template
  22. */
  23. public function __construct(
  24. $pageFormat = 'A4',
  25. $orientation = 'P',
  26. $params = array(),
  27. $template = null
  28. ) {
  29. $this->template = $template;
  30. /* More info @ http://mpdf1.com/manual/index.php?tid=184&searchstring=mPDF
  31. * 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 ]]]]]])
  32. */
  33. if (!in_array($orientation, array('P', 'L'))) {
  34. $orientation = 'P';
  35. }
  36. //left, right, top, bottom, margin_header, margin footer
  37. $params['left'] = isset($params['left']) ? $params['left'] : 15;
  38. $params['right'] = isset($params['right']) ? $params['right'] : 15;
  39. $params['top'] = isset($params['top']) ? $params['top'] : 30;
  40. $params['bottom'] = isset($params['bottom']) ? $params['bottom'] : 30;
  41. $this->params['filename'] = isset($params['filename']) ? $params['filename'] : api_get_local_time();
  42. $this->params['pdf_title'] = isset($params['pdf_title']) ? $params['pdf_title'] : get_lang('Untitled');
  43. $this->params['course_info'] = isset($params['course_info']) ? $params['course_info'] : api_get_course_info();
  44. $this->params['session_info'] = isset($params['session_info']) ? $params['session_info'] : api_get_session_info(api_get_session_id());
  45. $this->params['course_code'] = isset($params['course_code']) ? $params['course_code'] : api_get_course_id();
  46. $this->params['add_signatures'] = isset($params['add_signatures']) ? $params['add_signatures'] : [];
  47. $this->params['show_real_course_teachers'] = isset($params['show_real_course_teachers']) ? $params['show_real_course_teachers'] : false;
  48. $this->params['student_info'] = isset($params['student_info']) ? $params['student_info'] : false;
  49. $this->params['show_grade_generated_date'] = isset($params['show_grade_generated_date']) ? $params['show_grade_generated_date'] : false;
  50. $this->params['show_teacher_as_myself'] = isset($params['show_teacher_as_myself']) ? $params['show_teacher_as_myself'] : true;
  51. $localTime = api_get_local_time();
  52. $this->params['pdf_date'] = isset($params['pdf_date']) ? $params['pdf_date'] : api_format_date($localTime, DATE_TIME_FORMAT_LONG);
  53. $this->params['pdf_date_only'] = isset($params['pdf_date']) ? $params['pdf_date'] : api_format_date($localTime, DATE_FORMAT_LONG);
  54. $this->pdf = new mPDF(
  55. 'UTF-8',
  56. $pageFormat,
  57. '',
  58. '',
  59. $params['left'],
  60. $params['right'],
  61. $params['top'],
  62. $params['bottom'],
  63. 8,
  64. 8,
  65. $orientation
  66. );
  67. // Default value is 96 set in the mpdf library file config.php
  68. $value = api_get_configuration_value('pdf_img_dpi');
  69. if (!empty($value)) {
  70. $this->pdf->img_dpi = (int) $value;
  71. }
  72. }
  73. /**
  74. * Export the given HTML to PDF, using a global template
  75. *
  76. * @uses export/table_pdf.tpl
  77. * @param $content
  78. * @param bool|false $saveToFile
  79. * @param bool|false $returnHtml
  80. *
  81. * @return string
  82. */
  83. public function html_to_pdf_with_template($content, $saveToFile = false, $returnHtml = false)
  84. {
  85. if (empty($this->template)) {
  86. $tpl = new Template('', false, false, false);
  87. } else {
  88. $tpl = $this->template;
  89. }
  90. // Assignments
  91. $tpl->assign('pdf_content', $content);
  92. // Showing only the current teacher/admin instead the all teacher list name see BT#4080
  93. if (isset($this->params['show_real_course_teachers']) &&
  94. $this->params['show_real_course_teachers']
  95. ) {
  96. if (isset($this->params['session_info']) &&
  97. !empty($this->params['session_info'])
  98. ) {
  99. $teacher_list = SessionManager::getCoachesByCourseSessionToString(
  100. $this->params['session_info']['id'],
  101. $this->params['course_info']['real_id']
  102. );
  103. } else {
  104. $teacher_list = CourseManager::get_teacher_list_from_course_code_to_string(
  105. $this->params['course_code']
  106. );
  107. }
  108. } else {
  109. $user_info = api_get_user_info();
  110. if ($this->params['show_teacher_as_myself']) {
  111. $teacher_list = $user_info['complete_name'];
  112. }
  113. }
  114. $tpl->assign('pdf_course', $this->params['course_code']);
  115. $tpl->assign('pdf_course_info', $this->params['course_info']);
  116. $tpl->assign('pdf_session_info', $this->params['session_info']);
  117. $tpl->assign('pdf_date', $this->params['pdf_date']);
  118. $tpl->assign('pdf_date_only', $this->params['pdf_date_only']);
  119. $tpl->assign('pdf_teachers', $teacher_list);
  120. $tpl->assign('pdf_title', $this->params['pdf_title']);
  121. $tpl->assign('pdf_student_info', $this->params['student_info']);
  122. $tpl->assign('show_grade_generated_date', $this->params['show_grade_generated_date']);
  123. $tpl->assign('add_signatures', $this->params['add_signatures']);
  124. // Getting template
  125. $tableTemplate = $tpl->get_template('export/table_pdf.tpl');
  126. $html = $tpl->fetch($tableTemplate);
  127. $html = api_utf8_encode($html);
  128. $css_file = api_get_path(SYS_CSS_PATH).'themes/'.$tpl->theme.'/print.css';
  129. if (!file_exists($css_file)) {
  130. $css_file = api_get_path(SYS_CSS_PATH).'print.css';
  131. }
  132. $css = file_get_contents($css_file);
  133. $html = self::content_to_pdf(
  134. $html,
  135. $css,
  136. $this->params['filename'],
  137. $this->params['course_code'],
  138. 'D',
  139. $saveToFile,
  140. null,
  141. $returnHtml
  142. );
  143. if ($returnHtml) {
  144. return $html;
  145. }
  146. }
  147. /**
  148. * Converts HTML files to PDF
  149. * @param mixed $html_file_array could be an html file path or an array
  150. * with paths example:
  151. * /var/www/myfile.html or array('/myfile.html','myotherfile.html') or
  152. * even an indexed array with both 'title' and 'path' indexes
  153. * for each element like
  154. * array(
  155. * 0 => array('title'=>'Hello','path'=>'file.html'),
  156. * 1 => array('title'=>'Bye','path'=>'file2.html')
  157. * );
  158. * @param string $pdf_name pdf name
  159. * @param string $course_code (if you are using html that are located in the document tool you must provide this)
  160. * @param bool $print_title add title
  161. * @param bool $complete_style show header and footer if true
  162. * @param bool $addStyle
  163. *
  164. * @return false|null
  165. */
  166. public function html_to_pdf(
  167. $html_file_array,
  168. $pdf_name = '',
  169. $course_code = null,
  170. $print_title = false,
  171. $complete_style = true,
  172. $addStyle = true
  173. ) {
  174. if (empty($html_file_array)) {
  175. return false;
  176. }
  177. if (is_array($html_file_array)) {
  178. if (count($html_file_array) == 0) {
  179. return false;
  180. }
  181. } else {
  182. if (!file_exists($html_file_array)) {
  183. return false;
  184. }
  185. // Converting the string into an array
  186. $html_file_array = array($html_file_array);
  187. }
  188. if (!empty($course_code)) {
  189. $course_data = api_get_course_info($course_code);
  190. } else {
  191. $course_data = api_get_course_info();
  192. }
  193. // Clean styles and javascript document
  194. $clean_search = array(
  195. '@<script[^>]*?>.*?</script>@si',
  196. '@<style[^>]*?>.*?</style>@si'
  197. );
  198. // Formatting the pdf
  199. self::format_pdf($course_data, $complete_style);
  200. $counter = 1;
  201. foreach ($html_file_array as $file) {
  202. //Add a page break per file
  203. $page_break = '<pagebreak>';
  204. if ($counter == count($html_file_array)) {
  205. $page_break = '';
  206. }
  207. $counter++;
  208. //if the array provided contained subarrays with 'title' entry,
  209. // then print the title in the PDF
  210. if (is_array($file) && isset($file['title'])) {
  211. $html_title = $file['title'];
  212. $file = $file['path'];
  213. } else {
  214. //we suppose we've only been sent a file path
  215. $html_title = basename($file);
  216. }
  217. if (empty($file) && !empty($html_title)) {
  218. //this is a chapter, print title & skip the rest
  219. if ($print_title) {
  220. $this->pdf->WriteHTML(
  221. '<html><body><h3>'.$html_title.'</h3></body></html>'.$page_break
  222. );
  223. }
  224. continue;
  225. }
  226. if (!file_exists($file)) {
  227. //the file doesn't exist, skip
  228. continue;
  229. }
  230. if ($addStyle) {
  231. $css_file = api_get_path(SYS_CSS_PATH).'/print.css';
  232. $css = file_exists($css_file) ? @file_get_contents($css_file) : '';
  233. $this->pdf->WriteHTML($css, 1);
  234. }
  235. //it's not a chapter but the file exists, print its title
  236. if ($print_title) {
  237. $this->pdf->WriteHTML(
  238. '<html><body><h3>'.$html_title.'</h3></body></html>'
  239. );
  240. }
  241. $file_info = pathinfo($file);
  242. $extension = $file_info['extension'];
  243. if (in_array($extension, array('html', 'htm'))) {
  244. $dirName = $file_info['dirname'];
  245. $filename = $file_info['basename'];
  246. $filename = str_replace('_', ' ', $filename);
  247. if ($extension === 'html') {
  248. $filename = basename($filename, '.html');
  249. } elseif ($extension === 'htm') {
  250. $filename = basename($filename, '.htm');
  251. }
  252. $document_html = @file_get_contents($file);
  253. $document_html = preg_replace($clean_search, '', $document_html);
  254. //absolute path for frames.css //TODO: necessary?
  255. $absolute_css_path = api_get_path(WEB_CODE_PATH).'css/'.api_get_setting('stylesheets').'/frames.css';
  256. $document_html = str_replace('href="./css/frames.css"', $absolute_css_path, $document_html);
  257. if (!empty($course_data['path'])) {
  258. $document_html = str_replace('../', '', $document_html);
  259. $document_path = api_get_path(SYS_COURSE_PATH).$course_data['path'].'/document/';
  260. $doc = new DOMDocument();
  261. $result = @$doc->loadHTML($document_html);
  262. //Fixing only images @todo do the same thing with other elements
  263. $elements = $doc->getElementsByTagName('img');
  264. if (!empty($elements)) {
  265. foreach ($elements as $item) {
  266. $old_src = $item->getAttribute('src');
  267. if (strpos($old_src, 'http') === false) {
  268. if (strpos($old_src, '/main/default_course_document') === false) {
  269. $old_src_fixed = '';
  270. if (strpos($old_src, '/main/img') === false) {
  271. if (api_get_path(REL_PATH) != '/') {
  272. $old_src_fixed = str_replace(
  273. api_get_path(REL_PATH).'courses/'.$course_data['path'].'/document/',
  274. '',
  275. $old_src
  276. );
  277. // Try with the dirname if exists
  278. if ($old_src_fixed == $old_src) {
  279. if (file_exists($dirName.'/'.$old_src)) {
  280. $document_path = '';
  281. $old_src_fixed = $dirName.'/'.$old_src;
  282. }
  283. }
  284. } else {
  285. if (strpos($old_src, 'courses/'.$course_data['path'].'/document/') !== false) {
  286. $old_src_fixed = str_replace('courses/'.$course_data['path'].'/document/', '', $old_src);
  287. } else {
  288. // Try with the dirname if exists
  289. if (file_exists($dirName.'/'.$old_src)) {
  290. $document_path = '';
  291. $old_src_fixed = $dirName.'/'.$old_src;
  292. } else {
  293. $document_path = '';
  294. $old_src_fixed = $old_src;
  295. }
  296. }
  297. }
  298. $new_path = $document_path.$old_src_fixed;
  299. } else {
  300. $new_path = $old_src;
  301. }
  302. $document_html = str_replace($old_src, $new_path, $document_html);
  303. }
  304. } else {
  305. //Check if this is a complete URL
  306. /*if (strpos($old_src, 'courses/'.$course_data['path'].'/document/') === false) {
  307. } else {
  308. $old_src_fixed = str_replace(api_get_path(SYS_COURSE_PATH).$course_data['path'].'/document/', '', $old_src);
  309. $new_path = $document_path.$old_src_fixed;
  310. $document_html= str_replace($old_src, $new_path, $document_html);
  311. }*/
  312. }
  313. }
  314. }
  315. }
  316. api_set_encoding_html($document_html, 'UTF-8'); // The library mPDF expects UTF-8 encoded input data.
  317. // TODO: Maybe it is better idea the title to be passed through
  318. $title = api_get_title_html($document_html, 'UTF-8', 'UTF-8');
  319. // $_GET[] too, as it is done with file name.
  320. // At the moment the title is retrieved from the html document itself.
  321. //echo $document_html;exit;
  322. if (empty($title)) {
  323. $title = $filename; // Here file name is expected to contain ASCII symbols only.
  324. }
  325. if (!empty($document_html)) {
  326. $this->pdf->WriteHTML($document_html.$page_break);
  327. }
  328. } elseif (in_array($extension, array('jpg', 'jpeg', 'png', 'gif'))) {
  329. //Images
  330. $image = Display::img($file);
  331. $this->pdf->WriteHTML('<html><body>'.$image.'</body></html>'.$page_break);
  332. }
  333. }
  334. if (empty($pdf_name)) {
  335. $output_file = 'pdf_'.date('Y-m-d-his').'.pdf';
  336. } else {
  337. $pdf_name = api_replace_dangerous_char($pdf_name);
  338. $output_file = $pdf_name.'.pdf';
  339. }
  340. // F to save the pdf in a file
  341. $this->pdf->Output($output_file, 'D');
  342. exit;
  343. }
  344. /**
  345. * Converts an html string to PDF
  346. * @param string $document_html valid html
  347. * @param string $css CSS content of a CSS file
  348. * @param string $pdf_name pdf name
  349. * @param string $course_code course code
  350. * (if you are using html that are located in the document tool you must provide this)
  351. * @param string $outputMode the MPDF output mode can be:
  352. * 'I' (print on standard output),
  353. * 'D' (download file) (this is the default value),
  354. * 'F' (save to local file) or
  355. * 'S' (return as a string)
  356. * @return string Web path
  357. */
  358. public function content_to_pdf(
  359. $document_html,
  360. $css = '',
  361. $pdf_name = '',
  362. $course_code = null,
  363. $outputMode = 'D',
  364. $saveInFile = false,
  365. $fileToSave = null,
  366. $returnHtml = false
  367. ) {
  368. $urlAppend = api_get_configuration_value('url_append');
  369. if (empty($document_html)) {
  370. return false;
  371. }
  372. //clean styles and javascript document
  373. $clean_search = array(
  374. '@<script[^>]*?>.*?</script>@si',
  375. '@<style[^>]*?>.*?</style>@siU'
  376. );
  377. // Formatting the pdf
  378. $course_data = api_get_course_info($course_code);
  379. self::format_pdf($course_data);
  380. $document_html = preg_replace($clean_search, '', $document_html);
  381. //absolute path for frames.css //TODO: necessary?
  382. $absolute_css_path = api_get_path(WEB_CSS_PATH).api_get_setting('stylesheets').'/frames.css';
  383. $document_html = str_replace('href="./css/frames.css"', 'href="'.$absolute_css_path.'"', $document_html);
  384. $document_html = str_replace('../../', '', $document_html);
  385. $document_html = str_replace('../', '', $document_html);
  386. $document_html = str_replace(
  387. (empty($urlAppend) ? '' : $urlAppend.'/').'courses/'.$course_code.'/document/',
  388. '',
  389. $document_html
  390. );
  391. if (!empty($course_data['path'])) {
  392. $document_path = api_get_path(SYS_COURSE_PATH).$course_data['path'].'/document/';
  393. $doc = new DOMDocument();
  394. $result = @$doc->loadHTML($document_html);
  395. //Fixing only images @todo do the same thing with other elements
  396. $elements = $doc->getElementsByTagName('img');
  397. if (!empty($elements)) {
  398. foreach ($elements as $item) {
  399. $old_src = $item->getAttribute('src');
  400. //$old_src= str_replace('../','',$old_src);
  401. if (strpos($old_src, 'http') === false) {
  402. if (strpos($old_src, '/main/default_course_document') === false) {
  403. if (strpos($old_src, '/main/inc/lib/') === false) {
  404. $old_src_fixed = str_replace(api_get_path(REL_COURSE_PATH).$course_data['path'].'/document/', '', $old_src);
  405. $old_src_fixed = str_replace('courses/'.$course_data['path'].'/document/', '', $old_src_fixed);
  406. $new_path = $document_path.$old_src_fixed;
  407. $document_html = str_replace($old_src, $new_path, $document_html);
  408. }
  409. }
  410. }
  411. }
  412. }
  413. }
  414. //replace relative path by absolute path for resources
  415. //$document_html= str_replace('src="/chamilo/main/default_course_document/', 'temp_template_path', $document_html);// before save src templates not apply
  416. //$document_html= str_replace('src="/', 'temp_template_path', $document_html);// before save src templates not apply
  417. //$document_html= str_replace('src="/chamilo/main/default_course_document/', 'temp_template_path', $document_html);// before save src templates not apply
  418. //$src_http_www= 'src="'.api_get_path(WEB_COURSE_PATH).$course_data['path'].'/document/';
  419. //$document_html= str_replace('src="',$src_http_www, $document_html);
  420. //$document_html= str_replace('temp_template_path', 'src="/main/default_course_document/', $document_html);// restore src templates
  421. api_set_encoding_html($document_html, 'UTF-8'); // The library mPDF expects UTF-8 encoded input data.
  422. $title = api_get_title_html($document_html, 'UTF-8', 'UTF-8'); // TODO: Maybe it is better idea the title to be passed through
  423. // $_GET[] too, as it is done with file name.
  424. // At the moment the title is retrieved from the html document itself.
  425. if ($returnHtml) {
  426. return "<style>$css</style>".$document_html;
  427. }
  428. if (!empty($css)) {
  429. $this->pdf->WriteHTML($css, 1);
  430. }
  431. $this->pdf->WriteHTML($document_html);
  432. if (empty($pdf_name)) {
  433. $output_file = 'pdf_'.date('Y-m-d-his').'.pdf';
  434. } else {
  435. $pdf_name = api_replace_dangerous_char($pdf_name);
  436. $output_file = $pdf_name.'.pdf';
  437. }
  438. //$this->pdf->Output($output_file, $outputMode); // F to save the pdf in a file
  439. if ($outputMode == 'F') {
  440. $output_file = api_get_path(SYS_ARCHIVE_PATH).$output_file;
  441. }
  442. if ($saveInFile) {
  443. $fileToSave = !empty($fileToSave) ? $fileToSave : api_get_path(SYS_ARCHIVE_PATH).uniqid();
  444. $this->pdf->Output(
  445. $fileToSave,
  446. $outputMode
  447. ); // F to save the pdf in a file
  448. } else {
  449. $this->pdf->Output(
  450. $output_file,
  451. $outputMode
  452. ); // F to save the pdf in a file
  453. }
  454. if ($outputMode != 'F') {
  455. exit;
  456. }
  457. return $output_file;
  458. }
  459. /**
  460. * Gets the watermark from the platform or a course
  461. * @param string course code (optional)
  462. * @param mixed web path of the watermark image, false if there is nothing to return
  463. */
  464. public static function get_watermark($course_code = null)
  465. {
  466. $web_path = false;
  467. if (!empty($course_code) && api_get_setting('pdf_export_watermark_by_course') == 'true') {
  468. $course_info = api_get_course_info($course_code);
  469. $store_path = api_get_path(SYS_COURSE_PATH).$course_info['path'].'/'.api_get_current_access_url_id().'_pdf_watermark.png'; // course path
  470. if (file_exists($store_path)) {
  471. $web_path = api_get_path(WEB_COURSE_PATH).$course_info['path'].'/'.api_get_current_access_url_id().'_pdf_watermark.png';
  472. }
  473. } else {
  474. $store_path = api_get_path(SYS_CODE_PATH).'default_course_document/images/'.api_get_current_access_url_id().'_pdf_watermark.png'; // course path
  475. if (file_exists($store_path))
  476. $web_path = api_get_path(WEB_CODE_PATH).'default_course_document/images/'.api_get_current_access_url_id().'_pdf_watermark.png';
  477. }
  478. return $web_path;
  479. }
  480. /**
  481. * Deletes the watermark from the Platform or Course
  482. * @param string $course_code course code (optional)
  483. * @param mixed web path of the watermark image, false if there is nothing to return
  484. * @return bool
  485. */
  486. public function delete_watermark($course_code = null)
  487. {
  488. if (!empty($course_code) && api_get_setting('pdf_export_watermark_by_course') == 'true') {
  489. $course_info = api_get_course_info($course_code);
  490. // course path
  491. $store_path = api_get_path(SYS_COURSE_PATH).$course_info['path'].'/'.api_get_current_access_url_id().'_pdf_watermark.png';
  492. } else {
  493. // course path
  494. $store_path = api_get_path(SYS_CODE_PATH).'default_course_document/images/'.api_get_current_access_url_id().'_pdf_watermark.png';
  495. }
  496. if (file_exists($store_path)) {
  497. unlink($store_path);
  498. return true;
  499. }
  500. return false;
  501. }
  502. /**
  503. * Uploads the pdf watermark in the main/default_course_document directory or in the course directory
  504. * @param string $filename filename
  505. * @param string $source_file path of the file
  506. * @param string $course_code
  507. * @return mixed web path of the file if sucess, false otherwise
  508. */
  509. public function upload_watermark($filename, $source_file, $course_code = null)
  510. {
  511. if (!empty($course_code) && api_get_setting('pdf_export_watermark_by_course') == 'true') {
  512. $course_info = api_get_course_info($course_code);
  513. $store_path = api_get_path(SYS_COURSE_PATH).$course_info['path']; // course path
  514. $web_path = api_get_path(WEB_COURSE_PATH).$course_info['path'].'/pdf_watermark.png';
  515. } else {
  516. $store_path = api_get_path(SYS_CODE_PATH).'default_course_document/images'; // course path
  517. $web_path = api_get_path(WEB_CODE_PATH).'default_course_document/images/'.api_get_current_access_url_id().'_pdf_watermark.png';
  518. }
  519. $course_image = $store_path.'/'.api_get_current_access_url_id().'_pdf_watermark.png';
  520. if (file_exists($course_image)) {
  521. @unlink($course_image);
  522. }
  523. $my_image = new Image($source_file);
  524. $result = $my_image->send_image($course_image, -1, 'png');
  525. if ($result) {
  526. $result = $web_path;
  527. }
  528. return $result;
  529. }
  530. /**
  531. * Returns the default header
  532. */
  533. public function get_header($course_code = null)
  534. {
  535. /*$header = api_get_setting('pdf_export_watermark_text');
  536. if (!empty($course_code) && api_get_setting('pdf_export_watermark_by_course') == 'true') {
  537. $header = api_get_course_setting('pdf_export_watermark_text');
  538. }
  539. return $header;*/
  540. }
  541. /**
  542. * Sets the PDF footer
  543. */
  544. public function set_footer()
  545. {
  546. $this->pdf->defaultfooterfontsize = 12; // in pts
  547. $this->pdf->defaultfooterfontstyle = 'B'; // blank, B, I, or BI
  548. $this->pdf->defaultfooterline = 1; // 1 to include line below header/above footer
  549. $view = new Template('', false, false, false, true, false, false);
  550. $template = $view->get_template('export/pdf_footer.tpl');
  551. $footerHTML = $view->fetch($template);
  552. $this->pdf->SetHTMLFooter($footerHTML, 'E'); //Even pages
  553. $this->pdf->SetHTMLFooter($footerHTML, 'O'); //Odd pages
  554. }
  555. /**
  556. * Sets the PDF header
  557. * @param array $course_data
  558. */
  559. public function set_header($course_data)
  560. {
  561. $this->pdf->defaultheaderfontsize = 10; // in pts
  562. $this->pdf->defaultheaderfontstyle = 'BI'; // blank, B, I, or BI
  563. $this->pdf->defaultheaderline = 1; // 1 to include line below header/above footer
  564. $userId = api_get_user_id();
  565. if (!empty($course_data['code'])) {
  566. $teacher_list = CourseManager::get_teacher_list_from_course_code($course_data['code']);
  567. $teachers = '';
  568. if (!empty($teacher_list)) {
  569. foreach ($teacher_list as $teacher) {
  570. if ($teacher['user_id'] != $userId) {
  571. continue;
  572. }
  573. // Do not show the teacher list see BT#4080 only the current teacher name
  574. $teachers = api_get_person_name($teacher['firstname'], $teacher['lastname']);
  575. }
  576. }
  577. $organization = ChamiloApi::getPlatformLogo();
  578. // Use custom logo image.
  579. $pdfLogo = api_get_setting('pdf_logo_header');
  580. if ($pdfLogo === 'true') {
  581. $visualTheme = api_get_visual_theme();
  582. $img = api_get_path(SYS_CSS_PATH).'themes/'.$visualTheme.'/images/pdf_logo_header.png';
  583. if (file_exists($img)) {
  584. $img = api_get_path(WEB_CSS_PATH).'themes/'.$visualTheme.'/images/pdf_logo_header.png';
  585. $organization = "<img src='$img'>";
  586. }
  587. }
  588. $view = new Template('', false, false, false, true, false, false);
  589. $view->assign('teacher_name', $teachers);
  590. $view->assign('organization', $organization);
  591. $template = $view->get_template('export/pdf_header.tpl');
  592. $headerHTML = $view->fetch($template);
  593. $this->pdf->SetHTMLHeader($headerHTML, 'E');
  594. $this->pdf->SetHTMLHeader($headerHTML, 'O');
  595. }
  596. }
  597. /**
  598. * @param string $header html content
  599. */
  600. public function set_custom_header($header)
  601. {
  602. $this->custom_header = $header;
  603. }
  604. /**
  605. * @param array $footer html content
  606. */
  607. public function set_custom_footer($footer)
  608. {
  609. $this->custom_footer = $footer;
  610. }
  611. /**
  612. * Pre-formats a PDF to the right size and, if not stated otherwise, with
  613. * header, footer and watermark (if any)
  614. * @param array $course_data General course information (to fill headers)
  615. * @param bool $complete Whether we want headers, footers and watermark or not
  616. */
  617. public function format_pdf($course_data, $complete = true)
  618. {
  619. if ($complete === false) {
  620. error_log('Asked with no decoration');
  621. }
  622. $course_code = null;
  623. if (!empty($course_data)) {
  624. $course_code = $course_data['code'];
  625. }
  626. /*$pdf->SetAuthor('Documents Chamilo');
  627. $pdf->SetTitle('title');
  628. $pdf->SetSubject('Exported from Chamilo Documents');
  629. $pdf->SetKeywords('Chamilo Documents');
  630. */
  631. // TODO: To be read from the html document.
  632. $this->pdf->directionality = api_get_text_direction();
  633. $this->pdf->useOnlyCoreFonts = true;
  634. // Use different Odd/Even headers and footers and mirror margins
  635. $this->pdf->mirrorMargins = 1;
  636. // Add decoration only if not stated otherwise
  637. if ($complete) {
  638. // Adding watermark
  639. if (api_get_setting('pdf_export_watermark_enable') == 'true') {
  640. $watermark_file = self::get_watermark($course_code);
  641. if ($watermark_file) {
  642. //http://mpdf1.com/manual/index.php?tid=269&searchstring=watermark
  643. $this->pdf->SetWatermarkImage($watermark_file);
  644. $this->pdf->showWatermarkImage = true;
  645. } else {
  646. $watermark_file = self::get_watermark(null);
  647. if ($watermark_file) {
  648. $this->pdf->SetWatermarkImage($watermark_file);
  649. $this->pdf->showWatermarkImage = true;
  650. }
  651. }
  652. if ($course_code) {
  653. $watermark_text = api_get_course_setting('pdf_export_watermark_text');
  654. if (empty($watermark_text)) {
  655. $watermark_text = api_get_setting('pdf_export_watermark_text');
  656. }
  657. } else {
  658. $watermark_text = api_get_setting('pdf_export_watermark_text');
  659. }
  660. if (!empty($watermark_text)) {
  661. $this->pdf->SetWatermarkText(
  662. strcode2utf($watermark_text),
  663. 0.1
  664. );
  665. $this->pdf->showWatermarkText = true;
  666. }
  667. }
  668. if (empty($this->custom_header)) {
  669. self::set_header($course_data);
  670. } else {
  671. $this->pdf->SetHTMLHeader($this->custom_header, 'E');
  672. $this->pdf->SetHTMLHeader($this->custom_header, 'O');
  673. }
  674. if (empty($this->custom_footer)) {
  675. self::set_footer();
  676. } else {
  677. $this->pdf->SetHTMLFooter($this->custom_footer);
  678. }
  679. }
  680. }
  681. /**
  682. * Generate a PDF file from $html in SYS_APP_PATH
  683. *
  684. * @param string $html PDF content
  685. * @param string $fileName File name
  686. * @param string $dest Optional. Directory to move file
  687. * @return string The PDF path
  688. */
  689. public function exportFromHtmlToFile($html, $fileName, $dest = null)
  690. {
  691. $this->template = $this->template ?: new Template('', false, false, false, false, false, false);
  692. $cssFile = api_get_path(SYS_CSS_PATH).'themes/'.$this->template->theme.'/print.css';
  693. if (!file_exists($cssFile)) {
  694. $cssFile = api_get_path(SYS_CSS_PATH).'print.css';
  695. }
  696. $pdfPath = self::content_to_pdf(
  697. $html,
  698. file_get_contents($cssFile),
  699. $fileName,
  700. $this->params['course_code'],
  701. 'F'
  702. );
  703. if (!$dest) {
  704. return $pdfPath;
  705. }
  706. move($pdfPath, $dest);
  707. return $dest.basename($pdfPath);
  708. }
  709. /**
  710. * Create a PDF and save it into the documents area
  711. * @param string $htmlContent HTML Content
  712. * @param string $fileName The file name
  713. * @param integer $courseId The course ID
  714. * @param int $sessionId Optional. The session ID
  715. */
  716. public function exportFromHtmlToDocumentsArea($htmlContent, $fileName, $courseId, $sessionId = 0)
  717. {
  718. $userId = api_get_user_id();
  719. $courseInfo = api_get_course_info_by_id($courseId);
  720. $courseDirectory = api_get_path(SYS_COURSE_PATH).$courseInfo['directory'].'/document/';
  721. $docPath = $this->exportFromHtmlToFile(
  722. $htmlContent,
  723. $fileName,
  724. $courseDirectory
  725. );
  726. $docId = add_document(
  727. $courseInfo,
  728. str_replace($courseDirectory, '/', $docPath),
  729. 'file',
  730. filesize($docPath),
  731. $fileName,
  732. null,
  733. false,
  734. true,
  735. null,
  736. $sessionId,
  737. $userId
  738. );
  739. api_item_property_update($courseInfo, TOOL_DOCUMENT, $docId, 'DocumentAdded', $userId);
  740. Display::addFlash(Display::return_message(get_lang('ItemAdded')));
  741. }
  742. }