Practical phpdocx

Headers and Footers

Introduction

In the new documents and templates, you can add headers and footers with text, images, tables and almost any kind of content.

Thanks to the WordFragment class you can easily add headers and footers, either simple ones or with multiple contents.

To make the header and footer insertion simpler, you can also use an extra template or templates from which you can import its headers and/or footers.

How to set the area of insertion of WordFragment

When creating a WordFragment object you can set where to add the contents.

By default, when creating a document with:

...simply add the content to the document. But, in the second parameter of the constructor you can define other areas:

  • defaultHeader or defaultFooter: for all headers and footers
  • firstHeader or firstFooter: just for the first page
  • evenHeader or evenFooter: for even number pages

For example, for adding a text as the header of all pages, call the code:

Headers

The available method for adding headers is the following:

You can use an array of WordFragment with it to add the content.

For example, to add an image as a header, first create the pertinent WordFragment:

Finally, insert the content in the header:

Footers

Inserting footers is like the headers process, only coding this method:

It counts with the same options as addHeader.

This way, to add the image in the footer, use the code:

Pagination

The method:

...allows to add pagination in headers and footers.

The available options are:

  • $type: numerical or alphabetical
  • %options: for text properties, such as size, color and alignment

For example, for adding a footer with numerical pagination, apply this method after creating the WordFragment:

Contents positioning

It's necessary to define a table to correctly organize the content of headers and footers. For example, to insert a logotype as an image, a text and a paginator after creating the pertinent WordFragment, generate the table as a new WordFragment:

And add this table to the header as a new element:

Replacing headers and footers in templates

It is possible to replace the defined placeholders in the template headers and footers. To do so, you can use the methods replaceVariableByText and replaceVariableByWordFragment.

When calling the method replaceVariableByText it is mandatory to specify the value of headers and footers with the parameter target, depending on where the placeholder is located.

Tips and Tricks

If the header or footer is created in Word, you can import it to the document with this method:

You have to indicate the path to the document to import, choosing:

  • headerAndFooter: for inserting both contents
  • header: for inserting just the header
  • footer: for inserting just the footer

For example, to import and add both headers and footers of the DOCX, use:

Next - Pictures and images