Zum Fußzeileninhalt springen
IRONPDF NUTZEN
Wie man eine PDF aus einer Vorlage in C# generiert | IronPDF

Wie man ein PDF aus einer Vorlage in C# generiert

PDF documents are prevalent in today's culture, used by various enterprises for creating invoices and other documents. When selecting a .NET Library for projects, the ease of creating, reading, and writing PDF files should be considered.

IronPDF Features

IronPDF is one of the best HTML-to-PDF converters available on the market. IronPDF can handle almost any operation that a browser is capable of handling. It can create PDF files from HTML5, JavaScript, CSS, and images. The .NET PDF library makes it simple to produce/generate PDF files, read existing PDFs, and edit PDF files. Possible modifications include changing font sizes, pagination, text content, etc. Users of IronPDF can create form fields in rendered PDF documents.

IronPDF is compatible with all .NET Framework project types, including ASP.NET, Windows Forms, and other traditional Windows Application types. IronPDF is capable of rendering ASPX, Razor, and other MVC view components directly into PDFs.

IronPDF's full set of features include:

  • Convert images to PDFs (and PDF pages into images)
  • Merge and split PDFs
  • Complete PDF forms programmatically
  • Extract text and images from PDFs
  • IronPDF can convert picture files as well as HTML files to PDF
  • Create PDFs from web pages, HTML markup, and offline HTML documents
  • Generate PDFs from web pages locked behind HTML login forms.
  • Annotate PDFs.
  • Add headers, footers, text, images, bookmarks, watermarks, and more

Creating a New Project in Visual Studio

This article will demonstrate IronPDF's document generation abilities with a simple Console Application.

Open Visual Studio software and go to the File menu. Select "New project", and then select "Console App".

How to Generate PDF from Template in C#, Figure 1: New Project New Project

Specify the project name and its location. Click on the Next button and choose a .NET Framework.

How to Generate PDF from Template in C#, Figure 2: .NET Framework Selection .NET Framework Selection

Finally, click on Create to generate the new Visual Studio project.

How to Generate PDF from Template in C#, Figure 3: .NET Program.cs .NET Program.cs

3. Install the IronPDF Library

The IronPDF library can be downloaded and installed in four ways.

These four ways are:

  • Use Visual Studio.
  • Use the Visual Studio Command-Line.
  • Download from the NuGet website directly.
  • Download from the IronPDF website directly.

3.1 Using Visual Studio

The NuGet Package Manager is available in the Visual Studio software for easy installation of packages from NuGet. The below screenshot shows how to open the NuGet Package Manager GUI.

How to Generate PDF from Template in C#, Figure 4: NuGet Package Manager NuGet Package Manager

Search for "IronPDF" in the Browse tab of the Package Manager GUI.

How to Generate PDF from Template in C#, Figure 5: IronPDF Installation IronPDF Installation

Choose the IronPdf package (first option) and click on the Install button to add it to the Solution.

3.2 Using the Visual Studio Command-Line

In Visual Studio, go to Tools > NuGet Package Manager > Package Manager Console

Enter the following command in the Package Manager Console tab and press ENTER.

Install-Package IronPdf

How to Generate PDF from Template in C#, Figure 6: Install IronPDF Install IronPDF

3.3 Download from the NuGet Website Directly

  • Navigate to the IronPDF NuGet package page.
  • Click the Download package from the menu on the right-hand side.
  • Double-click the downloaded package from within Windows Explorer to install it in your project automatically.

3.4 Download from the IronPDF Website Directly

Download the IronPDF ZIP file directly with the latest version of the IronPDF package.

Once downloaded, follow the steps below to add the package to the project.

  • Right-click the project from the Solution Explorer window.
  • Then, select the option Reference and browse the location of the downloaded reference.
  • Next, click OK to add the reference.

4. Create a PDF Document from Template

The code example below shows how to create PDF files from the given HTML template with just a few lines of code.

using System;
using System.Collections.Generic;
using System.Text;
using IronPdf;

class Program
{
    static void Main()
    {
        // Create an instance of ChromePdfRenderer
        var renderer = new IronPdf.ChromePdfRenderer();

        // Render the HTML as PDF and save it as Test.pdf
        renderer.RenderHtmlAsPdf(BuildTemplate()).SaveAs("Test.pdf");
    }

    /// <summary>
    /// Builds an HTML template string using StringBuilder
    /// </summary>
    /// <returns>HTML string representation of a table</returns>
    static string BuildTemplate()
    {
        var builder = new StringBuilder();
        builder.Append("<table border='1'>");
        builder.Append("<tr>");
        builder.Append("<th>");
        builder.Append("Cat Family");
        builder.Append("</th>");
        builder.Append("</tr>");

        // Iterate over the data and populate the table rows
        foreach (var item in GetData())
        {
            builder.Append("<tr>");
            builder.Append("<td>");
            builder.Append(item.ToString());
            builder.Append("</td>");
            builder.Append("</tr>");
        }

        builder.Append("</table>");
        return builder.ToString();
    }

    /// <summary>
    /// Provides a list of data representing different members of the cat family
    /// </summary>
    /// <returns>List of strings</returns>
    static List<string> GetData()
    {
        List<string> data = new List<string>
        {
            "Lion",
            "Tiger",
            "Cat",
            "Cheetah",
            "Lynx"
        };

        return data;
    }
}
using System;
using System.Collections.Generic;
using System.Text;
using IronPdf;

class Program
{
    static void Main()
    {
        // Create an instance of ChromePdfRenderer
        var renderer = new IronPdf.ChromePdfRenderer();

        // Render the HTML as PDF and save it as Test.pdf
        renderer.RenderHtmlAsPdf(BuildTemplate()).SaveAs("Test.pdf");
    }

    /// <summary>
    /// Builds an HTML template string using StringBuilder
    /// </summary>
    /// <returns>HTML string representation of a table</returns>
    static string BuildTemplate()
    {
        var builder = new StringBuilder();
        builder.Append("<table border='1'>");
        builder.Append("<tr>");
        builder.Append("<th>");
        builder.Append("Cat Family");
        builder.Append("</th>");
        builder.Append("</tr>");

        // Iterate over the data and populate the table rows
        foreach (var item in GetData())
        {
            builder.Append("<tr>");
            builder.Append("<td>");
            builder.Append(item.ToString());
            builder.Append("</td>");
            builder.Append("</tr>");
        }

        builder.Append("</table>");
        return builder.ToString();
    }

    /// <summary>
    /// Provides a list of data representing different members of the cat family
    /// </summary>
    /// <returns>List of strings</returns>
    static List<string> GetData()
    {
        List<string> data = new List<string>
        {
            "Lion",
            "Tiger",
            "Cat",
            "Cheetah",
            "Lynx"
        };

        return data;
    }
}
Imports System
Imports System.Collections.Generic
Imports System.Text
Imports IronPdf

Friend Class Program
	Shared Sub Main()
		' Create an instance of ChromePdfRenderer
		Dim renderer = New IronPdf.ChromePdfRenderer()

		' Render the HTML as PDF and save it as Test.pdf
		renderer.RenderHtmlAsPdf(BuildTemplate()).SaveAs("Test.pdf")
	End Sub

	''' <summary>
	''' Builds an HTML template string using StringBuilder
	''' </summary>
	''' <returns>HTML string representation of a table</returns>
	Private Shared Function BuildTemplate() As String
		Dim builder = New StringBuilder()
		builder.Append("<table border='1'>")
		builder.Append("<tr>")
		builder.Append("<th>")
		builder.Append("Cat Family")
		builder.Append("</th>")
		builder.Append("</tr>")

		' Iterate over the data and populate the table rows
		For Each item In GetData()
			builder.Append("<tr>")
			builder.Append("<td>")
			builder.Append(item.ToString())
			builder.Append("</td>")
			builder.Append("</tr>")
		Next item

		builder.Append("</table>")
		Return builder.ToString()
	End Function

	''' <summary>
	''' Provides a list of data representing different members of the cat family
	''' </summary>
	''' <returns>List of strings</returns>
	Private Shared Function GetData() As List(Of String)
		Dim data As New List(Of String) From {"Lion", "Tiger", "Cat", "Cheetah", "Lynx"}

		Return data
	End Function
End Class
$vbLabelText   $csharpLabel

In the above code:

  • First, we create an instance of the IronPDF ChromePdfRenderer class to access PDF creation features.
  • Next, we call RenderHtmlAsPdf passing the HTML string built by the BuildTemplate method. This method converts the HTML into a PDF.
  • The BuildTemplate method uses a StringBuilder to construct an HTML table populated with data.
  • GetData returns a list of strings representing the 'cat family', which fills the rows of the HTML table.

Below is the sample PDF file, generated from the above code with just a few lines using the given template.

How to Generate PDF from Template in C#, Figure 7: Generated PDF File Generated PDF File

Any type of HTML tag can be used to create a template that can help the user generate user forms, receipts, etc., with a sample template but different data.

It is possible to use the method RenderUrlAsPdf or RenderHtmlFileAsPdf to generate PDF files from different sources. The former method accepts a URL to a webpage, while the latter accepts a string containing the location of an HTML file on the computer.

Read this tutorial for generating PDFs from HTML for more information.

Conclusion

Use IronPDF in production without a watermark with a free trial key. IronPDF comes with SaaS and OEM Redistribution licensing for an additional cost. To know more, refer to the IronPDF Licensing page.

Häufig gestellte Fragen

Wie kann ich ein PDF aus einer HTML-Vorlage mit C# generieren?

Sie können IronPDF verwenden, um ein PDF aus einer HTML-Vorlage in C# zu generieren. Erstellen Sie zuerst einen HTML-String mit Datenplatzhaltern mithilfe der StringBuilder-Klasse. Füllen Sie dann die Vorlage mit Ihren Daten und verwenden Sie die RenderHtmlAsPdf-Methode von IronPDF, um das HTML in ein PDF-Dokument umzuwandeln.

Welche Methoden bietet IronPDF zur Konvertierung von HTML in PDF?

IronPDF bietet verschiedene Methoden zur Konvertierung von HTML in PDF, einschließlich RenderHtmlAsPdf für HTML-Strings, RenderHtmlFileAsPdf für lokale HTML-Dateien und RenderUrlAsPdf für Webseiten nach URL. Diese Methoden ermöglichen eine flexible PDF-Erstellung aus verschiedenen HTML-Quellen.

Wie installiere ich IronPDF in meinem C#-Projekt?

Um IronPDF in einem C#-Projekt zu installieren, können Sie den NuGet-Paketmanager in Visual Studio verwenden. Suchen Sie nach 'IronPDF' und klicken Sie auf Installieren oder verwenden Sie die Paket-Manager-Konsole mit dem Befehl Install-Package IronPdf.

Kann IronPDF komplexes HTML5 und JavaScript beim Umwandeln in PDF verarbeiten?

Ja, IronPDF kann komplexes HTML5 und JavaScript verarbeiten und sicherstellen, dass die Umwandlung von komplexen Webseiten in PDF-Dokumente die beabsichtigte Formatierung und Funktionalität beibehält.

Was sind einige gängige Anwendungen zum Erstellen von PDFs aus Vorlagen in C#?

Gängige Anwendungen zum Erstellen von PDFs aus Vorlagen in C# umfassen das Erstellen von Rechnungen, Berichten und Formularen. IronPDF ermöglicht es Ihnen, diese Prozesse zu automatisieren, indem dynamische HTML-Vorlagen mit Daten in professionelle PDF-Dokumente umgewandelt werden.

Ist IronPDF mit ASP.NET und Windows Forms kompatibel?

Ja, IronPDF ist mit verschiedenen .NET Framework-Projekttypen kompatibel, einschließlich ASP.NET und Windows Forms, was es vielseitig für verschiedene Anwendungsentwicklungsumgebungen macht.

Wie kann ich ein neues Visual Studio-Projekt erstellen, um IronPDF für die PDF-Erstellung zu verwenden?

Um ein neues Visual Studio-Projekt zur Verwendung von IronPDF zu erstellen, öffnen Sie Visual Studio, wählen 'Neues Projekt', wählen 'Konsolenanwendung', geben den Projektnamen und den Speicherort an, wählen ein .NET-Framework aus und klicken 'Erstellen'. Anschließend installieren Sie IronPDF über NuGet.

Kann IronPDF PDFs von gesicherten Webseiten mit Anmeldeformularen generieren?

Ja, IronPDF kann PDFs von Webseiten generieren, die eine Authentifizierung über HTML-Anmeldeformulare erfordern, sodass Sie sichere und geschützte Webinhalte effektiv bearbeiten können.

Ist IronPDF vollständig mit .NET 10 kompatibel und was genau beinhaltet diese Unterstützung?

Ja, IronPDF ist vollständig mit .NET 10 kompatibel. Es funktioniert sofort in .NET 10-Projekten ohne zusätzliche Konfiguration, unterstützt moderne Bereitstellungsziele (Windows, Linux, Container) und nutzt die neuen Leistungsverbesserungen von .NET 10, während API und Funktionsumfang unverändert bleiben. (Quelle: IronPDF-Dokumentation zur Kompatibilität mit .NET 10)

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