public static bool MergePdfs(string folderInput, string mergePdfName, ref List <ColumbusIndex> documentsToMerge) { using (FileStream stream = new FileStream(mergePdfName, FileMode.Create)) { var totalDocs = 0; PdfReader reader = null; Document document = new Document(); PdfSmartCopy pdf = new PdfSmartCopy(document, stream); List <ColumbusIndex> tempList = new List <ColumbusIndex>(); try { document.Open(); foreach (var doc in documentsToMerge) { tempList.Add(doc); if (totalDocs > 0) { if (documentsToMerge[totalDocs - 1].PdfTempData != null) { documentsToMerge[totalDocs - 1].PdfTempData = null; //Release from memory } } totalDocs++; try { if (doc.PdfTempData == null) { doc.PdfTempData = File.ReadAllBytes(Path.Combine(folderInput, doc.FileName)); } reader = new PdfReader(doc.PdfTempData); doc.Pages = reader.NumberOfPages; if (doc.Pages == 0) { throw new Exception("Do not allow documents with zero pages"); } for (int i = 1; i <= doc.Pages; i++) { //import the page from source pdf var copiedPage = pdf.GetImportedPage(reader, i); // add the page to the new document if (pdf != null) { pdf.AddPage(copiedPage); } } if (pdf != null && reader != null) { pdf.FreeReader(reader); pdf.Flush(); } if (reader != null) { reader.Close(); } long fileSize = new FileInfo(mergePdfName).Length; long columbusPDFMaxSize = Convert.ToInt64(ConfigurationManager.AppSettings["ColumbusPDFMaxSize"]); if (fileSize > columbusPDFMaxSize) //If file size is bigger than 200mb, start a new file { GenerateControlFile(mergePdfName, tempList); documentsToMerge = documentsToMerge.Except(tempList).ToList(); return(true); } } catch (Exception ex1) { doc.FileMissing = true; throw new ProcessingException("COMBINE PDF: [" + Path.Combine(folderInput, doc.FileName) + "] " + ex1.Message + " : " + ex1.StackTrace); } } //Generate control file for last merged PDF GenerateControlFile(mergePdfName, tempList); documentsToMerge = documentsToMerge.Except(tempList).ToList(); return(true); } catch (Exception ex) { Log.Error(string.Format("Failed to merge files in {0} to {1}. ex: {2}", folderInput, mergePdfName, ex)); if (reader != null) { reader.Close(); } return(false); } finally { if (document != null) { document.Close(); } } } }