### Complete Page Setup Example Source: https://github.com/eiceblue/spire.doc-for-python/blob/main/_autodocs/08-page-setup-and-sections.md A comprehensive example demonstrating the setup of multiple sections with different page sizes, orientations, margins, and column layouts. Saves the document as a DOCX file. ```python from spire.doc import Document from spire.doc.common import ( FileFormat, Orientation, TextDirection ) document = Document() # Section 1: Standard letter with narrow margins section1 = document.AddSection() section1.PageSetup.PageWidth = 612 # 8.5 inches section1.PageSetup.PageHeight = 792 # 11 inches section1.PageSetup.Orientation = Orientation.Portrait # Set 0.5-inch margins margins1 = section1.PageSetup.Margins margins1.Top = 36 margins1.Bottom = 36 margins1.Left = 36 margins1.Right = 36 section1.AddParagraph().AppendText("Section 1: Standard Letter") # Section 2: Landscape with wide margins section2 = document.AddSection() section2.PageSetup.PageWidth = 792 # 11 inches section2.PageSetup.PageHeight = 612 # 8.5 inches section2.PageSetup.Orientation = Orientation.Landscape # Set 1.5-inch margins margins2 = section2.PageSetup.Margins margins2.Top = 108 margins2.Bottom = 108 margins2.Left = 108 margins2.Right = 108 section2.AddParagraph().AppendText("Section 2: Landscape") # Section 3: Multi-column section3 = document.AddSection() section3.PageSetup.PageWidth = 612 section3.PageSetup.PageHeight = 792 # Two columns with line separator section3.PageSetup.AddColumn(150, 30) section3.PageSetup.ColumnsLineBetween = True # Add multi-column content content = section3.AddParagraph() content.AppendText("This content will flow across two columns with a dividing line...") document.SaveToFile("page_setup.docx", FileFormat.Docx) document.Close() ``` -------------------------------- ### Install Spire.Doc for Python Source: https://github.com/eiceblue/spire.doc-for-python/blob/main/_autodocs/00-index.md Installs the Spire.Doc for Python library using pip. ```bash pip install spire.doc ``` -------------------------------- ### Example: Get Document Statistics Source: https://github.com/eiceblue/spire.doc-for-python/blob/main/_autodocs/11-document-properties-and-metadata.md Demonstrates loading a document and retrieving its character, word, and page counts. Ensure the 'spire.doc' module is imported. ```python from spire.doc import Document document = Document() document.LoadFromFile("report.docx") # Get document statistics char_count = document.BuiltinDocumentProperties.CharCount char_with_space = document.BuiltinDocumentProperties.CharCountWithSpace word_count = document.BuiltinDocumentProperties.WordCount print(f"Characters: {char_count}") print(f"Characters (with spaces): {char_with_space}") print(f"Words: {word_count}") ``` -------------------------------- ### Basic Document Setup for Hyperlinks Source: https://github.com/eiceblue/spire.doc-for-python/blob/main/_autodocs/12-bookmarks-and-hyperlinks.md Initializes a new document and adds a section, serving as a basic structure for adding content, including hyperlinks. ```python from spire.doc import Document from spire.doc.common import FileFormat, Color, UnderlineStyle document = Document() section = document.AddSection() # Title title = section.AddParagraph() title.AppendText("Resources and References") title.ApplyStyle("Heading 1") ``` -------------------------------- ### Example: Accessing Owning Paragraph and its Properties Source: https://github.com/eiceblue/spire.doc-for-python/blob/main/_autodocs/06-textrange-and-character-format.md Demonstrates how to load a document, access a specific text range, and then use its OwnerParagraph property to get information about the containing paragraph. ```python from spire.doc import Document document = Document() document.LoadFromFile("input.docx") section = document.Sections[0] para = section.Paragraphs[0] text_range = para.ChildObjects[0] # Get first text range # Access the owning paragraph owner = text_range.OwnerParagraph print(f"Text range belongs to paragraph with {owner.ChildObjects.Count} objects") ``` -------------------------------- ### Example: Set and Use Document Title Source: https://github.com/eiceblue/spire.doc-for-python/blob/main/_autodocs/11-document-properties-and-metadata.md Demonstrates setting the document title and initializing a document object. Ensure the 'spire.doc' module is imported. ```python from spire.doc import Document document = Document() document.BuiltinDocumentProperties.Title = "Technical Report 2024" ``` -------------------------------- ### Example: Setting Font Size Source: https://github.com/eiceblue/spire.doc-for-python/blob/main/_autodocs/06-textrange-and-character-format.md Appends text to a paragraph and sets different font sizes for distinct text segments. ```python heading = para.AppendText("Large Text") heading.CharacterFormat.FontSize = 18 body = para.AppendText("Normal text") body.CharacterFormat.FontSize = 11 ``` -------------------------------- ### Document() Constructor Source: https://github.com/eiceblue/spire.doc-for-python/blob/main/_autodocs/01-document-class.md Creates a new, empty Word document instance. This is the starting point for creating documents programmatically. ```APIDOC ## Document() ### Description Creates a new empty Word document. ### Method Constructor ### Parameters None ### Returns `Document` instance ### Example ```python from spire.doc import Document document = Document() ``` ``` -------------------------------- ### Example: Applying Character Formatting Source: https://github.com/eiceblue/spire.doc-for-python/blob/main/_autodocs/06-textrange-and-character-format.md Creates a document, adds a paragraph, and applies different character formatting (bold, size, color) to distinct text segments. ```python from spire.doc import Document from spire.doc.common import Color document = Document() section = document.AddSection() para = section.AddParagraph() # Create formatted text title = para.AppendText("Important Notice") title.CharacterFormat.Bold = True title.CharacterFormat.FontSize = 16 title.CharacterFormat.TextColor = Color.get_Red() # Create normal text body = para.AppendText(" - Please read carefully") body.CharacterFormat.FontSize = 12 ``` -------------------------------- ### Configure Page Margins and Size Source: https://github.com/eiceblue/spire.doc-for-python/blob/main/_autodocs/13-quick-start-guide.md Set the page orientation for a document section to landscape. This demonstrates basic page setup configuration. ```python from spire.doc import Document from spire.doc.common import FileFormat, Orientation document = Document() section = document.AddSection() # Set page orientation section.PageSetup.Orientation = Orientation.Landscape ``` -------------------------------- ### Insert and Highlight New Text Source: https://github.com/eiceblue/spire.doc-for-python/blob/main/Python Examples/doc_python.md This example shows how to find all occurrences of a specific string, insert new text after each occurrence, and then highlight the newly inserted text. ```python #Find all the text string "Word" from the sample document selections = doc.FindAllString("Word", True, True) index = 0 #Defines text range trange = TextRange(doc) #Insert new text string (New) after the searched text string for selection in selections: trange = selection.GetAsOneRange() newrange = TextRange(doc) newrange.Text = ("(New text)") index = trange.OwnerParagraph.ChildObjects.IndexOf(trange) trange.OwnerParagraph.ChildObjects.Insert(index + 1, newrange) #Find and highlight the newly added text string New text = doc.FindAllString("New text", True, True) for seletion in text: seletion.GetAsOneRange().CharacterFormat.HighlightColor = Color.get_Yellow() ``` -------------------------------- ### Example: Setting Underline Styles Source: https://github.com/eiceblue/spire.doc-for-python/blob/main/_autodocs/06-textrange-and-character-format.md Applies single and double underline styles to different text ranges within a paragraph. ```python from spire.doc.common import UnderlineStyle tr = para.AppendText("Underlined") tr.CharacterFormat.Underline = UnderlineStyle.Single tr2 = para.AppendText("Double underline") tr2.CharacterFormat.Underline = UnderlineStyle.Double ``` -------------------------------- ### Example: Setting Font Name Source: https://github.com/eiceblue/spire.doc-for-python/blob/main/_autodocs/06-textrange-and-character-format.md Appends text to a paragraph and sets different font names for different text ranges. ```python tr = para.AppendText("Courier text") tr.CharacterFormat.FontName = "Courier New" tr2 = para.AppendText("Arial text") tr2.CharacterFormat.FontName = "Arial" ``` -------------------------------- ### Insert Table into Textbox Source: https://github.com/eiceblue/spire.doc-for-python/blob/main/Python Examples/doc_python.md This example shows how to create a Word document, add a textbox, and then insert a table with data into that textbox. It also demonstrates applying a table style. ```python #Create a new document doc = Document() #Add a section section = doc.AddSection() #Add a paragraph to the section paragraph = section.AddParagraph() #Add a textbox to the paragraph textbox = paragraph.AppendTextBox(300, 100) #Set the position of the textbox textbox.Format.HorizontalOrigin = HorizontalOrigin.Page textbox.Format.HorizontalPosition = 140 textbox.Format.VerticalOrigin = VerticalOrigin.Page textbox.Format.VerticalPosition = 50 #Add text to the textbox textboxParagraph = textbox.Body.AddParagraph() textboxRange = textboxParagraph.AppendText("Table 1") textboxRange.CharacterFormat.FontName = "Arial" #Insert table to the textbox table = textbox.Body.AddTable(True) #Specify the number of rows and columns of the table table.ResetCells(4, 4) data = [["Name", "Age", "Gender", "ID"], ["John", "28", "Male", "0023"], ["Steve", "30", "Male", "0024"], ["Lucy", "26", "female", "0025"]] #Add data to the table for i in range(0, 4): for j in range(0, 4): tableRange = table.Rows[i].Cells[j].AddParagraph().AppendText(data[i][j]) tableRange.CharacterFormat.FontName = "Arial" #Apply style to the table table.ApplyStyle(DefaultTableStyle.TableColorful2) ``` -------------------------------- ### Replace Bookmark Content Source: https://github.com/eiceblue/spire.doc-for-python/blob/main/Python Examples/doc_python.md This example demonstrates how to replace the content of a bookmark. It uses the BookmarksNavigator to locate the bookmark and then replaces its content with new text. ```python #Locate the bookmark. bookmarkNavigator = BookmarksNavigator(doc) bookmarkNavigator.MoveToBookmark("Test") #Replace the context with new. bookmarkNavigator.ReplaceBookmarkContent("This is replaced content.", False) ``` -------------------------------- ### Create a New Empty Document Source: https://github.com/eiceblue/spire.doc-for-python/blob/main/_autodocs/01-document-class.md Instantiate the Document class to create a new, blank Word document. This is the starting point for building documents programmatically. ```python from spire.doc import Document document = Document() ``` -------------------------------- ### Example: Setting Bold Formatting Source: https://github.com/eiceblue/spire.doc-for-python/blob/main/_autodocs/06-textrange-and-character-format.md Appends text to a paragraph and applies bold formatting to one text range while ensuring another remains regular. ```python tr = para.AppendText("Bold text") tr.CharacterFormat.Bold = True tr2 = para.AppendText(" Regular text") tr2.CharacterFormat.Bold = False ``` -------------------------------- ### Load Text with Specific Encoding Source: https://github.com/eiceblue/spire.doc-for-python/blob/main/Python Examples/doc_python.md This example shows how to create a Word document and load text from a file using a specific encoding, in this case, UTF-7. ```python #Create word document document = Document() #Load the text file document.LoadText(inputFile, Encoding.get_UTF7()) ``` -------------------------------- ### Complete Table Creation and Formatting Example Source: https://github.com/eiceblue/spire.doc-for-python/blob/main/_autodocs/04-table-class.md Demonstrates the creation of a table with specified rows and columns, populating it with header and data, and applying formatting including bold text, background colors, alignment, and row height settings. ```python from spire.doc import Document from spire.doc.common import ( FileFormat, Color, VerticalAlignment, HorizontalAlignment, TableRowHeightType ) document = Document() section = document.AddSection() # Create table table = section.AddTable(True) table.ResetCells(4, 3) # Header data headers = ["Product", "Price", "Quantity"] # Table data data = [ ["Widget A", "$10.00", "5"], ["Widget B", "$15.00", "3"], ["Widget C", "$20.00", "2"], ] # Format and populate header row header_row = table.Rows[0] header_row.IsHeader = True header_row.Height = 20 header_row.HeightType = TableRowHeightType.Exactly for i, header in enumerate(headers): cell = header_row.Cells[i] cell.CellFormat.Shading.BackgroundPatternColor = Color.get_Gray() cell.CellFormat.VerticalAlignment = VerticalAlignment.Middle para = cell.AddParagraph() para.Format.HorizontalAlignment = HorizontalAlignment.Center tr = para.AppendText(header) tr.CharacterFormat.Bold = True # Populate data rows (example snippet truncated for brevity, actual code would continue here) ``` -------------------------------- ### Initialize and Style a Document in Python Source: https://github.com/eiceblue/spire.doc-for-python/blob/main/Python Examples/doc_python.md Demonstrates initializing a new document, adding sections, and defining custom styles for titles and normal text, including character and paragraph formatting. ```python # Initialize a document document = Document() document.AddSection() #Add default title style to document and modify titleStyle = document.AddStyle(BuiltinStyle.Title) titleStyle.CharacterFormat.FontName= "cambria" titleStyle.CharacterFormat.FontSize = 28 titleStyle.CharacterFormat.TextColor = Color.FromArgb(255,42, 123, 136) #judge if it is Paragraph Style and then set paragraph format if isinstance(titleStyle, ParagraphStyle): ps = titleStyle if isinstance(titleStyle, ParagraphStyle) else None ps.ParagraphFormat.Borders.Bottom.BorderType = BorderStyle.Single ps.ParagraphFormat.Borders.Bottom.Color = Color.FromArgb(255,42, 123, 136) ps.ParagraphFormat.Borders.Bottom.LineWidth = 1.5 ps.ParagraphFormat.HorizontalAlignment = HorizontalAlignment.Left #Add default normal style and modify normalStyle = document.AddStyle(BuiltinStyle.Normal) normalStyle.CharacterFormat.FontName = "cambria" normalStyle.CharacterFormat.FontSize = 11 #Add default heading1 style heading1Style = document.AddStyle(BuiltinStyle.Heading1) heading1Style.CharacterFormat.FontName = "cambria" heading1Style.CharacterFormat.FontSize = 14 heading1Style.CharacterFormat.Bold = True heading1Style.CharacterFormat.TextColor = Color.FromArgb(255,42, 123, 136) #Add default heading2 style heading2Style = document.AddStyle(BuiltinStyle.Heading2) heading2Style.CharacterFormat.FontName = "cambria" heading2Style.CharacterFormat.FontSize = 12 heading2Style.CharacterFormat.Bold = True #List style bulletList = document.Styles.Add(ListType.Bulleted, "bulletList") ``` -------------------------------- ### Create Form Fields in Python Source: https://github.com/eiceblue/spire.doc-for-python/blob/main/Python Examples/doc_python.md Demonstrates the initial setup for creating different types of form fields within a Word document by adding a table structure to hold them. ```python # Add table for form fields table = section.AddTable() table.DefaultColumnsNumber = 2 table.DefaultRowHeight = 20 # Create a row for field group label row = table.AddRow(False) row.Cells[0].CellFormat.Shading.BackgroundPatternColor = Color.FromArgb(0xFF, 0x00, 0x71, 0xb6) row.Cells[0].CellFormat.VerticalAlignment = VerticalAlignment.Middle ``` -------------------------------- ### Create Professional Document with Formatting and Table Source: https://github.com/eiceblue/spire.doc-for-python/blob/main/_autodocs/13-quick-start-guide.md A comprehensive example demonstrating the creation of a professional document, including setting margins, document properties, applying styles, adding text, creating a table with data, and inserting a footer hyperlink. It also shows saving the document as DOCX and converting it to PDF. ```python from spire.doc import Document, ParagraphStyle from spire.doc.common import ( FileFormat, HorizontalAlignment, Color, UnderlineStyle ) # Create document document = Document() section = document.AddSection() # Set margins margins = section.PageSetup.Margins margins.Top = 72 margins.Bottom = 72 margins.Left = 72 margins.Right = 72 # Set document properties document.BuiltinDocumentProperties.Title = "Professional Report" document.BuiltinDocumentProperties.Author = "Report Author" document.BuiltinDocumentProperties.Company = "ABC Corporation" # Add title title = section.AddParagraph() title.AppendText("Quarterly Report Q1 2024") title.ApplyStyle("Heading 1") title.Format.HorizontalAlignment = HorizontalAlignment.Center # Add date date_para = section.AddParagraph() date_para.AppendText("January 1 - March 31, 2024") date_para.Format.HorizontalAlignment = HorizontalAlignment.Center date_para.Format.AfterSpacing = 12 # Add sections for section_name in ["Executive Summary", "Key Metrics", "Recommendations"]: heading = section.AddParagraph() heading.AppendText(section_name) heading.ApplyStyle("Heading 2") content = section.AddParagraph() content.AppendText(f"Content for {section_name}...") content.Format.BeforeSpacing = 6 content.Format.AfterSpacing = 6 # Add table with data table = section.AddTable(True) table.ResetCells(3, 3) headers = ["Metric", "Q1 2023", "Q1 2024"] data = [ ["Revenue", "$1.2M", "$1.5M"], ["Growth", "5%", "25%"] ] # Fill table for i, header in enumerate(headers): table.Rows[0].Cells[i].AddParagraph().AppendText(header) for row_idx, row_data in enumerate(data): for col_idx, value in enumerate(row_data): table.Rows[row_idx + 1].Cells[col_idx].AddParagraph().AppendText(value) # Add footer with link footer_para = section.AddParagraph() footer_para.AppendText("For more information, visit ") link = footer_para.AppendHyperlink("https://example.com", "our website", False) link.CharacterFormat.TextColor = Color.get_Blue() # Save document document.SaveToFile("professional_report.docx", FileFormat.Docx) document.Close() # Also convert to PDF document2 = Document() document2.LoadFromFile("professional_report.docx") document2.SaveToFile("professional_report.pdf", FileFormat.PDF) document2.Close() print("Professional report created successfully!") ``` -------------------------------- ### Get Form Fields Collection Source: https://github.com/eiceblue/spire.doc-for-python/blob/main/Python Examples/doc_python.md Access the collection of form fields within a document's section body and get the count. ```python # Get the first section section = document.Sections[0] # Get form fields from the section body formFields = section.Body.FormFields # Get the count of form fields formFields.Count ``` -------------------------------- ### Remove Content Between Bookmark Start and End Source: https://github.com/eiceblue/spire.doc-for-python/blob/main/Python Examples/doc_python.md This snippet removes the content within a specified bookmark. It identifies the bookmark by name and then iterates through the paragraph's child objects to remove elements between the bookmark's start and end markers. ```python #Get the bookmark by name. bookmark = document.Bookmarks["Test"] para = bookmark.BookmarkStart.Owner if isinstance(bookmark.BookmarkStart.Owner, Paragraph) else None startIndex = para.ChildObjects.IndexOf(bookmark.BookmarkStart) para = bookmark.BookmarkEnd.Owner if isinstance(bookmark.BookmarkEnd.Owner, Paragraph) else None endIndex = para.ChildObjects.IndexOf(bookmark.BookmarkEnd) #Remove the content object, and Start from next of BookmarkStart object, end up with previous of BookmarkEnd object. #This method is only to remove the content of the bookmark. for i in range(startIndex + 1, endIndex): para.ChildObjects.RemoveAt(startIndex + 1) ``` -------------------------------- ### Complete Document Metadata Example Source: https://github.com/eiceblue/spire.doc-for-python/blob/main/_autodocs/11-document-properties-and-metadata.md Creates a new document, populates it with content, sets a comprehensive range of built-in and custom properties, saves it, and then reloads it to display the set properties. This is useful for fully characterizing a document with metadata. ```python from spire.doc import Document from spire.doc.common import FileFormat from System import DateTime # Create document with full metadata document = Document() section = document.AddSection() # Add content title = section.AddParagraph() title.AppendText("Annual Technical Report") title.ApplyStyle("Heading 1") body = section.AddParagraph() body.AppendText("This report summarizes technical accomplishments and plans for the year.") # Set built-in properties document.BuiltinDocumentProperties.Title = "Annual Technical Report 2024" document.BuiltinDocumentProperties.Subject = "Year-End Technical Summary" document.BuiltinDocumentProperties.Author = "Engineering Team" document.BuiltinDocumentProperties.Company = "Innovation Corp" document.BuiltinDocumentProperties.Manager = "Department Head" document.BuiltinDocumentProperties.Category = "Annual Report" document.BuiltinDocumentProperties.Keywords = "technical annual report 2024 engineering" document.BuiltinDocumentProperties.Comments = "Official year-end report submitted to management" # Set custom properties document.CustomDocumentProperties.Add("Department", "Engineering") document.CustomDocumentProperties.Add("ReportYear", 2024) document.CustomDocumentProperties.Add("ApprovedByDirector", True) document.CustomDocumentProperties.Add("DistributionList", "exec-team@company.com") document.CustomDocumentProperties.Add("Revision", 1) document.CustomDocumentProperties.Add("ClassificationLevel", "Internal") # Save document document.SaveToFile("annual_report.docx", FileFormat.Docx) document.Close() # Read and display properties document2 = Document() document2.LoadFromFile("annual_report.docx") print("=== Built-in Properties ===") print(f"Title: {document2.BuiltinDocumentProperties.Title}") print(f"Author: {document2.BuiltinDocumentProperties.Author}") print(f"Company: {document2.BuiltinDocumentProperties.Company}") print(f"Category: {document2.BuiltinDocumentProperties.Category}") print(f"Words: {document2.BuiltinDocumentProperties.WordCount}") print(f"Characters: {document2.BuiltinDocumentProperties.CharCount}") print("\n=== Custom Properties ===") print(f"Department: {document2.CustomDocumentProperties['Department']}") print(f"Report Year: {document2.CustomDocumentProperties['ReportYear']}") print(f"Approved: {document2.CustomDocumentProperties['ApprovedByDirector']}") print(f"Revision: {document2.CustomDocumentProperties['Revision']}") document2.Close() ``` -------------------------------- ### Insert Text at Document Start and End Source: https://github.com/eiceblue/spire.doc-for-python/blob/main/Python Examples/doc_python.md Demonstrates inserting text at the beginning and end of a document using DocumentNavigator. Ensure DocumentNavigator and Document are imported. ```python # Create a document navigator to help navigate and modify the document content. navigator = DocumentNavigator(doc) # Move the cursor to the very beginning of the document. navigator.MoveToDocumentStart() # Write a new line of text at the start of the document. navigator.Writeln("Insert the content at the beginning of the document.") # Write another line of text immediately after the previous one at the start. navigator.Writeln("This is new content.") # Move the cursor to the very end of the document. navigator.MoveToDocumentEnd() # Insert a blank line at the end of the document. navigator.Writeln() # Insert a new line of text at the end of the document. navigator.Writeln("Insert the content at the end of the document.") ``` -------------------------------- ### Create a Simple Table Source: https://github.com/eiceblue/spire.doc-for-python/blob/main/_autodocs/13-quick-start-guide.md Create a table with a specified number of rows and columns, populate header and data cells with text, and save the document. This example shows basic table construction. ```python from spire.doc import Document from spire.doc.common import FileFormat, HorizontalAlignment, Color document = Document() section = document.AddSection() # Create table with 3 rows and 2 columns table = section.AddTable(True) table.ResetCells(3, 2) # Header row header_cells = table.Rows[0].Cells header_cells[0].AddParagraph().AppendText("Name") header_cells[1].AddParagraph().AppendText("Age") # Data rows table.Rows[1].Cells[0].AddParagraph().AppendText("John") table.Rows[1].Cells[1].AddParagraph().AppendText("30") table.Rows[2].Cells[0].AddParagraph().AppendText("Jane") table.Rows[2].Cells[1].AddParagraph().AppendText("28") document.SaveToFile("table.docx", FileFormat.Docx) document.Close() ``` -------------------------------- ### Extract Content Starting from Form Field Source: https://github.com/eiceblue/spire.doc-for-python/blob/main/Python Examples/doc_python.md Extracts three child objects starting from the paragraph containing a 'FieldFormTextInput' type form field and adds them to a new section in the destination document. The loop breaks after the first matching field is found. ```python #Create the source document sourceDocument = Document() #Create a destination document destinationDoc = Document() #Add a section section = destinationDoc.AddSection() #Define a variables index = 0 #Traverse FormFields for i in range(sourceDocument.Sections[0].Body.FormFields.Count): #Find FieldFormTextInput type field field = sourceDocument.Sections[0].Body.FormFields.get_Item(i) if field.Type == FieldType.FieldFormTextInput: #Get the paragraph paragraph = field.OwnerParagraph #Get the index index = sourceDocument.Sections[0].Body.ChildObjects.IndexOf(paragraph) break #Extract the content i = index while i < index + 3: #Clone the ChildObjects of source document doobj = sourceDocument.Sections[0].Body.ChildObjects[i].Clone() #Add to destination document section.Body.ChildObjects.Add(doobj) i += 1 ``` -------------------------------- ### Configure Different Page Settings for Document Sections Source: https://github.com/eiceblue/spire.doc-for-python/blob/main/Python Examples/doc_python.md Applies distinct page setup configurations to specific sections of a Word document, such as changing orientation to landscape. ```python # Get the second section SectionTwo = doc.Sections[1] # Set the orientation SectionTwo.PageSetup.Orientation = PageOrientation.Landscape # Set page size #SectionTwo.PageSetup.PageSize = new SizeF(800, 800) ``` -------------------------------- ### AfterSpacing Source: https://github.com/eiceblue/spire.doc-for-python/blob/main/_autodocs/10-styles-and-formatting.md Gets or sets the space after the paragraph in points. ```APIDOC ## AfterSpacing (Property) Gets or sets the space after the paragraph in points. ```python paragraph.Format.AfterSpacing = 12 ``` **Type:** `float` **Returns:** Space in points ``` -------------------------------- ### Create and Populate a Table Source: https://github.com/eiceblue/spire.doc-for-python/blob/main/_autodocs/04-table-class.md Demonstrates how to create a new document, add a section, create a table with a specific number of rows and columns, and populate its cells with text, including a header row. ```python from spire.doc import Document from spire.doc.common import FileFormat document = Document() section = document.AddSection() # Create a table with 3 rows and 2 columns table = section.AddTable(True) table.ResetCells(3, 2) # Add header row table.Rows[0].Cells[0].AddParagraph().AppendText("Header 1") table.Rows[0].Cells[1].AddParagraph().AppendText("Header 2") # Add data rows table.Rows[1].Cells[0].AddParagraph().AppendText("Data 1-1") table.Rows[1].Cells[1].AddParagraph().AppendText("Data 1-2") document.SaveToFile("output.docx", FileFormat.Docx) ``` -------------------------------- ### BeforeSpacing Source: https://github.com/eiceblue/spire.doc-for-python/blob/main/_autodocs/10-styles-and-formatting.md Gets or sets the space before the paragraph in points. ```APIDOC ## BeforeSpacing (Property) Gets or sets the space before the paragraph in points. ```python paragraph.Format.BeforeSpacing = 12 ``` **Type:** `float` **Returns:** Space in points ``` -------------------------------- ### RightIndent Source: https://github.com/eiceblue/spire.doc-for-python/blob/main/_autodocs/10-styles-and-formatting.md Gets or sets the right indentation of a paragraph in points. ```APIDOC ## RightIndent (Property) Gets or sets the right indentation in points. ```python paragraph.Format.RightIndent = 36 ``` **Type:** `float` **Returns:** Right indent in points ``` -------------------------------- ### Create and Save a Simple Document Source: https://github.com/eiceblue/spire.doc-for-python/blob/main/_autodocs/01-document-class.md Demonstrates creating a new document, adding content, and saving it to a DOCX file. Ensure to close the document after saving. ```python from spire.doc import Document from spire.doc.common import FileFormat # Create a new blank document document = Document() section = document.AddSection() paragraph = section.AddParagraph() paragraph.AppendText("Hello World!") document.SaveToFile("output.docx", FileFormat.Docx) document.Close() ``` -------------------------------- ### PageSetup Methods and Properties Source: https://github.com/eiceblue/spire.doc-for-python/blob/main/_autodocs/14-api-summary.md Allows configuration of page dimensions, orientation, margins, and columns. ```APIDOC ## PageSetup Methods and Properties ### Description Methods and properties for configuring page setup. ### Methods - `AddColumn(width, spacing)`: Add column. Returns None. ### Properties - `PageWidth` (float): Page width in points. - `PageHeight` (float): Page height in points. - `Orientation` (Orientation): Portrait/Landscape. - `Margins` (Margins): Page margins. - `ColumnsLineBetween` (bool): Display column separator. - `TextDirection` (TextDirection): Section text direction. ``` -------------------------------- ### LeftIndent Source: https://github.com/eiceblue/spire.doc-for-python/blob/main/_autodocs/10-styles-and-formatting.md Gets or sets the left indentation of a paragraph in points. ```APIDOC ## LeftIndent (Property) Gets or sets the left indentation in points. ```python paragraph.Format.LeftIndent = 36 # 0.5 inch ``` **Type:** `float` **Returns:** Left indent in points ``` -------------------------------- ### FirstLineIndent Source: https://github.com/eiceblue/spire.doc-for-python/blob/main/_autodocs/10-styles-and-formatting.md Gets or sets the first line indentation of a paragraph in points. ```APIDOC ## FirstLineIndent (Property) Gets or sets the first line indentation in points. ```python paragraph.Format.FirstLineIndent = 36 # 0.5 inch indent for first line ``` **Type:** `float` **Returns:** First line indent in points ``` -------------------------------- ### Get Bookmarks from Word Document Source: https://github.com/eiceblue/spire.doc-for-python/blob/main/Python Examples/doc_python.md Retrieves bookmarks from a document by their index and by their name. ```python #Get the bookmark by index. bookmark1 = document.Bookmarks[0] #Get the bookmark by name. bookmark2 = document.Bookmarks["Test2"] ``` -------------------------------- ### Format Table Borders and Display Source: https://github.com/eiceblue/spire.doc-for-python/blob/main/_autodocs/04-table-class.md Provides an example of setting table borders, including line style, width, and specifying which borders to display. This snippet requires importing `BordersDisplayType`. ```python from spire.doc import Document from spire.doc.common import BordersDisplayType table = section.AddTable(True) table.ResetCells(2, 2) # Format table table.TableFormat.Borders.LineStyle = LineStyle.Single table.TableFormat.Borders.LineWidth = 1.5 table.TableFormat.BordersDisplayType = BordersDisplayType.All ``` -------------------------------- ### Style Name Property Source: https://github.com/eiceblue/spire.doc-for-python/blob/main/_autodocs/10-styles-and-formatting.md Gets or sets the name of a style, which is used for identification and application. ```APIDOC ## Property: ParagraphStyle.Name ### Description Gets or sets the style name. ### Type `str` ### Example ```python style.Name = "MyCustomStyle" ``` ``` -------------------------------- ### Get Page Count Source: https://github.com/eiceblue/spire.doc-for-python/blob/main/_autodocs/11-document-properties-and-metadata.md Retrieves the total number of pages in the document. This property is read-only. ```python page_count = document.BuiltinDocumentProperties.PageCount ``` -------------------------------- ### Create a Simple Word Document Source: https://github.com/eiceblue/spire.doc-for-python/blob/main/Python Examples/doc_python.md Creates a new Word document and adds a section with a paragraph containing 'Hello World!'. ```python #Create a word document document = Document() #Create a new section section = document.AddSection() #Create a new paragraph paragraph = section.AddParagraph() #Append Text paragraph.AppendText("Hello World!") ``` -------------------------------- ### Get Line Count Source: https://github.com/eiceblue/spire.doc-for-python/blob/main/_autodocs/11-document-properties-and-metadata.md Retrieves the total number of lines in the document. This property is read-only. ```python line_count = document.BuiltinDocumentProperties.LineCount ``` -------------------------------- ### Get Word Count Source: https://github.com/eiceblue/spire.doc-for-python/blob/main/_autodocs/11-document-properties-and-metadata.md Retrieves the total number of words in the document. This property is read-only. ```python word_count = document.BuiltinDocumentProperties.WordCount ``` -------------------------------- ### CharacterFormat Class - Underline Property Source: https://github.com/eiceblue/spire.doc-for-python/blob/main/_autodocs/06-textrange-and-character-format.md Demonstrates how to set and get the underline style for a text range. ```APIDOC ## CharacterFormat.Underline ### Description Gets or sets the underline style. ### Method Set: text_range.CharacterFormat.Underline = UnderlineStyle.Single Get: text_range.CharacterFormat.Underline ### Parameters #### Set Parameters - **Underline** (UnderlineStyle) - Required - The underline style to apply. Available styles: None, Single, Double, Thick, Dotted, Dashed, DashDot, DashDotDot, Wave. ### Response #### Success Response (Get) - **Underline** (UnderlineStyle) - The current underline style. ### Request Example ```python from spire.doc.common import UnderlineStyle # Assuming 'para' is a Paragraph object tr = para.AppendText("Underlined") tr.CharacterFormat.Underline = UnderlineStyle.Single tr2 = para.AppendText("Double underline") tr2.CharacterFormat.Underline = UnderlineStyle.Double ``` ``` -------------------------------- ### Configure Page Settings, Headers, and Footers in Word Source: https://github.com/eiceblue/spire.doc-for-python/blob/main/Python Examples/doc_python.md Create a Word document, set page size and margins, and add custom headers and footers with images and page numbers. Requires Spire.Doc library. ```python #Create Word document. document = Document() section = document.AddSection() #The unit of all measures below is point, 1point = 0.3528 mm. section.PageSetup.PageSize = PageSize.A4() section.PageSetup.Margins.Top = 72 section.PageSetup.Margins.Bottom = 72 section.PageSetup.Margins.Left = 89.85 section.PageSetup.Margins.Right = 89.85 #Insert header and footer. header = section.HeadersFooters.Header footer = section.HeadersFooters.Footer #Insert picture and text to header. headerParagraph = header.AddParagraph() headerPicture = headerParagraph.AppendPicture("./Data/Header.png") #Header text. text = headerParagraph.AppendText("Demo of Spire.Doc") text.CharacterFormat.FontName = "Arial" text.CharacterFormat.FontSize = 10 text.CharacterFormat.Italic = True headerParagraph.Format.HorizontalAlignment = HorizontalAlignment.Right #Border. headerParagraph.Format.Borders.Bottom.BorderType = BorderStyle.Single headerParagraph.Format.Borders.Bottom.Space = 0.05 #Header picture layout - text wrapping. headerPicture.TextWrappingStyle = TextWrappingStyle.Behind #Header picture layout - position. headerPicture.HorizontalOrigin = HorizontalOrigin.Page headerPicture.HorizontalAlignment = ShapeHorizontalAlignment.Left headerPicture.VerticalOrigin = VerticalOrigin.Page headerPicture.VerticalAlignment = ShapeVerticalAlignment.Top #Insert picture to footer. footerParagraph = footer.AddParagraph() footerPicture = footerParagraph.AppendPicture("./Data/Footer.png") #Footer picture layout. footerPicture.TextWrappingStyle = TextWrappingStyle.Behind footerPicture.HorizontalOrigin = HorizontalOrigin.Page footerPicture.HorizontalAlignment = ShapeHorizontalAlignment.Left footerPicture.VerticalOrigin = VerticalOrigin.Page footerPicture.VerticalAlignment = ShapeVerticalAlignment.Bottom #Insert page number. footerParagraph.AppendField("page number", FieldType.FieldPage) footerParagraph.AppendText(" of ") footerParagraph.AppendField("number of pages", FieldType.FieldNumPages) footerParagraph.Format.HorizontalAlignment = HorizontalAlignment.Right #Border. footerParagraph.Format.Borders.Top.BorderType = BorderStyle.Single footerParagraph.Format.Borders.Top.Space = 0.05 ``` -------------------------------- ### CharacterFormat Class - FontSize Property Source: https://github.com/eiceblue/spire.doc-for-python/blob/main/_autodocs/06-textrange-and-character-format.md Shows how to set and get the font size for a text range. ```APIDOC ## CharacterFormat.FontSize ### Description Gets or sets the font size in points. ### Method Set: text_range.CharacterFormat.FontSize = 14 Get: text_range.CharacterFormat.FontSize ### Parameters #### Set Parameters - **FontSize** (float) - Required - The font size in points. ### Response #### Success Response (Get) - **FontSize** (float) - The current font size in points. ### Request Example ```python # Assuming 'para' is a Paragraph object heading = para.AppendText("Large Text") heading.CharacterFormat.FontSize = 18 body = para.AppendText("Normal text") body.CharacterFormat.FontSize = 11 ``` ``` -------------------------------- ### Create Table Structure Source: https://github.com/eiceblue/spire.doc-for-python/blob/main/_autodocs/04-table-class.md Initializes a table with a specified number of rows and columns. This is a fundamental step before populating the table with content. ```python table.ResetCells(3, 4) # 3 rows, 4 columns ``` -------------------------------- ### TextRange Class - Text Property Source: https://github.com/eiceblue/spire.doc-for-python/blob/main/_autodocs/06-textrange-and-character-format.md Demonstrates how to get and set the text content of a TextRange object. ```APIDOC ## TextRange.Text ### Description Gets or sets the text content of the range. ### Method Set: text_range.Text = "New text" Get: current_text = text_range.Text ### Parameters #### Set Parameters - **Text** (str) - Required - The new text content to set. #### Get Parameters None ### Response #### Success Response (Get) - **Text** (str) - The current text content of the range. ### Request Example (Set) ```python from spire.doc import Document document = Document() section = document.AddSection() para = section.AddParagraph() # Append text and get reference tr = para.AppendText("Original") # Modify the text tr.Text = "Modified" ``` ### Response Example (Get) ```python # Access current text print(tr.Text) # Prints: "Modified" ``` ``` -------------------------------- ### Convert Markdown to Various Document Formats Source: https://github.com/eiceblue/spire.doc-for-python/blob/main/Python Examples/doc_python.md Shows how to load a Markdown file and save it into multiple formats including Markdown, DOCX, DOC, and PDF. Ensure the input Markdown file exists. ```python # Create a document object document = Document() # Load markdown file document.LoadFromFile("Data/FromMarkdown.md") # Save to markdown format document.SaveToFile("FromMarkdown_markdown.md", FileFormat.Markdown) # Save to docx format document.SaveToFile("FromMarkdown_docx.docx", FileFormat.Docx) # Save to doc format document.SaveToFile("FromMarkdown_doc.doc", FileFormat.Doc) # Save to pdf format document.SaveToFile("FromMarkdown_pdf.pdf", FileFormat.PDF) ``` -------------------------------- ### Get Form Field by Name Source: https://github.com/eiceblue/spire.doc-for-python/blob/main/Python Examples/doc_python.md Retrieve a specific form field from a document's section by its name. ```python # Create a Word document document = Document() # Get the first section section = document.Sections[0] # Get form field by name formField = section.Body.FormFields["email"] ``` -------------------------------- ### Set Snap To Grid for Paragraph Format Source: https://github.com/eiceblue/spire.doc-for-python/blob/main/Python Examples/doc_python.md Configures page setup for lines and then enables the 'SnapToGrid' property for a paragraph's format. Requires creating a new document and section. ```Python # Create a new instance of the Document class. doc = Document() # Add a new section to the document. section = doc.AddSection() # Set the grid type of the page setup in the section to "LinesOnly". section.PageSetup.GridType = GridPitchType.LinesOnly # Set the number of lines per page in the section to 15. section.PageSetup.LinesPerPage = 15 # Add a new paragraph to the section. paragraph = section.AddParagraph() # Set the "SnapToGrid" property of the paragraph's format to true. paragraph.Format.SnapToGrid = True ``` -------------------------------- ### CharacterFormat Class - SubSuperScript Property Source: https://github.com/eiceblue/spire.doc-for-python/blob/main/_autodocs/06-textrange-and-character-format.md Shows how to set and get superscript or subscript formatting for a text range. ```APIDOC ## CharacterFormat.SubSuperScript ### Description Gets or sets superscript or subscript formatting. ### Method Set: text_range.CharacterFormat.SubSuperScript = SubSuperScript.SuperScript Get: text_range.CharacterFormat.SubSuperScript ### Parameters #### Set Parameters - **SubSuperScript** (SubSuperScript) - Required - The vertical position value. Available values: None, SuperScript, SubScript. ### Response #### Success Response (Get) - **SubSuperScript** (SubSuperScript) - The current vertical position setting. ### Request Example ```python from spire.doc.common import SubSuperScript # Assuming 'section' is a Section object para = section.AddParagraph() para.AppendText("E = mc") exponent = para.AppendText("2") exponent.CharacterFormat.SubSuperScript = SubSuperScript.SuperScript ``` ``` -------------------------------- ### Create a Simple Document Source: https://github.com/eiceblue/spire.doc-for-python/blob/main/_autodocs/13-quick-start-guide.md Create a new Word document, add a section, a paragraph, append text, and save it to a file. Ensure to close the document when done. ```python from spire.doc import Document from spire.doc.common import FileFormat # Create a new document document = Document() # Add a section (every document needs at least one) section = document.AddSection() # Add a paragraph paragraph = section.AddParagraph() # Append text paragraph.AppendText("Hello World!") # Save the document document.SaveToFile("output.docx", FileFormat.Docx) # Always close when done document.Close() ``` -------------------------------- ### CharacterFormat Class - FontName Property Source: https://github.com/eiceblue/spire.doc-for-python/blob/main/_autodocs/06-textrange-and-character-format.md Demonstrates how to set and get the font family name for a text range. ```APIDOC ## CharacterFormat.FontName ### Description Gets or sets the font family name. ### Method Set: text_range.CharacterFormat.FontName = "Arial" Get: text_range.CharacterFormat.FontName ### Parameters #### Set Parameters - **FontName** (str) - Required - The name of the font family (e.g., "Arial", "Times New Roman"). ### Response #### Success Response (Get) - **FontName** (str) - The current font name. ### Request Example ```python # Assuming 'para' is a Paragraph object and 'tr' is a TextRange tr = para.AppendText("Courier text") tr.CharacterFormat.FontName = "Courier New" tr2 = para.AppendText("Arial text") tr2.CharacterFormat.FontName = "Arial" ``` ``` -------------------------------- ### Configure Page Setup for a Section Source: https://github.com/eiceblue/spire.doc-for-python/blob/main/_autodocs/02-section-class.md Provides access to page layout settings such as width, height, margins, orientation, and columns. Settings are in points (1 inch = 72 points). ```python section = document.Sections[0] setup = section.PageSetup # Set page orientation setup.Orientation = Orientation.Landscape # Set margins (in points, where 1 inch = 72 points) setup.Margins.Top = 72 # 1 inch setup.Margins.Bottom = 72 setup.Margins.Left = 72 setup.Margins.Right = 72 # Enable columns setup.AddColumn(100, 20) # 100 points width, 20 points spacing setup.ColumnsLineBetween = True ``` -------------------------------- ### PageHeight Source: https://github.com/eiceblue/spire.doc-for-python/blob/main/_autodocs/08-page-setup-and-sections.md Gets or sets the page height in points. This property is used to define the vertical dimension of the page. ```APIDOC ## PageHeight ### Description Gets or sets the page height in points. ### Method Set ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **PageHeight** (float) - Required - The height of the page in points. ### Request Example ```python section.PageSetup.PageHeight = 792 ``` ### Response #### Success Response (200) - **PageHeight** (float) - The current height of the page in points. #### Response Example ```python height = section.PageSetup.PageHeight ``` ``` -------------------------------- ### LineSpacing Source: https://github.com/eiceblue/spire.doc-for-python/blob/main/_autodocs/10-styles-and-formatting.md Gets or sets the line spacing multiplier (e.g., 1.0 for single, 1.5 for 1.5x, 2.0 for double). ```APIDOC ## LineSpacing (Property) Gets or sets the line spacing multiplier (1.0 = single, 1.5 = 1.5x, 2.0 = double). ```python paragraph.Format.LineSpacing = 1.5 # 1.5 line spacing ``` **Type:** `float` **Returns:** Line spacing multiplier **Example:** ```python from spire.doc import Document document = Document() section = document.AddSection() # Single spaced para1 = section.AddParagraph() para1.AppendText("Single spaced paragraph") para1.Format.LineSpacing = 1.0 # 1.5 line spaced para2 = section.AddParagraph() para2.AppendText("One and one-half spaced paragraph") para2.Format.LineSpacing = 1.5 para2.Format.BeforeSpacing = 12 # Double spaced para3 = section.AddParagraph() para3.AppendText("Double spaced paragraph") para3.Format.LineSpacing = 2.0 para3.Format.BeforeSpacing = 12 ``` ``` -------------------------------- ### Create a New Word Document Source: https://github.com/eiceblue/spire.doc-for-python/blob/main/_autodocs/00-index.md Demonstrates how to create a new Word document, add a section and paragraph, append text, and save the document to a file. Requires importing Document and FileFormat from spire.doc. ```python from spire.doc import Document from spire.doc.common import FileFormat document = Document() section = document.AddSection() paragraph = section.AddParagraph() paragraph.AppendText("Hello World!") document.SaveToFile("output.docx", FileFormat.Docx) document.Close() ``` -------------------------------- ### HorizontalAlignment Source: https://github.com/eiceblue/spire.doc-for-python/blob/main/_autodocs/10-styles-and-formatting.md Gets or sets paragraph horizontal alignment. Supports Left, Center, Right, Justify, and Distributed alignments. ```APIDOC ## HorizontalAlignment (Property) Gets or sets paragraph horizontal alignment. ```python from spire.doc.common import HorizontalAlignment paragraph.Format.HorizontalAlignment = HorizontalAlignment.Center ``` **Type:** `HorizontalAlignment` | Value | Description | |-------|-------------| | Left | Left alignment (default) | | Center | Center alignment | | Right | Right alignment | | Justify | Justified (aligned to both margins) | | Distributed | Distributed alignment | **Example:** ```python section = document.AddSection() # Left aligned (default) left_para = section.AddParagraph() left_para.AppendText("Left aligned text") left_para.Format.HorizontalAlignment = HorizontalAlignment.Left # Center aligned center_para = section.AddParagraph() center_para.AppendText("Center aligned text") center_para.Format.HorizontalAlignment = HorizontalAlignment.Center # Right aligned right_para = section.AddParagraph() right_para.AppendText("Right aligned text") right_para.Format.HorizontalAlignment = HorizontalAlignment.Right # Justified justify_para = section.AddParagraph() justify_para.AppendText("Justified text that spans multiple lines will be aligned to both left and right margins...") justify_para.Format.HorizontalAlignment = HorizontalAlignment.Justify ``` ``` -------------------------------- ### Complete Text Formatting Example Source: https://github.com/eiceblue/spire.doc-for-python/blob/main/_autodocs/06-textrange-and-character-format.md Applies multiple character formatting properties like font name, size, style, and color to create a styled document title and subtitle. ```python from spire.doc import Document from spire.doc.common import ( Color, UnderlineStyle, SubSuperScript, FileFormat ) document = Document() section = document.AddSection() # Create styled text para = section.AddParagraph() # Title title = para.AppendText("Document Title") title.CharacterFormat.FontName = "Arial" title.CharacterFormat.FontSize = 18 title.CharacterFormat.Bold = True title.CharacterFormat.TextColor = Color.get_DarkBlue() # Subtitle para.AppendBreak(BreakType.LineBreak) subtitle = para.AppendText("A formatted example") subtitle.CharacterFormat.FontName = "Courier New" subtitle.CharacterFormat.FontSize = 12 subtitle.CharacterFormat.Italic = True subtitle.CharacterFormat.TextColor = Color.get_Gray() ``` -------------------------------- ### ColumnsLineBetween Source: https://github.com/eiceblue/spire.doc-for-python/blob/main/_autodocs/08-page-setup-and-sections.md Gets or sets a boolean value to control whether a visible line is displayed between columns in a multi-column layout. ```APIDOC ## ColumnsLineBetween ### Description Gets or sets whether to display a line between columns. ### Method Set ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **ColumnsLineBetween** (bool) - Required - True to display a line between columns, False otherwise. ### Request Example ```python section.PageSetup.ColumnsLineBetween = True ``` ### Response #### Success Response (200) - **ColumnsLineBetween** (bool) - True if a line is displayed between columns, False otherwise. #### Response Example ```python line_enabled = section.PageSetup.ColumnsLineBetween ``` ``` -------------------------------- ### Orientation Source: https://github.com/eiceblue/spire.doc-for-python/blob/main/_autodocs/08-page-setup-and-sections.md Gets or sets the page orientation, allowing the user to switch between portrait (vertical) and landscape (horizontal) layouts. ```APIDOC ## Orientation ### Description Gets or sets the page orientation (portrait or landscape). ### Method Set ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **Orientation** (Orientation) - Required - The desired page orientation. Can be `Orientation.Portrait` or `Orientation.Landscape`. ### Request Example ```python from spire.doc.common import Orientation section.PageSetup.Orientation = Orientation.Landscape ``` ### Response #### Success Response (200) - **Orientation** (Orientation) - The current page orientation. #### Response Example ```python current_orientation = section.PageSetup.Orientation ``` ```