푸터 콘텐츠로 바로가기
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();
}
$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");
$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[];
    }
}
$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
}
$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");
}
$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

자주 묻는 질문

IronPDF란 무엇인가요?

IronPDF는 개발자가 C# 애플리케이션에서 PDF 파일에서 콘텐츠를 생성, 편집 및 추출할 수 있는 .NET 라이브러리입니다.

ASP.NET을 사용하여 데이터베이스에서 PDF 파일을 검색하려면 어떻게 해야 하나요?

ASP.NET의 데이터베이스에서 PDF 파일을 검색하려면 C# 코드를 사용하여 데이터베이스를 쿼리하고 PDF 데이터를 바이트 배열로 읽을 수 있습니다. 그런 다음 이 바이트 배열을 IronPDF와 함께 사용하여 필요에 따라 PDF를 렌더링하거나 조작할 수 있습니다.

ASP.NET 애플리케이션에서 PDF를 처리할 때 IronPDF를 사용해야 하는 이유는 무엇인가요?

IronPDF는 PDF 생성, HTML에서 변환, 조작 등 PDF 처리를 위한 강력한 기능 세트를 제공합니다. ASP.NET과 원활하게 통합되며 PDF 작업을 위한 사용하기 쉬운 API를 제공합니다.

ASP.NET에서 IronPDF를 사용하기 위한 전제 조건은 무엇인가요?

ASP.NET에서 IronPDF를 사용하려면 Visual Studio와 같은 .NET 개발 환경이 설정되어 있어야 하며 NuGet 패키지 관리자를 통해 프로젝트에 IronPDF 라이브러리를 포함시켜야 합니다.

IronPDF를 사용하여 기존 PDF 파일을 편집할 수 있나요?

예, IronPDF는 기존 PDF 파일을 편집하는 데 사용할 수 있습니다. 텍스트 또는 이미지 추가, 문서 병합 등의 수정 작업을 수행할 수 있습니다.

IronPDF로 HTML을 PDF로 변환할 수 있나요?

예, IronPDF는 HTML 콘텐츠를 PDF 형식으로 직접 변환할 수 있으므로 웹 페이지 또는 기타 HTML 콘텐츠에서 PDF를 쉽게 생성할 수 있습니다.

IronPDF를 사용하여 PDF 보안 기능을 처리하려면 어떻게 해야 하나요?

IronPDF는 비밀번호 보호, 문서 액세스 및 편집을 제어하는 권한 설정 등 PDF를 위한 다양한 보안 기능을 지원합니다.

PDF 검색을 위해 IronPDF와 호환되는 데이터베이스 유형은 무엇인가요?

IronPDF는 SQL Server, MySQL 또는 PostgreSQL과 같이 바이너리 데이터를 저장할 수 있는 모든 데이터베이스와 연동하여 PDF 파일을 검색하고 조작할 수 있습니다.

커티스 차우
기술 문서 작성자

커티스 차우는 칼턴 대학교에서 컴퓨터 과학 학사 학위를 취득했으며, Node.js, TypeScript, JavaScript, React를 전문으로 하는 프론트엔드 개발자입니다. 직관적이고 미적으로 뛰어난 사용자 인터페이스를 만드는 데 열정을 가진 그는 최신 프레임워크를 활용하고, 잘 구성되고 시각적으로 매력적인 매뉴얼을 제작하는 것을 즐깁니다.

커티스는 개발 분야 외에도 사물 인터넷(IoT)에 깊은 관심을 가지고 있으며, 하드웨어와 소프트웨어를 통합하는 혁신적인 방법을 연구합니다. 여가 시간에는 게임을 즐기거나 디스코드 봇을 만들면서 기술에 대한 애정과 창의성을 결합합니다.