예제 #1
7
 public function test()
 {
     // Include the PHPWord.php, all other classes were loaded by an autoloader
     require_once APPPATH . '/libraries/PHPWord.php';
     //$this->load->library('PHPWord');
     // Create a new PHPWord Object
     $PHPWord = new PHPWord();
     //$PHPWord = $this->phpword;
     // Every element you want to append to the word document is placed in a section. So you need a section:
     $section = $PHPWord->createSection();
     // After creating a section, you can append elements:
     $section->addText('Hello world!');
     // You can directly style your text by giving the addText function an array:
     $section->addText('Hello world! I am formatted.', array('name' => 'Tahoma', 'size' => 16, 'bold' => true));
     // If you often need the same style again you can create a user defined style to the word document
     // and give the addText function the name of the style:
     $PHPWord->addFontStyle('myOwnStyle', array('name' => 'Verdana', 'size' => 14, 'color' => '1B2232'));
     $section->addText('Hello world! I am formatted by a user defined style', 'myOwnStyle');
     // You can also putthe appended element to local object an call functions like this:
     $myTextElement = $section->addText('Hello World!');
     //$myTextElement->setBold();
     //$myTextElement->setName('Verdana');
     //$myTextElement->setSize(22);
     $styleTable = array('borderColor' => '006699', 'borderSize' => 6, 'cellMargin' => 50);
     $styleFirstRow = array('bgColor' => '66BBFF');
     $PHPWord->addTableStyle('myTable', $styleTable, $styleFirstRow);
     $table = $section->addTable('myTable');
     $table->addRow();
     $cell = $table->addCell(2000);
     $cell->addText('Cell 1');
     $cell = $table->addCell(2000);
     $cell->addText('Cell 2');
     //	$cell = $table->addCell(2000);
     //$cell->addText('Cell 3');
     // Add image elements
     $section->addImage(APPPATH . '/images/side/jqxs-l.JPG');
     $section->addTextBreak(1);
     //$section->addImage(APPPATH.'/images/side/jqxs-l.JPG', array('width'=>210, 'height'=>210, 'align'=>'center'));
     //$section->addTextBreak(1);
     //$section->addImage(APPPATH.'/images/side/jqxs-l.jpg', array('width'=>100, 'height'=>100, 'align'=>'right'));
     // At least write the document to webspace:
     $objWriter = PHPWord_IOFactory::createWriter($PHPWord, 'Word2007');
     $objWriter->save('helloWorld.docx');
     exit;
     //download
     /* 		
     $filename='just_some_random_name.docx'; //save our document as this file name
     header('Content-Type: application/vnd.openxmlformats-officedocument.wordprocessingml.document'); //mime type
     header('Content-Disposition: attachment;filename="'.$filename.'"'); //tell browser what's the file name
     header('Cache-Control: max-age=0'); //no cache
      
     $objWriter = PHPWord_IOFactory::createWriter($PHPWord, 'Word2007');
     $objWriter->save('php://output');
     */
     //force download
     // 		$this->load->helper('download');
     // 		$data = file_get_contents("helloWorld.docx"); // Read the file's contents
     // 		$name = 'helloWorld.docx';
     // 		force_download($name, $data);
 }
예제 #2
1
 public function generate($xml_file)
 {
     if (!file_exists($xml_file)) {
         throw new Exception("XML-file '{$xml_file}' NOT exosts.");
     }
     $xml = new SimpleXMLElement(file_get_contents($xml_file));
     // Create a new PHPWord Object
     $objPHPWord = new PHPWord();
     // Every element you want to append to the word document is placed in a section. So you need a section:
     $section = $objPHPWord->createSection();
     foreach ($xml->body->p as $p) {
         $section->addText((string) $p);
         dbg::write((string) $p);
     }
     header('Content-Type: application/vnd.ms-word');
     header('Content-Disposition: attachment;filename="' . (string) $xml->body['title'] . '.doc"');
     header('Cache-Control: max-age=0');
     $objWriter = PHPWord_IOFactory::createWriter($objPHPWord, 'Word2007');
     $objWriter->save('php://output');
     exit;
 }
예제 #3
1
 public function generateResume($id = NULL)
 {
     //Проверяем, зарегестрированн ли пользователь и его роль
     if (isset($this->session->userdata['id'])) {
         $user = Doctrine::getTable('User')->findOneBy('id', $this->session->userdata['id']);
         if ($user->getRole() == 'applicant') {
             echo json_encode(array('status' => false, 'msg' => 'Скачивать резюме могут только работодатели и агентства!'));
             exit;
         }
     } else {
         echo json_encode(array('status' => false, 'msg' => 'Скачивать резюме могут только зарегестрированные пользователи!'));
         exit;
     }
     if (empty($id)) {
         echo json_encode(array('status' => false));
         exit;
     }
     $resume = Doctrine::getTable('Resume')->findOneBy('id', $id);
     if (empty($resume)) {
         echo json_encode(array('status' => false));
         exit;
     }
     //Папка для хранения файлов
     $path = str_replace('system/', '', BASEPATH) . 'downloads/resumes/';
     //Создаем ее, если она была созданна ранее
     if (!file_exists($path)) {
         mkdir($path, 0, true);
     }
     //Имя файла с резюме
     $file_name = 'resume_' . $id . '.docx';
     //Если такой файл уже есть, то проверяем дату его создания
     if (file_exists($path . $file_name)) {
         if ($resume->modification_date != NULL and $resume->modification_date >= date('Y-m-d H:i:s', filectime($path . $file_name))) {
             echo json_encode(array('status' => true, 'url' => site_url() . 'downloads/resumes/' . $file_name));
             exit;
         } else {
             unlink($path . $file_name);
         }
     }
     $this->load->library('PHPWord');
     $word = new PHPWord();
     $section = $word->createSection();
     $section->addText('Резюме от: ' . date('Y.m.d', $resume->getPlacementDate()), array('name' => 'Verdana', 'color' => '006699'));
     $section->addText($resume->formatName('s n p'), array('name' => 'Verdana', 'bold' => true, 'size' => 20));
     $section->addImage($resume->getRealImagePath(), array('align' => 'left'));
     $section->addTextBreak();
     $bold = array('bold' => true);
     $grey = array('bgColor' => 'dcdcdc', 'valign' => 'center');
     $center = array('valign' => 'center');
     $styleTable = array('borderSize' => 4, 'borderColor' => 'dcdcdc');
     $word->addTableStyle('myOwnTableStyle', $styleTable);
     $table = $section->addTable('myOwnTableStyle');
     $data = array('Возраст:' => $resume->getResumeAuthorAge(), 'Пол:' => $resume->gender->getDescription(), 'Семейное положение:' => $resume->family_state->getValue(), 'Наличие детей:' => $resume->getChilds(), 'Город проживания:' => $resume->getCity(), 'Район проживания:' => $resume->getArea(), 'Национальность:' => $resume->getNationality(), 'E-mail:' => $resume->getContactEmail(), 'Контактный телефон:' => $resume->getContactPhone());
     foreach ($data as $key => $value) {
         $table->addRow();
         $table->addCell(3000, $grey)->addText($key, $bold, array('spaceAfter' => 0));
         $table->addCell(6000, $center)->addText($value, array(), array('spaceAfter' => 0));
     }
     $section->addTextBreak();
     //Желаемая должность
     $section->addText(trim($resume->getDesiredPosition()) == '' ? 'Точная информация о интересующей должности не указанна' : $resume->getDesiredPosition(), array('name' => 'Verdana', 'bold' => true, 'size' => 16));
     //Дополнительно рассматриваемые должности
     if (count($resume->getPositions()) > 0) {
         $section->addText('Также рассматриваются:', array('name' => 'Verdana', 'bold' => true, 'size' => 12));
         foreach ($resume->getPositions() as $position_id) {
             $position = Doctrine::getTable('Position')->findOneBy('id', $position_id);
             $section->addText($position->getName());
         }
     }
     $table = $section->addTable('myOwnTableStyle');
     $table->addRow();
     $table->addCell(3000, $grey)->addText("Квалификация:", $bold);
     $cell = $table->addCell('3000', $center);
     foreach ($resume->getQualificationForWord() as $item) {
         $cell->addText($item);
     }
     $data = array('Описание опыта работы:' => $resume->getExperienceDescription(), 'Период опыта работы:' => $resume->experience->getValue(), 'Наличие рекомендаций:' => $resume->getGuidanceAvailability());
     foreach ($data as $key => $value) {
         $table->addRow();
         $table->addCell(3000, $grey)->addText($key, $bold, array('spaceAfter' => 0));
         $table->addCell(6000, $center)->addText($value, array(), array('spaceAfter' => 0));
     }
     $section->addTextBreak();
     $section->addText('Образование', array('name' => 'Verdana', 'color' => '006699', 'bold' => true, 'size' => 16));
     $table = $section->addTable('myOwnTableStyle');
     $table->addRow();
     $table->addCell(3000, $grey)->addText("Образование:", $bold, array('spaceAfter' => 0));
     $table->addCell(6000, $center)->addText($resume->education->getValue(), array(), array('spaceAfter' => 0));
     $table->addRow();
     $table->addCell(3000, $grey)->addText("Специальность:", $bold, array('spaceAfter' => 0));
     $table->addCell(6000, $center)->addText($resume->getSpeciality(), array(), array('spaceAfter' => 0));
     $section->addTextBreak();
     $section->addText('Пожелания к работе', array('name' => 'Verdana', 'color' => '006699', 'bold' => true, 'size' => 16));
     $table = $section->addTable('myOwnTableStyle');
     $data = array('Регион работы:' => $resume->getWorkRegion()->getValue(), 'Работа с проживанием в семье:' => (int) $resume->getHomestay() == 1 ? 'Да' : 'Нет', 'Вид занятости:' => $resume->getOperatingSchedulesText(), 'График работы:' => $resume->getWorkTimetable(), 'Заработная плата:' => $resume->getPaymentDetails());
     foreach ($data as $key => $value) {
         $table->addRow();
         $table->addCell(3000, $grey)->addText($key, $bold, array('spaceAfter' => 0));
         $table->addCell(6000, $center)->addText($value, array(), array('spaceAfter' => 0));
     }
     $section->addTextBreak();
     $section->addText('Предоставляемые услуги', array('name' => 'Verdana', 'color' => '006699', 'bold' => true, 'size' => 16));
     foreach ($resume->getResposibilitysArrayForWord() as $item) {
         $section->addListItem($item, 0, 'fNormal', array('listType' => 7), 'pNormal');
     }
     $section->addText('Дополнительные данные', array('name' => 'Verdana', 'color' => '006699', 'bold' => true, 'size' => 16));
     $table = $section->addTable('myOwnTableStyle');
     $table->addRow();
     $table->addCell(3000, $grey)->addText("Владение языками:", $bold, array('spaceAfter' => 0));
     $cell = $table->addCell('3000', $center, array('spaceAfter' => 0));
     foreach ($resume->getLanguageSkillsArrayForWord() as $item) {
         $cell->addText($item);
     }
     $data = array('Наличие загранпаспорта:' => (int) $resume->getForeignPassport() == 0 ? 'Нет' : 'Есть', 'Вероисповедание:' => $resume->getFaith(), 'Водительские права:' => $resume->getDriverLicence(), 'Наличие собственного авто:' => $resume->getOwnCar(), 'Наличие медкниги:' => (int) $resume->getMedicalBook() == 0 ? 'Нет' : 'Есть', 'Отношение к животным:' => $resume->getAnimalsAttitude(), 'Вредные привычки:' => $resume->getBadHabits());
     foreach ($data as $key => $value) {
         $table->addRow();
         $table->addCell(3000, $grey)->addText($key, $bold, array('spaceAfter' => 0));
         $table->addCell(6000, $center)->addText($value, array(), array('spaceAfter' => 0));
     }
     $objWriter = PHPWord_IOFactory::createWriter($word, 'Word2007');
     $objWriter->save($path . $file_name);
     echo json_encode(array('status' => true, 'url' => site_url() . 'downloads/resumes/' . $file_name));
 }
예제 #4
0
파일: HtmlToDocx.php 프로젝트: tmlsoft/main
 public function save($html, $dir)
 {
     import("@.ORG.htmltodocx.documentation.support_functions");
     $phpword_object = new PHPWord();
     $section = $phpword_object->createSection();
     // HTML Dom object:
     $html_dom = new simple_html_dom();
     $html_dom->load('<html><body>' . $html . '</body></html>');
     // Note, we needed to nest the html in a couple of dummy elements.
     // Create the dom array of elements which we are going to work on:
     $html_dom_array = $html_dom->find('html', 0)->children();
     // We need this for setting base_root and base_path in the initial_state array
     // (below). We are using a function here (derived from Drupal) to create these
     // paths automatically - you may want to do something different in your
     // implementation. This function is in the included file
     // documentation/support_functions.inc.
     $paths = htmltodocx_paths();
     // Provide some initial settings:
     $initial_state = array('phpword_object' => &$phpword_object, 'base_root' => $paths['base_root'], 'base_path' => $paths['base_path'], 'current_style' => array('size' => '11'), 'parents' => array(0 => 'body'), 'list_depth' => 0, 'context' => 'section', 'pseudo_list' => TRUE, 'pseudo_list_indicator_font_name' => 'Wingdings', 'pseudo_list_indicator_font_size' => '7', 'pseudo_list_indicator_character' => 'l ', 'table_allowed' => TRUE, 'treat_div_as_paragraph' => TRUE, 'style_sheet' => htmltodocx_styles_example());
     // Convert the HTML and put it into the PHPWord object
     htmltodocx_insert_html($section, $html_dom_array[0]->nodes, $initial_state);
     // Clear the HTML dom object:
     $html_dom->clear();
     unset($html_dom);
     // Save File
     $str = explode(".", $h2d_file_uri);
     $h2d_file_uri = $dir . "wordtemp/" . time() . ".docx";
     if (!file_exists($dir . "wordtemp/")) {
         $this->createFolders($dir . "wordtemp/");
         //判断目标文件夹是否存在
     }
     $objWriter = PHPWord_IOFactory::createWriter($phpword_object, 'Word2007');
     $objWriter->save($h2d_file_uri);
     return $h2d_file_uri;
 }
예제 #5
0
function generate_docx($html, $file_path, &$file_takeout_tmp_files)
{
    $phpword_object = new PHPWord();
    $section = $phpword_object->createSection();
    $html_dom = new simple_html_dom();
    $html_dom->load($html);
    $html_dom_array = $html_dom->find('html', 0)->children();
    $paths = htmltodocx_paths();
    $initial_state = array('phpword_object' => &$phpword_object, 'base_root' => $paths['base_root'], 'base_path' => $paths['base_path'], 'current_style' => array('size' => '11'), 'parents' => array(0 => 'body'), 'list_depth' => 0, 'context' => 'section', 'pseudo_list' => TRUE, 'pseudo_list_indicator_font_name' => 'Wingdings', 'pseudo_list_indicator_font_size' => '7', 'pseudo_list_indicator_character' => 'l ', 'table_allowed' => TRUE, 'treat_div_as_paragraph' => FALSE, 'style_sheet' => htmltodocx_styles(), 'download_img_path' => elgg_get_data_path(), 'download_img_tmp' => &$file_takeout_tmp_files);
    htmltodocx_insert_html($section, $html_dom_array[0]->nodes, $initial_state);
    $html_dom->clear();
    unset($html_dom);
    $objWriter = PHPWord_IOFactory::createWriter($phpword_object, 'Word2007');
    // Word2007 is the only option :-(
    $objWriter->save($file_path);
}
예제 #6
0
 function display()
 {
     //declare variables
     global $db;
     $fileName = "TestTour.docx";
     $PHPWord = new PHPWord();
     $section = $PHPWord->createSection(array("marginTop" => "0", "marginLeft" => "0"));
     /*  $tour = new Tour();
         $record = isset($_GET["record"]) ? htmlspecialchars($_GET["record"]) : '';
         $sql = " SELECT t.id,t.name,t.tour_code,t.picture,
                                 t.duration,t.transport2, t.operator,t.description,
                                 t.deleted,t.tour_code,t.from_place,t.to_place,
                                 t.start_date,t.end_date,t.division,contract_value,currency_id,
                                 currency,u.first_name,u.last_name
                             FROM tours t
                             INNER JOIN users u
                             ON t.assigned_user_id = u.id
                             WHERE t.id = '" . $record . "' AND t.deleted = 0 AND u.deleted = 0 ";
         $result = $db->query($sql);
         $row = $db->fetchByAssoc($result);*/
     //create word ile
     //  $section->addImage('C:\xampp\htdocs\carnival\modules\Tours\views\carnival_header.jpg', array("align" => "center"));
     //$section->addText("haha");
     $section->addImage('modules\\Tours\\views\\carnival_header.jpg', array("width" => 793, "height" => 125, "align" => "center"));
     //save file
     $objWriter = PHPWord_IOFactory::createWriter($PHPWord, "Word2007");
     $objWriter->save($fileName);
     //return word file
     if (!$fileName) {
         die("file not found");
     }
     ob_end_clean();
     header("Cache-Control: public");
     header("Content-Description: File Transfer");
     header("Content-Disposition: attachment; filename={$fileName}");
     header("Content-Type: application/vnd.openxmlformats-officedocument.wordprocessingml.document");
     header("Content-Transfer-Encoding: binary");
     readfile($fileName);
     //unlink($fileName);
     exit;
 }
예제 #7
0
파일: Docx.php 프로젝트: fredcido/simuweb
 /**
  * 
  */
 protected function _initDoc()
 {
     $this->_word = new PHPWord();
     $sectionStyle = array('orientation' => $this->_orientation, 'marginLeft' => 900, 'marginRight' => 900, 'marginTop' => 900, 'marginBottom' => 900);
     $this->_mainSection = $this->_word->createSection($sectionStyle);
 }
예제 #8
0
<?php

require_once '../PHPWord.php';
// New Word Document
$PHPWord = new PHPWord();
// New portrait section
$section = $PHPWord->createSection(array('borderColor' => '00FF00', 'borderSize' => 12));
$section->addText('I am placed on a default section.');
// New landscape section
$section = $PHPWord->createSection(array('orientation' => 'landscape'));
$section->addText('I am placed on a landscape section. Every page starting from this section will be landscape style.');
$section->addPageBreak();
$section->addPageBreak();
// New portrait section
$section = $PHPWord->createSection(array('marginLeft' => 600, 'marginRight' => 600, 'marginTop' => 600, 'marginBottom' => 600));
$section->addText('This section uses other margins.');
// Save File
$objWriter = PHPWord_IOFactory::createWriter($PHPWord, 'Word2007');
$objWriter->save('Section.docx');
예제 #9
0
 /**
  * @Title: repStrPHPword
  * @Description: todo(模板标签文件和数据进行替换,然后到处word)
  * @param 模板标签文件地址 $docfile
  * @param 生成的最新文件目录 $causedir
  * @param 导出的数据源数组 $bookNamearr
  * @param 生成的最新文件名 $fileName
  * @param 导出的文件类型,默认为word $type
  * @author 王昭侠
  * @date 2015-6-29 下午4:54:45
  * @throws
  */
 public function repStrPHPword($docfile, $causedir, $bookNamearr, $fileName, $type = "word", $export = 'word')
 {
     set_time_limit(0);
     //验证模板标签文件是否存在
     if (!file_exists($docfile)) {
         $this->error("模板文件不存在,请检查");
     }
     //验证最新文件目录是否存在
     if (!file_exists($causedir)) {
         //不存在则生成最新文件目录
         $this->createFolders($causedir);
         //判断目标文件夹是否存在
     }
     import('@.ORG.PHPWord', '', $ext = '.php');
     $PHPWord = new PHPWord();
     $filepath = pathinfo($docfile);
     $filenameGBK = $causedir . '/' . $fileName . '.' . $filepath['extension'];
     $filenameUTF8 = iconv("UTF-8", "GBK", $filenameGBK);
     $document = $PHPWord->loadTemplate($docfile);
     $document->clearAllBiaoji();
     foreach ($bookNamearr as $k => $v) {
         if ($v["is_datatable"]) {
             $data = array();
             $data["showname"] = $v["showname"];
             $data["value"] = $v["value"];
             $data["showtype"] = $v["showtype"] !== NULL ? $v["showtype"] : 0;
             $data["showtitle"] = $v["showtitle"] !== NULL ? $v["showtitle"] : 0;
             $data["zihao"] = $v["zihao"];
             $data["hangjianju"] = $v["hangjianju"];
             $data["ziti"] = $v["ziti"];
             if (isset($v["colORrow"])) {
                 $data["colORrow"] = $v["colORrow"];
             }
             //title_none 如果等于1表示去掉hearder头部
             if (is_array($v["value"]) && !isset($v["colORrow"]) && $v['title_none'] != 1) {
                 foreach ($v["value"] as $kk => $vv) {
                     $data["titleArr"][] = empty($vv["showname"]) ? "" : $vv["showname"];
                     $data["fieldwidth"][] = $v["fieldwidth"][$vv["name"]];
                 }
             }
             $document->setValue($v["name"], $data);
         } else {
             $document->setValue($v["name"], $v);
         }
     }
     if (!empty($_SESSION["htmltodocx_img"])) {
         $content = $document->getStr();
         $document->clearTemplateTag();
         $document->save($filenameUTF8);
         // New portrait section
         $section = $PHPWord->createSection();
         // Add image elements
         foreach ($_SESSION["htmltodocx_img"] as $v => $k) {
             $section->addImage($k["src"], $k["style"]);
             $section->addTextBreak(1);
         }
         // Save File
         $objWriter = PHPWord_IOFactory::createWriter($PHPWord, 'Word2007');
         $imgurl = UPLOAD_SampleWord . 'Image.docx';
         $objWriter->save($imgurl);
         unset($_SESSION["htmltodocx_img"]);
         $documentImg = $PHPWord->loadTemplate($imgurl);
         $documentImg->setStr($content);
         $documentImg->save($filenameUTF8);
         unlink($imgurl);
     } else {
         $document->clearTemplateTag();
         $document->save($filenameUTF8);
     }
     if ($export == 'swf') {
         //生成PDF
         $HttpSoctetIOAction = A('Http');
         $filenamePDFUTF8 = $HttpSoctetIOAction->createPDF($causedir, $filenameUTF8);
         $swfurl = str_replace("pdf", "swf", $filenamePDFUTF8);
         $swfurl = preg_replace("/^([\\s\\S]+)\\/Public\\//", "", $swfurl);
         if ($type == "pdf") {
             $filenameUTF8 = $filenamePDFUTF8;
         }
     }
     //导出后,就修改版本信息
     $savewordmodel = M('mis_system_template_saveword');
     $filenameUTF8Quan = preg_replace("/^([\\s\\S]+)\\/Public\\//", "", $filenameUTF8);
     //获取参数
     $id = $_REQUEST['id'];
     $saveWordId = $_REQUEST['fileid'];
     $modelname = $this->getActionName();
     $wordMap['modelid'] = $id;
     $wordMap['modelname'] = $modelname;
     $wordMap['id'] = $saveWordId;
     if ($export == 'swf' && !$saveWordId) {
         //如果是在线查看,却又没有版本id 那么直接获取最新版本号
         $swfnewmap['modelid'] = $id;
         $swfnewmap['modelname'] = $modelname;
         $saveWordId = $wordMap['id'] = $savewordmodel->where($swfnewmap)->order("id desc")->getField("id");
     }
     $wordData['fileurl'] = $filenameUTF8Quan;
     $wordData['swfurl'] = $swfurl;
     $wordData['isexport'] = 1;
     if ($modelname == 'MisSalesMyProject') {
         $wordData['modelid'] = $id;
         $wordData['modelname'] = $modelname;
         unset($wordMap['id']);
         $wlist = $savewordmodel->where($wordMap)->select();
         if ($wlist) {
             $query = $savewordmodel->where($wordMap)->save($wordData);
         } else {
             $query = $savewordmodel->add($wordData);
         }
     } else {
         if ($wordMap['id']) {
             $query = $savewordmodel->where($wordMap)->save($wordData);
         }
     }
     $savewordmodel->commit();
     if ($export == 'word') {
         ob_end_clean();
         header("Cache-Control: public");
         header("Content-Type: application/force-download");
         header("Content-Disposition: attachment; filename=" . basename($filenameUTF8));
         readfile($filenameUTF8);
         exit;
     } elseif ($export == "swf") {
         // 			if($saveWordId){
         // 				$swfmap['id']=$saveWordId;
         // 				$templateModel = M("mis_system_template_saveword");
         // 				$rs = $templateModel->where($swfmap)->order("id desc")->find();
         // 				$file_path = "/Public/".$rs['swfurl'];//暂时修改,等保存路径正常后直接取路径
         // 			}else{
         // 				$file_path = "/Public/".$swfurl;//暂时修改,等保存路径正常后直接取路径
         // 			}
         //$file_path = preg_replace("/^([\s\S]+)\/Public/", "__PUBLIC__", $rs['swfurl']);
         // 			$this->assign("file_name", $rs['filename']);
         // 			$this->assign("file_type", 'file');
         // 			$this->assign('file_path', $file_path);
         // 			$this->display("Public:playswf");
         // 			$ip = GetHostByName($_SERVER['SERVER_NAME']);//获取本机IP
         $ip = C("DB_HOST_WORD");
         //"192.168.0.238";
         require_once "http://{$ip}:8088/JavaBridge/java/Java.inc";
         //此行必须
         $PageOfficeCtrl = new Java("com.zhuozhengsoft.pageoffice.PageOfficeCtrlPHP");
         //此行必须
         $PageOfficeCtrl->setServerPage("http://{$ip}:8088/JavaBridge/poserver.zz");
         //此行必须,设置服务器页面
         java_set_file_encoding("utf8");
         //设置中文编码,若涉及到中文必须设置中文编码
         $PageOfficeCtrl->setAllowCopy(false);
         //禁止拷贝
         //$PageOfficeCtrl->setMenubar(false);//隐藏菜单栏
         $PageOfficeCtrl->setOfficeToolbars(false);
         //隐藏Office工具条
         $PageOfficeCtrl->setCustomToolbar(false);
         //隐藏自定义工具栏
         $PageOfficeCtrl->setJsFunction_AfterDocumentOpened("AfterDocumentOpened");
         //打开excel文档
         $PageOfficeCtrl->UserAgent = $_SERVER['HTTP_USER_AGENT'];
         //若使用谷歌浏览器此行代码必须有,其他浏览器此行代码可不加
         $OpenMode = new Java("com.zhuozhengsoft.pageoffice.OpenModeType");
         $file_path = preg_replace("/^([\\s\\S]+)\\/Public/", "/Public/", $filenameUTF8);
         $PageOfficeCtrl->webOpen($file_path, $OpenMode->docReadOnly, "张三");
         //此行必须
         $this->assign('PageOfficeCtrl', $PageOfficeCtrl->getDocumentView("PageOfficeCtrl1"));
         $this->display("Public:showEditWord");
         exit;
     }
 }
예제 #10
0
 public static function makePaper($questions, $subCode, $date, $time, $session, $internal, $sec)
 {
     $sem = $questions[1][1]->subject()->first()->sem;
     $subject = $questions[1][1]->subject()->first()->name;
     // Create a new PHPWord Object
     $PHPWord = new PHPWord();
     // Every element you want to append to the word document is placed in a section. So you need a section:
     $section = $PHPWord->createSection();
     $PHPWord->addFontStyle('myNoteStyle', array('name' => 'Calibri', 'size' => 11, 'bold' => true, 'underline' => PHPWord_Style_Font::UNDERLINE_SINGLE));
     $PHPWord->addFontStyle('myOwnStyle', array('name' => 'Calibri', 'size' => 11, 'bold' => true));
     $PHPWord->addParagraphStyle('myGapTStyle', array('name' => 'Calibri', 'size' => 5, 'bold' => true));
     $PHPWord->addParagraphStyle('myGapPStyle', array('spaceAfter' => 0));
     $PHPWord->addParagraphStyle('myHeaderStyle', array('spaceAfter' => 0));
     $PHPWord->addParagraphStyle('myQuestionStyle', array('spaceAfter' => 0));
     // Header
     $table = $section->addTable();
     $table->addRow();
     $table->addCell(4200)->addText('USN: [  ][  ][  ][  ][  ][  ][  ][  ][  ][  ]', 'myOwnStyle');
     $table->addCell(8000)->addText('');
     $table->addCell(700)->addText($subCode, 'myOwnStyle');
     $center = array('spaceAfter' => 0, 'align' => 'center');
     $table_block_format = array('cellMarginTop' => -10, 'cellMarginLeft' => 30, 'valign' => 'center');
     $table_block_format2 = array('cellMarginBottom' => 0, 'cellMarginLeft' => 100, 'valign' => 'center');
     $questionTextStyle = array('bold' => false, 'size' => 10.5, 'name' => 'Calibri');
     $cellTextStyleBigBold = array('bold' => true, 'size' => 13, 'name' => 'Calibri');
     $PHPWord->addTableStyle('myTable', $table_block_format, array('align' => 'center'));
     $PHPWord->addTableStyle('myQuestionTable', $table_block_format, array('align' => 'center'));
     // $table = $section->addTable('myTable');
     // $table->addRow();
     // $table->addCell(10000)->addText('Semester '.$sem.', B.E Degree Examination, '.$date, $cellTextStyleBigBold, $center);
     // $table->addRow();
     // $table->addCell(10000)->addText($subject, $cellTextStyleBigBold, $center);
     $section->addText('Dayananda Sagar College of Engineering, Bangalore - 78', $cellTextStyleBigBold, $center);
     $section->addText('Department of Computer Science & Engineering', $cellTextStyleBigBold, $center);
     $section->addText('Session: ' . $session, $cellTextStyleBigBold, $center);
     $section->addText('Internal Assessment - ' . $internal, $cellTextStyleBigBold, $center);
     $table = $section->addTable();
     $table->addRow();
     $cell = $table->addCell(6000);
     // $textrun = $cell->createTextRun();
     $cell->addText('Semester: ' . $sem, 'myOwnStyle', 'myHeaderStyle');
     $cell->addText('Subject: ' . $subject, 'myOwnStyle', 'myHeaderStyle');
     $cell->addText('Time: ' . $time, 'myOwnStyle', 'myHeaderStyle');
     $table->addCell(4000)->addText('');
     $cell = $table->addCell(2100);
     // $textrun = $cell->createTextRun();
     $cell->addText('Section: ' . $sec, 'myOwnStyle', 'myHeaderStyle');
     $cell->addText('Date: ' . $date, 'myOwnStyle', 'myHeaderStyle');
     $cell->addText('Max Marks: 50', 'myOwnStyle', 'myHeaderStyle');
     // After creating a section, you can append elements:
     $listStyle = array('listType' => PHPWord_Style_ListItem::TYPE_NUMBER_NESTED);
     $section->addText('PART A', 'myOwnStyle', $center);
     $section->addText('Answer any 2 questions out of 3. Each question carries 20 Marks', 'myNoteStyle', $center);
     $table = $section->addTable('myQuestionTable');
     for ($i = 1; $i <= 3; $i++) {
         $letter = 'a';
         for ($j = 1; $j <= sizeof($questions[$i]); $j++) {
             $table->addRow();
             if (sizeof($questions[$i]) == 1) {
                 $table->addCell(100)->addText($i . '.');
             } elseif ($j == 1) {
                 $table->addCell(100)->addText($i . '.' . $letter++ . ")");
             } else {
                 $table->addCell(100)->addText("   " . $letter++ . ")");
             }
             $subQuestions = preg_split('/[\\n]/', $questions[$i][$j]->question, -1, NULL);
             $cell = $table->addCell(9000);
             foreach ($subQuestions as $subQuestion) {
                 $cell->addText($subQuestion, $questionTextStyle, 'myQuestionStyle');
             }
             if ($questions[$i][$j]->images()->first()) {
                 $cell->addImage('images/' . $questions[$i][$j]->images()->first()->path, array('align' => 'center'));
             }
             if ($j == sizeof($questions[$i])) {
                 $cell->addText('', 'myGapTStyle', 'myGapPStyle');
             }
             $table->addCell(100)->addText('(' . $questions[$i][$j]->marks . ')');
         }
     }
     $section->addText('PART B', 'myOwnStyle', $center);
     $section->addText('Answer any 1 question out of 2. Each question carries 10 Marks', 'myNoteStyle', $center);
     $table = $section->addTable('myQuestionTable');
     for ($i = 4; $i <= 5; $i++) {
         $letter = 'a';
         for ($j = 1; $j <= sizeof($questions[$i]); $j++) {
             $table->addRow();
             if (sizeof($questions[$i]) == 1) {
                 $table->addCell(100)->addText($i . '.');
             } elseif ($j == 1) {
                 $table->addCell(100)->addText($i . '.' . $letter++ . ")");
             } else {
                 $table->addCell(100)->addText("   " . $letter++ . ")");
             }
             $subQuestions = preg_split('/[\\n]/', $questions[$i][$j]->question, -1, NULL);
             $cell = $table->addCell(9000);
             foreach ($subQuestions as $subQuestion) {
                 $cell->addText($subQuestion, $questionTextStyle, 'myQuestionStyle');
             }
             if ($questions[$i][$j]->images()->first()) {
                 $cell->addImage('images/' . $questions[$i][$j]->images()->first()->path, array('align' => 'center'));
             }
             if ($j == sizeof($questions[$i])) {
                 $cell->addText('', 'myGapTStyle', 'myGapPStyle');
             }
             $table->addCell(100)->addText('(' . $questions[$i][$j]->marks . ')');
         }
     }
     //Footer
     $footer = $section->createFooter();
     $footer->addPreserveText('{PAGE}/{NUMPAGES}', $center);
     // At last write the document to webspace:
     $objWriter = PHPWord_IOFactory::createWriter($PHPWord, 'Word2007');
     $objWriter->save('papers/' . $questions[1][1]->subject()->first()->name . '[' . $date . ']' . '.docx');
 }
예제 #11
0
<?php

require_once 'PHPWord.php';
// New Word Document
$PHPWord = new PHPWord();
// New portrait section
$section = $PHPWord->createSection(array('orientation' => 'landscape', 'marginLeft' => 600, 'marginRight' => 600, 'marginTop' => 200, 'marginBottom' => 200));
// Define table style arrays
$styleTable = array('borderSize' => 1, 'borderColor' => 'black', 'cellMargin' => 5);
$styleFirstRow = array('borderBottomSize' => 5, 'borderBottomColor' => '0000FF', 'bgColor' => 'lavender');
// Define cell style arrays
$styleCell = array('valign' => 'center');
$styleCellBTLR = array('valign' => 'right', 'textDirection' => PHPWord_Style_Cell::TEXT_DIR_BTLR);
// Define font style for first row
$fontStyle = array('bold' => false, 'align' => 'right', 'size' => 7);
// Add table style
$PHPWord->addTableStyle('myOwnTableStyle', $styleTable, $styleFirstRow);
$section->addText('LAPORAN KWITANSI', 'rStyle', 'pStyle');
$section->addText(' ' . $periode . '', array('name' => 'Arial'), 'pStyle');
// Add table
$table = $section->addTable('myOwnTableStyle');
// Add row
$table->addRow(900);
// Add cells
$table->addCell(300, $styleCell)->addText('No', array('align' => 'center'));
$table->addCell(1900, $styleCell)->addText('No KW', $fontStyle);
$table->addCell(1600, $styleCell)->addText('Tgl KW', $fontStyle);
$table->addCell(1600, $styleCell)->addText('No.Kontrak', $fontStyle);
$table->addCell(2000, $styleCell)->addText('Asuransi', $fontStyle);
$table->addCell(2000, $styleCell)->addText('Tertanggung', $fontStyle);
$table->addCell(2000, $styleCell)->addText('Surveyor', $fontStyle);
예제 #12
0
<?php

require_once '../PHPWord.php';
// New Word Document
$PHPWord = new PHPWord();
// New portrait section
$section = $PHPWord->createSection();
// Add text elements
$section->addText('You can open this OLE object by double clicking on the icon:');
$section->addTextBreak(2);
// Add object
$section->addObject('_sheet.xls');
// Save File
$objWriter = PHPWord_IOFactory::createWriter($PHPWord, 'Word2007');
$objWriter->save('Object.docx');
예제 #13
0
 /**
  * @return boolean
  */
 function downloadApprovalNotice()
 {
     $phpword_object = new PHPWord();
     $section = $phpword_object->createSection();
     $header = $section->createHeader();
     $footer = $section->createFooter();
     // Replace the keys by the values of the proposal
     $this->_replaceHTMLs($this->sectionEditorSubmission);
     // Convert the HTML and put it into the PHPWord object
     $headerDomArray = $this->_getHtmlDomArray($this->header);
     $headerDomArray = $headerDomArray[0];
     $bodyDomArray = $this->_getHtmlDomArray($this->body);
     $bodyDomArray = $bodyDomArray[0];
     $footerDomArray = $this->_getHtmlDomArray($this->footer);
     $footerDomArray = $footerDomArray[0];
     htmltodocx_insert_html($header, $headerDomArray->nodes, $this->_getSettings('header'));
     htmltodocx_insert_html($section, $bodyDomArray->nodes, $this->_getSettings());
     htmltodocx_insert_html($footer, $footerDomArray->nodes, $this->_getSettings('footer'));
     // Always include the page number in the footer
     $footer->addPreserveText(Locale::translate('submission.approvalNotice.pageNumberOfTotalPages.page') . ' {PAGE} ' . Locale::translate('submission.approvalNotice.pageNumberOfTotalPages.of') . ' {NUMPAGES}', null, array('size' => 6, 'align' => 'center'));
     // Save File
     $h2d_file_uri = tempnam('', 'htd');
     $objWriter = PHPWord_IOFactory::createWriter($phpword_object, 'Word2007');
     $objWriter->save($h2d_file_uri);
     // Download the file:
     header('Content-Description: File Transfer');
     header('Content-Type: application/octet-stream');
     header('Content-Disposition: attachment; filename=' . $this->fileName . '.docx');
     header('Content-Transfer-Encoding: binary');
     header('Expires: 0');
     header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
     header('Pragma: public');
     header('Content-Length: ' . filesize($h2d_file_uri));
     ob_clean();
     flush();
     $status = readfile($h2d_file_uri);
     unlink($h2d_file_uri);
     return true;
 }
예제 #14
0
 public function generatedocx()
 {
     if ($this->request->is('post')) {
         $sentenceId = $this->request['data']['sentenceId'];
         $startIndex = $this->request['data']['startIndex'];
         $endIndex = $this->request['data']['endIndex'];
         $maxLevel = $this->request['data']['maxLevel'];
         $tmpDocumentPath = '/tmp/IAtagger_generated.docx';
         $sentenceData = Utils::getSentenceData($sentenceId);
         //die(print_r($sentenceData, true));
         // New Word Document
         $PHPWord = new PHPWord();
         // New portrait section
         $section = $PHPWord->createSection();
         $PHPWord->addParagraphStyle('centering', array('align' => 'center'));
         $PHPWord->addFontStyle('wordsRowTextStyle', array('bold' => true));
         $PHPWord->addFontStyle('tagsTextStyle', array('bold' => true, 'color' => '000066', 'align' => 'center'));
         $PHPWord->addFontStyle('defaultTextStyle', array('bold' => false));
         $wordsRowCellStyle = array('borderTopSize' => 6, 'borderTopColor' => '006699', 'borderLeftSize' => 6, 'borderLeftColor' => '006699', 'borderRightSize' => 6, 'borderRightColor' => '006699', 'borderBottomSize' => 18, 'borderBottomColor' => '000066', 'bgColor' => 'E2F0FF', 'cellMargin' => 30, 'valign' => 'center');
         $cellStyle = array('borderSize' => 6, 'borderColor' => '006699', 'cellMargin' => 30, 'valign' => 'center');
         $table = $section->addTable();
         // Bracket row
         $table->addRow();
         $table->addCell(900);
         $wordIndex = 0;
         foreach ($sentenceData['sentence']['Word'] as $word) {
             if ($wordIndex >= $startIndex && $wordIndex < $endIndex) {
                 $cell = $table->addCell(2000);
                 if ($word['postposition_id']) {
                     $cell->addImage('/var/www/html/tagging/app/webroot/img/leftBracket.png', array('width' => 40, 'height' => 15, 'align' => 'right'));
                 }
                 if ($word['is_postposition']) {
                     $cell->addImage('/var/www/html/tagging/app/webroot/img/rightBracket.png', array('width' => 40, 'height' => 15, 'align' => 'left'));
                 }
             }
             $wordIndex++;
         }
         // Words row
         $table->addRow(900);
         $table->addCell(900, $wordsRowCellStyle);
         $wordIndex = 0;
         foreach ($sentenceData['sentence']['Word'] as $word) {
             if ($wordIndex >= $startIndex && $wordIndex < $endIndex) {
                 $cell = $table->addCell(2000, $wordsRowCellStyle);
                 if ($word['split']) {
                     $wordText = $word['stem'] . '-' . $word['suffix'];
                 } else {
                     $wordText = $word['text'];
                 }
                 $cell->addText($wordText, 'wordsRowTextStyle', 'centering');
             }
             $wordIndex++;
         }
         // Annotation rows
         $legend = array();
         $levelIndex = 0;
         foreach ($sentenceData['sentence']['WordAnnotations'] as $annotationData) {
             if ($levelIndex < $maxLevel) {
                 $table->addRow(900);
                 $wordAnnotationType = $annotationData['type']['WordAnnotationType'];
                 // annotation name cell
                 $cell = $table->addCell(900, $cellStyle);
                 $cell->addText($wordAnnotationType['name'], 'defaultTextStyle', 'centering');
                 $wordIndex = 0;
                 foreach ($annotationData['annotations'] as $annotation) {
                     if ($wordIndex >= $startIndex && $wordIndex < $endIndex) {
                         $cell = $table->addCell(900, $cellStyle);
                         if (!empty($annotation)) {
                             if ($wordAnnotationType['strict_choices']) {
                                 foreach ($annotation['WordAnnotationTypeChoice'] as $choice) {
                                     $cell->addText($choice['value'], 'tagsTextStyle', 'centering');
                                     $legend[$choice['value']] = $choice['description'];
                                 }
                             } else {
                                 $cell->addText($annotation['text_value'], 'defaultTextStyle', 'centering');
                             }
                         }
                     }
                     $wordIndex++;
                 }
             }
             $levelIndex++;
         }
         foreach ($sentenceData['sentence']['SentenceAnnotations'] as $annotationData) {
             if ($levelIndex < $maxLevel) {
                 $table->addRow(900);
                 $sentenceAnnotationType = $annotationData['type']['SentenceAnnotationType'];
                 // annotation name cell
                 $cell = $table->addCell(900, $cellStyle);
                 $cell->addText($sentenceAnnotationType['name'], 'defaultTextStyle', 'centering');
                 $spanningCellStyle = $cellStyle;
                 $spanningCellStyle['gridSpan'] = $endIndex - $startIndex;
                 $cell = $table->addCell(900, $spanningCellStyle);
                 $text = isset($annotationData['annotation']['text']) ? $annotationData['annotation']['text'] : '';
                 $cell->addText($text);
             }
             $levelIndex++;
         }
         // Legend
         ksort($legend);
         $section->addTextBreak(2);
         $section->addText("Legend:", array('bold' => true));
         foreach ($legend as $value => $description) {
             $section->addListItem($value . ' - ' . $description);
         }
         // Save File
         $objWriter = PHPWord_IOFactory::createWriter($PHPWord, 'Word2007');
         $objWriter->save($tmpDocumentPath);
         $this->response->file($tmpDocumentPath, array('download' => true, 'name' => 'IAtagger_table.docx'));
         // Return response object to prevent controller from trying to render
         // a view
         return $this->response;
     }
 }
 public function generate($id = 0)
 {
     $this->load->library('PHPWord');
     $this->load->helper('util');
     $date = date('Y-m-d_H-i-s');
     //if ($id==0);
     $conf = $this->db->get($this->cms_complete_table_name('konfigurasi'))->result();
     $data = $this->db->where('id_ket_lulusan', $id)->get($this->cms_complete_table_name('ket_lulusan'))->result();
     $ket = $this->db->where('fk_id_ket_lulusan', $id)->get($this->cms_complete_table_name('keterangan_lulusan'))->result();
     $PHPWord = new PHPWord();
     // New portrait section
     $section = $PHPWord->createSection(array('pageSizeH' => 20500));
     // Define the TOC font style
     // Add title styles
     $PHPWord->addFontStyle(1, array('size' => 16, 'color' => '000', 'underline' => PHPWord_Style_Font::UNDERLINE_SINGLE));
     $PHPWord->addFontStyle(2, array('size' => 12, 'color' => '000', 'bold' => true));
     $PHPWord->addParagraphStyle('pStyle', array('align' => 'center', 'spaceAfter' => 10));
     $PHPWord->addParagraphStyle('pStyle_footer', array('tabs' => array(new PHPWord_Style_Tab('left', 6000)), 'align' => 'center', 'spaceAfter' => 10));
     $PHPWord->addParagraphStyle('pStyle_tbs', array('size' => 11, 'align' => 'left', 'spaceAfter' => 10));
     $fontStyle = array('spaceAfter' => 60, 'size' => 12);
     //Generate Document
     foreach ($data as $d) {
         $section->addTitle('');
         $section->addTitle('');
         $section->addTitle('');
         $section->addText('SURAT KETERANGAN LULUSAN', 1, 'pStyle');
         $section->addText('No.' . $d->nomor_surat . '/B-01/STMIK-AMIK/' . $d->bulan . '/' . $d->tahun, $fontStyle, 'pStyle');
         $section->addTitle('');
         $section->addTitle('');
         $section->addText('Yang bertanda tangan dibawah ini :', $fontStyle);
         //Table
         foreach ($conf as $c) {
             $table = $section->addTable();
             $table->addRow();
             $table->addCell(500)->addText("");
             $table->addCell(1750)->addText("Nama", $fontStyle);
             $table->addCell(3750)->addText(": " . $c->nama_puket, $fontStyle);
             $table->addRow();
             $table->addCell(500)->addText("");
             $table->addCell(1750)->addText("Pangkat/Gol", $fontStyle);
             $table->addCell(3750)->addText(": " . $c->pangkat_puket, $fontStyle);
             $table->addRow();
             $table->addCell(500)->addText("");
             $table->addCell(1750)->addText("Jabatan", $fontStyle);
             $table->addCell(3750)->addText(": Pembantu Ketua I. Bid. Akademis", $fontStyle);
         }
         //End OfTable
         $section->addText('Menerangkan bahwa :', $fontStyle);
         //Table
         $table = $section->addTable();
         $table->addRow();
         $table->addCell(500)->addText("");
         $table->addCell(1750)->addText("Nama", $fontStyle);
         $table->addCell(3750)->addText(": " . $d->nama_mahasiswa, $fontStyle);
         $table->addRow();
         $table->addCell(500)->addText("");
         $table->addCell(1750)->addText("NPM", $fontStyle);
         $table->addCell(3750)->addText(": " . $d->npm, $fontStyle);
         $table->addRow();
         $table->addCell(500)->addText("");
         $table->addCell(1750)->addText("Tempat/Tgl Lahir", $fontStyle);
         $table->addCell(3750)->addText(": " . $d->tempat_lahir . ", " . tanggal(date($d->tanggal_lahir)), $fontStyle);
         //End OfTable
         $section->addText('Adalah   benar   mahasiswa   Sekolah Tinggi  Manajemen   Informatika   &   Komputer   AMIK Riau (STMIK-AMIK) Riau yang telah :', $fontStyle);
         $section->addText("");
         foreach ($ket as $k) {
             $section->addListItem($k->keterangan, 0, $fontStyle);
         }
         //End OfTable
         foreach ($conf as $c) {
             $section->addText('Demikian surat keterangan kelulusan ini dikeluarkan untuk dapat dipergunakan sebagaimana mestinya.', $fontStyle);
             $section->addTitle('');
             $section->addText("\tPekanbaru, " . tanggal(date('d-m-Y')), $fontStyle, 'pStyle_footer');
             $section->addTitle('');
             $section->addTitle('');
             $section->addTitle('');
             $section->addText("\t{$c->nama_puket}", 2, 'pStyle_footer');
             $section->addText("\tPuket I Bid. Akademis", $fontStyle, 'pStyle_footer');
             $section->addTitle('');
             $section->addTitle('');
             $section->addText("Tembusan disampaikan kepada Yth :", 'pStyle_tbs');
             $section->addText("1. Ketua STMIK-AMIK Riau", 'pStyle_tbs');
             $section->addText("2. Arsip ……", 'pStyle_tbs');
         }
         ////open file////
         $objWriter = PHPWord_IOFactory::createWriter($PHPWord, 'Word2007');
         $filename = $d->npm . '-Ket_Lulusan.docx';
         $objWriter->save($filename);
         header('Content-Description: File Transfer');
         header('Content-Type: application/octet-stream');
         header('Content-Disposition: attachment; filename=' . $filename);
         header('Content-Transfer-Encoding: binary');
         header('Expires: 0');
         header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
         header('Pragma: public');
         header('Content-Length: ' . filesize($filename));
         flush();
         readfile($filename);
         unlink($filename);
         // deletes the temporary file
         exit;
     }
     ////end of open file////
     ///save file////
     //$document->save('assets/docs/'.$d->nama_kar.'-'.$d->id_pegawai.'.docx');
     //redirect(base_url().'assets/docs/'.$d->nama_kar.'-'.$d->id_pegawai.'.docx', 'assets/manage_pegawai');
     ///end of save file////
 }
예제 #16
0
function gen_prosmotr()
{
    require_once 'custom/include/PHPWord/PHPWord.php';
    $bean = loadBean('Meetings');
    $bean->retrieve($_REQUEST['record']);
    $user = loadBean('Users');
    // получаем реелтора
    $user->retrieve($bean->assigned_user_id);
    $client = loadBean($bean->parent_type);
    // получаем клиента
    $client->retrieve($bean->parent_id);
    $realty = loadBean('Realty');
    // получаем объект
    $realty->retrieve($bean->realty_id);
    /*$client = loadBean('Contacts');// получаем клиента
    	$client->retrieve($bean->contact_id);*/
    $doc = new Document();
    // создаем запись в документах и описание файла к нему
    $doc->id = create_guid();
    $doc->new_with_id = true;
    $doc->document_name = "Просмотровый лист по показу {$bean->name}";
    $doc->status_id = "Active";
    $doc_rev = new DocumentRevision();
    $doc_rev->filename = "просмотровый лист - {$bean->name}.docx";
    $doc_rev->file_ext = "docx";
    $doc_rev->file_mime_type = "application/octet-stream";
    $doc_rev->revision = "1";
    $doc_rev->document_id = $doc->id;
    $doc_rev->save();
    $doc->document_revision_id = $doc_rev->id;
    $doc->save();
    /*$client->load_relationship('documents'); // цепляем документ к клиенту
    	$client->documents->add($doc->id,array());*/
    //Set table cells style
    $cellStyle = array('borderTopSize' => 1, 'borderTopColor' => '000000', 'borderLeftSize' => 1, 'borderLeftColor' => '000000', 'borderRightSize' => 1, 'borderRightColor' => '000000', 'borderBottomSize' => 1, 'borderBottomColor' => '000000');
    // New Word Document
    $PHPWord = new PHPWord();
    // New portrait section
    $section = $PHPWord->createSection();
    //Add title
    $section->addText('Просмотровый лист', array('size' => 18, 'bold' => true), array('align' => 'center'));
    // Add table
    $table = $section->addTable();
    $table->addRow();
    // Add Cell
    $table->addCell(1750, $cellStyle)->addText("Дата и время");
    $table->addCell(1750, $cellStyle)->addText("Адрес");
    $table->addCell(1750, $cellStyle)->addText("Описание");
    $table->addCell(1750, $cellStyle)->addText("Объект");
    $table->addCell(1750, $cellStyle)->addText("Клиент");
    $table->addCell(1750, $cellStyle)->addText("Риэлтор");
    $table->addRow();
    $table->addCell(1750, $cellStyle)->addText($bean->date_start);
    $table->addCell(1750, $cellStyle)->addText($bean->location);
    $table->addCell(1750, $cellStyle)->addText($bean->description);
    $table->addCell(1750, $cellStyle)->addText($realty->name);
    $table->addCell(1750, $cellStyle)->addText($client->first_name . ' ' . $client->last_name);
    $table->addCell(1750, $cellStyle)->addText($user->first_name . ' ' . $user->last_name);
    // Save File
    $objWriter = PHPWord_IOFactory::createWriter($PHPWord, 'Word2007');
    $objWriter->save("upload/{$doc_rev->id}");
    echo "<h1>Просмотровый лист создан</h1><br/>\n\t\t<a href='index.php?entryPoint=download&id={$doc_rev->id}&type=Documents'>Скачать файл</a><br/>\n\t\t<a href='index.php?module=Documents&action=DetailView&record={$doc->id}'>Перейти в документ</a><hr/>\n\t\t<a href='index.php?module=Meetings&action=DetailView&record={$_REQUEST['record']}'>Вернуться в карточку показа</a>\n\t\t";
}
예제 #17
0
function doDoc($title, $headertext, $footertext, $items)
{
    // New Word Document
    $PHPWord = new PHPWord();
    // New portrait section
    $section = $PHPWord->createSection();
    // Add header
    $header = $section->createHeader();
    $table = $header->addTable();
    $table->addRow();
    $table->addCell(4500)->addText($headertext);
    // Add footer
    $footer = $section->createFooter();
    //$footer->addPreserveText('Page {PAGE} of {NUMPAGES}.', array('align'=>'center'));
    $footer->addPreserveText($footertext, array('align' => 'center'));
    // Title styles
    $PHPWord->addTitleStyle(1, array('size' => 20, 'color' => '333333', 'bold' => true));
    $PHPWord->addTitleStyle(2, array('size' => 16, 'color' => '666666'));
    $section->addTitle($title, 1);
    foreach ($items as $item) {
        $section->addTitle($item->title, 2);
        $section->addTextBreak(1);
        $section->addText($item->text);
        $section->addTextBreak(1);
        $section->addImage($item->filename);
        $section->addTextBreak(1);
    }
    $objWriter = PHPWord_IOFactory::createWriter($PHPWord, 'Word2007');
    header('Content-Type: application/vnd.ms-word');
    header('Content-Disposition: attachment;filename="' . $title . '.docx"');
    header('Cache-Control: max-age=0');
    // At least write the document to webspace:
    $objWriter = PHPWord_IOFactory::createWriter($PHPWord, 'Word2007');
    $objWriter->save('php://output');
}
예제 #18
0
 public function generate($id = 0)
 {
     $this->load->library('PHPWord');
     $this->load->helper('util');
     $date = date('Y-m-d_H-i-s');
     $no = 1;
     $no2 = 1;
     //if ($id==0);
     $conf = $this->db->get($this->cms_complete_table_name('konfigurasi'))->result();
     $cont = $this->db->get($this->cms_complete_table_name('master_cont_pkl'))->result();
     $mhs = $this->db->where('fk_id_pkl', $id)->join($this->cms_complete_table_name('mas_jurusan'), 'mas_jurusan.id_jurusan=mhs_pkl.id_jurusan', 'left')->get($this->cms_complete_table_name('mhs_pkl'))->result();
     $data = $this->db->where('id_pkl', $id)->join($this->cms_complete_table_name('mhs_pkl'), 'fk_id_pkl=fk_id_pkl', 'left')->join($this->cms_complete_table_name('mas_jurusan'), 'mas_jurusan.id_jurusan=mhs_pkl.id_jurusan', 'left')->get($this->cms_complete_table_name('pkl'))->result();
     $PHPWord = new PHPWord();
     // New portrait section
     $section = $PHPWord->createSection(array('pageSizeH' => 20500));
     // Define the TOC font style
     // Add title styles
     $styleTable = array('cellMargin' => 20);
     $styleTable_mhs = array('cellMargin' => 20, 'borderSize' => 6);
     $PHPWord->addFontStyle(1, array('size' => 16, 'color' => '333333', 'underline' => PHPWord_Style_Font::UNDERLINE_SINGLE));
     $PHPWord->addFontStyle(2, array('size' => 12, 'bold' => true));
     $PHPWord->addFontStyle('underline', array('size' => 11.5, 'underline' => PHPWord_Style_Font::UNDERLINE_SINGLE));
     $PHPWord->addFontStyle('bold', array('size' => 11.5, 'bold' => true));
     $PHPWord->addParagraphStyle('pStyle', array('align' => 'center', 'spaceAfter' => 10));
     $PHPWord->addParagraphStyle('pHead', array('spaceAfter' => 0));
     $PHPWord->addParagraphStyle('pTempat', array('spaceAfter' => 10, 'marginLeft' => 3000));
     $PHPWord->addParagraphStyle('pStyle_footer', array('tabs' => array(new PHPWord_Style_Tab('left', 5700)), 'align' => 'center', 'spaceAfter' => 10));
     $PHPWord->addParagraphStyle('pStyle_tbs', array('size' => 11, 'align' => 'left', 'spaceAfter' => 10));
     $fontStyle = array('size' => 11.5);
     //Content
     foreach ($data as $d) {
         $section->addText('', 'pHead');
         $table = $section->addTable();
         $table->addRow();
         $table->addCell(1250, $styleTable)->addText("", $fontStyle, 'pHead');
         $table->addCell(20, $styleTable)->addText("", $fontStyle, 'pHead');
         $table->addCell(9000, $styleTable)->addText("", $fontStyle, 'pHead');
         $table->addRow();
         $table->addCell(1250, $styleTable)->addText("Nomor", $fontStyle, 'pHead');
         $table->addCell(20, $styleTable)->addText(": ", $fontStyle, 'pHead');
         $table->addCell(9000, $styleTable)->addText("{$d->nomor}", $fontStyle, 'pHead');
         $table->addRow();
         $table->addCell(1250, $styleTable)->addText("Lamp", $fontStyle, 'pHead');
         $table->addCell(20, $styleTable)->addText(": ", $fontStyle, 'pHead');
         $table->addCell(9000, $styleTable)->addText("{$d->lampiran}", $fontStyle, 'pHead');
         $table->addRow();
         $table->addCell(1250, $styleTable)->addText("Hal", $fontStyle, 'pHead');
         $table->addCell(20, $styleTable)->addText(": ", $fontStyle, 'pHead');
         $table->addCell(9000, $styleTable)->addText("Permohonan PKL/Magang Mahasiswa", 'underline', 'pHead');
         $section->addText('', 'pHead');
         $table = $section->addTable();
         $table->addRow();
         $table->addCell(400, $styleTable)->addText("", $fontStyle, 'pHead');
         $table->addCell(8200, $styleTable)->addText("Kepada Yth.", $fontStyle, 'pHead');
         $table->addRow();
         $table->addCell(400, $styleTable)->addText("", $fontStyle, 'pHead');
         $table->addCell(8200, $styleTable)->addText("{$d->kepada}", 'bold', 'pHead');
         $section->addText('', $fontStyle, 'pHead');
         $table = $section->addTable();
         $table->addRow();
         $table->addCell(400, $styleTable)->addText("", $fontStyle, 'pHead');
         $table->addCell(400, $styleTable)->addText("Di -", $fontStyle, 'pHead');
         $table->addCell(8200, $styleTable)->addText("", $fontStyle, 'pHead');
         $table->addRow();
         $table->addCell(400, $styleTable)->addText("", $fontStyle, 'pHead');
         $table->addCell(400, $styleTable)->addText("", $fontStyle, 'pHead');
         $table->addCell(8200, $styleTable)->addText("{$d->di}", 'underline', 'pHead');
         $section->addText('', $fontStyle, 'pHead');
         $table = $section->addTable();
         $table->addRow();
         $table->addCell(400)->addText("");
         $table->addCell(10000)->addText("Dengan Hormat,", $fontStyle, 'pHead');
         $table->addRow();
         $table->addCell(400, $styleTable)->addText("", $fontStyle, 'pHead');
         $table->addCell(10000, $styleTable)->addText("Pertama sekali kami do’akan agar Bapak/Ibu senantiasa dalam keadaan sehat dan sukses selalu dalam menjalankan aktifitas, Amin.", $fontStyle, 'pHead');
         $table->addRow();
         $table->addCell(400)->addText("");
         $table->addCell(10000)->addText("Selanjutnya kami memperkenalkan diri bahwa kami adalah Perguruan Tinggi Ilmu Komputer (STMIK-AMIK Riau) yang berlokasi di Jalan Purwodadi Indah Km. 10 Panam Pekanbaru Riau.", $fontStyle);
         $table->addRow();
         $table->addCell(400, $styleTable)->addText("", $fontStyle, 'pHead');
         $table->addCell(10000, $styleTable)->addText("Sesuai dengan kalender akademik, setiap mahasiswa Jenjang Strata I (S.1)  dan Diploma III (D.3) yang akan memasuki tahap akhir diwajibkan untuk melaksanakan Praktek Kerja Lapangan (PKL) / Magang dalam rangka mengasah kemampuan mereka untuk mengenal  dunia kerja yang sesungguhnya.", $fontStyle, 'pHead');
         $table->addRow();
         $table->addCell(400)->addText("");
         $table->addCell(10000)->addText("Sebagai upaya pelaksanaan kegiatan magang tersebut, kami mohon kiranya Bapak/Ibu dapat berkenan memberikan kesempatan kepada para mahasiswa kami untuk dapat melaksanakan PKL/Magang dari tangal 01 Juli s/d 24 Agustus 2013.", $fontStyle);
         $table->addRow();
         $table->addCell(400, $styleTable)->addText("", $fontStyle, 'pHead');
         $table->addCell(10000, $styleTable)->addText("Perhatian dan binaan dari Bapak/Ibu sangat kami harapkan nantinya selama kegiatan tersebut dilaksanakan. Untuk Konfirmasi Selanjutnya Bapak/Ibu dapat menghubungi STMIK-AMIK Riau. Melalui :", $fontStyle, 'pHead');
         //Kontak Dosen
         $section->addText('', $fontStyle, 'pHead');
         $table = $section->addTable();
         foreach ($cont as $cnt) {
             $table->addRow();
             $table->addCell(400, $styleTable)->addText("", $fontStyle, 'pHead');
             $table->addCell(400, $styleTable)->addText("{$no}. ", $fontStyle, 'pHead');
             $table->addCell(4300, $styleTable)->addText("{$cnt->nama_dosen}", $fontStyle, 'pHead');
             $table->addCell(4300, $styleTable)->addText("Hp ({$cnt->nomor_telp})", $fontStyle, 'pHead');
             $no++;
         }
         $section->addText('', $fontStyle, 'pHead');
         $table = $section->addTable();
         $table->addRow();
         $table->addCell(400, $styleTable)->addText("", $fontStyle, 'pHead');
         $table->addCell(9000, $styleTable)->addText("Adapun nama-nama mahasiswa kami tersebut adalah :", $fontStyle, 'pHead');
         //Nama Mahasiswa
         $section->addText('', $fontStyle, 'pHead');
         $table = $section->addTable();
         $table->addRow();
         $table->addCell(400, $styleTable)->addText("", $fontStyle, 'pHead');
         $table->addCell(400, $styleTable_mhs)->addText("No. ", $fontStyle, 'pHead');
         $table->addCell(2600, $styleTable_mhs)->addText("Nama", $fontStyle, 'pHead');
         $table->addCell(2500, $styleTable_mhs)->addText("NPM", $fontStyle, 'pHead');
         $table->addCell(2500, $styleTable_mhs)->addText("Jurusan", $fontStyle, 'pHead');
         foreach ($mhs as $m) {
             $table->addRow();
             $table->addCell(400, $styleTable)->addText("", $fontStyle, 'pHead');
             $table->addCell(400, $styleTable_mhs)->addText("{$no2}.", $fontStyle, 'pHead');
             $table->addCell(2600, $styleTable_mhs)->addText("{$m->nama_mahasiswa}", $fontStyle, 'pHead');
             $table->addCell(2500, $styleTable_mhs)->addText("{$m->npm}", $fontStyle, 'pHead');
             $table->addCell(2500, $styleTable_mhs)->addText("{$m->nama_jurusan}", $fontStyle, 'pHead');
             $no2++;
         }
         //Footer
         $section->addText('', $fontStyle);
         $table = $section->addTable();
         $table->addRow();
         $table->addCell(400)->addText("", $fontStyle);
         $table->addCell(8600)->addText("Besar Harapan Kami kiranya Bapak/Ibu dapat menerima mahasiswa kami tersebut, selanjutnya kami  sangat mengharapkan informasi berapa orang mahasiswa kami yang dapat diterima untuk melaksanakan PKL di instansi/perusahaan yang Bapak/Ibu pimpin.", $fontStyle);
         $table->addRow();
         $table->addCell(400)->addText("", $fontStyle);
         $table->addCell(8600)->addText("Atas bantuan dan kerjasama yang baik dari Bapak/Ibu kami ucapkan terima kasih.", $fontStyle, 'pHead');
         $section->addTitle('');
         $section->addText("\tPekanbaru, " . tanggal(date('d-m-Y')), $fontStyle, 'pStyle_footer');
         $section->addText("\tAn. Ketua, ", $fontStyle, 'pStyle_footer');
         $section->addTitle('');
         $section->addTitle('');
         $section->addText("\t{$d->ketua_jurusan}", 2, 'pStyle_footer');
         $section->addText("\tKetua Jurusan {$d->nama_jurusan}", $fontStyle, 'pStyle_footer');
         $section->addText("Tembusan :", 'underline', 'pStyle_tbs');
         $section->addText("1. Yth. Bapak Ketua STMIK-AMIK Riau", 'pStyle_tbs');
         $section->addText("2. Yth. Ibu Pembantu Ketua I", 'pStyle_tbs');
         $section->addText("3. Arsip", 'pStyle_tbs');
         ////open file////
         $objWriter = PHPWord_IOFactory::createWriter($PHPWord, 'Word2007');
         $filename = date('d-m-Y-Hms') . '-Permohonan_PKL.docx';
         $objWriter->save($filename);
         header('Content-Description: File Transfer');
         header('Content-Type: application/octet-stream');
         header('Content-Disposition: attachment; filename=' . $filename);
         header('Content-Transfer-Encoding: binary');
         header('Expires: 0');
         header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
         header('Pragma: public');
         header('Content-Length: ' . filesize($filename));
         flush();
         readfile($filename);
         unlink($filename);
         // deletes the temporary file
         exit;
     }
     ////end of open file////
     ///save file////
     //$document->save('assets/docs/'.$d->nama_kar.'-'.$d->id_pegawai.'.docx');
     //redirect(base_url().'assets/docs/'.$d->nama_kar.'-'.$d->id_pegawai.'.docx', 'assets/manage_pegawai');
     ///end of save file////
 }
예제 #19
0
파일: word.php 프로젝트: prolin99/tad_cal
<?php

include_once "header.php";
$dates = dates_range($_POST['start'], $_POST['end']);
$myts =& MyTextSanitizer::getInstance();
$sitename = $myts->addSlashes($xoopsConfig['sitename']);
$page_title = "{$sitename} {$_POST['start']}~{$_POST['end']}" . _MD_TADCAL_SIMPLE_CAL;
$filename = str_replace(" ", "", $page_title);
require_once XOOPS_ROOT_PATH . "/modules/tadtools/PHPWord.php";
$PHPWord = new PHPWord();
$PHPWord->setDefaultFontSize(9);
//設定預設字型大小
$sectionStyle = array('orientation' => 'portrait', 'marginTop' => 900, 'marginLeft' => 900, 'marginRight' => 900, 'marginBottom' => 900);
$cw = array(_MD_TADCAL_SU, _MD_TADCAL_MO, _MD_TADCAL_TU, _MD_TADCAL_WE, _MD_TADCAL_TH, _MD_TADCAL_FR, _MD_TADCAL_SA);
$section = $PHPWord->createSection($sectionStyle);
$fontStyle = array('color' => '000000', 'size' => 16, 'bold' => true);
$PHPWord->addTitleStyle(1, $fontStyle);
$section->addTitle($page_title, 1);
$contentfontStyle = array('color' => '000000', 'size' => 9, 'bold' => false);
$styleTable = array('borderColor' => '000000', 'borderSize' => 6, 'cellMargin' => 50);
$styleFirstRow = array('bgColor' => 'CFCFCF');
//首行樣式
$PHPWord->addTableStyle('myTable', $styleTable, $styleFirstRow);
//建立表格樣式
$table = $section->addTable('myTable');
//建立表格
$cellStyle = array('valign' => 'center');
//儲存格樣式(設定項:valign、textDirection、bgColor、borderTopSize、borderTopColor、borderLeftSize、borderLeftColor、borderRightSize、borderRightColor、borderBottomSize、borderBottomColor)
$paraStyle = array('align' => 'center');
$headStyle = array('bold' => true);
//取得目前使用者可讀的群組
예제 #20
0
/**
*  Example of use of HTML to docx converter
*/
// Load the files we need:
require_once 'phpword/PHPWord.php';
require_once 'simplehtmldom/simple_html_dom.php';
require_once 'htmltodocx_converter/h2d_htmlconverter.php';
require_once 'example_files/styles.inc';
// Functions to support this example.
require_once 'documentation/support_functions.inc';
// HTML fragment we want to parse:
$html = file_get_contents('../../tes/naskah/2013-11/07/A12-Menderita_Leukemia,_Tahanan_Palestina_Meninggal_di_Penjara_Israel.html');
// $html = file_get_contents('test/table.html');
// New Word Document:
$phpword_object = new PHPWord();
$section = $phpword_object->createSection();
// HTML Dom object:S
$html_dom = new simple_html_dom();
$html_dom->load('<html><body>' . $html . '</body></html>');
// Note, we needed to nest the html in a couple of dummy elements.
// Create the dom array of elements which we are going to work on:
$html_dom_array = $html_dom->find('html', 0)->children();
// We need this for setting base_root and base_path in the initial_state array
// (below). We are using a function here (derived from Drupal) to create these
// paths automatically - you may want to do something different in your
// implementation. This function is in the included file
// documentation/support_functions.inc.
$paths = htmltodocx_paths();
// Provide some initial settings:
$initial_state = array('phpword_object' => &$phpword_object, 'base_root' => $paths['base_root'], 'base_path' => $paths['base_path'], 'current_style' => array('size' => '11'), 'parents' => array(0 => 'body'), 'list_depth' => 0, 'context' => 'section', 'pseudo_list' => TRUE, 'pseudo_list_indicator_font_name' => 'Wingdings', 'pseudo_list_indicator_font_size' => '7', 'pseudo_list_indicator_character' => 'l ', 'table_allowed' => TRUE, 'treat_div_as_paragraph' => TRUE, 'style_sheet' => htmltodocx_styles_example());
// Convert the HTML and put it into the PHPWord object
예제 #21
0
파일: Template.php 프로젝트: tmlsoft/main
 /**
  * @Title: getWordPHPTableXmlStr
  * @Description: todo(用phpword对象生成word表格xml字符串)
  * @param $title         表格表名
  * @param $titleArr      表头
  * @param $titleGroupArr 分组表头  例:array(array("colspan"=>2, "title"=>"第一大组"),array("colspan"=>3, "title"=>"第二大组"))
  * @param $data          表数据
  * @author 王昭侠
  * @date 2015-01-30 上午90:30:00
  * @throws
  */
 public function getPHPWordTableXmlStr($title, $titleArr, $data = NULL, $titleGroupArr = NULL, $showtype = 0, $textStyle = array(), $widthArray = array())
 {
     $th_count = count($titleArr);
     $obPHPWord = new PHPWord();
     $section = $obPHPWord->createSection();
     $styleTable = array('borderSize' => 6, 'borderColor' => '000000', 'cellMargin' => 80, 'align' => 'center');
     $obPHPWord->addTableStyle('myOwnTableStyle', $styleTable);
     $table = $section->addTable('myOwnTableStyle');
     $cellStyle = array('borderSize' => 6, 'name' => $textStyle["name"], 'size' => $textStyle["size"], 'spacing' => $textStyle["spacing"], 'borderColor' => '000000', 'cellMargin' => 80);
     $td_width = 2000;
     $newStats = array();
     foreach ($data as $k => $v) {
         if ($v["is_stats"] === "1") {
             $sum = 0;
             if (!empty($v["original"][0]) && is_numeric($v["original"][0])) {
                 foreach ($v["original"] as $kk => $vv) {
                     $sum += floatval($vv);
                 }
                 $sum = unitExchange($sum, $v["funcdata"][0][0][1], $v["funcdata"][0][0][2], 3);
                 $newStats[] = "小计:" . $sum;
             } else {
                 $newStats[] = "";
             }
         } else {
             $newStats[] = "";
         }
     }
     $stats = false;
     foreach ($newStats as $k => $v) {
         if (!empty($v)) {
             $stats = true;
             break;
         }
     }
     if (!$stats) {
         $newStats = array();
     }
     if (!empty($title)) {
         if ($showtype != 0) {
             $th_count = count($data[0]["value"]) + 1;
         }
         $table->addRow();
         $table->addCell($td_width * $th_count, array('borderSize' => 6, 'borderColor' => '000000', 'cellMargin' => 80, 'align' => 'center', 'gridSpan' => $th_count))->addText($title, array('name' => $textStyle["name"], 'size' => $textStyle["size"], 'spacing' => $textStyle["spacing"], 'align' => 'center'));
     }
     if (!empty($titleGroupArr)) {
         $table->addRow();
         foreach ($titleGroupArr as $k => $v) {
             $table->addCell($td_width * $v["colspan"], array('borderSize' => 6, 'borderColor' => '000000', 'cellMargin' => 80, 'gridSpan' => $v["colspan"]))->addText($v["title"], array('name' => $textStyle["name"], 'size' => $textStyle["size"], 'spacing' => $textStyle["spacing"], 'align' => 'center'));
         }
     }
     if (empty($showtype)) {
         //默认为横向输出
         if (!empty($titleArr)) {
             $table->addRow();
             foreach ($titleArr as $k => $v) {
                 $table->addCell($widthArray[$k] ? $widthArray[$k] : $td_width, array('borderSize' => 6, 'borderColor' => '000000', 'cellMargin' => 80, 'valign' => 'center', 'align' => 'center'))->addText($v, $textStyle);
             }
         }
         foreach ($data[0]["value"] as $k => $v) {
             $table->addRow();
             foreach ($data as $kk => $vv) {
                 $table->addCell($widthArray[$kk] ? $widthArray[$kk] : $td_width, $cellStyle)->addText($vv["value"][$k], $textStyle);
             }
         }
         if (count($newStats) > 0) {
             $table->addRow();
             foreach ($newStats as $k => $v) {
                 $table->addCell($widthArray[$k] ? $widthArray[$k] : $td_width, $cellStyle)->addText($v, $textStyle);
             }
         }
     } else {
         if (!empty($titleArr)) {
             foreach ($titleArr as $k => $v) {
                 $table->addRow();
                 $table->addCell($widthArray[$k] ? $widthArray[$k] : $td_width, array('borderSize' => 6, 'borderColor' => '000000', 'cellMargin' => 80, 'align' => 'center'))->addText($v, $textStyle);
                 if (!empty($data)) {
                     foreach ($data[$k]["value"] as $kk => $vv) {
                         $table->addCell($widthArray[$kk] ? $widthArray[$kk] : $td_width, $cellStyle)->addText($vv, $textStyle);
                     }
                 }
             }
         } else {
             foreach ($titleArr as $k => $v) {
                 $table->addRow();
                 if (!empty($data)) {
                     foreach ($data[$k]["value"] as $kk => $vv) {
                         $table->addCell($widthArray[$kk] ? $widthArray[$kk] : $td_width, $cellStyle)->addText($vv, $textStyle);
                     }
                     if (count($newStats) > 0) {
                         $table->addCell($widthArray[$kk] ? $widthArray[$kk] : $td_width, $cellStyle)->addText($newStats[$k], $textStyle);
                     }
                 }
             }
         }
     }
     $objWriter = PHPWord_IOFactory::createWriter($obPHPWord, 'Word2007');
     $tableXml = $objWriter->getWriterPart('document')->getObjectAsText($table);
     return $tableXml;
 }
예제 #22
0
/**
 * Generates the DOCX question/correction form for an offlinequiz group.
 *
 * @param question_usage_by_activity $templateusage the template question  usage for this offline group
 * @param object $offlinequiz The offlinequiz object
 * @param object $group the offline group object
 * @param int $courseid the ID of the Moodle course
 * @param object $context the context of the offline quiz.
 * @param boolean correction if true the correction form is generated.
 * @return stored_file instance, the generated DOCX file.
 */
function offlinequiz_create_docx_question(question_usage_by_activity $templateusage, $offlinequiz, $group, $courseid, $context, $correction = false)
{
    global $CFG, $DB, $OUTPUT;
    $letterstr = 'abcdefghijklmnopqrstuvwxyz';
    $groupletter = strtoupper($letterstr[$group->number - 1]);
    $coursecontext = context_course::instance($courseid);
    PHPWord_Media::resetMedia();
    $docx = new PHPWord();
    $trans = new offlinequiz_html_translator();
    // Define cell style arrays.
    $cellstyle = array('valign' => 'center');
    // Add text styles.
    // Normal style.
    $docx->addFontStyle('nStyle', array('size' => $offlinequiz->fontsize));
    // Italic style.
    $docx->addFontStyle('iStyle', array('italic' => true, 'size' => $offlinequiz->fontsize));
    // Bold style.
    $docx->addFontStyle('bStyle', array('bold' => true, 'size' => $offlinequiz->fontsize));
    $docx->addFontStyle('brStyle', array('bold' => true, 'align' => 'right', 'size' => $offlinequiz->fontsize));
    // Underline style.
    $docx->addFontStyle('uStyle', array('underline' => PHPWord_Style_Font::UNDERLINE_SINGLE, 'size' => $offlinequiz->fontsize));
    $docx->addFontStyle('ibStyle', array('italic' => true, 'bold' => true, 'size' => $offlinequiz->fontsize));
    $docx->addFontStyle('iuStyle', array('italic' => true, 'underline' => PHPWord_Style_Font::UNDERLINE_SINGLE, 'size' => $offlinequiz->fontsize));
    $docx->addFontStyle('buStyle', array('bold' => true, 'underline' => PHPWord_Style_Font::UNDERLINE_SINGLE, 'size' => $offlinequiz->fontsize));
    $docx->addFontStyle('ibuStyle', array('italic' => true, 'bold' => true, 'underline' => PHPWord_Style_Font::UNDERLINE_SINGLE, 'size' => $offlinequiz->fontsize));
    // Header style.
    $docx->addFontStyle('hStyle', array('bold' => true, 'size' => $offlinequiz->fontsize + 4));
    // Center style.
    $docx->addParagraphStyle('cStyle', array('align' => 'center', 'spaceAfter' => 100));
    $docx->addParagraphStyle('cStyle', array('align' => 'center', 'spaceAfter' => 100));
    $docx->addParagraphStyle('questionTab', array('tabs' => array(new PHPWord_Style_Tab("left", 360))));
    // Define table style arrays.
    $tablestyle = array('borderSize' => 0, 'borderColor' => 'FFFFFF', 'cellMargin' => 20, 'align' => 'center');
    $firstrowstyle = array('borderBottomSize' => 0, 'borderBottomColor' => 'FFFFFF', 'bgColor' => 'FFFFFF');
    $docx->addTableStyle('tableStyle', $tablestyle, $firstrowstyle);
    $boldfont = new PHPWord_Style_Font();
    $boldfont->setBold(true);
    $boldfont->setSize($offlinequiz->fontsize);
    $normalfont = new PHPWord_Style_Font();
    $normalfont->setSize($offlinequiz->fontsize);
    // Define custom list item style for question answers.
    $level1 = new PHPWord_Style_Paragraph();
    $level1->setTabs(new PHPWord_Style_Tabs(array(new PHPWord_Style_Tab('clear', 720), new PHPWord_Style_Tab('num', 360))));
    $level1->setIndentions(new PHPWord_Style_Indentation(array('left' => 360, 'hanging' => 360)));
    $level2 = new PHPWord_Style_Paragraph();
    $level2->setTabs(new PHPWord_Style_Tabs(array(new PHPWord_Style_Tab('left', 720), new PHPWord_Style_Tab('num', 720))));
    $level2->setIndentions(new PHPWord_Style_Indentation(array('left' => 720, 'hanging' => 360)));
    // Create the section that will be used for all outputs.
    $section = $docx->createSection();
    $title = offlinequiz_str_html_docx($offlinequiz->name);
    if (!empty($offlinequiz->time)) {
        if (strlen($title) > 35) {
            $title = substr($title, 0, 33) . ' ...';
        }
        $title .= ": " . offlinequiz_str_html_docx(userdate($offlinequiz->time));
    } else {
        if (strlen($title) > 40) {
            $title = substr($title, 0, 37) . ' ...';
        }
    }
    $title .= ",  " . offlinequiz_str_html_docx(get_string('group') . " {$groupletter}");
    // Add a header.
    $header = $section->createHeader();
    $header->addText($title, array('size' => 10), 'cStyle');
    $header->addImage($CFG->dirroot . '/mod/offlinequiz/pix/line.png', array('width' => 600, 'height' => 5, 'align' => 'center'));
    // Add a footer.
    $footer = $section->createFooter();
    $footer->addImage($CFG->dirroot . '/mod/offlinequiz/pix/line.png', array('width' => 600, 'height' => 5, 'align' => 'center'));
    $footer->addPreserveText($title . '  |  ' . get_string('page') . ' ' . '{PAGE} / {NUMPAGES}', null, array('align' => 'left'));
    // Print title page.
    if (!$correction) {
        $section->addText(offlinequiz_str_html_docx(get_string('questionsheet', 'offlinequiz') . ' - ' . get_string('group') . " {$groupletter}"), 'hStyle', 'cStyle');
        $section->addTextBreak(2);
        $table = $section->addTable('tableStyle');
        $table->addRow();
        $cell = $table->addCell(200, $cellstyle)->addText(offlinequiz_str_html_docx(get_string('name')) . ':  ', 'brStyle');
        $table->addRow();
        $cell = $table->addCell(200, $cellstyle)->addText(offlinequiz_str_html_docx(get_string('idnumber', 'offlinequiz')) . ':  ', 'brStyle');
        $table->addRow();
        $cell = $table->addCell(200, $cellstyle)->addText(offlinequiz_str_html_docx(get_string('studycode', 'offlinequiz')) . ':  ', 'brStyle');
        $table->addRow();
        $cell = $table->addCell(200, $cellstyle)->addText(offlinequiz_str_html_docx(get_string('signature', 'offlinequiz')) . ':  ', 'brStyle');
        $section->addTextBreak(2);
        // The DOCX intro text can be arbitrarily long so we have to catch page overflows.
        if (!empty($offlinequiz->pdfintro)) {
            $blocks = offlinequiz_convert_image_docx($offlinequiz->pdfintro);
            offlinequiz_print_blocks_docx($section, $blocks);
        }
        $section->addPageBreak();
    }
    // Load all the questions needed for this offline quiz group.
    $sql = "SELECT q.*, c.contextid, ogq.page, ogq.slot, ogq.maxmark \n              FROM {offlinequiz_group_questions} ogq,\n                   {question} q,\n                   {question_categories} c\n             WHERE ogq.offlinequizid = :offlinequizid\n               AND ogq.offlinegroupid = :offlinegroupid\n               AND q.id = ogq.questionid\n               AND q.category = c.id\n          ORDER BY ogq.slot ASC ";
    $params = array('offlinequizid' => $offlinequiz->id, 'offlinegroupid' => $group->id);
    // Load the questions.
    $questions = $DB->get_records_sql($sql, $params);
    if (!$questions) {
        echo $OUTPUT->box_start();
        echo $OUTPUT->error_text(get_string('noquestionsfound', 'offlinequiz', $groupletter));
        echo $OUTPUT->box_end();
        return;
    }
    // Load the question type specific information.
    if (!get_question_options($questions)) {
        print_error('Could not load question options');
    }
    // Restore the question sessions to their most recent states.
    // Creating new sessions where required.
    $number = 1;
    // We need a mapping from question IDs to slots, assuming that each question occurs only once.
    $slots = $templateusage->get_slots();
    $texfilter = new filter_tex($context, array());
    // Create the docx question numbering. This is only created once since we number all questions from 1...n.
    $questionnumbering = new PHPWord_Numbering_AbstractNumbering("Question-level", array(new PHPWord_Numbering_Level("1", PHPWord_Numbering_Level::NUMFMT_DECIMAL, "%1)", "left", $level1, $boldfont), new PHPWord_Numbering_Level("1", PHPWord_Numbering_Level::NUMFMT_LOWER_LETTER, "%2)", "left", $level2, $normalfont)));
    $docx->addNumbering($questionnumbering);
    // If shufflequestions has been activated we go through the questions in the order determined by
    // the template question usage.
    if ($offlinequiz->shufflequestions) {
        foreach ($slots as $slot) {
            $slotquestion = $templateusage->get_question($slot);
            $myquestion = $slotquestion->id;
            set_time_limit(120);
            $question = $questions[$myquestion];
            // Either we print the question HTML.
            $questiontext = $question->questiontext;
            // Filter only for tex formulas.
            if (!empty($texfilter)) {
                $questiontext = $texfilter->filter($questiontext);
            }
            // Remove all HTML comments (typically from MS Office).
            $questiontext = preg_replace("/<!--.*?--\\s*>/ms", "", $questiontext);
            // Remove <font> tags.
            $questiontext = preg_replace("/<font[^>]*>[^<]*<\\/font>/ms", "", $questiontext);
            // Remove <script> tags that are created by mathjax preview.
            $questiontext = preg_replace("/<script[^>]*>[^<]*<\\/script>/ms", "", $questiontext);
            // Remove all class info from paragraphs because TCDOCX won't use CSS.
            $questiontext = preg_replace('/<p[^>]+class="[^"]*"[^>]*>/i', "<p>", $questiontext);
            $questiontext = $trans->fix_image_paths($questiontext, $question->contextid, 'questiontext', $question->id, 0.6, 300, 'docx');
            $blocks = offlinequiz_convert_image_docx($questiontext);
            offlinequiz_print_blocks_docx($section, $blocks, $questionnumbering, 0);
            $answernumbering = new PHPWord_Numbering_AbstractNumbering("Adv Multi-level", array(new PHPWord_Numbering_Level("1", PHPWord_Numbering_Level::NUMFMT_DECIMAL, "%1.", "left", $level1, $boldfont), new PHPWord_Numbering_Level("1", PHPWord_Numbering_Level::NUMFMT_LOWER_LETTER, "%2)", "left", $level2, $normalfont)));
            $docx->addNumbering($answernumbering);
            if ($question->qtype == 'multichoice' || $question->qtype == 'multichoiceset') {
                // Save the usage slot in the group questions table.
                //                 $DB->set_field('offlinequiz_group_questions', 'usageslot', $slot,
                //                         array('offlinequizid' => $offlinequiz->id,
                //                                 'offlinegroupid' => $group->id, 'questionid' => $question->id));
                // There is only a slot for multichoice questions.
                $attempt = $templateusage->get_question_attempt($slot);
                $order = $slotquestion->get_order($attempt);
                // Order of the answers.
                foreach ($order as $key => $answer) {
                    $answertext = $question->options->answers[$answer]->answer;
                    // Filter only for tex formulas.
                    if (!empty($texfilter)) {
                        $answertext = $texfilter->filter($answertext);
                    }
                    // Remove all HTML comments (typically from MS Office).
                    $answertext = preg_replace("/<!--.*?--\\s*>/ms", "", $answertext);
                    // Remove all paragraph tags because they mess up the layout.
                    $answertext = preg_replace("/<p[^>]*>/ms", "", $answertext);
                    // Remove <script> tags that are created by mathjax preview.
                    $answertext = preg_replace("/<script[^>]*>[^<]*<\\/script>/ms", "", $answertext);
                    $answertext = preg_replace("/<\\/p[^>]*>/ms", "", $answertext);
                    $answertext = $trans->fix_image_paths($answertext, $question->contextid, 'answer', $answer, 0.6, 200, 'docx');
                    $blocks = offlinequiz_convert_image_docx($answertext);
                    offlinequiz_print_blocks_docx($section, $blocks, $answernumbering, 1);
                }
                if ($offlinequiz->showgrades) {
                    $pointstr = get_string('points', 'grades');
                    if ($question->maxgrade == 1) {
                        $pointstr = get_string('point', 'offlinequiz');
                    }
                    // Indent the question grade like the answers.
                    $textrun = $section->createTextRun($level2);
                    $textrun->addText('(' . ($question->maxgrade + 0) . ' ' . $pointstr . ')', 'bStyle');
                }
            }
            $section->addTextBreak();
            $number++;
        }
    } else {
        // Not shufflequestions.
        // We have to compute the mapping  questionid -> slotnumber.
        $questionslots = array();
        foreach ($slots as $slot) {
            $questionslots[$templateusage->get_question($slot)->id] = $slot;
        }
        // No shufflequestions, so go through the questions as they have been added to the offlinequiz group
        // We also add custom page breaks.
        $currentpage = 1;
        foreach ($questions as $question) {
            // Add page break if set explicitely by teacher.
            if ($question->page > $currentpage) {
                $section->addPageBreak();
                $currentpage++;
            }
            set_time_limit(120);
            // Print the question.
            $questiontext = $question->questiontext;
            // Filter only for tex formulas.
            if (!empty($texfilter)) {
                $questiontext = $texfilter->filter($questiontext);
            }
            // Remove all HTML comments (typically from MS Office).
            $questiontext = preg_replace("/<!--.*?--\\s*>/ms", "", $questiontext);
            // Remove <font> tags.
            $questiontext = preg_replace("/<font[^>]*>[^<]*<\\/font>/ms", "", $questiontext);
            // Remove <script> tags that are created by mathjax preview.
            $questiontext = preg_replace("/<script[^>]*>[^<]*<\\/script>/ms", "", $questiontext);
            // Remove all class info from paragraphs because TCDOCX won't use CSS.
            $questiontext = preg_replace('/<p[^>]+class="[^"]*"[^>]*>/i', "<p>", $questiontext);
            $questiontext = $trans->fix_image_paths($questiontext, $question->contextid, 'questiontext', $question->id, 0.6, 300, 'docx');
            $blocks = offlinequiz_convert_image_docx($questiontext);
            // Description questions are printed without a number because they are not on the answer form.
            if ($question->qtype == 'description') {
                offlinequiz_print_blocks_docx($section, $blocks);
            } else {
                offlinequiz_print_blocks_docx($section, $blocks, $questionnumbering, 0);
            }
            $answernumbering = new PHPWord_Numbering_AbstractNumbering("Adv Multi-level", array(new PHPWord_Numbering_Level("1", PHPWord_Numbering_Level::NUMFMT_DECIMAL, "%1.", "left", $level1), new PHPWord_Numbering_Level("1", PHPWord_Numbering_Level::NUMFMT_LOWER_LETTER, "%2)", "left", $level2)));
            $docx->addNumbering($answernumbering);
            if ($question->qtype == 'multichoice' || $question->qtype == 'multichoiceset') {
                $slot = $questionslots[$question->id];
                // Save the usage slot in the group questions table.
                //                 $DB->set_field('offlinequiz_group_questions', 'usageslot', $slot,
                //                         array('offlinequizid' => $offlinequiz->id,
                //                                 'offlinegroupid' => $group->id, 'questionid' => $question->id));
                // Now retrieve the order of the answers.
                $slotquestion = $templateusage->get_question($slot);
                $attempt = $templateusage->get_question_attempt($slot);
                $order = $slotquestion->get_order($attempt);
                // Order of the answers.
                foreach ($order as $key => $answer) {
                    $answertext = $question->options->answers[$answer]->answer;
                    // Filter only for tex formulas.
                    if (!empty($texfilter)) {
                        $answertext = $texfilter->filter($answertext);
                    }
                    // Remove all HTML comments (typically from MS Office).
                    $answertext = preg_replace("/<!--.*?--\\s*>/ms", "", $answertext);
                    // Remove all paragraph tags because they mess up the layout.
                    $answertext = preg_replace("/<p[^>]*>/ms", "", $answertext);
                    // Remove <script> tags that are created by mathjax preview.
                    $answertext = preg_replace("/<script[^>]*>[^<]*<\\/script>/ms", "", $answertext);
                    $answertext = preg_replace("/<\\/p[^>]*>/ms", "", $answertext);
                    $answertext = $trans->fix_image_paths($answertext, $question->contextid, 'answer', $answer, 0.6, 200, 'docx');
                    $blocks = offlinequiz_convert_image_docx($answertext);
                    offlinequiz_print_blocks_docx($section, $blocks, $answernumbering, 1);
                }
                if ($offlinequiz->showgrades) {
                    $pointstr = get_string('points', 'grades');
                    if ($question->maxgrade == 1) {
                        $pointstr = get_string('point', 'offlinequiz');
                    }
                    // Indent the question grade like the answers.
                    $textrun = $section->createTextRun($level2);
                    $textrun->addText('(' . ($question->maxgrade + 0) . ' ' . $pointstr . ')', 'bStyle');
                }
                $section->addTextBreak();
                $number++;
                // End if multichoice.
            }
        }
        // End forall questions.
    }
    // End else no shufflequestions.
    $fs = get_file_storage();
    $fileprefix = 'form';
    if ($correction) {
        $fileprefix = 'correction';
    }
    srand(microtime() * 1000000);
    $unique = str_replace('.', '', microtime(true) . rand(0, 100000));
    $tempfilename = $CFG->dataroot . '/temp/offlinequiz/' . $unique . '.docx';
    check_dir_exists($CFG->dataroot . '/temp/offlinequiz', true, true);
    if (file_exists($tempfilename)) {
        unlink($tempfilename);
    }
    // Save file.
    $objwriter = PHPWord_IOFactory::createWriter($docx, 'Word2007');
    $objwriter->save($tempfilename);
    // Prepare file record object.
    $timestamp = date('Ymd_His', time());
    $fileinfo = array('contextid' => $context->id, 'component' => 'mod_offlinequiz', 'filearea' => 'pdfs', 'filepath' => '/', 'itemid' => 0, 'filename' => $fileprefix . '-' . strtolower($groupletter) . '_' . $timestamp . '.docx');
    // Delete existing old files, should actually not happen.
    if ($oldfile = $fs->get_file($fileinfo['contextid'], $fileinfo['component'], $fileinfo['filearea'], $fileinfo['itemid'], $fileinfo['filepath'], $fileinfo['filename'])) {
        $oldfile->delete();
    }
    // Create a Moodle file from the temporary file.
    $file = $fs->create_file_from_pathname($fileinfo, $tempfilename);
    // Remove all temporary files.
    unlink($tempfilename);
    $trans->remove_temp_files();
    return $file;
}
예제 #23
0
    public function process_wizard_form_one()
    {
        if ($_POST) {
            // Sanitize form
            $form = $this->toolbox('Sanitize')->form($_POST);
            $this->company = $form['company'];
            $this->url = $form['url'];
            $this->cosultant = $form['consultant'];
            $this->toolbox('session')->set('assessment_company', $form['company']);
            $this->toolbox('session')->set('assessment_url', $form['url']);
            // We want to assemble the file name here in the following format:
            // Intials_Web_Assess_MMDDYY
            // Get the first letter of each word (including hyphenated/underscored words)
            $corpname = preg_split("/[\\s,_ -]+/", $form['company']);
            $initials = "";
            foreach ($corpname as $firstletter) {
                $initials .= $firstletter[0];
            }
            $this->file_name = $initials . '_Web_Assess_' . date("mdY") . $this->file_extension;
            $this->toolbox('session')->set('assessment_file_name', $this->file_name);
            // Now let's create the file
            $file = $this->file_name;
            // Create a new PHPWord Object
            $PHPWord = new PHPWord();
            // Every element you want to append to the word document is placed in a section. So you need a section:
            $section = $PHPWord->createSection();
            // After creating a section, you can append elements:
            $section->addImage('http://www.dynamicartisans.com/area51/public/template/update/assets/images/dynamicartisans-logo-mobi.png', array('width' => 100, 'height' => 100, 'marginTop' => -1, 'marginLeft' => -1, 'wrappingStyle' => 'behind'));
            $section->addTextBreak(1);
            // You can directly style your text by giving the addText function an array:
            $section->addText('sight, sound, color, motion, and emotion.', array('name' => 'Tahoma', 'size' => 12, 'bold' => false));
            // If you often need the same style again you can create a user defined style to the word document
            // and give the addText function the name of the style:
            $PHPWord->addFontStyle('date-style', array('text-align' => 'right', 'size' => 12, 'color' => '1B2232'));
            $section->addText(date("F d, Y"), 'date-style');
            $section->addTextBreak(1);
            $section->addText('Contact:' . $this->company, array('bold' => true));
            #$section->addText( $this->company );
            $section->addText('Consultant:' . $form['consultant'], array('bold' => true));
            #$section->addText( $form['consultant'] );
            $section->addTextBreak(1);
            $section->addText('We took a moment to assess the website for ' . $this->toolbox('session')->get('assessment_company') . ' and these are the observations and
				recommendations from our web development team: ');
            // You can also putthe appended element to local object an call functions like this:
            //$myTextElement = $section->addText('Hello World!');
            //$myTextElement->setBold();
            //$myTextElement->setName('Verdana');
            //$myTextElement->setSize(22);
            // At least write the document to webspace:
            $objWriter = PHPWord_IOFactory::createWriter($PHPWord, 'Word2007');
            $objWriter->save($this->draft_folder . $this->file_name);
            // $this->model('Assessments')->generate_tags( $this->company );
            // Compile form variable tags
            // $this->model('Assessments')->initialize_var_tags( $this->company, $this->url, $form['consultant'], $this->file_name );
            // Track network speeds
            $this->model('Assessments')->network_speed($this->toolbox('Performance')->check_latency_raw($this->toolbox('session')->get('assessment_url')), $this->toolbox('Performance')->check_download_speed_raw($this->toolbox('session')->get('assessment_url')), $this->company);
            // Autosave draft
            $this->save_draft($this->company, $this->file_name, time(), $this->author);
            // Saving wizard -- move on two step two
            if ($this->model('Assessments')->wizard_step_one($this->company, $this->url, $form['first_name'], $form['last_name'], $form['consultant'], $this->file_name, $this->author)) {
                $this->redirect('assessments/wizard/server');
            } else {
                throw new Exception('Error processing request');
            }
        }
    }