MemoryStream - 合并PDF时无法访问封闭的Stream

时间:2016-11-04 16:02:20

标签: c# pdf stream itext

请告诉我,我的代码有什么问题?我使用它来合并PDF,我创建了一个内存流,然后将其输出为PDF。它适用于我,但有些用户无法在IE中下载文件,或在Chrome中出现网络错误:

public static MemoryStream MergePdfForms(List<byte[]> files)
    {
        if (files.Count > 1)
        {
            PdfReader pdfFile;
            Document doc;
            PdfWriter pCopy;
            MemoryStream msOutput = new MemoryStream();

            pdfFile = new PdfReader(files[0]);

            doc = new Document();
            pCopy = new PdfSmartCopy(doc, msOutput);

            doc.Open();

            for (int k = 0; k < files.Count; k++)
            {
                pdfFile = new PdfReader(files[k]);
                for (int i = 1; i < pdfFile.NumberOfPages + 1; i++)
                {
                    ((PdfSmartCopy)pCopy).AddPage(pCopy.GetImportedPage(pdfFile, i));
                }
                pCopy.FreeReader(pdfFile);
            }

            pdfFile.Close();
            pCopy.Close();
            doc.Close();

            return msOutput;
        }
        else if (files.Count == 1)
        {
            return new MemoryStream(files[0]);
        }

        return null;
    }

调试后,我注意到内存流msOutput有一些错误:

enter image description here

导致它的原因,以及如何避免它?

谢谢。

1 个答案:

答案 0 :(得分:0)

CloseStream设置为false,否则当您致电pCopy.Close()时,输出流将会关闭。

pCopy = new PdfSmartCopy(doc, msOutput) { CloseStream = false };

解释

我没有在互联网上找到任何文档,所以我必须直接查看源代码。

这里是PdfSmartCopy类的声明:

public class PdfSmartCopy : PdfCopy
{
    // ...

    public PdfSmartCopy(Document document, Stream os) : base(document, os) {
        // ...
    }

    // ...
}

以下是PdfCopy类的声明:

public class PdfCopy : PdfWriter
{
    // ...

    public PdfCopy(Document document, Stream os) : base(new PdfDocument(), os)     {
        // ...
    }

    // ...
}

PdfWriter类的声明:

public class PdfWriter : DocWriter, 
    IPdfViewerPreferences,
    IPdfEncryptionSettings,
    IPdfVersion,
    IPdfDocumentActions,
    IPdfPageActions,
    IPdfIsoConformance,
    IPdfRunDirection,
    IPdfAnnotations
{
    // ...

    protected PdfWriter(PdfDocument document, Stream os) : base(document, os) {
        // ...
    }

    // ...
}

最后,DocWriter类的声明:

public abstract class DocWriter : IDocListener
{
    // ...

    // default value is true
    protected bool closeStream = true;

    public virtual bool CloseStream {
        get {
            return closeStream;
        }
        set {
            closeStream = value;
        }
    }

     protected DocWriter(Document document, Stream os)  
     {
        this.document = document;
        this.os = new OutputStreamCounter(os);
     }

     public virtual void Close() {
        open = false;
        os.Flush();
        if (closeStream) // <-- Take a look at this line
            os.Close();
     }

     // ...
}