跳過到頁腳內容
USING IRONPDF

How to Display a PDF from a Database in ASP.NET

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

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

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

為什麼將PDF檔案儲存在資料庫中而不是檔案系統中?

將 PDF 檔案作為二進位資料儲存在資料庫表中,可以更好地控製文件的存取和版本控制。 當您需要向使用者顯示 PDF 文件時,必須有效率地從資料庫中檢索位元組數組並將其呈現在瀏覽器中。 IronPDF 透過其高效的 API 簡化了在 ASP.NET 應用程式中處理 PDF 文件的整個過程

IronPDF能提供哪些好處?

本教學課程示範如何使用 IronPDF 的可靠功能,透過 ASP.NET 從資料庫顯示 PDF。 您將學習如何建立一個完整的解決方案,用於上傳、儲存和顯示 PDF 文件,並實現最佳效能和安全性。 該庫支援多種渲染選項高級 PDF 處理功能。

顯示PDF資料庫需要哪些先決條件?

在實現 PDF 顯示功能之前,請確保您的 ASP.NET 專案已安裝 IronPDF。 在 Visual Studio 的解決方案資源管理器中開啟程式包管理器控制台,然後執行:

Install-Package IronPdf

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

您的資料庫表結構需要一個varbinary(max)欄位來將 PDF 檔案儲存為二進位資料。 為了更好地管理文檔,表格應包含文件名稱、上傳日期和文件大小等元資料欄位。 以下程式碼用於設定ASP.NET 中處理 PDF 的環境:

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

如何配置資料庫連線?

web.config檔案中配置連接字串以建立資料庫連線。 PDF 檢視器實作將使用此連接從資料庫中檢索上傳的文件,並流暢地顯示 PDF 內容。 考慮實作自訂日誌記錄以偵錯資料庫操作。

如何建立用於儲存 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 儲存應使用哪些資料類型?

該表將每個 PDF 檔案以位元組數組的形式儲存在FileData列中。 varbinary(max)資料類型可以儲存最大 2GB 的文件,足以滿足大多數PDF 文件的需求。 FileName欄位保留原始檔案名,以便顯示和下載。 為了節省資料庫空間,請考慮在儲存前壓縮 PDF 檔案

如何提高資料庫效能?

檢索 PDF 文件時,可以考慮在經常查詢的列上新增索引,以提高效能。 以下程式碼在UploadDate列上建立索引,以改進 PDF 操作

CREATE INDEX IX_PdfDocuments_UploadDate 
ON PdfDocuments(UploadDate DESC);

CREATE INDEX IX_PdfDocuments_FileName 
ON PdfDocuments(FileName);

這種結構確保了上傳文件的高效儲存和檢索,同時保持了根據需要添加其他元資料欄位的靈活性。 對於大型 PDF 文件,請考慮實作串流操作

如何將PDF檔案上傳到資料庫?

使用 ASP.NET 的FileUpload控制項實作上傳功能。 將此 HTML 標記新增至您的 .aspx 頁面中,最好將其放在具有適當驗證的表單元素中:

<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 Web 應用程式介面,顯示一個 PDF 上傳表單,其中包含"選擇檔案"按鈕和"上傳 PDF"按鈕,下方還有一個用於文件管理的空白 PDF 文件清單部分。

如何處理文件上傳事件?

上傳按鈕會觸發伺服器端事件處理程序。 以下是上傳函數的完整實現,該函數將上傳的檔案從指定的檔案路徑轉換為位元組數組並儲存。 你需要編寫邏輯來處理 POST 請求,並進行適當的錯誤處理

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;
                }
            }

            // Connection string is retrieved from web.config
            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(); // Refresh the list after upload
        }
        catch (Exception ex)
        {
            lblMessage.Text = "Error uploading file: " + ex.Message;
            // Log error details
        }
    }
    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;
                }
            }

            // Connection string is retrieved from web.config
            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(); // Refresh the list after upload
        }
        catch (Exception ex)
        {
            lblMessage.Text = "Error uploading file: " + ex.Message;
            // Log error details
        }
    }
    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 PdfDocument(stream)
                If testPdf.PageCount = 0 Then
                    lblMessage.Text = "Invalid PDF file."
                    Return
                End If
            End Using

            ' Connection string is retrieved from web.config
            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() ' Refresh the list after upload
        Catch ex As Exception
            lblMessage.Text = "Error uploading file: " & ex.Message
            ' Log error details
        End Try
    Else
        lblMessage.Text = "Please select a valid PDF file."
    End If
End Sub
$vbLabelText   $csharpLabel

應該實施哪些驗證?

這段程式碼會在上傳文件前驗證文件類型,確保資料庫中只儲存有效的 PDF 文件。 位元組數組轉換透過FileBytes屬性自動完成。 其他驗證措施包括檢查PDF文件的完整性和文件大小限制。

帶有上傳檔案的使用者介面

! ASP.NET Web 應用程式介面,展示了 PDF 上傳功能,包括文件上傳表單和列出已上傳 PDF 文件的表格,以及用於完整文件管理的檢視和下載操作按鈕。

如何使用 IronPDF 檢索和顯示 PDF 文件?

IronPDF 擅長渲染從資料庫擷取的 PDF 文件。 該庫提供了多種選項,可在具有高級渲染功能的瀏覽器中顯示 PDF 內容。 首先,從資料庫表中檢索二進位資料:

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);

            // Format file sizes for display
            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";
}

// Helper method to retrieve PDF data from the database
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())
                {
                    // Retrieve binary data
                    pdfBytes = (byte[])reader["FileData"];
                    filename = reader["FileName"].ToString();
                }
            }
        }
    }
    if (pdfBytes != null)
    {
        return new PdfData { Bytes = pdfBytes, FileName = filename };
    }
    return null;
}

// ----------------- GridView Command Handlers -----------------
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 if needed
        pdf.SecuritySettings.AllowUserPrinting = true;
        pdf.SecuritySettings.AllowUserCopyPasteContent = false;

        // Configure response to display inline in the browser
        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);

            // Format file sizes for display
            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";
}

// Helper method to retrieve PDF data from the database
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())
                {
                    // Retrieve binary data
                    pdfBytes = (byte[])reader["FileData"];
                    filename = reader["FileName"].ToString();
                }
            }
        }
    }
    if (pdfBytes != null)
    {
        return new PdfData { Bytes = pdfBytes, FileName = filename };
    }
    return null;
}

// ----------------- GridView Command Handlers -----------------
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 if needed
        pdf.SecuritySettings.AllowUserPrinting = true;
        pdf.SecuritySettings.AllowUserCopyPasteContent = false;

        // Configure response to display inline in the browser
        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.Web.UI.WebControls
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)

            ' Format file sizes for display
            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

' Helper method to retrieve PDF data from the database
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
                    ' Retrieve binary data
                    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

' ----------------- GridView Command Handlers -----------------
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 System.IO.MemoryStream(pdfData.Bytes)
            pdf = New PdfDocument(stream)
        End Using

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

        ' Configure response to display inline in the browser
        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

如何處理PDF渲染參數?

SQL 命令的參數對於安全地檢索特定 PDF 檔案至關重要。 ViewPdfDocument方法隨後會處理將文件串流回客戶端並設定適當的安全設定

查看已上傳的PDF文件

PDF 檢視器介面顯示一份名為"什麼是 PDF?"的文檔,其中包含關於便攜式文檔格式的解釋性文字,以 100% 縮放比例顯示,並帶有導航控制項和多頁支援指示器。

您可以為 PDF 檔案添加哪些進階功能?

IronPDF 的 PDF 處理功能不僅限於簡單的顯示。 您可以在渲染之前對PDF 文件進行操作,例如新增浮水印註解和數位簽章

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

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

// Convert specific pages to images for preview
var previewImages = pdf.RasterizeToImageFiles("preview_*.png", 1, 3, 150, 
                                              IronPdf.Imaging.ImageType.Png);

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

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

// Convert specific pages to images for preview
var previewImages = pdf.RasterizeToImageFiles("preview_*.png", 1, 3, 150, 
                                              IronPdf.Imaging.ImageType.Png);

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

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

' Convert specific pages to images for preview
Dim previewImages = pdf.RasterizeToImageFiles("preview_*.png", 1, 3, 150, 
                                              IronPdf.Imaging.ImageType.Png)

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

查看帶有浮水印的 PDF 文件

PDF 檢視器正在顯示一份關於"什麼是 PDF?"的文檔,其中包含詳細的文字內容和一個斜角"機密"浮水印,以展示 IronPDF 的文件安全浮水印功能。

如何改進瀏覽器整合?

PDF檢視器支援穩定可靠。 為了更好地進行 Web 整合並控制內容的顯示寬度,請使用 CSS 和 JavaScript在對話方塊或新標籤頁中開啟文檔,並將其居中顯示在螢幕上。 您還可以實現自訂視口設定

<script type="text/javascript">
    function openPdfInNewTab(documentId) {
        // This generates a simple HTTP GET request to a handler URL
        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';
    }
</script>

<div id="pdfModal" class="modal">
    <div class="modal-content">
        <span class="close">&times;</span>
        <iframe id="pdfFrame" width="100%" height="600px"></iframe>
    </div>
</div>
```## What Does a Complete PDF Viewer Example Look Like?

Here's a complete sample code combining all components to create a fully functional system for [managing PDF files](https://ironpdf.com/tutorials/organize-pdfs-complete-tutorial/) in your database with [improved security features](https://ironpdf.com/tutorials/csharp-pdf-security-complete-tutorial/):

```csharp
using IronPdf;
using System;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Web.UI.WebControls;

namespace PdfDatabaseViewer
{
    public partial class Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                LoadPdfList();
            }
            License.LicenseKey = "Your-License-Key";
        }

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

                    if (fileBytes.Length > maxFileSize)
                    {
                        lblMessage.Text = "File size exceeds 10MB limit.";
                        lblMessage.CssClass = "error-message";
                        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.";
                            lblMessage.CssClass = "error-message";
                            return;
                        }
                        lblFileInfo.Text = $"Pages: {testPdf.PageCount}, Size: {FormatFileSize(fileBytes.Length)}";
                    }

                    // Connection string is retrieved from web.config
                    string constr = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
                    using (SqlConnection conn = new SqlConnection(constr))
                    {
                        string query = @"INSERT INTO PdfDocuments 
                                       (FileName, FileData, FileSize, CreatedBy, LastModified) 
                                       VALUES (@FileName, @FileData, @FileSize, @CreatedBy, GETDATE())";
                        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!";
                    lblMessage.CssClass = "success-message";
                    LoadPdfList(); // Refresh the list after upload
                }
                catch (Exception ex)
                {
                    lblMessage.Text = "Error uploading file: " + ex.Message;
                    lblMessage.CssClass = "error-message";
                    // Log error details for debugging
                    System.Diagnostics.Trace.WriteLine($"Upload Error: {ex}");
                }
            }
            else
            {
                lblMessage.Text = "Please select a valid PDF file.";
                lblMessage.CssClass = "warning-message";
            }
        }

        // ----------------- Data Retrieval and List Display -----------------
        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);

                    // Add formatted columns
                    dt.Columns.Add("FormattedSize", typeof(string));
                    dt.Columns.Add("FormattedDate", typeof(string));

                    foreach (DataRow row in dt.Rows)
                    {
                        int fileSize = Convert.ToInt32(row["FileSize"]);
                        row["FormattedSize"] = FormatFileSize(fileSize);
                        row["FormattedDate"] = Convert.ToDateTime(row["UploadDate"]).ToString("MMM dd, yyyy HH:mm");
                    }

                    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.0).ToString("F2") + " MB";
        }

        // Helper method to retrieve PDF data from the database
        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())
                        {
                            // Retrieve binary data
                            pdfBytes = (byte[])reader["FileData"];
                            filename = reader["FileName"].ToString();
                        }
                    }
                }
            }
            if (pdfBytes != null)
            {
                return new PdfData { Bytes = pdfBytes, FileName = filename };
            }
            return null;
        }

        // ----------------- GridView Command Handlers -----------------
        protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            try
            {
                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);
                }
            }
            catch (Exception ex)
            {
                lblMessage.Text = "Error processing request: " + ex.Message;
                lblMessage.CssClass = "error-message";
            }
        }

        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 watermark for viewing
                pdf.ApplyWatermark("<h2 style='color:red; font-family:Arial'>CONFIDENTIAL</h2>", 
                                 rotation: 30, 
                                 opacity: 50);

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

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

                // Configure response to display inline in the browser
                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 DownloadPdfDocument(int id)
        {
            var pdfData = GetPdfFromDatabase(id);
            if (pdfData != null)
            {
                // Configure response to force a download/save prompt
                Response.Clear();
                Response.ContentType = "application/pdf";
                Response.AddHeader("content-disposition", $"attachment; filename={pdfData.FileName}");
                Response.AddHeader("content-length", pdfData.Bytes.Length.ToString());
                Response.BinaryWrite(pdfData.Bytes);
                Response.End();
            }
        }
    }
}

// Helper class must be outside the Default class
public class PdfData
{
    public byte[] Bytes { get; set; }
    public string FileName { get; set; }
}
<script type="text/javascript">
    function openPdfInNewTab(documentId) {
        // This generates a simple HTTP GET request to a handler URL
        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';
    }
</script>

<div id="pdfModal" class="modal">
    <div class="modal-content">
        <span class="close">&times;</span>
        <iframe id="pdfFrame" width="100%" height="600px"></iframe>
    </div>
</div>
```## What Does a Complete PDF Viewer Example Look Like?

Here's a complete sample code combining all components to create a fully functional system for [managing PDF files](https://ironpdf.com/tutorials/organize-pdfs-complete-tutorial/) in your database with [improved security features](https://ironpdf.com/tutorials/csharp-pdf-security-complete-tutorial/):

```csharp
using IronPdf;
using System;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Web.UI.WebControls;

namespace PdfDatabaseViewer
{
    public partial class Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                LoadPdfList();
            }
            License.LicenseKey = "Your-License-Key";
        }

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

                    if (fileBytes.Length > maxFileSize)
                    {
                        lblMessage.Text = "File size exceeds 10MB limit.";
                        lblMessage.CssClass = "error-message";
                        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.";
                            lblMessage.CssClass = "error-message";
                            return;
                        }
                        lblFileInfo.Text = $"Pages: {testPdf.PageCount}, Size: {FormatFileSize(fileBytes.Length)}";
                    }

                    // Connection string is retrieved from web.config
                    string constr = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
                    using (SqlConnection conn = new SqlConnection(constr))
                    {
                        string query = @"INSERT INTO PdfDocuments 
                                       (FileName, FileData, FileSize, CreatedBy, LastModified) 
                                       VALUES (@FileName, @FileData, @FileSize, @CreatedBy, GETDATE())";
                        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!";
                    lblMessage.CssClass = "success-message";
                    LoadPdfList(); // Refresh the list after upload
                }
                catch (Exception ex)
                {
                    lblMessage.Text = "Error uploading file: " + ex.Message;
                    lblMessage.CssClass = "error-message";
                    // Log error details for debugging
                    System.Diagnostics.Trace.WriteLine($"Upload Error: {ex}");
                }
            }
            else
            {
                lblMessage.Text = "Please select a valid PDF file.";
                lblMessage.CssClass = "warning-message";
            }
        }

        // ----------------- Data Retrieval and List Display -----------------
        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);

                    // Add formatted columns
                    dt.Columns.Add("FormattedSize", typeof(string));
                    dt.Columns.Add("FormattedDate", typeof(string));

                    foreach (DataRow row in dt.Rows)
                    {
                        int fileSize = Convert.ToInt32(row["FileSize"]);
                        row["FormattedSize"] = FormatFileSize(fileSize);
                        row["FormattedDate"] = Convert.ToDateTime(row["UploadDate"]).ToString("MMM dd, yyyy HH:mm");
                    }

                    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.0).ToString("F2") + " MB";
        }

        // Helper method to retrieve PDF data from the database
        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())
                        {
                            // Retrieve binary data
                            pdfBytes = (byte[])reader["FileData"];
                            filename = reader["FileName"].ToString();
                        }
                    }
                }
            }
            if (pdfBytes != null)
            {
                return new PdfData { Bytes = pdfBytes, FileName = filename };
            }
            return null;
        }

        // ----------------- GridView Command Handlers -----------------
        protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            try
            {
                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);
                }
            }
            catch (Exception ex)
            {
                lblMessage.Text = "Error processing request: " + ex.Message;
                lblMessage.CssClass = "error-message";
            }
        }

        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 watermark for viewing
                pdf.ApplyWatermark("<h2 style='color:red; font-family:Arial'>CONFIDENTIAL</h2>", 
                                 rotation: 30, 
                                 opacity: 50);

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

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

                // Configure response to display inline in the browser
                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 DownloadPdfDocument(int id)
        {
            var pdfData = GetPdfFromDatabase(id);
            if (pdfData != null)
            {
                // Configure response to force a download/save prompt
                Response.Clear();
                Response.ContentType = "application/pdf";
                Response.AddHeader("content-disposition", $"attachment; filename={pdfData.FileName}");
                Response.AddHeader("content-length", pdfData.Bytes.Length.ToString());
                Response.BinaryWrite(pdfData.Bytes);
                Response.End();
            }
        }
    }
}

// Helper class must be outside the Default class
public class PdfData
{
    public byte[] Bytes { get; set; }
    public string FileName { get; set; }
}
HTML

此實作方案包含完整的錯誤處理和驗證機制,以確保可靠的PDF文件管理。 原始碼演示了處理二進位資料檔案操作的最佳實踐。

為什麼應該使用 IronPDF 來顯示資料庫 PDF 檔案?

使用 IronPDF,實現 ASP.NET 從資料庫顯示 PDF 檔案的功能變得非常簡單。 該庫能夠處理PDF 文件渲染的複雜性,同時提供廣泛的自訂選項。 從簡單的顯示場景到複雜的文件操作,IronPDF 提供了在 ASP.NET 應用程式中進行專業PDF 管理所需的工具。

該解決方案具備哪些生產就緒條件?

本文介紹的技術為建立可靠的文件管理系統奠定了堅實的基礎。 IronPDF 的完整 API確保您的應用程式能夠有效率地處理各種與 PDF 相關的需求,從基本的文件上傳和儲存到進階渲染操作功能。 該程式庫也支援部署到AzureAWS雲端平台

如何開始使用 IronPDF?

準備好在您的 ASP.NET 應用程式中實現專業的 PDF 功能了嗎? 立即開始 IronPDF 的免費試用,體驗流暢的 PDF 管理功能。 對於生產環境部署,請了解我們靈活的授權選項,這些選項可根據您的需求進行擴展。

常見問題解答

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

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

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

IronPDF for .NET 可提供強大的函式庫,讓開發人員從資料庫儲存中無縫渲染 PDF,確保順利整合至 ASP.NET 應用程式,從而簡化流程。

使用 IronPDF 在 ASP.NET 中顯示 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 for .NET 支援安全的 PDF 處理,包括加密和密碼保護,有助於保護 ASP.NET 應用程式中的敏感資訊。

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

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

Curtis Chau
技術撰稿人

Curtis Chau 擁有電腦科學學士學位(卡爾頓大學),專長於前端開發,精通 Node.js、TypeScript、JavaScript 和 React。Curtis 對製作直覺且美觀的使用者介面充滿熱情,他喜歡使用現代化的架構,並製作結構良好且視覺上吸引人的手冊。

除了開發之外,Curtis 對物聯網 (IoT) 也有濃厚的興趣,他喜歡探索整合硬體與軟體的創新方式。在空閒時間,他喜歡玩遊戲和建立 Discord bots,將他對技術的熱愛與創意結合。