跳至页脚内容
使用IRONPDF

如何在 ASP.NET 中从数据库显示 PDF

要在 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 存储应该使用哪些数据类型?

此表在FileData列中以字节数组形式存储每个 PDF 文件。 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文件的完整性和文件大小限制。

上传文件后 UI

! 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通过提供强大的库简化了过程,使开发者可以从数据库存储中无缝呈现PDF,确保到ASP.NET应用程序的平滑集成。

在ASP.NET中使用IronPDF显示PDF的优势是什么?

使用IronPDF的优势包括易于集成、高质量渲染以及对各种PDF功能的支持,这可以显著提升ASP.NET应用程序的可用性和性能。

IronPDF能否高效处理来自数据库的大型PDF文件?

是的,IronPDF设计用于高效处理大型PDF文件,确保快速加载和渲染时间,这对于维护应用程序性能至关重要。

在ASP.NET中可以使用IronPDF自定义PDF显示吗?

当然,IronPDF提供各种自定义选项,允许开发者根据其特定要求定制PDF显示在ASP.NET环境中。

IronPDF可以在ASP.NET应用程序中将哪些文件格式转换为PDF?

IronPDF支持将多种文件格式如HTML、图像等转换为PDF,这对于动态内容生成尤为有用。

IronPDF支持ASP.NET应用程序的安全PDF处理吗?

是的,IronPDF支持安全PDF处理,包括加密和密码保护,这有助于在ASP.NET应用程序中保护敏感信息。

IronPDF可以与其他Iron Software产品集成以增强功能吗?

是的,IronPDF可以与其他Iron Software产品如IronOCR和IronBarcode集成,以提供ASP.NET应用程序中文档管理和处理的全面解决方案。

Curtis Chau
技术作家

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

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