USING IRONPDF

How to Save PDF File in C# (Beginner Tutorial)

Updated March 10, 2024
Share:

This article will explore how to use IronPDF to save PDF files from a Windows Forms Application or any .NET Application.

IronPDF is a .NET library that provides easy-to-use classes and Methods for generating and working with PDF files in C# applications. It allows developers to create, modify, and save PDF files with just a few lines of code, making it an excellent choice for Windows Forms Applications.

Step 1: Create a New Windows Forms application

First, create a new Visual Studio Project. Here are the steps to create a new C# Windows Forms Application in Visual Studio 2022

  1. Open Visual Studio 2022 as shown below.

    How to Save PDF File in C# (Beginner Tutorial), Figure 1: Visual Studio 2022 Visual Studio 2022

  2. Click on "Create a new project" on the start page or go to "File" > "New" > "Project".
  3. In the "Create a new project" dialog box, select "Windows Forms App" or "Windows Forms App (.NET Framework)" under "Create a new project" as shown below.

    How to Save PDF File in C# (Beginner Tutorial), Figure 2: New Forms App New Forms App

  4. Enter a name for your project and choose a location to save it to.

    How to Save PDF File in C# (Beginner Tutorial), Figure 3: Project location Project location

  5. Choose .NET Framework. Select .NET 7.0 from the drop-down menu.
  6. Click on the Create button.

    How to Save PDF File in C# (Beginner Tutorial), Figure 4: Additional Information Additional Information

  7. Visual Studio will create a new C# Windows Forms Application project for you, with a default form named "Form1" added to the project as shown below.

    How to Save PDF File in C# (Beginner Tutorial), Figure 5: Form1 project Form1 project

That's it! Now we will start building the Windows Forms Application using the designer, adding controls and functionality for creating and saving a PDF document file.

Step 2: Design the Form

You can design the form as per your preferences. This tutorial will make a minimalistic design by adding two labels, one rich text box and two buttons.

How to Save PDF File in C# (Beginner Tutorial), Figure 6: Adding buttons to form Adding buttons to form

Step 3: Install IronPDF

The next step is to install IronPDF in this project to use its rich functionalities.

IronPDF can be installed using NuGet Package Manager in Visual Studio. You can navigate to the NuGet Package Manager Console by going to Tools > NuGet Package Manager > Package Manager Console.

Type the following command and press Enter:

Install-Package IronPdf

This command will download and install the IronPDF package in your project. Once installed, we can start using IronPDF.

Write Code to Create and Save PDF File

To start with the flow, write two methods: Save_Click and getFilePath in Form1.cs class These methods are used together to save the content of a text box as a PDF file using the ChromePdfRenderer library. Let's go through each method to understand how it works.

Save_Click Method (Create PDF Document)

The following method is an event handler for a button-click event. The purpose of this method is to save the content of a text box as a PDF file.

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#

Here's a step-by-step breakdown of what this method does:

  1. The method calls the getFilePath method to get the file path where the PDF file will be saved.
  2. If the file path is not empty or null, the method proceeds with saving the PDF file.
  3. The method creates a new instance of the ChromePdfRenderer class. This is a library that provides a way to convert HTML content into PDF documents using the Google Chrome browser engine.
  4. The method then uses the RenderHtmlAsPdf method of the ChromePdfRenderer class to convert the HTML content of the text box pdfContent into a PDF document. This PDF document is assigned to the PdfDocument variable.
  5. The method saves the PDF document to the specified file path using the SaveAs method of the PdfDocument class.
  6. Finally, the method shows a message box to indicate that the PDF file has been saved successfully.

getFilePath Method (Save PDF Files)

This method is used to display a SaveFileDialog to the user to select a file path where the PDF file will be saved.

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 "";
}
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 ""
End Function
VB   C#

Here's a step-by-step breakdown of what this method does:

  1. The method creates a new instance of the SaveFileDialog class. This class is part of the Windows Forms library and provides a dialog box that allows the user to select a file path where the PDF file will be saved.
  2. The method sets several properties of the SaveFileDialog object to customize its behavior. The InitialDirectory property sets the directory where the dialog box will first open. The Title property sets the title of the dialog box. The CheckPathExists property specifies whether the dialog box should check if the specified path exists. The DefaultExt property sets the default file extension for the file type. The Filter property sets the file type filters that are displayed in the dialog box. The FilterIndex property sets the default filter to display. Finally, the RestoreDirectory property specifies whether the dialog box should restore the current directory before closing.
  3. The method shows the SaveFileDialog by calling its ShowDialog method. This method displays the dialog box and returns a DialogResult value that indicates whether the user clicked the "OK" button or the Cancel button.
  4. If the user clicks the "OK" button, the method returns the file path that the user selected by accessing the FileName property of the SaveFileDialog.
  5. If the user clicks the "Cancel" button or closes the dialog box, the method returns an empty string.

Let's run the project and see the output. Run the project, and the following form will open.

How to Save PDF File in C# (Beginner Tutorial), Figure 7: Running Windows Forms project Running Windows Forms project

Enter your PDF content and click on the "Save" button as shown below.

How to Save PDF File in C# (Beginner Tutorial), Figure 8: Save dialog box Save dialog box

The following PDF is created.

How to Save PDF File in C# (Beginner Tutorial), Figure 9: Created PDF file Created PDF file

IronPDF provides a simple way to convert HTML content into PDF documents and save them to a user-selected file path using the ChromePdfRenderer class and the SaveFileDialog dialog box.

Conclusion

Saving PDF files from a Windows Forms Application is a common requirement, and IronPDF provides an easy-to-use and flexible method to accomplish this task. This article demonstrated how to use IronPDF to create, add content, and save files in a C# Windows Forms Application. With IronPDF, developers can generate high-quality PDF files from their applications with just a few lines of code.

IronPDF offers a range of features such as HTML to PDF conversion, PDF merging and splitting, text and image extraction, and more. Iron PDF 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. Additionally, IronPDF is part of the Iron Suite, which is a bundle of .NET software components that includes libraries for barcode generation (IronBarcode), creating, reading, and manipulating Excel documents (IronXL) working with text extraction (IronOCR), and more. Purchasing the complete Iron Suite is a cost-effective solution as you can get all five products for the price of two.

< PREVIOUS
How to Convert CSHTML to PDF in C#
NEXT >
How to Display PDF From Byte Array in Blazor

Ready to get started? Version: 2024.10 just released

Free NuGet Download Total downloads: 11,308,499 View Licenses >