如何在python的word文档中的特定位置插入图片?

How to insert an Image in a specific position in a word document with python?

我的程序创建了一堆 word 文件:它们包含有关学生的信息,例如姓名地址 Phone 号码 ... 和条形码。 当我将 QRCode 作为图片插入时,它会附加在文件末尾。我希望它被插入到文本 "Barcode" 的最右边。 我徒劳地寻找解决方案。 我插入了一张解释单词的图片。抱歉,我隐藏了这些信息,因为它是机密信息。 这是我的代码:

import uuid 
import pandas as pd
import pyqrcode 
from docx import Document
from docx.shared import Inches


def generateBarCode(length):
    return str(uuid.uuid4()).replace('-','')[0:length]


df=pd.DataFrame(pd.read_excel('Komplette- 
GastAccountFHZugangsdatenFertig.xlsx'))
array=[]
for i in range(len(df)):
    qr=pyqrcode.create(generateBarCode(8))
    array.append(qr)


df.insert(8,'Barcode',array)
x=['.png']

with pd.ExcelWriter('Komplette-GastAccountFHZugangsdatenFertig.xlsx') as 
writer :
   df.to_excel(writer,sheet_name='Sheet1')

for i in range(len(df)):
    document=Document()
    document.add_heading('Informationen')
    document.add_paragraph('Name : ' + df['Name'][i])
    document.add_paragraph('Vorname : ' + df['Vorname '][i])
    document.add_paragraph('Geschlecht : ' + df['Geschlecht'][i])
    document.add_paragraph('Adresse(in Marokko) : ' + df['Adresse (in 
Marokko)'][i])
    document.add_paragraph('Telefonnummer : ' + str(df['Telefonnummer'][i]))
    document.add_paragraph('E-Mailadresse : ' + str(df['E-Mailadresse'][i]))
    document.add_paragraph('Studiengang : ' + df['Studiengang'][i] )
    document.add_paragraph('Semester : ' + str(df['Semester'][i]))
    document.add_paragraph('Barcode : ')
    qr=df['Barcode'][i]

    qr.png(df['Name'][i]+df['Vorname '][i]+x[0])
    document.add_picture(df['Name'][i]+df['Vorname '] 
[i]+'.png',width=Inches(2.0))

    document.save(df['Name'][i]+' '+ df['Vorname '][i]+'.docx')

截图

谢谢

在 python-docx here 的文档中查看 Document.add_picture 的实现给出

def add_picture(self, image_path_or_stream, width=None, height=None):
    run = self.add_paragraph().add_run()
    return run.add_picture(image_path_or_stream, width, height)

利用这些信息,您可以使用

document.add_paragraph('Barcode : ')
        .add_run()
        .add_picture(df['Name'][i]+df['Vorname '] [i]+'.png',width=Inches(2.0))

将图片添加到同一个段落。我还没有测试过,但我希望这能解决问题。

在word文档的特定位置插入一张图片 python

使用Python的docx模块,我们可以在文档

的特定位置添加图片

请参阅我的 post 此处链接相同