开发者

OutputStream is not available when a custom TextWriter is used

this is my function which converts pdf to png image, it's throwing an error on this line--> stream.WriteTo(Response.OutputStream); Is there some thing wrong??

protected void CreatePngFromPdf() 
        {

            try
            {

                string PDFLocation = string.Format(@"\\XXXX\{0}\{1}\{2}.pdf", Yr, Loc.Substring(0, 4), Loc.Substring(4, 4));
                Utilities.WebPDF.PDF WebPDF = new DocuvaultMVC.Utilities.WebPDF.PDF();

                WebPDF.Credent开发者_运维百科ials = new NetworkCredential(@"xyz", "xyz");
                byte[] png = WebPDF.StreamPdfPageAsPngResize(PDFLocation,PageNumber, 612, 792);

                MemoryStream ms = new MemoryStream(png);
                MemoryStream stream = new MemoryStream();
                int newWidth = 612;
                int newHeight = 792;
                System.Drawing.Image newImg = System.Drawing.Image.FromStream(ms);

                Bitmap temp = new Bitmap(newWidth, newHeight, newImg.PixelFormat);
                Graphics newImage = Graphics.FromImage(temp);
                newImage.DrawImage(newImg, 0, 0, newWidth, newHeight);
                newImg.Dispose();

                temp.Save(stream, ImageFormat.Png);
                stream.WriteTo(Response.OutputStream);
                temp.Dispose();
                stream.Dispose();
            }
            catch (Exception ex)
            {
                Response.Write(ex.Message.ToString());
            }
        }


This is not directly relevant to your problem, but I got the same exception when doing something else, so I thought I'd put that answer here for posterity...

I got this exception merely when the homepage was rendering, rather than when going to the relevant controller action.

Much head-scratching ensues, until I realise that I've used Html.Action (which runs the action and emits the HTML inline) rather than Url.Action (which generates the URL).


In my case the reason was wrong argument in Controller.File method.

Controller.File method with third parameter as null will render the image in the browser window:

public ActionResult GenerateImage(...)
{
    ...
    return File(fileResult.Buffer, fileResult.ContentType, null);
}

Controller.File method with third parameter as filename will trigger downloading of the image in the browser:

public ActionResult GenerateImage(...)
{
    ...
    return File(fileResult.Buffer, fileResult.ContentType, "image.jpg");
}

Controller.File method with third parameter as extension will cause the error: OutputStream is not available when a custom TextWriter is used

public ActionResult GenerateImage(...)
{
    ...
    return File(fileResult.Buffer, fileResult.ContentType, ".jpg");
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜