How to Change Style of a Title with Python-Docx?

I'm using python-docx but I don't understand or retrieve any way to change the style (from bold to normal) of the title. My code is:

import docx
from docx.shared import RGBColor
from docx.shared import Pt
from docx.dml.color import ColorFormat
from docx.enum.style import WD_STYLE_TYPE

#format only the filename as return text
def format_filename(fname):
    index = fname.rfind('\\')
    font.color.rgb = RGBColor(255,0,0)
    #IF statement for structuring the fine name
    if index>0:
        filename = fname[index + 1, len(fname)]
    else:
        index = fname.rfind('/')
        filename = fname[index + 1 : len(fname)]
    return filename

#print all the file into docx
def print_file(file):
    font.bold = False
    font.color.rgb = RGBColor(0,0,0)
    cnt = 0
    fp = open(file, 'r')
    #read all the file and use every single line
    for line in fp.readlines():
        cnt += 1
        #if it's the first line add paragraph
        if cnt == 1:
            paragraph = document.add_paragraph(line)
        #else continue the paragraph
        else:
            paragraph.add_run(line)

#open file
document = docx.Document()
filepath = '../cap1/prg1.txt'

# set the font in the paragraph
run = document.add_paragraph().add_run()
style = document.styles['Normal']
font = style.font
font.name = 'Courier New'
font.size = Pt(10.5)
font.bold = True
font.color.rgb = RGBColor(255,0,0)

#print as a heading the filename
filename = format_filename(filepath) #self procedure for format the filename
document.add_heading(filename , level=2)
#print all the file
print_file(filepath)

document.save('my_cake_file.docx')

Here is how the title looks like after coloring:

4

1 Answer

You need to update color for Heading 2 style. Here is the example:

import docx

# Create doc
document = docx.Document()

# Add black title
styles = document.styles
styles['Heading 2'].font.color.rgb = docx.shared.RGBColor(0, 0, 0)
document.add_heading('Title', level=2)

# Add text
paragraph = document.add_paragraph()
paragraph.add_run('text')

# Save file
document.save('output.docx')

Output:

1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Robert Thorne

Robert Thorne

Automotive & Future Transportation Editor

Robert Thorne covers electric vehicle innovations, autonomous driving systems, global mobility trends, and automotive engineering developments.

Share this article
Twitter Facebook Pinterest