简体   繁体   English

如何更改 docx 文件中的字体大小 python

[英]How do I change font size in a docx file python

I am trying to create a Finance Log, however I canot change the font size from one size to another without the entire font size of all the text changing.我正在尝试创建财务日志,但是我无法将字体大小从一种大小更改为另一种大小,而不更改所有文本的整个字体大小。

I want "Finance Log" and "Created On..." to be in 48 and "Log Begins:" to be in 24.我希望“财务日志”和“创建于……”在 48 中,“日志开始:”在 24 中。

Tstyle = doc.styles['Normal']
font = Tstyle.font
font.name = "Nunito Sans"
font.size = Pt(48)
Title = doc.add_paragraph()
TRun = Title.add_run("Finance Log")
TRun.bold = True
CurrentDate= datetime.datetime.now()
FormattedDate= CurrentDate.strftime('%d-%m-%Y')
FCreated = Title.add_run("\nFile Created On "+FormattedDate)
Fstyle = doc.styles['Heading 1']
font = Fstyle.font
font.name = "Nunito Sans"
font.size = Pt(24)
FLog = doc.add_paragraph()
FinanceTitle = FLog.add_run("Log Begins:")
doc.save(path_to_docx)

I have tried multiple things such as creating a new style, setting the new style to a heading etc...我尝试了多种方法,例如创建新样式,将新样式设置为标题等...

I am aware of Set paragraph font in python-docx however I could not resolve the problem from this我知道在 python-docx设置段落字体但是我无法解决这个问题

I canot change the font size from one size to another without the entire font size of all the text changing.如果不更改所有文本的整个字体大小,我无法将字体大小从一种大小更改为另一种大小。

That's because you're changing the underlying font size of the style objects:那是因为您正在更改style对象的底层字体大小:

Tstyle = doc.styles['Normal']
font = Tstyle.font  # << this line assigns font = doc.styles['Normal'].font

So, you're not working with some generic "font" property, you're working with the font that belongs to the named style "Normal".因此,您没有使用一些通用的“字体”属性,而是使用属于命名样式“Normal”的字体。 And so:所以:

font.name = "Nunito Sans"
font.size = Pt(48)  # << this line changes the font size of doc.styles['Normal']

Untested, but try something like:未经测试,但尝试类似:

TStyle, FStyle = doc.styles['Normal'], doc.styles['Heading 1']
for style in (TStyle, FStyle):
    style.font.name = "Nunito Sans"
TStyle.font.size = Pt(48)
FStyle.font.size = Pt(24)


Title = doc.add_paragraph()
Title.style = TStyle
TRun = Title.add_run("Finance Log")
TRun.bold = True

FCreated = Title.add_run("\nFile Created On {0}".format(datetime.datetime.now().strftime('%d-%m-%y')))

FLog = doc.add_paragraph()
FLog.style = FStyle
FinanceTitle = FLog.add_run("Log Begins:")
doc.save(path_to_docx)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM