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); }
public function postCancelar() { //return Input::all(); $this->response->Cancelar(Input::get('contratos'), Input::get('penaCapital'), Input::get('penaAccesorios'), Input::get('penaMoratorios'), Input::get('capital')); $cliente = DB::table('expediente')->where('id_expediente', Input::get('contratos'))->join('cliente', 'cliente.rfc', '=', 'expediente.fk_rfc')->select('cliente.nombre', 'cliente.ape_mate', 'cliente.ape_pate')->get()[0]; $terreno = DB::table('expediente')->where('id_expediente', Input::get('contratos'))->join('solicitud', 'solicitud.fk_expediente', '=', 'expediente.id_expediente')->join('lote', 'lote.id_lote', '=', 'solicitud.fk_lote')->join('manzana', 'manzana.id_manzana', '=', 'lote.fk_manzana')->join('desarrollo', 'desarrollo.id_desarrollo', '=', 'manzana.fk_desarrollo')->select('lote.lote', 'manzana.num_letra', 'desarrollo.nombre')->get()[0]; if (Input::get('capital') - Input::get('penaCapital') > 0) { $ImporteLiquido = Input::get('capital') - Input::get('penaCapital'); } else { $ImporteLiquido = 0; } $PHPWord = new PHPWord(); $document = $PHPWord->loadTemplate(dirname(__FILE__) . '/PHPWord/recibo_liquidacion.docx'); $fecha = explode('-', date('Y-m-d')); $document->setValue('dia', $fecha[2]); $document->setValue('mes', $fecha[1]); $document->setValue('anio', $fecha[0]); $document->setValue('cantidadDevuelta', '$' . $ImporteLiquido); $document->setValue('expediente', Input::get('contratos')); $document->setValue('Terreno', $terreno->lote); $document->setValue('Manzana', $terreno->num_letra); $document->setValue('Fraccionamiento', $terreno->nombre); $document->setValue('Penalizacion', Input::get('penalizacionCapital') . '%'); $document->setValue('PrecioVenta', '$' . Input::get('importeTotal')); $document->setValue('CapitalPagado', '$' . Input::get('capital')); $document->setValue('cantidadPenal', '$' . Input::get('penaCapital')); $document->setValue('ImporteLiquido', '$' . $ImporteLiquido); $document->setValue('Cliente', $cliente->nombre . " " . $cliente->ape_pate . " " . $cliente->ape_mate); $document->save(Input::get('contratos') . '_cancelacion.docx'); return View::make('cobranza/mensajeCobranza')->with('datos', array('seccion' => 'SICyA | Cobranza | Cancealr Terreno', 'cabecera' => 'Cancelando Contrato', 'icono' => 'glyphicon glyphicon-file', 'tipo_mensaje' => true, 'mensaje' => "Se ha Cancelado el Contrato.")); }
public function writeDocument(PHPWord $pPHPWord = null) { // Create XML writer if ($this->getParentWriter()->getUseDiskCaching()) { $objWriter = new PHPWord_Shared_XMLWriter(PHPWord_Shared_XMLWriter::STORAGE_DISK, $this->getParentWriter()->getDiskCachingDirectory()); } else { $objWriter = new PHPWord_Shared_XMLWriter(PHPWord_Shared_XMLWriter::STORAGE_MEMORY); } // XML header $objWriter->startDocument('1.0', 'UTF-8', 'yes'); // w:document $objWriter->startElement('w:document'); $objWriter->writeAttribute('xmlns:ve', 'http://schemas.openxmlformats.org/markup-compatibility/2006'); $objWriter->writeAttribute('xmlns:o', 'urn:schemas-microsoft-com:office:office'); $objWriter->writeAttribute('xmlns:r', 'http://schemas.openxmlformats.org/officeDocument/2006/relationships'); $objWriter->writeAttribute('xmlns:m', 'http://schemas.openxmlformats.org/officeDocument/2006/math'); $objWriter->writeAttribute('xmlns:v', 'urn:schemas-microsoft-com:vml'); $objWriter->writeAttribute('xmlns:wp', 'http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing'); $objWriter->writeAttribute('xmlns:w10', 'urn:schemas-microsoft-com:office:word'); $objWriter->writeAttribute('xmlns:w', 'http://schemas.openxmlformats.org/wordprocessingml/2006/main'); $objWriter->writeAttribute('xmlns:wne', 'http://schemas.microsoft.com/office/word/2006/wordml'); $objWriter->startElement('w:body'); $_sections = $pPHPWord->getSections(); $countSections = count($_sections); $pSection = 0; if ($countSections > 0) { foreach ($_sections as $section) { $pSection++; $_elements = $section->getElements(); foreach ($_elements as $element) { if ($element instanceof PHPWord_Section_Text) { $this->_writeText($objWriter, $element); } elseif ($element instanceof PHPWord_Section_TextRun) { $this->_writeTextRun($objWriter, $element); } elseif ($element instanceof PHPWord_Section_Link) { $this->_writeLink($objWriter, $element); } elseif ($element instanceof PHPWord_Section_Title) { $this->_writeTitle($objWriter, $element); } elseif ($element instanceof PHPWord_Section_TextBreak) { $this->_writeTextBreak($objWriter); } elseif ($element instanceof PHPWord_Section_PageBreak) { $this->_writePageBreak($objWriter); } elseif ($element instanceof PHPWord_Section_Table) { $this->_writeTable($objWriter, $element); } elseif ($element instanceof PHPWord_Section_ListItem) { $this->_writeListItem($objWriter, $element); } elseif ($element instanceof PHPWord_Section_Image || $element instanceof PHPWord_Section_MemoryImage) { $this->_writeImage($objWriter, $element); } elseif ($element instanceof PHPWord_Section_Object) { $this->_writeObject($objWriter, $element); } elseif ($element instanceof PHPWord_TOC) { $this->_writeTOC($objWriter); } } if ($pSection == $countSections) { $this->_writeEndSection($objWriter, $section); } else { $this->_writeSection($objWriter, $section); } } } $objWriter->endElement(); // End w:body $objWriter->endElement(); // End w:document // Return return $objWriter->getData(); }
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; }
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)); }
/** * Executes index action * * @param sfRequest $request A request object */ public function executeIndex(sfWebRequest $request) { // Recuperar el Tramite y el Proceso $this->setLayout('descarga'); $template = Doctrine::getTable('ClaDocumentos')->findOneByClaTramiteIdAndClaProcesoId($request->getParameter('tramite'), $request->getParameter('proceso')); $seguimiento = Doctrine::getTable('ProcSeguimiento')->getTramite($request->getParameter('seguimiento')); $PHPWord = new PHPWord(); $filename = 'carta_' . $request->getParameter('tramite') . '_' . $request->getParameter('proceso') . '.docx'; $document = $PHPWord->loadTemplate(sfConfig::get('sf_root_dir') . '/archivos/templates/' . $template->getPath()); date_default_timezone_set('America/La_Paz'); setlocale(LC_TIME, 'spanish'); $document->setValue('fecha_carta', strftime("%d de %B de %Y")); foreach ($seguimiento->ProcFormularios as $formulario) { $tabla = Doctrine::getTable($formulario->ClaTabla->getDescripcion())->findOneById($formulario->getGetId()); if ($formulario->ClaTabla->getDescripcion() == 'DatPersonas') { $document->setValue('nombre_estudiante', $tabla->getNombreCompleto()); } } $document->save(sfConfig::get('sf_root_dir') . '/archivos/generados/' . $filename); // $guardar = new ClaDocumentos(); // $guardar->setClaTramiteId(1); // $guardar->setClaProcesoId(1); // $guardar->setPath($filename); // $guardar->save(); $this->filename = $filename; $this->enlace = sfConfig::get('sf_root_dir') . '/archivos/generados//' . $filename; }
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; }
/** * New instance * @param bool $setDefaultProperties initialize instance with default properties * @return PHPWord */ public function getInstance($setDefaultProperties = true) { $phpWord = new PHPWord(); if ($setDefaultProperties) { $phpWord->getDocInfo()->setCreator(ArrayHelper::getValue($this->properties, 'creator'))->setLastModifiedBy(ArrayHelper::getValue($this->properties, 'creator'))->setTitle(ArrayHelper::getValue($this->properties, 'title'))->setSubject(ArrayHelper::getValue($this->properties, 'subject'))->setDescription(ArrayHelper::getValue($this->properties, 'description'))->setKeywords(ArrayHelper::getValue($this->properties, 'keywords'))->setCategory(ArrayHelper::getValue($this->properties, 'category'))->setCompany(ArrayHelper::getValue($this->properties, 'company')); } return $phpWord; }
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); }
/** * Write Meta file to XML format * * @param PHPWord $pPHPWord * @return string XML Output * @throws Exception */ public function writeMeta(PHPWord $pPHPWord = null) { // Create XML writer $objWriter = null; if ($this->getParentWriter()->getUseDiskCaching()) { $objWriter = new PHPWord_Shared_XMLWriter(PHPWord_Shared_XMLWriter::STORAGE_DISK, $this->getParentWriter()->getDiskCachingDirectory()); } else { $objWriter = new PHPWord_Shared_XMLWriter(PHPWord_Shared_XMLWriter::STORAGE_MEMORY); } // XML header $objWriter->startDocument('1.0', 'UTF-8'); // office:document-meta $objWriter->startElement('office:document-meta'); $objWriter->writeAttribute('xmlns:office', 'urn:oasis:names:tc:opendocument:xmlns:office:1.0'); $objWriter->writeAttribute('xmlns:xlink', 'http://www.w3.org/1999/xlink'); $objWriter->writeAttribute('xmlns:dc', 'http://purl.org/dc/elements/1.1/'); $objWriter->writeAttribute('xmlns:meta', 'urn:oasis:names:tc:opendocument:xmlns:meta:1.0'); $objWriter->writeAttribute('xmlns:ooo', 'http://openoffice.org/2004/office'); $objWriter->writeAttribute('xmlns:grddl', 'http://www.w3.org/2003/g/data-view#'); $objWriter->writeAttribute('office:version', '1.2'); // office:meta $objWriter->startElement('office:meta'); // dc:creator $objWriter->writeElement('dc:creator', $pPHPWord->getProperties()->getLastModifiedBy()); // dc:date $objWriter->writeElement('dc:date', gmdate('Y-m-d\\TH:i:s.000', $pPHPWord->getProperties()->getModified())); // dc:description $objWriter->writeElement('dc:description', $pPHPWord->getProperties()->getDescription()); // dc:subject $objWriter->writeElement('dc:subject', $pPHPWord->getProperties()->getSubject()); // dc:title $objWriter->writeElement('dc:title', $pPHPWord->getProperties()->getTitle()); // meta:creation-date $objWriter->writeElement('meta:creation-date', gmdate('Y-m-d\\TH:i:s.000', $pPHPWord->getProperties()->getCreated())); // meta:initial-creator $objWriter->writeElement('meta:initial-creator', $pPHPWord->getProperties()->getCreator()); // meta:keyword $objWriter->writeElement('meta:keyword', $pPHPWord->getProperties()->getKeywords()); // @todo : Where these properties are written ? // $pPHPWord->getProperties()->getCategory() // $pPHPWord->getProperties()->getCompany() $objWriter->endElement(); $objWriter->endElement(); // Return return $objWriter->getData(); }
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; }
function createDoc($name = null) { $PHPWord = new PHPWord(); //return; $this->getData(); $template = $PHPWord->loadTemplate($this->modelliDir . $this->modello); foreach ($this->data as $tb => $data) { foreach ($data as $col => $val) { try { $val = mb_detect_encoding($val) == 'UTF-8' ? utf8_decode($val) : $val; $template->setValue("{$tb}.{$col}", $val); } catch (Exception $e) { echo "<p>{$tb}.{$col}</p>"; } } } $template->setValue("data", date("d/m/Y")); $pr = new pratica($this->pratica); $file = $name ? $pr->documenti . $name : $pr->documenti . $this->docName; $template->save($file); }
/** * create new excel document * * @return void */ protected function _createDocument() { // this looks stupid, but the PHPDoc library is beta, so this is needed. otherwise the lib would create temp files in the template folder ;( $templateFile = $this->_getTemplateFilename(); $tempTemplateFile = Tinebase_Core::guessTempDir() . DIRECTORY_SEPARATOR . Tinebase_Record_Abstract::generateUID() . '.docx'; copy($templateFile, $tempTemplateFile); $this->_docObject = new PHPWord(); if ($templateFile !== NULL) { $this->_docTemplate = $this->_docObject->loadTemplate($tempTemplateFile); } unlink($tempTemplateFile); }
/** * * @param PHPWord $PHPWord * @return string */ public function writeDocument(PHPWord $PHPWord = null) { $numbering = $PHPWord->getNumbering(); // Create XML writer if ($this->getParentWriter()->getUseDiskCaching()) { $objWriter = new PHPWord_Shared_XMLWriter(PHPWord_Shared_XMLWriter::STORAGE_DISK, $this->getParentWriter()->getDiskCachingDirectory()); } else { $objWriter = new PHPWord_Shared_XMLWriter(PHPWord_Shared_XMLWriter::STORAGE_MEMORY); } // XML header $objWriter->startDocument('1.0', 'UTF-8', 'yes'); // START w:numbering $objWriter->startElement('w:numbering'); $objWriter->writeAttribute('xmlns:ve', 'http://schemas.openxmlformats.org/markup-compatibility/2006'); $objWriter->writeAttribute('xmlns:o', 'urn:schemas-microsoft-com:office:office'); $objWriter->writeAttribute('xmlns:r', 'http://schemas.openxmlformats.org/officeDocument/2006/relationships'); $objWriter->writeAttribute('xmlns:m', 'http://schemas.openxmlformats.org/officeDocument/2006/math'); $objWriter->writeAttribute('xmlns:v', 'urn:schemas-microsoft-com:vml'); $objWriter->writeAttribute('xmlns:wp', 'http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing'); $objWriter->writeAttribute('xmlns:w10', 'urn:schemas-microsoft-com:office:word'); $objWriter->writeAttribute('xmlns:w', 'http://schemas.openxmlformats.org/wordprocessingml/2006/main'); $objWriter->writeAttribute('xmlns:wne', 'http://schemas.microsoft.com/office/word/2006/wordml'); // Write all of the abstractNum elements foreach ($numbering as $key => $value) { $value->toXml($objWriter); } // Write all of the num elements foreach ($numbering as $key => $value) { $objWriter->startElement('w:num'); $objWriter->writeAttribute("w:numId", $key + 1); $objWriter->startElement('w:abstractNumId'); $objWriter->writeAttribute("w:val", $key + 1); $objWriter->endElement(); $objWriter->endElement(); } // END w:numbering $objWriter->endElement(); return $objWriter->getData(); }
public Function GeraArquivoDoc() { $PHPWord = new PHPWord(); $arquivo_clinica = "../../../sgmo/laudo_modelo/$MY_PARAMETRO_ID/normal/$arquivo_laudo"; $document = $PHPWord->loadTemplate($arquivo_clinica); //caso seja necessário preencher o cabeçalho com os dados da clínica $document->setValue('nome_emp', " $clinica_rs"); $document->setValue('cnpj_emp', " $clinica_cnpj"); $document->setValue('rua_emp', " $endereco"); $document->setValue('tel_emp', " $tel_clinica"); $document->setValue('cidade_emp', " $cidade"); $document->setValue('estado_emp', " $estado"); //Dados do funcinário para preencher o cabeçalho $document->setValue('nome_func', " $funcionario"); $document->setValue('doc_func', " $doc_funcionario"); $document->setValue('empresa_func', " $empresa"); $document->setValue('dat_func', " $data_nascimento"); $document->setValue('func_funcionario', " $funcao"); $document->setValue('idade_func', " $idade"); $document->setValue('tel_func', " $telefone"); $document->setValue('idade_func', " $idade"); $document->setValue('data_exame_func', " $data_exame"); $document->setValue('medico_solicitante', " "); $document->setValue('medico_solicitante', " "); $document->setValue('convenio_func', " $clinica_rs"); $document->setValue('observacao', " XXXXXXXXXXXXXXXXXXXXXX"); //Marcações no documento $document->setValue('nx', "X"); $nome_arquivo = $funcionario . "_" . $numero_ficha; $arquivo = "laudados/" . removerAcento($nome_arquivo) . ".docx"; $document->save($arquivo); }
public function generate($id = 0) { $this->load->library('PHPWord'); $this->load->helper('util'); $date = date('Y-m-d_H-i-s'); //if ($id==0); $data = $this->db->where('id_permohonan_peng_data', $id)->join($this->cms_complete_table_name('mas_jurusan'), 'id_jurusan=fk_id_jurusan')->get($this->cms_complete_table_name('permohonan_peng_data'))->result(); $PHPWord = new PHPWord(); //Generate Document foreach ($data as $d) { $document = $PHPWord->loadTemplate('assets/surat_keluar/Permohonan Pengambilan Data/peng_data.docx'); $document->setValue('nomor_surat', $d->nomor_surat); $document->setValue('lampiran', $d->lampiran); $document->setValue('kepada', $d->kepada); $document->setValue('di', $d->di); $document->setValue('nama_mahasiswa', $d->nama_mahasiswa); $document->setValue('npm', $d->npm); $document->setValue('jurusan', $d->nama_jurusan); $document->setValue('ketua_jurusan', $d->ketua_jurusan); $document->setValue('tanggal', tanggal(date('d-m-Y'))); $document->setValue('bulan', bulan_romawi(date('m'))); $document->setValue('tahun', date('Y')); ////open file//// $objWriter = PHPWord_IOFactory::createWriter($PHPWord, 'Word2007'); $filename = $d->npm . '-Surat_Permohonan_Peng_Data.docx'; $document->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//// }
<?php require_once '../PHPWord.php'; // New Word Document $PHPWord = new PHPWord(); // New portrait section $section = $PHPWord->createSection(); // Define table style arrays $styleTable = array('borderSize' => 6, 'borderColor' => '006699', 'cellMargin' => 80); $styleFirstRow = array('borderBottomSize' => 18, 'borderBottomColor' => '0000FF', 'bgColor' => '66BBFF'); // Define cell style arrays $styleCell = array('valign' => 'center'); $styleCellBTLR = array('valign' => 'center', 'textDirection' => PHPWord_Style_Cell::TEXT_DIR_BTLR); // Define font style for first row $fontStyle = array('bold' => true, 'align' => 'center'); // Add table style $PHPWord->addTableStyle('myOwnTableStyle', $styleTable, $styleFirstRow); // Add table $table = $section->addTable('myOwnTableStyle'); // Add row $table->addRow(900); // Add cells $table->addCell(2000, $styleCell)->addText('Row 1', $fontStyle); $table->addCell(2000, $styleCell)->addText('Row 2', $fontStyle); $table->addCell(2000, $styleCell)->addText('Row 3', $fontStyle); $table->addCell(2000, $styleCell)->addText('Row 4', $fontStyle); $table->addCell(500, $styleCellBTLR)->addText('Row 5', $fontStyle); // Add more rows / cells for ($i = 1; $i <= 10; $i++) { $table->addRow(); $table->addCell(2000)->addText("Cell {$i}");
<?php require_once '../PHPWord.php'; // New Word Document $PHPWord = new PHPWord(); // New portrait section $section = $PHPWord->createSection(); // Add style definitions $PHPWord->addParagraphStyle('pStyle', array('spacing' => 100)); $PHPWord->addFontStyle('BoldText', array('bold' => true)); $PHPWord->addFontStyle('ColoredText', array('color' => 'FF8080')); $PHPWord->addLinkStyle('NLink', array('color' => '0000FF', 'underline' => PHPWord_Style_Font::UNDERLINE_SINGLE)); // Add text elements $textrun = $section->createTextRun('pStyle'); $textrun->addText('Each textrun can contain native text or link elements.'); $textrun->addText(' No break is placed after adding an element.', 'BoldText'); $textrun->addText(' All elements are placed inside a paragraph with the optionally given p-Style.', 'ColoredText'); $textrun->addText(' The best search engine: '); $textrun->addLink('http://www.google.com', null, 'NLink'); $textrun->addText('. Also not bad: '); $textrun->addLink('http://www.bing.com', null, 'NLink'); // Save File $objWriter = PHPWord_IOFactory::createWriter($PHPWord, 'Word2007'); $objWriter->save('Textrun.docx');
<?php require_once '../PHPWord.php'; // New Word Document $PHPWord = new PHPWord(); // New portrait section $section = $PHPWord->createSection(); // Add hyperlink elements $section->addLink('http://www.google.com', 'Best search engine', array('color' => '0000FF', 'underline' => PHPWord_Style_Font::UNDERLINE_SINGLE)); $section->addTextBreak(2); $PHPWord->addLinkStyle('myOwnLinkStyle', array('bold' => true, 'color' => '808000')); $section->addLink('http://www.bing.com', null, 'myOwnLinkStyle'); $section->addLink('http://www.yahoo.com', null, 'myOwnLinkStyle'); // Save File $objWriter = PHPWord_IOFactory::createWriter($PHPWord, 'Word2007'); $objWriter->save('Link.docx');
<?php require APPPATH . 'third_party/PHPWord/PHPWord.php'; $PHPWord = new PHPWord(); $section = $PHPWord->createSection(); $PHPWord->addTableStyle('schedule_billdoc', array('borderSize' => 1, 'borderColor' => '333', 'cellMargin' => 100)); $table = $section->addTable('schedule_billdoc'); foreach ($document_catalog as $doctype) { $table->addRow(); $table->addCell(1500)->addText($doctype); $table->addCell(8000); } // Save File $objWriter = PHPWord_IOFactory::createWriter($PHPWord, 'Word2007'); $filename = $_SESSION['username'] . $this->date->now . '.docx'; $path = iconv('utf-8', 'gbk', 'temp/' . $filename); $objWriter->save($path); document_exportHead($filename); readfile($path); unlink($path); exit;
public function hoja_tramite() { $doc = $this->input->get_post('doc'); $nrodoc = $this->input->get_post('nrodoc'); $ini = $this->input->get_post('ini'); $fin = $this->input->get_post('fin'); $estado = "Dar Tramite"; $estado1 = "Dar Tramite"; $origen = "Tramite Documentario"; $origen1 = "Tramite Documentario"; if ($nrodoc % 2 == 0) { $doc1 = $nrodoc - 1; $doc2 = $nrodoc; } else { $doc1 = $nrodoc; $doc2 = $nrodoc + 1; } $filter = new stdClass(); $filter_not = new stdClass(); $filter->tipo_doc = $doc; $filter->nrodoc = $doc1; $filter->fecha_ini = str_replace('/', '-', $ini); $filter->fecha_fin = str_replace('/', '-', $fin); $var = $this->documento_model->listarDocumentoMovimiento($filter, $filter_not); $filter->tipo_doc = $doc; $filter->nrodoc = $doc2; $filter->fecha_ini = str_replace('/', '-', $ini); $filter->fecha_fin = str_replace('/', '-', $fin); $var1 = $this->documento_model->listarDocumentoMovimiento($filter, $filter_not); if ($var == "0") { $var = '[{"nroTramite":"","dependenciaMovimiento":"","tipo":"","fechaCreada":""}]'; $var = json_decode($var); $estado = ""; $origen = ""; } if ($var1 == "0") { $var1 = '[{"nroTramite":"","dependenciaMovimiento":"","tipo":"","fechaCreada":""}]'; $var1 = json_decode($var1); $estado1 = ""; $origen1 = ""; } $PHPWord = new PHPWord(); //Searching for values to replace $document = $PHPWord->loadTemplate('./plantilla/plantilla01.docx'); $document->setValue('Tramite', $var[0]->nroTramite); $document->setValue('Tramite2', $var1[0]->nroTramite); $document->setValue('Gerencia', $origen); $document->setValue('Gerencia2', $origen1); $document->setValue('Dependencia', $var[0]->dependenciaMovimiento); $document->setValue('Dependencia2', $var1[0]->dependenciaMovimiento); $document->setValue('Tipo', $var[0]->tipo); $document->setValue('Tipo2', $var1[0]->tipo); $document->setValue('Fecha', $var[0]->fechaCreada == "" ? "" : date('d/m/Y', strtotime($var[0]->fechaCreada))); $document->setValue('Fecha2', $var1[0]->fechaCreada == "" ? "" : date('d/m/Y', strtotime($var1[0]->fechaCreada))); $document->setValue('Estado', $estado); $document->setValue('Estado2', $estado1); // save as a random file in temp file $temp_file = tempnam(sys_get_temp_dir(), 'PHPWord'); $document->save($temp_file); header("Content-Disposition: attachment; filename='hoja_tramite.doc'"); header("Content-Type: application/vnd.ms-word; charset=utf-8"); readfile($temp_file); // or echo file_get_contents($temp_file); unlink($temp_file); // remove temp file }
<?php require_once '../PHPWord.php'; // New Word Document $PHPWord = new PHPWord(); // New portrait section $section = $PHPWord->createSection(); // Define the TOC font style $fontStyle = array('spaceAfter' => 60, 'size' => 12); // Add title styles $PHPWord->addTitleStyle(1, array('size' => 20, 'color' => '333333', 'bold' => true)); $PHPWord->addTitleStyle(2, array('size' => 16, 'color' => '666666')); // Add text elements $section->addText('Table of contents:'); $section->addTextBreak(2); // Add TOC $section->addTOC($fontStyle); // Add Titles $section->addPageBreak(); $section->addTitle('I am Title 1', 1); $section->addText('Some text...'); $section->addTextBreak(2); $section->addTitle('I am a Subtitle of Title 1', 2); $section->addTextBreak(2); $section->addText('Some more text...'); $section->addTextBreak(2); $section->addTitle('Another Title (Title 2)', 1); $section->addText('Some text...'); $section->addPageBreak(); $section->addTitle('I am Title 3', 1); $section->addText('And more text...');
$_etapas = obtenerEtapasFuncion($idDiseno, $conexion); $_actividades_etapa1 = obtenerActividadesPorEtapaFuncion($_etapas[0]['e_id_etapa'], $conexion); $_actividades_etapa2 = obtenerActividadesPorEtapaFuncion($_etapas[1]['e_id_etapa'], $conexion); $_actividades_etapa3 = obtenerActividadesPorEtapaFuncion($_etapas[2]['e_id_etapa'], $conexion); $totalEtapa1 = count($_actividades_etapa1); $totalEtapa2 = count($_actividades_etapa2); $totalEtapa3 = count($_actividades_etapa3); $maxActividades = $totalEtapa1; if ($totalEtapa2 > $maxActividades) { $maxActividades = $totalEtapa2; } if ($totalEtapa3 > $maxActividades) { $maxActividades = $totalEtapa3; } // New Word Document $PHPWord = new PHPWord(); $properties = $PHPWord->getProperties(); $properties->setCreator('Kelluwen'); $properties->setCompany('Kelluwen'); $_estilo_titulo = array('name' => 'Verdana', 'color' => '000000'); $_estilo_titulo_form_diseno = array('bold' => true); $_estilo_titulo_actividad = array('bold' => true); // New portrait section $section = $PHPWord->createSection(); $sectionStyle = $section->getSettings(); // Add header $header = $section->createHeader(); $styleTable = array('borderColor' => '006699', 'borderSize' => 2); $styleFirstRow = array('bgColor' => '66BBFF'); $PHPWord->addTableStyle('myTable', $styleTable, $styleFirstRow); $table = $header->addTable();
</div> </div> </div> </div> <?php include "view/default/footer.php"; ?> </div> <!-- /container --> </body> </html> <?php $PHPWord = new PHPWord(); //untuk bersama $qWhere = array("kode" => $KODE); $data = $MHS->readMahasiswa($qWhere); $jData = count($data); if ($data != "") { $jData = count($data); } else { $jData = 0; } if ($jData > 0) { $mahasiswa_idmahasiswa = $data['idmahasiswa']; } $query_ijin = array("mahasiswa_idmahasiswa" => $mahasiswa_idmahasiswa); $hasil_ijin = $IJIN->readIjin($query_ijin); $file = $hasil_ijin['file'];
<?php require_once '../PHPWord.php'; // New Word Document $PHPWord = new PHPWord(); // New portrait section $section = $PHPWord->createSection(); // Add listitem elements $section->addListItem('List Item 1', 0); $section->addListItem('List Item 2', 0); $section->addListItem('List Item 3', 0); $section->addTextBreak(2); // Add listitem elements $section->addListItem('List Item 1', 0); $section->addListItem('List Item 1.1', 1); $section->addListItem('List Item 1.2', 1); $section->addListItem('List Item 1.3 (styled)', 1, array('bold' => true)); $section->addListItem('List Item 1.3.1', 2); $section->addListItem('List Item 1.3.2', 2); $section->addTextBreak(2); // Add listitem elements $listStyle = array('listType' => PHPWord_Style_ListItem::TYPE_NUMBER); $section->addListItem('List Item 1', 0, null, $listStyle); $section->addListItem('List Item 2', 0, null, $listStyle); $section->addListItem('List Item 3', 0, null, $listStyle); $section->addTextBreak(2); // Add listitem elements $PHPWord->addFontStyle('myOwnStyle', array('color' => 'FF0000')); $PHPWord->addParagraphStyle('P-Style', array('spaceAfter' => 95)); $listStyle = array('listType' => PHPWord_Style_ListItem::TYPE_NUMBER_NESTED); $section->addListItem('List Item 1', 0, 'myOwnStyle', $listStyle, 'P-Style');
<?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');
/** * 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());
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_kelakuan_baik', $id)->join($this->cms_complete_table_name('mas_jurusan'), 'id_jurusan=fk_id_jurusan')->get($this->cms_complete_table_name('kelakuan_baik'))->result(); $PHPWord = new PHPWord(); //Generate Document foreach ($data as $d) { $document = $PHPWord->loadTemplate('assets/surat_keluar/Ket. Kelakuan Baik/kelakuan_baik.docx'); $document->setValue('nomor_surat', $d->nomor_surat); $document->setValue('nama_mahasiswa', $d->nama_mahasiswa); $document->setValue('npm', $d->npm); $document->setValue('tempat_lahir', $d->tempat_lahir); $document->setValue('tanggal_lahir', tanggal(date($d->tanggal_lahir))); $document->setValue('jurusan', $d->nama_jurusan); $document->setValue('semester', $d->semester); $document->setValue('tahun_akademis', $d->tahun_akademis); $document->setValue('tanggal', tanggal(date('d-m-Y'))); $document->setValue('bulan', bulan_romawi(date('m'))); $document->setValue('tahun', date('Y')); foreach ($conf as $c) { $document->setValue('nama_instansi', $c->nama_instansi); $document->setValue('alamat', $c->alamat); $document->setValue('status_akreditasi', $c->status_akreditasi); $document->setValue('nama_puket', $c->nama_puket); $document->setValue('pangkat_puket', $c->pangkat_puket); } ////open file//// $objWriter = PHPWord_IOFactory::createWriter($PHPWord, 'Word2007'); $filename = $d->npm . '-Surat_Kelakuan_Baik.docx'; $document->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//// }
<?php // examples header("Content-type: text/html; charset=utf-8"); require_once '../PHPWord.php'; $PHPWord = new PHPWord(); $document = $PHPWord->loadTemplate('source.docx'); // simple parsing $document->setValue('{var1}', 'value'); $document->setValue('{var2}', 'Clone'); $document->setValue('{var3}', 'ONE', 1); // prepare data for tables $data1 = array('num' => array(1, 2, 3), 'color' => array('red', 'blue', 'green'), 'code' => array('ff0000', '0000ff', '00ff00')); $data2 = array('val1' => array(1, 2, 3), 'val2' => array('red', 'blue', 'green'), 'val3' => array('a', 'b', 'c')); $data3 = array('day' => array('Mon', 'Tue', 'Wed', 'Thu', 'Fri'), 'dt' => array(12, 14, 13, 11, 10), 'nt' => array(0, 2, 1, 2, -1), 'dw' => array('SSE at 3 mph', 'SE at 2 mph', 'S at 3 mph', 'S at 1 mph', 'Calm'), 'nw' => array('SSE at 1 mph', 'SE at 1 mph', 'S at 1 mph', 'Calm', 'Calm')); $data4 = array('val1' => array('blue 1', 'blue 2', 'blue 3'), 'val2' => array('green 1', 'green 2', 'green 3'), 'val3' => array('red 1', 'red 2', 'red 3')); // clone rows $document->cloneRow('TBL1', $data1); $document->cloneRow('TBL2', $data2); $document->cloneRow('DATA3', $data3); $document->cloneRow('T4', $data4); $document->cloneRow('DinamicTable', $data4); // save file $tmp_file = 'result.docx'; $document->save($tmp_file); print date("Y-m-d H:i:s") . " <br>"; print "source.docx → result.docx <br>"; print "complete.";
<?php require_once 'PHPWord.php'; $PHPWord = new PHPWord(); $document = $PHPWord->loadTemplate('Templateku.docx'); foreach ($lhs as $row) { $typekendaraan = $row->type_kendaraan; $modelkendaraan = $row->model_kendaraan; $nopolisi = $row->no_polisi; $nokuasa = $row->no_kuasa; $tglkuasa = date("d-M-Y", strtotime($row->terbit_kuasa)); $nm_asuransi = $row->nm_asuransi; $id = $row->id_surat_tugas; $terimakuasa = date("d-M-Y", strtotime($row->terima_kuasa)); $nmtertanggung = $row->nm_tertanggung; $almt_tertanggung = $row->almt_tertanggung; $nopolis = $row->no_polis; $tglberlaku = date("d-M-Y", strtotime($row->tgl_berlaku)); $tglkedaluwarsa = date("d-M-Y", strtotime($row->tgl_kedaluwarsa)); $surveyor = $row->nm_surveyor; $ket = $row->uraian_singkat; $saksi1 = $row->saksi1; $almt_saksi1 = $row->almt_saksi1; $ket_saksi1 = $row->ket_saksi1; $saksi2 = $row->saksi2; $almt_saksi2 = $row->almt_saksi2; $ket_saksi2 = $row->ket_saksi2; $saksi3 = $row->saksi3; $almt_saksi3 = $row->almt_saksi3; $ket_saksi3 = $row->ket_saksi3; $saksi4 = $row->saksi4;