Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Docx line spacing for specific paragraph

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.)

like image 586
iFunction Avatar asked Mar 19 '26 18:03

iFunction


1 Answers

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
like image 131
scanny Avatar answered Mar 21 '26 07:03

scanny



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!