跳至頁尾內容
使用IRONPDF
如何在ASP.NET | IronPDF中從資料庫顯示PDF

您如何在C# .NET中合併PDF文件?

要在ASP.NET中從資料庫顯示PDF,請檢索儲存的二進位資料,並使用IronPDF的PdfDocument類進行渲染,該類能有效處理位元組陣列,並提供具有自訂選項的瀏覽器相容輸出。

什麼是ASP.NET中的PDF資料庫顯示?

在ASP.NET應用程式中管理PDF文件通常涉及將PDF檔直接儲存在資料庫中而不是檔案系統中。 此方法提供了更好的安全性、集中備份和簡化的部署。 然而,從資料庫檢索和顯示PDF文件可能會很具有挑戰性,除非有適合的工具。

將PDF檔案以二進位資料形式儲存於資料庫表格中,允許更好地控制文件存取和版本控制。 當您需要向使用者顯示PDF文件時,必須高效地從資料庫檢索位元組陣列,並在瀏覽器中渲染它。 IronPDF簡化了這整個過程,通過有效的API處理ASP.NET應用程式中的PDF文件。

本教程演示了使用IronPDF的已驗證功能在ASP.NET中從資料庫顯示PDF的功能。 您將學習建立一個完整的解決方案來上傳、儲存和顯示PDF文件,以實現最佳性能和安全性。 該程式庫支持多種渲染選項和先進的PDF操作功能,使其易於構建生產級的文件管理系統。

如何在您的ASP.NET專案中安裝PDF程式庫?

在實現PDF顯示功能之前,確保您的ASP.NET專案已安裝IronPDF。 打開Visual Studio中的包管理控制台,並根據您的工具偏好運行以下命令之一:

Install-Package IronPdf

您也可以通過NuGet包管理員UI安裝IronPDF,在專案的瀏覽標籤中搜索IronPdf。 安裝後,在應用程式啟動時設置您的授權金鑰:

IronPdf.License.LicenseKey = "YOUR-LICENSE-KEY-HERE";
IronPdf.License.LicenseKey = "YOUR-LICENSE-KEY-HERE";
IronPdf.License.LicenseKey = "YOUR-LICENSE-KEY-HERE"
$vbLabelText   $csharpLabel

免費試用授權允許您在評估期間完全存取所有功能。 對於生產部署,請查看可用的授權級別,以找到適合您專案規模的選擇。

需要什麼樣的資料庫結構?

您的資料庫表格結構需要一個varbinary(max)列來將PDF文件儲存為二進位資料。 該表應包含元資料字段,如文件名、上傳日期和文件大小,以更好的管理文件。 以下SQL為此場景建立了合適的表:

using IronPdf;
using System.Data.SqlClient;
using System.IO;
using System.Configuration;
using IronPdf;
using System.Data.SqlClient;
using System.IO;
using System.Configuration;
Imports IronPdf
Imports System.Data.SqlClient
Imports System.IO
Imports System.Configuration
$vbLabelText   $csharpLabel

web.config文件中配置您的連接字串,以建立資料庫連接。 PDF查看器的實現將使用此連接從資料庫檢索上傳的檔案,並順利顯示PDF內容。

該解決方案需要什麼命名空間?

該解決方案使用標準的ADO.NET命名空間以及IronPDF命名空間。 您不需要任何第三方ORM——直接的ADO.NET方法保持依賴性最小,並讓您對查詢執行有完全掌控。 確保連接字串指向您的PDF儲存表所在的SQL Server實例。

如何為PDF建立資料庫表?

首先建立一個專為儲存PDF文件設計的資料庫表。 該表結構應容納二進位資料和管理PDF文件所需的基本元資料:

CREATE TABLE PdfDocuments (
    Id INT PRIMARY KEY IDENTITY(1,1),
    FileName NVARCHAR(255) NOT NULL,
    FileData VARBINARY(MAX) NOT NULL,
    ContentType NVARCHAR(100) DEFAULT 'application/pdf',
    FileSize INT,
    UploadDate DATETIME DEFAULT GETDATE(),
    CreatedBy NVARCHAR(100),
    LastModified DATETIME,
    DocumentVersion INT DEFAULT 1
);

此表將每個PDF文件儲存為FileData列中的位元組陣列。 varbinary(max)資料型別可以容納最多2GB的檔案,這對大多數PDF文件來說足夠了。 FileName字段保留顯示和下載用途的原始文件名。

如何提高PDF檢索的資料庫性能?

考慮在頻繁查詢的列上新增索引,以提高檢索PDF文件時的性能。 以下SQL在最有可能出現在WHERE和ORDER BY子句中的列上建立索引:

CREATE INDEX IX_PdfDocuments_UploadDate
ON PdfDocuments(UploadDate DESC);

CREATE INDEX IX_PdfDocuments_FileName
ON PdfDocuments(FileName);

此結構確保了上傳檔案的高效儲存和檢索,同時保持隨需新增額外元資料字段的靈活性。 對於非常大的PDF文件,請考慮資料庫儲存是否適合您的架構,或者是否應該採用混合方法——將文件儲存在磁碟或物件儲存中,僅在資料庫中保持元資料——在規模化方面會表現得更好。

PDF儲存策略比較
策略 最適合 優勢 考量
資料庫(VARBINARY) 小到中型文件,高安全性 交易一致性,集中備份 可快速增加資料庫大小
檔案系統 大型文件,高吞吐量 快速文件IO,低資料庫開銷 需要單獨的備份策略
物件儲存(Azure Blob/S3) 雲部署,無限擴展 成本效益,高可用性 需要額外的SDK依賴

如何將PDF文件上傳到資料庫?

使用ASP.NET的FileUpload控制來實現上傳功能。 在您的.aspx頁面中將此HTML標記新增到具有適當驗證的表單元素中:

<div class="pdf-upload-container">
    <asp:FileUpload ID="FileUpload1" runat="server" accept=".pdf" />
    <asp:Button ID="btnUpload" Text="Upload PDF"
                OnClick="btnUpload_Click" runat="server" CssClass="btn-primary" />
    <asp:Label ID="lblMessage" runat="server" CssClass="status-message" />
    <div class="file-info">
        <asp:Label ID="lblFileInfo" runat="server" />
    </div>
</div>
<div class="pdf-upload-container">
    <asp:FileUpload ID="FileUpload1" runat="server" accept=".pdf" />
    <asp:Button ID="btnUpload" Text="Upload PDF"
                OnClick="btnUpload_Click" runat="server" CssClass="btn-primary" />
    <asp:Label ID="lblMessage" runat="server" CssClass="status-message" />
    <div class="file-info">
        <asp:Label ID="lblFileInfo" runat="server" />
    </div>
</div>
HTML

範例UI輸出

ASP.NET網頁應用程式介面顯示一個PDF上傳表單,其中有

如何處理文件上傳事件?

上傳按鈕觸發伺服器端事件處理程式。 以下是該上傳功能的完整實現,將上傳的文件轉換為位元組陣列並儲存它們,並進行適當的錯誤處理:

protected void btnUpload_Click(object sender, EventArgs e)
{
    if (FileUpload1.HasFile && FileUpload1.PostedFile.ContentType == "application/pdf")
    {
        try
        {
            string fileName = FileUpload1.FileName;
            byte[] fileBytes = FileUpload1.FileBytes;
            int maxFileSize = 10 * 1024 * 1024; // 10MB limit

            if (fileBytes.Length > maxFileSize)
            {
                lblMessage.Text = "File size exceeds 10MB limit.";
                return;
            }

            // Validate PDF using IronPDF
            using (var stream = new MemoryStream(fileBytes))
            {
                var testPdf = new IronPdf.PdfDocument(stream);
                if (testPdf.PageCount == 0)
                {
                    lblMessage.Text = "Invalid PDF file.";
                    return;
                }
            }

            string constr = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
            using (SqlConnection conn = new SqlConnection(constr))
            {
                string query = "INSERT INTO PdfDocuments (FileName, FileData, FileSize, CreatedBy) " +
                               "VALUES (@FileName, @FileData, @FileSize, @CreatedBy)";
                using (SqlCommand cmd = new SqlCommand(query, conn))
                {
                    cmd.Parameters.AddWithValue("@FileName", fileName);
                    cmd.Parameters.AddWithValue("@FileData", fileBytes);
                    cmd.Parameters.AddWithValue("@FileSize", fileBytes.Length);
                    cmd.Parameters.AddWithValue("@CreatedBy", User.Identity.Name ?? "Anonymous");

                    conn.Open();
                    cmd.ExecuteNonQuery();
                }
            }
            lblMessage.Text = "PDF document uploaded successfully!";
            lblFileInfo.Text = $"File: {fileName} ({fileBytes.Length / 1024}KB)";
            LoadPdfList();
        }
        catch (Exception ex)
        {
            lblMessage.Text = "Error uploading file: " + ex.Message;
        }
    }
    else
    {
        lblMessage.Text = "Please select a valid PDF file.";
    }
}
protected void btnUpload_Click(object sender, EventArgs e)
{
    if (FileUpload1.HasFile && FileUpload1.PostedFile.ContentType == "application/pdf")
    {
        try
        {
            string fileName = FileUpload1.FileName;
            byte[] fileBytes = FileUpload1.FileBytes;
            int maxFileSize = 10 * 1024 * 1024; // 10MB limit

            if (fileBytes.Length > maxFileSize)
            {
                lblMessage.Text = "File size exceeds 10MB limit.";
                return;
            }

            // Validate PDF using IronPDF
            using (var stream = new MemoryStream(fileBytes))
            {
                var testPdf = new IronPdf.PdfDocument(stream);
                if (testPdf.PageCount == 0)
                {
                    lblMessage.Text = "Invalid PDF file.";
                    return;
                }
            }

            string constr = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
            using (SqlConnection conn = new SqlConnection(constr))
            {
                string query = "INSERT INTO PdfDocuments (FileName, FileData, FileSize, CreatedBy) " +
                               "VALUES (@FileName, @FileData, @FileSize, @CreatedBy)";
                using (SqlCommand cmd = new SqlCommand(query, conn))
                {
                    cmd.Parameters.AddWithValue("@FileName", fileName);
                    cmd.Parameters.AddWithValue("@FileData", fileBytes);
                    cmd.Parameters.AddWithValue("@FileSize", fileBytes.Length);
                    cmd.Parameters.AddWithValue("@CreatedBy", User.Identity.Name ?? "Anonymous");

                    conn.Open();
                    cmd.ExecuteNonQuery();
                }
            }
            lblMessage.Text = "PDF document uploaded successfully!";
            lblFileInfo.Text = $"File: {fileName} ({fileBytes.Length / 1024}KB)";
            LoadPdfList();
        }
        catch (Exception ex)
        {
            lblMessage.Text = "Error uploading file: " + ex.Message;
        }
    }
    else
    {
        lblMessage.Text = "Please select a valid PDF file.";
    }
}
Imports System
Imports System.IO
Imports System.Data.SqlClient
Imports System.Configuration
Imports IronPdf

Protected Sub btnUpload_Click(sender As Object, e As EventArgs)
    If FileUpload1.HasFile AndAlso FileUpload1.PostedFile.ContentType = "application/pdf" Then
        Try
            Dim fileName As String = FileUpload1.FileName
            Dim fileBytes As Byte() = FileUpload1.FileBytes
            Dim maxFileSize As Integer = 10 * 1024 * 1024 ' 10MB limit

            If fileBytes.Length > maxFileSize Then
                lblMessage.Text = "File size exceeds 10MB limit."
                Return
            End If

            ' Validate PDF using IronPDF
            Using stream As New MemoryStream(fileBytes)
                Dim testPdf As New IronPdf.PdfDocument(stream)
                If testPdf.PageCount = 0 Then
                    lblMessage.Text = "Invalid PDF file."
                    Return
                End If
            End Using

            Dim constr As String = ConfigurationManager.ConnectionStrings("DefaultConnection").ConnectionString
            Using conn As New SqlConnection(constr)
                Dim query As String = "INSERT INTO PdfDocuments (FileName, FileData, FileSize, CreatedBy) " &
                                      "VALUES (@FileName, @FileData, @FileSize, @CreatedBy)"
                Using cmd As New SqlCommand(query, conn)
                    cmd.Parameters.AddWithValue("@FileName", fileName)
                    cmd.Parameters.AddWithValue("@FileData", fileBytes)
                    cmd.Parameters.AddWithValue("@FileSize", fileBytes.Length)
                    cmd.Parameters.AddWithValue("@CreatedBy", If(User.Identity.Name, "Anonymous"))

                    conn.Open()
                    cmd.ExecuteNonQuery()
                End Using
            End Using
            lblMessage.Text = "PDF document uploaded successfully!"
            lblFileInfo.Text = $"File: {fileName} ({fileBytes.Length \ 1024}KB)"
            LoadPdfList()
        Catch ex As Exception
            lblMessage.Text = "Error uploading file: " & ex.Message
        End Try
    Else
        lblMessage.Text = "Please select a valid PDF file."
    End If
End Sub
$vbLabelText   $csharpLabel

此程式碼在上傳之前驗證文件型別,確保僅有效的PDF文件被儲存在資料庫中。 位元組陣列轉換通過FileBytes屬性自動完成。 附加驗證包括檢查PDF完整性和文件大小限制。 使用IronPDF在保存之前打開位元組陣列,確認該文件是一個真正的、可解析的PDF文件——而不僅僅是一個重命名擴展名的文件。

帶上傳文件的UI

ASP.NET網頁應用程式介面顯示PDF上傳功能,帶有一個文件上傳表單和一個上傳PDF文件列表的表格,其中有查看和下載操作按鈕以完成文件管理

如何從資料庫檢索和顯示PDF?

IronPDF在渲染從資料庫檢索的PDF文件方面表現出色。 該程式庫提供多種選擇,以在瀏覽器中顯示PDF內容,具備先進的渲染功能。 首先從您的資料庫表中檢索二進位資料,然後將其傳遞給IronPDF進行處理,然後在流回客戶端之前進行處理:

private void LoadPdfList()
{
    string constr = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
    using (SqlConnection conn = new SqlConnection(constr))
    {
        string query = @"SELECT Id, FileName, FileSize, UploadDate, CreatedBy
                        FROM PdfDocuments
                        ORDER BY UploadDate DESC";
        using (SqlCommand cmd = new SqlCommand(query, conn))
        {
            conn.Open();
            SqlDataAdapter adapter = new SqlDataAdapter(cmd);
            DataTable dt = new DataTable();
            adapter.Fill(dt);

            foreach (DataRow row in dt.Rows)
            {
                int fileSize = Convert.ToInt32(row["FileSize"]);
                row["FileSize"] = FormatFileSize(fileSize);
            }

            GridView1.DataSource = dt;
            GridView1.DataBind();
        }
    }
}

private string FormatFileSize(int bytes)
{
    if (bytes < 1024) return bytes + " B";
    if (bytes < 1048576) return (bytes / 1024) + " KB";
    return (bytes / 1048576) + " MB";
}

private PdfData GetPdfFromDatabase(int id)
{
    byte[] pdfBytes = null;
    string filename = "";
    string constr = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
    using (SqlConnection conn = new SqlConnection(constr))
    {
        string query = "SELECT FileData, FileName FROM PdfDocuments WHERE Id = @Id";
        using (SqlCommand cmd = new SqlCommand(query, conn))
        {
            cmd.Parameters.AddWithValue("@Id", id);
            conn.Open();
            using (SqlDataReader reader = cmd.ExecuteReader())
            {
                if (reader.Read())
                {
                    pdfBytes = (byte[])reader["FileData"];
                    filename = reader["FileName"].ToString();
                }
            }
        }
    }
    if (pdfBytes != null)
    {
        return new PdfData { Bytes = pdfBytes, FileName = filename };
    }
    return null;
}

protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
    if (e.CommandName == "ViewPdf")
    {
        int documentId = Convert.ToInt32(e.CommandArgument);
        ViewPdfDocument(documentId);
    }
    else if (e.CommandName == "DownloadPdf")
    {
        int documentId = Convert.ToInt32(e.CommandArgument);
        DownloadPdfDocument(documentId);
    }
}

private void ViewPdfDocument(int id)
{
    var pdfData = GetPdfFromDatabase(id);
    if (pdfData != null)
    {
        IronPdf.PdfDocument pdf;
        using (var stream = new System.IO.MemoryStream(pdfData.Bytes))
        {
            pdf = new IronPdf.PdfDocument(stream);
        }

        // Apply security settings
        pdf.SecuritySettings.AllowUserPrinting = true;
        pdf.SecuritySettings.AllowUserCopyPasteContent = false;

        Response.Clear();
        Response.ContentType = "application/pdf";
        Response.AddHeader("content-disposition", $"inline; filename={pdfData.FileName}");
        Response.AddHeader("content-length", pdf.BinaryData.Length.ToString());
        Response.BinaryWrite(pdf.BinaryData);
        Response.End();
    }
}
private void LoadPdfList()
{
    string constr = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
    using (SqlConnection conn = new SqlConnection(constr))
    {
        string query = @"SELECT Id, FileName, FileSize, UploadDate, CreatedBy
                        FROM PdfDocuments
                        ORDER BY UploadDate DESC";
        using (SqlCommand cmd = new SqlCommand(query, conn))
        {
            conn.Open();
            SqlDataAdapter adapter = new SqlDataAdapter(cmd);
            DataTable dt = new DataTable();
            adapter.Fill(dt);

            foreach (DataRow row in dt.Rows)
            {
                int fileSize = Convert.ToInt32(row["FileSize"]);
                row["FileSize"] = FormatFileSize(fileSize);
            }

            GridView1.DataSource = dt;
            GridView1.DataBind();
        }
    }
}

private string FormatFileSize(int bytes)
{
    if (bytes < 1024) return bytes + " B";
    if (bytes < 1048576) return (bytes / 1024) + " KB";
    return (bytes / 1048576) + " MB";
}

private PdfData GetPdfFromDatabase(int id)
{
    byte[] pdfBytes = null;
    string filename = "";
    string constr = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
    using (SqlConnection conn = new SqlConnection(constr))
    {
        string query = "SELECT FileData, FileName FROM PdfDocuments WHERE Id = @Id";
        using (SqlCommand cmd = new SqlCommand(query, conn))
        {
            cmd.Parameters.AddWithValue("@Id", id);
            conn.Open();
            using (SqlDataReader reader = cmd.ExecuteReader())
            {
                if (reader.Read())
                {
                    pdfBytes = (byte[])reader["FileData"];
                    filename = reader["FileName"].ToString();
                }
            }
        }
    }
    if (pdfBytes != null)
    {
        return new PdfData { Bytes = pdfBytes, FileName = filename };
    }
    return null;
}

protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
    if (e.CommandName == "ViewPdf")
    {
        int documentId = Convert.ToInt32(e.CommandArgument);
        ViewPdfDocument(documentId);
    }
    else if (e.CommandName == "DownloadPdf")
    {
        int documentId = Convert.ToInt32(e.CommandArgument);
        DownloadPdfDocument(documentId);
    }
}

private void ViewPdfDocument(int id)
{
    var pdfData = GetPdfFromDatabase(id);
    if (pdfData != null)
    {
        IronPdf.PdfDocument pdf;
        using (var stream = new System.IO.MemoryStream(pdfData.Bytes))
        {
            pdf = new IronPdf.PdfDocument(stream);
        }

        // Apply security settings
        pdf.SecuritySettings.AllowUserPrinting = true;
        pdf.SecuritySettings.AllowUserCopyPasteContent = false;

        Response.Clear();
        Response.ContentType = "application/pdf";
        Response.AddHeader("content-disposition", $"inline; filename={pdfData.FileName}");
        Response.AddHeader("content-length", pdf.BinaryData.Length.ToString());
        Response.BinaryWrite(pdf.BinaryData);
        Response.End();
    }
}
Imports System.Configuration
Imports System.Data
Imports System.Data.SqlClient
Imports System.IO
Imports IronPdf

Private Sub LoadPdfList()
    Dim constr As String = ConfigurationManager.ConnectionStrings("DefaultConnection").ConnectionString
    Using conn As New SqlConnection(constr)
        Dim query As String = "SELECT Id, FileName, FileSize, UploadDate, CreatedBy FROM PdfDocuments ORDER BY UploadDate DESC"
        Using cmd As New SqlCommand(query, conn)
            conn.Open()
            Dim adapter As New SqlDataAdapter(cmd)
            Dim dt As New DataTable()
            adapter.Fill(dt)

            For Each row As DataRow In dt.Rows
                Dim fileSize As Integer = Convert.ToInt32(row("FileSize"))
                row("FileSize") = FormatFileSize(fileSize)
            Next

            GridView1.DataSource = dt
            GridView1.DataBind()
        End Using
    End Using
End Sub

Private Function FormatFileSize(bytes As Integer) As String
    If bytes < 1024 Then Return bytes & " B"
    If bytes < 1048576 Then Return (bytes \ 1024) & " KB"
    Return (bytes \ 1048576) & " MB"
End Function

Private Function GetPdfFromDatabase(id As Integer) As PdfData
    Dim pdfBytes As Byte() = Nothing
    Dim filename As String = ""
    Dim constr As String = ConfigurationManager.ConnectionStrings("DefaultConnection").ConnectionString
    Using conn As New SqlConnection(constr)
        Dim query As String = "SELECT FileData, FileName FROM PdfDocuments WHERE Id = @Id"
        Using cmd As New SqlCommand(query, conn)
            cmd.Parameters.AddWithValue("@Id", id)
            conn.Open()
            Using reader As SqlDataReader = cmd.ExecuteReader()
                If reader.Read() Then
                    pdfBytes = CType(reader("FileData"), Byte())
                    filename = reader("FileName").ToString()
                End If
            End Using
        End Using
    End Using
    If pdfBytes IsNot Nothing Then
        Return New PdfData With {.Bytes = pdfBytes, .FileName = filename}
    End If
    Return Nothing
End Function

Protected Sub GridView1_RowCommand(sender As Object, e As GridViewCommandEventArgs)
    If e.CommandName = "ViewPdf" Then
        Dim documentId As Integer = Convert.ToInt32(e.CommandArgument)
        ViewPdfDocument(documentId)
    ElseIf e.CommandName = "DownloadPdf" Then
        Dim documentId As Integer = Convert.ToInt32(e.CommandArgument)
        DownloadPdfDocument(documentId)
    End If
End Sub

Private Sub ViewPdfDocument(id As Integer)
    Dim pdfData = GetPdfFromDatabase(id)
    If pdfData IsNot Nothing Then
        Dim pdf As PdfDocument
        Using stream As New MemoryStream(pdfData.Bytes)
            pdf = New PdfDocument(stream)
        End Using

        ' Apply security settings
        pdf.SecuritySettings.AllowUserPrinting = True
        pdf.SecuritySettings.AllowUserCopyPasteContent = False

        Response.Clear()
        Response.ContentType = "application/pdf"
        Response.AddHeader("content-disposition", $"inline; filename={pdfData.FileName}")
        Response.AddHeader("content-length", pdf.BinaryData.Length.ToString())
        Response.BinaryWrite(pdf.BinaryData)
        Response.End()
    End If
End Sub
$vbLabelText   $csharpLabel

ViewPdfDocument方法將文件流式傳回客戶端,並應用適當的安全設置。 inline內容分配通知瀏覽器顯示PDF而不是提示下載。 您可以調整安全設置,如列印權限和複製粘貼限制,以滿足您的文件政策要求。

如何處理PDF渲染參數?

SQL命令的參數對於安全地通過主鍵檢索特定的PDF至關重要。 參數化查詢可防止SQL注入攻擊並確保正確的資料綁定。 在檢索到二進位資料後,IronPDF會從MemoryStream中載入資料,讓您在將文件發送到瀏覽器之前,可以完全存取該文件物件以進行進一步的操作。

查看上傳的PDF文件

PDF查看器介面顯示題為

在顯示之前,您可以為PDF新增什麼高級功能?

IronPDF的PDF操作功能不僅限於簡單顯示。 您可以在渲染之前通過水印頁眉和頁腳數位簽章來操作PDF文件:

// Add a confidentiality watermark before displaying
pdf.ApplyWatermark("<h2 style='color:red; font-family:Arial'>CONFIDENTIAL</h2>",
                   rotation: 30,
                   opacity: 50);

// Add page numbers in the footer
pdf.AddTextHeaders("{page} of {total-pages}",
                  IronPdf.Editing.TextHeaderFooter.DisplayLocation.BottomCenter);

// Add document metadata
pdf.MetaData.Author = "Your Application";
pdf.MetaData.ModifiedDate = DateTime.Now;
// Add a confidentiality watermark before displaying
pdf.ApplyWatermark("<h2 style='color:red; font-family:Arial'>CONFIDENTIAL</h2>",
                   rotation: 30,
                   opacity: 50);

// Add page numbers in the footer
pdf.AddTextHeaders("{page} of {total-pages}",
                  IronPdf.Editing.TextHeaderFooter.DisplayLocation.BottomCenter);

// Add document metadata
pdf.MetaData.Author = "Your Application";
pdf.MetaData.ModifiedDate = DateTime.Now;
' Add a confidentiality watermark before displaying
pdf.ApplyWatermark("<h2 style='color:red; font-family:Arial'>CONFIDENTIAL</h2>", 
                   rotation:=30, 
                   opacity:=50)

' Add page numbers in the footer
pdf.AddTextHeaders("{page} of {total-pages}", 
                   IronPdf.Editing.TextHeaderFooter.DisplayLocation.BottomCenter)

' Add document metadata
pdf.MetaData.Author = "Your Application"
pdf.MetaData.ModifiedDate = DateTime.Now
$vbLabelText   $csharpLabel

觀看有水印的PDF

PDF查看器顯示題為

水印特別有用於顯示使用者應查看但不應逐字複製的文件。 您還可以在顯示之前從PDF中提取文字以建立搜尋索引,或將特定頁面轉換為圖像以生成縮略圖。

為什麼這種方法非常適合生產應用程式?

結合ADO.NET和IronPDF提供了一種簡單明了的模式,可以從小型內部工具擴展到企業級文件管理系統。 這個方法完全是伺服器端的——不需要使用者端PDF渲染程式庫,當正確的MIME型別返回時,瀏覽器內建的PDF查看器會處理顯示。

這種模式的主要優勢在於:

  • 上傳時的驗證:IronPDF在文件進入資料庫之前打開文件,立即拒絕損壞或非PDF文件。
  • 查看時的安全控制:如列印和複製粘貼的許可權由IronPDF在位元組到達瀏覽器之前進行強制執行。
  • 最少的使用者端程式碼:瀏覽器本身處理渲染,減少JavaScript的複雜性。
  • 靈活的預處理:您可以在流回之前應用HTML字串到PDF轉換合併和拆分操作自訂水印——所有這些都在同一伺服器端方法內。

如何處理瀏覽器整合和下載選項?

為了更好的網頁整合,使用JavaScript在新標籤中打開文件,而不是替換當前頁面。 這給使用者在瀏覽文件列表時提供了更好的體驗:

function openPdfInNewTab(documentId) {
    window.open('/PdfHandler.ashx?id=' + documentId, '_blank');
}

function openPdfInModal(documentId) {
    var modal = document.getElementById('pdfModal');
    var iframe = document.getElementById('pdfFrame');
    iframe.src = '/PdfHandler.ashx?id=' + documentId;
    modal.style.display = 'block';
}
function openPdfInNewTab(documentId) {
    window.open('/PdfHandler.ashx?id=' + documentId, '_blank');
}

function openPdfInModal(documentId) {
    var modal = document.getElementById('pdfModal');
    var iframe = document.getElementById('pdfFrame');
    iframe.src = '/PdfHandler.ashx?id=' + documentId;
    modal.style.display = 'block';
}
JAVASCRIPT

下載路徑遵循相同的資料庫檢索邏輯,但使用inline作為內容分配。 這迫使瀏覽器儲存文件而不是顯示文件。 兩個路徑共享相同的GetPdfFromDatabase輔助程式,保持資料存取程式碼DRY(不重複自己)。

對於基於表單的文件工作流程,探索IronPDF的PDF表單填充功能——您可以在顯示或下載文件之前預填表單字段,這對於發票生成和合同管理方案非常有用。

服務PDF的安全考慮有哪些?

在提供位元組之前,始終驗證請求使用者是否有權存取請求的文件ID。 查詢字串中的一個簡單整數ID很容易被枚舉——如果沒有授權檢查,任何身份驗證的使用者都可以通過猜測ID來查看任何文件。

最佳實踐包括:

  • 儲存FileData之前將其與當前使用者身份進行驗證。
  • 使用GUID而不是連續的整數作為文件標識符,使枚舉變得不切實際。
  • 在上傳時為高度敏感的文件應用PDF密碼保護,使即使在應用程式外被存取時,文件本身也是受保護的。
  • 記錄所有查看和下載事件以供審計追蹤。

有關ASP.NET安全模式的外部參考,OWASP ASP.NET安全備忘單微軟的ASP.NET安全編碼指南提供了權威的指導。 IronPDF的NuGet畫廊條目也記錄了版本歷史和依賴性。

如何開始使用PDF資料庫顯示?

要在您自己的專案中實現此解決方案:

  1. 通過NuGet安裝IronPDF(dotnet add package IronPdf)。
  2. 使用上面的SQL結構建立PdfDocuments表。
  3. 將上傳處理程式新增到您的.aspx後置程式碼中。
  4. 新增經由IronPDF流式傳輸的檢視和下載處理程式。
  5. 將GridView與指向這些處理程式的行命令連接起來。

您可以探索完整的IronPDF功能組來發現其他功能,例如HTML到PDF轉換PDF合併和拆分,這些功能自然融入文件管理工作流程中。 開始免費試用以測試完整的API,然後再決定授權

常見問題

在ASP.NET中從資料庫中顯示PDF的主要焦點是什麼?

主要目的是為開發人員提供有效的方法以便在ASP.NET網頁應用程式中直接從資料庫顯示PDF,從而增強專案的功能性和使用者體驗。

IronPDF如何幫助在ASP.NET中從資料庫中顯示PDF?

IronPDF可以通過提供強大的函式庫來簡化過程,使開發人員能夠順利地從資料庫儲存中呈現PDF,確保順利整合到ASP.NET應用程式中。

在ASP.NET中使用IronPDF顯示PDF有哪些優勢?

使用IronPDF提供了易於整合、高品質呈現和對各種PDF功能的支援等優勢,能顯著增強您的ASP.NET應用程式的可用性和性能。

IronPDF可以高效處理來自資料庫的大型PDF文件嗎?

是的,IronPDF設計用來高效處理大型PDF文件,確保快速載入和呈現時間,這對於維護應用程式性能至關重要。

是否可以在ASP.NET中使用IronPDF自訂PDF顯示?

完全可以,IronPDF提供各種自訂選項,讓開發人員能夠根據其特定需求在ASP.NET環境中調整PDF顯示。

IronPDF能在ASP.NET應用程式中將哪些文件格式轉換為PDF?

IronPDF支援將各種文件格式如HTML、圖像等轉換為PDF,這對於動態內容生成在ASP.NET應用程式中特別有用。

IronPDF是否支援在ASP.NET應用程式中安全處理PDF?

是的,IronPDF支援安全的PDF處理,包括加密和密碼保護,有助於保護ASP.NET應用程式中的敏感資訊。

IronPDF可以與其他Iron Software產品整合以增強功能嗎?

是的,IronPDF可以與其他Iron Software產品如IronOCR和IronBarcode整合,以在ASP.NET應用程式中提供全面的文件管理和處理解決方案。

Curtis Chau
技術作家

Curtis Chau擁有Carleton大學的電腦科學學士學位,專精於前端開發,擁有Node.js、TypeScript、JavaScript和React的專業知識。Curtis熱衷於建立直觀且美觀的使用者介面,喜愛使用現代框架並建立結構良好、視覺吸引力的手冊。

除了開發,Curtis對物聯網(IoT)有濃厚的興趣,探索創新的方法來整合硬體和軟體。在空閒時間,他喜歡玩遊戲和建立Discord機器人,結合他對技術的熱愛與創造力。

Iron 支援團隊

我們線上24小時,每週5天。
聊天
電子郵件
給我打電話