IRONPDFの使用 ASP.NETでデータベースからPDFを表示する方法 カーティス・チャウ 更新日:2026年1月21日 IronPDF をダウンロード NuGet ダウンロード DLL ダウンロード Windows 版 無料トライアル LLM向けのコピー LLM向けのコピー LLM 用の Markdown としてページをコピーする ChatGPTで開く このページについてChatGPTに質問する ジェミニで開く このページについてGeminiに問い合わせる Grokで開く このページについてGrokに質問する 困惑の中で開く このページについてPerplexityに問い合わせる 共有する Facebook で共有 Xでシェア(Twitter) LinkedIn で共有 URLをコピー 記事をメールで送る ASP.NET でデータベースから PDF を表示するには、保存されているバイナリ データを取得し、 IronPDF の PdfDocument クラスを使用してレンダリングします。このクラスは、バイト配列を効率的に処理し、カスタマイズ オプションを備えたブラウザー互換の出力を提供します。 ASP.NET での PDF データベース表示とは何ですか? ASP.NET アプリケーションでPDF ドキュメントを管理する場合、多くの場合、PDF ファイルをファイル システムではなくデータベースに直接保存する必要があります。 この方法により、セキュリティが向上し、バックアップが集中化され、展開が簡素化されます。 しかし、適切なツールなしでデータベースからPDFドキュメントを取得して表示するのは困難です。 PDF をファイル システムではなくデータベースに保存するのはなぜですか? データベーステーブルにPDFファイルをバイナリデータとして保存することで、ドキュメントのアクセスとバージョン管理をより良く制御できます。 ユーザーにPDFドキュメントを表示する必要がある場合、データベースからバイト配列を効率的に取得し、ブラウザでレンダリングしなければなりません。 IronPDF は、ASP.NET アプリケーションでPDF ドキュメントを処理するための効果的な API を使用して、このプロセス全体を簡素化します。 IronPDF にはどのような利点がありますか? このチュートリアルでは、IronPDF の信頼性の高い機能を使用して、ASP.NET でデータベースから PDF を表示する機能について説明します。 最適なパフォーマンスとセキュリティを備えたPDF ファイルをアップロード、保存、表示するための完全なソリューションを作成する方法を学習します。 ライブラリは、さまざまなレンダリング オプションと高度な PDF 操作機能をサポートしています。 PDF データベースの表示に必要な前提条件は何ですか? PDF表示機能を実装する前に、ASP.NETプロジェクトにIronPDFがインストールされていることを確認してください。 Visual Studioのソリューションエクスプローラでパッケージマネージャコンソールを開き、以下を実行します。 Install-Package IronPdf どのようなデータベース構造が必要ですか? データベーステーブル構造には、PDFファイルをバイナリデータとして保存するvarbinary(max)列が必要です。 管理の向上のために、テーブルにはファイル名、アップロード日、ファイルサイズといったメタデータフィールドを含めるべきです。 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 ドキュメントを取得する際のパフォーマンスを向上させるには、頻繁にクエリされる列にインデックスを追加することを検討してください。 次のコードは、PDF 操作を改善するためにUploadDate列にインデックスを作成します。 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 とは何か?"というタイトルの文書と、Portable Document Format についての説明文が表示され、ナビゲーション コントロールと複数ページのサポート インジケータとともに 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 ビューアのサポートは信頼できます。 ウェブ統合を改善し、コンテンツの表示幅を制御するには、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">×</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">×</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 ドキュメント管理を保証するための完全なエラー処理と検証が含まれています。 ソース コードは、バイナリ データとファイル操作を扱うためのベスト プラクティスを示しています。 データベース PDF 表示に IronPDF を使用する理由 データベースからASP.NETでPDFファイルを表示する機能の実装が、IronPDFを使用することで簡単になります。 このライブラリは、広範なカスタマイズ オプションを提供しながら、 PDF ドキュメントのレンダリングの複雑さを処理します。 シンプルな表示シナリオから複雑なドキュメント操作まで、IronPDF は ASP.NET アプリケーションでのプロフェッショナルなPDF 管理に必要なツールを提供します。 このソリューションが本番環境に対応できる理由は何ですか? この記事で説明する手法は、信頼性の高いドキュメント管理システムを構築するための強固な基盤を提供します。 IronPDF の完全な APIにより、アプリケーションは、基本的なファイルのアップロードと保存から高度なレンダリングと操作機能まで、さまざまなPDF 関連の要件を効率的に処理できるようになります。 このライブラリは、 AzureやAWSなどのクラウド プラットフォームへのデプロイメントもサポートしています。 IronPDF を使い始めるにはどうすればいいですか? ASP.NETアプリケーションでプロフェッショナルなPDF機能を実装する準備はできましたか? 今すぐIronPDF の無料トライアルを開始して、スムーズな PDF 管理の威力を体験してください。 実稼働環境での展開には、ニーズに合わせて拡張できる柔軟なライセンス オプションをご確認ください。 よくある質問 ASP.NETでデータベースからPDFを表示する主な焦点は何ですか? 主な焦点は、ASP.NETウェブアプリケーション内でデータベースから直接PDFを表示する効果的な方法を開発者に提供し、プロジェクトの機能とユーザーエクスペリエンスを向上させることです。 IronPDFはASP.NETでデータベースからPDFを表示するのにどのように役立ちますか? IronPDFは、開発者がデータベースストレージからシームレスにPDFをレンダリングできる強力なライブラリを提供することでプロセスを簡素化し、ASP.NETアプリケーションへのスムーズな統合を保証します。 ASP.NETでのPDF表示にIronPDFを使用する利点は何ですか? IronPDFを使用することで、容易な統合、高品質なレンダリング、またさまざまなPDF機能のサポートなどの利点があり、ASP.NETアプリケーションの使いやすさとパフォーマンスを大きく向上させることができます。 IronPDFはデータベースからの大きなPDFファイルを効率的に処理できますか? はい、IronPDFは大きなPDFファイルを効率的に処理するように設計されており、素早い読み込みとレンダリング時間を保証し、アプリケーションパフォーマンス維持に欠かせません。 IronPDFを使用してASP.NETでPDF表示をカスタマイズすることは可能ですか? もちろん、IronPDFはさまざまなカスタマイズオプションを提供しているため、開発者はASP.NET環境内で特定の要件に従ってPDF表示を調整することができます。 IronPDFはASP.NETアプリケーションでどのファイル形式をPDFに変換できますか? IronPDFは、HTML、画像などのさまざまなファイル形式をPDFに変換することをサポートしており、ASP.NETアプリケーションでの動的コンテンツ生成に特に便利です。 IronPDFはASP.NETアプリケーションでの安全なPDF処理をサポートしていますか? はい、IronPDFは暗号化およびパスワード保護などの安全なPDF処理をサポートしており、ASP.NETアプリケーション内で機密情報を保護するのに役立ちます。 IronPDFは他のIron Software製品と統合して機能を強化できますか? はい、IronPDFはIronOCRやIronBarcodeなど、他のIron Software製品と統合して、ASP.NETアプリケーションでのドキュメント管理と処理に包括的なソリューションを提供できます。 カーティス・チャウ 今すぐエンジニアリングチームとチャット テクニカルライター Curtis Chauは、カールトン大学でコンピュータサイエンスの学士号を取得し、Node.js、TypeScript、JavaScript、およびReactに精通したフロントエンド開発を専門としています。直感的で美しいユーザーインターフェースを作成することに情熱を持ち、Curtisは現代のフレームワークを用いた開発や、構造の良い視覚的に魅力的なマニュアルの作成を楽しんでいます。開発以外にも、CurtisはIoT(Internet of Things)への強い関心を持ち、ハードウェアとソフトウェアの統合方法を模索しています。余暇には、ゲームをしたりDiscordボットを作成したりして、技術に対する愛情と創造性を組み合わせています。 関連する記事 更新日 2026年1月22日 .NETでIronPDFを使ってPDFドキュメントを作成する方法:完全ガイド C#で開発者向けにPDFファイルを作成する効果的な方法を発見します。コーディングスキルを向上させ、プロジェクトを効率化します。この記事を今すぐお読みください! 詳しく読む 更新日 2026年1月21日 VB.NETでPDFファイルをマージする方法:完全なチュートリアル IronPDF で PDF をマージします。シンプルな VB.NET コードを使用して、複数の PDF ファイルを1つのドキュメントに結合する方法を学びます。ステップバイステップの例が含まれています。 詳しく読む 更新日 2026年1月21日 C# PDFWriter チュートリアル:.NETでPDFドキュメントを作成する このステップバイステップガイドで開発者がC# PDFWriterを使用してPDFを効率的に作成する方法を学びます。記事を読んでスキルを向上させましょう! 詳しく読む IronPDF による信頼性の高いASP.NET MVC PDFビューアの構築C#とVB.NETでPDFをTIFFに変換する
更新日 2026年1月22日 .NETでIronPDFを使ってPDFドキュメントを作成する方法:完全ガイド C#で開発者向けにPDFファイルを作成する効果的な方法を発見します。コーディングスキルを向上させ、プロジェクトを効率化します。この記事を今すぐお読みください! 詳しく読む
更新日 2026年1月21日 VB.NETでPDFファイルをマージする方法:完全なチュートリアル IronPDF で PDF をマージします。シンプルな VB.NET コードを使用して、複数の PDF ファイルを1つのドキュメントに結合する方法を学びます。ステップバイステップの例が含まれています。 詳しく読む
更新日 2026年1月21日 C# PDFWriter チュートリアル:.NETでPDFドキュメントを作成する このステップバイステップガイドで開発者がC# PDFWriterを使用してPDFを効率的に作成する方法を学びます。記事を読んでスキルを向上させましょう! 詳しく読む