3

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
asked Nov 2 at 9:05

1 Answer 1

6

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
Sign up to request clarification or add additional context in comments.

2 Comments

Also need to rewind the stream to Position = 0
or return File(ms.ToArray(), "application/pdf");

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.