2010-09-30 46 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