I want to allow the user to choose the PDF file save location and filename. I'm generating PDF by using iText library. In the code I used, it's saving the PDF file in a predefined name and root folder.
try {
Document document = new Document();
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("Supplier Details Report.pdf"));
document.open();
//code for generate pdf
document.close();
JOptionPane.showMessageDialog(null, "PDF Saved");
} catch(Exception e) {
JOptionPane.showMessageDialog(null, e);
}
As I see in your code you're using Swing. You can use the JFileChooser class. It has some basic file chooser layouts. One of them is a save dialog.
JFrame parentComponent = new JFrame();
JFileChooser fileChooser= new JFileChooser();
// Some init code, if you need one, like setting title
int returnVal = fileChooser.showOpenDialog(parentComponent)
if ( returnVal == JFileChooser.APPROVE_OPTION) {
File fileToSave = fileChooser.getSelectedFile();
try{
Document document = new Document();//library: itextpdf
PdfWriter writer =PdfWriter.getInstance(document, new FileOutputStream(fileToSave ));
document.open();
//code for generate pdf
document.close();
JOptionPane.showMessageDialog(null, "PDF Saved");
}
catch(Exception e){
JOptionPane.showMessageDialog(null, e);
}
}