itextsharp将gridview导出为pdf ascx页面

时间:2013-08-28 22:13:30

标签: pdf gridview data-binding pdf-generation itextsharp

我正在使用itextsharp生成动态事件列表的pdf。我已经将gridview设置为visible = false但是我的理解是我需要有一个gridview才能导出为pdf。

我打开pdf并且它是空白的,就像来自网格的信息没有正确复制一样。我可能错过了使用gridview进行数据绑定的一步。

这是gridview:

<asp:GridView BackColor="Green" ID="gvEventCaf" runat="server" visible="false" >
 <Columns>
        <asp:TemplateField HeaderText="EventName" 
            SortExpression="EventName" >
            <ItemTemplate>
                <%# Eval("EventName") %>
            </ItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="EventDate" 
            SortExpression="EventDate">
            <ItemTemplate>
                <%# Eval("EventDate") %>
            </ItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="EventTime" 
            SortExpression="EventTime">
            <ItemTemplate>
                <%# Eval("EventTime") %>
            </ItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="Description" 
            SortExpression="Description">
            <ItemTemplate>
                <%# Eval("Description") %>
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>`

这是代码隐藏:

using System;
using System.Text;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using iTextSharp.text;
using iTextSharp.text.pdf;
using iTextSharp.text.html;
using iTextSharp.text.html.simpleparser;
using System.IO;

public partial class Objects_EventList : System.Web.UI.UserControl
{

public string city;
public int showcount;

protected void Page_Load(object sender, EventArgs e)
{

    if (!IsPostBack)
    {
        Load_Events();
    };
}

protected void Load_Events()
{
    EventsDataContext edc = new EventsDataContext();

    var events = (from e in edc.tblEvents_Cafes
                  where e.EventDateTime >= DateTime.Now && e.VenueCity.Trim() == city.Trim() && (e.VenueName.Contains("Café") || e.VenueName.Contains("Cafe") )
                  orderby e.EventDateTime
                  select new {
                      EventName = e.EventName,
                      EventDate = e.EventDate,
                      EventTime = e.EventTime,
                      Description = edc.tblEvents_Cafe_Descriptions.OrderBy(d => d.Priority).Where(d => d.Keywords.ToLower() == e.EventName.ToLower()).Select(d => d.Description).First(), // edc.tblEvents_Cafe_Descriptions.OrderBy(d => d.Priority).Where(d => d.Keywords.ToLower() == e.EventName.ToLower() || d.Keywords.ToLower().CompareTo(e.EventName.ToLower()) >= 0).Select(d => d.Description).First()
                  }).Take(showcount);

    gvEventCaf.DataSource = events;
    gvEventCaf.DataBind();
}


protected void btnGenerateReport(object sender, EventArgs e)
{
    gvEventCaf.DataBind();

 //Create a table

iTextSharp.text.Table table = new iTextSharp.text

             .Table(gvEventCaf.Columns.Count);

table.Cellpadding = 5;





//Transfer rows from GridView to table

for (int i = 0; i < gvEventCaf.Rows.Count; i++)

{

    if (gvEventCaf.Rows[i].RowType == DataControlRowType.DataRow)

    {

        for (int j = 0; j < gvEventCaf.Columns.Count; j++)

        {

            string cellText = Server.HtmlDecode

                              (gvEventCaf.Rows[i].Cells[j].Text);

            iTextSharp.text.Cell cell = new iTextSharp.text.Cell(cellText);



            //Set Color of Alternating row

            if (i % 2 != 0)

            {

                cell.BackgroundColor = new Color(System.Drawing

                                    .ColorTranslator.FromHtml("#C2D69B"));

            }

            table.AddCell(cell);

        }

    }

}



//Create the PDF Document

Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 10f, 0f);

PdfWriter.GetInstance(pdfDoc, Response.OutputStream);

pdfDoc.Open();

pdfDoc.Add(table);

pdfDoc.Close(); 

Response.ContentType = "application/pdf";

Response.AddHeader("content-disposition", "attachment;" +

                               "filename=GridViewExport.pdf");

Response.Cache.SetCacheability(HttpCacheability.NoCache);

Response.Write(pdfDoc);

Response.End();

  }
}   

1 个答案:

答案 0 :(得分:0)

尝试使用这组代码从html获取内容并使用ItextSharp另存为pdf。

gd.DataSource = GetTable();
        gd.DataBind();


        System.IO.StringWriter stringWrite = new System.IO.StringWriter();

        System.Web.UI.HtmlTextWriter htmlWrite =
        new HtmlTextWriter(stringWrite);

        gd.RenderControl(htmlWrite);

        String htmlText = "<div>" + stringWrite.ToString() +"</div>";

        using (FileStream fs = new FileStream(Request.PhysicalApplicationPath + "\\test.htm", FileMode.Create))
        {
            using (StreamWriter w = new StreamWriter(fs, Encoding.UTF8))
            {
                w.WriteLine(htmlText);
            }
        }

          String html = String.Empty;
          using (StreamReader sr = new StreamReader(Request.PhysicalApplicationPath + "\\test.htm"))
          {
              html = sr.ReadToEnd();
          }

          Document document = new Document();

          PdfWriter.GetInstance(document, new FileStream(Request.PhysicalApplicationPath + "\\outfile.pdf", FileMode.Create));
          document.Open();
          iTextSharp.text.html.simpleparser.StyleSheet styles = new iTextSharp.text.html.simpleparser.StyleSheet();
          iTextSharp.text.html.simpleparser.HTMLWorker hw = new iTextSharp.text.html.simpleparser.HTMLWorker(document);
          hw.Parse(new StringReader(html));
          document.Close();

          Response.ClearContent();
          Response.ClearHeaders();
          Response.AddHeader("Content-Disposition", "inline;filename=outfile.pdf");
          Response.ContentType = "application/pdf";
          Response.WriteFile(Request.PhysicalApplicationPath + "\\outfile.pdf");
          Response.Flush();
          Response.Clear();




public static DataTable GetTable()
    {

        DataTable table = new DataTable();
        table.Columns.Add("Dosage", typeof(int));
        table.Columns.Add("Drug", typeof(string));
        table.Columns.Add("Patient", typeof(string));
        table.Columns.Add("Date", typeof(DateTime));


        table.Rows.Add(25, "Indocin", "David", DateTime.Now);
        table.Rows.Add(50, "Enebrel", "Sam", DateTime.Now);
        table.Rows.Add(10, "Hydralazine", "Christoff", DateTime.Now);
        table.Rows.Add(21, "Combivent", "Janet", DateTime.Now);
        table.Rows.Add(100, "Dilantin", "Melanie", DateTime.Now);
        return table;
    }