您能告诉我,我的代码有什么问题吗?我正在使用它来合并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有一些错误:

c# - MemoryStream-合并PDF时无法访问关闭的Stream-LMLPHP

是什么原因造成的,以及如何避免呢?

谢谢。

最佳答案

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

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




说明

我没有在Internet上找到任何文档,因此不得不直接查看源代码。

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

     // ...
}

10-07 20:54