Add image caption using python-docx

Viewed 2170

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

1 Answers
Related