ITextSharp内存不足异常合并多个pdf
ITextSharp Out of memory exception merging multiple pdf
我必须将多个 1 页 pdf 合并为一个 pdf。我正在使用 iTextSHarp 5.5.5.0 来完成此操作,但是当我合并超过 900-1000 个 pdf 时,出现内存不足异常。我注意到即使我释放 reader 并关闭它,内存也永远不会被正确清理(进程使用的内存量永远不会减少)所以我想知道我可能做错了什么。这是我的代码:
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 的文档和有关 Whosebug 的各种问题,但在我看来,我正在采纳所有建议以保持低内存使用率,但这并没有发生。
对此有什么想法吗?
因为内容很多,我建议直接写到 FileStream
而不是 MemoryStream
。这可能是实际情况,其中内存不足异常可能字面意思是 "Out of Memory".
此外,正如 Bruno 指出的那样,不幸的是 PdfSmartCopy
的 "smart" 部分也以内存为代价。切换到 PdfCopy
应该可以减少内存压力,尽管您的最终 PDF 可能更大。
我必须将多个 1 页 pdf 合并为一个 pdf。我正在使用 iTextSHarp 5.5.5.0 来完成此操作,但是当我合并超过 900-1000 个 pdf 时,出现内存不足异常。我注意到即使我释放 reader 并关闭它,内存也永远不会被正确清理(进程使用的内存量永远不会减少)所以我想知道我可能做错了什么。这是我的代码:
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 的文档和有关 Whosebug 的各种问题,但在我看来,我正在采纳所有建议以保持低内存使用率,但这并没有发生。 对此有什么想法吗?
因为内容很多,我建议直接写到 FileStream
而不是 MemoryStream
。这可能是实际情况,其中内存不足异常可能字面意思是 "Out of Memory".
此外,正如 Bruno 指出的那样,不幸的是 PdfSmartCopy
的 "smart" 部分也以内存为代价。切换到 PdfCopy
应该可以减少内存压力,尽管您的最终 PDF 可能更大。