"File does not begin with '%PDF-'." 尝试加载 PDF 时出错 - ASP.NET MVC

"File does not begin with '%PDF-'." Error when trying to load a PDF - ASP.NET MVC

我有多个 MemoryStreams 形式的 PDF,我需要合并 MemoryStreams,使它们成为一个长 PDF,然后将它们发送到浏览器。

我使用 iText7 创建了以下函数,它采用假定为 PDF 的 MemoryStreams 列表,输出是串联 PDF 的 MemoryStream

    public static MemoryStream PdfCat(List<MemoryStream> pdfs)
        {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            using(PdfDocument applicationPdf = new PdfDocument(new PdfWriter(baos)))
            {

                PdfMerger merger = new PdfMerger(applicationPdf);

                // add every document to the empty pdf
                foreach (MemoryStream pdfMemStream in pdfs)
                {
                    using (PdfDocument pdf = new PdfDocument(new PdfReader(pdfMemStream)))
                    {
                        merger.Merge(pdf, 1, pdf.GetNumberOfPages());
                    }
                }

                baos.Position = 0;
                merger.Close();
            }

            return new MemoryStream(baos.ToArray());
        }

我正在尝试使用以下方法将 PDF 发送到控制器中的浏览器:

    MemoryStream application = FileUtils.PdfCat(applicationPdfs);
    return new FileStreamResult(application, "application/pdf");

其中 applicationPdfsList<MemoryStream>

我的 HTML 中的按钮如下所示:

<a href="~/Report/Index/@Model.id" target="_blank">View all attachments</a>

问题是当我点击 "View all attachments" 按钮时,我在浏览器中收到以下错误:

我能够在本地保存 PDF 并以这种方式查看,因此 PDF 正在正确合并。有谁知道错误的含义以及我该如何解决?

更新: 似乎这仅在我使用 FireFox 作为浏览器时才有效。由于某种原因,该错误仅发生在 IE 和 Chrome.

删除行

baos.Position = 0;

或至少将它移到 using(PdfDocument...) {...} 块之后。

关闭合并或基础文档时,仍有一些数据写入输出流,通过在关闭前更改流位置,您可以使这些数据覆盖输出的开始(%PDF-... header is) 而不是附加在末尾。