-2

I can successfully create/generate PDF file without any issue. But when I try to download it after generation, the execution gets redirected to,

void Application_Error(object sender, EventArgs e)
{
    // Code that runs when an unhandled error occurs
}

On button's click event, I create PDF file which works as expected as below.

using System.Data;
using iTextSharp.text;
using iTextSharp.text.html.simpleparser;
using iTextSharp.text.pdf;
using System.Net;

protected void Button2_Click(object sender, EventArgs e)
{
    try
    {
        string htmlContent = "<div> PDF Code </div>"; // you html code (for example table from your page)
        Document document = new Document();
        string FileName = Guid.NewGuid().ToString();
        PdfWriter.GetInstance(document, new FileStream("C:\\...\\...\\PDF\\" + FileName + ".pdf", FileMode.Create));
        document.Open();

        HTMLWorker worker = new HTMLWorker(document);
        worker.Parse(new StringReader(htmlContent));

        document.Close();

         //To download same PDF I write below code

        Response.Clear();
        string pdfPath = Server.MapPath(@"~\PDF\" + FileName + ".pdf");
        WebClient client = new WebClient();
        Byte[] buffer = client.DownloadData(pdfPath);
        Response.ContentType = "application/pdf";
        Response.AddHeader("content-length", buffer.Length.ToString());
        Response.BinaryWrite(buffer);
        Response.Flush();
        HttpContext.Current.ApplicationInstance.CompleteRequest();
        ////Response.End();

    }
    catch (Exception ex)
    {
        Response.Write(ex.Message.ToString());
    }
}

This code doesn't throw any exception rather it gets redirected to above mention method. Please help.

What I want is with button's click event, I want to generate PDF and download the same. Tried so many things but getting no success.

M. Schena
  • 2,039
  • 1
  • 21
  • 29
nyks
  • 2,103
  • 6
  • 14
  • 17

3 Answers3

0

[...]The CompleteRequest() method does not end execution when it's called. So if that's really what you want to do then Response.Redirect(string) would be the way to go.

CompleteRequest() simply bypasses the Response.End() method, which is what generates the ThreadAbortException you mentioned, but crucially CompleteRequest() flushes the response buffer. This means the HTTP 302 redirect response is sent to the browser at the line where you call CompleteRequest(), which gives you a chance to do operations that don't affect the response after it's been sent to the user.[...]

Source

Community
  • 1
  • 1
diiN__________
  • 7,393
  • 6
  • 42
  • 69
  • Tried your suggestion. But then it doesn't download PDF file. Don't know why. – nyks Feb 02 '16 at 10:16
  • Did you use `Response.End()` instead of `CompleteRequest()`? – diiN__________ Feb 02 '16 at 10:24
  • Yes tried. Look I have posted my answer. it now generates PDF but still it directly opens it to the browser. I want to just download it so user himself will open file. Any way? – nyks Feb 02 '16 at 10:30
0

I'm able to solve my problem lately by adding following code to page_load() event,

protected void Page_Load(object sender, EventArgs e)
        {
            ScriptManager scriptManager = ScriptManager.GetCurrent(this.Page);
            scriptManager.RegisterPostBackControl(this.Button2);

             //where button2 is the button by which pdf is generated and post back happens.          

        }

Below new code is working absolutely fine.

protected void Button2_Click(object sender, EventArgs e)
        {
            try
            {
                string htmlContent = "<div> PDF Code </div>"; // you html code (for example table from your page)
                Document document = new Document();
                string FileName = Guid.NewGuid().ToString();
                PdfWriter.GetInstance(document, new FileStream("C:\\...\\...\\PDF\\" + FileName + ".pdf", FileMode.Create));
                document.Open();
                HTMLWorker worker = new HTMLWorker(document);
                worker.Parse(new StringReader(htmlContent));
                document.Close();
                Response.ContentType = "application/pdf";
                Response.AppendHeader("Content-Disposition", "attachment; filename=" + FileName + ".pdf");
                Response.TransmitFile(Server.MapPath(@"~\PDF\" + FileName + ".pdf"));
                Response.End();
            }
            catch (Exception ex)
            {
                Response.Write(ex.Message.ToString());
            }
        }
nyks
  • 2,103
  • 6
  • 14
  • 17
-1

add this code in your click event

Response.ContentType = "application/pdf";
Response.AddHeader("content-disposition", "attachment;filename=Panel.pdf");
Response.Cache.SetCacheability(HttpCacheability.NoCache);
StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);
pnlPerson.RenderControl(hw);
StringReader sr = new StringReader(sw.ToString());
Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 100f, 0f);
HTMLWorker htmlparser = new HTMLWorker(pdfDoc);
PdfWriter.GetInstance(pdfDoc, Response.OutputStream);
pdfDoc.Open();
htmlparser.Parse(sr);
pdfDoc.Close();
Response.Write(pdfDoc);
Response.End();
Naimish Mungara
  • 213
  • 1
  • 4
  • 14