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.
Click on 'Create a new project'.
Now, select 'Windows Forms App' from the Template, and press 'Next'. The following window will appear:
Enter the Project Name 'Create PDF using IronPDF'.
Click on the 'Create' button. The Project will be created as shown below.
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.
You will get a new screen under the command line. In it, write the command to install the IronPdf
package.
Install-Package IronPdf
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.
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".
Next, add a Rich Text Box and a Button from the Toolbox. Set the Button Text as 'Convert'.
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.
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
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
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
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:
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>
Click on 'Convert'. You will get a save file dialog.
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:
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
How can I convert HTML to PDF in C#?
You can use IronPDF's RenderHtmlAsPdf
method to convert HTML strings into PDFs. Simply create an HtmlToPdf
object and call the method to render HTML into a PDF document.
What steps are involved in setting up a Visual Studio project for PDF generation?
Begin by opening Visual Studio 2019, select 'Create a new project', choose 'Windows Forms App', and set your project name. Then, install IronPDF via NuGet to start integrating PDF generation capabilities.
How do I install a PDF generation library in Visual Studio?
You can install IronPDF by navigating to the Package Manager Console in Visual Studio and executing the command: Install-Package IronPdf
.
What components should be included in the form to generate PDFs?
Include a label for guidance, a Rich Text Box for HTML input, and a Button labeled 'Convert' that users will click to generate the PDF.
How do I implement the backend code for PDF file creation?
Use IronPDF to declare an HtmlToPdf
object. Retrieve HTML input from a text box, prompt the user to save the PDF, and render the HTML with the RenderHtmlAsPdf
method.
What is the function of the HtmlToPdf object in the PDF library?
The HtmlToPdf
object in IronPDF is used to transform HTML content into PDF documents using the library's comprehensive conversion features.
How can I verify my PDF generation project is functioning correctly?
Execute the project in Visual Studio, input HTML into the RichTextBox, and click 'Convert'. Then, use the SaveFileDialog to select a location for the PDF file, ensuring the conversion is completed successfully.
What advanced features does the PDF library offer?
IronPDF allows for creating fully customizable PDFs, as well as merging and splitting files programmatically. The library also provides sample codes for various functionalities.
Can I trial the PDF library before purchasing?
Yes, a 30-day trial key for IronPDF is available on their official website, allowing you to explore its features before committing to a purchase.
Where can I find licensing details for the PDF library?
Detailed licensing information for IronPDF can be found on the IronPDF Licensing Information page on their website, including options and current offers.