gpt4 book ai didi

java - 如何打开 PDF 文件

转载 作者:行者123 更新时间:2023-12-01 18:05:14 25 4
gpt4 key购买 nike

我想打开一个 pdf 文件并在单击按钮时将其显示在新窗口中我尝试了这个,但它不起作用:

Button btn = new Button();

File file=new File("Desktop/Test.pdf");
btn.setText("Open");

btn.setOnAction(new EventHandler<ActionEvent>() {

public void handle(ActionEvent event) {

try {
desktop.open(file);
} catch (IOException ex) {
Logger.getLogger(Exemple.class.getName())
.log(Level.SEVERE, null, ex);
}
}
});

最佳答案

您可以尝试以下方式打开 PDF 文件:

File file = new File("C:/Users/YourUsername/Desktop/Test.pdf");
HostServices hostServices = getHostServices();
hostServices.showDocument(file.getAbsolutePath());

如果您想使用 FileChooser,请使用:

btn.setOnAction(new EventHandler<ActionEvent>()
{
@Override
public void handle(ActionEvent event)
{
FileChooser fileChooser = new FileChooser();

// Set Initial Directory to Desktop
fileChooser.setInitialDirectory(new File(System.getProperty("user.home") + "\\Desktop"));

// Set extension filter, only PDF files will be shown
FileChooser.ExtensionFilter extFilter = new FileChooser.ExtensionFilter("PDF files (*.pdf)", "*.pdf");
fileChooser.getExtensionFilters().add(extFilter);

// Show open file dialog
File file = fileChooser.showOpenDialog(primaryStage);

//Open PDF file
HostServices hostServices = getHostServices();
hostServices.showDocument(file.getAbsolutePath());
}
});

关于java - 如何打开 PDF 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36960844/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com