首页 文章

itextsharp PDF连接不起作用

提问于
浏览
0

我有一个webapi,我有路由连接pdfs并使用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文档 . 知道我可能做错了什么吗?谢谢 .

编辑:

如果我创建一个物理文件而不使用MemoryStream,这是有效的

1 回答

  • 1

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

    从它的外观来看,这似乎不是一个iText问题,因为你已经确认你可以创建一个物理文件 .

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

    无论如何,我认为解决这个问题的第一步是存储你回来的字节,并将它们与物理文件进行比较 .

相关问题