itextsharp中的gridview列宽pdf工作需要样式

时间:2013-08-29 22:09:30

标签: c# css pdf gridview itext

这正在使用itextsharp在新窗口中以PDF格式打开正确的信息。 但是第一列太宽,第二列,第三列和第四列太小。 我该如何设计呢?

<form id="f1">
<asp:ImageButton BorderStyle="0" CssClass="submitbutton" runat="server" AlternateText="Get PDF" ID="LinkButton1" OnClick="btnGenerateReport" />

<asp:GridView BackColor="#FFFFFF" ID="gvEventCaf" runat="server" >
</asp:GridView>
</form>

以下是get pdf onclick的代码隐藏:

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Text;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.Security;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using iTextSharp.text;
using iTextSharp.text.pdf;
using iTextSharp.text.html;
using iTextSharp.text.html.simpleparser;
using System.IO;

protected void btnGenerateReport(object sender, EventArgs e)
{
    MyPage tmpPage = new MyPage();
    HtmlForm form = new HtmlForm();
    form.Controls.Add(gvEventCaf);
    tmpPage.Controls.Add(form);
    StringWriter sw = new StringWriter();
    HtmlTextWriter htmlWriter = new HtmlTextWriter(sw);
    form.Controls[0].RenderControl(htmlWriter);
    string htmlContent = sw.ToString();
    Document document = new Document();
    // step 2:
    // we create a writer that listens to the document
    // and directs a PDF-stream to a file
    PdfWriter.GetInstance(document, new FileStream("c:\\users\\My\\Downloads\\Calendar.pdf", FileMode.Create));

    // step 3: we open the document
    document.Open();

    // step 4: we add a paragraph to the document
    //document.Add(new Paragraph(htmlContent.ToString()));

    System.Xml.XmlTextReader _xmlr = new System.Xml.XmlTextReader(new StringReader(htmlContent));

    HtmlParser.Parse(document, _xmlr);

    // step 5: we close the document
    document.Close();

    ShowPdf("c:\\users\\Me\\Downloads\\Calendar.pdf");

}

这是我看到pdf的地方:

private void ShowPdf(string s)
{
    Response.ClearContent();
    Response.ClearHeaders();
    Response.AddHeader("Content-Disposition", "inline;filename=" + s);
    Response.ContentType = "application/pdf";
    Response.WriteFile(s);
    Response.Flush();
    Response.Clear();
}

这是我放在App_Code中的Mypage.cs帮助文件:

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

/// <summary>
/// Summary description for MyPage
/// </summary>
public class MyPage : Page
{
public override void VerifyRenderingInServerForm(Control control)
{
    GridView grid = control as GridView;
    if (grid != null && grid.ID == "gvEventCaf")
        return;
    else
        base.VerifyRenderingInServerForm(control);

}
}

1 个答案:

答案 0 :(得分:1)

这对我有用。我不得不对事件列表中的所有事件进行网格视图,但是与事件列表分开,我对gridview进行了样式设置,因此它远离网站页面,没有人可以看到它。

在对象eventlist.ascx的公共方面:

<%@ Control Language="C#" AutoEventWireup="true" CodeFile="EventList.ascx.cs"   Inherits="Objects_EventList" %>
<asp:ListView runat="server" ID="lstvwEvents" OnItemDataBound="lstvwEvents_OnItemDataBound">
<LayoutTemplate>
    <div class="eventtease" style="width: 249px;border-bottom: 1px solid #c0c06b;padding-right: 10px;padding-top: 10px;height: 300px;overflow: auto;">
        <asp:Literal runat="server" ID="itemPlaceholder" />
        <div style="clear: both;"></div>
    </div>
</LayoutTemplate>
<ItemTemplate>
    <h3 style="clear: both;border-top: 1px solid #c0c06b;padding-top: 10px;"><asp:Literal runat="server" ID="ltrlShortDate" /><br /><%# Eval("EventName").ToString().ToUpper() %><br />(<asp:Literal runat="server" ID="ltrlTimes" />)</h3>
    <p class="eventdescription" style="font: normal normal normal 7.5pt/normal Arial, Sans-Serif;margin-top: 3px;">
        <%# Eval("Description") %>

    </p>
    <asp:HyperLink runat="server" ID="lnkLearnMore" Text="LEARN MORE" CssClass="learnmore" Visible="false" />
</ItemTemplate>
</asp:ListView>

<form id="f1">
<div>
<asp:GridView ID="gvEventCaf" runat="server" 
    AutoGenerateColumns= "false" Font-Names= "Arial"  AllowPaging="true"   
    OnPageIndexChanging= "OnPaging" CssClass="offframe" >
   <Columns>
    <asp:BoundField ItemStyle-Width = "50px" ItemStyle-Font-Size ="10px" DataField = "EventName" HeaderText = "Event Name" />
    <asp:BoundField ItemStyle-Width = "50px" ItemStyle-Font-Size ="10px" DataField = "EventTime" HeaderText = "Event Time"/>
    <asp:BoundField ItemStyle-Width = "50px" ItemStyle-Font-Size ="10px" DataField = "EventDate" HeaderText = "Event Date"/>
    <asp:BoundField ItemStyle-Width = "100px" ItemStyle-Font-Size ="10px" DataField = "Description" HeaderText = "Description"/>
   </Columns> 
</asp:GridView>
</div>
<asp:Button ID="btnExportPDF" runat="server" Text="Download PDF" OnClick="btnExportPDF_Click" />
</form>

在后面的代码中,eventlist.ascx.cs:

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Text;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.Security;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
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);

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

protected void lstvwEvents_OnItemDataBound(Object sender, ListViewItemEventArgs e)
{
    ListViewDataItem dataItem = (ListViewDataItem)e.Item;
    if (e.Item.ItemType == ListViewItemType.DataItem)
    {
        var tempevent = dataItem.DataItem;
        Type t = tempevent.GetType();

        DateTime tempdate;

        if (DateTime.TryParse((t.GetProperty("EventDate").GetValue(tempevent, null)).ToString(), out tempdate))
        {
            Literal ltrlShortDate = new Literal();
            ltrlShortDate = (Literal)e.Item.FindControl("ltrlShortDate");
            ltrlShortDate.Text = tempdate.ToString("MM/dd/yyyy");
        }

        if (DateTime.TryParse((t.GetProperty("EventTime").GetValue(tempevent, null)).ToString(), out tempdate))
        {
            Literal ltrlTimes = new Literal();
            ltrlTimes = (Literal)e.Item.FindControl("ltrlTimes");
            ltrlTimes.Text = tempdate.ToString("hh:mm tt");
        }
    }
 }

//Begin gridview for pdf

protected void btnExportPDF_Click(object sender, EventArgs e)
{
    gvEventCaf.AllowPaging = Convert.ToBoolean(rbPaging.SelectedItem.Value);
    EventsDataContext edc = new EventsDataContext();
    var events = (from f in edc.tblEvents_Cafes
                  where f.EventDateTime >= DateTime.Now && f.VenueCity.Trim() == city.Trim() && (f.VenueName.Contains("Café") || f.VenueName.Contains("Cafe"))
                  orderby f.EventDateTime
                  select new
                  {
                      EventName = f.EventName,
                      EventDate = f.EventDate,
                      EventTime = f.EventTime,
                      VenueName = f.VenueName,
                      Description = edc.tblEvents_Cafe_Descriptions.OrderBy(d => d.Priority).Where(d => d.Keywords.ToLower() == f.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();

    //Create a table
    iTextSharp.text.Table table = new iTextSharp.text.Table(gvEventCaf.Columns.Count);
    table.Cellpadding = 5;

    //Set the column widths 
    int[] widths = new int[gvEventCaf.Columns.Count];
    for (int x = 0; x < gvEventCaf.Columns.Count; x++)
    {
        widths[x] = (int)gvEventCaf.Columns[x].ItemStyle.Width.Value;
        string cellText = Server.HtmlDecode(gvEventCaf.HeaderRow.Cells[x].Text);
        iTextSharp.text.Cell cell = new iTextSharp.text.Cell(cellText);
        cell.BackgroundColor = new Color(System.Drawing.ColorTranslator.FromHtml("#25925c"));
        table.AddCell(cell);
    }
    table.SetWidths(widths);

    //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();
    Paragraph chunk = new Paragraph("Calendar of Events for " + city + "Cafe" );
    pdfDoc.Add(chunk);
    pdfDoc.Add(table);
    pdfDoc.Close();
    Response.ContentType = "application/pdf";
    Response.AddHeader("content-disposition", "attachment;filename=CafeCalendar.pdf");
    Response.Cache.SetCacheability(HttpCacheability.NoCache);
    Response.Write(pdfDoc);
    Response.End();
}

protected void OnPaging(object sender, GridViewPageEventArgs e)
{
    gvEventCaf.PageIndex = e.NewPageIndex;
    gvEventCaf.DataBind();
}
}