Search code examples
c#asp.net-mvcpdfitextout-of-memory

how to avoid 'System.OutOfMemoryException' Merging large number of PDF files using iTextSharp in asp.net mvc c#


I am merging large number of pdf files using iTextSharp in asp.net mvc c#, it works fine for small number of files but when it reaches about (1000) files it breaks on line pdf.AddDocument(reader); and throws 'System.OutOfMemoryException'. I am already using PdfCopy and FileStream to better utilize memory which is suggested every where I searched. My code is given below. Please suggest me how to handle this.

        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();
            }
        }

Solution

  • Add

    pdf.FreeReader(reader);
    

    right before

    reader.Close();
    

    to make sure that as little memory as possible is required for managing copied content from that reader.

    That method (of the parent class of PdfCopy) is documented as Writes the reader to the document and frees the memory used by it. The main use is when concatenating multiple documents to keep the memory usage restricted to the current appending document.