2
votes

I'm using PHPWord (https://github.com/PHPOffice/PHPWord/tree/develop) to generate a Word document with some text needing a background color.

PHPWord has the ability to apply inline styles to text added to a section. I am doing that via the following:

$section->addText(
    "Some text", 
    [
        "name" => "Tahoma",
        "size" => 12,           
        "bgColor" => "#FF0000"
    ]);

The problem is that when I open up the resulting document in Microsoft Word I note that the colored background text is not colored in a way that is recognized as "Text Highlight Color" that you would get from using the tool in Word.

enter image description here

Thus, even if I select (i.e. highlight) some of the text and choose the "Text Highlight Color" tool and select "None" it doesn't remove the background color formatting that PHPWord has applied. The same goes for a text foreground color too.

My question is this: Is there a way in PHPWord to apply a background color style—and a text font color—that is recognized by the Microsoft Word application as a true "Text Highlight Color" and a true "Font Color" as would be applied in the application using that tool? Or are we limited to the inline styling that PHPWord provides?

1

1 Answers

1
votes

Word has two different ways to add (background) color to text:

  • Shading: This can be used to set the color behind text, a paragraph or a table cell to an arbitrary RGB color value.
  • Text Highlight Color: This allows you to pick one out of 15 pre-defined colors for highlighting ranges of text in your document. Highlighting has some special properties, e.g. you can search for highlighted text in Word's Find dialog.

I'm not too familiar with the PHPWord library, but it looks as if they expose the Highlight feature in the fgColor property (as you can see in their sample):

$section->addText(
    'This is some text highlighted using fgColor (limited to 15 colors)',
    array('fgColor' => \PhpOffice\PhpWord\Style\Font::FGCOLOR_YELLOW)
);

Note that you can see the list of available colors in the file Font.php:

/**
 * Foreground colors
 *
 * @const string
 */
const FGCOLOR_YELLOW = 'yellow';
const FGCOLOR_LIGHTGREEN = 'green';
const FGCOLOR_CYAN = 'cyan';
const FGCOLOR_MAGENTA = 'magenta';
const FGCOLOR_BLUE = 'blue';
const FGCOLOR_RED = 'red';
const FGCOLOR_DARKBLUE = 'darkBlue';
const FGCOLOR_DARKCYAN = 'darkCyan';
const FGCOLOR_DARKGREEN = 'darkGreen';
const FGCOLOR_DARKMAGENTA = 'darkMagenta';
const FGCOLOR_DARKRED = 'darkRed';
const FGCOLOR_DARKYELLOW = 'darkYellow';
const FGCOLOR_DARKGRAY = 'darkGray';
const FGCOLOR_LIGHTGRAY = 'lightGray';
const FGCOLOR_BLACK = 'black';