How to Display a PDF from a Database in ASP.NET
Introduction
Managing PDF documents in ASP.NET applications often requires storing PDF files directly in a database rather than the file system. This approach provides better security, centralized backup, and simplified deployment. However, retrieving and displaying PDF documents from a database can be challenging without the right tools.
Storing PDF files as binary data in a database table allows for better control over document access and versioning. When you need to display PDF documents to users, you must efficiently retrieve the byte array from the database and render it in the browser. IronPDF simplifies this entire process with its powerful API for handling PDF documents in ASP.NET applications.
This tutorial demonstrates ASP.NET display PDF from database functionality using IronPDF's robust features. You'll learn to create a complete solution for uploading, storing, and displaying PDF files with optimal performance and security.
Prerequisites and Setup
Before implementing PDF display functionality, ensure your ASP.NET project has IronPDF installed. Open the Package Manager Console in Visual Studio's Solution Explorer and run:
Install-Package IronPdf
Your database table structure needs a varbinary(max) column to store PDF files as binary data. The table should include metadata fields like file name, upload date, and file size for better document management. Here's the following code to set up your environment:
using IronPdf;
using System.Data.SqlClient;
using System.IO;using IronPdf;
using System.Data.SqlClient;
using System.IO;IRON VB CONVERTER ERROR developers@ironsoftware.comConfigure your connection string in the web.config file to establish database connectivity. The PDF viewer implementation will use this connection to retrieve uploaded files from the database and display PDF content seamlessly.
Creating the Database Table
Start by creating a database table specifically designed for storing PDF documents. The table structure should accommodate both the binary data and essential metadata:
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()
);This table stores each PDF file as a byte array in the FileData column. The varbinary(max) data type can hold files up to 2GB, sufficient for most PDF documents. The FileName field preserves the original file name for display and download purposes.
Consider adding indexes on frequently queried columns for better performance when retrieving PDF documents. The following code creates an index on the UploadDate column:
CREATE INDEX IX_PdfDocuments_UploadDate
ON PdfDocuments(UploadDate DESC);This structure ensures efficient storage and retrieval of uploaded files while maintaining the flexibility to add additional metadata fields as needed.
Uploading PDF Files to Database
Implement the upload functionality using ASP.NET's FileUpload control. Add this HTML markup to your .aspx page, perhaps within a form element:
<div>
<asp:FileUpload ID="FileUpload1" runat="server" />
<asp:Button ID="btnUpload" Text="Upload PDF"
OnClick="btnUpload_Click" runat="server" />
<asp:Label ID="lblMessage" runat="server" />
</div><div>
<asp:FileUpload ID="FileUpload1" runat="server" />
<asp:Button ID="btnUpload" Text="Upload PDF"
OnClick="btnUpload_Click" runat="server" />
<asp:Label ID="lblMessage" runat="server" />
</div>Example UI Output

The upload button triggers the server-side event handler. Here's the complete implementation for the upload function that converts uploaded files from the specified file path to a byte array and stores them. We will write the logic to handle the post request:
protected void btnUpload_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile && FileUpload1.PostedFile.ContentType == "application/pdf")
{
string fileName = FileUpload1.FileName;
byte[] fileBytes = FileUpload1.FileBytes;
// 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) " +
"VALUES (@FileName, @FileData, @FileSize)";
using (SqlCommand cmd = new SqlCommand(query, conn))
{
cmd.Parameters.AddWithValue("@FileName", fileName);
cmd.Parameters.AddWithValue("@FileData", fileBytes);
cmd.Parameters.AddWithValue("@FileSize", fileBytes.Length);
conn.Open();
cmd.ExecuteNonQuery();
}
}
lblMessage.Text = "PDF document uploaded successfully!";
LoadPdfList(); // Refresh the list after upload
}
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")
{
string fileName = FileUpload1.FileName;
byte[] fileBytes = FileUpload1.FileBytes;
// 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) " +
"VALUES (@FileName, @FileData, @FileSize)";
using (SqlCommand cmd = new SqlCommand(query, conn))
{
cmd.Parameters.AddWithValue("@FileName", fileName);
cmd.Parameters.AddWithValue("@FileData", fileBytes);
cmd.Parameters.AddWithValue("@FileSize", fileBytes.Length);
conn.Open();
cmd.ExecuteNonQuery();
}
}
lblMessage.Text = "PDF document uploaded successfully!";
LoadPdfList(); // Refresh the list after upload
}
else
{
lblMessage.Text = "Please select a valid PDF file.";
}
}IRON VB CONVERTER ERROR developers@ironsoftware.comThis code validates the file type before uploading, ensuring only PDF files are stored in the database. The byte array conversion happens automatically through the FileBytes property.
UI with Uploaded Files

Retrieving and Displaying PDF Documents with IronPDF
IronPDF excels at rendering PDF documents retrieved from a database. The library provides multiple options to display PDF content in browsers. First, retrieve the binary data from your database table:
private void LoadPdfList()
{
string constr = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
using (SqlConnection conn = new SqlConnection(constr))
{
string query = "SELECT Id, FileName, FileSize, UploadDate FROM PdfDocuments ORDER BY UploadDate DESC";
using (SqlCommand cmd = new SqlCommand(query, conn))
{
conn.Open();
GridView1.DataSource = cmd.ExecuteReader();
GridView1.DataBind();
}
}
}
// 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 == "Download Pdf")
{
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);
}
// Configure response to display inline in the browser
Response.Clear();
Response.ContentType = "application/pdf";
Response.AddHeader("content-disposition", $"inline; filename={pdfData.FileName}");
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 FROM PdfDocuments ORDER BY UploadDate DESC";
using (SqlCommand cmd = new SqlCommand(query, conn))
{
conn.Open();
GridView1.DataSource = cmd.ExecuteReader();
GridView1.DataBind();
}
}
}
// 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 == "Download Pdf")
{
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);
}
// Configure response to display inline in the browser
Response.Clear();
Response.ContentType = "application/pdf";
Response.AddHeader("content-disposition", $"inline; filename={pdfData.FileName}");
Response.BinaryWrite(pdf.BinaryData);
Response.End();
}
}IRON VB CONVERTER ERROR developers@ironsoftware.comThe parameters for the SQL command are crucial for safely retrieving the specific PDF. The ViewPdfDocument method then handles streaming the document back to the client.
Viewing an Uploaded PDF File

IronPDF's PDF viewer capabilities extend beyond simple display. You can manipulate the PDF document before rendering:
// Add watermark before displaying
pdf.ApplyWatermark("<h2>CONFIDENTIAL</h2>", rotation: 30, opacity: 50);
// Convert specific pages to images for preview
var previewImage = pdf.RasterizeToImageFiles("preview*.png", 1, 3);// Add watermark before displaying
pdf.ApplyWatermark("<h2>CONFIDENTIAL</h2>", rotation: 30, opacity: 50);
// Convert specific pages to images for preview
var previewImage = pdf.RasterizeToImageFiles("preview*.png", 1, 3);IRON VB CONVERTER ERROR developers@ironsoftware.comViewing PDF with Watermark

The PDF viewer support is robust. For better web integration and controlling the display width of the content, use CSS and JavaScript to open a document in a dialog or a new tab, centered on the screen.
<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');
}
</script><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');
}
</script>Complete Working Example: PDF Viewer in ASP.NET C#
Here's a comprehensive sample code combining all components to create a fully functional system for managing PDF files in your database:
using IronPdf;
using System;
using System.Configuration; // Required for ConfigurationManager
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")
{
string fileName = FileUpload1.FileName;
byte[] fileBytes = FileUpload1.FileBytes;
// 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) " +
"VALUES (@FileName, @FileData, @FileSize)";
using (SqlCommand cmd = new SqlCommand(query, conn))
{
cmd.Parameters.AddWithValue("@FileName", fileName);
cmd.Parameters.AddWithValue("@FileData", fileBytes);
cmd.Parameters.AddWithValue("@FileSize", fileBytes.Length);
conn.Open();
cmd.ExecuteNonQuery();
}
}
lblMessage.Text = "PDF document uploaded successfully!";
LoadPdfList(); // Refresh the list after upload
}
else
{
lblMessage.Text = "Please select a valid PDF file.";
}
}
// ----------------- 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 FROM PdfDocuments ORDER BY UploadDate DESC";
using (SqlCommand cmd = new SqlCommand(query, conn))
{
conn.Open();
GridView1.DataSource = cmd.ExecuteReader();
GridView1.DataBind();
}
}
}
// 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 == "Download Pdf")
{
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);
}
pdf.ApplyWatermark("<h2 style='color:red'>CONFIDENTIAL</h2>", rotation: 30, opacity: 50);
// Configure response to display inline in the browser
Response.Clear();
Response.ContentType = "application/pdf";
Response.AddHeader("content-disposition", $"inline; filename={pdfData.FileName}");
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.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; }
}using IronPdf;
using System;
using System.Configuration; // Required for ConfigurationManager
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")
{
string fileName = FileUpload1.FileName;
byte[] fileBytes = FileUpload1.FileBytes;
// 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) " +
"VALUES (@FileName, @FileData, @FileSize)";
using (SqlCommand cmd = new SqlCommand(query, conn))
{
cmd.Parameters.AddWithValue("@FileName", fileName);
cmd.Parameters.AddWithValue("@FileData", fileBytes);
cmd.Parameters.AddWithValue("@FileSize", fileBytes.Length);
conn.Open();
cmd.ExecuteNonQuery();
}
}
lblMessage.Text = "PDF document uploaded successfully!";
LoadPdfList(); // Refresh the list after upload
}
else
{
lblMessage.Text = "Please select a valid PDF file.";
}
}
// ----------------- 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 FROM PdfDocuments ORDER BY UploadDate DESC";
using (SqlCommand cmd = new SqlCommand(query, conn))
{
conn.Open();
GridView1.DataSource = cmd.ExecuteReader();
GridView1.DataBind();
}
}
}
// 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 == "Download Pdf")
{
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);
}
pdf.ApplyWatermark("<h2 style='color:red'>CONFIDENTIAL</h2>", rotation: 30, opacity: 50);
// Configure response to display inline in the browser
Response.Clear();
Response.ContentType = "application/pdf";
Response.AddHeader("content-disposition", $"inline; filename={pdfData.FileName}");
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.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; }
}IRON VB CONVERTER ERROR developers@ironsoftware.comThis implementation includes error handling and validation to ensure robust PDF document management. The source code demonstrates best practices for working with binary data and file operations.
Conclusion
Implementing ASP.NET display PDF files from database functionality becomes straightforward with IronPDF. The library handles the complexities of PDF document rendering while providing extensive customization options. From simple display scenarios to complex document manipulation, IronPDF offers the tools needed for professional PDF management in ASP.NET applications.
The techniques covered in this article provide a solid foundation for building robust document management systems. IronPDF's comprehensive API ensures your application can handle various PDF-related requirements efficiently, from basic file upload and storage to advanced rendering and manipulation features.
Ready to implement professional PDF functionality in your ASP.NET applications? Start your free trial of IronPDF today and experience the power of seamless PDF management. For production deployments, explore our flexible licensing options that scale with your needs.







