フッターコンテンツにスキップ
IRONPDFの使用

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アプリケーションを作成する手順は以下の通りです。

  1. 以下に示すようにVisual Studio 2022を開きます。

C#でPDFファイルを保存する方法(初心者向けチュートリアル)、図1: Visual Studio 2022 Visual Studio 2022

  1. スタートページで"新しいプロジェクトの作成"をクリックするか、「ファイル」>「新しい」>「プロジェクト」に移動します。
  2. "新しいプロジェクトの作成"ダイアログボックスで、以下に示すように"Windows Forms App"または"Windows Forms App (.NET Framework)"を選択します。

C#でPDFファイルを保存する方法(初心者向けチュートリアル)、図2: 新しいForms App New Forms App

  1. プロジェクトの名前を入力し、保存先を選択します。

C#でPDFファイルを保存する方法(初心者向けチュートリアル)、図3: プロジェクトの場所 Project location

  1. .NET Frameworkを選択します。 ドロップダウンメニューから.NET 7.0を選択します。
  2. Createボタンをクリックします。

C#でPDFファイルを保存する方法(初心者向けチュートリアル)、図4: 追加情報 Additional Information

  1. Visual Studioがプロジェクトを作成し、デフォルトのフォーム "Form1" が追加された新しいC# Windows Formsアプリケーションプロジェクトが作成されます。

C#でPDFファイルを保存する方法(初心者向けチュートリアル)、図5: Form1プロジェクト Form1 project

それだけです! 次に、デザイナーを使用してWindows Formsアプリケーションを構築し、コントロールとPDFドキュメントファイルを作成して保存するための機能を追加します。

ステップ2: フォームのデザイン

お好みに応じてフォームをデザインできます。 このチュートリアルでは、2つのラベル、1つのリッチテキストボックス、および2つのボタンを追加することでミニマリストデザインを作成します。

C#でPDFファイルを保存する方法(初心者向けチュートリアル)、図6: フォームへのボタンの追加 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
$vbLabelText   $csharpLabel

このメソッドが行う各ステップの詳細は次のとおりです。

  1. メソッドは、PDFファイルが保存されるファイルパスを取得するためにgetFilePathメソッドを呼び出します。
  2. ファイルパスが空でないか、nullでない場合、メソッドはPDFファイルの保存を続行します。
  3. メソッドは、ChromePdfRendererクラスの新しいインスタンスを作成します。 これは、Google Chromeブラウザーエンジンを使用してHTMLコンテンツをPDFドキュメントに変換する方法を提供するライブラリです。
  4. メソッドは、その後RenderHtmlAsPdfメソッドを使用して、テキストボックスpdfContentのHTMLコンテンツをPDFドキュメントに変換します。 このPDFドキュメントは、PdfDocument変数に割り当てられます。
  5. メソッドは、指定したファイルパスにPDFドキュメントをSaveAsメソッドを使用して保存します。
  6. 最後に、メソッドは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
$vbLabelText   $csharpLabel

このメソッドが行う各ステップの詳細は次のとおりです。

  1. メソッドは、SaveFileDialogクラスの新しいインスタンスを作成します。 このクラスはWindows Formsライブラリの一部で、ユーザーがPDFファイルを保存するファイルパスを選択できるダイアログボックスを提供します。
  2. メソッドは、SaveFileDialogオブジェクトのいくつかのプロパティを設定して、その動作をカスタマイズします。 InitialDirectoryプロパティはダイアログボックスが最初に開くディレクトリを設定します。 Titleプロパティはダイアログボックスのタイトルを設定します。 CheckPathExistsプロパティは、指定されたパスが存在するかどうかをダイアログボックスがチェックするかどうかを指定します。 DefaultExtプロパティは、ファイルタイプのデフォルトファイル拡張子を設定します。 Filterプロパティはダイアログボックスに表示されるファイルタイプフィルターを設定します。 FilterIndexプロパティは表示するデフォルトフィルターを設定します。 最後に、RestoreDirectoryプロパティは、ダイアログボックスが閉じる前に現在のディレクトリを復元するかどうかを指定します。
  3. メソッドはSaveFileDialogShowDialogメソッドを呼び出してダイアログボックスを表示します。 このメソッドはダイアログボックスを表示し、ユーザーが"OK"ボタンまたはキャンセルボタンをクリックしたことを示すDialogResult値を返します。
  4. ユーザーが"OK"ボタンをクリックした場合、メソッドはSaveFileDialogFileNameプロパティにアクセスして、ユーザーが選択したファイルパスを返します。
  5. ユーザーが"キャンセル"ボタンをクリックするか、ダイアログボックスを閉じた場合、メソッドは空の文字列を返します。

プロジェクトを実行して出力を確認しましょう。 プロジェクトを実行し、次のフォームが開きます。

C#でPDFファイルを保存する方法(初心者向けチュートリアル)、図7: Windows Formsプロジェクトの実行 Running Windows Forms project

PDFコンテンツを入力して、以下に示すように"保存"ボタンをクリックします。

C#でPDFファイルを保存する方法(初心者向けチュートリアル)、図8: 保存ダイアログボックス Save dialog box

次のPDFが作成されます。

C#でPDFファイルを保存する方法(初心者向けチュートリアル)、図9: 作成されたPDFファイル Created PDF file

IronPDFは、Google Chromeエンジンを使用したChromePdfRendererクラスを提供し、HTMLコンテンツをPDFドキュメントに変換し、SaveFileDialogダイアログボックスを使用してユーザーが選択したファイルパスに保存する簡単な方法を提供します。

結論

Windows FormsアプリケーションからPDFファイルを保存することは一般的な要件であり、IronPDFはこのタスクを実行するための使いやすく柔軟な方法を提供します。 この記事では、IronPDFを使用してC# Windows Formsアプリケーションでファイルを作成、内容を追加、保存する方法を示しました。 IronPDFを使用すると、開発者はわずか数行のコードでアプリケーションから高品質のPDFファイルを生成できます。

IronPDF offers a range of features such as HTML to PDF Conversion Tutorial, PDF Merging Example Code, Splitting PDF Pages Guide, and Extracting Text and Images How-to, and more. IronPDF is free for development and available under a Commercial License with a Free Trial, which allows developers to use it in commercial projects and includes dedicated support and updates.

加えて、IronPDFは、以下のライブラリを含む.NETソフトウェアコンポーネントのバンドルである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 のRenderHtmlAsPdfSaveAsメソッドによる PDF の作成と保存がより効率的になります。

Curtis Chau
テクニカルライター

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

開発以外にも、CurtisはIoT(Internet of Things)への強い関心を持ち、ハードウェアとソフトウェアの統合方法を模索しています。余暇には、ゲームをしたりDiscordボットを作成したりして、技術に対する愛情と創造性を組み合わせています。