Reputation: 1
Is there a way to insert a picture inside a cell using pptx python? I'm also thinking of finding the coordinate of the cell and adjust the numbers for inserting the picture, but can not find anything.
Thank you.
Upvotes: 0
Views: 860
Reputation: 11
I have created a function that computes the cell position and size where you have to add the image. You simply have to pass the table object and the row and col number (starting from 0).
from pptx import Presentation
def calculate_cell_position(table, row, col):
table_gf = table._graphic_frame
x = table_gf._element.xfrm.off.x
y = table_gf._element.xfrm.off.y
cell_left = x
cell_top = y
cell_height = table.rows[0].height
cell_width = table.columns[0].width
for r in range(row):
cell_height = table.rows[r].height
cell_top += cell_height
for c in range(col):
cell_width = table.columns[c].width
cell_left += cell_width
cell_height = table.rows[row].height
cell_width = table.columns[col].width
return cell_left, cell_top, cell_width, cell_height
prs = Presentation('input.pptx')
slide = prs.slides[0]
table = slide.shapes[1].table
# Row and col number you want to place the image.
image_row = 1
image_col = 1
cell_left, cell_top, cell_width, cell_height = calculate_cell_position(table, image_row, image_col)
# Insert the image into the cell.
img_path = 'image.png'
slide.shapes.add_picture(img_path, cell_left, cell_top, width=cell_width, height=cell_height)
prs.save('output.pptx')
Upvotes: 1
Reputation: 29021
No, unfortunately not. Note that this is not a limitation of python-pptx
, it is a limitation of PowerPoint in general. Only text can be placed in a table cell.
There is nothing stopping you from placing a picture shape above (in z-order) a table cell, which will look like the picture is inside. This is a common approach but unfortunately is somewhat brittle. In particular, the row height is not automatically adjusted to "fit" the picture and changes in the content of cells in prior rows can cause lower rows to "move down" and no longer be aligned with the picture. So this approach has some drawbacks.
Another possible approach is to use a picture as the background for a cell (like you might use colored shading or a texture). There is no API support for this in python-pptx
and it's not without its own problems, but might be an approach worth considering.
Upvotes: 2