public function generateDOC($html) { $objPHPWord = new PhpWord(); // Create new PHPWord object $section = $objPHPWord->addSection(); Html::addHtml($section, $html, true); $objWriter = IOFactory::createWriter($objPHPWord, 'Word2007'); ob_start(); $objWriter->save('php://output'); $contents = ob_get_clean(); return $contents; }
/** * Create word file using phpWord library * * @param array $text * @param $file * @return string * @throws \PhpOffice\PhpWord\Exception\Exception */ public function createDocx(array $text, $file) { $file_path = public_path($file); $phpWord = new PhpWord(); foreach ($text as $page) { $section = $phpWord->addSection(); $page = $this->escape($page); Html::addHtml($section, $page); } $objWriter = IOFactory::createWriter($phpWord, 'Word2007'); $objWriter->save($file_path); return $file_path; }
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; }
function exportWord($text, $font, $size, $bold) { $phpWord = new \PhpOffice\PhpWord\PhpWord(); $section = $phpWord->addSection(); // // $section->addText($text); // // $section->addText('Hello world! I am formatted.', // array('name'=>'Tahoma', 'size'=>16, 'bold'=>true)); // $phpWord->addFontStyle('myOwnStyle', // array('name'=>'Verdana', 'size'=>14, 'color'=>'1B2232')); // $section->addText('Hello world! I am formatted by a user defined style', // 'myOwnStyle'); $fontStyle = new \PhpOffice\PhpWord\Style\Font(); $fontStyle->setBold($bold); $fontStyle->setName($font); $fontStyle->setSize($size); $myTextElement = $section->addText($text); $myTextElement->setFontStyle($fontStyle); $objWriter = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord, 'Word2007'); $objWriter->save('helloWorld.docx'); }
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}`; }
/** * Get document content * * @param \PhpOffice\PhpWord\PhpWord $phpWord * @param string $writerName * @return \PhpOffice\PhpWord\Tests\XmlDocument */ public static function getDocument(PhpWord $phpWord, $writerName = 'Word2007') { self::$file = tempnam(sys_get_temp_dir(), 'PhpWord'); if (!is_dir(sys_get_temp_dir() . '/PhpWord_Unit_Test/')) { mkdir(sys_get_temp_dir() . '/PhpWord_Unit_Test/'); } $xmlWriter = IOFactory::createWriter($phpWord, $writerName); $xmlWriter->save(self::$file); $zip = new \ZipArchive(); $res = $zip->open(self::$file); if ($res === true) { $zip->extractTo(sys_get_temp_dir() . '/PhpWord_Unit_Test/'); $zip->close(); } return new XmlDocument(sys_get_temp_dir() . '/PhpWord_Unit_Test/'); }
/** * Write documents * * @param \PhpOffice\PhpWord\PhpWord $phpWord * @param string $filename * @param array $writers */ function write($phpWord, $filename, $writers) { $result = ''; // Write documents foreach ($writers as $writer => $extension) { $result .= date('H:i:s') . " Write to {$writer} format"; if (!is_null($extension)) { $xmlWriter = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord, $writer); $xmlWriter->save("{$filename}.{$extension}"); rename("{$filename}.{$extension}", "results/{$filename}.{$extension}"); } else { $result .= ' ... NOT DONE!'; } $result .= EOL; } $result .= getEndingNotes($writers); return $result; }
/** * Get document content * * @since 0.12.0 Throws CreateTemporaryFileException. * * @param \PhpOffice\PhpWord\PhpWord $phpWord * @param string $writerName * * @return \PhpOffice\PhpWord\Tests\XmlDocument * * @throws \PhpOffice\PhpWord\Exception\CreateTemporaryFileException */ public static function getDocument(PhpWord $phpWord, $writerName = 'Word2007') { self::$file = tempnam(Settings::getTempDir(), 'PhpWord'); if (false === self::$file) { throw new CreateTemporaryFileException(); } if (!is_dir(Settings::getTempDir() . '/PhpWord_Unit_Test/')) { mkdir(Settings::getTempDir() . '/PhpWord_Unit_Test/'); } $xmlWriter = IOFactory::createWriter($phpWord, $writerName); $xmlWriter->save(self::$file); $zip = new \ZipArchive(); $res = $zip->open(self::$file); if (true === $res) { $zip->extractTo(Settings::getTempDir() . '/PhpWord_Unit_Test/'); $zip->close(); } return new XmlDocument(Settings::getTempDir() . '/PhpWord_Unit_Test/'); }
public function prepare() { $file = path('tmp') . sha1(microtime()); $lines = $this->getData(); $phpWord = new PhpWord(); $section = $phpWord->addSection(['orientation' => 'landscape']); /** * Make header */ $table = $section->addTable(['width' => 100 * 50]); $i = 0; $j = 0; $table->addRow(); foreach ($lines[0] as $key => $val) { $table->addCell(1750)->addText($key); $j++; } /** * Make data */ foreach ($lines as $line) { $i++; $j = 0; $table->addRow(); foreach ($line as $val) { $table->addCell(1750)->addText($val); $j++; } } /** * Save file. */ $objWriter = IOFactory::createWriter($phpWord, 'Word2007'); $objWriter->save($file); /** * Implement strategy. */ $this->setFileContent(file_get_contents($file)); unlink($file); }
/** * 生成简历文件字符串 * @param $sp_id 快照主键 * @param string $type 类型 doc/doc_no_contact(隐藏了联系方式) */ public function getDocFileStr($id, $type = 'doc_no_contact') { $sp_model = new ResumeSnapshot(); $sp_info = $sp_model->getResumeSnapshotInfoById($id); //根据简历快照生成word $phpWord = new PhpWord(); // New portrait section $section = $phpWord->addSection(); // Add header for all other pages //todo logo图片需传到线上 $subsequent = $section->addHeader(); $subsequent->addText(htmlspecialchars('51CTO高招-中高端IT人才的招聘平台')); $subsequent->addImage('http://job.51cto.com/pic/logo_s.jpg', array('width' => 80, 'height' => 80, 'align' => 'right')); //// $section = $phpWord->addSection(); // $html = '<h1>Adding element via HTML</h1>'; // $html .= '<p>Some well formed HTML snippet needs to be used</p>'; // $html .= '<p>With for example <strong>some<sup>1</sup> <em>inline</em> formatting</strong><sub>1</sub></p>'; // $html .= '<p>Unordered (bulleted) list:</p>'; // $html .= '<ul><li>Item 1</li><li>Item 2</li><ul><li>Item 2.1</li><li>Item 2.1</li></ul></ul>'; // $html .= '<p>Ordered (numbered) list:</p>'; // $html .= '<ol><li>Item 1</li><li>Item 2</li></ol>'; // // \PhpOffice\PhpWord\Shared\Html::addHtml($section, $html); $section = $phpWord->addSection(); $header = array('size' => 16, 'bold' => true); //1.Use EastAisa FontStyle $section->addText(htmlspecialchars('邵燕'), array('name' => '微软雅黑', 'size' => '二号', 'color' => '1B2232')); $section->addText(htmlspecialchars('邵燕'), array('name' => '微软雅黑', 'size' => '二号', 'color' => '1B2232')); $objWriter = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord, 'Word2007'); $rand = time() . rand(10000, 99999); $file = WEB_ROOT . "/runtime/{$rand}.docx"; //临时文件 $file = WEB_ROOT . "/runtime/test.docx"; //临时文件 $objWriter->save($file, 'Word2007', true); // $file_str = file_get_contents($file); // unlink($file);//删除文件 // // return $file_str; }
/** * Download file from PHPWord instance * @param PHPWord $phpWord reference to phpWord * @param string $fileName file name * @param string $format file save format */ public function download(PHPWord &$phpWord, $fileName, $format = 'Word2007') { if (!in_array($format, array_keys(static::$map))) { $format = $this->defaultFormat; } $fileName .= '.' . static::$map[$format]; header('Content-Type: ' . FileHelper::getMimeTypeByExtension($fileName)); header('Content-Disposition: attachment;filename="' . $fileName . '"'); header('Cache-Control: max-age=0'); header('Cache-Control: max-age=1'); // If you're serving to IE 9, then the following may be needed // If you're serving to IE over SSL, then the following may be needed header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT'); // always modified header('Cache-Control: cache, must-revalidate'); // HTTP/1.1 header('Pragma: public'); // HTTP/1.0 $writer = IOFactory::createWriter($phpWord, $format); $writer->save('php://output'); Yii::$app->end(); }
/** * Save to file or download * * All exceptions should already been handled by the writers * * @param string $filename * @param string $format * @param bool $download * @return bool */ public function save($filename, $format = 'Word2007', $download = false) { $mime = array('Word2007' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', 'ODText' => 'application/vnd.oasis.opendocument.text', 'RTF' => 'application/rtf', 'HTML' => 'text/html', 'PDF' => 'application/pdf'); $writer = IOFactory::createWriter($this, $format); if ($download === true) { header("Content-Description: File Transfer"); header('Content-Disposition: attachment; filename="' . $filename . '"'); header('Content-Type: ' . $mime[$format]); header('Content-Transfer-Encoding: binary'); header('Cache-Control: must-revalidate, post-check=0, pre-check=0'); header('Expires: 0'); $filename = 'php://output'; // Change filename to force download } $writer->save($filename); return true; }
$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 $url = $carpeta . "/" . $_REQUEST['idcurso'] . ".html"; $html = file_get_contents($url); $dom = new domDocument(); $dom->loadHTML($html); /*** eliminar espacios en blanco ***/ $dom->preserveWhiteSpace = false; $ps = $dom->getElementsByTagName('p'); /*** obteniendo todas las tablas ***/
/** * Test load exception * * @expectedException \Exception * @expectedExceptionMessage Cannot read */ public function testLoadException() { $filename = __DIR__ . '/../_files/documents/foo.rtf'; IOFactory::load($filename, 'RTF'); }
protected function createReader() { return IOFactory::load($this->filename, "Word2007"); }
/** * Load */ public function testLoad() { $filename = __DIR__ . '/../_files/documents/reader.odt'; $phpWord = IOFactory::load($filename, 'ODText'); $this->assertInstanceOf('PhpOffice\\PhpWord\\PhpWord', $phpWord); }
function make_word_doc($doc, $dir) { /** * uses the $doc object to create a new word doc whose name is sent back to hte client where an <iframe> downloads it * * @since 1.0 * * @caller user action * @ingroup editor * * @param object $doc created in js - a big object w all the info needed * @param string $dir the directory name to add the .doc * @return echos the word doc's name */ // make the a new instance of a phpword // you will add all the info to this $phpWord = new \PhpOffice\PhpWord\PhpWord(); $i = 0; $l = count($doc) - 1; // loop through each page in the doc // each page is a 'section' for ($i; $i < $l; $i = $i + 1) { $Paragraphs = $doc['Page' . $i]; $ii = 0; $ll = count($Paragraphs) - 1; ${"page_" . $i} = $phpWord->addSection(); $Page = ${"page_" . $i}; // in each page loop through each paragraph // style the the paragraph's alignment for ($ii; $ii < $ll; $ii = $ii + 1) { $Spans = $Paragraphs['Paragraph' . $ii]; $iii = 0; $lll = count($Spans) - 1; ${"paragraph_" . $i . '_' . $ii} = $Page->addTextRun(array('align' => $Spans['align'])); $Paragraph = ${"paragraph_" . $i . '_' . $ii}; // loop through each text span for ($iii; $iii < $lll; $iii = $iii + 1) { $Span = $Spans['Span' . $iii]; // create the style info for the text span $Style = array('name' => $Span['Styles']['name'], 'size' => intval($Span['Styles']['size']), 'bold' => filter_var($Span['Styles']['bold'], FILTER_VALIDATE_BOOLEAN), 'italic' => filter_var($Span['Styles']['italic'], FILTER_VALIDATE_BOOLEAN), 'color' => $Span['Styles']['color'], 'fgColor' => $Span['Styles']['fgColor']); // add the text span with it's style to the paragraph $Paragraph->addText($Span['text'], $Style); } } } // assign it as a word doc $objWriter = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord, 'Word2007'); // create an empty word doc file w. the new file name $pathAndFile = $dir . '/' . $doc['title'] . '.docx'; // save the file with content included $objWriter->save($pathAndFile); // return the .doc's title so it can be downloaded echo $doc['title'] . '.docx'; die; }
/** * @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 = 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'; }
function ciniki_conferences_conferenceScheduleDownload($ciniki) { // // Find all the required and optional arguments // ciniki_core_loadMethod($ciniki, 'ciniki', 'core', 'private', 'prepareArgs'); $rc = ciniki_core_prepareArgs($ciniki, 'no', array('business_id' => array('required' => 'yes', 'blank' => 'no', 'name' => 'Business'), 'conference_id' => array('required' => 'yes', 'blank' => 'no', 'name' => 'Conference'))); if ($rc['stat'] != 'ok') { return $rc; } $args = $rc['args']; // // Make sure this module is activated, and // check permission to run this function for this business // ciniki_core_loadMethod($ciniki, 'ciniki', 'conferences', 'private', 'checkAccess'); $rc = ciniki_conferences_checkAccess($ciniki, $args['business_id'], 'ciniki.conferences.conferenceScheduleDownload'); if ($rc['stat'] != 'ok') { return $rc; } ciniki_core_loadMethod($ciniki, 'ciniki', 'core', 'private', 'dbHashQuery'); ciniki_core_loadMethod($ciniki, 'ciniki', 'core', 'private', 'dbHashQueryArrayTree'); ciniki_core_loadMethod($ciniki, 'ciniki', 'core', 'private', 'dbHashQueryIDTree'); // // Load business settings // ciniki_core_loadMethod($ciniki, 'ciniki', 'businesses', 'private', 'intlSettings'); $rc = ciniki_businesses_intlSettings($ciniki, $args['business_id']); if ($rc['stat'] != 'ok') { return $rc; } $intl_timezone = $rc['settings']['intl-default-timezone']; $intl_currency_fmt = numfmt_create($rc['settings']['intl-default-locale'], NumberFormatter::CURRENCY); $intl_currency = $rc['settings']['intl-default-currency']; ciniki_core_loadMethod($ciniki, 'ciniki', 'users', 'private', 'dateFormat'); ciniki_core_loadMethod($ciniki, 'ciniki', 'users', 'private', 'timeFormat'); $date_format = ciniki_users_dateFormat($ciniki, 'php'); $time_format = ciniki_users_timeFormat($ciniki, 'php'); $mysql_date_format = ciniki_users_dateFormat($ciniki, 'mysql'); // // Load conference maps // ciniki_core_loadMethod($ciniki, 'ciniki', 'conferences', 'private', 'maps'); $rc = ciniki_conferences_maps($ciniki); if ($rc['stat'] != 'ok') { return $rc; } $maps = $rc['maps']; $strsql = "SELECT ciniki_conferences.id, " . "ciniki_conferences.name, " . "ciniki_conferences.permalink, " . "ciniki_conferences.status, " . "ciniki_conferences.status AS status_text, " . "ciniki_conferences.flags, " . "DATE_FORMAT(ciniki_conferences.start_date, '" . ciniki_core_dbQuote($ciniki, $mysql_date_format) . "') AS start_date, " . "DATE_FORMAT(ciniki_conferences.end_date, '" . ciniki_core_dbQuote($ciniki, $mysql_date_format) . "') AS end_date, " . "ciniki_conferences.synopsis, " . "ciniki_conferences.description, " . "ciniki_conferences.imap_mailbox, " . "ciniki_conferences.imap_username, " . "ciniki_conferences.imap_password, " . "ciniki_conferences.imap_subject " . "FROM ciniki_conferences " . "WHERE ciniki_conferences.business_id = '" . ciniki_core_dbQuote($ciniki, $args['business_id']) . "' " . "AND ciniki_conferences.id = '" . ciniki_core_dbQuote($ciniki, $args['conference_id']) . "' " . ""; $rc = ciniki_core_dbHashQuery($ciniki, $strsql, 'ciniki.conferences', 'conference'); if ($rc['stat'] != 'ok') { return array('stat' => 'fail', 'err' => array('pkg' => 'ciniki', 'code' => '3631', 'msg' => 'Conference not found', 'err' => $rc['err'])); } if (!isset($rc['conference'])) { return array('stat' => 'fail', 'err' => array('pkg' => 'ciniki', 'code' => '3632', 'msg' => 'Unable to find Conference')); } $conference = $rc['conference']; if (isset($maps['conference']['status'][$conference['status_text']])) { $conference['status_text'] = $maps['conference']['status'][$conference['status_text']]; } $strsql = "SELECT ciniki_conferences_sessions.id, " . "CONCAT_WS('-', ciniki_conferences_sessions.id, ciniki_conferences_presentations.id) AS rowid, " . "ciniki_conferences_sessions.conference_id, " . "ciniki_conferences_sessions.room_id, " . "ciniki_conferences_rooms.name AS room, " . "ciniki_conferences_rooms.sequence, " . "ciniki_conferences_sessions.name, " . "ciniki_conferences_sessions.session_start AS start_time, " . "ciniki_conferences_sessions.session_start AS start_date, " . "ciniki_conferences_sessions.session_end AS end_time, " . "IFNULL(ciniki_conferences_presentations.id, 0) AS presentation_id, " . "IFNULL(ciniki_conferences_presentations.customer_id, 0) AS customer_id, " . "IFNULL(ciniki_conferences_presentations.presentation_number, '') AS presentation_number, " . "IFNULL(ciniki_conferences_presentations.title, '') AS presentation_title, " . "IFNULL(ciniki_conferences_presentations.description, '') AS presentation_description, " . "IFNULL(ciniki_customers.display_name, '') AS display_name, " . "IFNULL(ciniki_conferences_presentations.status, 0) AS status, " . "IFNULL(ciniki_conferences_presentations.status, '') AS status_text, " . "IFNULL(ciniki_conferences_attendees.status, 0) AS registration, " . "IFNULL(ciniki_conferences_attendees.status, 0) AS registration_text " . "FROM ciniki_conferences_sessions " . "INNER JOIN ciniki_conferences_rooms ON (" . "ciniki_conferences_sessions.room_id = ciniki_conferences_rooms.id " . "AND ciniki_conferences_rooms.business_id = '" . ciniki_core_dbQuote($ciniki, $args['business_id']) . "' " . ") " . "LEFT JOIN ciniki_conferences_presentations ON (" . "ciniki_conferences_sessions.id = ciniki_conferences_presentations.session_id " . "AND ciniki_conferences_presentations.business_id = '" . ciniki_core_dbQuote($ciniki, $args['business_id']) . "' " . ") " . "LEFT JOIN ciniki_conferences_attendees ON (" . "ciniki_conferences_presentations.customer_id = ciniki_conferences_attendees.customer_id " . "AND ciniki_conferences_presentations.conference_id = ciniki_conferences_attendees.conference_id " . "AND ciniki_conferences_attendees.business_id = '" . ciniki_core_dbQuote($ciniki, $args['business_id']) . "' " . ") " . "LEFT JOIN ciniki_customers ON (" . "ciniki_conferences_presentations.customer_id = ciniki_customers.id " . "AND ciniki_customers.business_id = '" . ciniki_core_dbQuote($ciniki, $args['business_id']) . "' " . ") " . "WHERE ciniki_conferences_sessions.business_id = '" . ciniki_core_dbQuote($ciniki, $args['business_id']) . "' " . "AND ciniki_conferences_sessions.conference_id = '" . ciniki_core_dbQuote($ciniki, $args['conference_id']) . "' " . "ORDER BY ciniki_conferences_sessions.session_start, " . "ciniki_conferences_rooms.name, " . "ciniki_conferences_rooms.sequence, " . "ciniki_conferences_presentations.title " . ""; ciniki_core_loadMethod($ciniki, 'ciniki', 'core', 'private', 'dbHashQueryArrayTree'); $rc = ciniki_core_dbHashQueryArrayTree($ciniki, $strsql, 'ciniki.conferences', array(array('container' => 'times', 'fname' => 'start_time', 'fields' => array('start_time', 'start_date', 'end_time'), 'utctotz' => array('start_time' => array('format' => $time_format, 'timezone' => $intl_timezone), 'start_date' => array('format' => $date_format, 'timezone' => $intl_timezone), 'end_time' => array('format' => $time_format, 'timezone' => $intl_timezone))), array('container' => 'rooms', 'fname' => 'room_id', 'fields' => array('id' => 'room_id', 'name' => 'room', 'session_name' => 'name', 'presentation_id')), array('container' => 'presentations', 'fname' => 'presentation_id', 'fields' => array('id', 'conference_id', 'room_id', 'room', 'sequence', 'name', 'start_time', 'start_date', 'end_time', 'presentation_id', 'customer_id', 'presentation_number', 'presentation_title', 'presentation_description', 'display_name', 'status', 'status_text', 'registration', 'registration_text'), 'utctotz' => array('start_time' => array('format' => $time_format, 'timezone' => $intl_timezone), 'start_date' => array('format' => $date_format, 'timezone' => $intl_timezone), 'end_time' => array('format' => $time_format, 'timezone' => $intl_timezone)), 'maps' => array('status_text' => $maps['presentation']['status'], 'registration_text' => $maps['attendee']['status'])))); if ($rc['stat'] != 'ok') { return $rc; } if (isset($rc['times'])) { $timeslots = $rc['times']; } else { $timeslots = array(); } // // Generate the word file // require_once $ciniki['config']['core']['lib_dir'] . '/PHPWord/src/PhpWord/Autoloader.php'; \PhpOffice\PhpWord\Autoloader::register(); require $ciniki['config']['core']['lib_dir'] . '/PHPWord/src/PhpWord/PhpWord.php'; $PHPWord = new \PhpOffice\PhpWord\PhpWord(); $PHPWord->addTitleStyle(1, array('bold' => true, 'size' => 18), array('spaceBefore' => 240, 'spaceAfter' => 120)); $PHPWord->addTitleStyle(2, array('bold' => true, 'size' => 16), array('spaceBefore' => 120, 'spaceAfter' => 120)); $PHPWord->addTitleStyle(3, array('bold' => false, 'size' => 14), array('spaceBefore' => 120, 'spaceAfter' => 120)); $style_table = array('cellMargin' => 80, 'borderColor' => 'aaaaaa', 'borderSize' => 6); $style_header = array('borderSize' => 6, 'borderColor' => 'aaaaaa', 'bgColor' => 'dddddd', 'valign' => 'center'); $style_cell = array('borderSize' => 6, 'borderColor' => 'aaaaaa', 'valign' => 'center', 'bgcolor' => 'ffffff'); $style_header_font = array('bold' => true, 'spaceAfter' => 20); $style_cell_font = array(); $style_header_pleft = array('align' => 'left'); $style_header_pright = array('align' => 'right'); $style_cell_pleft = array('align' => 'left'); $style_cell_pright = array('align' => 'right'); $section = $PHPWord->addSection(); $header = $section->addHeader(); $table = $header->addTable(); $table->addRow(); $cell = $table->addCell(9600); $cell->addText($conference['name'], array('size' => '16'), array('align' => 'center')); //print "<pre>" . print_r($timeslots, true) . "</pre>"; //exit; // // Create a table with a row for each time slot // $cur_date = ''; $table = $section->addTable($style_table); $session_number = 1; foreach ($timeslots as $timeslot) { // // Add the date as a header // if ($timeslot['start_date'] != $cur_date) { $table->addRow(); $cell = $table->addCell(1500, $style_cell); $cell->addText($timeslot['start_date']); $cell->setGridSpan(2); $cur_date = $timeslot['start_date']; // $session_number = 1; } // // Add the time slot // $table->addRow(); $cell = $table->addCell(1500, $style_cell); $cell->addText($timeslot['start_time'] . ' - ' . $timeslot['end_time'], $style_cell_font); $nonsession_info = array(); $session_info = array(); if (isset($timeslot['rooms']) && count($timeslot['rooms']) > 0) { foreach ($timeslot['rooms'] as $room) { if (!isset($room['presentations']) || $room['presentation_id'] == 0) { if (isset($room['presentations'][0])) { $session = $room['presentations'][0]; if ($session['name'] != '') { $nonsession_info[] = $session['name']; } } $nonsession_info[] = "Location: " . $room['name']; } else { $session_info[] = $session_number . ". " . $room['session_name'] . ": "; $presentation_number = 1; $presentation_info = ''; foreach ($room['presentations'] as $presentation) { if ($presentation_number > 1) { $presentation_info .= "; "; } $presentation_info .= $presentation_number . ") " . $presentation['display_name']; $presentation_number++; } $session_info[] = $presentation_info; $session_info[] = "Location: " . $room['name']; $session_info[] = ""; $session_number++; } } } $cell = $table->addCell(2500, $style_cell); foreach ($nonsession_info as $line) { $cell->addText($line, $style_cell_font); } $cell = $table->addCell(5500, $style_cell); foreach ($session_info as $line) { $cell->addText($line, $style_cell_font); } } $section = $PHPWord->addSection(); $header = $section->addHeader(); $table = $header->addTable(); $table->addRow(); $cell = $table->addCell(9600); $cell->addText($conference['name'], array('size' => '16'), array('align' => 'center')); $session_number = 1; foreach ($timeslots as $timeslot) { if (isset($timeslot['rooms']) && count($timeslot['rooms']) > 0) { foreach ($timeslot['rooms'] as $room) { if (!isset($room['presentations']) || $room['presentation_id'] == 0) { continue; } $section->addTitle($session_number . ". " . $room['session_name'], 1); if (isset($room['presentations']) && $room['presentation_id'] != 0) { foreach ($room['presentations'] as $pid => $presentation) { $section->addTitle($presentation['display_name'], 2); $section->addTitle(htmlspecialchars($presentation['presentation_title']), 3); $lines = explode("\n", $presentation['presentation_description']); foreach ($lines as $line) { $section->addText(htmlspecialchars($line), array()); } $section->addText(''); } } $session_number++; } } } // // Output the word file // header('Content-Type: application/vnd.openxmlformats-officedocument.wordprocessingml.document'); header('Content-Disposition: attachment;filename="' . preg_replace("/[^A-Za-z0-9]/", '', $conference['name']) . '.docx"'); header('Cache-Control: max-age=0'); $objWriter = \PhpOffice\PhpWord\IOFactory::createWriter($PHPWord, 'Word2007'); $objWriter->save('php://output'); return array('stat' => 'exit'); }
/** * 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); }
$section->addText(htmlspecialchars('"Learn from yesterday, live for today, hope for tomorrow. ' . 'The important thing is not to stop questioning." ' . '(Albert Einstein)')); /* * Note: it's possible to customize font style of the Text element you add in three ways: * - inline; * - using named font style (new font style object will be implicitly created); * - using explicitly created font style object. */ // Adding Text element with font customized inline... $section->addText(htmlspecialchars('"Great achievement is usually born of great sacrifice, ' . 'and is never the result of selfishness." ' . '(Napoleon Hill)'), array('name' => 'Tahoma', 'size' => 10)); // Adding Text element with font customized using named font style... $fontStyleName = 'oneUserDefinedStyle'; $phpWord->addFontStyle($fontStyleName, array('name' => 'Tahoma', 'size' => 10, 'color' => '1B2232', 'bold' => true)); $section->addText(htmlspecialchars('"The greatest accomplishment is not in never falling, ' . 'but in rising again after you fall." ' . '(Vince Lombardi)'), $fontStyleName); // Adding Text element with font customized using explicitly created font style object... $fontStyle = new \PhpOffice\PhpWord\Style\Font(); $fontStyle->setBold(true); $fontStyle->setName('Tahoma'); $fontStyle->setSize(13); $myTextElement = $section->addText(htmlspecialchars('"Believe you can and you\'re halfway there." (Theodor Roosevelt)')); $myTextElement->setFontStyle($fontStyle); // Saving the document as OOXML file... $objWriter = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord, 'Word2007'); $objWriter->save('helloWorld.docx'); // Saving the document as ODF file... $objWriter = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord, 'ODText'); $objWriter->save('helloWorld.odt'); // Saving the document as HTML file... $objWriter = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord, 'HTML'); $objWriter->save('helloWorld.html'); /* Note: we skip RTF, because it's not XML-based and requires a different example. */ /* Note: we skip PDF, because "HTML-to-PDF" approach is used to create PDF documents. */
/** * */ public function exportMemberProfile($id) { $user = User::find($id); if (!$user) { return Redirect::route('members')->with('mError', 'Cet utilisateur est introuvable !'); } $phpWord = new \PhpOffice\PhpWord\PhpWord(); $phpWord->addTitleStyle(1, array('name' => 'Tahoma', 'size' => 30, 'bold' => true), array('align' => 'center', 'spaceBefore' => true, 'spaceAfter' => true)); $phpWord->addTitleStyle(2, array('name' => 'Tahoma', 'size' => 14, 'color' => '666666', 'bold' => true), array('align' => 'center', 'spaceBefore' => true, 'spaceAfter' => true)); $phpWord->addFontStyle('defaultText', array('name' => 'Tahoma', 'size' => 12, 'spaceBefore' => true, 'spaceAfter' => true)); $section = $phpWord->addSection(array('marginTop' => \PhpOffice\PhpWord\Shared\Converter::cmToTwip(1), 'marginLeft' => \PhpOffice\PhpWord\Shared\Converter::cmToTwip(1), 'marginRight' => \PhpOffice\PhpWord\Shared\Converter::cmToTwip(1))); $textrun = $section->addTextRun('Heading1'); $textrun->addText($user->fullname); $section->addTextBreak(); $textrun = $section->addTextRun('Heading2'); $textrun->addText(htmlspecialchars($user->bio_short)); $section->addTextBreak(); $table = $section->addTable(); $table->addRow(); $cell1 = $table->addCell(\PhpOffice\PhpWord\Shared\Converter::cmToTwip(14)); foreach (explode("\n", htmlspecialchars($user->bio_long)) as $line) { $cell1->addText($line, 'defaultText'); } $cell1->addTextBreak(); if ($user->phone) { $cell1->addText(htmlspecialchars(sprintf('Tél: %s', $user->phoneFmt)), 'defaultText', array('align' => 'right')); } $cell1->addText(htmlspecialchars(sprintf('Email: %s', $user->email)), 'defaultText', array('align' => 'right')); if ($user->website) { $cell1->addText(htmlspecialchars($user->website), 'defaultText', array('align' => 'right')); } $cell2 = $table->addCell(\PhpOffice\PhpWord\Shared\Converter::cmToTwip(5)); $image_url = $user->largeAvatarUrl; $image_url = preg_replace('!^(.+)\\?.+$!', '$1', $image_url); if (false === strpos($image_url, 'http')) { $image_url = public_path() . $image_url; } $cell2->addImage($image_url, array('width' => \PhpOffice\PhpWord\Shared\Converter::cmToPixel(5))); $filename = sprintf('%s.docx', Str::slug($user->fullname)); $objWriter = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord, 'Word2007'); $objWriter->save($filename); $content = file_get_contents($filename); unlink($filename); $headers = array("Content-Description" => "File Transfer", "Content-Transfer-Encoding" => "binary", "Content-type" => "application/vnd.openxmlformats-officedocument.wordprocessingml.document", "Content-Disposition" => "attachment; filename=" . $filename); return Response::make($content, 200, $headers); }
public function posliSubor($phpWord) { if (URLParser::v("type") == "1") { $objWriter = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord, 'Word2007'); $objWriter->save($name = '../docs/' . md5(uniqid()) . '.docx'); $pripona = ".docx"; } elseif (URLParser::v("type") == "2") { $objWriter = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord, 'ODText'); $objWriter->save($name = '../docs/' . md5(uniqid()) . '.odt'); $pripona = ".odt"; } elseif (URLParser::v("type") == "3") { $objWriter = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord, 'RTF'); $objWriter->save($name = '../docs/' . md5(uniqid()) . '.rtf'); $pripona = ".rtf"; } header('Content-Description: File Transfer'); header('Content-Type: application/octet-stream'); header('Content-Disposition: attachment; filename=NaPodpis' . $pripona); 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($name)); flush(); readfile($name); unlink($name); exit; }
/** * 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 document */ public function testLoad() { $file = __DIR__ . "/_files/templates/blank.docx"; $this->assertInstanceOf('PhpOffice\\PhpWord\\PhpWord', IOFactory::load($file)); }
function write($phpWord, $filename, $writers,$target_path) { $result = ''; foreach ($writers as $writer => $extension) { $result .= date('H:i:s') . " Write to {$writer} format"; if (!is_null($extension)) { $xmlWriter = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord, $writer); $xmlWriter->save($tmp_path . "/{$filename}.{$extension}"); $result = true; } else { $result = false; } } return $result; }
foreach ($projects as $project) { $textRunObj = $section->createTextRun(); if ($this->action === 'em-cartaz-preview') { $textRunObj->addText('PROJETO ' . $project['project']->name . ' ', $eventTitleFont); $textRunObj->addText('('); $textRunObj->addLink($project['project']->singleUrl, 'link', $eventTitleFont, $eventTitleFont); $textRunObj->addText(')'); } else { $section->addText('PROJETO ' . $project['project']->name, $eventTitleFont); } foreach ($project['events'] as $event) { if ($this->action === 'em-cartaz-preview') { $addEventBlockHtml($event); } else { $addEventBlockDoc($event); } } } } if ($this->action === 'em-cartaz-preview') { //$content = '<a href="'.$app->createUrl('panel', 'em-cartaz-download').'">Salvar Documento Em Formato Microsoft Word</a>'; $objWriter = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord, 'HTML'); $this->render('em-cartaz', array('content' => $objWriter->getWriterPart('Body')->write(), 'from' => $from, 'to' => $to)); } else { $objWriter = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord, 'Word2007'); $objWriter->save("php://output"); $app->response()->header('Content-Type', 'application/vnd.ms-word'); $app->response()->header('Content-Disposition', 'attachment;filename="Em Cartaz de ' . $from->format('d-m-Y') . ' a ' . $to->format('d-m-Y') . '.docx"'); $app->response()->header('Cache-Control', 'max-age=0'); } });
protected function convertImpl($text) { $descr['book_title'] = $this->nameru; $descr['author'] = ""; foreach ([$this->author, $this->illustrator] as $aut) { if ($aut) { foreach (explode(',', $aut) as $au) { $a = explode(' ', trim($au)); $descr['author'] = (isset($descr['author']) ? $descr['author'] : '') . "<h1>"; $descr['author'] .= $this->escapexml(trim($au)); $descr['author'] .= "</h1>"; } } } $descr['annotation'] = ''; if ($this->annotation) { $this->annotation = preg_replace('@\\n@', '</p><p>', $this->annotation); $this->annotation = preg_replace("@'''(.*?)'''@", '<b>\\1</b>', $this->annotation); $this->annotation = preg_replace("@''(.*?)''@", '<i>\\1</i>', $this->annotation); $this->annotation = preg_replace('@<p></p>@', '<br/>', $this->annotation); $descr['annotation'] = "<h2>Аннотация</h2><p>{$this->annotation}</p>"; } $descr['coverpage'] = ''; $images = []; if ($this->covers) { $innerHeight = $this->height; $cover = $this->covers[0]; $image = $this->images[$cover]; /* Width and height are unimportant. Actual resizing is done not in this class. We must save aspect ratio though. */ $descr['coverpage'] = "<img src=\"" . $image['thumbnail'] . "\" width=\"" . $image['convert_width'] . "\" height=\"" . $image['convert_height'] . "\" />"; $images[] = $cover; $descr['coverpage_n'] = $cover; } // echo $descr['coverpage']; // exit; if ($this->translators) { foreach ($this->translators as $translator) { if (!array_key_exists('translator', $descr)) { $descr['translator'] = ''; } $descr['translator'] .= "<p name=\"translator\">" . $this->escapexml($translator) . "</p>"; } } if ($this->seriestitle) { $descr['sequence'] = "<h1>" . $this->escapexml($this->seriestitle) . ($this->seriesnum ? " {$this->seriesnum}" : '') . " </h1>"; } $descr['date2'] = date('j F Y, H:i', $this->touched); $descr['id'] = 'RuRa_' . str_replace('/', '_', $this->nameurl); if ($this->isbn) { $descr['isbn'] = ";isbn:{$this->isbn}"; } if ($this->command == 'RuRa-team') { $credit = "<h2>Реквизиты переводчиков</h2>\n \t\t\t\t <p>Над переводом работала команда <b>RuRa-team</b></p>\n"; foreach ($this->workers as $activity => $workers) { $credit .= '<p>' . $activity . ': <b>' . implode('</b>, <b>', $workers) . "</b></p>\n"; } $credit .= '<p>Самый свежий перевод всегда можно найти на сайте нашего проекта:</p> <p><a href="http://ruranobe.ru">http://ruranobe.ru</a></p> <p>Чтобы оставаться в курсе всех новостей, вступайте в нашу группу в Контакте:</p> <p><a href="http://vk.com/ru.ranobe">http://vk.com/ru.ranobe</a></p> <p>Для желающих отблагодарить переводчика материально имеются webmoney-кошельки команды:</p> <p><b>R125820793397</b></p> <p><b>U911921912420</b></p> <p><b>Z608138208963</b></p> <p>QIWI-кошелек:</p> <p><b>+79116857099</b></p> <p>Яндекс-деньги:</p> <p><b>410012692832515</b></p> <p>PayPal:</p> <p><b>paypal@ruranobe.ru</b></p> <p>А так же счет для перевода с кредитных карт:</p> <p><b>4890 4941 5384 9302</b></p> <p>Версия от ' . date('d.m.Y', $this->touched) . '</p> <p></p> <p></p> <p></p> <p><b>Любое распространение перевода за пределами нашего сайта запрещено. Если вы скачали файл на другом сайте - вы поддержали воров</b></p> <p></p> <p></p> <p></p>'; } elseif (strpos($this->command, 'RuRa-team') !== false) { $credit = "<h2>Реквизиты переводчиков</h2>\n\t\t\t\t\t\t <p>Над релизом работали {$this->command}</p>\n"; foreach ($this->workers as $activity => $workers) { $credit .= '<p>' . $activity . ': <b>' . implode('</b>, <b>', $workers) . "</b></p>\n"; } $credit .= '<p>Самый свежий перевод всегда можно найти на сайте нашего проекта:</p> <p><a l:href="http://ruranobe.ru">http://ruranobe.ru</a></p> <p>Чтобы оставаться в курсе всех новостей, вступайте в нашу группу в Контакте:</p> <p><a l:href="http://vk.com/ru.ranobe">http://vk.com/ru.ranobe</a></p> <p>Версия от ' . date('d.m.Y', $this->touched) . '</p> <p><b>Любое коммерческое использование данного текста или его фрагментов запрещено</b></p>'; } else { $credit = "<h2>Реквизиты переводчиков</h2>"; if ($this->command) { $credit .= "<p>Перевод команды {$this->command}</p>"; } foreach ($this->workers as $activity => $workers) { $credit .= '<p>' . $activity . ': <b>' . implode('</b>, <b>', $workers) . "</b></p>\n"; } $credit .= '<p>Версия от ' . date('d.m.Y', $this->touched) . '</p> <p><b>Любое коммерческое использование данного текста или его фрагментов запрещено</b></p>'; } if ($this->height == 0) { $text = preg_replace('/(<p[^>]*>)?<img[^>]*>(<\\/p>)?/u', '', $text); } else { for ($i = 1; $i < count($this->covers); ++$i) { $image = $this->images[$this->covers[$i]]; $text = "<img src=\"" . $image['thumbnail'] . "\" width=\"" . $image['convert_width'] . "\" height=\"" . $image['convert_height'] . "\" />" . $text; } $text = preg_replace_callback('/(<a[^>]*>)?<img[^>]*data-resource-id="(-?\\d*)"[^>]*>(<\\/a>)?/u', function ($match) use(&$images) { if ($match[2] < 0) { return ''; } $image = $this->images[$match[2]]; /* Width and height are unimportant. Actual resizing is done not in this class. We must save aspect ratio though. */ return "<img src=\"" . $image['thumbnail'] . "\" width=\"" . $image['convert_width'] . "\" height=\"" . $image['convert_height'] . "\" />"; }, $text); } $footnotes = array(); $footnotes_temp = explode(',;,', $this->footnotes); for ($i = 0; $i < sizeof($footnotes_temp); $i++) { if (is_numeric($footnotes_temp[$i])) { $footnotes[$footnotes_temp[$i]] = $footnotes_temp[$i + 1]; $i++; } } $text = trim($text); $epubText = "<html>\n\t<body>\n\t\t{$descr['coverpage']}\n\t\t{$descr['author']}\n\t\t{$descr['sequence']}\n\t {$descr['annotation']}\n\t\t{$credit}\n\t\t{$text}\n\t</body>\n\t</html>"; $epubText = preg_replace_callback('@(<span[^>]*><a href="#cite_note-(\\d*)"[^>]*>.{0,15}</span>)@', function ($match) use(&$footnotes) { $footnote = $footnotes[$match[2]]; $footnote = preg_replace('@</p>\\s*<p[^>]*>@', '<br/>', $footnote); if ($footnote) { return '<footnote>' . $footnote . '</footnote>'; } else { return $match[1]; } }, $epubText); //preg_replace('@cite_note-(\d*)@',"<footnote></footnote>", $epubText); //echo '<xmp>'.$epubText; //echo $footnotes[137603266]; //exit; //echo '<xmp>'.$epubText; //exit; $epubText = preg_replace('@section@', "div", $epubText); /* Delete extra <br/> tag before images */ $epubText = preg_replace('@<div>(.){0,20}<br\\/>(.){0,20}<img src@', '<div><img src', $epubText); /* Eliminate caret return before <h1> (Each div starts with caret return in h2d_htmlconverter.php) */ $epubText = preg_replace('@\\s*<div>(.{0,40})(<h1>.*?<\\/h1>)@', '\\1\\2<div>', $epubText); /* NGNL Specific names */ //$text=str_replace('<span style="position: relative; text-indent: 0;"><span style="display: inline-block; font-style: normal">『   』</span><span style="position: absolute; font-size: .7em; top: -11px; left: 50%"><span style="position: relative; left: -50%;">','『<sup>',$text); //$text=str_replace('</span></span></span>','</sup>』',$text); // Styles of elements in which footnote is nested should not count. Thus close them $epubText = preg_replace('@pb@', "br", $epubText); //echo '<xmp>'.$epubText; //exit; //PHPWord doesn't support tags nested in link element. Unnest images from them $epubText = preg_replace('@<a[^>]*>(<img[^>]*>)<\\/a>@', "\\1", $epubText); // Delete extra page breaks related to images. $epubText = preg_replace('@<div[^>]*>(.){0,20}(<img[^>]*>)(.){0,20}<\\/div>@', "\\1\\2\\3", $epubText); $epubText = preg_replace('@<p[^>]*>(.){0,20}(<img[^>]*>)(.){0,20}<\\/p>@', "\\1\\2\\3", $epubText); /* Swap h2 and img tags if img follows h2. (It gave a bad look in docx). */ $epubText = preg_replace('@(<h2>.{0,100}<\\/h2>)(<img[^>]*>)@', '\\2\\1', $epubText); /* After swap we often needs to further lift img tag in previous <div> or <p> tag */ $epubText = preg_replace('@<\\/div>(<img[^>]*>)<h2@', '\\1</div><h2', $epubText); $epubText = preg_replace('@<\\/p>(<img[^>]*>)<h2@', '\\1</p><h2', $epubText); //echo '<xmp>'.$epubText; //exit; $phpword_object = new \PhpOffice\PhpWord\PhpWord(); \PhpOffice\PhpWord\Settings::setCompatibility(false); $html_dom = new \simple_html_dom(); $html_dom->load($epubText); $html_dom_array = $html_dom->find('html', 0)->children(); $paths = htmltodocx_paths(); $initial_state = ['phpword_object' => &$phpword_object, 'base_root' => $paths['base_root'], 'base_path' => $paths['base_path'], 'current_style' => ['size' => '11'], 'parents' => [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, 'structure_headings' => true, 'structure_document' => true, 'style_sheet' => htmltodocx_styles_example()]; htmltodocx_insert_html($phpword_object, $html_dom_array[0]->nodes, $initial_state); //var_dump($html_dom_array[0]->nodes); // exit; $html_dom->clear(); unset($html_dom); $h2d_file_uri = tempnam(sys_get_temp_dir(), 'htd'); /*if ($h2d_file_uri === false) { var_dump(sys_get_temp_dir()); }*/ $objWriter = \PhpOffice\PhpWord\IOFactory::createWriter($phpword_object, 'Word2007'); $objWriter->save($h2d_file_uri); $bin = file_get_contents($h2d_file_uri); unlink($h2d_file_uri); //echo 'sdfjnsdlkvjn'; //exit; return $bin; }