2014-01-09 51 views
0

我在尝试将aspx页面导出为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

您是否已将触发器添加到您的aspx文件中。如果没有请加触发器为一个例子

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

,我相信你正在使用您的UpdatePanel内页 – Damith

+0

你的意思是上面加后,我宣布我的aspx文件按钮行。不,我没有使用任何更新面板 –

+0

我应该使用更新面板? –