Exemplo n.º 1
0
 /**
  * Action - report
  * display table data in a report in HTML or PDF format
  * 
  * Access to the action is possible in the following paths:
  * - /admin/user/report
  *
  * @return void
  */
 public function reportAction()
 {
     try {
         $params = $this->getRequest()->getParams();
         // Тип отчета
         $report_type = $params['type'];
         // Таблица для отчета
         $table = $params['table'];
         // Получим данные по отчету
         $reportData = $this->_getReportData($table);
         // Получим данные для отчета
         switch ($report_type) {
             case 'html':
                 $templater = Default_Plugin_SysBox::createViewSmarty();
                 // Отображается в режиме отчета
                 $templater->report = TRUE;
                 //------ Установим параметры и переменные HTML ------
                 // ---- Титл -----
                 $templater->title_name = $reportData['html']['title_report'];
                 $templater->title_logo = $reportData['html']['logo_report'];
                 // ---- Заголовок -----
                 $templater->column_model = $reportData['html']['column_model'];
                 $templater->is_group_head = isset($reportData['html']['is_group_head']) ? $reportData['html']['is_group_head'] : 0;
                 // ---- Нижний колонтитул -----
                 $templater->rows_footer = $reportData['html']['rows_footer'];
                 $templater->footer_colspan = $reportData['html']['footer_colspan'];
                 // ---- Тело таблицы -----
                 $templater->rows_body = $reportData['html']['rows_body'];
                 $templater->is_row_header = isset($reportData['html']['is_row_header']) ? $reportData['html']['is_row_header'] : 0;
                 // Получим результат шаблона
                 $html = $templater->render('reports/report-table.tpl');
                 $this->sendJson(array('result' => $this->Translate('Создан отчет в формате HTML'), 'html' => $html));
                 break;
             case 'pdf':
                 // Проверим наличие файла mpdf.php
                 // Если нет, то выдадим ошибку!
                 $path = APPLICATION_BASE . '/library/mPDF/mpdf.php';
                 if (!is_file($path)) {
                     throw new Exception($this->Translate('Не установлена библиотека mPDF', '/library/mPDF', 'http://www.mpdf1.com/mpdf/index.php?page=Download'));
                 }
                 // Создадим обьект шаблона
                 if ($this->_isAjaxRequest) {
                     $templater = Default_Plugin_SysBox::createViewSmarty();
                 } else {
                     $templater = $this->view;
                 }
                 //------ Установим параметры и переменные HTML ------
                 // ---- Титл -----
                 $templater->title_name = $reportData['html']['title_report'];
                 $templater->title_logo = $reportData['html']['logo_report'];
                 // ---- Заголовок -----
                 $templater->column_model = $reportData['html']['column_model'];
                 $templater->is_group_head = isset($reportData['html']['is_group_head']) ? $reportData['html']['is_group_head'] : 0;
                 // ---- Нижний колонтитул -----
                 $templater->rows_footer = $reportData['html']['rows_footer'];
                 $templater->footer_colspan = $reportData['html']['footer_colspan'];
                 // ---- Тело таблицы -----
                 $templater->rows_body = $reportData['html']['rows_body'];
                 $templater->is_row_header = isset($reportData['pdf']['is_row_header']) ? $reportData['pdf']['is_row_header'] : 0;
                 // Получим результат шаблона
                 $html = $templater->render('reports/table.tpl');
                 // Установим имя отчета PDF
                 // в названии файла будет присутствовать хеш полученного HTML
                 // это нужно для того, чтобы не создавать существующих файлов
                 $md5Html = md5($html);
                 $report = $table . '_' . $md5Html;
                 // Установим параметры для отчета PDF
                 $pdfParams['pdfReport'] = $report;
                 $pdfParams['html'] = $html;
                 $pdfParams['isCommonFont'] = FALSE;
                 $pdfParams['pathStylesheet'] = 'css/report/blue-style.css';
                 //phpinfo blue-style
                 $pdfParams['headerLeftMargin'] = $reportData['pdf']['title_report'];
                 $pdfParams['headerCentreMargin'] = $reportData['pdf']['logo_report'];
                 $pdfParams['pageFormat'] = $reportData['pdf']['pageFormat'];
                 ob_start();
                 // Получим имя файла и проверим его наличие
                 $filename = Default_Plugin_SysBox::getPath_For_FilePDF($report);
                 if (file_exists($filename)) {
                     // Файл уже существует
                     sleep(1);
                     // Получить URL PDF файла
                     $urlFilePDF = Default_Plugin_SysBox::getFullUrl_For_FilePDF($report);
                     $this->sendJson(array('result' => $this->Translate('Этот отчет уже существует'), 'url_file_pdf' => $urlFilePDF));
                 } else {
                     // Создадим отчет...
                     // Удалим ранее созданные отчеты
                     // Получим директорию с файлами отчетов
                     $patch_dir = Default_Plugin_SysBox::getPath_For_FilePDF('');
                     // Получим обьект построения дерева файлов
                     $ft = new Default_Plugin_FileTree($patch_dir);
                     // создадим дерево файлов
                     $report_del = $table . '_*.pdf';
                     $ft->readTree(array('name' => $report_del));
                     // удалим файлы и директории
                     $result = $ft->delFiles();
                     // Создать PDF файл из HTML
                     $urlFilePDF = Default_Plugin_SysBox::mpdfGenerator_Html2PDF($pdfParams);
                     $this->sendJson(array('result' => $this->Translate('Создан отчет в формате PDF'), 'url_file_pdf' => $urlFilePDF));
                 }
                 break;
             case 'exel':
                 break;
             default:
                 break;
         }
     } catch (Exception $exc) {
         $jsons = array('class_message' => 'warning', 'messages' => array('<em>' . $this->Translate('Ошибка формирования отчета') . '</em>', Default_Plugin_SysBox::getMessageError($exc)));
         $this->sendJson($jsons);
     }
 }
Exemplo n.º 2
0
 static function mpdfGenerator_Html2PDF($params = array())
 {
     $translate = Zend_Registry::get('Zend_Translate');
     //-----------------------------
     if (!$params['pdfReport'] || !$params['html']) {
         throw new Exception($translate->_('ERR_CREATE_PDF_REPORT'));
     }
     $mode = '';
     // Получим URLLogoReport
     $config = Zend_Registry::get('config');
     $urlLogoReport = $config['user']['main']['logo_report'];
     $urlLogoReport = self::getFullURL_Res($urlLogoReport);
     //------------------------------------------------------
     // Установим значения по умолчанию
     $defaults = array('pdfReport' => '', 'html' => '', 'isCommonFont' => FALSE, 'pathStylesheet' => 'css/report/mpdf-style.css', 'isHeaders' => TRUE, 'isFooters' => TRUE, 'mirrorMargins' => TRUE, 'headerLeftMargin' => '', 'headerCentreMargin' => $urlLogoReport, 'headerRightMargin' => '{PAGENO}/{nbpg}', 'footerLeftMargin' => '{DATE Y-m-j}', 'footerCentreMargin' => '', 'footerRightMargin' => '', 'pageFormat' => 'A4');
     // Обьединим два массива
     $params = array_merge($defaults, $params);
     if (!$params['footerRightMargin']) {
         $params['footerRightMargin'] = self::getFullUrl_For_FilePDF($params['pdfReport']);
     }
     // Установим значения переменных из массива
     //        extract($params, EXTR_OVERWRITE);
     try {
         // Изменим параметры PHP
         self::iniSetConfig_PHP(array("memory_limit" => "500M", "max_execution_time" => "300"));
         //            require_once("mpdf_source.php");
         require_once "mpdf.php";
         if ($params['isCommonFont']) {
             $mode = 'c';
         }
         $isHeaders = (bool) $params['isHeaders'];
         $isFooters = (bool) $params['isFooters'];
         if ($isHeaders || $isFooters) {
             $mpdf = new mPDF($mode, $params['pageFormat'], '', '', 15, 15, 32, 20, 10, 10);
         } else {
             $mpdf = new mPDF($mode, $params['pageFormat']);
         }
         // Установим параметры для оптимизации (уменьшим время испольнения и используемую память)
         $mpdf->useOnlyCoreFonts = true;
         $mpdf->useSubstitutions = false;
         $mpdf->simpleTables = true;
         // Уменьшает время выполнения
         $mpdf->packTableData = true;
         // Уменьшает используемую память
         $mpdf->use_kwt = true;
         //Keep-with-table  Оставить заголовок таблицы вместе с маблицей на одной странице
         //            $mpdf->shrink_tables_to_fit=0;
         //            $mpdf->hyphenate = true;
         //            $mpdf->SHYlang = 'ru';
         //            $mpdf->SHYleftmin = 3;
         // Определим заголовок страницы
         $header = " \n            <table width=\"100%\" style=\"border-bottom: 1px solid #000000; vertical-align: bottom;  font-weight: bold; font-size: 14pt; color: #000088;\"><tr>\n            <td width=\"33%\"><span style=\"\">{$params['headerLeftMargin']}</span></td>\n            <td width=\"33%\" align=\"center\"><img src=\"{$params['headerCentreMargin']}\" /></td>\n            <td width=\"33%\" style=\"text-align: right;\"><span style=\"\">{$params['headerRightMargin']}</span></td>\n            </tr></table>\n            ";
         // Определим подвал страницы
         $footer = "\n            <table width=\"100%\" style=\"vertical-align: bottom;  font-size: 14pt; color: #000088; font-weight: bold; font-style: italic;\"><tr>\n            <td width=\"33%\"><span style=\"\">{$params['footerLeftMargin']}</span></td>\n            <td width=\"33%\" align=\"center\" style=\"\">{$params['footerCentreMargin']}</td>\n            <td width=\"33%\" style=\"text-align: right; \">{$params['footerRightMargin']}</td>\n            </tr></table>\n            ";
         if ($mirrorMargins) {
             $headerE = "\n                <table width=\"100%\" style=\"border-bottom: 1px solid #000000; vertical-align: bottom;  font-weight: bold; font-size: 14pt; color: #000088;\"><tr>\n                <td width=\"33%\"><span style=\"\"><span style=\"\">{$params['headerRightMargin']}</span></span></td>\n                <td width=\"33%\" align=\"center\"><img src=\"{$params['headerCentreMargin']}\" /></td>\n                <td width=\"33%\" style=\"text-align: right;\"><span style=\"\">{$params['headerLeftMargin']}</span></td>\n                </tr></table>\n                ";
             $footerE = "\n                <table width=\"100%\" style=\"vertical-align: bottom;  font-size: 14pt; color: #000088; font-weight: bold; font-style: italic;\"><tr>\n                <td width=\"33%\"><span style=\"\">{$params['footerRightMargin']}</span></td>\n                <td width=\"33%\" align=\"center\" style=\"\">{$params['footerCentreMargin']}</td>\n                <td width=\"33%\" style=\"text-align: right; \">{$params['footerLeftMargin']}</td>\n                </tr></table>\n                ";
             if ($isHeaders) {
                 $mpdf->mirrorMargins = TRUE;
                 // Use different Odd/Even headers and footers and mirror margins
                 $mpdf->SetHTMLHeader($headerE, 'E');
             }
             if ($isFooters) {
                 $mpdf->mirrorMargins = TRUE;
                 // Use different Odd/Even headers and footers and mirror margins
                 $mpdf->SetHTMLFooter($footerE, 'E');
             }
         }
         if ($isHeaders) {
             $mpdf->SetHTMLHeader($header);
         }
         if ($isFooters) {
             $mpdf->SetHTMLFooter($footer);
         }
         $html = $params['html'];
         //$html = '';
         //$params['pathStylesheet'] = '';
         if ($params['pathStylesheet']) {
             $stylesheet = file_get_contents($params['pathStylesheet']);
             $mpdf->WriteHTML($stylesheet, 1);
             $mpdf->WriteHTML($html, 2);
         } else {
             $mpdf->WriteHTML($html);
         }
         // Получим директорию сохранения файлов
         $dirFilePDF = self::getPath_For_FilePDF($params['pdfReport']);
         // Сохраним файл на серверном ресурсе пользователя
         $mpdf->Output($dirFilePDF, 'F');
     } catch (Exception $exc) {
         throw new Exception($exc->getMessage());
     }
     // Возвратим URL путь, полученного файла PDF
     return Default_Plugin_SysBox::getFullUrl_For_FilePDF($params['pdfReport']);
 }
Exemplo n.º 3
0
 /**
  * Action - pdf
  * сreate a PDF document using the mPDF library
  *
  * Access to the action is possible in the following paths:
  * - /admin/tools/pdf
  *
  * @return void
  */
 public function pdfAction()
 {
     $isCommonFont = false;
     $pdfParams = array();
     //---------------------
     // Получим параметры
     $params = $this->getRequest()->getParams();
     $report = $params['name'];
     // Определим параметры для конвертации HTML в PDF
     switch ($report) {
         case 'phpinfo':
             // Установим параметры для отчета
             $html = Default_Plugin_SysBox::getPHPInfo();
             $pdfParams['pdfReport'] = $report;
             $pdfParams['html'] = $html;
             $pdfParams['isCommonFont'] = true;
             $pdfParams['pathStylesheet'] = 'css/report/phpinfo.css';
             $pdfParams['headerLeftMargin'] = 'Params of PHP';
             $pdfParams['headerCentreMargin'] = Default_Plugin_SysBox::getFullURL_Res('/images/system/settings32x32.png');
             $pdfParams['footerRightMargin'] = Default_Plugin_SysBox::getFullUrl_For_FilePDF($report);
             break;
         case 'zend-progress':
             $adapter = new Zend_ProgressBar_Adapter_JsPush(array('updateMethodName' => 'BSA.Dialogs.Zend_ProgressBar_Update', 'finishMethodName' => 'BSA.Dialogs.Zend_ProgressBar_Finish'));
             $progressBar = new Zend_ProgressBar($adapter, 0, 100);
             for ($i = 1; $i <= 100; $i++) {
                 if ($i < 20) {
                     $text = 'Just beginning';
                 } else {
                     if ($i < 50) {
                         $text = 'A bit done';
                     } else {
                         if ($i < 80) {
                             $text = 'Getting closer';
                         } else {
                             $text = 'Nearly done';
                         }
                     }
                 }
                 $progressBar->update($i, $text);
                 usleep(100000);
             }
             $progressBar->finish();
             die;
             break;
         default:
             break;
     }
     // Создать PDF файл из HTML
     $urlFilePDF = Default_Plugin_SysBox::mpdfGenerator_Html2PDF($pdfParams);
     // Установим свой и предыдущий Breadcrumbs
     $Zend_Auth = Zend_Registry::get("Zend_Auth");
     $lastBreadcrumbs = $Zend_Auth->lastBreadcrumbs;
     $this->_breadcrumbs->addStep($lastBreadcrumbs['title'], $this->getUrl($lastBreadcrumbs['action'], $lastBreadcrumbs['controller'], $lastBreadcrumbs['module']));
     $this->_breadcrumbs->addStep($this->Translate('Отчет в PDF формате'));
     $this->view->urlFilePDF = $urlFilePDF;
 }