Question

I'm using python-docx to generate .docx files. I'd like to be able to control the style of the paragraphs (and of individual words within if that's possible) that I'm appending to the document body.

The business-end of generating a paragraph looks like this:

body.append(paragraph("This is a new paragraph"))

Now, I'm not familiar with the complexities of XML and to be honest, learning enough of it to parse and manipulate it using lxml would be overkill for what I have in mind. Can anyone provide a simple example of, say, changing the font of my paragraph above from the default to Courier New?

There are a couple of similar (but unanswered) questions here, so apologies for the breach of protocol if I've got it wrong.

Was it helpful?

Solution

I don't think there's a one-click super easy way to edit font/size etc with the docx module (yet, at least). Fortunately, it's relatively easy with lxml and it's not too difficult to get a basic grasp of the xml format with a bit of poking and prodding.

Try changing the extension of your file from .docx to .zip, and open /word/document.xml. The elements there that modify specific text are children of both the w:pPr (paragraph properties) and the w:rPr (run properties) elements. This link provides a good overview of the methods that you can use to sift through the document.xml file and add/remove/edit as you see fit.

I'd also suggest looking at the "def paragraph" function in the docx.py module. There are a couple of direct examples there of appending various descriptive elements to paragraphs and runs in there.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top