Saltar al pie de página
USANDO IRONPDF

5 pasos para Generar un Archivo PDF en C# usando 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.

Preguntas Frecuentes

¿Cómo puedo convertir HTML a PDF en C#?

Puedes usar el método RenderHtmlAsPdf de IronPDF para convertir cadenas HTML en PDFs. Simplemente crea un objeto HtmlToPdf y llama al método para renderizar HTML en un documento PDF.

¿Qué pasos están involucrados en configurar un proyecto de Visual Studio para la generación de PDFs?

Comienza abriendo Visual Studio 2019, selecciona 'Crear un nuevo proyecto', elige 'Aplicación de formularios de Windows', y establece el nombre de tu proyecto. Luego, instala IronPDF a través de NuGet para empezar a integrar capacidades de generación de PDFs.

¿Cómo instalo una biblioteca de generación de PDF en Visual Studio?

Puedes instalar IronPDF navegando a la Consola del administrador de paquetes en Visual Studio y ejecutando el comando: Install-Package IronPdf.

¿Qué componentes se deben incluir en el formulario para generar PDFs?

Incluye una etiqueta para orientación, un cuadro de texto enriquecido para la entrada HTML y un botón etiquetado como 'Convertir' que los usuarios harán clic para generar el PDF.

¿Cómo implemento el código de back-end para la creación de archivos PDF?

Usa IronPDF para declarar un objeto HtmlToPdf. Recupera la entrada de HTML de un cuadro de texto, invita al usuario a guardar el PDF y renderiza el HTML con el método RenderHtmlAsPdf.

¿Cuál es la función del objeto HtmlToPdf en la biblioteca PDF?

El objeto HtmlToPdf en IronPDF se usa para transformar contenido HTML en documentos PDF usando las funciones de conversión completas de la biblioteca.

¿Cómo puedo verificar que mi proyecto de generación de PDF está funcionando correctamente?

Ejecuta el proyecto en Visual Studio, ingresa HTML en el RichTextBox y haz clic en 'Convertir'. Luego, usa el cuadro de diálogo Guardar archivo para seleccionar una ubicación para el archivo PDF, asegurando que la conversión se completa con éxito.

¿Qué características avanzadas ofrece la biblioteca PDF?

IronPDF permite crear PDFs totalmente personalizables, así como fusionar y dividir archivos programáticamente. La biblioteca también proporciona códigos de muestra para varias funcionalidades.

¿Puedo probar la biblioteca PDF antes de comprarla?

Sí, está disponible una clave de prueba de 30 días para IronPDF en su sitio web oficial, permitiéndote explorar sus características antes de comprometerte a una compra.

¿Dónde puedo encontrar detalles de licencias para la biblioteca PDF?

La información detallada sobre las licencias de IronPDF se encuentra en la página de Información de Licencias de IronPDF en su sitio web, incluyendo opciones y ofertas actuales.

¿IronPDF es compatible con .NET 10?

Sí. IronPDF ya es compatible con todas las versiones modernas de .NET y con la próxima versión de .NET 10, prevista para noviembre de 2025. Funciona de inmediato con proyectos de .NET 10 sin necesidad de soluciones alternativas adicionales. (ironpdf.com/blog/using-ironpdf/5-steps-to-generate-a-pdf-file-in-c-sharp/)

Curtis Chau
Escritor Técnico

Curtis Chau tiene una licenciatura en Ciencias de la Computación (Carleton University) y se especializa en el desarrollo front-end con experiencia en Node.js, TypeScript, JavaScript y React. Apasionado por crear interfaces de usuario intuitivas y estéticamente agradables, disfruta trabajando con frameworks modernos y creando manuales bien ...

Leer más