C# 将 ASP.NET 生成的 pdf byte[] 显示到网页而不保存文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 
原文地址: http://stackoverflow.com/questions/17108278/
Warning: these are provided under cc-by-sa 4.0 license.  You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Display ASP.NET generated pdf byte[] to web page without saving the file
提问by Sen Jacob
I'm using iTextSharp for generating a pdf. I can save the PDF file from the PDF byte[].
我正在使用 iTextSharp 生成 pdf。我可以从 PDF byte[] 保存 PDF 文件。
byte[] outputPDF = cnt.CreateBreakPDF();
File.WriteAllBytes(pdfOutPutPath, outputPDF);
What is the best way to display the output byte[]to a web page? 
将输出显示byte[]到网页的最佳方式是什么?
I want to show the PDF inside a div in my page. Not the PDF as a full response.
我想在我的页面的 div 中显示 PDF。不是作为完整回复的 PDF。
I've seen answers for MVC, but I'm using ASP.NET Web Application.
我已经看到了 MVC 的答案,但我使用的是 ASP.NET Web 应用程序。
Is there a better way than using HTTP handlers to do so? I don't want to send all the details for creating PDF as query string.
有没有比使用 HTTP 处理程序更好的方法呢?我不想将创建 PDF 的所有详细信息作为查询字符串发送。
采纳答案by Sen Jacob
I tried this in jsFiddle, and it works well in Chrome & FF, need to check on other browsers as well.
我在 jsFiddle 中尝试过这个,它在 Chrome 和 FF 中运行良好,还需要检查其他浏览器。
Convert the byte[]to Base64using,
转换byte[]为Base64使用,
string base64PDF = System.Convert.ToBase64String(outputPDF, 0, outputPDF.Length);
All I had to do is specify the MIME typeas data:application/pdf;base64,in the source and give the Base64version of the PDF.
所有我需要做的是指定MIME type为data:application/pdf;base64,源,并给予Base64版本PDF。
<object data="data:application/pdf;base64, JVBERi0xLjQKJeLjz9MKMyA..." type="application/pdf" width="160px">
    <embed src="data:application/pdf;base64, JVBERi0xLjQKJeLjz9MKMyA..." type="application/pdf" />
</object>
I couldn't be able to hide the top toolbar which appears in FF by appending #toolbar=0&navpanes=0&statusbar=0. 
我无法通过附加#toolbar=0&navpanes=0&statusbar=0.
IE8 needs a saved pdf file to be displayed.
IE8 需要显示已保存的 pdf 文件。
回答by Karthik
Try this
尝试这个
Response.ContentType = "application/pdf";
Response.AddHeader("content-length", outputPDF.Length.ToString());
Response.BinaryWrite(outputPDF);
回答by ovaltein
Would something like this work?
这样的东西会起作用吗?
<div>
<object data="myPDF.pdf" type="application/pdf" width="200" height="500">
alt : <a href="myPDF.pdf">myPDF.pdf</a>
</object>
</div> 
You would just need to pass your pdf into the object data source.
您只需要将您的 pdf 传递到对象数据源中。
回答by Weihui Guo
I have being using Convert.ToBase64String(content)for some projects without any issue, until today with a 18 page file at about 1 MB. The error from Chrome's console is Failed to load resource: net::ERR_INVALID_URL. I guess it's because of the string size?!
我一直在使用Convert.ToBase64String(content)一些项目没有任何问题,直到今天有一个大约 1 MB 的 18 页文件。Chrome 控制台的错误是Failed to load resource: net::ERR_INVALID_URL. 我猜是因为字符串的大小?!
I ended up using web api and just return it as FileStreamResultinstead of Base64 string.
我最终使用了 web api,只是将它作为FileStreamResult而不是 Base64 字符串返回。
var stream = new MemoryStream();
await stream.WriteAsync(content, 0, content.Length);
stream.Position = 0;
return new FileStreamResult(stream, "application/pdf");
Update: It's basically the same to display it on a razor page. I just copied my code for retrieving fax content using RingCentral here. And better yet, just use
FileContentResultas you already have thebyte[].
更新:在剃刀页面上显示它基本上是一样的。我只是在这里复制了使用 RingCentral 检索传真内容的代码。更好的是,只需使用
FileContentResult您已经拥有的byte[].
public async Task<IActionResult> OnGet(string messageId)
{
    try
    {
        using (var rc = new RingCentral.RestClient(setting.ClientId, setting.ClientSecret, setting.Production, "Fax"))
        {
            await rc.Authorize(setting.UserName, setting.Extension, setting.Password);
            var extension = rc.Restapi().Account().Extension();
            var outputPDF = await extension.MessageStore(messageId).Content(messageId).Get();
            return new FileContentResult(outputPDF, "application/pdf");
        }
        return Page();
    }
    catch (Exception ex)
    {
        _logger.Error(ex.Message);
        throw;
    }
}

