2012-03-12 177 views
1

嗨,我想通过使用asp.net应用程序获取当前页面源代码。我发现了一段代码将HTML转换为PDF,但为了将我的页面转换为PDF,我需要获取页面的HTML代码。我怎样才能得到这些字符串?我简单的代码是这样的:如何从asp.net获取当前页面源代码页面

 string sPathToWritePdfTo = Server.MapPath("") + "/pdf_dosya_adi.pdf"; 

     System.Text.StringBuilder sbHtml = new System.Text.StringBuilder(); 
     sbHtml.Append("<html>"); 
     sbHtml.Append("<body>"); 
     sbHtml.Append("<font size='14'>HTML den PDF çevirme Test</font>"); 
     sbHtml.Append("<br />"); 
     sbHtml.Append("Body kısmında yazacak yazı"); 
     sbHtml.Append("</body>"); 
     sbHtml.Append("</html>"); 

     using (System.IO.Stream stream = new System.IO.FileStream 

     (sPathToWritePdfTo, System.IO.FileMode.OpenOrCreate)) 
     { 
      Pdfizer.HtmlToPdfConverter htmlToPdf = new Pdfizer.HtmlToPdfConverter(); 
      htmlToPdf.Open(stream); 
      htmlToPdf.Run(sbHtml.ToString()); 
      htmlToPdf.Close(); 
     } 
     HttpContext.Current.Response.Clear(); 
     HttpContext.Current.Response.AddHeader("content-disposition", string.Format("attachment; filename={0}", "friendlypdfname.pdf")); 
     HttpContext.Current.Response.ContentType = "application/pdf"; 

     HttpContext.Current.Response.WriteFile(sPathToWritePdfTo); 
     HttpContext.Current.Response.End(); 

如果我能得到HTML代码关闭我的asp.net页面,我把我的网页上的所有行成 sbHtml.Append(“”); 代码通过使用for循环,这将解决我的问题在我看来。

回答

3

一种可能性是使用Web客户端发送一个HTTP请求到指定的网页并获取生成的HTML:

using (var client = new WebClient()) 
{ 
    string html = client.DownloadString("http://example.com/somepage.aspx"); 
} 

这种方法的缺点是它发送一个额外的HTTP请求。

另一种可能性是直接呈现在Web窗体转换成字符串:

using (var writer = new StringWriter()) 
{ 
    Server.Execute("SomePage.aspx", writer); 
    string html = writer.GetStringBuilder().ToString(); 
} 
+0

这可以为mycurrent页面吗?这是工作本地主机 – EmreAltun 2012-03-12 13:43:15

+0

@EmreAltun,如果你想使用WebClient你需要指定网页的完整地址。 – 2012-03-12 13:45:05

+0

我使用这段代码,但它总是再次调用我的当前页面,并导致循环。 – EmreAltun 2012-03-12 13:57:00

0

您可以创建一个隐藏字段,当前的HTML添加到它,并在一个ASYC回传能够从内检索事件。假设您正在渲染一个页面,可能会进行编辑或更改数据,然后单击一个按钮以下载PDF。

//隐藏的输入字段

<input type="hidden" runat="server" id="hdn_container" /> 

//按钮与客户端事件和服务器端事件。应该包装在UpdatePanel中。

<asp:Button ID="btnDownload" runat="server" OnClientClick="refreshHtml();" OnClick="btnDownloadButton_Click" Text="Download Pdf"></asp:Button> 

页面底部//脚本标签
<script language="javascript" type="text/javascript"> 
     function refreshHtml() { 
      document.getElementById('<%= hdn_container.ClientID %>').value = document.head.innerHTML + document.body.innerHTML; 
     } 
</script> 

//然后在C#中,你可以从隐藏字段的网页的HTML。

hdn_container.Value 

确保为脚本管理器设置了适当的AsyncPostBackTimeout。并在你的webconfig,一个适当的maxRequestLength和executionTimeout。