How to create a new PDF file if a file name already exists?
I need to create simple receipts which contain user details such as a name, a fare and a number. Whenever a new user inputs data in the main form, the following code just overwrites the data of the first user in the PDF file:
Document document = new Document(); PdfWriter.getInstance(document, new FileOutputStream("C://sample.pdf")); document.open(); // adding content as Paragraph objects document.close();
Posted on StackOverflow on Mar 27, 2015 by Gelly
Almost all the methods you might need to achieve what you want can be found in the Java API documentation for the File class
You want to create a unique file that starts with sample
and ends with pdf
. To achieve this, you can use the createTempFile()
method. This question was already answered on StackOverflow 6 years ago: What is the best way to generate a unique and short file name in Java?
Suppose that you really want to have incremental numbers in your file name, e.g. sample0001.pdf, sample0002.pdf, sample0003.pdf and so on, then you can use the list()
method. This returns an array of String
values with the names of all files in a directory. I suggest that you use a FilenameFilter
so that you only get the PDF files starting with sample
. You could then sort these names to find the name with the highest number. See How to list latest files in a directory using FileNameFilter? to find out how to create such a filter. Once you have the file name with the highest number, it's only a matter of String
manipulation to create a new file name. Use that file name (or that File
instance) when you define the OutputStream
. As you can see, this answer doesn't mention iText anywhere and although the extension of the files we create or list is .pdf
, it has nothing to do with PDF or PDF generation either. It's a pure Java question.
Click How to create a new PDF file if a file name already exists? if you want to see how to answer this question in iText 5.