4

I have created a website using MVC3 along with the Razor view engine. What I want to do is take the resulting HTML and store it in a stream or string so that I can write it to a file instead of writing it to the browser.

What I need to do is take the resulting HTML and convert it to PDF and supply the PDF to the user as a form of reporting. I have that portion of it worked out already, I just can't figure out the best way to get the HTML in to a variable of some sort.

EDIT - I ended up going in a little bit different direction and wanted to share the results. I created an attribute that uses the WKHTMLTOPDF project to convert the stream to PDF. Now all I do is add an attribute to the action and instead of rendering the HTML to the browser it pops up a save as dialog.

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);
    }
}
4

2 回答 2

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();
}

这使用电流ControllerContext;如果你不想这样,你需要模拟一个HttpContextBase.

如果你想从视图传回数据,你需要传入TempData,而不是ViewBag.

于 2011-02-28T21:45:13.253 回答
0

看看@http ://razorengine.codeplex.com/

于 2011-02-28T21:56:07.840 回答