Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 4024916
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 20, 20262026-05-20T10:46:53+00:00 2026-05-20T10:46:53+00:00

I have created a website using MVC3 along with the Razor view engine. What

  • 0

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);
    }
}
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-20T10:46:53+00:00Added an answer on May 20, 2026 at 10:46 am

    I use this code:

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

    This uses the current ControllerContext; if you don’t want that, you’ll need to mock an HttpContextBase.

    If you want to pass data back from the view, you’ll need to pass it in TempData, not ViewBag.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have created a clickonce deployment and published it to a website. I want
I have a website which uses PHP and HTML pages, I want to create
I have created a pretty basic Flash website for a client and am having
I have a button on a website that creates a directory and copys a
Let's say that I have a Flash website where you could create an avatar
We let users create ad-hoc queries in our website. We would like to have
Have created a c++ implementation of the Hough transform for detecting lines in images.
I have created a template for Visual Studio 2008 and it currently shows up
Can you create websites with Chinese characters in PHP? UPDATE: Perhaps I should have
I have a simple PowerShell script that uses WMI to create a web site

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.