Using a FileStreamResult with a MemoryStream in ASP.NET MVC 3

I was playing around with EO.Pdf 2011.2 for .NET from Essential Objects to see how easy it would be to use HTML and Razor to generate a report and convert it to a PDF file.

EO.Pdf allows you to save a PDF document on disk or to a Stream. Since ASP.NET MVC 3 lets you return a FileStreamResult based on a Stream, I thought this would be the easiest solution and I came up with something like this:

[HttpGet]
public FileResult Download()
{
    var doc = new EO.Pdf.PdfDocument();
    EO.Pdf.HtmlToPdf.ConvertUrl("http://www.google.com/", doc);

    var ms = new MemoryStream();
    doc.Save(ms);

    return new FileStreamResult(ms, "application/pdf")
               {
                   FileDownloadName = "download.pdf"
               };
}

When trying it out, all I got was a corrupt PDF file. Something was wrong. But what? Apparently, you have to reset the Position of the MemoryStream before you pass it to the FileStreamResult constructor. Adding this solved the problem.

[HttpGet]
public FileResult Download()
{
    var doc = new EO.Pdf.PdfDocument();
    EO.Pdf.HtmlToPdf.ConvertUrl("http://www.google.com/", doc);

    var ms = new MemoryStream();
    doc.Save(ms);

    ms.Position = 0;

    return new FileStreamResult(ms, "application/pdf")
               {
                   FileDownloadName = "download.pdf"
               };
}
This entry was posted in Development and tagged . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Please leave these two fields as-is: