跳過到頁腳內容
使用IRONPDF

如何使用 C# 和 IronPDF for .NET 在 ASP.NET 中從資料庫擷取 PDF 檔案

如何在 ASP.NET 中使用 C# 和 IronPDF 從資料庫中擷取 PDF 檔案:圖 5 - 輸出

檢索並顯示PDF文檔

將 PDF 檔案儲存到資料庫後,下一步是在 Web 瀏覽器中檢索和顯示它們。 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

此方法根據文件 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 與 ASP.NET Core 結合使用,讓開發人員可以輕鬆地在 SQL Server 資料庫中管理 PDF 檔案。 從儲存、檢索到顯示 PDF 文件,IronPDF 利用其強大的 Chrome 渲染引擎,處理 PDF 操作的各個方面。本教學課程示範如何將 IronPDF 整合到 ASP.NET Core 應用程式中,以有效地處理 PDF 文檔,無論這些文檔是上傳的、從 HTML 產生的,還是檢索後用於顯示的。

有關 IronPDF 的功能和許可的更多信息,請訪問IronPDF 官方網站

如何在 ASP.NET 中使用 C# 和 IronPDF 從資料庫中擷取 PDF 檔案:圖 5 - Web 輸出

如何在 ASP.NET 中使用 C# 和 IronPDF 從資料庫中擷取 PDF 檔案:圖 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: true File()方法可確保 PDF 直接在瀏覽器中顯示,而不是觸發下載,從而解決了使用 C# 在 ASP.NET 中從資料庫檢索 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

透過將 filename 參數傳遞給File()方法並將 content disposition 設為"attachment",ASP.NET Core 會提示瀏覽器將 PDF 儲存到使用者的預設下載資料夾。

輸出

如何在 ASP.NET 中使用 C# 和 IronPDF 從資料庫中擷取 PDF 檔案:圖 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 並新增安全標記時,此功能尤其有用。 對於更進階的浮水印技術,開發人員通常會參考微軟關於 PDF 安全性的文件

如何在 ASP.NET 中使用 C# 和 IronPDF 從資料庫中擷取 PDF 檔案:圖 8 - 如何在 ASP.NET 中使用 C# 從資料庫擷取 PDF 檔案 - IronPDF

跨平台部署

IronPDF 的架構確保您的 PDF 檢索系統在不同平台上都能穩定運作。 無論部署到 Windows 伺服器、Linux 容器,或是 Azure 和 AWS 等雲端平台,相同的程式碼無需修改即可運作。 該庫在內部處理特定於平台的渲染細節,使其成為使用 Docker 或 Kubernetes 的現代容器化部署的理想選擇。

當您建立需要從資料庫表中檢索 PDF 文件的 .NET 應用程式時,IronPDF 的跨平台支援意味著您可以在一個平台上進行開發,然後部署到另一個平台,而無需更改您的程式碼。 只需在所有環境中引用同一個 NuGet 套件並使用相同的 API 方法。 該程式庫能夠自動處理跨平台一致的 URL 渲染、HTML 轉換和二進位資料處理。

如何在 ASP.NET 中使用 C# 和 IronPDF 從資料庫中擷取 PDF 檔案:圖 9 - 跨平台相容性

最佳實踐和性能考量

為確保從資料庫中檢索 PDF 文件時獲得最佳效能,請遵循以下基本做法。 本文建議實施適當的錯誤處理和資源管理:

連接字串管理:將連接字串儲存在appsettings.json中,並透過依賴注入存取它們。 這樣可以避免敏感資訊洩漏到程式碼中,並方便進行特定環境的配置。 切勿將資料庫連接字串或許可證密鑰資訊硬編碼到原始程式碼中。

資源釋放SqlConnectionPdfDocument都實作了IDisposable 。 在高流量的 .NET 應用程式中,務必使用using語句來確保資源正確清理,並防止記憶體洩漏。 當處理多個上傳文件或向多個使用者提供 PDF 文件時,這一點至關重要。

非同步操作:對所有資料庫操作使用async / await模式,以防止阻塞執行緒。 這可以提高應用程式的可擴展性和回應能力,尤其是在處理多個並發 PDF 請求時。 系統可以在等待資料庫操作完成的同時處理其他請求。

錯誤處理:始終將程式碼放在try-catch區塊中,以便優雅地處理異常。 記錄錯誤詳情以便偵錯,並在出現問題時傳回對應的 HTTP 狀態碼以通知使用者。

文件類型驗證:當使用者上傳 PDF 文件時,在處理之前驗證文件類型和大小。 這可以防止檔案損壞問題,並保護您的伺服器免受惡意上傳的侵害。

結論

使用 IronPDF 從 ASP.NET Core 資料庫中擷取 PDF 檔案變得異常簡單。 利用其 Chrome 渲染引擎和直覺的 API,您可以用最少的程式碼處理複雜的 PDF 操作,同時保持專業品質的輸出。 該程式庫與 ADO.NET 和 ASP.NET Core 的回應處理無縫集成,使其成為需要可靠的 PDF 文件管理的企業級 .NET 應用程式的理想選擇。

無論您是建立文件歸檔系統、需要在 ASP.NET C# 應用程式中顯示 PDF 流,還是建立從資料庫下載文件的功能,IronPDF 都提供了高效檢索 PDF 文件所需的所有工具。 本文中示範的以下命名空間和程式碼範例展示如何:

  • 將PDF格式檔案儲存並檢索為位元組數組
  • 處理上傳按鈕事件中的object sender EventArgs e
  • 在瀏覽器中顯示 PDF 內容或觸發下載
  • 使用查詢字串參數連結特定文檔
  • 在頁面上新增浮水印和評論 編寫安全的程式碼,防止 SQL 注入
  • 為生產系統創建強大的錯誤處理機制

立即開始 IronPDF 的免費試用版,體驗它如何改變 ASP.NET Core 和 .NET Framework 應用程式中的 PDF 處理方式。 憑藉全面的文件和專門的支持,您的 PDF 檢索系統將在一個迭代周期內投入生產運作。 請造訪我們的文件頁面,查看更多範例和詳細的 API 參考。

如何在 ASP.NET 中使用 C# 和 IronPDF 從資料庫中擷取 PDF 檔案:圖 10 - 許可

常見問題解答

什麼是IronPDF?

IronPDF for .NET 是一個 .NET 函式庫,可讓開發人員在 C# 應用程式中建立、編輯 PDF 檔案,並從 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 熱衷於創建直觀且美觀的用戶界面,喜歡使用現代框架並打造結構良好、視覺吸引人的手冊。

除了開發之外,Curtis 對物聯網 (IoT) 有著濃厚的興趣,探索將硬體和軟體結合的創新方式。在閒暇時間,他喜愛遊戲並構建 Discord 機器人,結合科技與創意的樂趣。