Python docx page size

python-docx¶

python-docx is a Python library for creating and updating Microsoft Word (.docx) files.

What it can do¶

Here’s an example of what python-docx can do:

from docx import Document from docx.shared import Inches document = Document() document.add_heading('Document Title', 0) 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='Intense Quote') document.add_paragraph( 'first item in unordered list', style='List Bullet' ) document.add_paragraph( 'first item in ordered list', style='List Number' ) document.add_picture('monty-truth.png', width=Inches(1.25)) records = ( (3, '101', 'Spam'), (7, '422', 'Eggs'), (4, '631', 'Spam, spam, eggs, and spam') ) 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' for qty, id, desc in records: row_cells = table.add_row().cells row_cells[0].text = str(qty) row_cells[1].text = id row_cells[2].text = desc document.add_page_break() document.save('demo.docx') 

User Guide¶

API Documentation¶

  • Document objects
    • Document constructor
    • Document objects
    • CoreProperties objects
    • Styles objects
    • BaseStyle objects
    • _CharacterStyle objects
    • _ParagraphStyle objects
    • _TableStyle objects
    • _NumberingStyle objects
    • LatentStyles objects
    • _LatentStyle objects
    • Paragraph objects
    • ParagraphFormat objects
    • Run objects
    • Font objects
    • TabStop objects
    • TabStops objects
    • Table objects
    • _Cell objects
    • _Row objects
    • _Column objects
    • _Rows objects
    • _Columns objects
    • Sections objects
    • Section objects
    • _Header and _Footer objects
    • InlineShapes objects
    • InlineShape objects
    • ColorFormat objects
    • Length objects
    • RGBColor objects
    • MSO_COLOR_TYPE
    • MSO_THEME_COLOR_INDEX
    • WD_PARAGRAPH_ALIGNMENT
    • WD_BUILTIN_STYLE
    • WD_CELL_VERTICAL_ALIGNMENT
    • WD_COLOR_INDEX
    • WD_LINE_SPACING
    • WD_ORIENTATION
    • WD_TABLE_ALIGNMENT
    • WD_ROW_HEIGHT_RULE
    • WD_SECTION_START
    • WD_STYLE_TYPE
    • WD_TAB_ALIGNMENT
    • WD_TAB_LEADER
    • WD_TABLE_DIRECTION
    • WD_UNDERLINE

    Источник

    How to change page size to A4 in python-docx

    I believe you want this, from the documentation.

    Three properties on Section describe page dimensions and orientation. Together these can be used, for example, to change the orientation of a section from portrait to landscape:

    >>> section.orientation, section.page_width, section.page_height (PORTRAIT (0), 7772400, 10058400) # (Inches(8.5), Inches(11)) >>> new_width, new_height = section.page_height, section.page_width >>> section.orientation = WD_ORIENT.LANDSCAPE >>> section.page_width = new_width >>> section.page_height = new_height >>> section.orientation, section.page_width, section.page_height (LANDSCAPE (1), 10058400, 7772400) 

    David Metcalfe 2031

    It appears that a Document is made of several Section s 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.

    mkrieger1 15694

    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) 

    Tedo Vrbanec 471

    • How to change a figure’s size in Python Seaborn package
    • How to change font size using the Python ImageDraw Library
    • How to change page size to A4 in python-docx
    • How can I change the size of my python turtle window?
    • Python keras how to change the size of input after convolution layer into lstm layer
    • How to change the default 404 page while using python SimpleHTTPServer
    • How do I change the size of figures drawn with Matplotlib?
    • How to change the font size on a matplotlib plot
    • How do I change the figure size with subplots?
    • How to change legend size with matplotlib.pyplot
    • How to change the figure size of a seaborn axes or figure level plot
    • How do I change the string representation of a Python class?
    • How to change default Anaconda python environment
    • How to change default Python version?
    • How to change backends in matplotlib / Python
    • How to change Python version of existing conda virtual environment?
    • How can I change the font size using seaborn FacetGrid?
    • How to obtain image size using standard Python class (without using external library)?
    • How to change the message in a Python AssertionError?
    • How to run a Python script in a web page
    • Why does the size of this Python String change on a failed int conversion
    • How to change filehandle with Python logging on the fly with different classes and imports
    • How to know bytes size of python object like arrays and dictionaries? — The simple way
    • How to change json encoding behaviour for serializable python object?
    • How do I change the format of a Python log message on a per-logger basis?
    • How can I change directory with Python pathlib
    • How can I change the Python version in Visual Studio Code?
    • How to set the labels size on a pie chart in python
    • How to limit log file size in python
    • How to change python version in anaconda spyder
    • How do I change the text size in a Label widget? (tkinter)
    • How to change size of bokeh figure
    • How to change tcp keepalive timer using python script?
    • How do I reduce a python (docker) image size using a multi-stage build?
    • How to change the Python Interpreter that gdb uses?
    • How do I change button size in Python?
    • How can I change the font size of ticks of axes object in matplotlib
    • How to change the path of Python in Spyder?
    • How can I change the size of my Dash Graph?
    • how to submit query to .aspx page in python
    • How to change the date/time in Python for all modules?
    • How to change the point size for regplot(), seaborn’s scatter plot function (python)
    • How do I change Sublime Python comments color specifically?
    • How to increase message size in grpc using python
    • Python WebDriver how to print whole page source (html)
    • How to change the default Python interpreter in Sublime text 3
    • How to change font and size of buttons and frame in tkinter using python?
    • How to extract URLs from an HTML page in Python
    • How to change python version in Anaconda?
    • How do I change a value while debugging python with pdb?

    More Query from same tag

    • How to Retrieve name of current Windows User (AD or local) using Python?
    • Create stacked histogram from unequal length arrays
    • subprocess.CalledProcessError: what *is* the error?
    • How to pass an entire list as command line argument in Python?
    • Draw underline text with PIL
    • Explanation of need for Multi Threading GUI programming
    • Python module ecdsa errors while running paramiko
    • bottle framework with multiple files
    • How to list objects based on prefixes with wildcard using Python Boto3?
    • Why manual string reverse is worse than slice reverse in Python 2.7? What is the algorithm being used in Slice?
    • Python reversing an UTF-8 string
    • How do I get rid of Python Tkinter root window?
    • TensorFlow — Difference between tf.keras.layers.Layer vs tf.keras.Model
    • Can’t turn off images in Selenium / Firefox
    • How to avoid repetitive filter specification in mako %def’s?
    • What is the difference between SymPy and Sage?
    • library for transforming a node tree
    • Get all __slots__ of derived class
    • Should I be using SQLObject, SQLAlchemy, or SQLAlchemy + Elixir?
    • `UnencryptedCookieSessionFactoryConfig` error when importing Apex
    • networks with random power-law distributed weights
    • Python — The Standard Library — ascii( ) Function
    • Handling PyLint Warning of Inconsistent Return Statement
    • Python recursion challenge
    • guessing the rgb gradient from a map?
    • Is there a good emacs plugin for Python just like ESS for R and slime for Lisp?
    • Python package dependency tree
    • Temporarily modify the current process’s environment
    • The specified device is not open or is not recognized by MCI
    • How can I suppress newline in Python logging module.
    • Why Bother With Recurrent Neural Networks For Structured Data?
    • Labeling points in matplotlib scatterplot
    • IOError: [Errno 2] No such file or directory (when it really exist) Python
    • List comprehension for multiplying each string in a list by numbers from given range
    • Add a dll/so to a python built distribution

    Источник

    Working with Sections¶

    Word supports the notion of a section, a division of a document having the same page layout settings, such as margins and page orientation. This is how, for example, a document can contain some pages in portrait layout and others in landscape.

    Most Word documents have only the single section that comes by default and further, most of those have no reason to change the default margins or other page layout. But when you do need to change the page layout, you’ll need to understand sections to get it done.

    Accessing sections¶

    Access to document sections is provided by the sections property on the Document object:

    >>> document = Document() >>> sections = document.sections >>> sections >>> len(sections) 3 >>> section = sections[0] >>> section >>> for section in sections: . print(section.start_type) . NEW_PAGE (2) EVEN_PAGE (3) ODD_PAGE (4) 

    It’s theoretically possible for a document not to have any explicit sections, although I’ve yet to see this occur in the wild. If you’re accessing an unpredictable population of .docx files you may want to provide for that possibility using a len() check or try block to avoid an uncaught IndexError exception stopping your program.

    Adding a new section¶

    The Document.add_section() method allows a new section to be started at the end of the document. Paragraphs and tables added after calling this method will appear in the new section:

    >>> current_section = document.sections[-1] # last section in document >>> current_section.start_type NEW_PAGE (2) >>> new_section = document.add_section(WD_SECTION.ODD_PAGE) >>> new_section.start_type ODD_PAGE (4) 

    Section properties¶

    The Section object has eleven properties that allow page layout settings to be discovered and specified.

    Section start type¶

    Section.start_type describes the type of break that precedes the section:

    >>> section.start_type NEW_PAGE (2) >>> section.start_type = WD_SECTION.ODD_PAGE >>> section.start_type ODD_PAGE (4) 

    Values of start_type are members of the WD_SECTION_START enumeration.

    Page dimensions and orientation¶

    Three properties on Section describe page dimensions and orientation. Together these can be used, for example, to change the orientation of a section from portrait to landscape:

    >>> section.orientation, section.page_width, section.page_height (PORTRAIT (0), 7772400, 10058400) # (Inches(8.5), Inches(11)) >>> new_width, new_height = section.page_height, section.page_width >>> section.orientation = WD_ORIENT.LANDSCAPE >>> section.page_width = new_width >>> section.page_height = new_height >>> section.orientation, section.page_width, section.page_height (LANDSCAPE (1), 10058400, 7772400) 

    Page margins¶

    Seven properties on Section together specify the various edge spacings that determine where text appears on the page:

    >>> from docx.shared import Inches >>> section.left_margin, section.right_margin (1143000, 1143000) # (Inches(1.25), Inches(1.25)) >>> section.top_margin, section.bottom_margin (914400, 914400) # (Inches(1), Inches(1)) >>> section.gutter 0 >>> section.header_distance, section.footer_distance (457200, 457200) # (Inches(0.5), Inches(0.5)) >>> section.left_margin = Inches(1.5) >>> section.right_margin = Inches(1) >>> section.left_margin, section.right_margin (1371600, 914400) 

    Источник

    Читайте также:  End команда в python
Оцените статью