Merging PDFs with ITextSharp

LordHits picture LordHits · Feb 9, 2010 · Viewed 44k times · Source

What is the optimum way to merge 2 PDF files with ITextSharp in C#? I'm using ASP.NET/.NET3.5.

Answer

tommy picture tommy · Dec 10, 2013
public static void Merge(List<String> InFiles, String OutFile)
    {
        using (FileStream stream = new FileStream(OutFile, FileMode.Create))
        using (Document doc      = new Document())
        using (PdfCopy pdf       = new PdfCopy(doc, stream))
        {
            doc.Open();

            PdfReader reader     = null;
            PdfImportedPage page = null;

            //fixed typo
            InFiles.ForEach(file =>
            {
                reader = new PdfReader(file);

                for (int i = 0; i < reader.NumberOfPages; i++)
                {
                    page = pdf.GetImportedPage(reader, i + 1);
                    pdf.AddPage(page);
                }

                pdf.FreeReader(reader);
                reader.Close();
            });
        }
    }