Keep placeholder font size and other styles when replacing a placeholder by HTML

When replacing a placeholder with HTML using the replaceVariableByHTML method, a bunch of default styles are applied, e.g., for the font size. Those default styles are set with the templates/html.css file on the conversion class and they are necessary for a correct transformation of HTML and CSS.

With the replacement, the existing styles in the placeholder are overwritten, either at paragraph level when performing a block type replacement or at text level (run-of-text) with an inline type replacement.

There are two ways to keep the placeholder styles when replacing them with HTML: either applying the same styles in the HTML to be transformed, or using the extended options included in the phpdocx Premium licenses.

Adding the styles in the HTML to be imported

This approach is available for all licenses. For example, in order to apply a font size of 11pt in an inline type replacement:

This inline replacement only substitutes the variable along with its run-of-text styles. The styles applied to the placeholder paragraph (e.g., the ones from a custom paragraph styles) remain by adding the new styles of the HTML.

In case of a block type replacement:

The entire placeholder paragraph is deleted along with its styles, adding the contents and styles of the HTML.

If the styles to be applied are not known beforehand, the getWordStyles method (available in Advanced and Premium licenses) allows to get them.

Using a Premium license

The stylesReplacementType option (available in the replaceVariableByHTML method in Premium licenses) lets you apply the existing styles in a placeholder. This option works for inline and block replacements.

For example, in order to apply the placeholder styles:

When calling usePlaceholderStyles, the HTML styles are ignored. The styles of the placeholder are the only ones applied. For mixing both (the styles of the placeholder and the HTML), use mixPlaceholderStyles:

The stylesReplacementTypeIgnore option defines the styles of the HTML that are going to be ignored. Those styles are indicated in OOXML format.

When using mixPlaceholderStyles, the placeholder existing styles are more important than the ones of the HTML. Therefore, the specific HTML styles are ignored if the placeholder includes the same styles. Enabling the stylesReplacementTypeOverwrite options applies the styles from the HTML that are also associated to the placeholder:

If you just need to ignore the HTML font size, it is enough to use the data-font-size style, available in CSS Extended: