Setting the background colors for paragraphs and text in Word documents can significantly enhance the presentation and readability of content. Customizing background color is an effective approach to emphasize key information, categorize content, and add a personalized touch, thereby making it easy to create polished and professional documents. By carefully selecting and applying background colors, documents can be transformed into visually appealing works that effectively convey information and engage the reader. This article shows how to use Spire.Doc for Python to set background colors for paragraphs and text in Word documents, unlocking new possibilities for document styling and customization.

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 VS Code 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 in VS Code

Set Background Color for Paragraphs Using Python

By using Spire.Doc for Python, developers can get any paragraph in any section. After getting a paragraph, developers can apply a background color to it by assigning a Color object to Paragraph.Format.BackColor property. Below are the detailed steps:

  • Create an instance of Document class and load a Word document using Document.LoadFromFile() method.
  • Get a section using Document.Sections.get_Item() method.
  • Get a paragraph in the section using Section.Paragraphs.get_Item() method.
  • Set the background color of the paragraph through Paragraph.Format.BackColor property.
  • Save the document using Document.SaveToFile() method.
  • Python
from spire.doc import *
from spire.doc.common import *

# Create an instance of Document class and load a Word document
doc = Document()
doc.LoadFromFile("Sample.docx")

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

# Get the fifth paragraph
paragraph = section.Paragraphs.get_Item(4)

# Set background color for the paragraph
paragraph.Format.BackColor = Color.get_DarkGreen()

# Save the document
doc.SaveToFile("output/ParagraphBackground.docx")
doc.Close()

Python: Set Background Colors for Word Paragraphs or Text

Set Background Colors for Selected Text Using Python

Spire.Doc for Python enables developers to find all the occurrences of specific text in a Word document with Document.FindAllString() method. After getting the finding results, developers can set the background for them through TextRange.CharacterFormat.TextBackgroundColor property. The detailed steps are as follows:

  • Create an instance of Document class and load a Word document using Document.LoadFromFile() method.
  • Find all the occurrences of specific text using Document.FindAllString() method.
  • Loop through the occurrences, get each occurrence as a text range using TextSelection.GetAsOneRange(True) method, and set the background color of each occurrence through TextRange.CharacterFormat.TextBackgroundColor property. It is also possible to get only one occurrence from the result list and set the background color for the occurrence.
  • Save the document using Document.SaveToFile() method.
  • Python
from spire.doc import *
from spire.doc.common import *

# Create an instance of Document class and load a Word document
doc = Document()
doc.LoadFromFile("Sample.docx")

# Find text in the Word document
findResults = doc.FindAllString("advantages of LCD screens", False, False)

# Loop through the finding results to set background color for all occurrences
for text in findResults:
    # Get an occurrence as a text range
    textRange = text.GetAsOneRange(True)
    # Set the background color of the text range
    textRange.CharacterFormat.TextBackgroundColor = Color.get_LightCoral()

# Set the background color of a sepecified occurrence
# Get an occurrence as one text range
# textRange = findResults[1].GetAsOneRange()
# Set the background color of the text range
# textRange.CharacterFormat.BackgroundColor = Color.get_DarkCyan()

# Save the document
doc.SaveToFile("output/TextBackground.docx")
doc.Close()

Python: Set Background Colors for Word Paragraphs or Text

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 Paragraph
Thursday, 09 November 2023 01:30

Python: Remove Paragraphs from Word Documents

When working with Word documents, sometimes you may need to adjust the content or layout of the document by deleting certain paragraphs. For example, when you have copied a very long paragraph from the Internet, you can delete redundant paragraphs as needed and keep only the useful ones. Or you can create a new document by deleting irrelevant paragraphs in an existing document. In this case, performing this process programmatically is a better option than tedious manual deletion, which can help you batch process a large number of documents in a short period of time. In this article, we will show you how to remove a specific paragraph or all paragraphs from 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 VS Code 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 in VS Code

Delete a Specific Paragraph from Word Documents

With Spire.Doc for Python library, you are allowed to remove specific paragraphs from Word documents. You just need to get the desired section, and then call the Section.Paragraphs.RemoveAt() method to remove the paragraphs you want. The detailed steps are as follows.

  • Create an object of Document class.
  • Load a Word document from disk using Document.LoadFromFile() method.
  • Get the first section of this file using Document.Sections[] property.
  • Remove the first paragraph from this section using Section.Paragraphs.RemoveAt() method.
  • Save the result file using Document.SaveToFile() method.
  • Python
from spire.doc import *
from spire.doc.common import *

inputFile = "C:/Users/Administrator/Desktop/Sample.docx"
outputFile = "C:/Users/Administrator/Desktop/RemoveParagraphs.docx"
    
#Create an object of Document class
document = Document()

#Load a sample file from disk
document.LoadFromFile(inputFile)

#Get the first section of this file
section=document.Sections[0]

#Remove the first paragraph from this section
section.Paragraphs.RemoveAt(0)

#Save the result file
document.SaveToFile(outputFile, FileFormat.Docx2013)
document.Close()

Python: Remove Paragraphs from Word Documents

Delete All Paragraphs from Word Documents

In addition, if you want to clear all paragraphs of the Word document at once, please loop through all sections first and call the Section.Paragraphs.Clear() method to do that. The detailed steps are as follows.

  • Create an object of Document class.
  • Load a Word document from disk using Document.LoadFromFile() method.
  • Loop through all sections first and remove all paragraphs in each section by using Section.Paragraphs.Clear() method.
  • Save the result file using Document.SaveToFile() method.
  • Python
from spire.doc import *
from spire.doc.common import *

inputFile = "C:/Users/Administrator/Desktop/Sample.docx"
outputFile = "C:/Users/Administrator/Desktop/RemoveAllParagraphs.docx"
    
#Create an object of Document class
document = Document()

#Load a sample file from disk
document.LoadFromFile(inputFile)

#Remove paragraphs from the body of every section in the document
for i in range(document.Sections.Count):
    section = document.Sections.get_Item(i)
    section.Paragraphs.Clear()

#Save the result file
document.SaveToFile(outputFile, FileFormat.Docx2013)
document.Close()

Python: Remove Paragraphs from 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 Paragraph
Thursday, 21 September 2023 00:56

Python: Remove Blank Lines from Word Documents

During the process of document creation, it is common to encounter numerous blank lines. These empty spaces can disrupt the flow of the content, clutter the layout, and undermine the overall aesthetic presentation of the document. In order to optimize the reading experience and ensure a well-structured document, it becomes crucial to eliminate the blank lines. This article will demonstrate how to delete blank lines from Word documents through Python programs 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 VS Code 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 in VS Code

Remove Blank Lines from Word Documents

Blank lines in a Word document appear as blank paragraphs, which are child objects of sections. Therefore, removing blank lines simply requires iterating through the sections, identifying and deleting empty paragraphs within them. The detailed steps are as follows:

  • Create an object of Document class.
  • Load a Word document using Document.LoadFromFile() method.
  • Iterate through each section and each child object of the sections.
  • First, check if a child object is of paragraph type. If it is, continue to check if the sub-object is an instance of the "Paragraph" class. If it is, further check if the paragraph has no text. If there is no text, delete the paragraph using Section.Body.ChildObjects.Remove() method.
  • Save the document using Document.SaveToFile() method.
  • Python
from spire.doc import *
from spire.doc.common import *

# Create an object of the Document class
doc = Document()

# Load a Word document
doc.LoadFromFile("Sample.docx")

# Iterate through each section in the document
for i in range(doc.Sections.Count):
    section = doc.Sections.get_Item(i)
    j = 0
    # Iterate through each child object in the section
    while j < section.Body.ChildObjects.Count:
        # Check if the child object is of type Paragraph
        if section.Body.ChildObjects[j].DocumentObjectType == DocumentObjectType.Paragraph:
            objItem = section.Body.ChildObjects[j]
            # Check if the child object is an instance of the Paragraph class
            if isinstance(objItem, Paragraph):
                paraObj = Paragraph(objItem)
                # Check if the paragraph text is empty
                if len(paraObj.Text) == 0:
                    # If the paragraph text is empty, remove the object from the section's child objects list
                    section.Body.ChildObjects.Remove(objItem)
                    j -= 1
        j += 1

# Save the document
doc.SaveToFile("output/RemoveBlankLines.docx")

Python: Remove Blank Lines from 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 Paragraph