Saltar al pie de página
USANDO IRONPDF

Cómo Crear un Reporte en ASP .NET

Reports are essential for presenting data in a structured and visually appealing format. Whether it's sales data, analytics, or financial summaries, generating reports is a common requirement in web applications. Microsoft provides RDLC report services, which can be integrated into web applications using the Web Forms Report Viewer Control. However, the process can often be complex and time-consuming.

This is where IronPDF comes in. IronPDF is a versatile library that simplifies the generation of PDF reports in ASP.NET and other web frameworks, offering powerful features and ease of use. In this article, we'll explore how to create a report in ASP.NET using IronPDF.

How to Create Report in ASP.NET

  1. Create an ASP.NET Web App using Visual Studio
  2. Install IronPDF and IronPDF.Extensions.MVC.Core
  3. Instantiate ChromePdfRenderer object sender
  4. Call the RenderRazorViewToPdf method to convert the view to PDF
  5. Add "Content-Disposition" using Response.Headers.Append
  6. Create a Report using the File method with PDF.BinaryData

Introduction to IronPDF

IronPDF is a versatile library that simplifies the generation of PDF documents in ASP.NET and other web frameworks. Its rich feature set and intuitive APIs make it an ideal choice for developers looking to generate dynamic reports, invoices, receipts, and more directly from their web applications. With IronPDF, developers can effortlessly convert HTML, CSS, and even Razor views into high-quality PDF documents, enabling seamless integration of reporting functionality into their ASP.NET projects.

Features of IronPDF

  • HTML to PDF Conversion: Easily convert HTML content, including CSS styles, into high-quality PDF documents.
  • PDF Editing: Modify existing PDF documents by adding or removing text, images, and annotations.
  • PDF Form Filling: Populate PDF forms dynamically with data from your web application.
  • Barcode Generation: Generate barcodes and QR codes within PDF documents for product labels or inventory tracking.
  • Watermarking: Add watermarks to PDF pages to protect sensitive information or brand documents.
  • Encryption and Security: Secure PDF documents with encryption, passwords, and permissions settings.

Prerequisites

Before we begin, ensure you have the following prerequisites:

  • Basic knowledge of ASP.NET development.
  • Visual Studio is installed on your machine.
  • IronPDF and IronPDF.Extensions.Mvc.Core

Steps to Create ASP.NET Project in Visual Studio

  1. Open Visual Studio and create a new ASP.NET Core project.
  2. Choose the desired project template (e.g., MVC or Razor Pages).

    How to Create Report in ASP .NET: Figure 1

  3. Configure project settings such as project name, location, and framework version.

    How to Create Report in ASP .NET: Figure 2

  4. Click "Create" to generate the project structure.

Installing IronPDF and IronPDF.Extensions.Mvc.Core

Next, let's install IronPDF and its MVC extension package using the NuGet Package Manager:

  1. Open the NuGet Package Manager for Solutions by right-clicking the Solution Explorer.
  2. Search for "IronPDF" and "IronPDF.Extensions.Mvc.Core".

    How to Create Report in ASP .NET: Figure 3

  3. Install both packages into your solution.

Steps to Create Report Viewer in ASP.NET Web Application

Now, let's dive into the steps to create a PDF report using IronPDF in our ASP.NET project. Before converting a view to a report, we need a Model, View, and Controller to create a data source for creating and downloading a new report in PDF format.

Step 1: Define a Model Class

First, create a model class (SalesModel.cs) to represent the sales data. This sample SalesModel class will include properties such as Date, ProductName, Quantity, UnitPrice, and TotalAmount. This is useful when retrieving information from a data source like Microsoft SQL Server or MySQL Server.

namespace ReportGenerator.Models
{
    public class SalesModel
    {
        public DateTime Date { get; set; }
        public string ProductName { get; set; }
        public int Quantity { get; set; }
        public decimal UnitPrice { get; set; }
        public decimal TotalAmount => Quantity * UnitPrice;
    }
}
namespace ReportGenerator.Models
{
    public class SalesModel
    {
        public DateTime Date { get; set; }
        public string ProductName { get; set; }
        public int Quantity { get; set; }
        public decimal UnitPrice { get; set; }
        public decimal TotalAmount => Quantity * UnitPrice;
    }
}
Namespace ReportGenerator.Models
	Public Class SalesModel
		Public Property [Date]() As DateTime
		Public Property ProductName() As String
		Public Property Quantity() As Integer
		Public Property UnitPrice() As Decimal
		Public ReadOnly Property TotalAmount() As Decimal
			Get
				Return Quantity * UnitPrice
			End Get
		End Property
	End Class
End Namespace
$vbLabelText   $csharpLabel

Step 2: Create a new Web Form View

Next, create a Razor view (Sales.cshtml) to display the sales data in a tabular format and provide a button to generate the PDF report.

<!-- Sales.cshtml -->
@model List<SalesModel>
<!DOCTYPE html>
<html>
<head>
    <title>Sales Report</title>
    <style>
        table {
            border-collapse: collapse;
            width: 100%;
        }
        th, td {
            border: 1px solid #dddddd;
            text-align: left;
            padding: 8px;
        }
        th {
            background-color: #f2f2f2;
        }
    </style>
</head>
<body>
    <h2>Sales Report</h2>
    <table>
        <tr>
            <th>Date</th>
            <th>Product Name</th>
            <th>Quantity</th>
            <th>Unit Price</th>
            <th>Total Amount</th>
        </tr>
        @foreach (var item in Model)
        {
            <tr>
                <td>@item.Date.ToShortDateString()</td>
                <td>@item.ProductName</td>
                <td>@item.Quantity</td>
                <td>@item.UnitPrice.ToString("C")</td>
                <td>@item.TotalAmount.ToString("C")</td>
            </tr>
        }
    </table>
    <br />
    @using (Html.BeginForm("GeneratePdf", "Sales", FormMethod.Post))
    {
        <button type="submit">Generate PDF Report</button>
    }
</body>
</html>
<!-- Sales.cshtml -->
@model List<SalesModel>
<!DOCTYPE html>
<html>
<head>
    <title>Sales Report</title>
    <style>
        table {
            border-collapse: collapse;
            width: 100%;
        }
        th, td {
            border: 1px solid #dddddd;
            text-align: left;
            padding: 8px;
        }
        th {
            background-color: #f2f2f2;
        }
    </style>
</head>
<body>
    <h2>Sales Report</h2>
    <table>
        <tr>
            <th>Date</th>
            <th>Product Name</th>
            <th>Quantity</th>
            <th>Unit Price</th>
            <th>Total Amount</th>
        </tr>
        @foreach (var item in Model)
        {
            <tr>
                <td>@item.Date.ToShortDateString()</td>
                <td>@item.ProductName</td>
                <td>@item.Quantity</td>
                <td>@item.UnitPrice.ToString("C")</td>
                <td>@item.TotalAmount.ToString("C")</td>
            </tr>
        }
    </table>
    <br />
    @using (Html.BeginForm("GeneratePdf", "Sales", FormMethod.Post))
    {
        <button type="submit">Generate PDF Report</button>
    }
</body>
</html>
HTML

Now, add the Sales as a menu item in _Layout.cshtml file found in the Views->Shared folder to create a report wizard view:

<!— Layout.cshtml —>
<li class="nav-item">
    <a class="nav-link text-dark" asp-area="" asp-controller="Sales" asp-action="Sales">Sales</a>
</li>
<!— Layout.cshtml —>
<li class="nav-item">
    <a class="nav-link text-dark" asp-area="" asp-controller="Sales" asp-action="Sales">Sales</a>
</li>
HTML

How to Create Report in ASP .NET: Figure 4

Step 3: Registering the View Render Service

Including the registration of the view render service in the Program.cs file is crucial for dependency injection to work properly. Add the following code to the Program.cs file to register the IRazorViewRenderer service:

// Register the IRazorViewRenderer service
builder.Services.AddSingleton<IRazorViewRenderer, RazorViewRenderer>();
// Register the IRazorViewRenderer service
builder.Services.AddSingleton<IRazorViewRenderer, RazorViewRenderer>();
' Register the IRazorViewRenderer service
builder.Services.AddSingleton(Of IRazorViewRenderer, RazorViewRenderer)()
$vbLabelText   $csharpLabel

Step 4: Implement Web API Controller Class

Implement a controller (SalesController.cs) with actions to render the sales view and generate the PDF report. Inject the IRazorViewRenderer service provided by IronPDF into the controller constructor.

using ReportGenerator.Models;
namespace ReportGenerator.Controllers
{
    public class SalesController : Controller
    {
        private readonly IRazorViewRenderer _viewRenderService;
        private readonly List<SalesModel> salesData;

        public SalesController(IRazorViewRenderer viewRenderService)
        {
            _viewRenderService = viewRenderService;
            // Example data with sales information
            salesData = new List<SalesModel>
            {
                new SalesModel { Date = DateTime.Parse("2024-03-01"), ProductName = "Product A", Quantity = 10, UnitPrice = 50.00m },
                new SalesModel { Date = DateTime.Parse("2024-03-02"), ProductName = "Product B", Quantity = 15, UnitPrice = 40.00m },
                new SalesModel { Date = DateTime.Parse("2024-03-03"), ProductName = "Product C", Quantity = 20, UnitPrice = 30.00m }
                // Add more data as needed
            };
        }

        public IActionResult Sales()
        {
            // Renders the sales view with the sales data
            return View(salesData);
        }
    }
}
using ReportGenerator.Models;
namespace ReportGenerator.Controllers
{
    public class SalesController : Controller
    {
        private readonly IRazorViewRenderer _viewRenderService;
        private readonly List<SalesModel> salesData;

        public SalesController(IRazorViewRenderer viewRenderService)
        {
            _viewRenderService = viewRenderService;
            // Example data with sales information
            salesData = new List<SalesModel>
            {
                new SalesModel { Date = DateTime.Parse("2024-03-01"), ProductName = "Product A", Quantity = 10, UnitPrice = 50.00m },
                new SalesModel { Date = DateTime.Parse("2024-03-02"), ProductName = "Product B", Quantity = 15, UnitPrice = 40.00m },
                new SalesModel { Date = DateTime.Parse("2024-03-03"), ProductName = "Product C", Quantity = 20, UnitPrice = 30.00m }
                // Add more data as needed
            };
        }

        public IActionResult Sales()
        {
            // Renders the sales view with the sales data
            return View(salesData);
        }
    }
}
Imports ReportGenerator.Models
Namespace ReportGenerator.Controllers
	Public Class SalesController
		Inherits Controller

		Private ReadOnly _viewRenderService As IRazorViewRenderer
		Private ReadOnly salesData As List(Of SalesModel)

		Public Sub New(ByVal viewRenderService As IRazorViewRenderer)
			_viewRenderService = viewRenderService
			' Example data with sales information
			salesData = New List(Of SalesModel) From {
				New SalesModel With {
					.Date = DateTime.Parse("2024-03-01"),
					.ProductName = "Product A",
					.Quantity = 10,
					.UnitPrice = 50.00D
				},
				New SalesModel With {
					.Date = DateTime.Parse("2024-03-02"),
					.ProductName = "Product B",
					.Quantity = 15,
					.UnitPrice = 40.00D
				},
				New SalesModel With {
					.Date = DateTime.Parse("2024-03-03"),
					.ProductName = "Product C",
					.Quantity = 20,
					.UnitPrice = 30.00D
				}
			}
		End Sub

		Public Function Sales() As IActionResult
			' Renders the sales view with the sales data
			Return View(salesData)
		End Function
	End Class
End Namespace
$vbLabelText   $csharpLabel

In the above code, inside the constructor, the IRazorViewRenderer service is assigned to the private field _viewRenderService. Additionally, the controller initializes a list named salesData containing instances of the SalesModel class, representing sales information for demonstration purposes.

The Sales() action method returns a view named "Sales", passing the salesData list as the model. This action is responsible for rendering the sales data in the associated view, allowing users to visualize the sales information in a tabular format or any other desired layout.

How to Create Report in ASP .NET: Figure 5

Step 5: Generate PDF Report

In the GeneratePdf action of the controller, use IronPDF's ChromePdfRenderer to render the Razor view to a PDF Report document. Set the appropriate response headers and return the PDF file to the client.

public FileContentResult GeneratePdf()
{
    // Set license key for IronPDF
    License.LicenseKey = "YOUR-LICENSE-KEY-HERE";

    // Initialize the ChromePdfRenderer
    ChromePdfRenderer renderer = new ChromePdfRenderer();

    // Render the Sales Razor view to a PDF document
    PdfDocument pdf = renderer.RenderRazorViewToPdf(_viewRenderService, "Views/Sales/Sales.cshtml", salesData);

    // Set HTTP response header to display the PDF inline
    Response.Headers.Append("Content-Disposition", "inline");

    // Return the PDF document as a FileContentResult
    return File(pdf.BinaryData, "application/pdf", "SalesReport.pdf");
}
public FileContentResult GeneratePdf()
{
    // Set license key for IronPDF
    License.LicenseKey = "YOUR-LICENSE-KEY-HERE";

    // Initialize the ChromePdfRenderer
    ChromePdfRenderer renderer = new ChromePdfRenderer();

    // Render the Sales Razor view to a PDF document
    PdfDocument pdf = renderer.RenderRazorViewToPdf(_viewRenderService, "Views/Sales/Sales.cshtml", salesData);

    // Set HTTP response header to display the PDF inline
    Response.Headers.Append("Content-Disposition", "inline");

    // Return the PDF document as a FileContentResult
    return File(pdf.BinaryData, "application/pdf", "SalesReport.pdf");
}
Public Function GeneratePdf() As FileContentResult
	' Set license key for IronPDF
	License.LicenseKey = "YOUR-LICENSE-KEY-HERE"

	' Initialize the ChromePdfRenderer
	Dim renderer As New ChromePdfRenderer()

	' Render the Sales Razor view to a PDF document
	Dim pdf As PdfDocument = renderer.RenderRazorViewToPdf(_viewRenderService, "Views/Sales/Sales.cshtml", salesData)

	' Set HTTP response header to display the PDF inline
	Response.Headers.Append("Content-Disposition", "inline")

	' Return the PDF document as a FileContentResult
	Return File(pdf.BinaryData, "application/pdf", "SalesReport.pdf")
End Function
$vbLabelText   $csharpLabel

Let's understand the workings of the above code in detail:

  1. License Key Setup:
    • License.LicenseKey = "YOUR-LICENSE-KEY-HERE";
    • This line sets the license key required for IronPDF. It's essential for using IronPDF functionalities within the application.
  2. Renderer Initialization:
    • ChromePdfRenderer renderer = new ChromePdfRenderer();
    • An instance of ChromePdfRenderer is created. This renderer is responsible for converting Razor views to PDF format using the Chromium browser engine.
  3. Rendering View to PDF:
    • PdfDocument PDF = renderer.RenderRazorViewToPdf(_viewRenderService, "Views/Sales/Sales.cshtml", salesData);
    • The RenderRazorViewToPdf() method of ChromePdfRenderer is invoked to render the specified Razor view (Views/Sales/Sales.cshtml) to a PDF document. The salesData variable serves as the model for the view.
  4. Content-Disposition Header:
    • Response.Headers.Append("Content-Disposition", "inline");
    • The HTTP response header Content-Disposition is set to "inline". This instructs the browser to display the PDF content directly to view reports within the browser window or tab when opened.
  5. Returning PDF File:
    • return File(pdf.BinaryData, "application/pdf", "SalesReport.pdf");
    • The PDF document content is returned as a FileContentResult. It includes the binary data of the PDF (pdf.BinaryData), specifies the MIME type as "application/pdf", and suggests the filename as "SalesReport.pdf".

Overall, this method efficiently orchestrates the process of generating a PDF report from a Razor view, making it suitable for integration within the ASP.NET application to enhance reporting capabilities.

How to Create Report in ASP .NET: Figure 6

For detailed information on how IronPDF eases the process of PDF report generation and other PDF-related tasks, please visit the documentation page.

Conclusion

In this article, we've explored how IronPDF simplifies the process of generating PDF reports in ASP.NET applications. By following the step-by-step guide provided above, you can quickly integrate IronPDF into your ASP.NET projects and generate dynamic PDF reports with ease.

With its rich feature set and seamless integration, IronPDF empowers developers to create professional-quality reports that meet the needs of their users and businesses.

IronPDF offers a free trial. Download the library from here and give it a try.

Preguntas Frecuentes

¿Cómo puedo generar un informe PDF en ASP.NET?

Puedes generar un informe PDF en ASP.NET usando IronPDF. Comienza configurando una aplicación web ASP.NET en Visual Studio, luego instala IronPDF y su extensión MVC. Utiliza la clase ChromePdfRenderer para convertir vistas Razor en PDFs y utiliza el método File para crear el informe.

¿Cuáles son los beneficios de usar una biblioteca PDF para ASP.NET?

Usar una biblioteca PDF como IronPDF para ASP.NET simplifica el proceso de generar y gestionar informes PDF. Soporta la conversión de HTML a PDF, edición de PDF, llenado de formularios, generación de códigos de barras y seguridad de documentos, haciéndola versátil para diversas necesidades de aplicaciones web.

¿Cómo convierto vistas Razor a PDF en ASP.NET?

Para convertir vistas Razor a PDF en ASP.NET, puedes usar el método ChromePdfRenderer.RenderRazorViewToPdf de IronPDF. Esto te permite integrar sin problemas la generación de PDFs dentro de tus aplicaciones ASP.NET.

¿Qué características ofrece IronPDF para la generación de informes PDF?

IronPDF ofrece características como conversión de HTML a PDF, edición de PDF, llenado de formularios, generación de códigos de barras, inclusión de marcas de agua y cifrado y seguridad de documentos. Estas características facilitan la creación de informes PDF dinámicos y seguros.

¿Cómo puedo asegurar documentos PDF en ASP.NET?

IronPDF proporciona características de cifrado y seguridad que permiten a los desarrolladores asegurar documentos PDF con cifrado, contraseñas y configuraciones de permisos. Esto garantiza que la información sensible permanezca protegida en tus aplicaciones ASP.NET.

¿Hay una prueba gratuita disponible para IronPDF?

Sí, IronPDF ofrece una prueba gratuita. Puedes descargar la biblioteca desde el sitio web de IronPDF y explorar sus características para generar informes PDF de calidad profesional en tus aplicaciones.

¿Cómo agrego una marca de agua a un PDF en una aplicación ASP.NET?

Puedes agregar una marca de agua a un PDF en una aplicación ASP.NET usando IronPDF. La biblioteca proporciona APIs para superponer marcas de agua en documentos PDF, permitiendo proteger información sensible o marcar tus documentos de manera efectiva.

¿Cuáles son los requisitos previos para usar IronPDF en mi proyecto ASP.NET?

Antes de usar IronPDF, asegúrate de tener un conocimiento básico del desarrollo en ASP.NET y tener instalado Visual Studio. Además, necesitas instalar IronPDF y su extensión MVC en tu proyecto para utilizar sus características.

¿Dónde puedo encontrar más información sobre IronPDF?

Para más información detallada sobre IronPDF y sus capacidades, puedes visitar la página de documentación en el sitio web de IronPDF. La documentación ofrece información sobre la configuración, características y código de ejemplo.

¿IronPDF es compatible con .NET 10 y qué ventajas aporta?

Sí, IronPDF es totalmente compatible con .NET 10 en proyectos web, de escritorio y de consola. Aprovecha las mejoras de rendimiento del entorno de ejecución de .NET 10 (como la reducción de las asignaciones de montón y un JIT más rápido), las mejoras del lenguaje C# y las API modernas. Los desarrolladores pueden usar métodos como RenderHtmlAsPdf y RenderHtmlAsPdfAsync sin problemas en aplicaciones .NET 10, beneficiándose de la velocidad de salida, la implementación multiplataforma y un código más limpio.

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