Reputation: 9
I have a series of PDF byte arrays in a arraylist files that i wish to concatenate into one file,
Currently when the PDF application tries to open the file is it corrupted:
foreach (byte[] array in files)
{
using (Stream s = new MemoryStream(downloadbytes))
{
s.Write(array, 0, array.Length);
}
}
downloadbytes is the resultant concatenated array of bytes below is another implementation which also failed
foreach (byte[] array in files)
{
System.Buffer.BlockCopy(array, 0, downloadbytes, offset, array.Length);
offset += array.Length;
}
any pointers?
Upvotes: 0
Views: 2434
Reputation: 630
You will likely need to use a PDF library to concatenate the files. Take a look at iTextSharp.
Upvotes: 2
Reputation: 15794
You can't just merge the bytes together - you need a 3rd party library, for instance PDFSharp. PDFSharp has a tutorial on merging documents:
http://www.pdfsharp.net/wiki/CombineDocuments-sample.ashx
Upvotes: 1
Reputation: 38434
You will need to use a PDF handling tool to do this job as PDF files cannot be simply concatenated to form a single PDF. PDF files follow a specification, you can't just join them together. Think about XML, you cannot just join XML files together to form a single XML file.
Upvotes: 1
Reputation: 1500425
If you've got byte arrays, you can just write them directly:
using (Stream output = File.OpenWrite("output.pdf"))
{
foreach (byte[] array in files)
{
output.Write(array, 0, array.Length);
}
}
That will effectively concatenate the byte arrays... but if each byte array represents an individual, complete PDF file you shouldn't expect the result of the concatenation to be a single valid PDF file. Combining PDFs isn't just a case of writing one after the other. You'll need to use a PDF library (e.g. iText) to do that.
To put it another way: what do you get if you build 5 two-bedroom houses next to each other? Not a ten-bedroom mansion...
Upvotes: 2
Reputation: 1038780
using (var result = File.OpenWrite("result.bin"))
{
foreach (byte[] array in files)
{
result.Write(array, 0, array.Length);
}
}
Also you talk about PDFs. Don't expect that if you have a series of PDF files and concatenate the binaries you will receive a valid PDF file by just adding the bytes. If this is what you want you may take a look at iTextSharp which allows you to concatenate PDFs.
Upvotes: 1