What happens to the file if you create an object with a document and don't save it?

If you look at the code below, the file name was inserted when creating the document object.
If you don’t save it after performing logic, the file will not be deleted, so I wonder if you must save it.

Code

public Document mergePdf(Document mergedPdf, String pdfPath){
Document doc = new Document(pdfPath);
mergedPdf.getPages().add(doc.getPages());
//doc.save(pdfPath);
return mergedPdf;
}

@daesunglee

Would you please explain a bit more about the inquiry? The document object will save the updated Page collection after the code that you have shared even without saving it. Please share if you are facing some issue or what is the question really about?

I tested it on a web application.
When saving function is used, pdfPath has a file:
It was deleted when I deleted it.
However, the file was not deleted when the save function was not used.

save function not used file not delete.JPG (418.4 KB)
save function used file delete1.JPG (277.6 KB)
save function used file delete2.JPG (432.1 KB)

@daesunglee

This behavior of the API is expected. The API keeps resources in the memory until the document is saved. In your case, when you add the document pages into the destination PDF, API keeps those pages in the memory until the destination document is saved. In other words, the pages from the source PDF will remain associated with the former document until the new document is saved. The same behavior of the API can be noticed in the case of using different fonts and images.

Then, should I save when I create a Document?

Document doc = new Document(fileName);
doc.save(fileName); //Essential

@daesunglee

You should save the document when all processing is done. In case you want to delete the PDF file after using it, you can delete it after saving its pages into another document.

Thank you for your answer.

1 Like