I have multiple PDFs in the form of MemoryStreams and I need to merge the MemoryStreams so that they are one long PDF and send them to the browser.
I have created the following function using iText7 which takes a list of MemoryStreams which are assumed to be PDF's and the output is a MemoryStream of the concatenated PDFs
public static MemoryStream PdfCat(List<MemoryStream> pdfs)
{
ByteArrayOutputStream baos = new ByteArrayOutputStream();
using(PdfDocument applicationPdf = new PdfDocument(new PdfWriter(baos)))
{
PdfMerger merger = new PdfMerger(applicationPdf);
// add every document to the empty pdf
foreach (MemoryStream pdfMemStream in pdfs)
{
using (PdfDocument pdf = new PdfDocument(new PdfReader(pdfMemStream)))
{
merger.Merge(pdf, 1, pdf.GetNumberOfPages());
}
}
baos.Position = 0;
merger.Close();
}
return new MemoryStream(baos.ToArray());
}
I am trying to send the PDF to the browser in a controller using the following:
MemoryStream application = FileUtils.PdfCat(applicationPdfs);
return new FileStreamResult(application, "application/pdf");
Where applicationPdfs is a List<MemoryStream>.
The button in my HTML looks like this:
<a href="~/Report/Index/@Model.id" target="_blank">View all attachments</a>
The issue is that when I click the "View all attachments" button, I get the following error in the browser:

I was able to save the PDF locally and view it that way, so the PDF is being merged properly. Does anyone know what the error means and how I can fix it?
Update: It seems that this only works when I use FireFox as my browser. For some reason the error only occurs with IE and Chrome.
Remove the line
baos.Position = 0;
or at least move it after the using(PdfDocument...) {...} block.
When closing the merger or the underlying document there still some data are written to the output stream, and by changing the stream position before closing, you make those data overwrite the start of the output (where the %PDF-... header is) instead of being appended at the end.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With