Как добавить изображения с подписями к рисункам в документ Word

import win32com.client as win32
import os

#creating a word application object
wordApp = win32.gencache.EnsureDispatch('Word.Application') #create a word application object
wordApp.Visible = True # hide the word application
doc = wordApp.Documents.Add() # create a new application

#Formating the document
doc.PageSetup.RightMargin = 10
doc.PageSetup.LeftMargin = 10
doc.PageSetup.Orientation = win32.constants.wdOrientLandscape
# a4 paper size: 595x842
doc.PageSetup.PageWidth = 595
doc.PageSetup.PageHeight = 842


# Inserting Tables
my_dir="C:/Users/David/Documents/EGi/EGi Plots/FW_plots/Boxplots"
filenames = os.listdir(my_dir)
piccount=0
file_count = 0
for i in filenames:
    if i[len(i)-3: len(i)].upper() == 'JPG': # check whether the current object is a JPG file
        piccount = piccount + 1

print piccount, " images will be inserted"

total_column = 1
total_row = int(piccount/total_column)+2
rng = doc.Range(0,0)
rng.ParagraphFormat.Alignment = win32.constants.wdAlignParagraphCenter
table = doc.Tables.Add(rng,total_row, total_column)
table.Borders.Enable = False
if total_column > 1:
    table.Columns.DistributeWidth()

#Collecting images in the same directory and inserting them into the document


piccount = 1

for index, filename in enumerate(filenames): # loop through all the files and folders for adding pictures

    if os.path.isfile(os.path.join(os.path.abspath(my_dir), filename)): # check whether the current object is a file or not
        if filename[len(filename)-3: len(filename)].upper() == 'JPG': # check whether the current object is a JPG file
            piccount = piccount + 1
            print filename, len(filename), filename[len(filename)-3: len(filename)].upper()


            cell_column = (piccount % total_column + 1) #calculating the position of each image to be put into the correct table cell
            cell_row = (piccount/total_column + 1)
            #print 'cell_column=%s,cell_row=%s' % (cell_column,cell_row)

            #we are formatting the style of each cell
            cell_range= table.Cell(cell_row, cell_column).Range
            cell_range.ParagraphFormat.LineSpacingRule = win32.constants.wdLineSpaceSingle
            cell_range.ParagraphFormat.SpaceBefore = 0
            cell_range.ParagraphFormat.SpaceAfter = 3

            #this is where we are going to insert the images
            current_pic=cell_range.InlineShapes.AddPicture(os.path.join(os.path.abspath(my_dir), filename))


            #Currently this puts a lable in a cell after the pic, I want to put a proper ms word figure caption below the image instead.
            table.Cell(cell_row, cell_column).Range.InsertAfter("\n"+"Appendix II Figure "+ str(piccount-1)+": "+filename[:len(filename)-4]+"\n"+"\n"+"\n")


        else: continue

Этот код получает все изображения в выбранном каталоге и помещает их в таблицу в документе Word, а затем помещает имя файла (без расширения файла) в ячейку ниже. Я хотел бы правильную подпись к рисунку (чтобы они обновлялись, если я вставлю дополнительные изображения), но все, что я пробовал, не помогло.

Я просто не могу правильно понять команды VB, это:

table.Cell(cell_row, cell_column).Range.InsertAfter(InsertCaption(Label="Figure", Title=": "+filename[:len(filename)-4]))

дает мне список подписей к рисункам в конце документа, что на самом деле не то, что мне нужно. Я чувствую, что я близок, но я просто не могу этого понять. Спасибо!


person flashliquid    schedule 14.12.2018    source источник
comment
Вы пробовали current_pic.InsertCaption? docs.microsoft.com/en-us/office/ vba/апи/   -  person najeem    schedule 14.12.2018
comment
@najeem да, я получаю следующее: AttributeError: '‹win32com.gen_py.Microsoft Word 16.0 Object Library.InlineShape instance at 0x1245537160›' объект не имеет атрибута 'InsertCaption'   -  person flashliquid    schedule 14.12.2018
comment
@flashliquid См.: msofficeforums.com/ слово-vba/   -  person macropod    schedule 15.12.2018


Ответы (1)


Чтобы использовать встроенные субтитры Word, вместо current_pic.InsertCaption используйте current_Pic.Range.InsertCaption. Метод InsertCaption является членом объекта Range, а не объекта InlineShape. Для меня это автоматически вставляет заголовок под изображением в отдельный абзац. Но если вы хотите указать «ниже», используйте также аргумент Position:

current_pic.Range.InsertCaption(Label="Figure", Title=": "+filename[:len(filename)-4]), Position=win32.constants.wdCaptionPositionBelow

Примечание: FWIW, когда я тестирую строку кода (в VBA), которая, как вы говорите, дает вам список подписей в конце документа, я вижу текст в той же ячейке, что и вставленное изображение.

person Cindy Meister    schedule 14.12.2018
comment
Спасибо, Синди Мейстер, я рвал на себе волосы из-за этого и обнаружил, что документы VBA совершенно непонятны, а obs теперь кажутся довольно глупыми. Спасибо за решение, делает именно то, что я хочу (и не нуждался в позиции). Ваше здоровье! - person flashliquid; 14.12.2018