Published May 24, 2023
How to Save PDF File in C# (Beginner Tutorial)
PDFs are a widely used file format for sharing documents and information electronically. In a C# Windows Form Application, there are many ways to save a PDF file, but one of the easiest and most flexible methods is to use the IronPDF library. In this article, we will explore how to use IronPDF to save PDF files from a Windows Form Application or any .NET Applications.
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 Form Applications.
Step 1: Create a New Windows forms application
First, we will need to create a new Visual Studio Project. Here are the steps to create a new C# Windows Form Application in Visual Studio 2022
Open Visual Studio 2022 as shown below.
Click on "Create a new project" on the start page or go to "File" > "New" > "Project".
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.
Enter a name for your project and choose a location to save it to.
Choose .NET Framework. I have selected .NET 7.0 from the drop-down menu.
Click on the "Create" Button.
Visual Studio will create a new C# Windows Form Application project for you, with a default form named "Form1" added to the project as shown below.
That's it! Now we will start building our Windows Form 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. We made a minimalistic design by adding two labels, one rich text box and two buttons.
Step 3: Install IronPDF
We need to install IronPDF in our project for using 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:
PM > Install-Package IronPdf
This command will download and install the IronPDF package in your project. Once installed, we can start using IronPDF in our code.
Write Code to Create and Save PDF File
We need to 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 they work.
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(pdfContents.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(pdfContents.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(pdfContents.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
Here's a step-by-step breakdown of what this method does:
- The method calls the
getFilePath
method to get the file path where the PDF file will be saved. - If the file path is not empty or null, the method proceeds with saving the PDF file.
- 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. - The method then uses the
RenderHtmlAsPdf
method of theChromePdfRenderer
class to convert the HTML content of the text boxpdfContent
into a PDF document. This PDF document is assigned to thepdfDocument
variable. - The method saves the PDF document to the specified file path using the
SaveAs
method of thePdfDocument
class. - 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
Here's a step-by-step breakdown of what this method does:
- 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. - The method sets several properties of the
SaveFileDialog
object to customize its behavior. TheInitialDirectory
property sets the directory where the dialog box will first open. TheTitle
property sets the title of the dialog box. TheCheckPathExists
property specifies whether the dialog box should check if the specified path exists. TheDefaultExt
property sets the default file extension for the file type. TheFilter
property sets the file type filters that are displayed in the dialog box. TheFilterIndex
property sets the default filter to display. Finally, theRestoreDirectory
property specifies whether the dialog box should restore the current directory before closing. - The method shows the
SaveFileDialog
by calling itsShowDialog
method. This method displays the dialog box and returns aDialogResult
value that indicates whether the user clicked the "OK" button or the Cancel button. - If the user clicked the "OK" button, the method returns the file path that the user selected by accessing the
FileName
property of theSaveFileDialog
. - If the user clicked the "Cancel" button or closed 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.
Enter your PDF content and click on the "Save" button as shown below.
The following PDF is created.
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 Form Application is a common requirement, and IronPDF provides an easy-to-use and flexible method to accomplish this task. In this article, we explored how to use IronPDF to create, add content, and save files in a C# Windows Form 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 30-day 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 (Iron Barcode), creating, reading, and manipulating Excel documents (IronXL) working with text extraction (Iron OCR), and more. Purchasing the complete Iron Suite is a cost-effective solution as you can get all five products for the price of two.