News Category

Spire.Doc for .NET

Adding, inserting, and deleting pages in a Word document is crucial for managing and presenting content. By adding or inserting a new page in Word, you can expand the document to accommodate more content, making it more structured and readable. Deleting pages can help streamline the document by removing unnecessary information or erroneous content. This article will explain how to use Spire.Doc for .NET to add, insert, or delete a page 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 a Page in a Word Document using C#

The steps to add a new page at the end of a Word document involve first obtaining the last section, then inserting a page break at the end of the last paragraph of that section to ensure that subsequently added content appears on a new page. Here are the detailed steps:

  • Create a Document object.
  • Load a Word document using the Document.LoadFromFile() method.
  • Get the body of the last section of the document using Document.LastSection.Body.
  • Add a page break by calling Paragraph.AppendBreak(BreakType.PageBreak) method.
  • Create a new ParagraphStyle object.
  • Add the new paragraph style to the document's style collection using Document.Styles.Add() method.
  • Create a new Paragraph object and set the text content.
  • Apply the previously created paragraph style to the new paragraph using Paragraph.ApplyStyle(ParagraphStyle.Name) method.
  • Add the new paragraph to the document using Body.ChildObjects.Add(Paragraph) method.
  • Save the resulting document using the Document.SaveToFile() method.
  • C#
// Create a new document object
Document document = new Document();

// Load a document
document.LoadFromFile("Sample.docx");

// Get the body of the last section of the document
Body body = document.LastSection.Body;

// Insert a page break after the last paragraph in the body
body.LastParagraph.AppendBreak(BreakType.PageBreak);

// Create a new paragraph style
ParagraphStyle paragraphStyle = new ParagraphStyle(document);
paragraphStyle.Name = "CustomParagraphStyle1";
paragraphStyle.ParagraphFormat.LineSpacing = 12;
paragraphStyle.ParagraphFormat.AfterSpacing = 8;
paragraphStyle.CharacterFormat.FontName = "Microsoft YaHei";
paragraphStyle.CharacterFormat.FontSize = 12;

// Add the paragraph style to the document's style collection
document.Styles.Add(paragraphStyle);

// Create a new paragraph and set the text content
Paragraph paragraph = new Paragraph(document);
paragraph.AppendText("Thank you for using our Spire.Doc for .NET product. The trial version will add a red watermark to the generated document and only supports converting the first 10 pages to other formats. Upon purchasing and applying a license, these watermarks will be removed, and the functionality restrictions will be lifted.");

// Apply the paragraph style
paragraph.ApplyStyle(paragraphStyle.Name);

// Add the paragraph to the body's content collection
body.ChildObjects.Add(paragraph);

// Create another new paragraph and set the text content
paragraph = new Paragraph(document);
paragraph.AppendText("To experience our product more fully, we provide a one-month temporary license free of charge to each of our customers. Please send an email to sales@e-iceblue.com, and we will send the license to you within one working day.");

// Apply the paragraph style
paragraph.ApplyStyle(paragraphStyle.Name);

// Add the paragraph to the body's content collection
body.ChildObjects.Add(paragraph);

// Save the document to the specified path
document.SaveToFile("Add a Page.docx", FileFormat.Docx);

// Close the document
document.Close();

// Release the resources of the document object
document.Dispose();

C#: Add, Insert, or Delete Pgaes in Word Documents

Insert a Page in a Word Document using C#

Before inserting a new page, it is necessary to determine the ending position index of the specified page content within the section. Subsequently, add the content of the new page to the document one by one after this position. Finally, to separate the content from the following pages, adding a page break is essential. The detailed steps are as follows:

  • Create a Document object.
  • Load a Word document using the Document.LoadFromFile() method.
  • Create a FixedLayoutDocument object.
  • Obtain the FixedLayoutPage object of a page in the document.
  • Determine the index position of the last paragraph on the page within the section.
  • Create a new ParagraphStyle object.
  • Add the new paragraph style to the document's style collection using Document.Styles.Add() method.
  • Create a new Paragraph object and set the text content.
  • Apply the previously created paragraph style to the new paragraph using the Paragraph.ApplyStyle(ParagraphStyle.Name) method.
  • Insert the new paragraph at the specified using the Body.ChildObjects.Insert(index, Paragraph) method.
  • Create another new paragraph object, set its text content, add a page break by calling the Paragraph.AppendBreak(BreakType.PageBreak) method, apply the previously created paragraph style, and then insert this paragraph into the document.
  • Save the resulting document using the Document.SaveToFile() method.
  • C#
using Spire.Doc;
using Spire.Doc.Pages;
using Spire.Doc.Documents;

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

            // Load the sample document from a file
            document.LoadFromFile("Sample.docx");

            // Create a fixed layout document object
            FixedLayoutDocument layoutDoc = new FixedLayoutDocument(document);

            // Get the first page
            FixedLayoutPage page = layoutDoc.Pages[0];

            // Get the body of the document
            Body body = page.Section.Body;

            // Get the last paragraph of the current page
            Paragraph paragraphEnd = page.Columns[0].Lines[page.Columns[0].Lines.Count - 1].Paragraph;

            // Initialize the end index
            int endIndex = 0;
            if (paragraphEnd != null)
            {
                // Get the index of the last paragraph
                endIndex = body.ChildObjects.IndexOf(paragraphEnd);
            }

            // Create a new paragraph style
            ParagraphStyle paragraphStyle = new ParagraphStyle(document);
            paragraphStyle.Name = "CustomParagraphStyle1";
            paragraphStyle.ParagraphFormat.LineSpacing = 12;
            paragraphStyle.ParagraphFormat.AfterSpacing = 8;
            paragraphStyle.CharacterFormat.FontName = "Microsoft YaHei";
            paragraphStyle.CharacterFormat.FontSize = 12;

            // Add the paragraph style to the document's style collection
            document.Styles.Add(paragraphStyle);

            // Create a new paragraph and set the text content
            Paragraph paragraph = new Paragraph(document);
            paragraph.AppendText("Thank you for using our Spire.Doc for .NET product. The trial version will add a red watermark to the generated document and only supports converting the first 10 pages to other formats. Upon purchasing and applying a license, these watermarks will be removed, and the functionality restrictions will be lifted.");

            // Apply the paragraph style
            paragraph.ApplyStyle(paragraphStyle.Name);

            // Insert the paragraph at the specified position
            body.ChildObjects.Insert(endIndex + 1, paragraph);

            // Create another new paragraph
            paragraph = new Paragraph(document);
            paragraph.AppendText("To experience our product more fully, we provide a one-month temporary license free of charge to each of our customers. Please send an email to sales@e-iceblue.com, and we will send the license to you within one working day.");

            // Apply the paragraph style
            paragraph.ApplyStyle(paragraphStyle.Name);

            // Add a page break
            paragraph.AppendBreak(BreakType.PageBreak);

            // Insert the paragraph at the specified position
            body.ChildObjects.Insert(endIndex + 2, paragraph);

            // Save the document to the specified path
            document.SaveToFile("Insert a Page.docx", Spire.Doc.FileFormat.Docx);

            // Close and release the original document
            document.Close();
            document.Dispose();
        }
    }
}

C#: Add, Insert, or Delete Pgaes in Word Documents

Delete a Page from a Word Document using C#

To delete the content of a page, first determine the index positions of the starting and ending elements of that page in the document. Then, you can utilize a loop to systematically remove these elements one by one. The detailed steps are as follows:

  • Create a Document object.
  • Load a Word document using the Document.LoadFromFile() method.
  • Create a FixedLayoutDocument object.
  • Obtain the FixedLayoutPage object of the first page in the document.
  • Use the FixedLayoutPage.Section property to get the section where the page is located.
  • Determine the index position of the first paragraph on the page within the section.
  • Determine the index position of the last paragraph on the page within the section.
  • Use a for loop to remove the content of the page one by one.
  • Save the resulting document using the Document.SaveToFile() method.
  • C#
using Spire.Doc;
using Spire.Doc.Pages;
using Spire.Doc.Documents;

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

            // Load the sample document from a file
            document.LoadFromFile("Sample.docx");

            // Create a fixed layout document object
            FixedLayoutDocument layoutDoc = new FixedLayoutDocument(document);

            // Get the second page
            FixedLayoutPage page = layoutDoc.Pages[1];

            // Get the section of the page
            Section section = page.Section;

            // Get the first paragraph on the first page
            Paragraph paragraphStart = page.Columns[0].Lines[0].Paragraph;
            int startIndex = 0;
            if (paragraphStart != null)
            {
                // Get the index of the starting paragraph
                startIndex = section.Body.ChildObjects.IndexOf(paragraphStart);
            }

            // Get the last paragraph on the last page
            Paragraph paragraphEnd = page.Columns[0].Lines[page.Columns[0].Lines.Count - 1].Paragraph;

            int endIndex = 0;
            if (paragraphEnd != null)
            {
                // Get the index of the ending paragraph
                endIndex = section.Body.ChildObjects.IndexOf(paragraphEnd);
            }

            // Delete all content within the specified range
            for (int i = 0; i <= (endIndex - startIndex); i++)
            {
                section.Body.ChildObjects.RemoveAt(startIndex);
            }

            // Save the document to the specified path
            document.SaveToFile("Delete a Page.docx", Spire.Doc.FileFormat.Docx);

            // Close and release the original document
            document.Close();
            document.Dispose();
        }
    }
}

C#: Add, Insert, or Delete Pgaes 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.

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.

Charts in Word documents are a valuable tool for presenting and analyzing data in a visually appealing and understandable format. They help summarize key trends, patterns, or relationships within the data, which is especially useful when you are creating company reports, business proposals or research papers. In this article, you will learn how to programmatically add a line chart to a Word document 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

Create a Line Chart in Word in C# and VB.NET

A line chart is a common type of chart that connects a series of data points with a continuous line. To add a line chart in Word, Spire.Doc for .NET offers the Paragraph.AppendChart(ChartType.Line, float width, float height) method. The following are the detailed steps.

  • Create a Document object.
  • Add a section and then add a paragraph to the section.
  • Add a line chart with specified size to the paragraph using Paragraph.AppendChart(ChartType.Line, float width, float height) method.
  • Get the chart and then set the chart title using Chart.Tilte.Text property.
  • Add a custom series to the chart using Chart.Series.Add(string seriesName, string[] categories, double[] values) method.
  • Set the legend position using Chart.Legend.Position property.
  • Save the result document using Document.SaveToFile() method.
  • C#
  • VB.NET
using Spire.Doc;
using Spire.Doc.Documents;
using Spire.Doc.Fields.Shapes.Charts;
using Spire.Doc.Fields;

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

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

            //Add a paragraph to the section
            Paragraph newPara = section.AddParagraph();

            //Add a line chart with specified size to the paragraph
            ShapeObject shape = newPara.AppendChart(ChartType.Line, 460, 300);

            //Get the chart
            Chart chart = shape.Chart;

            //Set chart title
            chart.Title.Text = "Sales Report";

            //Clear the default series data of the chart
            chart.Series.Clear();

            //Add three custom series with specified series names, category names, and series values to chart
            string[] categories = { "Jan", "Feb", "Mar", "Apr"};
            chart.Series.Add("Team A", categories, new double[] { 1000, 2000, 2500, 4200 });
            chart.Series.Add("Team B", categories, new double[] { 1500, 1800, 3500, 4000 });
            chart.Series.Add("Team C", categories, new double[] { 1200, 2500, 2900, 3600 });

            //Set the legend position
            chart.Legend.Position = LegendPosition.Bottom;

            //Save the result document
            document.SaveToFile("AppendLineChart.docx", FileFormat.Docx);
        }
    }
}

C#/VB.NET: Create a Line Chart 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.

Page 2 of 56