【问题标题】:ITextSharp Out of memory exception merging multiple pdfITextSharp内存不足异常合并多个pdf
【发布时间】:2015-06-07 12:42:29
【问题描述】:

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

 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 的各种问题,但在我看来,我正在接受所有建议以保持低内存使用率,但这并没有发生。 对此有什么想法吗?

【问题讨论】:

  • 使用PdfCopy 而不是PdfSmartCopyPdfSmartCopy 是“聪明的”,因为它在内存中保存了大量的东西。
  • 还可以尝试直接写信给FileStream,而不是MemoryStream。你可能真的是内存不足了。
  • 嗨,非常感谢您的快速响应,PdfCopy 代替 PdfSmartCopy 很好,将内存使用量减少了近一半,但 FileStream 好多了,我现在只使用了 15 MB内存而不是1GB,还不错。我可以使用 PDfSmartCopy 来生成更小的 PDF。如果您做出并回答它,我会赞成并接受,谢谢。

标签: c# pdf memory memory-leaks itextsharp


【解决方案1】:

由于这是一大堆东西,我建议直接写信给FileStream,而不是MemoryStream。这可能是一个实际情况,其中内存不足异常的字面意思可能是“内存不足”。

另外,正如 Bruno 所指出的,不幸的是,PdfSmartCopy 的“智能”部分也以内存为代价。切换到PdfCopy 应该可以减少内存压力,尽管您的最终 PDF 可能会更大。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-03
    • 1970-01-01
    • 2010-10-05
    • 1970-01-01
    相关资源
    最近更新 更多