2012-03-12 187 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。