Search code examples
c#asp.net-core-mvcitext

iTextSharp Created PDF is still in use


If i create a pdf with the given source-code, i have the problem that i can not open the pdf-document for example in "adobe-acrobat" because it says that it is still in use by another process. What i am missing in my code to release the lock?

var a = Guid.NewGuid();

Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 10f, 0f);

PdfWriter writer2 = PdfWriter.GetInstance(pdfDoc, new FileStream(a.ToString()+".pdf", FileMode.Create));
writer2.SetFullCompression();
writer2.CloseStream = true;

iTextSharp.text.Image img = iTextSharp.text.Image.GetInstance(AppContext.BaseDirectory + "Ehrungsantrag.png");
img.SetAbsolutePosition(0, 0);
img.ScaleAbsoluteHeight(pdfDoc.PageSize.Height);
img.ScaleAbsoluteWidth(pdfDoc.PageSize.Width);
pdfDoc.Open();
pdfDoc.NewPage();
pdfDoc.Add(img);

pdfDoc.Close();
writer2.Close();

Solution

  • The error was not closed FileStream. Also as @Amy already mentioned, you need be sure that your clean up code is executed, for example like this:

    Document pdfDoc = null;
    PdfWriter writer2 = null;
    System.IO.FileStream fs = null; // <- create the FileStream
    
    try
    {
       var a = Guid.NewGuid();
       pdfDoc = new Document(PageSize.A4, 10f, 10f, 10f, 0f);
    
       fs =  new FileStream(a.ToString()+".pdf", FileMode.Create);
       writer2 = PdfWriter.GetInstance(pdfDoc, fs);
       writer2.SetFullCompression();
       writer2.CloseStream = true;
    
       iTextSharp.text.Image img = iTextSharp.text.Image.GetInstance(AppContext.BaseDirectory + "Ehrungsantrag.png");
       img.SetAbsolutePosition(0, 0);
       img.ScaleAbsoluteHeight(pdfDoc.PageSize.Height);
       img.ScaleAbsoluteWidth(pdfDoc.PageSize.Width);
    
       pdfDoc.Open();
       pdfDoc.NewPage();
       pdfDoc.Add(img);
    }
    finally
    {
            pdfDoc.Close();
            pdfDoc = null;
    
            //writer2.Close(); 
    
           // That was the eroor -> always close open filehandles explicity !
           fs.Close(); 
    }