MVC中使用RazorPDF创建PDF

这篇文章主要介绍使用Nuget package中的RazorPDF简单的创建PDF的方法。

 

关于RazorPDF

这个Nuget PackageAl Nyveldt创建。它内部使用ITextSharp。RazorPDF使用Razor视图引擎创建iTextXMLiTextXML用来生成PDF文件。如果你想了解更多的关于RazorPDF的情况,可以访问:

https://www.nuget.org/packages/RazorPDF

 

下面举个例子使用RazorPDF

1、首先创建一个MVC项目

 MVC中使用RazorPDF创建PDF

MVC中使用RazorPDF创建PDF

2、使用Nuget安装RazorPDF Package

 

MVC中使用RazorPDF创建PDF

3、创建一个Customer Model

namespacePDFDemor.Models

{

    publicclassCustomer

    {

        publicintCustomerID {get;set; }



        publicstringFirstName {get;set; }



        publicstringLastName {get;set; }

    }

}

4、创建一个包含返回Costomer ListAction的控制器,名字叫做CustomerController 

 MVC中使用RazorPDF创建PDF

接着在Index中编写返回List的代码,

usingSystem;

usingSystem.Collections.Generic;

usingSystem.Linq;

usingSystem.Web;

usingSystem.Web.Mvc;

usingPDFDemo.Models;



namespacePDFDemo.Controllers

{

    publicclassCustomerController : Controller

    {

        //



        // GET: /Customer/



        publicActionResult Index()

        {

            List<Customer> customers=newList<Customer>();



            for(inti = 1; i <= 10; i++)

            {

                Customer customer =newCustomer

                {

                    CustomerID = i,

                    FirstName =string.Format("FirstName{0}", i.ToString()),

                    LastName =string.Format("LastName{0}", i.ToString())

                };

                customers.Add(customer);

            }

            returnView(customers);

        }

    }

}

 

然后给这个Index创建一个List视图,

 MVC中使用RazorPDF创建PDF

创建完视图之后,浏览之后的结果如下:

 MVC中使用RazorPDF创建PDF

5、添加生成PDF文档的功能

以上都是铺垫啊,这里才是本文的重点啊。

在控制器中添加一个新的Action取名叫做“PDF”,返回RazorPDF.pdfResult

publicActionResult PDF()

{

    List<Customer> customers =newList<Customer>();



    for(inti = 1; i <= 10; i++)

    {

        Customer customer =newCustomer

        {

            CustomerID = i,

            FirstName =string.Format("FirstName{0}", i.ToString()),

            LastName =string.Format("LastName{0}", i.ToString())



        };

        customers.Add(customer);

    }

    return new RazorPDF.PdfResult(customers,"PDF"); // 注意这里,这里返回的是一个RazorPDF.PdfResult

}

 

然后给这个Action添加视图,

@model List<PDFDemo.Models.Customer>



@{

    Layout = null;

}



<!DOCTYPE html>

<html>

<head>

</head>

<body>

    <h2>Html List in PDF</h2>

    <tablewidth="100%">

        <tr>

            <td>First Name</td>

            <td>Last Name</td>

        </tr>

        @foreach (var item in Model)

        {

            <tr>

                <td>@item.FirstName</td>

                <td>@item.LastName</td>

            </tr>

        }

    </table>

</body>

</html>

浏览的结果如下:

 MVC中使用RazorPDF创建PDF

总结

本文使用RazorPDF创建了一个简单的PDF页面,从当前的使用来看,使用RazorPDF穿件PDF还是挺简单的。如果大家想更多的查看RazorPDF的例子,可以访问:

https://github.com/RazorAnt/RazorPDFSample

 

原文链接:http://www.dotnetjalps.com/2013/06/Creating-PDF-with-ASP-Net-MVC-and-RazorPDF.html

你可能感兴趣的:(mvc)