如何将生成的HTML存储为字符串,而不是使用Razor视图引擎写入浏览器?

Dea*_*ean 4 asp.net-mvc wkhtmltopdf razor

我使用MVC3和Razor视图引擎创建了一个网站.我想要做的是获取生成的HTML并将其存储在流或字符串中,以便我可以将其写入文件而不是将其写入浏览器.

我需要做的是获取生成的HTML并将其转换为PDF并将PDF作为报告形式提供给用户.我已经解决了它的部分问题,我只是无法弄清楚将HTML转换为某种变量的最佳方法.

编辑 - 我最终走向了一个不同的方向,想分享结果.我创建了一个使用WKHTMLTOPDF项目将流转换为PDF的属性.现在我所做的就是为动作添加一个属性,而不是将HTML呈现给浏览器,它会弹出一个另存为对话框.

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)
    {
        // assemble destination PDF file name

        var workingDir = ConfigurationManager.AppSettings["PdfWorkingPath"];
        var exePath = ConfigurationManager.AppSettings["PdfExePath"]; //Path to the WKHTMLTOPDF executable.
        var p = new Process
                    {
                        StartInfo = {FileName = @"""" + exePath + @""""}
                    };

        var switches = "--print-media-type ";
        switches += "--margin-top 4mm --margin-bottom 4mm --margin-right 0mm --margin-left 0mm ";
        switches += "--page-size A4 ";

        p.StartInfo.Arguments = switches + " " + "-" + " " + fileName;

        p.StartInfo.UseShellExecute = false; // needs to be false in order to redirect output
        p.StartInfo.RedirectStandardOutput = true;
        //p.StartInfo.RedirectStandardError = true;
        p.StartInfo.RedirectStandardInput = true; // redirect all 3, as it should be all 3 or none
        p.StartInfo.WorkingDirectory = workingDir;

        p.Start();
        var sw = p.StandardInput;
        sw.Write(file.ToString());
        sw.Close();

        // read the output here...
        string output = p.StandardOutput.ReadToEnd();

        // ...then wait n milliseconds for exit (as after exit, it can't read the output)
        p.WaitForExit(60000);

        // read the exit code, close process
        int returnCode = p.ExitCode;
        p.Close();

        // if 0 or 2, it worked (not sure about other values, I want a better way to confirm this)
        return (returnCode <= 2);
    }
}
Run Code Online (Sandbox Code Playgroud)

SLa*_*aks 5

我用这个代码:

private string RenderView<TModel>(string viewPath, TModel model, TempDataDictionary tempData = null) {
    var view = new RazorView(
        ControllerContext,
        viewPath: viewPath,
        layoutPath: null,
        runViewStartPages: false,
        viewStartFileExtensions: null
    );

    var writer = new StringWriter();
    var viewContext = new ViewContext(ControllerContext, view, new ViewDataDictionary<TModel>(model), tempData ?? new TempDataDictionary(), writer);
    view.Render(viewContext, writer);
    return writer.ToString();
}
Run Code Online (Sandbox Code Playgroud)

这使用了当前的ControllerContext; 如果你不想那样,你需要嘲笑一个HttpContextBase.

如果要从视图中传回数据,则需要将其传入TempData,而不是ViewBag.