cocoa
cocoa

Reputation: 3921

UserControl Export GridView to PDF

I have a UserControl and I'm trying to export my GridView table to a PDF. I am able to do a CSV file just fine, but I get errors when trying to do a PDF. (I am using iTextSharp Library) This is the error I'm getting:

"Control 'DoNotAddList_1_GridView1' of type 'GridView' must be placed inside a form tag with runat=server."

I have a form tag in my html, and I tried adding it in the ascx file but nothing works. I've found many people getting this error and most everyone suggested adding this to code to the ascx.cs file:

public override void VerifyRenderingInServerForm(Control control) {     }

But that gives me this error "no suitable method found to override..."

I don't know what to do. I haven't been able to find a solution. Please Help!!

using System;
using System.Data;
using System.Configuration;
using System.Collections;
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;
using System.IO;
using iTextSharp.text;
using iTextSharp.text.pdf;
using iTextSharp.text.html;
using iTextSharp.text.html.simpleparser;

public partial class UserControls_DoNotAddListControl : System.Web.UI.UserControl
{
protected void PDF_Click(object sender, EventArgs e)
{   
    Response.ContentType = "application/pdf";
    Response.AddHeader("content-disposition",
     "attachment;filename=GridViewExport.pdf");
    Response.Cache.SetCacheability(HttpCacheability.NoCache);
    StringWriter sw = new StringWriter();
    HtmlTextWriter hw = new HtmlTextWriter(sw);
    GridView1.AllowPaging = false;
    GridView1.DataBind();
    GridView1.RenderControl(hw);
    StringReader sr = new StringReader(sw.ToString());
    Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 10f, 0f);
    HTMLWorker htmlparser = new HTMLWorker(pdfDoc);
    PdfWriter.GetInstance(pdfDoc, Response.OutputStream);
    pdfDoc.Open();
    htmlparser.Parse(sr);
    pdfDoc.Close();
    Response.Write(pdfDoc);
    Response.End();
}
protected void CSV_Click(object sender, EventArgs e)
{
     Response.ClearContent();
    Response.AddHeader("content-disposition", string.Format("attachment; filename={0}", "BloombergDaily.csv"));
    Response.ContentType = "application/text";
    GridView1.AllowPaging = false;
    GridView1.DataBind();
    StringBuilder strbldr = new StringBuilder();
    for (int i = 0; i < GridView1.Columns.Count; i++)
    {
        strbldr.Append(GridView1.Columns[i].HeaderText + ',');
    }
    strbldr.Append("\n");
    for (int j = 0; j < GridView1.Rows.Count; j++)
    {
        for (int k = 0; k < GridView1.Columns.Count; k++)
        {
            strbldr.Append(GridView1.Rows[j].Cells[k].Text + ',');
        }
        strbldr.Append("\n");
    }
    Response.Write(strbldr.ToString());
    Response.End();
}
}

Here's what I have in the aspx file:

<form id="form1" runat="server" action="/">          
        <div id="donotadd" class="tableWrapper">
            <div id="tabs1">
                <p>
                    <div id="tabs-1" >                           
                        <div id="DoNotAddListMacro" class="dataTable table_Center">
                        <umbraco:Macro ID="Macro1" Alias="DoNotAddListControl" runat="server"></umbraco:Macro>
                        </div>                                                                          
                    </div>   
                </p>
            </div>    
        </div>            
    </form> 

Upvotes: 2

Views: 3585

Answers (4)

cocoa
cocoa

Reputation: 3921

Here's the solution I found:

protected void BtnPDF_Click(object sender, EventArgs e)
    {
        GridView gv = new GridView();
        gv.DataSource = SqlDataSource1;
        gv.DataBind();
        StringWriter sw = new StringWriter();
        HtmlTextWriter htw = new HtmlTextWriter(sw);

        gv.RenderControl(htw);

        var mem = new MemoryStream();

        Document document = new Document(PageSize.LETTER, 50, 50, 50, 50);
        PdfWriter.GetInstance(document,mem);

        document.Open();

        iTextSharp.text.html.simpleparser.HTMLWorker hw = new iTextSharp.text.html.simpleparser.HTMLWorker(document);
        hw.Parse(new StringReader(sw.ToString()));
        document.Close();

        Response.ClearContent();
        Response.ClearHeaders();
        Response.ContentType = "application/pdf";
        Response.AddHeader("Content-Disposition", "attachment; filename=" + DateTime.Now);

        Response.BinaryWrite(mem.ToArray());
        Response.End();
        Response.Flush();
        Response.Clear();
    }

Upvotes: 2

Pramesh
Pramesh

Reputation: 1244

I ran into same situation a while ago. I see you have already overridden following method. But did you put that method in your usercontrol? That will give you "no suitable method found to override". This method needs to be overridden in your .aspx.cs file where you will drop the usercontrol.

Hers's code behind for UserControl that has ExportPdf() Method

 protected void btnExportPdf_Click(object sender, EventArgs e)
    {
        System.Threading.Thread.Sleep(1000);
        ExportPdf();
    }

    protected void ExportPdf()
    {
        using (StringWriter sw = new StringWriter())
        {
            using (HtmlTextWriter hw = new HtmlTextWriter(sw))
            {
                //To export all pages
                gvCharges.AllowPaging = false;
                this.BindRepeater();

                gvCharges.RenderControl(hw);
                StringReader sr = new StringReader(sw.ToString());
                Document pdfDoc = new Document(PageSize.A2, 10f, 10f, 10f, 0f);
                HTMLWorker htmlparser = new HTMLWorker(pdfDoc);
                PdfWriter.GetInstance(pdfDoc, Response.OutputStream);
                pdfDoc.Open();
                htmlparser.Parse(sr);
                pdfDoc.Close();

                Response.ContentType = "application/pdf";
                Response.AddHeader("content-disposition", "attachment;filename=GridViewExport.pdf");
                Response.Cache.SetCacheability(HttpCacheability.NoCache);
                Response.Write(pdfDoc);
                Response.End();
            }
        }
    }

Here's the source for .ascx file

<asp:Button ID="btnExportPdf" runat="server" Text="Export to pdf" Visible = "false" 
    onclick="btnExportPdf_Click" CssClass="btn btn-primary" />

Here's the source for .aspx where i dropped the usercontrol to

 <div class="form-section-body">
     <table style="width: 100%">
         <tr>
             <td colspan="2" style="padding: 20px 5px 5px 5px;">
                 <uc2:PosTrans ID="PosTrans1" runat="server" />
             </td>
         </tr>
     </table>
 </div>

And here's the code behind .aspx.cs where i dropped the usercontrol to

 namespace DFM.Dashboard
{
    public partial class Dashboard : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        public override void VerifyRenderingInServerForm(Control control)
        {
            /* Verifies that the control is rendered */
        }
    }

}

Upvotes: 1

santosh singh
santosh singh

Reputation: 28692

try this.Replace control type accordingly

public override void VerifyRenderingInServerForm(Control control)
     {
         Macro grid = control as Macro ;
         if (grid != null && grid.ID == "Macro1")
             return;
         else
             base.VerifyRenderingInServerForm(control);

     }

Update Check out following link for complete example

Export Html to Pdf using iTextSharp(GridView)

Upvotes: 0

mason
mason

Reputation: 32728

I know this probably is coming out of left field, but did you place your user control inside a form tag with the runat="server" attribute?

<form runat="server">
<myprefix:MyControl runat="server" />
</form>

Upvotes: 0

Related Questions