java - 如何允许用户选择保存位置和文件名
问题描述
我想让用户选择 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);
}
解决方案
正如我在您的代码中看到的那样,您正在使用 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);
}
}
推荐阅读
- ms-access - LibreOffice Base - 如何输入合并数据?
- kotlin - X 轴与 Y 轴 Kotlin
- javascript - 将文件的表单数据从 javascript 提交到 Laravel 中的控制器函数
- android - Android:无法同步旧项目,无法解析“:app@debug/compileClasspath”的依赖关系:无法解析错误
- php - PHP中不推荐使用的构造函数的问题
- hierarchy - 如何从表中删除非分层数据
- swiftui - 在 SwiftUI 中,每当列表的底层数据源从层次结构中远处的视图更新时,就会触发列表视图刷新
- c# - 获取和设置条件值
- c++ - Hexadecimal in [] operator
- powershell - New-AzResourceGroupDeployment:无法检索 cmdlet 的动态参数