9

I am writing an application in MVC4.

I have a physical pdf file on the server. I want to convert this to a memory stream and send it back to the user like this:

return File(stream, "application/pdf", "myPDF.pdf");

But how do I convert a pdf file to a memory stream?

Thanks!

meJustAndrew
  • 6,011
  • 8
  • 50
  • 76
user2206329
  • 2,792
  • 10
  • 54
  • 81
  • 1
    I would not say "convert". Given that a pdf in file form IS a stream of bytes that is no conversion. Why do you need a memory stream? Any stream should do, and guess what, there is a file stream. – TomTom Feb 17 '14 at 10:52
  • possible duplicate of [How to create file and return it via FileResult in ASP.NET MVC?](http://stackoverflow.com/questions/1375486/how-to-create-file-and-return-it-via-fileresult-in-asp-net-mvc) – Panagiotis Kanavos Feb 17 '14 at 10:55

3 Answers3

16

You don't need MemoryStream. Easiest way is to use overload that accepts file name:

return File(@"C:\MyFile.pdf", "application/pdf");

another solution is to use overload that accepts byte[]:

return File(System.IO.File.ReadAllBytes(@"C:\Myfile.pdf"), "application/pdf");

or if you want use FileStream:

return File(new FileStream(@"C:\MyFile.pdf", FileMode.Open, FileAccess.Read), "application/pdf");
dkozl
  • 32,814
  • 8
  • 87
  • 89
6

Worked it out

 var pdfContent = new MemoryStream(System.IO.File.ReadAllBytes(imageLocation));
                pdfContent.Position = 0;
                return new FileStreamResult(pdfContent, "application/pdf");
user2206329
  • 2,792
  • 10
  • 54
  • 81
  • 1
    This isn't bad, but this allocates a lot of memory unnecessarily. You lose the advantage of having a physical file that can be *streamed*. – fejesjoco Feb 17 '14 at 10:58
1

Use an overload that uses a filename, see here. It's the easiest solution when you have a physical file.

fejesjoco
  • 11,763
  • 3
  • 35
  • 65