Paragraph indentations determine the horizontal space between the page margins and the text of paragraphs. They are an important formatting tool used in various types of written documents, such as essays, reports, and articles, to improve readability and create a visual distinction between paragraphs. In this article, we will demonstrate how to set paragraph indentations in 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

Set Paragraph Indentations in Word in Python

Microsoft Word provides four types of paragraph indent options that enable you to format your document efficiently. These options are as follows:

  • First Line Indent: The first line indent refers to the horizontal space between the left margin and the beginning of the first line of a paragraph. It indents only the first line while keeping the subsequent lines aligned with the left margin.
  • Left Indent: The left indent, also known as the paragraph indent or the left margin indent, determines the horizontal distance between the left margin and the entire paragraph. It uniformly indents the entire paragraph from the left margin.
  • Right Indent: The right indent sets the horizontal distance between the right margin and the entire paragraph. It indents the paragraph from the right side, shifting the text towards the left.
  • Hanging Indent: The hanging indent is a unique indentation style where the first line remains aligned with the left margin, while all subsequent lines of the paragraph are indented inward. This creates a "hanging" effect, commonly used for bibliographies, references, or citations.

Spire.Doc for Python supports all these types of indents. The table below lists some of the core classes and methods that are used to set different paragraph indents in Word with Spire.Doc for Python:

Name Description
ParagraphFormat Class Represents the format of a paragraph.
ParagraphFormat.SetLeftIndent() Method Sets the left indent value for paragraph.
ParagraphFormat.SetRightIndent() Method Sets the right indent value for paragraph.
ParagraphFormat.SetFirstLineIndent() Method Sets the first line or hanging indent value.  Positive value represents first-line indent, and negative value represents hanging indent.

The steps below explain how to set paragraph indents in a Word document using Spire.Doc for Python:

  • Create a Document instance.
  • Load a sample Word document using Document.LoadFromFile() method.
  • Get a specific section using Document.Sections[] property.
  • Get a specific paragraph using Section.Paragraphs[] property.
  • Get the paragraph format using Paragraph.Format property, and then set the paragraph indent using the above listed methods of ParagraphFormat class.
  • Save the document to another file using Document.SaveToFile() method.
  • Python
from spire.doc import *
from spire.doc.common import *

# Create a Document instance
doc = Document()
# Load a sample Word document
doc.LoadFromFile("Sample6.docx")

# Get the first section
section = doc.Sections[0]

# Get the first paragraph and set the left indent
para1 = section.Paragraphs[0]
para1.Format.SetLeftIndent(30)

# Get the second paragraph and set the right indent
para2 = section.Paragraphs[1]
para2.Format.SetRightIndent(30)

# Get the third paragraph and set the first line indent
para3 = section.Paragraphs[2]
para3.Format.SetFirstLineIndent(30)

# Get the fourth paragraph and set the hanging indent
para4 = section.Paragraphs[3]
para4.Format.SetFirstLineIndent(-30)

# Save the document to file
doc.SaveToFile("SetIndents.docx", FileFormat.Docx2013)
doc.Close()

Python: Set Paragraph Indentations 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 Paragraph
Thursday, 11 April 2024 05:59

Python: Align Text in Word

Text alignment in Word refers to the way text is aligned along the horizontal axis of the page. Proper text alignment can significantly affect the overall appearance and aesthetics of a document, making it more engaging for readers. There are several types of text alignment available in Word:

  • Left Alignment: Text is aligned along the left margin.
  • Center Alignment: Text is centered between the left and right margins.
  • Right Alignment: Text is aligned along the right margin.
  • Justified Alignment: Text is aligned along both the left and right margins.
  • Distributed Alignment: Text is evenly distributed between the left and right margins.

In this article, you will learn how to set different text alignments for paragraphs 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 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

Align Text in Word in Python

With Spire.Doc for Python, you can get the paragraph formatting through the Paragraph.Format property, and then use the HorizontalAlignment property of the ParagraphFormat class to align text left/ right, center text, justify text, or distribute text in Word paragraphs. The following are the detailed steps:

  • Create a Document instance.
  • Add a section to the document using Document.AddSection() method.
  • Add a paragraph to the section using Section.AddParagraph() method, and then append text to the paragraph.
  • Get the paragraph formatting using Paragraph.Format property.
  • Set left/center/right/justified/distributed text alignment for the paragraph using ParagraphFormat.HorizontalAlignment property.
  • Save the result document using Document.SaveToFile() method.
  • Python
from spire.doc import *
from spire.doc.common import *

# Create a Document instance
document = Document()

# Add a section
sec = document.AddSection()

# Add a paragraph and make it left-aligned
para = sec.AddParagraph()
para.AppendText("This paragraph is left-aligned.")
para.Format.HorizontalAlignment = HorizontalAlignment.Left

# Add a paragraph and make it centered
para = sec.AddParagraph()
para.AppendText("This paragraph is centered.")
para.Format.HorizontalAlignment = HorizontalAlignment.Center

# Add a paragraph and make it right-aligned
para = sec.AddParagraph()
para.AppendText("This paragraph is right-aligned.")
para.Format.HorizontalAlignment = HorizontalAlignment.Right

# Add a paragraph and make it justified
para = sec.AddParagraph()
para.AppendText("This paragraph is justified.")
para.Format.HorizontalAlignment = HorizontalAlignment.Justify

# Add a paragraph and make it distributed
para = sec.AddParagraph()
para.AppendText("This paragraph is distributed.")
para.Format.HorizontalAlignment = HorizontalAlignment.Distribute

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

Python: Align Text 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 Paragraph

Paragraph spacing and line spacing are crucial formatting options in Microsoft Word that greatly influence the visual presentation and readability of your documents. Paragraph spacing determines the vertical space between paragraphs, creating a distinct separation between each paragraph. Line spacing, on the other hand, controls the vertical distance between lines within a paragraph, directly impacting the density and readability of the text. By appropriately setting paragraph spacing and line spacing, you can easily create visually appealing and easy-to-read documents. In this article, we will explain how to set paragraph spacing and line spacing in 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 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

Set Paragraph Spacing in Word in Python

Spire.Doc for Python provides the Paragraph.Format.BeforeSpacing and Paragraph.Format.AfterSpacing properties to adjust the spacing before and after a paragraph. The detailed steps are as follows.

  • Create an object of the Document class.
  • Add a section to the document using Document.AddSection() method.
  • Add two paragraphs to the section using Section.AddParagraph() methods.
  • Set the spacing before and after the paragraphs using Paragraph.Format.BeforeSpacing and Paragraph.Format.AfterSpacing properties.
  • Save the result document using Document.SaveToFile() method.
  • Python
from spire.doc import *
from spire.doc.common import *

# Create an object of the Document class
document = Document()
# Add a section to the document
section = document.AddSection()

# Add two paragraphs to the section
para1 = section.AddParagraph()
para1.Format.HorizontalAlignment = HorizontalAlignment.Center
textRange1 = para1.AppendText("Spire.Doc for Python")
textRange1.CharacterFormat.TextColor = Color.get_Blue()
textRange1.CharacterFormat.FontName = "Calibri"
textRange1.CharacterFormat.FontSize = 15

para2 = section.AddParagraph()
textRange2 = para2.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.")
textRange2.CharacterFormat.FontName = "Calibri"
textRange2.CharacterFormat.FontSize = 12

# Set the spacing after the first paragraph
para1.Format.AfterAutoSpacing = False
para1.Format.AfterSpacing = 10

# Set the spacing before and after the second paragraph
para2.Format.BeforeAutoSpacing = False
para2.Format.BeforeSpacing = 10
para2.Format.AfterAutoSpacing = False
para2.Format.AfterSpacing = 10

# Save the result file
document.SaveToFile("SetParagraphSpacing.docx", FileFormat.Docx2013)
document.Close()

Python: Set Paragraph Spacing and Line Spacing in Word

Set Line Spacing in Word in Python

To set the pacing between lines in a paragraph, you can use the Paragraph.Format.LineSpacing property. The detailed steps are as follows.

  • Create an object of the Document class.
  • Add a section to the document using Document.AddSection() method.
  • Add a paragraph to the section using Section.AddParagraph() methods.
  • Set the spacing between lines in the paragraph using Paragraph.Format.LineSpacing property.
  • Save the result document using Document.SaveToFile() method.
  • Python
from spire.doc import *
from spire.doc.common import *

# Create an object of the Document class
document = Document()
# Add a section
section = document.AddSection()

# Add a paragraph to the section
para = section.AddParagraph()
textRange = para.AppendText("Spire.Doc for Python is a proven reliable MS Word API for Python which enables to perform many Word document processing tasks. Spire.Doc for Python 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.")
textRange.CharacterFormat.FontName = "Calibri"
textRange.CharacterFormat.FontSize = 12

# Set line spacing rule
para.Format.LineSpacingRule = LineSpacingRule.Multiple
# Set line spacing value (The line spacing rule "Multiple" with value 18 sets the line spacing to "1.5 lines", value 12 sets the line spacing to "Single")
para.Format.LineSpacing = 18

# Save the result file
document.SaveToFile("SetLineSpacing.docx", FileFormat.Docx2013)
document.Close()

Python: Set Paragraph Spacing and Line Spacing 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 Paragraph

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 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

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 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

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 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

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