0

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);
}

Amedee Van Gasse
  • 7,280
  • 5
  • 55
  • 101
Geo Tech
  • 307
  • 3
  • 11

1 Answers1

1

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);
        }
    }
alcan
  • 31
  • 1
  • 8
omido
  • 76
  • 5
  • When I use this, it's appear that save a file. But actually it's save only temporally file in root file – Geo Tech May 19 '20 at 10:26
  • @GeoTech `getSelecteFile()`should return the value you need. I've updated my answer to clarify this, or do I miss something? What do you mean with 'temporally file in the root file'? – omido May 19 '20 at 12:03
  • It's save file named "Supplier Details Report.pdf" in my root folder.And update every time when save a file. – Geo Tech May 19 '20 at 12:41
  • Do you pass the `File` from `getSelectedFile()` into the `FileOutputStream`? (There was an typo in my code. Should be fileToSave instead of file) – omido May 19 '20 at 12:49