Am trying to decrease spacing between paragraph with the code below in python-docx but when apply the the formatting to the paragraph the last paragraph shrinks but the line between the paragraphs doesn't decrease.
i found some examples here link 1 and link 2which but don't understand the xml part to achieve desired results.
I need your assistances to decrease the spacing between the paragraphs through python but not setting it via word file.
from docx import Document
from docx.shared import Inches
from docx.enum.style import WD_STYLE_TYPE
from docx.shared import Pt
document = Document()
document.add_heading('THIS IS MY HEADER WANT TO UNDERLINE IT')
paragraph = document.add_paragraph('THIS IS MY FIRST PARAGRAPH ')
paragraph = document.add_paragraph('THIS IS SECOND PARAGRAPH')
paragraph = document.add_paragraph('SPACING BETWEEN EACH SHOULD BE DECREASED')
paragraph_format = paragraph.paragraph_format
paragraph_format.line_spacing = Pt(3)
paragraph_format.space_after = Pt(5)
print("document created")
document.save('demo.docx')
If you check the generated Word file, you can see your code worked precisely the way you stated. That last paragraph – the only one you apply your formatting to – has a line spacing of 3pt and 5 pts of space after; all other paragraphs appear with default formatting.
So python-docx is working correctly, and if your output is wrong then it's because your code is wrong.
First off, I'd strongly advise not to set your line spacing to 3 pt; I assume you got confused because it 'didn't work' and you intended to set space_before instead. Secondly, make sure to apply your formatting to all paragraphs and not just that final one:
from docx import Document
from docx.shared import Pt
document = Document()
document.add_heading('THIS IS MY HEADER WANT TO UNDERLINE IT')
paragraph = document.add_paragraph('THIS IS MY FIRST PARAGRAPH ')
paragraph.paragraph_format.space_before = Pt(3)
paragraph.paragraph_format.space_after = Pt(5)
paragraph = document.add_paragraph('THIS IS SECOND PARAGRAPH')
paragraph.paragraph_format.space_before = Pt(3)
paragraph.paragraph_format.space_after = Pt(5)
paragraph = document.add_paragraph('SPACING BETWEEN EACH SHOULD BE DECREASED')
paragraph.paragraph_format.space_before = Pt(3)
# no need to set space_after because there is no text after this
print("document created")
document.save('demo.docx')
This results in a document with 3 pts of extra space before and 5 pts after (and with a regular leading) for all three text paragraphs.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With