function createFile($dt) { // cleanup old prog files $oldPdfs = glob("files/prog_" . $dt['id'] . "*.html"); foreach ($oldPdfs as $target) { unlink($target); } // load PhpWord & mpdf libraries via composer require_once 'vendor/autoload.php'; // load, alter and save new docx based on template $templ = new \PhpOffice\PhpWord\TemplateProcessor('files/tmpl.docx'); foreach ($dt as $k => $v) { $templ->setValue("{$k}", htmlspecialchars($v)); } $docxFile = "files/exp_" . $dt['id'] . ".docx"; $templ->saveAs($docxFile); // prepare PDF renderer (unused because of high overhead for sch.gr servers - left as a paradigm) //\PhpOffice\PhpWord\Settings::setPdfRendererPath(realpath(__DIR__ . '/vendor/mpdf/mpdf/')); //\PhpOffice\PhpWord\Settings::setPdfRendererName('MPDF'); // open the new docx $phpWord = \PhpOffice\PhpWord\IOFactory::load($docxFile); $random = rand(1000, 3000); // add a window.print() section @ end of HTML $section = $phpWord->addSection(); $section->addText('<script>window.print();</script>'); // save HTML with a random number on filename $fileLink = 'files/prog_' . $dt['id'] . $random . '.html'; $phpWord->save($fileLink, 'HTML'); // save PDF (unused - see above) //$fileLink = 'files/prog_'.$dt['id'].$random.'.pdf'; //$phpWord->save($fileLink, 'PDF'); // delete docx unlink($docxFile); return $fileLink; }
<?php include_once 'Sample_Header.php'; // Read contents $name = basename(__FILE__, '.php'); $source = __DIR__ . "/test.docx"; //echo date('H:i:s'), " Reading contents from `{$source}`", EOL; $phpWord = \PhpOffice\PhpWord\IOFactory::load($source); $sections = $phpWord->getSections(); //foreach($sections as $section){ // $elements = $section->getElements(); // var_dump($elements); //} $elements = $sections[0]->getElements(); var_dump($elements); // Save file //echo write($phpWord, basename(__FILE__, '.php'), $writers); //if (!CLI) { // include_once 'Sample_Footer.php'; //}
function readDocument($path){ $conf =& JFactory::getConfig(); $tmp_path = $conf->getValue('config.tmp_path'); $acceptableFiles = array( 'application/msword' => "doc",//doc 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' => "docx",//docx, 'application/pdf' => "pdf" //pdf ); $finfo = finfo_open(FILEINFO_MIME_TYPE); $file_extension = finfo_file($finfo, $path); finfo_close($finfo); if(array_key_exists($file_extension, $acceptableFiles)){ if($acceptableFiles[$file_extension] == "doc" || $acceptableFiles[$file_extension] == "docx"){ require_once 'libraries/PHPWord-master/src/PhpWord/Autoloader.php'; \PhpOffice\PhpWord\Autoloader::register(); $phpWord = \PhpOffice\PhpWord\IOFactory::load($path); $result = $this->write($phpWord, "temp", array('HTML' => 'html'),$tmp_path); $contents = file_get_contents($tmp_path.'/temp.html', true); }else if($acceptableFiles[$file_extension] == "pdf"){ include 'libraries/pdfparser/vendor/autoload.php'; $parser = new \Smalot\PdfParser\Parser(); $pdf = $parser->parseFile($path); $contents = $pdf->getText(); } } return $contents; }
protected function createReader() { try { return IOFactory::load($this->filename, "MsDoc"); } catch (Exception $error) { // check set_error_handler on top throw new ParseException($error); } }
public function _testReadWriteCycleSucks() { PhpWord\Settings::setTempDir(Tinebase_Core::getTempDir()); $source = str_replace('tests/tine20', 'tine20', __DIR__) . '/templates/addressbook_contact_letter.docx'; $phpWord = PhpWord\IOFactory::load($source); $tempfile = tempnam(Tinebase_Core::getTempDir(), __METHOD__ . '_') . '.docx'; $writer = $phpWord->save($tempfile); `open {$tempfile}`; }
<?php include_once 'Sample_Header.php'; // Read contents $name = basename(__FILE__, '.php'); $source = realpath(__DIR__ . "/resources/{$name}.html"); echo date('H:i:s'), " Reading contents from `{$source}`", EOL; $phpWord = \PhpOffice\PhpWord\IOFactory::load($source, 'HTML'); // Save file echo write($phpWord, basename(__FILE__, '.php'), $writers); if (!CLI) { include_once 'Sample_Footer.php'; }
/** * generate doc * @var array $params */ public function generateDoc($params) { Yii::$app->user->identity = \app\models\User::findIdentityByAccessToken($params['template']['key']); header("Content-Description: File Transfer"); header('Content-Transfer-Encoding: binary'); header('Cache-Control: must-revalidate, post-check=0, pre-check=0'); header('Expires: 0'); switch ($params['template']['format']) { case 'PDF': $file = Yii::$app->user->id . '_temp.pdf'; $writeFormat = 'PDF'; PhpWordSettings::setPdfRendererPath(dirname(__DIR__) . '/../../../vendor/tecnickcom/tcpdf'); PhpWordSettings::setPdfRendererName('TCPDF'); header('Content-Type: application/pdf'); break; case 'Word2013': $file = Yii::$app->user->id . '_temp.docx'; $writeFormat = 'Word2013'; header('Content-Type: application/vnd.openxmlformats-officedocument.wordprocessingml.document'); break; default: $file = Yii::$app->user->id . '_temp.doc'; $writeFormat = 'Word2007'; header('Content-Type: application/vnd.openxmlformats-officedocument.wordprocessingml.document'); break; } header('Content-Disposition: attachment; filename="' . $file . '"'); $document = new TemplateProcessor(dirname(__DIR__) . '/../../../files/' . $this->id . '/' . $this->template_file); /** * process the fields, that have been send through the rest interface */ foreach ($params['template']['fields'] as $field) { foreach ($field as $key => $value) { $document->setValue($key, UTF8encoding::fixUTF8($value)); } } /** * process the tables, that have been send through the rest interface */ foreach ($params['template']['tables'] as $tables) { foreach ($tables as $name => $rows) { //first we create a clone for the master row $document->cloneRow($name, count($rows)); //our walking variable for the table $ii = 1; foreach ($rows as $row) { foreach ($row as $cell) { $document->setValue(key($cell) . '#' . $ii, current($cell)); } $ii++; } } } // save as a random file in temp file $temp_file = tempnam(sys_get_temp_dir(), $file); $document->saveAs($temp_file); switch ($params['template']['format']) { case 'PDF': $phpWord = IOFactory::load($temp_file); $xmlWriter = IOFactory::createWriter($phpWord, $writeFormat); $xmlWriter->save("php://output"); break; case 'Word2007': $phpWord = IOFactory::load($temp_file); $xmlWriter = IOFactory::createWriter($phpWord, $writeFormat); $xmlWriter->save("php://output"); break; default: readfile($temp_file); break; } unlink($temp_file); $LogEvent = new TemplateEvent(); $LogEvent->aTemplateCreated(Yii::$app->user->identity->username, $this->id); \Yii::$app->end(); }
/** * Load */ public function testLoad() { $fqFilename = join(DIRECTORY_SEPARATOR, array(PHPWORD_TESTS_BASE_DIR, 'PhpWord', 'Tests', '_files', 'documents', 'reader.docx')); $object = IOFactory::load($fqFilename); $this->assertInstanceOf('PhpOffice\\PhpWord\\PhpWord', $object); }
/** * @param array $path docx/odt file path * @param string $type File type * * @return array * Return extracted content of document in HTML and document type */ public static function docReader($path, $type) { $type = array_search($type, CRM_Core_SelectValues::documentApplicationType()); $fileType = $type == 'docx' ? 'Word2007' : 'ODText'; $phpWord = \PhpOffice\PhpWord\IOFactory::load($path, $fileType); $phpWordHTML = new \PhpOffice\PhpWord\Writer\HTML($phpWord); // return the html content for tokenreplacment and eventually used for document download return array($phpWordHTML->getWriterPart('Body')->write(), $type); }
<?php include_once 'Sample_Header.php'; // Read contents $name = basename(__FILE__, '.php'); $source = "resources/{$name}.doc"; echo date('H:i:s'), " Reading contents from `{$source}`", EOL; $phpWord = \PhpOffice\PhpWord\IOFactory::load($source, 'MsDoc'); // (Re)write contents $writers = array('Word2007' => 'docx', 'ODText' => 'odt', 'RTF' => 'rtf'); foreach ($writers as $writer => $extension) { echo date('H:i:s'), " Write to {$writer} format", EOL; $xmlWriter = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord, $writer); $xmlWriter->save("{$name}.{$extension}"); rename("{$name}.{$extension}", "results/{$name}.{$extension}"); } include_once 'Sample_Footer.php';
/** * Test load exception * * @expectedException \Exception * @expectedExceptionMessage Cannot read */ public function testLoadException() { $filename = __DIR__ . '/../_files/documents/foo.rtf'; IOFactory::load($filename, 'RTF'); }
public function actionExport($id) { $templateFilepath = dirname(__FILE__) . '/../runtime/templates/Template2.docx'; $source = dirname(__FILE__) . '/../runtime/temp.docx'; \PhpOffice\PhpWord\Autoloader::register(); $templateProcessor = new \PhpOffice\PhpWord\TemplateProcessor($templateFilepath); $months = ['Січня', 'Лютого', 'Березня', 'Квітня', 'Травня', 'Червня', 'Липня', 'Серпня', 'Вересня', 'Жовтня', 'Листопада', 'Грудня']; $date = getdate(); $currentDate = $date['mday'] . ' ' . $months[$date['mon'] - 1] . ' ' . $date['year'] . ' року'; $extractNumber = '№' . $date['mday'] . ($date['mon'] - 1) . substr($date['year'], -2); $templateProcessor->setValue('date', $currentDate); $templateProcessor->setValue('number', $extractNumber); $templateProcessor->saveAs($source); $phpWord = \PhpOffice\PhpWord\IOFactory::load($source); //$phpWord = new \PhpOffice\PhpWord\PhpWord(); $phpWord->setDefaultFontName('Times New Roman'); $phpWord->setDefaultFontSize(11); $sectionStyle = ['marginTop' => 1000]; $tableStyle = ['borderSize' => 6, 'borderColor' => '000', 'cellMargin' => 0]; $innerTableStyle = ['cellMargin' => 20]; $boldFontStyle = ['bold' => true]; $italicFontStyle = ['italic' => true]; $styleCell = ['valign' => 'center']; $styleCellBTLR = ['valign' => 'center', 'textDirection' => \PhpOffice\PhpWord\Style\Cell::TEXT_DIR_BTLR]; $innerTableCellStyle = ['borderRightSize' => 6, 'borderRightColor' => '000', 'borderLeftSize' => 6, 'borderLeftColor' => '000', 'borderBottomSize' => 6, 'borderBottomColor' => '000']; $innerTableRightCellStyle = ['borderLeftSize' => 6, 'borderLeftColor' => '000', 'borderBottomSize' => 6, 'borderBottomColor' => '000']; $innerTableFontStyle = ['size' => 9]; $innerTableParagraphStyle = ['align' => 'center']; // Get resource data $resource = Resource::findOne($id); $filename = $resource->name . '.docx'; $coordinates = json_decode($resource->coordinates); $owner_name = 'народ України (Український народ)'; $resource_class = 'природний ресурс'; $resource_subclass = ResourceClass::findOne($resource->class_id)->name; $creation_date = $resource->date; $registrar = PersonalData::findOne($resource->registrar_data_id); $registrar_info = $registrar->last_name . ' ' . $registrar->first_name . ' ' . $registrar->middle_name . ' ' . $registrar->address; $registrar_shortname = $registrar->last_name . $registrar->first_name[0] . '. ' . $registrar->middle_name[0] . '.'; $parameters = Parameter::find()->where(['resource_id' => $id])->all(); $attributes = []; foreach ($parameters as $parameter) { $parameter_name = ResourceAttribute::findOne($parameter->attribute_id); $attributes[$parameter_name->name] = $parameter->value; } $length = $attributes['length']; $width = $attributes['width']; $height = $attributes['height']; if ($length || $width || $height) { if (!$length) { $length = '0'; } if (!$width) { $width = '0'; } if (!$height) { $height = '0'; } $attributes['linear_size'] = $length . ':' . $width . ':' . $height; } $reason = $resource->reason; function formatCoords($num) { $num = round($num, 4, PHP_ROUND_HALF_DOWN); $degrees = floor($num); $minfloat = ($num - $degrees) * 60; $minutes = floor($minfloat); $secfloat = ($minfloat - $minutes) * 60; $seconds = round($secfloat); if ($seconds == 60) { $minutes++; $seconds = 0; } if ($minutes == 60) { $degrees++; $minutes = 0; } return (string) $degrees . '°' . (string) $minutes . '\'' . (string) $seconds . '"'; } $tableFields = ['Найменування об’єкту' => $resource->name, 'Клас об’єкту' => $resource_class, 'Підклас об’єкту' => $resource_subclass, 'Власник об’єкту' => $owner_name, 'Географічні координати кутів (вершин) об’єкту у форматі ГГ°ММ\'СС,СС". ' => $coordinates, 'Лінійні розміри об’єкту, Д:Ш:В, м' => $attributes['linear_size'], 'Загальна площа об’єкту, га' => $attributes['square'] / 10000, 'Маса (вага) об’єкту, кг' => $attributes['weight'], 'Периметр об’єкту, м' => $attributes['perimeter'], 'Об’єм об’єкту, м3' => $attributes['volume'], 'Підстава для внесення відомостей до Реєстру' => $reason, 'ПІБ та поштова адреса народного реєстратора' => $registrar_info, 'Реєстраційний номер об’єкту' => $registration_number, 'Дата створення запису' => $creation_date]; $tableUnitalicFields = ['Клас об’єкту', 'Власник об’єкту']; $sections = $phpWord->getSections(); $section = $sections[0]; $phpWord->addTableStyle('Resource Table', $tableStyle); $table = $section->addTable('Resource Table'); foreach ($tableFields as $key => $value) { if ($value) { if (!is_array($value)) { $valueFontStyle = []; if (in_array($key, $tableUnitalicFields)) { $valueFontStyle = $italicFontStyle; } $table->addRow(200); $table->addCell(\PhpOffice\PhpWord\Shared\Converter::cmToTwip(8))->addText(htmlspecialchars($key, ENT_COMPAT, 'UTF-8'), $boldFontStyle); $table->addCell(\PhpOffice\PhpWord\Shared\Converter::cmToTwip(15))->addText(htmlspecialchars($value, ENT_COMPAT, 'UTF-8'), $valueFontStyle); } else { $row = $table->addRow(); $row->addCell(\PhpOffice\PhpWord\Shared\Converter::cmToTwip(8))->addText(htmlspecialchars($key, ENT_COMPAT, 'UTF-8'), $boldFontStyle); $cell = $row->addCell(); $innerTable = $cell->addTable($innerTableStyle); $innerTable->addRow(10); $innerTable->addCell(\PhpOffice\PhpWord\Shared\Converter::cmToTwip(4), $innerTableCellStyle)->addText(htmlspecialchars('Північна широта', ENT_COMPAT, 'UTF-8'), $innerTableFontStyle, $innerTableParagraphStyle); $innerTable->addCell(\PhpOffice\PhpWord\Shared\Converter::cmToTwip(4), $innerTableCellStyle)->addText(htmlspecialchars('Східна довгота', ENT_COMPAT, 'UTF-8'), $innerTableFontStyle, $innerTableParagraphStyle); $innerTable->addCell(\PhpOffice\PhpWord\Shared\Converter::cmToTwip(4), $innerTableCellStyle)->addText(htmlspecialchars("Північна широта \n(продовження)", ENT_COMPAT, 'UTF-8'), $innerTableFontStyle, $innerTableParagraphStyle); $innerTable->addCell(\PhpOffice\PhpWord\Shared\Converter::cmToTwip(4), $innerTableRightCellStyle)->addText(htmlspecialchars("Східна довгота \n(продовження)", ENT_COMPAT, 'UTF-8'), $innerTableFontStyle, $innerTableParagraphStyle); $coordinatesNumber = count($coordinates); for ($i = 1; $i <= round($coordinatesNumber / 2); $i++) { $lat = ''; $lng = ''; $latCont = ''; $lngCont = ''; if ($coordinatesNumber >= $i) { $lat = formatCoords($coordinates[$i - 1][0]); $lng = formatCoords($coordinates[$i - 1][1]); } if ($coordinatesNumber >= round($coordinatesNumber / 2) + $i) { $latCont = formatCoords($coordinates[$i + round($coordinatesNumber / 2) - 1][0]); $lngCont = formatCoords($coordinates[$i + round($coordinatesNumber / 2) - 1][1]); } $innerTable->addRow(10); $innerTable->addCell(\PhpOffice\PhpWord\Shared\Converter::cmToTwip(4), $innerTableCellStyle)->addText(htmlspecialchars($lat, ENT_COMPAT, 'UTF-8'), $italicFontStyle); $innerTable->addCell(\PhpOffice\PhpWord\Shared\Converter::cmToTwip(4), $innerTableCellStyle)->addText(htmlspecialchars($lng, ENT_COMPAT, 'UTF-8'), $italicFontStyle); $innerTable->addCell(\PhpOffice\PhpWord\Shared\Converter::cmToTwip(4), $innerTableCellStyle)->addText(htmlspecialchars($latCont, ENT_COMPAT, 'UTF-8'), $italicFontStyle); $innerTable->addCell(\PhpOffice\PhpWord\Shared\Converter::cmToTwip(4), $innerTableRightCellStyle)->addText(htmlspecialchars($lngCont, ENT_COMPAT, 'UTF-8'), $italicFontStyle); } } } } $section->addTextBreak(2); $section->addText('Народний реєстратор', $boldFontStyle); $section->addText(htmlspecialchars($registrar_shortname, ENT_COMPAT, 'UTF-8')); 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'); header('Cache-Control: must-revalidate, post-check=0, pre-check=0'); header('Expires: 0'); $xmlWriter = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord, 'Word2007'); $xmlWriter->save("php://output"); }
$string = gmdate('Y-m-d H:i:s') . " item.create webhook received. "; $string .= "Post params: " . print_r($_POST, true) . "\n"; $item_id = (int) $_POST['item_id']; // get item $item = PodioItem::get($item_id); $item_file = $item->files[0]; $file = PodioFile::get($item_file->file_id); $mimetype = $file->mimetype; // validate mime and get reader $reader_name = $controller->getReaderByMime($mimetype); if ($reader_name) { file_put_contents(__DIR__ . '/temp/' . $item_file->name, $file->get_raw()); $file_name_exploded = explode('.', $item_file->name); $file_name_no_ext = $file_name_exploded[0]; $controller->init_pdf_renderer(); \PhpOffice\PhpWord\Autoloader::register(); // Creating the new document... $phpWord = new \PhpOffice\PhpWord\PhpWord(); // Read contents $source = __DIR__ . '/temp/' . $item_file->name; $phpWord = \PhpOffice\PhpWord\IOFactory::load($source, $reader_name); //Save pdf file $xmlWriter = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord, 'PDF'); $xmlWriter->save(__DIR__ . '/temp/' . $file_name_no_ext . '.pdf'); $uploadedFile = PodioFile::upload(__DIR__ . '/temp/' . $file_name_no_ext . '.pdf', $file_name_no_ext . '.pdf'); PodioFile::attach($uploadedFile->file_id, array('ref_type' => 'item', 'ref_id' => $item_id)); } // log request file_put_contents($file, $string, FILE_APPEND | LOCK_EX); break; }
//, 'PDF' => 'pdf' foreach ($writers as $writer => $extension) { echo date('H:i:s'), " Escribir como formato {$writer} ", EOL; if (file_exists($carpeta . "/prueba.{$extension}")) { echo "El archivo ya existe.<br>"; } else { $xmlWriter = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord, $writer); $xmlWriter->save("prueba.{$extension}"); rename("prueba.{$extension}", "{$carpeta}/prueba.{$extension}"); } } // Save file //echo write($phpWord, basename(__FILE__, '.php'), $writers); } else { echo date('H:i:s'), " Reading contents from `{$ruta}`", EOL; $phpWord = \PhpOffice\PhpWord\IOFactory::load($ruta, 'MsDoc'); // (Re)write contents $writers = array('Word2007' => 'docx', 'ODText' => 'odt', 'RTF' => 'rtf', 'HTML' => 'html'); //, 'PDF' => 'pdf' foreach ($writers as $writer => $extension) { echo date('H:i:s'), " Escribir como formato {$writer} ", EOL; if (file_exists($carpeta . "/prueba.{$extension}")) { echo "El archivo ya existe.<br>"; } else { $xmlWriter = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord, $writer); $xmlWriter->save("prueba.{$extension}"); rename("prueba.{$extension}", "{$carpeta}/prueba.{$extension}"); } } $sections = $phpWord->getSections(); $DocInfo = $phpWord->getDocInfo();
/** * Load */ public function testLoad() { $filename = __DIR__ . '/../_files/documents/reader.odt'; $phpWord = IOFactory::load($filename, 'ODText'); $this->assertInstanceOf('PhpOffice\\PhpWord\\PhpWord', $phpWord); }
} //$carpeta = "/".$cod."/".$year."/".$semestre; $ruta = $carpeta . "/" . $nombre_archivo; // Checkear si existe ya el archivo $resultado = false; if (file_exists($ruta)) { echo "El archivo ya existe.<br>"; } else { $resultado = move_uploaded_file($tmp_name, $ruta); if ($resultado) { //$insertar = llamada a la bd echo date('H:i:s'), "Silabus guardado correctamente<br>"; $uploadOk = true; if ($extension == "docx") { echo date('H:i:s'), " Leyendo archivo de `{$ruta}`"; $phpWord = \PhpOffice\PhpWord\IOFactory::load($ruta); $writers = array('HTML' => 'html'); //'Word2007' => 'docx', 'ODText' => 'odt', 'RTF' => 'rtf', foreach ($writers as $writer => $extension) { echo date('H:i:s'), " Convirtiendo a formato {$writer} <br>"; if (file_exists($carpeta . "/{$id_curso}.{$extension}")) { echo "El archivo ya existe.<br>"; } else { $xmlWriter = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord, $writer); $xmlWriter->save("temporal.{$extension}"); rename("{$id_curso}.{$extension}", "{$carpeta}/{$id_curso}.{$extension}"); } } } echo date('H:i:s'), " Leyendo archivo html <br><br>"; //Agregar codigo de captura de datos
<?php include_once 'Sample_Header.php'; // Read contents $name = basename(__FILE__, '.php'); $source = "resources/{$name}.odt"; echo date('H:i:s'), " Reading contents from `{$source}`", EOL; $phpWord = \PhpOffice\PhpWord\IOFactory::load($source, 'ODText'); // Save file echo write($phpWord, basename(__FILE__, '.php'), $writers); if (!CLI) { include_once 'Sample_Footer.php'; }
/** * Load document */ public function testLoad() { $file = __DIR__ . "/_files/templates/blank.docx"; $this->assertInstanceOf('PhpOffice\\PhpWord\\PhpWord', IOFactory::load($file)); }
protected function createReader() { return IOFactory::load($this->filename, "Word2007"); }