Skip to content

Adding styles to Headers #2847

@lucasnetau

Description

@lucasnetau

Describe the problem

Header styles are only set once per document, however in Word you can also override Header styles with per Header items like Alignment and Colour.

Through investigating how Word/LibreOffice produce these docx files I've worked out the following POC patch that changes the colour and alignment of the Header just to prove it's possible. You do need to put the colour in both spots I've found.

--- src/PhpWord/Writer/Word2007/Element/Title.php      2025-10-23 20:31:59
+++ src/PhpWord/Writer/Word2007/Element/TitleStyled.php        2025-10-23 20:12:54
@@ -45,7 +45,13 @@
             $xmlWriter->startElement('w:pStyle');
             $xmlWriter->writeAttribute('w:val', $style);
             $xmlWriter->endElement();
+            $xmlWriter->startElement('w:jc');
+            $xmlWriter->writeAttribute('w:val',"center");
             $xmlWriter->endElement();
+            $xmlWriter->startElement('w:color');
+            $xmlWriter->writeAttribute('w:val','800000');
+            $xmlWriter->endElement();
+            $xmlWriter->endElement();
         }
 
         $bookmarkRId = null;
@@ -64,6 +70,9 @@
         $text = $element->getText();
         if (is_string($text)) {
             $xmlWriter->startElement('w:r');
+            $xmlWriter->startElement('w:color');
+            $xmlWriter->writeAttribute('w:val','800000');
+            $xmlWriter->endElement();
             $xmlWriter->startElement('w:t');
             $this->writeText($text);
             $xmlWriter->endElement(); // w:t

I'm happy to work on a more succinct patch if this is something the project would accept. Would appreciate some guidance if addTitle should take optional font and paragraph styles

Describe the expected behavior

Be able to override the Header styles

Priority

  • I want to crowdfund the feature (with @algora-io) and fund a community developer.
  • I want to pay the feature and fund a maintainer for that. (Contact @Progi1984)

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions