IRONPDFの使用

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

更新済み 5月 23, 2023
共有:

この記事では、IronPDFを使用してWindows Formsアプリケーションや任意の.NETアプリケーションからPDFファイルを保存する方法について探ります。

IronPDF は、C#アプリケーションでPDFファイルを生成および操作するための、使いやすいクラスとメソッドを提供する.NETライブラリです。 数行のコードでPDFファイルを作成、修正、および保存することができるため、Windows Formsアプリケーションに最適な選択肢となります。

ステップ1: 新しいWindows Formsアプリケーションを作成する

まず、新しいVisual Studioプロジェクトを作成します。 Visual Studio 2022で新しいC# Windows Formsアプリケーションを作成する手順は以下の通りです。

  1. 以下のようにVisual Studio 2022を開いてください。

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

    Visual Studio 2022

(Visual Studio 2022)

  1. スタートページで「新しいプロジェクトを作成」をクリックするか、「ファイル」 > 「新規」 > 「プロジェクト」に進んでください。

  2. 「新しいプロジェクトの作成」ダイアログボックスで、「Windows Forms App」または「Windows Forms App」を選択します。 (.NETフレームワーク)「新しいプロジェクトを作成する」の下に、以下のように表示されます。

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

    新しいFormsアプリ

  3. プロジェクトの名前を入力し、保存する場所を選択してください。

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

    プロジェクトの場所

  4. .NETフレームワークを選択してください。 ドロップダウンメニューから.NET 7.0を選択してください。

  5. Createボタンをクリックしてください。

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

    追加情報

  6. Visual Studio は、新しい C# Windows Forms アプリケーション プロジェクトを作成します。プロジェクトには、デフォルトのフォーム「Form1」が追加され、以下のように表示されます。

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

    Form1プロジェクト

    以上です! では、デザイナーを使用して、Windowsフォームアプリケーションの構築を開始し、PDFドキュメントファイルを作成および保存するためのコントロールと機能を追加します。

ステップ2: フォームの設計

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

PDFファイルをC#で保存する方法(初心者チュートリアル)、図6:フォームにボタンを追加する

フォームにボタンを追加

ステップ3:IronPDFのインストール

次のステップとして、このプロジェクトにIronPDFをインストールして、豊富な機能を活用します。

IronPDFは、Visual StudioのNuGetパッケージマネージャーを使用してインストールできます。 ツール > NuGet パッケージ マネージャー > パッケージ マネージャー コンソール に移動することで、NuGet パッケージ マネージャー コンソールにアクセスできます。

次のコマンドを入力し、Enterキーを押してください:

Install-Package IronPdf

このコマンドは、あなたのプロジェクトにIronPDFパッケージをダウンロードしてインストールします。 インストールが完了したら、IronPDFの使用を開始できます。

PDFファイルを作成して保存するコードを記述する

以下の内容を日本語に翻訳してください:

まず最初に、Form1.csクラス内に Save_ClickgetFilePath の2つのメソッドを書きます。これらのメソッドは一緒に使用され、テキストボックスの内容をPDFファイルとして保存します。 ChromePdfRenderer ライブラリ。 各メソッドの動作を理解するために、順番に見ていきましょう。

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(filePath))
    {
        // 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(filePath))
    {
        // 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(filePath) 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
VB   C#

このメソッドが行う処理の詳細な手順は以下の通りです:

  1. メソッドは、PDFファイルが保存されるファイルパスを取得するために、getFilePathメソッドを呼び出します。

  2. ファイルパスが空でないか null でない場合、メソッドはPDFファイルの保存を続行します。

  3. このメソッドはChromePdfRendererクラスの新しいインスタンスを作成します。 これは、Google Chrome ブラウザエンジンを使用してHTMLコンテンツをPDFドキュメントに変換するためのライブラリです。

  4. その後、メソッドは RenderHtmlAsPdf ChromePdfRenderer クラスのメソッドを使用して、テキスト ボックス pdfContent の HTML コンテンツを PDF ドキュメントに変換します。 このPDFドキュメントは次のものに割り当てられています PdfDocument(PDFドキュメント) 変数。

  5. メソッドは、指定されたファイルパスにPDFドキュメントを保存します。 SaveAs PdfDocumentクラスのメソッド。

  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 "";
}
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 "";
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
VB   C#

このメソッドが行う処理の詳細な手順は以下の通りです:

  1. このメソッドは SaveFileDialog クラスの新しいインスタンスを作成します。 このクラスはWindows Formsライブラリの一部であり、ユーザーがPDFファイルを保存するファイルパスを選択できるダイアログボックスを提供します。

  2. このメソッドは、SaveFileDialogオブジェクトの動作をカスタマイズするために、いくつかのプロパティを設定します。 InitialDirectoryプロパティは、ダイアログボックスが最初に開かれるディレクトリを設定します。 Title プロパティはダイアログボックスのタイトルを設定します。 CheckPathExists プロパティは、指定されたパスが存在するかどうかをダイアログボックスが確認するかどうかを指定します。 DefaultExt プロパティはファイルタイプのデフォルトファイル拡張子を設定します。 Filterプロパティは、ダイアログボックスに表示されるファイルタイプのフィルターを設定します。 FilterIndex プロパティは、表示するデフォルトのフィルターを設定します。 最後に、RestoreDirectory プロパティは、ダイアログボックスが閉じる前に現在のディレクトリを復元するかどうかを指定します。

  3. このメソッドは ShowDialog メソッドを呼び出して SaveFileDialog を表示します。 このメソッドはダイアログボックスを表示し、ユーザーが「OK」ボタンまたはキャンセルボタンをクリックしたかどうかを示す DialogResult 値を返します。

  4. ユーザーが「OK」ボタンをクリックすると、メソッドは SaveFileDialogFileName プロパティにアクセスして、ユーザーが選択したファイルパスを返します。

  5. ユーザーが「キャンセル」ボタンをクリックするか、ダイアログボックスを閉じた場合、メソッドは空の文字列を返します。

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

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

    Windows Formsプロジェクトの実行

    PDFコンテンツを入力し、以下に示す「保存」ボタンをクリックしてください。

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

    保存ダイアログボックス

    次のPDFが作成されました。

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

    作成されたPDFファイル

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

結論

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

IronPDFは、次のような様々な機能を提供します: HTMLからPDFへの変換PDF マージ 以下のコンテンツを日本語に翻訳してください: 分割, テキストおよび画像の抽出など。 IronPDFは開発用として無料で利用可能で、 商用ライセンス と一緒に 無料トライアルそれは、開発者が商用プロジェクトで使用できるようにし、専用のサポートとアップデートを含みます。 加えて、IronPDFは アイアン スイートこれは、バーコード生成のためのライブラリを含む.NETソフトウェアコンポーネントのバンドルです (IronBarcode)Excelドキュメントの作成、読み取り、操作 (IronXL) テキスト抽出の作業 (IronOCR)など。 完全な Iron Suite を購入することは、2 つの料金で 5 つの製品すべてを手に入れることができるため、コストパフォーマンスの高いソリューションです。

< 以前
C#でCSHTMLをPDFに変換する方法
次へ >
Blazorでバイト配列からPDFを表示する方法

準備はできましたか? バージョン: 2024.9 新発売

無料のNuGetダウンロード 総ダウンロード数: 10,659,073 View Licenses >