使用ITextSharp从Gridview导出为PDF

时间:2015-07-16 08:49:16

标签: c# asp.net gridview itextsharp

我用来使用iTextSharp库从gridview生成PDF文件。

这是我在aspx页面中的简单GridView:

        <asp:GridView ID="gvUsers" runat="server" AutoGenerateColumns="False" EmptyDataText="GV Empty."
            DataKeyNames="ID" CssClass="mGrid" Width="500" HorizontalAlign="Center">
            <Columns>
                <asp:BoundField DataField="Day" HeaderText="Day" ReadOnly="true" HtmlEncode="false" ItemStyle-HorizontalAlign="Center" ItemStyle-CssClass="ddl_Class_new" DataFormatString="{0:dd/MM/yyyy}" />
                <asp:BoundField DataField="Code" HeaderText="Code" ReadOnly="true" HtmlEncode="false" ItemStyle-HorizontalAlign="Center" ItemStyle-CssClass="ddl_Class_new" />
                <asp:BoundField DataField="Name" HeaderText="Name" ReadOnly="true" HtmlEncode="false" ItemStyle-HorizontalAlign="Center" ItemStyle-CssClass="ddl_Class_new" />
                <asp:BoundField DataField="User" HeaderText="User" ReadOnly="true" HtmlEncode="false" ItemStyle-HorizontalAlign="Center" ItemStyle-CssClass="ddl_Class_new" />
                <asp:BoundField DataField="Number" HeaderText="Number" ReadOnly="true" HtmlEncode="false" ItemStyle-HorizontalAlign="Center" ItemStyle-CssClass="ddl_Class_new" />
                <asp:BoundField DataField="Age" HeaderText="Age" ReadOnly="true" HtmlEncode="false" ItemStyle-HorizontalAlign="Center" ItemStyle-CssClass="ddl_Class_new" />
                <asp:BoundField DataField="Annotation" HeaderText="Annotation" ReadOnly="true" HtmlEncode="false" ItemStyle-HorizontalAlign="Center" ItemStyle-CssClass="ddl_Class_new" />
            </Columns>
        </asp:GridView>

我有一个问题,因为在导出的pdf文件中,我找不到GV&#34; Annotation&#34;的最后一列。

我没有错误,但列标题为#34;注释&#34;并且你的价值不会被出口。

我的代码如下,出了什么问题?

有人知道我该怎么办?

提前谢谢。

for (int colIndex = 0; colIndex < colCount; colIndex++)
                {
                    table.SetWidths(new int[] { 20, 20, 20, 20, 20, 20 });
                    cellText = Server.HtmlDecode(gv.HeaderRow.Cells[colIndex].Text);
                    BaseFont bf = BaseFont.CreateFont(
                                            BaseFont.HELVETICA,
                                            BaseFont.CP1252,
                                            BaseFont.EMBEDDED,
                                            false);

                    iTextSharp.text.Font font = new iTextSharp.text.Font(bf, 10, iTextSharp.text.Font.BOLD, BaseColor.WHITE);
                    cell = new PdfPCell(new Phrase(cellText.Replace("<br />", Environment.NewLine), font));
                    cell.HorizontalAlignment = Element.ALIGN_CENTER;
                    cell.VerticalAlignment = Element.ALIGN_MIDDLE;
                    cell.FixedHeight = 45f;
                    cell.BackgroundColor = new BaseColor(System.Drawing.ColorTranslator.FromHtml("#a52a2a"));
                    table.AddCell(cell);
                }
for (int rowIndex = ; rowIndex < gvUsers.Rows.Count; rowIndex++)
                {
                    if (gvUsers.Rows[rowIndex].RowType == DataControlRowType.DataRow)
                    {
                        for (int j = 0; j < gvUsers.Columns.Count - 1; j++)
                        {
                            cellText = Server.HtmlDecode(gvUsers.Rows[rowIndex].Cells[j].Text);
                            cell = new PdfPCell(new Phrase(cellText, FontFactory.GetFont("PrepareForExport", 8)));
                            cell.HorizontalAlignment = Element.ALIGN_CENTER;
                            cell.VerticalAlignment = Element.ALIGN_MIDDLE;
                            cell.FixedHeight = 25f;
                            table.AddCell(cell);
                        }
                    }
                }

编辑#1

Exception Details: iTextSharp.text.DocumentException: Wrong number of columns.

table.SetWidths(new int[] { 15, 15, 15, 15, 15, 15, 10 });

编辑#2

                int colCount = gvUsers.Columns.Count - 1;
                table = new PdfPTable(colCount);
                table.HorizontalAlignment = 0;
                table.WidthPercentage = 100;
                int[] colWidths = new int[gvUsers.Columns.Count];
                PdfPCell cell;
                string cellText;

                for (int colIndex = 0; colIndex < colCount; colIndex++)
                { ....

1 个答案:

答案 0 :(得分:1)

有问题:

table.SetWidths(new int[] { 20, 20, 20, 20, 20, 20 });

您可以看到,您为PdfPTable设置了6列,但您的GridView有7列。并且,所有widths的总和超过100%

尝试:

table.SetWidths(new int[] { 15, 15, 15, 15, 15, 15, 10 });

或者更改width每个column的方式。顺便说一句。 columns width位于single,因此您可以使用width14.5等值。

更新 :(抱歉,它在vb中,但您可以转换为c#)

Dim ttbl As New PdfPTable(7)
ttbl.WidthPercentage = 100
Dim cp() As Integer = {15,15,15,15,15,15,10}
ttbl.SetWidths(cp)

为表定义了7 cols。你这样做了吗?

顺便说一句。为什么将table.SetWidths(new int[] { 15, 15, 15, 15, 15, 15, 10 });置于for...next块中?必须放在for之前和之外。

更新#2:

vb中有完整的代码,工作正常:

Private Sub PrintTable()
        Dim ft As BaseFont = BaseFont.CreateFont(BaseFont.TIMES_ROMAN, BaseFont.CP1250, BaseFont.EMBEDDED)
        Dim mf As New iTextSharp.text.Font(ft, 12, iTextSharp.text.Font.NORMAL, iTextSharp.text.Color.BLACK)
        Dim doc As Document = New Document(PageSize.A4, 70, 30, 40, 40)
        Dim output As MemoryStream = New MemoryStream
        Dim wr As PdfWriter = PdfWriter.GetInstance(doc, output)
        doc.Open()
        Dim tbl As New PdfPTable(7)  'set 7 columns in table
        tbl.WidthPercentage = 100
        Dim cp() As Integer = {15, 15, 15, 15, 15, 15, 10}
        tbl.SetWidths(cp)
        'write header
        For x = 0 To gvUsers.Columns.Count - 1
            Dim cell As New PdfPCell(New Phrase(gvUsers.Columns(x).HeaderText.ToString, mf))
            cell.HorizontalAlignment = Element.ALIGN_CENTER
            cell.VerticalAlignment = Element.ALIGN_MIDDLE
            cell.FixedHeight = 45.0F
            cell.BackgroundColor = New Color(System.Drawing.ColorTranslator.FromHtml("#a52a2a"))
            tbl.AddCell(cell)
        Next
        mf = New iTextSharp.text.Font(ft, 8, iTextSharp.text.Font.NORMAL, iTextSharp.text.Color.BLACK)
        'write content of table
        For x = 0 To gvUsers.Rows.Count - 1
            If gvUsers.Rows(x).RowType = DataControlRowType.DataRow Then
                For y = 0 To gvUsers.Columns.Count - 1
                    Dim cellText = Server.HtmlDecode(gvUsers.Rows(x).Cells(y).Text)
                    Dim cell As New PdfPCell(New Phrase(cellText, mf))
                    cell.HorizontalAlignment = Element.ALIGN_CENTER
                    cell.VerticalAlignment = Element.ALIGN_MIDDLE
                    cell.FixedHeight = 25.0F
                    tbl.AddCell(cell)
                Next
            End If
        Next
        doc.Add(tbl)
        doc.Close()
        Response.ContentType = "application/pdf"
        Response.AddHeader("Content-Disposition", "attachment;filename=test.pdf")
        Response.BinaryWrite(output.ToArray())
    End Sub