Search code examples
python-3.xpython-docx

Python: How to set font using python-docx library?


For an existing .docx file, I can access font information using python-docx:

import docx
doc = docx.Document(*some file*)
some_font = doc.paragraphs[0].runs[0].font

But when I try to apply this font to a new run in a new document, it fails:

newdoc = docx.Document()
p = newdoc.add_paragraph()
r = p.add_run(*some string*)
r.font = some_font

It returns an error:

AttributeError: can't set attribute

What should I do? Can I apply this specific font to a new string?

I'm using Python 3.4 on a Windows 64-bit machine.


Solution

  • The short answer is No. You can't directly assign a Font object to a run. A Font object provides access to a variety of character-level formatting properties such as typeface name, size, color, underline, etc.; it cannot be applied all at once to another run.

    You can however assign a typeface name, which is what folks often mean when they use the word font.

    some_typeface_name = doc.paragraphs[0].runs[0].font.name
    r = p.add_run('some string')
    r.font.name = some_typeface_name