C#でPDFファイルを保存する方法(初心者向けチュートリアル)
この記事では、IronPDFをどのように使用してWindows Formsアプリケーションまたは任意の.NETアプリケーションからPDFファイルを保存するかについて探ります。
The IronPDF Libraryは、C#アプリケーションでPDFファイルを生成して操作するための簡単に使用できるクラスとメソッドを提供する.NETライブラリです。 これにより、開発者はわずか数行のコードでPDFファイルを作成、変更、保存でき、Windows Formsアプリケーションにとって優れた選択肢となります。
ステップ1: 新しいWindows Formsアプリケーションの作成
まず、新しいVisual Studioプロジェクトを作成します。 Visual Studio 2022で新しいC# Windows Formsアプリケーションを作成する手順は以下の通りです。
- 以下に示すように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キーを押します:
Install-Package IronPdf
このコマンドは、プロジェクトにIronPDFパッケージをダウンロードしてインストールします。 インストールが完了すると、IronPDFの使用を開始できます。
PDFファイルを作成して保存するコードを書く
フローを開始するには、Form1.csクラスにSave_ClickメソッドとgetFilePathメソッドの2つのメソッドを書きます。 これらのメソッドは、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 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ドキュメントに変換する方法を提供するライブラリです。 - メソッドは、その後RenderHtmlAsPdfメソッドを使用して、テキストボックス
pdfContentのHTMLコンテンツをPDFドキュメントに変換します。 このPDFドキュメントは、PdfDocument変数に割り当てられます。 - メソッドは、指定したファイルパスにPDFドキュメントをSaveAsメソッドを使用して保存します。
- 最後に、メソッドは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 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プロパティは、ダイアログボックスが閉じる前に現在のディレクトリを復元するかどうかを指定します。 - メソッドは
SaveFileDialogのShowDialogメソッドを呼び出してダイアログボックスを表示します。 このメソッドはダイアログボックスを表示し、ユーザーが"OK"ボタンまたはキャンセルボタンをクリックしたことを示すDialogResult値を返します。 - ユーザーが"OK"ボタンをクリックした場合、メソッドは
SaveFileDialogのFileNameプロパティにアクセスして、ユーザーが選択したファイルパスを返します。 - ユーザーが"キャンセル"ボタンをクリックするか、ダイアログボックスを閉じた場合、メソッドは空の文字列を返します。
プロジェクトを実行して出力を確認しましょう。 プロジェクトを実行し、次のフォームが開きます。
Running Windows Forms project
PDFコンテンツを入力して、以下に示すように"保存"ボタンをクリックします。
Save dialog box
次のPDFが作成されます。
Created PDF file
IronPDFは、Google Chromeエンジンを使用したChromePdfRendererクラスを提供し、HTMLコンテンツをPDFドキュメントに変換し、SaveFileDialogダイアログボックスを使用してユーザーが選択したファイルパスに保存する簡単な方法を提供します。
結論
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つの価格で入手できるため、コスト効果の高いソリューションです。
よくある質問
C# Windows FormsアプリケーションでPDFファイルをどのように保存できますか?
IronPDFを使用して、テキストボックスやボタンなどのコントロールを設定することにより、C# Windows FormsアプリケーションでPDFファイルを保存できます。ChromePdfRendererクラスを使用してコンテンツをレンダリングし、PDFとして保存するためにSave_Clickメソッドを実装します。
C#を使用してPDFを保存するためにWindows Formsアプリケーションを設定するためにはどのような手順がありますか?
PDFを保存するためのWindows Formsアプリケーションを設定するには、Visual Studioで新しいプロジェクトを作成し、ラベルやリッチテキストボックスなど必要なコントロールを追加し、NuGetパッケージマネージャーを介してIronPDFをインストールして、そのPDFレンダリング機能を利用します。
C# で HTML コンテンツを PDF に変換するにはどうすればよいですか?
C#でHTMLコンテンツをPDFに変換するには、IronPDFのRenderHtmlAsPdfメソッドを使用します。これにより、HTML文字列を直接PDFドキュメントとしてレンダリングできます。
PDF生成のコンテキストでSave_Clickメソッドの役割は何ですか?
Save_Clickメソッドは、アプリケーション内でボタンのクリックイベントをキャプチャして、IronPDFのレンダリングクラスを使用してテキストボックスの内容をPDFファイルにレンダリングするプロセスを開始するイベントハンドラーとして機能します。
C#アプリケーションでPDFを保存するためのファイルパスをユーザーに選択させるにはどのようにしますか?
C#アプリケーションでは、SaveFileDialogクラスを使用して、ファイル選択用のインターフェースを設定し、レンダリングされたPDFを保存するために選択されたパスを返すことで、ファイルパスを選択するようにユーザーに促すことができます。
PDF操作においてIronPDFが提供する高度な機能は何ですか?
IronPDFは、HTMLからPDFへの変換、PDFの結合、PDFページの分割、テキストや画像の抽出などの高度な機能を提供し、.NETアプリケーション内でPDF操作のための包括的なツールセットを提供します。
商業プロジェクトでPDF生成のためにIronPDFを使用する場合、費用はかかりますか?
IronPDFはトライアルライセンスで開発目的には無料ですが、商業プロジェクトには商業ライセンスが必要で、専用のサポートや定期的なアップデートなどの特典を含みます。
Iron Suiteとは何で、開発者にどのような利点がありますか?
Iron Suiteは、バーコード生成、Excelドキュメント管理、PDF処理のためのツールを含む.NETライブラリのコレクションです。これは、アプリケーションに複数の機能を必要とする開発者に対して費用対効果の高いソリューションを提供します。
IronPDF は .NET 10 と互換性がありますか? また、C# で PDF を保存する場合、どのような利点がありますか?
はい。IronPDF は、デスクトップ、Web、クロスプラットフォームのプロジェクトタイプを含む .NET 10 を完全にサポートしています。.NET 10 でビルドすると、ランタイムパフォーマンスの向上、最新の C# 拡張機能へのアクセス、プラットフォーム機能との緊密な統合などの改善が実現し、IronPDF のRenderHtmlAsPdfとSaveAsメソッドによる PDF の作成と保存がより効率的になります。






