Practical phpdocx

Pictures and images

Introduction

Adding images to new documents is as easy as inserting texts, either in the body of the document, header, footer or background.

If you use a template, you can both replace an existing image and replace a text placeholder for an image.

Valid format files for working with images are JPG, PNG and GIF.

Adding images

The method for adding new images is:

Backgrounds

If instead of inserting an image in the document you want to place it as a background, run this method:

You have to indicate the path of the image in it. For example:

Replacing pictures/images in a template

phpdocx counts with two methods for replacing images in templates.

First method

It replaces an image present in a document for the new one. The available parameters are:

  • $variable: Name of the placeholder
  • $scr: Path to the new image
  • The third parameter is optional. It's an array which can have these keys:
    • firstMatch: It just replaces the first placeholder, with the name of the placeholder
    • target: Area of the variable like document, header or footer; width and height, in cm or auto to take the original size
    • dpi: Dots per inch

To make this replacement you have to to define an image or images attribute to replace.

In order to do this just right click on it, open the image properties and search for the field alternate text (this name may vary in each version of Word MS). Type in this field the name of the placeholder, for example: $IMAGE$.

For example, to replace an image in the header:

Second method

The second method for adding images in a template replaces a placeholder for a WordFragment. This is the method to use:

For example, for replacing the placeholder IMAGE for a picture, after creating the new image instantiating the class WordFragment typr this code:

And replace it by calling this method:

Tips and tricks

To add a background color instead of a background image, call the method:

The value of $color is hexadecimal, for example:

With the preset settings of Word the background images won't appear in the printed document. Add it as a watermark with this method:

This method is available for the Advanced and Premium licenses.

Replacing more than an image in a template.

Due to Word internal functioning, to replace two or more images in a template with the method replacePlaceholderImage, it's necessary to insert a different image for each one you want to replace. Otherwise just the last image will be replaced.

This happens because Word reuses the same picture in the file DOCX, which causes a wrong replacement when there are more than one substitution in the template.

This won't happen working with the method replaceVariableByWordFragment.

Next - Graphic charts