1

I'm using c# and asp core 3 and have this right now.

string templatePath = Path.Combine(_webHostEnvironment.WebRootPath, @"templates\pdf\test.pdf");
Stream finalStream = new MemoryStream();

foreach (Info p in list)
{
    Stream pdfInputStream = new FileStream(path: templatePath, mode: FileMode.Open);
    Stream outStream = PdfService.FillForm(pdfInputStream, p);
    outStream.Position = 0;
    outStream.CopyTo(finalStream);
    outStream.Dispose();
    pdfInputStream.Dispose();
}

finalStream.Position = 0;
return File(finalStream, "application/pdf", "test.pdf"));

Right now I just get the first PDF when there should be 3. How to combine all the streams (PDF) created in the loop into 1 PDF? I'm using iTextSharp and using this as a guide to produce the FillForm code.

https://medium.com/@taithienbo/fill-out-a-pdf-form-using-itextsharp-for-net-core-4b323cb58459

Kirk Larkin
  • 84,915
  • 16
  • 214
  • 203
g00n3r
  • 135
  • 12

1 Answers1

3

You can't just combine PDF by adding them into a single stream :-)

You can add each PDF stream to an array and request ITextSharp to combine them and after that returning the newly created stream.

List<Stream> pdfStreams = new List<Stream>();

foreach(var item in list)
{
   // Open PDF + fill form
   pdfStreams.Add(outstream);
}

var newStream = Merge(pdfStreams);

return File(newStream)

I don't know ITextSharp but it seems you can merge PDFs : https://weblogs.sqlteam.com/mladenp/2014/01/10/simple-merging-of-pdf-documents-with-itextsharp-5-4-5/

Edit By the way, you could use "using" statement for stream (you wouldn't have to call dispose yourself) and I don't know how heavy are your PDFs but you should maybe consider to use the ".CopyToAsync".

Arcord
  • 1,724
  • 1
  • 11
  • 16
  • I did originally but I was getting an error that the stream was closed when i returned the stream to the client. This way was what worked. I'll revisit after and try using statement again once everything is working. Thank you for your help! – g00n3r Jun 18 '20 at 15:49
  • Also in the merge link you provided, is it possible to do it without saving the PDF requiring a temp folder to store it and just combine them in memory so there is no saving to the server? – g00n3r Jun 18 '20 at 15:58
  • 1
    Maybe this link can help you : https://stackoverflow.com/questions/6029142/merging-multiple-pdfs-using-itextsharp-in-c-net. – Arcord Jun 18 '20 at 20:51