Search code examples
pythonfontsms-wordpython-docx

font type and font size in python-docx


I am generating a MS Word document from a template using python-docx and I need a function that allows me to format text within the same paragraph.

I found this snippet in another topic that worked for me:

class Text:
    def __init__(self, text, bold=False, italic=False, color=None):
        self.text = text
        self.bold = bold
        self.italic = italic
        self.color = color

def add_text(textitems):
    p = doc.add_paragraph('')
    for t in textitems:
        r = p.add_run(t.text)
        if t.bold:
            r.bold = True
        if t.italic:
            r.italic = True
        if isinstance(t.color, RGBColor):
            r.font.color.rgb = t.color

This is called from another function this way:

add_text([Text('This is an ', bold=False, italic=False, color=None),
          Text('example', bold=True, italic=False, color=RGBColor(0xFF, 0x00, 0x00))])

Now I want to implement font type and font size. Which is the best way to do it?

Solved this way:

class Text:
    def __init__(self, text, bold=False, italic=False, color=None, name=None, size=None):
        self.text = text
        self.bold = bold
        self.italic = italic
        self.color = color
        self.name = name
        self.size = size

def add_text(textitems):
    p = doc.add_paragraph('')
    for t in textitems:
        r = p.add_run(t.text)
        if t.bold:
            r.bold = True
        if t.italic:
            r.italic = True
        if isinstance(t.color, RGBColor):
            r.font.color.rgb = t.color
        if t.name:
            r.font.name = t.name
        if t.size:
            r.font.size = t.size

And calling it:

add_text([Text('This is an ', bold=False, italic=False, color=None, name='Calibri', size=Pt(12)), Text('example', bold=True, italic=False, color=RGBColor(0xFF, 0x00, 0x00), name='Calibri', size=Pt(12))])

Solution

  • Something like this should work just fine. Note that it's probably cleaner to leave out keyword arguments that are not changing the default, like:

    add_text(
        [
            Text('This is an '),
            Text('example', bold=True, color=RGBColor(0xFF, 0x00, 0x00))
        ]
    )
    

    Also, there is a .from_string() method on RGBColor that allows more compact expression, like:

    Text('example', color="FF0000")
    

    and RGBColor.from_string(color) in your add_text() function.