I created a website using MVC3 along with the Razor view engine. I want to make the resulting HTML and save it in a stream or line so that I can write it to a file, and not write to the browser.
I need to make the resulting HTML and convert it to PDF and provide PDF to the user as a reporting form. I already have this part, I just can’t figure out how best to embed HTML in some kind of variable.
EDIT . I ended up in a different direction and wanted to share the results. I created an attribute that uses the WKHTMLTOPDF project to convert a stream to a PDF. Now all I do is add an attribute to the action and instead of displaying the HTML in the browser, it opens the save dialog as.
public class PdfInterceptAttribute : ActionFilterAttribute { public override void OnResultExecuted(ResultExecutedContext filterContext) { var viewResult = filterContext.Result as ViewResult; var workingDir = ConfigurationManager.AppSettings["PdfWorkingPath"]; var fileName = workingDir + @"\" + Guid.NewGuid() + ".pdf"; if (viewResult != null) { var view = viewResult.View; var writer = new StringWriter(); var viewContext = new ViewContext(filterContext.Controller.ControllerContext, view, viewResult.ViewData, viewResult.TempData, writer); view.Render(viewContext, writer); HtmlToPdf(new StringBuilder(writer.ToString()), fileName); filterContext.HttpContext.Response.Clear(); var pdfByte = File.ReadAllBytes(fileName); filterContext.HttpContext.Response.ContentType = "application/pdf"; filterContext.HttpContext.Response.AddHeader("Content-Disposition", "attachment; filename=Report.pdf"); filterContext.HttpContext.Response.BinaryWrite(pdfByte); filterContext.HttpContext.Response.End(); } base.OnResultExecuted(filterContext); } private static bool HtmlToPdf(StringBuilder file, string fileName) {
source share