Convert html to pdf in asp net mvc

Introduction

Converting HTML to PDF is a common requirement in ASP.NET MVC applications. are several libraries and tools that can help achieve this functionality. In this article, we will explore one such library and demonstrate how to convert HTML to PDF in ASP.NET MVC.

Using the SelectPdf Library

The SelectPdf library is a popular choice for converting HTML to PDF in ASP.NET MVC. It provides a simple and straightforward API to generate high-quality PDF documents from HTML content.

To get , you need to install the SelectPdf NuGet package in your ASP.NET MVC . Open the NuGet Package Manager Console and run the following command:

Install-Package SelectPdf

Converting HTML to PDF

Once you have the SelectPdf package, you can start converting HTML to PDF in your ASP.NET MVC application. Here's an example:

using SelectPdf;

public ActionResult ConvertToPdf()
{
    // Create a new PDF document
    PdfDocument doc = new PdfDocument();

    // Create a new PDF page
    PdfPage page = doc.AddPage();

    // Create a new HTML to PDF converter
    HtmlToPdf converter = new HtmlToPdf();

    // Set the HTML content to convert
    string html = "

, World!

"; converter.Options.PdfPageSize = PdfPageSize.A4; converter.Options.PdfPageOrientation = PdfPageOrientation.Portrait; converter.Options.WebPageWidth = 1024; converter.Options.WebPageHeight = 0; // Convert HTML to PDF PdfDocument pdf = converter.ConvertHtmlString(html); // Save the PDF document byte[] pdfBytes = pdf.Save(); // Close the PDF document pdf.Close(); // Return the PDF file return File(pdfBytes, "application/pdf", "output.pdf"); }

In the above example, we first create a new PDF document using the PdfDocument . Then, we add a new page to the document using the AddPage method.

Next, we create a new of the HtmlToPdf class, which is responsible for converting HTML to PDF. We set the HTML content to convert, with other options such as page size, orientation, and webpage dimensions.

Finally, we call the ConvertHtmlString method of the HtmlToPdf class to convert the HTML content to PDF. The resulting PDF document is then and returned as a file.

Conclusion

Converting HTML to PDF in ASP.NET MVC can be easily achieved using the SelectPdf library. By following the steps outlined in this article, you can generate high-quality PDF documents from HTML content in your ASP.NET MVC applications.

Rate this post

Leave a Reply

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

Table of Contents