Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't change "heading 1" font name using docx

I am using the following script :

header = self.document.add_paragraph(style='Heading 1')
header.style.font.name = 'Arial'
header.style.font.size = Pt(16)
header.add_run('Header One')

The result is that "Header One" get 'Calibri'.

like image 892
Omar Avatar asked May 13 '16 23:05

Omar


People also ask

How do I change Heading 1 in Word?

Select Home > Styles (or press Alt+H, then L), and then select the heading you want, such as the Heading 1 button.

How do I change font in DOCX?

Right-click somewhere in the document and choose “Font”. In the Font dialog box, select your preferred typeface and any other settings you want to change (e.g., font size). Click the “Set As Default” button. In the dialog box that appears, choose the “All documents based on the Normal template” option.

What does Heading 1 mean in Word?

Heading 1 – page title or main content. There is usually only 1. Heading 2 – a major section heading. Heading 3 – a subsection heading of a major section. Heading 4 – a subsection of the Heading 3 subsection and so on through Heading 6.


1 Answers

This is a legitimate bug even with python-docx version 0.8.5. If you were to change the font name of the style 'Normal', it works (as shown in the examples on the python-docx manuals), but this does not work for the 'Heading 1' style.

One workaround is to create a new heading style that takes Heading 1 as a base style and then modify the new style's font name & size:

from docx.enum.style import WD_STYLE_TYPE

styles = self.document.styles
new_heading_style = styles.add_style('New Heading', WD_STYLE_TYPE.PARAGRAPH)
new_heading_style.base_style = styles['Heading 1']
font = new_heading_style.font
font.name = 'Arial'
font.size = Pt(16)
self.document.add_paragraph('Header One', style='New Heading')
like image 127
gchaks Avatar answered Nov 13 '22 02:11

gchaks