How to change to font of a specific paragraph with docx (It's changing the font of the entire word document)

Viewed 155

so my main problem is that I am currently trying to use code to output a cover letter based on my input. I'll change the code for variables and input later. I am using a word document template that has specific strings that I'll change with regex. my main problem is that when I change something, it returns to the original font. However nothing changes too much but I have to bolden 2 words and make the font of 2 words smaller in order to return a few changed words to the original template.

When I change the boldness of one specific paragraph using docx.paragraphs it changes the font of the entire paper and not for that specific paragraph. I used document.paragraphs[3].text to make sure it should only change the two words I need and that's showing up correctly but when I use document.paragraphs[3].style.font.bold = True , it changes the boldness of the entire document.

from docx import Document
import re

document = Document('Cover_Letter.docx')
for para in  document.paragraphs:
    if 'Buisness_Name' in para.text:
        para.text = re.sub('Buisness_Name', 'NEWBUISNESS', para.text)
    if 'Date_Name' in para.text:
        para.text = re.sub('Date_Name', 'NEWDATE', para.text)
    if 'Internship_Name' in para.text:
        para.text = re.sub('Internship_Name', 'NEWINTERNSHIP', para.text)
    if 'parachange567' in para.text:
        para.text = re.sub('parachange567', 'NEWTEXT', para.text)

document.paragraphs[3].style.font.bold = True
    # print(para.text)
document.save('demo.docx')
1 Answers

Did you try creating a new style?

From the docs:

>>> from docx.enum.style import WD_STYLE_TYPE
>>> styles = document.styles
>>> style = styles.add_style('Citation', WD_STYLE_TYPE.PARAGRAPH)
>>> style.name
'Citation'
>>> style.type
PARAGRAPH (1)

And then setting the paragraph style to the new style?

Related