C#: Add or Remove Captions in Word Documents

2024-01-03 01:14:57 Written by  support iceblue
Rate this item
(0 votes)

Captions are important elements in a Word document that enhance readability and organizational structure. They provide explanations and supplementary information for images, tables, and other content, improving the clarity and comprehensibility of the document. Captions are also used to emphasize key points and essential information, facilitating referencing and indexing of specific content. By using captions effectively, readers can better understand and interpret data and images within the document while quickly locating the desired information. This article will demonstrate how to use Spire.Doc for .NET to add or remove captions in a Word document within a C# project.

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

Add Image Captions to a Word document in C#

To add captions to images in a Word document, you can achieve it by creating a paragraph, adding an image, and calling the method DocPicture.AddCaption(string name, CaptionNumberingFormat format, CaptionPosition captionPosition) to generate the caption with a specified name, numbering format, and caption position. The following are the detailed steps:

  • Create an object of the Document class.
  • Use the Document.AddSection() method to add a section.
  • Add a paragraph using Section.AddParagraph() method.
  • Use the Paragraph.AppendPicture(Image image) method to add a DocPicture image object to the paragraph.
  • Use the DocPicture.AddCaption(string name, CaptionNumberingFormat format, CaptionPosition captionPosition) method to add a caption with numbering format as CaptionNumberingFormat.Number.
  • Set the Document.IsUpdateFields property to true to update all fields.
  • Use the Document.SaveToFile() method to save the resulting document.
  • C#
using Spire.Doc;
using Spire.Doc.Documents;
using Spire.Doc.Fields;
using System.Drawing;
namespace AddPictureCaption
{
    internal class Program
    {
        static void Main(string[] args)
        {
            // Create a Word document object
            Document document = new Document();

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

            // Add a new paragraph and insert an image
            Paragraph pictureParagraphCaption = section.AddParagraph();
            pictureParagraphCaption.Format.AfterSpacing = 10;
            DocPicture pic1 = pictureParagraphCaption.AppendPicture(Image.FromFile("Data\\1.png"));
            pic1.Height = 100;
            pic1.Width = 100;

            // Add a caption to the image
            CaptionNumberingFormat format = CaptionNumberingFormat.Number;
            pic1.AddCaption("Image", format, CaptionPosition.BelowItem);

            // Add another paragraph and insert another image
            pictureParagraphCaption = section.AddParagraph();
            DocPicture pic2 = pictureParagraphCaption.AppendPicture(Image.FromFile("Data\\2.png"));
            pic2.Height = 100;
            pic2.Width = 100;

            // Add a caption to the second image
            pic2.AddCaption("Image", format, CaptionPosition.BelowItem);

            // Update all fields in the document
            document.IsUpdateFields = true;

            // Save to a docx document
            string result = "AddImageCaption.docx";
            document.SaveToFile(result, Spire.Doc.FileFormat.Docx2016);

            // Close and dispose of the document object to release resources
            document.Close();
            document.Dispose();
        }
    }
}

C#: Add or Remove Captions in Word documents

Add Table Captions to a Word document in C#

To add captions to a table in a Word document, you can achieve this by creating the table and using the Table.AddCaption(string name, CaptionNumberingFormat format, CaptionPosition captionPosition) method to generate a numbered caption. The steps involved are as follows:

  • Create an object of the Document class.
  • Use the Document.AddSection() method to add a section.
  • Create a Table object and add it to the specified section in the document.
  • Use the Table.ResetCells(int rowsNum, int columnsNum) method to set the number of rows and columns in the table.
  • Add a caption to the table using the Table.AddCaption(string name, CaptionNumberingFormat format, CaptionPosition captionPosition) method, specifying the caption numbering format as CaptionNumberingFormat.Number.
  • Set the Document.IsUpdateFields property to true to update all fields.
  • Use the Document.SaveToFile() method to save the resulting document.
  • C#
using Spire.Doc;
namespace AddTableCation
{
    internal class Program
    {
        static void Main(string[] args)
        {
            // Create a Word document object
            Document document = new Document();

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

            // Add a table
            Table tableCaption = section.AddTable(true);
            tableCaption.ResetCells(3, 2);

            // Add a caption to the table
            tableCaption.AddCaption("Table", CaptionNumberingFormat.Number, CaptionPosition.BelowItem);

            // Add another table and caption
            tableCaption = section.AddTable(true);
            tableCaption.ResetCells(2, 3);
            tableCaption.AddCaption("Table", CaptionNumberingFormat.Number, CaptionPosition.BelowItem);

            // Update all fields in the document
            document.IsUpdateFields = true;

            // Save to a docx document
            string result = "AddTableCaption.docx";
            document.SaveToFile(result, Spire.Doc.FileFormat.Docx2016);

            // Close and dispose of the document object to release resources
            document.Close();
            document.Dispose();
        }
    }
}

C#: Add or Remove Captions in Word documents

Remove Captions from a Word document in C#

Spire.Doc for .NET can also facilitate the removal of captions from an existing Word document. Here are the detailed steps:

  • Create an object of the Document class.
  • Use the Document.LoadFromFile() method to load a Word document.
  • Create a custom method, named DetectCaptionParagraph(Paragraph paragraph), to determine if a paragraph contains a caption.
  • Iterate through all the Paragraph objects in the document using a loop and utilize the custom method, DetectCaptionParagraph(Paragraph paragraph), to identify and delete paragraphs that contain captions.
  • Use the Document.SaveToFile() method to save the resulting document.
  • C#
using Spire.Doc;
using Spire.Doc.Documents;
using Spire.Doc.Fields;
namespace DeleteCaptions
{
    internal class Program
    {
        static void Main(string[] args)
        {
            // Create a Word document object
            Document document = new Document();

            // Load the example.docx file
            document.LoadFromFile("Data/Sample.docx");
            Section section;

            // Iterate through all sections
            for (int i = 0; i < document.Sections.Count; i++)
            {
                section = document.Sections[i];

                // Iterate through paragraphs in reverse order
                for (int j = section.Body.Paragraphs.Count - 1; j >= 0; j--)
                {
                    // Check if the paragraph is a caption paragraph
                    if (DetectCaptionParagraph(section.Body.Paragraphs[j]))
                    {
                        // If it's a caption paragraph, remove it
                        section.Body.Paragraphs.RemoveAt(j);
                    }
                }
            }

            // Save the document after removing captions
            string result = "RemoveCaptions.docx";
            document.SaveToFile(result, Spire.Doc.FileFormat.Docx2016);

            // Close and dispose of the document object to release resources
            document.Close();
            document.Dispose();
        }
        // Method to detect if a paragraph is a caption paragraph
        static bool DetectCaptionParagraph(Paragraph paragraph)
        {
            bool tag = false;
            Field field;

            // Iterate through the child objects in the paragraph
            for (int i = 0; i < paragraph.ChildObjects.Count; i++)
            {
                if (paragraph.ChildObjects[i].DocumentObjectType == DocumentObjectType.Field)
                {
                    // Check if the child object is of Field type
                    field = (Field)paragraph.ChildObjects[i];
                    if (field.Type == FieldType.FieldSequence)
                    {
                        // Check if the Field type is FieldSequence, indicating a caption field type
                        return true;
                    }
                }
            }
            return tag;
        }
    }
}

C#: Add or Remove Captions in Word documents

Apply for a Temporary License

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

Additional Info

  • tutorial_title:
Last modified on Wednesday, 03 January 2024 06:47