Knowledgebase (2300)

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.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 :
- 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.
Convert Excel to JSON and JSON to Excel in C# .NET – Step-by-Step Guide
2025-08-13 09:40:46 Written by zaki zou
Converting between Excel and JSON formats is a valuable skill for developers dealing with data exchange, API integration, and modern web applications.
Excel files (.xls, .xlsx) are excellent for organizing and analyzing tabular data, while JSON (JavaScript Object Notation) is lightweight, human-readable, and ideal for transmitting data across platforms.
In this step-by-step tutorial, you’ll learn how to seamlessly convert Excel to JSON and JSON to Excel in C# using the Spire.XLS for .NET library. Whether you’re exporting Excel data for frontend apps, feeding structured datasets into APIs, or importing JSON into spreadsheets, this guide provides clear explanations, complete code samples, and tips to help you get started quickly.
What You Will Learn
- Why Convert Between Excel and JSON Formats
- Prerequisites
- Installing Required Packages
- How to Convert Excel to JSON in C# .NET (Step-by-Step)
- How to Convert JSON to Excel in C# .NET (Step-by-Step)
- Tips and Best Practices
- Conclusion
- Further Reading
- FAQs
Why Convert Between Excel and JSON Formats?
Converting between Excel and JSON can be beneficial for several reasons:
- Data Exchange: JSON is a standard format for data interchange in web applications, making it easier to share data across platforms.
- Integration with APIs: Many web APIs require data in JSON format, necessitating conversion from Excel for seamless integration.
- Lightweight and Compact: JSON files are generally smaller in size compared to Excel files, leading to faster data transfer and reduced storage needs.
- Readability: JSON is human-readable and easier to understand, which can simplify data analysis and troubleshooting.
- Compatibility with NoSQL Databases: JSON format is commonly used in NoSQL databases, facilitating easy data migration and storage.
Prerequisites
Before we start, ensure you have the following:
- Visual Studio or any C# development IDE installed.
- .NET Framework or .NET Core installed.
- Spire.XLS package installed for handling Excel files.
- Newtonsoft.Json package installed for handling JSON serialization and deserialization.
Installing Required Packages
You can install the required packages using NuGet Package Manager in Visual Studio:
Install-Package Spire.XLS
Install-Package Newtonsoft.Json
How to Convert Excel to JSON in C# .NET (Step-by-Step)
Exporting Excel files to JSON format in C# involves extracting data from Excel spreadsheets and transforming it into a structured JSON string. This process is particularly useful for applications that require data interchange between web services or databases. Below are detailed steps to guide you through the conversion process.
Steps to Export Excel to JSON
- Load the Excel File:
- Begin by creating a Workbook object that will hold the Excel file's content using the Spire.XLS library. Load the Excel file into this object.
- Access the Desired Worksheet:
- Identify and access the specific worksheet from which you want to extract data. This is done by referencing the appropriate index of the Worksheets collection.
- Export to DataTable:
- Utilize the ExportDataTable() method to convert the worksheet's content into a DataTable. This provides a structured representation of the data, making it easier to manipulate.
- Serialize to JSON:
- Use the Newtonsoft.Json library to serialize the DataTable into a JSON string. This step involves converting the structured data into a JSON format, which is human-readable and suitable for web applications.
- Save the JSON to a File:
- Finally, write the generated JSON string to a file. This allows for easy access and reuse of the data in future applications or processes.
Complete Code Example: Excel to JSON
Here’s a complete code example demonstrating the process:
using Newtonsoft.Json;
using Spire.Xls;
using System.Data;
using System.IO;
namespace ConvertExcelToJSON
{
class Program
{
static void Main(string[] args)
{
// Path to the Excel file
string excelFilePath = @"Sample.xlsx";
// Create a new Workbook instance
Workbook workbook = new Workbook();
// Load the Excel file
workbook.LoadFromFile(excelFilePath);
// Get the first worksheet
Worksheet worksheet = workbook.Worksheets[0];
// Export the worksheet content to a DataTable
DataTable dataTable = worksheet.ExportDataTable();
// Convert the DataTable to a JSON string
string jsonResult = JsonConvert.SerializeObject(dataTable, Formatting.Indented);
// Save JSON string to a text file
File.WriteAllText("output.txt", jsonResult);
}
}
}

How to Convert JSON to Excel in C# .NET (Step-by-Step)
Importing JSON data into an Excel file is a valuable process, especially when you need to analyze or present data in a more user-friendly format. JSON is easy for humans to read and write, and easy for machines to parse and generate. However, for many users, Excel remains the preferred tool for data analysis, reporting, and visualization.
In the following steps, we will outline the process of importing JSON into Excel, enabling you to effectively utilize your JSON data within Excel for further analysis and reporting.
Steps to Import JSON into Excel
- Read the JSON String:
- Start by reading the JSON data from a file or other sources. This could include API responses, local files, or even hardcoded strings for testing purposes.
- Deserialize to DataTable:
- Use the Newtonsoft.Json library to deserialize the JSON string into a DataTable. This structured format makes it easy to manipulate data before inserting it into Excel.
- Create a New Excel Workbook:
- Initialize a new Workbook instance using the Spire.XLS library. This workbook will serve as the container for your Excel data.
- Insert the DataTable into the Worksheet:
- Use the InsertDataTable() method to transfer the contents of the DataTable into the first worksheet of the workbook. This method allows you to include column headers and organize the data neatly.
- Apply Optional Formatting:
- Enhance the visual appeal of your Excel file by applying formatting to headers and data cells. This step involves defining styles for fonts, background colors, and borders, making the data easier to read.
- Save the Workbook:
- Finally, save the populated workbook as an Excel file. Choose an appropriate file format (e.g., .xlsx) to ensure compatibility with modern Excel versions.
Complete Code Example: JSON to Excel
Here’s a complete code snippet demonstrating the conversion process:
using Newtonsoft.Json;
using Spire.Xls;
using System.Data;
using System.Drawing;
namespace ConvertJSONToExcel
{
class Program
{
static void Main(string[] args)
{
// Sample JSON data
string json = @"
[
{""Name"":""John Smith"",""Age"":30,""Department"":""Sales"",""StartDate"":""2020-05-12"",""FullTime"":true},
{""Name"":""Jane Doe"",""Age"":25,""Department"":""Marketing"",""StartDate"":""2021-09-01"",""FullTime"":false},
{""Name"":""Michael Lee"",""Age"":40,""Department"":""IT"",""StartDate"":""2018-03-15"",""FullTime"":true},
{""Name"":""Emily Davis"",""Age"":35,""Department"":""Finance"",""StartDate"":""2019-07-20"",""FullTime"":true}
]";
// Deserialize JSON into DataTable
DataTable dataTable = JsonConvert.DeserializeObject<DataTable>(json);
// Create a new Excel workbook
Workbook workbook = new Workbook();
// Get the first worksheet
Worksheet worksheet = workbook.Worksheets[0];
// Insert DataTable into worksheet with column headers
worksheet.InsertDataTable(dataTable, true, 1, 1);
// (Optional) Applying formatting to Excel data
// Set style for heading row
CellStyle headerStyle = workbook.Styles.Add("HeaderStyle");
headerStyle.Font.IsBold = true;
headerStyle.Font.Size = 12;
headerStyle.Font.Color = Color.White;
headerStyle.HorizontalAlignment = HorizontalAlignType.Center;
headerStyle.VerticalAlignment = VerticalAlignType.Center;
headerStyle.Color = Color.DarkBlue;
int colCount = dataTable.Columns.Count;
for (int c = 1; c <= colCount; c++)
{
worksheet.Range[1, c].CellStyleName = "HeaderStyle";
}
// Set style for data cells
CellStyle dataStyle = workbook.Styles.Add("DataStyle");
dataStyle.HorizontalAlignment = HorizontalAlignType.Center;
dataStyle.VerticalAlignment = VerticalAlignType.Center;
dataStyle.Borders[BordersLineType.EdgeLeft].LineStyle = LineStyleType.Thin;
dataStyle.Borders[BordersLineType.EdgeRight].LineStyle = LineStyleType.Thin;
dataStyle.Borders[BordersLineType.EdgeTop].LineStyle = LineStyleType.Thin;
dataStyle.Borders[BordersLineType.EdgeBottom].LineStyle = LineStyleType.Thin;
int rowCount = dataTable.Rows.Count;
worksheet.Range[2, 1, rowCount + 1, colCount].CellStyleName = "DataStyle";
// Auto-fit column widths
worksheet.AllocatedRange.AutoFitColumns();
// Save Excel file
workbook.SaveToFile("output.xlsx", ExcelVersion.Version2013);
// Release resources
workbook.Dispose();
}
}
}

Tips and Best Practices
When converting between Excel and JSON, following best practices can help ensure data integrity and usability. Here are some key tips to keep in mind:
- Validate Data Types: Ensure that data types (e.g., dates, numbers) are correctly formatted to avoid issues during conversion.
- Handle Empty Cells: Decide how to treat empty cells (e.g., convert to null or omit) to maintain data integrity.
- Use Consistent Naming Conventions: Standardize column names in Excel for clear and consistent JSON keys.
- Test Thoroughly: Always test the conversion processes to ensure valid JSON output and accurate Excel representation.
- Include Headers: When converting JSON to Excel, always insert headers for improved readability and usability.
Conclusion
Converting Excel to JSON and JSON to Excel is a common but critical operation in modern C# development, especially for applications involving data exchange and API integration. Using Spire.XLS together with Newtonsoft.Json simplifies this process with intuitive APIs and robust functionality.
This guide has walked you through every step—from installing necessary packages to implementing complete converters—with clear explanations and sample code. With these tools and knowledge, you can confidently integrate Excel-JSON conversion into your applications, improving flexibility and interoperability.
Further Reading
FAQs
Q1: How to convert multiple worksheets to JSON at once?
You can iterate through the Workbook.Worksheets collection and export each worksheet’s data individually, supporting batch Excel to JSON conversion.
Q2: How to customize JSON output formatting?
JsonConvert.SerializeObject allows you to set indentation, camelCase naming, or ignore null values. You can also use custom converters for more control.
Q3: How to improve readability when converting JSON to Excel?
Keep column headers, set alignment, apply borders and styles to generate a clear and easy-to-read Excel report.
Q4: Is this method compatible with .NET Core?
Yes, it is fully compatible. Both Spire.XLS and Newtonsoft.Json support .NET Core and .NET Framework, making it usable in various C# projects.
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.