2010-09-30 74 views
2

我使用itexsharp生成pdf。 我正在創建MemoryStream,然後當我試圖將MemoryStream字節寫入響應但沒有運氣。當我在我的控制器中執行這個代碼時,pdf不會迴應。內存流正常使用,我可以在調試器中看到這一點,但由於某些原因,這些數量的butes沒有響應。MVC。 Itextsharp將pdf寫入響應

這裏是我的代碼:

 HttpContext.Current.Response.ContentType = "application/pdf"; 
     ... 
     using (Stream inputPdfStream = new FileStream(pdfFilePath, FileMode.Open, FileAccess.Read, FileShare.Read)) 
     using (Stream outputPdfStream = new MemoryStream()) 
     { 
      PdfReader reader = new PdfReader(inputPdfStream); 
      PdfStamper stamper = new PdfStamper(reader, outputPdfStream); 
      .... 

      //try one 
      outputPdfStream.WriteTo(HttpContext.Current.Response.OutputStream); // NOT POPULATING Response 
      //try two 
      HttpContext.Current.Response.BinaryWrite(outputPdfStream.ToArray()); // NOT POPULATING Response Too 

      HttpContext.Current.Response.End(); 
     } 

可能有人有什麼想法?

+0

你會在迴應中得到什麼嗎? – BlackICE 2010-09-30 13:35:39

+0

是的,幾個字節,但沒有我的pdf的字節 – Cranik 2010-09-30 13:37:49

+0

我會發佈一個更簡單的例子,不包括inputPdfStream這是另一個pdf文件,所以它會導致混淆。只需輸出MemoryStream作爲PdfWriter實例的流,一個document.open(),一些document.Add(..)和一個document.close()。然後,這個問題簡化爲「我想在迴應中發送包含在輸出MemoryStream中的PDF。如何?......」 – mmutilva 2011-01-30 13:27:28

回答

0

可能內存流仍然設置在最後一個寫入字節之後的位置。它會寫入當前位置的所有字節(不是)。如果您執行outputPdfStream.Seek(0)它將設置位置回到第一個字節,並將整個流的內容寫入響應輸出。

無論如何,就像Dean說的,你應該只使用Reponse.WriteFile方法。

3

你能不能用

Response.ContentType = "application/pdf" 
Response.AddHeader("Content-Type", "application/pdf") 
Response.WriteFile(pdfFilePath) 
Response.End() 
+0

在原始問題中,他讀取PDF作爲FileStream的輸入,並生成另一個PDF作爲輸出MemoryStream中,MemoryStream中的pdf是響應內容中需要發送的內容。爲什麼「Response.WriteFile(pdfFilePath)」呢? – mmutilva 2011-01-30 13:07:44

1

您應該使用FileContentResult Controller.File(byte[] content, string contentType)方法:

public ActionResult GeneratePDF() 
{ 
    var outputStream = new MemoryStream(); // This will hold the pdf you want to send in the response 

    /* 
    * ... code here to create the pdf in the outputStrem 
    */ 

    return File(outputStream.ToArray(), "application/pdf"); 
} 

來源:Building PDFs in Asp.Net MVC 2