I use the Itext5 library to merge PDFs. Once the merge is complete I want to be able to delete the PDFs, but I cannot delete them yet I have used reader.close(). My Code :
public static void main(String[] args) {
System.out.println("CONCAT PDF");
pdfConcat2("C:\\Users\\File1.pdf",
"C:\\Users\\File2.pdf",
"C:\\Users\\File_FINAL.pdf");
System.out.println("-------------ACTION DELETE");
if (FileTools.deleteFile("C:\\Users\\File1.pdf")) {
System.out.println("DELETE PDF OK");
} else {
System.out.println("DELETE PDF NOK");
}
if (FileTools.deleteFile("C:\\Users\\File2.pdf")) {
System.out.println("DELETE PDF OK");
} else {
System.out.println("DELETE PDF NOK");
}
}
public static void pdfConcat2(String pathFile1, String pathFile2, String destinationPDF) {
//
Document document = null;
FileOutputStream outputStream = null;
PdfCopy copy = null;
PdfReader reader = null;
//
try {
document = new Document();
outputStream = new FileOutputStream(destinationPDF);
copy = new PdfSmartCopy(document, outputStream);
document.open();
// for (int i = 0; i < mergeFile.size(); i++) {
reader = new PdfReader(pathFile1);
copy.addDocument(reader);
copy.freeReader(reader);
reader.close();
reader = new PdfReader(pathFile2);
copy.addDocument(reader);
copy.freeReader(reader);
reader.close();
// }
outputStream.flush();
document.close();
outputStream.close();
copy.flush();
copy.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (DocumentException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
I always have the same result : DELETE PDF NOK
Do you have an idea ? Thanks
I have contourned the problem, adding FileinputStream in the PDFReader. There are a problem with Itext5 since java9.
public static void pdfConcat2(String pathFile1, String pathFile2, String destinationPDF) {
//
Document document = null;
FileOutputStream outputStream = null;
PdfCopy copy = null;
PdfReader reader = null;
//
try {
document = new Document();
outputStream = new FileOutputStream(destinationPDF);
copy = new PdfSmartCopy(document, outputStream);
document.open();
reader = new PdfReader(new FileInputStream(pathFile1));
copy.addDocument(reader);
copy.freeReader(reader);
reader.close();
reader = new PdfReader(new FileInputStream(pathFile2));
copy.addDocument(reader);
copy.freeReader(reader);
reader.close();
outputStream.flush();
document.close();
outputStream.close();
copy.flush();
copy.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (DocumentException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}