Set paragraph font to python-docx

I am using Python docx 0.7.6

I can't seem to figure out how to set the font-family and size for a specific paragraph.

There is a .style property, but style = "Times New Roman" doesn't work.

Can anyone point me to an example?

Thank.

+3


source to share


4 answers


Run style support has been added to the latest version of python-docx



0


source


Here's how to set style Normal

to font Arial

and size 10pt

.

from docx.shared import Pt

style = document.styles['Normal']
font = style.font
font.name = 'Arial'
font.size = Pt(10)

      

And here's how to apply it to paragraph

.



paragraph.style = document.styles['Normal']

      

Using the current latest version of python-docx (0.8.5)

+6


source


After reading the API documentation, I was able to figure out how to create my own style and apply it. You can create a paragraph style object in the same way, changing this code to use WD_STYLE_TYPE.PARAGRAPH. Something that took me a minute to figure out if the objects were and at what level they are applied, so just make sure you understand this clearly. Something I found counter intuitive is that you define the properties of the styles after you create it.

This is how I created a character level style object.

document = Document(path to word document)

      

# Creates a character style style Object ("CommentsStyle"), then defines its parameters

obj_styles = document.styles
obj_charstyle = obj_styles.add_style('CommentsStyle', WD_STYLE_TYPE.CHARACTER)
obj_font = obj_charstyle.font
obj_font.size = Pt(10)
obj_font.name = 'Times New Roman'

      

This is how I applied the styling to the launch.

paragraph.add_run(any string variable, style = 'CommentsStyle').bold = True

      

+5


source


The documentation for python-docx is here: http://python-docx.readthedocs.org/en/latest/

The following are the styles available in the default template: http://python-docx.readthedocs.org/en/latest/user/styles.html

In the above example, you used the font name ("Times New Roman") instead of the style ID. If you use "Heading1" for example, it will change the appearance of the font, by the way, since this is a paragraph style.

There is currently no API to directly apply font name or font size to text in python-docx, although that and more is coming in the next release, perhaps within a month. In the meantime, you can define styles for the paragraph and character options you want and apply those styles. Styles are the recommended way to apply formatting in Word, much like CSS is the recommended way to apply formatting to HTML.

0


source







All Articles