【问题标题】:How do you insert an image into a specific location in an existing Word document with Python?如何使用 Python 将图像插入到现有 Word 文档中的特定位置?
【发布时间】:2021-04-05 18:23:13
【问题描述】:

我想要做的是使用 Python 将图像插入到现有 Word 文档中的特定位置。我查看了各种库来做到这一点;我正在使用docx-mailmerge 包使用 Word 合并字段插入文本和表格,但不幸的是,图像合并只是 TODO/wishlist 功能。 python-docx 同时允许插入图片,但只能在文档末尾,不能在特定位置。

是否有其他库可以做到这一点,或者有一个很好的技巧来完成它?

【问题讨论】:

    标签: python ms-word


    【解决方案1】:

    摆弄底层 API(感谢this SO answer)我破解了成功之路:

    1. 在您的 Word 文档中添加一个占位符,该占位符应该放在图像所在的位置,类似于显示 [ChartImage1] 的单行
    2. 在包含该文本的文档中查找段落对象
    3. 将该段落的文本替换为空字符串
    4. 添加一个运行,然后在其中添加您的图像

    比如:

    document = Document("template.docx")
    image_paras = [i for i, p in enumerate(document.paragraphs) if "[ChartImage1]" in p.text]
    p = document.paragraphs[image_paras[0]]
    p.text = ""
    r = p.add_run()
    r.add_picture("path/to/image.png")
    document.save("my_doc.docx")
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-12-25
      • 1970-01-01
      相关资源
      最近更新 更多