Tiaan
Tiaan

Reputation: 699

Saving an MVC View to PDF

As the title suggests, I am looking for a way to export a .NET MVC View to a PDF.

My program works like this:

Page 1 Takes in information

Page 2 Takes this information and heavily styles it with CSS etc

So basically I need to save page 2 after it has been processed and used the information from Page 1's model.

Thanks in advance!

Upvotes: 0

Views: 1838

Answers (1)

RickL
RickL

Reputation: 3403

To render a non-static page to a pdf, you need to render the page to a string, using a ViewModel, and then convert to a pdf:

Firstly, create a method RenderViewToString in a static class, that can be referenced in a Controller:

public static class StringUtilities
{
    public static string RenderViewToString(ControllerContext context, string viewPath, object model = null, bool partial = false)
    {
        // first find the ViewEngine for this view
        ViewEngineResult viewEngineResult = null;
        if (partial)
        {
            viewEngineResult = ViewEngines.Engines.FindPartialView(context, viewPath);
        }
        else
        {
            viewEngineResult = ViewEngines.Engines.FindView(context, viewPath, null);
        }

        if (viewEngineResult == null)
        {
            throw new FileNotFoundException("View cannot be found.");
        }

        // get the view and attach the model to view data
        var view = viewEngineResult.View;
        context.Controller.ViewData.Model = model;

        string result = null;

        using (var sw = new StringWriter())
        {
            var ctx = new ViewContext(context, view, context.Controller.ViewData, context.Controller.TempData, sw);
            view.Render(ctx, sw);
            result = sw.ToString();
        }

        return result.Trim();
    }
}

Then, in your Controller:

var viewModel = new YourViewModelName
{
    // Assign ViewModel values
}

// Render the View to a string using the Method defined above
var viewToString = StringUtilities.RenderViewToString(ControllerContext, "~/Views/PathToView/ViewToRender.cshtml", viewModel, true);

You then have the view, generated by a ViewModel, as a string that can be converted to a pdf, using one of the libraries out there.

Hope it helps, or at least sets you on the way.

Upvotes: 2

Related Questions