Export html to pdf in asp net core

Introduction

HTML to PDF is a common requirement in ASP.NET Core applications. Whether you need to generate , invoices, or any other printable documents, converting HTML to PDF can be a useful feature. In this article, we will explore different approaches to achieve this in ASP.NET Core.

Using third-party

One of the easiest ways to export HTML to PDF in ASP.NET Core is by using third-party libraries. These libraries APIs that allow you to convert HTML to PDF with just a few lines of code. One popular library for this is IronPdf.


using IronPdf;

 void ExportToPdf(string htmlContent, string outputPath)
{
    var renderer = new HtmlToPdf();
    var pdf = renderer.RenderHtmlAsPdf(htmlContent);
    pdf.SaveAs(outputPath);
}

In the above example, we are using the IronPdf library to convert the provided HTML content to a PDF document. The RenderHtmlAsPdf method takes the HTML content as input and returns a PDF document. We then save the PDF document to the specified output path using the SaveAs method.

Using the built-in PDF generation capabilities

ASP.NET Core also provides built-in capabilities for generating PDF documents. This can be achieved using the PDFSharp library, which is included in the ASP.NET Core framework.


using PdfSharpCore.Drawing;
using PdfSharpCore.Pdf;

public void ExportToPdf(string htmlContent, string outputPath)
{
    var document = new PdfDocument();
    var page = document.AddPage();
    var graphics = XGraphics.FromPdfPage(page);
    var renderer = new HtmlRenderer();
    var formattedHtml = new HtmlFormatter();
    var pdfRenderer = new PdfRenderer();

    renderer.Render(formattedHtml.(htmlContent), graphics);
    document.Save(outputPath);
}

In the above example, we are using the PDFSharp library to generate a PDF document from the provided HTML content. We a new PdfDocument object and add a page to it. We then create an XGraphics object from the page to draw the HTML content onto the PDF document. The HtmlRenderer, HtmlFormatter, and PdfRenderer classes are used to parse and render the HTML content. Finally, we save the PDF document to the specified output path using the Save method.

Conclusion

Exporting HTML to PDF in ASP.NET Core can be achieved using third-party libraries or the built-in capabilities provided by the framework. Both approaches have their own advantages and limitations. It is important to choose the approach that best suits your requirements and project constraints. By following the provided in this article, you should be able to successfully export HTML to PDF in your ASP.NET Core applications.

Rate this post

Leave a Reply

Your email address will not be published. Required fields are marked *

Table of Contents