PHPWord is a library written in pure PHP that provides a set of classes to write to and read from different document file formats. The current version of PHPWord supports Microsoft [Office Open XML](http://en.wikipedia.org/wiki/Office_Open_XML) (OOXML or OpenXML), OASIS [Open Document Format for Office Applications](http://en.wikipedia.org/wiki/OpenDocument) (OpenDocument or ODF), and [Rich Text Format](http://en.wikipedia.org/wiki/Rich_Text_Format) (RTF).
No Windows operating system is needed for usage because the resulting DOCX, ODT, or RTF files can be opened by all major [word processing softwares](http://en.wikipedia.org/wiki/List_of_word_processors).
PHPWord is an open source project licensed under LGPL. PHPWord is [unit tested](https://travis-ci.org/PHPOffice/PHPWord) to make sure that the released versions are stable.
**Want to contribute?** [Fork us](https://github.com/PHPOffice/PHPWord/fork) or [submit](https://github.com/PHPOffice/PHPWord/issues) your bug reports or feature requests to us.
## Features
- Set document properties, e.g. title, subject, and creator.
- Create document sections with different settings, e.g. portrait/landscape, page size, and page numbering
- Create header and footer for each sections
- Set default font type, font size, and paragraph style
- Use UTF-8 and East Asia fonts/characters
- Define custom font styles (e.g. bold, italic, color) and paragraph styles (e.g. centered, multicolumns, spacing) either as named style or inline in text
- Insert paragraphs, either as a simple text or complex one (a text run) that contains other elements
- Insert titles (headers) and table of contents
- Insert text breaks and page breaks
- Insert and format images, either local, remote, or as page watermarks
- Insert binary OLE Objects such as Excel or Visio
- Insert and format table with customized properties for each rows (e.g. repeat as header row) and cells (e.g. background color, rowspan, colspan)
- Insert list items as bulleted, numbered, or multilevel
- Insert hyperlinks
- Insert footnotes and endnotes
- Create document from templates
- Use XSL 1.0 style sheets to transform main document part of OOXML template
- ... and many more features on progress
## File formats
Below are the supported features for each file formats.
There are two ways to install PHPWord, i.e. via [Composer](http://getcomposer.org/) or manually by downloading the library.
### Using Composer
To install via Composer, add the following lines to your `composer.json`:
```json
{
"require": {
"phpoffice/phpword": "dev-master"
}
}
```
### Manual install
To install manually, [download PHPWord package from github](https://github.com/PHPOffice/PHPWord/archive/master.zip). Extract the package and put the contents to your machine. To use the library, include `src/PhpWord/Autoloader.php` in your script and invoke `Autoloader::register`.
After installation, you can browse and use the samples that we've provided, either by command line or using browser. If you can access your PHPWord library folder using browser, point your browser to the `samples` folder, e.g. `http://localhost/PhpWord/samples/`.
# General usage
## Basic example
The following is a basic example of the PHPWord library. More examples are provided in the [samples folder](https://github.com/PHPOffice/PHPWord/tree/master/samples/).
```php
require_once 'src/PhpWord/Autoloader.php';
\PhpOffice\PhpWord\Autoloader::register();
$phpWord = new \PhpOffice\PhpWord\PhpWord();
// Every element you want to append to the word document is placed in a section.
// To create a basic section:
$section = $phpWord->addSection();
// After creating a section, you can append elements:
$section->addText('Hello world!');
// You can directly style your text by giving the addText function an array:
The `PhpOffice\PhpWord\Settings` class provides some options that will affect the behavior of PHPWord. Below are the options.
### XML Writer compatibility
This option sets [XMLWriter::setIndent](http://www.php.net/manual/en/function.xmlwriter-set-indent.php) and [XMLWriter::setIndentString](http://www.php.net/manual/en/function.xmlwriter-set-indent-string.php). The default value of this option is `true` (compatible), which is [required for OpenOffice](https://github.com/PHPOffice/PHPWord/issues/103) to render OOXML document correctly. You can set this option to `false` during development to make the resulting XML file easier to read.
By default, PHPWord uses PHP [ZipArchive](http://php.net/manual/en/book.zip.php) to read or write ZIP compressed archive and the files inside them. If you can't have ZipArchive installed on your server, you can use pure PHP library alternative, [PCLZip](http://www.phpconcept.net/pclzip/), which included with PHPWord.
Containers are objects where you can put elements (texts, lists, tables, etc). There are 3 main containers, i.e. sections, headers, and footers. There are 3 elements that can also act as containers, i.e. textruns, table cells, and footnotes.
## Sections
Every visible element in word is placed inside of a section. To create a section, use the following code:
Each section can have its own header reference. To create a header use the `addHeader` method:
```php
$header = $section->addHeader();
```
Be sure to save the result in a local object. You can use all elements that are available for the footer. See "Footer" section for detail. Additionally, only inside of the header reference you can add watermarks or background pictures. See "Watermarks" section.
## Footers
Each section can have its own footer reference. To create a footer, use the `addFooter` method:
```php
$footer = $section->addFooter();
```
Be sure to save the result in a local object to add elements to a footer. You can add the following elements to footers:
- Texts `addText` and `createTextrun`
- Text breaks
- Images
- Tables
- Preserve text
See the "Elements" section for the detail of each elements.
## Other containers
Textruns, table cells, and footnotes are elements that can also act as containers. See the corresponding "Elements" section for the detail of each elements.
# Elements
Below are the matrix of element availability in each container. The column shows the containers while the rows lists the elements.
| Num | Element | Section | Header | Footer | Cell | Text Run | Footnote |
Text can be added by using `addText` and `addTextRun` method. `addText` is used for creating simple paragraphs that only contain texts with the same style. `addTextRun` is used for creating complex paragraphs that contain text with different style (some bold, other italics, etc) or other elements, e.g. images or links. The syntaxes are as follow:
You can use the `$fontStyle` and `$paragraphStyle` variable to define text formatting. There are 2 options to style the inserted text elements, i.e. inline style by using array or defined style by adding style definition.
Inline style examples:
```php
$fontStyle = array('name' => 'Times New Roman', 'size' => 9);
$paragraphStyle = array('align' => 'both');
$section->addText('I am simple paragraph', $fontStyle, $paragraphStyle);
$textrun = $section->addTextRun();
$textrun->addText('I am bold', array('bold' => true));
$textrun->addText('I am italic', array('italic' => true));
$textrun->addText('I am colored, array('color' => 'AACC00'));
-`hint` Font content type, *default*, *eastAsia*, or *cs*
-`bold` Bold, *true* or *false*
-`italic` Italic, *true* or *false*
-`superScript` Superscript, *true* or *false*
-`subScript` Subscript, *true* or *false*
-`underline` Underline, *dash*, *dotted*, etc.
-`strikethrough` Strikethrough, *true* or *false*
-`color` Font color, e.g. *FF0000*
-`fgColor` Font highlight color, e.g. *yellow*, *green*, *blue*
-`bgColor` Font background color, e.g. *FF0000*
#### Paragraph style
Available paragraph styles:
-`align` Paragraph alignment, *left*, *right* or *center*
-`spaceBefore` Space before paragraph
-`spaceAfter` Space after paragraph
-`indent` Indent by how much
-`hanging` Hanging by how much
-`basedOn` Parent style
-`next` Style for next paragraph
-`widowControl` Allow first/last line to display on a separate page, *true* or *false*
-`keepNext` Keep paragraph with next paragraph, *true* or *false*
-`keepLines` Keep all lines on one page, *true* or *false*
-`pageBreakBefore` Start paragraph on next page, *true* or *false*
-`lineHeight` text line height, e.g. *1.0*, *1.5*, ect...
-`tabs` Set of custom tab stops
### Titles
If you want to structure your document or build table of contents, you need titles or headings. To add a title to the document, use the `addTitleStyle` and `addTitle` method.
-`$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 "Paragraph style" section.
Advanced usage:
You can also create your own numbering style by changing the `$listStyle` parameter with the name of your numbering style.
-`align` Image alignment, *left*, *right*, or *center*
-`marginTop` Top margin in inches, can be negative
-`marginLeft` Left margin in inches, can be negative
-`wrappingStyle` Wrapping style, *inline*, *square*, *tight*, *behind*, or *infront*
### Watermarks
To add a watermark (or page background image), your section needs a header reference. After creating a header, you can use the `addWatermark` method to add a watermark.
-`$minDepth`: Minimum depth of header to be shown. Default 1
-`$maxDepth`: Maximum depth of header to be shown. Default 9
Options for `$tocStyle`:
-`tabLeader` Fill type between the title text and the page number. Use the defined constants in PHPWord\_Style\_TOC.
-`tabPos` The position of the tab where the page number appears in twips.
-`indent` The indent factor of the titles in twips.
## Footnotes & endnotes
You can create footnotes with `addFootnote` and endnotes with `addEndnote` in texts or textruns, but it's recommended to use textrun to have better layout. You can use `addText`, `addLink`, `addTextBreak`, `addImage`, `addObject` on footnotes and endnotes.
On textrun:
```php
$textrun = $section->addTextRun();
$textrun->addText('Lead text.');
$footnote = $textrun->addFootnote();
$footnote->addText('Footnote text can have ');
$footnote->addLink('http://test.com', 'links');
$footnote->addText('.');
$footnote->addTextBreak();
$footnote->addText('And text break.');
$textrun->addText('Trailing text.');
$endnote = $textrun->addEndnote();
$endnote->addText('Endnote put at the end');
```
On text:
```php
$section->addText('Lead text.');
$footnote = $section->addFootnote();
$footnote->addText('Footnote text.');
```
The footnote reference number will be displayed with decimal number starting from 1. This number use `FooterReference` style which you can redefine by `addFontStyle` method. Default value for this style is `array('superScript' => true)`;
## Checkboxes
Checkbox elements can be added to sections or table cells by using `addCheckBox`.
You can create a docx template with included search-patterns that can be replaced by any value you wish. Only single-line values can be replaced. To load a template file, use the `loadTemplate` method. After loading the docx template, you can use the `setValue` method to change the value of a search pattern. The search-pattern model is: `${search-pattern}`. It is not possible to add new PHPWord elements to a loaded template file.
## Is this the same with PHPWord that I found in CodePlex?
No. This one is much better with tons of new features that you can’t find in PHPWord 0.6.3. The development in CodePlex is halted and switched to GitHub to allow more participation from the crowd. The more the merrier, right?
## I’ve been running PHPWord from CodePlex flawlessly, but I can’t use the latest PHPWord from GitHub. Why?
PHPWord requires PHP 5.3+ since 0.8, while PHPWord 0.6.3 from CodePlex can run with PHP 5.2. There’s a lot of new features that we can get from PHP 5.3 and it’s been around since 2009! You should upgrade your PHP version to use PHPWord 0.8+.
# References
## Formal specifications
- [Office Open XML (OOXML) (ECMA-376) Schema](http://www.schemacentral.com/sc/ooxml/ss.html)
- [Oasis OpenDocument Standard Version 1.2](http://docs.oasis-open.org/office/v1.2/os/OpenDocument-v1.2-os.html)
- [Rich Text Format (RTF) Specification, version 1.9.1](http://www.microsoft.com/en-us/download/details.aspx?id=10725)
## Other resources
- [DocumentFormat.OpenXml.Wordprocessing Namespace on MSDN](http://msdn.microsoft.com/en-us/library/documentformat.openxml.wordprocessing%28v=office.14%29.aspx)