.NET (1322)
Children categories
How to Generate & Create QR Code in ASP.NET C# (Full Example)
2025-08-08 05:38:37 Written by zaki zou
QR codes have become a standard feature in modern web applications, widely used for user authentication, contactless transactions, and sharing data like URLs or contact information. For developers working with ASP.NET, implementing QR code generation using C# is a practical requirement in many real-world scenarios.
In this article, you’ll learn how to generate QR codes in ASP.NET using Spire.Barcode for .NET. We’ll walk through a complete example based on an ASP.NET Core Web App (Razor Pages) project, including backend logic and a simple UI to display the generated code. The same approach can be easily adapted to MVC, Web API, and Web Forms applications.
Article Overview
- 1. Project Setup and Dependencies
- 2. Generate QR Code in ASP.NET Using C#
- 3. Customize QR Code Output
- 4. Apply Logic in MVC, Web API, and Web Forms
- 5. Conclusion
- FAQs
1. Project Setup and Dependencies
Prerequisites
To follow along, make sure you have:
- Visual Studio 2019 or newer
- .NET 6 or later
- ASP.NET Core Web App (Razor Pages Template)
- NuGet package: Spire.Barcode for .NET
Install Spire.Barcode for .NET
Install the required library using NuGet Package Manager Console:
Install-Package Spire.Barcode
Spire.Barcode is a fully self-contained .NET barcode library that supports in-memory generation of QR codes without external APIs. You can also use Free Spire.Barcode for .NET for smaller projects.
2. Generate QR Code in ASP.NET Using C#
This section describes how to implement QR code generation in an ASP.NET Core Web App (Razor Pages) project. The example includes a backend C# handler that generates the QR code using Spire.Barcode for .NET, and a simple Razor Page frontend for user input and real-time display.
Step 1: Add QR Code Generation Logic in PageModel
The backend logic resides in the Index.cshtml.cs file. It processes the form input, generates a QR code using Spire.Barcode, and returns the result as a Base64-encoded image string that can be directly embedded in HTML.
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Spire.Barcode;
public class IndexModel : PageModel
{
[BindProperty]
public string InputData { get; set; }
public string QrCodeBase64 { get; set; }
public void OnPost()
{
if (!string.IsNullOrWhiteSpace(InputData))
{
QrCodeBase64 = GenerateQrCodeBase64(InputData);
}
}
private string GenerateQrCodeBase64(string input)
{
var settings = new BarcodeSettings
{
Type = BarCodeType.QRCode, // QR code type
Data = input, // Main encoded data
Data2D = input, // Required for 2D barcode, usually same as Data
QRCodeDataMode = QRCodeDataMode.Byte, // Byte mode (supports multilingual content)
QRCodeECL = QRCodeECL.M, // Medium error correction (15%)
X = 3, // Module size (affects image dimensions)
ShowText = false, // Hide default barcode text
ShowBottomText = true, // Show custom bottom text
BottomText = input // Bottom text to display under the QR code
};
var generator = new BarCodeGenerator(settings);
using var ms = new MemoryStream();
var qrImage = generator.GenerateImage();
qrImage.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
return Convert.ToBase64String(ms.ToArray());
}
}
Key Components:
-
BarcodeSettings: Specifies the QR code's core configuration, such as type (QRCode), data content, encoding mode, and error correction level.
-
BarCodeGenerator: Takes the settings and generates the QR code image as a System.Drawing.Image object using the GenerateImage() method.
-
Base64 Conversion: Converts the image to a Base64 string so it can be directly embedded into the HTML page without saving to disk.
This approach keeps the entire process in memory, making it fast, portable, and suitable for serverless or cloud-hosted applications.
Step 2: Create the Razor Page for User Input and QR Code Display and Download
The following Razor markup in the Index.cshtml file defines a form for entering text or URLs, displays the generated QR code upon submission, and provides a button to download the QR code image.
@page
@model IndexModel
@{
ViewData["Title"] = "QR Code Generator";
}
<h2>QR Code Generator</h2>
<form method="post">
<label for="InputData">Enter text or URL:</label>
<input type="text" id="InputData" name="InputData" style="width:300px;" required />
<button type="submit">Generate QR Code</button>
</form>
@if (!string.IsNullOrEmpty(Model.QrCodeBase64))
{
<div style="margin-top:20px">
<img src="data:image/png;base64,@Model.QrCodeBase64" alt="QR Code" />
<br />
<a href="data:image/png;base64,@Model.QrCodeBase64" download="qrcode.png">Download QR Code</a>
</div>
}
The Base64-encoded image is displayed directly in the browser using a data: URI. This eliminates the need for file storage and allows for immediate rendering and download.
The following screenshot shows the result after submitting text input.

If you need to scan QR codes instead, please refer to How to Scan QR Codes in C#.
3. Customize QR Code Output
Spire.Barcode provides several customization options through the BarcodeSettings class to control the appearance and behavior of the generated QR code:
| Property | Function | Example |
|---|---|---|
| QRCodeDataMode | Text encoding mode | QRCodeDataMode.Byte |
| QRCodeECL | Error correction level | QRCodeECL.H (high redundancy) |
| X | Module size (resolution) | settings.X = 6 |
| ImageWidth/Height | Control dimensions of QR image | settings.ImageWidth = 300 |
| ForeColor | Set QR code color | settings.ForeColor = Color.Blue |
| ShowText | Show or hide text below barcode | settings.ShowText = false |
| BottomText | Custom text to display below barcode | settings.BottomText = "Scan Me" |
| ShowBottomText | Show or hide the custom bottom text | settings.ShowBottomText = true |
| QRCodeLogoImage | Add a logo image to overlay at QR code center | settings.QRCodeLogoImage = System.Drawing.Image.FromFile("logo.png"); |
These properties help you tailor the appearance of your QR code for branding, readability, or user interaction purposes.
To explore more QR code settings, refer to the BarcodeSettings API reference.
4. Apply Logic in MVC, Web API, and Web Forms
The same QR code generation logic used in Razor Pages can also be reused in other ASP.NET frameworks such as MVC, Web API, and Web Forms.
MVC Controller Action
In an MVC project, you can add a Generate action in a controller (e.g., QrController.cs) to generate and return the QR code image directly:
public class QrController : Controller
{
public ActionResult Generate(string data)
{
var settings = new BarcodeSettings
{
Type = BarCodeType.QRCode,
Data = data,
QRCodeDataMode = QRCodeDataMode.Byte,
QRCodeECL = QRCodeECL.M,
X = 5
};
var generator = new BarCodeGenerator(settings);
using var ms = new MemoryStream();
generator.GenerateImage().Save(ms, System.Drawing.Imaging.ImageFormat.Png);
return File(ms.ToArray(), "image/png");
}
}
This method returns the QR code as a downloadable PNG file, ideal for server-side rendering.
Web API Endpoint
For Web API, you can define a GET endpoint in a controller such as QrApiController.cs that responds with the generated image stream:
[ApiController]
[Route("api/[controller]")]
public class QrApiController : ControllerBase
{
[HttpGet("generate")]
public IActionResult GetQr(string data)
{
var settings = new BarcodeSettings
{
Type = BarCodeType.QRCode,
Data = data
};
var generator = new BarCodeGenerator(settings);
using var ms = new MemoryStream();
generator.GenerateImage().Save(ms, System.Drawing.Imaging.ImageFormat.Png);
return File(ms.ToArray(), "image/png");
}
}
This approach is suitable for frontends built with React, Vue, Angular, or any JavaScript framework.
Web Forms Code-Behind
In ASP.NET Web Forms, you can handle QR code generation in the code-behind of a page like Default.aspx.cs:
protected void btnGenerate_Click(object sender, EventArgs e)
{
var settings = new BarcodeSettings
{
Type = BarCodeType.QRCode,
Data = txtInput.Text
};
var generator = new BarCodeGenerator(settings);
using var ms = new MemoryStream();
generator.GenerateImage().Save(ms, System.Drawing.Imaging.ImageFormat.Png);
imgQR.ImageUrl = "data:image/png;base64," + Convert.ToBase64String(ms.ToArray());
}
The generated image is embedded directly into an asp:Image control using a Base64 data URI.
5. Conclusion
With Spire.Barcode for .NET, you can seamlessly generate and customize QR codes across all ASP.NET project types — Razor Pages, MVC, Web API, or Web Forms. The solution is fully offline, fast, and requires no third-party API.
Returning images as Base64 strings simplifies deployment and avoids file management. Whether you're building authentication tools, ticketing systems, or contact sharing, this approach is reliable and production-ready.
FAQs
Q: Does Spire.Barcode support Unicode characters like Chinese or Arabic?
A: Yes. Use QRCodeDataMode.Byte for full Unicode support.
Q: Can I adjust QR code size and color?
A: Absolutely. Use properties like X, ForeColor, and ImageWidth.
Q: Is this solution fully offline?
A: Yes. It works without any external API calls or services.
Q: Can I expose this QR logic via API?
A: Yes. Use ASP.NET Web API to serve generated images to client apps.
Export Database to Excel in C#: Practical Guide with SQL Example
2025-08-06 01:59:33 Written by zaki zou
Exporting data from a database to Excel using C# is a frequent requirement in business applications—be it for internal reporting, audit logs, data migration, or ad-hoc analysis. Excel's portability and familiarity make it a go-to format for sharing structured data with both technical and non-technical users.
In this guide, you'll learn how to export database records to Excel using C# and Spire.XLS for .NET. We’ll walk through retrieving data from a SQL Server database and writing it into a well-formatted Excel file. The same workflow applies to other relational databases such as SQLite, MySQL, or Oracle with only minimal adjustments.
Table of Contents:
- Prerequisites and Environment Setup
- Exporting Data from SQL Database to Excel in C#
- Format the Excel Output
- Alternative Approaches to Read Data
- Common Issues and Troubleshooting
- Conclusion
- FAQ
Prerequisites and Environment Setup
Before we dive into code, ensure your development environment is ready:
-
.NET Version: .NET Framework or .NET Core / .NET 6 / .NET 8
-
IDE: Visual Studio (Community or higher)
-
Database: A relational database (e.g., SQL Server, SQLite, MySQL, Oracle). This tutorial uses SQL Server Express as the example. By default, the connection uses Windows Authentication, but you can switch to SQL Authentication if needed.
-
Libraries:
- Spire.XLS for .NET (Install via NuGet: Install-Package Spire.XLS)
- Microsoft.Data.SqlClient (Install via NuGet if using SQL Server)
Sample Data
In the following examples, we'll use a simple Employees table stored in SQL Server Express. Here's the SQL script to create and populate it:
CREATE TABLE Employees (
Id INT PRIMARY KEY IDENTITY,
Name NVARCHAR(100) NOT NULL,
Department NVARCHAR(50) NOT NULL,
Position NVARCHAR(50),
HireDate DATE NOT NULL,
Salary DECIMAL(10, 2) NOT NULL,
IsFullTime BIT NOT NULL
);
INSERT INTO Employees (Name, Department, Position, HireDate, Salary, IsFullTime) VALUES
('Alice Johnson', 'Human Resources', 'HR Manager', '2018-05-01', 5500.00, 1),
('Bob Smith', 'IT', 'Software Engineer', '2020-09-15', 7200.50, 1),
('Charlie Lee', 'Finance', 'Accountant', '2019-11-20', 6300.75, 0),
('Diana Chen', 'Marketing', 'Content Specialist', '2021-02-10', 4800.00, 1);
If you're using another database system like MySQL or SQLite, just adjust the SQL syntax and connection string accordingly. The export logic remains the same.
Exporting Data from SQL Database to Excel in C#
Let’s walk through how to retrieve data from a database and export it to an Excel file using Spire.XLS for .NET.
Step 1: Connect to the SQL Server Database
We start by establishing a connection to the database using SqlConnection. Here's an example connection string targeting SQL Server Express:
string connectionString = @"Data Source=YourServer\SQLEXPRESS;Initial Catalog=YourDatabaseName;Integrated Security=True;";
The above connection string uses Windows Authentication (Integrated Security=True). If you prefer SQL Server Authentication, replace it with: User ID=yourUsername;Password=yourPassword;Encrypt=True;TrustServerCertificate=True;
Make sure that your SQL Server Express instance is running, and that the specified database and table exist.
Step 2: Retrieve Data into a DataTable
To make the data ready for export, we use SqlDataAdapter to fill a DataTable with the results of a SQL query:
using System.Data;
using Microsoft.Data.SqlClient;
DataTable dataTable = new DataTable();
using (SqlConnection conn = new SqlConnection(connectionString))
{
conn.Open();
string query = "SELECT * FROM Employees";
using (SqlDataAdapter adapter = new SqlDataAdapter(query, conn))
{
adapter.Fill(dataTable);
}
}
Spire.XLS can directly import data from a DataTable using InsertDataTable, which makes it ideal for structured exports from relational databases.
Step 3: Export the DataTable to Excel Using Spire.XLS
Once the DataTable is populated, we can use Spire.XLS to write its contents into a new Excel worksheet:
using Spire.Xls;
// Create a new workbook
Workbook workbook = new Workbook();
// Clear the default sheets and create a new one
workbook.Worksheets.Clear();
Worksheet sheet = workbook.Worksheets.Add("Employees");
// Insert data starting from row 1, column 1, and include column headers
sheet.InsertDataTable(dataTable, true, 1, 1);
// Save the workbook as an Excel xlsx file
workbook.SaveToFile("Employees.xlsx", ExcelVersion.Version2013);
Key classes and methods used:
- Workbook: The main entry point for creating or loading Excel files.
- Worksheet: Represents a single sheet in the workbook. Use workbook.Worksheets[] to access a sheet, or Worksheets.Add() to add more.
- InsertDataTable(DataTable dataTable, bool columnHeaders, int firstRow, int firstColumn):
- columnHeaders = true tells Spire.XLS to write column names as the first row.
- firstRow, firstColumn specify where the data begins (1-based index).
- Workbook.SaveToFile(string fileName, ExcelVersion version): Saves the workbook to a file. Spire.XLS supports saving Excel workbooks to various formats, including .xlsx, .xls, and .csv. You can also save to a stream using SaveToStream().
Here’s what the resulting Excel file looks like with the raw data exported from the database.

Step 4: Format the Excel Output (Optional but Recommended)
While the data is already exported, applying some formatting can significantly improve readability for end users:
// Write data to Excel, including column names, starting at row 1, column 1
sheet.InsertDataTable(dataTable, true, 1, 1);
// Make header row bold and highlight with background color
sheet.Rows[0].Style.Font.IsBold = true;
sheet.Rows[0].Style.Font.Size = 14;
sheet.Rows[0].Style.HorizontalAlignment = HorizontalAlignType.Center;
sheet.Rows[0].Style.Color = System.Drawing.Color.LightGray;
// Format data rows
for (int i = 1; i < sheet.Rows.Count(); i++)
{
CellRange dataRow = sheet.Rows[i];
dataRow.Style.Font.Size = 12;
dataRow.Style.HorizontalAlignment = HorizontalAlignType.Left;
}
// Set font name
sheet.AllocatedRange.Style.Font.FontName = "Arial";
// Set borders
sheet.AllocatedRange.BorderAround(LineStyleType.Thin, System.Drawing.Color.Black);
sheet.AllocatedRange.BorderInside(LineStyleType.Medium, System.Drawing.Color.Black);
// Auto-fit columns
sheet.AllocatedRange.AutoFitColumns();
Here's what the Excel file looks like after formatting.

Spire.XLS provides full access to cell styles, fonts, colors, borders, alignment, and more—making it suitable for generating production-quality Excel reports.
If you need advanced number formatting, learn how to set number formats for Excel cells using C#.
Alternative Approaches to Read Data
The export process relies on having a DataTable, but how you populate it can vary based on your application architecture:
A. Using Entity Framework (ORM)
If you use EF Core or EF6, you can load data via LINQ and manually insert it into Excel:
var employees = dbContext.Employees.ToList();
To export, either convert this list into a DataTable, or use a loop to write rows manually using sheet.Range[row, col].Value = value.
B. Using Stored Procedures
Stored procedures allow encapsulating SQL logic. You can execute them using SqlCommand and fill the result into a DataTable:
SqlCommand cmd = new SqlCommand("GetEmployees", conn);
cmd.CommandType = CommandType.StoredProcedure;
C. Reading from SQLite
For lightweight scenarios, replace the connection string and class:
using (SQLiteConnection conn = new SQLiteConnection("Data Source=mydb.db"))
Export logic remains identical—fill a DataTable and use InsertDataTable.
D. Reading from MySQL or Oracle
Same pattern applies—just change the connection class:
using (MySqlConnection conn = new MySqlConnection("server=localhost;uid=root;pwd=123;database=test"))
Make sure to install the appropriate ADO.NET data provider (e.g., Microsoft.Data.SqlClient, Microsoft.Data.Sqlite, or MySql.Data) via NuGet when connecting to different databases.
As long as you populate a DataTable, Spire.XLS handles the Excel generation the same way.
You may also like: How to Import Data from Excel to Database – learn how to complete the full data exchange cycle using Spire.XLS.
Common Issues and Troubleshooting
| Issue | Solution |
|---|---|
| Excel file opens empty | Ensure the DataTable has data before calling InsertDataTable() |
| Access denied on save | Check folder permissions or file path conflicts |
| Connection fails | Verify your database server, credentials, and connection string |
| Special characters not displaying | Use NVARCHAR in SQL and Unicode-compatible fonts in Excel |
| Login failed or authentication error | Check authentication method: use Integrated Security=True for Windows, or provide User ID and Password for SQL Authentication. |
Conclusion
Exporting a database to Excel in C# can be done efficiently using Spire.XLS for .NET. By retrieving data into a DataTable and exporting it with InsertDataTable(), you can automate reporting and data extraction without needing Microsoft Office installed.
This solution can also be integrated into scheduled tasks, background services, or web applications for automated report generation.
To unlock all features during development or testing, you can apply for a free 30-day temporary license. For smaller projects, Free Spire.XLS for .NET may also be sufficient.
FAQ
How do I export SQL to Excel in C#?
Use SqlConnection to retrieve data into a DataTable, and export it using Spire.XLS’s InsertDataTable() method.
Can I use this method with SQLite or MySQL?
Yes. Just change the connection type and query, then pass the resulting DataTable to Spire.XLS.
Do I need Excel installed to use Spire.XLS?
No. Spire.XLS is a standalone library and does not require Microsoft Excel on the machine.
Can I export multiple tables to Excel?
Yes. Use Workbook.Worksheets.Add() to create additional worksheets, and export each DataTable separately.

Exporting a DataTable to Excel in C# is a common task in .NET development, such as generating reports, exporting logs, or preparing data for sharing across systems. By using a standalone component, developers can quickly export data and apply formatting to create professional, ready-to-use Excel files from DataTables without relying on complex setup or external dependencies.
To streamline this process, Spire.XLS for .NET offers a lightweight and fully independent library. In this article, you'll learn how to export a DataTable to Excel (.xlsx or .xls) in C#, apply formatting to improve readability, and address common export scenarios effectively.
Quick Navigation
- Install and Configure Spire.XLS
- Step-by-Step: Export DataTable to Excel
- Format and Style the Exported Excel File
- Common Issues and Solutions
- Conclusion
- Frequently Asked Questions
Install and Configure Spire.XLS
Before you start, make sure your project includes Spire.XLS for .NET.
Install Spire.XLS via NuGet
Run this command in the NuGet Package Manager Console:
Install-Package Spire.XLS
Spire.XLS works with .NET Framework, .NET Core, .NET 6/7+, and ASP.NET projects — no Microsoft Office installation required.
Step-by-Step: Export DataTable to Excel in C#
The following steps demonstrate how to export a DataTable to an Excel file using Spire.XLS, including data preparation, file generation, optional streaming, and output formatting.
1. Create a Sample DataTable
First, create a DataTable and add some sample rows:
DataTable dt = new DataTable("Employees");
// Insert columns
dt.Columns.Add("ID", typeof(int));
dt.Columns.Add("Name", typeof(string));
dt.Columns.Add("Department", typeof(string));
dt.Columns.Add("Join Date", typeof(DateTime));
dt.Columns.Add("Salary", typeof(double));
dt.Columns.Add("Full-Time", typeof(bool));
dt.Columns.Add("Bonus Rate", typeof(decimal));
// Insert rows
dt.Rows.Add(1001, "Alice", "HR", new DateTime(2021, 5, 10), 55000.5, true, 0.05m);
dt.Rows.Add(1002, "Bob", "IT", new DateTime(2020, 11, 23), 72000.0, false, 0.03m);
dt.Rows.Add(1003, "Carol", "Finance", new DateTime(2019, 8, 15), 63000.75, true, 0.07m);
dt.Rows.Add(1004, "David", "Marketing", new DateTime(2022, 3, 8), 48800.0, true, 0.06m);
Tip: This is just sample data — you can bind any DataTable your app generates.
2. Import DataTable and Save to Excel File
Next, initialize the Excel workbook, import the DataTable into a worksheet, and save the file:
// Create a new workbook
Workbook workbook = new Workbook();
// Clear the default worksheets and add a new one
workbook.Worksheets.Clear();
Worksheet sheet = workbook.Worksheets.Add(dt.TableName);
// Import the DataTable starting at cell A1
sheet.InsertDataTable(dt, true, 1, 1);
// Save as XLSX (recommended)
workbook.SaveToFile("EmployeeData.xlsx", FileFormat.Version2016);
// Or save as XLS (older format)
workbook.SaveToFile("EmployeeData.xls", FileFormat.Version97to2003);
Explanation:
- Workbook is the container for your Excel file.
- InsertDataTable(dataTable, includeColumnHeaders, startRow, startColumn) maps the entire table to the Excel grid.
- SaveToFile() writes the file to disk in your chosen format.
Output Preview
Example of the exported Excel file:

3. Export Excel File as Stream in ASP.NET
When building a web app, you might want to export the file directly as a stream instead of saving to disk:
MemoryStream stream = new MemoryStream();
workbook.SaveToStream(stream, FileFormat.Version2013);
stream.Position = 0;
Return this MemoryStream in your ASP.NET controller to trigger a file download in the browser.
For additional tips on managing Excel files in C#, check out How to Create and Manipulate Excel Files in C#.
Format and Style the Exported Excel File
Formatting is optional but recommended for creating professional Excel files. Below is how you can format the exported content using Spire.XLS.
// Style the header row
CellRange header = sheet.Rows[0];
header.Style.Font.IsBold = true;
header.Style.Font.FontName = "Arial";
header.Style.Font.Size = 13;
header.Style.Color = Color.LightGray;
header.Style.Borders[BordersLineType.EdgeBottom].LineStyle = LineStyleType.Thick;
// Style the data rows
for (int i = 1; i < sheet.Rows.Length; i++)
{
CellRange dataRow = sheet.Rows[i];
dataRow.Style.Font.FontName = "Times New Roman";
dataRow.Style.Font.Size = 11;
dataRow.BorderInside();
}
// Format date column to display as date
CellRange dateColumn = sheet.Range[2, 4, sheet.Rows.Length + 1, 4];
dateColumn.Style.NumberFormat = "yyyy-mm-dd";
// Auto-fit columns
sheet.AllocatedRange.AutoFitColumns();
Key Properties and Methods:
- Style: Applies font, color, border, number formatting, etc. to cells.
- AutoFitColumns(): Automatically adjusts column width to fit content.
- NumberFormat: Sets how dates or numbers are displayed in Excel, e.g., "yyyy-mm-dd".
- BorderInside(): Adds internal borders to improve table readability.
Formatted Output Preview
Excel file with formatted header and date column:

For more advanced number formatting options, see how to set number format in Excel using C#.
Common Issues and Solutions
- File won’t open or shows corruption error
Ensure streams are closed properly and file extensions match the format.
- Special characters or non-English text look garbled
Confirm strings are UTF-8 encoded and use appropriate fonts.
- Columns too narrow
Use AutoFitColumns() to adjust widths automatically or use CellRange.ColumnWidth to set a fixed column width.
Conclusion
Exporting a DataTable to Excel in C# is straightforward with Spire.XLS. This approach lets you create .xlsx or .xls files easily without relying on Office, while giving you full control over the output layout for both desktop and web applications.
If needed, you can also request a free temporary license to unlock the full feature set for evaluation.
Frequently Asked Questions
Q1: How to convert DataTable to Excel in C#?
You can use sheet.InsertDataTable() from Spire.XLS to load a DataTable into a worksheet, then save it as an Excel file using workbook.SaveToFile().
Q2: Is there a free library to export a DataTable to Excel in C#?
Yes — Free Spire.XLS for .NET is a standalone library that lets you create and export Excel files directly in C# without needing to install Microsoft Office.
Q3: Can I export DataTable to Excel in ASP.NET?
Yes, the same logic can be applied in ASP.NET by generating the workbook in a controller and streaming it back as a downloadable file.
Q4: What's the difference between .xlsx and .xls export?
.xlsx is the newer Office Open XML format, compatible with Excel 2007 and later. .xls supports legacy Excel 97–2003 but is limited to 65,536 rows.
Read Email in C# via IMAP and POP3 (Outlook Example Included)
2025-07-30 08:56:03 Written by zaki zou
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 = "your-email@outlook.com";
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 = "your-address@gmail.com";
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 zou
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 zou
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.

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 = "your@example.com";
smtp.Password = "your_password";
smtp.ConnectionProtocols = ConnectionProtocols.StartTls;
// Create maill addresses
MailAddress sender = new MailAddress("your@example.com", "Sender Name");
MailAddress recipient = new MailAddress("recipient@example.com", "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("your@gmail.com", "Your Name");
MailAddress to1 = new MailAddress("user1@example.com", "User One");
MailAddress to2 = new MailAddress("user2@example.com", "User Two");
// Create a mail message
MailMessage message = new MailMessage(from, to1);
message.To.Add(to2);
message.Cc.Add(new MailAddress("cc@example.com", "CC Person"));
message.Bcc.Add(new MailAddress("bcc@example.com"));
// 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 = "your@gmail.com";
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("your@domain.com", "Sender"),
new MailAddress("client@domain.com", "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("your@domain.com"),
new MailAddress("sales@domain.com"));
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 = "your@domain.com";
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.