Zum Fußzeileninhalt springen
IRONPDF NUTZEN

5 Schritte zur Generierung einer PDF-Datei in C# mit 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.

Häufig gestellte Fragen

Wie kann ich HTML in PDF in C# konvertieren?

Sie können die Methode RenderHtmlAsPdf von IronPDF verwenden, um HTML-Strings in PDFs zu konvertieren. Erstellen Sie einfach ein HtmlToPdf-Objekt und rufen Sie die Methode auf, um HTML in ein PDF-Dokument zu rendern.

Welche Schritte sind erforderlich, um ein Visual Studio-Projekt zur PDF-Erzeugung einzurichten?

Beginnen Sie mit dem Öffnen von Visual Studio 2019, wählen Sie 'Neues Projekt erstellen', wählen Sie 'Windows Forms App' und benennen Sie Ihr Projekt. Installieren Sie dann IronPDF über NuGet, um mit der Integration von PDF-Erzeugungsfunktionen zu beginnen.

Wie installiere ich eine Bibliothek zur PDF-Erzeugung in Visual Studio?

Sie können IronPDF installieren, indem Sie zur Paket-Manager-Konsole in Visual Studio navigieren und den Befehl: Install-Package IronPdf ausführen.

Welche Komponenten sollten im Formular zur PDF-Erzeugung enthalten sein?

Fügen Sie ein Label zur Führung hinzu, eine Rich Text Box für HTML-Eingaben und eine Schaltfläche mit der Aufschrift 'Konvertieren', die Benutzer anklicken, um das PDF zu erstellen.

Wie implementiere ich den Backend-Code zur Erstellung von PDF-Dateien?

Verwenden Sie IronPDF, um ein HtmlToPdf-Objekt zu deklarieren. Rufen Sie HTML-Eingaben aus einer Textbox ab, fordern Sie den Benutzer auf, das PDF zu speichern, und rendern Sie das HTML mit der Methode RenderHtmlAsPdf.

Welche Funktion hat das HtmlToPdf-Objekt in der PDF-Bibliothek?

Das HtmlToPdf-Objekt in IronPDF wird verwendet, um HTML-Inhalte in PDF-Dokumente umzuwandeln, indem die umfassenden Konvertierungsfunktionen der Bibliothek genutzt werden.

Wie kann ich überprüfen, ob mein PDF-Erzeugungsprojekt korrekt funktioniert?

Führen Sie das Projekt in Visual Studio aus, geben Sie HTML in die RichTextBox ein und klicken Sie auf 'Konvertieren'. Dann verwenden Sie den SaveFileDialog, um einen Speicherort für die PDF-Datei auszuwählen und sicherzustellen, dass die Konvertierung erfolgreich abgeschlossen ist.

Welche erweiterten Funktionen bietet die PDF-Bibliothek?

IronPDF ermöglicht die Erstellung vollständig anpassbarer PDFs sowie das programmatische Zusammenführen und Teilen von Dateien. Die Bibliothek bietet auch Beispielcodes für verschiedene Funktionen.

Kann ich die PDF-Bibliothek vor dem Kauf ausprobieren?

Ja, auf ihrer offiziellen Website ist ein 30-tägiger Testschlüssel für IronPDF verfügbar, mit dem Sie die Funktionen erkunden können, bevor Sie sich zum Kauf entscheiden.

Wo finde ich Lizenzdetails für die PDF-Bibliothek?

Detaillierte Lizenzinformationen für IronPDF finden Sie auf der Webseite der IronPDF-Lizenzinformationen, einschließlich Optionen und aktueller Angebote.

Ist IronPDF mit .NET 10 kompatibel?

Ja – IronPDF unterstützt bereits alle modernen .NET-Versionen und ist mit der kommenden .NET 10-Version, die für November 2025 geplant ist, kompatibel. Es funktioniert sofort mit .NET 10-Projekten, ohne dass zusätzliche Anpassungen erforderlich sind. (ironpdf.com/blog/using-ironpdf/5-steps-to-generate-a-pdf-file-in-c-sharp/)

Curtis Chau
Technischer Autor

Curtis Chau hat einen Bachelor-Abschluss in Informatik von der Carleton University und ist spezialisiert auf Frontend-Entwicklung mit Expertise in Node.js, TypeScript, JavaScript und React. Leidenschaftlich widmet er sich der Erstellung intuitiver und ästhetisch ansprechender Benutzerschnittstellen und arbeitet gerne mit modernen Frameworks sowie der Erstellung gut strukturierter, optisch ansprechender ...

Weiterlesen