푸터 콘텐츠로 바로가기
IRONPDF 사용

How to Create Report in 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;
    }
}
$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.


@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>

@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>();
$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);
        }
    }
}
$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");
}
$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.

자주 묻는 질문

ASP.NET에서 PDF 보고서를 생성하려면 어떻게 해야 하나요?

IronPDF를 사용하여 ASP.NET에서 PDF 보고서를 생성할 수 있습니다. 먼저 Visual Studio에서 ASP.NET 웹 애플리케이션을 설정한 다음 IronPDF와 해당 MVC 확장 프로그램을 설치하세요. ChromePdfRenderer 클래스를 사용하여 Razor 뷰를 PDF로 변환하고 File 메서드를 활용하여 보고서를 생성합니다.

ASP.NET용 PDF 라이브러리를 사용하면 어떤 이점이 있나요?

ASP.NET용 IronPDF와 같은 PDF 라이브러리를 사용하면 PDF 보고서 생성 및 관리 프로세스가 간소화됩니다. HTML에서 PDF로 변환, PDF 편집, 양식 채우기, 바코드 생성 및 문서 보안을 지원하므로 다양한 웹 애플리케이션 요구 사항에 다용도로 사용할 수 있습니다.

ASP.NET에서 Razor 뷰를 PDF로 변환하려면 어떻게 하나요?

ASP.NET에서 Razor 뷰를 PDF로 변환하려면 IronPDF의 ChromePdfRenderer.RenderRazorViewToPdf 메서드를 사용할 수 있습니다. 이를 통해 ASP.NET 애플리케이션 내에서 PDF 생성을 원활하게 통합할 수 있습니다.

IronPDF는 PDF 보고서 생성을 위해 어떤 기능을 제공하나요?

IronPDF는 HTML을 PDF로 변환, PDF 편집, 양식 작성, 바코드 생성, 워터마킹, 문서 암호화 및 보안과 같은 기능을 제공합니다. 이러한 기능을 통해 동적이고 안전한 PDF 보고서를 쉽게 만들 수 있습니다.

ASP.NET에서 PDF 문서를 보호하려면 어떻게 해야 하나요?

IronPDF는 개발자가 암호화, 비밀번호 및 권한 설정으로 PDF 문서를 보호할 수 있는 암호화 및 보안 기능을 제공합니다. 이를 통해 ASP.NET 애플리케이션에서 민감한 정보를 안전하게 보호할 수 있습니다.

IronPDF에 무료 평가판이 있나요?

예, IronPDF는 무료 평가판을 제공합니다. IronPDF 웹사이트에서 라이브러리를 다운로드하고 애플리케이션에서 전문가 수준의 PDF 보고서를 생성할 수 있는 기능을 살펴볼 수 있습니다.

ASP.NET 애플리케이션에서 PDF에 워터마크를 추가하려면 어떻게 해야 하나요?

IronPDF를 사용하여 ASP.NET 애플리케이션의 PDF에 워터마크를 추가할 수 있습니다. 이 라이브러리는 PDF 문서에 워터마크를 오버레이하기 위한 API를 제공하여 민감한 정보를 보호하거나 문서를 효과적으로 브랜딩할 수 있습니다.

ASP.NET 프로젝트에서 IronPDF를 사용하기 위한 전제 조건은 무엇인가요?

IronPDF를 사용하기 전에 ASP.NET 개발에 대한 기본적인 이해가 있고 Visual Studio가 설치되어 있는지 확인하세요. 또한 IronPDF의 기능을 활용하려면 프로젝트에 IronPDF와 해당 MVC 확장 프로그램을 설치해야 합니다.

IronPDF에 대한 자세한 정보는 어디에서 찾을 수 있나요?

IronPDF와 그 기능에 대한 자세한 내용은 IronPDF 웹사이트의 문서 페이지에서 확인할 수 있습니다. 이 문서에서는 설정, 기능 및 샘플 코드에 대한 인사이트를 제공합니다.

IronPDF는 .NET 10과 호환되며 어떤 이점이 있나요?

예, IronPDF는 웹, 데스크톱 및 콘솔 프로젝트 유형에서 .NET 10을 완벽하게 지원합니다. .NET 10 런타임 성능 향상(힙 할당 감소, JIT 속도 향상 등), C# 언어 개선, 최신 API를 활용합니다. 개발자는 .NET 10 앱에서 RenderHtmlAsPdfRenderHtmlAsPdfAsync와 같은 메서드를 원활하게 사용하여 출력 속도, 크로스 플랫폼 배포 및 깔끔한 코드의 이점을 누릴 수 있습니다.

커티스 차우
기술 문서 작성자

커티스 차우는 칼턴 대학교에서 컴퓨터 과학 학사 학위를 취득했으며, Node.js, TypeScript, JavaScript, React를 전문으로 하는 프론트엔드 개발자입니다. 직관적이고 미적으로 뛰어난 사용자 인터페이스를 만드는 데 열정을 가진 그는 최신 프레임워크를 활용하고, 잘 구성되고 시각적으로 매력적인 매뉴얼을 제작하는 것을 즐깁니다.

커티스는 개발 분야 외에도 사물 인터넷(IoT)에 깊은 관심을 가지고 있으며, 하드웨어와 소프트웨어를 통합하는 혁신적인 방법을 연구합니다. 여가 시간에는 게임을 즐기거나 디스코드 봇을 만들면서 기술에 대한 애정과 창의성을 결합합니다.