.NET (1322)
Children categories
Math equations in Word documents are essential tools for expressing mathematical concepts and relationships. Whether you are writing an academic paper, a scientific report, or any other document involving mathematical content, incorporating math equations can greatly enhance your ability to convey complex mathematical concepts and improve the visual appeal and professionalism of your document. In this article, we will explain how to insert math equations into Word documents 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 Math Equations into a Word Document in C# and VB.NET
Spire.Doc for .NET allows generating math equations from LaTeX code and MathML code using OfficeMath.FromLatexMathCode(string latexMathCode) and OfficeMath.FromMathMLCode(string mathMLCode) methods. The detailed steps are as follows:
- Create two string arrays from LaTeX code and MathML code.
- Create a Document instance and add a section to it using Document.AddSection() method.
- Iterate through each LaTeX code in the string array.
- Create a math equation from the LaTeX code using OfficeMath.FromLatexMathCode(string latexMathCode) method.
- Add a paragraph to the section, then add the math equation to the paragraph using Paragraph.Items.Add() method.
- Iterate through each MathML code in the string array.
- Create a math equation from the MathML code using OfficeMath.FromMathMLCode(string mathMLCode) method.
- Add a paragraph to the section, then add the math equation to the paragraph using Paragraph.Items.Add() method.
- Save the result document using Document.SaveToFile() method.
- C#
- VB.NET
using Spire.Doc;
using Spire.Doc.Documents;
using Spire.Doc.Fields.OMath;
namespace AddMathEquations
{
internal class Program
{
static void Main(string[] args)
{
//Create a string array from LaTeX code
string[] latexMathCode = {
"x^{2}+\\sqrt{x^{2}+1}=2",
"\\cos (2\\theta) = \\cos^2 \\theta - \\sin^2 \\theta",
"k_{n+1} = n^2 + k_n^2 - k_{n-1}",
"\\frac {\\frac {1}{x}+ \\frac {1}{y}}{y-z}",
"\\int_0^ \\infty \\mathrm {e}^{-x} \\, \\mathrm {d}x",
"\\forall x \\in X, \\quad \\exists y \\leq \\epsilon",
"\\alpha, \\beta, \\gamma, \\Gamma, \\pi, \\Pi, \\phi, \\varphi, \\mu, \\Phi",
"A_{m,n} = \\begin{pmatrix} a_{1,1} & a_{1,2} & \\cdots & a_{1,n} \\\\ a_{2,1} & a_{2,2} & \\cdots & a_{2,n} \\\\ \\vdots & \\vdots & \\ddots & \\vdots \\\\ a_{m,1} & a_{m,2} & \\cdots & a_{m,n} \\end{pmatrix}",
};
//Create a string array from MathML code
string[] mathMLCode = {
"<math xmlns=\"http://www.w3.org/1998/Math/MathML\"><mi>a</mi><mo>≠</mo><mn>0</mn></math>",
"<math xmlns=\"http://www.w3.org/1998/Math/MathML\"><mi>a</mi><msup><mi>x</mi><mn>2</mn></msup><mo>+</mo><mi>b</mi><mi>x</mi><mo>+</mo><mi>c</mi><mo>=</mo><mn>0</mn></math>",
"<math xmlns=\"http://www.w3.org/1998/Math/MathML\"><mi>x</mi><mo>=</mo><mrow><mfrac><mrow><mo>−</mo><mi>b</mi><mo>±</mo><msqrt><msup><mi>b</mi><mn>2</mn></msup><mo>−</mo><mn>4</mn><mi>a</mi><mi>c</mi></msqrt></mrow><mrow><mn>2</mn><mi>a</mi></mrow></mfrac></mrow></math>",
};
//Create a Document instance
Document doc = new Document();
//Add a section
Section section = doc.AddSection();
//Add a paragraph to the section
Paragraph textPara = section.AddParagraph();
textPara.AppendText("Creating Equations from LaTeX Code");
textPara.ApplyStyle(BuiltinStyle.Heading1);
textPara.Format.HorizontalAlignment = HorizontalAlignment.Center;
//Iterate through each LaTeX code in the string array
for (int i = 0; i < latexMathCode.Length; i++)
{
//Create a math equation from the LaTeX code
OfficeMath officeMath = new OfficeMath(doc);
officeMath.FromLatexMathCode(latexMathCode[i]);
//Add the math equation to the section
Paragraph paragraph = section.AddParagraph();
paragraph.Items.Add(officeMath);
section.AddParagraph();
}
section.AddParagraph();
//Add a paragraph to the section
textPara = section.AddParagraph();
textPara.AppendText("Creating Equations from MathML Code");
textPara.ApplyStyle(BuiltinStyle.Heading1);
textPara.Format.HorizontalAlignment = HorizontalAlignment.Center;
//Iterate through each MathML code in the string array
for (int j = 0; j < mathMLCode.Length; j++)
{
//Create a math equation from the MathML code
OfficeMath officeMath = new OfficeMath(doc);
officeMath.FromMathMLCode(mathMLCode[j]);
//Add the math equation to the section
Paragraph paragraph = section.AddParagraph();
paragraph.Items.Add(officeMath);
section.AddParagraph();
}
//Save the result document
doc.SaveToFile("AddMathEquations.docx", FileFormat.Docx2013);
doc.Dispose();
}
}
}

Apply for a Temporary License
If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.
A signature confirms that the digital document originated from the signer and has not been tampered with during transit. The use of digital signatures eliminates the need for sending paper documents, and reduces the number of the documents that need to be printed, mailed, and stored, saving you time and money. In this article, you will learn how to digitally sign 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
Add a Digital Signature to Word in C#, VB.NET
The steps are as follows.
- Create a Document object.
- Load a Word document using Document.LoadFromFile() method.
- Specify the path and the password of a .pfx certificate.
- Digitally sign the document while saving the document using Document.SaveToFile(string fileName, FileFormat fileFormat, string certificatePath, string securePassword) method. Here are some other methods that you can use to digitally sign a Word document.
- public void SaveToFile(string fileName, FileFormat fileFormat, byte[] certificateData, string securePassword);
- public void SaveToStream(Stream stream, FileFormat fileFormat, byte[] certificateData, string securePassword);
- public void SaveToStream(Stream stream, FileFormat fileFormat, string certificatePath, string securePassword);
- public static byte[] Document.Sign(Stream sourceStream, byte[] certificateData, string securePassword);
- public static byte[] Document.Sign(Stream sourceStream, string certificatePath, string securePassword);
- C#
- VB.NET
using Spire.Doc;
namespace DigitallySignWord
{
class Program
{
static void Main(string[] args)
{
//Create a Document object
Document doc = new Document();
//Load a Word file
doc.LoadFromFile("C:\\Users\\Administrator\\Desktop\\sample.docx");
//Specify the certificate path
string certificatePath = "C:\\Users\\Administrator\\Desktop\\gary.pfx";
//Specify the password of the certificate
string password = "e-iceblue";
//Digitally sign the document while saving it to a .docx file
doc.SaveToFile("AddDigitalSignature.docx", FileFormat.Docx2013, certificatePath, password);
}
}
}

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.
Add checkbox and picture content control to word document in C#
2019-05-29 07:31:42 Written by KoohjiBesides the Combo Box, Text, Date Picker and Drop-Down List content controls, Checkbox and picture content control also are the mostly used content control in word document. Spire.Doc supports to add many kinds of content controls to the word document. This article will show you how to add checkbox and picture content control to word document by Spire.Doc for .NET.
Code snippets of how to add checkbox and picture content control:
using System;
using System.Drawing;
namespace AddCheckbox
{
class Program
{
static void Main(string[] args)
{
//Create a new word document
Document document = new Document();
//Add a section to the document
Section section = document.AddSection();
//Add a document to the section
Paragraph paragraph = section.AddParagraph();
//Add checkbox content control
StructureDocumentTagInline sdt = new StructureDocumentTagInline(document);
paragraph = section.AddParagraph();
sdt = new StructureDocumentTagInline(document);
sdt.CharacterFormat.FontSize = 20;
paragraph.ChildObjects.Add(sdt);
sdt.SDTProperties.SDTType = SdtType.CheckBox;
SdtCheckBox scb = new SdtCheckBox();
sdt.SDTProperties.ControlProperties = scb;
TextRange tr = new TextRange(document);
tr.CharacterFormat.FontName = "MS Gothic";
tr.CharacterFormat.FontSize = 20;
sdt.ChildObjects.Add(tr);
scb.Checked = true;
sdt.SDTProperties.Alias = "CheckoBox";
sdt.SDTProperties.Tag = "Checkbox";
//Add picture content control
paragraph = section.AddParagraph();
sdt = new StructureDocumentTagInline(document);
paragraph.ChildObjects.Add(sdt);
sdt.SDTProperties.ControlProperties = new SdtPicture();
sdt.SDTProperties.Alias = "Picture";
sdt.SDTProperties.Tag = "Picture";
DocPicture pic = new DocPicture(document) { Width = 10, Height = 10 };
pic.LoadImage(Image.FromFile("Logo.jpg"));
sdt.SDTContent.ChildObjects.Add(pic);
document.SaveToFile("Sample.docx", FileFormat.Docx2013);
}
}
}
Effective screenshot after adding checkbox and picture content control to word document:

With the help of Spire.Presentation, developers can easily add and get speaker notes on presentation slides. From v 4.4.3, Spire.Presentation supports to retain the notes when converting presentation slides to SVG. This article will show you how to keep the notes when saving presentation slides to SVG in C#.
using Spire.Presentation;
using Spire.Presentation.Drawing;
using System.IO;
using System.Collections.Generic;
namespace PPT
{
class Program
{
static void Main(string[] args)
{
//load the sample document with speaker notes
Presentation ppt = new Presentation();
ppt.LoadFromFile("Sample.pptx");
//retain the notes when converting ppt to svg
ppt.IsNoteRetained = true;
//convert presentation slides to SVG
Queue<byte[]> bytes = ppt.SaveToSVG();
int length = bytes.Count;
for (int i = 0; i < length; i++)
{
FileStream filestream = new FileStream(string.Format(@"output_{0}.svg", i), FileMode.Create);
byte[] outputBytes = bytes.Dequeue();
filestream.Write(outputBytes, 0, outputBytes.Length);
}
ppt.Dispose();
ppt.SaveToSVG();
}
}
}
Effective screenshot of retaining the speaker notes when converting presentation slides to SVG:

C# add new text strings after the searched text string in word document
2019-04-04 07:54:55 Written by KoohjiWith Spire.Doc for .NET, we can easily insert new text to word document at exact position, it also supports to insert new text after the certain text strings at many places. This article will show you how to insert new text strings after the searched text string in word document.
using Spire.Doc;
using Spire.Doc.Documents;
using Spire.Doc.Fields;
using System.Drawing;
namespace Word
{
class Program
{
static void Main(string[] args)
{
//load the sample document
Document doc = new Document();
doc.LoadFromFile("Sample.docx", FileFormat.Docx2010);
//find all the text string “New Zealand” from the sample document
TextSelection[] selections = doc.FindAllString("New Zealand", true, true);
int index = 0;
//defines text range
TextRange range = new TextRange(doc);
//insert new text string (NY) after the searched text string
foreach (TextSelection selection in selections)
{
range = selection.GetAsOneRange();
TextRange newrange = new TextRange(doc);
newrange.Text = ("(NY)");
index = range.OwnerParagraph.ChildObjects.IndexOf(range);
range.OwnerParagraph.ChildObjects.Insert(index + 1, newrange);
}
//find and highlight the newly added text string NY
TextSelection[] text2 = doc.FindAllString("NY", false, true);
foreach (TextSelection seletion in text2)
{
seletion.GetAsOneRange().CharacterFormat.HighlightColor = Color.Yellow;
}
//save the document
doc.SaveToFile("Result.docx", FileFormat.Docx2010);
}
}
}
Effective screenshot after adding the text strings to the searched text:

Page labels are used to identify each page visually on the screen or in print. This article demonstrates how to get the PDF page labels using Spire.PDF.
Below is the screenshot of the sample PDF document:

Detail steps:
Step 1: Create a PdfDocument instance and load the sample.pdf file.
PdfDocument pdf = new PdfDocument();
pdf.LoadFromFile("sample.pdf");
Step 2: Get the labels of the pages in the PDF file.
StringBuilder sb = new StringBuilder();
for (int i = 0; i < pdf.Pages.Count; i++)
{
sb.AppendLine(pdf.Pages[i].PageLabel);
}
Step 3: Save to a .txt file.
File.WriteAllText("PageLabels.txt", sb.ToString());
Output:

Full code:
using System.IO;
using System.Text;
using Spire.Pdf;
namespace Get_PDF_Page_Labels
{
class Program
{
static void Main(string[] args)
{
//Create a PdfDocument instance
PdfDocument pdf = new PdfDocument();
//Load the PDF file
pdf.LoadFromFile("sample.pdf");
//Create a StringBuilder instance
StringBuilder sb = new StringBuilder();
//Get the lables of the pages in the PDF file
for (int i = 0; i < pdf.Pages.Count; i++)
{
sb.AppendLine(pdf.Pages[i].PageLabel);
}
//Save to a .txt file
File.WriteAllText("PageLabels.txt", sb.ToString());
}
}
}
With Spire.XLS, developers can add text or image to the textbox to Excel worksheet easily. From version 9.3.10, Spire.XLS supports to set the inner margin of contents on Excel text box. With this feature, we can adjust the position of the text contents on the textbox to make it beautiful. This article is going to introduce how to set the inner margins of the textbox in Excel worksheet in C#.
using Spire.Xls;
using Spire.Xls.Core.Spreadsheet.Shapes;
namespace SetInternalMargin
{
class Program
{
static void Main(string[] args)
{
{
//load the sample document
Workbook workbook = new Workbook();
workbook.LoadFromFile("Sample.xlsx", ExcelVersion.Version2010);
//get the first worksheet
Worksheet sheet = workbook.Worksheets[0];
//add a textbox to the sheet and set its position and size
XlsTextBoxShape textbox = sheet.TextBoxes.AddTextBox(4, 2, 100, 300) as XlsTextBoxShape;
//set the text on the textbox
textbox.Text = "Insert TextBox in Excel and set the margin for the text";
textbox.HAlignment = CommentHAlignType.Center;
textbox.VAlignment = CommentVAlignType.Center;
//set the inner margins of the contents
textbox.InnerLeftMargin = 1;
textbox.InnerRightMargin = 3;
textbox.InnerTopMargin = 1;
textbox.InnerBottomMargin = 1;
//save the document to file
workbook.SaveToFile("Result.xlsx", ExcelVersion.Version2010);
}
}
}
}
Effective screenshot after setting the margins of the contents:

When working with Excel files programmatically in C#, determining the data type of a cell is critical for accurate data processing. Whether you're validating user inputs, parsing spreadsheets, or migrating data, knowing how to get the cell data types ensures your application handles information correctly.
In this guide, you'll learn how to use Spire.XLS for .NET library to check the cell data types in Excel in C#, covering the following aspects:
- Install the .NET Excel Library
- Learn the Cell Data Types in Spire.XLS
- How to Get Cell Data Type in Excel in C#
Install the .NET Excel Library
Before proceeding, you need to have the Spire.XLS for .NET library installed in your project. A recommended way to install it is via NuGet, and there are two available options:
- 1.Right-click the project in “Solution Explorer -> Manage NuGet Packages”. Search for “Spire.XLS” and install the latest version.
- 2.Go to “Tools -> NuGet Package Manager -> Package Manager Console”, and then run the following command:
PM> Install-Package Spire.XLS
Alternatively, you can download the library from this link and manually add the DLL files as references.
Learn the Cell Data Types in Spire.XLS
Spire.XLS provides the XlsWorksheet.TRangeValueType enumeration to represents the cell value types. It includes following members:
| Cell Type | Description |
| String | Represents the cells that store alphanumeric characters, including numbers stored as text. |
| Number | Represents the cells that contain numeric value, including integers, decimals, scientific notation, and date-time values. |
| Formula | Represents the cells that contain a formula. |
| Blank | Represents the cells contain no data. |
| Boolean | Represents the cells that contain TRUE or FALSE. |
| Error | Represents the cells may display errors as #VALUE! or #N/A due to invalid operations. |
How to Get Cell Data Type in Excel in C#
To check the value type of a cell, you need to follow the below steps.
- Create a Workbook object.
- Load an XLS or XLSX Excel file, and then get a specified worksheet within it.
- Get a specified cell range in the sheet though the Worksheet.Range[] property.
- Iterate through each cell in the cell range.
- Get the row number and column number of the current cell.
- Call the Worksheet.GetCellType(int row, int column, bool bNeedFormulaSubType) method to get the value type of the current cell, and return a specific enumeration member of the XlsWorksheet.TRangeValueType enumeration type.
- Converts the value of the enumeration member to its corresponding text string.
- Write the text string to another cell and set its font style.
- Save the result file using the Workbook.SaveToFile() method.
- Sample C# Code
using System.Drawing;
using Spire.Xls;
using Spire.Xls.Core.Spreadsheet;
namespace GetCellType
{
class Program
{
static void Main(string[] args)
{
// Create a Workbook object
Workbook workbook = new Workbook();
// Load an Excel file
workbook.LoadFromFile("Test1.xlsx");
// Get the first worksheet
Worksheet sheet = workbook.Worksheets[0];
// Get a specified cell range
CellRange range = sheet.Range["A2:A8"];
// Iterate through all cells in the range
foreach (CellRange cell in range)
{
// Get the row number and column number of the current cell
int row = cell.Row;
int column = cell.Column;
// Get the value type of the current cell
XlsWorksheet.TRangeValueType cellType = sheet.GetCellType(row, column, false);
// Convert the cell type value to a text string and write to another cell
sheet[row, column + 1].Text = cellType.ToString();
// Set the font style of the output cell
sheet[row, column + 1].Style.Font.Color = Color.Red;
sheet[row, column + 1].Style.Font.IsBold = true;
}
// Save the result file
workbook.SaveToFile("GetCellType.xlsx", ExcelVersion.Version2016);
}
}
}
A screenshot of the result file:

Conclusion
Spire.XLS simplifies checking Excel cell data types in C# with its intuitive API. By leveraging the GetCellType() method, you can accurately determine whether a cell contains a number, string, boolean, etc. This approach ensures robust data processing for applications that interact with Excel files.
Get a Free License
To fully experience the capabilities of Spire.XLS for .NET without any evaluation limitations, you can request a free 30-day trial license.
To emphasize the text on a shape, we can only animate text instead of the whole shape. This article demonstrates how to apply animations to text in PowerPoint using Spire.Presenstation with C# and VB.NET.
Code Snippets
//create a PowerPoint document
Presentation ppt = new Presentation();
//get the first slide
ISlide slide = ppt.Slides[0];
//add a shape to the slide
IAutoShape shape = slide.Shapes.AppendShape(ShapeType.Rectangle, new RectangleF(50, 50, 200, 80));
shape.Fill.FillType = FillFormatType.Solid;
shape.Fill.SolidColor.Color = Color.Purple;
shape.ShapeStyle.LineColor.Color = Color.White;
shape.AppendTextFrame("Welcome to download Spire.Presentation");
//apply animation to the text in shape
AnimationEffect animation = shape.Slide.Timeline.MainSequence.AddEffect(shape, AnimationEffectType.Float);
animation.SetStartEndParagraphs(0, 0);
//save to file
ppt.SaveToFile("result.pptx", FileFormat.Pptx2013);
ppt.Dispose();
'create a PowerPoint document
Dim ppt As Presentation = New Presentation()
'get the first slide
Dim slide As ISlide = ppt.Slides(0)
'add a shape to the slide
Dim shape As IAutoShape = slide.Shapes.AppendShape(ShapeType.Rectangle,New RectangleF(50,50,200,80))
shape.Fill.FillType = FillFormatType.Solid
shape.Fill.SolidColor.Color = Color.Purple
shape.ShapeStyle.LineColor.Color = Color.White
shape.AppendTextFrame("Welcome to download Spire.Presentation")
'apply animation to the text in shape
Dim animation As AnimationEffect = shape.Slide.Timeline.MainSequence.AddEffect(shape,AnimationEffectType.Float)
animation.SetStartEndParagraphs(0, 0)
'save to file
ppt.SaveToFile("result.pptx", FileFormat.Pptx2013)
ppt.Dispose()
Output

Digital timestamps mark a PDF signature with the time and date as proof of integrity. A timestamp shows that the contents of the document existed at a point in time, and are unchanged. This article is going to introduce how to digitally sign a PDF document with a timestamp server by using Spire.PDF.
Code Snippets
using Spire.Pdf;
using Spire.Pdf.Graphics;
using Spire.Pdf.Security;
using System.Drawing;
namespace SignPDFwithTimestamp
{
class Program
{
static void Main(string[] args)
{
//create a PdfDocument object and load a PDF file
PdfDocument doc = new PdfDocument();
doc.LoadFromFile(@"C:\Users\Administrator\Desktop\Example.pdf");
//load the certificate .pfx file
PdfCertificate cert = new PdfCertificate(@"C:\Users\Administrator\Desktop\gary.pfx", "e-iceblue");
//add a signature to the specified position
PdfSignature signature = new PdfSignature(doc, doc.Pages[0], cert, "signature");
signature.Bounds = new RectangleF(new PointF(350, 700), new SizeF(180, 90));
//set the signature content
signature.NameLabel = "Digitally signed by:Gary";
signature.LocationInfoLabel = "Location:";
signature.LocationInfo = "CN";
signature.ReasonLabel = "Reason: ";
signature.Reason = "Ensure authenticity";
signature.ContactInfoLabel = "Contact Number: ";
signature.ContactInfo = "028-81705109";
signature.DocumentPermissions = PdfCertificationFlags.AllowFormFill | PdfCertificationFlags.ForbidChanges;
signature.SignImageSource = PdfImage.FromFile(@"C:\Users\Administrator\Desktop\company-logo.jpg");
//configure a timestamp server
string url = "http://timestamp.wosign.com/rfc3161";
signature.ConfigureTimestamp(url);
//save to file
doc.SaveToFile("output.pdf");
}
}
}
Imports Spire.Pdf
Imports Spire.Pdf.Graphics
Imports Spire.Pdf.Security
Imports System.Drawing
Namespace SignPDFwithTimestamp
Class Program
Private Shared Sub Main(args As String())
'create a PdfDocument object and load a PDF file
Dim doc As PdfDocument = New PdfDocument()
doc.LoadFromFile("C:\Users\Administrator\Desktop\Example.pdf")
'load the certificate .pfx file
Dim cert As PdfCertificate = New PdfCertificate("C:\Users\Administrator\Desktop\gary.pfx","e-iceblue")
'add a signature to the specified position
Dim signature As PdfSignature = New PdfSignature(doc,doc.Pages(0),cert,"signature")
signature.Bounds = New RectangleF(New PointF(350, 700), New SizeF(180, 90))
'set the signature content
signature.NameLabel = "Digitally signed by:Gary"
signature.LocationInfoLabel = "Location:"
signature.LocationInfo = "CN"
signature.ReasonLabel = "Reason: "
signature.Reason = "Ensure authenticity"
signature.ContactInfoLabel = "Contact Number: "
signature.ContactInfo = "028-81705109"
signature.DocumentPermissions = PdfCertificationFlags.AllowFormFill Or PdfCertificationFlags.ForbidChanges
signature.SignImageSource = PdfImage.FromFile("C:\Users\Administrator\Desktop\company-logo.jpg")
'configure a timestamp server
Dim url As String = "http://timestamp.wosign.com/rfc3161"
signature.ConfigureTimestamp(url)
'save to file
doc.SaveToFile("output.pdf")
End Sub
End Class
End Namespace
Output
