Generate pdf in Asp.Net Mvc using ITextSharp library

How to create pdf in Asp.Net mvc using ITextSharp.dll. Generate pdf from any html it is simple.

 Asp.Net   
 

Posted: April 8, 2017. | By: mustafa

In this article I will show you how to convert well formed html into pdf using ITextSharp. We require XMLWorkerHelper class to convert html into pdf in Asp.Net Mvc using C#.

We have two methods one is to send the file content using Mvc ActionResult Or We can write pdf file to the specified folder on the server and then redirect browser to open file in new window.

Users on our websites always require to generate and view pdf report and it is more good if we can generate pdf from existing html in our site. It can be achieved by using ITextSharp.dll in Asp.Net Mvc Project.
Let us write a method in C# to convert html string into pdf report.

First add reference to ITextSharp.dll and ITextSharp.xmlworker in our mvc project, both dll's are available in NuGet Package Manager in Visual Studio 2013.

public byte[] GeneratePdf(string finalHtml)
 {
 Byte[] bytes;

 // do some additional cleansing to handle some scenarios that are out of control with the html data 
 finalHtml = finalHtml.Replace("<br>", "<br />"); 
 
 // Create a stream that we can write to, in this case a MemoryStream
 using (var ms = new MemoryStream())
 {
 // Create an iTextSharp Document which is an abstraction of a PDF but **NOT** a PDF
 using (var doc = new Document())
 {
 // Create a writer that's bound to our PDF abstraction and our stream
 using (var writer = PdfWriter.GetInstance(doc, ms))
 {
 // Open the document for writing
 doc.Open();

 using (var srHtml = new StringReader(finalHtml))
 {
 // Parse the HTML
 iTextSharp.tool.xml.XMLWorkerHelper.GetInstance().ParseXHtml(writer, doc, srHtml);
 }

 doc.Close();
 }
 }

 // After all of the PDF "stuff" above is done and closed but **before** we
 // close the MemoryStream, grab all of the active bytes from the stream
 bytes = ms.ToArray();

 return bytes;
 }
 }


 

 

Html string passed to GeneratePdf() must be correct and well-formed or iTextSharp might throw an error, same is described in a blog example by Matthew Pavey.
Add action method in controller to consume above method and write pdf file to server.

public ActionResult DownloadPDFIText(string htmlContent)
 {
 try
 {
 TestProject.Helper.ITextSharp iText = new ITextSharp();
 byte[] bytes = iText.GeneratePdf(htmlContent);

var filePath = Server.MapPath("~/Pdf/Report.pdf");
 System.IO.File.WriteAllBytes(filePath, bytes);
 return Json(new
 {
 Valid = true,
 });
 }
 catch (Exception ex)
 {
 return Json(new
 {
 Valid = false,
 });
 }
 }
 


1. Now calling action method DownloadPDFIText() using jquery ajax for simple example I have used html of div "divReport" to pass data as html string. But suppose if we have well-formed html data from server we can produce very nice pdf files.

 

$(document).ready(function () {
 $("#linkDownloadIText").click(function () {
 var html = $('#divPdf').html(); // document.body.innerHTML;
 $.ajax({
 url: "/PDFHtml/DownloadPDFIText",
 //global: false,
 type: "POST",
 contentType: "application/json; charset=utf-8",
 data: JSON.stringify({
 htmlContent: html,
 }),
 dataType: "json",
 //processdata: false,
 success: function (response) {
 if (response.Valid)
 window.location = "/Pdf/Report.pdf";
 else {
 alert('download failed.');
 alert(response.Errors);
 }
 },
 error: function (XMLHttpRequest, textStatus, errorThrown) {
 alert("XMLHttpRequest=" + XMLHttpRequest.responseText + "\ntextStatus=" + textStatus + "\nerrorThrown=" + errorThrown);
 }
 });


 });
 });



2. Another method is to stream pdf file directly to browser using Mvc FileContentResult in this case we do not need to save file physically on to our server.

public FileContentResult DownloadPDFContent(string htmlContent)
 {
 TestProject.Helper.ITextSharp iText = new ITextSharp();
 byte[] bytes = iText.GeneratePdf(htmlContent);

 return File(bytes, "application/pdf", "Report.pdf");
 
 }
 


Now add html link with id="linkDownloadIText" for the ajax method and Html.ActionLink to call action method DownloadPDFContent to return File as FileContentResult.

<div id="divReport">
 <h2>Index</h2>
 <p>Hello World!</p>

<div class="col-lg-3">
 <a href="#" id="linkDownloadIText">Download IText PDF</a><br />
 @Html.ActionLink("PDFHtml", "DownloadPDFContent", "PDFHtml")<br />
 </div>
</div>

Also optionally we can pass css file to ParseXHtml method for styling the html content.


related posts

Back to top