
How to Display a PDF File in ASP.NET Core
この記事では、IronPDFをどのように使用してWindows Formsアプリケーションまたは任意 for .NETアプリケーションからPDFファイルを保存するかについて探ります。
The IronPDF Libraryは、C#アプリケーションでPDFファイルを生成して操作するための簡単に使用できるクラスとメソッドを提供する.NETライブラリです。 これにより、開発者はわずか数行のコードでPDFファイルを作成、変更、保存でき、Windows Formsアプリケーションにとって優れた選択肢となります。
ステップ1: 新しいWindows Formsアプリケーションの作成
まず、新しいVisual Studioプロジェクトを作成します。 ここでは、Visual Studio 2022で新しいC# Windows Forms Applicationを作成する手順を示します。
-
以下に示すようにVisual Studio 2022を開きます。
Visual Studio 2022 -
スタートページで"新しいプロジェクトの作成"をクリックするか、"ファイル">"新しい">"プロジェクト"に移動します。
-
"新しいプロジェクトの作成"ダイアログボックスで、以下に示すように"Windows Forms App"または"Windows Forms App (.NET Framework)"を選択します。
New Forms App -
プロジェクトの名前を入力し、保存先を選択します。
Project location -
.NET Frameworkを選択します。 ドロップダウンメニューから.NET 7.0を選択します。
-
Createボタンをクリックします。
Additional Information -
Visual Studioがプロジェクトを作成し、デフォルトのフォーム "Form1" が追加された新しいC# Windows Formsアプリケーションプロジェクトが作成されます。
Form1 project
それだけです! 次に、デザイナーを使用してWindows Formsアプリケーションを構築し、コントロールとPDFドキュメントファイルを作成して保存するための機能を追加します。
ステップ2: フォームのデザイン
お好みに応じてフォームをデザインできます。 このチュートリアルでは、2つのラベル、1つのリッチテキストボックス、および2つのボタンを追加することでミニマリストデザインを作成します。
Adding buttons to form
ステップ3: IronPDFのインストール
次のステップは、このプロジェクトにIronPDFをインストールして、豊富な機能を利用します。
IronPDFはVisual StudioのNuGetパッケージマネージャーを使用してインストールできます。 NuGetパッケージマネージャコンソールに移動するには、ツール > NuGetパッケージマネージャ > パッケージマネージャコンソールに行きます。
次のコマンドを入力し、Enterキーを押します:
このコマンドは、プロジェクトにIronPDFパッケージをダウンロードしてインストールします。 インストールが完了すると、IronPDFの使用を開始できます。
PDFファイルを作成して保存するコードを書く
流れを開始するには、Form1.csクラスに書いてください。 これらのメソッドは、ChromePdfRendererクラスライブラリーを使用してテキストボックスの内容をPDFファイルとして保存するために使用されます。 各メソッドを確認して、それがどのように機能するかを理解しましょう。
Save_Click メソッド (PDF ドキュメントを作成)
次のメソッドは、ボタンのクリックイベントのイベントハンドラーです。 このメソッドの目的は、テキストボックスの内容をPDFファイルとして保存することです。
private void Save_Click(object sender, EventArgs e)
{
// Get the file path to save the PDF file.
string filename = getFilePath();
// If the file path is not empty or null, proceed with saving the PDF file.
if (!String.IsNullOrEmpty(filename))
{
// Create a new instance of the ChromePdfRenderer class.
var renderer = new ChromePdfRenderer();
// Render the file contents of the text box as a PDF document using the ChromePdfRenderer.
var pdfDocument = renderer.RenderHtmlAsPdf(pdfContent.Text);
// Save the PDF document to the specified file path using the SaveAs method.
pdfDocument.SaveAs(filename);
// Show a message box to indicate that the PDF file has been saved successfully.
MessageBox.Show("PDF has been saved Successfully!");
}
}Private Sub Save_Click(ByVal sender As Object, ByVal e As EventArgs)
' Get the file path to save the PDF file.
Dim filename As String = getFilePath()
' If the file path is not empty or null, proceed with saving the PDF file.
If Not String.IsNullOrEmpty(filename) Then
' Create a new instance of the ChromePdfRenderer class.
Dim renderer = New ChromePdfRenderer()
' Render the file contents of the text box as a PDF document using the ChromePdfRenderer.
Dim pdfDocument = renderer.RenderHtmlAsPdf(pdfContent.Text)
' Save the PDF document to the specified file path using the SaveAs method.
pdfDocument.SaveAs(filename)
' Show a message box to indicate that the PDF file has been saved successfully.
MessageBox.Show("PDF has been saved Successfully!")
End If
End Subこのメソッドが行う各ステップの詳細は次のとおりです。
- メソッドはPDFファイルが節約されるファイルパスを取得するために
getFilePathメソッドを呼び出します。 - ファイルパスが空でないか、nullでない場合、メソッドはPDFファイルの保存を続行します。
- メソッドは
ChromePdfRendererクラスの新しいインスタンスを作成します。 これは、Google Chromeブラウザーエンジンを使用してHTMLコンテンツをPDFドキュメントに変換する方法を提供するライブラリです。 - メソッドは、その後、
ChromePdfRendererクラスのRenderHtmlAsPdfメソッドを使用して、テキストボックスpdfContentのHTMLコンテンツをPDFドキュメントに変換します。 このPDFドキュメントは、PdfDocument変数に割り当てられます。 - メソッドは、
PdfDocumentクラスのSaveAsメソッドを使用して、指定されたファイルパスにPDFドキュメントを節約します。 - 最後に、メソッドはPDFファイルが正常に保存されたことを示すメッセージボックスを表示します。
getFilePathメソッド (PDFファイルを保存する)
このメソッドは、ユーザーがPDFファイルが節約されるファイルパスを選択するためのSaveFileDialogを表示するために使用されます。
public string getFilePath()
{
// Create a new instance of the SaveFileDialog class.
SaveFileDialog saveFileDialog1 = new SaveFileDialog();
// Set the initial directory where the SaveFileDialog will open.
saveFileDialog1.InitialDirectory = @"D:\";
// Set the title of the SaveFileDialog.
saveFileDialog1.Title = "Save the PDF Files";
// Set the SaveFileDialog to check if the specified path exists.
saveFileDialog1.CheckPathExists = true;
// Set the default extension for the file type.
saveFileDialog1.DefaultExt = ".pdf";
// Set the filter to display only PDF files or all files.
saveFileDialog1.Filter = "PDF files (*.pdf)|*.pdf|All files (*.*)|*.*";
// Set the filter index to display the PDF filter as the default.
saveFileDialog1.FilterIndex = 2;
// Set the RestoreDirectory property to true so that the SaveFileDialog
// restores the current directory before closing.
saveFileDialog1.RestoreDirectory = true;
// Show the SaveFileDialog and get the result.
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
// If the user clicked the OK button in the SaveFileDialog, return the selected file path.
return saveFileDialog1.FileName;
}
// If the user did not click the OK button, return an empty string.
return String.Empty;
}Public Function getFilePath() As String
' Create a new instance of the SaveFileDialog class.
Dim saveFileDialog1 As New SaveFileDialog()
' Set the initial directory where the SaveFileDialog will open.
saveFileDialog1.InitialDirectory = "D:\"
' Set the title of the SaveFileDialog.
saveFileDialog1.Title = "Save the PDF Files"
' Set the SaveFileDialog to check if the specified path exists.
saveFileDialog1.CheckPathExists = True
' Set the default extension for the file type.
saveFileDialog1.DefaultExt = ".pdf"
' Set the filter to display only PDF files or all files.
saveFileDialog1.Filter = "PDF files (*.pdf)|*.pdf|All files (*.*)|*.*"
' Set the filter index to display the PDF filter as the default.
saveFileDialog1.FilterIndex = 2
' Set the RestoreDirectory property to true so that the SaveFileDialog
' restores the current directory before closing.
saveFileDialog1.RestoreDirectory = True
' Show the SaveFileDialog and get the result.
If saveFileDialog1.ShowDialog() = DialogResult.OK Then
' If the user clicked the OK button in the SaveFileDialog, return the selected file path.
Return saveFileDialog1.FileName
End If
' If the user did not click the OK button, return an empty string.
Return String.Empty
End Functionこのメソッドが行う各ステップの詳細は次のとおりです。
- メソッドは
SaveFileDialogクラスの新しいインスタンスを作成します。 このクラスはWindows Formsライブラリの一部で、ユーザーがPDFファイルを保存するファイルパスを選択できるダイアログボックスを提供します。 - メソッドは、
SaveFileDialogオブジェクトのいくつかのプロパティを設定して、その動作をカスタマイズします。InitialDirectoryプロパティは、ダイアログボックスが最初に開かれるディレクトリを設定します。Titleプロパティは、ダイアログボックスのタイトルを設定します。CheckPathExistsプロパティは、指定されたパスが存在するかどうかをダイアログボックスが確認すべきかどうかを指定します。DefaultExtプロパティは、ファイルタイプのデフォルトのファイル拡張子を設定します。Filterプロパティは、ダイアログボックスに表示されるファイルタイプフィルターを設定します。FilterIndexプロパティは、表示されるデフォルトのフィルターを設定します。 最後に、RestoreDirectoryプロパティは、ダイアログボックスが閉じる前に現在のディレクトリを復元するかどうかを指定します。 - メソッドは、
ShowDialogメソッドを呼び出します。 このメソッドはダイアログボックスを表示し、ユーザーが"OK"ボタンをクリックしたかキャンセルボタンをクリックしたかを示すDialogResult値を返します。 - ユーザーが"OK"ボタンをクリックした場合、メソッドはユーザーが選択したファイルパスを
FileNameのプロパティにアクセスすることで返します。 - ユーザーが"キャンセル"ボタンをクリックするか、ダイアログボックスを閉じた場合、メソッドは空の文字列を返します。
プロジェクトを実行して出力を確認しましょう。 プロジェクトを実行し、次のフォームが開きます。
Running Windows Forms project
PDFコンテンツを入力して、以下に示すように"保存"ボタンをクリックします。
Save dialog box
次のPDFが作成されます。
Created PDF file
IronPDFは、SaveFileDialogダイアログボックスを使用して、HTMLコンテンツをPDFドキュメントに簡単に変換し、ユーザーが選択したファイルパスに節約できます。
結論
Windows FormsアプリケーションからPDFファイルを保存することは一般的な要件であり、IronPDFはこのタスクを実行するための使いやすく柔軟な方法を提供します。 この記事では、IronPDFを使用してC# Windows Formsアプリケーションでファイルを作成、内容を追加、保存する方法を示しました。 IronPDFを使用すると、開発者はわずか数行のコードでアプリケーションから高品質のPDFファイルを生成できます。
IronPDFは、HTMLからPDFへの変換チュートリアル、PDFのマージ例、PDFページの分割ガイド、およびテキストと画像の抽出ハウツーなどの一連の機能を提供します。 IronPDFは開発用に無料で、商用プロジェクトで使用することを可能にする商用ライセンスおよび無料試用版と共に利用可能であり、専用のサポートとアップデートが含まれています。
加えて、IronPDFは、以下のライブラリを含む.NETソフトウェアコンポーネントのバンドルであるIron Suiteの一部でもあります。
- バーコード生成 (IronBarcode)、
- エクセル管理 (IronXL)、
- テキスト抽出 (IronOCR)
[Iron Suiteの購入](Iron Suite)は、5つの製品すべてを2つの価格で入手できるため、コスト効果の高いソリューションです。

Curtis Chauは、カールトン大学でコンピュータサイエンスの学士号を取得し、Node.js、TypeScript、JavaScript、およびReactに精通したフロントエンド開発を専門としています。直感的で美しいユーザーインターフェースを作成することに情熱を持ち、Curtisは現代のフレームワークを用いた開発や、構造の良い視覚的に魅力的なマニュアルの作成を楽しんでいます。
関連する記事


