簡體   English   中英

使用 python-docx 將整頁圖像添加到 docx

[英]Prepending a full-page image to docx using python-docx

我正在嘗試使用 python-docx 在現有 docx 中添加一個完整的頁面圖像,沒有邊距。

據我了解,代碼應該像這樣 go (使用之前建議的解決方案)

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. 新建部分在腳本的開頭創建了一個在文檔開頭的空白頁。

我該如何正確地做到這一點? 謝謝。

調用.add_section()會在文檔末尾追加一個新部分,由分頁符分隔。

使用現有部分設置第一個部分的屬性,然后添加第二個部分並根據文檔其余部分的需要調整其屬性。

新默認文檔中現有的單個部分可在document.sections[0]上找到。

from docx import Document
from docx.shared import Inches

target_document = Document()
target_document.sections[0].left_margin = Inches(0.3)
target_document.add_picture('frontpage.jpg', width=Inches(8.0))

new_section = target_document.add_section()
new_section.left_margin = Inches(1.0)

source_document = Document('existing.docx')
for paragraph in source_document.paragraphs:
     target_document.add_paragraph(paragraph.text)
new_doc.save('new.docx')

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM