Python docx ориентация страницы

Python Docx — Разделы — Ориентация страницы

Следующий код пытается использовать landscape ориентация, но документ создается как potrait.
Можете ли вы предложить, где проблема?

from docx import Document from docx.enum.section import WD_ORIENT document = Document() section = document.sections[-1] section.orientation = WD_ORIENT.LANDSCAPE document.add_heading('text') document.save('demo.docx') 

Когда я читаю код обратно как XML

Я плохо знаю XML, предполагая, что теги раздела должны располагаться над тегами TEXT сверху, а не снизу.

5 ответов

Хотя страница правильно помечена как альбомная, ее размеры остаются такими же, как и раньше, и должны быть изменены вручную.

Размеры и ориентация страницы

Три свойства в разделе описывают размеры и ориентацию страницы. Вместе они могут использоваться, например, для изменения ориентации раздела от портрета до пейзажа:

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

Я сделал функцию, которая позволяет легко перейти от альбомной ориентации к портретной ориентации и наоборот:

def change_orientation(): current_section = document.sections[-1] new_width, new_height = current_section.page_height, current_section.page_width new_section = document.add_section(WD_SECTION.NEW_PAGE) new_section.orientation = WD_ORIENT.LANDSCAPE new_section.page_width = new_width new_section.page_height = new_height return new_section 

Тогда просто используйте его, когда захотите:

change_orientation() document.add_picture(ax1) change_orientation() document.add_picture(ax2) 
from docx import Document from docx.shared import Inches from docx.enum.section import WD_SECTION from docx.enum.section import WD_ORIENT 

Отображаете ли вы созданный документ с WordPad или с MS Word?

Если я запускаю следующий код:

$ cat stackru1.py import sys from docx import Document from docx.enum.section import WD_ORIENT document = Document() section = document.sections[0] print section.orientation section.orientation = WD_ORIENT.LANDSCAPE print section.orientation document.add_heading('text') document.save('demo.docx') 

Я вижу, что ориентация меняется:

$ python stackru1.py PORTRAIT (0) LANDSCAPE (1) 

Но на WordPad (У меня нет MS Word), документ показывает в portrait:

введите описание изображения здесь

def change_orientation(): current_section = document.sections[-1] new_width, new_height = current_section.page_height, current_section.page_width new_section = document.add_section(WD_SECTION_START.NEW_PAGE) new_section.orientation = WD_ORIENTATION.LANDSCAPE new_section.page_width = new_width new_section.page_height = new_height return new_section 

Источник

Saved searches

Use saved searches to filter your results more quickly

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

section.orientation = WD_ORIENT.LANDSCAPE don’t work #298

section.orientation = WD_ORIENT.LANDSCAPE don’t work #298

Comments

https://python-docx.readthedocs.io/en/latest/user/sections.html
Describe: There is no change for my docx document by input following code. (No Error raised)
env: win10, office2016, python3.5.1

Page dimensions and orientation

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)

The text was updated successfully, but these errors were encountered:

4 sections, following is my code

from docx import Document from docx.enum.section import WD_ORIENT from docx.enum.section import WD_SECTION from docx.shared import Inches # Accessing sections document = Document() document.add_paragraph('section one ') sections = document.sections # Sections object print('len(sections) = <>'.format(len(sections))) # 1 section = sections[0] # Section object for section in sections: print(section.start_type) # NEW_PAGE (2) # Adding a new section new_section = document.add_section(WD_SECTION.ODD_PAGE) print(new_section.start_type) # ODD_PAGE (4) document.add_paragraph('section two odd page') # Section properties # The Section object has eleven properties that allow page layout settings # to be discovered and specified ## Section start type, describes the type of break that precedes the section section3 = document.add_section() section3.start_type = WD_SECTION.ODD_PAGE document.add_paragraph('section start type even page') ## Page dimensions and orientation (there still some bug) section4 = document.add_section(WD_SECTION.ODD_PAGE) print( 'sec3: orient = <>, page_width = <>, page_height = <>'.format( section4.orientation, section4.page_width, section4.page_height ) ) section4.orientation = WD_ORIENT.LANDSCAPE print('len(sections) = <>'.format(len(sections))) # 4 section4.page_width = 6566865 section4.page_height = 809000 document.add_paragraph('LANDSCAPE') # Page margins(there still some bug) section5 = document.add_section() section5.left_margin = Inches(10) section5.right_margin = Inches(10)

Источник

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¶

Оцените статью