- Python Docx — Разделы — Ориентация страницы
- 5 ответов
- Размеры и ориентация страницы
- Отображаете ли вы созданный документ с WordPad или с MS Word?
- Saved searches
- Use saved searches to filter your results more quickly
- section.orientation = WD_ORIENT.LANDSCAPE don’t work #298
- section.orientation = WD_ORIENT.LANDSCAPE don’t work #298
- Comments
- python-docx¶
- What it can do¶
- User Guide¶
- API Documentation¶
- Working with Sections¶
- Accessing sections¶
- Adding a new section¶
- Section properties¶
- Section start type¶
- Page dimensions and orientation¶
- Page margins¶
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¶
- 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
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)