Knowledgebase (2300)
Java: Create a Table Of Contents for a Newly Created Word Document
2024-05-06 01:12:30 Written by KoohjiCreating a table of contents in a Word document can help readers quickly understand the structure and content of the document, thereby enhancing its readability. The creation of a table of contents also aids authors in organizing the document's content, ensuring a clear structure and strong logical flow. When modifications or additional content need to be made to the document, the table of contents can help authors quickly locate the sections that require editing. This article will explain how to use Spire.Doc for Java to create a table of contents for a newly created Word document in a Java project.
- Java Create a Table Of Contents Using Heading Styles
- Java Create a Table Of Contents Using Outline Level Styles
- Java Create a Table Of Contents Using Image Captions
- Java Create a Table Of Contents Using Table Captions
Install Spire.Doc for Java
First, you're required to add the Spire.Doc.jar file as a dependency in your Java program. The JAR file can be downloaded from this link. If you use Maven, you can easily import the JAR file in your application by adding the following code to your project's pom.xml file.
<repositories>
<repository>
<id>com.e-iceblue</id>
<name>e-iceblue</name>
<url>https://repo.e-iceblue.com/nexus/content/groups/public/</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>e-iceblue</groupId>
<artifactId>spire.doc</artifactId>
<version>13.11.2</version>
</dependency>
</dependencies>
Java Create a Table Of Contents Using Heading Styles
In Spire.Doc, creating a table of contents using heading styles is the default method for generating a table of contents. By applying different levels of heading styles to sections and subsections in the document, the table of contents is automatically generated. Here are the detailed steps:
- Create a Document object.
- Add a section using the Document.addSection() method.
- Add a paragraph using the Section.addParagraph() method.
- Create a table of contents object using the Paragraph.appendTOC(int lowerLevel, int upperLevel) method.
- Create a CharacterFormat character format object and set the font.
- Apply a heading style to the paragraph using the Paragraph.applyStyle(BuiltinStyle.Heading_1) method.
- Add text content using the Paragraph.appendText() method.
- Set character formatting for the text using the TextRange.applyCharacterFormat() method.
- Update the table of contents using the Document.updateTableOfContents() method.
- Save the document using the Document.saveToFile() method.
- Java
import com.spire.doc.*;
import com.spire.doc.documents.*;
import com.spire.doc.fields.*;
import com.spire.doc.formatting.*;
public class CreateTOCByHeadingStyle {
public static void main(String[] args) {
// Create a new Document object
Document doc = new Document();
// Add a section to the document
Section section = doc.addSection();
// Add a table of contents paragraph
Paragraph TOCparagraph = section.addParagraph();
TOCparagraph.appendTOC(1, 3);
// Create a character format object and set the font
CharacterFormat characterFormat1 = new CharacterFormat(doc);
characterFormat1.setFontName("Microsoft YaHei");
// Create another character format object and set the font and font size
CharacterFormat characterFormat2 = new CharacterFormat(doc);
characterFormat2.setFontName("Microsoft YaHei");
characterFormat2.setFontSize(12);
// Add a paragraph with Heading 1 style
Paragraph paragraph = section.getBody().addParagraph();
paragraph.applyStyle(BuiltinStyle.Heading_1);
// Add text and apply character format
TextRange textRange1 = paragraph.appendText("Overview");
textRange1.applyCharacterFormat(characterFormat1);
// Add regular content
paragraph = section.getBody().addParagraph();
TextRange textRange2 = paragraph.appendText("Spire.Doc for Java is a professional Word API that empowers Java applications to create, convert, manipulate and print Word documents without dependency on Microsoft Word.");
textRange2.applyCharacterFormat(characterFormat2);
// Add a paragraph with Heading 1 style
paragraph = section.getBody().addParagraph();
paragraph.applyStyle(BuiltinStyle.Heading_1);
textRange1 = paragraph.appendText("MAIN FUNCTION");
textRange1.applyCharacterFormat(characterFormat1);
// Add a paragraph with Heading 2 style
paragraph = section.getBody().addParagraph();
paragraph.applyStyle(BuiltinStyle.Heading_2);
textRange1 = paragraph.appendText("Only Spire.Doc for Java, No Microsoft Office");
textRange1.applyCharacterFormat(characterFormat1);
// Add regular content
paragraph = section.getBody().addParagraph();
textRange2 = paragraph.appendText("Spire.Doc for Java is a totally independent Word component, Microsoft Office is not required in order to use Spire.Doc for Java.");
textRange2.applyCharacterFormat(characterFormat2);
// Add a paragraph with Heading 3 style
paragraph = section.getBody().addParagraph();
paragraph.applyStyle(BuiltinStyle.Heading_3);
textRange1 = paragraph.appendText("Word Versions");
textRange1.applyCharacterFormat(characterFormat1);
paragraph = section.getBody().addParagraph();
textRange2 = paragraph.appendText("Word97-03 Word2007 Word2010 Word2013 Word2016 Word2019");
textRange2.applyCharacterFormat(characterFormat2);
// Add a paragraph with Heading 2 style
paragraph = section.getBody().addParagraph();
paragraph.applyStyle(BuiltinStyle.Heading_2);
textRange1 = paragraph.appendText("High Quality File Conversion");
textRange1.applyCharacterFormat(characterFormat1);
// Add regular content
paragraph = section.getBody().addParagraph();
textRange2 = paragraph.appendText("Spire.Doc for Java allows converting popular file formats like HTML, RTF, ODT, TXT, WordML, WordXML to Word and exporting Word to commonly used file formats such as PDF, XPS, Image, EPUB, HTML, TXT, ODT, RTF, WordML, WordXML in high quality. Moreover, conversion between Doc and Docx is supported as well.");
textRange2.applyCharacterFormat(characterFormat2);
// Add a paragraph with Heading 2 style
paragraph = section.getBody().addParagraph();
paragraph.applyStyle(BuiltinStyle.Heading_2);
textRange1 = paragraph.appendText("Support a Rich Set of Word Elements");
textRange1.applyCharacterFormat(characterFormat1);
// Add regular content
paragraph = section.getBody().addParagraph();
textRange2 = paragraph.appendText("Spire.Doc for Java supports a rich set of Word elements, including section, header, footer, footnote, endnote, paragraph, list, table, text, TOC, form field, mail merge, hyperlink, bookmark, watermark, image, style, shape, textbox, ole, WordArt, background settings, digital signature, document encryption and many more.");
textRange2.applyCharacterFormat(characterFormat2);
// Update the table of contents
doc.updateTableOfContents();
// Save the document
doc.saveToFile("Table of Contents Created Using Heading Styles.docx", FileFormat.Docx_2016);
// Dispose of resources
doc.dispose();
}
}

Java Create a Table Of Contents Using Outline Level Styles
You can also use outline level styles to create a table of contents in a Word document. In Spire.Doc, by setting the OutlineLevel property of a paragraph, you can specify the hierarchical style of the paragraph in the outline. Then, by calling the TableOfContent.setTOCLevelStyle() method, you can apply these outline level styles to the generation rules of the table of contents. Here are the detailed steps:
- Create a Document object.
- Add a section using the Document.addSection() method.
- Create a ParagraphStyle object and set the outline level using ParagraphStyle.getParagraphFormat().setOutlineLevel(OutlineLevel.Level_1).
- Add the created ParagraphStyle object to the document using Document.getStyles().add() method.
- Add a paragraph using Section.addParagraph() method.
- Create a table of contents object using Paragraph.appendTOC(int lowerLevel, int upperLevel) method.
- Set the default setting for creating the table of contents using heading styles to false, TableOfContent.setUseHeadingStyles(false).
- Apply the outline level styles to the table of contents rules using TableOfContent.setTOCLevelStyle(int levelNumber, string styleName) method.
- Create a CharacterFormat object and set the font.
- Apply the style to the paragraph using Paragraph.applyStyle(ParagraphStyle.getName()) method.
- Add text content using Paragraph.appendText() method.
- Apply character formatting to the text using TextRange.applyCharacterFormat() method.
- Update the table of contents using Document.updateTableOfContents() method.
- Save the document using Document.saveToFile() method.
- Java
import com.spire.doc.*;
import com.spire.doc.documents.*;
import com.spire.doc.fields.*;
import com.spire.doc.formatting.*;
public class CreateTOCByOutlineLevelStyle {
public static void main(String[] args) {
// Create a new Document object
Document doc = new Document();
Section section = doc.addSection();
// Define Outline Level 1
ParagraphStyle titleStyle1 = new ParagraphStyle(doc);
titleStyle1.setName("T1S");
titleStyle1.getParagraphFormat().setOutlineLevel(OutlineLevel.Level_1);
titleStyle1.getCharacterFormat().setBold(true);
titleStyle1.getCharacterFormat().setFontName("Microsoft YaHei");
titleStyle1.getCharacterFormat().setFontSize(18f);
titleStyle1.getParagraphFormat().setHorizontalAlignment(HorizontalAlignment.Left);
doc.getStyles().add(titleStyle1);
// Define Outline Level 2
ParagraphStyle titleStyle2 = new ParagraphStyle(doc);
titleStyle2.setName("T2S");
titleStyle2.getParagraphFormat().setOutlineLevel(OutlineLevel.Level_2);
titleStyle2.getCharacterFormat().setBold(true);
titleStyle2.getCharacterFormat().setFontName("Microsoft YaHei");
titleStyle2.getCharacterFormat().setFontSize(16f);
titleStyle2.getParagraphFormat().setHorizontalAlignment(HorizontalAlignment.Left);
doc.getStyles().add(titleStyle2);
// Define Outline Level 3
ParagraphStyle titleStyle3 = new ParagraphStyle(doc);
titleStyle3.setName("T3S");
titleStyle3.getParagraphFormat().setOutlineLevel(OutlineLevel.Level_3);
titleStyle3.getCharacterFormat().setBold(true);
titleStyle3.getCharacterFormat().setFontName("Microsoft YaHei");
titleStyle3.getCharacterFormat().setFontSize(14f);
titleStyle3.getParagraphFormat().setHorizontalAlignment(HorizontalAlignment.Left);
doc.getStyles().add(titleStyle3);
// Add Table of Contents paragraph
Paragraph TOCparagraph = section.addParagraph();
TableOfContent toc = TOCparagraph.appendTOC(1, 3);
toc.setUseHeadingStyles(false);
toc.setUseHyperlinks(true);
toc.setUseTableEntryFields(false);
toc.setRightAlignPageNumbers(true);
toc.setTOCLevelStyle(1, titleStyle1.getName());
toc.setTOCLevelStyle(2, titleStyle2.getName());
toc.setTOCLevelStyle(3, titleStyle3.getName());
// Define Character Format
CharacterFormat characterFormat = new CharacterFormat(doc);
characterFormat.setFontName("Microsoft YaHei");
characterFormat.setFontSize(12);
// Add paragraph and apply Outline Level Style 1
Paragraph paragraph = section.getBody().addParagraph();
paragraph.applyStyle(titleStyle1.getName());
paragraph.appendText("Overview");
// Add paragraph and set text content
paragraph = section.getBody().addParagraph();
TextRange textRange = paragraph.appendText("Spire.Doc for Java is a professional Word API that empowers Java applications to create, convert, manipulate and print Word documents without dependency on Microsoft Word.");
textRange.applyCharacterFormat(characterFormat);
// Add paragraph and apply Outline Level Style 1
paragraph = section.getBody().addParagraph();
paragraph.applyStyle(titleStyle1.getName());
paragraph.appendText("MAIN FUNCTION");
// Add paragraph and apply Outline Level Style 2
paragraph = section.getBody().addParagraph();
paragraph.applyStyle(titleStyle2.getName());
paragraph.appendText("Only Spire.Doc for Java, No Microsoft Office");
// Add paragraph and set text content
paragraph = section.getBody().addParagraph();
textRange = paragraph.appendText("Spire.Doc for Java is a totally independent Word component, Microsoft Office is not required in order to use Spire.Doc for Java.");
textRange.applyCharacterFormat(characterFormat);
// Add paragraph and apply Outline Level Style 3
paragraph = section.getBody().addParagraph();
paragraph.applyStyle(titleStyle3.getName());
paragraph.appendText("Word Versions");
// Add paragraph and set text content
paragraph = section.getBody().addParagraph();
textRange = paragraph.appendText("Word97-03 Word2007 Word2010 Word2013 Word2016 Word2019");
textRange.applyCharacterFormat(characterFormat);
// Add paragraph and apply Outline Level Style 2
paragraph = section.getBody().addParagraph();
paragraph.applyStyle(titleStyle2.getName());
paragraph.appendText("High Quality File Conversion");
// Add paragraph and set text content
paragraph = section.getBody().addParagraph();
textRange = paragraph.appendText("Spire.Doc for Java allows converting popular file formats like HTML, RTF, ODT, TXT, WordML, WordXML to Word and exporting Word to commonly used file formats such as PDF, XPS, Image, EPUB, HTML, TXT, ODT, RTF, WordML, WordXML in high quality. Moreover, conversion between Doc and Docx is supported as well.");
textRange.applyCharacterFormat(characterFormat);
// Add paragraph and apply Outline Level Style 2
paragraph = section.getBody().addParagraph();
paragraph.applyStyle(titleStyle2.getName());
paragraph.appendText("Support a Rich Set of Word Elements");
// Add paragraph and set text content
paragraph = section.getBody().addParagraph();
textRange = paragraph.appendText("Spire.Doc for Java supports a rich set of Word elements, including section, header, footer, footnote, endnote, paragraph, list, table, text, TOC, form field, mail merge, hyperlink, bookmark, watermark, image, style, shape, textbox, ole, WordArt, background settings, digital signature, document encryption and many more.");
textRange.applyCharacterFormat(characterFormat);
// Update the table of contents
doc.updateTableOfContents();
// Save the document
doc.saveToFile("Creating Table of Contents with Outline Level Styles.docx", FileFormat.Docx_2016);
// Dispose of resources
doc.dispose();
}
}

Java Create a Table Of Contents Using Image Captions
Using the Spire.Doc library, you can create a table of contents based on image titles using the TableOfContent tocForImage = new TableOfContent(Document, " \\h \\z \\c \"Image\"") method. Here are the detailed steps:
- Create a Document object.
- Add a section using the Document.addSection() method.
- Create a table of contents object TableOfContent tocForImage = new TableOfContent(Document, " \\h \\z \\c \"Image\"") and specify the style of the table of contents.
- Add a paragraph using the Section.addParagraph() method.
- Add the table of contents object to the paragraph using the Paragraph.getItems().add(tocForImage) method.
- Add a field separator using the Paragraph.appendFieldMark(FieldMarkType.Field_Separator) method.
- Add the text content "TOC" using the Paragraph.appendText("TOC") method.
- Add a field end mark using the Paragraph.appendFieldMark(FieldMarkType.Field_End) method.
- Add an image using the Paragraph.appendPicture() method.
- Add a paragraph for the image title, including product information and formatting, using the DocPicture.addCaption() method.
- Update the table of contents to reflect changes in the document using the Document.updateTableOfContents(tocForImage) method.
- Save the document using the Document.saveToFile() method.
- Java
import com.spire.doc.*;
import com.spire.doc.documents.*;
import com.spire.doc.fields.*;
public class CreateTOCByImageCaption {
public static void main(String[] args) {
// Create a new document object
Document doc = new Document();
// Add a section to the document
Section section = doc.addSection();
// Create a table of content object for images
TableOfContent tocForImage = new TableOfContent(doc, " \\h \\z \\c \"Images\"");
// Add a paragraph to the section
Paragraph tocParagraph = section.getBody().addParagraph();
// Add the table of content object to the paragraph
tocParagraph.getItems().add(tocForImage);
// Add a field separator
tocParagraph.appendFieldMark(FieldMarkType.Field_Separator);
// Add text content
tocParagraph.appendText("TOC");
// Add a field end mark
tocParagraph.appendFieldMark(FieldMarkType.Field_End);
// Add a blank paragraph to the section
section.getBody().addParagraph();
// Add a paragraph to the section
Paragraph paragraph = section.getBody().addParagraph();
// Add an image
DocPicture docPicture = paragraph.appendPicture("images/Doc-Java.png");
docPicture.setWidth(100);
docPicture.setHeight(100);
// Add a paragraph for the image caption
Paragraph pictureCaptionParagraph = (Paragraph) docPicture.addCaption("Images", CaptionNumberingFormat.Number, CaptionPosition.Below_Item);
pictureCaptionParagraph.appendText(" Spire.Doc for Java Product ");
pictureCaptionParagraph.getFormat().setAfterSpacing(20);
// Continue adding paragraphs to the section
paragraph = section.getBody().addParagraph();
docPicture = paragraph.appendPicture("images/PDF-Java.png");
docPicture.setWidth(100);
docPicture.setHeight(100);
pictureCaptionParagraph = (Paragraph) docPicture.addCaption("Images", CaptionNumberingFormat.Number, CaptionPosition.Below_Item);
pictureCaptionParagraph.appendText(" Spire.PDF for Java Product ");
pictureCaptionParagraph.getFormat().setAfterSpacing(20);
paragraph = section.getBody().addParagraph();
docPicture = paragraph.appendPicture("images/XLS-Java.png");
docPicture.setWidth(100);
docPicture.setHeight(100);
pictureCaptionParagraph = (Paragraph) docPicture.addCaption("Images", CaptionNumberingFormat.Number, CaptionPosition.Below_Item);
pictureCaptionParagraph.appendText(" Spire.XLS for Java Product ");
pictureCaptionParagraph.getFormat().setAfterSpacing(20);
paragraph = section.getBody().addParagraph();
docPicture = paragraph.appendPicture("images/PPT-Java.png");
docPicture.setWidth(100);
docPicture.setHeight(100);
pictureCaptionParagraph = (Paragraph) docPicture.addCaption("Images", CaptionNumberingFormat.Number, CaptionPosition.Below_Item);
pictureCaptionParagraph.appendText(" Spire.Presentation for Java Product ");
// Update the table of contents
doc.updateTableOfContents(tocForImage);
// Save the document to a file
doc.saveToFile("CreateTOCWithImageCaptions.docx", FileFormat.Docx_2016);
// Dispose of the document object
doc.dispose();
}
}

Java Create a Table Of Contents Using Table Captions
You can also create a table of contents using table titles by the method TableOfContent tocForImage = new TableOfContent(Document, " \\h \\z \\c \"Table\""). Here are the detailed steps:
- Create a Document object.
- Add a section using the Document.addSection() method.
- Create a table of contents object TableOfContent tocForTable = new TableOfContent(Document, " \\h \\z \\c \"Table\"") and specify the style of the table of contents.
- Add a paragraph using the Section.addParagraph() method.
- Add the table of contents object to the paragraph using the Paragraph.getItems().add(tocForTable) method.
- Add a field separator using the Paragraph.appendFieldMark(FieldMarkType.Field_Separator) method.
- Add the text "TOC" using the Paragraph.appendText("TOC") method.
- Add a field end mark using the Paragraph.appendFieldMark(FieldMarkType.Field_End) method.
- Add a table using the Section.addTable() method and set the number of rows and columns using the Table.resetCells(int rowsNum, int columnsNum) method.
- Add a caption paragraph to the table using the Table.addCaption() method, including product information and formatting.
- Update the table of contents to reflect changes in the document using the Document.updateTableOfContents(tocForTable) method.
- Save the document using the Document.saveToFile() method.
- Java
import com.spire.doc.*;
import com.spire.doc.documents.*;
import com.spire.doc.fields.*;
public class CreateTOCByTableCaption {
public static void main(String[] args) {
// Create a new document
Document doc = new Document();
// Add a section to the document
Section section = doc.addSection();
// Create a table of content object
TableOfContent tocForTable = new TableOfContent(doc, " \\h \\z \\c \"Table\"");
// Add a paragraph in the section to place the table of content
Paragraph tocParagraph = section.getBody().addParagraph();
tocParagraph.getItems().add(tocForTable);
tocParagraph.appendFieldMark(FieldMarkType.Field_Separator);
tocParagraph.appendText("TOC");
tocParagraph.appendFieldMark(FieldMarkType.Field_End);
// Add two empty paragraphs in the section
section.getBody().addParagraph();
section.getBody().addParagraph();
// Add a table in the section
Table table = section.getBody().addTable(true);
table.resetCells(1, 3);
// Add a title for the table
Paragraph tableCaptionParagraph = (Paragraph) table.addCaption("Table", CaptionNumberingFormat.Number, CaptionPosition.Below_Item);
tableCaptionParagraph.appendText(" One row, three columns");
tableCaptionParagraph.getFormat().setAfterSpacing(18);
// Add a new table in the section
table = section.getBody().addTable(true);
table.resetCells(3, 3);
// Add a title for the second table
tableCaptionParagraph = (Paragraph) table.addCaption("Table", CaptionNumberingFormat.Number, CaptionPosition.Below_Item);
tableCaptionParagraph.appendText(" Three rows, three columns");
tableCaptionParagraph.getFormat().setAfterSpacing(18);
// Add another new table in the section
table = section.getBody().addTable(true);
table.resetCells(5, 3);
// Add a title for the third table
tableCaptionParagraph = (Paragraph) table.addCaption("Table", CaptionNumberingFormat.Number, CaptionPosition.Below_Item);
tableCaptionParagraph.appendText(" Five rows, three columns");
// Update the table of contents
doc.updateTableOfContents(tocForTable);
// Save the document to a specified file
doc.saveToFile("CreateTableOfContentsUsingTableCaptions.docx", FileFormat.Docx_2016);
// Dispose of resources
doc.dispose();
}
}

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.
C#: Count Words, Characters, Paragraphs, Lines, and Pages in Word Documents
2024-04-30 07:38:58 Written by KoohjiAccurate counting of words, characters, paragraphs, lines, and pages is essential in achieving precise document analysis. By meticulously tracking these metrics, writers can gain valuable insights into the length, structure, and overall composition of their work. In this article, we will explain how to count words, characters, paragraphs, lines, and pages in Word documents in C# using Spire.Doc for .NET.
- Count Words, Characters, Paragraphs, Lines, and Pages in a Word Document in C#
- Count Words and Characters in a Specific Paragraph of a Word Document in C#
Install Spire.Doc for .NET
To begin with, you need to add the DLL files included in the Spire.Doc for .NET package as references in your .NET project. The DLL files can be either downloaded from this link or installed via NuGet.
PM> Install-Package Spire.Doc
Count Words, Characters, Paragraphs, Lines, and Pages in a Word Document in C#
Spire.Doc for .NET provides the BuiltinDocumentProperties class that enables you to retrieve crucial information from your Word documents. By using this class, you can access a wealth of details, including both the built-in and custom properties, as well as the precise counts of words, characters, paragraphs, lines, and pages contained within the document. The detailed steps are as follows.
- Initialize an object of the Document class.
- Load a sample Word document using the Document.LoadFromFile() method.
- Get the BuiltinDocumentProperties object using the Document.BuiltinDocumentProperties property.
- Get the numbers of words, characters, paragraphs, lines, and pages in the document using the WordCount, CharCount, ParagraphCount, LinesCount and PageCount properties of the BuiltinDocumentProperties class.
- Initialize an object of the StringBuilder class and append the results to it using the StringBuilder.AppendLine() method.
- Write the content in the StringBuilder to a text file using the File.WriteAllText() method.
- C#
using Spire.Doc;
using System.IO;
using System.Text;
namespace CountWordsCharactersEtcInWord
{
internal class Program
{
static void Main(string[] args)
{
//Initialize an object of the Document class
Document document = new Document();
//Load a sample Word document
document.LoadFromFile("Input.docx");
//Get the BuiltinDocumentProperties object
BuiltinDocumentProperties properties = document.BuiltinDocumentProperties;
//Get the numbers of words, characters, paragraphs, lines, and pages in the document
int wordCount = properties.WordCount;
int charCount = properties.CharCount;
int paraCount = properties.ParagraphCount;
int lineCount = properties.LinesCount;
int pageCount = properties.PageCount;
//Initialize an object of the StringBuilder class
StringBuilder sb = new StringBuilder();
//Append the results to the StringBuilder
sb.AppendLine("The number of words: " + wordCount);
sb.AppendLine("The number of characters: " + charCount);
sb.AppendLine("The number of paragraphs: " + paraCount);
sb.AppendLine("The number of lines: " + lineCount);
sb.AppendLine("The number of pages: " + pageCount);
//Write the content of the StringBuilder to a text file
File.WriteAllText("result.txt", sb.ToString());
document.Close();
}
}
}

Count Words and Characters in a Specific Paragraph of a Word Document in C#
In addition to counting the words and characters in an entire Word document, Spire.Doc for .NET enables you to count the words and characters of a specific paragraph by using the Paragraph.WordCount and Paragraph.CharCount properties. The detailed steps are as follows.
- Initialize an object of the Document class.
- Load a sample Word document using the Document.LoadFromFile() method.
- Get a specific paragraph using the Document.Sections[sectionindex].Paragraphs[paragraphIndex] property.
- Get the numbers of words and characters in the paragraph using the Paragraph.WordCount and Paragraph.CharCount properties.
- Initialize an object of the StringBuilder class and append the results to it using the StringBuilder.AppendLine() method.
- Write the content in the StringBuilder to a text file using the File.WriteAllText() method.
- C#
using Spire.Doc;
using Spire.Doc.Documents;
using System.IO;
using System.Text;
namespace CountWordsAndCharactersForParagraph
{
internal class Program
{
static void Main(string[] args)
{
//Initialize an object of the Document class
Document document = new Document();
//Load a sample Word document
document.LoadFromFile("Input.docx");
//Get a specific paragraph
Paragraph paragraph = document.Sections[0].Paragraphs[0];
//Get the numbers of words and characters in the paragraph
int wordCount = paragraph.WordCount;
int charCount = paragraph.CharCount;
//Initialize an object of the StringBuilder class
StringBuilder sb = new StringBuilder();
//Append the results to the StringBuilder
sb.AppendLine("The number of words: " + wordCount);
sb.AppendLine("The number of characters: " + charCount);
//Write the content of the StringBuilder to a text file
File.WriteAllText("result.txt", sb.ToString());
document.Close();
}
}
}

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.
In the modern office environment, Microsoft Word has become an indispensable part of our daily work and study. Whether it's writing reports, creating resumes, or designing promotional materials, Word provides us with a rich set of features and tools. Among them, the function of adding shapes is particularly popular among users because it allows us to easily enhance the visual appeal and expressiveness of documents. Manipulating shape elements is one of the highlights of Spire.Doc functionality, and this article will introduce you to how to add or delete shapes in Word 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 Shapes in Word Document in Python
Spire.Doc for Python supports adding various shapes such as rectangles, trapezoids, triangles, arrows, lines, emoticons, and many other predefined shape types. By calling the Paragraph.AppendShape(width: float, height: float, shapeType: 'ShapeType') method, you can not only easily insert these shapes at any position in the document but also customize various properties of the shapes, such as fill color, border style, rotation angle, transparency, etc., to meet different typesetting needs and visual effects. Below are the detailed steps:
- Create a new Document object.
- Call Document.AddSection() and Section.AddParagraph() methods to add a section and a paragraph within the section, respectively.
- Call the Paragraph.AppendShape(width: float, height: float, shapeType: 'ShapeType') method to add a shape on the paragraph, where width and height represent the dimensions of the shape, and shapeType enum is used to specify the type of shape.
- Define the style of the shape, such as fill color, border color, border style, and width.
- Set the horizontal and vertical position of the shape relative to the page.
- Add multiple other types of shapes using the same method.
- Save the document using the Document.SaveToFile() method.
- Python
from spire.doc import * from spire.doc.common import * # Create a new Document object doc = Document() # Add a new section in the document sec = doc.AddSection() # Add a paragraph in the new section para = sec.AddParagraph() # Add a rectangle shape in the paragraph with width and height both 60 shape1 = para.AppendShape(60, 60, ShapeType.Rectangle) # Define the fill color of the shape shape1.FillColor = Color.get_YellowGreen() # Define the border color shape1.StrokeColor = Color.get_Gray() # Define the border style and width shape1.LineStyle = ShapeLineStyle.Single shape1.StrokeWeight = 1 # Set the horizontal and vertical position of the shape relative to the page shape1.HorizontalOrigin = HorizontalOrigin.Page shape1.HorizontalPosition = 100 shape1.VerticalOrigin = VerticalOrigin.Page shape1.VerticalPosition = 200 # Similarly, add a triangle shape in the same paragraph and set its properties shape2 = para.AppendShape(60, 60, ShapeType.Triangle) shape2.FillColor = Color.get_Green() shape2.StrokeColor = Color.get_Gray() shape2.LineStyle = ShapeLineStyle.Single shape2.StrokeWeight = 1 shape2.HorizontalOrigin = HorizontalOrigin.Page shape2.HorizontalPosition = 200 shape2.VerticalOrigin = VerticalOrigin.Page shape2.VerticalPosition = 200 # Add an arrow shape and set its properties shape3 = para.AppendShape(60, 60, ShapeType.Arrow) shape3.FillColor = Color.get_SeaGreen() shape3.StrokeColor = Color.get_Gray() shape3.LineStyle = ShapeLineStyle.Single shape3.StrokeWeight = 1 shape3.HorizontalOrigin = HorizontalOrigin.Page shape3.HorizontalPosition = 300 shape3.VerticalOrigin = VerticalOrigin.Page shape3.VerticalPosition = 200 # Add a smiley face shape and set its properties shape4 = para.AppendShape(60, 60, ShapeType.SmileyFace) shape4.FillColor = Color.get_LightGreen() shape4.StrokeColor = Color.get_Gray() shape4.LineStyle = ShapeLineStyle.Single shape4.StrokeWeight = 1 shape4.HorizontalOrigin = HorizontalOrigin.Page shape4.HorizontalPosition = 400 shape4.VerticalOrigin = VerticalOrigin.Page shape4.VerticalPosition = 200 # Save the document outputFile = "AddShapes.docx" doc.SaveToFile(outputFile, FileFormat.Docx2016) # Release the document doc.Close()

Add Shape Group in Word Document
Spire.Doc for Python not only provides the functionality to add individual shapes (such as rectangles, circles, lines, etc.) but also supports creating and managing grouped shapes. A grouped shape is a special collection of shapes that organizes multiple independent shapes together to form a whole, sharing the same transformation properties (such as position, rotation angle, etc.). Here are the specific steps to achieve this:
- Create an object of the Document class.
- Call the Document.AddSection() method to add a blank section.
- Call the Section.AddParagraph() method to add a blank paragraph in the section.
- Call Paragraph.AppendShapeGroup() to add a shape group and specify its dimensions.
- Create a Textbox and specify its shape type, dimensions, position, fill color, and other properties.
- Add paragraphs within the Textbox and insert text, setting the paragraph's horizontal alignment to center.
- Add the Textbox to the list of child objects of the shape group.
- Similar to the above steps, create shapes for symbols like arrows, diamond-shaped text boxes, octagonal text boxes, and set their properties, adding them to the list of child objects of the shape group.
- Save the document using the Document.SaveToFile() method.
- Python
from spire.doc import *
from spire.doc.common import *
# Create a Document object
doc = Document()
# Add a section to the document
sec = doc.AddSection()
# Add a paragraph to the section
para = sec.AddParagraph()
# Add a shape group to the paragraph and specify its horizontal position
shapegroup = para.AppendShapeGroup(375, 350)
shapegroup.HorizontalPosition = 180
# Calculate the relative unit scale X and Y for the shape group for subsequent element size positioning
X = float((shapegroup.Width / 1000.0))
Y = float((shapegroup.Height / 1000.0))
# Create a rounded rectangle text box
txtBox = TextBox(doc)
# Set the shape type of the text box
txtBox.SetShapeType(ShapeType.RoundRectangle)
# Set the width and height of the text box
txtBox.Width = 125 / X
txtBox.Height = 54 / Y
# Add a paragraph inside the text box and set its horizontal alignment to center
paragraph = txtBox.Body.AddParagraph()
paragraph.Format.HorizontalAlignment = HorizontalAlignment.Center
# Add the text "Step One" to the paragraph
paragraph.AppendText("Step One")
# Set the horizontal and vertical position of the text box
txtBox.HorizontalPosition = 19 / X
txtBox.VerticalPosition = 27 / Y
# Set the fill color of the text box and remove the border line
txtBox.Format.FillColor = Color.FromRgb(153, 255, 255)
txtBox.Format.NoLine = True
# Add the text box to the list of child objects of the shape group
shapegroup.ChildObjects.Add(txtBox)
# Create a downward arrow shape and specify its shape type
arrowLineShape = ShapeObject(doc, ShapeType.DownArrow)
# Set the width and height of the arrow shape
arrowLineShape.Width = 16 / X
arrowLineShape.Height = 40 / Y
# Set the horizontal and vertical position of the arrow shape
arrowLineShape.HorizontalPosition = 73 / X
arrowLineShape.VerticalPosition = 87 / Y
# Set the stroke color of the arrow shape
arrowLineShape.StrokeColor = Color.get_CadetBlue()
# Add the arrow shape to the list of child objects of the shape group
shapegroup.ChildObjects.Add(arrowLineShape)
# (Similar subsequent code, creating diamond-shaped text boxes, downward arrow shapes, and octagonal text boxes, with corresponding property settings and positioning)
txtBox = TextBox(doc)
txtBox.SetShapeType(ShapeType.Diamond)
txtBox.Width = 125 / X
txtBox.Height = 54 / Y
paragraph = txtBox.Body.AddParagraph()
paragraph.Format.HorizontalAlignment = HorizontalAlignment.Center
paragraph.AppendText("Step Two")
txtBox.HorizontalPosition = 19 / X
txtBox.VerticalPosition = 131 / Y
txtBox.Format.FillColor = Color.FromRgb(0, 102, 102)
txtBox.Format.NoLine = True
shapegroup.ChildObjects.Add(txtBox)
arrowLineShape = ShapeObject(doc, ShapeType.DownArrow)
arrowLineShape.Width = 16 / X
arrowLineShape.Height = 40 / Y
arrowLineShape.HorizontalPosition = 73 / X
arrowLineShape.VerticalPosition = 192 / Y
arrowLineShape.StrokeColor = Color.get_CadetBlue()
shapegroup.ChildObjects.Add(arrowLineShape)
txtBox = TextBox(doc)
txtBox.SetShapeType(ShapeType.Octagon)
txtBox.Width = 149 / X
txtBox.Height = 59 / Y
paragraph = txtBox.Body.AddParagraph()
paragraph.Format.HorizontalAlignment = HorizontalAlignment.Center
paragraph.AppendText("Step Three")
txtBox.HorizontalPosition = 7 / X
txtBox.VerticalPosition = 236 / Y
txtBox.Format.FillColor = Color.FromRgb(51, 204, 204)
txtBox.Format.NoLine = True
shapegroup.ChildObjects.Add(txtBox)
# Define the output file name
outputFile = "ShapeGroup.docx"
# Save the document
doc.SaveToFile(outputFile, FileFormat.Docx2016)
# Close the document object
doc.Close()

Remove Shapes from Word Document
Spire.Doc for Python supports efficiently removing individual shapes and shape groups from a Word document. Below are the detailed steps:
- Create an object of the Document class.
- Call the Document.LoadFromFile() method to load a document containing shapes.
- Traverse through all the sections of the document and the body elements within the sections to get paragraphs.
- Check if the child elements under the paragraph are shape objects or shape group objects.
- Call the Paragraph.ChildObjects.Remove() method to remove the shape object.
- Save the document using the 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("ShapeGroup.docx")
# Iterate through all sections of the document
for s in range(doc.Sections.Count):
# Get the current section
section = doc.Sections[s]
# Iterate through all child objects within the section
for i in range(section.Body.ChildObjects.Count):
# Get the current child object
document_object = section.Body.ChildObjects[i]
# If the current child object is a paragraph
if isinstance(document_object, Paragraph):
# Convert the child object to a paragraph object
paragraph = document_object
# Initialize the inner loop index
j = 0
# Iterate through all child objects within the paragraph
while j < paragraph.ChildObjects.Count:
# Get the current child object within the paragraph
c_obj = paragraph.ChildObjects[j]
# If the current child object is a shape group or shape object
if isinstance(c_obj, ShapeGroup) or isinstance(c_obj, ShapeObject):
# Remove the shape object from the paragraph
paragraph.ChildObjects.Remove(c_obj)
# Update the inner loop index
j -= 1
# Increment the inner loop index
j += 1
# Save the document
doc.SaveToFile("RemovedShapes.docx", FileFormat.Docx2016)
# Close the document object
doc.Close()
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.