Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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*/  
like image 265
ArslanIqbal Avatar asked Aug 25 '15 12:08

ArslanIqbal


People also ask

How do I combine the contents of two PDF files?

Open Acrobat to combine files: Open the Tools tab and select "Combine files." Add files: Click "Add Files" and select the files you want to include in your PDF. You can merge PDFs or a mix of PDF documents and other files.

How do I make a collage of multiple PDFs into one?

Select the files you want to merge using the Acrobat PDF combiner tool. Reorder the files if needed. Click Merge files. Sign in to download or share the merged file.

Can you combine multiple files and file types into a single PDF?

Multiple files (optionally even different types of files) can be combined into a single Adobe PDF file by using Create PDF From Multiple Files. You can also use this command to combine multiple PDF files.

How do I combine two downloaded files?

Method 1: Use an online tool called PDF Joiner. Select the files you'd like to merge. You can put together up to 20 at once with PDF Joiner, so just hold down the Ctrl button while clicking on files so that you can select multiple. Click Open.


1 Answers

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.

like image 125
ArslanIqbal Avatar answered Nov 04 '22 06:11

ArslanIqbal