How to Convert CSHTML to PDF in C#

Converting CSHTML to PDF is a common requirement in many applications. This task can be easily accomplished using the IronPDF library in C#.

IronPDF is a popular .NET library that enables developers to create, read, edit, and convert PDF documents programmatically. In this article, we will walk you through the steps of converting CSHTML to PDF with IronPDF in C#, along with examples.

Before we get started, let's discuss some important concepts that are necessary for this tutorial.

Important Concepts

PDF Converter

A PDF converter is a tool that converts any printable document or web page into a PDF document. It can be used to generate PDF files from HTML, Word, Excel, or any other printable document. PDF converters come in various forms, including online tools, desktop software, and libraries.

Razor View

A Razor view is a view engine that is used in ASP.NET Core to generate HTML pages dynamically. It is a markup syntax that combines HTML markup with C# code.

How to Convert CSHTML to PDF in C#: Figure 1 - Razor View

Razor view makes it easy for developers to create dynamic web pages by separating the presentation logic from the business logic.

Controller Class

A controller class is a C# class that handles incoming HTTP requests in an ASP.NET Core application. It contains methods that correspond to specific HTTP verbs (e.g., GET, POST, PUT, DELETE), and it returns an HTTP response.

NuGet Package Manager

NuGet Package Manager is a tool that is used in Visual Studio to manage packages in .NET projects. It makes it easy for developers to install, update, and uninstall packages in their projects. NuGet packages are libraries that contain reusable code and are distributed via the NuGet package manager.

Dependency Injection

Dependency Injection is a design pattern that allows developers to decouple their application components by injecting dependencies into their classes. It makes it easy to test and maintain applications by reducing dependencies and making the code more modular.

Now that we have covered the important concepts, let's dive into the process of converting CSHTML to PDF using IronPDF.

What is CSHTML?

CSHTML stands for C# Razor Syntax HTML. It is a type of file that contains both HTML markup and C# code. These files are used in AS.NET Core MVC applications to define the user interface of web pages. The Razor view engine is used to interpret the CSHTML files and generate HTML output that can be rendered by a web browser.

How to Convert CSHTML to PDF in C#: Figure 2 - CSHTML5

What is IronPDF?

IronPDF is a powerful .NET library that allows developers to create, read, edit, and convert PDF documents in C#. It is a popular tool for generating PDF documents programmatically in .NET applications. IronPDF supports a wide range of features, including PDF generation, PDF manipulation, PDF conversion, and PDF rendering.

How to Convert CSHTML to PDF in C#: Figure 3 - IronPDF for .NET

How to Convert CSHTML HTML string to PDF files with IronPDF in C#

Converting CSHTML to PDF with IronPDF is a simple process. The library provides a convenient API for converting HTML files to PDF documents. Here are the steps to convert CSHTML to PDF with IronPDF in C#:

Step 1 Install IronPDF

The first step is to install IronPDF in your C# project. You can install IronPDF using the NuGet package manager or by downloading the IronPDF.dll file and adding it to your project references. To install IronPDF using the NuGet Package Manager, open the Package Manager Console and run the following command

Install-Package IronPdf

Step 2 Create a CSHTML File

Next, create a CSHTML file that contains the content you want to convert to PDF. In this example, we will create a simple CSHTML file that displays the text "Hello, World!".


    @{
        Layout = null;
    }

        Hello

        Hello, World!

    @{
        Layout = null;
    }

        Hello

        Hello, World!
@
If True Then
		Layout = Nothing
End If

'INSTANT VB TODO TASK: The following line uses invalid syntax:
'		Hello Hello, World!
VB   C#

Save this file as "Hello.cshtml" in your project directory.

How to Convert CSHTML to PDF in C#: Figure 4 - PDF Files in C#

Step 3 Convert CSHTML to PDF document

To convert the CSHTML file to PDF, we'll use the IronPDF library in C#. Here's the code to convert "Hello.cshtml" to PDF:


    using System.IO;
    using IronPDF;
    using Microsoft.A.NETCore.Mvc;

    namespace CSHTMLtoPDF.Controllers
    {
        public class HomeController : Controller
        {
            public IActionResult Index()
            {
                var items = new[] { "Item 1", "Item 2", "Item 3" };
                return View(items);
            }

            public IActionResult DownloadPDF()
            {
                var items = new[] { "Item 1", "Item 2", "Item 3" };

                var html = this.RenderViewToString("PDFView", items);

                var renderer = new HtmlToPdf();
                var PDF = renderer.RenderHtmlAsPdf(html);

                var contentDisposition = new Syste.NET.Mime.ContentDisposition
                {
                    FileName = "Items.PDF",
                    Inline = false,
                };
                Response.Headers.Add("Content-Disposition", contentDisposition.ToString());

                return File(PDF.BinaryData, "application/PDF");
            }
        }

        public static class ControllerExtensions
        {
            public static string RenderViewToString(this Controller controller, string viewName, TModel model)
            {
                controller.ViewData.Model = model;

                using (var stringWriter = new StringWriter())
                {
                    var viewResult = ViewEngines.Engines.FindPartialView(controller.ControllerContext, viewName);
                    var viewContext = new ViewContext(controller.ControllerContext, viewResult.View, controller.ViewData, controller.TempData, stringWriter);
                    viewResult.View.Render(viewContext, stringWriter);
                    viewResult.ViewEngine.ReleaseView(controller.ControllerContext, viewResult.View);

                    return stringWriter.GetStringBuilder().ToString();
                }
            }
        }
    }

    using System.IO;
    using IronPDF;
    using Microsoft.A.NETCore.Mvc;

    namespace CSHTMLtoPDF.Controllers
    {
        public class HomeController : Controller
        {
            public IActionResult Index()
            {
                var items = new[] { "Item 1", "Item 2", "Item 3" };
                return View(items);
            }

            public IActionResult DownloadPDF()
            {
                var items = new[] { "Item 1", "Item 2", "Item 3" };

                var html = this.RenderViewToString("PDFView", items);

                var renderer = new HtmlToPdf();
                var PDF = renderer.RenderHtmlAsPdf(html);

                var contentDisposition = new Syste.NET.Mime.ContentDisposition
                {
                    FileName = "Items.PDF",
                    Inline = false,
                };
                Response.Headers.Add("Content-Disposition", contentDisposition.ToString());

                return File(PDF.BinaryData, "application/PDF");
            }
        }

        public static class ControllerExtensions
        {
            public static string RenderViewToString(this Controller controller, string viewName, TModel model)
            {
                controller.ViewData.Model = model;

                using (var stringWriter = new StringWriter())
                {
                    var viewResult = ViewEngines.Engines.FindPartialView(controller.ControllerContext, viewName);
                    var viewContext = new ViewContext(controller.ControllerContext, viewResult.View, controller.ViewData, controller.TempData, stringWriter);
                    viewResult.View.Render(viewContext, stringWriter);
                    viewResult.ViewEngine.ReleaseView(controller.ControllerContext, viewResult.View);

                    return stringWriter.GetStringBuilder().ToString();
                }
            }
        }
    }
Imports System.IO
	Imports IronPDF
	Imports Microsoft.A.NETCore.Mvc

	Namespace CSHTMLtoPDF.Controllers
		Public Class HomeController
			Inherits Controller

			Public Function Index() As IActionResult
				Dim items = { "Item 1", "Item 2", "Item 3" }
				Return View(items)
			End Function

			Public Function DownloadPDF() As IActionResult
				Dim items = { "Item 1", "Item 2", "Item 3" }

				Dim html = Me.RenderViewToString("PDFView", items)

				Dim renderer = New HtmlToPdf()
				Dim PDF = renderer.RenderHtmlAsPdf(html)

				Dim contentDisposition = New Syste.NET.Mime.ContentDisposition With {
					.FileName = "Items.PDF",
					.Inline = False
				}
				Response.Headers.Add("Content-Disposition", contentDisposition.ToString())

				Return File(PDF.BinaryData, "application/PDF")
			End Function
		End Class

		Public Module ControllerExtensions
			<System.Runtime.CompilerServices.Extension> _
			Public Function RenderViewToString(ByVal controller As Controller, ByVal viewName As String, ByVal model As TModel) As String
				controller.ViewData.Model = model

				Using stringWriter As New StringWriter()
					Dim viewResult = ViewEngines.Engines.FindPartialView(controller.ControllerContext, viewName)
					Dim viewContext As New ViewContext(controller.ControllerContext, viewResult.View, controller.ViewData, controller.TempData, stringWriter)
					viewResult.View.Render(viewContext, stringWriter)
					viewResult.ViewEngine.ReleaseView(controller.ControllerContext, viewResult.View)

					Return stringWriter.GetStringBuilder().ToString()
				End Using
			End Function
		End Module
	End Namespace
VB   C#

Let's walk through this code step-by-step:

  • We first import the necessary namespaces, including the IronPDF namespace, which contains the HTML to PDF conversion functionality.
  • We then define the Index method, which simply returns a list of items to the PDFView view.
  • We define the DownloadPDF method, which is responsible for generating the PDF document.
  • We start by rendering the PDFView view as an HTML string using the RenderViewToString method.
  • We then create an instance of the HtmlToPdf class, which is used to convert the HTML to a PDF document.
  • We pass the HTML string to the RenderHtmlAsPdf method of the HtmlToPdf class to generate the PDF document.
  • We then set the content disposition headers to force the PDF to be downloaded rather than displayed in the browser.
  • Finally, we return the PDF document as a file using the File method.

We also define an extension method called RenderViewToString, which is used to render a partial view as an HTML string.

This is the basic code to convert CSHTML to PDF with IronPDF in C#. However, there are many options and settings that you can use to customize the PDF output. Let's take a look at some of these options.

How to Convert CSHTML to PDF in C#: Figure 5 - PDF File

Customizing the PDF Output return file

IronPDF provides many options for customizing the PDF file output. You can set options such as page size, margins, orientation, header and footer, and more. Here's an example of how to customize the PDF output:


    using IronPDF;

    namespace ConsoleApp
    {
        class Program
        {
            static void Main(string[] args)
            {
                var renderer = new HtmlToPdf();
                renderer.PrintOptions.PaperSize = PdfPrintOptions.PdfPaperSize.A4;
                renderer.PrintOptions.MarginTop = 10;
                renderer.PrintOptions.MarginBottom = 10;
                renderer.PrintOptions.MarginLeft = 20;
                renderer.PrintOptions.MarginRight = 20;
                renderer.PrintOptions.Header = new SimpleHeaderFooter()
                {
                    CenterText = "{PDF-title}",
                    DrawDividerLine = true,
                    FontSize = 12
                };
                renderer.PrintOptions.Footer = new SimpleHeaderFooter()
                {
                    LeftText = "Page {page}/{total-pages}",
                    RightText = DateTime.Now.ToString("dd/MM/yyyy"),
                    DrawDividerLine = true,
                    FontSize = 10
                };
                var PDF = renderer.RenderHtmlAsPdf("\r\n\r\n\r\n    \r\n    Hello\r\n\r\n\r\n    Hello, World!\r\n\r\n");
                PDF.SaveAs("Hello.PDF");
            }
       }
    }

    using IronPDF;

    namespace ConsoleApp
    {
        class Program
        {
            static void Main(string[] args)
            {
                var renderer = new HtmlToPdf();
                renderer.PrintOptions.PaperSize = PdfPrintOptions.PdfPaperSize.A4;
                renderer.PrintOptions.MarginTop = 10;
                renderer.PrintOptions.MarginBottom = 10;
                renderer.PrintOptions.MarginLeft = 20;
                renderer.PrintOptions.MarginRight = 20;
                renderer.PrintOptions.Header = new SimpleHeaderFooter()
                {
                    CenterText = "{PDF-title}",
                    DrawDividerLine = true,
                    FontSize = 12
                };
                renderer.PrintOptions.Footer = new SimpleHeaderFooter()
                {
                    LeftText = "Page {page}/{total-pages}",
                    RightText = DateTime.Now.ToString("dd/MM/yyyy"),
                    DrawDividerLine = true,
                    FontSize = 10
                };
                var PDF = renderer.RenderHtmlAsPdf("\r\n\r\n\r\n    \r\n    Hello\r\n\r\n\r\n    Hello, World!\r\n\r\n");
                PDF.SaveAs("Hello.PDF");
            }
       }
    }
Imports Microsoft.VisualBasic
Imports IronPDF

	Namespace ConsoleApp
		Friend Class Program
			Shared Sub Main(ByVal args() As String)
				Dim renderer = New HtmlToPdf()
				renderer.PrintOptions.PaperSize = PdfPrintOptions.PdfPaperSize.A4
				renderer.PrintOptions.MarginTop = 10
				renderer.PrintOptions.MarginBottom = 10
				renderer.PrintOptions.MarginLeft = 20
				renderer.PrintOptions.MarginRight = 20
				renderer.PrintOptions.Header = New SimpleHeaderFooter() With {
					.CenterText = "{PDF-title}",
					.DrawDividerLine = True,
					.FontSize = 12
				}
				renderer.PrintOptions.Footer = New SimpleHeaderFooter() With {
					.LeftText = "Page {page}/{total-pages}",
					.RightText = DateTime.Now.ToString("dd/MM/yyyy"),
					.DrawDividerLine = True,
					.FontSize = 10
				}
				Dim PDF = renderer.RenderHtmlAsPdf(vbCrLf & vbCrLf & vbCrLf & "    " & vbCrLf & "    Hello" & vbCrLf & vbCrLf & vbCrLf & "    Hello, World!" & vbCrLf & vbCrLf)
				PDF.SaveAs("Hello.PDF")
			End Sub
		End Class
	End Namespace
VB   C#

In this example, we first create an instance of the HtmlToPdf class. We then set various options using the PrintOptions property of the HtmlToPdf class. Here are some of the options we set:

  • PaperSize: Sets the paper size of the PDF document to A4.

  • MarginTop, MarginBottom, MarginLeft', 'MarginRight: Sets the margins of the PDF document to 10 mm on the top and bottom and 20 mm on the left and right.

  • Header: Sets the header of the PDF document to display the title of the document and a divider line.

  • Footer: Sets the footer of the PDF document to display the page number, total pages, and the current date.

How to Convert CSHTML to PDF in C#: Figure 6 - IronPDF

After setting the options, we call the RenderHtmlAsPdf method with the same HTML content as before. Finally, we save the PDF document to a file named "Hello.PDF".

Test the application

With all the necessary code in place, we can now test the application. Follow these steps:

  • Run the application by pressing F5 or clicking the green "Play" button in Visual Studio.

  • In your web browser, navigate to http://localhost:/Home/Index, where is the port number assigned by Visual Studio.

  • Verify that the list of items is displayed correctly.

  • Click the "Download PDF" link to generate and download the PDF document.

If everything is working correctly, you should see a PDF document containing the list of items you defined earlier.

Converting a PDF to a CSHTML File with IronPDF

How to Convert CSHTML to PDF in C#: Figure 7 - PDF To CSHTML

To demonstrate how to convert a PDF to a CSHTML file with IronPDF, we will create a new console application in Visual Studio and use IronPDF to convert a sample PDF document to a CSHTML file. Follow these steps:

Step 1 Create a New Console Application

Open Visual Studio and create a new console application by selecting "File > New > Project" from the menu, then selecting "Console App (.NET Framework)" or "Console App (.NET Core)" from the list of project templates.

Step 2 Install the IronPDF NuGet Package

Next, we need to install the IronPDF NuGet package in our console application. To do this, right-click on the project in the Solution Explorer and select "Manage NuGet Packages" from the context menu.

In the NuGet Package Manager, search for "IronPDF" and select the "IronPDF" package from the search results. Click the "Install" button to install the package and its dependencies.

Step 3 Add PDF and CSHTML Files to the Project

For this example, we will use a sample PDF file that we want to convert to a CSHTML file. You can use any PDF file you like for this step.

Add the PDF file to the project by right-clicking on the project in the Solution Explorer and selecting "Add > Existing Item" from the context menu.

We also need to create an empty CSHTML file that we will use to store the converted HTML string. To do this, right-click on the project in the Solution Explorer and select "Add > New Item" from the context menu. Select "HTML Page" from the list of templates, then give the file a name (e.g. "converted.cshtml") and click "Add".

Step 4 Convert the PDF to a CSHTML File

With the necessary files in place, we can now write the code to convert the PDF to a CSHTML file using IronPDF. Add the following code to the Main method of your console application:


    using IronPDF;

    namespace PdfToHtml
    {
        class Program
        {
            static void Main(string[] args)
            {
                // Load the PDF file
                PdfDocument PDF = PdfDocument.FromFile("sample.PDF");

                // Convert the PDF to an HTML string
                string html = PDF.ToHtml();

                // Save the HTML string to the CSHTML file

    using IronPDF;

    namespace PdfToHtml
    {
        class Program
        {
            static void Main(string[] args)
            {
                // Load the PDF file
                PdfDocument PDF = PdfDocument.FromFile("sample.PDF");

                // Convert the PDF to an HTML string
                string html = PDF.ToHtml();

                // Save the HTML string to the CSHTML file
Imports IronPDF

	Namespace PdfToHtml
		Friend Class Program
			Shared Sub Main(ByVal args() As String)
				' Load the PDF file
				Dim PDF As PdfDocument = PdfDocument.FromFile("sample.PDF")

				' Convert the PDF to an HTML string
				Dim html As String = PDF.ToHtml()

				' Save the HTML string to the CSHTML file
VB   C#

Why should you use IronPDF?

IronPDF is a popular choice among .NET developers for a few key reasons:

Powerful PDF generation capabilities: IronPDF provides a wide range of features and options for creating and manipulating PDF documents programmatically, including the ability to add text, images, and other content to PDF pages, as well as the ability to merge and split existing PDF documents.

Versatile PDF conversion capabilities: IronPDF not only allows developers to generate PDF documents, but also provides functionality for converting PDFs to HTML strings or CSHTML files. This can be useful in situations where you need to display PDF content in a web application or extract data from PDF documents and use it in a web-based workflow.

Easy-to-use API: IronPDF's API is designed to be intuitive and easy to use, with a wide range of helper methods and properties that make it easy for developers to generate and manipulate PDF documents programmatically.

Strong community support: IronPDF has a large and active community of .NET developers who contribute to its development and provide support to other developers who are using the library.

Good documentation: IronPDF's documentation is extensive and well-organized, with detailed API reference documentation, tutorials, and examples that make it easy for developers to get started and learn how to use the library.

IronPDF's combination of powerful PDF generation and conversion capabilities, easy-to-use API, strong community support, and good documentation make it a popular choice among .NET developers who need to work with PDF documents in their applications.

Conclusion

Converting CSHTML to PDF is a common requirement in many applications. With IronPDF, this task can be easily accomplished in C#. In this article, we walked you through the steps of converting CSHTML to PDF with IronPDF, along with examples.

We also showed you how to customize the PDF output by setting various options such as paper size, margins, header and footer, and more. With IronPDF, you can create high-quality PDF documents from your CSHTML files quickly and easily.

Whether you need to create PDF documents from scratch, convert PDFs to HTML strings or CSHTML files, or extract data from PDF documents, IronPDF provides a flexible and intuitive API that makes it easy to get the job done.

With its strong community support and extensive documentation, IronPDF is a popular choice among .NET developers who need to work with PDFs in their applications. And by purchasing the Iron Software package, developers can get access to a comprehensive set of .NET libraries for working with common file formats at a discounted price, making it an excellent value for any .NET development team.

If you need to work with PDF documents in your .NET applications, IronPDF is definitely worth considering. With its powerful features, ease of use, and range of licensing options, it's a versatile and reliable tool that can help you get the job done quickly and efficiently.