I'm trying to copy pages from an existing PDF to a new one and return it. I'm writing to the new PDF with memory, but it returns an error stating
Cannot access a closed Stream.
Here is my code:
var ms = new MemoryStream();
using PdfReader pdfReader = new PdfReader(pdfStream);
using PdfDocument pdfDocument = new PdfDocument(pdfReader);
using PdfWriter pdfWriter = new PdfWriter(ms);
using PdfDocument newDocument = new PdfDocument(pdfWriter);
pdfDocument.CopyPagesTo(1, 2, newDocument);
return File(ms, "application/pdf");
wohlstad
35.7k18 gold badges77 silver badges110 bronze badges
1 Answer 1
You have to call iText.IO.Source.OutputStream<T>.SetCloseStream(false) to prevent the Stream instance from disposing by default when disposing the OutputStream.
using PdfWriter pdfWriter = new PdfWriter(ms);
pdfWriter.SetCloseStream(false);
answered Nov 2 at 9:22
Yong Shun
54.4k6 gold badges38 silver badges66 bronze badges
Sign up to request clarification or add additional context in comments.
2 Comments
Charlieface
Also need to rewind the stream to
Position = 0Sir Rufo
or
return File(ms.ToArray(), "application/pdf");Explore related questions
See similar questions with these tags.
default