跳過到頁腳內容
使用IRONPDF

如何使用C#在ASP .NET中將HTML轉換為PDF

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");
        }
    }
}
Imports IronPdf
Imports Microsoft.AspNetCore.Mvc

Namespace IronPdfTest.Controllers
	Public Class PdfController
		Inherits Controller

		' Action method to generate a PDF from HTML content
		Public Function GeneratePdf() As IActionResult
			' String of HTML code to be converted to PDF
			Dim htmlContent As String = "<h1>Hello, IronPDF!</h1><p>This is a PDF generated from HTML.</p>"

			' Creating a renderer to convert the HTML string to PDF
			Dim renderer As New ChromePdfRenderer()

			' Convert HTML string to PDF
			Dim pdf As PdfDocument = renderer.RenderHtmlAsPdf(htmlContent)

			' Return the generated PDF file
			Return File(pdf.BinaryData, "application/pdf", "generatedDocument.pdf")
		End Function
	End Class
End Namespace
$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");
        }
    }
}
Imports IronPdf
Imports Microsoft.AspNetCore.Mvc

Namespace IronPdfTest.Controllers
	' Controller for our PDF converter
	Public Class PdfController
		Inherits Controller

		' Action method to generate a customized PDF from HTML content
		Public Function GeneratePdf() As IActionResult
			' String of HTML code to be converted to PDF
			Dim htmlContent As String = "<h1>Hello, IronPDF!</h1><p>This is a PDF generated from HTML.</p>"

			' Creating a renderer to convert the URL to PDF
			Dim renderer As New ChromePdfRenderer()

			' Creating the cover page
			Dim cover As PdfDocument = 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
			Dim pdf As PdfDocument = 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")
		End Function
	End Class
End Namespace
$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?

若要在 ASP.NET 中使用 C# 將 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,然後將產生的 PDF 傳回給客戶端。

IronPDF中有哪些選項可用於自訂PDF輸出?

IronPDF 可讓您自訂 PDF 輸出,例如設定紙張大小、方向、頁邊距以及新增頁首和頁尾。您可以在配置 PDF 文件時使用RenderingOptions屬性來調整這些設定。

如何使用 IronPDF 從 HTML 輸出高品質的 PDF 檔案?

IronPDF 支援現代 Web 標準,確保從 HTML 輸出高品質的 PDF 檔案。透過使用ChromePdfRenderer ,您可以保持格式和樣式的一致性,從而產生專業美觀的 PDF 文件。

IronPDF 能否整合到現有的 ASP.NET Web 應用程式中?

是的,IronPDF 可以輕鬆整合到現有的 ASP.NET Web 應用程式中。透過 NuGet 安裝程式庫並設定授權後,即可使用它將 HTML 內容轉換為 PDF,從而增強應用程式的文件產生功能。

在 ASP.NET 專案中使用 IronPDF 時,有哪些故障排除技巧?

如果在 ASP.NET 專案中使用 IronPDF 時遇到問題,請確保已透過 NuGet 正確安裝該程式庫,檢查您的授權金鑰是否有效,並檢查控制器的轉換邏輯是否有 HTML 渲染或 PDF 產生錯誤。

在哪裡可以找到更多關於使用 IronPDF 將 HTML 轉換為 PDF 的資源?

有關使用 IronPDF 的更多資源和文檔,請訪問 IronPDF 官方網站,您可以在那裡訪問指南、API 文件和示例,以幫助您有效地使用該庫在 ASP.NET 中進行 HTML 到 PDF 的轉換。

IronPDF 是否與新發布的 .NET 10 相容? .NET 10 為 HTML 到 PDF 的轉換帶來了哪些好處?

是的-IronPDF 完全相容 .NET 10。它「開箱即用」地支援 .NET 10,包括跨平台部署、新的運行時效能增強(例如減少堆疊分配、優化記憶體使用以及更好地相容於現代 C# 特性)。這些改進意味著在 .NET 10 下,使用 IronPDF 進行 HTML 到 PDF 的轉換速度更快、更有效率、更容易維護。

Curtis Chau
技術作家

Curtis Chau 擁有卡爾頓大學計算機科學學士學位,專注於前端開發,擅長於 Node.js、TypeScript、JavaScript 和 React。Curtis 熱衷於創建直觀且美觀的用戶界面,喜歡使用現代框架並打造結構良好、視覺吸引人的手冊。

除了開發之外,Curtis 對物聯網 (IoT) 有著濃厚的興趣,探索將硬體和軟體結合的創新方式。在閒暇時間,他喜愛遊戲並構建 Discord 機器人,結合科技與創意的樂趣。