如何在ASP.NET中使用C#從資料庫中檢索PDF文件
使用 C# 從 ASP.NET 資料庫中檢索 PDF 檔案需要三個步驟:查詢資料庫表中的二進位 BLOB 列,使用IronPDF將位元組載入到 PdfDocument 物件中,並透過 @@--CODE-26982--@@ 或 @@--CODE-26983--@@ 回應將位元組傳回給瀏覽器。 IronPDF 負責渲染、浮水印和安全功能,讓您可以專注於資料存取邏輯。
如何為 ASP.NET 安裝 IronPDF?
在編寫任何 PDF 取得程式碼之前,請透過 NuGet 套件管理器將 IronPDF 新增至您的專案:
Install-Package IronPdf
dotnet add package IronPdf
Install-Package IronPdf
dotnet add package IronPdf
安裝完成後,請在呼叫任何 IronPDF 方法之前,在 Program.cs 或 appsettings.json 中設定您的許可證金鑰:
IronPdf.License.LicenseKey = "YOUR-LICENSE-KEY";
IronPdf.License.LicenseKey = "YOUR-LICENSE-KEY";
IronPdf.License.LicenseKey = "YOUR-LICENSE-KEY"
IronPDF 支援.NET 10 、.NET 8、.NET 6 和 .NET Framework 4.6.2+。 它可在 Windows、Linux 和 macOS 上運行,無需任何額外的依賴項或無頭瀏覽器安裝。 提供免費試用許可證供評估。
如何設定 SQL Server 資料庫表?
最常見的方法是將 PDF 檔案作為二進位資料儲存在 SQL Server 的 VARBINARY(MAX) 列中。 這樣可以將文件及其元資料保存在單一表中,簡化備份,並避免文件系統路徑管理。
使用以下 SQL 腳本建立儲存表:
// SQL Server table definition (run this in SSMS or via EF migrations)
// CREATE TABLE PdfDocuments (
// ID INT 身份(1,1) PRIMARY KEY,
// 檔案名稱 NVARCHAR(255) NOT NULL,
// 文件內容 VARBINARY(MAX) NOT NULL,
// 上傳於 日期時間2 DEFAULT GETUTCDATE()
// );
// SQL Server table definition (run this in SSMS or via EF migrations)
// CREATE TABLE PdfDocuments (
// ID INT 身份(1,1) PRIMARY KEY,
// 檔案名稱 NVARCHAR(255) NOT NULL,
// 文件內容 VARBINARY(MAX) NOT NULL,
// 上傳於 日期時間2 DEFAULT GETUTCDATE()
// );
表格建立完成後,請在 appsettings.json 中設定連接字串:
// appsettings.json snippet (not C# -- shown as reference)
// "ConnectionStrings": {
// "DefaultConnection": "Server=localhost;Database=PdfStorage;Integrated Security=True;"
// }
// appsettings.json snippet (not C# -- shown as reference)
// "ConnectionStrings": {
// "DefaultConnection": "Server=localhost;Database=PdfStorage;Integrated Security=True;"
// }
' appsettings.json snippet (not VB.NET -- shown as reference)
' "ConnectionStrings": {
' "DefaultConnection": "Server=localhost;Database=PdfStorage;Integrated Security=True;"
' }
在 Program.cs 中透過依賴注入註冊連接字串:
using Microsoft.Extensions.DependencyInjection;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers();
builder.Services.AddSingleton<IConfiguration>(builder.Configuration);
IronPdf.License.LicenseKey = builder.Configuration["IronPdf:LicenseKey"];
var app = builder.Build();
app.MapControllers();
app.Run();
using Microsoft.Extensions.DependencyInjection;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers();
builder.Services.AddSingleton<IConfiguration>(builder.Configuration);
IronPdf.License.LicenseKey = builder.Configuration["IronPdf:LicenseKey"];
var app = builder.Build();
app.MapControllers();
app.Run();
Imports Microsoft.Extensions.DependencyInjection
Dim builder = WebApplication.CreateBuilder(args)
builder.Services.AddControllers()
builder.Services.AddSingleton(Of IConfiguration)(builder.Configuration)
IronPdf.License.LicenseKey = builder.Configuration("IronPdf:LicenseKey")
Dim app = builder.Build()
app.MapControllers()
app.Run()
如何在 ASP.NET Core 中從 SQL Server 檢索 PDF 檔案?
檢索模式遵循三個步驟:開啟連接,執行參數化的 SELECT 查詢,並將二進位列讀取到 byte[]。 IronPDF 接著將該陣列載入PdfDocument物件中,以便在串流傳輸到客戶端之前進行可選處理。
建置 API 控制器
建立一個控制器,該控制器公開用於內嵌顯示和檔案下載的 GET 端點:
using IronPdf;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Data.SqlClient;
[ApiController]
[Route("api/[controller]")]
public class PdfController : ControllerBase
{
private readonly string _connectionString;
public PdfController(IConfiguration configuration)
{
_connectionString = configuration.GetConnectionString("DefaultConnection")
?? throw new InvalidOperationException("Connection string not found.");
}
[HttpGet("{id}")]
public async Task<IActionResult> GetPdf(int id)
{
byte[] pdfBytes = await RetrievePdfBytesAsync(id);
if (pdfBytes is null || pdfBytes.Length == 0)
return NotFound("PDF document not found.");
// Load into IronPDF for validation or optional modification
using var pdfDocument = new PdfDocument(pdfBytes);
// Inline display -- browser opens PDF viewer
Response.Headers.Append("Content-Disposition", "inline; filename=\"document.pdf\"");
return File(pdfDocument.BinaryData, "application/pdf");
}
private async Task<byte[]> RetrievePdfBytesAsync(int documentID)
{
await using var connection = new SqlConnection(_connectionString);
await connection.OpenAsync();
const string query = "SELECT 文件內容 FROM PdfDocuments WHERE ID = @ID";
await using var command = new SqlCommand(query, connection);
command.Parameters.AddWithValue("@ID", documentID);
var result = await command.ExecuteScalarAsync();
return result as byte[] ?? Array.Empty<byte>();
}
}
using IronPdf;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Data.SqlClient;
[ApiController]
[Route("api/[controller]")]
public class PdfController : ControllerBase
{
private readonly string _connectionString;
public PdfController(IConfiguration configuration)
{
_connectionString = configuration.GetConnectionString("DefaultConnection")
?? throw new InvalidOperationException("Connection string not found.");
}
[HttpGet("{id}")]
public async Task<IActionResult> GetPdf(int id)
{
byte[] pdfBytes = await RetrievePdfBytesAsync(id);
if (pdfBytes is null || pdfBytes.Length == 0)
return NotFound("PDF document not found.");
// Load into IronPDF for validation or optional modification
using var pdfDocument = new PdfDocument(pdfBytes);
// Inline display -- browser opens PDF viewer
Response.Headers.Append("Content-Disposition", "inline; filename=\"document.pdf\"");
return File(pdfDocument.BinaryData, "application/pdf");
}
private async Task<byte[]> RetrievePdfBytesAsync(int documentID)
{
await using var connection = new SqlConnection(_connectionString);
await connection.OpenAsync();
const string query = "SELECT 文件內容 FROM PdfDocuments WHERE ID = @ID";
await using var command = new SqlCommand(query, connection);
command.Parameters.AddWithValue("@ID", documentID);
var result = await command.ExecuteScalarAsync();
return result as byte[] ?? Array.Empty<byte>();
}
}
Imports IronPdf
Imports Microsoft.AspNetCore.Mvc
Imports Microsoft.Data.SqlClient
<ApiController>
<Route("api/[controller]")>
Public Class PdfController
Inherits ControllerBase
Private ReadOnly _connectionString As String
Public Sub New(configuration As IConfiguration)
_connectionString = configuration.GetConnectionString("DefaultConnection")
If _connectionString Is Nothing Then
Throw New InvalidOperationException("Connection string not found.")
End If
End Sub
<HttpGet("{id}")>
Public Async Function GetPdf(id As Integer) As Task(Of IActionResult)
Dim pdfBytes As Byte() = Await RetrievePdfBytesAsync(id)
If pdfBytes Is Nothing OrElse pdfBytes.Length = 0 Then
Return NotFound("PDF document not found.")
End If
' Load into IronPDF for validation or optional modification
Using pdfDocument As New PdfDocument(pdfBytes)
' Inline display -- browser opens PDF viewer
Response.Headers.Append("Content-Disposition", "inline; filename=""document.pdf""")
Return File(pdfDocument.BinaryData, "application/pdf")
End Using
End Function
Private Async Function RetrievePdfBytesAsync(documentID As Integer) As Task(Of Byte())
Await Using connection As New SqlConnection(_connectionString)
Await connection.OpenAsync()
Const query As String = "SELECT 文件內容 FROM PdfDocuments WHERE ID = @ID"
Await Using command As New SqlCommand(query, connection)
command.Parameters.AddWithValue("@ID", documentID)
Dim result = Await command.ExecuteScalarAsync()
Return If(TryCast(result, Byte()), Array.Empty(Of Byte)())
End Using
End Using
End Function
End Class
此控制器使用參數化查詢來防止 SQL 注入,並正確釋放 await using 和 SqlConnection 和 SqlCommand 。 PdfDocument 類別驗證位元組數組,並公開 BinaryData 屬性以進行串流傳輸。
傳回一個可供下載的指定文件
當使用者需要儲存文件而不是線上檢視時,請將 Content-Disposition 標頭設定為 attachment 並傳遞原始檔案名稱:
[HttpGet("download/{id}")]
public async Task<IActionResult> DownloadPdf(int id)
{
await using var connection = new SqlConnection(_connectionString);
await connection.OpenAsync();
const string query = "SELECT 檔案名稱, 文件內容 FROM PdfDocuments WHERE ID = @ID";
await using var command = new SqlCommand(query, connection);
command.Parameters.AddWithValue("@ID", documentID);
await using var reader = await command.ExecuteReaderAsync();
if (!await reader.ReadAsync())
return NotFound("Document not found.");
var fileName = reader.GetString(reader.GetOrdinal("檔案名稱"));
var pdfBytes = (byte[])reader["文件內容"];
using var pdfDocument = new PdfDocument(pdfBytes);
return File(pdfDocument.BinaryData, "application/pdf", fileName);
}
[HttpGet("download/{id}")]
public async Task<IActionResult> DownloadPdf(int id)
{
await using var connection = new SqlConnection(_connectionString);
await connection.OpenAsync();
const string query = "SELECT 檔案名稱, 文件內容 FROM PdfDocuments WHERE ID = @ID";
await using var command = new SqlCommand(query, connection);
command.Parameters.AddWithValue("@ID", documentID);
await using var reader = await command.ExecuteReaderAsync();
if (!await reader.ReadAsync())
return NotFound("Document not found.");
var fileName = reader.GetString(reader.GetOrdinal("檔案名稱"));
var pdfBytes = (byte[])reader["文件內容"];
using var pdfDocument = new PdfDocument(pdfBytes);
return File(pdfDocument.BinaryData, "application/pdf", fileName);
}
Imports System.Data.SqlClient
Imports Microsoft.AspNetCore.Mvc
<HttpGet("download/{id}")>
Public Async Function DownloadPdf(id As Integer) As Task(Of IActionResult)
Await Using connection As New SqlConnection(_connectionString)
Await connection.OpenAsync()
Const query As String = "SELECT 檔案名稱, 文件內容 FROM PdfDocuments WHERE ID = @ID"
Await Using command As New SqlCommand(query, connection)
command.Parameters.AddWithValue("@ID", id)
Await Using reader As SqlDataReader = Await command.ExecuteReaderAsync()
If Not Await reader.ReadAsync() Then
Return NotFound("Document not found.")
End If
Dim fileName As String = reader.GetString(reader.GetOrdinal("檔案名稱"))
Dim pdfBytes As Byte() = CType(reader("文件內容"), Byte())
Using pdfDocument As New PdfDocument(pdfBytes)
Return File(pdfDocument.BinaryData, "application/pdf", fileName)
End Using
End Using
End Using
End Using
End Function
將 fileName 作為 File() 的第三個參數傳遞給 Content-Disposition 會自動將 attachment 標頭設為 @@--CODE-27000--@@。 ASP.NET Core 可以正確處理包含空格的檔名。
如何為下載的PDF檔案添加浮水印?
檢索後最實用的操作之一是在提供文件之前,在每一頁上添加浮水印。 這對於機密報告、文件草稿或任何需要明顯安全標記的文件都很有用。
使用 IronPDF 應用 HTML 浮水印
IronPDF 的浮水印 API 接受任何 HTML 字串,這表示您可以使用內聯 CSS 設定浮水印文字的樣式。 將透明度調低,使底層內容仍清晰可讀:
[HttpGet("watermarked/{id}")]
public async Task<IActionResult> GetWatermarkedPdf(int id)
{
byte[] pdfBytes = await RetrievePdfBytesAsync(id);
if (pdfBytes is null || pdfBytes.Length == 0)
return NotFound("PDF document not found.");
using var pdfDocument = new PdfDocument(pdfBytes);
// HTML watermark applied to every page
string watermarkHtml = "<h2 style='color:red; opacity:0.4; font-family:Arial;'>CONFIDENTIAL</h2>";
pdfDocument.ApplyWatermark(
watermarkHtml,
rotation: 30,
verticalAlignment: VerticalAlignment.Middle,
horizontalAlignment: HorizontalAlignment.Center
);
return File(pdfDocument.BinaryData, "application/pdf");
}
[HttpGet("watermarked/{id}")]
public async Task<IActionResult> GetWatermarkedPdf(int id)
{
byte[] pdfBytes = await RetrievePdfBytesAsync(id);
if (pdfBytes is null || pdfBytes.Length == 0)
return NotFound("PDF document not found.");
using var pdfDocument = new PdfDocument(pdfBytes);
// HTML watermark applied to every page
string watermarkHtml = "<h2 style='color:red; opacity:0.4; font-family:Arial;'>CONFIDENTIAL</h2>";
pdfDocument.ApplyWatermark(
watermarkHtml,
rotation: 30,
verticalAlignment: VerticalAlignment.Middle,
horizontalAlignment: HorizontalAlignment.Center
);
return File(pdfDocument.BinaryData, "application/pdf");
}
Imports Microsoft.AspNetCore.Mvc
<HttpGet("watermarked/{id}")>
Public Async Function GetWatermarkedPdf(id As Integer) As Task(Of IActionResult)
Dim pdfBytes As Byte() = Await RetrievePdfBytesAsync(id)
If pdfBytes Is Nothing OrElse pdfBytes.Length = 0 Then
Return NotFound("PDF document not found.")
End If
Using pdfDocument As New PdfDocument(pdfBytes)
' HTML watermark applied to every page
Dim watermarkHtml As String = "<h2 style='color:red; opacity:0.4; font-family:Arial;'>CONFIDENTIAL</h2>"
pdfDocument.ApplyWatermark(
watermarkHtml,
rotation:=30,
verticalAlignment:=VerticalAlignment.Middle,
horizontalAlignment:=HorizontalAlignment.Center
)
Return File(pdfDocument.BinaryData, "application/pdf")
End Using
End Function
ApplyWatermark方法接受標準 HTML 和 CSS,因此您可以完全控製字體、顏色、不透明度和位置。 浮水印會自動套用於文件中的所有頁面。 有關PDF 的其他操作功能,包括新增影像印章、新增頁首和頁尾或合併多個文檔,請參閱 IronPDF 文件。
如何將上傳的PDF檔案儲存回SQL Server?
完成往返流程需要一個上傳端點,該端點讀取傳入的表單檔案並將其寫入資料庫。 這與上述檢索端點配合使用,構成了一個完整的文件管理系統:
[HttpPost("upload")]
public async Task<IActionResult> UploadPdf(IFormFile file)
{
if (file is null || file.Length == 0)
return BadRequest("No file uploaded.");
if (!file.內容類型.Equals("application/pdf", StringComparison.OrdinalIgnoreCase))
return BadRequest("Only PDF files are accepted.");
using var memoryStream = new MemoryStream();
await file.CopyToAsync(memoryStream);
byte[] pdfBytes = memoryStream.ToArray();
// Validate using IronPDF before storage
using var pdfDocument = new PdfDocument(pdfBytes);
await using var connection = new SqlConnection(_connectionString);
await connection.OpenAsync();
const string insertQuery = @"
INSERT INTO PdfDocuments (檔案名稱, 文件內容)
VALUES (@檔案名稱, @文件內容);
SELECT SCOPE_IDENTITY();";
await using var command = new SqlCommand(insertQuery, connection);
command.Parameters.AddWithValue("@檔案名稱", file.檔案名稱);
command.Parameters.AddWithValue("@文件內容", pdfDocument.BinaryData);
var newID = Convert.ToInt32(await command.ExecuteScalarAsync());
return Ok(new { id = newID, fileName = file.檔案名稱 });
}
[HttpPost("upload")]
public async Task<IActionResult> UploadPdf(IFormFile file)
{
if (file is null || file.Length == 0)
return BadRequest("No file uploaded.");
if (!file.內容類型.Equals("application/pdf", StringComparison.OrdinalIgnoreCase))
return BadRequest("Only PDF files are accepted.");
using var memoryStream = new MemoryStream();
await file.CopyToAsync(memoryStream);
byte[] pdfBytes = memoryStream.ToArray();
// Validate using IronPDF before storage
using var pdfDocument = new PdfDocument(pdfBytes);
await using var connection = new SqlConnection(_connectionString);
await connection.OpenAsync();
const string insertQuery = @"
INSERT INTO PdfDocuments (檔案名稱, 文件內容)
VALUES (@檔案名稱, @文件內容);
SELECT SCOPE_IDENTITY();";
await using var command = new SqlCommand(insertQuery, connection);
command.Parameters.AddWithValue("@檔案名稱", file.檔案名稱);
command.Parameters.AddWithValue("@文件內容", pdfDocument.BinaryData);
var newID = Convert.ToInt32(await command.ExecuteScalarAsync());
return Ok(new { id = newID, fileName = file.檔案名稱 });
}
Imports System
Imports System.IO
Imports System.Threading.Tasks
Imports Microsoft.AspNetCore.Http
Imports Microsoft.AspNetCore.Mvc
Imports System.Data.SqlClient
Imports IronPdf
<HttpPost("upload")>
Public Async Function UploadPdf(file As IFormFile) As Task(Of IActionResult)
If file Is Nothing OrElse file.Length = 0 Then
Return BadRequest("No file uploaded.")
End If
If Not file.ContentType.Equals("application/pdf", StringComparison.OrdinalIgnoreCase) Then
Return BadRequest("Only PDF files are accepted.")
End If
Using memoryStream As New MemoryStream()
Await file.CopyToAsync(memoryStream)
Dim pdfBytes As Byte() = memoryStream.ToArray()
' Validate using IronPDF before storage
Using pdfDocument As New PdfDocument(pdfBytes)
Await Using connection As New SqlConnection(_connectionString)
Await connection.OpenAsync()
Const insertQuery As String = "
INSERT INTO PdfDocuments (檔案名稱, 文件內容)
VALUES (@檔案名稱, @文件內容);
SELECT SCOPE_IDENTITY();"
Await Using command As New SqlCommand(insertQuery, connection)
command.Parameters.AddWithValue("@檔案名稱", file.FileName)
command.Parameters.AddWithValue("@文件內容", pdfDocument.BinaryData)
Dim newID As Integer = Convert.ToInt32(Await command.ExecuteScalarAsync())
Return Ok(New With {.id = newID, .fileName = file.FileName})
End Using
End Using
End Using
End Using
End Function
使用 PdfDocument 在儲存之前進行驗證,可確保只有可解析、格式良好的 PDF 檔案才能進入資料庫。 如果位元組數組損壞或截斷,IronPDF 會拋出異常,您可以捕獲該異常並將其作為 400 Bad Request 回應傳回。
PDF 儲存的關鍵表和列類型有哪些?
你使用的模式會影響查詢效能和儲存效率。 下表顯示了 SQL Server 的建議列配置:
| 列 | 資料類型 | 目的 |
|---|---|---|
| ID | INT 身份 | 主鍵,自動遞增 |
| 檔案名稱 | NVARCHAR(255) | 下載頭檔的原始檔名 |
| 文件內容 | VARBINARY(MAX) | 原始PDF二進位資料(BLOB) |
| 內容類型 | NVARCHAR(100) | MIME 類型,例如 application/pdf |
| 檔案大小(位元組) | 大情報 | 用於配額管理的儲存大小 |
| 上傳於 | 日期時間2 | 用於審計的UTC時間戳 |
| 上傳者 | NVARCHAR(100) | 用於存取控制的使用者身份 |
對於需要 SQL Server 檔案流的大型系統,Microsoft 將FILESTREAM 功能作為替代方案記錄下來,該功能將大型 BLOB 儲存在檔案系統中,同時仍可透過 T-SQL 進行查詢。 然而,對於大多數提供數百兆位元組以下文件的 ASP.NET 應用程式來說,行內儲存效果很好,並且簡化了部署。
如何處理錯誤並優化效能?
生產環境中可靠的 PDF 檢索需要在每個層面進行錯誤處理—資料庫、IronPDF 和 HTTP 回應。 下表總結了關鍵做法:
| 憂慮 | 推薦 | 原因 |
|---|---|---|
| 連接處置 | await using語句 |
防止連接池耗盡 |
| PDF文件處理 | using語句 |
及時釋放未管理的記憶體 |
| SQL注入 | 僅限參數化查詢 | 防止惡意輸入篡改查詢 |
| 文件類型驗證 | 檢查 MIME 類型和魔數字節 | 儲存前阻止非 PDF 檔案的上傳 |
| 大檔案處理 | 使用FileStreamResult流回應 |
避免將整個檔案載入到伺服器記憶體中 |
| 快取 | 使用IMemoryCache或IDistributedCache |
減少重複的資料庫往返次數 |
| 非同步操作 | async / await過程 |
在磁碟和網路等待期間保持線程空閒。 |
對於連接字串管理,請將值儲存在 appsettings.json 中,切勿將其硬編碼到來源檔案中。 在本機開發期間使用 ASP.NET Core內建的金鑰管理,在生產環境中使用 Azure Key Vault 或 AWS Secrets Manager。 切勿將連接字串或許可證金鑰提交到原始碼控制系統中。
在提供大型 PDF 檔案時,請考慮傳回由 @@--CODE-27007--@@ 支援的 @@--CODE-27006--@@,而不是將整個位元組陣列載入記憶體。 對於超過 100 MB 的大型文檔, SQL Server FILESTREAM API可以直接從文件系統進行分塊串流傳輸。
快取常用文檔
如果重複要求某些 PDF 文件(例如條款和條件文件或產品目錄),則將位元組數組快取到 IMemoryCache 中可以避免重複的資料庫往返。 在 IMemoryCache 中註冊 Program.cs,並將其註入到 builder.Services.AddMemoryCache() 中,然後將其註入到控制器中,並在查詢資料庫之前檢查快取。 設定一個與文件預期更新頻率相符的絕對過期時間。 當文件更新時,按鍵刪除快取條目,以便下次請求取得新版本。
對於分散式場景(例如具有多個伺服器執行個體的負載平衡部署),請將 IMemoryCache 替換為 IDistributedCache,並由 Redis 或 SQL Server 提供支援。 ASP.NET Core 的分散式快取抽象化使控制器程式碼幾乎保持不變; 僅 Program.cs 中的註冊資訊已變更。
如何使用 IronPDF 實現跨平台 PDF 檢索?
IronPDF 可在 Linux、Windows 和 macOS 上運行,無需單獨安裝 Chromium 或進行任何配置變更。 同一個 NuGet 套件適用於所有平台,因此無論您部署到哪個平台,您的 PDF 控制器都能正常運作:
- 帶有 IIS 的 Windows Server
- 在 Docker 或 Kubernetes 上執行的 Ubuntu 容器
- Azure 應用程式服務(Linux 或 Windows)
- AWS Elastic Beanstalk
部署到 Docker 和 Linux
對於 Docker 部署,請將 IronPDF 依賴項新增至 Dockerfile 中。 IronPDF Linux 文件提供了 Debian 和 Alpine 基礎鏡像所需的確切 apt 軟體包。 典型的多階段 Dockerfile 會在運行時鏡像階段安裝作業系統依賴項,然後將已發布的 ASP.NET 應用程式複製到其上。使用 Azure 時, Azure 部署指南涵蓋了應用程式服務配置,包括支援大規模 PDF 渲染的記憶體和 CPU 設定。
由於 IronPDF 捆綁了自己的基於 Chromium 的渲染引擎,因此您無需在伺服器上安裝單獨的瀏覽器。 與需要係統級瀏覽器的解決方案相比,這大大簡化了 Linux 容器的設定。 IronPDF 團隊每次發布新版本都會針對最常見的 Linux 基礎鏡像進行測試,因此您可以放心,Alpine 或 Debian 容器可以開箱即用。
使用 Entity Framework Core 而非 ADO.NET
IronPDF 也整合了Entity Framework Core ,作為原始 ADO.NET 的替代方案。 如果您的專案已經使用 EF Core,您可以將 文件內容 列對應到模型類別上的 byte[] 屬性,並讓 EF 處理查詢產生。 這種方法可以顯著減少樣板程式碼,並且可以透過 EF 的 LINQ 提供者更輕鬆地添加篩選、分頁和稽核行為。
這樣做的代價是,EF Core 會將整個 BLOB 作為實體圖的一部分載入到記憶體中。 對於非常大的 PDF 文件,請考慮使用原始 ADO.NET 或 EF Core 的 FromSql 方法,並進行投影,僅選擇位元組數組列而不是整個實體。
下一步計劃是什麼?
在 ASP.NET Core 中使用 C# 和 IronPDF 從 SQL Server 資料庫中擷取 PDF 檔案遵循一個清晰的模式:使用參數化的 SELECT 查詢 BLOB 列,將位元組載入到 PdfDocument 中,並傳回具有正確 Content-Disposition@ 資料標頭的二進位資料。 IronPDF 增加了在文件離開伺服器之前對其進行驗證、添加浮水印、合併或保護的功能。
若要進一步了解 IronPDF 的文件管理功能,請探索以下資源:
IronPDF 從 HTML 生成 PDF——動態生成 PDF 並將其直接儲存到您的資料庫中 IronPDF 合併和分割 PDF-將檢索到的文件合併成單一回應
- IronPDF 安全性與權限-在提供敏感文件之前新增密碼保護 IronPDF HTML 轉 PDF 教學-將網頁內容轉換為 PDF 以便存檔
- IronPDF PDF 加蓋印章-- 將文字和圖像印章套用至擷取的文件
- IronPDF 許可-查看開發、測試和生產用途的許可級別
首先取得IronPDF 的免費試用許可證,即可不受限制地測試所有功能。 該試驗產生帶有浮水印的輸出; 使用付費許可證金鑰即可移除浮水印。 本文中使用的每種方法的完整API 參考文件和程式碼範例均可在 IronPDF 網站上找到。
如果您的專案已在使用 Entity Framework Core, IronPDF EF Core 整合指南將展示如何在保持 IronPDF 處理管道不變的情況下,以實體模型取代原始 ADO.NET。對於使用 .NET 10 和最新 ASP.NET Core 功能的團隊,此處描述的模式無需修改即可使用——IronPDF 支援所有活躍的 .NET LTS 和 STS 版本。
請查看IronPDF 定價頁面,找到適合您部署的授權等級。 單一開發者許可證涵蓋本地開發和測試; SaaS 產品和具有多個伺服器的本地部署均可獲得再分發授權。
常見問題解答
什麼是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 檔案。



