4. Headers, Footers, and Page Setup
4. Headers, Footers, and Page Setup
"""
Configure headers, footers, page numbers, and page setup.
"""
from docx import Document
from docx.shared import Inches, Pt, Cm
from docx.enum.text import WD_ALIGN_PARAGRAPH
from docx.enum.section import WD_ORIENT
from docx.oxml.ns import qn
from docx.oxml import OxmlElement
def add_page_number(paragraph) -> None:
"""Add page number field to paragraph."""
run = paragraph.add_run()
fldChar1 = OxmlElement('w:fldChar')
fldChar1.set(qn('w:fldCharType'), 'begin')
instrText = OxmlElement('w:instrText')
instrText.set(qn('xml:space'), 'preserve')
instrText.text = "PAGE"
fldChar2 = OxmlElement('w:fldChar')
fldChar2.set(qn('w:fldCharType'), 'separate')
fldChar3 = OxmlElement('w:fldChar')
fldChar3.set(qn('w:fldCharType'), 'end')
run._r.append(fldChar1)
run._r.append(instrText)
run._r.append(fldChar2)
run._r.append(fldChar3)
def add_total_pages(paragraph) -> None:
"""Add total page count field to paragraph."""
run = paragraph.add_run()
fldChar1 = OxmlElement('w:fldChar')
fldChar1.set(qn('w:fldCharType'), 'begin')
instrText = OxmlElement('w:instrText')
instrText.set(qn('xml:space'), 'preserve')
instrText.text = "NUMPAGES"
fldChar2 = OxmlElement('w:fldChar')
fldChar2.set(qn('w:fldCharType'), 'separate')
fldChar3 = OxmlElement('w:fldChar')
fldChar3.set(qn('w:fldCharType'), 'end')
run._r.append(fldChar1)
run._r.append(instrText)
run._r.append(fldChar2)
run._r.append(fldChar3)
def create_document_with_headers_footers(output_path: str) -> None:
"""Create document with headers, footers, and page numbers."""
doc = Document()
# Access the default section
section = doc.sections[0]
# Set page margins
section.top_margin = Inches(1)
section.bottom_margin = Inches(1)
section.left_margin = Inches(1.25)
section.right_margin = Inches(1.25)
# Set page size (Letter)
section.page_width = Inches(8.5)
section.page_height = Inches(11)
# Configure header
header = section.header
header_para = header.paragraphs[0]
# Add company logo placeholder and title
header_para.text = "ACME Corporation"
header_para.alignment = WD_ALIGN_PARAGRAPH.CENTER
header_run = header_para.runs[0]
header_run.bold = True
header_run.font.size = Pt(14)
# Add subtitle to header
subtitle_para = header.add_paragraph()
subtitle_para.text = "Confidential Document"
subtitle_para.alignment = WD_ALIGN_PARAGRAPH.CENTER
subtitle_para.runs[0].font.size = Pt(10)
subtitle_para.runs[0].italic = True
# Configure footer with page numbers
footer = section.footer
footer_para = footer.paragraphs[0]
footer_para.alignment = WD_ALIGN_PARAGRAPH.CENTER
# Add "Page X of Y" format
footer_para.add_run("Page ")
add_page_number(footer_para)
footer_para.add_run(" of ")
add_total_pages(footer_para)
# Add document content
doc.add_heading('Document Title', level=0)
# Add multiple paragraphs to create multiple pages
for i in range(1, 4):
doc.add_heading(f'Section {i}', level=1)
for j in range(5):
doc.add_paragraph(
f'This is paragraph {j+1} of section {i}. '
'Lorem ipsum dolor sit amet, consectetur adipiscing elit. '
'Sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. '
'Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris.'
)
# Add page break after each section (except last)
if i < 3:
doc.add_page_break()
doc.save(output_path)
print(f"Document with headers/footers saved to {output_path}")
def create_landscape_document(output_path: str) -> None:
"""Create document with landscape orientation."""
doc = Document()
section = doc.sections[0]
# Set landscape orientation
section.orientation = WD_ORIENT.LANDSCAPE
# Swap width and height for landscape
new_width = section.page_height
new_height = section.page_width
section.page_width = new_width
section.page_height = new_height
# Add content
doc.add_heading('Wide Format Report', level=0)
doc.add_paragraph('This document is in landscape orientation, ideal for wide tables.')
# Add wide table
table = doc.add_table(rows=5, cols=8)
table.style = 'Table Grid'
headers = ['ID', 'Name', 'Q1', 'Q2', 'Q3', 'Q4', 'Total', 'Growth']
for i, header in enumerate(headers):
table.rows[0].cells[i].text = header
doc.save(output_path)
print(f"Landscape document saved to {output_path}")
create_document_with_headers_footers('headers_footers.docx')
create_landscape_document('landscape_report.docx')
1---2name: python-docx-4-headers-footers-and-page-setup3description: Sub-skill of python-docx: 4. Headers, Footers, and Page Setup.4---56# 4. Headers, Footers, and Page Setup78## 4. Headers, Footers, and Page Setup91011```python12"""13Configure headers, footers, page numbers, and page setup.14"""15from docx import Document16from docx.shared import Inches, Pt, Cm17from docx.enum.text import WD_ALIGN_PARAGRAPH18from docx.enum.section import WD_ORIENT19from docx.oxml.ns import qn20from docx.oxml import OxmlElement2122def add_page_number(paragraph) -> None:23 """Add page number field to paragraph."""24 run = paragraph.add_run()25 fldChar1 = OxmlElement('w:fldChar')26 fldChar1.set(qn('w:fldCharType'), 'begin')2728 instrText = OxmlElement('w:instrText')29 instrText.set(qn('xml:space'), 'preserve')30 instrText.text = "PAGE"3132 fldChar2 = OxmlElement('w:fldChar')33 fldChar2.set(qn('w:fldCharType'), 'separate')3435 fldChar3 = OxmlElement('w:fldChar')36 fldChar3.set(qn('w:fldCharType'), 'end')3738 run._r.append(fldChar1)39 run._r.append(instrText)40 run._r.append(fldChar2)41 run._r.append(fldChar3)424344def add_total_pages(paragraph) -> None:45 """Add total page count field to paragraph."""46 run = paragraph.add_run()47 fldChar1 = OxmlElement('w:fldChar')48 fldChar1.set(qn('w:fldCharType'), 'begin')4950 instrText = OxmlElement('w:instrText')51 instrText.set(qn('xml:space'), 'preserve')52 instrText.text = "NUMPAGES"5354 fldChar2 = OxmlElement('w:fldChar')55 fldChar2.set(qn('w:fldCharType'), 'separate')5657 fldChar3 = OxmlElement('w:fldChar')58 fldChar3.set(qn('w:fldCharType'), 'end')5960 run._r.append(fldChar1)61 run._r.append(instrText)62 run._r.append(fldChar2)63 run._r.append(fldChar3)646566def create_document_with_headers_footers(output_path: str) -> None:67 """Create document with headers, footers, and page numbers."""68 doc = Document()6970 # Access the default section71 section = doc.sections[0]7273 # Set page margins74 section.top_margin = Inches(1)75 section.bottom_margin = Inches(1)76 section.left_margin = Inches(1.25)77 section.right_margin = Inches(1.25)7879 # Set page size (Letter)80 section.page_width = Inches(8.5)81 section.page_height = Inches(11)8283 # Configure header84 header = section.header85 header_para = header.paragraphs[0]8687 # Add company logo placeholder and title88 header_para.text = "ACME Corporation"89 header_para.alignment = WD_ALIGN_PARAGRAPH.CENTER90 header_run = header_para.runs[0]91 header_run.bold = True92 header_run.font.size = Pt(14)9394 # Add subtitle to header95 subtitle_para = header.add_paragraph()96 subtitle_para.text = "Confidential Document"97 subtitle_para.alignment = WD_ALIGN_PARAGRAPH.CENTER98 subtitle_para.runs[0].font.size = Pt(10)99 subtitle_para.runs[0].italic = True100101 # Configure footer with page numbers102 footer = section.footer103 footer_para = footer.paragraphs[0]104 footer_para.alignment = WD_ALIGN_PARAGRAPH.CENTER105106 # Add "Page X of Y" format107 footer_para.add_run("Page ")108 add_page_number(footer_para)109 footer_para.add_run(" of ")110 add_total_pages(footer_para)111112 # Add document content113 doc.add_heading('Document Title', level=0)114115 # Add multiple paragraphs to create multiple pages116 for i in range(1, 4):117 doc.add_heading(f'Section {i}', level=1)118 for j in range(5):119 doc.add_paragraph(120 f'This is paragraph {j+1} of section {i}. '121 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. '122 'Sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. '123 'Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris.'124 )125126 # Add page break after each section (except last)127 if i < 3:128 doc.add_page_break()129130 doc.save(output_path)131 print(f"Document with headers/footers saved to {output_path}")132133134def create_landscape_document(output_path: str) -> None:135 """Create document with landscape orientation."""136 doc = Document()137138 section = doc.sections[0]139140 # Set landscape orientation141 section.orientation = WD_ORIENT.LANDSCAPE142143 # Swap width and height for landscape144 new_width = section.page_height145 new_height = section.page_width146 section.page_width = new_width147 section.page_height = new_height148149 # Add content150 doc.add_heading('Wide Format Report', level=0)151 doc.add_paragraph('This document is in landscape orientation, ideal for wide tables.')152153 # Add wide table154 table = doc.add_table(rows=5, cols=8)155 table.style = 'Table Grid'156157 headers = ['ID', 'Name', 'Q1', 'Q2', 'Q3', 'Q4', 'Total', 'Growth']158 for i, header in enumerate(headers):159 table.rows[0].cells[i].text = header160161 doc.save(output_path)162 print(f"Landscape document saved to {output_path}")163164165create_document_with_headers_footers('headers_footers.docx')166create_landscape_document('landscape_report.docx')167```