C#MVC网站PDF文件存储在字节数组中,在浏览器中显示

时间:2022-12-18 21:11:52

I am receiving a byte[] which contains a PDF.

我收到一个包含PDF的byte []。

I need to take the byte[] and display the PDF in the browser. I have found similar questions like this - How to return PDF to browser in MVC?. But, it opens the PDF in a PDF viewer, also I am getting an error saying the file couldn't be opened because it's - "not a supported file type or because the file has been damaged".

我需要取字节[]并在浏览器中显示PDF。我发现了类似的问题 - 如何在MVC中将PDF返回到浏览器?但是,它在PDF查看器中打开PDF,我也收到一个错误,说文件无法打开,因为它是“ - 不支持的文件类型或因为文件已被损坏”。

How can I open the PDF in the browser? My code so far looks like the following -

如何在浏览器中打开PDF?到目前为止,我的代码如下所示 -

    public ActionResult DisplayPDF()
    {
        byte[] byteArray = GetPdfFromDB();
        Stream stream = new MemoryStream(byteArray);
        stream.Flush(); 
        stream.Position = 0; 

        return File(stream, "application/pdf", "Labels.pdf");
    }

1 个解决方案

#1


6  

You can show the byte array PDF directly in your browser simply by using MemoryStream instead of Stream and FileStreamResult instead of File:

您可以直接在浏览器中显示字节数组PDF,只需使用MemoryStream而不是Stream和FileStreamResult而不是File:

public ActionResult DisplayPDF()
{
byte[] byteArray = GetPdfFromDB();
MemoryStream pdfStream = new MemoryStream();
pdfStream.Write(byteArray , 0,byteArray .Length);
pdfStream.Position = 0;
return new FileStreamResult(pdfStream, "application/pdf");
}

#1


6  

You can show the byte array PDF directly in your browser simply by using MemoryStream instead of Stream and FileStreamResult instead of File:

您可以直接在浏览器中显示字节数组PDF,只需使用MemoryStream而不是Stream和FileStreamResult而不是File:

public ActionResult DisplayPDF()
{
byte[] byteArray = GetPdfFromDB();
MemoryStream pdfStream = new MemoryStream();
pdfStream.Write(byteArray , 0,byteArray .Length);
pdfStream.Position = 0;
return new FileStreamResult(pdfStream, "application/pdf");
}