将aspx网页导出为pdf并下载

时间:2014-01-09 02:06:33

标签: c# asp.net pdf

我在尝试将aspx页面导出为pdf并下载时遇到了一些问题。这是代码:

    protected void Button1_Click(object sender, EventArgs e)
    {
        string url = Request.Url.AbsoluteUri;
        using (StreamReader reader = new StreamReader(Server.MapPath(url)))
        {
            String line = reader.ReadToEnd();
            Text2PDF(line);
        }
    }

    protected void Text2PDF(string PDFText)
    {
        //HttpContext context = HttpContext.Current;
        StringReader reader = new StringReader(PDFText);

        //Create PDF document 
        Document document = new Document(PageSize.A4);
        HTMLWorker parser = new HTMLWorker(document);

        string PDF_FileName = Server.MapPath("MyFirstPdf.pdf");
        PdfWriter.GetInstance(document, new FileStream(PDF_FileName, FileMode.Create));
        document.Open();

        try
        {
            parser.Parse(reader);
        }
        catch (Exception ex)
        {
            //Display parser errors in PDF. 
            Paragraph paragraph = new Paragraph("Error!" + ex.Message);
            Chunk text = paragraph.Chunks[0] as Chunk;
            if (text != null)
            {
                text.Font.Color = BaseColor.RED;
            }
            document.Add(paragraph);
        }
        finally
        {
            document.Close();
            DownLoadPdf(PDF_FileName);
        }
    }
    private void DownLoadPdf(string PDF_FileName)
    {
        WebClient client = new WebClient();
        Byte[] buffer = client.DownloadData(PDF_FileName);
        Response.ContentType = "application/pdf";
        Response.AddHeader("content-length", buffer.Length.ToString());
        Response.BinaryWrite(buffer);
    }

然而,当我点击按钮时,没有任何反应。浏览器也不会提示我下载。我想知道为什么。提前谢谢。

1 个答案:

答案 0 :(得分:0)

您是否将触发器添加到了aspx文件中?如果没有,请添加触发器作为示例

<Triggers>
        <asp:PostBackTrigger ControlID="Button1" />
</Triggers>