Skip to footer content
USING IRONPDF

5 steps to Generate a PDF File in C# using IRON PDF

Generating PDFs in C# using IronPDF

C# developers can use IronPDF to generate PDFs from HTML. This article will demonstrate this process with a C# Windows Forms application created using the .NET Framework.

Please follow these steps to create a project in Visual Studio 2019.

Step 1. Create a Visual Studio Project

First, open Visual Studio 2019.

Main Window of Visual Studio 2019

Click on 'Create a new project'.

Now, select 'Windows Forms App' from the Template, and press 'Next'. The following window will appear:

Create a New Project Window

Enter the Project Name 'Create PDF using IronPDF'.

Set Name of the Project

Click on the 'Create' button. The Project will be created as shown below.

First window after creating a new project

Step 2. Install IronPDF using NuGet

  • First, click the 'Tools' button on the Menu bar.
  • A menu will open. Now click on the NuGet Package Manager Option.
  • Another submenu will open. Now click on the option named Package Manager Console.

Open Package Manager Console window

You will get a new screen under the command line. In it, write the command to install the IronPdf package.

Install-Package IronPdf

Enter command window

Press Enter after typing the command. Make sure your computer/laptop is connected to the Internet. The IronPdf package will automatically add to your existing project.

Successfully Package Install window

The screen above shows the package added successfully to your project.

Step 3. Design Form for User Input

Now add a label and set the text to "Create a PDF from HTML using IronPDF".

Set a Label Window

Next, add a Rich Text Box and a Button from the Toolbox. Set the Button Text as 'Convert'.

Design RichText Box And Button window

Step 4. Write Back-end Code to Create PDF File

Double-click on the 'Convert' button. A code window with a convert button click event will open.

Back-end code window

Add code for importing the IronPDF library at the top of the .cs file.

First, add the following code to use IronPDF Library methods.

using IronPdf;
using IronPdf;
Imports IronPdf
$vbLabelText   $csharpLabel

Below is the initial code for the btnConvert_Click event, which is currently empty:

private void btnConvert_Click(object sender, EventArgs e)
{

}
private void btnConvert_Click(object sender, EventArgs e)
{

}
Private Sub btnConvert_Click(ByVal sender As Object, ByVal e As EventArgs)

End Sub
$vbLabelText   $csharpLabel

Now write the following code in the button click event:

private void btnConvert_Click(object sender, EventArgs e)
{
    // Declare an HtmlToPdf object
    var HtmlLine = new HtmlToPdf();

    // Get HTML text from the user
    string strHtml = txtHtml.Text;

    // Create SaveFileDialog to choose the save path for the PDF file
    SaveFileDialog saveFileDialog = new SaveFileDialog
    {
        InitialDirectory = @"D:\",
        Title = "Save PDF",
        CheckPathExists = true,
        DefaultExt = "pdf",
        Filter = "pdf files (*.pdf)|*.pdf",
        FilterIndex = 2,
        RestoreDirectory = true
    };

    // If the user presses Save
    if (saveFileDialog.ShowDialog() == DialogResult.OK)
    {
        // Get the file path from the user
        string filePath = saveFileDialog.FileName;

        // Convert HTML to PDF and save at the specified path
        using var PDF = HtmlLine.RenderHtmlAsPdf(strHtml);
        PDF.SaveAs(filePath);

        // Clear the TextBox and show a message confirming the successful creation
        txtHtml.Text = "";
        MessageBox.Show("File created successfully.");
    }
}
private void btnConvert_Click(object sender, EventArgs e)
{
    // Declare an HtmlToPdf object
    var HtmlLine = new HtmlToPdf();

    // Get HTML text from the user
    string strHtml = txtHtml.Text;

    // Create SaveFileDialog to choose the save path for the PDF file
    SaveFileDialog saveFileDialog = new SaveFileDialog
    {
        InitialDirectory = @"D:\",
        Title = "Save PDF",
        CheckPathExists = true,
        DefaultExt = "pdf",
        Filter = "pdf files (*.pdf)|*.pdf",
        FilterIndex = 2,
        RestoreDirectory = true
    };

    // If the user presses Save
    if (saveFileDialog.ShowDialog() == DialogResult.OK)
    {
        // Get the file path from the user
        string filePath = saveFileDialog.FileName;

        // Convert HTML to PDF and save at the specified path
        using var PDF = HtmlLine.RenderHtmlAsPdf(strHtml);
        PDF.SaveAs(filePath);

        // Clear the TextBox and show a message confirming the successful creation
        txtHtml.Text = "";
        MessageBox.Show("File created successfully.");
    }
}
Private Sub btnConvert_Click(ByVal sender As Object, ByVal e As EventArgs)
	' Declare an HtmlToPdf object
	Dim HtmlLine = New HtmlToPdf()

	' Get HTML text from the user
	Dim strHtml As String = txtHtml.Text

	' Create SaveFileDialog to choose the save path for the PDF file
	Dim saveFileDialog As New SaveFileDialog With {
		.InitialDirectory = "D:\",
		.Title = "Save PDF",
		.CheckPathExists = True,
		.DefaultExt = "pdf",
		.Filter = "pdf files (*.pdf)|*.pdf",
		.FilterIndex = 2,
		.RestoreDirectory = True
	}

	' If the user presses Save
	If saveFileDialog.ShowDialog() = DialogResult.OK Then
		' Get the file path from the user
		Dim filePath As String = saveFileDialog.FileName

		' Convert HTML to PDF and save at the specified path
		Dim PDF = HtmlLine.RenderHtmlAsPdf(strHtml)
		PDF.SaveAs(filePath)

		' Clear the TextBox and show a message confirming the successful creation
		txtHtml.Text = ""
		MessageBox.Show("File created successfully.")
	End If
End Sub
$vbLabelText   $csharpLabel

Explanation:

  • An HtmlToPdf object is created to utilize IronPDF's conversion capabilities.
  • The HTML input is retrieved from a text box.
  • A SaveFileDialog is used to prompt the user to specify where the resulting PDF should be saved.
  • If the user chooses a file location and presses Save, the path is obtained.
  • The HTML input is then rendered to a PDF using RenderHtmlAsPdf and saved to the chosen path.
  • After saving, the text box is cleared, and a message box is displayed to confirm the PDF creation.

Step 5. Run the Project

When you run the project, you will see the following screen:

Write HTML in RichTextBox window

Enter HTML code in the RichTextBox, for example:

<h1>A Simple PDF File</h1><br><h6>Heading 6</h6>
<h1>A Simple PDF File</h1><br><h6>Heading 6</h6>
HTML

Click on 'Convert'. You will get a save file dialog.

Set Output file path & name window

Once you click the save button, the file will be saved at your specified path with the name and location defined.

Output File

The output PDF document will look like this:

Output file

Conclusion

The tutorial above explains creating a PDF from HTML using the IronPDF Library.

For more information, visit the IronPDF Official Site. The library also provides other functionalities that support fully customizable PDF files, merging and splitting files programmatically, or simply checking sample codes demonstrating various features.

You can evaluate it using the 30-day trial key. There's currently an excellent offer available where you can get five Iron Software products for the price of just two. Visit this IronPDF Licensing Information for more information about licensing.

Frequently Asked Questions

What is the PDF generation library discussed?

IronPDF is a C# library that allows developers to generate PDF files from HTML, facilitating the creation, editing, and management of PDF documents programmatically.

How do I create a new Visual Studio project for PDF generation?

To create a new project, open Visual Studio 2019, select 'Create a new project', choose 'Windows Forms App' from the template options, and set your project name before clicking 'Create'.

How can I install the PDF library in my project?

You can install IronPDF using NuGet by opening the Package Manager Console in Visual Studio and typing the command: Install-Package IronPdf.

What steps are necessary to design a form for generating PDFs?

Add a label to the form for instructions, a Rich Text Box for HTML input, and a Button labeled 'Convert' to trigger the PDF generation.

How do I write backend code to create a PDF file?

Use the IronPDF library to declare an HtmlToPdf object. Retrieve HTML input from a text box, prompt the user to specify where to save the PDF, and render the HTML to a PDF using the RenderHtmlAsPdf method.

What is the role of the object for converting HTML in the PDF library?

The HtmlToPdf object in IronPDF is used to convert HTML strings into PDF documents, leveraging the library's conversion capabilities.

How can I test my project for generating PDFs?

Run the project in Visual Studio, enter some HTML code in the RichTextBox, and click 'Convert'. Use the SaveFileDialog to specify where to save the resulting PDF file.

What are some additional features of the PDF library?

IronPDF supports fully customizable PDF files, merging and splitting files programmatically, and offers sample codes demonstrating various features.

Is there a trial available for the PDF library?

Yes, you can evaluate IronPDF using a 30-day trial key available on their official site.

Where can I find more information about licensing for the PDF library?

Visit the IronPDF Licensing Information page on their website to learn more about licensing options and current offers.

Chipego
Software Engineer
Chipego has a natural skill for listening that helps him to comprehend customer issues, and offer intelligent solutions. He joined the Iron Software team in 2023, after studying a Bachelor of Science in Information Technology. IronPDF and IronOCR are the two products Chipego has been focusing on, but his knowledge of all products is growing daily, as he finds new ways to support customers. He enjoys how collaborative life is at Iron Software, with team members from across the company bringing their varied experience to contribute to effective, innovative solutions. When Chipego is away from his desk, he can often be found enjoying a good book or playing football.