Python-docx very ugly justification

Solution 1:

I'm not an expert, but the difference between your example and the built-in method is, most certainly, that you did not exclude the last line of the paragraph from your justification function.

There should be an if clause that stops your code from executing if it is the last line of a paragraph, because only then you have a very few words in the line which means broad spaces. Also, this is the standard way of doing it in regular text processors.

Solution 2:

The answer to my own question

I thought a lot about Dorian's solution which was :

There should be an if clause that stops your code from executing if it is the last line of a paragraph

But the main issue was that I couldn't find a way to identify lines inside a paragraph. And the other issue was that my 'paragraph' items sometime contains line break. So even the inside of a paragraph (and not just the last line) could be streched too much by the justification.

The hidden problem

So I figured out that the real problem was in fact that my paragraphs contains line break that weren't officially recognized as line break (at least not the same line break than the one that appears when you press 'enter' in Word) because I was getting them from an *.xml file. Therefore the justification couldn't identify those line break as 'line that shouldn't be justified'.

Once I got there, the solution was pretty easy to find out :

string_from_my_xml_file = get_xml(path,...)

for i in string_from_my_xml.split("\n"):
   if i != "":
      write_docx(path, i,...)

And my *.xml file looks like this:

<item>This text is on multiple lines:
- One line here
- Another one here 
</item>