简体   繁体   中英

ASP.NET MVC has File(outPdfStream, “application/pdf”) returned bloating bytes?

In the MVC controller function, I have the following codes:

                EvoPdf.PdfConverter converter = new EvoPdf.PdfConverter();
            converter.LicenseKey = "e/MyLicenceKey+uT05+X65eb67e3t7Q==";
            converter.PdfDocumentOptions.BottomMargin = margin;
            converter.PdfDocumentOptions.TopMargin = margin;
            converter.PdfDocumentOptions.LeftMargin = margin;
            converter.PdfDocumentOptions.RightMargin = margin;
            var outPdfStream = new System.IO.MemoryStream();
            converter.SavePdfFromHtmlStreamToStream(stream, System.Text.Encoding.UTF8
                , ControllerContext.HttpContext.Request.Url.GetLeftPart(UriPartial.Authority), outPdfStream);
            Response.AddHeader("Content-Disposition", $"inline; filename={reportInfo.ReportName}");
            Response.Cache.SetCacheability(System.Web.HttpCacheability.Private);
           // System.IO.File.WriteAllBytes(@"c:\test\aaaa.pdf", bytes);
            return File(outPdfStream, "application/pdf");

Firefox could receive the PDF response and display correctly. The Adobe Reader XI plugin in IE 10 complains that "File does not begin with'%PDF'. Local\\EWH([b~rkqj", and Chrome complains incorrect format. When I save the PDF through Firefox, the size of the file is around 2.6 MB, however, the commented out codes above saved pdf to aaaa.pdf with size around 400k. And the file could be open and rendered correctly in all browsers and PDF readers.

Apparently somehow ASP.NET or IIS 7.5/8 has bloat/pollute the 400KB which something else which may be tolerated by Firefox but not others. Through the VS debugger, I am pretty sure the bytes/stream is around 400 KB when the function returns, but somehow when the response leaves IIS, the response becomes a few times bigger.

I am using MVC5 and .NET 4.5, and the hosts are IIS EXpress, IIS 7.5, IIS8 on Windows 7 and Server 2012 with all latest patches.

This is a very common issue.

You should clear the response with Response.Clear() before writing the pdf content to the response,

and then should call Response.End() afterwards.

That would send only the pdf content to the client.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM