Try this approach using hiqpdf html to pdf converter , a commercial product:
public class HomeController : Controller
{
public ActionResult Index()
{
ViewBag.Message = "Welcome to ASP.NET MVC!";
Session["MySessionVariable"] = "My Session Variable Value assigned in Index";
return View();
}
public ActionResult About()
{
return View();
}
public string RenderViewAsString(string viewName, object model)
{
StringWriter stringWriter = new StringWriter();
ViewEngineResult viewResult = ViewEngines.Engines.FindView(ControllerContext, viewName, null);
ViewContext viewContext = new ViewContext(
ControllerContext,
viewResult.View,
new ViewDataDictionary(model),
new TempDataDictionary(),
stringWriter
);
viewResult.View.Render(viewContext, stringWriter);
return stringWriter.ToString();
}
[HttpPost]
public ActionResult ConvertThisPageToPdf()
{
string htmlToConvert = RenderViewAsString("Index", null);
String thisPageUrl = this.ControllerContext.HttpContext.Request.Url.AbsoluteUri;
String baseUrl = thisPageUrl.Substring(0, thisPageUrl.Length - "Home/ConvertThisPageToPdf".Length);
HtmlToPdf htmlToPdfConverter = new HtmlToPdf();
htmlToPdfConverter.HiddenHtmlElements = new string[] { "#convertThisPageButtonDiv" };
byte[] pdfBuffer = htmlToPdfConverter.ConvertHtmlToMemory(htmlToConvert, baseUrl);
FileResult fileResult = new FileContentResult(pdfBuffer, "application/pdf");
fileResult.FileDownloadName = "ThisMvcViewToPdf.pdf";
return fileResult;
}
[HttpPost]
public ActionResult ConvertAboutPageToPdf()
{
string htmlToConvert = RenderViewAsString("About", null);
String thisPageUrl = this.ControllerContext.HttpContext.Request.Url.AbsoluteUri;
String baseUrl = thisPageUrl.Substring(0, thisPageUrl.Length - "Home/ConvertAboutPageToPdf".Length);
HtmlToPdf htmlToPdfConverter = new HtmlToPdf();
byte[] pdfBuffer = htmlToPdfConverter.ConvertHtmlToMemory(htmlToConvert, baseUrl);
FileResult fileResult = new FileContentResult(pdfBuffer, "application/pdf");
fileResult.FileDownloadName = "AboutMvcViewToPdf.pdf";
return fileResult;
}
}
Source of this sample code: How to convert HTML to PDF using HiQPDF
source
share