How to close a PDF file to recreate it? (File in use problem)

Tags: existing filefile in useiText 5

I have the Java application that can create a PDF file. For example, I create a simple file from my program and I also wrote some code to open the file as soon as it's created correctly. However, if I want to run the code again, I must close the open file before I recreate it. If I don't close the file I have this error: Archivio_Etichette_12-4-2015.pdf (Impossibile accedere al file. Il file è utilizzato da un altro processo) How can I fixed this problem?

Posted on StackOverflow on Apr 12, 2015 by bircastri

You need to close the file. The problem is similar to trying to delete or rename a file that is open: if you're working on Windows, Windows will show this error:

"File in use" dialog
"File in use" dialog

You are experiencing the exact same problem: in this case, I tried to rename a file called hello.pdf in Windows Explorer. However, this action could not be completed because the file was open in Adobe Acrobat. Tools such as Adobe Reader and Adobe Acrobat need random file access to the file and will therefore lock that file so that no other process can remove, rewrite, rename that file.

The solution is also shown in the dialog box: Close the file and try again. You are trying to do something that is impossible (and that is not related or limited to you using iText).


When working on an iText project, I experience the same problem you describe very often: I write some code, run it, look at the resulting PDF, change the code, run it, and then get the same exception you get. To avoid this, I often create files that have a timestamp in their name. E.g. hello-20150411163400.pdf, and then when I run the same code 30 seconds later hello-20150411163430.pdf and so on (the filename is created based on the current date and time). This way, I can avoid that exception.