如何在python-docx中为每个节设置不同的页脚?
解决python-docx中各节页脚同步修改的问题
问题根源是python-docx中新增的节默认会继承前一节的页眉页脚关联对象,导致所有节共享同一个页脚实例,修改其中一个就会同步到所有节。要让每个节的页脚独立,必须先断开与前一节的链接。
修改后的代码如下:
from docx import Document from docx.enum.section import WD_SECTION document = Document() n_pages = 5 for pp in range(0, n_pages): if pp < n_pages - 1: document.add_section(WD_SECTION.NEW_PAGE) current_section = document.sections[-1] # 断开当前节页脚与前一节的链接,使其独立 current_section.footer.is_linked_to_previous = False current_section.first_page_footer.is_linked_to_previous = False # 现在修改页脚就只会影响当前节 current_section.footer.paragraphs[0].text = str(pp) current_section.first_page_footer.paragraphs[0].text = str(pp) document.save('Apple.doc') # 此时每页页脚分别是0、1、2、3、4 document.sections[1].footer.paragraphs[0].text = 'Banana' document.save('Banana.doc') # 只有第2节的页脚变成Banana,其他节不受影响
关键修改点:
- 对每个节的
footer和first_page_footer设置is_linked_to_previous = False,切断与前一节的关联,让当前节拥有独立的页脚对象。 - 必须在修改页脚内容前执行断开操作,否则修改的还是共享的实例。
内容的提问来源于stack exchange,提问作者Castim
相关产品推荐
相关产品推荐

