Export to PDF from Gridview with ITextSharp

做~自己de王妃 提交于 2019-12-25 04:36:33

问题


I use to generate a PDF file from a gridview using iTextSharp library.

This is my simple GridView in aspx page:

        <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>

I have one problem because in exported pdf file I don't find the last column on GV "Annotation".

I don't have error but the header of column "Annotation" and your value they are not exported.

My code below, what's wrong?

Anybody know how can I do that?

Thank you in advance.

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);
                        }
                    }
                }

Edit # 1

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

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

Edit # 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:


There is problem :

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

Like You can see, You set 6 columns for PdfPTable, but Your GridView have 7 columns. And, sum of all widths are more then 100%.

Try :

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

Or change width of each column how You wish. btw. columns width are in single, so You can use width values like 14.5 etc.

Update : (sorry, it's in vb, but You can convert to 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 are defined for table. Do You do that?

btw. Why You put table.SetWidths(new int[] { 15, 15, 15, 15, 15, 15, 10 }); in for...next block? Must put before, and out of, for.

Update #2 :

There is complete code in vb and work fine :

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


来源:https://stackoverflow.com/questions/31449532/export-to-pdf-from-gridview-with-itextsharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!