Print asp.net page as PDF

1.2k views Asked by At

I would like to print a page as PDF. But the thing is that before printing, I want to expand all the controls (GridView, Treeview...).

I found somes solutions using Page.RenderControl (or Control.RenderControl) but i have some error saying "A page can have only one server-side Form tag.". I understand the error (that only one Form must be added). but I would have thought RenderControl would write in the new Writer (and not the current one).

    Dim stringWriter As New StringWriter()
    Dim htmlWriter As New HtmlTextWriter(stringWriter)
    Me.Page.RenderControl(htmlWriter)

To expand controls, I have to change properties and then, render the page. Once rendered in a PDF, I would like to let the page load as normal. Response.End stop loading and the page is blank.

Is there an (good) alternative to take page content, change content (ex: grid.AllowPaging = False) and send him in a stream?

1

There are 1 answers

1
ematica On

Try with HtmlForm instead of Me.Page.RenderControl

        Response.ContentType = "application/pdf";
        Response.AddHeader("content-disposition", "attachment;filename=this.pdf");
        Response.Cache.SetCacheability(HttpCacheability.NoCache);
        StringWriter sw = new StringWriter();
        HtmlTextWriter hw = new HtmlTextWriter(sw);
        HtmlForm frm = new HtmlForm();
        GridView1.AllowPaging = false;
        GridView1.Parent.Controls.Add(frm);
        frm.Controls.Add(GridView1);
        frm.RenderControl(hw);
        StringReader sr = new StringReader(sw.ToString());
        Document PDFdoc = new Document(PageSize.A4, 10.0F, 10.0F, 10.0F, 0.0F);
        iTextSharp.text.html.simpleparser.HTMLWorker htmlparser =   new iTextSharp.text.html.simpleparser.HTMLWorker(PDFdoc);
        PdfWriter.GetInstance(PDFdoc, Response.OutputStream);
        PDFdoc.Open();
        htmlparser.Parse(sr);
        PDFdoc.Close();
        Response.Write(PDFdoc);
        Response.End();