5

Im using python-docx to generate a Microsoft Word document that contains a table with images. The following code block shows the for-loop adding the images to the table:

        row_num = 2
        img_cnt = 0
        for i, var in enumerate(img_list_obj):
            img = "img/NO-" + str(technical_object) + "/" + img_list_obj[i]
            img_cnt = img_cnt + 1
            row = table.rows[row_num].cells

            if (img_cnt % 2) != 0:
                paragraph = row[0].paragraphs[0]
                paragraph.alignment = WD_ALIGN_PARAGRAPH.CENTER
                table.cell(row_num, 0).vertical_alignment = WD_ALIGN_VERTICAL.CENTER
                run = paragraph.add_run()
                run.add_picture(img, width=Cm(7.50), height=Cm(5.50))
            else:
                paragraph = row[1].paragraphs[0]
                paragraph.alignment = WD_ALIGN_PARAGRAPH.CENTER
                table.cell(row_num, 1).vertical_alignment = WD_ALIGN_VERTICAL.CENTER
                run = paragraph.add_run()
                run.add_picture(img, width=Cm(7.50), height=Cm(5.50))
                if i + 1 != len(img_list_obj):
                    table.add_row()
                    row = table.rows[row_num + 1].cells
                    row_num = row_num + 1

Is there any way to add a caption to the images? I am relatively new to Python and python-docx but I cant find any documentation about this topic.

Thanks a lot! Joshua

JCoordes
  • 147
  • 4
  • 10

1 Answers1

6

It seems like python-docx does not support image captions. When you call add_picture an InlineShape is returned according to the documentation. The documentation for InlineShape does not mention anything about captions. In fact, the only time captions are mentioned are in the context of text styles. Additionally, there's an open issue in the python-docx repository regarding this limitation.

ToJa92
  • 431
  • 4
  • 8