Search code examples
phpwordphpoffice

How to add styles to incoming HTML in PHPWord


In phpword, I see you used to be able to pass a styles array to the addHTML function, but not any more.

If my HTML doesn't have any inline styles set, is there a way to specify a fontStyle and paragraphStyle so it doesn't end up as plain 'Arial 10pt' in the Word file?

I've had some success by setting default styles before calling addHTML:

$phpWord->setDefaultFontName('...');
$phpWord->setDefaultFontSize('...');
$phpWord->setDefaultParagraphStyle('...');

However, this isn't a complete font style. For example, how would you change the text's color?


Solution

  • It seems the most versatile solution is actually to add the styles directly into your html, before calling addHTML(). Something like...

    $html = str_replace("<p>", 
        "<p style='font-size: 10pt; font-family: Arial; color:#595959; line-height: 140%; margin-bottom: 160pt;'>", 
        $html);