When creating a speaker notes in a presentation slide, you can add more than one item or paragraph in notes and display them within a numbered list. In this tutorial, we’ll show you how to add a numbered list to notes using Spire.Presentation in C#.

Step 1: Initialize an instance of Presentation and get the first slide.

Presentation ppt = new Presentation();
ISlide slide = ppt.Slides[0];

Step 2: Add a new notes slide in the specified slide.

NotesSlide notesSlide = slide.AddNotesSlide();

Step 3: Add a new paragraph with the text to speaker notes.

TextParagraph paragraph = new TextParagraph();
paragraph.Text = "Tips for making effective presentations:";
notesSlide.NotesTextFrame.Paragraphs.Append(paragraph);

Step 4: Add another paragraph with the text to notes, set the bullet type of the paragraph as numbered, and set the numbered style as Arabic number following by period.

paragraph = new TextParagraph();
paragraph.Text = "Use the slide master feature to create a consistent and simple design template.";
notesSlide.NotesTextFrame.Paragraphs.Append(paragraph);
notesSlide.NotesTextFrame.Paragraphs[1].BulletType = TextBulletType.Numbered;
notesSlide.NotesTextFrame.Paragraphs[1].BulletStyle = NumberedBulletStyle.BulletArabicPeriod;

Step 5: Repeat step 4 to add many more numbered paragraphs to notes.

paragraph = new TextParagraph();
paragraph.Text = "Simplify and limit the number of words on each screen.";
notesSlide.NotesTextFrame.Paragraphs.Append(paragraph);
notesSlide.NotesTextFrame.Paragraphs[2].BulletType = TextBulletType.Numbered;
notesSlide.NotesTextFrame.Paragraphs[2].BulletStyle = NumberedBulletStyle.BulletArabicPeriod;

paragraph = new TextParagraph();
paragraph.Text = "Use contrasting colors for text and background.";
notesSlide.NotesTextFrame.Paragraphs.Append(paragraph);
notesSlide.NotesTextFrame.Paragraphs[3].BulletType = TextBulletType.Numbered;
notesSlide.NotesTextFrame.Paragraphs[3].BulletStyle = NumberedBulletStyle.BulletArabicPeriod;

Step 6: Save the file.

ppt.SaveToFile("Output.pptx", FileFormat.Pptx2013);

Output:

How to Add a Numbered List to Notes in PowerPoint in C#

Full Code:

using Spire.Presentation;
namespace AddNumberedList
{

    class Program
    {

        static void Main(string[] args)
        {
            Presentation ppt = new Presentation();
            ISlide slide = ppt.Slides[0];

            NotesSlide notesSlide = slide.AddNotesSlide();

            TextParagraph paragraph = new TextParagraph();
            paragraph.Text = "Tips for making effective presentations:";
            notesSlide.NotesTextFrame.Paragraphs.Append(paragraph);

            paragraph = new TextParagraph();
            paragraph.Text = "Use the slide master feature to create a consistent and simple design template.";
            notesSlide.NotesTextFrame.Paragraphs.Append(paragraph);
            notesSlide.NotesTextFrame.Paragraphs[1].BulletType = TextBulletType.Numbered;
            notesSlide.NotesTextFrame.Paragraphs[1].BulletStyle = NumberedBulletStyle.BulletArabicPeriod;

            paragraph = new TextParagraph();
            paragraph.Text = "Simplify and limit the number of words on each screen.";
            notesSlide.NotesTextFrame.Paragraphs.Append(paragraph);
            notesSlide.NotesTextFrame.Paragraphs[2].BulletType = TextBulletType.Numbered;
            notesSlide.NotesTextFrame.Paragraphs[2].BulletStyle = NumberedBulletStyle.BulletArabicPeriod;

            paragraph = new TextParagraph();
            paragraph.Text = "Use contrasting colors for text and background.";
            notesSlide.NotesTextFrame.Paragraphs.Append(paragraph);
            notesSlide.NotesTextFrame.Paragraphs[3].BulletType = TextBulletType.Numbered;
            notesSlide.NotesTextFrame.Paragraphs[3].BulletStyle = NumberedBulletStyle.BulletArabicPeriod;

            ppt.SaveToFile("Output.pptx", FileFormat.Pptx2013);

        }

    }
}
Friday, 12 May 2017 01:59

Creating Mail Merge for a group in C#

In Spire.Doc, we can use mail merge to insert multiple records from data source to a specified region in a Word template document. The region must be marked by two merge fileds with special names like «GroupStart:GroupName» and «GroupEnd:GroupName», where GroupStart and GroupEnd means the start and end point of a group, it's also the start and end point of the region. After performing Mail merge, the region gets repeated for every record from the data source.

For better demonstration, we created a template document with merge fields as follows:

Creating Mail Merge for a group in C#

In this template, "Products" is the group name and we should use the same name when executing mail merge using code. The merge fileds “GroupStart:Products” and “GroupEnd:Products” mean the start and end of the group and the region.

Code snippets:

At first, we defined a class named "Product", in which we created a constructor Product (int number, string type, string name, string price, string vendor, string expirydate) and added four properties "Number", "Type", "Name", "Price", "Vendor" and "ExpiryDate".

Step 1: Instantiate two objects of the Product class and add them into a list.

Product p1 = new Product(1, "Software", "Spire.Doc", "$799", "E-iceblue", "April 28th,2018");
Product p2 = new Product(2, "Software", "Spire.PDF", "$599", "E-iceblue", "September 15th,2017");
            
List<Product> list = new List<Product>();
list.Add(p1);
list.Add(p2);

Step 2: Load the template document.

Document document = new Document("ProductsList.docx");

Step 3: Use the list as data source and execute Mail merge for the group "Products".

MailMergeDataTable table = new MailMergeDataTable("Products", list);           
document.MailMerge.ExecuteGroup(table);

Step 4: Save the document.

document.SaveToFile("Output.docx");

After executing above code, we will get the resultant document as follows:

Creating Mail Merge for a group in C#

Full codes:

using Spire.Doc;
using Spire.Doc.Reporting;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MailMerge
{
    class Program
    {
        static void Main(string[] args)
        {
            Product p1 = new Product(1, "Software", "Spire.Doc", "$799", "E-iceblue", "April 28th,2018");
            Product p2 = new Product(2, "Software", "Spire.PDF", "$599", "E-iceblue", "September 15th,2017");

            List list = new List();
            list.Add(p1);
            list.Add(p2);

            Document document = new Document("ProductsList.docx");

            MailMergeDataTable table = new MailMergeDataTable("Products", list);
            document.MailMerge.ExecuteGroup(table);

            document.SaveToFile("Output.docx");
        }
    }


    public class Product
    {
        public Product(int number, string type, string name, string price, string vendor, string expirydate)
        {
            this.Number = number;
            this.Type = type;
            this.Name = name;
            this.Price = price;
            this.Vendor = vendor;
            this.ExpiryDate = expirydate;
        }

        public int Number { get; set; }
        public string Type { get; set; }
        public string Name { get; set; }
        public string Price { get; set; }
        public string Vendor { get; set; }
        public string ExpiryDate { get; set; }
    }
    
}

The data validation feature in Excel allows the user to control what data can be entered into a cell. For example, you could use data validation to make sure a numeric entry is between 1 and 5, make sure a text entry is less than 20 characters, or make sure the value entered in a cell is from a predefined list. In this article, you will learn how to apply or remove data validation in Excel in C# and VB.NET using Spire.XLS for .NET.

Install Spire.XLS for .NET

To begin with, you need to add the DLL files included in the Spire.XLS 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.XLS

Apply Data Validation to Excel Cells

The following are the steps to add various types of data validation to cells using Spire.XLS for .NET.

  • Create a Workbook object
  • Get the first worksheet through Workbook.Worksheets[index] property.
  • Get a specific cell through Worksheet.Range property.
  • Set the data type allowed in the cell through CellRange.DataValidation.AllowType property. You can select Integer, Time, Date, TextLength, Decimal, etc. as the data type.
  • Set the comparison operator through CellRange.DataValiation.CompareOperator property. The comparison operators include Between, NotBetween, Less, Greater, and Equal.
  • Set one or two formulas for the data validation through CellRange.DataValidation.Formula1 and CellRange.DataValidation.Formula2 properties.
  • Set the input prompt through CellRange.DataValidation.InputMessage property.
  • Save the workbook to an Excel file using Workbook.SaveToFile() method.
  • C#
  • VB.NET
using System;
using Spire.Xls;

namespace ApplyDataValidation
{
    class Program
    {
        static void Main(string[] args)
        {
            //Create a Workbook object
            Workbook workbook = new Workbook();

            //Get the first worksheet
            Worksheet sheet = workbook.Worksheets[0];

            //Insert text in cells
            sheet.Range["B2"].Text = "Number Validation:";
            sheet.Range["B4"].Text = "Date Validation:";
            sheet.Range["B6"].Text = "Text Length Validation:";
            sheet.Range["B8"].Text = "List Validation:";
            sheet.Range["B10"].Text = "Time Validation:";

            //Add a number validation to C2
            CellRange rangeNumber = sheet.Range["C2"];
            rangeNumber.DataValidation.AllowType = CellDataType.Integer;
            rangeNumber.DataValidation.CompareOperator = ValidationComparisonOperator.Between;
            rangeNumber.DataValidation.Formula1 = "1";
            rangeNumber.DataValidation.Formula2 = "10";
            rangeNumber.DataValidation.InputMessage = "Enter a number between 1 and 10";
            rangeNumber.Style.KnownColor = ExcelColors.Gray25Percent;

            //Add a date validation to C4
            CellRange rangeDate = sheet.Range["C4"];
            rangeDate.DataValidation.AllowType = CellDataType.Date;
            rangeDate.DataValidation.CompareOperator = ValidationComparisonOperator.Between;
            rangeDate.DataValidation.Formula1 = "1/1/2010";
            rangeDate.DataValidation.Formula2 = "12/31/2020";
            rangeDate.DataValidation.InputMessage = "Enter a date between 1/1/2010 and 12/31/2020";
            rangeDate.Style.KnownColor = ExcelColors.Gray25Percent;

            //Add a text length validation to C6
            CellRange rangeTextLength = sheet.Range["C6"];
            rangeTextLength.DataValidation.AllowType = CellDataType.TextLength;
            rangeTextLength.DataValidation.CompareOperator = ValidationComparisonOperator.LessOrEqual;
            rangeTextLength.DataValidation.Formula1 ="5";
            rangeTextLength.DataValidation.InputMessage = "Enter text lesser than 5 characters";
            rangeTextLength.Style.KnownColor = ExcelColors.Gray25Percent;

            //Apply a list validation to C8
            CellRange rangeList = sheet.Range["C8"];
            rangeList.DataValidation.Values = new String[] { "United States", "Canada", "United Kingdom", "Germany" };
            rangeList.DataValidation.IsSuppressDropDownArrow = false;
            rangeList.DataValidation.InputMessage ="Choose an item from the list";
            rangeList.Style.KnownColor =ExcelColors.Gray25Percent;

            //Apply a time validation to C10
            CellRange rangeTime = sheet.Range["C10"];
            rangeTime.DataValidation.AllowType = CellDataType.Time;
            rangeTime.DataValidation.CompareOperator = ValidationComparisonOperator.Between;
            rangeTime.DataValidation.Formula1 = "9:00";
            rangeTime.DataValidation.Formula2 = "12:00";
            rangeTime.DataValidation.InputMessage = "Enter a time between 9:00 and 12:00";
            rangeTime.Style.KnownColor = ExcelColors.Gray25Percent;

            //Auto fit width of column 2
            sheet.AutoFitColumn(2);

            //Set the width of column 3
            sheet.Columns[2].ColumnWidth = 20;

            //Save to file
            workbook.SaveToFile("ApplyDataValidation.xlsx", ExcelVersion.Version2016);
        }
    }
}

C#/VB.NET: Apply or Remove Data Validation in Excel

Remove Data Validation from Excel Cells

Below are the steps to remove data validation from the specified cell using Spire.XLS for .NET.

  • Create a Workbook object.
  • Load the Excel file containing data validation using Workbook.LoadFromFile() method.
  • Get the first worksheet though Workbook.Worksheets[index] property.
  • Create an array of rectangles, which is used to locate the cells where the validation will be removed.
  • Remove the data validation from the selected cells using Worksheet.DVTable.Remove() method.
  • Save the workbook to another Excel file using Workbook.SaveToFile() method.
  • C#
  • VB.NET
using Spire.Xls;
using System.Drawing;

namespace RemoveDataValidation
{
    class Program
    {
        static void Main(string[] args)
        {
            //Create a Workbook object
            Workbook workbook = new Workbook();

            //Load a sample Excel file
            workbook.LoadFromFile("C:\\Users\\Administrator\\Desktop\\ApplyDataValidation.xlsx");

            //Get the first worksheet
            Worksheet worksheet = workbook.Worksheets[0];

            //Create an array of rectangles, which is used to locate the ranges in worksheet
            Rectangle[] rectangles = new Rectangle[]{

                //one Rectangle(startColumnIndex, startRowIndex, endColumnIndex, endRowIndex) specifies a  cell range to remove data validation
                //the column or row index starts at 0
                new Rectangle(0, 0, 2, 9)
            };

            //Remove the data validation from the selected cells
            worksheet.DVTable.Remove(rectangles);

            //Save the workbook to an Excel file
            workbook.SaveToFile("RemoveDataValidation.xlsx");
        }
    }
}

C#/VB.NET: Apply or Remove Data Validation in Excel

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.

With the help of Spire.Doc, we can easily add and remove header on the word documents in C#. This article we will demonstrate how to lock down the header information from editing. We will divide it into two parts for the demo. Once is for locking the header information on the existing word document with header and the other is on the new creating word document.

How to lock the header information on the existing word document.

//Load the sample document with header
Document doc = new Document();
doc.LoadFromFile("sample.docx");

//Get the first section from the word document
Section section = doc.Sections[0];

//Protect the document and set the ProtectionType as AllowOnlyFormFields
doc.Protect(ProtectionType.AllowOnlyFormFields, "123");

//Set the ProtectForm as false to unprotect the section
section.ProtectForm = false;

//Save the document to file
doc.SaveToFile("Result.docx", FileFormat.Docx2013);

Effective screenshot of the header has been locked and the other area can be edited:

How to lock the header from editing on word document in C#

How to lock the header information for the new word document.

//Create a new instance of word document
Document doc = new Document();

//Add a section to the word document
Section section = doc.AddSection();

//Add header information to the section
HeaderFooter header = section.HeadersFooters.Header;
Paragraph HParagraph = header.AddParagraph();
TextRange HText = HParagraph.AppendText("Protect header");

//Add a paragraph to the section
Paragraph Para = section.AddParagraph();
Para.AppendText("Demo of how to lock the header information by Spire.Doc ");

//Set the ProtectionType as AllowOnlyFormFields and then unprotect the section
doc.Protect(ProtectionType.AllowOnlyFormFields, "123");
section.ProtectForm = false;

//Save the document to file
doc.SaveToFile("Result.docx", FileFormat.Docx2013);

How to lock the header from editing on word document in C#

Excel enables us to split an excel worksheet into two or four independent panes. After splitting up the window into panes, we can use the horizontal and vertical scroll bars to view and compare data in different parts of the same worksheet. This article demonstrates how to vertical and horizontal split an excel worksheet into four panes programmatically using Spire.XLS.

Detail steps:

Step 1: Instantiate a Workbook instance and load the excel document.

Workbook workbook = new Workbook();
workbook.LoadFromFile("Sample.xlsx");

Step 2: Get the first worksheet.

Worksheet sheet = workbook.Worksheets[0];

Step 3: Split the worksheet horizontally and vertically.

sheet.FirstVisibleColumn = 3;

sheet.FirstVisibleRow = 5;

sheet.VerticalSplit = 110;

sheet.HorizontalSplit = 100;
sheet.ActivePane = 1;

Step 4: Save the excel document.

workbook.SaveToFile("Output.xlsx", ExcelVersion.Version2013);

Screenshot after splitting:

How to Split Excel Worksheet into Multiple Panes in C#

Full codes:

using Spire.Xls;

namespace Split_Panes
{
    class Program
    {
        static void Main(string[] args)
        {
            //Load the excel document
            Workbook workbook = new Workbook();
            workbook.LoadFromFile("Sample.xlsx");
            
            //Get the first worksheet
            Worksheet sheet = workbook.Worksheets[0];

            //Vertical and horizontal split the worksheet into four panes

            sheet.FirstVisibleColumn = 3;

            sheet.FirstVisibleRow = 5;

            sheet.VerticalSplit = 110;

            sheet.HorizontalSplit = 100;

            sheet.ActivePane = 1;
 
            //Save the excel document
            workbook.SaveToFile("Output.xlsx", ExcelVersion.Version2013);

            workbook.Dispose();
        }
    }
}
Thursday, 04 May 2017 09:39

Set Row Height in PDF Table in C#

When creating a PDF table using PdfTable, there is no direct API available in this class that allows to change the row height of the table. However, it is possible to change the row height through BeginRowLayout event.

Step 1: Create a new PDF document.

PdfDocument doc = new PdfDocument();
PdfPageBase page = doc.Pages.Add();

Step 2: Initialize an instance of PdfTable class.

PdfTable table = new PdfTable();

Step 3: Create a DataTable.

DataTable dataTable = new DataTable();
dataTable.Columns.Add("ID");
dataTable.Columns.Add("First Name");
dataTable.Columns.Add("Last Name");
dataTable.Columns.Add("Job Id");
dataTable.Rows.Add(new string[] { "102", "Lexa", "De Haan","AD_VP" });
dataTable.Rows.Add(new string[] { "103", "Alexander", "Hunoldsssss","IT_PROG" });
dataTable.Rows.Add(new string[] { "104", "Bruce", "Ernst", "IT_PROG" });
dataTable.Rows.Add(new string[] { "105", "John", "Chen", "FI_ACCOUNT" })

Step 4: Assign data table as data source to the table.

table.DataSource = dataTable;
table.Style.ShowHeader = true;

Step 5: Subscribe to event.

table.BeginRowLayout += Table_BeginRowLayout;

Step 6: Draw the table on the page and save the document.

table.Draw(page, new RectangleF(0,20,300,90)); 
doc.SaveToFile("Output.pdf");

Step 7: Set the row height in the BeginRowLayout event.

private static void Table_BeginRowLayout(object sender, BeginRowLayoutEventArgs args)
{
    args.MinimalHeight = 15f;
}

Output:

How to Set Row Height in PDF Table in C#

Full Code:

using Spire.Pdf;
using Spire.Pdf.Graphics;
using Spire.Pdf.Tables;
using System.Data;
using System.Drawing;


namespace SetRowHeight
{
    class Program
    {
        static void Main(string[] args)
        {
            PdfDocument doc = new PdfDocument();
            PdfPageBase page = doc.Pages.Add();

            PdfTable table = new PdfTable();
            DataTable dataTable = new DataTable();
            dataTable.Columns.Add("ID");
            dataTable.Columns.Add("First Name");
            dataTable.Columns.Add("Last Name");
            dataTable.Columns.Add("Job Id");
            dataTable.Rows.Add(new string[] { "102", "Lexa", "De Haan", "AD_VP" });
            dataTable.Rows.Add(new string[] { "103", "Alexander", "Hunoldsssss", "IT_PROG" });
            dataTable.Rows.Add(new string[] { "104", "Bruce", "Ernst", "IT_PROG" });
            dataTable.Rows.Add(new string[] { "105", "John", "Chen", "FI_ACCOUNT" });
            table.DataSource = dataTable;
            table.Style.ShowHeader = true;

            foreach (PdfColumn col in table.Columns)
            {
                col.StringFormat = new PdfStringFormat(PdfTextAlignment.Left, PdfVerticalAlignment.Middle);
            }
            table.Style.HeaderStyle.StringFormat = new PdfStringFormat(PdfTextAlignment.Center, PdfVerticalAlignment.Middle);
            table.Style.HeaderStyle.BackgroundBrush = PdfBrushes.Gray;

            table.BeginRowLayout += Table_BeginRowLayout;
            table.Draw(page, new RectangleF(0, 20, 300, 90));
            doc.SaveToFile("Output.pdf");


            System.Diagnostics.Process.Start("Output.pdf");

        }
        private static void Table_BeginRowLayout(object sender, BeginRowLayoutEventArgs args)
        {
            args.MinimalHeight = 15f;
        }
    }
}

With the help of Spire.Doc, developers can encrypt word with password, and also convert the word document to PDF. This article will show you how to convert Word to PDF with encrypted password for the resulted PDF file.

Make sure Spire.Doc for .NET Version 5.8.92 (or above) has been installed correctly and then add Spire.Doc.dll as reference in the downloaded Bin folder though the below path: "..\Spire.Doc\Bin\NET4.0\ Spire.Doc.dll".

Here comes to the code snippets of how to create password encrypted PDF directly from word to PDF conversion.

Step 1: Create a new word document and load the document from file.

Document document = new Document(false);
document.LoadFromFile("Sample.docx");

Step 2: Create an instance of ToPdfParameterList.

ToPdfParameterList toPdf = new ToPdfParameterList();

Step 3: Set open password, permission password and user's permission over the PDF document

toPdf.PdfSecurity.Encrypt("open password","permission password", PdfPermissionsFlags.None, PdfEncryptionKeySize.Key128Bit);

Step 4: Save the document to file.

document.SaveToFile("EncryptedPDF.pdf",toPdf);

Effective screenshot:

Encrypt PDF with password from word to PDF conversion

Full codes:

using Spire.Doc;
namespace EncryptPDF
{
    class Program
    {
        static void Main(string[] args)
        {
            Document document = new Document(false);
            document.LoadFromFile("Sample.docx");

            ToPdfParameterList toPdf = new ToPdfParameterList();
            toPdf.PdfSecurity.Encrypt("open password","permission password", PdfPermissionsFlags.None, PdfEncryptionKeySize.Key128Bit);

            document.SaveToFile("EncryptedPDF.pdf", toPdf);
        }
    }
}

In the previous article, we've introduced how to insert image into excel worksheet. In this article, we'll demonstrate how to extract image from Excel worksheet. Please check the below screenshot of the source excel worksheet which contains an image:

How to Extract Image from Excel Worksheet in C#, VB.NET

Code snippet:

Step 1: Instantiate an instance of Workbook class and load the excel file.

Workbook workbook = new Workbook();
workbook.LoadFromFile(@"C:\Users\Administrator\Desktop\test.xlsx");

Step 2: Get the first worksheet.

Worksheet sheet = workbook.Worksheets[0];

Step 3: Get the first picture in the worksheet and save it to disk.

ExcelPicture picture = sheet.Pictures[0];
picture.Picture.Save(@"Image\image.png", ImageFormat.Png);

Screenshot:

How to Extract Image from Excel Worksheet in C#, VB.NET

Full code:

[C#]
using System.Drawing.Imaging;
using Spire.Xls;

namespace Extract_Image
{
    class Program
    {
        static void Main(string[] args)
        {
            Workbook workbook = new Workbook();
            workbook.LoadFromFile(@"C:\Users\Administrator\Desktop\test.xlsx");
            Worksheet sheet = workbook.Worksheets[0];
            ExcelPicture picture = sheet.Pictures[0];
            picture.Picture.Save(@"Image\image.png", ImageFormat.Png);
        }
    }
}
[VB.NET]
Imports System.Drawing.Imaging
Imports Spire.Xls

Namespace Extract_Image
	Class Program
		Private Shared Sub Main(args As String())
			Dim workbook As New Workbook()
			workbook.LoadFromFile("C:\Users\Administrator\Desktop\test.xlsx")
			Dim sheet As Worksheet = workbook.Worksheets(0)
			Dim picture As ExcelPicture = sheet.Pictures(0)
			picture.Picture.Save("Image\image.png", ImageFormat.Png)
		End Sub
	End Class
End Namespace

In Word 2013 and later version, you can reply to a comment, so it's easier to follow the whole conversation. Spire.Doc also allows programmers to insert a comment as a reply to a selected comment through ReplyToComment method.

Step 1: Create an object of Document and load a Word document containing comments.

Document doc = new Document();
doc.LoadFromFile("Comment.docx");

Step 2: Get the first comment.

Comment comment = doc.Comments[0];

Step 3: Create a new comment and specify the author and content.

Comment replyComment = new Comment(doc);
replyComment.Format.Author = "Adam";
replyComment.Body.AddParagraph().AppendText("Exactly.");

Step 4: Add the new comment as a reply to the selected comment.

comment.ReplyToComment(replyComment);

Step 5: Save to file.

doc.SaveToFile("ReplyToComment.docx", FileFormat.Docx2013);

How to Reply to a Comment in Word in C#, VB.NET

Full Code:

[C#]
using Spire.Doc;
using Spire.Doc.Fields;
namespace ReplyComment
{
    class Program
    {

        static void Main(string[] args)
        {

            Document doc = new Document();
            doc.LoadFromFile("Comment.docx");
            Comment comment = doc.Comments[0];

            Comment replyComment = new Comment(doc);
            replyComment.Format.Author = "Adam";
            replyComment.Body.AddParagraph().AppendText("Exactly.");
            comment.ReplyToComment(replyComment);

            doc.SaveToFile("ReplyToComment.docx", FileFormat.Docx2013);

        }
    }
}
[VB.NET]
Imports Spire.Doc
Imports Spire.Doc.Fields
Namespace ReplyComment
	Class Program

		Private Shared Sub Main(args As String())

			Dim doc As New Document()
			doc.LoadFromFile("Comment.docx")
			Dim comment As Comment = doc.Comments(0)

			Dim replyComment As New Comment(doc)
			replyComment.Format.Author = "Adam"
			replyComment.Body.AddParagraph().AppendText("Exactly.")
			comment.ReplyToComment(replyComment)

			doc.SaveToFile("ReplyToComment.docx", FileFormat.Docx2013)

		End Sub
	End Class
End Namespace
Wednesday, 27 April 2022 06:14

C#/VB.NET: Remove Empty Lines in Word

When coping content from the Internet into a Word document, you may find that there are a lot of blank lines between paragraphs, which will not only make the document look lengthier but also affect the readability. In this article, you will learn how to programmatically remove empty lines/blank paragraphs in an existing 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

Remove Empty Lines in an Existing Word Document

The detailed steps are as follows:

  • Create a Document instance.
  • Load a sample Word document using Document.LoadFromFile() method.
  • Loop through all paragraphs in the document and determine whether the paragraph is a blank paragraph.
  • Remove blank paragraphs from the document using DocumentObjectCollection.Remove() method.
  • Save the document to another file using Document.SaveToFile() method.
  • C#
  • VB.NET
using Spire.Doc;
using Spire.Doc.Documents;
using System;

namespace RemoveEmptyLines
{
    class Program
    {

        static void Main(string[] args)
        {

            //Create a Document instance
            Document doc = new Document();

            //Load a sample Word document 
            doc.LoadFromFile(@"D:\Files\input.docx");

            //Loop through all paragraphs in the document
            foreach (Section section in doc.Sections)
            {
                for (int i = 0; i < section.Body.ChildObjects.Count; i++)
                {
                    if (section.Body.ChildObjects[i].DocumentObjectType == DocumentObjectType.Paragraph)
                    {
                        //Determine if the paragraph is a blank paragraph
                        if (String.IsNullOrEmpty((section.Body.ChildObjects[i] as Paragraph).Text.Trim()))
                        {
                            //Remove blank paragraphs
                            section.Body.ChildObjects.Remove(section.Body.ChildObjects[i]);
                            i--;
                        }
                    }

                }
            }

            //Save the document
            doc.SaveToFile("RemoveEmptyLines.docx", FileFormat.Docx2013);

        }

    }
}

C#/VB.NET: Remove Empty Lines 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.