C# iTextSharp Merge multiple pdf via byte array

20,760

This is pretty much just a C# version of Bruno's code here.

This is pretty much the simplest, safest and recommended way to merge PDF files. The PdfSmartCopy object is able to detect redundancies in the multiple files which can reduce file size some times. One of the overloads on it accepts a full PdfReader object which can be instantiated however you want.

public static byte[] concatAndAddContent(List<byte[]> pdfByteContent) {

    using (var ms = new MemoryStream()) {
        using (var doc = new Document()) {
            using (var copy = new PdfSmartCopy(doc, ms)) {
                doc.Open();

                //Loop through each byte array
                foreach (var p in pdfByteContent) {

                    //Create a PdfReader bound to that byte array
                    using (var reader = new PdfReader(p)) {

                        //Add the entire document instead of page-by-page
                        copy.AddDocument(reader);
                    }
                }

                doc.Close();
            }
        }

        //Return just before disposing
        return ms.ToArray();
    }
}
Share:
20,760

Related videos on Youtube

confusedandamused
Author by

confusedandamused

Programmer - always looking to learn more

Updated on August 08, 2022

Comments

  • confusedandamused
    confusedandamused almost 2 years

    I am new to using iTextSharp and working with Pdf files in general, but I think I'm on the right track.

    I iterate through a list of pdf files, convert them to bytes, and push all of the resulting bytes into a byte array. From there I pass the byte array to concatAndAddContent() to merge all of the pdf's into a single large pdf. Currently I'm just getting the last pdf in the list (they seem to be overwriting)

    public static byte[] concatAndAddContent(List<byte[]> pdfByteContent)
        {
            byte[] allBytes;
    
            using (MemoryStream ms = new MemoryStream())
            {
                Document doc = new Document();
                PdfWriter writer = PdfWriter.GetInstance(doc, ms);
    
                doc.SetPageSize(PageSize.LETTER);
                doc.Open();
                PdfContentByte cb = writer.DirectContent;
                PdfImportedPage page;
    
                PdfReader reader;
                foreach (byte[] p in pdfByteContent)
                {
                    reader = new PdfReader(p);
                    int pages = reader.NumberOfPages;
    
                    // loop over document pages
                    for (int i = 1; i <= pages; i++)
                    {
                        doc.SetPageSize(PageSize.LETTER);
                        doc.NewPage();
                        page = writer.GetImportedPage(reader, i);
                        cb.AddTemplate(page, 0, 0);
    
                    }
                }
    
                doc.Close();
                allBytes = ms.GetBuffer();
                ms.Flush();
                ms.Dispose();
            }
    
            return allBytes;
        }
    

    Above is the working code that results in a single pdf being created, and the rest of the files are being ignored. Any suggestions

    • Kent Munthe Caspersen
      Kent Munthe Caspersen almost 8 years
      Instead of allBytes = ms.GetBuffer(); try using allBytes = ms.ToArray(); The former method returns all data in the buffer, which may include uninitialized bytes / garbage. See the remarks of msdn.microsoft.com/en-us/library/…
  • confusedandamused
    confusedandamused almost 8 years
    Testing this right now - I've never tried passing types within a using statement, and currently receive an error "Type used in a using statement must me implicitly convertible to SystemIDisposible" Also where did you find documentation/use of copy.Adddocument() - it seems as though PdfSmartCopy doesn't contain a definition for it.
  • Chris Haas
    Chris Haas almost 8 years
    Are you using iTextSharp 4.1.6? If so this code won't work with that.
  • confusedandamused
    confusedandamused almost 8 years
    Ah I was on 4.x upgraded, and the function call worked. Currently it still seems to be overwriting each pdf I'm passing in via the bytes - could this be due to how I am passing in the byte array? I'm essentially taking each pdf, turning them into bytes, and placing them all into a List<byte[]> (which happens to be pdfByteContent) When calling File.WriteallBytes() each time I see the overwriting happening as well.
  • Euridice01
    Euridice01 almost 7 years
    @ChrisHaas, could you take a look at this question about itextSharp? stackoverflow.com/questions/45599357/… . Thank you so much in advance. I have a few questions that I would like clarified.
  • Justin T. Watts
    Justin T. Watts almost 7 years
    I'm seeing this does merge the pdfs together, but I lose any form fields in the AcroFields property of the document. Trying to find a fix for that. I'm use 5.x right now.
  • Venkataraman R
    Venkataraman R over 2 years
    add information about your answer. code only answers will not be very clear