itextsharp PDF 連接無法正常工作



我有一个webapi,我有连接PDF并使用MemoryStream返回字节数组的路由

public HttpResponseMessage ConcatPDFs(string id, ICollection<int> pdfs) {
        using (var db = new ApplicationDbContext())
        using (MemoryStream stream = new MemoryStream())
        using (Document doc = new Document())
        using (PdfCopy pdf = new PdfCopy(doc, stream))
        {
            doc.Open();
            PdfReader reader = null;
            PdfImportedPage page = null;
            db.PDFForms.Where(p => pdfs.Contains(p.Id)).ToList().ForEach(file =>
            {
                var filePath = Path.Combine(System.Web.Hosting.HostingEnvironment.MapPath("~/" + string.Format("Content/Uploads/PDFForms/")), file.FileName);
                reader = new PdfReader(filePath);
                for (int i = 0; i < reader.NumberOfPages; i++)
                {
                    page = pdf.GetImportedPage(reader, i + 1);
                    pdf.AddPage(page);
                }
                pdf.FreeReader(reader);
                reader.Close();
            });
            HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
            result.Content = new ByteArrayContent(stream.ToArray());
            result.Content.Headers.ContentType =
                new MediaTypeHeaderValue(string.Format("{0}", "application/pdf"));
            return result;
        }
    }

这是我的代码,但是当我将数据流式传输回客户端时,浏览器给我错误,无法加载PDF文档。知道我可能做错了什么吗?谢谢。

编辑:

如果我创建一个物理文件而不使用内存流,这有效

也许您可以使用wireshark调试应用程序?从响应中获取字节,将它们粘贴到文档中,然后查看是否可以使用Adobe Reader之类的内容读取该文档。

不过,从

外观上看,这似乎不是iText问题,因为您已确认可以创建物理文件。

因此,要么是 MemoryStream 的实现,要么是创建文档和发送 get 响应之间的其他步骤。

无论如何,我认为解决此问题的第一步是存储您返回的字节,并将它们与物理文件进行比较。

最新更新