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

How to convert HTML to PDF in ASP .NET using C#

In modern web applications, generating documents from HTML content is a common requirement. Whether you need to create invoices, reports, or any other types of documents, converting HTML to PDF can be accomplished efficiently with the IronPDF library in ASP.NET using C#.

Today, we will explore how to set up IronPDF and use it to convert HTML content into a PDF document.

How to Convert HTML to PDF in ASP.NET with IronPDF

  1. Create an ASP.NET project using Visual Studio or your IDE of choice.
  2. Install IronPDF and set up your license key.
  3. Create a new controller or page where you want to handle the PDF conversion.
  4. Write your conversion logic within the controller.
  5. Configure routing to allow access to your PDF generation action.

An Overview of IronPDF

IronPDF is a powerful PDF library that allows developers to read, create, and manipulate PDF documents. With a rich feature set and a quick, simple installation process, you can take your PDF projects to the next level in no time thanks to IronPDF. Its intuitive API is easy to learn, making it an ideal choice if you are looking to generate dynamic PDF documents, perform PDF security tasks, PDF annotations, etc., directly from your web application.

Features

  • PDF conversion: IronPDF can convert HTML files to PDF, with its full support for modern web standards. You can be assured that IronPDF will consistently return pixel-perfect PDFs from your HTML pages. IronPDF can also convert PDF files from other formats such as DOCX, images, RTF, and more.
  • PDF Generation: With IronPDF, you can generate PDFs from any web page, ASPX file, HTML string, or more.
  • Security features: With IronPDF, you can always be assured that any sensitive PDF files are secure thanks to its security features. Use IronPDF to encrypt your PDF files, set passwords, and set permissions for your PDF files.
  • PDF editing features: With IronPDF you can process existing PDF documents, edit them, and read PDF files with ease. IronPDF offers editing features such as adding headers and footers, stamping text and images onto the PDF pages, adding custom watermarks to the PDF, working with PDF forms, and splitting or merging PDF files.

Prerequisites

Before you start, ensure you have:

  • Visual Studio or another C# development environment set up.
  • IronPDF library installed. You can get it from NuGet or directly from the IronPDF website.

Create a New ASP.NET Project

Launch Visual Studio and select the ASP.NET project type that best suits your needs. For today's example, I will be creating an ASP.NET Core Web App (Model-view Controller).

How to convert HTML to PDF in ASP .NET using C#: Figure 1

Then, enter the name for your project and choose the location to house the project.

How to convert HTML to PDF in ASP .NET using C#: Figure 2

Finally, choose your .NET Framework for the project, and change any additional settings for the project such as the authentication type, or enabling container support and docker.

How to convert HTML to PDF in ASP .NET using C#: Figure 3

Create a Controller

To create a new controller to house our HTML to PDF code within, first right-click on the "Controllers" folder in the solution explorer and choose "Add -> Controller".

How to convert HTML to PDF in ASP .NET using C#: Figure 4

This will prompt a new window to open, where you can choose what form of controller you want to add to the project. We have picked an empty MVC Controller.

How to convert HTML to PDF in ASP .NET using C#: Figure 5

Finally, we give the new Controller a name and click "Add" to add it to our project.

How to convert HTML to PDF in ASP .NET using C#: Figure 6

Add HTML to PDF Conversion Code

Now that we have created our ASP.NET project, we can begin writing the code for converting HTML file content to a PDF. We will start with a simple example of HTML string to PDF, before looking at converting HTML content with customization.

using IronPdf;
using Microsoft.AspNetCore.Mvc;

namespace IronPdfTest.Controllers
{
    public class PdfController : Controller
    {
        // Action method to generate a PDF from HTML content
        public IActionResult GeneratePdf()
        {
            // String of HTML code to be converted to PDF
            string htmlContent = "<h1>Hello, IronPDF!</h1><p>This is a PDF generated from HTML.</p>";

            // Creating a renderer to convert the HTML string to PDF
            ChromePdfRenderer renderer = new ChromePdfRenderer();

            // Convert HTML string to PDF
            PdfDocument pdf = renderer.RenderHtmlAsPdf(htmlContent);

            // Return the generated PDF file
            return File(pdf.BinaryData, "application/pdf", "generatedDocument.pdf");
        }
    }
}
using IronPdf;
using Microsoft.AspNetCore.Mvc;

namespace IronPdfTest.Controllers
{
    public class PdfController : Controller
    {
        // Action method to generate a PDF from HTML content
        public IActionResult GeneratePdf()
        {
            // String of HTML code to be converted to PDF
            string htmlContent = "<h1>Hello, IronPDF!</h1><p>This is a PDF generated from HTML.</p>";

            // Creating a renderer to convert the HTML string to PDF
            ChromePdfRenderer renderer = new ChromePdfRenderer();

            // Convert HTML string to PDF
            PdfDocument pdf = renderer.RenderHtmlAsPdf(htmlContent);

            // Return the generated PDF file
            return File(pdf.BinaryData, "application/pdf", "generatedDocument.pdf");
        }
    }
}
$vbLabelText   $csharpLabel

How to convert HTML to PDF in ASP .NET using C#: Figure 7

ASP.NET MVC uses controllers to handle user requests. When a user navigates to a specific URL, ASP.NET will call a method in the controller associated with that route.

  • PdfController is a class inheriting from Controller, meaning it can handle web requests and send responses.
  • The GeneratePdf method inside this controller will handle a request to convert HTML into a PDF and return the result.

When a user visits a URL linked to the GeneratePdf action, the method executes.

  • IActionResult: This is the return type, representing the response that the web application will send back to the user. It could be a view (HTML page), file download, etc. In this case, it's a PDF file.

    • GeneratePdf() Method:

    • Inside the method, we define a string htmlContent that contains the HTML you want to convert to a PDF. For example, "<h1>Hello, IronPDF!</h1><p>This is a PDF generated from HTML.</p>".

    • We create a new instance of ChromePdfRenderer, which handles the conversion of HTML to PDF.

    • The method RenderHtmlAsPdf() takes the HTML string and returns a PDF object.

Configure Routing

In an ASP.NET MVC application, you define routes that map URLs to controller methods (actions). For example, if you navigate to /Pdf/GeneratePdf in the browser, ASP.NET will look for the PdfController and call its GeneratePdf method. Ensure your routing configuration allows access to the GeneratePdf action. If you are using ASP.NET Core MVC, this is usually configured automatically. If you are using Web API, make sure your routes are properly set up.

Custom PDF Output

Now that we have the basics down, let's look at creating a PDF file from HTML content with some customization settings set for the output PDF. IronPDF provides a powerful set of PDF customization tools, such as margins, headers/footers, custom PDF sizing, and more.

using IronPdf;
using Microsoft.AspNetCore.Mvc;

namespace IronPdfTest.Controllers
{
    // Controller for our PDF converter
    public class PdfController : Controller
    {
        // Action method to generate a customized PDF from HTML content
        public IActionResult GeneratePdf()
        {
            // String of HTML code to be converted to PDF
            string htmlContent = "<h1>Hello, IronPDF!</h1><p>This is a PDF generated from HTML.</p>";

            // Creating a renderer to convert the URL to PDF
            ChromePdfRenderer renderer = new ChromePdfRenderer();

            // Creating the cover page
            PdfDocument cover = renderer.RenderHtmlAsPdf("<h1>Cover Page</h1>");

            // Adding custom options for our final PDF
            renderer.RenderingOptions.PaperOrientation = IronPdf.Rendering.PdfPaperOrientation.Landscape;
            renderer.RenderingOptions.PaperSize = IronPdf.Rendering.PdfPaperSize.A3;
            renderer.RenderingOptions.TextHeader.CenterText = "IronPDF";
            renderer.RenderingOptions.TextHeader.FontSize = 12;
            renderer.RenderingOptions.MarginTop = 20;
            renderer.RenderingOptions.FirstPageNumber = 2;

            // Creating our main PDF
            PdfDocument pdf = renderer.RenderHtmlAsPdf(htmlContent);

            // Appending the cover to the main PDF
            pdf.InsertPdf(cover, 0);

            // Return the customized generated PDF file
            return File(pdf.BinaryData, "application/pdf", "generatedDocument.pdf");
        }
    }
}
using IronPdf;
using Microsoft.AspNetCore.Mvc;

namespace IronPdfTest.Controllers
{
    // Controller for our PDF converter
    public class PdfController : Controller
    {
        // Action method to generate a customized PDF from HTML content
        public IActionResult GeneratePdf()
        {
            // String of HTML code to be converted to PDF
            string htmlContent = "<h1>Hello, IronPDF!</h1><p>This is a PDF generated from HTML.</p>";

            // Creating a renderer to convert the URL to PDF
            ChromePdfRenderer renderer = new ChromePdfRenderer();

            // Creating the cover page
            PdfDocument cover = renderer.RenderHtmlAsPdf("<h1>Cover Page</h1>");

            // Adding custom options for our final PDF
            renderer.RenderingOptions.PaperOrientation = IronPdf.Rendering.PdfPaperOrientation.Landscape;
            renderer.RenderingOptions.PaperSize = IronPdf.Rendering.PdfPaperSize.A3;
            renderer.RenderingOptions.TextHeader.CenterText = "IronPDF";
            renderer.RenderingOptions.TextHeader.FontSize = 12;
            renderer.RenderingOptions.MarginTop = 20;
            renderer.RenderingOptions.FirstPageNumber = 2;

            // Creating our main PDF
            PdfDocument pdf = renderer.RenderHtmlAsPdf(htmlContent);

            // Appending the cover to the main PDF
            pdf.InsertPdf(cover, 0);

            // Return the customized generated PDF file
            return File(pdf.BinaryData, "application/pdf", "generatedDocument.pdf");
        }
    }
}
$vbLabelText   $csharpLabel

How to convert HTML to PDF in ASP .NET using C#: Figure 8

Conclusion

Today we have taken a closer look at how HTML to PDF conversion can be used with ASP.NET, and explored the process of creating PDF files from HTML within an ASP.NET project. By following the steps outlined above, you can easily integrate PDF generation into your web applications, allowing you to create high-quality, printable documents from HTML content.

IronPDF sports a rich set of features that can be leveraged to produce high-quality PDF documents. For more advanced features and detailed customization, refer to the IronPDF documentation. With its fast installation, you can have IronPDF set up within your project in no time.

자주 묻는 질문

C#을 사용하여 ASP.NET에서 HTML 콘텐츠를 PDF로 변환하려면 어떻게 해야 하나요?

C#을 사용하여 ASP.NET에서 HTML 콘텐츠를 PDF로 변환하려면 IronPDF 라이브러리를 사용할 수 있습니다. 먼저 Visual Studio에서 ASP.NET 프로젝트를 설정하고 NuGet을 통해 IronPDF를 설치한 다음 라이선스 키를 구성합니다. 그런 다음 IronPDF의 ChromePdfRenderer 클래스를 사용하여 HTML 콘텐츠를 PDF 문서로 렌더링하는 컨트롤러를 만듭니다.

ASP.NET 프로젝트에서 IronPDF를 설정하려면 어떤 단계를 거쳐야 하나요?

ASP.NET 프로젝트에서 IronPDF를 설정하려면 Visual Studio에서 새 ASP.NET 프로젝트를 생성하고 NuGet 패키지 관리자를 통해 IronPDF를 설치한 다음 라이선스 키를 입력해야 합니다. 설정이 완료되면 IronPDF의 기능을 활용하여 HTML을 PDF로 변환할 수 있습니다.

ASP.NET 컨트롤러에서 PDF 변환 로직을 처리하려면 어떻게 해야 하나요?

ASP.NET 컨트롤러에서는 IronPDF의 ChromePdfRenderer를 사용하여 PDF 변환 로직을 처리할 수 있습니다. HTML 콘텐츠를 가져와 RenderHtmlAsPdf 메서드를 적용하여 PDF를 생성한 다음 클라이언트에 반환할 수 있는 액션 메서드를 만듭니다.

IronPDF에서 PDF 출력을 사용자 지정하는 데 사용할 수 있는 옵션에는 어떤 것이 있나요?

IronPDF를 사용하면 용지 크기, 방향, 여백 설정, 머리글 및 바닥글 추가 등의 옵션으로 PDF 출력을 사용자 지정할 수 있습니다. 이러한 옵션은 PDF 문서를 구성할 때 렌더링옵션 속성을 사용하여 조정할 수 있습니다.

IronPDF를 사용하여 HTML에서 고품질 PDF 출력을 보장하려면 어떻게 해야 하나요?

IronPDF는 최신 웹 표준을 지원하여 HTML에서 고품질 PDF 출력을 보장합니다. ChromePdfRenderer를 사용하면 일관된 서식과 스타일을 유지하여 전문가 수준의 PDF 문서를 만들 수 있습니다.

IronPDF를 기존 ASP.NET 웹 애플리케이션에 통합할 수 있나요?

예, IronPDF는 기존 ASP.NET 웹 애플리케이션에 쉽게 통합할 수 있습니다. NuGet을 통해 라이브러리를 설치하고 라이선스를 구성한 후 이를 사용하여 HTML 콘텐츠를 PDF로 변환하여 애플리케이션의 문서 생성 기능을 향상시킬 수 있습니다.

ASP.NET 프로젝트에서 IronPDF를 사용하기 위한 몇 가지 문제 해결 팁은 무엇인가요?

ASP.NET 프로젝트에서 IronPDF와 관련된 문제가 발생하면 NuGet을 통해 라이브러리가 올바르게 설치되었는지 확인하고, 라이선스 키가 유효한지 확인하고, 컨트롤러의 변환 로직에 HTML 렌더링 또는 PDF 생성 오류가 있는지 검토하세요.

HTML을 PDF로 변환하는 데 IronPDF를 사용하는 데 대한 추가 리소스는 어디에서 찾을 수 있나요?

IronPDF 사용에 대한 추가 리소스 및 문서는 IronPDF 공식 웹사이트에서 찾을 수 있으며, 여기서 ASP.NET에서 HTML을 PDF로 변환하기 위한 라이브러리를 효과적으로 사용하는 데 도움이 되는 가이드, API 문서 및 예제에 액세스할 수 있습니다.

IronPDF는 새로 출시된 .NET 10과 호환되며, .NET 10은 HTML에서 PDF로 변환할 때 어떤 이점을 제공하나요?

예 - IronPDF는 .NET 10과 완벽하게 호환됩니다. 크로스 플랫폼 배포, 힙 할당 감소, 메모리 사용량 개선, 최신 C# 기능과의 호환성 향상 등 새로운 런타임 성능 향상을 포함하여 .NET 10을 '즉시' 지원합니다. 이러한 개선 사항으로 인해 .NET 10에서 IronPDF를 사용한 HTML-PDF 변환이 더 빠르고 효율적이며 유지 관리가 쉬워졌습니다.

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

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

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