File CopyTo Problem & Multiple Outputs
-
Hello,
I want to copy my view in mvc to an output.pdf of my choosing. I could do that using the code fragment below but it both writes to output file and tries to open the view in browser.[EnableJsReport()] public ActionResult Report() { string outPath = @"SomePath\Out.pdf"; HttpContext.JsReportFeature() .Recipe(Recipe.ChromePdf) .OnAfterRender((r) => { using (FileStream outFile = System.IO.File.Create(outPath)) { r.Content.CopyTo(outFile); } }); return View(new ReportModel()); }
But in browser I get Failed to Load PDF Document error each and every time. So I get the out file but view gets broken.
What I really want is save a copy of report to my server and download a copy from client. And for that I used the code below(old code with download line added):[EnableJsReport()] public ActionResult Report() { string outPath = @"SomePath\Out.pdf"; HttpContext.JsReportFeature() .Recipe(Recipe.ChromePdf) .OnAfterRender((r) => { HttpContext.Response.Headers["Content-Disposition"] = "attachment; filename=\"myReport.pdf\""; using (FileStream outFile = System.IO.File.Create(outPath)) { r.Content.CopyTo(outFile); } }); return View(new ReportModel()); }
I get the behavior I want but the problem above breaks downloaded pdf and when I open I get same Failed to Load PDF File error. How can I fix this?
Thanks in advance.
-
I think that when using
r.Content.CopyTo
you get to the end of the stream.
You need to seek back to beginning afterward if you want to read it again.
Something liker.Content.Position = 0;
-
Yea guess you are right. It is working properly now. Thank you so much!