将webgrid导出为pdf asp mvc razor

时间:2012-08-03 10:48:51

标签: asp.net asp.net-mvc asp.net-mvc-3 pdf razor

如何将webgrid导出到mvc .net Web应用程序中的.pdf文件?

2 个答案:

答案 0 :(得分:1)

以下是几种方法:

  • 您可以使用上一个回复中提到的RazorPDF
  • 您可以使用Rotativa。哪个工作得非常快,但您需要在Full Trust上运行服务器的权限,因为PDF转换发生在可执行文件上
  • 您可以使用iTextSharp来实现最困难/最麻烦,但与此同时,您可以根据自己的意愿编写PDF文档。

希望有所帮助 -

答案 1 :(得分:0)

如需完整参考,请关注How to Export Webgrid to PDF in MVC4 Application

创建指向视图页面的操作链接

<div>
     Export Data : @Html.ActionLink("Export to PDF","GETPdf","Webgrid")
</div>

然后创建一个MVC Action,用于将webgrid数据导出为pdf文件。这里iTextSharp.dll用于导出pdf文件。

public FileStreamResult GETPdf()
    {
        List<CustomerInfo> all = new List<CustomerInfo>();
        using (MyDatabaseEntities dc = new MyDatabaseEntities())
        {
            all = dc.CustomerInfoes.ToList();
        }

        WebGrid grid = new WebGrid(source: all, canPage: false, canSort: false);
        string gridHtml = grid.GetHtml(
                columns: grid.Columns(
                        grid.Column("CustomerID", "Customer ID"),
                        grid.Column("CustomerName", "Customer Name"),
                        grid.Column("Address", "Address"),
                        grid.Column("City", "City"),
                        grid.Column("PostalCode", "Postal Code")
                    )
                ).ToString();

        string exportData = String.Format("<html><head>{0}</head><body>{1}</body></html>", "<style>table{ border-spacing: 10px; border-collapse: separate; }</style>", gridHtml);
        var bytes = System.Text.Encoding.UTF8.GetBytes(exportData);
        using (var input = new MemoryStream(bytes))
        {
            var output = new MemoryStream();
            var document = new iTextSharp.text.Document(PageSize.A4, 50, 50, 50, 50);
            var writer = PdfWriter.GetInstance(document, output);
            writer.CloseStream = false;
            document.Open();

            var xmlWorker = iTextSharp.tool.xml.XMLWorkerHelper.GetInstance();
            xmlWorker.ParseXHtml(writer, document, input, System.Text.Encoding.UTF8);
            document.Close();
            output.Position = 0;
            return new FileStreamResult(output, "application/pdf");
        }