0

我正在使用 iTextSharp (5.4.1.0) 将一组 PDF 文件合并到一个文件中。如果有大文件,我在关闭文档 [document.Close();] 的行收到 System.OutOfMemoryException

这是我的合并功能:

    public static byte[] MergeFiles(List<string> sourceFiles)
    {
        Document document = new Document();
        MemoryStream output = new MemoryStream();

        // Initialize pdf writer
        PdfWriter writer = PdfWriter.GetInstance(document, output);
        writer.PageEvent = new PdfPageEvents();

        try
        {
            // Open document to write
            document.Open();
            PdfContentByte content = writer.DirectContent;

            PdfReader reader;
            PdfImportedPage importedPage;

            // Iterate through all pdf documents
            for (int fileCounter = 0; fileCounter < sourceFiles.Count; fileCounter++)
            {

                Console.WriteLine("File(" + (fileCounter + 1).ToString() + ") : " + sourceFiles[fileCounter].ToString());


                // Create pdf reader
                reader = new PdfReader(new iTextSharp.text.pdf.RandomAccessFileOrArray(sourceFiles[fileCounter]), null);
                //reader = new PdfReader(sourceFiles[fileCounter]);
                int numberOfPages = reader.NumberOfPages;

                // Iterate through all pages
                for (int currentPageIndex = 1; currentPageIndex <= numberOfPages; currentPageIndex++)
                {
                    // Determine page size for the current page
                    document.SetPageSize(reader.GetPageSizeWithRotation(currentPageIndex));
                    // Create page
                    document.NewPage();
                    importedPage = writer.GetImportedPage(reader, currentPageIndex);
                    // Determine page orientation
                    int pageOrientation = reader.GetPageRotation(currentPageIndex);
                    if ((pageOrientation == 90) || (pageOrientation == 270))
                    {
                        content.AddTemplate(importedPage, 0, -1f, 1f, 0, 0, reader.GetPageSizeWithRotation(currentPageIndex).Height);
                    }
                    else
                    {
                        content.AddTemplate(importedPage, 1f, 0, 0, 1f, 0, 0);
                    }
                }


            }

            document.Close();
            writer.Close();
        }
        catch (Exception ex)
        {
            ErrorsHandling.LogException("MergeFiles", ex.Message, ex.StackTrace);
        }

        return output.GetBuffer();
    }

提前致谢。

4

1 回答 1

1

这里的错误是我正在返回“output.GetBuffer();” 之后不要释放 MemoryStream。

于 2013-05-16T11:55:18.230 回答