Practical javadocx

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 addImage:

Backgrounds

If instead of inserting an image in the document you want to place it as a background, use addBackgroundImage:

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

Replacing pictures/images in a template

javadocx includes two methods to replace images in templates.

replacePlaceholderImage method

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

  • "variable": Name of the placeholder.
  • "src": Path to the new image.
  • The third parameter is optional. It's an OptionsReplacePlaceholderImage object which can have the followings options:
    • "firstMatch": It just replaces the first placeholder with the name of the placeholder.
    • "target": Area of the variable like document, header, footer, footnote, endnote or comment.
    • "dpi": Dots per inch.
    • "width": the new width
    • "height": the new height

To make this replacement you have 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:

replaceVariableByWordFragment method

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

For example, to replace the placeholder IMAGE with a picture, after creating the new image instantiating the class WordFragment type this code:

And replace it by calling replaceVariableByWordFragment:

Tips and tricks

To add a background color instead of a background image, use setBackgroundColor:

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 using watermarkDocx:

This method is available for the Advanced and Premium licenses.

Next - Graphic charts