Adding content to a document
To explain how the library works, let's create a new empty file and add different types of content to it: heading, paragraphs, lists, tables and page breaks.
As a first step, create the document, instantiating the class CreateDocx:
Now, add the new contents for this $docx object, always following the visualization order.
Titles are strings highlighted in the document. To add a title, call this method:
$text is the string, $level is the heading level and $options is the text properties as color, spacing or bold properties, underline, and so on.
For this document insert a text line with color and font size 24:
The method for adding paragraphs is the following:
The first parameter can be a string or a string array. In this array, you can add keys and values to modify the text, color, font type, bold style or size.
The second parameter is optional. It defines the properties of the paragraph, like background color, border, alignment and spacing.
Now, add to the document a string with background and text color:
If you prefer to add two or more strings, create a new array with the texts. For example:
The ‘text’ key is used in every position of the array for adding the text. The bold font type is enabled in the second paragraph only.
This is the method for adding lists to a document:
This method includes the following parameters:
- $data, array with the information to add to the list
- $styleType, for list types
- '0', list without styles
- '1', unordered lists
- '2', ordered lists
- $options, for colors and other text properties
Let's add an ordered list of Internet browsers to the document:
To nest lists, just add new arrays in the values array. For example:
Including tables is very similar to adding lists, but you must work with nested arrays to define the text and its properties.
This is the method you have to choose:
The $taleData parameter is an array which can contain strings or WordFragment objects and the cell specific properties. The other two parameters define the table global properties and particular row properties such as borders, sizes and spans.
Now, insert the usage statistics for the browsers previously defined for the list in the document:
To make page or line breaks, run the method:
You just need to indicate the type of break, ‘line’ or ‘page’, and the number of breaks to apply.
For example, to make a page break:
For adding a link, use this method:
The options array defines the link destination and the text properties, as well as the text used as a link in the first paragraph.
Here's a simple example:
This method links the text to the URL www.phpdocx.com with a color and no underline.
In addition to the mentioned methods, there are many others that will be reviewed in detail later on.
It's not necessary to call the addText method for each paragraph you want to add. Thanks to the option lineBreak you can make a line break before and/or after the chain.