### Open a New Document with Python-Docx Source: https://github.com/skelmis/python-docx/blob/master/docs/user/quickstart.md Initializes a new, blank Word document using the default template provided by the python-docx library. This is the starting point for most document generation tasks. ```python from skelmis.docx import Document document = Document() ``` -------------------------------- ### Add Paragraph with Style Source: https://github.com/skelmis/python-docx/blob/master/docs/user/quickstart.md Creates a new paragraph in the Word document and immediately applies a specified paragraph style. Requires a 'document' object. ```python document.add_paragraph('Lorem ipsum dolor sit amet.', style='ListBullet') ``` -------------------------------- ### Create and Populate a Table Source: https://github.com/skelmis/python-docx/blob/master/docs/user/quickstart.md Generates a table with a specified number of rows and columns. It also demonstrates how to access individual cells by index and set their text content. ```python table = document.add_table(rows=2, cols=2) cell = table.cell(0, 1) cell.text = 'parrot, possibly dead' row = table.rows[1] row.cells[0].text = 'Foo bar to you.' row.cells[1].text = 'And a hearty foo bar to you too sir!' ``` -------------------------------- ### Add Paragraphs and Runs in python-docx Source: https://github.com/skelmis/python-docx/blob/master/docs/user/quickstart.md Demonstrates how to add paragraphs and subsequent runs to a document. It highlights the importance of explicitly managing spaces between runs. ```python paragraph = document.add_paragraph('Lorem ipsum ') paragraph.add_run('dolor sit amet.') ``` ```python paragraph = document.add_paragraph() paragraph.add_run('Lorem ipsum ') paragraph.add_run('dolor sit amet.') ``` -------------------------------- ### Apply Character Styles in python-docx Source: https://github.com/skelmis/python-docx/blob/master/docs/user/quickstart.md Demonstrates applying a predefined character style to text within a run. It covers both applying the style during run creation and after the run is created. ```python paragraph = document.add_paragraph('Normal text, ') paragraph.add_run('text with emphasis.', 'Emphasis') ``` ```python paragraph = document.add_paragraph('Normal text, ') run = paragraph.add_run('text with emphasis.') run.style = 'Emphasis' ``` -------------------------------- ### Apply Style to Existing Paragraph Source: https://github.com/skelmis/python-docx/blob/master/docs/user/quickstart.md Applies a specified paragraph style to an already created paragraph object. Requires a 'paragraph' object. ```python paragraph = document.add_paragraph('Lorem ipsum dolor sit amet.') paragraph.style = 'List Bullet' ``` -------------------------------- ### Add a Page Break Source: https://github.com/skelmis/python-docx/blob/master/docs/user/quickstart.md Inserts a manual page break at the current position in the document, forcing subsequent content to start on a new page. Useful for controlling document layout. ```python document.add_page_break() ``` -------------------------------- ### Apply Bold and Italic Formatting in python-docx Source: https://github.com/skelmis/python-docx/blob/master/docs/user/quickstart.md Shows how to set the bold and italic properties for a run within a paragraph. It illustrates direct application and applying to the result of add_run(). ```python paragraph = document.add_paragraph('Lorem ipsum ') run = paragraph.add_run('dolor') run.bold = True paragraph.add_run(' sit amet.') ``` ```python paragraph.add_run('dolor').bold = True ``` ```python paragraph = document.add_paragraph() paragraph.add_run('Lorem ipsum ') paragraph.add_run('dolor').bold = True paragraph.add_run(' sit amet.') ``` -------------------------------- ### Iterate Through Table Cells Source: https://github.com/skelmis/python-docx/blob/master/docs/user/quickstart.md Provides methods to iterate through all rows and cells within a table, allowing for programmatic access and manipulation of table content. It also shows how to get the count of rows and columns. ```python for row in table.rows: for cell in row.cells: print(cell.text) row_count = len(table.rows) col_count = len(table.columns) ``` -------------------------------- ### Configure Document Sections and Page Setup in Python DOCX Source: https://context7.com/skelmis/python-docx/llms.txt Illustrates how to create and configure different document sections, including setting page dimensions, margins, and orientation (portrait, landscape). It covers adding new pages, continuous sections, and sections that start on even pages. Requires the 'python-docx' library. ```python from skelmis.docx import Document from skelmis.docx.enum.section import WD_SECTION, WD_ORIENTATION from skelmis.docx.shared import Inches doc = Document() # Configure first section (portrait) section = doc.sections[0] section.page_width = Inches(8.5) section.page_height = Inches(11) section.left_margin = Inches(1) section.right_margin = Inches(1) section.top_margin = Inches(1) section.bottom_margin = Inches(1) doc.add_heading('Portrait Section', level=1) doc.add_paragraph('This content is in portrait orientation.') # Add landscape section new_section = doc.add_section(WD_SECTION.NEW_PAGE) new_section.orientation = WD_ORIENTATION.LANDSCAPE new_section.page_width = Inches(11) new_section.page_height = Inches(8.5) doc.add_heading('Landscape Section', level=1) doc.add_paragraph('This content is in landscape orientation, useful for wide tables or charts.') # Add continuous section (no page break) doc.add_section(WD_SECTION.CONTINUOUS) doc.add_heading('Continuous Section', level=1) doc.add_paragraph('This section starts without a page break.') # Add even page section doc.add_section(WD_SECTION.EVEN_PAGE) doc.add_heading('Even Page Section', level=1) doc.add_paragraph('This section starts on the next even page.') # Access section properties for idx, section in enumerate(doc.sections): print(f"Section {idx}: {section.page_width} x {section.page_height}") doc.save('sections_document.docx') ``` -------------------------------- ### Install python-docx using pip Source: https://github.com/skelmis/python-docx/blob/master/README.md This command installs the skelmis-docx package using pip. Ensure you have pip installed and configured in your system's PATH. ```bash pip install skelmis-docx ``` -------------------------------- ### Apply Table Style Source: https://github.com/skelmis/python-docx/blob/master/docs/user/quickstart.md Applies a pre-defined style to a Word table. The style name is derived from the Word UI by removing spaces. Requires a 'table' object. ```python table.style = 'LightShading-Accent1' ``` -------------------------------- ### Populate Table Header and Data Rows Source: https://github.com/skelmis/python-docx/blob/master/docs/user/quickstart.md Populates the header row of a table with specified headings and then adds data rows for each item, assigning values to corresponding cells. Assumes a 'table' object and an 'items' list are available. ```python # populate header row -------- heading_cells = table.rows[0].cells heading_cells[0].text = 'Qty' heading_cells[1].text = 'SKU' heading_cells[2].text = 'Description' # add a data row for each item for item in items: cells = table.add_row().cells cells[0].text = str(item.qty) cells[1].text = item.sku cells[2].text = item.desc ``` -------------------------------- ### Create and Save a Word Document Source: https://github.com/skelmis/python-docx/blob/master/README.md Demonstrates how to create a new Word document, add a paragraph, and save it. This requires the skelmis-docx library to be installed. ```python from skelmis.docx import Document document = Document() document.add_paragraph("It was a dark and stormy night.") document.save("dark-and-stormy.docx") ``` -------------------------------- ### Insert a Paragraph Before an Existing One Source: https://github.com/skelmis/python-docx/blob/master/docs/user/quickstart.md Inserts a new paragraph with specified text immediately preceding a given paragraph in the document. This is useful for modifying existing document structures. ```python prior_paragraph = paragraph.insert_paragraph_before('Lorem ipsum') ``` -------------------------------- ### Add Picture with Specified Width Source: https://github.com/skelmis/python-docx/blob/master/docs/user/quickstart.md Inserts an image into the Word document and sets its width to a specific value, preserving aspect ratio. Requires 'Inches' or 'Cm' from 'docx.shared' and a 'document' object. ```python from skelmis.docx.shared import Inches document.add_picture('image-filename.png', width=Inches(1.0)) ``` -------------------------------- ### Add External Hyperlink Source: https://github.com/skelmis/python-docx/blob/master/docs/dev/analysis/features/text/hyperlink.md Provides an example of how to add a new external hyperlink to a paragraph. It demonstrates setting the address and text, and then verifies the created hyperlink's properties. ```python >>> hyperlink = paragraph.add_external_hyperlink( ... 'https://example.com', 'About' ... ) >>> hyperlink >>> hyperlink.text 'About' >>> hyperlink.address 'http://example.com' >>> hyperlink.url 'https://example.com' ``` -------------------------------- ### Create and Save a Word Document Source: https://context7.com/skelmis/python-docx/llms.txt Demonstrates basic document creation, adding headings and paragraphs, and saving the document to a .docx file. It also includes an example of converting the document to PDF using an external tool. ```python from skelmis.docx import Document from pathlib import Path # Create a document doc = Document() doc.add_heading('Report Title', level=0) doc.add_paragraph('This is the content of the report.') doc.add_heading('Section 1', level=1) doc.add_paragraph('Section content here.') # Save document docx_path = 'report.docx' doc.save(docx_path) # Convert to PDF (works on Linux with LibreOffice, Windows with Word, macOS with Word) try: document_to_pdf(docx_path) print('PDF created successfully as report.pdf') except Exception as e: print(f'PDF conversion failed: {e}') # Using Path object docx_file = Path('another_report.docx') doc.save(docx_file) # Creates another_report.docx document_to_pdf(docx_file) # Creates another_report.pdf ``` -------------------------------- ### Add a Heading to a Document Source: https://github.com/skelmis/python-docx/blob/master/docs/user/quickstart.md Adds a heading to the Word document. By default, it creates a top-level 'Heading 1'. You can specify a level from 1 to 9 for subheadings, or 0 for a 'Title' style paragraph. ```python document.add_heading('The REAL meaning of the universe') document.add_heading('The role of dolphins', level=2) ``` -------------------------------- ### Create and Save a New Document Source: https://github.com/skelmis/python-docx/blob/master/docs/user/documents.md This snippet demonstrates how to create a new, blank Word document using the default template and save it to a specified file. It's the simplest way to start with python-docx. ```python from skelmis.docx import Document document = Document() document.save('test.docx') ``` -------------------------------- ### Specimen XML for Paragraph Indentation Source: https://github.com/skelmis/python-docx/blob/master/docs/dev/analysis/features/text/paragraph-format.md Provides example XML structures for common paragraph indentation settings. These examples show how left, right, and first line or hanging indents are represented within the WordprocessingML (w:ind) element. ```xml ``` -------------------------------- ### XML Example of Word Styles Source: https://github.com/skelmis/python-docx/blob/master/docs/dev/analysis/features/styles/style.md This snippet showcases the XML structure for defining various styles in a Word document. It includes examples for 'Normal' paragraph, 'Default Paragraph Font' character, 'Normal Table' table, 'No List' numbering, and a custom 'Foobar' paragraph style. These definitions are crucial for programmatically controlling document formatting. ```xml ``` -------------------------------- ### XML Specimen: Baseline Run Source: https://github.com/skelmis/python-docx/blob/master/docs/dev/analysis/features/text/font-highlight-color.md A basic example of a WordprocessingML run element without any special formatting, such as highlighting. This serves as a baseline for comparison with formatted runs. ```xml Black text on white background ``` -------------------------------- ### Create and Format Tables in Python Source: https://context7.com/skelmis/python-docx/llms.txt Provides examples for creating tables in DOCX documents, populating them with data, and applying styles. It demonstrates how to add headers, data rows, and set basic formatting like bold text. Uses skelmis.docx Document and shared utilities. ```python from skelmis.docx import Document from skelmis.docx.shared import Inches, RGBColor from skelmis.docx.enum.table import WD_CELL_VERTICAL_ALIGNMENT, WD_TABLE_ALIGNMENT doc = Document() # Create basic table table = doc.add_table(rows=3, cols=3) # Populate table headers = ['Name', 'Age', 'City'] for idx, header in enumerate(headers): cell = table.rows[0].cells[idx] cell.text = header # Make header bold cell.paragraphs[0].runs[0].bold = True # Add data rows data = [ ['Alice', '30', 'New York'], ['Bob', '25', 'Los Angeles'] ] for row_idx, row_data in enumerate(data, start=1): for col_idx, value in enumerate(row_data): table.rows[row_idx].cells[col_idx].text = value # Apply table style table.style = 'Light Grid Accent 1' ``` -------------------------------- ### Add Picture to Document Source: https://github.com/skelmis/python-docx/blob/master/docs/user/quickstart.md Inserts an image into the Word document. It can load the image from a local file path or a file-like object. Requires a 'document' object. ```python document.add_picture('image-filename.png') ``` -------------------------------- ### Python: Create Footer using MS API Source: https://github.com/skelmis/python-docx/blob/master/docs/dev/analysis/features/header.md Demonstrates how to create a default footer for a document section using the MS API. It accesses the HeadersFooters collection of a section and sets the text for the default footer. ```python section = Document.Sections(1) footers = section.Footers # a HeadersFooters collection object default_footer = footers(wdHeaderFooterPrimary) default_footer.Range.Text = "Footer text" ``` -------------------------------- ### Add a Row to an Existing Table Source: https://github.com/skelmis/python-docx/blob/master/docs/user/quickstart.md Appends a new row to the end of an existing table. This is particularly useful when populating tables dynamically from data sources of variable length. ```python row = table.add_row() ``` -------------------------------- ### Run Methods and Properties Source: https://github.com/skelmis/python-docx/blob/master/docs/api/text.md Details on the `Run` object, including its methods like `insert_run` and `add_break`, and properties like `runs` and `text`. ```APIDOC ## Run Methods and Properties ### `insert_run(text: str | None = None, style: str | CharacterStyle | None = None) -> Run` - **Description**: Appends a new run containing the specified text and character style to the current run. - **Parameters**: - `text` (str | None): The text content for the new run. Can include tabs (`\t`), newlines (`\n`), or carriage returns (`\r`). If None, an empty run is created. - `style` (str | CharacterStyle | None): The character style to apply to the new run. - **Returns**: The newly created `Run` object. ### `add_break(break_type: WD_BREAK_TYPE = WD_BREAK_TYPE.LINE)` - **Description**: Adds a break element to the run. - **Parameters**: - `break_type` (WD_BREAK_TYPE): The type of break to add. Defaults to `WD_BREAK_TYPE.LINE`. Can be `WD_BREAK_TYPE.LINE`, `WD_BREAK_TYPE.PAGE`, or `WD_BREAK_TYPE.COLUMN`. ### `runs` (Property of Hyperlink, accessed via a Run context) - **Type**: list[Run] - **Description**: List of `Run` instances in this hyperlink. ### `text` (Property of Hyperlink, accessed via a Run context) - **Type**: str - **Description**: String formed by concatenating the text of each run in the hyperlink. ``` -------------------------------- ### Add a Paragraph to a Document Source: https://github.com/skelmis/python-docx/blob/master/docs/user/quickstart.md Appends a new paragraph containing specified text to the end of the Word document. The method returns a reference to the newly created paragraph object. ```python paragraph = document.add_paragraph('Lorem ipsum dolor sit amet.') ``` -------------------------------- ### Create, Load, and Save Word Documents with skelmis-docx Source: https://context7.com/skelmis/python-docx/llms.txt Demonstrates basic document operations including creating new documents, loading existing ones from file paths or file-like objects, accessing core properties, and saving documents to files or byte streams. Requires the 'skelmis-docx' library. ```python from skelmis.docx import Document from pathlib import Path # Create a new blank document doc = Document() # Load an existing document doc = Document('existing_document.docx') doc = Document(Path('/path/to/document.docx')) # Load from file-like object with open('document.docx', 'rb') as f: doc = Document(f) # Access document properties print(doc.core_properties.title) print(doc.core_properties.author) doc.core_properties.title = "Annual Report 2024" doc.core_properties.author = "John Doe" # Save document doc.save('output.docx') doc.save(Path('output.docx')) # Save to file-like object from io import BytesIO buffer = BytesIO() doc.save(buffer) ``` -------------------------------- ### Document Constructor Source: https://github.com/skelmis/python-docx/blob/master/docs/api/document.md Constructs a Document object, loading content from a specified .docx file path or a file-like object. If no source is provided, it loads a default template. ```APIDOC ## Document Constructor ### Description Initializes a new Document object. The `docx` argument can be a file path (string), a file-like object, or None to load the default template. ### Method `__init__` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body * **docx** (str | IO[bytes] | None) - Optional. Path to a .docx file or a file-like object. Defaults to None, loading the default template. ### Request Example ```python from docx import Document doc = Document('my_document.docx') # or doc = Document() ``` ### Response #### Success Response (200) Returns a `DocumentObject` representing the loaded or newly created document. #### Response Example ```json { "message": "Document object created successfully" } ``` ``` -------------------------------- ### Set Font Size using Pt in python-docx Source: https://github.com/skelmis/python-docx/blob/master/docs/api/text.md Demonstrates how to set the font size for a run using the `Pt` class from `docx.shared`. This allows specifying font size in points, which is then converted to EMU. The effective value is inherited if not explicitly set. ```python from docx.shared import Pt # Assuming 'font' is a Font object font.size = Pt(24) print(font.size) print(font.size.pt) ``` -------------------------------- ### XML Example of CT_Body in WordprocessingML Source: https://github.com/skelmis/python-docx/blob/master/docs/dev/analysis/schema/ct_body.md This snippet demonstrates the structure of the CT_Body element within a WordprocessingML document, showing how it encloses block-level markup like paragraphs. It's a fundamental example for understanding document structure. ```xml ``` -------------------------------- ### Python-docx Run Property Protocol Example Source: https://github.com/skelmis/python-docx/blob/master/docs/dev/analysis/features/text/font.md Demonstrates the read/write protocol for boolean run properties in python-docx. It shows how to set and query 'bold' property through its three states: None, True, and False. This protocol applies to other boolean run properties as well. ```python >>> run = p.add_run() >>> run.bold None >>> run.bold = True >>> run.bold True >>> run.bold = False >>> run.bold False >>> run.bold = None >>> run.bold None ``` -------------------------------- ### Run Object Class Source: https://github.com/skelmis/python-docx/blob/master/docs/api/text.md Information about the `Run` class, which acts as a proxy for the Word '' element. ```APIDOC ## Run Object Class ### `class skelmis.docx.text.run.Run` - **Description**: Proxy object wrapping the `` element in Word documents. Properties on `Run` can accept `True`, `False`, or `None`. `None` indicates the property's value is inherited from the style hierarchy. ``` -------------------------------- ### Accessing Section Headers in python-docx Source: https://github.com/skelmis/python-docx/blob/master/docs/dev/analysis/features/header.md Demonstrates how to get the header object for a section. The header object inherits content editing capabilities from `BlockItemContainer`. ```python >>> header = section.header >>> header ``` -------------------------------- ### Implement Numbered Lists with skelmis-docx Source: https://context7.com/skelmis/python-docx/llms.txt Illustrates how to create single and multi-level numbered lists, including restarting numbering for new lists. Requires 'skelmis-docx' and its style configuration method 'configure_styles_for_numbered_lists()'. ```python from skelmis.docx import Document doc = Document() # Configure document for multiple numbered lists doc.configure_styles_for_numbered_lists() # First numbered list doc.add_heading('Project Tasks', level=1) p1 = doc.add_paragraph('Design phase', style='List Number') p2 = doc.add_paragraph('Development phase', style='List Number') p3 = doc.add_paragraph('Testing phase', style='List Number') # Restart numbering for second list doc.add_heading('Quality Checks', level=1) p4 = doc.add_paragraph('Code review', style='List Number') p4.restart_numbering() # Restarts from 1 p5 = doc.add_paragraph('Security audit', style='List Number') p6 = doc.add_paragraph('Performance testing', style='List Number') # Multi-level numbered list p7 = doc.add_paragraph('Main item 1', style='List Number') p8 = doc.add_paragraph('Sub-item 1.1', style='List Number 2') p9 = doc.add_paragraph('Sub-item 1.2', style='List Number 2') p10 = doc.add_paragraph('Main item 2', style='List Number') doc.save('numbered_lists.docx') ``` -------------------------------- ### Define Section Type (XSD) Source: https://github.com/skelmis/python-docx/blob/master/docs/dev/analysis/features/sections.md Defines the complex type CT_SectType for section type, using the ST_SectionMark simple type for its 'val' attribute. This controls how a new section starts. ```xml ``` -------------------------------- ### Get and Set Style Hidden Property Source: https://github.com/skelmis/python-docx/blob/master/docs/dev/analysis/features/styles/style.md Illustrates how to check if a style is hidden and how to set its hidden status. The 'hidden' attribute's behavior can be inconsistent, especially with built-in styles. ```python >>> style = document.styles['Foo'] >>> style.hidden False >>> style.hidden = True >>> style.hidden True ``` -------------------------------- ### XML Structure for Distinct First, Even, and Odd Page Headers Source: https://github.com/skelmis/python-docx/blob/master/docs/dev/analysis/features/header.md Specimen XML showcasing the most complex header configuration: distinct first, even, and odd page headers. This involves references for default, first, and even headers, along with the title page marker. ```xml ... ``` -------------------------------- ### Modifying Section Start Type in Python Source: https://github.com/skelmis/python-docx/blob/master/docs/user/sections.md Shows how to change the `start_type` property of a `Section` object to control how the section break is rendered in the document, using values from the `WD_SECTION_START` enumeration. ```python from docx import Document from docx.enum.section import WD_SECTION document = Document() section = document.sections[0] # Assuming at least one section exists print(f"Original start type: {section.start_type}") # Change start type to ODD_PAGE section.start_type = WD_SECTION.ODD_PAGE print(f"Modified start type: {section.start_type}") ``` -------------------------------- ### XML Structure for Odd and Even Page Headers Source: https://github.com/skelmis/python-docx/blob/master/docs/dev/analysis/features/header.md Specimen XML illustrating the configuration for different odd and even page headers. This includes a default header reference and an even header reference (``). ```xml ... ``` -------------------------------- ### Delete a Style in python-docx Source: https://github.com/skelmis/python-docx/blob/master/docs/dev/analysis/features/styles/style.md Demonstrates the process of removing a style from a document using the delete() method in python-docx. The example shows the change in the number of styles before and after deletion and verifies that the style is no longer accessible. ```python >>> len(styles) 6 >>> style.delete() >>> len(styles) 5 >>> styles['Citation'] KeyError: no style with id or name 'Citation' ``` -------------------------------- ### Add Internal Hyperlink Source: https://github.com/skelmis/python-docx/blob/master/docs/dev/analysis/features/text/hyperlink.md Shows how to create an internal hyperlink that links to a bookmark within the document. It sets the bookmark ID and the display text, then verifies the hyperlink's text and fragment. ```python >>> hyperlink = paragraph.add_internal_hyperlink('bookmark_id', 'Display text') >>> hyperlink.text 'Display text' >>> hyperlink.fragment 'bookmark_id' ``` -------------------------------- ### Access Hyperlinks in Document Order with Runs Source: https://github.com/skelmis/python-docx/blob/master/docs/dev/analysis/features/text/hyperlink.md Shows how to iterate through the content of a paragraph in document order, distinguishing between runs of text and hyperlink objects. This provides a more granular view of paragraph content. ```python >>> list(paragraph.iter_inner_content()) [ ] ``` -------------------------------- ### Adding a New Section in Python Source: https://github.com/skelmis/python-docx/blob/master/docs/user/sections.md Illustrates how to add a new section to the end of a Word document using the `Document.add_section()` method. It shows how to specify the section's start type, such as `WD_SECTION.ODD_PAGE`. ```python from docx import Document from docx.enum.section import WD_SECTION document = Document() # Get the last section to check its properties before adding a new one current_section = document.sections[-1] print(f"Current section start type: {current_section.start_type}") # Add a new section with ODD_PAGE start type new_section = document.add_section(WD_SECTION.ODD_PAGE) print(f"New section start type: {new_section.start_type}") ``` -------------------------------- ### Accessing Document Sections in Python Source: https://github.com/skelmis/python-docx/blob/master/docs/user/sections.md Demonstrates how to access the collection of sections in a Word document using the `sections` property of the `Document` object. It shows how to iterate through sections and inspect their start types. ```python from docx import Document document = Document() sections = document.sections print(f"Number of sections: {len(sections)}") for section in sections: print(f"Section start type: {section.start_type}") ```