Python Docx line spacing for specific paragraph

8.8k views Asked by At

Having looked through the docs, I am trying to figure out how to apply line spacing to a single paragraph, but it appears that any line spacing can only be done on a global scale using styles. Is there a way to isolate specific paragraphs while leaving the rest of the document as normal? like this:

import docx
from docx.enum.text import WD_LINE_SPACING

text = 'Lorem ipsum...'
doc = Document()
para = doc.add_paragraph('text')
para.line_spacing = WD_LINE_SPACING.ONE_POINT_FIVE

The above code does not work of course and I can only guess that it is because line_spacing is a style level formatting. The other point about trying to localise this without doing styles is the portability of the document once built, if you cut and paste anything from one doc to another that may have been emailed to another computer runs the risk of reverting to the "Normal" style of the other machine. This can be prevented by not using document level styles (it's a nasty work around, but that is a word issue not a docx one.)

2

There are 2 answers

0
scanny On

Line spacing is explained in the documentation here:
https://python-docx.readthedocs.io/en/latest/user/text.html#line-spacing

The short answer is you need to access the ParagraphFormat object on each paragraph and use .line_spacing_rule for that:

paragraph_format = paragraph.paragraph_format
paragraph_format.line_spacing_rule = WD_LINE_SPACING.ONE_POINT_FIVE
0
Visrut On

Yes, the above answer is for a specific paragraph. If you want to configure for all the paragraphs in the document, you can do this.

document = Document()
style = document.styles['Normal']
style.paragraph_format.line_spacing = 0.5