使用python-docx将整页图像添加到docx

问题描述 投票:0回答:1

我正在尝试使用python-docx在现有的docx之前添加整页图像,不添加任何边距。

据我了解,代码应该像这样(使用建议的解决方案previously

from docx import Document
from docx.shared import Inches

document = Document('existing.docx')
new_doc = Document()
new_section = new_doc.add_section()
new_section.left_margin = Inches(0.3)
new_doc.add_picture('frontpage.jpg', width=Inches(8.0))
for element in document.element.body:
     new_doc.element.body.append(element)
# for section in new_doc.sections[1:]:
#   section.left_margin = Inches(1.0)
new_doc.save('new.docx')

这有两个问题:

  1. 原样,脚本会更改整个文档的左边距。在没有注释最后两行的情况下,首页的页边距改回1英寸。
  2. 新部分创建了脚本的开头,在文档的开头创建了空白页。

如何正确执行?谢谢。

python image margin python-docx
1个回答
0
投票

调用.add_section()在文档末尾添加一个新节,由分页符分隔。

使用现有部分来设置第一部分的属性,然后添加第二部分并根据文档其余部分的需要调整其属性。

document.sections[0]上提供了新的默认文档中的现有单节。

© www.soinside.com 2019 - 2024. All rights reserved.