使用iTextSharp问题创建和下载(HTML to)PDF

时间:2016-02-02 09:57:42

标签: c# asp.net download pdf-generation itextsharp

我可以毫无问题地成功创建/生成PDF文件。 但是当我尝试在生成后下载它时,执行被重定向到,

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

在按钮的点击事件中,我创建了PDF文件,其工作方式如下所示。

{{1}}

此代码不会抛出任何异常,而是将其重定向到上面提到的方法。请帮忙。

我想要的是按钮的点击事件,我想生成PDF并下载相同的内容。尝试了很多事情但没有成功。

3 个答案:

答案 0 :(得分:0)

  

[...] CompleteRequest()方法在调用时不会结束执行。所以,如果你真的想做什么,那么Response.Redirect(字符串)就是你的选择。

     

CompleteRequest()只是绕过Response.End()方法,该方法生成你提到的ThreadAbortException,但最重要的是CompleteRequest()刷新响应缓冲区。这意味着HTTP 302重定向响应被发送到您调用CompleteRequest()的行的浏览器,这使您有机会在响应发送给用户后执行不影响响应的操作。[...]

Source

答案 1 :(得分:0)

我最近可以通过向page_load()事件

添加以下代码来解决我的问题
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.          

        }

新代码以下工作正常。

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

答案 2 :(得分:0)

在点击事件中添加此代码

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