Pinch
Pinch

Reputation: 4207

How to Merge two Document objects using itextsharp

I have two Document objects

How does one Merge these two Document objects using itextsharp?

Upvotes: 0

Views: 1957

Answers (2)

Pinch
Pinch

Reputation: 4207

A little more easier on the palate:

You have to take the PDF Document memory streams and merge them together!

Here is a simple function that will accomplish this!

        public MemoryStream MemoryStreamMerger(List<MemoryStream> streams)
        {

            MemoryStream OurFinalReturnedMemoryStream;
            using (OurFinalReturnedMemoryStream = new MemoryStream())
            {
                //Create our copy object
                PdfCopyFields copy = new PdfCopyFields(OurFinalReturnedMemoryStream);

                //Loop through each MemoryStream
                foreach (MemoryStream ms in streams)
                {
                    //Reset the position back to zero
                    ms.Position = 0;
                    //Add it to the copy object
                    copy.AddDocument(new PdfReader(ms));
                    //Clean up
                    ms.Dispose();
                }
                //Close the copy object
                copy.Close();

                //Get the raw bytes to save to disk
                //bytes = finalStream.ToArray();
            }
            return new MemoryStream(OurFinalReturnedMemoryStream.ToArray());

        }

Upvotes: 0

Pinch
Pinch

Reputation: 4207

As per Mr. Haas (with the help of his code somewhere on SO),

"Unfortunately, to the best of my knowledge, there is no way to merge two Document objects. These objects are helper classes that abstract away the intricacies of the PDF file format. One of the "costs" of these abstractions is that you are limited to a single document. However, as others have pointed out, you can create separate PDFs (even in-memory) and then merge them."

So i did just that:

I used the PdfCopyFields object.

MemoryStream realfinalStream = new MemoryStream();
MemoryStream[] realstreams = { stream,new MemoryStream(finalStream.ToArray()) };

using (realfinalStream)
       {
           //Create our copy object
           PdfCopyFields copy = new PdfCopyFields(realfinalStream);

           //Loop through each MemoryStream
           foreach (MemoryStream ms in realstreams)
           {
               //Reset the position back to zero
               ms.Position = 0;
               //Add it to the copy object
               copy.AddDocument(new PdfReader(ms));
               //Clean up
               ms.Dispose();
           }
           //Close the copy object
           copy.Close();
       }
return File(new MemoryStream(realfinalStream.ToArray()), "application/pdf","hello.pdf");

FYI

new MemoryStream(realfinalStream.ToArray())

I did that because the MemoryString was closed.

Upvotes: 1

Related Questions