Thursday, 11 May 2023 03:48

Java: Insert Lists in a Word Document

A list is an effective way to organize information and present it clearly and logically. The elements in the list stand out from other parts of the text, encouraging readers to pay attention to them. Depending on your requirements, you can add numbered lists, bulleted lists or multi-level lists to your Word documents. This article demonstrates how to create these types of lists in a Word document in Java using Spire.Doc for Java.

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>14.1.0</version>
    </dependency>
</dependencies>

Insert a Numbered List in Word in Java

Spire.Doc for Java offers the ListStyle class that you can use to create a numbered list style or a bulleted style. Then, the list style can be applied to a paragraph using Paragraph.getListFormat().applyStyle() method. 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 using ListStyle.getLevels().get(index) method, and set the numbering type using ListLevel.setPatternType() method.
  • Add the list style to the document using Document.getListStyles().add() method.
  • Add several paragraphs to the document using Section.addParagraph() method.
  • Apply the list style to a specific paragraph using Paragraph.getListFormat().applyStyle() method.
  • Specify the list level using Paragraph.getListFormat().setListLevelNumber() method.
  • Save the document to a Word file using Document.saveToFile() method.
  • Java
import com.spire.doc.*;
import com.spire.doc.documents.*;
import com.spire.doc.collections.ListLevelCollection;

public class InsertNumberedList {
    public static void main(String[] args) {
        //Create a Document object
        Document document = new Document();

        //Add a section
        Section section = document.addSection();

        //Create a numbered list style
        ListStyle listStyle =document.getStyles().add(ListType.Numbered, "numberList");
        ListLevelCollection levels = listStyle.getListRef().getLevels();
        levels.get(0).setPatternType(ListPatternType.Decimal_Half_Width);
        levels.get(0).setTextPosition(20);

        //Add a paragraph
        Paragraph paragraph = section.addParagraph();
        paragraph.appendText("Required Web Development Skills:");
        paragraph.getFormat().setAfterSpacing(5);

        //Add a paragraph and apply the numbered list style to it
        paragraph = section.addParagraph();
        paragraph.appendText("HTML");
        paragraph.getListFormat().applyStyle("numberedList");
        paragraph.getListFormat().setListLevelNumber(0);

        //Add another four paragraphs and apply the numbered list style to them
        paragraph = section.addParagraph();
        paragraph.appendText("CSS");
        paragraph.getListFormat().applyStyle("numberedList");
        paragraph.getListFormat().setListLevelNumber(0);

        paragraph = section.addParagraph();
        paragraph.appendText("JavaScript");
        paragraph.getListFormat().applyStyle("numberedList");
        paragraph.getListFormat().setListLevelNumber(0);

        paragraph = section.addParagraph();
        paragraph.appendText("Python");
        paragraph.getListFormat().applyStyle("numberedList");
        paragraph.getListFormat().setListLevelNumber(0);

        paragraph = section.addParagraph();
        paragraph.appendText("MySQL");
        paragraph.getListFormat().applyStyle("numberedList");
        paragraph.getListFormat().setListLevelNumber(0);

        //Save the document to file
        document.saveToFile("output/NumberedList.docx", FileFormat.Docx);
    }
}

Java: Insert Lists in a Word Document

Insert a Bulleted List in Word in Java

The process of creating a bulleted list is similar to that of creating a numbered list. The difference is that when creating a list style, you must specify the list type as Bulleted and set a bullet symbol for 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 using ListStyle.getLevels().get(index) method, and set the bullet symbol using ListLevel.setBulletCharacter() method.
  • Add the list style to the document using Document.getListStyles().add() method.
  • Add several paragraphs to the document using Section.addParagraph() method.
  • Apply the list style to a specific paragraph using Paragraph.getListFormat().applyStyle() method.
  • Specify the list level using Paragraph.getListFormat().setListLevelNumber() method.
  • Save the document to a Word file using Document.saveToFile() method.
  • Java
import com.spire.doc.*;
import com.spire.doc.documents.*;
import com.spire.doc.collections.ListLevelCollection;

public class InsertBulletedList {
    public static void main(String[] args) {
        //Create a Document object
        Document document = new Document();

        //Add a section
        Section section = document.addSection();

        //Create a bulleted list style
        ListStyle numberList =document.getStyles().add(ListType.Bulleted, "bulletedList");
        ListLevelCollection Levels = numberList.getListRef().getLevels();
        Levels.get(0).setBulletCharacter("\u00B7");
        Levels.get(0).getCharacterFormat().setFontName("Symbol");
        Levels.get(0).setTextPosition(20);

        //Add a paragraph
        Paragraph paragraph = section.addParagraph();
        paragraph.appendText("Computer Science Subjects:");
        paragraph.getFormat().setAfterSpacing(5);

        //Add a paragraph and apply the bulleted list style to it
        paragraph = section.addParagraph();
        paragraph.appendText("Data Structure");
        paragraph.getListFormat().applyStyle("bulletedList");
        paragraph.getListFormat().setListLevelNumber(0);

        //Add another five paragraphs and apply the bulleted list style to them
        paragraph = section.addParagraph();
        paragraph.appendText("Algorithm");
        paragraph.getListFormat().applyStyle("bulletedList");
        paragraph.getListFormat().setListLevelNumber(0);

        paragraph = section.addParagraph();
        paragraph.appendText("Computer Networks");
        paragraph.getListFormat().applyStyle("bulletedList");
        paragraph.getListFormat().setListLevelNumber(0);

        paragraph = section.addParagraph();
        paragraph.appendText("Operating System");
        paragraph.getListFormat().applyStyle("bulletedList");
        paragraph.getListFormat().setListLevelNumber(0);

        paragraph = section.addParagraph();
        paragraph.appendText("C Programming");
        paragraph.getListFormat().applyStyle("bulletedList");
        paragraph.getListFormat().setListLevelNumber(0);

        paragraph = section.addParagraph();
        paragraph.appendText("Theory of Computations");
        paragraph.getListFormat().applyStyle("bulletedList");
        paragraph.getListFormat().setListLevelNumber(0);

        //Save the document to file
        document.saveToFile("output/BulletedList.docx", FileFormat.Docx);
    }
}

Java: Insert Lists in a Word Document

Insert a Multi-Level Numbered List in Word in Java

A multi-level list consists of at least two different levels. Each level of a nested list can be accessed using ListStyle.getLevels().get(index) method. Through ListLevel object, you can set the numbering type and prefix for a certain level. 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 using ListStyle.getLevels().get(index) method, and set the numbering type and prefix.
  • Add the list style to the document using Document.getListStyles().add() method.
  • Add several paragraphs to the document using Section.addParagraph() method.
  • Apply the list style to a specific paragraph using Paragraph.getListFormat().applyStyle() method.
  • Specify the list level using Paragraph.getListFormat().setListLevelNumber() method.
  • Save the document to a Word file using Document.saveToFile() method.
  • Java
import com.spire.doc.*;
import com.spire.doc.documents.*;
import com.spire.doc.collections.ListLevelCollection;

public class InsertMultilevelNumberedList  {
    public static void main(String[] args) {
        //Create a Document object
        Document document = new Document();

        //Add a section
        Section section = document.addSection();

        //Create a numbered list style, specifying number prefix and pattern type of each level
        ListStyle listStyle =document.getStyles().add(ListType.Numbered, "nestedStyle");
        ListLevelCollection levels = listStyle.getListRef().getLevels();
        levels.get(0).setPatternType(ListPatternType.Arabic);
        levels.get(0).setTextPosition(20);
        levels.get(1).setNumberPrefix("\u0000.");
        levels.get(1).setPatternType(ListPatternType.Arabic);
        levels.get(2).setNumberPrefix("\u0000.\u0001.");
        levels.get(2).setPatternType(ListPatternType.Arabic);

        //Add a paragraph
        Paragraph paragraph = section.addParagraph();
        paragraph.appendText("Here's a Multi-Level Numbered List:");
        paragraph.getFormat().setAfterSpacing(5f);

        //Add a paragraph and apply the numbered list style to it
        paragraph = section.addParagraph();
        paragraph.appendText("The first item");
        paragraph.getListFormat().applyStyle("nestedStyle");
        paragraph.getListFormat().setListLevelNumber(0);

        //Add another five paragraphs and apply the numbered list stype to them
        paragraph = section.addParagraph();
        paragraph.appendText("The second item");
        paragraph.getListFormat().applyStyle("nestedStyle");
        paragraph.getListFormat().setListLevelNumber(0);

        paragraph = section.addParagraph();
        paragraph.appendText("The first sub-item");
        paragraph.getListFormat().applyStyle("nestedStyle");
        paragraph.getListFormat().setListLevelNumber(1);

        paragraph = section.addParagraph();
        paragraph.appendText("The second sub-item");
        paragraph.getListFormat().continueListNumbering();
        paragraph.getListFormat().applyStyle("nestedStyle");

        paragraph = section.addParagraph();
        paragraph.appendText("A sub-sub-item");
        paragraph.getListFormat().applyStyle("nestedStyle");
        paragraph.getListFormat().setListLevelNumber(2);

        paragraph = section.addParagraph();
        paragraph.appendText("The third item");
        paragraph.getListFormat().applyStyle("nestedStyle");
        paragraph.getListFormat().setListLevelNumber(0);

        //Save the document to file
        document.saveToFile("output/MultilevelNumberedList.docx", FileFormat.Docx);
    }
}

Java: Insert Lists in a Word Document

Insert a Multi-Level Mixed-Type List in Word in Java

In some cases, you may want to mix number and symbol in a multi-level list. To create a mixed-type list, you just need to create a numbered list style and a bulleted list style 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.getListFormat().applyStyle() method.
  • Save the document to a Word file using Document.saveToFile() method.
  • Java
import com.spire.doc.*;
import com.spire.doc.documents.*;
import com.spire.doc.collections.ListLevelCollection;

public class InsertMultilevelMixedTypeList  {
    public static void main(String[] args) {
        //Create a Document object
        Document document = new Document();

        //Add a section
        Section section = document.addSection();

        //Create a numbered list style
        ListStyle numberedListStyle =document.getStyles().add(ListType.Numbered, "numberedStyle");
        ListLevelCollection levels = numberedListStyle.getListRef().getLevels();
        levels.get(0).setPatternType(ListPatternType.Arabic);
        levels.get(0).setTextPosition(20);
        levels.get(1).setPatternType(ListPatternType.Low_Letter);

        //Create a bulleted list style
        ListStyle bulletedListStyle = document.getStyles().add(ListType.Bulleted,"bulletedStyle");
        ListLevelCollection levels_bulletedListStyle = bulletedListStyle.getListRef().getLevels();
        levels_bulletedListStyle.get(2).setBulletCharacter("\u002A");
        levels_bulletedListStyle.get(2).getCharacterFormat().setFontName("Symbol");

        //Add a paragraph
        Paragraph paragraph = section.addParagraph();
        paragraph.appendText("Here's a Multi-Level Mixed List:");
        paragraph.getFormat().setAfterSpacing(5f);

        //Add a paragraph and apply the numbered list style to it
        paragraph = section.addParagraph();
        paragraph.appendText("The first item");
        paragraph.getListFormat().applyStyle("numberedStyle");
        paragraph.getListFormat().setListLevelNumber(0);

        //Add another five paragraphs and apply different list stype to them
        paragraph = section.addParagraph();
        paragraph.appendText("The first sub-item");
        paragraph.getListFormat().applyStyle("numberedStyle");
        paragraph.getListFormat().setListLevelNumber(1);

        paragraph = section.addParagraph();
        paragraph.appendText("The second sub-item");
        paragraph.getListFormat().setListLevelNumber(1);
        paragraph.getListFormat().applyStyle("numberedStyle");

        paragraph = section.addParagraph();
        paragraph.appendText("The first sub-sub-item");
        paragraph.getListFormat().applyStyle("bulletedStyle");
        paragraph.getListFormat().setListLevelNumber(2);

        paragraph = section.addParagraph();
        paragraph.appendText("The second sub-sub-item");
        paragraph.getListFormat().applyStyle("bulletedStyle");
        paragraph.getListFormat().setListLevelNumber(2);

        paragraph = section.addParagraph();
        paragraph.appendText("The second item");
        paragraph.getListFormat().applyStyle("numberedStyle");
        paragraph.getListFormat().setListLevelNumber(0);

        //Save the document to file
        document.saveToFile("output/MultilevelMixedList.docx", FileFormat.Docx);
    }
}

Java: Insert 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.

Lists are used in Word documents to outline, arrange, and emphasize text, making it easy for users to scan and understand a series of items. There are three different types of lists in Word, namely numbered lists, bulleted lists and multi-level lists. Numbered lists are used for items that have a sequence or priority, such as a series of instructions. Bulleted lists are used for items that have no particular priority, such as a list of functions or facts. Multi-level lists are used where there is a sequence and you want each paragraph numbered separately.

In this article, you will learn how to insert these types of lists into a Word document in C# and VB.NET using Spire.Doc for .NET.

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

Insert a Numbered List in Word in C#, VB.NET

Spire.Doc for .NET offers the ListStyle class that you can use to create a numbered list style or a bulleted style. Then, the list style can be applied to a paragraph using Paragraph.ListFormat.ApplyStyle() method. 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.
  • C#
  • VB.NET
using Spire.Doc;
using Spire.Doc.Documents;

namespace CreateOrderedList
{
    class Program
    {
        static void Main(string[] args)
        {
            //Create a Document object
            Document document = new Document();

            //Add a section
            Section section = document.AddSection();

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

            //Add a paragraph
            Paragraph paragraph = section.AddParagraph();
            paragraph.AppendText("Required Web Development Skills:");
            paragraph.Format.AfterSpacing = 5f;

            //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
            document.SaveToFile("NumberedList.docx", FileFormat.Docx);
        }
    }
}

C#/VB.NET: Insert Lists in a Word Document

Insert a Bulleted List in Word in C#, VB.NET

The process of creating a bulleted list is similar to that of creating a numbered list. The difference is that when creating a list style, you must specify the list type as Bulleted and set a bullet symbol for 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.
  • C#
  • VB.NET
using Spire.Doc;
using Spire.Doc.Documents;

namespace CreateUnorderedList
{
    class Program
    {
        static void Main(string[] args)
        {
            //Create a Document object
            Document document = new Document();

            //Add a section
            Section section = document.AddSection();

            //Create a bulleted list style
            ListStyle listStyle = document.Styles.Add( ListType.Bulleted, "bulletedList");
            listStyle.Name = "bulletedList";
            listStyle.ListRef.Levels[0].BulletCharacter = "\x00B7";
            listStyle.ListRef.Levels[0].CharacterFormat.FontName = "Symbol";
            listStyle.ListRef.Levels[0].TextPosition = 20;

            //Add a paragraph
            Paragraph paragraph = section.AddParagraph();
            paragraph.AppendText("Computer Science Subjects:");
            paragraph.Format.AfterSpacing = 5f;

            //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
            document.SaveToFile("BulletedList.docx", FileFormat.Docx);
        }
    }
}

C#/VB.NET: Insert Lists in a Word Document

Insert a Multi-Level Numbered List in Word in C#, VB.NET

A multi-level list consists of at least two different levels. Each level of a nested list is represented by the ListStyle.Levels[index] property, through which you can set the numbering type and prefix for a certain level. 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.
  • C#
  • VB.NET
using Spire.Doc;
using Spire.Doc.Documents;

namespace CreateMultiLevelList
{
    class Program
    {
        static void Main(string[] args)
        {
            //Create a Document object
            Document document = new Document();

            //Add a section
            Section section = document.AddSection();

            //Create a numbered list style, specifying number prefix and pattern type of each level
            ListStyle listStyle = document.Styles.Add(ListType.Numbered, "levelstyle");
            listStyle.Name = "levelstyle";
            listStyle.ListRef.Levels[0].PatternType = ListPatternType.Arabic;
            listStyle.ListRef.Levels[0].TextPosition = 20;
            listStyle.ListRef.Levels[1].NumberPrefix = "\x0000.";
            listStyle.ListRef.Levels[1].PatternType = ListPatternType.Arabic;
            listStyle.ListRef.Levels[2].NumberPrefix = "\x0000.\x0001.";
            listStyle.ListRef.Levels[2].PatternType = ListPatternType.Arabic;

            //Add a paragraph
            Paragraph paragraph = section.AddParagraph();
            paragraph.AppendText("Here's a Multi-Level Numbered List:");
            paragraph.Format.AfterSpacing = 5f;

            //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
            document.SaveToFile("MultilevelNumberedList.docx", FileFormat.Docx);
        }
    }
}

C#/VB.NET: Insert Lists in a Word Document

Insert a Multi-Level Mixed-Type List in Word in C#, VB.NET

In some cases, you may want to mix number and symbol bullet points in a multi-level list. To create a mixed-type list, you just need to create a numbered list style and a bulleted list style 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.
  • C#
  • VB.NET
using Spire.Doc;
using Spire.Doc.Documents;

namespace CreateMultilevelMixedList
{
    class Program
    {
        static void Main(string[] args)
        {
            //Create a Document object
            Document document = new Document();

            //Add a section
            Section section = document.AddSection();

            //Create a numbered list style
            ListStyle numberedListStyle = document.Styles.Add(ListType.Numbered, "numberedStyle");
            numberedListStyle.ListRef.Levels[0].PatternType = ListPatternType.Arabic;
            numberedListStyle.ListRef.Levels[0].TextPosition = 20;
            numberedListStyle.ListRef.Levels[1].PatternType = ListPatternType.LowLetter;
            
            //Create a bulleted list style
            ListStyle bulletedListStyle = document.Styles.Add(ListType.Bulleted, "bulltedStyle"); 
            bulletedListStyle.Name = "bulltedStyle";
            bulletedListStyle.ListRef.Levels[2].BulletCharacter = "\x002A";
            bulletedListStyle.ListRef.Levels[2].CharacterFormat.FontName = "Symbol";

            //Add a paragraph
            Paragraph paragraph = section.AddParagraph();
            paragraph.AppendText("Here's a Multi-Level Mixed List:");
            paragraph.Format.AfterSpacing = 5f;

            //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 another 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
            document.SaveToFile("MultilevelMixedList.docx", FileFormat.Docx);
        }
    }
}

C#/VB.NET: Insert 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.

Friday, 28 April 2023 00:47

C++: Find and Highlight Text in Word

In a large document, it is inevitable to use the find function when you want to quickly locate specific key information. At the same time, highlighting them with a bright color is also an effective way to make them stand out to grab the reader's attention. In this article, you will learn how to programmatically find and highlight text in a Word document using Spire.Doc for C++.

Install Spire.Doc for C++

There are two ways to integrate Spire.Doc for C++ into your application. One way is to install it through NuGet, and the other way is to download the package from our website and copy the libraries into your program. Installation via NuGet is simpler and more recommended. You can find more details by visiting the following link.

Integrate Spire.Doc for C++ in a C++ Application

Find and Highlight All Instances of a Specified Text in Word in C++

Spire.Doc for C++ offers the Document->FindAllString(LPCWSTR_S matchString, bool caseSensitive, bool wholeWord) method to find all instances of a specified text string, and then you can iterate through these instances to highlight them with a bright color. The following are the detailed steps.

  • Create a Document instance.
  • Load a Word document using Document->LoadFromFile() method.
  • Find all matching text in the document using Document->FindAllString() method.
  • Loop through all matching text in the document.
  • Get the text range of a specific matching text using TextSelection->GetAsOneRange() method, and then set its highlight color using TextRange->GetCharacterFormat()->SetHighlightColor() method.
  • Save the result document using Document->SaveToFile() method.
  • C++
#include "Spire.Doc.o.h"

using namespace Spire::Doc;

int main() {
 //Specify the input and output file paths
 std::wstring inputFile = L"Data\\input1.docx";
 std::wstring outputFile = L"Output\\FindAndHighlightAll.docx";

 //Create a Document instance
 intrusive_ptr<Document> document = new Document();

 //Load a Word document from disk
 document->LoadFromFile(inputFile.c_str());

 //Find all matching text in the document
 std::vector<intrusive_ptr<TextSelection>> textSelections = document->FindAllString(L"Transcendentalism", false, true);

 //Loop through all matching text and set highlight color for them
 for (auto selection : textSelections)
 {
  selection->GetAsOneRange()->GetCharacterFormat()->SetHighlightColor(Color::GetYellow());
 }

 //Save the result document
 document->SaveToFile(outputFile.c_str(), FileFormat::Docx);
 document->Close();
}

C++: Find and Highlight Text in Word

Find and Highlight the First Instance of a Specified Text in Word in C++

You can also use the Document->FindString(LPCWSTR_S matchString, bool caseSensitive, bool wholeWord) method to find only the first instance of a specified text string and then set highlight color for it. The following are the detailed steps.

  • Create a Document instance.
  • Load a Word document using Document->LoadFromFile() method.
  • Find the first matching text using Document->FindString() method.
  • Get the text range of the first matching text using TextSelection->GetAsOneRange() method, and then set its highlight color using TextRange->GetCharacterFormat()->SetHighlightColor() method.
  • Save the result document using Document->SaveToFile() method.
  • C++
#include "Spire.Doc.o.h"

using namespace Spire::Doc;
int main() {
 //Specify the input and output file paths
 std::wstring inputFile = L"Data\\input1.docx";
 std::wstring outputFile = L"Output\\FindAndHighlight.docx";

 //Create a Document instance
 intrusive_ptr<Document> document = new Document();

 //Load a Word document from disk
 document->LoadFromFile(inputFile.c_str());

 //Find the first matching text
 intrusive_ptr<TextSelection> textSelection = document->FindString(L"Transcendentalism", false, true);

 //Set highlight color for the text 
 textSelection->GetAsOneRange()->GetCharacterFormat()->SetHighlightColor(Color::GetYellow());

 //Save the result document
 document->SaveToFile(outputFile.c_str(), FileFormat::Docx);
 document->Close();
}

C++: Find and Highlight 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.

Comparison of two versions of a document is the process of checking the new version against the previous one to identify changes made by different contributors. By comparing documents, legal staffs can easily review contracts to determine what changes have been made or still need to be made, and teachers can quickly compare student papers to determine whether or not necessary changes have been applied. In this article, you will learn how to compare two Word documents in C++ using Spire.Doc for C++.

The following is a screenshot of the two Word documents we’re going to compare.

C++: Compare Two Word Documents for Differences

Install Spire.Doc for C++

There are two ways to integrate Spire.Doc for C++ into your application. One way is to install it through NuGet, and the other way is to download the package from our website and copy the libraries into your program. Installation via NuGet is simpler and more recommended. You can find more details by visiting the following link.

Integrate Spire.Doc for C++ in a C++ Application

Compare Two Word Documents in C++

Spire.Doc for C++ allows to compare two Word documents and save the result in a third document. When opening this document with MS Word, you can see all changes that have been made to the original document, including insertions, deletions as well as formatting modifications. The following are the detailed steps.

  • Load two Word documents separately while initialing two different Document objects.
  • Compare these two documents using Document->Compare() method.
  • Save the result in a third Word document using Document->SaveToFile() method.
  • C++
#include "Spire.Doc.o.h"

using namespace Spire::Doc;

int main() {

 //Load the first document
 intrusive_ptr<Document> doc1 = new Document(L"C:\\Users\\Administrator\\Desktop\\Original.docx");

 //Load the second document
 intrusive_ptr<Document> doc2 = new Document(L"C:\\Users\\Administrator\\Desktop\\Revised.docx");

 //Compare the second document on the basis of the first document 
 doc1->Compare(doc2, L"Patrick");

 //Save to a docx file
 doc1->SaveToFile(L"output/Result.docx", Spire::Doc::FileFormat::Docx2013);

 doc1->Close();
 doc2->Close();
}

C++: Compare Two Word Documents for Differences

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.

Speaker notes are hidden notes that can be added to slides to help recall some important or key information. Speaker notes are only visible to the presenter, so adding speaker notes in PowerPoint will not affect the overall visual effectiveness of the document. In this article, you will learn how to programmatically add, read or delete speaker notes in a PowerPoint presentation using Spire.Presentation for C++.

Install Spire.Presentation for C++

There are two ways to integrate Spire.Presentation for C++ into your application. One way is to install it through NuGet, and the other way is to download the package from our website and copy the libraries into your program. Installation via NuGet is simpler and more recommended. You can find more details by visiting the following link.

Integrate Spire.Presentation for C++ in a C++ Application

Add Speaker Notes in PowerPoint in C++

There are a number of benefits to using speaker notes in a PowerPoint presentation, such as it can help you stay on point and also appear more confident during a presentation. The following are the steps to add speaker notes to a specified slide.

  • Create a Presentation instance and load a PowerPoint document using Presentation->LoadFromFile() method.
  • Get a specified slide using Presentation->GetSlides()->GetItem(slideIndex) method.
  • Add a notes slide to the slide using ISlide->AddNotesSlide() method.
  • Create a TextParagraph instance.
  • Set text for the paragraph using TextParagraph->SetText() method, and then append the paragraph to the notes slide using NotesSlide->GetNotesTextFrame()->GetParagraphs()->Append() method.
  • Save the result document using Presentation->SaveToFile() method.
  • C++
#include "Spire.Presentation.o.h";

using namespace Spire::Presentation;
using namespace std;

int main()
{
	//Specify the input and output file paths
	std::wstring inputFile = L"Data\\Template.pptx";
	std::wstring outputFile = L"SpeakerNotes.pptx";

	//Create a Presentation instance
	intrusive_ptr<Presentation> ppt = new Presentation();

	//Load a sample PowerPoint document from disk
	ppt->LoadFromFile(inputFile.c_str());

	//Get the second slide
	intrusive_ptr<ISlide> slide = ppt->GetSlides()->GetItem(1);

	//Add a notes slide
	intrusive_ptr<NotesSlide> notesSlide = slide->AddNotesSlide();

	//Add paragraphs to the notes slide and set the content of the speaker notes
	intrusive_ptr⁢TextParagraph> paragraph = new TextParagraph();
	paragraph->SetText(L"Tips for making effective presentations:");
	notesSlide->GetNotesTextFrame()->GetParagraphs()->Append(paragraph);

	paragraph = new TextParagraph();
	paragraph->SetText(L"Use the slide master feature to create a consistent and simple design template.");
	notesSlide->GetNotesTextFrame()->GetParagraphs()->Append(paragraph);

	paragraph = new TextParagraph();
	paragraph->SetText(L"Simplify and limit the number of words on each screen.");
	notesSlide->GetNotesTextFrame()->GetParagraphs()->Append(paragraph);

	paragraph = new TextParagraph();
	paragraph->SetText(L"Use contrasting colors for text and background.");
	notesSlide->GetNotesTextFrame()->GetParagraphs()->Append(paragraph);

	//Set the bullet type and bullet style for specific paragraphs on the notes slide
	for (int i = 1; i < notesSlide->GetNotesTextFrame()->GetParagraphs()->GetCount(); i++)
	{
		notesSlide->GetNotesTextFrame()->GetParagraphs()->GetItem(i)->SetBulletType(TextBulletType::Numbered);
		notesSlide->GetNotesTextFrame()->GetParagraphs()->GetItem(i)->SetBulletStyle(NumberedBulletStyle::BulletArabicPeriod);
	}

	//Save the result file
	ppt->SaveToFile(outputFile.c_str(), FileFormat::Pptx2013);
	ppt->Dispose();
}

C++: Add, Read or Delete Speaker Notes in PowerPoint

Read Speaker Notes in PowerPoint in C++

To get speaker notes from a notes slide, Spire.Presentation for C++ offers the NotesSlide->GetNotesTextFrame()->GetText() method. The following are the detailed steps.

  • Create a Presentation instance and load a PowerPoint document using Presentation->LoadFromFile() method.
  • Get a specified slide using Presentation->GetSlides()->GetItem(slideIndex) method.
  • Get the notes slide from the slide using ISlide->GetNotesSlide() method.
  • Get the speaker notes from the notes slide using NotesSlide->GetNotesTextFrame()->GetText() method, and then save them to a .txt file.
  • C++
#include "Spire.Presentation.o.h";

using namespace Spire::Presentation;
using namespace std;

int main()
{
	//Specify the input and output file paths
	std::wstring inputFile = L"SpeakerNotes.pptx";
	std::wstring outputFile = L"GetSpeakerNotes.txt";

	//Create a Presentation instance
	intrusive_ptr⁢Presentation> presentation = new Presentation();

	//Load a sample PowerPoint document
	presentation->LoadFromFile(inputFile.c_str());

	//Get the second slide
	intrusive_ptr<ISlide> slide = presentation->GetSlides()->GetItem(1);

	//Get the notes slide from the second slide
	intrusive_ptr<NotesSlide> notesSlide = slide->GetNotesSlide();

	//Get the speaker notes and save to txt file
	wofstream desFile(outputFile, ios::out);
	desFile << notesSlide->GetNotesTextFrame()->GetText() << endl;
	desFile.close();
	presentation->Dispose();
}

C++: Add, Read or Delete Speaker Notes in PowerPoint

Delete Speaker Notes in PowerPoint in C++

With Spire.Presentation for C++, you are also allowed to remove all speaker notes at once or just remove a specified speaker note from the notes slide. The following are the detailed steps.

  • Create a Presentation instance and load a PowerPoint document using Presentation->LoadFromFile() method.
  • Get a specified slide using Presentation->GetSlides()->GetItem(slideIndex) method.
  • Get the notes slide from the slide using ISlide->GetNotesSlide() method.
  • Remove all speaker notes from the notes slide using NotesSlide->GetNotesTextFrame()->GetParagraphs()->Clear() method or remove a specific speaker note from the notes slide using NotesSlide->GetNotesTextFrame()->GetParagraphs()->RemoveAt(paragraphIndex) method.
  • Save the result document using Presentation->SaveToFile() method.
  • C++
#include "Spire.Presentation.o.h";

using namespace Spire::Presentation;
using namespace std;

int main()
{
	//Specify the input and output file paths
	std::wstring inputFile = L"SpeakerNotes.pptx";
	std::wstring outputFile = L"RemoveSpeakerNotes.pptx";

	//Create a Presentation instance
	intrusive_ptr<Presentation> presentation = new Presentation();


	//Load a sample PowerPoint document
	presentation->LoadFromFile(inputFile.c_str());

	//Get the second slide
	intrusive_ptr<ISlide> slide = presentation->GetSlides()->GetItem(1);

	//Get the notes slide from the second slide
	intrusive_ptr<NotesSlide> notesSlide = slide->GetNotesSlide();

	//Remove all the speaker notes from notes slide
	notesSlide->GetNotesTextFrame()->GetParagraphs()->Clear();

	//Remove a specific speak note from notes slide
	//notesSlide->GetNotesTextFrame()->GetParagraphs()->RemoveAt(1);

	//Save the result file
	presentation->SaveToFile(outputFile.c_str(), FileFormat::Pptx2013);
	presentation->Dispose();
}

C++: Add, Read or Delete Speaker Notes in PowerPoint

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.

Margins are the empty and unused spaces between the document's content and edges. The margins generally don't contain any text or image, and their primary purpose is to prevent text from colliding with document boundaries. Depending on your needs, you can change the margins to become wider or narrower. In this article, you will learn how to increase or decrease the page margins of a PDF document in C++ using Spire.PDF for C++.

Install Spire.PDF for C++

There are two ways to integrate Spire.PDF for C++ into your application. One way is to install it through NuGet, and the other way is to download the package from our website and copy the libraries into your program. Installation via NuGet is simpler and more recommended. You can find more details by visiting the following link.

Integrate Spire.PDF for C++ in a C++ Application

Increase the Margins of a PDF Document in C++

The way to enlarge the margins of a PDF document is to create a new PDF that has a larger page size, and then draw the source page on the large page at the appropriate location. The following are the steps to increase the margins of a PDF document using Spire.PDF for C++.

  • Load the original PDF document while initialing the PdfDocument object.
  • Create another PdfDocument object, which is used to create a new PDF document that has a larger page size.
  • Set the increasing values of the margins.
  • Calculate the page size of the new PDF document.
  • Loop through the pages in the original document, and create a template based on a specific page using PdfPageBase->CreateTemplate() method.
  • Add a page to the new PDF document using PdfDocument->GetPages()->Add() method.
  • Draw the template on the page at the coordinate (0, 0) using PdfTemplate->Draw() method.
  • Save the new PDF document to file using PdfDocument->SaveToFile() method.
  • C++
"    //Load the original PDF document
    PdfDocument* originalPdf = new PdfDocument(L"C:\\Users\\Administrator\\Desktop\\sample.pdf");

    //Get the first page
    boost::intrusive_ptr firstPage = originalPdf->GetPages()->GetItem(0);

    //Create a new PdfDocument object
    PdfDocument* newPdf = new PdfDocument();

    //Set increasing value of the margins
    boost::intrusive_ptr margins = newPdf->GetPageSettings()->GetMargins();
    margins->SetTop(40);
    margins->SetBottom(40);
    margins->SetLeft(40);
    margins->SetRight(40);

    //Calculate the new page size
    SizeF* sizeF = new SizeF(firstPage->GetSize()->GetWidth() + margins->GetLeft() + margins->GetRight(), firstPage->GetSize()->GetHeight() + margins->GetTop() + margins->GetBottom());

    //Loop through the pages in the original document
    for (size_t i = 0; i < originalPdf->GetPages()->GetCount(); i++)
    {
        //Create a template based on a spcific page
        boost::intrusive_ptr pdfTemplate = originalPdf->GetPages()->GetItem(i)->CreateTemplate();

        //Add a page to the new PDF
        boost::intrusive_ptr page = newPdf->GetPages()->Add(sizeF);

        //Draw template on the page
        pdfTemplate->Draw(page, 0.0f, 0.0f);
    }"

C++: Change the Margins of a PDF Document

Decrease the Margins of a PDF Document in C++

The way to decrease the margins of a PDF is to create a new PDF that has a smaller page size, and then draw the source page on the small page at a specified coordinate. The following are the steps to decrease the margins of a PDF document using Spire.PDF for C++.

  • Load the original PDF document while initialing the PdfDocument object.
  • Create another PdfDocument object, which is used to create a new PDF document that has a smaller page size.
  • Set the decreasing values of the margins.
  • Calculate the page size of the new PDF document.
  • Loop through the pages in the original document, and create a template based on a specific page using PdfPageBase->CreateTemplate() method.
  • Add a page to the new PDF document using PdfDocument->GetPages()->Add() method.
  • Draw the template on the page at a specified coordinate using PdfTemplate->Draw() method.
  • Save the new PDF document to file using PdfDocument->SaveToFile() method.
  • C++
#include "Spire.Pdf.o.h";

using namespace Spire::Pdf;

int main() {

    //Load the original PDF document
    PdfDocument* originalPdf = new PdfDocument(L"C:\\Users\\Administrator\\Desktop\\sample.pdf");

    //Get the first page
    PdfPageBase* firstPage = originalPdf->GetPages()->GetItem(0);

    //Create a new PdfDocument object
    PdfDocument* newPdf = new PdfDocument();

    //Set decreasing value
    double left = -20;
    double right = -20;
    double top = -20;
    double bottom = -20;

    //Calculate the new page size
    SizeF* sizeF = new SizeF(firstPage->GetSize()->GetWidth() + left + right, firstPage->GetSize()->GetHeight() + top + bottom);

    //Loop through the pages in the original document
    for (size_t i = 0; i < originalPdf->GetPages()->GetCount(); i++)
    {
        //Create a template based on a specific page
        PdfTemplate* pdfTemplate = originalPdf->GetPages()->GetItem(i)->CreateTemplate();

        //Add a page to the new PDF
        PdfPageBase* page = newPdf->GetPages()->Add(sizeF, new PdfMargins(0));

        //Draw template on the page
        pdfTemplate->Draw(page, left, top);
    }

    //Save the new document
    newPdf->SaveToFile(L"Output/DecreaseMargins.pdf", FileFormat::PDF);
    newPdf->Close();
    delete originalPdf;
    delete newPdf;
}

C++: Change the Margins of a PDF 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.

Friday, 14 April 2023 01:15

C++: Change Font Color in Word

Changing the font color in a Word document can be an effective way to emphasize important points. For example, if you are creating a report that contains crucial data, changing the font color of the data text to a brighter color can make it stand out from other text and quickly grab your reader's attention. Another benefit of changing the font color is that it can enhance the visual appearance and readability of the document. For instance, when preparing marketing materials, changing the font color of headings and subheadings to a different font color than the rest of the text can help create a clear information hierarchy, making the materials more attractive and easier to read. In this article, we will demonstrate how to change the font color in a Word document in C++ using Spire.Doc for C++.

Install Spire.Doc for C++

There are two ways to integrate Spire.Doc for C++ into your application. One way is to install it through NuGet, and the other way is to download the package from our website and copy the libraries into your program. Installation via NuGet is simpler and more recommended. You can find more details by visiting the following link.

Integrate Spire.Doc for C++ in a C++ Application

Change the Font Color of a Paragraph in Word in C++

To change the font color of a specific paragraph in a Word document, you can create a custom paragraph style with a specific font color, then add the style to the document and apply it to the paragraph you want to modify. The detailed steps are as follows:

  • Create an instance of the Document class.
  • Load a Word document using the Document->LoadFromFile() method.
  • Access a specific section in the document by its index using the Document->GetSections()->GetItem(int index) method.
  • Access the paragraph you want to modify by its index using the Section->GetParagraphs()->GetItem(int index) method.
  • Create an instance of the ParagraphStyle class to define a custom paragraph style.
  • Set the name and font color of the paragraph style using the ParagraphStyle->SetName() and ParagraphStyle->GetCharacterFormat()->SetTextColor() methods.
  • Add the custom paragraph style to the document using the Document->GetStyles()->Add() method.
  • Apply the custom paragraph style to the specific paragraph using the Paragraph->ApplyStyle() method.
  • Save the modified document using the Document->SaveToFile() method.
  • C++
#include "Spire.Doc.o.h";

using namespace Spire::Doc;

int main()
{
    //Create a Document instance
    intrusive_ptr<Document> document = new Document();

    //Load a Word document
    document->LoadFromFile(L"Sample.docx");

    //Get the first section
    intrusive_ptr<Section> section = document->GetSections()->GetItemInSectionCollection(0);

    //Change the font color of the first Paragraph
    intrusive_ptr<Paragraph> p1 = section->GetParagraphs()->GetItemInParagraphCollection(0);
    intrusive_ptr<ParagraphStyle> style1 = new ParagraphStyle(document);
    style1->SetName(L"Color1");
    style1->GetCharacterFormat()->SetTextColor(Color::GetRosyBrown());
    document->GetStyles()->Add(style1);
    p1->ApplyStyle(style1);

    //Change the font color of the second Paragraph
    intrusive_ptr<Paragraph> p2 = section->GetParagraphs()->GetItemInParagraphCollection(1);
    intrusive_ptr<ParagraphStyle> style2 = new ParagraphStyle(document);
    style2->SetName(L"Color2");
    style2->GetCharacterFormat()->SetTextColor(Color::GetDarkGreen());
    document->GetStyles()->Add(style2);
    p2->ApplyStyle(style2);

    //Save the result document
    document->SaveToFile(L"ChangeFontColorForParagraph.docx", FileFormat::Docx2013);
    document->Close();
}

C++: Change Font Color in Word

Change the Font Color of a Specific Text in Word in C++

To change the font color of a specific text in a Word document, you need to search for the text in the document, then change the font color of its all occurrences. The detailed steps are as follows:

  • Create an instance of the Document class.
  • Load a Word document using the Document->LoadFromFile() method.
  • Find the text that you want to change the font color of using the Document->FindAllString() method.
  • Iterate through all occurrences of the text and change the font color of each occurrence using the TextSelection->GetAsOneRange()->GetCharacterFormat()->SetTextColor() method.
  • Save the result document using the Document->SaveToFile() method.
  • C++
#include "Spire.Doc.o.h";

using namespace Spire::Doc;
using namespace std;

int main()
{
 //Create a Document instance
 intrusive_ptr<Document> document = new Document();

 //Load a Word document
 document->LoadFromFile(L"Sample.docx");

 //Find the text that you want to change the font color of
 vector<intrusive_ptr<TextSelection>> selection = document->FindAllString(L"Spire.Doc for C++", false, true);

 //Change the font color of all occurrences of the text
 for (auto text : selection)
 {
  text->GetAsOneRange()->GetCharacterFormat()->SetTextColor(Color::GetRed());
 }

 //Save the result document
 document->SaveToFile(L"ChangeFontColorForCertainText.docx", FileFormat::Docx2013);
 document->Close();
}

C++: Change Font Color 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.

PDF form fields are digital elements that allow users to input and manipulate data within a PDF document. PDF form fields enable users to complete forms, surveys, questionnaires, and other types of documents electronically, which streamlines the process of data collection and eliminates the need for paper-based methods. In this article, you will learn how to create, fill, or remove form fields in a PDF document in C++ using Spire.PDF for C++.

Install Spire.PDF for C++

There are two ways to integrate Spire.PDF for C++ into your application. One way is to install it through NuGet, and the other way is to download the package from our website and copy the libraries into your program. Installation via NuGet is simpler and more recommended. You can find more details by visiting the following link.

Integrate Spire.PDF for C++ in a C++ Application

Create Form Fields in PDF in C++

Spire.PDF for C++ offers a set of useful classes that allow developers to create and edit various types of form fields in PDF, including text box, check box, combo box, list box, and radio button. The table below lists some of the core classes involved in this tutorial.

Class Description
PdfForm Represents interactive form of the PDF document.
PdfField Represents field of the PDF document's interactive form.
PdfTextBoxField Represents text box field in the PDF form.
PdfCheckBoxField Represents check box field in the PDF form.
PdfComboBoxField Represents combo box field in the PDF Form.
PdfListBoxField Represents list box field of the PDF form.
PdfListFieldItem Represents an item of a list field.
PdfRadioButtonListField Represents radio button field in the PDF form.
PdfRadioButtonListItem Represents an item of a radio button list.
PdfButtonField Represents button field in the PDF form.
PdfSignatureField Represents signature field in the PDF form.

To create a field, initialize an instance of the corresponding class. Specify its size and position in the document using SetBounds() method, and then add it to the PDF form using PdfForm->GetFields()->Add() method. The following are the steps to create various types of form fields in a PDF document using Spire.PDF for C++.

  • Create a PdfDocument object.
  • Add a page using PdfDocument->GetPages()->Add() method.
  • Create a PdfTextBoxField object, set the properties of the field including Bounds, Font and Text, and then add it to the document using PdfForm->GetFields()->Add() method.
  • Repeat the step 3 to add check boxes, combo boxes, list boxes, radio buttons, and buttons to the document.
  • Save the document to a PDF file using PdfDocument->SaveToFile() method.
  • C++
#include "Spire.Pdf.o.h";

using namespace Spire::Pdf;
using namespace std;

int main() {

    //Create a PdfDocument object
    PdfDocument* doc = new PdfDocument();

    //Add a page
    intrusive_ptr⁢PdfPageBase> page = doc->GetPages()->Add();

    //Initialize x and y coordinates
    float baseX = 100;
    float baseY = 30;

    //Create two brush objects
    PdfSolidBrush* brush1 = new PdfSolidBrush(new PdfRGBColor(Spire::Pdf::Color::GetBlue()));
    PdfSolidBrush* brush2 = new PdfSolidBrush(new PdfRGBColor(Spire::Pdf::Color::GetBlack()));

    //Create a font
    PdfFont * font = new PdfFont(PdfFontFamily::TimesRoman, 12.0f, PdfFontStyle::Regular);

    //Add a textbox
    page->GetCanvas()->DrawString(L"TextBox:", font, brush1, 10, baseY);
    RectangleF* tbxBounds = new RectangleF(baseX, baseY, 150, 15);
    PdfTextBoxField* textBox = new PdfTextBoxField(page, L"textbox");
    textBox->SetBounds(tbxBounds);
    textBox->SetText(L"Hello World");
    textBox->SetFont(font);
    doc->GetForm()->GetFields()->Add(textBox);
    baseY += 25;

    //add two checkboxes
    page->GetCanvas()->DrawString(L"CheckBox:", font, brush1, 10, baseY);
    RectangleF* checkboxBound1 = new RectangleF(baseX, baseY, 15, 15);
    PdfCheckBoxField* checkBoxField1 = new PdfCheckBoxField(page, L"checkbox1");
    checkBoxField1->SetBounds(checkboxBound1);
    checkBoxField1->SetChecked(false);
    page->GetCanvas()->DrawString(L"Option 1", font, brush2, baseX + 20, baseY);

    RectangleF* checkboxBound2 = new RectangleF(baseX + 70, baseY, 15, 15);
    PdfCheckBoxField* checkBoxField2 = new PdfCheckBoxField(page, L"checkbox2");
    checkBoxField2->SetBounds(checkboxBound2);
    checkBoxField2->SetChecked(false);
    page->GetCanvas()->DrawString(L"Option 2", font, brush2, baseX + 90, baseY);
    doc->GetForm()->GetFields()->Add(checkBoxField1);
    doc->GetForm()->GetFields()->Add(checkBoxField2);
    baseY += 25;

    //Add a listbox
    page->GetCanvas()->DrawString(L"ListBox:", font, brush1, 10, baseY);
    RectangleF* listboxBound = new RectangleF(baseX, baseY, 150, 50);
    PdfListBoxField* listBoxField = new PdfListBoxField(page, L"listbox");
    listBoxField->GetItems()->Add(new PdfListFieldItem(L"Item 1", L"item1"));
    listBoxField->GetItems()->Add(new PdfListFieldItem(L"Item 2", L"item2"));
    listBoxField->GetItems()->Add(new PdfListFieldItem(L"Item 3", L"item3")); ;
    listBoxField->SetBounds(listboxBound);
    listBoxField->SetFont(font);
    listBoxField->SetSelectedIndex(0);
    doc->GetForm()->GetFields()->Add(listBoxField);
    baseY += 60;

    //Add two radio buttons
    page->GetCanvas()->DrawString(L"RadioButton:", font, brush1, 10, baseY);
    PdfRadioButtonListField* radioButtonListField = new PdfRadioButtonListField(page, L"radio");
    PdfRadioButtonListItem* radioItem1 = new PdfRadioButtonListItem(L"option1");
    RectangleF* radioBound1 = new RectangleF(baseX, baseY, 15, 15);
    radioItem1->SetBounds(radioBound1);
    page->GetCanvas()->DrawString(L"Option 1", font, brush2, baseX + 20, baseY);

    PdfRadioButtonListItem* radioItem2 = new PdfRadioButtonListItem(L"option2");
    RectangleF* radioBound2 = new RectangleF(baseX + 70, baseY, 15, 15);
    radioItem2->SetBounds(radioBound2);
    page->GetCanvas()->DrawString(L"Option 2", font, brush2, baseX + 90, baseY);
    radioButtonListField->GetItems()->Add(radioItem1);
    radioButtonListField->GetItems()->Add(radioItem2);
    radioButtonListField->SetSelectedIndex(0);
    doc->GetForm()->GetFields()->Add(radioButtonListField);
    baseY += 25;

    //Add a combobox
    page->GetCanvas()->DrawString(L"ComboBox:", font, brush1, 10, baseY);
    RectangleF* cmbBounds = new RectangleF(baseX, baseY, 150, 15);
    PdfComboBoxField* comboBoxField = new PdfComboBoxField(page, L"combobox");
    comboBoxField->SetBounds(cmbBounds);
    comboBoxField->GetItems()->Add(new PdfListFieldItem(L"Item 1", L"item1"));
    comboBoxField->GetItems()->Add(new PdfListFieldItem(L"Item 2", L"itme2"));
    comboBoxField->GetItems()->Add(new PdfListFieldItem(L"Item 3", L"item3"));
    comboBoxField->GetItems()->Add(new PdfListFieldItem(L"Item 4", L"item4"));
    comboBoxField->SetSelectedIndex(0);
    comboBoxField->SetFont(font);
    comboBoxField->SetEditable(true);
    doc->GetForm()->GetFields()->Add(comboBoxField);
    baseY += 25;

    //Add a button
    page->GetCanvas()->DrawString(L"Button:", font, brush1, 10, baseY);
    RectangleF* btnBounds = new RectangleF(baseX, baseY, 50, 15);
    PdfButtonField* buttonField = new PdfButtonField(page, L"button");
    buttonField->SetBounds(btnBounds);
    buttonField->SetText(L"Submit");
    buttonField->SetFont(font);
    PdfSubmitAction* submitAction = new PdfSubmitAction(L"https://www.e-iceblue.com/getformvalues.php");
    buttonField->GetActions()->SetMouseDown(submitAction);
    doc->GetForm()->GetFields()->Add(buttonField);

    //Save to file
    doc->SaveToFile(L"Output/FillableForm.pdf", FileFormat::PDF);
    doc->Close();
    delete doc;
}

C++: Create, Fill or Remove Form Fields in PDF

Fill Form Fields in PDF in C++

In order to fill out a form, you need first get all the form fields from the PDF document, determine the type of a certain field, and then input a value or select a value from a predefined list. The following are the steps to fill form fields in an existing PDF document using Spire.PDF for C++.

  • Create a PdfDocument object.
  • Load a sample PDF document using PdfDocument->LoadFromFile() method.
  • Get the form from the document using PdfDocument->GetForm() method.
  • Get the form field widget collection using PdfFormWidget->GetFieldsWidget() method.
  • Loop through the field widget collection to get a specific PdfField.
  • Determine if the PdfField is a certain field type such as text box. If yes, set the text of the text box using PdfTextBoxFieldWidget->SetText() method.
  • Repeat the step above to fill radio button, check box, combo box, and list box with values.
  • Save the document to a PDF file using PdfDocument->SaveToFile() method.
  • C++
#include "Spire.Pdf.o.h";

using namespace Spire::Pdf;
using namespace std;

int main() {

    //Create a PdfDocument object
    PdfDocument* doc = new PdfDocument();

    //Load a PDF file containing form fields
    doc->LoadFromFile(L"C:\\Users\\Administrator\\Desktop\\Form.pdf");

    //Get the form from the document
    intrusive_ptr⁢PdfFormWidget> form = Object::Convert⁢PdfFormWidget>(doc->GetForm());

    //Get the form widget collection
    intrusive_ptr⁢PdfFormFieldWidgetCollection> formWidgetCollection = form->GetFieldsWidget();

    //Loop through the widgets
    for (int i = 0; i < formWidgetCollection->GetCount(); i++)
    {
        //Get a specific field
        intrusive_ptr⁢PdfField> field = formWidgetCollection->GetItem(i);

        //Determine if the field is a text box
        wchar_t nm_w1[100];
        swprintf(nm_w1, 100, L"%hs", typeid(PdfTextBoxFieldWidget).name());
        LPCWSTR_S newName1 = nm_w1;
        if (wcscmp(newName1, field->GetInstanceTypeName()) == 0)
        {
            intrusive_ptr⁢PdfTextBoxFieldWidget> textBoxField = Object::Convert⁢PdfTextBoxFieldWidget>(field);
            wstring str = textBoxField->GetName();
            if (str == L"name")
            {
                //Set the text of text box
                textBoxField->SetText(L"Kaila Smith");
            }
        }

        //Determine if the field is a check box
        wchar_t nm_w2[100];
        swprintf(nm_w2, 100, L"%hs", typeid(PdfCheckBoxWidgetFieldWidget).name());
        LPCWSTR_S newName2 = nm_w2;
        if (wcscmp(newName2, field->GetInstanceTypeName()) == 0)
        {
            intrusive_ptr⁢PdfCheckBoxWidgetFieldWidget> checkBoxField = Object::Convert⁢PdfCheckBoxWidgetFieldWidget>(field);
            wstring str = checkBoxField->GetName();
            if (str == L"travel")
            {
                //Set the "Checked" status of check box
                checkBoxField->SetChecked(true);
            }
            else if (str == L"movie")
            {
                checkBoxField->SetChecked(true);
            }
        }

        //Determine if the field is a combo box
        wchar_t nm_w3[100];
        swprintf(nm_w3, 100, L"%hs", typeid(PdfListBoxWidgetFieldWidget).name());
        LPCWSTR_S newName3 = nm_w3;
        if (wcscmp(newName3, field->GetInstanceTypeName()) == 0)
        {
            intrusive_ptr⁢PdfListBoxWidgetFieldWidget> listBoxField = Object::Convert⁢PdfListBoxWidgetFieldWidget>(field);
            wstring str = listBoxField->GetName();
            if (str == L"country")
            {
                //Set the selected index of combo box
                vector item = { 0 };
                listBoxField->SetSelectedIndex(item);
            }
        }

        //Determine if the field is a radio button
        wchar_t nm_w4[100];
        swprintf(nm_w4, 100, L"%hs", typeid(PdfRadioButtonListFieldWidget).name());
        LPCWSTR_S newName4 = nm_w4;
        if (wcscmp(newName4, field->GetInstanceTypeName()) == 0)
        {
            intrusive_ptr⁢PdfRadioButtonListFieldWidget> radioButtonListField = Object::Convert⁢PdfRadioButtonListFieldWidget>(field);
            wstring str = radioButtonListField->GetName();
            if (str == L"gender")
            {
                //Set the selected index of radio button
                radioButtonListField->SetSelectedIndex(1);
            }
        }

        //Determine if the field is a list box
        wchar_t nm_w5[100];
        swprintf(nm_w5, 100, L"%hs", typeid(PdfComboBoxWidgetFieldWidget).name());
        LPCWSTR_S newName5 = nm_w5;
        if (wcscmp(newName5, field->GetInstanceTypeName()) == 0)
        {
            intrusive_ptr⁢PdfComboBoxWidgetFieldWidget> comBoxField = Object::Convert⁢PdfComboBoxWidgetFieldWidget>(field);
            wstring str = comBoxField->GetName();
            if (str == L"degree")
            {
                //Set the selected index of list box
                vector item = { 1 };
                comBoxField->SetSelectedIndex(item);
            }
        }
    }

    //Save to file
    doc->SaveToFile(L"Output/FillFormFields.pdf", FileFormat::PDF);
    doc->Close();
    delete doc;
}

C++: Create, Fill or Remove Form Fields in PDF

Remove Form Fields from PDF in C++

A form field in a PDF document can be accessed by its index or name and removed by PdfFieldCollection->Remove() method. The following are the steps to remove a particular field or all fields from a PDF document using Sprie.PDF for C++.

  • Create a PdfDocument object.
  • Load a sample PDF document using PdfDocument->LoadFromFile() method.
  • Get the form from the document using PdfDocument->GetForm() method.
  • Get the form field widget collection using PdfFormWidget->GetFieldsWidget() method.
  • Get a specific field using PdfFormFieldWidgetCollection->GetItem() method, and remove it using PdfFieldCollection->Remove() method.
  • To remove all fields at once, use PdfFieldCollection->Clear() method.
  • Save the document to a PDF file using PdfDocument->SaveToFile() method.
  • C++
#include "Spire.Pdf.o.h";

using namespace Spire::Pdf;
using namespace std;

int main() {

    //Create a PdfDocument object
    PdfDocument* doc = new PdfDocument();

    //Load a PDF file
    doc->LoadFromFile(L"C:\\Users\\Administrator\\Desktop\\Form.pdf");

    //Get the form from the document
    intrusive_ptr⁢PdfFormWidget> form = Object::Convert⁢PdfFormWidget>(doc->GetForm());

    //Get form widgets from the form
    intrusive_ptr⁢PdfFormFieldWidgetCollection> widgets = form->GetFieldsWidget();

    //Get a specific field by its name
    intrusive_ptr⁢PdfField> field = widgets->GetItem(L"name");

    //Remove the field
    widgets->Remove(field);

    //Remove all fields
    //widgets->Clear();

    //Save to file
    doc->SaveToFile(L"Output/DeleteFields.pdf", FileFormat::PDF);
    doc->Close();
    delete doc;
}

C++: Create, Fill or Remove Form Fields in PDF

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.

A bookmark in a Word document enables you to navigate to any specific place within the document without having to scroll through large blocks of text. It functions just like an internal link between sections of your document. Bookmarks are particularly useful for navigating through lengthy documents. In this article, you will learn how to add or remove bookmarks in Word documents in C++ using Spire.Doc for C++.

Install Spire.Doc for C++

There are two ways to integrate Spire.Doc for C++ into your application. One way is to install it through NuGet, and the other way is to download the package from our website and copy the libraries into your program. Installation via NuGet is simpler and more recommended. You can find more details by visiting the following link.

Integrate Spire.Doc for C++ in a C++ Application

Add a Bookmark to a Paragraph in C++

Bookmarks are usually created based on whole paragraphs, especially when the paragraphs themselves are headings. The following are the steps to add a bookmark to a paragraph using Spire.Doc for C++.

  • Create a Document object.
  • Load a Word file using Document->LoadFromFile() method.
  • Get a specific section using Document->GetSections()->GetItem() method.
  • Get a specific paragraph from the section using Section->GetParagraphs()->GetItem() method.
  • Create a BookmarkStart object, and insert it at the beginning of the paragraph using Paragraph->GetChildObjects()->Insert(int index, Spire::Doc::IDocumentObject *entity) method.
  • Append a BookmarkEnd object at the end of the paragraph using Paragraph->AppendBookmarkEnd(LPCWSTR_S name) method.
  • Save the document to another Word file using Document->SaveToFile() method.
  • C++
#include "Spire.Doc.o.h";

using namespace Spire::Doc;

int main() {

 //Create a Document object
 intrusive_ptr<Document> document = new Document();

 //Load a Word file
 document->LoadFromFile(L"C:\\Users\\Administrator\\Desktop\\sample2.docx");

 //Get a specific paragraph
 intrusive_ptr<Paragraph> paragraph = document->GetSections()->GetItemInSectionCollection(0)->GetParagraphs()->GetItemInParagraphCollection(1);

 //Create a bookmark start
 intrusive_ptr<BookmarkStart> start = new BookmarkStart(document, L"myBookmark");

 //Insert the bookmark start before the selected text
 paragraph->GetChildObjects()->Insert(0, start);

 //Append a bookmark end at the end of the paragraph
 paragraph->AppendBookmarkEnd(L"myBookmark");

 //Save the document to another Word file
 document->SaveToFile(L"Output/AddBookmarkToParagraph.docx", FileFormat::Docx2013);
 document->Close();
}

C++: Add or Remove Bookmarks in Word Documents

Add a Bookmark to Selected Text in C++

A bookmark can also be inserted to a specific position within a paragraph. The following are the steps to add a bookmark to selected text using Spire.Doc for C++.

  • Create a Document object.
  • Load a Word file using Document->LoadFromFile() method.
  • Find the selected text from the document using Document->FindAllString() method.
  • Find the owner paragraph of the text using TextSelection-> ->GetAsOneRange()->GetOwnerParagraph() method.
  • Get the index of the text in the paragraph using Paragraph->GetChildObjects()->IndexOf() method.
  • Create a BookmarkStart object, and insert it before the selected text using Paragraph->GetChildObjects()->Insert(int index, Spire::Doc::IDocumentObject *entity) method.
  • Create a BookmarkEnd object, and insert it after the selected text using Paragraph->GetChildObjects()->Insert(int index, Spire::Doc::IDocumentObject *entity) method.
  • Save the document to another Word file using Document->SaveToFile() method.
  • C++
#include "Spire.Doc.o.h";

using namespace Spire::Doc;
using namespace std;

int main() {

    //Create a Document object
    intrusive_ptr<Document> document = new Document();

    //Load a Word file
    document->LoadFromFile(L"C:\\Users\\Administrator\\Desktop\\sample2.docx");

    //Specify text to find
    wstring stringToFind = L"business-to-consumer";

    //Find the text from the document
    vector<intrusive_ptr<TextSelection>>  finds = document->FindAllString(stringToFind.c_str(), false, true);
    intrusive_ptr<TextSelection> specificText = finds[0];

    //Find the paragraph where the text is located
    intrusive_ptr<Paragraph> para = specificText->GetAsOneRange()->GetOwnerParagraph();

    //Get the index of the text in the paragraph
    int index = para->GetChildObjects()->IndexOf(specificText->GetAsOneRange());

    //Create a bookmark start
    intrusive_ptr<BookmarkStart> start = new BookmarkStart(document, L"myBookmark");

    //Insert the bookmark start before the selected text
    para->GetChildObjects()->Insert(index, start);

    //Create a bookmark end
    intrusive_ptr<BookmarkEnd> end = new BookmarkEnd(document, L"myBookmark");

    //Insert the bookmark end after the selected text
    para->GetChildObjects()->Insert(index + 2, end);

    //Save the document to another Word file
    document->SaveToFile(L"Output/AddBookmarkToText.docx", FileFormat::Docx2013);
    document->Close();
}

C++: Add or Remove Bookmarks in Word Documents

Remove Bookmarks from a Word Document in C++

Using Spire.Doc for C++, you can easily get and remove all bookmarks or a particular bookmark from a Word document. The following are the detailed steps.

  • Create a Document object.
  • Load a Word file containing bookmarks using Document->LoadFromFile() method.
  • Get a specific bookmark using Document->GetBookmarks()->GetItem() method.
  • Remove the bookmark using Document->GetBookmarks()->Remove() method. To remove all bookmarks at once, use Document->GetBookmarks()->Clear() method.
  • Save the document to another Word file using Document->SaveToFile() method.
  • C++
#include "Spire.Doc.o.h";

using namespace Spire::Doc;

int main() {

 //Create a Document object
 intrusive_ptr<Document> document = new Document();

 //Load a Word file
 document->LoadFromFile(L"C:\\Users\\Administrator\\Desktop\\Bookmarks.docx");

 //Get a specific bookmark by its index
 intrusive_ptr<Bookmark> bookmark = document->GetBookmarks()->GetItem(0);

 //Remove the bookmark
 document->GetBookmarks()->Remove(bookmark);

 //Remove all bookmarks
 //document->GetBookmarks()->Clear();

 //Save the document to another Word file
 document->SaveToFile(L"Output/RemoveBookmarks.docx", FileFormat::Docx2013);
 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.

Monday, 03 April 2023 01:15

C++: Protect or Unprotect Word Documents

Document security is particularly important when critical or private data is involved in a Word document. There are several security options in Word that you can use to protect your documents, including password protection, read-only mode, editing restrictions, and partial protection. On the contrary, when the protection is no longer required, you may need to unprotect a Word document to improve work efficiency.

In this article, you will learn how to protect or unprotect Word documents in C++ using Spire.Doc for C++.

Install Spire.Doc for C++

There are two ways to integrate Spire.Doc for C++ into your application. One way is to install it through NuGet, and the other way is to download the package from our website and copy the libraries into your program. Installation via NuGet is simpler and more recommended. You can find more details by visiting the following link.

Integrate Spire.Doc for C++ in a C++ Application

Password Protect a Word Document in C++

Encrypting a document with a password makes sure that only you and certain people can read or edit it. The following are the steps to password protect a Word document using Spire.Doc for C++.

  • Create a Document object.
  • Load a Word document using Document->LoadFromFile() method.
  • Encrypt the document with a password using Document->Eencrypt(LPCWSTR_S password) method.
  • Save the document to another Word file using Document->SaveToFile() method.
  • C++
#include "Spire.Doc.o.h";

using namespace Spire::Doc;

int main() {

    //Create a Document object
    intrusive_ptr<Document> document = new Document();

    //Load a Word file
    document->LoadFromFile(L"C:\\Users\\Administrator\\Desktop\\sample.docx");

    //Encrypt the document with a password
    document->Encrypt(L"open-psd");

    //Save the document to another Word file
    document->SaveToFile(L"Output/Encryption.docx", FileFormat::Docx2013);
    document->Close();
}

C++: Protect or Unprotect Word Documents

Restrict Editing of a Word Document in C++

If you want to grant people permission to read your document but restrict the types of modifications that someone can make, you can protect your document with a specific protection type and a permission password.

Protection Type Description
AllowOnlyComments Modification of comments in the document is allowed.
AllowOnlyFormFields The user can only enter data in the form fields in the document.
AllowOnlyReading The document is read-only.
AllowOnlyRevisions The user can only add revision marks to the document.
NoProtection The document is not protected.

The following are the steps to restrict editing of a Word document using Spire.Doc for C++.

  • Create a Document object.
  • Load a Word document using Document->LoadFromFile() method.
  • Protect the document by specifying the protection type and the permission password using Document->Protect(Spire::Doc::ProtectionType type, LPCWSTR_S password) method.
  • Save the document to another Word file using Document->SaveToFile() method.
  • C++
#include "Spire.Doc.o.h";

using namespace Spire::Doc;

int main() {

    //Create a Document object
    intrusive_ptr<Document> document = new Document();

    //Load a Word file
    document->LoadFromFile(L"C:\\Users\\Administrator\\Desktop\\sample.docx");

    //Protect the document by specifying the protection type and the password
    document->Protect(ProtectionType::AllowOnlyReading, L"permission-psd");

    //Save the document to another Word file
    document->SaveToFile(L"Output/RestrictEditing.docx", FileFormat::Docx2013);
    document->Close();
}

C++: Protect or Unprotect Word Documents

Protect Sections of a Word Document in C++

Word allows you to lock some sections of your Word document and leave the rest available for editing. The following are the steps to protect selected sections of a Word document using Spire.Doc for C++.

  • Create a Document object.
  • Load a Word document using Document->LoadFromFile() method.
  • Set the protection type to AllowOnlyFormFields using Document->Protect() method.
  • Unprotect a particular section by passing false as an argument to the Section->SetProtectForm() method. Other sections will continue to be protected.
  • Save the document to another Word file using Document->SaveToFile() method.
  • C++
#include "Spire.Doc.o.h";

using namespace Spire::Doc;

int main() {

    //Create a Document object
    intrusive_ptr<Document> document = new Document();

    //Load a Word file
    document->LoadFromFile(L"C:\\Users\\Administrator\\Desktop\\sample.docx");

    //Set the protection type as "AllowOnlyFormFields"
    document->Protect(ProtectionType::AllowOnlyFormFields, L"permission-psd");

    //Unprotect section 2
    document->GetSections()->GetItemInSectionCollection(1)->SetProtectForm(false);

    //Save the document to another Word file
    document->SaveToFile(L"Output/ProtectSections.docx", FileFormat::Docx2013);
    document->Close();
}

C++: Protect or Unprotect Word Documents

Create Editable Regions in a Word Document in C++

Aside from making certain sections editable, you can create editable regions based on text ranges in order to narrow down the scope of changes that users are able to make. The following are the steps to create editable regions in a read-only Word document using Spire.Doc for C++.

  • Create a Document object.
  • Load a Word file using Document->LoadFromFile() method.
  • Set the protection type to AllowOnlyReading using Document->Protect() method.
  • Create a PermissionStart object and a PermissionEnd object.
  • Insert the PermissionStart object at the beginning of a paragraph using DocumentObjectCollection->Insert(int index, Spire::Doc::lDocumentObject *entity) method, which indicates the start of an editable region.
  • Add the PermissionEnd object at the end of a paragraph using DocumentObjectCollection->Add(Spire::Doc::lDocumentObject *entity) method, which indicates the end of an editable region.
  • Save the document to another Word file using Document->SaveToFile() method.
  • C++
#include "Spire.Doc.o.h";

using namespace Spire::Doc;

int main() {

    //Create a Document object
    intrusive_ptr<Document> document = new Document();

    //Load a Word file
    document->LoadFromFile(L"C:\\Users\\Administrator\\Desktop\\sample2.docx");

    //Set the protect type to AllowOnlyReading
    document->Protect(ProtectionType::AllowOnlyReading, L"permission-psd");

    //Create tags for permission start and end
    intrusive_ptr<PermissionStart> start = new PermissionStart(document, L"regionOne");
    intrusive_ptr<PermissionEnd> end = new PermissionEnd(document, L"regionOne");

    //Add the start and end tags to allow the selected paragraphs to be editable
    document->GetSections()->GetItemInSectionCollection(0)->GetParagraphs()->GetItemInParagraphCollection(0)->GetChildObjects()->Insert(0, start);
    document->GetSections()->GetItemInSectionCollection(0)->GetParagraphs()->GetItemInParagraphCollection(1)->GetChildObjects()->Add(end);

    //Save the document to another Word file
    document->SaveToFile(L"Output/SetEditableRegions.docx", FileFormat::Docx2013);
    document->Close();
}

C++: Protect or Unprotect Word Documents

Remove Editable Regions from a Word Document in C++

In order to remove the editable regions, you need to find the "PermissionStart" and "PermissionEnd" tags in the document and remove them. The following are the detailed steps.

  • Create a Document object.
  • Load a Word document containing editable regions using Document->LoadFromFile() method.
  • Traverse through all the child objects in the document, and determine if a certain child object is an instance of PermissionStart class or PermissionEnd class. If yes, remove the child object from the paragraph using Paragraph->GetChildObjects()->Remove(Spire::Doc::IDocumentObject *entity) method.
  • Save the document to another Word file using Document->SaveToFile() method.
  • C++
#include "Spire.Doc.o.h";

using namespace Spire::Doc;

int main() {

 //Create a Document object
 intrusive_ptr<Document> document = new Document();

 //Load a Word file
 document->LoadFromFile(L"C:\\Users\\Administrator\\Desktop\\SetEditableRegions.docx");

 //Find "PermissionStart" and "PermissionEnd" tags and remove them
 for (int i = 0; i < document->GetSections()->GetCount(); i++)
 {
  intrusive_ptr<Section> section = document->GetSections()->GetItemInSectionCollection(i);
  for (int j = 0; j < section->GetBody()->GetParagraphs()->GetCount(); j++)
  {
   intrusive_ptr<Paragraph> para = section->GetBody()->GetParagraphs()->GetItemInParagraphCollection(j);
   for (int k = 0; k < para->GetChildObjects()->GetCount(); k++)
   {
    intrusive_ptr<DocumentObject> obj = para->GetChildObjects()->GetItem(k);
    if (Object::Dynamic_cast<PermissionStart>(obj) != nullptr || Object::Dynamic_cast<PermissionEnd>(obj) != nullptr)
    {
     para->GetChildObjects()->Remove(obj);
    }
    else
    {
     k++;
    }
   }
  }
 }

 //Save the document to another Word file
 document->SaveToFile(L"Output/RemoveEditableRegions.docx", FileFormat::Docx2013);
 document->Close();
}

Remove Restrictions from a Word Document in C++

Spire.Doc for C++ allows you to remove editing restrictions without knowing the permission password. The following are the detailed steps.

  • Create a Document object.
  • Load a Word document containing editing restrictions using Document->LoadFromFile() method.
  • Set the protection type to NoProtection using Document->Protect() method.
  • Save the document to another Word file using Document->SaveToFile() method.
  • C++
#include "Spire.Doc.o.h";

using namespace Spire::Doc;

int main() {

    //Create a Document object
    intrusive_ptr<Document> document = new Document();

    //Load a Word file
    document->LoadFromFile(L"C:\\Users\\Administrator\\Desktop\\RestrictEditing.docx");

    //Set the protect type to NoProtection
    document->Protect(ProtectionType::NoProtection);

    //Save the document to another Word file
    document->SaveToFile(L"Output/RemoveRestrictions.docx", FileFormat::Docx2013);
    document->Close();
}

Remove Password from a Password-Protected Word Document in C++

The password of an encrypted Word document can be removed if it is no longer needed. The following are the detailed steps.

  • Create a Document object.
  • Load a password-protected Word document using Document->LoadFromFile((LPCWSTR_S fileName, Spire::Doc::FileFormat fileFormat, LPCWSTR_S password) method.
  • Remove the password using Document->RemoveEncryption() method.
  • Save the document to another Word file using Document->SaveToFile() method.
  • C++
#include "Spire.Doc.o.h";

using namespace Spire::Doc;

int main() {

    //Create a Document object
    intrusive_ptr<Document> document = new Document();

    //Load an encrypted Word file
    document->LoadFromFile(L"C:\\Users\\Administrator\\Desktop\\Encryption.docx", FileFormat::Docx, L"open-psd");

    //Remove the open password
    document->RemoveEncryption();

    //Save the document to another Word file
    document->SaveToFile(L"Output/RemovePassword.docx", FileFormat::Docx2013);
    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.