c# - 分割 10k 页 PDF 时出现内存泄漏(iTextSharp PDF API)

标签 c# memory-management memory-leaks garbage-collection itext

我有一个略多于 10,000 页的 PDF,我试图根据分隔符页面将其拆分为更小的 PDF。我当前的实现效果很好,直到您开始一次向它扔完整的 10k 页。在大约第 50 个创建 pdf(每个大约 100 页)之后,它将开始显着减慢,并且在出现 OutOfMemoryException 之前,我的内存使用量会跃升至大约 2GB。我对内存管理的经验很少,但我做了很多研究。我在这里提出这个问题只是因为它对时间敏感,所以如果我自己没有进行合理的研究,我深表歉意。

我对原始 PDF 的初步阅读:

 var pdfDictionary = PDFHelper.ParsePDFByPage(_workItem.FileName);
        //Code behind
        public static Dictionary<int, string> ParsePDFByPage(string filePath)
        {
            var retVal = new Dictionary<int, string>();

            PdfReader reader = new PdfReader(filePath);
            for (int page = 1; page <= reader.NumberOfPages; page++)
            {
                retVal.Add(page, PdfTextExtractor.GetTextFromPage(reader, page, new StructuredTextExtractionStrategy()));
            }
            reader.Close();
            reader.Dispose();

            return retVal;
        }

读完后,我找到哪些页面是分隔符,并为需要从原始页面拆分的每个页面范围创建一个 HMPdf(定义如下)的实例

var pdfsToCreate= pdfDictionary.Where(x => x.Value.Contains("DELIMITER"));
var pdfList = new List<HMPdf>();
foreach (var item in pdfsToCreate) //pdfsToCreate = Dictionary<int,string> 
{
    //Parsing logic (most removed, just know that this part works fine)

    //After parsing, create new instance of HMPdf and add it to the list
    var pdf = new HMPdf(startPage, endPage, fileName);
    pdfList.Add(pdf);
}

解析后,创建 PDF

foreach (var hmpdf in pdfList)
{
    //I've tried forcing the GC to collect after every 10 pdfs created
    string error = string.Empty;
    if (!hmpdf.TryCreate(sourcePath, destinationPath, out error))
    {
        throw new Exception("Error creating new PDF - " + error);
    }
}

HMPdf 代码隐藏

public class HMPdf
{
    private string _path;
    private string _fileName;
    private PdfCopy _pdfCopy = null;
    private PdfReader _reader = null;
    private Document _sourceDocument = null;
    private PdfImportedPage _importedPage = null;
    private int _pageFrom;
    private int _pageTo;
    private FileStream _fileStream;

    public HMPdf(int pageFrom, int pageTo, string fileName)
    {
        _pageFrom = pageFrom;
        _pageTo = pageTo;
        _fileName = fileName;
    }

    public bool TryCreate(string sourcePath, string destinationPath, out string errorMessage)
    {        
        try
        {

            _reader = new PdfReader(sourcePath);
            _sourceDocument = new Document(_reader.GetPageSizeWithRotation(_pageFrom));
            _fileStream = new System.IO.FileStream(Path.Combine(destinationPath, _fileName.ToLower().Contains(".pdf") ? _fileName : _fileName + ".pdf"),
                    System.IO.FileMode.Create);
            _pdfCopy = new PdfCopy(_sourceDocument, _fileStream);
            _sourceDocument.Open();
            for (int i = _pageFrom; i <= _pageTo; i++)
            {
                _importedPage = _pdfCopy.GetImportedPage(_reader, i);
                _pdfCopy.AddPage(_importedPage);
                _importedPage = null;
            }
            return true;
        }
        catch (Exception ex)
        {
            errorMessage = ex.Message;
            return false;
        }
        finally
        {
            if (_reader != null)
            {
                _reader.Close();
                _reader.Dispose();
                _reader = null;
            }
            if (_sourceDocument != null)
            {
                _sourceDocument.Close();
                _sourceDocument.Dispose();
                _sourceDocument = null;
            }
            if (_pdfCopy != null)
            {
                _pdfCopy.Close();
                _pdfCopy.Dispose();
                _pdfCopy = null;
            }
            if (_fileStream != null)
            {
                _fileStream.Close();
                _fileStream.Dispose();
                _fileStream = null;
            }
        }
    }
}

正如你所知,我正在关闭/处置所有打开的文件流、读取器等......(对吗?)。我尝试过每创建 10 个 pdf 后强制垃圾收集器运行一次,但它不会清理任何内容。我运行了 Telerik JustTrace,由于我对内存管理知之甚少,有几件事很突出。首先,在几个快照之间,有 0 个已释放的对象,而在最后一个快照中,pdfList 对象占用了近 1 GB 的内存。

我是否遗漏了一些完全明显的东西?

抱歉写得太长了。

最佳答案

也许你正在证明The Dangers of the Large Object Heap ...

尝试以减少内存使用的方式改进逻辑。

并尽可能减少变量范围。即,不要创建不必要的类变量,而是将它们设为字段变量。

尝试如下所示的方法,这将减少变量的范围。

    public bool TryCreate(string sourcePath, string destinationPath, out string errorMessage)
    {
        try
        {

            using (var _reader = new PdfReader(sourcePath))
            {
                using (var _sourceDocument = new Document(_reader.GetPageSizeWithRotation(_pageFrom)))
                {
                    using (var _fileStream =
                        new System.IO.FileStream(
                            Path.Combine(destinationPath, _fileName.ToLower().Contains(".pdf") ? _fileName : _fileName + ".pdf"),
                            System.IO.FileMode.Create))
                    {
                        using (_pdfCopy = new PdfCopy(_sourceDocument, _fileStream))
                        {
                            _sourceDocument.Open();
                            for (int i = _pageFrom; i <= _pageTo; i++)
                            {
                                _importedPage = _pdfCopy.GetImportedPage(_reader, i);
                                _pdfCopy.AddPage(_importedPage);
                                _importedPage = null;
                            }
                        }
                    }
                }
            }
            return true;
        }

    }

关于c# - 分割 10k 页 PDF 时出现内存泄漏(iTextSharp PDF API),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35304425/

相关文章:

memory - JavaFX 和监听器内存泄漏

c# 对列表进行分组并获取每组的计数

ios - iVars 引用强、弱还是什么?

c++ - 默认的 STL 分配器如何分配?

c 内存分配和数组的数组

c - valgrind 给出错误但无法找到位置

c++ - 在 Visual Studio 单元测试中检查内存泄漏

c# - 底层连接已关闭 : An unexpected error occurred on a receive

c# - 如何序列化 Windows.Media.Brush

c# - 如何模拟构造函数内部的依赖关系?