2010-11-03 45 views
6

我使用FileResult作爲返回PDF文件的MVC中的函數的返回值。在Web窗體中等效的.NET MVC FileResult

我應該在Web窗體中使用哪種返回類型?

感謝

public FileResult PrintPDFVoucher(object sender, EventArgs e) 
    { 
     PdfDocument outputDoc = new PdfDocument(); 
     PdfDocument pdfDoc = PdfReader.Open(
      Server.MapPath(ConfigurationManager.AppSettings["Template"]), 
      PdfDocumentOpenMode.Import 
     ); 

     MemoryStream memory = new MemoryStream(); 

     try 
     { 
      //Add pages to the import document 
      int pageCount = pdfDoc.PageCount; 
      for (int i = 0; i < pageCount; i++) 
      { 
       PdfPage page = pdfDoc.Pages[i]; 
       outputDoc.AddPage(page); 
      } 
      //Target specifix page 
      PdfPage pdfPage = outputDoc.Pages[0]; 

      XGraphics gfxs = XGraphics.FromPdfPage(pdfPage); 
      XFont bodyFont = new XFont("Arial", 10, XFontStyle.Regular); 


      //Save 
      outputDoc.Save(memory, true); 
      gfxs.Dispose(); 
      pdfPage.Close(); 
     } 
     finally 
     { 
      outputDoc.Close(); 
      outputDoc.Dispose(); 
     } 

     var result = new FileContentResult(memory.GetBuffer(), "text/pdf"); 
     result.FileDownloadName = "file.pdf"; 
     return result; 
    } 

回答

5

在ASP.NET Web表單,你需要手動將文件寫入響應流。 webforms中沒有結果抽象。

Response.ContentType = "Application/pdf";  
    //Write the generated file directly to the response stream 
    Response.BinaryWrite(memory);//Response.WriteFile(FilePath); if you have a physical file you want them to download 
    Response.End(); 

這段代碼沒有經過測試,但是這應該讓你在大方向上。

3

經典ASP.NET不具有返回類型的想法。解決這個問題的方法是創建一個定製的.ashx頁面/處理程序來提供文件。

你背後的這個文件應該類似的東西代碼:

public class Download : IHttpHandler 
{ 
    public void ProcessRequest (HttpContext context) 
    { 
     PdfDocument outputDoc = new PdfDocument(); 
     PdfDocument pdfDoc = PdfReader.Open(
      Server.MapPath(ConfigurationManager.AppSettings["Template"]), 
      PdfDocumentOpenMode.Import 
     ); 

     MemoryStream memory = new MemoryStream(); 

     try 
     { 
      //Add pages to the import document 
      int pageCount = pdfDoc.PageCount; 
      for (int i = 0; i < pageCount; i++) 
      { 
       PdfPage page = pdfDoc.Pages[i]; 
       outputDoc.AddPage(page); 
      } 
      //Target specifix page 
      PdfPage pdfPage = outputDoc.Pages[0]; 

      XGraphics gfxs = XGraphics.FromPdfPage(pdfPage); 
      XFont bodyFont = new XFont("Arial", 10, XFontStyle.Regular); 


      //Save 
      Response.ContentType = ""text/pdf""; 
      Response.AppendHeader("Content-Disposition","attachment; filename=File.pdf"); 

      outputDoc.Save(Response.OutputStream, true); 

      gfxs.Dispose(); 
      pdfPage.Close(); 
     } 
     finally 
     { 
      outputDoc.Close(); 
      outputDoc.Dispose(); 
     } 
    } 

    public bool IsReusable 
    { 
     get 
     { 
       return false; 
     } 
    } 
} 
+0

感謝「內容處置」頭 – 2015-05-17 20:01:06