Practical phpdocx



Working with charts is as easy as with pictures. You just need to choose the kind of graphic to insert and add the values and legends.

There are 2D and 3D graphic available, with many formats like cylinder, cone or pyramid, column type, pie format, line, area, radar, surface, doughnut...

You can add charts to new documents, replace placeholders with charts in a template or change the values of already existing charts.

Premium licenses include additional options to assign sophisticated styles such as defining custom and individual colors for series and values, adding color backgrounds and applying styles to axes.

Adding charts

For adding charts in a document, call addChart:

It counts with multiple options to use in the array of parameters. The most important are:

  • type: Type of chart
  • data: Array of values
  • title: Text used as a title

Beside these three attributes, you can define other properties as rotation with rotX and rotY, perspective, distance between values, sizes, and so on.

For example, to add a pie chart, first define an array:

In this array, write the legends of the charts as keys and the arrays of data you want to insert as values.

Next, define the options of the chart:

Finally, add the chart:

Adding charts in templates

You can create a chart as a WordFragment and substitute it instead of an specific placehoder. This procedure is similar to the placeholder template replacement for text and images.

replaceVariableByWordFragment is the same method as the one explained for images:

For example, you can create as a WordFragment the same chart seen before.

Then, replace it in the template:

Modify the values of an existing chart

The class DocxUtilities, available in the Advanced and Premium licenses, has a useful method for replacing the values of a chart found in a document. This allows to create charts using MS Word and to easily replace its values without having to generate them previously.

This is the method to code:

These are the available parameters:

  • $source: DOCX document with the chart(s) to replace.
  • $target: DOCX destination.
  • $chartData: With an array which key is the chart number you want to change depending on its position in the document. Its value is the data you want to add.

For example, do this to replace the two charts of the document:

Define the new values:

Then, create an array to replace first and second charts:

Finally, make the replacement:

Tips and tricks

phpdocx includes the color schemes used in Word for charts. You can define this property through the 'color' parameter of the addChart method.

Premium licenses include a theme option to assign more advanced styles such as defining custom and individual colors for series and values, adding color backgrounds and applying styles to axes.

Next - HTML and CSS