/** * Get styles * * @return string */ private function writeStyles() { $css = '<style>' . PHP_EOL; // Default styles $defaultStyles = array('*' => array('font-family' => Settings::getDefaultFontName(), 'font-size' => Settings::getDefaultFontSize() . 'pt'), 'a.NoteRef' => array('text-decoration' => 'none'), 'hr' => array('height' => '1px', 'padding' => '0', 'margin' => '1em 0', 'border' => '0', 'border-top' => '1px solid #CCC')); foreach ($defaultStyles as $selector => $style) { $styleWriter = new GenericStyleWriter($style); $css .= $selector . ' {' . $styleWriter->write() . '}' . PHP_EOL; } // Custom styles $customStyles = Style::getStyles(); if (is_array($customStyles)) { foreach ($customStyles as $name => $style) { if ($style instanceof Font) { $styleWriter = new FontStyleWriter($style); if ($style->getStyleType() == 'title') { $name = str_replace('Heading_', 'h', $name); } else { $name = '.' . $name; } $css .= "{$name} {" . $styleWriter->write() . '}' . PHP_EOL; } elseif ($style instanceof Paragraph) { $styleWriter = new ParagraphStyleWriter($style); $name = '.' . $name; $css .= "{$name} {" . $styleWriter->write() . '}' . PHP_EOL; } } } $css .= '</style>' . PHP_EOL; return $css; }
/** * Test all methods * * @param string $zipClass * @covers ::<public> */ public function testZipArchive($zipClass = 'ZipArchive') { // Preparation $existingFile = __DIR__ . '/../_files/documents/sheet.xls'; $zipFile = __DIR__ . '/../_files/documents/ziptest.zip'; $destination1 = __DIR__ . '/../_files/documents/extract1'; $destination2 = __DIR__ . '/../_files/documents/extract2'; @mkdir($destination1); @mkdir($destination2); Settings::setZipClass($zipClass); $object = new ZipArchive(); $object->open($zipFile, ZipArchive::CREATE); $object->addFile($existingFile, 'xls/new.xls'); $object->addFromString('content/string.txt', 'Test'); $object->close(); $object->open($zipFile); // Run tests $this->assertEquals(0, $object->locateName('xls/new.xls')); $this->assertFalse($object->locateName('blablabla')); $this->assertEquals('Test', $object->getFromName('content/string.txt')); $this->assertEquals('Test', $object->getFromName('/content/string.txt')); $this->assertFalse($object->getNameIndex(-1)); $this->assertEquals('content/string.txt', $object->getNameIndex(1)); $this->assertFalse($object->extractTo('blablabla')); $this->assertTrue($object->extractTo($destination1)); $this->assertTrue($object->extractTo($destination2, 'xls/new.xls')); $this->assertFalse($object->extractTo($destination2, 'blablabla')); // Cleanup $this->deleteDir($destination1); $this->deleteDir($destination2); @unlink($zipFile); }
/** * @since 0.12.0 Throws CreateTemporaryFileException and CopyFileException instead of Exception. * * @param string $documentTemplate The fully qualified template filename. * * @throws \PhpOffice\PhpWord\Exception\CreateTemporaryFileException * @throws \PhpOffice\PhpWord\Exception\CopyFileException */ public function __construct($documentTemplate) { // Temporary document filename initialization $this->tempDocumentFilename = tempnam(Settings::getTempDir(), 'PhpWord'); if (false === $this->tempDocumentFilename) { throw new CreateTemporaryFileException(); } // Template file cloning if (false === copy($documentTemplate, $this->tempDocumentFilename)) { throw new CopyFileException($documentTemplate, $this->tempDocumentFilename); } // Temporary document content extraction $this->zipClass = new ZipArchive(); $this->zipClass->open($this->tempDocumentFilename); $index = 1; while (false !== $this->zipClass->locateName($this->getHeaderName($index))) { $this->tempDocumentHeaders[$index] = $this->fixBrokenMacros($this->zipClass->getFromName($this->getHeaderName($index))); $index++; } $index = 1; while (false !== $this->zipClass->locateName($this->getFooterName($index))) { $this->tempDocumentFooters[$index] = $this->fixBrokenMacros($this->zipClass->getFromName($this->getFooterName($index))); $index++; } $this->tempDocumentMainPart = $this->fixBrokenMacros($this->zipClass->getFromName('word/document.xml')); $this->temporaryWordRelDocumentPart = $this->zipClass->getFromName('word/_rels/document.xml.rels'); $this->temporaryContentType = $this->zipClass->getFromName('[Content_Types].xml'); // clean the temporary document $this->cleanTemporaryDocument(); }
/** * Create new XMLWriter * * @param int $tempLocation Temporary storage location * @param string $tempFolder Temporary storage folder */ public function __construct($tempLocation = self::STORAGE_MEMORY, $tempFolder = './') { // Create internal XMLWriter $this->xmlWriter = new \XMLWriter(); // Open temporary storage if ($tempLocation == self::STORAGE_MEMORY) { $this->xmlWriter->openMemory(); } else { // Create temporary filename $this->tempFile = @tempnam($tempFolder, 'xml'); // Fallback to memory when temporary file cannot be used // @codeCoverageIgnoreStart // Can't find any test case. Uncomment when found. if ($this->xmlWriter->openUri($this->tempFile) === false) { $this->xmlWriter->openMemory(); } // @codeCoverageIgnoreEnd } // Set xml Compatibility $compatibility = Settings::hasCompatibility(); if ($compatibility) { $this->xmlWriter->setIndent(false); $this->xmlWriter->setIndentString(''); } else { $this->xmlWriter->setIndent(true); $this->xmlWriter->setIndentString(' '); } }
/** * Create new XMLWriter * * @param int $tempLocation Temporary storage location * @param string $tempFolder Temporary storage folder */ public function __construct($tempLocation = self::STORAGE_MEMORY, $tempFolder = './') { // Create internal XMLWriter $this->xmlWriter = new \XMLWriter(); // Open temporary storage if ($tempLocation == self::STORAGE_MEMORY) { $this->xmlWriter->openMemory(); } else { // Create temporary filename $this->tempFile = @tempnam($tempFolder, 'xml'); // Open storage if ($this->xmlWriter->openUri($this->tempFile) === false) { // Fallback to memory... $this->xmlWriter->openMemory(); } } // Set xml Compatibility $compatibility = Settings::getCompatibility(); if ($compatibility) { $this->xmlWriter->setIndent(false); $this->xmlWriter->setIndentString(''); } else { $this->xmlWriter->setIndent(true); $this->xmlWriter->setIndentString(' '); } }
/** * Write link element. * * @return void */ public function write() { $xmlWriter = $this->getXmlWriter(); $element = $this->getElement(); if (!$element instanceof \PhpOffice\PhpWord\Element\Link) { return; } $rId = $element->getRelationId() + ($element->isInSection() ? 6 : 0); $this->startElementP(); $xmlWriter->startElement('w:hyperlink'); if ($element->isInternal()) { $xmlWriter->writeAttribute('w:anchor', $element->getSource()); } else { $xmlWriter->writeAttribute('r:id', 'rId' . $rId); } $xmlWriter->writeAttribute('w:history', '1'); $xmlWriter->startElement('w:r'); $this->writeFontStyle(); $xmlWriter->startElement('w:t'); $xmlWriter->writeAttribute('xml:space', 'preserve'); if (Settings::isOutputEscapingEnabled()) { $xmlWriter->text($element->getText()); } else { $xmlWriter->writeRaw($element->getText()); } $xmlWriter->endElement(); // w:t $xmlWriter->endElement(); // w:r $xmlWriter->endElement(); // w:hyperlink $this->endElementP(); // w:p }
/** * Write element */ public function write() { $xmlWriter = $this->getXmlWriter(); $element = $this->getElement(); if (!$element instanceof \PhpOffice\PhpWord\Element\Link) { return; } if (!$this->withoutP) { $xmlWriter->startElement('text:p'); // text:p } $xmlWriter->startElement('text:a'); $xmlWriter->writeAttribute('xlink:type', 'simple'); $xmlWriter->writeAttribute('xlink:href', $element->getSource()); if (Settings::isOutputEscapingEnabled()) { $xmlWriter->text($element->getText()); } else { $xmlWriter->writeRaw($element->getText()); } $xmlWriter->endElement(); // text:a if (!$this->withoutP) { $xmlWriter->endElement(); // text:p } }
/** * @since 0.12.0 Throws CreateTemporaryFileException and CopyFileException instead of Exception. * * @param string $documentTemplate The fully qualified template filename. * @throws \PhpOffice\PhpWord\Exception\CreateTemporaryFileException * @throws \PhpOffice\PhpWord\Exception\CopyFileException */ public function __construct($documentTemplate) { // Temporary document filename initialization $this->temporaryDocumentFilename = tempnam(Settings::getTempDir(), 'PhpWord'); if (false === $this->temporaryDocumentFilename) { throw new CreateTemporaryFileException(); } // Template file cloning if (false === copy($documentTemplate, $this->temporaryDocumentFilename)) { throw new CopyFileException($documentTemplate, $this->temporaryDocumentFilename); } // Temporary document content extraction $this->zipClass = new ZipArchive(); $this->zipClass->open($this->temporaryDocumentFilename); $index = 1; while ($this->zipClass->locateName($this->getHeaderName($index)) !== false) { $this->temporaryDocumentHeaders[$index] = $this->zipClass->getFromName($this->getHeaderName($index)); $index++; } $index = 1; while ($this->zipClass->locateName($this->getFooterName($index)) !== false) { $this->temporaryDocumentFooters[$index] = $this->zipClass->getFromName($this->getFooterName($index)); $index++; } $this->temporaryDocumentMainPart = $this->zipClass->getFromName('word/document.xml'); }
/** * Create a new Template Object * * @param string $strFilename * @throws \PhpOffice\PhpWord\Exception\Exception */ public function __construct($strFilename) { $this->tempFileName = tempnam(sys_get_temp_dir(), ''); if ($this->tempFileName === false) { throw new Exception('Could not create temporary file with unique name in the default temporary directory.'); } // Copy the source File to the temp File if (!copy($strFilename, $this->tempFileName)) { throw new Exception("Could not copy the template from {$strFilename} to {$this->tempFileName}."); } $zipClass = Settings::getZipClass(); $this->zipClass = new $zipClass(); $this->zipClass->open($this->tempFileName); // Find and load headers and footers $index = 1; while ($this->zipClass->locateName($this->getHeaderName($index)) !== false) { $this->headerXMLs[$index] = $this->zipClass->getFromName($this->getHeaderName($index)); $index++; } $index = 1; while ($this->zipClass->locateName($this->getFooterName($index)) !== false) { $this->footerXMLs[$index] = $this->zipClass->getFromName($this->getFooterName($index)); $index++; } $this->documentXML = $this->zipClass->getFromName('word/document.xml'); }
function __construct($testResultsHandler) { Autoloader::register(); Settings::loadConfig(); $this->testResultsHandler = $testResultsHandler; $this->phpWord = new PhpWord(); }
/** * Write preserve text element. * * @return void */ public function write() { $xmlWriter = $this->getXmlWriter(); $element = $this->getElement(); if (!$element instanceof \PhpOffice\PhpWord\Element\PreserveText) { return; } $texts = $element->getText(); if (!is_array($texts)) { $texts = array($texts); } $this->startElementP(); foreach ($texts as $text) { if (substr($text, 0, 1) == '{') { $text = substr($text, 1, -1); $xmlWriter->startElement('w:r'); $xmlWriter->startElement('w:fldChar'); $xmlWriter->writeAttribute('w:fldCharType', 'begin'); $xmlWriter->endElement(); $xmlWriter->endElement(); $xmlWriter->startElement('w:r'); $this->writeFontStyle(); $xmlWriter->startElement('w:instrText'); $xmlWriter->writeAttribute('xml:space', 'preserve'); if (Settings::isOutputEscapingEnabled()) { $xmlWriter->text($text); } else { $xmlWriter->writeRaw($text); } $xmlWriter->endElement(); $xmlWriter->endElement(); $xmlWriter->startElement('w:r'); $xmlWriter->startElement('w:fldChar'); $xmlWriter->writeAttribute('w:fldCharType', 'separate'); $xmlWriter->endElement(); $xmlWriter->endElement(); $xmlWriter->startElement('w:r'); $xmlWriter->startElement('w:fldChar'); $xmlWriter->writeAttribute('w:fldCharType', 'end'); $xmlWriter->endElement(); $xmlWriter->endElement(); } else { $xmlWriter->startElement('w:r'); $this->writeFontStyle(); $xmlWriter->startElement('w:t'); $xmlWriter->writeAttribute('xml:space', 'preserve'); if (Settings::isOutputEscapingEnabled()) { $xmlWriter->text($this->getText($text)); } else { $xmlWriter->writeRaw($this->getText($text)); } $xmlWriter->endElement(); $xmlWriter->endElement(); } } $this->endElementP(); // w:p }
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}`; }
/** * Convert twip value * * @param int|float $value * @param int|float $default * @return int|float */ protected function convertTwip($value, $default = 0) { $unit = Settings::getMeasurementUnit(); if ($unit == Settings::UNIT_TWIP || $value == $default) { return $value; } else { return $value * $unit; } }
/** * Clear document */ public static function clear() { if (file_exists(self::$file)) { unlink(self::$file); } if (is_dir(Settings::getTempDir() . '/PhpWord_Unit_Test/')) { self::deleteDir(Settings::getTempDir() . '/PhpWord_Unit_Test/'); } }
/** * Create new instance * * @param PhpWord $phpWord PhpWord object */ public function __construct(PhpWord $phpWord) { parent::__construct($phpWord); $configFile = Settings::getPdfRendererPath() . '/dompdf_config.inc.php'; if (file_exists($configFile)) { require_once $configFile; } else { throw new Exception('Unable to load PDF Rendering library'); } }
/** * Convert twip value * * @param int|float $value * @param int $default (int|float) * @return int|float */ protected function convertTwip($value, $default = 0) { $factors = array(Settings::UNIT_CM => 567, Settings::UNIT_MM => 56.7, Settings::UNIT_INCH => 1440, Settings::UNIT_POINT => 20, Settings::UNIT_PICA => 240); $unit = Settings::getMeasurementUnit(); $factor = 1; if (in_array($unit, $factors) && $value != $default) { $factor = $factors[$unit]; } return $value * $factor; }
/** * Create new instance */ public function __construct() { $this->usePclzip = Settings::getZipClass() != 'ZipArchive'; if ($this->usePclzip) { if (!defined('PCLZIP_TEMPORARY_DIR')) { define('PCLZIP_TEMPORARY_DIR', sys_get_temp_dir() . '/'); } require_once 'PCLZip/pclzip.lib.php'; } }
/** * Write element */ public function write() { $xmlWriter = $this->getXmlWriter(); $element = $this->getElement(); if (!$element instanceof \PhpOffice\PhpWord\Element\Text) { return; } $fontStyle = $element->getFontStyle(); $paragraphStyle = $element->getParagraphStyle(); // @todo Commented for TextRun. Should really checkout this value // $fStyleIsObject = ($fontStyle instanceof Font) ? true : false; $fStyleIsObject = false; if ($fStyleIsObject) { // Don't never be the case, because I browse all sections for cleaning all styles not declared throw new Exception('PhpWord : $fStyleIsObject wouldn\'t be an object'); } else { if (!$this->withoutP) { $xmlWriter->startElement('text:p'); // text:p } if (empty($fontStyle)) { if (empty($paragraphStyle)) { $xmlWriter->writeAttribute('text:style-name', 'P1'); } elseif (is_string($paragraphStyle)) { $xmlWriter->writeAttribute('text:style-name', $paragraphStyle); } if (Settings::isOutputEscapingEnabled()) { $xmlWriter->text($element->getText()); } else { $xmlWriter->writeRaw($element->getText()); } } else { if (empty($paragraphStyle)) { $xmlWriter->writeAttribute('text:style-name', 'Standard'); } elseif (is_string($paragraphStyle)) { $xmlWriter->writeAttribute('text:style-name', $paragraphStyle); } // text:span $xmlWriter->startElement('text:span'); if (is_string($fontStyle)) { $xmlWriter->writeAttribute('text:style-name', $fontStyle); } if (Settings::isOutputEscapingEnabled()) { $xmlWriter->text($element->getText()); } else { $xmlWriter->writeRaw($element->getText()); } $xmlWriter->endElement(); } if (!$this->withoutP) { $xmlWriter->endElement(); // text:p } } }
/** * Test normal construct */ public function testConstruct() { define('DOMPDF_ENABLE_AUTOLOAD', false); $file = __DIR__ . '/../_files/temp.pdf'; $rendererName = Settings::PDF_RENDERER_DOMPDF; $rendererLibraryPath = realpath(PHPWORD_TESTS_BASE_DIR . '/../vendor/dompdf/dompdf'); Settings::setPdfRenderer($rendererName, $rendererLibraryPath); $writer = new PDF(new PhpWord()); $writer->save($file); $this->assertTrue(file_exists($file)); unlink($file); }
/** * Write list item * * @return string */ public function write() { if (!$this->element instanceof \PhpOffice\PhpWord\Element\ListItem) { return ''; } if (Settings::isOutputEscapingEnabled()) { $content = '<p>' . $this->escaper->escapeHtml($this->element->getTextObject()->getText()) . '</p>' . PHP_EOL; } else { $content = '<p>' . $this->element->getTextObject()->getText() . '</p>' . PHP_EOL; } return $content; }
/** * Write heading * * @return string */ public function write() { if (!$this->element instanceof \PhpOffice\PhpWord\Element\Title) { return ''; } $tag = 'h' . $this->element->getDepth(); if (Settings::isOutputEscapingEnabled()) { $text = $this->escaper->escapeHtml($this->element->getText()); } else { $text = $this->element->getText(); } $content = "<{$tag}>{$text}</{$tag}>" . PHP_EOL; return $content; }
/** * Test construct */ public function testConstruct() { $file = __DIR__ . "/../../_files/tcpdf.pdf"; $phpWord = new PhpWord(); $section = $phpWord->addSection(); $section->addText('Test 1'); $rendererName = Settings::PDF_RENDERER_TCPDF; $rendererLibraryPath = realpath(PHPWORD_TESTS_BASE_DIR . '/../vendor/tecnick.com/tcpdf'); Settings::setPdfRenderer($rendererName, $rendererLibraryPath); $writer = new PDF($phpWord); $writer->save($file); $this->assertTrue(file_exists($file)); unlink($file); }
/** * Get XML Writer * * @return \PhpOffice\Common\XMLWriter */ protected function getXmlWriter() { $useDiskCaching = false; if (!is_null($this->parentWriter)) { if ($this->parentWriter->isUseDiskCaching()) { $useDiskCaching = true; } } if ($useDiskCaching) { return new XMLWriter(XMLWriter::STORAGE_DISK, $this->parentWriter->getDiskCachingDirectory(), Settings::hasCompatibility()); } else { return new XMLWriter(XMLWriter::STORAGE_MEMORY, './', Settings::hasCompatibility()); } }
/** * Test construct */ public function testConstruct() { $file = __DIR__ . '/../../_files/mpdf.pdf'; $phpWord = new PhpWord(); $section = $phpWord->addSection(); $section->addText(htmlspecialchars('Test 1', ENT_COMPAT, 'UTF-8')); $rendererName = Settings::PDF_RENDERER_MPDF; $rendererLibraryPath = realpath(PHPWORD_TESTS_BASE_DIR . '/../vendor/mpdf/mpdf'); Settings::setPdfRenderer($rendererName, $rendererLibraryPath); $writer = new PDF($phpWord); $writer->save($file); $this->assertTrue(file_exists($file)); unlink($file); }
/** * Write link * * @return string */ public function write() { if (!$this->element instanceof \PhpOffice\PhpWord\Element\Link) { return ''; } $content = ''; $content .= $this->writeOpening(); if (Settings::isOutputEscapingEnabled()) { $content .= "<a href=\"{$this->escaper->escapeHtmlAttr($this->element->getSource())}\">{$this->escaper->escapeHtml($this->element->getText())}</a>"; } else { $content .= "<a href=\"{$this->element->getSource()}\">{$this->element->getText()}</a>"; } $content .= $this->writeClosing(); return $content; }
/** * Instantiate a new renderer of the configured type within this container class * * @param \PhpOffice\PhpWord\PhpWord $phpWord * @throws \PhpOffice\PhpWord\Exception\Exception */ public function __construct(PhpWord $phpWord) { $pdfLibraryName = Settings::getPdfRendererName(); $pdfLibraryPath = Settings::getPdfRendererPath(); if (is_null($pdfLibraryName) || is_null($pdfLibraryPath)) { throw new Exception("PDF rendering library or library path has not been defined."); } $includePath = str_replace('\\', '/', get_include_path()); $rendererPath = str_replace('\\', '/', $pdfLibraryPath); if (strpos($rendererPath, $includePath) === false) { set_include_path(get_include_path() . PATH_SEPARATOR . $pdfLibraryPath); } $rendererName = get_class($this) . '\\' . $pdfLibraryName; $this->renderer = new $rendererName($phpWord); }
/** * Test set/get abstract renderer properties */ public function testSetGetAbstractRendererProperties() { define('DOMPDF_ENABLE_AUTOLOAD', false); $rendererName = Settings::PDF_RENDERER_DOMPDF; $rendererLibraryPath = realpath(PHPWORD_TESTS_BASE_DIR . '/../vendor/dompdf/dompdf'); Settings::setPdfRenderer($rendererName, $rendererLibraryPath); $writer = new PDF(new PhpWord()); $writer->setFont('arial'); $this->assertEquals('arial', $writer->getFont()); $writer->setPaperSize(); $this->assertEquals(9, $writer->getPaperSize()); $writer->setOrientation(); $this->assertEquals('default', $writer->getOrientation()); $writer->setTempDir(Settings::getTempDir()); $this->assertEquals(Settings::getTempDir(), $writer->getTempDir()); }
/** * Write element */ public function write() { $xmlWriter = $this->getXmlWriter(); $element = $this->getElement(); if (!$element instanceof \PhpOffice\PhpWord\Element\Title) { return; } $xmlWriter->startElement('text:h'); $xmlWriter->writeAttribute('text:outline-level', $element->getDepth()); if (Settings::isOutputEscapingEnabled()) { $xmlWriter->text($element->getText()); } else { $xmlWriter->writeRaw($element->getText()); } $xmlWriter->endElement(); // text:h }
/** * Create new instance * * @param PhpWord $phpWord PhpWord object * @throws \PhpOffice\PhpWord\Exception\Exception */ public function __construct(PhpWord $phpWord) { parent::__construct($phpWord); $includeFile = Settings::getPdfRendererPath() . '/' . $this->includeFile; if (file_exists($includeFile)) { /** @noinspection PhpIncludeInspection Dynamic includes */ require_once $includeFile; } else { // @codeCoverageIgnoreStart // Can't find any test case. Uncomment when found. throw new Exception('Unable to load PDF Rendering library'); // @codeCoverageIgnoreEnd } }
function mergeDOCX($source_file, $merged_file) { // Important: we get the merge data first, because the phpWord // autoloader included below stuffs up the Jethro autoloader // and causes errors. $data = array_values($this->getMergeData()); // NB THIS FILE HAS BEEN CHANGED! require_once 'include/phpword/src/PhpWord/Autoloader.php'; \PhpOffice\PhpWord\Autoloader::register(); \PhpOffice\PhpWord\Settings::setTempDir(dirname($source_file)); $templateProcessor = new \PhpOffice\PhpWord\TemplateProcessor($source_file); if (!$templateProcessor->cloneBlock('MERGEBLOCK', count($data))) { $vars = $templateProcessor->getVariables(); if (empty($vars)) { trigger_error("You don't seem to have included any \${keywords} in your file; cannot merge"); return; } $templateProcessor->cloneRow(reset($vars), count($data)); } foreach ($data as $num => $row) { foreach ($row as $k => $v) { $templateProcessor->setValue(strtoupper($k) . '#' . ($num + 1), $this->xmlEntities($v)); } } $templateProcessor->saveAs($merged_file); }