Reputation: 834
I am trying to prepend a full page image, no margins, to an existing docx, using python-docx.
It is my understanding that the code should go something like this (using the solution suggested 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')
There are two problems with this:
How do I do it correctly? Thx.
Upvotes: 2
Views: 1337
Reputation: 28893
Calling .add_section()
appends a new section to the end of the document, separated by a page break.
Use the existing section to set the properties of the first section, then add the second section and adjust its properties for what you want for the remainder of the document.
The existing single section in a new default document is available on 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')
Upvotes: 3