Skip to footer content
USING IRONPDF

How to Retrieve PDF File from Database in ASP.NET Using C# and IronPDF

How to Retrieve PDF File from Database in ASP.NET Using C# and IronPDF: Image 5 - Output

Retrieving and Displaying PDF Documents

After storing PDFs in your database, the next step is to retrieve and display them in a web browser. IronPDF simplifies the process of fetching and rendering PDF files stored as binary data in SQL Server.

Fetching PDF from the Database

Here's how you can retrieve a PDF document from your SQL Server database and send it to the browser:

using IronPdf;
using System.Data.SqlClient;
using System.IO;
using Microsoft.AspNetCore.Mvc;

public async Task<IActionResult> RetrievePdfFromDatabase(int documentId, string connectionString)
{
    using var connection = new SqlConnection(connectionString);
    await connection.OpenAsync();
    var query = "SELECT FileName, FileContent FROM PdfDocuments WHERE Id = @Id";
    using var command = new SqlCommand(query, connection);
    command.Parameters.AddWithValue("@Id", documentId);
    using var reader = await command.ExecuteReaderAsync();
    if (reader.Read())
    {
        var fileName = reader["FileName"].ToString();
        var pdfBytes = (byte[])reader["FileContent"];
        var contentType = "application/pdf";
        return new FileContentResult(pdfBytes, contentType)
        {
            FileDownloadName = fileName
        };
    }
    return new NotFoundResult();
}
using IronPdf;
using System.Data.SqlClient;
using System.IO;
using Microsoft.AspNetCore.Mvc;

public async Task<IActionResult> RetrievePdfFromDatabase(int documentId, string connectionString)
{
    using var connection = new SqlConnection(connectionString);
    await connection.OpenAsync();
    var query = "SELECT FileName, FileContent FROM PdfDocuments WHERE Id = @Id";
    using var command = new SqlCommand(query, connection);
    command.Parameters.AddWithValue("@Id", documentId);
    using var reader = await command.ExecuteReaderAsync();
    if (reader.Read())
    {
        var fileName = reader["FileName"].ToString();
        var pdfBytes = (byte[])reader["FileContent"];
        var contentType = "application/pdf";
        return new FileContentResult(pdfBytes, contentType)
        {
            FileDownloadName = fileName
        };
    }
    return new NotFoundResult();
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

This method fetches the PDF file based on its ID, retrieves the binary data, and sends it directly to the client's browser as a downloadable file. The FileContentResult class in ASP.NET Core handles the MIME type and file download name, ensuring that the browser recognizes the file as a PDF document.

Displaying PDF in Browser

To display a PDF directly in the browser without downloading, you can modify the FileContentResult to render the PDF within the browser window:

return new FileContentResult(pdfBytes, "application/pdf");
return new FileContentResult(pdfBytes, "application/pdf");
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

This line ensures that the PDF is opened in the browser's default PDF viewer, providing a seamless user experience for viewing documents.

Conclusion

Using IronPDF with ASP.NET Core allows developers to easily manage PDF files within SQL Server databases. From storing and retrieving to displaying PDFs, IronPDF handles all aspects of PDF manipulation, leveraging its powerful Chrome rendering engine. This tutorial has demonstrated how to integrate IronPDF into your ASP.NET Core applications to handle PDF documents efficiently, whether they are uploaded, generated from HTML, or retrieved for display.

For further information on IronPDF's capabilities and licensing, visit the official IronPDF website.

How to Retrieve PDF File from Database in ASP.NET Using C# and IronPDF: Image 5 - Web Output

How to Retrieve PDF File from Database in ASP.NET Using C# and IronPDF: Image 6 - SQL Server Output

Retrieve PDF Documents from the Database

Retrieving stored PDFs requires reading the binary data from SQL Server and properly formatting the HTTP response for browser display. IronPDF streamlines this process significantly.

Creating the Retrieval Controller

In your ASP.NET Core application, create a controller action to handle PDF retrieval. This controller can be linked to a grid view or called via query string parameters to display or download files:

using IronPdf;
using Microsoft.AspNetCore.Mvc;
using System.Data.SqlClient;
using System;
using System.Threading.Tasks;

[ApiController]
[Route("api/[controller]")]
public class PdfController : ControllerBase
{
    private readonly string _connectionString;
    public PdfController(IConfiguration configuration)
    {
        _connectionString = configuration.GetConnectionString("DefaultConnection");
    }

    [HttpGet("{id}")]
    public async Task<IActionResult> GetPdf(int id)
    {
        try
        {
            // Retrieve PDF documents from database
            byte[] pdfBytes = await RetrievePdfFromDatabase(id);
            if (pdfBytes == null || pdfBytes.Length == 0)
                return NotFound();
            // Load the PDF document using IronPDF for potential modifications
            var pdfDocument = new PdfDocument(pdfBytes);
            // Return file for inline display in browser
            Response.Headers.Add("Content-Disposition", "inline");
            return File(pdfDocument.BinaryData, "application/pdf");
        }
        catch (Exception ex)
        {
            // Handle exception and log error details
            return StatusCode(500, "Error retrieving PDF file");
        }
    }

    private async Task<byte[]> RetrievePdfFromDatabase(int documentId)
    {
        using var connection = new SqlConnection(_connectionString);
        await connection.OpenAsync();
        var query = "SELECT FileContent FROM PdfDocuments WHERE Id = @Id";
        using var command = new SqlCommand(query, connection);
        command.Parameters.AddWithValue("@Id", documentId);
        var result = await command.ExecuteScalarAsync();
        return result as byte[];
    }
}
using IronPdf;
using Microsoft.AspNetCore.Mvc;
using System.Data.SqlClient;
using System;
using System.Threading.Tasks;

[ApiController]
[Route("api/[controller]")]
public class PdfController : ControllerBase
{
    private readonly string _connectionString;
    public PdfController(IConfiguration configuration)
    {
        _connectionString = configuration.GetConnectionString("DefaultConnection");
    }

    [HttpGet("{id}")]
    public async Task<IActionResult> GetPdf(int id)
    {
        try
        {
            // Retrieve PDF documents from database
            byte[] pdfBytes = await RetrievePdfFromDatabase(id);
            if (pdfBytes == null || pdfBytes.Length == 0)
                return NotFound();
            // Load the PDF document using IronPDF for potential modifications
            var pdfDocument = new PdfDocument(pdfBytes);
            // Return file for inline display in browser
            Response.Headers.Add("Content-Disposition", "inline");
            return File(pdfDocument.BinaryData, "application/pdf");
        }
        catch (Exception ex)
        {
            // Handle exception and log error details
            return StatusCode(500, "Error retrieving PDF file");
        }
    }

    private async Task<byte[]> RetrievePdfFromDatabase(int documentId)
    {
        using var connection = new SqlConnection(_connectionString);
        await connection.OpenAsync();
        var query = "SELECT FileContent FROM PdfDocuments WHERE Id = @Id";
        using var command = new SqlCommand(query, connection);
        command.Parameters.AddWithValue("@Id", documentId);
        var result = await command.ExecuteScalarAsync();
        return result as byte[];
    }
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

This controller demonstrates several important concepts. First, it retrieves the binary data from the database using a parameterized query for security. Then, it loads the PDF into IronPDF's PdfDocument object using the FromBytes() method. This step is crucial because it allows you to modify the PDF before sending it to the client. Finally, the File() method with inline: true ensures the PDF is displayed directly in the browser rather than triggering a download, solving the common challenge of retrieving a PDF from a database in ASP.NET using C#.

Implementing Download Functionality

Sometimes users need to download PDF files rather than view them inline. You might add an upload button to save new files or a download link in your grid view. Here's how to modify the response headers for downloading with the correct file name and file path details:

[HttpGet("download/{id}")]
public async Task<IActionResult> DownloadPdf(int id)
{
    // Retrieve stored PDF file from database
    byte[] pdfBytes = await RetrievePdfFromDatabase(id);
    string fileName = await GetFileName(id);
    if (pdfBytes == null || pdfBytes.Length == 0)
        return NotFound("PDF file not found");
    // Load and validate PDF document
    var pdfDocument = new PdfDocument(pdfBytes);
    // Set content disposition for attachment download
    Response.Headers.Append("Content-Disposition", $"attachment; filename={fileName}");
    // Return file for download with default PDF content type
    return File(pdfDocument.BinaryData, "application/pdf", fileName);
}

private async Task<string> GetFileName(int documentId)
{
    using var connection = new SqlConnection(_connectionString);
    await connection.OpenAsync();
    // Query to retrieve PDF file name from database
    var query = "SELECT FileName FROM PdfDocuments WHERE Id = @Id";
    using var command = new SqlCommand(query, connection);
    command.Parameters.AddWithValue("@Id", documentId);
    var result = await command.ExecuteScalarAsync();
    return result as string ?? "document.pdf"; // Default filename if null
}
[HttpGet("download/{id}")]
public async Task<IActionResult> DownloadPdf(int id)
{
    // Retrieve stored PDF file from database
    byte[] pdfBytes = await RetrievePdfFromDatabase(id);
    string fileName = await GetFileName(id);
    if (pdfBytes == null || pdfBytes.Length == 0)
        return NotFound("PDF file not found");
    // Load and validate PDF document
    var pdfDocument = new PdfDocument(pdfBytes);
    // Set content disposition for attachment download
    Response.Headers.Append("Content-Disposition", $"attachment; filename={fileName}");
    // Return file for download with default PDF content type
    return File(pdfDocument.BinaryData, "application/pdf", fileName);
}

private async Task<string> GetFileName(int documentId)
{
    using var connection = new SqlConnection(_connectionString);
    await connection.OpenAsync();
    // Query to retrieve PDF file name from database
    var query = "SELECT FileName FROM PdfDocuments WHERE Id = @Id";
    using var command = new SqlCommand(query, connection);
    command.Parameters.AddWithValue("@Id", documentId);
    var result = await command.ExecuteScalarAsync();
    return result as string ?? "document.pdf"; // Default filename if null
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

By passing the filename parameter to the File() method and setting the content disposition to "attachment", ASP.NET Core prompts the browser to save the PDF to the user's default download folder.

Output

How to Retrieve PDF File from Database in ASP.NET Using C# and IronPDF: Image 7 - Download PDF Output

Enhancing Retrieved PDFs with IronPDF

One of IronPDF's standout features is the ability to modify PDFs after they are retrieved. You can add watermarks, stamps, or security features before sending documents to users.

Adding Watermarks to Retrieved PDFs

Here's an example of how to add a watermark to PDF documents as you retrieve them from your database. This is useful when you need to fill PDF pages with additional comments or security markings:

[HttpGet("watermarked/{id}")]
public async Task<IActionResult> GetWatermarkedPdf(int id)
{
    // Retrieve PDF file from database table
    byte[] pdfBytes = await RetrievePdfFromDatabase(id);
    if (pdfBytes == null || pdfBytes.Length == 0)
        return NotFound("Cannot retrieve PDF document");
    // Create new PdfDocument from stored byte array
    var pdfDocument = new PdfDocument(pdfBytes);
    // Add watermark to each page of the PDF document
    string watermarkHtml = "<h2 style='color:red; opacity:0.5'>CONFIDENTIAL</h2>";
    pdfDocument.ApplyWatermark(watermarkHtml, 30, VerticalAlignment.Middle, HorizontalAlignment.Center);
    // Write the modified PDF to response
    return File(pdfDocument.BinaryData, "application/pdf");
}
[HttpGet("watermarked/{id}")]
public async Task<IActionResult> GetWatermarkedPdf(int id)
{
    // Retrieve PDF file from database table
    byte[] pdfBytes = await RetrievePdfFromDatabase(id);
    if (pdfBytes == null || pdfBytes.Length == 0)
        return NotFound("Cannot retrieve PDF document");
    // Create new PdfDocument from stored byte array
    var pdfDocument = new PdfDocument(pdfBytes);
    // Add watermark to each page of the PDF document
    string watermarkHtml = "<h2 style='color:red; opacity:0.5'>CONFIDENTIAL</h2>";
    pdfDocument.ApplyWatermark(watermarkHtml, 30, VerticalAlignment.Middle, HorizontalAlignment.Center);
    // Write the modified PDF to response
    return File(pdfDocument.BinaryData, "application/pdf");
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

Note: IronPDF's watermarking feature accepts HTML content, giving you complete control over the appearance using CSS. The watermark is applied to all pages automatically, and you can adjust rotation, position, and opacity parameters to meet your requirements. This functionality is particularly useful when you need to retrieve a PDF from a database and add security markings or fill the document with additional details.

IronPDF's watermarking feature accepts HTML content, giving you complete control over the appearance using CSS. The watermark is applied to all pages automatically, and you can adjust rotation, position, and opacity to meet your requirements. This functionality is particularly useful when you need to retrieve a PDF from a database and add security markings. For more advanced watermarking techniques, developers often refer to Microsoft's documentation on PDF security.

How to Retrieve PDF File from Database in ASP.NET Using C# and IronPDF: Image 8 - How to retrieve PDF file from Database in ASP.NET using C# - IronPDF

Cross-Platform Deployment

IronPDF's architecture ensures your PDF retrieval system works consistently across different platforms. Whether you deploy to Windows servers, Linux containers, or cloud platforms like Azure and AWS, the same code runs without modification. The library handles platform-specific rendering details internally, making it ideal for modern containerized deployments using Docker or Kubernetes.

When you create .NET applications that need to retrieve PDF documents from a database table, IronPDF's cross-platform support means you can develop on one platform and deploy to another without changing your code. Simply reference the same NuGet package and use the same API methods across all environments. The library automatically handles URL rendering, HTML conversion, and binary data processing consistently across platforms.

How to Retrieve PDF File from Database in ASP.NET Using C# and IronPDF: Image 9 - Cross-platform compatibility

Best Practices and Performance Considerations

To ensure optimal performance when you retrieve PDF documents from your database, follow these essential practices. This article recommends implementing proper error handling and resource management:

Connection String Management: Store your connection strings in appsettings.json and access them through dependency injection. This keeps sensitive details out of your code and enables easy environment-specific configuration. Never hardcode database connection strings or license key information in your source code.

Resource Disposal: Both SqlConnection and PdfDocument implement IDisposable. Always use using statements to ensure proper cleanup of resources and prevent memory leaks in high-traffic .NET applications. This is crucial when handling multiple uploaded files or serving PDFs to multiple users.

Async Operations: Use async/await patterns for all database operations to prevent blocking threads. This improves your application's scalability and responsiveness, especially when handling multiple concurrent PDF requests. The system can process other requests while waiting for database operations to complete.

Error Handling: Always wrap your code in try-catch blocks to handle exceptions gracefully. Log error details for debugging and return appropriate HTTP status codes to inform users when issues occur.

File Type Validation: When users upload PDFs, validate the file type and size before processing. This prevents issues with corrupted files and protects your server from malicious uploads.

Conclusion

Retrieving PDF files from a database in ASP.NET Core becomes remarkably straightforward with IronPDF. By leveraging its Chrome rendering engine and intuitive API, you can handle complex PDF operations with minimal code while maintaining professional-quality output. The library's seamless integration with ADO.NET and ASP.NET Core's response handling makes it an ideal choice for enterprise .NET applications requiring reliable PDF document management.

Whether you're building a document archive system, need to display a PDF stream in ASP.NET C# applications, or create functionality to download files from your database, IronPDF provides all the tools to retrieve PDF documents efficiently. The following namespaces and code examples demonstrated in this article show how to:

  • Store and retrieve PDF format files as byte arrays
  • Handle object sender EventArgs e in upload button events
  • Display PDF content in the browser or trigger downloads
  • Use query string parameters to link specific documents
  • Fill pages with watermarks and comments
  • Write secure code that prevents SQL injection
  • Create robust error handling for production systems

Get started with IronPDF's free trial today and experience how it transforms PDF handling in your ASP.NET Core and .NET Framework applications. With comprehensive documentation and dedicated support, you'll have your PDF retrieval system running in production within a single sprint. Visit our documentation page for more examples and detailed API references.

How to Retrieve PDF File from Database in ASP.NET Using C# and IronPDF: Image 10 - Licensing

Frequently Asked Questions

What is IronPDF?

IronPDF is a .NET library that allows developers to create, edit, and extract content from PDF files in C# applications.

How can I retrieve a PDF file from a database using ASP.NET?

To retrieve a PDF file from a database in ASP.NET, you can use C# code to query the database and read the PDF data into a byte array. This byte array can then be used with IronPDF to render or manipulate the PDF as needed.

Why should I use IronPDF for handling PDFs in my ASP.NET application?

IronPDF offers a robust set of features for handling PDFs, including PDF generation, conversion from HTML, and manipulation. It integrates seamlessly with ASP.NET and provides an easy-to-use API for working with PDFs.

What are the prerequisites for using IronPDF in ASP.NET?

To use IronPDF in ASP.NET, you need to have a .NET development environment set up, such as Visual Studio, and include the IronPDF library in your project via NuGet package manager.

Can IronPDF be used to edit existing PDF files?

Yes, IronPDF can be used to edit existing PDF files. It allows for modifications such as adding text or images, merging documents, and more.

Is it possible to convert HTML to PDF with IronPDF?

Yes, IronPDF can convert HTML content directly into PDF format, making it easy to generate PDFs from web pages or other HTML content.

How do I handle PDF security features using IronPDF?

IronPDF supports various security features for PDFs, including password protection and setting permissions to control document access and editing.

What types of databases are compatible with IronPDF for PDF retrieval?

IronPDF can work with any database that can store binary data, such as SQL Server, MySQL, or PostgreSQL, to retrieve and manipulate PDF files.

Curtis Chau
Technical Writer

Curtis Chau holds a Bachelor’s degree in Computer Science (Carleton University) and specializes in front-end development with expertise in Node.js, TypeScript, JavaScript, and React. Passionate about crafting intuitive and aesthetically pleasing user interfaces, Curtis enjoys working with modern frameworks and creating well-structured, visually appealing manuals.

...

Read More