如何使用ASP.net mvc4将HTML导出为PDF?

Rio*_*hen 3 asp.net-mvc asp.net-mvc-4

我有一个使用HTML开发asp.net mvc4的报告,我想用asp.net MVC4将这个报告导出为PDF文件,有人帮帮我吗?谢谢!

ram*_*ilu 6

使用Razor PDF生成PDF报告.这是一个简单的过程.

第1步 - 创建MVC应用程序

第2步 - 安装Rotativa PDF Nuget.

第3步 - 放置一个这样的简单模型

public class Person
{
    public string Name { get; set; }
    public int Age { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

第4步 - 为我们上面创建的模型创建一个简单视图,将视图命名为Index.

@model IEnumerable<WebApplication1.Controllers.Person>

@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>

<table class="table">
    <tr>
        <th>
            @Html.DisplayNameFor(model => model.Name)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.Age)
        </th>
        <th></th>
    </tr>

@foreach (var item in Model) {
    <tr>
        <td>
            @Html.DisplayFor(modelItem => item.Name)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.Age)
        </td>
    </tr>
}

</table>
Run Code Online (Sandbox Code Playgroud)

第5步 - 创建一个简单的控制器操作.

    public ActionResult IndexNew()
    {
        return new ActionAsPdf("GeneratePDF");
    }

    public ActionResult GeneratePDF()
    {
        List<Person> persons = new List<Person>();
        persons.Add(new Person() { Age = "29", Name = "Rami1" });
        persons.Add(new Person() { Age = "28", Name = "Rami2" });
        return View("Index", persons);
    }
Run Code Online (Sandbox Code Playgroud)

运行应用程序并导航到IndexNew Controller Action,将从GeneratePDF()Action生成PDF,并将由浏览器下载,如下所示 -

在此输入图像描述