from docx import Document
from docx.shared import Inches
from docx.oxml.ns import qn
from docx.enum.text import WD_ALIGN_PARAGRAPH
def center_insert_img(doc, img):
? ? """插入圖片"""
? ? for paragraph in doc.paragraphs:
? ? ? ? # 根據(jù)文檔中的占位符定位圖片插入的位置
? ? ? ? if '<<img1>>' in paragraph.text:
? ? ? ? ? ? # 把占位符去掉
? ? ? ? ? ? paragraph.text = paragraph.text.replace('<<img1>>', '')
? ? ? ? ? ? run = paragraph.add_run('')
? ? ? ? ? ? run.add_break()
? ? ? ? ? ? # 添加圖片并指定大小
? ? ? ? ? ? run.add_picture(img, width=Inches(6.2))
def save_img_to_doc(img):
? ? """把圖片保存到doc文件中的指定位置"""
? ? tpl_doc = 'C:/Users/Thinkpad/Desktop/2.docx'
? ? res_doc = 'C:/Users/Thinkpad/Desktop/22.docx'
? ? # 打開模板文件
? ? document = Document(tpl_doc)
? ? # 插入圖片居中
? ? center_insert_img(document, img)
? ? # 保存結(jié)果文件
? ? document.save(res_doc)
def main():
? ? """主函數(shù)"""
? ? img = r'C:/Users/Thinkpad/Desktop/1.png'
? ? save_img_to_doc(img)文章來源:http://www.zghlxwxcb.cn/news/detail-516762.html
if __name__ == '__main__':
? ? main()
?文章來源地址http://www.zghlxwxcb.cn/news/detail-516762.html
到了這里,關(guān)于python 利用word中占位符號(hào)實(shí)現(xiàn)按word指定位置插入圖片的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!