.NET (1316)
Children categories
Using Excel conditional formatting, we can quickly find and highlight the duplicate and unique values in a selected cell range. In this article, we’re going to show you how to programmatically highlight duplicate and unique values with different colors using Spire.XLS and conditional formatting.
Detail steps:
Step 1: Initialize an object of Workbook class and Load the Excel file.
Workbook workbook = new Workbook();
workbook.LoadFromFile("Input.xlsx");
Step 2: Get the first worksheet.
Worksheet sheet = workbook.Worksheets[0];
Step 3: Use conditional formatting to highlight duplicate values in range "A2:A10" with IndianRed color.
ConditionalFormatWrapper format1 = sheet.Range["A2:A10"].ConditionalFormats.AddCondition(); format1.FormatType = ConditionalFormatType.DuplicateValues; format1.BackColor = Color.IndianRed;
Step 4: Use conditional formatting to highlight unique values in range "A2:A10" with Yellow color.
ConditionalFormatWrapper format2 = sheet.Range["A2:A10"].ConditionalFormats.AddCondition(); format2.FormatType = ConditionalFormatType.UniqueValues; format2.BackColor = Color.Yellow;
Step 5: Save the file.
workbook.SaveToFile("HighlightDuplicates.xlsx", ExcelVersion.Version2013);
Screenshot:

Full code:
using Spire.Xls;
using System.Drawing;
namespace HighlightDuplicateandUniqueValues
{
class Program
{
static void Main(string[] args)
{
{
//Load the Excel file
Workbook workbook = new Workbook();
workbook.LoadFromFile("Input.xlsx");
//Get the first worksheet
Worksheet sheet = workbook.Worksheets[0];
//Use conditional formatting to highlight duplicate values in range "A2:A10" with IndianRed color
ConditionalFormatWrapper format1 = sheet.Range["A2:A10"].ConditionalFormats.AddCondition();
format1.FormatType = ConditionalFormatType.DuplicateValues;
format1.BackColor = Color.IndianRed;
//Use conditional formatting to highlight unique values in range "A2:A10" with Yellow color
ConditionalFormatWrapper format2 = sheet.Range["A2:A10"].ConditionalFormats.AddCondition();
format2.FormatType = ConditionalFormatType.UniqueValues;
format2.BackColor = Color.Yellow;
//Save the file
workbook.SaveToFile("HighlightDuplicates.xlsx", ExcelVersion.Version2013);
}
}
}
}
How to set the position and number format for word footnote in C#
2017-12-11 08:22:32 Written by KoohjiWe have already demonstrated how to insert footnote to the word document with the help of Spire.Doc. This article we will show you how to set the position and number format for the footnote. The footnote position can be at the bottom of each page or below text. The default number format for the footnote is “1, 2, 3”. The following example shows how to set the position, number format, and the restart rule of footnote by calling the property of Section.FootnoteOptions.
Firstly, view the Footnote options under Microsoft Word and the original sample document file:



Step 1: Create a new instance of Document and load the document from file.
Document doc = new Document();
doc.LoadFromFile("Sample.docx",FileFormat.Docx2013);
Step 2: Get the first section from the document.
Section sec = doc.Sections[0];
Step 3: Set the number format, restart rule and position for the footnote.
sec.FootnoteOptions.NumberFormat = FootnoteNumberFormat.UpperCaseLetter; sec.FootnoteOptions.RestartRule = FootnoteRestartRule.RestartPage; sec.FootnoteOptions.Position = FootnotePosition.PrintAtBottomOfPage;
Step 4: Save the document to file.
doc.SaveToFile("Footnoteoptions.docx", FileFormat.Docx2013);
Effective screenshot after setting the formatting for the footnote.


Full codes of how to set the footnote options:
Document doc = new Document();
doc.LoadFromFile("Sample.docx", FileFormat.Docx2013);
Section sec = doc.Sections[0];
sec.FootnoteOptions.NumberFormat = FootnoteNumberFormat.UpperCaseLetter;
sec.FootnoteOptions.RestartRule = FootnoteRestartRule.RestartPage;
sec.FootnoteOptions.Position = FootnotePosition.PrintAtBottomOfPage;
////Clear all the formatting for the footnote and back to the default opitions
//sec.FootnoteOptions.ClearFormatting();
doc.SaveToFile("Footnoteoptions.docx", FileFormat.Docx2013);
Add text watermark and image watermark to word document in C#
2017-12-08 09:05:33 Written by zaki zouText watermark and image watermark are two kinds of watermarks in Word document. The text watermark always shows some additional but related information to the word context. While image watermark is used to make the Word document be more attractive. This section will demonstrate how to use Spire.Doc to add text watermark and image watermark to Word document in C#.
Add Image Watermark in C#:
using Spire.Doc;
namespace SetImageWatermark
{
class Program
{
static void Main(string[] args)
{
{
//create a new instance of Document and load the document from file.
Document doc = new Document();
doc.LoadFromFile("Sample.docx", FileFormat.Docx2013);
//create a new instance of the PictureWatermark and load the picture from file.
PictureWatermark picture = new PictureWatermark();
picture.Picture = System.Drawing.Image.FromFile("logo.png");
//set the image watermark scaling and Washout property
picture.Scaling = 20;
picture.IsWashout = false;
//add the picture watermark
doc.Watermark = picture;
//save the document to file
doc.SaveToFile("ImageWatermark.docx", FileFormat.Docx2013);
}
}
}
}

Add Text Watermark in C#::
using Spire.Doc;
using Spire.Doc.Documents;
using System.Drawing;
namespace SetTextWatermark
{
class Program
{
static void Main(string[] args)
{
{
//create a new instance of Document and load the document from file.
Document doc = new Document();
doc.LoadFromFile("Sample.docx", FileFormat.Docx2013);
//create a new instance of the TextWatermark
TextWatermark txtWatermark = new TextWatermark();
//set the text watermark with text string, font, color and layout.
txtWatermark.Text = "Confidential";
txtWatermark.FontSize = 45;
txtWatermark.Color = Color.Green;
txtWatermark.Layout = WatermarkLayout.Diagonal;
//add the text watermark
doc.Watermark = txtWatermark;
//save the file.
doc.SaveToFile("TextWatermark.docx", FileFormat.Docx2013);
}
}
}
}

Microsoft Excel provides 10 date options, ranging from yesterday to next month (see below image) to format selected cells based on the current date. Spire.XLS supports all of these options, in this article, we’re going to show you how to conditionally format dates in Excel using Spire.XLS. If you want to highlight cells based on a date in another cell, or create rules for other dates (i.e., more than a month from the current date), you will have to create your own conditional formatting rule based on a formula.

Detail steps:
Step 1: Initialize an object of Workbook class and load the Excel file.
Workbook workbook = new Workbook();
workbook.LoadFromFile("Input.xlsx");
Step 2: Get the first worksheet.
Worksheet sheet = workbook.Worksheets[0];
Step 3: Add a condition to the used range in the worksheet.
ConditionalFormatWrapper conditionalFormat = sheet.AllocatedRange.ConditionalFormats.AddCondition();
Step 4: Specify the format type of the condition as time period and set the time period as last 7 days.
conditionalFormat.FormatType = ConditionalFormatType.TimePeriod; conditionalFormat.SetTimePeriod(TimePeriodType.Last7Days);
Step 5:Set the highlight color.
conditionalFormat.BackColor = Color.Orange;
Step 6:Save the file.
workbook.SaveToFile("ConditionallyFormatDates.xlsx", ExcelVersion.Version2013);
Screenshot::

Full Code:
using Spire.Xls;
using Spire.Xls.Core.Spreadsheet.ConditionalFormatting;
using System.Drawing;
namespace ConditionallyFormatDates
{
class Program
{
static void Main(string[] args)
{
{
//Initialize an object of Workbook class
Workbook workbook = new Workbook();
//Load the Excel file
workbook.LoadFromFile("Input.xlsx");
//Get the first worksheet
Worksheet sheet = workbook.Worksheets[0];
//Highlight cells that contain a date occurring in the last 7 days
ConditionalFormatWrapper conditionalFormat = sheet.AllocatedRange.ConditionalFormats.AddCondition();
conditionalFormat.FormatType = ConditionalFormatType.TimePeriod;
conditionalFormat.SetTimePeriod(TimePeriodType.Last7Days);
conditionalFormat.BackColor = Color.Orange;
//Save the file
workbook.SaveToFile("ConditionallyFormatDates.xlsx", ExcelVersion.Version2013);
}
}
}
}
It is possible to add text transparency to any text shape in PowerPoint. In order to make the text transparent, we’d need to apply the transparency level to the text shape. This article will show you how to set the transparency level of text using Spire.Presentation.
Step 1: Create a Presentation instance.
Presentation ppt = new Presentation();
Step 2: Add a shape to the first slide.
IAutoShape textboxShape = ppt.Slides[0].Shapes.AppendShape(ShapeType.Rectangle, new RectangleF(50, 70,300, 120)); textboxShape.ShapeStyle.LineColor.Color = Color.Transparent; textboxShape.Fill.FillType = FillFormatType.None;
Step 3: Add text to shape.
textboxShape.TextFrame.Text = "Text Transparency";
Step 4: Set the fill type of TextRange to solid, and fill the TextRange using the color created with specified alpha value.
textboxShape.TextFrame.TextRange.Fill.FillType = FillFormatType.Solid; int alpha = 55; textboxShape.TextFrame.TextRange.Fill.SolidColor.Color = Color.FromArgb(alpha, Color.Purple);
Step 5:Save the file.
ppt.SaveToFile("result.pptx", FileFormat.Pptx2013);
Output:

Full Code:
using Spire.Presentation;
using Spire.Presentation.Drawing;
using System.Drawing;
namespace ApplyTransparency
{
class Program
{
static void Main(string[] args)
{
//create a PowerPoint document
Presentation ppt = new Presentation();
ppt.SlideSize.Type = SlideSizeType.Screen16x9;
//add a shape
IAutoShape textboxShape = ppt.Slides[0].Shapes.AppendShape(ShapeType.Rectangle, new RectangleF(50, 70, 300, 120));
textboxShape.ShapeStyle.LineColor.Color = Color.Transparent;
textboxShape.Fill.FillType = FillFormatType.None;
//remove default blank paragraphs
textboxShape.TextFrame.Paragraphs.Clear();
//add three paragraphs, apply color with different alpha values to text
int alpha = 55;
for (int i = 0; i < 3; i++)
{
textboxShape.TextFrame.Paragraphs.Append(new TextParagraph());
textboxShape.TextFrame.Paragraphs[i].TextRanges.Append(new TextRange("Text Transparency"));
textboxShape.TextFrame.Paragraphs[i].TextRanges[0].Fill.FillType = FillFormatType.Solid;
textboxShape.TextFrame.Paragraphs[i].TextRanges[0].Fill.SolidColor.Color = Color.FromArgb(alpha, Color.Purple);
alpha += 100;
}
//save to file
ppt.SaveToFile("result.pptx", FileFormat.Pptx2013);
}
}
}
Imports Spire.Presentation
Imports Spire.Presentation.Drawing
Imports System.Drawing
Namespace ApplyTransparency
Class Program
Private Shared Sub Main(args As String())
'create a PowerPoint document
Dim ppt As New Presentation()
ppt.SlideSize.Type = SlideSizeType.Screen16x9
'add a shape
Dim textboxShape As IAutoShape = ppt.Slides(0).Shapes.AppendShape(ShapeType.Rectangle, New RectangleF(50, 70, 300, 120))
textboxShape.ShapeStyle.LineColor.Color = Color.Transparent
textboxShape.Fill.FillType = FillFormatType.None
'remove default blank paragraphs
textboxShape.TextFrame.Paragraphs.Clear()
'add three paragraphs, apply color with different alpha values to text
Dim alpha As Integer = 55
For i As Integer = 0 To 2
textboxShape.TextFrame.Paragraphs.Append(New TextParagraph())
textboxShape.TextFrame.Paragraphs(i).TextRanges.Append(New TextRange("Text Transparency"))
textboxShape.TextFrame.Paragraphs(i).TextRanges(0).Fill.FillType = FillFormatType.Solid
textboxShape.TextFrame.Paragraphs(i).TextRanges(0).Fill.SolidColor.Color = Color.FromArgb(alpha, Color.Purple)
alpha += 100
Next
'save to file
ppt.SaveToFile("result.pptx", FileFormat.Pptx2013)
End Sub
End Class
End Namespace
If your worksheet has some important formulas that you don’t want others to view, you may want to hide these formulas. This article demonstrates how to hide formulas when protecting a worksheet using Spire.XLS and C#.
The XlsRange.IsFormulaHidden property is used to determine if the formula will be hidden when the worksheet is protected. You can hide the formulas in a specific cell range by setting the XlsRange.IsFormulaHidden property to true, but note that the formulas can be hidden only if the worksheet is protected, they won’t be hidden if the workbook is protected while the worksheet is not.
using Spire.Xls;
namespace HideFormulas
{
class Program
{
static void Main(string[] args)
{
//Initialize an object of Workbook class
Workbook workbook = new Workbook();
//Load the Excel file
workbook.LoadFromFile("Input.xlsx");
//Get the first worksheet
Worksheet sheet = workbook.Worksheets[0];
//Hide the formulas in the used range
sheet.AllocatedRange.IsFormulaHidden = true;
//Protect the worksheet with password
sheet.Protect("123");
//Save the file
workbook.SaveToFile("HideFormulas.xlsx", ExcelVersion.Version2013);
}
}
}
Screenshot:

In today's digital landscape, PDFs carry sensitive contracts, financial reports, and personal data. A single breach can lead to compliance violations or intellectual property theft. To protect your PDFs from unauthorized access, it’s necessary to encrypt them.

Spire.PDF for .NET provides enterprise-grade PDF security solution, enabling developers to easily implement PDF encryption/decryption workflows in .NET applications. This article will provide practical examples to show you how to use C# to encrypt PDF or decrypt PDF.
- .NET Library for PDF Security
- What is Involved in PDF Encryption?
- How to Encrypt a PDF in C# (Code Example)
- How to Decrypt a PDF in C# (Steps & Code)
- FAQs
.NET Library for PDF Security
Why Use Spire.PDF?
Spire.PDF is a robust, standalone .NET library designed to create, edit, convert and secure PDF documents without Adobe Acrobat. Speaking of its security features, it enables developers to:
- Apply AES/RC4 encryption with password protection
- Restrict printing/copying/editing permissions
- Support .NET Framework, ASP.NET Core, and .NET 5+
Installation Guide
Method 1: NuGet Package Manager (Recommended)
- Open your project in Visual Studio
- Go to “Tools -> NuGet Package Manager -> Package Manager Console”
- Run the following:
PM> Install-Package Spire.PDF
Method 2: Manual Installation
- Download DLL from Spire.PDF Official Site
- Right-click your project in Solution Explorer
- Go to “Add-> Reference -> Browse -> Select Spire.PDF.dll”.
What is Involved in PDF Encryption?
Spire.PDF allows developers to encrypt PDF with passwords, set encryption algorithm, and set permissions. Below is a comprehensive technical breakdown:
User & Owner Passwords
- User Password (Open Password): Required to open and view the PDF.
- Owner Password (Permissions Password): Controls security permissions (printing, copying, editing)
Critical Security Rule: The owner password overrides user password restrictions. If a PDF file is encrypted with both passwords, it can be opened with either one. 
Example code:
PdfSecurityPolicy securityPolicy = new PdfPasswordSecurityPolicy(
"user123", // Open password
"e-iceblue" // Permission password
);
Encryption Algorithms (RC4 and AES Encrypt)
Spire.PDF supports industry-standard encryption methods with varying key strengths:
| Algorithm | Key Length | Security Level | Use Case |
|---|---|---|---|
| AES | 128/256-bit | Military-grade | Sensitive documents (Default) |
| RC4 | 40/128-bit | Legacy | Backward compatibility |
Example code:
securityPolicy.EncryptionAlgorithm = PdfEncryptionAlgorithm.AES_256;
Permission Flags
Permission flags control user actions on encrypted PDF documents after opening. These flags are controlled via the properties of the PdfDocumentPrivilege class. Here are some common permission flags.
| Properties | Description |
|---|---|
| AllowContentCopying | Gets or sets the permission which allow copy contents or not. |
| AllowPrint | Gets or sets the permission which allow print or not. |
| AllowModifyContents | Gets or sets the permission which allow modify contents or not. |
| AllowFillFormFields | Gets or sets the permission which allow fill in form fields or not. |
| AllowAll | All allowed. |
| ForbidAll | All forbidden. |
Example code:
securityPolicy.DocumentPrivilege.AllowPrint = false; // Disable printing
securityPolicy.DocumentPrivilege.AllowContentCopying = false; // Disable copying
How to Encrypt a PDF in C# (Code Example)
The following C# code password protects a PDF file with AES-256 encryption and restrict permissions.
using Spire.Pdf;
namespace EncryptPDF
{
class Program
{
static void Main(string[] args)
{
// Create a PdfDocument object
PdfDocument pdf = new PdfDocument();
// Load a sample PDF file
pdf.LoadFromFile("sample.pdf");
// Specify the user and owner passwords
string userPassword = "user123";
string ownerPassword = "e-iceblue";
// Create a PdfSecurityPolicy object with the two passwords
PdfSecurityPolicy securityPolicy = new PdfPasswordSecurityPolicy(userPassword, ownerPassword);
// Set encryption algorithm
securityPolicy.EncryptionAlgorithm = PdfEncryptionAlgorithm.AES_256;
// Set document permissions (If you do not set, the default is ForbidAll)
securityPolicy.DocumentPrivilege = PdfDocumentPrivilege.AllowAll;
// Restrict printing and content copying
securityPolicy.DocumentPrivilege.AllowPrint = false;
securityPolicy.DocumentPrivilege.AllowContentCopying = false;
// Encrypt the PDF file
pdf.Encrypt(securityPolicy);
// Save the result file
pdf.SaveToFile("EncryptPDF.pdf", FileFormat.PDF);
}
}
}
The encrypted PDF will:
- Require a password to open.

- Block printing and copying content. Retain all other permissions (editing, form filling, etc.).

How to Decrypt a PDF in C# (Steps & Code)
Decrypt PDF removes passwords and restrictions, allowing full access to the document. With Spire.PDF, you can decrypt a password-protected PDF file in C# with <5 lines of code.
Main Steps:
- Open Encrypted PDF: Load your encrypted PDF file with the owner password.
- Remove Encryption: Invoke the Decrypt() method to remove all security restrictions.
- Save Decrypted PDF: Call the SaveToFile() method to save the decrypted PDF to the specified file path.
Code Example:
The following C# code removes the PDF passwords and restores access.
using Spire.Pdf;
namespace DecryptPDF
{
class Program
{
static void Main(string[] args)
{
// Create a PdfDocument object
PdfDocument pdf = new PdfDocument();
// Load a sample PDF file with owner password
pdf.LoadFromFile("EncryptPDF.pdf", "e-iceblue");
// Decrypt the PDF file
pdf.Decrypt();
// Save the Decrypted PDF
pdf.SaveToFile("DecryptPDF.pdf");
}
}
}
Open the decrypted PDF:

Conclusion
Securing PDFs with encryption is essential for protecting sensitive data. With Spire.PDF for .NET, developers can effortlessly encrypt, decrypt, and manage permissions in PDF files using C#. The .NET PDF library’s comprehensive features and straightforward implementation make it an ideal choice for enhancing document security in enterprise applications.
Next Steps:
- Getting started with Spire.PDF and request a free 30-day trial license to fully evaluate it.
- Explore the Online Documentation for more PDF protection features such as adding digital signatures, adding watermarks, and more.
FAQs
Q1: Can I encrypt a PDF without a user password?
A: Yes. Set the user password to an empty string and use the owner password to control permissions.
Q2: What encryption standards are supported?
A: Spire.PDF supports:
- 40-bit RC4 (legacy)
- 128-bit RC4/AES (standard)
- 256-bit AES (highest security)
Recommend 256-bit AES for sensitive data compliance (e.g., HIPAA, GDPR).
Q3: How to handle incorrect passwords when decrypting?
A: Use try-catch blocks to handle exceptions:
try
{
pdf.LoadFromFile("EncryptPDF.pdf", " wrongPassword");
}
catch (Exception ex)
{
Console.WriteLine($"Error: {ex.Message}");
}
Q4. How to check if a PDF is encrypted?
A: Use the PdfDocument.IsPasswordProtected(string fileName) method. A comprehensive guide can be found at: Check Whether a PDF is Password Protected in C#
EAN-13, based upon the UPC-A standard, is used world-wide for marking retail goods. The 13-digit EAN-13 number consists of four components:
- Country code - 2 or 3 digits
- Manufacturer Code - 5 to 7 digits
- Product Code - 3 to 5 digits
- Check digit - last digit
The following code snippets demonstrate how to create EAN-13 barcode image using Spire.Barcode in C#.
Step 1: Create a BarcodeSettings instance.
BarcodeSettings settings = new BarcodeSettings();
Step 2: Set the barcode type as EAN13.
settings.Type = BarCodeType.EAN13;
Step 3: Set the data to encode.
settings.Data = "123456789012";
Step 4: Calculate checksum and add the check digit to barcode.
settings.UseChecksum = CheckSumMode.ForceEnable;
Step 5: Display barcode's text on bottom and centrally align the text.
settings.ShowTextOnBottom = true; settings.TextAlignment = StringAlignment.Center;
Step 6: Generate barcode image based on the settings and save it in .png format.
BarCodeGenerator generator = new BarCodeGenerator(settings);
Image image = generator.GenerateImage();
image.Save("EAN-13.png", System.Drawing.Imaging.ImageFormat.Png);
Output:

Full Code:
using Spire.Barcode;
using System.Drawing;
namespace EAN-13
{
class Program
{
static void Main(string[] args)
{
BarcodeSettings settings = new BarcodeSettings();
settings.Type = BarCodeType.EAN13;
settings.Data = "123456789012";
settings.UseChecksum = CheckSumMode.ForceEnable;
settings.ShowTextOnBottom = true;
settings.TextAlignment = StringAlignment.Center;
BarCodeGenerator generator = new BarCodeGenerator(settings);
Image image = generator.GenerateImage();
image.Save("EAN-13.png", System.Drawing.Imaging.ImageFormat.Png);
}
}
}
When we work with the pie chart on the presentation slide, we may need to separate each part of pie chart to make them stand out. This article is going to introduce the method of how to set the pie explosion for the pie chart on the presentation slides in C# by using Spire.Presentation.
Spire.Presentation offers a property of chart.Series[].Distance to enable developers to pull the whole pie apart by exploding the pie chart.
On Microsoft PowerPoint, We can adjust the percentage of "Pie Explosion" on the Series Options at the "Format Data Series" area to control the distance between each section in the chart.

Step 1: Create a presentation document and load the file from disk.
Presentation ppt = new Presentation();
ppt.LoadFromFile("Sample.pptx");
Step 2: Get the chart that needs to set the point explosion.
IChart chart = ppt.Slides[0].Shapes[0] as IChart;
Step 3: Explode the pie chart.
chart.Series[0].Distance = 15;
Step 4: Save the document to file.
ppt.SaveToFile("Result.pptx", FileFormat.Pptx2010);
Effective screenshots after exploding the pie chart on presentation slide:

Full codes:
using Spire.Presentation;
using Spire.Presentation.Charts;
namespace ExplodePie
{
class Program
{
static void Main(string[] args)
{
Presentation ppt = new Presentation();
ppt.LoadFromFile("Sample.pptx");
IChart chart = ppt.Slides[0].Shapes[0] as IChart;
chart.Series[0].Distance = 15;
ppt.SaveToFile("Result.pptx", FileFormat.Pptx2010);
}
}
}
At some point, we may want to display a PDF file as it will appear when printed. This article demonstrates how to show print preview of a PDF file in Windows Forms application using Spire.PDF and c#.
Before using the following code, we need to create a windows forms application, add a PrintPreviewControl control to the form and reference Spire.Pdf.dll into the application.
using System;
using System.Windows.Forms;
using Spire.Pdf;
namespace PreviewPDF
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void printPreviewControl1_Click(object sender, EventArgs e)
{
//Load PDF file
PdfDocument pdf = new PdfDocument();
pdf.LoadFromFile("New Zealand.pdf");
//Set the PrintPreviewControl.Rows and PrintPreviewControl.Columns properties to show multiple pages
this.printPreviewControl1.Rows = 2;
this.printPreviewControl1.Columns = 2;
//Preview the pdf file
pdf.Preview(this.printPreviewControl1);
}
}
}
Screenshot:
