跳至页脚内容
使用IRONPDF

如何在 ASP.NET 中使用 C# 和 IronPDF 从数据库读取 PDF 文件

How to Retrieve PDF File from Database in ASP.NET Using C# and IronPDF:图像 5 - 输出

检索和显示 PDF 文档

在数据库中存储 PDF 后,下一步就是在网络浏览器中检索和显示 PDF。 IronPDF 简化了获取和渲染作为二进制数据存储在 SQL Server 中的 PDF 文件的过程。

从数据库获取 PDF 文件

以下是如何从 SQL Server 数据库检索 PDF 文档并将其发送到浏览器的方法:

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

该方法根据 PDF 文件的 ID 获取 PDF 文件,检索二进制数据,并将其作为可下载文件直接发送到客户端的浏览器。ASP.NET Core 中的 FileContentResult 类会处理 MIME 类型和文件下载名称,确保浏览器将文件识别为 PDF 文档。

在浏览器中显示 PDF.

要在浏览器中直接显示 PDF 而无需下载,您可以修改 FileContentResult 以在浏览器窗口中呈现 PDF:

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

该行可确保在浏览器的默认 PDF 查看器中打开 PDF,为查看文档提供无缝的用户体验。

结论

将 IronPDF for .NET 与 ASP.NET Core 结合使用,可以让开发人员轻松管理 SQL Server 数据库中的 PDF 文件。 从存储、检索到显示 PDF,IronPDF 可利用其强大的 Chrome 渲染引擎处理 PDF 操作的方方面面。本教程演示了如何将 IronPDF 集成到您的 ASP.NET Core 应用程序中,以便高效处理 PDF 文档,无论是上传、从 HTML 生成还是检索显示。

有关 IronPDF 功能和许可的更多信息,请访问 IronPDF 官方网站

How to Retrieve PDF File from Database in ASP.NET Using C# and IronPDF:图像 5 - Web 输出

How to Retrieve PDF File from Database in ASP.NET Using C# and IronPDF:图片 6 - SQL Server 输出

从数据库检索 PDF 文档

检索存储的 PDF 需要从 SQL Server 读取二进制数据,并正确格式化 HTTP 响应以便浏览器显示。 IronPdf 大大简化了这一过程。

创建检索控制器

在您的 ASP.NET Core 应用程序中,创建一个控制器动作来处理 PDF 检索。 该控制器可以链接到网格视图,也可以通过查询字符串参数调用,以显示或下载文件:

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

该控制器展示了几个重要概念。首先,它使用参数化查询从数据库中检索二进制数据,以确保安全。 然后,使用 FromBytes() 方法将 PDF 加载到 IronPDF 的 PdfDocument 对象中。 这一步至关重要,因为它允许您在将 PDF 发送给客户之前对其进行修改。 最后,带有 inline: trueFile() 方法可确保 PDF 直接显示在浏览器中,而不是触发下载,从而解决了在 ASP.NET 中使用 C# 从数据库检索 PDF 的常见难题。

实现下载功能

有时用户需要下载 PDF 文件,而不是在线查看。您可以在网格视图中添加一个上传按钮来保存新文件或下载链接。 以下是如何修改响应标头,以便在下载时提供正确的文件名和文件路径详情:

[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

通过向 File() 方法传递文件名参数并将内容处置设置为 "附件",ASP.NET Core 会提示浏览器将 PDF 保存到用户的默认下载文件夹中。

输出

!a href="/static-assets/pdf/blog/retrieve-pdf-file-from-database-apr-net/retrieve-pdf-file-from-database-apr-net-7.webp">How to Retrieve PDF File from Database in ASP.NET Using C# and IronPDF:图像 7 - 下载 PDF 输出。

使用 IronPDF 增强检索到的 PDF.

IronPDF 的突出特点之一是能够在检索 PDF 后对其进行修改。 您可以在向用户发送文档前添加水印、印章或安全功能。

为检索到的 PDF 添加水印

以下是如何在从数据库检索 PDF 文档时为其添加水印的示例。 当您需要在 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");
}
[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

注:IronPDF 的水印功能接受 HTML 内容,您可以使用 CSS 完全控制外观。 水印会自动应用到所有页面,您可以调整旋转、位置和不透明度参数,以满足您的要求。 当您需要从数据库中检索 PDF 并添加安全标记或在文档中填写其他详细信息时,该功能尤其有用。

IronPDF 的水印功能可接受 HTML 内容,让您使用 CSS 完全控制外观。 水印会自动应用到所有页面,您可以调整旋转、位置和不透明度,以满足您的要求。 当您需要从数据库中检索 PDF 并添加安全标记时,该功能尤其有用。 对于更高级的水印技术,开发人员通常会参考 Microsoft 有关 PDF 安全性的文档

How to Retrieve PDF File from Database in ASP.NET Using C# and IronPDF:图片 8 - 如何在 ASP.NET 中使用 C# 和 IronPDF for .NET 从数据库检索 PDF 文件

跨平台部署

IronPDF 的架构可确保您的 PDF 检索系统在不同平台上一致运行。 无论您是部署到 Windows 服务器、Linux 容器还是 Azure 和 AWS 等云平台,都可以运行相同的代码,无需修改。 该库在内部处理特定平台的渲染细节,因此非常适合使用 Docker 或 Kubernetes 的现代容器化部署。

当您创建需要从数据库表中检索 PDF 文档的 .NET 应用程序时,IronPDF 的跨平台支持意味着您可以在一个平台上进行开发,然后部署到另一个平台,而无需更改代码。 只需引用相同的 NuGet 软件包,并在所有环境中使用相同的 API 方法即可。 该库可跨平台自动处理 URL 渲染、HTML 转换和二进制数据处理。

How to Retrieve PDF File from Database in ASP.NET Using C# and IronPDF:图像 9 - 跨平台兼容性

最佳实践和性能注意事项

为确保从数据库中检索 PDF 文档时获得最佳性能,请遵循以下基本做法。 本文建议实施适当的错误处理和资源管理:

连接字符串管理:在 appsettings.json 中存储连接字符串,并通过依赖注入访问它们。 这样既能避免代码中出现敏感细节,又能轻松进行特定环境配置。 切勿在源代码中硬编码数据库连接字符串或许可证密钥信息。

资源处置SqlConnectionPdfDocument 都实现了 IDisposable。 始终使用 using 语句,以确保在大流量 .NET 应用程序中正确清理资源并防止内存泄漏。 在处理多个上传文件或向多个用户提供 PDF 时,这一点至关重要。

异步操作:对所有数据库操作使用 async/await 模式,以防止阻塞线程。 这可以提高应用程序的可扩展性和响应能力,尤其是在处理多个并发 PDF 请求时。 系统可以在等待数据库操作完成的同时处理其他请求。

错误处理:始终用 try-catch 块封装您的代码,以便优雅地处理异常。 记录错误细节以便调试,并在出现问题时返回适当的 HTTP 状态代码以通知用户。

文件类型验证:当用户上传 PDF 文件时,请在处理前验证文件类型和大小。 这样可以防止出现文件损坏的问题,并保护您的服务器免受恶意上传的影响。

结论

使用 IronPDF for .NET 在 ASP.NET Core 中从数据库中检索 PDF 文件变得非常简单。 通过利用其 Chrome 渲染引擎和直观的 API,您可以用最少的代码处理复杂的 PDF 操作,同时保持专业品质的输出。 该库与 ADO.NET 和 ASP.NET Core 的响应处理无缝集成,使其成为需要可靠 PDF 文档管理的企业级 .NET 应用程序的理想选择。

无论您是要构建一个文档归档系统,还是需要在 ASP.NET C# 应用程序中显示 PDF 流,或是创建从数据库中下载文件的功能,IronPDF for .NET 都能为您提供高效检索 PDF 文档的所有工具。 本文中演示的以下命名空间和代码示例展示了如何进行翻译:

  • 以字节数组形式存储和检索 PDF 格式文件
  • 在上传按钮事件中处理 object sender EventArgs e
  • 在浏览器中显示 PDF 内容或触发下载
  • 使用查询字符串参数链接特定文档
  • 在页面上填写水印和注释
  • 编写安全代码,防止 SQL 注入
  • 为生产系统创建强大的错误处理功能

立即开始使用 IronPDF 的免费试用版,体验它如何改变您的 ASP.NET Core 和 .NET Framework 应用程序中的 PDF 处理方式。 有了全面的文档和专门的支持,您就可以在一次冲刺中将 PDF 检索系统投入生产运行。 请访问我们的文档页面,了解更多示例和详细的 API 参考资料。

!a href="/static-assets/pdf/blog/retrieve-pdf-file-from-database-apr-net/retrieve-pdf-file-from-database-apr-net-10.webp">How to Retrieve PDF File from Database in ASP.NET Using C# and IronPDF:图像 10 - 许可

常见问题解答

什么是IronPDF?

IronPDF for .NET 是一个 .NET 库,允许开发人员在 C# 应用程序中创建、编辑和提取 PDF 文件中的内容。

如何使用 ASP.NET 从数据库中检索 PDF 文件?

要在 ASP.NET 中从数据库检索 PDF 文件,可以使用 C# 代码查询数据库并将 PDF 数据读入字节数组。然后,这个字节数组就可以与 IronPDF 一起使用,根据需要渲染或处理 PDF。

为什么要使用 IronPDF 在 ASP.NET 应用程序中处理 PDF?

IronPDF 为处理 PDF 提供了一套强大的功能,包括 PDF 生成、HTML 转换和操作。它可与 ASP.NET 无缝集成,并提供易于使用的 API 来处理 PDF。

在 ASP.NET 中使用 IronPDF 的前提条件是什么?

要在 ASP.NET 中使用 IronPDF,您需要设置一个 .NET 开发环境(如 Visual Studio),并通过 NuGet 包管理器在项目中包含 IronPDF 库。

IronPDF 可用于编辑现有的 PDF 文件吗?

是的,IronPDF 可用于编辑现有的 PDF 文件。它允许进行修改,如添加文本或图像、合并文档等。

是否可以用 IronPDF 将 HTML 转换为 PDF?

是的,IronPDF 可以将 HTML 内容直接转换为 PDF 格式,从而轻松地从网页或其他 HTML 内容生成 PDF。

如何使用 IronPDF 处理 PDF 安全功能?

IronPDF 支持 PDF 的各种安全功能,包括密码保护和设置权限以控制文档的访问和编辑。

IronPDF 兼容哪些类型的数据库进行 PDF 检索?

IronPdf 可以与任何可以存储二进制数据的数据库(如 SQL Server、MySQL 或 PostgreSQL)配合使用,以检索和处理 PDF 文件。

Curtis Chau
技术作家

Curtis Chau 拥有卡尔顿大学的计算机科学学士学位,专注于前端开发,精通 Node.js、TypeScript、JavaScript 和 React。他热衷于打造直观且美观的用户界面,喜欢使用现代框架并创建结构良好、视觉吸引力强的手册。

除了开发之外,Curtis 对物联网 (IoT) 有浓厚的兴趣,探索将硬件和软件集成的新方法。在空闲时间,他喜欢玩游戏和构建 Discord 机器人,将他对技术的热爱与创造力相结合。