无法打开使用 ITextSharp 创建的合并 pdf

Fail to open merged pdf created with ITextSharp

我正在尝试合并一些 PDF 并将其保存到 Azure 中的 Blob 存储中,文件正在以 Azure 中保存我可以在那里看到 Kbs 并下载文件,但是当我尝试打开它时我得到了"Failed to load PDF document"

public static bool MergePDFsAzure(IEnumerable<string> fileNames, string targetPdf, bool deleteInputFiles)
    {
        Stream finalStream = new MemoryStream();

        iTextSharp.text.Document document = new iTextSharp.text.Document();
        iTextSharp.text.pdf.PdfCopy copy = new iTextSharp.text.pdf.PdfCopy(document, finalStream);

        iTextSharp.text.pdf.PdfReader.unethicalreading = true;
        try
        {
            copy.Open();
            document.Open();
            foreach (string file in fileNames)
            {
                var ms = new MemoryStream(File.ReadAllBytes(file)) {
                    Position = 0 
                };

                copy.AddDocument(new PdfReader(ms));
                ms.Dispose();
            }
        }
        catch (Exception ex)
        {
            ...

        }
        finally
        {
            if (document != null)
            {
                finalStream.Position = 0;
                StorageUtil.SaveFileAzure(...);
                document.Close();
                copy.Close();
            }
        }

    }

如果我在发送到 Azure 之前关闭文档,它会崩溃,因为流也被释放了。

在将结果发送到 Azure 之前,您必须关闭 document。否则结果就是未完成。

不幸的是,对于您的使用,itext PdfCopy(以及 PdfWriterPdfStamper)在 [=15= 期间隐式关闭时关闭其目标流].

为防止这种情况发生,您可以通过设置

要求 itext 不要这样做
copy.CloseStream = false;

在关闭文档之前。

或者,您可以使用 finalStream.ToArray() 检索由内存流表示的字节数组,并使用该字节数组而不是流将数据存储在别处。在关闭内存流的情况下也可以检索此字节数组。