Saltar al pie de página
USANDO IRONPDF

Cómo crear archivos PDF en .NET Core

Creating a PDF document programmatically is a common approach and a frequent requirement in modern web applications. Whether you're building invoices, reports, or any document-based system, knowing how to create PDF files efficiently in ASP applications and .NET Core is essential. In this tutorial, we'll explore the best methods to handle the task .NET Core create PDF files using IronPDF. This is a powerful .NET Core library that simplifies PDF generation capabilities. For comprehensive technical details, refer to the official documentation.

Getting Started with IronPDF

IronPDF is a comprehensive .NET Core PDF library that transforms complex PDF creation into straightforward operations. Unlike traditional approaches that require drawing elements manually, IronPDF leverages HTML markup and CSS to generate PDF files that match your exact design requirements.

To begin creating PDFs in your .NET Core library project, install the IronPDF NuGet package using Visual Studio's Package Manager Console by running the following command:

Install-Package IronPdf

This simple installation provides immediate access to robust PDF generation capabilities for your web applications.

Creating Your First PDF Document

Let's create a simple PDF document to understand the basics. The following example demonstrates generating PDFs with formatted content:

using IronPdf;
// Create a new ChromePdfRenderer object
var renderer = new ChromePdfRenderer();
// Define HTML content with styling
var html = @"
    <html>
        <body style='font-family: Arial; margin: 40px;'>
            <h1>Hello World PDF Document</h1>
            <p>This is your first PDF file created with IronPDF!</p>
        </body>
    </html>";
// Generate PDF from HTML
var pdf = renderer.RenderHtmlAsPdf(html);
// Save the PDF document
pdf.SaveAs("output.pdf");
using IronPdf;
// Create a new ChromePdfRenderer object
var renderer = new ChromePdfRenderer();
// Define HTML content with styling
var html = @"
    <html>
        <body style='font-family: Arial; margin: 40px;'>
            <h1>Hello World PDF Document</h1>
            <p>This is your first PDF file created with IronPDF!</p>
        </body>
    </html>";
// Generate PDF from HTML
var pdf = renderer.RenderHtmlAsPdf(html);
// Save the PDF document
pdf.SaveAs("output.pdf");
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

This code creates a new PdfDocument object which will create a new PDF by rendering HTML content. The ChromePdfRenderer handles the conversion, ensuring your PDF documents maintain consistent formatting.

Output

Converting HTML to PDF with Advanced Features

IronPDF excels at converting complex web pages and HTML content into professional PDF files. The following code explores how create a new PDF document with more advanced features like tables, images, and styled elements works:

public void CreateAdvancedPdf()
{
    var renderer = new ChromePdfRenderer();
    // Configure rendering options
    renderer.RenderingOptions.MarginTop = 25;
    renderer.RenderingOptions.MarginBottom = 25;
    var html = @"
        <html>
        <head>
            <style>
                table { width: 100%; border-collapse: collapse; }
                th, td { padding: 10px; border: 1px solid #ddd; }
                th { background-color: #f2f2f2; }
            </style>
        </head>
        <body>
            <h2>Sales Report</h2>
            <table>
                <tr>
                    <th>Product</th>
                    <th>Quantity</th>
                    <th>Total</th>
                </tr>
                <tr>
                    <td>Software License</td>
                    <td>10</td>
                    <td>$500</td>
               </tr>
            </table>
        </body>
        </html>";
    // Create PDF file
    var pdf = renderer.RenderHtmlAsPdf(html);
    pdf.SaveAs("report.pdf");
}
public void CreateAdvancedPdf()
{
    var renderer = new ChromePdfRenderer();
    // Configure rendering options
    renderer.RenderingOptions.MarginTop = 25;
    renderer.RenderingOptions.MarginBottom = 25;
    var html = @"
        <html>
        <head>
            <style>
                table { width: 100%; border-collapse: collapse; }
                th, td { padding: 10px; border: 1px solid #ddd; }
                th { background-color: #f2f2f2; }
            </style>
        </head>
        <body>
            <h2>Sales Report</h2>
            <table>
                <tr>
                    <th>Product</th>
                    <th>Quantity</th>
                    <th>Total</th>
                </tr>
                <tr>
                    <td>Software License</td>
                    <td>10</td>
                    <td>$500</td>
               </tr>
            </table>
        </body>
        </html>";
    // Create PDF file
    var pdf = renderer.RenderHtmlAsPdf(html);
    pdf.SaveAs("report.pdf");
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

This example shows how to create PDF documents with formatted tables, demonstrating IronPDF's ability to handle complex layouts and CSS styling.

Output

How to Create PDF Files in .NET Core: Figure 2 - PDF with Advanced Features

Working with ASP.NET Core Applications

Integrating PDF generation in ASP.NET Core MVC views is straightforward. Here's an example project implementation for generating PDFs from a controller:

using Microsoft.AspNetCore.Mvc;
using IronPdf;
using System.IO;
public class DocumentController : Controller
{
    public IActionResult GeneratePdf()
    {
        var renderer = new ChromePdfRenderer();
        // Create HTML content
        var html = "<h1>Invoice</h1><p>Thank you for your purchase!</p>";
        // Generate PDF
        var pdf = renderer.RenderHtmlAsPdf(html);
        byte[] pdfBytes = pdf.BinaryData;
    // Return PDF file using the byte array, setting the content type to PDF
    return File(pdfBytes,
            "application/pdf",
            "document.pdf");
       }
    }
}
using Microsoft.AspNetCore.Mvc;
using IronPdf;
using System.IO;
public class DocumentController : Controller
{
    public IActionResult GeneratePdf()
    {
        var renderer = new ChromePdfRenderer();
        // Create HTML content
        var html = "<h1>Invoice</h1><p>Thank you for your purchase!</p>";
        // Generate PDF
        var pdf = renderer.RenderHtmlAsPdf(html);
        byte[] pdfBytes = pdf.BinaryData;
    // Return PDF file using the byte array, setting the content type to PDF
    return File(pdfBytes,
            "application/pdf",
            "document.pdf");
       }
    }
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

This controller method generates a PDF document and returns it as a downloadable file, perfect for server-side processing in web applications. You could also make use of a new MemoryStream object to handle the PDF document creation.

Output

How to Create PDF Files in .NET Core: Figure 3 - PDF generated with our ASP.NET controller

Advanced PDF Generation Techniques

IronPDF supports numerous advanced features for creating PDFs. You can add headers, footers, page numbers, and even merge multiple PDF files:

public void CreatePdfWithHeaderFooter()
{
    var renderer = new ChromePdfRenderer();
    // Add header
    renderer.RenderingOptions.TextHeader = new TextHeaderFooter
    {
        CenterText = "Company Report",
        DrawDividerLine = true
    };
    // Add footer with page numbers
    renderer.RenderingOptions.TextFooter = new TextHeaderFooter
    {
        CenterText = "Page {page} of {total-pages}",
        DrawDividerLine = true
    };
    var html = "<h1>Annual Report</h1><p>Content goes here...</p>";
    var pdf = renderer.RenderHtmlAsPdf(html);
    // Save the new document
    pdf.SaveAs("report-with-header.pdf");
}
// Merge multiple PDFs
public void MergePdfFiles()
{
    var renderer = new ChromePdfRenderer();
    var pdf1 = renderer.RenderHtmlAsPdf("<p>First Document</p>");
    var pdf2 = renderer.RenderHtmlAsPdf("<p>Second Document</p>");
    // Merge PDF documents
    var merged = PdfDocument.Merge(pdf1, pdf2);
    merged.SaveAs("merged.pdf");
}
// Example of iterating over something, illustrating 'int i' and 'index'
public void ProcessMultipleFiles(string[] filePaths)
{
    for (int i = 0; i < filePaths.Length; i++)
    {
        // Use 'i' as an index to process each source file
        var source file = filePaths[i];
        Console.WriteLine($"Processing file at index {i}: {source file}");
        // Imagine code here to load or process the file
        // var pdf = PdfDocument.FromFile(sourceFile); // load
    }
}
public void CreatePdfWithHeaderFooter()
{
    var renderer = new ChromePdfRenderer();
    // Add header
    renderer.RenderingOptions.TextHeader = new TextHeaderFooter
    {
        CenterText = "Company Report",
        DrawDividerLine = true
    };
    // Add footer with page numbers
    renderer.RenderingOptions.TextFooter = new TextHeaderFooter
    {
        CenterText = "Page {page} of {total-pages}",
        DrawDividerLine = true
    };
    var html = "<h1>Annual Report</h1><p>Content goes here...</p>";
    var pdf = renderer.RenderHtmlAsPdf(html);
    // Save the new document
    pdf.SaveAs("report-with-header.pdf");
}
// Merge multiple PDFs
public void MergePdfFiles()
{
    var renderer = new ChromePdfRenderer();
    var pdf1 = renderer.RenderHtmlAsPdf("<p>First Document</p>");
    var pdf2 = renderer.RenderHtmlAsPdf("<p>Second Document</p>");
    // Merge PDF documents
    var merged = PdfDocument.Merge(pdf1, pdf2);
    merged.SaveAs("merged.pdf");
}
// Example of iterating over something, illustrating 'int i' and 'index'
public void ProcessMultipleFiles(string[] filePaths)
{
    for (int i = 0; i < filePaths.Length; i++)
    {
        // Use 'i' as an index to process each source file
        var source file = filePaths[i];
        Console.WriteLine($"Processing file at index {i}: {source file}");
        // Imagine code here to load or process the file
        // var pdf = PdfDocument.FromFile(sourceFile); // load
    }
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

These examples demonstrate adding professional touches to your PDF documents and combining multiple files into a single document.

How to Create PDF Files in .NET Core: Figure 4 - PDF created with simple, custom header and footers

Working with Forms and Dynamic Content

IronPDF can create interactive PDF documents with form fields:

public void CreatePdfWithForm()
{
    var html = @"
    <!DOCTYPE html>
    <html>
    <head>
        <title>PDF Test Form</title>
        <style>
            body {
                font-family: Arial, sans-serif;
                margin: 20px;
                background-color: #f4f4f4;
            }
            .form-container {
                width: 400px;
                padding: 20px;
                border: 1px solid #ccc;
                border-radius: 8px;
                background-color: #fff;
                box-shadow: 2px 2px 5px rgba(0,0,0,0.1);
            }
            .form-group {
                margin-bottom: 15px;
            }
            label {
                display: block; /* Make label take up full width */
                margin-bottom: 5px;
                font-weight: bold;
                color: #333;
            }
            input[type='text'], textarea {
                width: 100%;
                padding: 10px;
                border: 1px solid #ddd;
                border-radius: 4px;
                box-sizing: border-box; /* Include padding and border in the element's total width and height */
            }
            textarea {
                height: 100px;
                resize: vertical;
            }
            .checkbox-group {
                display: flex;
                align-items: center;
            }
            .checkbox-group label {
                display: inline;
                font-weight: normal;
                margin-left: 8px;
            }
        </style>
    </head>
    <body>
        <div class='form-container'>
            <h2>Document Generation Test Form</h2>
            <form>
                <div class='form-group'>
                    <label for='fullName'>Full Name:</label>
                </div>
                <div class='form-group'>
                    <label for='comments'>Comments/Feedback:</label>
                    <textarea id='comments' name='comments' placeholder='Type your feedback here...'></textarea>
                </div>
                <div class='form-group checkbox-group'>
                    <label for='agree'>I agree to the terms and conditions.</label>
                </div>
                <button style='padding: 10px 15px; background-color: #007bff; color: white; border: none; border-radius: 4px; cursor: pointer;'>
                    Test Button Rendering
                </button>
            </form>
        </div>
    </body>
    </html>";
    var renderer = new ChromePdfRenderer();
    renderer.RenderingOptions.CreatePdfFormsFromHtml = true;
    var pdf = renderer.RenderHtmlAsPdf(html);
    pdf.SaveAs("form.pdf");
}
public void CreatePdfWithForm()
{
    var html = @"
    <!DOCTYPE html>
    <html>
    <head>
        <title>PDF Test Form</title>
        <style>
            body {
                font-family: Arial, sans-serif;
                margin: 20px;
                background-color: #f4f4f4;
            }
            .form-container {
                width: 400px;
                padding: 20px;
                border: 1px solid #ccc;
                border-radius: 8px;
                background-color: #fff;
                box-shadow: 2px 2px 5px rgba(0,0,0,0.1);
            }
            .form-group {
                margin-bottom: 15px;
            }
            label {
                display: block; /* Make label take up full width */
                margin-bottom: 5px;
                font-weight: bold;
                color: #333;
            }
            input[type='text'], textarea {
                width: 100%;
                padding: 10px;
                border: 1px solid #ddd;
                border-radius: 4px;
                box-sizing: border-box; /* Include padding and border in the element's total width and height */
            }
            textarea {
                height: 100px;
                resize: vertical;
            }
            .checkbox-group {
                display: flex;
                align-items: center;
            }
            .checkbox-group label {
                display: inline;
                font-weight: normal;
                margin-left: 8px;
            }
        </style>
    </head>
    <body>
        <div class='form-container'>
            <h2>Document Generation Test Form</h2>
            <form>
                <div class='form-group'>
                    <label for='fullName'>Full Name:</label>
                </div>
                <div class='form-group'>
                    <label for='comments'>Comments/Feedback:</label>
                    <textarea id='comments' name='comments' placeholder='Type your feedback here...'></textarea>
                </div>
                <div class='form-group checkbox-group'>
                    <label for='agree'>I agree to the terms and conditions.</label>
                </div>
                <button style='padding: 10px 15px; background-color: #007bff; color: white; border: none; border-radius: 4px; cursor: pointer;'>
                    Test Button Rendering
                </button>
            </form>
        </div>
    </body>
    </html>";
    var renderer = new ChromePdfRenderer();
    renderer.RenderingOptions.CreatePdfFormsFromHtml = true;
    var pdf = renderer.RenderHtmlAsPdf(html);
    pdf.SaveAs("form.pdf");
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

This creates an interactive PDF with form fields that users can fill out, perfect for applications requiring user input. The code also shows where an HTML link might be used within the generated content.

Output PDF with Editable Form

How to Create PDF Files in .NET Core: Figure 5 - PDF with fillable form

Best Practices and Error Handling

When generating PDF files in production, implement proper error handling:

try
{
    var renderer = new ChromePdfRenderer();
    var pdf = renderer.RenderHtmlAsPdf(html);
    pdf.SaveAs("output.pdf");
}
catch (Exception ex)
{
    // Log error and handle appropriately
    Console.WriteLine($"PDF generation failed: {ex.Message}");
}
try
{
    var renderer = new ChromePdfRenderer();
    var pdf = renderer.RenderHtmlAsPdf(html);
    pdf.SaveAs("output.pdf");
}
catch (Exception ex)
{
    // Log error and handle appropriately
    Console.WriteLine($"PDF generation failed: {ex.Message}");
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

Always validate input data and handle exceptions gracefully to ensure reliable PDF generation in your applications.

Conclusion

IronPDF transforms the complex task of creating a PDF file in .NET Core into a simple, manageable process. From basic document creation to advanced features like forms, images, and page management, this .NET library provides comprehensive tools for generating PDF documents programmatically. By using a common approach of converting HTML, you can quickly load data and download the finished files.

Whether you're building simple reports or complex multi-page documents, IronPDF's intuitive API and powerful rendering engine make it the ideal choice for .NET developers. Start creating professional PDF files in your ASP.NET Core applications today with IronPDF's free trial.

Ready to enhance your application with PDF generation capabilities? Get started with IronPDF and experience how easy creating PDFs can be.

Preguntas Frecuentes

¿Qué es IronPDF?

IronPDF es una poderosa biblioteca de .NET Core diseñada para simplificar la creación y manipulación de documentos PDF en aplicaciones ASP.NET.

¿Cómo puedo crear documentos PDF en .NET Core?

Puedes crear documentos PDF en .NET Core usando la biblioteca IronPDF, que ofrece métodos sencillos para generar PDFs programáticamente dentro de tus aplicaciones.

¿Qué tipos de documentos puedo crear usando IronPDF?

Con IronPDF, puedes crear una amplia gama de tipos de documentos, incluidos facturas, informes y cualquier otro sistema basado en documentos que requiera generación de PDF.

¿Es IronPDF adecuado para aplicaciones ASP.NET?

Sí, IronPDF es particularmente adecuado para aplicaciones ASP.NET, proporcionando una integración sin problemas y capacidades eficientes de creación de PDF.

¿Dónde puedo encontrar la documentación oficial de IronPDF?

La documentación oficial de IronPDF está disponible en el sitio web de Iron Software, ofreciendo detalles técnicos completos y guías para usar la biblioteca.

¿Cuáles son los beneficios de usar IronPDF para la creación de PDF?

Los beneficios de usar IronPDF incluyen facilidad de uso, funcionalidad robusta y la capacidad de generar PDFs de alta calidad programáticamente dentro de aplicaciones .NET Core.

¿Puede IronPDF manejar tareas complejas de generación de PDF?

Sí, IronPDF es capaz de manejar tareas complejas de generación de PDF, lo que lo hace ideal para aplicaciones que requieren manipulación y creación avanzada de PDF.

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