簡體   English   中英

ITextSharp合並多個pdf的內存不足異常

[英]ITextSharp Out of memory exception merging multiple pdf

我必須將多個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的各種問題,但在我看來,我正在采取一切建議來保持較低的內存使用率,但這種情況並沒有發生。 有什么想法嗎?

由於這是大量的東西,我建議直接寫入FileStream而不是MemoryStream 這可能是一個實際情況,其中內存異常可能實際上意味着“內存不足”。

此外,正如Bruno指出的那樣,不幸的是, PdfSmartCopy的“智能”部分也是以內存為代價的。 切換到PdfCopy應該會降低內存壓力,盡管最終的PDF可能會更大。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM