Asp.net输出Gridview为PDF文件

标签: Asp.net GridView C#
发布时间: 2009/6/15 21:32:50

首先创建实体类:

public class Customer
    {
        private string _firstName;
        private string _lastName;
        private string _email;

        public string FirstName
        {
            get { return _firstName; }
            set { _firstName = value; }
        }

        public string LastName
        {
            get { return _lastName; }
            set { _lastName = value; }
        }

        public string FullName
        {
            get { return _firstName + " " + _lastName; }
        }

        public string Email
        {
            get { return _email; }
            set { _email = value; }
        }
    }

创建一个gridview和生成一些虚拟数据。




 
private void BindData()
        {
            gvCustomers.DataSource = GetCustomers();
            gvCustomers.DataBind();
        }

        private List GetCustomers()
        {
            List customers = new List();

            for (int i = 1; i <= 20; i++)
            {
                Customer customer = new Customer();
                customer.FirstName = "FirstName" + i;
                customer.LastName = "LastName" + i;
                customer.Email = "Email" + i;
                customers.Add(customer);
            }

            return customers;
        }

生成如下图所示的gridview和数据

错误的生成PDF的方法:

protected void WrongExportGridViewToPDF(object sender, EventArgs e)
        {
            Response.Clear();
           
            StringWriter sw = new StringWriter();
            HtmlTextWriter htw = new HtmlTextWriter(sw);
            gvCustomers.RenderControl(htw);
           
            Response.ContentType = "application/pdf";
            Response.AddHeader("content-disposition", "attachment; filename=MypdfFile.pdf");
            Response.Write(sw.ToString());
            Response.End();
        }

为了生成pdf我们需要使用第三方库ITextSharp
下载地址请点击链接。
ITextSharp Library

我们将使用ITextSharp库输出文档到 ResponeOutputStream. 我们看一下下面的代码:

protected void ExportToPDFClick(object sender, EventArgs e)
        {
            Response.Clear();

            StringBuilder sb = new StringBuilder();
            StringWriter sw = new StringWriter(sb);
            HtmlTextWriter htw = new HtmlTextWriter(sw);

            gvCustomers.RenderControl(htw);

            Response.ContentType = "application/pdf";
            Response.AddHeader("content-disposition", "attachment; filename=MypdfFile.pdf");

            Document document = new Document();


            PdfWriter.GetInstance(document, Response.OutputStream);
            document.Open();

            string html = sb.ToString();

            XmlTextReader reader = new XmlTextReader(new StringReader(html));
            HtmlParser.Parse(document, reader);

            document.Close();
            sw.Close();

            Response.Flush();
            Response.End();
        }

上面的代码用Document对象代表一个PDF文档,gridview被翻译成HtmlTextWriter.HtmlTextWriter使用StringWriter and StringBuilder 来获得GridView的html 。 PdrWriter.getInstance 用于设置Document 实例转化为输出流。 HtmlParser 类负责转化显示的iGridView的HTML。 这是为了使PDF文档以表格形式的呈现 .如果你遗漏了 使用HtmlParser ,原始的HTML将会呈现在PDF文档中。

看一下下方的呈现为PDF文档Gridview的截图:

你能看到表格的样式不好看,我们来看看怎么改变表格的呈现。

ITextSharp 库包含用来创建表格的Table 类,我们用Table类改进我们的呈现。按钮的点击事件的代码如下

 protected void ExportCollectionToPDFClick(object sender,EventArgs e)
        {
            ExportToPDFCollection(new string[] { "FirstName", "LastName", "FullName" });
        }

ExportToPDFCollection方法是用Customer集合创建表格。他的每个参数是我们想要输出到PDF文档的列的名字。
这里是ExportToPDFCollection 方法的实现:

private void ExportToPDFCollection(string[] columnNames)
        {
            List customers = GetCustomers();

            int noOfColumns = columnNames.Length;
            int noOfRows = customers.Count;
            string propertyValue = String.Empty;
           
            iTextSharp.text.Table table = new iTextSharp.text.Table(noOfColumns, noOfRows);
            table.BackgroundColor = new iTextSharp.text.Color(gvCustomers.BackColor);
           
            table.AutoFillEmptyCells = true;

            for (int rowNo = 0; rowNo < noOfRows; rowNo++)
            {
                for (int columnNo = 0; columnNo < noOfColumns; columnNo++)
                {
                    propertyValue = GetPropertyValue(customers[rowNo], columnNames[columnNo]);
                    table.AddCell(propertyValue, new Point(rowNo, columnNo));
                }
            }

            Document document = new Document();
            PdfWriter.GetInstance(document, Response.OutputStream);
            document.Open();
            document.Add(table);
            document.Close();

            Response.ContentType = "application/pdf";
            Response.AddHeader("content-disposition", "attachment; filename=MypdfFile.pdf");
            Response.End();
        }


上面的代码创建了表格然后添加单元格,每个单元格是由Customer类的属性名构成。GetPropertyValue 方法使用反射获得属性的值。
private string GetPropertyValue(Customer customer,string propertyName)
        {
            PropertyInfo property = customer.GetType().GetProperty(propertyName);
            return property.GetValue(customer, null).ToString();
        }

这就是结果:

尽管pdf文档不是十分美观但是你能做出调整使他美观。记住单元格是根据属性列出来的。



结论:
这篇文章我们学习了怎么输出Gridview成PDF.我们讨论了不同的方法去实现这个操作。在以后的文章里我们将演示怎么样自定义输出的PDF文档的呈现。

官方微信
官方QQ群
31647020