I am trying to generate a Word document where each word is on a separate page and has a specific amount of spacing before the paragraph. I am using the python-docx library to create the Word document. However, I noticed that the same spacing before each word is not consistently applied.
Here is a snippet of my code:
from docx import Document
from docx.shared import Pt
from docx.oxml.ns import qn
from docx.enum.text import WD_ALIGN_PARAGRAPH
import os
def create_word_document(words, output_path):
doc = Document()
for word in words:
p = doc.add_paragraph(word)
run = p.runs[0]
run.font.size = Pt(130)
run.font.name = "Gulzar"
run.element.rPr.rFonts.set(qn('w:eastAsia'), "Gulzar")
p.alignment = WD_ALIGN_PARAGRAPH.CENTER
p.paragraph_format.space_before = Pt(78)
doc.add_page_break()
os.makedirs(os.path.dirname(output_path), exist_ok=True)
doc.save(output_path)
print(f"Saved Word document to {output_path}")
# Example usage
words = ["کلجقم", "کلجقم", "کلجقم"]
output_path = "output.docx"
create_word_document(words, output_path)
Despite setting p.paragraph_format.space_before = Pt(78), the spacing is not being consistently applied to each word. How can I ensure that the same spacing before each paragraph is applied correctly?
Below I have attached images of the first two pages of the document. Both words are the same and should appear the same on different pages, but they do not:
Page 1 image
Page 2 image
How can I fix this issue to ensure consistent formatting across all pages?
Rashid mehmood is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.