如何通过python-docx使用桌面

问题描述 投票:0回答:1

我是python-docx的新手,我想在一行中同时对齐左缩进和右缩进。但是我找不到一个示例来说明如何做到这一点。有人可以帮我吗?

我想为公司和职务添加一行,例如“ Google Engineer”,我希望“ Google”在一行中与左缩进对齐,而“ Engineer”在一行中右对齐。如何通过在段落格式中添加tabstop在python-docx中执行此操作?

python-docx tabstop
1个回答
0
投票

是,您可以通过添加制表符来完全解决此问题。

[如果您查看the picture,则首先需要计算在何处添加制表位。如果要使Engineer在同一行(段落)中向右对齐,则需要根据页面宽度和左/右页边距来计算端点。

然后有了这个,重要的是在添加制表位时设置WD_TAB_ALIGNMENT.RIGHT,这将确保内容右对齐并“粘”在右侧。

这里是您的案例的示例代码:

import docx
doc = docx.Document()

p = doc.add_paragraph('Google\tEngineer')  # tab will trigger tabstop
sec = doc.sections[0]
# finding end_point for the content 
margin_end = docx.shared.Inches(
    sec.page_width.inches - (sec.left_margin.inches + sec.right_margin.inches))
tab_stops = p.paragraph_format.tab_stops
# adding new tab stop, to the end point, and making sure that it's `RIGHT` aligned.
tab_stops.add_tab_stop(margin_end, docx.enum.text.WD_TAB_ALIGNMENT.RIGHT)

doc.save("test.docx")

希望这会有所帮助,最佳

© www.soinside.com 2019 - 2024. All rights reserved.