Can't set font size and rtl
Asked Answered
G

2

8

Using docx, I am trying to define for a run multiple attributes. When I set color, rtl, it works fine. But when I add also font size, it is ignored. If I set only font size, it works fine.

This works fine (font color changes and run is right-to-left):

run = p.add_run(line)
font = run.font
font.rtl = True
font.color.rgb = RGBColor(0x42, 0x24, 0xE9)

This also works fine (font size is modified):

run = p.add_run(line)
font = run.font
font.size = Pt(8)
#font.rtl = True # commented out

But this does not change the font's size:

run = p.add_run(line)
font = run.font
font.size = Pt(8)
font.rtl = True

I tried different order of the commands, but nothing works.

Glossectomy answered 11/11, 2018 at 8:25 Comment(2)
And if you do font.rtl = True before you change the size?Compaction
tried to reorder the command - same resultGlossectomy
G
4

ok, found it! It turns out that in word, the font size for such a case has to include complex script instructions. It means that you have to add

<w:szCs w:val="???"/> 

instead (or in addition to) the normal

<w:sz w:val="??"/> 

I had to add a new attribute to the font in the docx library and it now works fine. The change is in 3 docs files:

text/font.py
oxml/__init.py__
oxml/text/font.py

and the usage in my view:

run = p.add_run(line)
font = run.font
#font.size = Pt(8) This line is redundant - but you can leave it
font.cs_size = Pt(8)
font.rtl = True

Added a fork to docx library. In https://github.com/Oritk/python-docx

Glossectomy answered 16/11, 2018 at 10:57 Comment(1)
does it still work?Retread
E
0

accepted I haven't gotten around to playing with docx yet (I've mostly used Excel python modules), but based on the documentation here it's looking like you're modifying the wrong property of style. The Font property, per this definition of the rtl property, would only modify an added run (via myparagraph.add_run("Hello World", style = "rtl")).As far as I can tell, the code you're looking for is:

missingwords = Document()
style = missingwords.styles.add_style('rtl', WD_STYLE_TYPE.PARAGRAPH)
style.paragraph_format.alignment = WD_PARAGRAPH_ALIGNMENT.RIGHT

And then you can go ahead and add the paragraph like you were

paragraph = missingwords.add_paragraph("Hello world",style='rtl')

Again, just going off the documentation, so let me know if that works

Emaciation answered 11/11, 2018 at 8:41 Comment(1)
Thanks - but i tried this before and this does not work... 1) alignment is not the same as direction - it does not show the sentence correctly 2) i want to change the size for some words, not the whole paragraph, which is why i do not use style 3) font.rtl is a valid option, as far as i know - it works and i also see it in python-docx.readthedocs.io/en/latest/_modules/docx/text/… (and in few answers here in stackoverflow)Glossectomy

© 2022 - 2024 — McMap. All rights reserved.