【问题标题】:How to allow the user to choose save location and filename如何允许用户选择保存位置和文件名
【发布时间】:2020-05-19 07:00:48
【问题描述】:

我想允许用户选择 PDF 文件的保存位置和文件名。我正在使用 iText 库生成 PDF。在我使用的代码中,它将 PDF 文件保存在预定义的名称和根文件夹中。

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

【问题讨论】:

    标签: java swing jfilechooser filechooser


    【解决方案1】:

    正如我在您的代码中看到的,您使用的是 Swing。 您可以使用JFileChooser 类。 它有一些基本的文件选择器布局。其中之一是保存对话框。

        JFrame parentComponent = new JFrame();
        JFileChooser fileChooser= new JFileChooser();
        // Some init code, if you need one, like setting title
        int returnVal = fileChooser.showOpenDialog(parentComponent)
        if ( returnValue == == JFileChooser.APPROVE_OPTION) {
            File fileToSave = fileChooser.getSelectedFile();
            try{
                Document document = new Document();
                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);
            }
        }
    

    【讨论】:

    • 当我使用它时,似乎保存了一个文件。但实际上它只是将临时文件保存在根文件中
    • @GeoTech getSelecteFile()应该返回您需要的值。我已经更新了我的答案以澄清这一点,还是我错过了什么? “根文件中的临时文件”是什么意思?
    • 它在我的根文件夹中保存名为“Supplier Details Report.pdf”的文件。每次保存文件时都会更新。
    • 您是否将FilegetSelectedFile() 传递到FileOutputStream? (我的代码中有错字。应该是 fileToSave 而不是 file)
    猜你喜欢
    • 1970-01-01
    • 2013-03-27
    • 1970-01-01
    • 2023-03-11
    • 1970-01-01
    • 2016-05-27
    • 2016-04-08
    • 2011-05-19
    • 1970-01-01
    相关资源
    最近更新 更多