2012-03-28 95 views
0

我正在使用jquery ajax從webservice調用函數。如何使用webservice創建pdf

在這個函數中,我使用itextsharp工具創建一個pdf文件。 我希望我創建的PDF文件在返回時應該在瀏覽器中打開。

誰能幫助我應該是什麼我對於

下面的返回類型是我使用的Web服務代碼

public void GeneratePDf(string ID) { 
      string attachment = "attachment; filename=" + ID + ".pdf"; 
      HttpContext.Current.Response.ClearContent(); 
      HttpContext.Current.Response.AddHeader("content-disposition", attachment); 
      HttpContext.Current.Response.ContentType = "application/pdf"; 
      StringWriter stw = new StringWriter(); 
      HtmlTextWriter htextw = new HtmlTextWriter(stw); 
      htextw.AddStyleAttribute("font-size", "12px"); 
      htextw.AddStyleAttribute("color", "Black"); 
      Page pg = new Page(); 
      HtmlForm frm = new HtmlForm(); 
      pg.EnableEventValidation = false; 

      pg.RenderControl(htextw); 
      Document document = new Document(); 

      document = new Document(PageSize.A4, 10, 10, 0, 0); 
      PdfWriter.GetInstance(document, HttpContext.Current.Response.OutputStream); 
      document.Open(); 
      Font verdana = FontFactory.GetFont("Verdana", 10, Font.BOLD, new CMYKColor(75, 68, 67, 90)); 
      PdfPCell blank1 = new PdfPCell(new Phrase("Hello ", verdana)); 
      document.Add(blank1); 
      //document.Add(tablegrid); 
      StringReader str = new StringReader(stw.ToString()); 
      HTMLWorker htmlworker = new HTMLWorker(document); 
      htmlworker.Parse(str); 

      document.Close(); 
      HttpContext.Current.Response.Write(document); 
} 

誰能告訴我什麼,我做錯了

回答

0

的簡短的回答是,「不要爲此使用AJAX」,你正在創造不必要的複雜性。相反,只需通過瀏覽器進行正常的GET/POST請求即可。如果你願意,你仍然可以使用JavaScript,但重要的部分是你有瀏覽器發出請求,以便它可以收到響應。

長的答案是...

Web服務器響應請求從Web瀏覽器和事情發生,就像你希望他們(通常)。 Web瀏覽器有一個他們知道的內容類型列表,並使用這個列表來有時解析服務器的響應,有時將它交給第三方應用程序。一旦你開始搞亂AJAX和其他類似的技術,你打破了這種模式,並說你想處理處理而不是瀏覽器。瀏覽器會代理你的請求和服務器的響應,否則它不會做任何事情,除非你告訴它。這對於類似字符串的事情非常適用,但在處理二進制數據時會變得複雜得多。