.NET (1333)
Children categories
Read Email in C# via IMAP and POP3 (Outlook Example Included)
2025-07-30 08:56:03 Written by zaki zaki
Reading emails using C# is a common task in enterprise applications where automatic email processing is needed. For example, customer support systems retrieve tickets from email inboxes, financial platforms extract PDF invoices from attachments, and workflow tools react to notification emails. These applications require access to message content, metadata (sender, subject, timestamp), and attachments.
In this article, we’ll walk through how to read emails in C# using IMAP and POP3, and access Gmail or Outlook mailboxes securely with OAuth 2.0. We'll use Spire.Email for .NET, a library that simplifies email client implementation by providing a unified API for IMAP, POP3, and SMTP. It supports both OAuth and password-based authentication, and allows parsing full MIME messages including headers, bodies, and attachments.
This article covers:
- Environment Setup
- Authenticate Email Access via OAuth
- Read Emails Using IMAP in C#
- Read Emails via POP3 in C#
- Extract Attachments and Plain Text
- Summary
- Frequently Asked Questions
Environment Setup
To follow this tutorial, you’ll need the following:
- A .NET development environment (e.g., Visual Studio)
- Spire.Email for .NET (Install via NuGet: Install-Package Spire.Email)
- Access to a Gmail or Outlook account with OAuth 2.0 enabled
Spire.Email for .NET supports standard email protocols—IMAP, POP3, and SMTP—and provides built-in functionality for MIME parsing, attachments, HTML rendering, and encoding handling.
You can also try Free Spire.Email for .NET if your project is small or for evaluation.
Authenticate Email Access via OAuth
Modern email providers such as Gmail and Outlook require OAuth 2.0 for secure and token-based access to IMAP and POP3 services. Gmail still supports app passwords for POP3 in some cases, but OAuth is the preferred and more secure method.
Here’s how to use MSAL.NET to acquire an access token for Outlook:
var app = PublicClientApplicationBuilder
.Create("your-client-id")
.WithDefaultRedirectUri()
.Build();
string[] scopes = new[] { "https://outlook.office365.com/IMAP.AccessAsUser.All" };
AuthenticationResult result = await app
.AcquireTokenInteractive(scopes)
.ExecuteAsync();
string accessToken = result.AccessToken;
For Gmail, you can use Google.Apis.Auth or any OAuth 2.0 compliant method to retrieve a token with the https://mail.google.com/ scope. This token can then be passed to Spire.Email for authentication.
Read Emails Using IMAP in C# from Outlook and Gmail
To read emails from Outlook or Gmail in C#, IMAP is a widely used protocol that allows access to mailbox folders, message flags, and full message content. With Spire.Email for .NET, you can use the ImapClient class to connect securely to IMAP servers using OAuth tokens.
The following C# example demonstrates how to read emails from Outlook's IMAP server:
using Spire.Email;
using Spire.Email.IMap;
using System.Text;
class Program
{
static void Main()
{
ImapClient client = new ImapClient();
// Connect to IMAP server (Outlook)
client.Host = "outlook.office365.com";
client.Port = 993;
client.ConnectionProtocols = ConnectionProtocols.Ssl;
// Use OAuth 2.0
client.UseOAuth = true;
client.Username = "[email protected]";
client.AccessToken = "your-access-token";
client.Connect();
client.Login();
// Retrieve message count in the Inbox
int messageCount = client.GetMessageCount("Inbox");
StringBuilder messageDetails = new StringBuilder();
for (int i = 0; i <= messageCount; i++)
{
MailMessage message = client.GetFullMessage(i);
messageDetails.AppendLine("Message: " + i);
messageDetails.AppendLine("Subject: " + message.Subject);
messageDetails.AppendLine("From: " + message.From.Address);
messageDetails.AppendLine("Date: " + message.Date);
messageDetails.AppendLine("Body (HTML): " + message.BodyHtml);
}
File.WriteAllText("MessageInfo.txt", messageDetails.ToString());
client.Disconnect();
}
}
Technical Details
- ImapClient: Represents an IMAP client connection. It handles server communication and supports OAuth-based authentication via the UseOAuth property.
- Host and Port: Set the server address and port number. For Outlook, you can use "outlook.office365.com" and port 993 with SSL.
- AccessToken: Replace "your-access-token" with a valid token obtained via Microsoft or Google OAuth 2.0 flow.
- GetMessageCount("Inbox"): Retrieves the number of emails in the specified folder.
- GetFullMessage(i): Retrieves the full content of the message at the specified index as a MailMessage object.
- MailMessage: Represents an email message. Properties like Subject, From, Date, and BodyHtml allow structured access to message details.
The following screenshot shows the extracted email subject, sender, and HTML body saved from Outlook using IMAP:

By combining Spire.Email’s IMAP interface with OAuth security and flexible MIME parsing, you can reliably automate email reading in C# with full access to both content and context.
If you need examples of how to send emails, please refer to How to Send Emails Using C#.
Read Emails via POP3 in C#
If folder management and server-side search are not required, POP3 offers a simpler alternative to IMAP. The following example demonstrates how to read emails using POP3 with Spire.Email.
using Spire.Email;
using Spire.Email.Pop3;
Pop3Client popClient = new Pop3Client();
popClient.Host = "pop.gmail.com";
popClient.Port = 995;
popClient.EnableSsl = true;
popClient.Username = "[email protected]";
popClient.Password = "your-password";
// Or use OAuth
// popClient.UseOAuth = true;
// popClient.AccessToken = "your-access-token";
popClient.Connect();
popClient.Login();
for (int i = 1; i < popClient.GetMessageCount(); i++)
{
MailMessage msg = popClient.GetMessage(i);
Console.WriteLine("Message - " + i);
Console.WriteLine("Subject: " + msg.Subject);
Console.WriteLine("From: " + msg.From.Address);
}
popClient.Disconnect();
This screenshot displays the console output after fetching messages via POP3 from Gmail:

Unlike IMAP, POP3 downloads messages but does not maintain folder structure or message states on the server. Choose POP3 for simple retrieval scenarios.
Advanced Email Parsing in C#: Extract Attachments and Plain Text
In many cases, it's necessary to extract the plain-text content of an email for further processing, or to retrieve attachments for downstream use such as storage, analysis, or forwarding. The following C# example demonstrates how to access and save both the plain-text body and attachments using the MailMessage object.
MailMessage message = client.GetFullMessage(index);
// Retrieve plain text content
string plainText = message.BodyText;
// Extract attachments
foreach (Attachment attachment in message.Attachments)
{
string path = Path.Combine("Attachments", attachment.ContentType.Name);
Directory.CreateDirectory("Attachments");
using (var fileStream = new FileStream(path, FileMode.Create, FileAccess.Write))
{
attachment.Data.Position = 0;
attachment.Data.CopyTo(fileStream);
}
}
Notes:
- Most emails contain both HTML and plain text bodies; use the format appropriate for your application.
- To skip embedded images (like inline logos), check that attachment.ContentDisposition.DispositionType != "Inline".
Below is a sample output showing saved attachments and extracted plain text from the retrieved email:

For more detailed operations such as managing email folders—creating, deleting, or moving messages—please refer to our guide on Email Folder Management in C#.
Summary
With Spire.Email for .NET, you can programmatically access Gmail or Outlook inboxes in C# using either IMAP or POP3. The library supports OAuth 2.0 authentication, parses both HTML and plain-text email bodies, and enables attachment extraction for downstream processing. Whether you're building an internal automation tool, an alerting system, or an email parser, Spire.Email provides the essential components for email integration in .NET applications.
If you'd like to explore all features without limitations, you can apply for a free temporary license.
Frequently Asked Questions
Can I use Spire.Email for sending emails too?
Yes. Spire.Email for .NET includes support for SMTP as well, allowing you to send HTML-formatted emails, add attachments, and configure encoding and headers.
Does Spire.Email work with other email providers?
Yes. As long as the provider supports standard IMAP, POP3, or SMTP protocols, and offers compatible authentication (OAuth or basic), it will work with Spire.Email.
How do I get the access token programmatically?
For Outlook, you can use Microsoft’s MSAL.NET; for Gmail, use Google.Apis.Auth or any other OAuth library that retrieves a valid token with mail access scopes. These tokens can then be passed to the email client for secure login.

Optical Character Recognition (OCR) technology bridges the physical and digital worlds by converting text within images into machine-readable data. For .NET developers, the ability to extract text from images in C# is essential for building intelligent document processing, automated data entry, and accessibility solutions.
In this article, we’ll explore how to implement OCR in C# using the Spire.OCR for .NET library, covering basic extraction, advanced features like coordinate tracking, and best practices to ensure accuracy and efficiency.
Table of Contents:
- Understanding OCR and Spire.OCR
- Setting Up Your OCR Environment
- Basic Recognition: Extract Text from Images in C#
- Advanced Extraction: Extract Text with Coordinates in C#
- Tips to Optimize OCR Accuracy
- FAQs (Supported Languages and Image Formats)
- Conclusion & Free License
Understanding OCR and Spire.OCR
What is OCR?
OCR technology analyzes images of text - such as scanned documents, screenshots, or photos - and converts them into text strings that can be edited, searched, or processed programmatically.
Why Spire.OCR Stands Out?
Spire.OCR for .NET is a powerful, developer-friendly library that enables highly accurate text recognition from images in C# applications. Key features include:
- Support for multiple languages (English, Chinese, Japanese, etc.).
- High accuracy recognition algorithms optimized for various fonts and styles.
- Text coordinate extraction for precise positioning.
- Batch processing capabilities.
- Compatibility with .NET Framework and .NET Core.
Setting Up Your OCR Environment
Before diving into the C# code for image to text OCR operations, configure your development environment first:
1. Install via NuGet:
Open the NuGet Package Manager in Visual Studio. Search for "Spire.OCR" and install the latest version in your project. Alternatively, use the Package Manager Console:
Install-Package Spire.OCR
2. Download OCR Models:
Spire.OCR relies on pre-trained models to recognize image text. Download the model files for your operating system:
After downloading, extract to a directory (e.g., F:\OCR Model\win-x64)
Important Note: Remember to change the platform target of your solution to x64 as Spire.OCR only supports 64-bit platforms.

Basic Recognition: Extract Text from Images in C#
Let’s start with a simple example that demonstrates how to read text from an image using Spire.OCR.
C# code to get text from an image:
using Spire.OCR;
using System.IO;
namespace OCRTextFromImage
{
internal class Program
{
static void Main(string[] args)
{
// Create an instance of the OcrScanner class
OcrScanner scanner = new OcrScanner();
// Create an instance of the ConfigureOptions class
ConfigureOptions configureOptions = new ConfigureOptions();
// Set the path to the OCR model
configureOptions.ModelPath = "F:\\OCR Model\\win-x64";
// Set the language for text recognition. (The default is English.)
configureOptions.Language = "English";
// Apply the configuration options to the scanner
scanner.ConfigureDependencies(configureOptions);
// Scan image and extract text
scanner.Scan("sample.png");
// Save the extracted text to a txt file
string text = scanner.Text.ToString();
File.WriteAllText("output.txt", text);
}
}
}
Code Explanation:
- OcrScanner: Core class for text recognition.
- ConfigureOptions: Sets OCR parameters:
- ModelPath: Specifies the path to the OCR model files.
- Language: Defines the recognition language (e.g., "English", "Chinese").
- Scan(): Processes image and extracts text using the configured settings.
Output:
This C# code processes an image file (sample.png) and saves the extracted text to a text file (output.txt) using File.WriteAllText().

Advanced Extraction: Extract Text with Coordinates in C#
In many cases, knowing the position of extracted text within an image is as important as the text itself - for example, when processing invoices, forms, or structured documents. Spire.OCR allows you to extract not just text but also the coordinates of the text blocks, enabling precise analysis.
C# code to extract text with coordinates from an Image:
using Spire.OCR;
using System.Collections.Generic;
using System.IO;
namespace OCRWithCoordinates
{
internal class Program
{
static void Main(string[] args)
{
// Create an instance of the OcrScanner class
OcrScanner scanner = new OcrScanner();
// Create an instance of the ConfigureOptions class
ConfigureOptions configureOptions = new ConfigureOptions();
// Set the path to the OCR model
configureOptions.ModelPath = "F:\\OCR Model\\win-x64";
// Set the language for text recognition. (The default is English.)
configureOptions.Language = "English";
// Apply the configuration options to the scanner
scanner.ConfigureDependencies(configureOptions);
// Extract text from an image
scanner.Scan("invoice.png");
// Get the OCR result text
IOCRText text = scanner.Text;
// Create a list to store information
List<string> results = new List<string>();
// Iterate through each block of the OCR result text
foreach (IOCRTextBlock block in text.Blocks)
{
// Add the text of each block and its location information to the list
results.Add($"Block Text: {block.Text}");
results.Add($"Coordinates: {block.Box}");
results.Add("---------");
}
// Save the extracted text with coordinates to a txt file
File.WriteAllLines("ExtractWithCoordinates.txt", results);
}
}
}
Critical Details
- IOCRText: Represents the entire OCR result.
- IOCRTextBlock: Represents a block of contiguous text (e.g., a paragraph, line, or word).
- IOCRTextBlock.Box: Contains the rectangular coordinates of the text block:
- X (horizontal position)
- Y (vertical position)
- Width
- Height
Output:
This C# code performs OCR on an image file (invoice.png), extracting both the recognized text and its position coordinates in the image, then saves this information to a text file (ExtractWithCoordinates.txt).

Tips to Optimize OCR Accuracy
To ensure reliable results when using C# to recognize text from images, consider these best practices:
- Use high-resolution images (300 DPI or higher).
- Preprocess images (e.g., resize, deskew) for better results.
- Ensure correct language settings correspond to the text in image.
- Store OCR models in a secure, accessible location.
FAQs (Supported Languages and Image Formats)
Q1: What image formats does Spire.OCR support?
A: Spire.OCR supports all common formats:
- PNG
- JPEG/JPG
- BMP
- TIFF
- GIF
Q2: What languages does Spire.OCR support?
A: Multiple languages are supported:
- English (default)
- Chinese (Simplified and Traditional)
- Japanese
- Korean
- German
- French
Q3: Can I use Spire.OCR in ASP.NET Core applications?
A: Yes. Supported environments:
- .NET Framework 2.0+
- .NET Standard 2.0+
- .NET Core 2.0+
- .NET 5
Q4: Can Spire.OCR extract text from scanned PDFs in C#?
A: The task requires the Spire.PDF integration to convert PDFs to images or extract images from scanned PDFs first, and then use the above C# examples to get text from the images.
Conclusion & Free License
Spire.OCR for .NET provides a powerful yet straightforward solution for extracting text from images in C# applications. Whether you’re building a simple tool to convert images to text or a complex system for processing thousands of invoices, by following the techniques and best practices outlined in this guide, you can integrate OCR functionality into your C# applications with ease.
Request a 30-day trial license here to get unlimited OCR capabilities and unlock valuable information trapped in visual format.
How to Convert Markdown to PDF and Excel in C# .NET: A Complete Guide
2025-07-18 06:09:23 Written by zaki zaki
Markdown is a lightweight markup language widely used for writing formatted text using simple plain syntax. Favored by developers, writers, and technical content creators for its readability and ease of use, Markdown is perfect for drafting documents, notes, and technical content. However, Markdown files (.md) often need to be converted into other formats such as PDF for official distribution or Excel for data analysis and reporting.
In this comprehensive guide, you will learn how to convert Markdown files to PDF and Excel using C# and Spire.XLS for .NET — a powerful and easy-to-use library that supports direct Markdown loading and exporting to multiple formats. Whether you want to generate polished PDF documents or structured Excel spreadsheets, this tutorial covers everything you need.
Table of Contents
- Why Convert Markdown to PDF and Excel?
- Prerequisites (Library & Environment Setup)
- How to Convert Markdown to PDF in C# (Step-by-Step with Code)
- How to Convert Markdown to Excel in C# (Step-by-Step with Code)
- Complete C# Code Example: Convert Markdown to PDF and Excel in One Go
- Best Practices for Markdown Conversion
- Conclusion
- FAQs
Why Convert Markdown to PDF and Excel?
Markdown is great for writing, but it has limitations when sharing or processing documents:
- PDF files provide a fixed-layout, platform-independent format ideal for sharing polished reports, manuals, or official documentation. PDFs maintain the original style and layout regardless of device or software.
- Excel files are essential when Markdown contains tabular data that you want to analyze, manipulate, or integrate into business processes. Converting Markdown tables to Excel spreadsheets lets you utilize formulas, filters, charts, and data tools effectively.
By converting Markdown to these formats programmatically in C#, you can automate documentation workflows, batch-process files, and integrate with other .NET applications.
Prerequisites (Library & Environment Setup)
Before you start converting Markdown files, ensure your development environment meets the following requirements:
- .NET Framework or .NET Core installed.
- Spire.XLS for .NET: A comprehensive Excel library that supports loading Markdown and exporting to PDF and Excel formats.
Install Spire.XLS via NuGet
You can easily install Spire.XLS in your C# project via NuGet by opening the NuGet Package Manager and executing the following command:
Install-Package Spire.XLS
This package provides all the necessary classes and methods to load Markdown and export documents without relying on Microsoft Office automation.
How to Convert Markdown to PDF in C# (Step-by-Step with Code)
To convert a Markdown file to PDF in C#, follow the steps below:
Step 1: Load the Markdown File
Create a new instance of the Workbook class and load your Markdown file:
Workbook workbook = new Workbook();
workbook.LoadFromMarkdown("test.md");
This method parses the Markdown content, including text and tables, into an Excel workbook structure that Spire.XLS can manipulate.
Step 2: Customize Conversion Settings (Optional)
After loading the Markdown file, you can apply conversion settings to ensure the PDF output retains a clean and readable layout. For example, enabling the SheetFitToPage option ensures that the entire Markdown content fits within a single PDF page.
workbook.ConverterSetting.SheetFitToPage = true;
Step 3: Export as PDF
Save the workbook as a PDF file:
workbook.SaveToFile("output.pdf", FileFormat.PDF);
This generates a well-formatted PDF document preserving the Markdown layout and styling suitable for printing or sharing.

How to Convert Markdown to Excel in C# (Step-by-Step with Code)
After loading the Markdown file into the workbook, you can also export it to an Excel spreadsheet format:
workbook.SaveToFile("output.xls", ExcelVersion.Version97to2003);
You may also choose other Excel versions depending on your target compatibility:
workbook.SaveToFile("output.xlsx", ExcelVersion.Version2016);
The exported Excel file retains tables and structured data from your Markdown, allowing further analysis or manipulation.

Complete C# Code Example: Convert Markdown to PDF and Excel in One Go
Here’s the full example combining both PDF and Excel exports in a single run:
using Spire.Xls;
namespace MarkdownToPdfAndExcel
{
internal class Program
{
static void Main(string[] args)
{
// Initialize the workbook
Workbook workbook = new Workbook();
// Load Markdown content
workbook.LoadFromMarkdown("test.md");
// Fit the sheet data to one page (optional)
workbook.ConverterSetting.SheetFitToPage = true;
// Export to PDF
workbook.SaveToFile("output.pdf", FileFormat.PDF);
// Export to xls (Excel 97-2003 format)
workbook.SaveToFile("output.xls", ExcelVersion.Version97to2003);
// Export to xlsx (Excel 2016 format)
workbook.SaveToFile("output.xlsx", ExcelVersion.Version2016);
workbook.Dispose();
}
}
}
Best Practices for Markdown Conversion
- Use UTF-8 Encoding: Ensure your Markdown files use UTF-8 encoding, especially if they contain special or non-English characters. This ensures proper character display and avoids encoding errors during conversion.
- Maintain Clean and Well-Formatted Markdown Tables: To achieve accurate and reliable Excel conversions, structure your Markdown tables carefully. Use consistent pipe (|) delimiters and avoid malformed syntax to preserve table integrity in the output spreadsheet.
- Load Once, Export Multiple Formats: For optimal performance, load your Markdown content into the Workbook object a single time, then export it to various formats such as PDF and Excel. This reduces processing overhead and speeds up batch conversions.
- Assess Markdown Complexity: Spire.XLS effectively supports basic Markdown syntax, such as headings and tables. However, advanced features like embedded images or code blocks with syntax highlighting might require pre-processing or conversion through intermediate formats like HTML.
- Choose Appropriate Excel Export Versions: To maximize compatibility with your users’ software, select the Excel file format based on their environment. For example, use the .xls format for legacy Excel 97–2003 users, and .xlsx for Excel 2007 and later versions to ensure broad accessibility and full feature support.
Conclusion
Converting Markdown to PDF and Excel using C# and Spire.XLS is a fast, flexible, and reliable approach to modern document workflows. With minimal code, developers can automate the transformation of lightweight Markdown into professional PDFs for distribution and Excel spreadsheets for business analytics.
This method streamlines technical writing, reporting, and data handling tasks within .NET applications and enables seamless integration with other business processes.
FAQs
Q1: Can I batch convert multiple Markdown files using Spire.XLS in C#?
A1: Yes, you can loop through multiple Markdown files, load each one using Spire.XLS, and export them individually to PDF or Excel formats within the same C# project.
Q2: Is Microsoft Office required to use Spire.XLS for Markdown conversion?
A2: No, Spire.XLS is a standalone library and does not rely on Microsoft Office or Excel being installed on the machine.
Q3: Is Spire.XLS free to use?
A3: Spire.XLS offers a free version with some limitations. A commercial license is available for full features.
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.
Generate Excel File in C# – Create and Export in .NET & ASP.NET
2025-07-09 09:37:39 Written by zaki zaki
Generating Excel files in C# is a common task for developers building reporting systems, exporting structured data, or automating Excel-based workflows. Whether you're building desktop tools, web APIs with ASP.NET Core, or cross-platform apps using .NET, the ability to generate .xlsx files programmatically can simplify many data exchange scenarios.
In this guide, you'll learn how to generate Excel files in C# using Spire.XLS for .NET — a standalone Excel library that works seamlessly across different types of .NET applications — from desktop tools to web services and background jobs. We’ll cover use cases such as creating spreadsheets from scratch, exporting data from a DataTable, generating files on the server side, and applying formatting or formulas, all with practical code examples.
Table of Contents
- Set Up the Environment
- Create Excel Files from Scratch in C#
- Export DataTable to Excel in C#
- Apply Formatting and Formulas in Excel
- Generate Excel Files in ASP.NET Core
- Generate Excel Files in ASP.NET Web Forms
- FAQ
- Conclusion
Set Up the Environment
Spire.XLS for .NET is a lightweight Excel library that allows you to create .xlsx/.xls files entirely through code — without installing Microsoft Office or using COM Interop. This makes it an ideal solution for web servers, microservices, and cloud-hosted applications.
You can install the library via NuGet:
Install-Package Spire.XLS
For smaller tasks, Free Spire.XLS for .NET is also a good choice:
Install-Package FreeSpire.XLS
Create Excel Files from Scratch in C#
For simple tasks like configuration files, small datasets, or template generation, creating an Excel file from scratch in C# provides full control over content and layout.
The example below shows how to generate a basic worksheet with text and numeric data:
using Spire.Xls;
// Create a new workbook and worksheet
Workbook workbook = new Workbook();
Worksheet sheet = workbook.Worksheets[0];
sheet.Name = "Summary";
// Fill in headers and data
// Access cells by name
sheet.Range["A1"].Text = "Employee";
sheet.Range["B1"].Text = "Department";
sheet.Range["C1"].Text = "Salary";
// Access cells by row and column
sheet.Range[2, 1].Text = "Alice";
sheet.Range[2, 2].Text = "HR";
sheet.Range[2, 3].NumberValue = 6500;
sheet.Range[3, 1].Text = "Bob";
sheet.Range[3, 2].Text = "IT";
sheet.Range[3, 3].NumberValue = 7200;
// Apply styles
CellStyle headerStyle = workbook.Styles.Add("Header");
headerStyle.Font.IsBold = true;
sheet.Range["A1:C1"].Style = headerStyle;
// sheet.Range[1, 1, 1, 3].Style = headerStyle;
// Auto-fit columns
sheet.AllocatedRange.AutoFitColumns();
// Save the file
workbook.SaveToFile("BasicExcel.xlsx", ExcelVersion.Version2016);
workbook.Dispose();
Example output: A basic Excel file with employee names, departments, and salaries created in C#.

This approach works entirely without Excel installed, and is ideal for lightweight, structured exports.
Export DataTable to Excel in C#
When working with databases or APIs, exporting a DataTable directly to Excel in C# is often necessary. Instead of looping through rows manually, Spire.XLS provides an efficient way to load structured data in one line.
Here’s how you can convert a DataTable into a worksheet, including headers:
using System.Data;
using Spire.Xls;
// Create a simulated data table
DataTable dt = new DataTable("Products");
dt.Columns.Add("Product Name", typeof(string));
dt.Columns.Add("Price", typeof(double));
dt.Columns.Add("Stock", typeof(int));
dt.Rows.Add("Laptop", 1299.99, 20);
dt.Rows.Add("Monitor", 199.5, 50);
dt.Rows.Add("Mouse", 25.75, 150);
// Import into Excel
Workbook workbook = new Workbook();
Worksheet sheet = workbook.Worksheets[0];
sheet.Name = "Inventory";
sheet.InsertDataTable(dt, true, 1, 1);
// Auto-fit column widths
sheet.AllocatedRange.AutoFitColumns();
// Save the file
workbook.SaveToFile("InventoryReport.xlsx", ExcelVersion.Version2016);
workbook.Dispose();
Example output: Excel spreadsheet generated from a DataTable containing product details, prices, and stock levels.

This is a common approach for exporting reports, inventory lists, and analytics — with no Excel or Interop automation required.
Related article: Convert Data Between Excel Files and DataTable in C#
Apply Formatting and Formulas in Excel Using C#
In addition to exporting raw data, you can generate professional Excel files in C# by applying formatting, styling, and formulas — improving readability and enabling automatic calculations.
Below is an example that demonstrates basic styling and formula use:
using Spire.Xls;
using System.Drawing;
Workbook workbook = new Workbook();
Worksheet sheet = workbook.Worksheets[0];
sheet.Name = "Sales Report";
// Set header labels
sheet.Range["A1"].Text = "Item";
sheet.Range["B1"].Text = "Price";
sheet.Range["C1"].Text = "Quantity";
sheet.Range["D1"].Text = "Total";
// Add sample data
string[,] items = {
{ "Pen", "1.5", "10" },
{ "Notebook", "3.75", "5" },
{ "Eraser", "0.99", "20" }
};
for (int i = 0; i < items.GetLength(0); i++)
{
int row = i + 2;
sheet.Range[$"A{row}"].Text = items[i, 0];
sheet.Range[$"B{row}"].NumberValue = double.Parse(items[i, 1]);
sheet.Range[$"C{row}"].NumberValue = double.Parse(items[i, 2]);
sheet.Range[$"D{row}"].Formula = $"=B{row}*C{row}";
}
// Style: Header row
CellStyle headerStyle = workbook.Styles.Add("HeaderStyle");
headerStyle.Font.IsBold = true;
headerStyle.Font.Color = Color.White;
headerStyle.Font.Size = 12;
headerStyle.KnownColor = ExcelColors.DarkBlue;
headerStyle.HorizontalAlignment = HorizontalAlignType.Center;
headerStyle.VerticalAlignment = VerticalAlignType.Center;
headerStyle.Borders[BordersLineType.EdgeTop].LineStyle = LineStyleType.Thick;
headerStyle.Borders[BordersLineType.EdgeLeft].LineStyle = LineStyleType.Thick;
sheet.Range["A1:D1"].Style = headerStyle;
sheet.Range["A1:D1"].RowHeight = 22;
// Style: Data cells
CellStyle dataStyle = workbook.Styles.Add("DataStyle");
dataStyle.NumberFormat = "\"$\"#,##0.00";
dataStyle.HorizontalAlignment = HorizontalAlignType.Right;
dataStyle.VerticalAlignment = VerticalAlignType.Center;
dataStyle.Borders[BordersLineType.EdgeLeft].LineStyle = LineStyleType.Thin;
dataStyle.Borders[BordersLineType.EdgeBottom].LineStyle = LineStyleType.Thin;
// Apply data style to Price, Quantity, Total
sheet.Range["B2:D4"].Style = dataStyle;
// Optional: Alternating row colors for readability
for (int r = 2; r <= 4; r++)
{
if (r % 2 == 0)
sheet.Range[$"A{r}:D{r}"].Style.KnownColor = ExcelColors.LightYellow;
}
// Adjust widths and heights
sheet.AllocatedRange.AutoFitColumns();
sheet.AllocatedRange.RowHeight = 20;
// Save file
workbook.SaveToFile("styled.xlsx", FileFormat.Version2016);
workbook.Dispose();
Example output: A styled Excel sheet with headers, formulas, alternating row colors, and formatted currency values.

By using C# and Spire.XLS, you can apply styles, borders, colors, alignments, and Excel-compatible formulas to generate clean, automated, and user-friendly Excel reports.
To further enhance your Excel reports, you can also apply number formats such as currency, percentage, or custom formats. Learn more about setting number formats in C#
Generate Excel Files in ASP.NET Core
In modern ASP.NET Core applications (e.g., .NET 6/7/8), generating Excel files is a common requirement for admin dashboards, data exports, and reporting features. The example below shows how to generate an Excel file on the server and return it as a downloadable file from a Razor Page handler.
Here’s how you can implement it in a Razor Pages project:
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Spire.Xls;
using System.Data;
public class ExportModel : PageModel
{
public IActionResult OnGet()
{
// Simulated data
DataTable dt = new DataTable("Sales");
dt.Columns.Add("Date", typeof(DateTime));
dt.Columns.Add("Product", typeof(string));
dt.Columns.Add("Revenue", typeof(double));
dt.Rows.Add(DateTime.Today.AddDays(-2), "Laptop", 1250.00);
dt.Rows.Add(DateTime.Today.AddDays(-1), "Monitor", 320.50);
dt.Rows.Add(DateTime.Today, "Mouse", 25.99);
// Create Excel workbook and sheet
Workbook workbook = new Workbook();
Worksheet sheet = workbook.Worksheets[0];
sheet.Name = "DailySales";
// Insert data
sheet.InsertDataTable(dt, true, 1, 1);
// Apply simple header style
CellStyle headerStyle = workbook.Styles.Add("HeaderStyle");
headerStyle.Font.IsBold = true;
sheet.Rows[0].Style = headerStyle;
sheet.AllocatedRange.AutoFitColumns();
// Save to memory stream
using var stream = new MemoryStream();
workbook.SaveToStream(stream, FileFormat.Version2016);
stream.Position = 0;
// Return file to browser
return File(stream.ToArray(),
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
"SalesReport.xlsx");
}
}
Example output: Daily sales report generated in a .NET 8 console app with date, product, and revenue columns.

This method is ideal for web-based reporting tools, internal portals, and admin dashboards that require dynamic Excel downloads.
- ✅ Works in ASP.NET Core 3.1, .NET 5, .NET 6, .NET 7, .NET 8
- ✅ Suitable for: Razor Pages, MVC, and API endpoints with file download support
Generate Excel Files in ASP.NET Web Forms
If you're building an internal admin panel or classic ASP.NET Web Forms application, you may want to allow users to download Excel files directly from the browser. The example below demonstrates how to create an Excel file entirely in memory and return it in the HTTP response for immediate download — without saving it to disk.
using Spire.Xls;
using System;
using System.IO;
namespace YourNamespace
{
public partial class Default : System.Web.UI.Page
{
protected void btnExport_Click(object sender, EventArgs e)
{
// Create Excel file and output for download
Workbook workbook = new Workbook();
Worksheet sheet = workbook.Worksheets[0];
sheet.Name = "Users";
// Headers
string[] headers = { "ID", "Name", "Department", "Join Date" };
for (int i = 0; i < headers.Length; i++)
{
sheet.Range[1, i + 1].Text = headers[i];
sheet.Range[1, i + 1].Style.Font.IsBold = true;
}
// Sample data
string[,] data = {
{ "U001", "Gemma", "HR", "2023-01-15" },
{ "U002", "Bill", "IT", "2022-11-03" }
};
// Fill data
for (int r = 0; r < data.GetLength(0); r++)
for (int c = 0; c < data.GetLength(1); c++)
sheet.Range[r + 2, c + 1].Text = data[r, c];
// Auto-fit column widths
sheet.AllocatedRange.AutoFitColumns();
// Export for browser download
using (MemoryStream ms = new MemoryStream())
{
workbook.SaveToStream(ms, FileFormat.Version2016);
byte[] bytes = ms.ToArray();
Response.Clear();
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.AddHeader("Content-Disposition", "attachment; filename=Users.xlsx");
Response.BinaryWrite(bytes);
Response.End();
}
}
}
}
Example output: Excel file created and streamed to browser in ASP.NET containing employee records.

This pattern allows Excel files to be generated and downloaded dynamically, without writing to disk or requiring Office installed on the server.
FAQ
How to create an Excel file from C#?
You can use a library like Spire.XLS to create a new workbook, write data to worksheets, and save it as an Excel file — all without Office installed.
How to export an Excel file in C#?
If you want to export data (e.g. from a DataTable), you can load it into a worksheet and save the file using Spire.XLS. It supports automatic column headers and formatting.
How to generate Excel files in ASP.NET using C#?
You can generate Excel files in both ASP.NET Web Forms and ASP.NET Core using Spire.XLS. In ASP.NET Core, create the file in memory and return it in the HTTP response. In Web Forms, use a similar approach with Response.BinaryWrite() to stream the file to the browser.
Is Spire.XLS compatible with .NET Core?
Yes. It supports .NET Core 3.1+, .NET 5, .NET 6, .NET 7, and .NET 8, making it suitable for cross-platform Excel generation.
Conclusion
With Spire.XLS for .NET, you can easily generate Excel files in C# for any scenario — including desktop, ASP.NET Core, and classic Web Forms applications. Whether you need to export a DataTable, generate formatted reports, or automate Excel output, this guide helps you build Excel files in C# with zero dependencies.
Apply for a Free Temporary License to unlock all features and remove evaluation warnings.
Send Email in C# via SMTP – HTML Format and File Attachment
2025-07-04 02:56:14 Written by zaki zaki
Sending emails from a C# application is a common task in business and enterprise development. Whether you're delivering a project update, sending alerts, or automating reporting workflows, reliable email functionality is essential.
In this article, we’ll walk through how to send emails in C# using Spire.Email for .NET, a powerful component that simplifies SMTP communication and email formatting. We'll explore SMTP configuration, Gmail integration, HTML and plain-text content, file attachments, and multiple recipients.
Table of Contents
- 1. Project Setup
- 2. Send a Plain-Text Email via SMTP
- 3. Send HTML Email with Attachments via Gmail SMTP
- 4. Advanced Email Features with Spire.Email
- 5. Common Errors and Troubleshooting
- 6. Use Cases for Spire.Email
- 7. Free License
- 8. FAQ
1. Project Setup
To begin, create a .NET project (Console App or ASP.NET) and add the Spire.Email for .NET package.
Install via NuGet:
Install-Package Spire.Email
Or manually download the Spire.Email package and reference the Spire.Email.dll from your local installation package.
2. Send a Basic Email via SMTP in C#
The example below shows how to use Spire.Email to send a plain-text email through an SMTP server.
using Spire.Email;
using Spire.Email.Smtp;
// Configure the SMTP client
SmtpClient smtp = new SmtpClient();
smtp.Host = "smtp.example.com";
smtp.Port = 587;
smtp.Username = "[email protected]";
smtp.Password = "your_password";
smtp.ConnectionProtocols = ConnectionProtocols.StartTls;
// Create maill addresses
MailAddress sender = new MailAddress("[email protected]", "Sender Name");
MailAddress recipient = new MailAddress("[email protected]", "Recipient Name");
MailMessage message = new MailMessage(sender, recipient);
// Set the email content
message.Subject = "Test Email";
message.BodyText = "This is a plain-text test email.";
// Send the email
smtp.SendOne(message);
Explanation:
- Uses MailAddress and MailMessage from Spire.Email
- Establishes a secure SMTP connection using ConnectionProtocols.StartTls
The screenshot below shows the actual email received using the above SMTP code.

3. Send HTML Email with Attachments via Gmail SMTP in C#
The following C# code example demonstrates how to send an HTML-formatted email using Gmail SMTP, including multiple recipients, a file attachment, and plain-text fallback for clients that do not support HTML.
using Spire.Email;
using Spire.Email.Smtp;
// Create MailAddress objects
MailAddress from = new MailAddress("[email protected]", "Your Name");
MailAddress to1 = new MailAddress("[email protected]", "User One");
MailAddress to2 = new MailAddress("[email protected]", "User Two");
// Create a mail message
MailMessage message = new MailMessage(from, to1);
message.To.Add(to2);
message.Cc.Add(new MailAddress("[email protected]", "CC Person"));
message.Bcc.Add(new MailAddress("[email protected]"));
// Set the body HTML and text for the message
message.Subject = "Monthly Report - June 2025";
message.BodyHtml = "<h2 style='color:#2E86C1;'>Report Summary</h2><p>Please see the attached PDF report.</p>";
message.BodyText = "Report Summary - please see the attached PDF.";
// Add an attachment to the email
Attachment attachment = new Attachment(@"Sample.pdf");
message.Attachments.Add(attachment);
// Configure the SMTP client
SmtpClient smtp = new SmtpClient();
smtp.Host = "smtp.gmail.com";
smtp.Port = 587;
smtp.Username = "[email protected]";
smtp.Password = "your_app_password";
smtp.ConnectionProtocols = ConnectionProtocols.StartTls;
// Sen the email
smtp.SendOne(message);
Explanation:
- Uses MailAddress, MailMessage, Attachment, and SmtpClient from Spire.Email
- Combines BodyHtml and BodyText to support HTML and plain-text email clients
- Adds multiple recipients via To.Add(), Cc.Add(), and Bcc.Add()
- Sends email securely through Gmail using ConnectionProtocols.StartTls
Gmail requires App Passwords if 2FA is enabled.
The following screenshot shows the HTML-formatted email with rich text, CC and BCC recipients, and a PDF attachment, as received from Gmail SMTP.

Related article: How to Send an Email with Attachments in C#
4. Advanced Email Features with Spire.Email
This section demonstrates advanced C# email-sending capabilities using Spire.Email, including embedded images and batch dispatch.
// Prepare an email with embedded image
MailMessage message = new MailMessage(
new MailAddress("[email protected]", "Sender"),
new MailAddress("[email protected]", "Client"));
message.Subject = "Branding Update";
message.BodyHtml = "<h1>Our New Logo</h1><img src=\"cid:logo\">";
message.BodyText = "Please view this message in HTML to see the image.";
Attachment logo = new Attachment(@"C:\Images\logo.png");
logo.ContentId = "logo";
logo.DispositionType = "Inline";
message.Attachments.Add(logo);
// Prepare a second email
MailMessage message2 = new MailMessage(
new MailAddress("[email protected]"),
new MailAddress("[email protected]"));
message2.Subject = "Weekly Summary";
message2.BodyText = "This is an automated weekly update.";
// Create SMTP client
SmtpClient smtp = new SmtpClient();
smtp.Host = "smtp.domain.com";
smtp.Port = 587;
smtp.Username = "[email protected]";
smtp.Password = "your_password";
smtp.ConnectionProtocols = ConnectionProtocols.StartTls;
// Send one email
smtp.SendOne(message);
// Send emails in batch
smtp.SendSome(new List<MailMessage> { message, message2 });
Explanation:
Attachment.ContentIdandDispositionType = "Inline"allow inline images using CID references in HTML.SendOne()sends a single message.SendSome()sends multiple messages as a batch. Ideal for scheduled reports or group notifications.
The following screenshot shows an email with an embedded company logo and a plain-text fallback, demonstrating how Spire.Email renders HTML content with inline images.

You may also like: Creating MSG Files with RTF Body and Attachments Using C#
5. Common Errors and Troubleshooting
| Error | Likely Cause |
|---|---|
| Authentication failed | Incorrect credentials or missing app password |
| Secure connection required | Use StartTLS or SSL in ConnectionProtocols |
| HTML content not displaying | Ensure BodyHtml and fallback BodyText are set |
| File not found | Incorrect file path for attachment |
6. Use Cases for Spire.Email
Spire.Email for .NET is suitable for:
- Daily/weekly automated reporting
- User signup and notification emails
- Order confirmations with attachments
- Form submission alerts
- Embedded-image newsletters
Its clean API removes the need to manually handle SMTP headers, MIME formatting, and encoding issues.
Conclusion
With Spire.Email for .NET, developers can quickly build robust and flexible email-sending features directly into C# applications. Whether the goal is to deliver transactional messages, generate styled reports, or dispatch scheduled newsletters, this component provides a clean, reliable API that simplifies every step of the process.
By supporting plain-text and HTML formats, attachments, Gmail SMTP, embedded images, and batch sending, Spire.Email helps streamline email integration without the overhead of external dependencies.
7. Apply for a Free Temporary License
To remove the evaluation warning in the email body or attachment footer, you can apply for a free temporary license:
Request a Free 1-Month License
Simply fill out the form and follow the instructions to apply the license in your project. This enables full feature access during evaluation.
8. FAQ
How to send HTML email in C#?
You can set the BodyHtml property of the MailMessage object to send an HTML email using Spire.Email. You can also include BodyText as a fallback for clients that don't support HTML.
How to send email to multiple recipients in C#?
Add multiple recipients using message.To.Add(), message.Cc.Add(), and message.Bcc.Add() methods. Spire.Email supports To, Cc, and Bcc fields.
How to use SMTP to send email in ASP.NET or MVC projects?
The SMTP usage in ASP.NET or MVC is the same as in Console applications. Simply configure the SmtpClient with host, port, credentials, and use the same SendOne() or SendSome() methods to dispatch your message.

QR codes have become a common part of modern applications — from user authentication and digital payments to product packaging and event tickets. In many of these scenarios, developers often need to read QR codes in C# as part of their workflow, especially when working with image-based inputs like scanned documents or uploaded files.
To handle such tasks reliably, a decoding method that’s both accurate and easy to implement is essential. In this tutorial, we’ll walk through a straightforward approach to reading QR codes from images using C#, with minimal setup and clean integration.
Quick Navigation
- Project Setup
- Read QR Code from Image Using C#
- Read QR Code from Stream Using C#
- Improve Accuracy and Handle Errors
- Bonus: Get QR Code Coordinates
- FAQ
- Final Thoughts
1. Project Setup
To begin, we’ll use a .NET barcode library that supports QR code decoding. In this guide, we demonstrate with Spire.Barcode for .NET, which provides a simple API for reading QR codes from image files and streams.
1.1 Install the Library via NuGet
You can install the library through NuGet Package Manager:
Install-Package Spire.Barcode
For basic scenarios, you can also use Free Spire.Barcode for .NET:
Install-Package FreeSpire.Barcode
1.2 Create a New Console Project
For demonstration, create a C# Console App in Visual Studio:
- Target .NET Framework, .NET Core/.NET 6+, ASP.NET, or Xamarin for cross-platform mobile development
- Add reference to Spire.Barcode.dll (if not using NuGet)
2. Read QR Code from Image in C#
To read QR codes from an image file in C#, you can simply use the static BarcodeScanner.Scan() method provided by the library. This method takes an image path and the BarCodeType as input and returns all decoded results that match the specified barcode type — in this case, QR codes.
This method supports scanning images in formats like JPG, PNG, and EMF. It’s the most direct way to scan QR code data in desktop applications or backend services that receive uploaded files.
2.1 Sample Code: Decode QR Code from an Image File
using Spire.Barcode;
class Program
{
static void Main(string[] args)
{
// Load the QR code image
string imagePath = @"C:\qr-code.png";
// Barcode scanner reads QR code from image file
string[] results = BarcodeScanner.Scan(imagePath, BarCodeType.QRCode);
// Display QR code result(s)
foreach (string result in results)
{
Console.WriteLine("QR Code Data: " + result + "\n");
}
}
}
The QR code image and the scan results from C# code:

2.2 Explanation
- Scan() reads and decodes all barcodes found in the image.
- BarCodeType.QRCode ensures only QR codes are detected (you can change it to detect other types).
- Returns an array in case the image contains multiple QR codes.
You may also like: How to Generate QR Codes Using C#
3. Read QR Code from Stream in C#
In web APIs or modern applications where images are processed in memory, you’ll often deal with Stream objects—such as when handling file uploads or reading from cloud storage.
The BarcodeScanner.Scan() method also accepts a Stream directly, allowing you to decode QR codes from memory streams without converting them to Bitmap.
using Spire.Barcode;
using System.IO;
class Program
{
static void Main(string[] args)
{
using (FileStream fs = new FileStream(@"C:\qr-code.png", FileMode.Open, FileAccess.Read))
{
// Directly scan the QR codes from the image stream
string[] results = BarcodeScanner.Scan(fs, BarCodeType.QRCode, false);
foreach (string result in results)
{
Console.WriteLine("QR Code Data: " + result);
}
}
}
}
This method is useful for WPF or ASP.NET Core apps that handle QR code images in memory.
Related article: Scan Barcodes from PDF Using C#
4. Improve Accuracy and Handle Errors
In real-world scenarios, QR code recognition may occasionally fail due to image quality or unexpected input issues. Here are best practices to improve decoding accuracy and handle failures in C#:
4.1 Boost Recognition Accuracy
- Use high-resolution images. Avoid blurred or overcompressed files.
- Ensure quiet zone (white space) around the QR code is preserved.
- Use formats like PNG for better clarity.
- Avoid perspective distortion — use straight, scanned images.
4.2 Add Robust Error Handling
Wrap your decoding logic in a try-catch block to prevent crashes and inform the user clearly:
try
{
string[] results = BarcodeScanner.Scan(imagePath, BarCodeType.QRCode);
if (results.Length == 0)
{
Console.WriteLine("No QR code found.");
}
else
{
Console.WriteLine("QR Code: " + results[0]);
}
}
catch (Exception ex)
{
Console.WriteLine("Error decoding QR code: " + ex.Message);
}
5. Bonus: Get QR Code Coordinates
Sometimes, you may need to locate the QR code’s exact position in the image—for cropping, overlay, or annotation. The ScanInfo() method helps retrieve bounding boxes:
BarcodeInfo[] results = BarcodeScanner.ScanInfo(imagePath, BarCodeType.QRCode);
foreach (BarcodeInfo result in results)
{
Console.WriteLine("Data: " + result.DataString);
Console.WriteLine($"Coordinates: " + string.Join(",", result.Vertexes.Select(p => $"({p.X},{p.Y})")) + "\n");
}
This provides both the data and the coordinates of each detected QR code.
The reading results:

6. FAQ
How to read QR code in C#?
You can use the Spire.Barcode for .NET library and its BarcodeScanner.Scan() method to read QR codes from image files or memory streams in just a few lines of code.
How do I read my own QR code image?
Load your QR code image file path into the scanner, or open it as a stream if you're working in a web or WPF application. The scanner will decode all readable QR codes in the image.
How to read barcodes in C# (not just QR codes)?
You can simply pass the image path to the Scan() method, and it will automatically detect and read all supported barcode types. To restrict detection to a specific type (e.g., only QR codes or Code128), pass the corresponding BarCodeType as the second parameter.
What is the best barcode reader library for C#?
Spire.Barcode for .NET is a popular choice for its simplicity, format support, and clean API. It supports both free and commercial use cases.
7. Final Thoughts
Reading QR codes in C# can be implemented with just a few lines of code using Spire.Barcode for .NET. It supports image and stream-based decoding, works well for desktop, server-side, or WPF applications, and offers solid performance with minimal setup.
You can further explore QR code generation, document integration, and real-time scanning workflows based on this foundation.
Need to unlock full barcode reading features?
Request a free temporary license and try the full capabilities of Spire.Barcode for .NET without limitations.
How to Read Barcodes from PDF in C# – Easy Methods with Code
2025-06-19 06:58:45 Written by Administrator
Reading barcodes from PDF in C# is a common requirement in document processing workflows, especially when dealing with scanned forms or digital PDFs. In industries like logistics, finance, healthcare, and manufacturing, PDFs often contain barcodes—either embedded as images or rendered as vector graphics. Automating this process can reduce manual work and improve accuracy.
This guide shows how to read barcode from PDF with C# using two practical methods: extracting images embedded in PDF pages and scanning them, or rendering entire pages as images and detecting barcodes from the result. Both techniques support reliable recognition of 1D and 2D barcodes in different types of PDF documents.
Table of Contents
- Getting Started: Tools and Setup
- Step-by-Step: Read Barcodes from PDF in C#
- Which Method Should You Use?
- Real-World Use Cases
- FAQ
Getting Started: Tools and Setup
To extract or recognize barcodes from PDF documents using C#, make sure your environment is set up correctly.
Here’s what you need:
- Any C# project that supports NuGet package installation (such as .NET Framework, .NET Core, or .NET).
- The following libraries, Spire.Barcode for .NET for barcode recognition and Spire.PDF for .NET for PDF processing, can be installed via NuGet Package Manager:
Install-Package Spire.Barcode
Install-Package Spire.PDF
Step-by-Step: Read Barcodes from PDF in C#
There are two ways to extract barcode data from PDF files. Choose one based on how the barcode is stored in the document.
Method 1: Extract Embedded Images and Detect Barcodes
This method is suitable for scanned PDF documents, where each page often contains a raster image with one or more barcodes. The BarcodeScanner.ScanOne() method can read one barcode from one image.
Code Example: Extract and Scan
using Spire.Barcode;
using Spire.Pdf;
using Spire.Pdf.Utilities;
using System.Drawing;
namespace ReadPDFBarcodeByExtracting
{
class Program
{
static void Main(string[] args)
{
// Load a PDF file
PdfDocument pdf = new PdfDocument();
pdf.LoadFromFile("Sample.pdf");
// Get a page and the image information on the page
PdfPageBase page = pdf.Pages[0];
PdfImageHelper imageHelper = new PdfImageHelper();
PdfImageInfo[] imagesInfo = imageHelper.GetImagesInfo(page);
// Loop through the image information
int index = 0;
foreach (PdfImageInfo imageInfo in imagesInfo)
{
// Get the image as an Image object
Image image = imageInfo.Image;
// Scan the barcode and output the result
string scanResult = BarcodeScanner.ScanOne((Bitmap)image);
Console.WriteLine($"Scan result of image {index + 1}:\n" + scanResult + "\n");
index++;
}
}
}
}
The following image shows a scanned PDF page and the barcode recognition result using Method 1 (extracting embedded images):

When to use: If the PDF is a scan or contains images with embedded barcodes.
You may also like: Generate Barcodes in C# (QR Code Example)
Method 2: Render Page as Image and Scan
When barcodes are drawn using vector elements (not embedded images), you can render each PDF page as a bitmap and perform barcode scanning on it. The BarcodeScanner.Scan() method can read multiple barcodes from one image.
Code Example: Render and Scan
using Spire.Barcode;
using Spire.Pdf;
using System.Drawing;
namespace ReadPDFBarcodeByExtracting
{
class Program
{
static void Main(string[] args)
{
// Load a PDF file
PdfDocument pdf = new PdfDocument();
pdf.LoadFromFile("Sample.pdf");
// Save each page as an image
for (int i = 0; i < pdf.Pages.Count; i++)
{
Image image = pdf.SaveAsImage(i);
// Read the barcodes on the image
string[] scanResults = BarcodeScanner.Scan((Bitmap)image);
// Output the results
for (int j = 0; j < scanResults.Length; j++)
{
Console.WriteLine($"Scan result of barcode {j + 1} on page {i + 1}:\n" + scanResults[j] + "\n");
}
}
}
}
}
Below is the result of applying Method 2 (rendering full PDF page) to detect vector barcodes on the page:

When to use: When barcodes are drawn on the page directly, not embedded as image elements.
Related article: Convert PDF Pages to Images in C#
Which Method Should You Use?
| Use Case | Recommended Method |
|---|---|
| Scanned pages or scanned barcodes | Extract embedded images |
| Digital PDFs with vector barcodes | Render full page as image |
| Hybrid or unknown structure | Try both methods optionally |
You can even combine both methods for maximum reliability when handling unpredictable document structures.
Real-World Use Cases
Here are some typical scenarios where barcode recognition from PDFs in C# proves useful:
-
Logistics automation Extract tracking numbers and shipping IDs from scanned labels, dispatch forms, or signed delivery receipts in bulk.
-
Invoice and billing systems Read barcode-based document IDs or payment references from digital or scanned invoices in batch processing tasks.
-
Healthcare document digitization Automatically scan patient barcodes from lab reports, prescriptions, or admission forms in PDF format.
-
Manufacturing and supply chain Recognize barcodes from packaging reports, quality control sheets, or equipment inspection PDFs.
-
Educational institutions Process barcoded student IDs on scanned test forms or attendance sheets submitted as PDFs.
Tip: In many of these use cases, PDFs come from scanners or online systems, which may embed barcodes as images or page content—both cases are supported with the two methods introduced above.
Conclusion
Reading barcodes from PDF files in C# can be achieved reliably using either image extraction or full-page rendering. Whether you need to extract a barcode from a scanned document or recognize one embedded in PDF content, both methods provide flexible solutions for barcode recognition in C#.
FAQ
Q: Does this work with multi-page PDFs?
Yes. You can loop through all pages in the PDF and scan each one individually.
Q: Can I extract multiple barcodes per page?
Yes. The BarcodeScanner.Scan() method can detect and return all barcodes found on each image.
Q: Can I improve recognition accuracy by increasing resolution?
Yes. When rendering a PDF page to an image, you can set a higher DPI using PdfDocument.SaveAsImage(pageIndex: int, PdfImageType.Bitmap: PdfImageType, dpiX: int, dpiY: int). For example, 300 DPI is ideal for small or low-quality barcodes.
Q: Can I read barcodes from PDF using C# for free?
Yes. You can use Free Spire.Barcode for .NET and Free Spire.PDF for .NET to read barcodes from PDF files in C#. However, the free editions have feature limitations, such as page count or supported barcode types. If you need full functionality without restrictions, you can request a free temporary license to evaluate the commercial editions.
Extract Background Images from PowerPoint Presentations using C# .NET
2025-05-16 09:01:16 Written by Administrator
PowerPoint presentations often contain background images that enhance the visual appeal of slides. Extracting these background images can be crucial for designers and content managers who wish to reuse, analyze, or archive slide visuals independently of the slide content.
This guide provides a clear, step-by-step approach to extracting background images from PowerPoint presentations in .NET using C# and the Spire.Presentation for .NET library.
Table of Contents
- Why Extract Background Images from PowerPoint
- Install .NET PowerPoint Library – Spire.Presentation for .NET
- Extract Background Images from PowerPoint in .NET using C#
- FAQs
- Conclusion
Why Extract Background Images from PowerPoint
Extracting background images from PowerPoint provides several key benefits:
- Reuse Designs: Repurpose background images in other presentations or design projects.
- Analyze Slides: Review and understand slide designs by examining background images separately.
- Archive Visuals: Store background images for documentation, backup, or future use.
Install .NET PowerPoint Library – Spire.Presentation for .NET
Spire.Presentation for .NET is a robust .NET PowerPoint library that enables developers to create, manipulate, and convert PowerPoint presentations without the need for Microsoft PowerPoint.
Key Features of Spire.Presentation for .NET
Here are some key features of Spire.Presentation for .NET:
- Create and edit PowerPoint presentations.
- Convert PowerPoint to other formats such as PDF, Images, HTML, Markdown, and XPS.
- Secure PowerPoint presentations
- Merge/split PowerPoint presentations.
- Slides management, including adding/removing slides, setting/extracting/removing backgrounds, and more.
- Image/shape/chart/smartart insertion and manipulation.
- Animate text/shapes.
Install Spire.Presentation for .NET
Before starting the background image extraction process, you will need to install Spire.Presentation for .NET into your C# project using one of the following methods:
Option1. Install via NuGet (Recommended)
Install-Package Spire.Presentation
Option 2: Manually Add DLLs to Your Project
- Download the Spire.Presentation package and extract the files.
- In Visual Studio, right-click References > Add Reference > Browse, then select the appropriate Spire.Presentation.dll based on your target framework.
Extract Background Images from PowerPoint in .NET using C#
Background images in PowerPoint can be applied directly to individual slides or inherited from slide masters. This section demonstrates how to extract both types of background images using Spire.Presentation.
Extract Background Images from Individual Slides
To extract background images from individual slides in PowerPoint, follow these steps:
- Create a Presentation object and load the presentation.
- Loop through all slides in the presentation.
- Check if the slide’s background fill type is image fill (FillFormatType.Picture).
- If yes, retrieve and save the background image.
Sample Code
- C#
using Spire.Presentation;
using Spire.Presentation.Drawing;
using System.IO;
namespace ExtractSlideBackgroundImages
{
internal class Program
{
static void Main(string[] args)
{
// Specify the input file path and output folder
string inputFile = @"example1.pptx";
string outputFolder = @"ExtractedBackgrounds\Slides";
// Load the PowerPoint presentation
Presentation presentation = new Presentation();
presentation.LoadFromFile(inputFile);
// Create the output folder
Directory.CreateDirectory(outputFolder);
// Loop through all slides
for (int i = 0; i < presentation.Slides.Count; i++)
{
// Check if the slide's background fill type is image fill
var fill = presentation.Slides[i].SlideBackground.Fill;
if (fill.FillType == FillFormatType.Picture)
{
// Extract and save the background image
var image = fill.PictureFill.Picture.EmbedImage;
if (image != null)
{
string outputPath = Path.Combine(outputFolder, $"SlideBackground_{i + 1}.png");
image.Image.Save(outputPath, ImageFormat.Png);
}
}
}
}
}
}
Extract Background Images from Slide Masters
Slide masters define the design and layout of slides, including background images. To extract background images from slide masters:
- Create a Presentation object and load the presentation.
- Loop through all slide masters in the presentation.
- For each master, check if its background fill type is image fill.
- If yes, extract and save the background image.
Sample Code
- C#
using Spire.Presentation;
using Spire.Presentation.Drawing;
using System.Drawing.Imaging;
using System.IO;
namespace ExtractBackgroundImages
{
internal class Program
{
static void Main(string[] args)
{
// Specify the input file path and output folder
string inputFile = @"example2.pptx";
string outputFolder = @"C:\ExtractedBackgrounds\Masters";
// Load the PowerPoint presentation
Presentation presentation = new Presentation();
presentation.LoadFromFile(inputFile);
// Create the output folder
Directory.CreateDirectory(outputFolder);
// Loop through all slide masters
for (int i = 0; i < presentation.Masters.Count; i++)
{
// Check if the slide master's background fill type is image fill
var fill = presentation.Masters[i].SlideBackground.Fill;
if (fill.FillType == FillFormatType.Picture)
{
// Extract and save the background image
var image = fill.PictureFill.Picture.EmbedImage;
if (image != null)
{
string outputPath = Path.Combine(outputFolder, $"MasterBackground_{i + 1}.png");
image.Image.Save(outputPath, ImageFormat.Png);
}
}
}
}
}
}
Conclusion
Extracting background images from PowerPoint presentations is a crucial technique for developers and designers who want to access slide visuals independently of content. By leveraging the Spire.Presentation for .NET library with C#, you can programmatically extract background images from both individual slides and slide masters with ease.
FAQs
Q: What image formats are supported for extraction?
A: Extracted images can be saved in PNG, JPEG, BMP, or other formats supported by .NET.
Q: In addition to background images, can I extract other images from PowerPoint slides?
A: Yes, you can extract other images, such as those embedded within slide content or shapes, using Spire.Presentation.
Q: Does Spire.Presentation supports extracting text from PowerPoint presentations?
A: Yes, Spire.Presentation can also extract text from slides, including text in shapes, tables, and more.
Get a Free License
To fully experience the capabilities of Spire.Presentation for .NET without any evaluation limitations, you can request a free 30-day trial license.

In data processing and management scenarios, efficiently transforming raw text (TXT) files into structured Excel spreadsheets is a common requirement. For developers who are automating reports or processing log files, converting TXT to Excel using C# streamlines data organization and analysis. This guide explores how to achieve this using Spire.XLS for .NET, a powerful library designed to handle Excel XLS or XLSX files without requiring Microsoft Office.
- Why Convert TXT to Excel Programmatically?
- How to Convert Text Files to Excel in C# (Step-by-Step Guide)
- Pro Tips for TXT to Excel Conversion
Why Convert TXT to Excel Programmatically?
Text files are simple but lack the analytical power of Excel. Key advantages of converting TXT to XLS or XLSX format include:
- Automation: Process large or recurring files without manual intervention.
- Data Structuring: Organize raw text into rows, columns, and sheets.
- Advanced Features: Leverage Excel formulas, charts, and pivot tables.
- Integration: Embed conversion feature into .NET applications or APIs.
How to Convert Text Files to Excel in C# (Step-by-Step Guide)
Install Spire.XLS for .NET
Spire.XLS for .NET is a professional Excel document processing component, provides efficient and convenient APIs that allow developers to achieve TXT to Excel conversion through simple code.
Before getting started, you can choose one of these methods to install the library:
Method 1: NuGet Package Manager
- Open your project in Visual Studio.
- Right-click on the project in the Solution Explorer and select "Manage NuGet Packages."
- Search for "Spire.XLS" and click "Install".
Method 2: Package Manager Console
- Go to "Tools > NuGet Package Manager > Package Manager Console."
- Run the following command in the console:
PM> Install-Package Spire.XLS
Method 3: Manual Installation with DLL Files
- Visit the Spire.XLS Download Page and get the latest version.
- Extract the files and then add the Spire.Xls.dll to your project.
Import a Text File into Excel Using C#
Follow the below steps to write the data in a txt file into an Excel worksheet:
- Read TXT File: use the File.ReadAllLines() method to read all lines in a text file and returns them as an array of strings.
- Parse each line:
- Use the string.Trim() method to remove the leading/trailing whitespaces.
- Use the string.Split() method to split the data based on specified delimiters.
- Add the split text data to a list.
- Create a Workbook instance and get a worksheet
- Write Data to specified cells:
- Iterate through the rows and columns in the list.
- Assign the data in the list to the corresponding Excel cells through the Worksheet.Range[].Value property.
- Save the Excel File.
Code Example:
- C#
using Spire.Xls;
using System.IO;
using System.Collections.Generic;
class TxtToExcelConverter
{
static void Main()
{
// Open a text file and read all lines in it
string[] lines = File.ReadAllLines("Data.txt");
// Create a list to store the data in text file
List data = new List();
// Split data into rows and columns and add to the list
foreach (string line in lines)
{
data.Add(line.Trim().Split('\t')); // Adjust delimiter as needed
}
// Create a Workbook object
Workbook workbook = new Workbook();
// Get the first worksheet
Worksheet sheet = workbook.Worksheets[0];
// Iterate through the rows and columns in the data list
for (int row = 0; row < data.Count; row++)
{
for (int col = 0; col < data[row].Length; col++)
{
// Write the text data in specified cells
sheet.Range[row + 1, col + 1].Value = data[row][col];
// Set the header row to Bold
sheet.Range[1, col + 1].Style.Font.IsBold = true;
}
}
// Autofit columns
sheet.AllocatedRange.AutoFitColumns();
// Save the Excel file
workbook.SaveToFile("TXTtoExcel.xlsx", ExcelVersion.Version2016);
workbook.Dispose();
}
}
Result:

Pro Tips for TXT to Excel Conversion
- Handling Different Delimiters:
If your TXT file uses a different delimiter (e.g., space, comma, semicolon), modify the parameter of the Split(params char[] separator) method.
- Format Cells:
After a text file being converted to an Excel file, you can take advantage of the Spire.XLS library’s rich features to format cells, such as setting the background colors, adding cell borders, applying number formats, etc.
Conclusion
By following this step-by-step guide, you can efficiently transform unstructured text data into organized Excel spreadsheets, which is ideal for data analysis, reporting, and management. Remember to optimize your implementation for your specific delimiters and leverage Spire.XLS's advanced features for complex conversion scenarios.
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.
Generating Word documents programmatically is a common requirement in business applications, whether for creating reports, contracts, or personalized letters. Spire.Doc for .NET provides a comprehensive solution for working with Word documents in C# without Microsoft Office dependencies.
This article explores two effective approaches for document generation from templates: replacing text placeholders and modifying bookmark content.
- Create a Word Document By Replacing Text Placeholders
- Create a Word Document By Replacing Bookmark Content
.NET Library for Creating Word Documents
Spire.Doc for .NET is a professional Word API that enables developers to perform a wide range of document processing tasks. Key features include:
- Creating, reading, editing, and converting Word documents
- Support for DOC, DOCX, RTF, and other formats
- Template-based document generation
- Mail merge functionality
- Preservation of original formatting
The library is particularly useful for automating document generation in enterprise applications, where consistency and efficiency are crucial.
To begin generating Word documents from a template, donwload Spire.Doc for .NET from our official website or install it using the NuGet Package Manager with the following command:
PM> Install-Package Spire.Doc
Create a Word Document By Replacing Text Placeholders
The Document.Replace method in the Spire.Doc library is used to find and replace specific text within a Word document. This method allows for the efficient modification of text placeholders, enabling the dynamic generation of documents based on templates.
Here are the steps for Word generation through text pattern replacement:
- Document Initialization: Create a new Document object and load the template file.
- Placeholder Definition: Use a dictionary to map placeholders (like #name#) to their replacement values.
- Text Replacement: The Document.Replace method performs case-sensitive and whole-word replacement of all placeholders.
- Image Handling: The custom ReplaceTextWithImage method locates a text placeholder and substitutes it with an image.
- Document Saving: The modified document is saved with a new filename.
- C#
using Spire.Doc;
using Spire.Doc.Documents;
using Spire.Doc.Fields;
using System.Drawing;
namespace CreateWordByReplacingTextPlaceholders
{
class Program
{
static void Main(string[] args)
{
// Initialize a new Document object
Document document = new Document();
// Load the template Word file
document.LoadFromFile("C:\\Users\\Administrator\\Desktop\\Template.docx");
// Dictionary to hold text placeholders and their replacements
Dictionary<string, string> replaceDict = new Dictionary<string, string>
{
{ "#name#", "John Doe" },
{ "#gender#", "Male" },
{ "#birthdate#", "January 15, 1990" },
{ "#address#", "123 Main Street" },
{ "#city#", "Springfield" },
{ "#state#", "Illinois" },
{ "#postal#", "62701" },
{ "#country#", "United States" }
};
// Replace placeholders in the document with corresponding values
foreach (KeyValuePair<string, string> kvp in replaceDict)
{
document.Replace(kvp.Key, kvp.Value, true, true);
}
// Path to the image file
String imagePath = "C:\\Users\\Administrator\\Desktop\\portrait.png";
// Replace the placeholder “#photo#” with an image
ReplaceTextWithImage(document, "#photo#", imagePath);
// Save the modified document
document.SaveToFile("ReplacePlaceholders.docx", FileFormat.Docx);
// Release resources
document.Dispose();
}
// Method to replace a placeholder in the document with an image
static void ReplaceTextWithImage(Document document, String stringToReplace, String imagePath)
{
// Load the image from the specified path
Image image = Image.FromFile(imagePath);
DocPicture pic = new DocPicture(document);
pic.LoadImage(image);
// Find the placeholder in the document
TextSelection selection = document.FindString(stringToReplace, false, true);
// Get the range of the found text
TextRange range = selection.GetAsOneRange();
int index = range.OwnerParagraph.ChildObjects.IndexOf(range);
// Insert the image and remove the placeholder text
range.OwnerParagraph.ChildObjects.Insert(index, pic);
range.OwnerParagraph.ChildObjects.Remove(range);
}
}
}

Create a Word Document By Replacing Bookmark Content
The BookmarksNavigator class in Spire.Doc is specifically designed to manage and navigate through bookmarks in a Word document. This class simplifies the process of finding and replacing content in bookmarks, making it easy to update sections of a document without manually searching for each bookmark.
The following are the steps for Word generation using bookmark content replacement:
- Document Initialization: Create a new Document object and load the template file.
- Bookmark Content Definitions: Create a dictionary mapping bookmark names to their replacement content.
- Bookmark Navigation: The BookmarksNavigator class provides precise control over bookmark locations.
- Content Replacement: The ReplaceBookmarkContent method preserves the bookmark while updating its content.
- Document Saving: The modified document is saved with a new filename.
- C#
using Spire.Doc;
using Spire.Doc.Documents;
namespace CreateWordByReplacingBookmarkContent
{
class Program
{
static void Main(string[] args)
{
// Initialize a new Document object
Document document = new Document();
// Load the template Word file
document.LoadFromFile("C:\\Users\\Administrator\\Desktop\\Template.docx");
// Define bookmark names and their replacement values
Dictionary<string, string> replaceDict = new Dictionary<string, string>
{
{ "name", "Tech Innovations Inc." },
{ "year", "2015" },
{ "headquarter", "San Francisco, California, USA" },
{ "history", "Tech Innovations Inc. was founded by a group of engineers and " +
"entrepreneurs with a vision to revolutionize the technology sector. Starting " +
"with a focus on software development, the company expanded its portfolio to " +
"include artificial intelligence and cloud computing solutions." }
};
// Create a BookmarksNavigator to manage bookmarks in the document
BookmarksNavigator bookmarkNavigator = new BookmarksNavigator(document);
// Replace each bookmark's content with the corresponding value
foreach (KeyValuePair<string, string> kvp in replaceDict)
{
bookmarkNavigator.MoveToBookmark(kvp.Key); // Navigate to bookmark
bookmarkNavigator.ReplaceBookmarkContent(kvp.Value, true); // Replace content
}
// Save the modified document
document.SaveToFile("ReplaceBookmarkContent.docx", FileFormat.Docx2013);
// Release resources
document.Dispose();
}
}
}

Conclusion
Both approaches provide effective ways to generate documents from templates, but with important differences:
- Text Replacement Method:
- Permanently removes placeholders during replacement
- Best for one-time document generation
- Better suited for replacing text with images
- Bookmark Replacement Method:
- Preserves bookmarks for future updates
- Ideal for templates requiring periodic updates
Additionally, Spire.Doc for .NET supports Mail Merge functionality, which provides another powerful way to dynamically generate documents from templates. This feature is particularly useful for creating personalized documents in bulk, such as form letters or reports, where data comes from a database or other structured source.
Get a Free License
To fully experience the capabilities of Spire.Doc for .NET without any evaluation limitations, you can request a free 30-day trial license.