Search code examples
c#itextmemorystream

How to Merge two memory streams containing PDF file's data into one


I am trying to read two PDF files into two memory streams and then return a stream that will have both stream's data. But I don't seem to understand what's wrong with my code.

Sample Code:

string file1Path = "Sampl1.pdf";
string file2Path = "Sample2.pdf";
MemoryStream stream1 = new MemoryStream(File.ReadAllBytes(file1Path));
MemoryStream stream2 = new MemoryStream(File.ReadAllBytes(file2Path));
stream1.Position = 0;
stream1.Copyto(stream2);
return stream2;   /*supposed to be containing data of both stream1 and stream2 but contains data of stream1 only*/  

Solution

  • It appears in case of PDF files, the merging of memorystreams is not the same as with .txt files. For PDF, you need to use some .dll as I used iTextSharp.dll (available under the AGPL license) and then combine them using this library's functions as follows:

    MemoryStream finalStream = new MemoryStream();
    PdfCopyFields copy = new PdfCopyFields(finalStream);
    string file1Path = "Sample1.pdf";
    string file2Path = "Sample2.pdf";
    
    var ms1 = new MemoryStream(File.ReadAllBytes(file1Path));
    ms1.Position = 0;
    copy.AddDocument(new PdfReader(ms1));
    ms1.Dispose();
    
    var ms2 = new MemoryStream(File.ReadAllBytes(file2Path));
    ms2.Position = 0;
    copy.AddDocument(new PdfReader(ms2));
    ms2.Dispose();
    copy.Close();
    

    finalStream contains the merged pdf of both ms1 and ms2.