.NET (1333)
Children categories
.NET PDF to JPG Converter: Convert PDF Pages to Images in C#
2025-09-10 03:20:19 Written by Administrator
Working with PDF documents is a common requirement in modern applications. Whether you are building a document management system , an ASP.NET web service , or a desktop viewer application , there are times when you need to display a PDF page as an image. Instead of embedding the full PDF viewer, you can convert PDF pages to JPG images and use them wherever images are supported.
In this guide, we will walk through a step-by-step tutorial on how to convert PDF files to JPG images using Spire.PDF for .NET. We’ll cover the basics of converting a single page, handling multiple pages, adjusting resolution and quality, saving images to streams, and even batch converting entire folders of PDFs.
By the end, you’ll have a clear understanding of how to implement PDF-to-image conversion in your .NET projects.
Table of Contents:
- Install .NET PDF-to-JPG Converter Library
- Core Method: SaveAsImage
- Steps to Convert PDF to JPG in C# .NET
- Convert a Single Page to JPG
- Convert Multiple Pages (All or Range)
- Advanced Conversion Options
- Troubleshooting & Best Practices
- Conclusion
- FAQs
Install .NET PDF-to-JPG Converter Library
To perform the conversion, we’ll use Spire.PDF for .NET , a library designed for developers who need full control over PDFs in C#. It supports reading, editing, and converting PDFs without requiring Adobe Acrobat or any third-party dependencies.
Installation via NuGet
You can install Spire.PDF directly into your project using NuGet Package Manager Console:
Install-Package Spire.PDF
Alternatively, open NuGet Package Manager in Visual Studio, search for Spire.PDF , and click Install.
Licensing Note
Spire.PDF offers a free version with limitations, allowing conversion of only the first few pages. For production use, a commercial license unlocks the full feature set.
Core Method: SaveAsImage
The heart of PDF-to-image conversion in Spire.PDF lies in the SaveAsImage() method provided by the PdfDocument class.
Here’s what you need to know:
-
Syntax (overload 1):
-
Image SaveAsImage(int pageIndex, PdfImageType imageType);
- pageIndex: The zero-based index of the PDF page you want to convert.
- imageType: The type of image to generate, typically PdfImageType.Bitmap.
-
Syntax (overload 2 with resolution):
-
Image SaveAsImage(int pageIndex, PdfImageType imageType, int dpiX, int dpiY);
- dpiX, dpiY: Horizontal and vertical resolution (dots per inch).
Higher DPI = better quality but larger file size.
Supported PdfImageType Values
- Bitmap → returns a raw image.
- Metafile → returns a vector image (less common for JPG export).
Most developers use Bitmap when exporting to JPG.
Steps to Convert PDF to JPG in C# .NET
- Import the Spire.Pdf and System.Drawing namespaces.
- Create a new PdfDocument instance.
- Load the PDF file from the specified path.
- Use SaveAsImage() to convert one or more pages into images.
- Save the generated image(s) in JPG format.
Convert a Single Page to JPG
Here’s a simple workflow to convert a single PDF page to a JPG image:
using Spire.Pdf.Graphics;
using Spire.Pdf;
using System.Drawing.Imaging;
using System.Drawing;
namespace ConvertSpecificPageToPng
{
class Program
{
static void Main(string[] args)
{
// Create a PdfDocument object
PdfDocument doc = new PdfDocument();
// Load a sample PDF document
doc.LoadFromFile("C:\\Users\\Administrator\\Desktop\\sample.pdf");
// Convert a specific page to a bitmap image
Image image = doc.SaveAsImage(0, PdfImageType.Bitmap);
// Save the image as a JPG file
image.Save("ToJPG.jpg", ImageFormat.Jpeg);
// Disposes resources
doc.Dispose();
}
}
}
Output:

Spire.PDF supports converting PDF to various other image formats like PNG, BMP, SVG, and TIFF. For more details, refer to the documentation: Convert PDF to Image in C#.
Convert Multiple Pages (All or Range)
Convert All Pages
The following loop iterates over all pages, converts each one into an image, and saves it to disk with page numbers in the filename.
for (int i = 0; i < doc.Pages.Count; i++)
{
Image image = doc.SaveAsImage(i, PdfImageType.Bitmap);
string fileName = string.Format("Output\\ToJPG-{0}.jpg", i);
image.Save(fileName, ImageFormat.Jpeg);
}
Convert a Range of Pages
To convert a specific range of pages (e.g., pages 2 to 4), modify the for loop as follows:
for (int i = 1; i <= 3; i++)
{
Image image = doc.SaveAsImage(i, PdfImageType.Bitmap);
string fileName = string.Format("Output\\ToJPG-{0}.jpg", i);
image.Save(fileName, ImageFormat.Jpeg);
}
Advanced Conversion Options
Set Image Resolution/Quality
By default, the output resolution might be too low for printing or detailed analysis. You can set DPI explicitly:
Image image = doc.SaveAsImage(0, PdfImageType.Bitmap, 300, 300);
image.Save("ToJPG.jpg", ImageFormat.Jpeg);
Tips:
- 72 DPI : Default, screen quality.
- 150 DPI : Good for previews and web.
- 300 DPI : High quality, suitable for printing.
Higher DPI results in sharper images but also increases memory and file size.
Save the Converted Images as Stream
Instead of writing directly to disk, you can store the output in memory streams. This is useful in:
- ASP.NET applications returning images to browsers.
- Web APIs sending images as HTTP responses.
- Database storage for binary blobs.
using (MemoryStream ms = new MemoryStream())
{
pdf.SaveAsImage(0, PdfImageType.Bitmap, 300, 300).Save(ms, ImageFormat.Jpeg);
byte[] imageBytes = ms.ToArray();
}
Here, the JPG image is stored as a byte array , ready for further processing.
Batch Conversion (Multiple PDFs)
In scenarios where you need to process multiple PDF documents at once, you can apply batch conversion as shown below:
string[] files = Directory.GetFiles("InputPDFs", "*.pdf");
foreach (string file in files)
{
PdfDocument doc = new PdfDocument();
doc.LoadFromFile(file);
for (int i = 0; i < doc.Pages.Count; i++)
{
Image image = doc.SaveAsImage(i, PdfImageType.Bitmap);
string fileName = Path.GetFileNameWithoutExtension(file);
image.Save($"Output\\{fileName}-Page{i + 1}.jpg", ImageFormat.Jpeg);
}
doc.Dispose();
}
Troubleshooting & Best Practices
Working with PDF-to-image conversion in .NET can come with challenges. Here’s how to address them:
- Large PDFs consume memory
- Use lower DPI (e.g., 150 instead of 300).
- Process in chunks rather than loading everything at once.
- Images are blurry or low quality
- Increase DPI.
- Consider using PNG instead of JPG for sharp diagrams or text.
- File paths cause errors
- Always check that the output directory exists.
- Use Path.Combine() for cross-platform paths.
- Handling password-protected PDFs
- Provide the password when loading:
doc.LoadFromFile("secure.pdf", "password123");
- Dispose objects
- Always call Dispose() on PdfDocument and Image objects to release memory.
Conclusion
Converting PDF to JPG in .NET is straightforward with Spire.PDF for .NET . The library provides the SaveAsImage() method, allowing you to convert a single page or an entire document with just a few lines of code. With options for custom resolution, stream handling, and batch conversion , you can adapt the workflow to desktop apps, web services, or cloud platforms.
By following best practices like managing memory and adjusting resolution, you can ensure efficient, high-quality output that fits your project’s requirements.
If you’re exploring more advanced document processing, Spire also offers libraries for Word, Excel, and PowerPoint, enabling a complete .NET document solution.
FAQs
Q1. Can I convert PDFs to formats other than JPG?
Yes. Spire.PDF supports PNG, BMP, SVG, and other common formats.
Q2. What DPI should I use?
- 72 DPI for thumbnails.
- 150 DPI for web previews.
- 300 DPI for print quality.
Q3. Does Spire.PDF support encrypted PDFs?
Yes, but you need to provide the correct password when loading the file.
Q4. Can I integrate this in ASP.NET?
Yes. You can save images to memory streams and return them as HTTP responses.
Q5. Can I convert images back to PDF?
Yes. You can load JPG, PNG, or BMP files and insert them into PDF pages, effectively converting images back into a PDF.
Get a Free License
To fully experience the capabilities of Spire.PDF for .NET without any evaluation limitations, you can request a free 30-day trial license.

Converting HTML to RTF in C# is a key task for developers working with web content that needs to be transformed into editable, universally compatible documents. HTML excels at web display with dynamic styles and structure, while RTF is ideal for shareable, editable files in tools like Word or WordPad.
For .NET developers, using libraries like Spire.Doc can streamline the process. In this tutorial, we'll explore how to use C# to convert HTML to RTF, covering everything from basic implementations to advanced scenarios such as handling HTML images, batch conversion.
- Why Use Spire.Doc for HTML to RTF Conversion?
- Getting Started
- Convert HTML to RTF (C# Code Examples)
- Advanced Conversion Scenarios
- Final Thoughts
- Common Questions
Why Use Spire.Doc for HTML to RTF Conversion?
Spire.Doc for .NET is a lightweight, feature-rich library for creating, editing, and converting Word and RTF documents in .NET applications (supports .NET Framework, .NET Core, and .NET 5+). For HTML to rich text conversion, it offers key benefits:
- Preserves HTML formatting (fonts, colors, links, lists, tables).
- Supports loading HTML from strings or local files.
- No dependency on Microsoft Word or other third-party software.
- Intuitive API with minimal code required.
Getting Started
1. Create a C# Project
If you’re starting from scratch, create a new Console App (.NET Framework/.NET Core) project in Visual Studio. This example uses a console app for simplicity, but the code works in WinForms, WPF, or ASP.NET projects too.
2. Install Spire.Doc via NuGet
The fastest way to add Spire.Doc to your C# project is through NuGet Package Manager:
- Open your C# project in Visual Studio.
- Right-click the project in the Solution Explorer → Select Manage NuGet Packages.
- Search for Spire.Doc and click Install to add the latest version to your project.
Alternatively, use the NuGet Package Manager Console with this command:
Install-Package Spire.Doc
Convert HTML to RTF (C# Code Examples)
Spire.Doc’s Document class handles HTML loading and RTF saving. Below are two common scenarios:
Scenario 1: Convert HTML String to RTF in C#
Use this when HTML content is dynamic (e.g., from user input, APIs, or databases).
using Spire.Doc;
using Spire.Doc.Documents;
namespace HtmlToRtfConverter
{
class Program
{
static void Main(string[] args)
{
// Create a Document object
Document doc = new Document();
// Define your HTML content
string htmlString = @"
<html>
<body>
<h1 style='color: #00BFFF; font-family: Arial'>HTML to RTF Conversion</h1>
<p>This is a <b>bold paragraph</b> with a <a href='https://www.e-iceblue.com'>link</a>.</p>
<ul>
<li>Item 1 </li>
<li>Item 2</li>
</ul>
<table border='1' cellpadding='5'>
<tr><td>Name</td><td>Gender</td><td>Age</td></tr>
<tr><td>John</td><td>Male</td><td>30</td></tr>
<tr><td>Kate</td><td>Female</td><td>26</td></tr>
</table>
</body>
</html>";
// Add a paragraph in Word
Paragraph para = doc.AddSection().AddParagraph();
// Append the HTML string to the paragraph
para.AppendHTML(htmlString);
// Save the document as RTF
doc.SaveToFile("HtmlStringToRtf.rtf", FileFormat.Rtf);
doc.Dispose();
}
}
}
In this code:
- Document Object: Represents an empty document.
- HTML String: You can customize this to include any valid HTML (styles, media, or dynamic content from databases/APIs).
- AppendHTML(): Parses HTML tags (e.g.,
<h1>,<table>,<a>) and inserts them into a paragraph. - SaveToFile(): Writes the converted content to an RTF file.
Output:

The SaveToFile method accepts different FileFormat parameters. You can change it to implement HTML to Word conversion in C#.
Scenario 2: Convert HTML File to RTF File
For static HTML files (e.g., templates or saved web pages), use LoadFromFile with parameter FileFormat.Html:
using Spire.Doc;
namespace ConvertHtmlToRTF
{
class Program
{
static void Main()
{
// Create a Document object
Document doc = new Document();
// Load an HTML file
doc.LoadFromFile("Test.html", FileFormat.Html);
// Save the HTML file as rtf format
doc.SaveToFile("HTMLtoRTF.rtf", FileFormat.Rtf);
doc.Dispose();
}
}
}
This code simplifies HTML-to-RTF conversion into three core steps:
- Creates a Document object.
- Loads an existing HTML file using LoadFromFile() with the FileFormat.Html parameter.
- Saves the loaded HTML as an RTF format using SaveToFile() with the FileFormat.Rtf parameter.
Output:

Spire.Doc supports bidirectional conversion, so you can convert the RTF file back to HTML in C# when needed.
Advanced Conversion Scenarios
1. Handling Images in HTML
Spire.Doc preserves images embedded in HTML (via <img> tags). For local images, ensure the src path is correct. For remote images (URLs), Spire.Doc automatically downloads and embeds them.
// HTML with local and remote images
string htmlWithImages = @"<html>
<body>
<h3>HTML with Images</h3>
<p>Local image: <img src='https://cdn.e-iceblue.com/C:\Users\Administrator\Desktop\HelloWorld.png' alt='Sample Image' width='200'></p>
<p>Remote image: <img src='https://cdn.e-iceblue.com/images/art_images/csharp-html-to-rtf.png' alt='Online Image'></p>
</body>
</html>";
// Append the HTML string to a paragraph
Paragraph para = doc.AddSection().AddParagraph();
para.AppendHTML(htmlWithImages);
// Save the document as RTF
doc.SaveToFile("HtmlWithImage.rtf", FileFormat.Rtf);
2. Batch Conversion of Multiple HTML Files
Process an entire directory of HTML files with a loop:
string inputDir = @"C:\Input\HtmlFiles";
string outputDir = @"C:\Output\RtfFiles";
// Create output directory if it doesn't exist
Directory.CreateDirectory(outputDir);
// Get all .html files in input directory
foreach (string htmlFile in Directory.EnumerateFiles(inputDir, "*.html"))
{
using (Document doc = new Document())
{
doc.LoadFromFile(htmlFile, FileFormat.Html, XHTMLValidationType.None);
// Use the same filename but with .rtf extension
string fileName = Path.GetFileNameWithoutExtension(htmlFile) + ".rtf";
string outputPath = Path.Combine(outputDir, fileName);
doc.SaveToFile(outputPath, FileFormat.Rtf);
Final Thoughts
Converting HTML to RTF in C# is straightforward with Spire.Doc for .NET. This library eliminates the need for manual parsing and ensures consistent formatting across outputs. Whether you’re working with HTML strings or files, this article provides practical code examples to handle both scenarios.
For further exploration, refer to the Spire.Doc documentation.
Common Questions
Q1: Is Spire.Doc free to use?
A: For large-scale projects, you can request a free 30-day trial license to fully evaluate it. Alternatively, Spire.Doc offers a free community edition without any watermarks (but with certain page/functionality limits).
Q2: Does Spire.Doc preserve HTML hyperlinks, images, and tables in the RTF output?
A: Yes. Spire.Doc retains most HTML elements:
- Hyperlinks:
<a>tags are converted to clickable links in RTF. - Images: Local (
<img src="/path">) and remote (<img src="/URL">) images are embedded in the RTF. - Tables: HTML tables (with border, cellpadding, etc.) are converted to RTF tables with preserved structure.
Q3: Can I style the RTF output further after loading the HTML?
A: Absolutely. After loading the HTML content into the Document object, you can use the full Spire.Doc API to programmatically modify the document before saving it as RTF.
Q4: Can I convert HTML to other formats with Spire.Doc?
A: Yes. Apart from converting to RTF, the library also supports converting HTML to Word, HTML to XML, and HTML to images, etc.
Working with Data in C#: Exporting DataSet to Excel Made Easy
2025-09-05 09:30:38 Written by zaki zaki
In C# development, DataSet is widely used to manage in-memory data, often as a result of database queries or integration processes. There are many scenarios where you may need to create Excel files from DataSet in C# — for example, generating reports, sharing structured data with non-developers, or archiving records for future reference.
In this guide, we’ll walk through different approaches to export DataSet to Excel in C# using Spire.XLS for .NET, including creating an Excel file, writing multiple DataTables into separate sheets, applying formatting, and handling large data volumes.
Here's what's covered in this guide:
- DataSet Basics and Environment Setup
- Creating an Excel File from DataSet in C#
- Adding Formatting to Excel Sheets Using C#
- Handling Large DataSet Exports
- Read Excel into DataSet in C#
- Conclusion
- FAQ
1. DataSet Basics and Environment Setup for Excel Export
What is a DataSet?
A DataSet in C# is an in-memory representation of structured data. It can hold multiple DataTables, including their rows, columns, and relationships, making it useful for working with relational-style data without direct database connections.
Why Export DataSet to Excel?
- Data exchange – Excel is widely supported and easy to share across teams.
- Data analysis – Analysts can manipulate Excel data directly using formulas, pivot tables, and charts.
- Archiving – Storing query results or processed data in a readable, portable format.
Compared to raw text or CSV, Excel supports rich formatting, multiple sheets, and better readability.
Environment Setup
To export a DataSet to an Excel file in C#, we will use Spire.XLS for .NET, which provides APIs for handling Excel files. Install Spire.XLS via NuGet:
Install-Package Spire.XLS
Add the required namespaces:
using Spire.Xls;
using System.Data;
using System.Drawing; // for Color
2. Creating an Excel File from DataSet in C#
Exporting a DataSet to Excel involves two key steps: preparing the data and writing it into a workbook. In practice, the DataSet may come from queries or APIs, but for clarity, we’ll demonstrate with a simple example. First, we’ll build a DataSet in memory, then show how to export it into an Excel file where each DataTable becomes its own worksheet.
2.1 Initialize a DataSet with Sample Data
First, we’ll build a DataSet using C#. The following sample DataSet contains multiple business-style tables and a variety of column types (int, string, DateTime, decimal).
using System;
using System.Data;
class Program
{
static DataSet CreateSampleDataSet()
{
DataSet ds = new DataSet("CompanyData");
// Employees
DataTable employees = new DataTable("Employees");
employees.Columns.Add("ID", typeof(int));
employees.Columns.Add("Name", typeof(string));
employees.Columns.Add("DepartmentID", typeof(int));
employees.Columns.Add("HireDate", typeof(DateTime));
employees.Columns.Add("Salary", typeof(decimal));
employees.Rows.Add(1, "Alice", 101, new DateTime(2020, 5, 12), 5500.00m);
employees.Rows.Add(2, "Bob", 102, new DateTime(2019, 3, 8), 7200.50m);
employees.Rows.Add(3, "Charlie", 103, new DateTime(2021, 11, 20), 4800.75m);
// Departments
DataTable departments = new DataTable("Departments");
departments.Columns.Add("DepartmentID", typeof(int));
departments.Columns.Add("DepartmentName", typeof(string));
departments.Rows.Add(101, "HR");
departments.Rows.Add(102, "IT");
departments.Rows.Add(103, "Finance");
// Projects
DataTable projects = new DataTable("Projects");
projects.Columns.Add("ProjectID", typeof(int));
projects.Columns.Add("ProjectName", typeof(string));
projects.Columns.Add("OwnerID", typeof(int));
projects.Columns.Add("StartDate", typeof(DateTime));
projects.Rows.Add(1001, "Recruitment System", 1, new DateTime(2023, 1, 15));
projects.Rows.Add(1002, "ERP Upgrade", 2, new DateTime(2023, 4, 10));
projects.Rows.Add(1003, "Budget Planning", 3, new DateTime(2023, 7, 5));
ds.Tables.Add(employees);
ds.Tables.Add(departments);
ds.Tables.Add(projects);
return ds;
}
}
2.2 Export DataSet to Excel File
With the DataSet prepared, the next step is generating the Excel file. This involves creating a Workbook, iterating through the DataTables, inserting them into worksheets, and saving the workbook to an Excel file.
using Spire.Xls;
using System.Data;
class Program
{
static void Main()
{
DataSet ds = CreateSampleDataSet();
Workbook workbook = new Workbook();
// Export each DataTable as a separate worksheet
for (int i = 0; i < ds.Tables.Count; i++)
{
Worksheet sheet = (i == 0)
? workbook.Worksheets[0]
: workbook.Worksheets.Add(ds.Tables[i].TableName);
sheet.InsertDataTable(ds.Tables[i], true, 1, 1);
sheet.Name = ds.Tables[i].TableName; // ensure sheet is named after the table
}
workbook.SaveToFile("DatasetToExcel.xlsx", ExcelVersion.Version2016);
}
}
About the Exporting Process
- Each DataTable is written into a separate worksheet.
- InsertDataTable(DataTable table, bool columnHeaders, int row, int column) inserts data starting from a specific cell.
- SaveToFile() writes the workbook to disk in the specified format.
In addition to creating separate worksheets for each DataTable, you can also insert multiple DataTables into the same worksheet by adjusting the starting row and column parameters of the InsertDataTable method.
Result preview
Below is a quick preview of the output workbook showing three sheets populated from the DataSet.

For a practical example of exporting data directly from a database to Excel, see our guide on Export Database to Excel in C#.
3. Adding Formatting to Excel Sheets Using C#
Raw data often isn’t enough for reporting. Formatting improves readability and makes the Excel file more professional. With Spire.XLS, you can style fonts, apply background colors, add borders, and format numbers and dates.
using System.Drawing;
using Spire.Xls;
// Get the first sheet
Worksheet sheet1 = workbook.Worksheets["Employees"];
// 1) Header styling (A1:E1)
CellRange header = sheet1.AllocatedRange.Rows[0];
header.Style.Font.IsBold = true;
header.Style.Font.Size = 12;
header.Style.Font.Color = Color.White;
header.Style.Color = Color.SteelBlue;
// Borders around the header row
header.BorderAround(LineStyleType.Thin);
// 2) Number formats for entire columns (D: HireDate, E: Salary)
sheet1.AllocatedRange.Columns[3].Style.NumberFormat = "yyyy-mm-dd";
sheet1.AllocatedRange.Columns[4].Style.NumberFormat = "$#,##0.00";
// 3) Optional: zebra stripes for data area (A2:E4 here as example)
CellRange data = sheet1.Range["A2:E4"];
// CellRange data = sheet1.Range[2, 1, 4, 5];
data.Style.Color = Color.FromArgb(245, 247, 250);
data.BorderAround(LineStyleType.Thin);
// Auto-fit after formatting
sheet1.AllocatedRange.AutoFitColumns();
sheet1.AllocatedRange.AutoFitRows();
How Formatting Works
- Style.Font — font properties such as IsBold, Size, Color.
- Style.Color — background fill color for the selected range.
- Borders / BorderAround — draw borders on edges/around ranges with LineStyleType.
- NumberFormat — Excel-native formats (e.g., dates, currency, percentages).
- AutoFitColumns() / AutoFitRows() — adjust column widths / row heights to fit content.
For more formatting options, refer to the API reference for CellRange and CellStyle.
Formatting preview
The following image shows styled headers, borders, and proper date/currency formats applied.

4. Handling Large DataSet Exports
When exporting large datasets, performance and memory become critical. Consider:
- Split across sheets — When rows approach Excel/version limits or for logical separation.
- Batch writing — Insert data in segments (e.g., table-by-table or range-by-range).
- Lightweight formatting — Minimize heavy styling to reduce file size and processing time.
- Streaming (where applicable) — Prefer APIs that avoid loading everything into memory at once.
5. Bonus: Read Excel into DataSet in C#
In addition to exporting, the reverse workflow is equally important: reading Excel data back into a DataSet for processing or migration. This is useful when importing data from external reports, integrating spreadsheets with applications, or performing preprocessing before database insertion.
using System.Data;
using Spire.Xls;
class Program
{
static DataSet ReadExcelIntoDataSet(string filePath)
{
DataSet ds = new DataSet();
Workbook workbook = new Workbook();
workbook.LoadFromFile(filePath);
foreach (Worksheet sheet in workbook.Worksheets)
{
DataTable dt = sheet.ExportDataTable();
dt.TableName = sheet.Name;
ds.Tables.Add(dt);
}
return ds;
}
}
The ExportDataTable method allows each worksheet to be converted into a DataTable object, preserving both the structure and the cell values. By assigning the sheet name to TableName and adding it into a DataSet, you can combine multiple sheets into a single in-memory data container that is ready for further processing.
For a complete workflow on persisting Excel data into a database, see our guide on Import Excel into Database in C#.
Conclusion
Exporting a DataSet to Excel in C# allows you to generate reports, share data, and make information easier to analyze or present. With Spire.XLS for .NET, you can create Excel files directly from DataSet objects, apply formatting, manage multiple sheets, and handle large datasets efficiently. You can also import Excel data back into a DataSet for integration with applications or databases.
To explore more advanced features, you may request a free temporary license or use Free Spire.XLS for .NET for smaller projects.
FAQ: C# DataSet and Excel Integration
Q1: How can I export multiple DataTables from a DataSet into different Excel sheets?
Loop through ds.Tables and call InsertDataTable for each one, creating a new worksheet per DataTable.
Q2: Can I export a DataSet to a specific worksheet in an existing Excel file?
Yes. Load the file using Workbook.LoadFromFile(), then choose the worksheet and use InsertDataTable.
Q3: Does exporting DataSet to Excel preserve column formatting and data types?
Values are exported with the same data types as in the DataSet. You can also apply formatting (date, currency, alignment, etc.) after inserting.
Q4: How do I handle very large DataSet exports (over 100,000 rows)?
Split into multiple sheets, use batch inserts, and reduce complex formatting to improve performance.

CSV (Comma-Separated Values) files remain one of the most widely used formats for data exchange between applications. Whether you’re processing financial data, user records, or analytics reports, efficiently reading CSV files in C# is a common task in .NET development.
In this comprehensive guide, we'll explore how to parse CSV files in C# using Spire.XLS for .NET, covering both direct reading and converting CSV to DataTable.
- Install the C# CSV File Reader Library
- Read a CSV File in C#
- Read CSV into a DataTable in C#
- When to Use Each Method
- Conclusion
- FAQs
Install the C# CSV File Reader Library
While primarily designed for Excel files, Spire.XLS can also be used as a .NET CSV reader. It provides excellent support for CSV files, offering a range of features that make CSV processing efficient and straightforward.
The first step is to install the Spire.XLS package in your project. Here's how:
- Open your project in Visual Studio
- Right-click on your project in the Solution Explorer
- Select "Manage NuGet Packages"
- In the NuGet Package Manager, search for "Spire.XLS"
- Click "Install" to add the package to your project
Alternatively, you can install it using the Package Manager Console:
PM> Install-Package Spire.XLS
This will add the necessary dependencies to your project, allowing you to use Spire.XLS classes.
Read a CSV File in C#
Let's start with the fundamentals: reading a simple CSV file and extracting its data. The C# code example below loads a CSV file, accesses its data, and prints the contents to the console in a tabular format.
using Spire.Xls;
namespace ReadCSV
{
class Program
{
static void Main(string[] args)
{
// Create a workbook instance
Workbook workbook = new Workbook();
// Load the CSV file
workbook.LoadFromFile("sample.csv", ",");
// Get the first worksheet
Worksheet sheet = workbook.Worksheets[0];
// Get the used range
CellRange range = sheet.AllocatedRange;
// Iterate through rows and columns
for (int row = 1; row <= range.RowCount; row++)
{
for (int col = 1; col <= range.ColumnCount; col++)
{
// Get cell value
string cellValue = range[row, col].Value;
Console.Write(cellValue + "\t");
}
Console.WriteLine();
}
Console.ReadLine();
}
}
}
Explanation:
- Workbook class: Acts as a "container" for your CSV file in memory. Even though CSV isn’t a full Excel file, Spire.Xls treats it as a single-sheet workbook for consistency.
- Workbook.LoadFromFile(): Loads the CSV file. The parameters are:
- File path: "sample.csv".
- Delimiter: "," (comma, default for CSV).
- Worksheet.AllocatedRange: Retrieves only the cells that contain data.
- CellRange[row, col].Value: Retrieves the value of a specific cell.
Result: CSV data printed in a clean, tab-separated format.

If you need a demo for reading CSV files in VB.NET, convert the code directly using the C# to VB.NET converter.
Read CSV into a DataTable in C#
A DataTable is a versatile in-memory data structure in .NET that simplifies data manipulation (e.g., filtering, sorting, or binding to UI components). Here’s how to load CSV data into a DataTable using Spire.XLS:
using Spire.Xls;
using System.Data;
namespace ReadCSV
{
class Program
{
static void Main(string[] args)
{
// Create a workbook instance
Workbook workbook = new Workbook();
// Load the CSV file
workbook.LoadFromFile("sample.csv", ",");
// Get the first worksheet
Worksheet worksheet = workbook.Worksheets[0];
// Export data from the worksheet to a DataTable
DataTable dataTable = worksheet.ExportDataTable();
// Get row and column count
Console.WriteLine("\nConversion complete! DataTable information:");
Console.WriteLine($"Number of columns: {dataTable.Columns.Count}");
Console.WriteLine($"Number of rows: {dataTable.Rows.Count}");
Console.WriteLine();
// Print column names
for (int i = 0; i < dataTable.Columns.Count; i++)
{
Console.Write(dataTable.Columns[i].ColumnName + " | ");
}
Console.WriteLine();
Console.WriteLine("----------------------------------------------------------");
// Print row data
for (int i = 0; i < dataTable.Rows.Count; i++)
{
for (int j = 0; j < dataTable.Columns.Count; j++)
{
string value = dataTable.Rows[i][j].ToString();
Console.Write(value + "\t");
}
Console.WriteLine();
}
}
}
}
Explanation:
- Worksheet.ExportDataTable(): Converts the entire CSV worksheet into a DataTable.
- Metadata Access: DataTable.Columns.Count and DataTable.Rows.Count shows the size of your dataset, helping you verify that the import was successful.
- Column Headers and Data Output: Iterates through to display column names and row data.
Result: Structured output with metadata, headers, and rows:

To analyze, calculate, or format the data, you can convert CSV to Excel in C#.
When to Use Each Method
Choose the right approach based on your goal:
| Method | Best For | Use Case Example |
|---|---|---|
| Direct CSV Reading | Quick data verification | Checking if a CSV is loaded correctly. |
| Convert to DataTable | Advanced data processing | Filtering rows, sorting, or saving to SQL Server. |
Conclusion
Reading CSV files in C# is streamlined with Spire.XLS for .NET, and converting CSV data to a DataTable adds flexibility for data manipulation. Whether you’re working with small datasets or large files, Spire.XLS offers flexible options to meet your requirements.
The code examples in this guide are ready to use - just copy, paste, and adjust for your CSV file path. For more advanced features, refer to Spire.XLS’s official documentation.
FAQs (Common Questions)
Q1: Why choose Spire.XLS for CSV reading?
A: While the .NET Framework offers built-in StreamReader for CSV handling, Spire.XLS provides several distinct advantages:
- No dependencies: Doesn't require Microsoft Excel or Office to be installed
- High performance: Optimized for handling large CSV files efficiently
- Flexibility: Multiple ways to read CSV data based on your needs
- Cross-platform: Works with .NET Framework, .NET Core, .NET Standard, and Mono
Q2: Can I use a different delimiter (e.g., semicolon or tab)?
A: Yes. Replace the second parameter of LoadFromFile() method with your delimiter:
// For tab-delimited files
workbook.LoadFromFile("data.txt", "\t");
// For semicolon-delimited files
workbook.LoadFromFile("data.csv", ";");
// For pipe-delimited files
workbook.LoadFromFile("data.csv", "|");
Q3: Can I read specified rows or columns from a CSV file?
A: Yes. You can target a precise subset of your data by defining exact row and column boundaries. This is useful for extracting specific information (e.g., skipping headers, focusing on relevant columns) without processing the entire file.
For example:
// Define the specific range
int startRow = 2; // Start from row 2 (skip header)
int endRow = 4; // End at row 4
int startCol = 2; // Start from column 2
int endCol = 6; // End at column 6
// Loop through rows and columns
for (int row = startRow; row <= endRow; row++)
{
for (int col = startCol; col <= endCol; col++)
{
// Get cell value
string cellValue = worksheet.Range[row, col].Value;
Console.Write(cellValue + "\t");
Note: Spire.Xls uses 1-based indexing (like Excel), so the first row/column is numbered 1 (not 0).
How to Integrate Spire.PDFViewer for MAUI in .NET Project
2025-09-05 02:36:38 Written by AdministratorSpire.PDFViewer for MAUI is a dedicated PDF viewing component tailored for .NET Multi-platform App UI (MAUI) frameworks. This guide will show you how to configure it in your .NET MAUI project, including environment setup, product installation, and core PDF viewing feature implementation.
1. Prerequisites & Environment Setup
Ensure your development environment meets the following requirements before you begin.
1.1 Required Software
- IDE: Visual Studio 2022 (version 17.8 or later) for Windows, or Visual Studio 2022 for Mac (version 17.6 or later).
- Target Frameworks:
- Android 5.0 (API 21) or higher
- Windows 11, or Windows 10 Version 1809 or higher
1.2 Install the .NET MAUI Workload
The .NET Multi-platform App UI development workload is mandatory for MAUI projects. Follow these steps to install it:
- Open Visual Studio Installer:
- Search for "Visual Studio Installer" in your Start Menu (usually under the "Visual Studio 2022" folder).
- Alternatively, open Visual Studio, go to “Tools > Get Tools and Features”.
- Modify Your Installation:
- Click "Modify" next to your Visual Studio 2022 edition.
- Navigate to the "Workloads" tab.
- Check the box for ".NET Multi-platform App UI development".
- Ensure the optional components you need are selected.
- Click "Modify" to start the installation

2. Create a New .NET MAUI Project
After installing MAUI, follow these steps to create a new .NET MAUI project:
2.1 Select the Project Template
- Open Visual Studio and click “Create a new project”.
- Search for "MAUI" and select the .NET MAUI App template (C#).
- Click “Next” to proceed.

2.2 Configure Project Details
- Enter a project name (e.g., "PdfViewerMauiApp") and choose a Save location.
- Next, select .NET 7.0 or later (e.g., .NET 8.0) as the target framework.
- Click “Create” to generate the project.

3. Install Spire.PDFViewer and Dependencies
To implement the PDF viewer in .NET MAUI, you need to install the dependent NuGet packages and add Spire.PDFViewer DLLs.
3.1 Install Dependent NuGet Packages
- Go to “Tools > NuGet Package Manager > Package Manager Console”.
- Run the following command to install all required packages at once:
Install-Package Microsoft.Win32.Registry -Version 5.0.0
Install-Package System.Security.Permissions -Version 4.7.0
Install-Package System.Text.Encoding.CodePages -Version 4.7.0
Install-Package System.Security.Cryptography.Pkcs -Version 4.7.0
Install-Package System.Security.Cryptography.Xml -Version 4.7.1
Install-Package HarfBuzzSharp -Version 8.3.0.1
Install-Package SkiaSharp -Version 3.116.1
Install-Package SkiaSharp.Views.Maui.Controls -Version 2.88.5
Install-Package System.Buffers -Version 4.5.1
Install-Package System.Memory -Version 4.5.5
3.2 Add Spire.PDFViewer DLLs
- Download the Spire.PdfViewer package from the official website.
- Unzip the downloaded file to a specified file path.
- In Visual Studio’s Solution Explorer, right-click the project > Add > Project Reference.
- Click “Browse”, navigate to the unzipped folder (BIN\NET7.0\windows10.0.19041.0), and add both:
- Spire.PdfViewer.Maui.dll
- Spire.Pdf.dll

3.3 Restrict Target Platform to Windows
Currently, the Spire.PDFViewer for MAUI only supports the Windows platform. Therefore, it’s necessary to modify the project file (.csproj) to remove non-Windows target frameworks:
- In Solution Explorer, right-click the project and select “Edit Project File”.
- Locate the
<TargetFrameworks>element and delete or comment out this line. - Save the file (Ctrl+S) and reload the project when prompted by Visual Studio.

4. Add PDF Viewer to the Project
4.1 Initialize Spire.PDFViewer
In “MauiProgram.cs”, add the .UseSpirePdfViewer() method in the MauiAppBuilder chain:

4.2 Option 1: Use the Default PDF Viewer UI
For a quick setup with a pre-built toolbar (supports loading, zooming, and searching), use the minimal XAML configuration:
- Replace the default XAML content of “MainPage.xaml” with the following:
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:spire="clr-namespace:Spire.PdfViewer.Maui;assembly=Spire.PdfViewer.Maui"
x:Class="PdfViewerMauiApp.MainPage"> <!-- Modify “PdfViewerMauiApp” to match your project name -->
<Grid ColumnDefinitions="Auto, *" ColumnSpacing="0">
<!-- Default PDF Viewer with built-in toolbar -->
<spire:PdfViewer x:Name="PdfDocumentViewer1" Grid.Column="1" />
</Grid>
</ContentPage>
- Open “MainPage.xaml.cs” and ensure the namespace matches your project name:
namespace PdfViewerMauiApp; // Match the project name in the x:Class value
public partial class MainPage : ContentPage
{
public MainPage()
{
InitializeComponent();
}
}

When you run the project, a PDF viewer with a built-in toolbar (Home, Zoom, Find) will appear. You can load PDFs directly via the toolbar and use its default features.

4.3 Option 2: Customize the UI Layout & Functionality
For a tailored experience (e.g., a dedicated "Load PDF" button or page navigation), design a custom layout and implement core logic.
Step 1: Design the Custom UI (MainPage.xaml)
Replace the default XAML content of “MainPage.xaml” with a two-column grid (left: control panel; right: PDF viewer):
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:spire="clr-namespace:Spire.PdfViewer.Maui;assembly=Spire.PdfViewer.Maui"
x:Class="PdfViewerMauiApp.MainPage"> <!-- Modify “PdfViewerMauiApp” to match your project name -->
<Grid ColumnDefinitions="Auto, *" ColumnSpacing="0">
<!-- Left Control Panel -->
<VerticalStackLayout Grid.Column="0" WidthRequest="220"
Padding="10" Spacing="10">
<!-- Button to load PDF files -->
<Button Text="Load PDF File"
Clicked="LoadFromFile_Clicked"
HeightRequest="40"/>
<!-- Page Navigation: Entry + Button -->
<HorizontalStackLayout Spacing="10">
<Entry x:Name="pageEntry"
WidthRequest="100"
HeightRequest="40"
Keyboard="Numeric"
Placeholder="Page Number"/>
<Button Text="Go To"
Clicked="GoPages_Clicked"
WidthRequest="80"
HeightRequest="40"/>
</HorizontalStackLayout>
<Label x:Name="lbl1" HeightRequest="30"/>
</VerticalStackLayout>
<!-- Right PDF Viewing Area -->
<spire:PdfDocumentViewer x:Name="PdfDocumentViewer1" Grid.Column="1" />
</Grid>
</ContentPage>
Step 2: Add Functionality (MainPage.xaml.cs)
Add event handlers in “MainPage.xaml.cs” to enable PDF loading and page navigation:
namespace PdfViewerMauiApp; // Match your project name
public partial class MainPage : ContentPage
{
public MainPage()
{
InitializeComponent();
}
// Click event for the Load PDF File button
private async void LoadFromFile_Clicked(object sender, EventArgs e)
{
try
{
// Restrict file picker to PDF files only
var result = await FilePicker.PickAsync(new PickOptions
{
FileTypes = FilePickerFileType.Pdf,
PickerTitle = "Choose a PDF file"
});
if (result != null)
{
// Load the PDF file from the selected path
PdfDocumentViewer1.LoadFromFile(result.FullPath);
}
}
catch (Exception ex)
{
// Display error message
lbl1.Text = $"Loading failed: {ex.Message}";
}
}
// Click event for page navigation button
private void GoPages_Clicked(object sender, EventArgs e)
{
if (int.TryParse(pageEntry.Text, out int pageNumber) && pageNumber > 0)
{
// Verify that the page number is within the valid range.
if (pageNumber <= PdfDocumentViewer1.PageCount)
{
// Jump to a specific page number
PdfDocumentViewer1.GotoPage(pageNumber, true);
lbl1.Text = $"Navigated to Page: {pageNumber}/{PdfDocumentViewer1.PageCount}";
}
else
{
lbl1.Text = $"Out of Range (Max Page: {PdfDocumentViewer1.PageCount})";
}
}
else
{
lbl1.Text = "Please enter a valid page number.";
}
}
}
Step 3: Run the Project
Run the application, and test the PDF viewer functionality:
-
Click “Load PDF File” to select and open a PDF.
-
Enter a page number and click “Go To” to navigate to that page.

Integrating Spire.PDFViewer into a .NET MAUI project enables developers to quickly add robust, user-friendly PDF viewing capabilities, including document loading, page navigation, and built-in/ custom UI controls. By following the steps outlined here, developers can avoid common pitfalls (e.g., version mismatches, missing dependencies) and deploy a functional PDF viewer in minimal time.
C# Write to Excel Guide: Insert Data into Worksheets Easily
2025-09-04 09:05:06 Written by Administrator
Excel remains one of the most widely used tools for managing and analyzing data due to its powerful features and user-friendly interface. In C# applications, developers often need to generate reports, export database results, or automate tasks by writing directly to Excel files.
To achieve this efficiently, developers often turn to third-party libraries. Spire.XLS for .NET makes it simple to write to Excel programmatically without relying on Microsoft Excel. With Spire.XLS, you can insert text, numbers, dates, formulas, or even bulk datasets such as arrays, DataTables, and lists into Excel worksheets. This provides a fast, flexible, and reliable way to automate Excel writing in C# applications.
On this page:
- Getting Started with Spire.XLS for .NET
- How to Create a New Excel File in C#
- Write Different Data Types to Excel Cells
- Write Bulk Data to Excel Sheets
- Save and Export Excel Files
- Common Issues and Solutions
- Conclusion
- FAQs
Getting Started with Spire.XLS for .NET
What’s Spire.XLS for .NET
Spire.XLS for .NET is a professional .NET Excel library developed by E-iceblue. It allows developers to write to Excel files in C# and perform a wide range of operations including creating, editing, reading, and exporting Excel documents—without requiring Microsoft Excel to be installed.
Key features include:
- Write and update Excel files programmatically.
- Support for Excel formats (XLS, XLSX, CSV, ODS).
- Advanced features such as formulas, charts, pivot tables, and data validation.
- Export Excel to PDF, HTML, and image formats.
- High performance with large datasets, suitable for desktop, server, and web applications.
How to Install Spire.XLS for .NET
Option 1: Install via NuGet (recommended)
- Open Visual Studio.
- Navigate to Tools > NuGet Package Manager > Manage NuGet Packages for Solution.
- Search for Spire.XLS and install it.
Or, install it directly using the Package Manager Console :
PM> Install-Package Spire.XLS
Option 2: Manual installation
- Download the Spire.XLS package from our official website
- Add a reference to Spire.Xls.dll in your project.
Once installed, you’re ready to start writing to Excel in C#.
How to Create a New Excel File in C#
The first step is to create a new workbook and add a worksheet. Here’s how:
using Spire.Xls;
namespace CreateNewExcel
{
class Program
{
static void Main(string[] args)
{
// Create a new workbook
Workbook workbook = new Workbook();
// Remove default worksheets
workbook.Worksheets.Clear();
// Add a worksheet
Worksheet sheet = workbook.Worksheets.Add("Report");
// Save the empty Excel file
workbook.SaveToFile("NewExcelFile.xlsx", ExcelVersion.Version2016);
workbook.Dispose();
}
}
}
At this point, you have created an empty Excel file with a worksheet named “Report”. Next, let’s write data into it.
Write Different Data Types to Excel Cells in C#
Spire.XLS allows you to write various data types directly to Excel cells. Below are common examples:
Write Text Values
sheet.Range["A1"].Text = "Hello Excel!";
Write Numeric Values
sheet.Range["A2"].NumberValue = 123.45;
Write Date and Time
sheet.Range["A3"].DateTimeValue = DateTime.Now;
sheet.Range["A3"].NumberFormat = "yyyy-mm-dd hh:mm";
Write Boolean Values
sheet.Range["A4"].BooleanValue = true;
Write TimeSpan Values
sheet.Range["A5"].TimeSpanValue = new TimeSpan(2, 30, 0); // 2 hours 30 minutes;
sheet.Range["A5"].NumberFormat = "[h]:mm:ss";
Insert Formulas
sheet.Range["A6"].Formula = "=SUM(A2,100)";
Insert HTML Formatted Strings
string htmlText = "<span style=\"font-family: Times New Roman; color: blue; font-size: 15pt;\">Hello
<strong>Spire.XLS</strong></span>";
sheet.Range["A7"].HtmlString = htmlText;
Write General Values Without Specific Type
sheet.Range["A8"].Value = "General Value";
Output:

You might also be interested in: How to Read Excel Files in C#
Write Bulk Data to Excel Sheets in C#
When dealing with larger datasets, writing values cell by cell isn’t efficient. Spire.XLS provides methods to insert arrays , and DataTables directly. Other data structures can be converted to arrays or DataTables before being written to the Excel sheet.
Write Arrays to Excel
Spire.XLS provides the Worksheet.InsertArray(string[] stringArray, int firstRow, int firstColumn, bool isVertical) method, allowing developers to insert one-dimensional or two-dimensional arrays into a specified range of cells in a worksheet.
string[,] data = {
{ "Name", "Age", "Country" },
{ "Alice", "30", "USA" },
{ "Bob", "28", "UK" },
{ "Charlie", "35", "Canada" }
};
sheet.InsertArray(data, 1, 1);
Output:

Write DataTables to Excel
To import data from a DataTable to a worksheet, use the Worksheet.InsertDataTable(DataTable dataTable, bool columnHeaders, int firstRow, int firstColumn, bool transTypes) method.
using System.Data;
DataTable dt = new DataTable();
dt.Columns.Add("ID", typeof(int));
dt.Columns.Add("Product", typeof(string));
dt.Columns.Add("Price", typeof(double));
// Add rows
dt.Rows.Add(1, "Laptop", 1200.5);
dt.Rows.Add(2, "Tablet", 450.99);
dt.Rows.Add(3, "Phone", 799.0);
// Insert DataTable starting at cell A1
sheet.InsertDataTable(dt, true, 1, 1, true);
Output:

On the contrary, you can export data from Excel to DataTable by using the ExportDataTable method of the Worksheet class.
Write Lists to Excel
While Spire.XLS does not provide a direct method for writing lists to Excel, you can convert lists to a DataTable and then use the InsertDataTable method to write the DataTable to Excel.
using Spire.Xls;
using System.Data;
namespace WriteListToExcel
{
class Program
{
static void Main(string[] args)
{
// Create a Workbook instance
Workbook workbook = new Workbook();
// Remove default worksheets
workbook.Worksheets.Clear();
// Add a worksheet and name it
Worksheet worksheet = workbook.Worksheets.Add("Students");
// Create a list with student data
List<Student> students = new List<Student>
{
new Student("Michael", "Johnson", 20, "Computer Science", 3.8),
new Student("Sarah", "Williams", 22, "Mathematics", 3.6),
new Student("Jessica", "Brown", 19, "Physics", 3.9),
new Student("David", "Smith", 21, "Chemistry", 3.7),
new Student("Emily", "Davis", 23, "Biology", 3.5)
};
// Convert the list to DataTable
DataTable dataTable = ConvertListToDataTable(students);
// Write DataTable to the worksheet
worksheet.InsertDataTable(dataTable, true, 1, 1, true);
// Set column width
worksheet.AllocatedRange.ColumnWidth = 12;
// Align content to left
worksheet.AllocatedRange.HorizontalAlignment = HorizontalAlignType.Left;
// Save to an Excel file
workbook.SaveToFile("InsertStudents.xlsx", ExcelVersion.Version2016);
// Dispose resources
workbook.Dispose();
}
static DataTable ConvertListToDataTable(List<Student> students)
{
DataTable dataTable = new DataTable();
// Add columns
dataTable.Columns.Add("FirstName", typeof(string));
dataTable.Columns.Add("LastName", typeof(string));
dataTable.Columns.Add("Age", typeof(int));
dataTable.Columns.Add("Major", typeof(string));
dataTable.Columns.Add("GPA", typeof(double));
// Add rows
foreach (var student in students)
{
DataRow row = dataTable.NewRow();
row["FirstName"] = student.FirstName;
row["LastName"] = student.LastName;
row["Age"] = student.Age;
row["Major"] = student.Major;
row["GPA"] = student.GPA;
dataTable.Rows.Add(row);
}
return dataTable;
}
}
class Student
{
public string FirstName { get; set; }
public string LastName { get; set; }
public int Age { get; set; }
public string Major { get; set; }
public double GPA { get; set; }
public Student(string firstName, string lastName, int age, string major, double gpa)
{
FirstName = firstName;
LastName = lastName;
Age = age;
Major = major;
GPA = gpa;
}
}
}
Output:

Save and Export Excel Files
After writing data, you’ll want to save or export the Excel file. Spire.XLS supports multiple formats including XLSX, CSV, and PDF .
// Save as XLSX
workbook.SaveToFile("Output.xlsx", ExcelVersion.Version2016);
// Save as CSV
workbook.SaveToFile("Output.csv", ",", Encoding.UTF8);
// Export as PDF
workbook.SaveToFile("Output.pdf", FileFormat.PDF);
For web applications, you can also save to a MemoryStream :
using (MemoryStream ms = new MemoryStream())
{
workbook.SaveToStream(ms, FileFormat.Version2016);
// Write to Response in ASP.NET if needed
}
Common Issues and Solutions
1. Incorrect Date or Time Format
Issue: Dates/times appear as serial numbers.
Solution :
- Apply a proper number format to the cell:
sheet.Range["A1"].DateTimeValue = DateTime.Now;
sheet.Range["A1"].NumberFormat = "yyyy-mm-dd hh:mm";
2. Data Overwriting or Misaligned
Issue : Writing arrays or DataTables overwrites existing data unintentionally.
Solution :
- Check firstRow and firstColumn parameters in InsertArray() or InsertDataTable().
- Use separate worksheets or offset ranges if necessary.
3. Large Dataset Performance Issues
Issue : Writing thousands of rows is slow.
Solution :
- Use bulk writing methods instead of looping cell by cell.
- Apply styles after inserting data to avoid repeated formatting overhead.
4. Formula Not Calculating Correctly
Issue : Excel formulas inserted via sheet.Range["A1"].Formula do not return expected results.
Solution :
- Ensure the formula syntax is correct for Excel (e.g., =SUM(A2:A10)).
- Call workbook.CalculateAllValue() to update all formulas before saving if needed.
Conclusion
Writing to Excel in C# doesn’t have to be complex. With Spire.XLS for .NET , you can seamlessly write different data types—whether individual values or large datasets—into Excel worksheets. The library also provides support for styling, formulas, and advanced formatting, ensuring your Excel files are not only accurate but also presentation-ready.
By using efficient bulk-writing techniques like arrays and DataTables, you can handle both small and large data operations with ease. If your goal is to write to Excel files quickly and reliably , Spire.XLS gives you the tools you need—without the overhead of Microsoft Excel.
FAQs
Q1. Can I write to an existing Excel file with Spire.XLS?
Yes. Use workbook.LoadFromFile("file.xlsx") to open an existing file, then modify and save it.
Q2. Does Spire.XLS require Microsoft Excel to be installed?
No. It’s a standalone library that works without Excel.
Q3. Can Spire.XLS handle large Excel files with thousands of rows?
Yes. It’s optimized for high performance with large datasets.
Q4. How do I format cells while writing data?
You can style cells using properties like font, color, borders, and alignment:
sheet.Range["A1"].Style.Font.IsBold = true;
sheet.Range["A1"].Style.Color = Color.Yellow;
sheet.Range["A1"].Style.HorizontalAlignment = HorizontalAlignType.Left;
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.

Creating PDFs in ASP.NET applications is a common requirement, whether you're generating invoices, reports, forms, or exporting dynamic content. To streamline this process, you can utilize Spire.PDF for .NET, a professional and lightweight library that enables developers to easily create and manipulate PDF documents programmatically, without the need for complex APIs or third-party printer drivers.
In this tutorial, we’ll show you how to create PDF documents in an ASP.NET Core Web application using Spire.PDF for .NET, with examples of creating a PDF from scratch and converting HTML to PDF.
On this page:
- Why Use Spire.PDF for .NET?
- Step-by-Step: Generate PDF in ASP.NET Core Web App
- Create PDF from HTML in ASP.NET Core
- Best Practices for ASP.NET PDF Generation
- Conclusion
- FAQs
Why Use Spire.PDF for .NET?
There are many ways to create PDF in ASP.NET, but most involve trade-offs: some depend on printer drivers, others have limited layout control, and many require heavy third-party frameworks. Spire.PDF for .NET offers a more streamlined approach. It’s a dedicated .NET library that handles the majority of PDF creation and manipulation tasks on its own, without external tools.
Key advantages include:
- No Adobe dependency – Generate and manage PDFs without Acrobat installed.
- Full-featured PDF toolkit – Beyond creation, you can edit, merge, split, protect, or annotate PDFs.
- High-fidelity rendering – Preserve fonts, CSS, images, and layouts when exporting content.
- ASP.NET ready – Compatible with both ASP.NET Web Forms/MVC and ASP.NET Core projects.
- Flexible generation options – Create PDFs from scratch, images, or streams.
(Note: HTML-to-PDF conversion requires a lightweight external plugin such as Qt WebEngine.)
Step-by-Step: Generate PDF in ASP.NET Core Web App
Step 1. Create a New ASP.NET Core Web App
- Open Visual Studio .
- Select Create a new project .
- Choose ASP.NET Core Web App (Model-View-Controller) → Click Next .
- Enter a project name, e.g., PdfDemoApp.
- Select your target framework (e.g., . NET 6 , 7 , or 8 ).
- Click Create .
Step 2. Install Spire.PDF via NuGet
- Right-click on your project → Manage NuGet Packages .
- Search for Spire.PDF .
- Install the package Spire.PDF (latest stable version).
Or install using the Package Manager Console :
Install-Package Spire.PDF
Step 3. Add a Controller for PDF Generation
- Right-click on the Controllers folder → Add → Controller → MVC Controller – Empty .
- Name it: PdfController.cs.
- Replace the default code with this:
using Microsoft.AspNetCore.Mvc;
using Spire.Pdf;
using Spire.Pdf.Graphics;
using System.Drawing;
namespace PdfDemoApp.Controllers
{
public class PdfController : Controller
{
public IActionResult CreatePdf()
{
// Create a new PDF document
PdfDocument doc = new PdfDocument();
PdfPageBase page = doc.Pages.Add(PdfPageSize.A4, new PdfMargins(40));
// Draw text on the page
PdfFont font = new PdfFont(PdfFontFamily.Helvetica, 25f);
PdfSolidBrush brush = new PdfSolidBrush(Color.Black);
page.Canvas.DrawString("Hello from ASP.NET Core!", font, brush, 10, 50);
// Save to memory stream
using (MemoryStream ms = new MemoryStream())
{
doc.SaveToStream(ms);
doc.Close();
ms.Position = 0;
// Return PDF file
return File(ms.ToArray(), "application/pdf", "Generated.pdf");
}
}
}
}
Step 4: (Optional) Add a Button or Link in Your View
Open Views/Home/Index.cshtml (or whichever view is your homepage).
Add a button or link like this:
<div>
<a asp-controller="Pdf" asp-action="CreatePdf" class="btn btn-primary">
Create PDF from Scratch
</a>
</div>
This uses ASP.NET Core tag helpers to generate the correct route (/Pdf/CreatePdf).
Step 5. Run and Test
- Press F5 to run your app.
- On the home page, click the "Create PDF from Scratch" button. This will call the CreatePdf method in PdfController and trigger a download of the generated PDF.
- If you didn’t add the button, you can still run the CreatePdf method directly by visiting this URL in your browser:
https://localhost:xxxx/Pdf/CreatePdf
(where xxxx is your local port number).
Output:

In addition to text, Spire.PDF supports adding a wide range of elements to PDF, such as images, shapes, tables, lists, hyperlinks, annotations, and watermarks. For more details and advanced usage, check the .NET PDF Tutorials.
Create PDF from HTML in ASP.NET Core
Spire.PDF allows you to convert HTML content directly into PDF files. This feature is particularly useful for generating invoices, reports, receipts, or exporting styled web pages with consistent formatting.
To render HTML as PDF, Spire.PDF relies on an external rendering engine. You can choose between Qt WebEngine or Google Chrome . In this guide, we’ll use Qt WebEngine .
Setup the Qt plugin:
-
Download the Qt WebEngine plugin for your operating system:
-
Extract the package to obtain the plugins directory, e.g.: C:\plugins-windows-x64\plugins
-
Register the plugin path inyour code:
HtmlConverter.PluginPath = @"C:\plugins-windows-x64\plugins";
Once the plugin is ready, you can follow the steps from the previous section and add the code snippet below to your controller to generate PDF output from HTML content.
using Microsoft.AspNetCore.Mvc;
using Spire.Additions.Qt;
using Spire.Pdf.Graphics;
using System.Drawing;
namespace PdfDemoApp.Controllers
{
public class PdfController : Controller
{
[HttpGet]
public IActionResult HtmlToPdf()
{
// Example HTML string
string html = @"
<html>
<head>
<style>
body { font-family: Arial, sans-serif; }
h1 { color: #2563eb; }
</style>
</head>
<body>
<h1>ASP.NET Core: Create PDF from HTML</h1>
<p>This PDF was generated using the Qt-based converter.</p>
</body>
</html>";
// Path to the Qt plugin folder
// ⚠️ Ensure this folder exists on your server/deployment environment
string pluginPath = @"C:\plugins-windows-x64\plugins";
HtmlConverter.PluginPath = pluginPath;
// Create a temp file path (on server side)
string tempFile = Path.GetTempFileName();
// Convert HTML string → PDF using Qt
HtmlConverter.Convert(
html,
tempFile,
enableJavaScript: true,
timeout: 100000, // milliseconds
pageSize: new SizeF(595, 842), // A4 page size in points
margins: new PdfMargins(40), // 40pt margins
LoadHtmlType.SourceCode // Load from HTML string
);
// Read the generated PDF into memory
byte[] fileBytes = System.IO.File.ReadAllBytes(tempFile);
// Clean up temp file
System.IO.File.Delete(tempFile);
// Return PDF to browser as download
return File(fileBytes, "application/pdf", "HtmlToPdf.pdf");
}
}
}
Output:

This example converts inline HTML into a properly formatted PDF. You can also load external HTML files or URLs - see our detailed guide on Convert HTML to PDF in C# for more information.
Best Practices for ASP.NET PDF Generation
- Use memory streams instead of disk storage for performance and scalability.
- Cache static PDFs (like terms & conditions or forms) to reduce server load.
- Use HTML-to-PDF for dynamic reports with CSS styling.
- Consider templates (like Word-to-PDF with Spire.Doc) when documents have complex layouts.
- Secure sensitive PDFs with password protection or access permissions.
Conclusion
With Spire.PDF for .NET, you can easily generate PDF in ASP.NET Core applications. Whether you’re creating PDFs from scratch or performing HTML-to-PDF conversion in C# , Spire.PDF provides a reliable, developer-friendly solution—no external dependencies required.
If you also need to generate PDFs from Word documents, that feature is available via Spire.Doc for .NET, another product in the Spire family. Together, they cover the full range of PDF document generation scenarios.
By integrating these tools, developers can streamline workflows, reduce reliance on Adobe or other third-party components, and ensure consistent, professional-quality output. This makes your ASP.NET PDF solutions more scalable, maintainable, and ready for enterprise use.
FAQs
Q1. Do I need Adobe Acrobat installed on the server?
No. Spire.PDF is a standalone library and works independently of Adobe Acrobat.
Q2. Can I generate PDFs from both raw content and HTML?
Yes. You can build documents programmatically (drawing text, shapes, tables) or convert HTML pages to PDF.
Q3. Can I convert Word documents to PDF with Spire.PDF?
No. Word-to-PDF is supported by Spire.Doc for .NET, not Spire.PDF. You can use them together if your project requires it.
Q4. How can I protect generated PDFs?
Spire.PDF supports setting passwords, permissions, and digital signatures for document security.
Q5. Does Spire.PDF support ASP.NET Framework?
Yes. It works with both ASP.NET Core and ASP.NET Framework.
Get a Free License
To fully experience the capabilities of Spire.PDF for .NET without any evaluation limitations, you can request a free 30-day trial license.
Convert PDF and Byte Array in C# (Load, Edit, Save in Memory)
2025-08-25 06:56:30 Written by zaki zaki
Working with PDFs as byte arrays is common in C# development. Developers often need to store PDF documents in a database, transfer them through an API, or process them entirely in memory without touching the file system. In such cases, converting between PDF and bytes using C# becomes essential.
This tutorial explains how to perform these operations step by step using Spire.PDF for .NET. You will learn how to convert a byte array to PDF, convert a PDF back into a byte array, and even edit a PDF directly from memory with C# code.
Jump right where you need
- Why Work with Byte Arrays and PDFs in C#?
- Convert Byte Array to PDF in C#
- Convert PDF to Byte Array in C#
- Create and Edit PDF Directly from a Byte Array
- Advantages of Using Spire.PDF for .NET
- Conclusion
- FAQ
Why Work with Byte Arrays and PDFs in C#?
Using byte[] as the transport format lets you avoid temporary files and makes your code friendlier to cloud and container environments.
- Database storage (BLOB): Persist PDFs as raw bytes; hydrate only when needed.
- Web APIs: Send/receive PDFs over HTTP without touching disk.
- In-memory processing: Transform or watermark PDFs entirely in streams.
- Security & isolation: Limit file I/O, reduce temp-file risks.
Getting set up: before running the examples, add the NuGet package of Spire.PDF for .NET so the API surface is available in your project.
Install-Package Spire.PDF
Once installed, you can load from byte[] or Stream, edit pages, and write outputs back to memory or disk—no extra converters required.
Convert Byte Array to PDF in C#
When an upstream service (e.g., an API or message queue) hands you a byte[] that represents a PDF, you often need to materialize it as a document for further processing or for a one-time save to disk. With Spire.PDF for .NET, this is a direct load operation—no intermediate temp file.
Scenario & approach: we’ll accept a byte[] (from DB/API), construct a PdfDocument in memory, optionally validate basic metadata, and then save the document.
using Spire.Pdf;
using System.IO;
class Program
{
static void Main()
{
// Example source: byte[] retrieved from DB/API
byte[] pdfBytes = File.ReadAllBytes("Sample.pdf"); // substitute with your source
// 1) Load PDF from raw bytes (in memory)
PdfDocument doc = new PdfDocument();
doc.LoadFromBytes(pdfBytes);
// 2) (Optional) inspect basic info before saving or further processing
// int pageCount = doc.Pages.Count;
// 3) Save to a file
doc.SaveToFile("Output.pdf");
doc.Close();
}
}
The diagram below illustrates the byte[] to PDF conversion workflow:

What the code is doing & why it matters:
- LoadFromBytes(byte[]) initializes the PDF entirely in memory—perfect for services without write access.
- You can branch after loading: validate pages, redact, stamp, or route elsewhere.
- SaveToFile(string) saves the document to disk for downstream processing or storing.
Convert PDF to Byte Array in C#
In the reverse direction, converting a PDF to a byte[] enables database writes, caching, or streaming the file through an HTTP response. Spire.PDF for .NET writes directly to a MemoryStream, which you can convert to a byte array with ToArray().
Scenario & approach: load an existing PDF, push the document into a MemoryStream, then extract the byte[]. This pattern is especially useful when returning PDFs from APIs or persisting them to databases.
using Spire.Pdf;
using System.IO;
class Program
{
static void Main()
{
// 1) Load a PDF from disk, network share, or embedded resource
PdfDocument doc = new PdfDocument();
doc.LoadFromFile("Input.pdf");
// 2) Save to a MemoryStream for fileless output
byte[] pdfBytes;
using (var ms = new MemoryStream())
{
doc.SaveToStream(ms);
pdfBytes = ms.ToArray();
}
doc.Close();
// pdfBytes now contains the full document (ready for DB/API)
// e.g., return File(pdfBytes, "application/pdf");
}
}
The diagram below shows the PDF to byte[] conversion workflow:

Key takeaways after the code:
- SaveToStream → ToArray is the standard way to obtain a PDF as bytes in C# without creating temp files.
- This approach scales for large PDFs; the only limit is available memory.
- Great for ASP.NET: return the byte array directly in your controller or minimal API endpoint.
If you want to learn more about working with streams, check out our guide on loading and saving PDF documents via streams in C#.
Create and Edit PDF Directly from a Byte Array
The real power comes from editing PDFs fully in memory. You can load from byte[], add text or images, stamp a watermark, fill form fields, and save the edited result back into a new byte[]. This enables fileless pipelines and is well-suited for microservices.
Scenario & approach: we’ll load a PDF from bytes, draw a small text annotation on page 1 (stand-in for any edit operation), and emit the edited document as a fresh byte array.
using Spire.Pdf;
using Spire.Pdf.Graphics;
using System.Drawing;
using System.IO;
class Program
{
static void Main()
{
// Source could be DB, API, or file — represented as byte[]
byte[] inputBytes = File.ReadAllBytes("Input.pdf");
// 1) Load in memory
var doc = new PdfDocument();
doc.LoadFromBytes(inputBytes);
// 2) Edit: write a small marker on the first page
PdfPageBase page = doc.Pages[0];
page.Canvas.DrawString(
"Edited in memory",
new PdfFont(PdfFontFamily.Helvetica, 12f),
PdfBrushes.DarkBlue,
new PointF(100, page.Size.Height - 100)
);
// 3) Save the edited PDF back to byte[]
byte[] editedBytes;
using (var ms = new MemoryStream())
{
doc.SaveToStream(ms);
editedBytes = ms.ToArray();
}
doc.Close();
// editedBytes can now be persisted or returned by an API
}
}
The image below shows the edited PDF page:

After-code insights:
- The same pattern works for text, images, watermarks, annotations, and form fields.
- Keep edits idempotent (e.g., check if you already stamped a page) for safe reprocessing.
- For ASP.NET, this is ideal for on-the-fly stamping or conditional redaction before returning the response.
For a step-by-step tutorial on building a PDF from scratch, see our article on creating PDF documents in C#.
Advantages of Using Spire.PDF for .NET
A concise view of why this API pairs well with byte-array workflows:
| Concern | What you get with Spire.PDF for .NET |
|---|---|
| I/O flexibility | Load/save from file path, Stream, or byte[] with the same PdfDocument API. |
| In-memory editing | Draw text/images, manage annotations/forms, watermark, and more—no temp files. |
| Service-friendly | Clean integration with ASP.NET endpoints and background workers. |
| Scales to real docs | Handles multi-page PDFs; you control memory via streams. |
| Straightforward code | Minimal boilerplate; avoids manual byte fiddling and fragile interop. |
Conclusion
You’ve seen how to convert byte array to PDF in C#, how to convert PDF to byte array, and how to edit a PDF directly from memory—all with concise code. Keeping everything in streams and byte[] simplifies API design, accelerates response times, and plays nicely with databases and cloud hosting. Spire.PDF for .NET gives you a consistent, fileless workflow that’s easy to extend from quick conversions to full in-memory document processing.
If you want to try these features without limitations, you can request a free 30-day temporary license. Alternatively, you can explore Free Spire.PDF for .NET for lightweight PDF tasks.
FAQ
Can I create a PDF from a byte array in C# without saving to disk?
Yes. Load from byte[] with LoadFromBytes, then either save to a MemoryStream or return it directly from an API—no disk required.
How do I convert PDF to byte array in C# for database storage?
Use SaveToStream on PdfDocument and call ToArray() on the MemoryStream. Store that byte[] as a BLOB (or forward it to another service).
Can I edit a PDF that only exists as a byte array?
Absolutely. Load from bytes, apply edits (text, images, watermarks, annotations, form fill), then save the result back to a new byte[].
Any tips for performance and reliability?
Dispose streams promptly, reuse buffers when appropriate, and create a new PdfDocument per operation/thread. For large files, stream I/O keeps memory usage predictable.

Many business applications today need the ability to scan barcodes and QR codes in ASP.NET environments. From ticket validation and payment processing to inventory management, an ASP.NET QR code scanner or barcode reading feature can greatly improve efficiency and accuracy for both web and enterprise systems.
This tutorial demonstrates how to build a complete solution to scan barcodes in ASP.NET with C# code using Spire.Barcode for .NET. We’ll create an ASP.NET Core web application that can read both QR codes and various barcode formats from uploaded images, delivering high recognition accuracy and easy integration into existing projects.
Guide Overview
- 1. Project Setup
- 2. Implementing QR Code and Barcode Scanning Feature with C# in ASP.NET
- 3. Testing and Troubleshooting
- 4. Extending to Other .NET Applications
- 5. Conclusion
1. Project Setup
Step 1: Create the Project
Create a new ASP.NET Core Razor Pages project, which will serve as the foundation for the scanning feature. Use the following command to create a new project or manually configure it in Visual Studio:
dotnet new webapp -n QrBarcodeScanner
cd QrBarcodeScanner
Step 2: Install Spire.Barcode for .NET
Install the Spire.Barcode for .NET NuGet package, which supports decoding a wide range of barcode types with a straightforward API. Search for the package in the NuGet Package Manager or use the command below to install it:
dotnet add package Spire.Barcode
Spire.Barcode for .NET offers built-in support for both QR codes and multiple barcode formats such as Code128, EAN-13, and Code39, making it suitable for ASP.NET Core integration without requiring additional image processing libraries. To find out all the supported barcode types, refer to the BarcodeType API reference.
You can also use Free Spire.Barcode for .NET for smaller projects.
2. Implementing QR Code and Barcode Scanning Feature with C# in ASP.NET
A reliable scanning feature involves two main parts:
- Backend logic that processes and decodes uploaded images.
- A simple web interface that lets users upload files for scanning.
We will first focus on the backend implementation to ensure the scanning process works correctly, then connect it to a minimal Razor Page frontend.
Backend: QR & Barcode Scanning Logic with Spire.Barcode
The backend code reads the uploaded file into memory and processes it with Spire.Barcode, using either a memory stream or a file path. The scanned result is then returned. This implementation supports QR codes and other barcode types without requiring format-specific logic.
Index.cshtml.cs
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Spire.Barcode;
public class IndexModel : PageModel
{
[BindProperty]
public IFormFile Upload { get; set; } // Uploaded file
public string Result { get; set; } // Scanning result
public string UploadedImageBase64 { get; set; } // Base64 string for preview
public void OnPost()
{
if (Upload != null && Upload.Length > 0)
{
using (var ms = new MemoryStream())
{
// Read the uploaded file into memory
Upload.CopyTo(ms);
// Convert the image to Base64 for displaying in HTML <img>
UploadedImageBase64 = "data:" + Upload.ContentType + ";base64," +
Convert.ToBase64String(ms.ToArray());
// Reset the stream position before scanning
ms.Position = 0;
// Scan the barcode or QR code from the stream
try
{
string[] scanned = BarcodeScanner.Scan(ms);
// Return the scanned result
Result = scanned != null && scanned.Length > 0
? string.Join(", ", scanned)
: "No code detected.";
}
catch (Exception ex)
{
Result = "Error while scanning: " + ex.Message;
}
}
}
}
}
Explanation of Key Classes and Methods
- BarcodeScanner: A static class in Spire.Barcode that decodes images containing QR codes or barcodes.
- BarcodeScanner.Scan(Stream imageStream): Scans an uploaded image directly from a memory stream and returns an array of decoded strings. This method scans all barcodes in the given image.
- Supplementary methods (optional):
- BarcodeScanner.Scan(string imagePath): Scans an image from a file path.
- BarcodeScanner.ScanInfo(string imagePath): Scans an image from a file path and returns additional barcode information such as type, location, and data.
These methods can be used in different ways, depending on the application requirements.
Frontend: QR & Barcode Upload & Scanning Result Interface
The following page design provides a simple upload form where users can submit an image containing a QR code or barcode. Once uploaded, the image is displayed along with the recognized result, which can be copied with a single click. The layout is intentionally kept minimal for fast testing, yet styled for a clear and polished presentation.
Index.cshtml
@page
@model IndexModel
@{
ViewData["Title"] = "QR & Barcode Scanner";
}
<div style="max-width:420px;margin:40px auto;padding:20px;border:1px solid #ccc;border-radius:8px;background:#f9f9f9;">
<h2>QR & Barcode Scanner</h2>
<form method="post" enctype="multipart/form-data" id="uploadForm">
<input type="file" name="upload" accept="image/*" required onchange="this.form.submit()" style="margin:10px 0;" />
</form>
@if (!string.IsNullOrEmpty(Model.UploadedImageBase64))
{
<div style="margin-top:15px;text-align:center;">
<img src="/@Model.UploadedImageBase64" style="width:300px;height:300px;object-fit:contain;border:1px solid #ddd;background:#fff;" />
</div>
}
@if (!string.IsNullOrEmpty(Model.Result))
{
<div style="margin-top:15px;padding:10px;background:#e8f5e9;border-radius:6px;">
<b>Scan Result:</b>
<p id="scanText">@Model.Result</p>
<button type="button" onclick="navigator.clipboard.writeText(scanText.innerText)" style="background:#28a745;color:#fff;padding:6px 10px;border:none;border-radius:4px;">Copy</button>
</div>
}
</div>
Below is a screenshot showing the scan page after successfully recognizing both a QR code and a Code128 barcode, with the results displayed and a one-click copy button available.

This ASP.NET Core application can scan QR codes and other barcodes from uploaded images. If you're looking to generate QR codes or barcodes, check out How to Generate QR Codes in ASP.NET Core.
3. Testing and Troubleshooting
After running the application, test the scanning feature with:
- A QR code image containing a URL or plain text.
- A barcode image such as Code128 or EAN-13.
If recognition fails:
- Ensure the image has good contrast and minimal distortion.
- Use images of reasonable resolution (not excessively large or pixelated).
- Test with different file formats such as JPG, PNG, or BMP.
- Avoid images with reflections, glare, or low lighting.
- When scanning multiple barcodes in one image, ensure each code is clearly separated to improve recognition accuracy.
A good practice is to maintain a small library of sample QR codes and barcodes to test regularly after making code changes.
4. Extending to Other .NET Applications
The barcode scanning logic in this tutorial works the same way across different .NET application types — only the way you supply the image file changes. This makes it easy to reuse the core decoding method, BarcodeScanner.Scan(), in various environments such as:
- ASP.NET Core MVC controllers or Web API endpoints
- Desktop applications like WinForms or WPF
- Console utilities for batch processing
Example: Minimal ASP.NET Core Web API Endpoint — receives an image file via HTTP POST and returns decoded results as JSON:
[ApiController]
[Route("api/[controller]")]
public class ScanController : ControllerBase
{
[HttpPost]
public IActionResult Scan(IFormFile file)
{
if (file == null) return BadRequest("No file uploaded");
using var ms = new MemoryStream();
file.CopyTo(ms);
ms.Position = 0;
string[] results = BarcodeScanner.Scan(ms);
return Ok(results);
}
}
Example: Console application — scans a local image file and prints the decoded text:
string[] result = BarcodeScanner.Scan(@"C:\path\to\image.png");
Console.WriteLine(string.Join(", ", result));
This flexibility makes it simple for developers to quickly add QR code and barcode scanning to new projects or extend existing .NET applications.
5. Conclusion
This tutorial has shown how to implement a complete QR code and barcode scanning solution in ASP.NET Core using Spire.Barcode for .NET. From receiving uploaded images to decoding and displaying the results, the process is straightforward and adaptable to a variety of application types. With this approach, developers can quickly integrate reliable scanning functionality into e-commerce platforms, ticketing systems, document verification tools, and other business-critical web applications.
For more advanced scenarios, Spire.Barcode for .NET provides additional features such as customizing the recognition process, handling multiple image formats and barcode types, and more. Apply for a free trial license to unlock all the advanced features.
Download Spire.Barcode for .NET today and start building your own ASP.NET barcode scanning solution.

Optical Character Recognition (OCR) technology has become essential for developers working with scanned documents and image-based PDFs. In this tutorial, you learn how to perform OCR on PDFs in C# to extract text from scanned documents or images within a PDF using the Spire.PDF for .NET and Spire.OCR for .NET libraries. By transferring scanned PDFs into editable and searchable formats, you can significantly improve your document management processes.
Table of Contents :
- Why OCR is Needed for Scanned PDFs?
- Setting Up: Installing Required Libraries
- Performing OCR on Scanned PDFs
- Extracting Text from Images within PDFs
- Wrapping Up
- FAQs
Why OCR is Needed for Scanned PDFs?
Scanned PDFs are essentially image files —they contain pictures of text rather than actual selectable and searchable text content. When you scan a paper document or receive an image-based PDF, the text exists only as pixels , making it impossible to edit, search, or extract. This creates significant limitations for businesses and individuals who need to work with these documents digitally.
OCR technology solves this problem by analyzing the shapes of letters and numbers in scanned images and converting them into machine-readable text. This process transforms static PDFs into usable, searchable, and editable documents—enabling text extraction, keyword searches, and seamless integration with databases and workflow automation tools.
In fields such as legal, healthcare, and education, where large volumes of scanned documents are common, OCR plays a crucial role in document digitization, making important data easily accessible and actionable.
Setting Up: Installing Required Libraries
Before we dive into the code, let's first set up our development environment with the necessary components: Spire.PDF and Spire.OCR . Spire.PDF handles PDF operations, while Spire.OCR performs the actual text recognition.
Step 1. Install Spire.PDF and Spire.OCR via NuGet
To begin, open the NuGet Package Manager in Visual Studio, and search for "Spire.PDF" and "Spire.OCR" to install them in your project. Alternatively, you can use the Package Manager Console :
Install-Package Spire.PDF
Install-Package Spire.OCR
Step 2. Download OCR Models:
Spire.OCR requires pre-trained language models for text recognition. Download the appropriate model files for your operating system (Windows, Linux, or MacOS) and extract them to a directory (e.g., D:\win-x64).
Important Note : Ensure your project targets x64 platform (Project Properties > Build > Platform target) as Spire.OCR only supports 64-bit systems.

Performing OCR on Scanned PDFs in C#
With the necessary libraries installed, we can now perform OCR on scanned PDFs. Below is a sample code snippet demonstrating this process.
using Spire.OCR;
using Spire.Pdf;
using Spire.Pdf.Graphics;
using System.Drawing;
namespace OCRPDF
{
class Program
{
static void Main(string[] args)
{
// Create an instance of the OcrScanner class
OcrScanner scanner = new OcrScanner();
// Configure the scanner
ConfigureOptions configureOptions = new ConfigureOptions
{
ModelPath = @"D:\win-x64", // Set model path
Language = "English" // Set language
};
// Apply the configuration options
scanner.ConfigureDependencies(configureOptions);
// Load a PDF document
PdfDocument doc = new PdfDocument();
doc.LoadFromFile(@"C:\Users\Administrator\Desktop\Input5.pdf");
// Iterate through all pages
for (int i = 0; i < doc.Pages.Count; i++)
{
// Convert page to image
Image image = doc.SaveAsImage(i, PdfImageType.Bitmap);
// Convert the image to a MemoryStream
using (MemoryStream stream = new MemoryStream())
{
image.Save(stream, System.Drawing.Imaging.ImageFormat.Png);
stream.Position = 0; // Reset the stream position
// Perform OCR on the image stream
scanner.Scan(stream, OCRImageFormat.Png);
string pageText = scanner.Text.ToString();
// Save extracted text to a separate file
string outputTxtPath = Path.Combine(@"C:\Users\Administrator\Desktop\Output", $"Page-{i + 1}.txt");
File.WriteAllText(outputTxtPath, pageText);
}
}
// Close the document
doc.Close();
}
}
}
Key Components Explained :
- OcrScanner Class : This class is crucial for performing OCR. It provides methods to configure and execute the scanning operation.
- ConfigureOptions Class : This class is used to set up the OCR scanner's configurations. The ModelPath property specifies the path to the OCR model files, and the Language property allows you to specify the language for text recognition.
- PdfDocument Class : This class represents the PDF document. The LoadFromFile method loads the PDF file that you want to process.
- Image Conversion : Each PDF page is converted to an image using the SaveAsImage method. This is essential because OCR works on image files.
- MemoryStream : The image is saved into a MemoryStream , allowing us to perform OCR without saving the image to disk.
- OCR Processing : The Scan method performs OCR on the image stream. The recognized text can be accessed using the Text property of the OcrScanner instance.
- Output : The extracted text is saved to a text file for each page.
Output :

To extract text from searchable PDFs, refer to this guide: Automate PDF Text Extraction Using C#
Extracting Text from Images within PDFs in C#
In addition to processing entire PDF pages, you can also extract text from images embedded within PDFs. Here’s how:
using Spire.Pdf;
using Spire.Pdf.Utilities;
using Spire.OCR;
using System.Drawing;
namespace OcrImageFromPdf
{
class Program
{
static void Main(string[] args)
{
// Create a PdfDocument object
PdfDocument doc = new PdfDocument();
// Load a PDF document
doc.LoadFromFile(@"C:\Users\Administrator\Desktop\AI.pdf");
// Create a PdfImageHelper object
PdfImageHelper imageHelper = new PdfImageHelper();
// Create an instance of the OcrScanner class
OcrScanner scanner = new OcrScanner();
// Configure the scanner
ConfigureOptions configureOptions = new ConfigureOptions
{
ModelPath = @"D:\win-x64", // Set model path
Language = "English" // Set language
};
scanner.ConfigureDependencies(configureOptions);
// Declare an int variable
int m = 0;
// Iterate through the pages
for (int i = 0; i < doc.Pages.Count; i++)
{
// Get a specific page
PdfPageBase page = doc.Pages[i];
// Get all image information from the page
PdfImageInfo[] imageInfos = imageHelper.GetImagesInfo(page);
// Iterate through the image information
for (int j = 0; j < imageInfos.Length; j++)
{
// Get a specific image information
PdfImageInfo imageInfo = imageInfos[j];
// Get the image
Image image = imageInfo.Image;
// Convert the image to a MemoryStream
using (MemoryStream stream = new MemoryStream())
{
image.Save(stream, System.Drawing.Imaging.ImageFormat.Png);
stream.Position = 0; // Reset the stream position
// Perform OCR on the image stream
scanner.Scan(stream, OCRImageFormat.Png);
string imageText = scanner.Text.ToString();
// Save the OCR result to a text file
string outputTxtPath = Path.Combine(@"C:\Users\Administrator\Desktop\Output", $"Image-Text-{m + 1}.txt");
File.WriteAllText(outputTxtPath, imageText);
m++;
}
}
}
// Dispose resources
doc.Dispose();
}
}
}
Key Components Explained :
- PdfImageHelper Class : This class is essential for extracting images from a PDF page. It provides methods to retrieve image information such as GetImagesInfo , which returns an array of PdfImageInfo objects.
- PdfImageInfo Class : Each PdfImageInfo object contains properties related to an image, including the actual Image object that can be processed further.
- Image Processing : Similar to the previous example, each image is saved to a MemoryStream for OCR processing.
- Output : The extracted text from each image is saved to a separate text file.
Output:

Wrapping Up
By combining Spire.PDF with Spire.OCR , you can seamlessly transform scanned PDFs and image-based documents into fully searchable and editable text. Whether you need to process entire pages or extract text from specific embedded images, the approach is straightforward and flexible.
This OCR integration not only streamlines document digitization but also enhances productivity by enabling search, copy, and automated data extraction. In industries where large volumes of scanned documents are the norm, implementing OCR with C# can significantly improve accessibility, compliance, and information retrieval speed.
FAQs
Q1. Can I perform OCR on non-English PDFs?
Yes, Spire.OCR supports multiple languages. You can set the Language property in ConfigureOptions to the desired language.
Q2. What should I do if the output is garbled or incorrect?
Check the quality of the input PDF images. If the images are blurry or have low contrast, OCR may struggle to recognize text accurately. Consider enhancing the image quality before processing.
Q3. Can I extract text from images embedded within a PDF?
Yes, you can. Use a helper class to extract images from each page and then apply OCR to recognize text.
Q4. Can Spire.OCR handle handwritten text in PDFs?
Spire.OCR is primarily optimized for printed text. Handwriting recognition typically has lower accuracy.
Q5. Do I need to install additional language models for OCR?
Yes, Spire.OCR requires pre-trained language model files. Download and configure the appropriate models for your target language before performing OCR.
Get a Free License
To fully experience the capabilities of Spire.PDF for .NET and Spire.OCR for .NET without any evaluation limitations, you can request a free 30-day trial license.