Slinky
Slinky

Reputation: 5832

Output current html view to string when button clicked

I have a print-ready view that renders nicely in the browser. It would be nice to offer users the option to click a link or button located on that view that would call an action to create a PDF from the raw HTML in the view. I have the PDF processing part figured out, I just need help figuring out:

  1. When link or button is clicked, put the rendered HTML from that view into a string variable to be sent to my PDF processing code.

Here is my Controller method that renders the page:

 public ActionResult ViewReport(int? id, string memberID, int month, int year)
 {
            var task = new ViewReportTask();


            return View(task.BuildViewModel(id, memberID, month, year));
  }

The view is just a lot of html and razor code blocks so I did not include it here.

Thanks

Upvotes: 0

Views: 156

Answers (1)

Andrey Gubal
Andrey Gubal

Reputation: 3479

I'm using following approach:

You have Action method which generates your View:

public ActionResult ViewReport(int? id, string memberID, int month, int year)
 {
            var task = new ViewReportTask(); 
            return View(task.BuildViewModel(id, memberID, month, year));
  }

Create one more ActionResult:

  public ActionResult PrintMyView(int? id, string memberID, int month, int year)
    {
      return new ActionAsPdf( "ViewReport", new { id= id; memberID=memberID; month=month; year=year})
{ FileName = "ViewReport.pdf"};
    }

To have ActionAsPdf method you need to install Rotativa Nuget Package:

Install-Package Rotativa

Now to save your page as pdf user must click on following link on your view:

    @Html.ActionLink("Save as PDF, "PrintMyView", "Home", new{id= id, memberID=memberID, month=month, year=year}, null) 
//** I can't see where you takes parameters in your view, so I just list them.

It works fine for me.

Upvotes: 1

Related Questions