10 .NET API products for your office documents
Total Suite Value:
$7,192 USD
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.
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.
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.
Razor View
Razor view makes it easy for developers to create dynamic web pages by separating the presentation logic from the business logic.
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 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 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.
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.
CSHTML5
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.
IronPDF for .NET
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#:
The first step is to install IronPDF from NuGet Package Manager in your C# project. You can install IronPDF 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
Next, create a CSHTML file that contains the content you want to convert to PDF. In this example, we will create a simple CSHTML tutorial 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!
Save this file as "Hello.cshtml" in your project directory.
PDF Files in C#
To convert the CSHTML to PDF 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.AspNetCore.Mvc;
namespace CSHTMLtoPDF.Controllers
{
public class HomeController : Controller
{
private readonly IRazorViewRenderer _viewRenderService;
public HomeController(IRazorViewRenderer viewRenderService)
{
_viewRenderService = viewRenderService;
}
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" };
ChromePdfRenderer renderer = new ChromePdfRenderer();
PdfDocument pdf = renderer.RenderRazorViewToPdf(_viewRenderService, "Views/Home/Index.cshtml", items);
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");
}
}
}
using System.IO;
using IronPdf;
using Microsoft.AspNetCore.Mvc;
namespace CSHTMLtoPDF.Controllers
{
public class HomeController : Controller
{
private readonly IRazorViewRenderer _viewRenderService;
public HomeController(IRazorViewRenderer viewRenderService)
{
_viewRenderService = viewRenderService;
}
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" };
ChromePdfRenderer renderer = new ChromePdfRenderer();
PdfDocument pdf = renderer.RenderRazorViewToPdf(_viewRenderService, "Views/Home/Index.cshtml", items);
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");
}
}
}
Imports System.IO
Imports IronPdf
Imports Microsoft.AspNetCore.Mvc
Namespace CSHTMLtoPDF.Controllers
Public Class HomeController
Inherits Controller
Private ReadOnly _viewRenderService As IRazorViewRenderer
Public Sub New(ByVal viewRenderService As IRazorViewRenderer)
_viewRenderService = viewRenderService
End Sub
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 renderer As New ChromePdfRenderer()
Dim pdf As PdfDocument = renderer.RenderRazorViewToPdf(_viewRenderService, "Views/Home/Index.cshtml", items)
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
End Namespace
Let's walk through this code step-by-step:
Index
method, which simply returns a list of items to a Razor view.DownloadPDF
method, which is responsible for generating the PDF document.ChromePdfRenderer
.RenderRazorViewToPdf
extension method to generate a Razor view with data into a PDF file.Content-Disposition
headers to force the PDF to be downloaded rather than displayed in the browser.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.
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 ChromePdfRenderer();
renderer.RenderingOptions.MarginTop = 10;
renderer.RenderingOptions.MarginBottom = 10;
renderer.RenderingOptions.MarginLeft = 20;
renderer.RenderingOptions.MarginRight = 20;
renderer.RenderingOptions.HtmlHeader = new HtmlHeaderFooter()
{
MaxHeight = 20, //millimeters
HtmlFragment = "<img src='logo.png'>",
BaseUrl = new Uri(@"C:\assets\images\").AbsoluteUri
};
renderer.RenderingOptions.HtmlFooter = new HtmlHeaderFooter()
{
MaxHeight = 15, //millimeters
HtmlFragment = "<center><i>{page} of {total-pages}<i></center>",
DrawDividerLine = true
};
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 ChromePdfRenderer();
renderer.RenderingOptions.MarginTop = 10;
renderer.RenderingOptions.MarginBottom = 10;
renderer.RenderingOptions.MarginLeft = 20;
renderer.RenderingOptions.MarginRight = 20;
renderer.RenderingOptions.HtmlHeader = new HtmlHeaderFooter()
{
MaxHeight = 20, //millimeters
HtmlFragment = "<img src='logo.png'>",
BaseUrl = new Uri(@"C:\assets\images\").AbsoluteUri
};
renderer.RenderingOptions.HtmlFooter = new HtmlHeaderFooter()
{
MaxHeight = 15, //millimeters
HtmlFragment = "<center><i>{page} of {total-pages}<i></center>",
DrawDividerLine = true
};
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 ChromePdfRenderer()
renderer.RenderingOptions.MarginTop = 10
renderer.RenderingOptions.MarginBottom = 10
renderer.RenderingOptions.MarginLeft = 20
renderer.RenderingOptions.MarginRight = 20
renderer.RenderingOptions.HtmlHeader = New HtmlHeaderFooter() With {
.MaxHeight = 20,
.HtmlFragment = "<img src='logo.png'>",
.BaseUrl = (New Uri("C:\assets\images\")).AbsoluteUri
}
renderer.RenderingOptions.HtmlFooter = New HtmlHeaderFooter() With {
.MaxHeight = 15,
.HtmlFragment = "<center><i>{page} of {total-pages}<i></center>",
.DrawDividerLine = True
}
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
In this example, we first create an instance of the ChromePdfRenderer
class. We then set various options using the RenderingOptions
property of the ChromePdfRenderer
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.HtmlHeader
: Sets the header of the PDF document to display the title of the document and a divider line.HtmlFooter
: Sets the footer of the PDF document to display the page number, total pages, and the current date.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".
With all the necessary code in place, we can now test the application. Follow these steps:
http://localhost:/Home/Index
, where is the port number assigned by Visual Studio.If everything is working correctly, you should see a PDF document containing the list of items you defined earlier.
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:
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.
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.
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".
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
End Sub
End Class
End Namespace
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.
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.