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項目

 

2、使用Nuget安裝RazorPDF Package

 

3、創建一個Customer Model

namespacePDFDemor.Models
{
    publicclassCustomer
    {
        publicintCustomerID {get;set; }

        publicstringFirstName {get;set; }

        publicstringLastName {get;set; }
    }
}

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

 

接着在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視圖,

 

創建完視圖之后,瀏覽之后的結果如下:

 

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>

瀏覽的結果如下:

 

總結

本文使用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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM