iTextSharp使用Large文件抛出异常OutOfMemoryException

时间:2013-05-16 09:51:23

标签: pdf-generation itextsharp out-of-memory

我正在使用iTextSharp(5.4.1.0)将一组PDF文件合并到一个文件中。 如果有larg文件,我在关闭文档的行[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();
    }

提前致谢。

1 个答案:

答案 0 :(得分:1)

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