【发布时间】:2021-09-12 07:15:35
【问题描述】:
我在 asp.net mvc c# 中使用 iTextSharp 合并大量 pdf 文件,它适用于少量文件,但是当它达到大约 (1000) 个文件时,它会在 pdf.AddDocument(reader);并抛出“System.OutOfMemoryException”。 我已经在使用 PdfCopy 和 FileStream 来更好地利用我搜索的每个地方都建议的内存。我的代码如下。请建议我如何处理。
using (FileStream stream = new FileStream(outMergeFile, FileMode.Create))
{
Document document = new Document();
PdfCopy pdf = new PdfCopy(document, stream);
PdfReader reader = null;
PdfReader.unethicalreading = true;
try
{
document.Open();
for (int i = 0; i < fileList.Count; i++)
{
var fileStr = Request.MapPath(fileList[i].Path)
reader = new PdfReader(fileStr);
pdf.AddDocument(reader);
reader.Close();
}
}
catch (Exception ex)
{
reader.Close();
}
finally
{
document.Close();
}
}
【问题讨论】:
-
您是在 32 位还是 64 位运行 IIS?
-
感谢您的快速回复,我使用的是 64 位的 IIS。
-
要么改进你的实现,要么添加更多内存,这是没有办法的。
-
您的代码不太正确。
Document, PdfCopy, PdfReader是一次性物品。他们必须有using语句。它们都应该在for循环内;不在外面。 -
@KosalaW 在 itext
Dispose和Close的情况下基本上做同样的事情,并且操作尝试关闭。因此,他们不必使用using。但这绝对是一种很好的风格。
标签: c# asp.net-mvc pdf itext out-of-memory