ITextSharp合并多个pdf的内存不足异常 [英] ITextSharp Out of memory exception merging multiple pdf

查看:941
本文介绍了ITextSharp合并多个pdf的内存不足异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须将多个1页pdf合并为一个pdf。我正在使用iTextSHarp 5.5.5.0来实现这一目标,但是当我合并超过900-1000 pdf时,我会遇到内存不足异常。我注意到,即使我释放我的阅读器并关闭它,内存永远不会被正确清理(进程使用的内存量永远不会减少)所以我想知道我可能做错了什么。这是我的代码:

I have to merge multiple 1 page pdf's into one pdf. I'm using iTextSHarp 5.5.5.0 to accomplish this, but when I get to merge more than 900-1000 pdf I get an out of memory exception. I noticed that even if I free my reader and close it the memory never gets cleaned properly (the amount of memory used by the process never decreases)so I was wondering what I could possibly be doing wrong. This is my code:

 using (MemoryStream msOutput = new MemoryStream())
        {
            Document doc = new Document();
            PdfSmartCopy pCopy = new PdfSmartCopy(doc, msOutput);
            doc.Open();
            foreach (Tuple<string, int> file in filesList)
            {
                PdfReader pdfFile = new PdfReader(file.Item1);
                for (int j = 0; j < file.Item2; j++)
                    for (int i = 1; i < pdfFile.NumberOfPages + 1; i++)//in this case it's always 1. 
                        pCopy.AddPage(pCopy.GetImportedPage(pdfFile, i));
                pCopy.FreeReader(pdfFile);
                pdfFile.Close();
                File.Delete(file.Item1);
            }
            pCopy.Close();
            doc.Close();

            byte[] content = msOutput.ToArray();
            using (FileStream fs = File.Create(Out))
            {
                fs.Write(content, 0, content.Length);
            }
        }

它永远不会写文件,我得到了p.Copy()期间的内存不足异常.AddPage()部分。我甚至尝试刷新pCopy变量,但没有改变任何东西。我查看了iText的文档以及StackOverflow的各种问题,但在我看来,我正在采取一切建议来保持较低的内存使用率,但这种情况并没有发生。
对此有何看法?

It never gets to writing the file, I get an out of memory exception during the p.Copy().AddPage() part. I even tried flushing the pCopy variable but didn't change anything. I looked in the documentation of iText and various questions around StackOverflow but seems to me that I'm taking every suggestion to keep memory usage low, but this isn't happening. Any ideas on this?

推荐答案

由于这是大量的东西我建议直接写一个 FileStream 而不是 MemoryStream 。这可能是一个实际情况,其中内存不足异常可能意味着内存不足。

Since this is a large amount of stuff I'd recommend writing directly to a FileStream instead of a MemoryStream. This might be an actual case where an Out of Memory Exception might literally mean "Out of Memory".

此外,正如布鲁诺所指出的那样,<聪明的部分<不幸的是,code> PdfSmartCopy 也是以内存为代价的。切换到 PdfCopy 应该可以减少内存压力,尽管最终的PDF可能会更大。

Also, as Bruno pointed out, the "smart" part of PdfSmartCopy unfortunately comes at the cost of memory, too. Switching to PdfCopy should reduce memory pressure although your final PDF might be larger.

这篇关于ITextSharp合并多个pdf的内存不足异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆