Lists are a powerful organizational tool that can be used to present information in a structured and easy-to-follow manner. Whether you want to create numbered lists, bulleted lists, or even custom lists with specific formatting, Word provides flexible options to suit your needs. By utilizing different list styles, you can improve the readability and visual appeal of your documents, making it simpler for readers to grasp key points and navigate through the content. In this article, you will learn how to programmatically create various types of lists in a Word document in Python using Spire.Doc for Python.

Install Spire.Doc for Python

This scenario requires Spire.Doc for Python and plum-dispatch v1.7.4. They can be easily installed in your Windows through the following pip command.

pip install Spire.Doc

If you are unsure how to install, please refer to this tutorial: How to Install Spire.Doc for Python on Windows

Create a Numbered List in Word in Python

Spire.Doc for Python provides the ListStyle class, which enables you to establish either a numbered list style or a bulleted style. Subsequently, you can utilize the Paragraph.ListFormat.ApplyStyle() method to apply the defined list style to a paragraph. The steps to create a numbered list are as follows.

  • Create a Document object.
  • Add a section using Document.AddSection() method.
  • Create an instance of ListStyle class, specifying the list type to Numbered.
  • Get a specific level of the list through ListStyle.Levels[index] property, and set the numbering type through ListLevel.PatternType property.
  • Add the list style to the document using Document.ListStyles.Add() method.
  • Add several paragraphs to the document using Section.AddParagraph() method.
  • Apply the list style to a specific paragraph using Paragraph.ListFormat.ApplyStyle() method.
  • Specify the list level through Paragraph.ListFormat.ListLevelNumber property.
  • Save the document to a Word file using Document.SaveToFile() method.
  • Python
from spire.doc import *
from spire.doc.common import *

# Create a Document object
doc = Document()

# Add a section
section = doc.AddSection()

# Create a numbered list style
listStyle = ListStyle(doc, ListType.Numbered)
listStyle.Name = "numberedList"
listStyle.Levels[0].PatternType = ListPatternType.DecimalEnclosedParen
listStyle.Levels[0].TextPosition = 20;  
doc.ListStyles.Add(listStyle)

# Add a paragraph
paragraph = section.AddParagraph()
paragraph.AppendText("Required Web Development Skills:")
paragraph.Format.AfterSpacing = 5.0

# Add a paragraph and apply the numbered list style to it
paragraph = section.AddParagraph()
paragraph.AppendText("HTML")
paragraph.ListFormat.ApplyStyle("numberedList")
paragraph.ListFormat.ListLevelNumber = 0

# Add another four paragraphs and apply the numbered list style to them
paragraph = section.AddParagraph()
paragraph.AppendText("CSS")
paragraph.ListFormat.ApplyStyle("numberedList")
paragraph.ListFormat.ListLevelNumber = 0

paragraph = section.AddParagraph()
paragraph.AppendText("JavaScript")
paragraph.ListFormat.ApplyStyle("numberedList")
paragraph.ListFormat.ListLevelNumber = 0

paragraph = section.AddParagraph()
paragraph.AppendText("Python")
paragraph.ListFormat.ApplyStyle("numberedList")
paragraph.ListFormat.ListLevelNumber = 0

paragraph = section.AddParagraph()
paragraph.AppendText("MySQL")
paragraph.ListFormat.ApplyStyle("numberedList")
paragraph.ListFormat.ListLevelNumber = 0

# Save the document to file
doc.SaveToFile("output/NumberedList.docx", FileFormat.Docx)

Python: Create Various Types of Lists in a Word Document

Create a Bulleted List in Word in Python

Creating a bulleted list follows a similar process to creating a numbered list, with the main difference being that you need to specify the list type as "Bulleted" and assign a bullet symbol to it. The following are the detailed steps.

  • Create a Document object.
  • Add a section using Document.AddSection() method.
  • Create an instance of ListStyle class, specifying the list type to Bulleted.
  • Get a specific level of the list through ListStyle.Levels[index] property, and set the bullet symbol through ListLevel.BulletCharacter property.
  • Add the list style to the document using Document.ListStyles.Add() method.
  • Add several paragraphs to the document using Section.AddParagraph() method.
  • Apply the list style to a specific paragraph using Paragraph.ListFormat.ApplyStyle() method.
  • Specify the list level through Paragraph.ListFormat.ListLevelNumber property.
  • Save the document to a Word file using Document.SaveToFile() method.
  • Python
from spire.doc import *
from spire.doc.common import *

# Create a Document object
doc = Document()

# Add a section
section = doc.AddSection()

# Create a bulleted list style
listStyle = ListStyle(doc, ListType.Bulleted)
listStyle.Name = "bulletedList"
listStyle.Levels[0].BulletCharacter = "\u00B7"
listStyle.Levels[0].CharacterFormat.FontName = "Symbol"
listStyle.Levels[0].TextPosition = 20
doc.ListStyles.Add(listStyle)

# Add a paragraph
paragraph = section.AddParagraph()
paragraph.AppendText("Computer Science Subjects:")
paragraph.Format.AfterSpacing = 5.0

# Add a paragraph and apply the bulleted list style to it
paragraph = section.AddParagraph()
paragraph.AppendText("Data Structure")
paragraph.ListFormat.ApplyStyle("bulletedList")
paragraph.ListFormat.ListLevelNumber = 0

# Add another five paragraphs and apply the bulleted list style to them
paragraph = section.AddParagraph()
paragraph.AppendText("Algorithm")
paragraph.ListFormat.ApplyStyle("bulletedList")
paragraph.ListFormat.ListLevelNumber = 0

paragraph = section.AddParagraph()
paragraph.AppendText("Computer Networks")
paragraph.ListFormat.ApplyStyle("bulletedList")
paragraph.ListFormat.ListLevelNumber = 0

paragraph = section.AddParagraph()
paragraph.AppendText("Operating System")
paragraph.ListFormat.ApplyStyle("bulletedList")
paragraph.ListFormat.ListLevelNumber = 0

paragraph = section.AddParagraph()
paragraph.AppendText("C Programming")
paragraph.ListFormat.ApplyStyle("bulletedList")
paragraph.ListFormat.ListLevelNumber = 0

paragraph = section.AddParagraph()
paragraph.AppendText("Theory of Computations")
paragraph.ListFormat.ApplyStyle("bulletedList")
paragraph.ListFormat.ListLevelNumber = 0

# Save the document to file
doc.SaveToFile("output/BulletedList.docx", FileFormat.Docx);

Python: Create Various Types of Lists in a Word Document

Create a Multi-Level Numbered List in Word in Python

A multi-level list consists of at least two different levels. A certain level of a nested list can be accessed by the ListStyle.Levels[index] property, through which you can set the numbering type and prefix. The following are the steps to create a multi-level numbered list in Word.

  • Create a Document object.
  • Add a section using Document.AddSection() method.
  • Create an instance of ListStyle class, specifying the list type to Numbered.
  • Get a specific level of the list through ListStyle.Levels[index] property, and set the numbering type and prefix.
  • Add the list style to the document using Document.ListStyles.Add() method.
  • Add several paragraphs to the document using Section.AddParagraph() method.
  • Apply the list style to a specific paragraph using Paragraph.ListFormat.ApplyStyle() method.
  • Specify the list level through Paragraph.ListFormat.ListLevelNumber property.
  • Save the document to a Word file using Document.SaveToFile() method.
  • Python
from spire.doc import *
from spire.doc.common import *

# Create a Document object
doc = Document()

# Add a section
section = doc.AddSection()

# Create a numbered list style, specifying number prefix and pattern type of each level
listStyle = ListStyle(doc, ListType.Numbered)
listStyle.Name = "levelstyle"
listStyle.Levels.get_Item(0).PatternType = ListPatternType.Arabic
listStyle.Levels.get_Item(0).TextPosition = 20.0
listStyle.Levels.get_Item(1).NumberPrefix = "%1."
listStyle.Levels.get_Item(1).PatternType = ListPatternType.Arabic
listStyle.Levels.get_Item(2).NumberPrefix = "%1.%2."
listStyle.Levels.get_Item(2).PatternType = ListPatternType.Arabic
doc.ListStyles.Add(listStyle)

# Add a paragraph 
paragraph = section.AddParagraph()
paragraph.AppendText("Here's a Multi-Level Numbered List:")
paragraph.Format.AfterSpacing = 5.0

# Add a paragraph and apply the numbered list style to it
paragraph = section.AddParagraph()
paragraph.AppendText("The first item")
paragraph.ListFormat.ApplyStyle("levelstyle")
paragraph.ListFormat.ListLevelNumber = 0

# Add another five paragraphs and apply the numbered list stype to them
paragraph = section.AddParagraph()
paragraph.AppendText("The second item")
paragraph.ListFormat.ApplyStyle("levelstyle")
paragraph.ListFormat.ListLevelNumber = 0

paragraph = section.AddParagraph()
paragraph.AppendText("The first sub-item")
paragraph.ListFormat.ApplyStyle("levelstyle")
paragraph.ListFormat.ListLevelNumber = 1

paragraph = section.AddParagraph()
paragraph.AppendText("The second sub-item")
paragraph.ListFormat.ContinueListNumbering()
paragraph.ListFormat.ApplyStyle("levelstyle")

paragraph = section.AddParagraph()
paragraph.AppendText("A sub-sub-item")
paragraph.ListFormat.ApplyStyle("levelstyle")
paragraph.ListFormat.ListLevelNumber = 2

paragraph = section.AddParagraph()
paragraph.AppendText("The third item")
paragraph.ListFormat.ApplyStyle("levelstyle")
paragraph.ListFormat.ListLevelNumber = 0

# Save the document to file
doc.SaveToFile("output/MultilevelNumberedList.docx", FileFormat.Docx)

Python: Create Various Types of Lists in a Word Document

Create a Multi-Level Mixed-Type List in Word in Python

To combine number and symbol bullet points in a multi-level list, create separate list styles (numbered and bulleted) and apply them to different paragraphs. The detailed steps are as follows.

  • Create a Document object.
  • Add a section using Document.AddSection() method.
  • Create a numbered list style and a bulleted list style.
  • Add several paragraphs to the document using Section.AddParagraph() method.
  • Apply different list style to different paragraphs using Paragraph.ListFormat.ApplyStyle() method.
  • Save the document to a Word file using Document.SaveToFile() method.
  • Python
from spire.doc import *
from spire.doc.common import *

# Create a Document object
doc = Document()

# Add a section
section = doc.AddSection()

# Create a numbered list style
numberedListStyle = ListStyle(doc, ListType.Numbered)
numberedListStyle.Name = "numberedStyle"
numberedListStyle.Levels[0].PatternType = ListPatternType.Arabic
numberedListStyle.Levels[0].TextPosition = 20
numberedListStyle.Levels[1].PatternType = ListPatternType.LowLetter
doc.ListStyles.Add(numberedListStyle)

# Create a bulleted list style
bulletedListStyle = ListStyle(doc, ListType.Bulleted)
bulletedListStyle.Name = "bulltedStyle"
bulletedListStyle.Levels[2].BulletCharacter = "\u002A"
bulletedListStyle.Levels[2].CharacterFormat.FontName = "Symbol"
doc.ListStyles.Add(bulletedListStyle)

# Add a paragraph 
paragraph = section.AddParagraph()
paragraph.AppendText("Here's a Multi-Level Mixed List:")
paragraph.Format.AfterSpacing = 5.0

# Add a paragraph and apply the numbered list style to it
paragraph = section.AddParagraph()
paragraph.AppendText("The first item")
paragraph.ListFormat.ApplyStyle("numberedStyle")
paragraph.ListFormat.ListLevelNumber = 0

# Add the other five paragraphs and apply different list stype to them
paragraph = section.AddParagraph()
paragraph.AppendText("The first sub-item")
paragraph.ListFormat.ApplyStyle("numberedStyle")
paragraph.ListFormat.ListLevelNumber = 1

paragraph = section.AddParagraph()
paragraph.AppendText("The second sub-item")
paragraph.ListFormat.ListLevelNumber = 1
paragraph.ListFormat.ApplyStyle("numberedStyle")

paragraph = section.AddParagraph()
paragraph.AppendText("The first sub-sub-item")
paragraph.ListFormat.ApplyStyle("bulltedStyle")
paragraph.ListFormat.ListLevelNumber = 2

paragraph = section.AddParagraph()
paragraph.AppendText("The second sub-sub-item")
paragraph.ListFormat.ApplyStyle("bulltedStyle")
paragraph.ListFormat.ListLevelNumber = 2

paragraph = section.AddParagraph()
paragraph.AppendText("The second item")
paragraph.ListFormat.ApplyStyle("numberedStyle")
paragraph.ListFormat.ListLevelNumber = 0

# Save the document to file
doc.SaveToFile("output/MultilevelMixedList.docx", FileFormat.Docx)

Python: Create Various Types of Lists in a Word Document

Apply for a Temporary License

If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.

Published in List
Saturday, 07 October 2023 01:13

Python: Add Bookmarks to a Word Document

Adding bookmarks to Word documents is a useful feature that allows users to mark specific locations within their documents for quick reference or navigation. Bookmarks serve as virtual placeholders, making it easier to find and revisit important sections of a document without scrolling through lengthy pages. In this article, you will learn how to add bookmarks to a Word document in Python using Spire.Doc for Python.

Install Spire.Doc for Python

This scenario requires Spire.Doc for Python and plum-dispatch v1.7.4. They can be easily installed in your Windows through the following pip command.

pip install Spire.Doc

If you are unsure how to install, please refer to this tutorial: How to Install Spire.Doc for Python on Windows

Add Bookmarks to a Paragraph in Python

Spire.Doc for Python offers the BookmarkStart to represent the start of a bookmark and the BookmarkEnd to represent the end of a bookmark. To bookmark a paragraph, a BookmarkStart object is placed at the beginning of the paragraph and a BookmarkEnd object is appended at the end of the paragraph. The following are the detailed steps.

  • Create a Document object.
  • Load a Word file using Document.LoadFromFile() method.
  • Get a specific paragraph through Document.Sections[index].Paragraphs[index] property.
  • Create a BookmarkStart using Paragraph.AppendBookmarkStart() method and insert it at the beginning of the paragraph using Paragraph.Items.Insert() method.
  • Append a BookmarkEnd at the end of the paragraph using Paragraph.AppendBookmarkEnd() method.
  • Save the document to a different Word file using Document.SaveToFile() method.
  • Python
from spire.doc import *
from spire.doc.common import *

# Create a Document object
doc = Document()

# Load a sample Word file
doc.LoadFromFile('C:/Users/Administrator/Desktop/input.docx')

# Get the second paragraph
paragraph = doc.Sections[0].Paragraphs[2]

# Create a bookmark start
start = paragraph.AppendBookmarkStart('myBookmark')

# Insert it at the beginning of the paragraph
paragraph.Items.Insert(0, start)

# Append a bookmark end at the end of the paragraph
paragraph.AppendBookmarkEnd('myBookmark')

# Save the file
doc.SaveToFile('output/AddBookmarkToParagraph.docx', FileFormat.Docx2019)

Python: Add Bookmarks to a Word Document

Add Bookmarks to Selected Text in Python

To bookmark a piece of text, you need first to get the text from the document and get its position inside its owner paragraph. And then place a BookmarkStart before it and a BookmarEnd after it. The detailed steps are as follows.

  • Create a Document object.
  • Load a Word file using Document.LoadFromFile() method.
  • Find the string to be marked from the document.
  • Get its owner paragraph and its position inside the paragraph.
  • Insert a BookmarkStart before the text and a BookmarkEnd after the text.
  • Save the document to a different Word file using Document.SaveToFile() method.
  • Python
from spire.doc import *
from spire.doc.common import *

# Create a Document object
doc = Document()

# Load a sample Word file
doc.LoadFromFile('C:/Users/Administrator/Desktop/input.docx')

# Specify the string to find
stringToFind = 'programming paradigms'

# Find the selected text from the document
finds = doc.FindAllString(stringToFind, False, True)
specificText = finds[0]

# Find the paragraph where the text is located
paragraph = specificText.GetAsOneRange().OwnerParagraph

# Get the index of the text in the paragraph
index = paragraph.ChildObjects.IndexOf(specificText.GetAsOneRange())

# Create a bookmark start
start = paragraph.AppendBookmarkStart("myBookmark")

# Insert the bookmark start at the index position
paragraph.ChildObjects.Insert(index, start)

# Create a bookmark end
end = paragraph.AppendBookmarkEnd("myBookmark")

# Insert the bookmark end at the end of the selected text
paragraph.ChildObjects.Insert(index + 2, end)

# Save the document to a different file
doc.SaveToFile("output/AddBookmarkToSelectedText.docx", FileFormat.Docx2019)

Python: Add Bookmarks to a Word Document

Apply for a Temporary License

If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.

Published in Bookmark

Adding or removing rows and columns in a Word table allows you to adjust the table's structure to accommodate your data effectively. By adding rows and columns, you can effortlessly expand the table as your data grows, ensuring that all relevant information is captured and displayed in a comprehensive manner. On the other hand, removing unnecessary rows and columns allows you to streamline the table, eliminating any redundant or extraneous data that may clutter the document. In this article, we will demonstrate how to add or delete table rows and columns in Word in Python using Spire.Doc for Python.

Install Spire.Doc for Python

This scenario requires Spire.Doc for Python and plum-dispatch v1.7.4. They can be easily installed in your Windows through the following pip command.

pip install Spire.Doc

If you are unsure how to install, please refer to this tutorial: How to Install Spire.Doc for Python on Windows

Add or Insert a Row into a Word Table in Python

You can add a row to the end of a Word table or insert a row at a specific location of a Word table using the Table.AddRow() or Table.InsertRow() method. The following are the detailed steps:

  • Create a Document object.
  • Load a Word document using Document.LoadFromFile() method.
  • Get the first section of the document using Document.Sections[] property.
  • Get the first table of the section using Section.Tables[] property.
  • Insert a row at a specific location of the table using Table.Rows.Insert() method.
  • Add data to the newly inserted row.
  • Add a row to the end of the table using Table.AddRow() method.
  • Add data to the newly added row.
  • Save the resulting document using Document.SaveToFile() method.
  • Python
from spire.doc import *
from spire.doc.common import *

# Create a Document object
document = Document()
# Load a Word document
document.LoadFromFile("Table1.docx")

# Get the first section of the document
section = document.Sections.get_Item(0)

# Get the first table of the first section
table = section.Tables.get_Item(0) if isinstance(section.Tables.get_Item(0), Table) else None

# Insert a row into the table as the third row
table.Rows.Insert(2, table.AddRow())
# Get the inserted row
insertedRow = table.Rows[2]
# Add data to the row
for i in range(insertedRow.Cells.Count):
    cell = insertedRow.Cells[i]
    paragraph = cell.AddParagraph()
    paragraph.AppendText("Inserted Row")
    paragraph.Format.HorizontalAlignment = HorizontalAlignment.Center
    cell.CellFormat.VerticalAlignment = VerticalAlignment.Middle

# Add a row at the end of the table
addedRow = table.AddRow()
# Add data to the row
for i in range(addedRow.Cells.Count):
    cell = addedRow.Cells[i]
    paragraph = cell.AddParagraph()
    paragraph.AppendText("End Row")
    paragraph.Format.HorizontalAlignment = HorizontalAlignment.Center
    cell.CellFormat.VerticalAlignment = VerticalAlignment.Middle

# Save the resulting document
document.SaveToFile("AddRows.docx", FileFormat.Docx2016)
document.Close()

Python: Add or Delete Table Rows and Columns in Word

Add or Insert a Column into a Word Table in Python

Spire.Doc for Python doesn't offer a direct method to add or insert a column into a Word table. But you can achieve this by adding or inserting cells at a specific location of each table row using TableRow.Cells.Add() or TableRow.Cells.Insert() method. The detailed steps are as follows:

  • Create a Document object.
  • Load a Word document using Document.LoadFromFile() method.
  • Get the first section of the document using Document.Sections[] property.
  • Get the first table of the section using Section.Tables[] property.
  • Loop through each row of the table.
  • Create a TableCell object, then insert it at a specific location of each row using TableRow.Cells.Insert() method and set cell width.
  • Add data to the cell and set text alignment.
  • Add a cell to the end of each row using TableRow.AddCell() method and set cell width.
  • Add data to the cell and set text alignment.
  • Save the resulting document using Document.SaveToFile() method.
  • Python
from spire.doc import *
from spire.doc.common import *

# Create a Document object
document = Document()
# Load a Word document
document.LoadFromFile("Table1.docx")

# Get the first section of the document
section = document.Sections.get_Item(0)

# Get the first table of the first section
table = section.Tables.get_Item(0) if isinstance(section.Tables.get_Item(0), Table) else None

# Loop through the rows of the table
for i in range(table.Rows.Count):
    row = table.Rows.get_Item(i)
    # Create a TableCell object
    cell = TableCell(document)
    # Insert the cell as the third cell of the row and set cell width
    row.Cells.Insert(2, cell)
    cell.Width = row.Cells[0].Width
    # Add data to the cell
    paragraph = cell.AddParagraph()
    paragraph.AppendText("Inserted Column")
    # Set text alignment
    paragraph.Format.HorizontalAlignment = HorizontalAlignment.Center
    cell.CellFormat.VerticalAlignment = VerticalAlignment.Middle

    # Add a cell to the end of the row and set cell width
    cell = row.AddCell()
    cell.Width = row.Cells[1].Width
    # Add data to the cell
    paragraph = cell.AddParagraph()
    paragraph.AppendText("End Column")
    # Set text alignment
    paragraph.Format.HorizontalAlignment = HorizontalAlignment.Center
    cell.CellFormat.VerticalAlignment = VerticalAlignment.Middle

# Save the resulting document
document.SaveToFile("AddColumns.docx", FileFormat.Docx2016)
document.Close()

Python: Add or Delete Table Rows and Columns in Word

Delete a Row from a Word Table in Python

To delete a specific row from a Word table, you can use the Table.Rows.RemoveAt() method. The detailed steps are as follows:

  • Create a Document object.
  • Load a Word document using Document.LoadFromFile() method.
  • Get the first section of the document using Document.Sections[] property.
  • Get the first table of the section using Section.Tables[] property.
  • Remove a specific row from the table using Table.Rows.RemoveAt() method.
  • Save the resulting document using Document.SaveToFile() method.
  • Python
from spire.doc import *
from spire.doc.common import *

# Create a Document object
document = Document()
# Load a Word document
document.LoadFromFile("AddRows.docx")

# Get the first section of the document
section = document.Sections.get_Item(0)

# Get the first table of the first section
table = section.Tables.get_Item(0) if isinstance(section.Tables.get_Item(0), Table) else None

# Remove the third row
table.Rows.RemoveAt(2)
# Remove the last row
table.Rows.RemoveAt(table.Rows.Count - 1)

# Save the resulting document
document.SaveToFile("RemoveRows.docx", FileFormat.Docx2016)
document.Close()

Python: Add or Delete Table Rows and Columns in Word

Delete a Column from a Word Table in Python

To delete a specific column from a Word table, you need to remove the corresponding cell from each table row using the TableRow.Cells.RemoveAt() method. The detailed steps are as follows:

  • Create a Document object.
  • Load a Word document using Document.LoadFromFile() method.
  • Get the first section of the document using Document.Sections[] property.
  • Get the first table of the section using Section.Tables[] property.
  • Loop through each row of the table.
  • Remove a specific cell from each row using TableRow.Cells.RemoveAt() method.
  • Save the resulting document using Document.SaveToFile() method.
  • Python
from spire.doc import *
from spire.doc.common import *

# Create a Document object
document = Document()
# Load a Word document
document.LoadFromFile("AddColumns.docx")

# Get the first section of the document
section = document.Sections.get_Item(0)

# Get the first table of the first section
table = section.Tables.get_Item(0) if isinstance(section.Tables.get_Item(0), Table) else None

# Loop through the rows of the table
for i in range(table.Rows.Count):
    row = table.Rows.get_Item(i)
    # Remove the third cell from the row
    row.Cells.RemoveAt(2)
    # Remove the last cell from the row
    row.Cells.RemoveAt(row.Cells.Count - 1)

# Save the resulting document
document.SaveToFile("RemoveColumns.docx", FileFormat.Docx2016)
document.Close()

Python: Add or Delete Table Rows and Columns in Word

Apply for a Temporary License

If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.

Published in Table
Monday, 11 September 2023 01:47

Python: Insert Images in Word

Images in Word documents can break up large blocks of text and make the content more visually interesting. In addition, they can also effectively illustrate complex ideas or concepts that are difficult to explain solely through text. In this article, you will learn how to programmatically add images to a Word document using Spire.Doc for Python.

Install Spire.Doc for Python

This scenario requires Spire.Doc for Python and plum-dispatch v1.7.4. They can be easily installed in your Windows through the following pip commands.

pip install Spire.Doc

If you are unsure how to install, please refer to this tutorial: How to Install Spire.Doc for Python on Windows

Insert an Image in a Word Document in Python

Spire.Doc for Python offers the Paragraph.AppendPicture() method to insert an image into a Word document. The following are the detailed steps.

  • Create a Document object.
  • Add a section using Document.AddSection() method.
  • Add two paragraphs to the section using Section.AddParagraph() method.
  • Add text to the paragraphs and set formatting.
  • Load an image and add it to a specified paragraph using Paragraph.AppendPicture() method.
  • Set width and height for the image using DocPicture.Width and DocPicture.Height properties.
  • Set a text wrapping style for the image using DocPicture.TextWrappingStyle property.
  • Save the result document using Document.SaveToFile() method.
  • Python
from spire.doc import *
from spire.doc.common import *

# Create a Document object
document = Document()

# Add a seciton
section = document.AddSection()

# Add a paragraph
paragraph1 = section.AddParagraph()
# Add text to the paragraph and set formatting
tr = paragraph1.AppendText("Spire.Doc for Python is a professional Word Python API specifically designed for developers to create, read, write, convert, and compare Word documents with fast and high-quality performance.")
tr.CharacterFormat.FontName = "Calibri"
tr.CharacterFormat.FontSize = 11
paragraph1.Format.LineSpacing = 18
paragraph1.Format.BeforeSpacing = 10
paragraph1.Format.AfterSpacing = 10

# Add another paragraph
paragraph2 = section.AddParagraph()
tr = paragraph2.AppendText("Spire.Doc for Python enables to perform many Word document processing tasks. It supports Word 97-2003 /2007/2010/2013/2016/2019 and it has the ability to convert them to commonly used file formats like XML, RTF, TXT, XPS, EPUB, EMF, HTML and vice versa. Furthermore, it supports to convert Word Doc/Docx to PDF using Python, Word to SVG, and Word to PostScript in high quality.")
# Add text to the paragraph and set formatting
tr.CharacterFormat.FontName = "Calibri"
tr.CharacterFormat.FontSize = 11
paragraph2.Format.LineSpacing = 18

# Add an image to the specified paragraph
picture = paragraph1.AppendPicture("Spire.Doc.jpg")

# Set image width and height
picture.Width = 100
picture.Height = 100

# Set text wrapping style for the image
picture.TextWrappingStyle = TextWrappingStyle.Square

#Save the result document
document.SaveToFile("InsertImage.docx", FileFormat.Docx)
document.Close()

Python: Insert Images in Word

Insert an Image at a Specified Location in a Word document in Python

If you wish to place the image at a specified location in the Word document, you can set its position through the DocPicture.HorizontalPosition and DocPicture.VerticalPosition properties. The following are the detailed steps.

  • Create a Document object.
  • Add a section using Document.AddSection() method.
  • Add a paragraph to the section using Section.AddParagraph() method.
  • Add text to the paragraph and set formatting.
  • Add an image to the paragraph using Paragraph.AppendPicture() method.
  • Set width and height for the image using DocPicture.Width and DocPicture.Height properties.
  • Set the horizontal position and vertical position for the image using DocPicture.HorizontalPosition and DocPicture.VerticalPosition properties.
  • Set a text wrapping style for the image using DocPicture.TextWrappingStyle property.
  • Save the result document using Document.SaveToFile() method.
  • Python
from spire.doc import *
from spire.doc.common import *

# Create a Document object
doc = Document()

# Add a section
section = doc.AddSection()

# Add a paragraph to the section
paragraph = section.AddParagraph()

# Add text to the paragraph and set formatting
paragraph.AppendText("The sample demonstrates how to insert an image at a specified location in a Word document.")
paragraph.ApplyStyle(BuiltinStyle.Heading2)

# Add an image to the paragraph
picture = paragraph.AppendPicture("pic.jpg")

# Set image position
picture.HorizontalPosition = 150.0
picture.VerticalPosition = 60.0

# Set image size
picture.Width = 120.0
picture.Height = 180.0

# Set a text wrapping style for the image  (note that the position settings are not applicable when the text wrapping style is Inline)
picture.TextWrappingStyle = TextWrappingStyle.Through

# Save the result document
doc.SaveToFile("WordImage.docx", FileFormat.Docx)
doc.Close()

Python: Insert Images in Word

Apply for a Temporary License

If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.

Published in Image and Shape
Tuesday, 05 September 2023 01:40

Python: Create, Read, or Update a Word Document

Creating, reading, and updating Word documents is a common need for many developers working with the Python programming language. Whether it's generating reports, manipulating existing documents, or automating document creation processes, having the ability to work with Word documents programmatically can greatly enhance productivity and efficiency. In this article, you will learn how to create, read, or update Word documents in Python using Spire.Doc for Python.

Install Spire.Doc for Python

This scenario requires Spire.Doc for Python and plum-dispatch v1.7.4. They can be easily installed in your Windows through the following pip command.

pip install Spire.Doc

If you are unsure how to install, please refer to this tutorial: How to Install Spire.Doc for Python on Windows

Create a Word Document from Scratch in Python

Spire.Doc for Python offers the Document class to represent a Word document model. A document must contain at least one section (represented by the Section class) and each section is a container for various elements such as paragraphs, tables, charts, and images. This example shows you how to create a simple Word document containing several paragraphs using Spire.Doc for Python.

  • Create a Document object.
  • Add a section using Document.AddSection() method.
  • Set the page margins through Section.PageSetUp.Margins property.
  • Add several paragraphs to the section using Section.AddParagraph() method.
  • Add text to the paragraphs using Paragraph.AppendText() method.
  • Create a ParagraphStyle object, and apply it to a specific paragraph using Paragraph.ApplyStyle() method.
  • Save the document to a Word file using Document.SaveToFile() method.
  • Python
from spire.doc import *	
from spire.doc.common import *

# Create a Document object
doc = Document()

# Add a section
section = doc.AddSection()

# Set the page margins
section.PageSetup.Margins.All = 40

# Add a title
titleParagraph = section.AddParagraph()
titleParagraph.AppendText("Introduction of Spire.Doc for Python")

# Add two paragraphs
bodyParagraph_1 = section.AddParagraph()
bodyParagraph_1.AppendText("Spire.Doc for Python is a professional Python library designed for developers to " +
                           "create, read, write, convert, compare and print Word documents in any Python application " +
                           "with fast and high-quality performance.")

bodyParagraph_2 = section.AddParagraph()
bodyParagraph_2.AppendText("As an independent Word Python API, Spire.Doc for Python doesn't need Microsoft Word to " +
                           "be installed on neither the development nor target systems. However, it can incorporate Microsoft Word " +
                           "document creation capabilities into any developers' Python applications.")

# Apply heading1 to the title
titleParagraph.ApplyStyle(BuiltinStyle.Heading1)

# Create a style for the paragraphs
style2 = ParagraphStyle(doc)
style2.Name = "paraStyle"
style2.CharacterFormat.FontName = "Arial"
style2.CharacterFormat.FontSize = 13
doc.Styles.Add(style2)
bodyParagraph_1.ApplyStyle("paraStyle")
bodyParagraph_2.ApplyStyle("paraStyle")

# Set the horizontal alignment of the paragraphs
titleParagraph.Format.HorizontalAlignment = HorizontalAlignment.Center
bodyParagraph_1.Format.HorizontalAlignment = HorizontalAlignment.Left
bodyParagraph_2.Format.HorizontalAlignment = HorizontalAlignment.Left

# Set the after spacing
titleParagraph.Format.AfterSpacing = 10
bodyParagraph_1.Format.AfterSpacing = 10

# Save to file
doc.SaveToFile("output/WordDocument.docx", FileFormat.Docx2019)

Python: Create, Read, or Update a Word Document

Read Text of a Word Document in Python

To get the text of an entire Word document, you could simply use Document.GetText() method. The following are the detailed steps.

  • Create a Document object.
  • Load a Word document using Document.LoadFromFile() method.
  • Get text from the entire document using Document.GetText() method.
  • Python
from spire.doc import *
from spire.doc.common import *

# Create a Document object
doc = Document()

# Load a Word file
doc.LoadFromFile("C:\\Users\\Administrator\\Desktop\\WordDocument.docx")

# Get text from the entire document
text = doc.GetText()

# Print text
print(text)

Python: Create, Read, or Update a Word Document

Update a Word Document in Python

To access a specific paragraph, you can use the Section.Paragraphs[index] property. If you want to modify the text of the paragraph, you can reassign text to the paragraph through the Paragraph.Text property. The following are the detailed steps.

  • Create a Document object.
  • Load a Word document using Document.LoadFromFile() method.
  • Get a specific section through Document.Sections[index] property.
  • Get a specific paragraph through Section.Paragraphs[index] property.
  • Change the text of the paragraph through Paragraph.Text property.
  • Save the document to another Word file using Document.SaveToFile() method.
  • Python
from spire.doc import *
from spire.doc.common import *

# Create a Document object
doc = Document()

# Load a Word file
doc.LoadFromFile("C:\\Users\\Administrator\\Desktop\\WordDocument.docx")

# Get a specific section
section = doc.Sections.get_Item(0)

# Get a specific paragraph
paragraph = section.Paragraphs.get_Item(1)

# Change the text of the paragraph
paragraph.Text = "The title has been changed"

# Save to file
doc.SaveToFile("output/Updated.docx", FileFormat.Docx2019)

Python: Create, Read, or Update a Word Document

Apply for a Temporary License

If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.

Published in Document Operation

Adding background colors or pictures to your Word documents is a powerful way to enhance their visual appeal and captivate your audience. Whether you're creating a professional report, a creative flyer, or a personal invitation, incorporating a well-chosen background color or image can transform an ordinary document into a visually captivating piece. In this article, we will demonstrate how to add a background color or picture to a Word document in Python using Spire.Doc for Python.

Install Spire.Doc for Python

This scenario requires Spire.Doc for Python and plum-dispatch v1.7.4. They can be easily installed in your Windows through the following pip command.

pip install Spire.Doc

If you are unsure how to install, please refer to this tutorial: How to Install Spire.Doc for Python on Windows

Add a Background Color to Word in Python

You can set a background color for a Word document by changing its background type to "Color" and then selecting a color as the background. The detailed steps are as follows.

  • Create a Document object.
  • Load a Word document using Document.LoadFromFile() method.
  • Get the background of the document using Document.Background property.
  • Set the background type as Color using Background.Type property.
  • Set a color as the background using Background.Color property.
  • Save the resulting document using Document.SaveToFile() method.
  • Python
from spire.doc import *
from spire.doc.common import *

# Create a Document object
document = Document()
# Load a Word document
document.LoadFromFile("Sample.docx")

# Get the document's background
background = document.Background

# Set the background type as Color
background.Type = BackgroundType.Color
# Set the background color
background.Color = Color.get_AliceBlue()

#save the resulting document
document.SaveToFile("AddBackgroundColor.docx", FileFormat.Docx2016)
document.Close()

Python: Add Background Color or Picture to Word Documents

Add a Gradient Background to Word in Python

A gradient background refers to a background style that transitions smoothly between two or more colors. To add a gradient background, you need to change the background type as "Gradient", specify the gradient colors and then set the gradient shading variant and style. The detailed steps are as follows.

  • Create a Document object.
  • Load a Word document using Document.LoadFromFile() method.
  • Get the background of the document using Document.Background property.
  • Set the background type as Gradient using Background.Type property.
  • Set two gradient colors using Background.Gradient.Color1 and Background.Gradient.Color2 properties.
  • Set gradient shading variant and style using Background.Gradient.ShadingVariant and Background.Gradient.ShadingStyle properties.
  • Save the resulting document using Document.SaveToFile() method.
  • Python
from spire.doc import *
from spire.doc.common import *

# Create a Document object
document = Document()
# Load a Word document
document.LoadFromFile("Sample.docx")

# Get the document's background
background = document.Background

# Set the background type as Gradient
background.Type = BackgroundType.Gradient

# Set two gradient colors
background.Gradient.Color1 = Color.get_White()
background.Gradient.Color2 = Color.get_LightBlue()

# Set gradient shading variant and style
background.Gradient.ShadingVariant = GradientShadingVariant.ShadingDown
background.Gradient.ShadingStyle = GradientShadingStyle.Horizontal

#Save the resulting document
document.SaveToFile("AddGradientBackground.docx", FileFormat.Docx2016)
document.Close()

Python: Add Background Color or Picture to Word Documents

Add a Background Picture to Word in Python

To add a background picture to a Word document, you need to change the background type as "Picture", and then set a picture as the background. The detailed steps are as follows.

  • Create a Document object.
  • Load a Word document using Document.LoadFromFile() method.
  • Get the background of the document using Document.Background property.
  • Set the background type as Picture using Background.Type property.
  • Set a picture as the background using Background.SetPicture() method.
  • Save the resulting document using Document.SaveToFile() method.
  • Python
from spire.doc import *
from spire.doc.common import *

# Create a Document object
document = Document()
# Load a Word document
document.LoadFromFile("Sample.docx")

# Get the document's background
background = document.Background

# Set the background type as Picture
background.Type = BackgroundType.Picture

# Set the background picture
background.SetPicture("background.jpg")

#save the resulting document
document.SaveToFile("AddBackgroundPicture.docx", FileFormat.Docx2016)
document.Close()

Python: Add Background Color or Picture to Word Documents

Apply for a Temporary License

If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.

Published in Page Background
Page 3 of 3