from docx import Documentfrom docx.text.parargaph import Paragraph
Document creation:
Let’s start with the basics, we’re gonna create a document and add some text to it:
document =Document()document.add_heading('This is the title', 0)p = document.add_paragraph('And this is text ')p.add_run('some bold text').bold =Truep.add_run('and italic text.').italic = Truedocument.save('output.docx')
There’s other stuff you can do to change the style of the paragraphs, here are a few examples using the same variable p from above, this can be done at any point after calling add_paragraph():
#0: Left alignment, 1: Center, 2: Right, 3: Justifiedp.alignment =1#this will set the line spacing in the paragraph to 1.5 linesp.paragraph_format.line_spacing =1.5
Even more, python-docx has support for styles, you can create your own styles like this:
from docx import Documentfrom docx.text.parargaph import Paragraphfrom docx.enum.style import WD_STYLE_TYPEfrom docx.shared import Ptdocument = Document()styles = document.stylesstyle = styles.add_style('Tahoma', WD_STYLE_TYPE.PARAGRAPH)#Tahoma is the name I set because that's the font I'm gonna usestyle.font.name ='Tahoma'style.font.size =Pt(11)