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

问题描述 投票:0回答:1

我正在尝试合并一些PDF并以天蓝色将其保存到blob存储中,文件正在以天蓝色保存,我可以在那里看到Kb并下载文件,但是当我尝试打开它时,出现了“加载PDF文档”

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();
            }
        }

    }

如果我在发送到天蓝色之前关闭文档,则由于流也被处理而崩溃。

c# asp.net itext memorystream
1个回答
0
投票

您必须先关闭document,然后再将结果发送到Azure。否则结果将无法完成。

但是不幸的是,当您在PdfCopy中隐式关闭itext PdfWriter(以及PdfStamperdocument.Close()时,它本身也会关闭其目标流。

为了防止这种情况,您可以通过设置来要求itext不这样做

copy.CloseStream = false;

在关闭文档之前。

或者,您可以使用finalStream.ToArray()检索由内存流表示的字节数组,并使用该字节数组代替流来将数据存储到其他位置。在关闭的内存流的情况下,也可以检索此字节数组。

© www.soinside.com 2019 - 2024. All rights reserved.