简体   繁体   English

特定段落的Python Docx行距

[英]Python Docx line spacing for specific paragraph

Having looked through the docs, I am trying to figure out how to apply line spacing to a single paragraph, but it appears that any line spacing can only be done on a global scale using styles.浏览了文档后,我试图弄清楚如何将行距应用于单个段落,但似乎任何行距只能使用样式在全局范围内完成。 Is there a way to isolate specific paragraphs while leaving the rest of the document as normal?有没有办法隔离特定段落,同时让文档的其余部分保持正常? like this:像这样:

import docx
from docx.enum.text import WD_LINE_SPACING

text = 'Lorem ipsum...'
doc = Document()
para = doc.add_paragraph('text')
para.line_spacing = WD_LINE_SPACING.ONE_POINT_FIVE

The above code does not work of course and I can only guess that it is because line_spacing is a style level formatting.上面的代码当然不起作用,我只能猜测这是因为 line_spacing 是一种样式级别的格式。 The other point about trying to localise this without doing styles is the portability of the document once built, if you cut and paste anything from one doc to another that may have been emailed to another computer runs the risk of reverting to the "Normal" style of the other machine.关于在不做样式的情况下尝试本地化的另一点是文档一旦构建的可移植性,如果您将任何内容从一个文档剪切并粘贴到另一个可能已通过电子邮件发送到另一台计算机的内容,则有恢复到“正常”样式的风险另一台机器。 This can be prevented by not using document level styles (it's a nasty work around, but that is a word issue not a docx one.)这可以通过不使用文档级样式来防止(这是一个令人讨厌的解决方法,但这是一个文字问题而不是 docx 问题。)

Line spacing is explained in the documentation here: 行间距在文档中解释如下:
https://python-docx.readthedocs.io/en/latest/user/text.html#line-spacing https://python-docx.readthedocs.io/en/latest/user/text.html#line-spacing

The short answer is you need to access the ParagraphFormat object on each paragraph and use .line_spacing_rule for that: 简短的答案是您需要访问每个段落上的ParagraphFormat对象,并.line_spacing_rule使用.line_spacing_rule

paragraph_format = paragraph.paragraph_format
paragraph_format.line_spacing_rule = WD_LINE_SPACING.ONE_POINT_FIVE

Yes, the above answer is for a specific paragraph.是的,上面的答案是针对特定段落的。 If you want to configure for all the paragraphs in the document, you can do this.如果要为文档中的所有段落进行配置,可以这样做。

document = Document()
style = document.styles['Normal']
style.paragraph_format.line_spacing = 0.5

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

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