Python-docx: Feature: Adding picture to table cell

Created on 10 Oct 2015  路  4Comments  路  Source: python-openxml/python-docx

A perfect use for a tool such as python-docx is to archive a large number of images in an automated fashion. Unfortunately, floating images is a poor way of doing this and inserting the images in table cells is my preferred route. I had hoped that python-docx would allow me to do that (and it was, in fact, the only reason I needed it for). However, it seems to support only floating pictures at this time. I urge you to consider adding extra functionality to table cells, along the lines of:
row.cells[1].add_picture('image-filename.png', width=Inches(1.0))
Thanks.

Most helpful comment

This is currently possible, you just have to append the runs in the empty cells. Something like this should work:

import docx
pic = "some_picture.jpg"
document = docx.Document()
tbl = document.add_table(rows=1, cols=1)
row_cells = tbl.add_row().cells
paragraph = row_cells[0].paragraphs[0]
run = paragraph.add_run()
run.add_picture(pic, width = 1400000, height = 1400000)
document.save("demo.docx")

All 4 comments

This is currently possible, you just have to append the runs in the empty cells. Something like this should work:

import docx
pic = "some_picture.jpg"
document = docx.Document()
tbl = document.add_table(rows=1, cols=1)
row_cells = tbl.add_row().cells
paragraph = row_cells[0].paragraphs[0]
run = paragraph.add_run()
run.add_picture(pic, width = 1400000, height = 1400000)
document.save("demo.docx")

I can confirm that it works very well for using label template files by opening them and adding images to the template table cells. I have used this for DataMatrix codes. This issue should be closed.

Using the similar code mentioned above I was saving some pictures to a document in a loop. that is i was writing an image in a location with its file name in a document as below.
1.jpg [image file]
2.jpg [image file]
3.jpg [image file]
.....
But when the first was successfully written in the document, others are not written and it shows the error
docx.image.exceptions.UnrecognizedImageError
Can anyone tell me what is the error.

run = paragraph.insert_paragraph_before().add_run()

Was this page helpful?
0 / 5 - 0 ratings

Related issues

sskadit picture sskadit  路  4Comments

aekoch picture aekoch  路  7Comments

achillis1 picture achillis1  路  5Comments

kndidox picture kndidox  路  5Comments

raphaelvalentin picture raphaelvalentin  路  7Comments