How to Convert MVC View to PDF Using C# in ASP.NET
The Syncfusion HTML to PDF converter is a .NET library for converting webpages, SVG, MHTML, and HTML to PDF using C#. It is reliable and accurate. The result preserves all graphics, images, texts, fonts, and the layout of the original HTML document or webpage.
Using this library, you can convert MVC view to a PDF document using C# in ASP.NET.
Steps to convert MVC view to PDF document programmatically:
- Create a new ASP.NET Web application project.
- Install the Syncfusion.HtmlToPdfConverter.AspNet.Mvc5 NuGet package as reference to your MVC application from NuGet.org. To achieve this, Got to Tools -> NuGet package manager -> Package manager console and paste the following command.
NuGet\Install-Package Syncfusion.HtmlToPdfConverter.AspNet.Mvc5 -Version 21.1.41
Then, install the Syncfusion.EJ2.MVC5 NuGet package as a reference to your application to render the chart in the output window.
- Include the following namespaces in HomeController.cs file.
using Syncfusion.HtmlConverter;
using Syncfusion.Pdf;
using System.Drawing;
using Syncfusion.EJ2.Charts;
Steps to render the pie chart in output window:
- Add Syncfusion.EJ2 namespace reference in Web.config under Views folder.
<namespaces>
<add namespace="Syncfusion.EJ2"/>
</namespaces>
- The theme is referred to using CDN inside the of ~/Views/Shared/_Layout.cshtml file as follows.
<!-- Syncfusion Essential JS 2 Styles -->
<link rel="stylesheet" href="https://cdn.syncfusion.com/ej2/material.css" />
- The required scripts are referenced using CDN inside the of ~/Views/Shared/_Layout.cshtml file as follows.
<!-- Syncfusion ASP.NET MVC controls scripts -->
<script src="https://cdn.syncfusion.com/ej2/dist/ej2.min.js"></script>
7.The required scripts are reference using CDN inside the of ~/Views/Shared/_Layout.cshtml file as follows.
<body>
...
<!-- Syncfusion ASP.NET MVC Script Manager -->
@Html.EJS().ScriptManager()
</body>
- To render the pie chart, add the following code example in index.cshtml and Homecontroller.cs file.
Index.cshtml
@(Html.EJS().AccumulationChart("container").Series(
series =>
{
series.DataLabel(dl => dl.Visible(true).Name("DataLabelMappingName").Position(Syncfusion.EJ2.Charts.AccumulationLabelPosition.Outside).Font(ft => ft.FontWeight("600")).ConnectorStyle(cs => cs.Length("20px").Type(Syncfusion.EJ2.Charts.ConnectorType.Curve)))
.XName("Browser")
.YName("Users")
.Name("Browser")
.Explode(true)
.ExplodeOffset("10%")
.ExplodeIndex(0)
.InnerRadius("0%")
.DataSource(ViewBag.ChartPoints)
.Add();
})
.EnableSmartLabels(true)
.EnableAnimation(false)
.Title("Browser Market Share")
.LegendSettings(ls => ls.Visible(false))
.Tooltip(tp => tp.Enable(true).Format("<b>${point.x}</b><br>Browser Share: <b>${point.y}%</b>").Header(""))
.Load("load").EnableBorderOnMouseMove(false).Render()
)
Homecontroller.cs
public ActionResult Index()
{
List<PieChartData> ChartPoints = new List<PieChartData>
{
new PieChartData { Browser= "Chrome", Users= 59.28, DataLabelMappingName= "Chrome: 59.28%" },
new PieChartData { Browser= "UC Browser", Users= 4.37, DataLabelMappingName= "UC Browser: 4.37%" },
new PieChartData { Browser= "Internet Explorer", Users= 6.12, DataLabelMappingName= "Internet Explorer: 6.12%" },
new PieChartData { Browser= "Sogou Explorer", Users= 1.73, DataLabelMappingName= "Sogou Explorer: 1.73%" },
new PieChartData { Browser= "QQ", Users= 3.96, DataLabelMappingName= "QQ: 3.96%" },
new PieChartData { Browser= "Safari", Users= 4.73, DataLabelMappingName= "Safari: 4.73%" },
new PieChartData { Browser= "Opera", Users= 3.12, DataLabelMappingName= "Opera: 3.12%" },
new PieChartData { Browser= "Edge", Users= 7.48, DataLabelMappingName= "Edge: 7.48%" },
new PieChartData { Browser= "Others", Users= 9.57, DataLabelMappingName= "Others: 9.57%" }
};
ViewBag.ChartPoints = ChartPoints;
return View();
}
public class PieChartData
{
public string Browser;
public double Users;
public string DataLabelMappingName;
}
Steps to convert MVC view to PDF document
- Add a new button in index.cshtml for converting MVC view to the PDF document.
@{Html.BeginForm("ExportToPDF", "Home", FormMethod.Post);
{
<div>
<input type="submit" value="Convert PDF" style="width:150px;height:27px" />
</div>
}
Html.EndForm();
}
- Include the following code example in HomeController.cs file to convert MVC view to the PDF document.
public ActionResult ExportToPDF()
{
Syncfusion.Licensing.SyncfusionLicenseProvider.RegisterLicense("");
string html = string.Format("{0}://{1}", HttpContext.Request.Url.Scheme, HttpContext.Request.Url.Authority);
string baseUrl = "http://localhost:59979/";
using (WebClient client = new WebClient())
{
html = client.DownloadString(html);
}
//Initialize HTML to PDF converter.
HtmlToPdfConverter htmlConverter = new HtmlToPdfConverter(HtmlRenderingEngine.Blink);
BlinkConverterSettings blinkSettings = new BlinkConverterSettings();
blinkSettings.EnableJavaScript = true;
blinkSettings.AdditionalDelay = 4000;
blinkSettings.ViewPortSize = new Size(1024, 0);
htmlConverter.ConverterSettings = blinkSettings;
//Convert HTML string to a PDF document.
PdfDocument document = htmlConverter.Convert(html, baseUrl);
//Create a memory stream.
MemoryStream stream = new MemoryStream();
//Save the document to the memory stream.
document.Save(stream);
return File(stream.ToArray(), System.Net.Mime.MediaTypeNames.Application.Pdf, "Output.pdf");
}
By executing the above sample, you will get the output window as follows.
After clicking the Convert PDF button, the output PDF document shows as follows.
Take a moment to peruse the documentation, where you can find information on converting HTML pages to PDF document along with respective customization options and features.
Refer here to explore the rich set of Syncfusion Essential PDF features.
An online sample link for converting HTML to PDF.
Starting with v16.2.0.x, if you reference Syncfusion assemblies from trial setup or from the NuGet feed, include a license key in your projects. Refer to link to learn about generating and registering Syncfusion license key in your application to use the components without trail message.