You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

使用python-docx无法设置文本“从右到左”对齐样式的问题

Fixing Right-to-Left Alignment in python-docx

Got it, let's sort out this RTL alignment issue you're facing! The problem with your current code is that you’re only setting the font’s rtl property, which affects individual character direction (great for bi-directional text like Arabic/Hebrew) but doesn’t change the overall paragraph layout direction—that’s why your text still isn’t aligning right-to-left as expected.

Here’s the corrected code:

from docx import Document
from docx.enum.style import WD_STYLE_TYPE
from docx.enum.text import WD_PARAGRAPH_DIRECTION, WD_ALIGN_PARAGRAPH

missingwords = Document()
styles = missingwords.styles

# Create a custom paragraph style for RTL
style = missingwords.styles.add_style('rtl', WD_STYLE_TYPE.PARAGRAPH)

# Enable RTL for character rendering (for bi-directional languages)
style.font.rtl = True
# Critical: Set the entire paragraph's layout direction to RTL
style.paragraph_format.direction = WD_PARAGRAPH_DIRECTION.RTL
# Optional: Align text to the right to match RTL reading habits
style.paragraph_format.alignment = WD_ALIGN_PARAGRAPH.RIGHT

# Add your paragraph with the custom RTL style
paragraph = missingwords.add_paragraph("Hello world", style='rtl')

# Don't forget to save the document!
missingwords.save("rtl_output.docx")

Key changes explained:

  • We added style.paragraph_format.direction = WD_PARAGRAPH_DIRECTION.RTL: This tells Word to lay out the entire paragraph from right to left, which is the core setting you were missing.
  • The optional WD_ALIGN_PARAGRAPH.RIGHT ensures the text sits flush against the right margin, which is standard for RTL layouts.
  • We kept style.font.rtl = True because this ensures characters in bi-directional languages render correctly (though for English text, this alone won’t change the layout).

If you just want to right-align English text without full RTL layout, you could skip the direction setting and only use the alignment—but for true RTL language support, both settings work together.

内容的提问来源于stack exchange,提问作者Rajat

火山引擎 最新活动