Federico Sammarco
Federico Sammarco

Reputation: 80

How to print a GridView on a PDF?

I have a Gridview that I should print on a PDF. I am using iTextSharp dlls and references, but I'm kinda stuck. I open the pdf and it is blank, like the info from the grid is not copying correctly. I am probably missing a step in databinding with the gridview. Anyone can help? Here's ASP.NET code:

   <asp:GridView ID="grdContact" runat="server" DataKeyNames="id_riga"
        OnRowCancelingEdit="grdContact_RowCancelingEdit"
        OnRowDataBound="grdContact_RowDataBound"
        OnRowEditing="grdContact_RowEditing"
        OnRowUpdating="grdContact_RowUpdating"
        ShowFooter="True"
        OnRowCommand="grdContact_RowCommand"
        OnRowDeleting="grdContact_RowDeleting"
        BackColor="#DEBA84"
        BorderColor="#DEBA84"
        BorderStyle="None"
        BorderWidth="1px"
        AutoGenerateColumns="False"
        CellSpacing="2"
        CellPadding="4"
        Width="1195px"
        ForeColor="#333333" GridLines="Horizontal">


        <EditRowStyle BackColor="#2461BF" />
        <FooterStyle BackColor="#507CD1" ForeColor="White" Font-Bold="True" />
        <HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
        <PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
        <RowStyle BackColor="#EFF3FB" />
        <SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
        <SortedAscendingCellStyle BackColor="#F5F7FB" />
        <SortedAscendingHeaderStyle BackColor="#6D95E1" />
        <SortedDescendingCellStyle BackColor="#E9EBEF" />
        <SortedDescendingHeaderStyle BackColor="#4870BE" />

        <Columns>

            <asp:TemplateField HeaderText="Id_Riga" HeaderStyle-HorizontalAlign="Left">
                <EditItemTemplate>
                    <asp:Label ID="lblId_Riga" runat="server" Text='<%# Bind("id_riga") %>'></asp:Label>
                </EditItemTemplate>
                <FooterTemplate>
                    <asp:Label ID="lblNewId_Riga" runat="server"></asp:Label>
                </FooterTemplate>
                <ItemTemplate>
                    <asp:Label ID="lblId_Riga" runat="server" Text='<%# Bind("id_riga") %>'></asp:Label>
                </ItemTemplate>

                <HeaderStyle HorizontalAlign="Left"></HeaderStyle>
            </asp:TemplateField>

            <asp:TemplateField HeaderText="Num_Riga" HeaderStyle-HorizontalAlign="Left">
                <EditItemTemplate>
                    <asp:Label ID="lblnumero_posizione" runat="server" Text='<%# Bind("numero_posizione") %>'></asp:Label>
                </EditItemTemplate>
                <FooterTemplate>
                    <asp:Label ID="lblNewnumero_posizione" runat="server"></asp:Label>
                </FooterTemplate>
                <ItemTemplate>
                    <asp:Label ID="lblnumero_posizione" runat="server" Text='<%# Bind("numero_posizione") %>'></asp:Label>
                </ItemTemplate>

                <HeaderStyle HorizontalAlign="Left"></HeaderStyle>
            </asp:TemplateField>


            <asp:TemplateField HeaderText="Quantità" HeaderStyle-HorizontalAlign="Left">
                <EditItemTemplate>
                    <asp:TextBox ID="txtQuantita" runat="server" Text='<%# Bind("quantita") %>'></asp:TextBox>
                </EditItemTemplate>
                <FooterTemplate>
                    <asp:TextBox ID="txtNewQuantita" runat="server"></asp:TextBox>
                </FooterTemplate>
                <ItemTemplate>
                    <asp:Label ID="lblQuantita" runat="server" Text='<%# Bind("quantita") %>'></asp:Label>
                </ItemTemplate>

                <HeaderStyle HorizontalAlign="Left"></HeaderStyle>
            </asp:TemplateField>

            <asp:TemplateField HeaderText="Unità Di Misura" HeaderStyle-HorizontalAlign="Left">
                <EditItemTemplate>
                    <asp:TextBox ID="txtUnita_Misura" runat="server" Text='<%# Bind("Unita_Misura") %>'></asp:TextBox>
                </EditItemTemplate>
                <FooterTemplate>
                    <asp:TextBox ID="txtNewUnita_Misura" runat="server"></asp:TextBox>
                </FooterTemplate>
                <ItemTemplate>
                    <asp:Label ID="lblUnita_Misura" runat="server" Text='<%# Bind("Unita_Misura") %>'></asp:Label>
                </ItemTemplate>

                <HeaderStyle HorizontalAlign="Left"></HeaderStyle>
            </asp:TemplateField>

            <asp:TemplateField HeaderText="Descrizione" HeaderStyle-HorizontalAlign="Left">
                <EditItemTemplate>
                    <asp:TextBox ID="txtDescrizione" runat="server" Text='<%# Bind("Descrizione") %>'></asp:TextBox>
                </EditItemTemplate>
                <FooterTemplate>
                    <asp:TextBox ID="txtNewDescrizione" runat="server"></asp:TextBox>
                </FooterTemplate>
                <ItemTemplate>
                    <asp:Label ID="lblDescrizione" runat="server" Text='<%# Bind("Descrizione") %>'></asp:Label>
                </ItemTemplate>

                <HeaderStyle HorizontalAlign="Left"></HeaderStyle>
            </asp:TemplateField>

            <asp:TemplateField HeaderText="Prezzo Unitario" HeaderStyle-HorizontalAlign="Left">
                <EditItemTemplate>
                    <asp:TextBox ID="txtPrezzo_Unitario" runat="server" Text='<%# Bind("valore_unitario") %>'></asp:TextBox>
                </EditItemTemplate>
                <FooterTemplate>
                    <asp:TextBox ID="txtNewPrezzo_Unitario" runat="server"></asp:TextBox>
                </FooterTemplate>
                <ItemTemplate>
                    <asp:Label ID="lblPrezzo_Unitario" runat="server" Text='<%# Bind("valore_unitario") %>'></asp:Label>
                </ItemTemplate>

                <HeaderStyle HorizontalAlign="Left"></HeaderStyle>
            </asp:TemplateField>

            <asp:TemplateField HeaderText="Iva" HeaderStyle-HorizontalAlign="Left">
                <EditItemTemplate>
                    <asp:TextBox ID="txtIva" runat="server" Text='<%# Bind("iva_percento") %>'></asp:TextBox>
                </EditItemTemplate>
                <FooterTemplate>
                    <asp:TextBox ID="txtNewIva" runat="server"></asp:TextBox>
                </FooterTemplate>
                <ItemTemplate>
                    <asp:Label ID="lblIva" runat="server" Text='<%# Bind("iva_percento") %>'></asp:Label>
                </ItemTemplate>

                <HeaderStyle HorizontalAlign="Left"></HeaderStyle>
            </asp:TemplateField>

            <asp:TemplateField HeaderText="Modifica" ShowHeader="False" HeaderStyle-HorizontalAlign="Left">
                <EditItemTemplate>
                    <asp:LinkButton ID="lbkUpdate" runat="server" CausesValidation="False" CommandName="Update" Text="Aggiorna"></asp:LinkButton>
                    <asp:LinkButton ID="lnkCancel" runat="server" CausesValidation="False" CommandName="Cancel" Text="Cancella"></asp:LinkButton>
                </EditItemTemplate>
                <FooterTemplate>
                    <asp:LinkButton ID="lnkAdd" runat="server" CausesValidation="False" CommandName="Insert" Text="Inserisci"></asp:LinkButton>
                </FooterTemplate>
                <ItemTemplate>
                    <asp:LinkButton ID="lnkEdit" runat="server" CausesValidation="False" CommandName="Edit" Text="Modifica"></asp:LinkButton>
                </ItemTemplate>

                <HeaderStyle HorizontalAlign="Left"></HeaderStyle>
            </asp:TemplateField>

            <asp:CommandField HeaderText="Cancella" ShowDeleteButton="True" ShowHeader="True" />


        </Columns>
    </asp:GridView>

And here's code behind:

protected void creaPDF()
{
    var document = new Document(PageSize.A4, 50, 50, 25, 25);
    var output = new MemoryStream();
    var writer = PdfWriter.GetInstance(document, output);
    document.Open();

    var titleFont = FontFactory.GetFont("Arial", 18, Font.BOLD);
    var subTitleFont = FontFactory.GetFont("Arial", 14, Font.BOLD);
    var boldTableFont = FontFactory.GetFont("Arial", 12, Font.BOLD);
    var endingMessageFont = FontFactory.GetFont("Arial", 10, Font.ITALIC);
    var bodyFont = FontFactory.GetFont("Arial", 12, Font.NORMAL);
    var orderInfoTable = new PdfPTable(2);
    orderInfoTable.HorizontalAlignment = 0;
    orderInfoTable.SpacingBefore = 10;
    orderInfoTable.SpacingAfter = 10;
    orderInfoTable.DefaultCell.Border = 0;
    orderInfoTable.SetWidths(new int[] { 1, 4 });


    orderInfoTable.AddCell(new Phrase("Tipo di documento:", boldTableFont));
    orderInfoTable.AddCell(txtPrenum.Text);
    orderInfoTable.AddCell(new Phrase("Cognome:", boldTableFont));            
    orderInfoTable.AddCell(txtCognome.Text);
    orderInfoTable.AddCell(new Phrase("Nome:", boldTableFont));
    orderInfoTable.AddCell(txtNome.Text);
    orderInfoTable.AddCell(new Phrase("Indirizzo:", boldTableFont));
    orderInfoTable.AddCell(txtIndirizzo.Text);            
    orderInfoTable.AddCell(new Phrase("Prezzo totale:", boldTableFont));



    document.Add(orderInfoTable);
    document.Close();

    Response.ContentType = "application/pdf";
    Response.AddHeader("Content-Disposition", string.Format("attachment;filename=Fattura-{0}.pdf", txtPrezzoTotale.Text));
    Response.BinaryWrite(output.ToArray()); 
}

Upvotes: 1

Views: 2094

Answers (2)

Federico Sammarco
Federico Sammarco

Reputation: 80

I had this totally wrong. I'm advicing not to use iTextSharp. Visual Studio has some brilliant objects included: they are Report Viewer and can be referenced at "using Microsoft.Reporting.WebForms;" First of all a report has to be created, then it has to be bound to a data source. The data source has to be displayed on a data set. Piece of cake!

Upvotes: 1

Cristina Alboni
Cristina Alboni

Reputation: 1022

This is the code that handles the export of the grid view, it's from the following article: http://highoncoding.com/Articles/483_Exporting_GridView_to_PDF_Document.aspx

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

But I don't see this line in your code, it's the code that renders the grid into a HtmlTextWriter object.

grdContact.RenderControl(htw);

Upvotes: 0

Related Questions