My task is to automate the formatting of a document according to the user’s input. I had to add cover and back page images with smaller margins than the rest of the document. I figured out how to add the cover page image with some help from ChatGPT, but I am unable to figure out how to properly add a back page image. The problem I’m facing is when adding a new section(since I need different margins), it inherits the header and footer property from the previous section. To prevent this I used is_linked_to_previous = False
for both header and footer. But it didn’t quite work. On examining the XML of the docx produced, I found that the new section still had references for header and footer and even the page margin had tags for header and footer which I guess are taking the extra space.
Following is the XML:
<w:sectPr w:rsidR="00C84B07" w:rsidRPr="00813D6B">
<w:headerReference w:type="default" r:id="rId13" />
<w:footerReference w:type="default" r:id="rId14" />
<w:pgSz w:w="11906" w:h="16838" />
<w:pgMar w:top="288" w:right="1440" w:bottom="1440" w:left="288" w:header="708"
w:footer="708" w:gutter="0" />
<w:cols w:space="708" />
<w:docGrid w:linePitch="360" />
</w:sectPr>
Shouldn’t the headerReference
and footerReference
not be present since I have mentioned not the link to previous. Same goes for the w:header
and w:footer
tags in <w:pgMar>
.
I have used the following code to add a back page image:
def add_back_page_image(doc, image, margin_size=Inches(0.2)):
"""Adding a back page image."""
back_section = doc.add_section()
back_section.header.is_linked_to_previous = False
back_section.footer.is_linked_to_previous = False
back_section.top_margin = margin_size
back_section.left_margin = margin_size
image_width = back_section.page_width - margin_size * 2
image_height = back_section.page_height - margin_size * 2
back_paragraph = doc.add_paragraph()
back_paragraph.alignment = WD_ALIGN_PARAGRAPH.CENTER
back_paragraph.add_run().add_picture(image, width=image_width, height=image_height)
This is the result obtained: