Practical phpdocx



Applying styles to a document with phpdocx is an easy task, either creating new content, importing them from a DOCX or even modifying existing styles in a document.

Apply styles to new contents

Methods to add contents to a document include options that let you apply styles. E.g., to associate bold and Arial as font-family with the addText method:

Do the same to create tables, lists, run-of-text contents and other elements. Available styles are described on the API documentation pages for each method.

Create styles from scratch

Styles created directly with methods such as addText or addTable are quite easy to run, but they have the disadvantage that they are not reusable. In other words, in order to apply the same styles to other content, it is mandatory to define them again.

MS Word allows applying custom styles to: paragraphs, characters (run-of-text contents), lists (numberings) and tables. Thanks to those custom styles it is possible to define reusable styles associated to a name. E.g., creating a custom paragraph style to be used to create several paragraphs:

Methods to add contents have options to apply custom styles.

Import styles

If, instead of creating the styles from scratch with phpdocx, you prefer to generate a document with MS Word with the desired styles, you may open it as DOCX template and use the included styles:

or import the styles from an external DOCX with the importStyles and importListStyle methods. The code that follows imports the style myStyle, existing in document.docx, and adds a new text while applying the imported style:

Information of the imported styles, as well as their names, can be obtained with the parseStyles method and the Indexer class.


Premium licenses include the sophisticated functionality DOCXCustomizer to modify existing styles on the fly.

To make it work it is required to call the customizeWordContent method along with the content to be changed and the new styles. E.g., to modify the paragraphs that contain the text Sed tu and associate bold, Times New Roman as font-family and 36 as font size:

Available options on DOCXCustomizer allow to easily choose the contents to be changed.

Tips and Tricks

Styles created with createCharacterStyle, createListStyle, createParagraphStyle and createTableStyle, as well as the imported ones, may also be used when converting HTML with embedHTML and replaceVariableByHTML.

Default styles applied to the document can be changed with the setDocumentDefaultStyles method.

Next - Blocks