views:

1878

answers:

2

I am exporting the HTML Content to PDF.

System.IO.StringWriter sWriter = new System.IO.StringWriter();

    System.Web.UI.HtmlTextWriter htmlWriter = new HtmlTextWriter(sWriter);

    Response.Buffer = true;
    FormId.RenderControl(htmlWriter);
    Response.ContentType = "application/pdf";
    // Added appropriate headers
    Response.AddHeader("Content-Disposition", "inline; filename=XXX.pdf");
    Response.AddHeader("Content-Length", htmlWriter.ToString().Length.ToString());
    Response.Output.Write(sWriter.ToString());

    Response.Flush();
    Response.Close();

FormId is my Div past of the content..

I am getting the error as "File does not begin with '%PDF-'"

I have included Response.clear(); The output is not coming

+1  A: 

You're rendering out the html (div as you said) before the pdf in the output stream, so the two are combined. That's causing any app looking at the output to interpret it as a corrupted file. I'd try removing the first two lines:

Response.Buffer = true;
FormId.RenderControl(htmlWriter);

If that doesn't solve the issue, add a Response.Clear() call before everything.

This is all assuming sWriter contains the PDF at the beginning of this code block -- if not, a little more context might be helpful.

Some advice: if at all possible, move this out of the page to a .ashx or other IHttpHandler.

Chris Hynes
Good advice, the overhead for an http handler is much lower than for a page handler.
Chris Ballance
A: 

Do a Response.Clear() before starting to stream your output.

Dave Markle