Mad Physicist
Mad Physicist

Reputation: 114330

How to vertically align picture in line using python-docx

I am adding a picture (some latex converted into a PNG using matplotlib) to my text using the following code:

par = doc.add_paragraph()
par.add_run().text = 'foo bar baz'
par.add_run().add_picture('pic.png')
par.add_run().text = 'blah blah blah'

This works OK, except that the picture pic.png is not vertically aligned in the rest of the text in the document:

raised

I can get the alignment manually in MS Word by adding a character style with the advanced vertical alignment property set to "lowered by 10pt":

fixed

The problem is that I have no idea how to do this programatically using python-docx. Conceptually the steps would be to compute the size of the image, create a character style that was lowered by half that size minus half the size of the font and apply the style to the run containing the picture. How do you create a raised or lowered font style in python-docx?

For reference, here is pic.png: pic.png

Upvotes: 0

Views: 2242

Answers (1)

scanny
scanny

Reputation: 28903

Your image has a fairly large (transparent) border around it. I added a single pixel border inside its extents here to make it visible:

enter image description here

I expect Word is aligning the bottom of the image with the baseline (as expected). One approach would be to see if there was a way you could specify zero bottom border.

You could also try subscript on that image run. I'm not sure what it would do but it's worth a try. So something like this:

run = par.add_run()
run.add_picture('x.png')
run.font.subscript = True

If you find the run that you manually set to "lowered by 10pt", you can view the XML for it like this (aircode):

run = vertically_adjusted_run()  # however you get ahold of it
print(run._element.xml)

I expect you'll see something like this:

<w:r>
  <w:rPr>
    <w:position w:val="20"/>
    ...

... where the w:position element sets the adjustment from the baseline. The value is specified in half-points.

Anyway, neither this adjustment nor even that low-level element are supported by python-docx yet, so you'd need to get in there with lxml calls to do the needful if you wanted it badly enough.

Upvotes: 1

Related Questions