python docx align both left and right on same line

為{幸葍}努か 提交于 2020-01-04 05:51:01

问题


This is my first question on SO and would like to thank you all in advance for any help. I'm pretty new to python, python-docx and programming in general. I am working on a GUI program (using PyQt) to generate a contract in docx format. I have most things working, but here is the problem I am having. I need to align text both left and right on the same line. In word, I believe this is done by changing to a right indent and hitting tab, then adding the text. However, I cannot figure out how to do this in python-docx. I tried:

paragraph = document.add_paragraph()
paragraph.add_run('SOME TEXT')
paragraph.alignment = 0
paragraph.add_run('SOME OTHER TEXT')
paragraph.alignment = 2

but this didn't work. I tried some other ideas per the documentation, like enum WD_PARAGRAPH_ALIGNMENT, but nothing worked.

Is this possible to do in python-docx (im using version 0.8.5)?

Thanks for any help!


回答1:


Not sure if you're still looking for a solution, but...

I am also generating contracts with python-docx and came across this same issue. Until the right-aligned tab stop feature is added, my workaround is to format the line as a table, using a custom table style.

  • First, open a document ('custom_styles.docx') and add a table with 1 row and 2 columns.
  • Select the table and add a new table style ('CustomTable'), where the first column is left-aligned and the last column is right-aligned. (I also made the borders invisible by setting them to 'none' or coloring them white.)
  • Delete the table and save the document, which will give you an empty document with the new 'CustomTable' style.

The following should work for creating a line that appears to be both left-aligned and right-aligned:

from docx import Document

document = Document('custom_styles.docx')
table = document.add_table(1, 2, style='CustomTable')
table.cell(0,0).text = 'Left Text'
table.cell(0,1).text = 'Right Text'
document.save('new_document_name.docx')

The trickiest part for me was figuring out how to create the table style in Word.




回答2:


If what you're looking for is a paragraph that is fully justified, meaning it lines up with the margins on both the left and right side, that is done with the Paragraph.alignment property:

from docx.enum.text import WD_ALIGN_PARAGRAPH
paragraph = document.add_paragraph('A paragraph of text ..')
paragraph.alignment = WD_ALIGN_PARAGRAPH.JUSTIFY

If you're looking to establish a right-aligned tab stop, that's not supported yet in python-docx. You can add a feature request on the GitHub issues list here: https://github.com/python-openxml/python-docx/issues

A good issue name would be "feature: tab stops".



来源:https://stackoverflow.com/questions/28884114/python-docx-align-both-left-and-right-on-same-line

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!