Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change page size to A4 in python-docx

I try out creating Word documents with python-docx. The created file is in letter dimensions 8.5 x 11 inches. But in Germany the standard format is A4 8.27 x 11.69 inches.

from docx import Document
from docx.shared import Inches

document = Document()

document.add_heading('Document Title', 0)
document.settings


p = document.add_paragraph('A plain paragraph having some ')
p.add_run('bold').bold = True
p.add_run(' and some ')
p.add_run('italic.').italic = True

document.add_heading('Heading, level 1', level=1)
document.add_paragraph('Intense quote', style='IntenseQuote')

document.add_paragraph(
    'first item in unordered list', style='ListBullet'
)
document.add_paragraph(
    'first item in ordered list', style='ListNumber'
)



table = document.add_table(rows=1, cols=3)
hdr_cells = table.rows[0].cells
hdr_cells[0].text = 'Qty'
hdr_cells[1].text = 'Id'
hdr_cells[2].text = 'Desc'


document.add_page_break()

document.save('demo.docx')

I don't find any information about this topic in the documentation.

like image 700
Georg Gutsche Avatar asked May 01 '17 18:05

Georg Gutsche


2 Answers

from docx.shared import Mm

document = Document()
section = document.sections[0]
section.page_height = Mm(297)
section.page_width = Mm(210)
section.left_margin = Mm(25.4)
section.right_margin = Mm(25.4)
section.top_margin = Mm(25.4)
section.bottom_margin = Mm(25.4)
section.header_distance = Mm(12.7)
section.footer_distance = Mm(12.7)
like image 94
Tedo Vrbanec Avatar answered Sep 26 '22 12:09

Tedo Vrbanec


It appears that a Document is made of several Sections with page_height and page_width attributes.

To set the dimensions of the first section to A4, you could try (untested):

section = document.sections[0]
section.page_height = Mm(297)
section.page_width = Mm(210)

Note that A4 is defined in millimeters.

like image 20
mkrieger1 Avatar answered Sep 23 '22 12:09

mkrieger1