### Install PHPWord using Composer Source: https://github.com/phpoffice/phpword/blob/master/docs/install.md To install PHPWord via Composer, add the provided lines to your `composer.json` file. This specifies `phpoffice/phpword` as a development dependency, allowing Composer to manage its installation and autoloading. ```json { "require": { "phpoffice/phpword": "dev-master" } } ``` -------------------------------- ### Register PHPWord Autoloader for Manual Installation Source: https://github.com/phpoffice/phpword/blob/master/docs/install.md After manually downloading and extracting the PHPWord library, use this snippet to include the autoloader file. This ensures that PHPWord classes are correctly loaded when your application runs, making the library's components available. ```php addSection(); $section->addImage( 'mars.jpg', array( 'width' => 100, 'height' => 100, 'marginTop' => -1, 'marginLeft' => -1, 'wrappingStyle' => 'behind' ) ); $footer = $section->addFooter(); $footer->addImage('http://example.com/image.php'); $textrun = $section->addTextRun(); $textrun->addImage('http://php.net/logo.jpg'); $source = file_get_contents('/path/to/my/images/earth.jpg'); $textrun->addImage($source); ``` -------------------------------- ### Install PHPWord using Composer Source: https://github.com/phpoffice/phpword/blob/master/README.md Instructions to install PHPWord as a project dependency using Composer. This includes commands for both the latest stable version and the latest unreleased development version. ```Shell composer require phpoffice/phpword composer require phpoffice/phpword:dev-master ``` -------------------------------- ### Load PHPWord Default Configuration Source: https://github.com/phpoffice/phpword/blob/master/docs/install.md This code snippet demonstrates how to load the default PHPWord configuration. It assumes a `phpword.ini` file is present in a standard location, allowing the library to apply predefined settings without specifying a path. ```php addSection(); $properties = new RubyProperties(); $properties->setAlignment(RubyProperties::ALIGNMENT_RIGHT_VERTICAL); $properties->setFontFaceSize(10); $properties->setFontPointsAboveBaseText(4); $properties->setFontSizeForBaseText(18); $properties->setLanguageId('ja-JP'); $baseTextRun = new TextRun(null); $baseTextRun->addText('私'); $rubyTextRun = new TextRun(null); $rubyTextRun->addText('わたし'); $section->addRuby($baseTextRun, $rubyTextRun, $properties); ``` -------------------------------- ### Set page numbering start for a section in PHPWord Source: https://github.com/phpoffice/phpword/blob/master/docs/usage/containers.md This snippet illustrates two methods to set the starting page number for a section. Method 1 applies the `pageNumberingStart` style directly during section creation, while Method 2 retrieves the section's style object and then sets the property. ```php addSection(array('pageNumberingStart' => 1)); // Method 2 $section = $phpWord->addSection(); $section->getStyle()->setPageNumberingStart(1); ``` -------------------------------- ### Load PHPWord Configuration from Custom Path Source: https://github.com/phpoffice/phpword/blob/master/docs/install.md To load PHPWord configuration from a specific file path, use this snippet. Provide the absolute or relative path to your custom `phpword.ini` file, ensuring the library uses your desired settings from the specified location. ```php addSection(); $section->addText('Hello World!'); $file = 'HelloWorld.docx'; header("Content-Description: File Transfer"); header('Content-Disposition: attachment; filename="' . $file . '"'); 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"); ``` -------------------------------- ### Add Ruby Phonetic Guide to a Title in PhpWord Source: https://github.com/phpoffice/phpword/blob/master/docs/usage/elements/ruby.md Illustrates how to add a Ruby phonetic guide within a document title in PhpWord. It sets up a custom title style, then creates `RubyProperties` and `TextRun` objects for the base and ruby text, similar to a regular ruby element. Finally, it adds the `TextRun` containing the ruby element as a title to the section. ```php $phpWord = new PhpWord(); $fontStyle = new Font(); $fontStyle->setAllCaps(true); $fontStyle->setBold(true); $fontStyle->setSize(24); $phpWord->addTitleStyle(1, ['name' => 'Arial', 'size' => 24, 'bold' => true, 'color' => '990000']); $section = $phpWord->addSection(); $properties = new RubyProperties(); $properties->setAlignment(RubyProperties::ALIGNMENT_RIGHT_VERTICAL); $properties->setFontFaceSize(10); $properties->setFontPointsAboveBaseText(4); $properties->setFontSizeForBaseText(18); $properties->setLanguageId('ja-JP'); $baseTextRun = new TextRun(null); $baseTextRun->addText('私'); $rubyTextRun = new TextRun(null); $rubyTextRun->addText('わたし'); $textRun = new TextRun(); $textRun->addRuby($baseTextRun, $rubyTextRun, $properties); $section->addTitle($textRun, 1); ``` -------------------------------- ### Configure Mirror Margins with Custom Paper and Page Sizes in PhpWord Source: https://github.com/phpoffice/phpword/blob/master/docs/usage/introduction.md This example combines mirror margins with specific paper and page size settings. It demonstrates how to set up a document for printing on A4 landscape paper that folds into A5 portrait pages, using `Converter::cmToTwip` for precise measurements. ```php getSettings()->setMirrorMargins(true); $phpWord->addSection([ 'paperSize' => 'A4', 'orientation' => 'landscape', 'pageSizeW' => Converter::cmToTwip(14.85), 'pageSizeH' => Converter::cmToTwip(21), ]); ``` -------------------------------- ### Define Custom Macro Opening Characters (PHP) Source: https://github.com/phpoffice/phpword/blob/master/docs/usage/template.md Allows customization of the opening characters for search patterns (macros) in the template. This example sets `{#` as the new opening delimiter. ```php setMacroOpeningChars('{#'); ``` -------------------------------- ### Add Specific Field Types (XE, INDEX, REF) in PhpWord Source: https://github.com/phpoffice/phpword/blob/master/docs/usage/elements/field.md This example demonstrates adding specific field types: 'XE' (Index Entry), 'INDEX', and 'REF' (Reference to a bookmark). It shows how to use a simple string or a 'TextRun' object for the field text to enable rich formatting, and how to apply specific options for the INDEX field. ```php addText('My '); $fieldText->addText('bold index', ['bold' => true]); $fieldText->addText(' entry'); $section->addField('XE', array(), array(), $fieldText); // this actually adds the index $section->addField('INDEX', array(), array('\\e "\t" \\h "A" \\c "3"'), 'right click to update index'); // Adding reference to a bookmark $fieldText->addField('REF', [ 'name' => 'bookmark' ], [ 'InsertParagraphNumberRelativeContext', 'CreateHyperLink' ]); ``` -------------------------------- ### Line Numbering Style Properties in PHPWord Source: https://github.com/phpoffice/phpword/blob/master/docs/usage/containers.md This API documentation outlines the available properties for configuring line numbering within a section. It details parameters such as starting value, increment, distance from text, and restart settings. ```APIDOC Line Numbering Style Properties: start: Line numbering starting value increment: Line number increments distance: Distance between text and line numbering in twip restart: Line numbering restart setting (continuous|newPage|newSection) ``` -------------------------------- ### Configure multicolumn section layout in PHPWord Source: https://github.com/phpoffice/phpword/blob/master/docs/usage/containers.md This example demonstrates two ways to create a multicolumn section. Method 1 sets `breakType` to 'continuous' and `colsNum` to 2 directly during section creation. Method 2 retrieves the section's style object and sets these properties separately. ```php addSection(array('breakType' => 'continuous', 'colsNum' => 2)); // Method 2 $section = $phpWord->addSection(); $section->getStyle()->setBreakType('continuous'); $section->getStyle()->setColsNum(2); ``` -------------------------------- ### Define Custom Macro Opening and Closing Characters (PHP) Source: https://github.com/phpoffice/phpword/blob/master/docs/usage/template.md Enables setting both the opening and closing characters for macros simultaneously. This example configures macros to use `{#` for opening and `#}` for closing, resulting in patterns like `{#search-pattern#}`. ```php setMacroChars('{#', '#}'); ``` -------------------------------- ### Define section style array in PHPWord Source: https://github.com/phpoffice/phpword/blob/master/docs/usage/containers.md This example shows how to define an associative array for section styling. It sets the page orientation to landscape, top margin to 600 twips, and the number of columns to 2, which can be passed to the `addSection` method. ```php 'landscape', 'marginTop' => 600, 'colsNum' => 2, ); ``` -------------------------------- ### Programmatically Specify PDF Renderer in PhpWord Source: https://github.com/phpoffice/phpword/blob/master/docs/usage/writers.md Details how to set the desired PDF rendering library (e.g., MPDF, DomPDF, TCPDF) and its installation path using `Settings::setPdfRendererName` and `Settings::setPdfRendererPath`. This is a crucial step for PDF generation and must be done before creating the PDF writer. ```php Settings::setPdfRendererName(Settings::PDF_RENDERER_MPDF); Settings::setPdfRendererPath(__DIR__ . '/../vendor/mpdf/mpdf'); ``` -------------------------------- ### Define and Apply Custom Multilevel Numbering Styles in PHPWord Source: https://github.com/phpoffice/phpword/blob/master/docs/usage/elements/list.md This example demonstrates how to create a custom multilevel numbering style using `addNumberingStyle` in PHPWord, specifying format, text, and indentation for each level. It then shows how to apply this custom style to list items using `addListItem`. ```php addNumberingStyle( 'multilevel', array( 'type' => 'multilevel', 'levels' => array( array('format' => 'decimal', 'text' => '%1.', 'left' => 360, 'hanging' => 360, 'tabPos' => 360), array('format' => 'upperLetter', 'text' => '%2.', 'left' => 720, 'hanging' => 360, 'tabPos' => 720) ) ) ); $section->addListItem('List Item I', 0, null, 'multilevel'); $section->addListItem('List Item I.a', 1, null, 'multilevel'); $section->addListItem('List Item I.b', 1, null, 'multilevel'); $section->addListItem('List Item II', 0, null, 'multilevel'); ``` -------------------------------- ### Define Custom Macro Closing Characters (PHP) Source: https://github.com/phpoffice/phpword/blob/master/docs/usage/template.md Allows customization of the closing characters for search patterns (macros) in the template. This example sets `#}` as the new closing delimiter. ```php setMacroClosingChars('#}'); ``` -------------------------------- ### PHPWord: Convert Measurement Units to Twips Source: https://github.com/phpoffice/phpword/blob/master/docs/usage/introduction.md This snippet demonstrates how to convert common measurement units like points, inches, and centimeters into twips, the base length unit in Open Office XML. It shows examples for setting paragraph spacing and section margins using these conversions. ```php addParagraphStyle('My Style', array( 'spaceAfter' => \PhpOffice\PhpWord\Shared\Converter::pointToTwip(6)) ); $section = $phpWord->addSection(); $sectionStyle = $section->getStyle(); // half inch left margin $sectionStyle->setMarginLeft(\PhpOffice\PhpWord\Shared\Converter::inchToTwip(.5)); // 2 cm right margin $sectionStyle->setMarginRight(\PhpOffice\PhpWord\Shared\Converter::cmToTwip(2)); ``` -------------------------------- ### Clone Template Block Multiple Times (PHP) Source: https://github.com/phpoffice/phpword/blob/master/docs/usage/template.md Explains how to duplicate a defined block within a template a specified number of times. The example shows cloning a block named 'block_name' three times, with an option to rename internal macros. ```clean ${block_name} Customer: ${customer_name} Address: ${customer_address} ${/block_name} ``` ```php cloneBlock('block_name', 3, true, true); ``` ```clean Customer: ${customer_name#1} Address: ${customer_address#1} Customer: ${customer_name#2} Address: ${customer_address#2} Customer: ${customer_name#3} Address: ${customer_address#3} ``` -------------------------------- ### Control Footnote Numbering and Position in PhpWord Source: https://github.com/phpoffice/phpword/blob/master/docs/usage/elements/note.md Illustrates how to customize footnote properties such as position (e.g., beneath text), number format (e.g., lower Roman), starting number, and restart behavior (e.g., each page) using the `FootnoteProperties` class. These properties are then applied to the section. ```php setPos(\PhpOffice\PhpWord\ComplexType\FootnoteProperties::POSITION_BENEATH_TEXT); //set the number format to use (decimal (default), upperRoman, upperLetter, ...) $fp->setNumFmt(\PhpOffice\PhpWord\SimpleType\NumberFormat::LOWER_ROMAN); //force starting at other than 1 $fp->setNumStart(2); //when to restart counting (continuous (default), eachSect, eachPage) $fp->setNumRestart(\PhpOffice\PhpWord\ComplexType\FootnoteProperties::RESTART_NUMBER_EACH_PAGE); //And finaly, set it on the Section $section->setFootnoteProperties($fp); ``` -------------------------------- ### Applying Track Changes to Text Elements in PhpWord Source: https://github.com/phpoffice/phpword/blob/master/docs/usage/elements/trackchanges.md This PHP snippet demonstrates how to apply track changes (insertions and deletions) to text elements within a PhpOffice/PhpWord document. It illustrates two methods: `setChangeInfo()` for detailed change information including author and timestamp, and `setTrackChange()` for applying a `TrackChange` instance directly. The example shows adding text, marking insertions, and marking deletions. ```php addSection(); $textRun = $section->addTextRun(); $text = $textRun->addText('Hello World! Time to '); $text = $textRun->addText('wake ', array('bold' => true)); $text->setChangeInfo(TrackChange::INSERTED, 'Fred', time() - 1800); $text = $textRun->addText('up'); $text->setTrackChange(new TrackChange(TrackChange::INSERTED, 'Fred')); $text = $textRun->addText('go to sleep'); $text->setChangeInfo(TrackChange::DELETED, 'Barney', new \DateTime('@' . (time() - 3600))); ``` -------------------------------- ### Save PhpWord Document as ODText File Source: https://github.com/phpoffice/phpword/blob/master/docs/usage/writers.md Shows how to save a PhpWord document in the OpenDocument Text (ODText) format. The `IOFactory::createWriter` method is used with the 'ODText' type to generate the output, saving to a `.docx` extension as per the example. ```php save(__DIR__ . '/sample.docx'); ``` -------------------------------- ### Add Formula using PhpOffice/Math Source: https://github.com/phpoffice/phpword/blob/master/docs/usage/elements/formula.md This PHP code snippet demonstrates how to create a mathematical formula, specifically a fraction (π/2), using the PhpOffice\Math library. It initializes a Fraction element, sets its numerator and denominator, then adds it to a Math object, which is finally added as a formula to a document section. ```php setDenominator(new Element\Numeric(2)) ->setNumerator(new Element\Identifier('π')) ; $math = new Math(); $math->add($fraction); $formula = $section->addFormula($math); ``` -------------------------------- ### Set Complex Value in PhpWord Template Source: https://github.com/phpoffice/phpword/blob/master/docs/usage/template.md Replaces a macro placeholder (`${macro}`) with a complex object, such as a `TextRun`, allowing for rich text formatting or other complex content insertion. Refer to `Sample_40_TemplateSetComplexValue.php` for more examples. ```php addText('by a red italic text', array('italic' => true, 'color' => 'red')); $templateProcessor->setComplexValue('inline', $inline); ``` -------------------------------- ### Create and Save Basic PHPWord Document with Text Styling Source: https://github.com/phpoffice/phpword/blob/master/docs/usage/introduction.md This snippet demonstrates how to initialize a new PHPWord document, add a section, and insert text with various font styling methods: inline, using a named style, and applying an explicitly created font style object. It also shows how to save the generated document in Word2007 (.docx), ODText (.odt), and HTML (.html) formats. ```php addSection(); // Adding Text element to the Section having font styled by default... $section->addText( '"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( '"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( '"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('"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. */ ``` -------------------------------- ### Add Basic List Items and Understand Parameters in PHPWord Source: https://github.com/phpoffice/phpword/blob/master/docs/usage/elements/list.md This snippet illustrates the fundamental methods `addListItem` and `addListItemRun` for creating lists in PHPWord. `addListItem` is for simple text, while `addListItemRun` allows for complex content. It also details the parameters for these methods, including text, depth, font style, list style (e.g., `TYPE_NUMBER`, `TYPE_BULLET_FILLED`), and paragraph style. ```php addListItem($text, [$depth], [$fontStyle], [$listStyle], [$paragraphStyle]); $listItemRun = $section->addListItemRun([$depth], [$listStyle], [$paragraphStyle]) ``` ```APIDOC Parameters: - $text: Text that appears in the document. - $depth: Depth of list item. - $fontStyle: See Styles > Font.. - $listStyle: List style of the current element TYPE_NUMBER, TYPE_ALPHANUM, TYPE_BULLET_FILLED, etc. See list of constants in PHPWord\Style\ListItem. - $paragraphStyle: See Styles > Paragraph.. ``` -------------------------------- ### Load Template File with TemplateProcessor (PHP) Source: https://github.com/phpoffice/phpword/blob/master/docs/usage/template.md Initializes a new instance of the TemplateProcessor class, loading a specified OOXML document template file. This is the first step to begin processing a template. ```php setCheckbox('checkbox', true); ``` -------------------------------- ### Configure PDF Renderer via phpword.ini File Source: https://github.com/phpoffice/phpword/blob/master/docs/usage/writers.md Illustrates an alternative method to specify the PDF renderer and its path using a `phpword.ini` configuration file. This allows for external configuration of the PDF rendering engine without modifying code. ```ini pdfRendererName = MPDF ;DomPDF, TCPDF, MPDF pdfRendererPath = /path/to/your/renderer/folder ``` -------------------------------- ### Set Complex Block in PhpWord Template Source: https://github.com/phpoffice/phpword/blob/master/docs/usage/template.md Replaces a macro placeholder (`${macro}`) with a complex block object, such as a `Table`, enabling the insertion of structured content like tables or other complex document elements. Refer to `Sample_40_TemplateSetComplexValue.php` for more examples. ```php 12, 'borderColor' => 'green', 'width' => 6000, 'unit' => TblWidth::TWIP)); $table->addRow(); $table->addCell(150)->addText('Cell A1'); $table->addCell(150)->addText('Cell A2'); $table->addCell(150)->addText('Cell A3'); $table->addRow(); $table->addCell(150)->addText('Cell B1'); $table->addCell(150)->addText('Cell B2'); $table->addCell(150)->addText('Cell B3'); $templateProcessor->setComplexBlock('table', $table); ``` -------------------------------- ### Create and load HTML reader in PHP Source: https://github.com/phpoffice/phpword/blob/master/docs/usage/readers.md Initializes an HTML reader using `IOFactory::createReader('HTML')` and loads a sample HTML file from the specified directory. This reader is used to process HTML documents. ```php load(__DIR__ . '/sample.html'); ``` -------------------------------- ### Create Numbered Headings in PHPWord Source: https://github.com/phpoffice/phpword/blob/master/docs/howto.md This snippet illustrates how to define and apply numbered heading styles in a PHPWord document. It involves setting up a multilevel numbering style and then associating it with specific title styles using 'pStyle' and 'numStyle' properties. ```php addNumberingStyle( 'hNum', array('type' => 'multilevel', 'levels' => array( array('pStyle' => 'Heading1', 'format' => 'decimal', 'text' => '%1'), array('pStyle' => 'Heading2', 'format' => 'decimal', 'text' => '%1.%2'), array('pStyle' => 'Heading3', 'format' => 'decimal', 'text' => '%1.%2.%3') ) ) ); $phpWord->addTitleStyle(1, array('size' => 16), array('numStyle' => 'hNum', 'numLevel' => 0)); $phpWord->addTitleStyle(2, array('size' => 14), array('numStyle' => 'hNum', 'numLevel' => 1)); $phpWord->addTitleStyle(3, array('size' => 12), array('numStyle' => 'hNum', 'numLevel' => 2); $section->addTitle('Heading 1', 1); $section->addTitle('Heading 2', 2); $section->addTitle('Heading 3', 3); ``` -------------------------------- ### PhpOffice/PhpWord Title Methods API Reference Source: https://github.com/phpoffice/phpword/blob/master/docs/usage/elements/title.md Detailed API documentation for the `addTitleStyle` and `addTitle` methods within the PhpOffice/PhpWord library. It outlines the required parameters, their types, and descriptions for each method, essential for correctly implementing titles and headings. ```APIDOC addTitleStyle: $depth: int $fontStyle: array (See Styles > Font) $paragraphStyle: array (See Styles > Paragraph) addTitle: $text: string | \PhpOffice\PhpWord\Element\TextRun (Text to be displayed in the document) $depth: int $pageNumber: int (Number of the page) ``` -------------------------------- ### Set Image Values in Template (PHP) Source: https://github.com/phpoffice/phpword/blob/master/docs/usage/template.md Demonstrates how to replace image placeholders in a template with actual images. It supports various placeholder formats and allows specifying image properties like width, height, and aspect ratio, including using a closure for dynamic image generation. ```clean ${CompanyLogo} ${UserLogo:50:50} ${Name} - ${City} - ${Street} ``` ```php setValue('Name', 'John Doe'); $templateProcessor->setValue(array('City', 'Street'), array('Detroit', '12th Street')); $templateProcessor->setImageValue('CompanyLogo', 'path/to/company/logo.png'); $templateProcessor->setImageValue('UserLogo', array('path' => 'path/to/logo.png', 'width' => 100, 'height' => 100, 'ratio' => false)); $templateProcessor->setImageValue('FeatureImage', function () { // Closure will only be executed if the replacement tag is found in the template return array('path' => SlowFeatureImageGenerator::make(), 'width' => 100, 'height' => 100, 'ratio' => false); }); ``` -------------------------------- ### PhpOffice\PhpWord\NumberingLevel Style Options Reference Source: https://github.com/phpoffice/phpword/blob/master/docs/usage/styles/numberinglevel.md Defines the configurable properties for NumberingLevel styles in PhpOffice\PhpWord, including their descriptions, accepted values, and cross-references to other relevant styles or constants. ```APIDOC NumberingLevel Style Options: alignment: Description: Supports all alignment modes since 1st Edition of ECMA-376 standard up till ISO/IEC 29500:2012. See: \PhpOffice\PhpWord\SimpleType\Jc class constants for possible values. font: Description: Font name. format: Description: Numbering format bullet|decimal|upperRoman|lowerRoman|upperLetter|lowerLetter. hanging: Description: See paragraph style. hint: Description: See font style. left: Description: See paragraph style. restart: Description: Restart numbering level symbol. start: Description: Starting value. suffix: Description: Content between numbering symbol and paragraph text tab|space|nothing. tabPos: Description: See paragraph style. text: Description: Numbering level text e.g. %1 for nonbullet or bullet character. ``` -------------------------------- ### Activate and Configure Track Revisions in PhpWord Source: https://github.com/phpoffice/phpword/blob/master/docs/usage/introduction.md This snippet shows how to enable track revisions and further configure it to not track moves (treating them as deletions and additions) and not track formatting changes, providing fine-grained control over revision tracking. ```php getSettings()->setTrackRevisions(true); $phpWord->getSettings()->setDoNotTrackMoves(true); $phpWord->getSettings()->setDoNotTrackFormatting(true); ``` -------------------------------- ### Create and save documents with PHPWord Source: https://github.com/phpoffice/phpword/blob/master/README.md This PHP code snippet demonstrates the fundamental steps to create a new document using the PHPWord library. It shows how to add a section, insert text with default styling, apply inline font styles, use named font styles, and apply explicitly created font style objects. Finally, it illustrates how to save the generated document in Word2007 (.docx), ODT (.odt), and HTML (.html) formats. ```php addSection(); // Adding Text element to the Section having font styled by default... $section->addText( "\"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( "\"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( "\"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('"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. */ ``` -------------------------------- ### Save PhpWord Document as HTML File Source: https://github.com/phpoffice/phpword/blob/master/docs/usage/writers.md Demonstrates the fundamental process of converting a PhpWord document to an HTML file. It initializes the HTML writer using `IOFactory::createWriter` and then saves the document to a specified path. ```php save(__DIR__ . '/sample.html'); ``` -------------------------------- ### Create a basic section in PHPWord Source: https://github.com/phpoffice/phpword/blob/master/docs/usage/containers.md This snippet demonstrates how to create a new section within a PHPWord document using the `addSection` method. The `$sectionStyle` parameter is optional and can be used to apply specific styling to the section. ```php addSection($sectionStyle); ``` -------------------------------- ### Add Link Within a Title in PHPWord Source: https://github.com/phpoffice/phpword/blob/master/docs/howto.md This example demonstrates how to embed a hyperlink within a title or apply a link directly to a title in a PHPWord document. It shows using 'addTextRun' with a 'HeadingN' style for inline links and 'addLink' for direct title links, along with defining a custom font style for links. ```php addTitleStyle(1, array('size' => 16, 'bold' => true)); $phpWord->addTitleStyle(2, array('size' => 14, 'bold' => true)); $phpWord->addFontStyle('Link', array('color' => '0000FF', 'underline' => 'single')); $section = $phpWord->addSection(); // Textrun $textrun = $section->addTextRun('Heading1'); $textrun->addText('The '); $textrun->addLink('https://github.com/PHPOffice/PHPWord', 'PHPWord', 'Link'); // Link $section->addLink('https://github.com/', 'GitHub', 'Link', 'Heading2'); ``` -------------------------------- ### Configure even and odd headers in PHPWord settings Source: https://github.com/phpoffice/phpword/blob/master/docs/usage/containers.md This snippet shows how to enable distinct headers for even and odd pages. It accesses the global settings object via `getSettings()` and then calls `setEvenAndOddHeaders(true)` to activate this feature. ```php getSettings()->setEvenAndOddHeaders(true); ``` -------------------------------- ### Define and Apply Table Styles in PHPWord Source: https://github.com/phpoffice/phpword/blob/master/docs/usage/elements/table.md Illustrates how to define custom table styles using addTableStyle, specifying properties like border color, border size, and cell margin. It also shows how to apply a different style to the first row and then associate the defined style with a new table. ```php '006699', 'borderSize' => 6, 'cellMargin' => 50 ); $firstRowStyle = array('bgColor' => '66BBFF'); $phpWord->addTableStyle('myTable', $tableStyle, $firstRowStyle); $table = $section->addTable('myTable'); ``` -------------------------------- ### Set PHPWord Zip Class Source: https://github.com/phpoffice/phpword/blob/master/docs/usage/introduction.md This snippet demonstrates how to configure PHPWord to use the PclZip library instead of the default Zip extension for handling ZIP compressed archives. This is useful if the Zip extension is not available on your server. ```php load(__DIR__ . '/sample.rtf'); ``` -------------------------------- ### Add Tables, Rows, and Cells in PHPWord Source: https://github.com/phpoffice/phpword/blob/master/docs/usage/elements/table.md Demonstrates the basic usage of addTable, addRow, and addCell methods to construct a table structure within a PHPWord document. It shows how to initialize a table, add a row to it, and then add a cell to that row, optionally applying predefined styles. ```php addTable([$tableStyle]); $table->addRow([$height], [$rowStyle]); $cell = $table->addCell($width, [$cellStyle]); ``` -------------------------------- ### Set Proof State for Spelling and Grammar Checks in PhpWord Source: https://github.com/phpoffice/phpword/blob/master/docs/usage/introduction.md This snippet demonstrates how to explicitly set the proofing state for grammar and spelling. Marking them as 'dirty' forces a re-check when the document is opened, while 'clean' indicates no re-check is needed. ```php setGrammar(\PhpOffice\PhpWord\ComplexType\ProofState::CLEAN); $proofState->setSpelling(\PhpOffice\PhpWord\ComplexType\ProofState::DIRTY); $phpWord->getSettings()->setProofState($proofState); ``` -------------------------------- ### Set Document Properties and Metadata in PhpWord Source: https://github.com/phpoffice/phpword/blob/master/docs/usage/introduction.md This snippet demonstrates how to access and set various document properties and metadata, such as creator, company, title, description, category, last modified by, creation/modification dates, subject, and keywords, using the `getDocInfo()` method. ```php getDocInfo(); $properties->setCreator('My name'); $properties->setCompany('My factory'); $properties->setTitle('My title'); $properties->setDescription('My description'); $properties->setCategory('My category'); $properties->setLastModifiedBy('My name'); $properties->setCreated(mktime(0, 0, 0, 3, 12, 2014)); $properties->setModified(mktime(0, 0, 0, 3, 14, 2014)); $properties->setSubject('My subject'); $properties->setKeywords('my, key, word'); ``` -------------------------------- ### PhpOffice PhpWord Table Style Options Source: https://github.com/phpoffice/phpword/blob/master/docs/usage/styles/table.md Defines the available style options for tables in PhpOffice/PhpWord, including alignment, colors, borders, margins, width, and layout. ```APIDOC Table Style Options: alignment: Supports all alignment modes (\PhpOffice\PhpWord\SimpleType\JcTable, \PhpOffice\PhpWord\SimpleType\Jc constants) bgColor: Background color (e.g., '9966CC') border(Top|Right|Bottom|Left)Color: Border color (e.g., '9966CC') border(Top|Right|Bottom|Left)Size: Border size in twip cellMargin(Top|Right|Bottom|Left): Cell margin in twip indent: Table indent from leading margin (instance of \PhpOffice\PhpWord\ComplexType\TblWidth) width: Table width in Fiftieths of a Percent or Twentieths of a Point unit: The unit to use for the width (one of \PhpOffice\PhpWord\SimpleType\TblWidth, defaults to 'auto') layout: Table layout ('fixed' or 'autofit', see \PhpOffice\PhpWord\Style\Table constants) cellSpacing: Cell spacing in twip position: Floating Table Positioning options (see below) bidiVisual: Present table as Right-To-Left (boolean) ``` -------------------------------- ### Create and load Word2007 reader in PHP Source: https://github.com/phpoffice/phpword/blob/master/docs/usage/readers.md Initializes a Word2007 reader using `IOFactory::createReader('Word2007')` and loads a sample Office Open XML WordprocessingML document from the specified directory. This reader is used to process .docx files. ```php load(__DIR__ . '/sample.docx'); ``` -------------------------------- ### Create and load MsDoc reader in PHP Source: https://github.com/phpoffice/phpword/blob/master/docs/usage/readers.md Initializes an MsDoc reader using `IOFactory::createReader('MsDoc')` and loads a sample Microsoft Word 97-2003 document from the specified directory. This reader is used to process .doc files. ```php load(__DIR__ . '/sample.doc'); ``` -------------------------------- ### Change ZIP Adapter for Word2007 Writer in PhpWord Source: https://github.com/phpoffice/phpword/blob/master/docs/usage/writers.md Explains how to customize the ZIP adapter used by the Word2007 writer, allowing selection between `ZipArchiveAdapter` (default) and `PclZipAdapter`. This is useful for environments with specific ZIP library requirements or compatibility issues. ```php setZipAdapter(new PclZipAdapter()); $writer->save(__DIR__ . '/sample.docx'); ``` -------------------------------- ### Enable Mirror Margins for Double-Sided Documents in PhpWord Source: https://github.com/phpoffice/phpword/blob/master/docs/usage/introduction.md This snippet shows how to enable mirror margins, which are essential for setting up facing pages in double-sided documents like books or magazines, ensuring proper layout for binding. ```php getSettings()->setMirrorMargins(true); ``` -------------------------------- ### Configure PHPWord XML Writer Compatibility Source: https://github.com/phpoffice/phpword/blob/master/docs/usage/introduction.md This snippet shows how to set the XML Writer compatibility option in PHPWord. Setting it to `false` can make the resulting XML file more readable during development, but `true` (the default) is required for OpenOffice to correctly render OOXML documents. ```php getSettings()->getDocumentProtection(); $documentProtection->setEditing(DocProtect::READ_ONLY); $documentProtection->setPassword('myPassword'); ``` -------------------------------- ### Apply line numbering to a section in PHPWord Source: https://github.com/phpoffice/phpword/blob/master/docs/usage/containers.md This snippet shows two methods to enable line numbering for a section. Method 1 applies an empty `lineNumbering` array directly during section creation. Method 2 retrieves the section's style object and then sets the `lineNumbering` property. ```php addSection(array('lineNumbering' => array())); // Method 2 $section = $phpWord->addSection(); $section->getStyle()->setLineNumbering(array()); ``` -------------------------------- ### Create and load ODText reader in PHP Source: https://github.com/phpoffice/phpword/blob/master/docs/usage/readers.md Initializes an ODText reader using `IOFactory::createReader('ODText')` and loads a sample OpenDocument Text file from the specified directory. This reader is used to process .odt files. ```php load(__DIR__ . '/sample.odt'); ``` -------------------------------- ### Configure HTML Writer Options in PhpWord Source: https://github.com/phpoffice/phpword/blob/master/docs/usage/writers.md Illustrates how to customize the HTML output by setting default generic font and whitespace handling. These options, `setDefaultGenericFont` and `setDefaultWhiteSpace`, provide fine-grained control over the generated HTML's presentation. ```php setDefaultGenericFont('serif'); $writer->setDefaultWhiteSpace('pre-wrap'); $writer->save(__DIR__ . '/sample.html'); ``` -------------------------------- ### PHPWord Add Image Method Signature and Parameters Source: https://github.com/phpoffice/phpword/blob/master/docs/usage/elements/image.md Illustrates the `addImage` method signature in PHPWord, detailing its parameters. The `$src` parameter accepts a local path, URL, or image data string, with a security warning against user-generated input. The optional `$style` parameter refers to image styling options. ```php addImage($src, [$style]); ``` -------------------------------- ### PHPWord addTOC Method Parameters and TOC Style Options Source: https://github.com/phpoffice/phpword/blob/master/docs/usage/elements/toc.md This API documentation details the parameters for the `addTOC` method and the configurable options for the `$tocStyle` array in PhpOffice/PhpWord. It specifies the purpose and default values for each parameter, including how to control the appearance and depth of the generated Table of Contents. ```APIDOC addTOC( $fontStyle: array, $tocStyle: array, $minDepth: int = 1, $maxDepth: int = 9 ) $fontStyle: See font style section. $tocStyle: See available options below. $minDepth: Minimum depth of header to be shown. Default 1. $maxDepth: Maximum depth of header to be shown. Default 9. $tocStyle Options: tabLeader: Fill type between the title text and the page number. Use the defined constants in \PhpOffice\PhpWord\Style\TOC. tabPos: The position of the tab where the page number appears in twip. indent: The indent factor of the titles in twip. ``` -------------------------------- ### PhpOffice PhpWord Image Style Options Reference Source: https://github.com/phpoffice/phpword/blob/master/docs/usage/styles/image.md Defines the available style options for images within the PhpOffice/PhpWord library, including properties for dimensions, margins, alignment, and text wrapping behavior. These options are typically passed as an array to image insertion methods. ```APIDOC Image Style Options: alignment: Alignment of the image. See \PhpOffice\PhpWord\SimpleType\Jc class for details. height: Height in points (pt). marginLeft: Left margin in inches (can be negative). marginTop: Top margin in inches (can be negative). width: Width in points (pt). wrappingStyle: Text wrapping style (inline, square, tight, behind, or infront). wrapDistanceTop: Top text wrapping distance in pixels. wrapDistanceBottom: Bottom text wrapping distance in pixels. wrapDistanceLeft: Left text wrapping distance in pixels. wrapDistanceRight: Right text wrapping distance in pixels. ```