Reputation: 1
I am trying to use Python Docx to generate a word document that will later be manually manipulated. My problem arises when trying to add paragraph headings and space underneath to write, using a different font style.
My desired output would look like
Title
Section One (In Times New Roman)
Yada Yada Yada (In Ariel)
Section Two (Times New Roman)
etc.
Although I have managed to create the sections and the breaks in between, whichever font comes last in my code, is used for every section and break. My goal is to leave the breaks empty, but when written in the font style/size is automatically set to the properties in the "sections_break" part of the code.
from docx import Document
from docx.shared import Inches
from docx.shared import Pt
from docx.enum.style import WD_STYLE_TYPE
document = Document()
heading = document.add_paragraph("Heading")
heading.style = document.styles.add_style('Style Name', WD_STYLE_TYPE.PARAGRAPH)
heading_font = heading.style.font
heading_font.name = 'Times New Roman'
heading_font.size = Pt(12)
heading_font.bold = True
for section in profile_sections:
sections = document.add_paragraph(section)
sections_font = sections.style.font
sections_font.name = 'Palatino Linotype'
sections_font.size = Pt(11)
sections_font.bold = True
sectionbreaks = document.add_paragraph(" ")
sectionbreaks.name = 'Times New Roman'
sectionbreaks.size = Pt(11)
sectionbreaks.bold = False
Upvotes: 0
Views: 229
Reputation: 28863
You're changing the font of the paragraph's style instead of the font of the paragraph itself. All of these paragraphs share the same (default) style (very likely "Normal"), so they all get the final style.
Try changing the font of the run containing the text you want to have distinct character formatting:
paragraph = document.add_paragraph("foobar")
font = paragraph.runs[0].font
font.name = 'Palatino Linotype'
font.size = Pt(11)
font.bold = True
Check out the documentation for paragraph styles here:
https://python-docx.readthedocs.io/en/latest/user/styles-understanding.html
and here:
https://python-docx.readthedocs.io/en/latest/user/styles-using.html
This documentation page on text can help you understand the important differences between paragraphs and runs and why the font is applied at the run level:
https://python-docx.readthedocs.io/en/latest/user/text.html
Upvotes: 0