使用自定义TextWriter时,OutputStream不可用

时间:2010-05-05 21:21:17

标签: c# asp.net

这是我的函数,它将pdf转换为png图像,它会引发错误 这一行 - > stream.WriteTo(Response.OutputStream);有什么问题吗?

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.Credentials = 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());
            }
        }

2 个答案:

答案 0 :(得分:46)

这与你的问题没有直接关系,但是在做其他事情时我得到了同样的例外,所以我想我会把这个答案放在后面......

我仅在主页渲染时才获得此异常,而不是在进行相关控制器操作时。

直到我意识到我已经使用Html.Action(运行动作并发出HTML内联)而不是Url.Action(生成URL)时,会发生很多令人头疼的问题。

答案 1 :(得分:1)

在我的情况下,原因是Controller.File方法中的错误参数。

带有第三个参数 null 的Controller.File方法将在浏览器窗口中呈现图像:

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

带有第三个参数 filename 的Controller.File方法将触发在浏览器中下载图像:

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

将第三个参数设置为扩展名的Controller.File方法将导致错误:使用自定义TextWriter时,OutputStream不可用

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