Jerry
Jerry

Reputation: 1

Aligning Text/Formating Text - Docx - Python

I'm looking for a way to format a report that is being generated with Python. I've already reviewed Python docx library text align, but this didn't work and didn't really meet my needs.

What I'm hoping to do is to format one paragraph center, another left, etc.

from docx import Document
from docx.enum.section import WD_SECTION
from docx.enum.text import WD_ALIGN_PARAGRAPH

document = Document()
app_name = "Company App Here"
consultant = "Jerry"

document.add_heading (app_name + "  Report",0)

document.add_paragraph("Testing performed by " + consultant) #How do I align this to the center?

document.add_page_break()

document.add_heading('Executive Summary\n',1)
document.add_paragraph('''\tThe blah blah blah text here''') #Align left and bold this paragraph

document.add_page_break()


document.save('./report.docx')

Upvotes: 0

Views: 1536

Answers (1)

Sahil Jain
Sahil Jain

Reputation: 471

This code Will Run For You

from docx import Document
from docx.enum.section import WD_SECTION
from docx.enum.text import WD_ALIGN_PARAGRAPH

document = Document()
app_name = "Company App Here"
consultant = "Jerry"

document.add_heading (app_name + "  Report",0)

p1=document.add_paragraph("Testing performed by " + consultant)
p1.alignment=WD_ALIGN_PARAGRAPH.CENTER
document.add_page_break()

document.add_heading('Executive Summary\n',1)
p2=document.add_paragraph()
p2.add_run('\tThe blah blah blah text here').bold=True
p2.alignment=WD_ALIGN_PARAGRAPH.LEFT
document.add_page_break()


document.save('./report.docx')

This will generate a docx (as per the question's requirement).

Upvotes: 2

Related Questions