<?php
// This file is part of Exabis Eportfolio (extension for Moodle)
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
// (c) 2016 GTN - Global Training Network GmbH <office@gtn-solutions.com>.

// require_once __DIR__.'/classes/fpdf.php';
require_once ($CFG->dirroot.'/lib/tcpdf/tcpdf.php');

class exaportTCPDF extends TCPDF {

    public $view_meta_data = null;
    private $working_page = 1;

    public function __construct($orientation='P', $unit='mm', $format='A4', $unicode=true, $encoding='UTF-8', $diskcache=false, $pdfa=false, $view = null){
        if ($view) {
            $this->view_meta_data = $view;
        }
        return parent::__construct($orientation, $unit, $format, $unicode, $encoding, $diskcache, $pdfa);
    }

    protected function setHeader() {
        if ($this->getPage() == 1) {
            return; // do not add pahe header into first page. Header of the first page is the common content
        }
        return parent::setHeader();
    }

    // Page header
    public function Header() {
        // Line
        $style = array('width' => 0.25, 'cap' => 'round', 'join' => 'round', 'dash' => '0', 'phase' => 0, 'color' => array(240));
        $page_params = $this->getPageDimensions(1);
        // line
        $base_line_y = 7;
        $this->Line(-10, $base_line_y, $page_params['wk'] + 10, $base_line_y, $style);
        // view title:
        $name = $this->getViewMetaData()->name;
        $width_text = $page_params['wk'] - $page_params['rm'] - 5;
        $this->SetTextColor(200, 200, 200);
        $this->SetFont('helvetica', '', 10);
        $text_height = $this->getStringHeight($width_text, $name);
        $this->SetY($base_line_y - $text_height, false);
        $this->Cell($width_text, 0, $name, 0, 0, 'R');

        // lines for margins (developing)
        // $style = array('width' => 1, 'cap' => 'round', 'join' => 'round', 'dash' => '0', 'phase' => 0, 'color' => array(250, 0, 0));
        // $this->Line(-10, 15, $page_params['wk'] + 10, 15, $style);

    }

    // Page footer
    public function Footer() {
        $page_params = $this->getPageDimensions(1);
        $base_line_y = $page_params['hk'] - 15;
        $this->SetTextColor(170, 170, 170);
        $this->SetFont('helvetica', '', 10);
        $zero_x = $this->GetX();

        // Position at 15 mm from bottom
        $this->SetY($base_line_y, false);
        // Line
        $style = array('width' => 0.25, 'cap' => 'round', 'join' => 'round', 'dash' => '0', 'phase' => 0, 'color' => array(170));
        $this->Line(-10, $base_line_y, $page_params['wk'] + 10, $base_line_y, $style);
        // current date
        $this->Cell(0, 0, date('d.m.Y'), 0, false, 'L', 0, '', 0, false, 'T', 'M');
        $this->SetX($zero_x);
        // Page number
        $this->Cell(0, 0, $this->getAliasNumPage().'/'.$this->getAliasNbPages(), 0, false, 'C', 0, '', 0, false, 'T', 'M');
        $this->SetX($zero_x);
        // generated
        $this->Cell(0, 0, 'Generated by exabis ePortfolio', 0, false, 'R', 0, '', 0, false, 'T', 'M');
        $this->SetX($zero_x);
    }

    public function Output($name = 'doc.pdf', $dest = 'I'){
        $this->tcpdflink = false; // to delete extra empty page
        return parent::Output($name, $dest);
    }

    public function fillMetaData($view){
        $this->view_meta_data = $view;
    }

    public function getViewMetaData(){
        return $this->view_meta_data;
    }

    public function getWorkingPage(){
        return $this->working_page;
    }

    public function setWorkingPage($page){
        $this->working_page = $this->page;
    }

    public function setPage($pnum, $resetmargins = false){
        $this->working_page = $pnum;
        return parent::setPage($pnum, $resetmargins);
    }

}

class ExaportVievPdf {

    /** @var null TCPDF */
    private $pdf = null;

    private $y_top_position = 15;

    private $first_page_top_margin = 5;

    private $page_top_margin = 15;
    private $page_bottom_margin = 15;
    private $page_left_margin = 5;
    private $page_bottom_margin = 5;

    private $main_font_size = 10;
    private $main_font_name = 'helvetica';

    private $column_hights = [];

    private $current_y = 0;

    private $vertical_margin_after_block = 5;
    private $max_thumbnail_height = 15;
    private $maxThumbnailWidth = 20;

    private $orientation = 'P';
    private $format = 'A4';

    private $first_page_for_main_report_data = 1;

    private $view_meta_data = null;

    private $page_added = false;

    public function __construct($view = null)
    {

        // create new PDF document
        $this->pdf = new exaportTCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false, false, $view);
        // set document properties
        $this->pdf->SetCreator(PDF_CREATOR);
        $this->pdf->SetAuthor('Moodle "Exabis ePortfolio" block'); // TODO: username?
        $this->pdf->SetTitle('Exaport view');
        $this->pdf->SetSubject('Exaport view');
        // remove default header/footer
        // $this->pdf->setPrintHeader(false);
        // $this->pdf->setPrintFooter(false);

        // set default header data
        $this->pdf->SetHeaderData(PDF_HEADER_LOGO, PDF_HEADER_LOGO_WIDTH, PDF_HEADER_TITLE, PDF_HEADER_STRING);

        // set header and footer fonts
        $this->pdf->setHeaderFont(array(PDF_FONT_NAME_MAIN, '', PDF_FONT_SIZE_MAIN));
        $this->pdf->setFooterFont(array(PDF_FONT_NAME_DATA, '', PDF_FONT_SIZE_DATA));

        // set default monospaced font
        $this->pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);
        // set margins
        $this->pdf->SetMargins($this->page_left_margin, $this->page_top_margin, $this->page_bottom_margin);
        // set auto page breaks
        $this->pdf->SetAutoPageBreak(true, $this->page_bottom_margin);
        // set image scale factor
        $this->pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);
        // default fill color
        $this->pdf->SetFillColor(255, 255, 255);

    }

    /**
     * @param $layout
     * @param int $column_ind note: indexes are from 1
     * @param int $fact_value_from_source
     * @return float
     */
    public function getColumnWidth($layout, $column_ind = 1, $fact_value_from_source = 0) {
        $widths = [
            1 => [100],
            2 => [50, 50],
            3 => [67, 33],
            4 => [33, 67],
            5 => [33, 33, 33],
            6 => [25, 50, 25],
            7 => [14, 70, 15],
            8 => [25, 25, 25, 25],
            9 => [20, 30, 30, 20],
            10 => [20, 20, 20, 20, 20],
        ];
        $result_percent = @$widths[$layout][$column_ind - 1];
        if ($fact_value_from_source) {
            return round($fact_value_from_source * $result_percent / 100);
        }
        return $result_percent;
    }

    // Function to test tcpdf functionalities. Rename it to "generateView" and change name of original "generateView" to some other
    function genarateViewDev($layout, $columnsWithBlocks, $access) {

        // set font
        $this->setDefaultFont();
        // add first page
        $this->addDefaultPage();

        $h = 23;

        $page_height = $this->pdf->getPageDimensions(1)['hk'] - $this->pdf->getPageDimensions(1)['bm'] - $this->pdf->getPageDimensions(1)['tm']; // from first page?
        $page_limit = 4;
        $current_page = $this->pdf->getPage();

        while ($h <= 1000 && $current_page <= $page_limit) {
            // $this->pdf->MultiCell(50, 0, $this->pdf->GetY(), 0, 'L', false, 1, 20, $h, true);
            $block_h = $this->writeHTMLCellReturnHeight(80, 20, $h, $h.'<br>'.str_repeat('<br>', rand(2, 7)));
            // $h += 20;
            $h = $this->increaseBlockY($h, $block_h);
            if ($h > $page_height) {
                $h = 20;
                $this->addDefaultPage();
                $current_page++;// = $this->pdf->getPage();
                $this->pdf->setPage($current_page);
            }
        }

        $this->pdf->Output('myview.pdf', 'I');

    }

    public function genarateView($layout, $columns_with_blocks, $access) {
        global $DB;

        $this->pdf->setHtmlVSpace(
            array(
                // 0 - for start tag; 1 - for end tag
                // h - how big; n - how many used 'h'
                'p' => array(0 => array('h' => 0.1, 'n' => 1), 1 => array('h' => 0.1, 'n' => 1)),
                'a' => array(0 => array('h' => 0.1, 'n' => 1), 1 => array('h' => 0.1, 'n' => 1)),
                'ul' => array(0 => array('h' => 0.1, 'n' => 10), 1 => array('h' => 0.1, 'n' => 10)),
                'li' => array(0 => array('h' => 0.1, 'n' => 10), 1 => array('h' => 0.1, 'n' => 10)),
            )
        );

        // set font
        $this->setDefaultFont();
        // add a page
        $this->addDefaultPage();

        // get view from first block
        $first_block = @$columns_with_blocks[1][0];
        if (!$first_block) {
            return 'no any block added yet';
        }
        $view = $DB->get_record("block_exaportview", array("id" => $first_block->viewid));
        if (!$this->pdf->view_meta_data) {
            $this->fillViewMetaData($view);
        }

        // background
        // $this->pdf->SetFillColor(200, 200, 200, -1);
        // $this->pdf->Rect(0, 0, $this->pdf->getPageWidth(), $this->pdf->getPageHeight(), 'DF', "");

        $this->addFirstPageHeader();

        $this->first_page_for_main_report_data = $this->pdf->getPage(); // for the case with very big view description

        // get current vertical position
        $y_original = $this->current_y;

        $columns_margin = 5;
        if (count($columns_with_blocks) == 1) {
            $columns_margin = 0;
        }
        $page_width = $this->pdf->getPageWidth() - $this->page_left_margin - $this->page_bottom_margin;

        foreach ($columns_with_blocks as $column_i => $column_blocks) {
            $this->column_hights[$column_i] = $y_original;
            $column_width = round($this->getColumnWidth($layout, $column_i, $page_width) - ($columns_margin / 2));
            $this->pdf->setPage($this->first_page_for_main_report_data); // always return to first page
            $this->pdf->setY($y_original, false);
            $this->current_y = $y_original;
            $y = $y_original;
            $x_start_column = ($column_width + $columns_margin) * ($column_i - 1) + $columns_margin;
            foreach ($column_blocks as $bclock_i => $block) {
            // $yBlockStart = $this->pdf->GetY();
                $ln = 1;
                if ($bclock_i == (count($column_blocks) - 1)) { // for last block
                    $ln = 0;
                }
                $this->setWorkingPage($this->pdf->getPage());
                $this->pdf->MultiCell($column_width, 0, ' ', 0, 'J', false, 0, $x_start_column + 25, $this->current_y, true); // Hack. restore some pdf behaviour
                // if ($this->page_added) {
                // $this->increaseBlockY($this->current_y, 2);
                // $this->page_added = false;
                // }
                $this->getViewBlockContent($column_i, $block, $access, $column_width, $x_start_column, $this->current_y, $ln);

            }

        }

        $this->pdf->Output('myview.pdf', 'I');

    }

    // template of block title
    public function addBlockName($name, $column_width) {
        $orig_font_size = $this->pdf->getFontSizePt();
        $orig_font_style = $this->pdf->getFontStyle();
        $this->pdf->SetFontSize($this->main_font_size + 3);
        $this->pdf->SetFont($this->titlesFontName, 'B');
        $name = $this->cleanHtmlContent($name);
        $this->pdf->Cell($column_width, 0, $name, 0, 1, 'J', true, '', 0, false, 'T', 'T');
        // return fonts
        $this->pdf->SetFont('helvetica', $orig_font_style, $orig_font_size);
    }


     function getViewBlockContent($column_i, $block, $access, $column_width, $x, $y, $ln) {
        global $USER, $CFG, $DB, $OUTPUT;
        $content = '';
        $view = $DB->get_record("block_exaportview", array("id" => $block->viewid));

        if ($block->text) {
            $block->text = file_rewrite_pluginfile_urls($block->text, 'pluginfile.php', context_user::instance($USER->id)->id, 'block_exaport', 'view_content', $access);
            $block->text = $this->cleanHtmlContent($block->text);
        }

        switch ($block->type) {
            case 'item':
                $item = $block->item;
                $y_before_block_inserted = $y;
                $y_block_original = $y;
                $y_block_current = $this->increaseBlockY(0, $y); // this Y used for every block, but can decrease if the new page is added
                $height_block_current = 0;

                // link to web-preview
                $linked = false;
                $block_href = $CFG->wwwroot.'/blocks/exaport/shared_item.php?access=view/'.$access.'&itemid='.$item->id.'&att='.$item->attachment;

                if ($item->name) {
                    $head_hight = $this->addHeadLine(strip_tags($item->name), $x, $y_block_current, $column_width, 0, null, true, 'L', $block_href);
                    $height_block_current += $head_hight;
                    $y_block_current = $this->increaseBlockY($y_block_current, $head_hight);
                    $linked = true;
                }

                switch($item->type) {
                    case 'file':
                        $file_links = [];
                        $select = "contextid='".context_user::instance($item->userid)->id."' ".
                            " AND component='block_exaport' AND filearea='item_file' AND itemid='".$item->id."' AND filesize>0 ";
                        if ($files = $DB->get_records_select('files', $select, null, 'id, filename, mimetype, filesize')) {
                            if (is_array($files)) {
                                $imgs = [];
                                $img_ws = [];
                                $im_hs = [];
                                // $width = 100;
                                $max_width = $max_height = $column_width / count($files);
                                $max_height = ($max_height > $this->max_thumbnail_height ? $this->max_thumbnail_height : $max_height);
                                $file_index = 1;
                                foreach ($files as $file) {
                                    if (strpos($file->mimetype, "image") !== false) {
                                        $imgsrc = moodle_url::make_pluginfile_url(context_user::instance($item->userid)->id, 'block_exaport', 'item_file/view/'.$access.'/itemid', $item->id, '/', $file->filename, false, false)->out();
                                        $imgsrc .= '/forPdf/'.$view->hash.'/'.$view->id.'/'.$USER->id; // images are got from PHP pdf generator, so they are not logged in as FE-user
                                        // file thumbnail
                                        // get list of images with sizes:
                                        $img_x = $x + $column_width - ($max_width * $file_index);
                                        list($img_ws[], $im_hs[], $imgs[]) = $this->addImageBySrc($imgsrc, $img_x, $y_block_current, $max_width, $max_height, '', false);
                                    } else {
                                        // get data for Fileinfo block.
                                        // Link to the file.
                                        $ffurl = s("{$CFG->wwwroot}/blocks/exaport/portfoliofile.php?access=view/".$access."&itemid=".$item->id."&inst=".$file->pathnamehash);
                                        // Human filesizes.
                                        $units = array('B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB');
                                        $power = $file->filesize > 0 ? floor(log($file->filesize, 1024)) : 0;
                                        $filesize = number_format($file->filesize / pow(1024, $power), 2, '.', ',').' '.$units[$power];
                                        $file_links[$file->filename] = [
                                            'url' => $ffurl,
                                            'size' => $filesize,
                                            'iconShown' => false,
                                        ];
                                        // if icon is possible
                                        // not for pdf?
                                        /*if (block_exaport_is_valid_media_by_filename($file->filename)) {
                                            $file_links[$file->filename]['iconShown'] = true;
                                            $iconSrc = $OUTPUT->image_url(file_mimetype_icon($file->mimetype, 256))->out();
                                            $img_x = $x + $column_width - ($max_width * $file_index);
                                            list($img_ws[], $im_hs[], $imgs[]) = $this->addImageBySrc($iconSrc, $img_x, $y_block_current, $max_width, $max_height, $ffurl, false);
                                        }*/
                                    };
                                    $file_index++;
                                }
                                $height_block_current += max($im_hs);
                                $curr_page = $this->pdf->getPage();
                                $y_block_current = $this->increaseBlockY($y_block_current, max($im_hs));
                                $page_changed_by_image = ($curr_page != $this->pdf->getPage());
                                if ($page_changed_by_image) { // inserted image added new page
                                    $y_block_current = $this->y_top_position;
                                    $this->current_y = $this->y_top_position;
                                }
                                if ($item->id == 50) {
                                    $this->pdf->Circle(150, $y_block_current, 2);
                                }
                                // add file links (list)
                                if (count($file_links) > 0) {
                                    $linkscontent = '<p>';
                                    foreach ($file_links as $f_name => $f_data) {
                                        $linkscontent .= '<a style="text-decoration: none;" href="'.$f_data['url'].'">'.$f_name.'</a> ('.$f_data['size'].')';
                                    }
                                    $linkscontent .= '</p>';
                                    $cell_hight = $this->writeHTMLCellReturnHeight($column_width, $x, $y_block_current, $linkscontent);
                                    $height_block_current += $cell_hight;
                                    $y_block_current = $this->increaseBlockY($y_block_current, $cell_hight);
                                }
                            }
                        }
                        if ($item->id == 50) {
                            $this->pdf->Circle(150, $y_block_current, 2);
                        }
                        break;
                    case 'link':
                        $thumbnail_part_width = round($column_width / 4);

                        $thumb_url = $CFG->wwwroot.'/blocks/exaport/item_thumb.php?item_id='.$item->id.'&access='.$access.'&ispdf=1&vhash='.$view->hash.'&vid='.$view->id.'&uid='.$USER->id;

                        // item thumbnail
                        if (list($img_w, $im_h) = $this->addImageBySrc($thumb_url, $x + $column_width - $thumbnail_part_width, $y_block_current, $this->maxThumbnailWidth, $this->max_thumbnail_height, $item->url)) {
                            $textContentWidth = $column_width - $thumbnail_part_width;
                        } else {
                            // no image
                            $textContentWidth = $column_width;
                        }

                        $url_text = '<a style="text-decoration: none;" href="'.$item->url.'">'.$item->url.'</a>';
                        $cell_hight = $this->writeHTMLCellReturnHeight($textContentWidth, $x, $y_block_current, $url_text);
                        $item->url = false; // DISABLE for next adding
                        if ($im_h > $cell_hight) {
                            $y_block_current = $this->increaseBlockY($y_block_current, $im_h);
                            $height_block_current += $im_h;
                        } else {
                            $y_block_current = $this->increaseBlockY($y_block_current, $cell_hight);
                            $height_block_current += $cell_hight;
                        }

                        break;
                    default:

                }
                // item url
                if ($item->url && $item->url != "false") {
                    // Link.
                    $this->pdf->SetXY($x, $y_block_current);
                    $cell_hight = $this->pdf->getStringHeight($column_width, $item->url);
                    $this->pdf->Cell($column_width, 0, $item->url, 0, 1, 'J', true, $item->url, 0, false, 'T', 'M');
                    $y_block_current = $this->increaseBlockY($y_block_current, $cell_hight);
                    $height_block_current += $cell_hight;
                }
                // description
                $intro = trim($item->intro);
                if ($intro) {
                    $cell_hight = 0;
                    if (strpos($intro, '<iframe') !== false) {
                        // embeded media
                        $dom = new DOMDocument;
                        $dom->loadHTML($intro);
                        $iframe_element = $dom->getElementsByTagName('iframe')->item(0);
                        $src = $iframe_element->getAttribute("src");
                        if ($src) {
                            $src_text = '<a style="text-decoration: none;" href="'.$src.'">'.$src.'</a>';
                            $cell_hight = $this->writeHTMLCellReturnHeight($column_width, $x, $y_block_current, $src_text);
                        }
                    } else {
                        // common html
                        $intro = file_rewrite_pluginfile_urls($intro, 'pluginfile.php', context_user::instance($item->userid)->id,
                            'block_exaport', 'item_content', 'view/' . $access . '/itemid/' . $item->id);
                        $intro = $this->convertHtmlToPdfHtml($intro);
                        $cell_hight = $this->writeHTMLCellReturnHeight($column_width, $x, $y_block_current, $intro);
                    }
                    $y_block_current = $this->increaseBlockY($y_block_current, $cell_hight);
                    $height_block_current += $cell_hight;
                }

                // add link to block web-view if it is not linked in title
                if (!$linked) {
                    $href = $CFG->wwwroot . '/blocks/exaport/shared_item.php?access=view/' . $access . '&itemid=' . $item->id . '&att=' . $item->attachment;
                    $link_height = $this->addLinkToBlock($block_href, $x, $y_block_current);
                    $y_block_current = $this->increaseBlockY($y_block_current, $link_height);
                    $height_block_current += $link_height;
                }

                // $this->increaseY($height_block_current);
                // bottom block margin
                $this->increaseY($this->vertical_margin_after_block);
                break;

            case 'personal_information':
                $height_block_current = 0;
                $y_block_current = $y;
                if ($block->block_title) {
                    $head_height = $this->addHeadLine(strip_tags($block->block_title), $x, $y, $column_width);
                    $height_block_current += $head_height;
                    $y_block_current = $this->increaseBlockY($y_block_current, $head_height);
                }
                // picture
                $textContentWidth = $column_width;
                $imgH = 0;
                if (isset($block->picture)) {
                    // pictureWidth = 50%; ???
                    $picture_part_width = round($column_width / 4);
                    $imgSrc = $block->picture;
                    $curr_page = $this->pdf->getPage();
                    list($img_w, $imgH) = $this->addImageBySrc($imgSrc, $x + $column_width - $picture_part_width, $y_block_current, $picture_part_width, 30, '');
                    $page_changed_by_image = ($curr_page != $this->pdf->getPage());
                    if ($page_changed_by_image) { // inserted image added new page
                        $y_block_current = $this->y_top_position;
                        $this->current_y = $this->y_top_position;
                    }
                }
                $person_info = [];
                $name = '';
                if (isset($block->firstname)) {
                    $name .= $block->firstname;
                }
                if (isset($block->lastname)) {
                    $name .= ' '.$block->lastname;
                }
                $name = trim($name);
                $person_info['name'] = $name;

                if (isset($block->email)) {
                    $person_info['email'] = $block->email;
                }
                if (isset($block->text)) {
                    $person_info['description'] = $block->text;// strip_tags($block->text);
                }
                $full_text_height = 0;
                foreach ($person_info as $key => $info_item) {
                    $cell_hight = $this->pdf->getStringHeight($column_width, $info_item);
                    switch ($key) {
                        case 'name':
                            $this->pdf->SetFont($this->main_font_name, 'B', $this->main_font_size + 1);
                            $this->pdf->MultiCell($textContentWidth, 0, $info_item, 0, 'L', true, 0, $x, $y_block_current, false, 0, false, true, 0, 'T', false);
                            $this->setDefaultFont();
                            break;
                        case 'description':
                            $info_item = $this->convertHtmlToPdfHtml($info_item);
                            $cell_hight = $this->writeHTMLCellReturnHeight($textContentWidth, $x, $y_block_current, $info_item);
                            break;
                        default:
                            $this->pdf->MultiCell($textContentWidth, 0, $info_item, 0, 'J', true, 0, $x, $y_block_current, false, 0, false, true, 0, 'T', false);
                    }
                    $y_block_current = $this->increaseBlockY($y_block_current, $cell_hight);
                    $full_text_height += $cell_hight;
                }
                if ($imgH > $full_text_height) {
                    $full_text_height = $imgH;
                }
                $height_block_current += $full_text_height;

                $this->increaseY($height_block_current);
                // bottom block margin
                $this->increaseY($this->vertical_margin_after_block);
                break;
            case 'headline':
                $y_block_current = $y;
                $line_height = $this->addHeadLine(strip_tags($block->text), $x, $y, $column_width);
                $y_block_current = $this->increaseBlockY($y_block_current, $line_height);
                $this->increaseY($line_height);
                break;
            case 'media':
                // really it is a NOTE artifact
                /*if ($block->block_title) {
                    $line_height = $this->addHeadLine(strip_tags($block->block_title), $x, $y, $column_width);
                    $this->increaseY($line_height);
                }*/
                break;
            case 'badge':
                $badges = block_exaport_get_all_user_badges($view->userid);
                if (count($badges) == 0) {
                    return false;
                }
                $badge = null;
                foreach ($badges as $tmp) {
                    if ($tmp->id == $block->itemid) {
                        $badge = $tmp;
                        break;
                    };
                };
                if (!$badge) {
                    // Badge not found.
                    return false;
                }
                $height_block_current = 0;
                $y_block_current = $y;
                $head_height = $this->addHeadLine(strip_tags($badge->name), $x, $y, $column_width);
                $y_block_current = $this->increaseBlockY($y_block_current, $head_height);
                $height_block_current += $head_height;
                $picture_part_width = $column_width / 4;
                if (!$badge->courseid) { // For badges with courseid = NULL.
                    $badge->imageUrl = (string) moodle_url::make_pluginfile_url(1, 'badges', 'badgeimage', $badge->id, '/', 'f1', false);
                } else {
                    $context = context_course::instance($badge->courseid);
                    $badge->imageUrl = (string) moodle_url::make_pluginfile_url($context->id, 'badges', 'badgeimage', $badge->id, '/', 'f1', false);
                }
                $curr_page = $this->pdf->getPage();
                list($img_w, $imgH) = $this->addImageBySrc($badge->imageUrl, $x + $column_width - $picture_part_width, $y_block_current, $picture_part_width, 30, '');
                $page_changed_by_image = ($curr_page != $this->pdf->getPage());
                if ($page_changed_by_image) { // inserted image added new page
                    $y_block_current = $this->y_top_position;
                    $this->current_y = $this->y_top_position;
                }

                $description = $this->convertHtmlToPdfHtml($badge->description);
                $cell_hight = $this->writeHTMLCellReturnHeight($column_width - $picture_part_width, $x, $y_block_current, $description);

                if ($cell_hight < $imgH) {
                    $y_block_current = $this->increaseBlockY($y_block_current, $imgH);
                    $height_block_current += $imgH;
                } else {
                    $y_block_current = $this->increaseBlockY($y_block_current, $cell_hight);
                    $height_block_current += $cell_hight;
                }

                $this->increaseY($height_block_current);
                // bottom block margin
                $this->increaseY($this->vertical_margin_after_block);

                break;
            case 'cv_information':
                // CV information
                $height_block_current = 0;
                $y_block_current = $y;
                $body_content = '';
                $attachments = [];
                $resume = block_exaport_get_resume_params($view->userid, true);
                switch ($block->resume_itemtype) {
                    case 'edu':
                        if ($block->itemid && $resume && $resume->educations[$block->itemid]) {
                            $item_data = $resume->educations[$block->itemid];
                            $attachments = $item_data->attachments;
                            $description = '';
                            $description .= $item_data->institution.': ';
                            $description .= $item_data->qualname;
                            if ($item_data->startdate != '' || $item_data->enddate != '') {
                                $description .= ' (';
                                if ($item_data->startdate != '') {
                                    $description .= $item_data->startdate;
                                }
                                if ($item_data->enddate != '') {
                                    $description .= ' - '.$item_data->enddate;
                                }
                                $description .= ')';
                            }
                            if ($item_data->qualdescription != '') {
                                $description .= '<br>'.$item_data->qualdescription;
                            }
                            $body_content .= $description;
                        }
                        break;
                    case 'employ':
                        if ($block->itemid && $resume && $resume->employments[$block->itemid]) {
                            $item_data = $resume->employments[$block->itemid];
                            $attachments = $item_data->attachments;
                            $description = '';
                            $description .= $item_data->jobtitle.': ';
                            $description .= $item_data->employer;
                            if ($item_data->startdate != '' || $item_data->enddate != '') {
                                $description .= ' (';
                                if ($item_data->startdate != '') {
                                    $description .= $item_data->startdate;
                                }
                                if ($item_data->enddate != '') {
                                    $description .= ' - '.$item_data->enddate;
                                }
                                $description .= ')';
                            }
                            if ($item_data->positiondescription != '') {
                                $description .= '<br>'.$item_data->positiondescription;
                            }
                            $body_content .= $description;
                        }
                        break;
                    case 'certif':
                        if ($block->itemid && $resume && $resume->certifications[$block->itemid]) {
                            $item_data = $resume->certifications[$block->itemid];
                            $attachments = $item_data->attachments;
                            $description = '';
                            $description .= $item_data->title.' ';
                            if ($item_data->date != '') {
                                $description .= '('.$item_data->date.')';
                            }
                            if ($item_data->description != '') {
                                $description .= '<br>'.$item_data->description;
                            }
                            $body_content = $description;
                        }
                        break;
                    case 'public':
                        if ($block->itemid && $resume && $resume->publications[$block->itemid]) {
                            $item_data = $resume->publications[$block->itemid];
                            $attachments = $item_data->attachments;
                            $description = '';
                            $description .= $item_data->title;
                            if ($item_data->contribution != '') {
                                $description .= ' ('.$item_data->contribution.')';
                            }
                            if ($item_data->date != '') {
                                $description .= '('.$item_data->date.')';
                            }
                            if ($item_data->contributiondetails != '' || $item_data->url != '') {
                                $description .= '<br>';
                                if ($item_data->contributiondetails != '') {
                                    $description .= $item_data->contributiondetails;
                                }
                                if ($item_data->url != '') {
                                    $description .= '<br /><a href="'.$item_data->url.'" target="_blank">'.$item_data->url.'</a>';
                                }
                            }
                            $body_content = $description;
                        }
                        break;
                    case 'mbrship':
                        if ($block->itemid && $resume && $resume->profmembershipments[$block->itemid]) {
                            $item_data = $resume->profmembershipments[$block->itemid];
                            $attachments = $item_data->attachments;
                            $description = '';
                            $description .= $item_data->title.' ';
                            if ($item_data->startdate != '' || $item_data->enddate != '') {
                                $description .= ' (';
                                if ($item_data->startdate != '') {
                                    $description .= $item_data->startdate;
                                }
                                if ($item_data->enddate != '') {
                                    $description .= ' - '.$item_data->enddate;
                                }
                                $description .= ')';
                            }
                            if ($item_data->description != '') {
                                $description .= '<br>'.$item_data->description;
                            }
                            $body_content = $description;
                        }
                        break;
                    case 'goalspersonal':
                    case 'goalsacademic':
                    case 'goalscareers':
                    case 'skillspersonal':
                    case 'skillsacademic':
                    case 'skillscareers':
                        $attachments = @$resume->{$block->resume_itemtype.'_attachments'};
                        $description = '';
                        if ($resume && $resume->{$block->resume_itemtype}) {
                            $description .= '<br>'.$resume->{$block->resume_itemtype}.' ';
                        }
                        $body_content = $description;
                        break;
                    case 'interests':
                        $description = '';
                        if ($resume->interests != '') {
                            $description .= $resume->interests;
                        }
                        $body_content = $description;
                        break;
                    default:
                        // no!
                }

                if ($attachments && is_array($attachments) && count($attachments) > 0 && $block->resume_withfiles) {
                    $body_content .= '<ul>';
                    foreach ($attachments as $attachm) {
                        $body_content .= '<li><p><a href="'.$attachm['fileurl'].'" target="_blank">'.$attachm['filename'].'</a></p></li>';
                    }
                    $body_content .= '</ul>';
                }

                // if the resume item is empty - do not show
                $body_content = trim($body_content);
                if ($body_content != ''/* && 11==22*/) {
                    $text = $this->convertHtmlToPdfHtml($body_content);
                    $html_height = $this->writeHTMLCellReturnHeight($column_width, $x, $y_block_current, $text);
                    $y_block_current = $this->increaseBlockY($y_block_current, $html_height);
                    $height_block_current += $html_height;
                    $this->increaseY($height_block_current);
                    // bottom block margin
                    // $this->increaseY($this->vertical_margin_after_block);
                }
                break;

            default:
                // Text block
                $height_block_current = 0;
                $y_block_current = $y;
                if ($block->block_title) {
                    $head_height = $this->addHeadLine(strip_tags($block->block_title), $x, $y, $column_width);
                    $y_block_current = $this->increaseBlockY($y_block_current, $head_height);
                    $height_block_current += $head_height;
                }
                $text = $this->convertHtmlToPdfHtml($block->text);
                $html_height = $this->writeHTMLCellReturnHeight($column_width, $x, $y_block_current, $text);
                $y_block_current = $this->increaseBlockY($y_block_current, $html_height);
                $height_block_current += $html_height;
                $this->increaseY($height_block_current);
                // bottom block margin
                $this->increaseY($this->vertical_margin_after_block);

        }

    }

    function cleanHtmlContent($htmlContent = '') {
        $htmlContent = format_text($htmlContent, FORMAT_HTML);
        // TODO: !!! simplifire html
        return $htmlContent;
    }

    // used for position of next block
    public function increaseY($add_y = 0) {
        return true;
        $this->current_y += $add_y;
        $page_height = $this->pdf->getPageDimensions($this->first_page_for_main_report_data)['hk'] - $this->pdf->getPageDimensions($this->first_page_for_main_report_data)['bm'] - $this->pdf->getPageDimensions($this->first_page_for_main_report_data)['tm']; // from first page?

        if ($this->current_y >= $page_height) {
            $num_pages = $this->pdf->getNumPages();
            $this->working_page++;
            if ($this->working_page > $num_pages) {
                $this->addDefaultPage();
            }
            $this->pdf->setPage($this->working_page);
            $this->current_y = $this->y_top_position;
        }

    }

    // used for position of elements of the block
    function increaseBlockY($current_y, $add_y = 0) {
        // return true;
        $dev_text = '';
        $dev_text .= $this->pdf->getPage().'p = ';

        $page_height = $this->pdf->getPageDimensions($this->first_page_for_main_report_data)['hk'] - $this->pdf->getPageDimensions($this->first_page_for_main_report_data)['bm'] - $this->pdf->getPageDimensions($this->first_page_for_main_report_data)['tm']; // from first page?
        $current_page = $this->pdf->getPage();
        $current_y_before_change = $current_y;
        $y_before_increasing = $current_y;
        $new_y = $current_y + $add_y;

        if ($new_y >= $page_height || $this->getWorkingPage() < $this->pdf->getPage()) {

            $new_y = $new_y - ($page_height - $y_before_increasing); // delete part in the end of first page

            $current_page = $current_page + floor($new_y / $page_height);

            $new_y = $new_y - ($page_height * floor($new_y / $page_height)); // delete Remainder of heigh divided by page heigh

            $new_y = round($new_y);

            // if ($new_y < $this->y_top_position) {
                $new_y = $new_y + $this->y_top_position;// + ($this->pdf->getStringHeight(100, '.') * 2);
            // $this->addDeveloperInfo('--'.round($new_y).'--', 100, $new_y);
            // }

            if ($this->pdf->getNumPages() < $current_page) {
                $add_pages = $current_page - $this->pdf->getNumPages();
                for ($i = 1; $i <= $add_pages; $i++) {
                    $this->addDefaultPage();
                }
                $this->page_added = true;
            }
            // $current_page++;
            $this->pdf->setPage($current_page);
            $current_y = $new_y;//$this->y_top_position;
            $this->current_y = $new_y;//$this->y_top_position; // main y position is also must be changed!

            $dev_text .= ' new: '.$current_page.'p = '.$this->current_y;
        }

        // $this->addDeveloperInfo('added: '.$add_y, $this->pdf->GetX() - 5, $current_y);

        /* $this->pdf->SetTextColor(255, 0, 0);
        $yCurr = $this->pdf->GetY();
        $this->pdf->SetX(50 * ($this->pdf->getPage() - 1));
        // 2p = 293.91952733333 new: 3p = 15 !!!!!!!!!!!!! <----
        $this->pdf->SetY($yCurr - 3, false);
        $this->pdf->Cell(200, 0, $dev_text);
        $this->setDefaultFont();
        $this->pdf->SetY($yCurr, false); */

        $this->current_y = $new_y;
        return $new_y;

    }

    function addImageBySrc($src, $x, $y, $max_width = 0, $max_height = 0, $url = '', $hide = false){
        static $downloaded_images = null;
        if ($downloaded_images === null) {
            $downloaded_images = [];
        }
        /* if (!$hide && is_numeric($src)) {
            // add image from images buffer
            $this->pdf->Image('*'.$src, $x, $y, 0, $max_height, '', $url, 'T', false, 300, '', false, false, 0, 'R T', false, false, false);
            return array($max_width, $max_height, null);
        } */

        if (!$src) {
            return false;
        }
        if (array_key_exists($src, $downloaded_images)) {
            $file_data = $downloaded_images[$src];
        } else {
            $file_data = file_get_contents($src);
        }
        if ($file_data) {
            $downloaded_images[$src] = $file_data;

            $imagesize = getimagesizefromstring($file_data);

            if (!$imagesize) {
                $imagesize = getimagesize($src);
            }

            if (!$imagesize) {
                return false;
            }

            $block_w = $max_width;

            // WIDTH is MAIN dimension
            $im_w = ($imagesize[0] <= $max_width ? $imagesize[0] : $max_width);
            $im_koef = $im_w / $imagesize[0];
            $im_h = round($imagesize[1] * $im_koef);

            if ($max_height && $im_h > $max_height) {
                $im_h = $max_height;
                $koef = $im_h / $max_height;
                $im_w = round($im_w * $koef);
            }

            $r_color = random_int(10, 240);
            $g_color = random_int(10, 240);
            $b_color = random_int(10, 240);
            // $this->pdf->Rect($x, $y, $max_width, $max_height, 'S', [], array($r_color, $g_color, $b_color)); // for debugging
            // why horizontal align is not working????!!!!
            // hack with 'template' to align them to right!
            $template_id = $this->pdf->startTemplate($max_width, $max_height);
            $img = $this->pdf->Image('@' . $file_data, 0, 0, $max_width, $max_height, '', $url, 'T', true, 300, 'R', false, false, 0, 'R T', $hide, false, false);
            $this->pdf->endTemplate();
            $this->pdf->printTemplate($template_id, $x, $y);

            return array($im_w, $im_h, $img);
        }

        return false;

    }

    // danger function. can return not correct result, because html is very different
    public function getCountLinesFromHtml($html){
        $html = trim($html);
        if (!$html) {
            return 0;
        }
        $dom = new DOMDocument;
        $dom->loadHTML($html);
        $all_elements = $dom->getElementsByTagName('*');
        $all_element_tags = array();
        foreach ($all_elements as $element) {
            if (array_key_exists($element->tagName, $all_element_tags)) {
                $all_element_tags[$element->tagName] += 1;
            } else {
                $all_element_tags[$element->tagName] = 1;
            }
        }
        // which tags create new lines
        $tags = ['p', 'br', 'div', 'li', 'ol'];
        $result_count = 0;
        foreach ($tags as $tag) {
            $result_count += @$all_element_tags[$tag];
        }

        return $result_count;
    }

    public function addHeadLine($headline_text, $x, $y, $w = 0, $h = 0, $file_size = null, $with_line = true, $align = 'L', $link_to_web_block_view = '') {
        global $CFG;
        $headline_text = utf8_decode($headline_text);
        if ($file_size === null) {
            $file_size = $this->main_font_size + 2;
        }
        $this->pdf->SetFont($this->main_font_name, 'B', $file_size);
        $text_height = $this->pdf->getStringHeight($w, strip_tags($headline_text));
        $header_top_margin = 5;
        $this->pdf->MultiCell($w, $h, $headline_text, 0, $align, true, 1, $x, $y + $header_top_margin, false, 0, false, true, 0, 'T', false);
        $this->setDefaultFont();
        // add line
        if ($with_line) {
            $y_line = $y + $text_height + $header_top_margin;
            $text_height += 3;
            $style = array('width' => 0.5, 'cap' => 'round', 'join' => 'round', 'dash' => '0', 'phase' => 0, 'color' => array(200));
            $this->pdf->Line($x, $y_line, $x + $w, $y_line, $style);
            $this->pdf->SetLineStyle($style);
            $this->pdf->Circle($x, $y_line, 0.5);
            $this->pdf->Circle($x + $w, $y_line, 0.5);
        }
        // add link to the web view
        if ($link_to_web_block_view) {
            /*$this->pdf->Image($CFG->wwwroot.'/blocks/exaport/pix/link_external32.png',
                    $x + $w - 5, $y + $header_top_margin + ($text_height / 12), 0, $text_height / 2, '', $link_to_web_block_view
            );*/
            $link_icon = '<img src="'.$CFG->wwwroot.'/blocks/exaport/pix/link_external32.png" />';
            $link = '<a href="'.$link_to_web_block_view.'" style="text-decoration: none;" target="_blank">'.$link_icon.'</a>';
            $this->pdf->writeHTMLCell($text_height / 1.5, 0, $x + $w - 5, $y + $header_top_margin + ($text_height / 12), $link);
        }

        $text_height += $header_top_margin;
        return $text_height;
    }

    public function addLinkToBlock($link, $x, $y){
        $link_height = $this->pdf->getStringHeight(100, 'link');
        $link = '<a href="'.$link.'" target="_blank" style="text-decoration: none;">link</a>';
        $this->pdf->writeHTMLCell(0, 0, $x, $y, $link);
        // $link_height = 15;
        return $link_height;
    }

    public function addSubHeadLine($headline_text, $x, $y, $w = 0, $h = 0){
        $this->pdf->SetFont($this->main_font_name, 'B', $this->main_font_size);
        $text_height = $this->pdf->getStringHeight($w, strip_tags($headline_text));
        $this->pdf->MultiCell($w, $h, $headline_text, 0, 'L', true, 1, $x, $y, false, 0, false, true, 0, 'T', false);
        $this->setDefaultFont();
        return $text_height;
    }

    public function setDefaultFont(){
        $this->pdf->SetFont($this->main_font_name, '', $this->main_font_size);
        $this->pdf->SetTextColor(30, 30, 30);
    }

    public function convertHtmlToPdfHtml($html){
        // if (strpos($html, 'FOTOLADENFABRIK') !== false) {
        // echo '<textarea>';
        // echo $html;
        // echo '</textarea>';
        // }

        $text = format_text($html, FORMAT_HTML);
        $text = trim($text);
        // $text = utf8_decode($text);
        $text = mb_convert_encoding($text, 'HTML-ENTITIES', 'UTF-8');
        $text = preg_replace("/(\s){2,}/", " ", $text); // many spaces to single
        $text = preg_replace("/> </", "><", $text); // spaces between tags - important for pdf

        // div to span - because div will be used for additional linebreak
        // $text = preg_replace("/<(\/?)div\b((?:[^>\"']|\"[^\"]*\"|'[^']*')*)>/", "<$1span$2>", $text); // full changed
        $text = preg_replace("/<div\b((?:[^>\"']|\"[^\"]*\"|'[^']*')*)>/", "<span$1>", $text); // start tag
        $text = preg_replace("/<\/?div>/", "</span><br>", $text); // end tag - add <br>
        // $text = preg_replace("/<strong\b((?:[^>\"']|\"[^\"]*\"|'[^']*')*)>/", "<b$1>", $text); // start tag
        // $text = preg_replace("/<\/?strong>/", "</b>", $text); // end tag - add <br>
        $dom = new DOMDocument;
        // for leaving html wrappers (<html><body>) - wrong with umlauts and other...
        // $fragment = $dom->createDocumentFragment();
        // $fragment->appendXML($text);
        // $dom->appendChild($fragment)
        $dom->loadHTML($text, LIBXML_HTML_NODEFDTD);
        $all_elements = $dom->getElementsByTagName('*');
        foreach ($all_elements as $element) {
            /*                    if ($element->hasAttribute('width')) {
                                    if ($element->getAttribute('width') > $column_width) {
                                        $element->setAttribute('width', $column_width); // needed to convert in mm
                                    }
                                }*/
            $element->removeAttribute('height');
            $element->removeAttribute('width');
            $element->removeAttribute('style');
            $element->removeAttribute('class');
        }
        // remove empty tags
        // $xpath = new DOMXPath($dom);
        // foreach( $xpath->query('//*[not(node())]') as $node) {
            // $node->parentNode->removeChild($node);
        // }

        $text = $dom->saveHTML();

        // remove html wrappers
        $trim_off_front = strpos($text,'<body>') + 6;
        $trim_off_end = (strrpos($text,'</body>')) - strlen($text);
        $text = substr($text, $trim_off_front, $trim_off_end);
        $text = preg_replace("/(\r?\n){1,}/", "", $text); // delete linebreaks
        $text = trim($text);
        // if full text is wrapped with some tag - remove this wrapping:
        $wrapped = true;
        do {
            preg_match('/^<(\w+)(.*?\>)(.*)(\<\/\w+\>)$/i', $text, $matches);
            if ($matches) {
                if ('</'.$matches[1].'>' == $matches[4] && !in_array($matches[1], ['b', 'strong', 'i'])) {
                    $text = $matches[3];
                } else {
                    $wrapped = false;
                }
            } else {
                $wrapped = false;
            }
        } while ($wrapped);
        // br to linebreaks and than trim - so we will delete last br's
        $text = str_ireplace(array("<br />", "<br>", "<br/>"), "\r\n", $text);
        $text = trim($text);
        // sometimes in the end of the text we have non-closed tags - remove them
        $text = $this->closeNonClosedHtmlTags($text);

        // wrap full text with single P
        // $text = '<p>'.$text.'</p>';


        // for debug
        //if (strpos($text, 'FOTOLADENFABRIK') !== false) {
             // echo '<textarea>';
             // echo $text;
             // echo '</textarea>';
        // }
        return $text;
    }

    public function closeNonClosedHtmlTags($html){
        preg_match_all('#<([a-z]+)(?: .*)?(?<![/|/ ])>#iU', $html, $result);
        $openedtags = $result[1];
        preg_match_all('#</([a-z]+)>#iU', $html, $result);

        $closedtags = $result[1];
        $len_opened = count($openedtags);

        if (count($closedtags) == $len_opened) {
            return $html; // all tags are closed!
        }
        $openedtags = array_reverse($openedtags);
        for ($i = 0; $i < $len_opened; $i++) {
            // ignore tags, which does not need to be closed
            if (in_array($openedtags[$i], ['br', 'img', 'area', 'base', 'col', 'command', 'embed', 'hr', 'input', 'keygen', 'link', 'meta', 'param', 'source', 'track', 'wbr'])) {
                continue;
            }
            if (!in_array($openedtags[$i], $closedtags)) {
                $html .= '</'.$openedtags[$i].'>';
            } else {
                unset($closedtags[array_search($openedtags[$i], $closedtags)]);
            }
        }
        return $html;
    }

    public function writeHTMLCellReturnHeight($column_width, $x, $y, $text, $align = 'J'){
        $html_height = 0;
        $current_page_id = $this->pdf->getPage();
        $y_before_html = $this->pdf->GetY();
        $this->pdf->writeHTMLCell($column_width, 0, $x, $y, $text, 0, 1, true, true, $align, true);
        $y_after_html = $this->pdf->GetY();
        $new_page_id = $this->pdf->getPage();
        $pages_koef = $new_page_id - $current_page_id;
        if ($pages_koef == 0) {
            // no page changed
            $html_height = $y_after_html - $y_before_html;
            // $this->page_added = false;
        }
        if ($html_height < 0) {

            // sometimes pdf lib does not know about changed page (why?)
            // in this case $html_height is < 0
            $html_height = $y_after_html;
            $this->page_added = true;
        }
        if ($pages_koef >= 1 || $html_height < 0) {
            // pages added
            $page_height = $this->pdf->getPageDimensions($this->first_page_for_main_report_data)['hk'] - $this->pdf->getPageDimensions($this->first_page_for_main_report_data)['bm'] - $this->pdf->getPageDimensions($this->first_page_for_main_report_data)['tm']; // from first page?
            $html_height = $page_height - $y_before_html + $y_after_html + ($page_height * ($pages_koef - 1));
            // return page before inserting - real positioning will be changed later - in 'increaseBlockY' function
            $this->pdf->setPage($current_page_id);
            $this->page_added = true;
            // $this->pdf->SetY($y_before_html, false);

            // $this->addDeveloperInfo($y_after_html, 3, $this->pdf->GetY());
            // $this->addDeveloperInfo($html_height, 50, $this->pdf->GetY());
            // $this->addDeveloperInfo($new_page_id, 100, $this->pdf->GetY());

        }
        // strange very big height: s decrease it on $this->vertical_margin_after_block
        // $html_height -= $this->vertical_margin_after_block;

        return $html_height;
    }

    public function addDefaultPage(){
        $this->pdf->AddPage($this->orientation, $this->format, true);
    }

    public function addFirstPageHeader(){

        $this->pdf->SetFont($this->main_font_name, 'B', $this->main_font_size);

        $y = $this->first_page_top_margin;
        $head_height = 0;
        $page_params = $this->pdf->getPageDimensions(1);
        $title = trim($this->getViewMetaData()->name);
        if ($title) {
            $head_height += $this->addHeadLine($title, $this->page_bottom_margin, $y, $page_params['wk'] - $page_params['lm'] - $page_params['rm'], 0, 18, false, 'R');
            $y = $this->increaseBlockY($y, $head_height);
        }
        $description = trim($this->getViewMetaData()->description);
        if ($description) {
            $description = $this->convertHtmlToPdfHtml($description);
            $head_height += $this->writeHTMLCellReturnHeight($page_params['wk'] - $page_params['lm'] - $page_params['rm'], $this->page_bottom_margin, $y, $description, 'R');
            $y = $this->increaseBlockY($y, $head_height);
        }

        $this->increaseY($y);
        $this->setDefaultFont();

    }

    public function fillViewMetaData($view){
        $this->pdf->fillMetaData($view);
    }

    public function getViewMetaData(){
        return $this->pdf->getViewMetaData();
    }

    public function getWorkingPage(){
        return $this->pdf->getWorkingPage();
    }

    public function setWorkingPage($page){
        $this->pdf->setWorkingPage($page);
    }

    public function addDeveloperInfo($text, $x = null, $y = null){
        // get current position
        $current_y = $this->pdf->GetY();
        $current_x = $this->pdf->GetX();
        // developer text style
        $this->pdf->SetTextColor(255, 0, 0);
        if ($x !== null) {
            $this->pdf->SetX($x);
        }
        if ($y !== null) {
            $this->pdf->SetY($y, false);
        }
        $this->pdf->Cell(200, 0, $text);
        // return font to default
        $this->setDefaultFont();
        // return to before position
        $this->pdf->SetX($current_x);
        $this->pdf->SetY($current_y, false);
    }

?>



