OpenPDF
OpenPDF copied to clipboard
Merge pdf files. Merged files are not released and cannot be deleted
I have a Java method that needs to read the PDF files inside a folder and create a file corresponding to the merge of all those inside the folder. Finally I have to delete the files and leave only the result in the folder. The problem is that once the final file is created, I can't delete all the other files used for the merge, as if it doesn't release them after use. I also tried to delete them manually from the file explorer, but I can't (as long as the application remains running). I'm using this version:(Java 11)
<dependency>
<groupId>com.github.librepdf</groupId>
<artifactId>openpdf</artifactId>
<version>1.4.1</version>
</dependency>
My Code:
File[] files = directory.listFiles();
if (files != null && files.length > 0) {
try (Document document = new Document()) {
PdfCopy copy = new PdfCopy(document, new FileOutputStream(fileName));
document.open();
for (File file : files) {
try (PdfReader reader = new PdfReader(file.getAbsolutePath())) {
for (int i = 1; i <= reader.getNumberOfPages(); i++) {
copy.addPage(copy.getImportedPage(reader, i));
}
copy.freeReader(reader);
}
}
}
}
if after this piece of code I try to delete all the files in the "files" list by calling the .delete() method, it doesn't work
I also tried removing the try wth resources and manually closing reader, document copy etc... I tried inserting the PdfCopy in the try with resources together with document, but nothing, I can't find a solution...