marc.fargas
marc.fargas

Reputation: 786

Replace picture (from page header)

I have a base .docx for which I need to change the page header / footer image on a case by case basis. I read that python-docx does not yet handle headers/footers but it does handle Pictures.

What I cannot work around is how to replace them.

I found the Pictures in the documents ._package.parts objects as ImagePart, I could even try to identify the image by its partname attribute.

What I could not find in any way is how to replace the image. I tried replacing the ImagePart ._blob and ._image attributes but it makes no difference after saving.

So, what would be the "good" way to replace one Image blob with another one using python-docx? (it is the only change I need to do).

Current code is:

d = Document(docx='basefile.docx')
parts = d._package
for p in parts:
    if isinstance(p, docx.parts.image.ImagePart) and p.partname.find('image1.png'):
        img = p
        break
img._blob = open('newfile.png', 'r').read()
d.save('newfile.docx')

Thanks, marc

Upvotes: 2

Views: 2970

Answers (1)

marc.fargas
marc.fargas

Reputation: 786

There is no requirement to use python-docx. I found another Python library for messing with docx files called "paradocx" altought it seems a bit abandoned it works for what I need.

python-docx would be preferable as the project seems more healthy so a solution based on it is still desired.

Anyway, here is the paradocx based solution:

from paradocx import Document
from paradocx.headerfooter import HeaderPart

template = 'template.docx'
newimg = open('new_file.png', 'r')

doc = Document.from_file(template)
header = doc.get_parts_by_class(HeaderPart).next()
img = header.related('http://schemas.openxmlformats.org/officeDocument/2006/relationships/image')[0]

img.data = newimg.read()
newimg.close()

doc.save('prueba.docx')

Upvotes: 2

Related Questions