Home > Software engineering >  ITextSharp - Cannot Open .pdf because it is being used by another process?
ITextSharp - Cannot Open .pdf because it is being used by another process?

Time:01-04

I am having a issue where I write to a pdf file and then close it and later on open it up again and try to read it.

I get "Cannot Open .pdf because it is being used by another process?"

var path = // get path
Directory.CrateDirctory(path);

using(var writer = new PdfWriter(path, //writer properties)){
    var reader = new PdfReader(//template);
    var pdfDoc = new PdfDcoument(reader, writer);
    writer.SetCloseStream(false)
    // some code to fill in the pdf
   
   reader.Close();
   pdfDoc.Close();
}

//later in code

using(var stream = new MemoryStream(File.ReadAllBytes(//the file that I crated above)))
{
  // do some stuff here
}

I get the error right on the using statement above. I thought all the streams for creating the pdf are closed at this point but it seems like it is not.

CodePudding user response:

The issue is with the line writer.SetCloseStream(false);. That is telling it to not close the stream when the writer is closed. Since the stream is left open you will get an IOException when you create another stream for reading. Remove this line or set to true to resolve the issue.

If you need to keep the stream open for whatever reason, like issues with flushing the write buffer too soon when PdfWriter is closed. Then you can get access to the write stream and close it later when you are ready to read it. Something like this:

        Stream outputStream;
        using (var writer = new PdfWriter(path)){
            writer.SetCloseStream(false);
            // do whatever you need here
            outputStream = writer.GetOutputStream();
        }

        // do whatever else you need here

        // close the stream before creating a read stream
        if(null != outputStream) { 
            outputStream.Close();
        }

        using (var stream = new MemoryStream(File.ReadAllBytes(path)))
        {
            // do some stuff here
        }
  • Related