在自定义 javafx 应用程序中创建 PDF

问题描述 投票:0回答:1

我正在开发一个 Javafx 项目,并已使用 IntelliJ 成功将其转换为 .dmg 文件。一个功能是,当按下按钮时,应创建 PDF 并将其保存在下载文件夹中。这在 IntelliJ 中运行程序时效果很好,但在程序的应用程序版本(打开 .dmg 文件后得到的版本)中不起作用。我正在使用 Apache PDFBox 创建 PDF。

这是保存PDF的方法,文档已经初始化并且不为空:

public void savePDF(String title) throws IOException{
   String home = System.getProperty("user.home");
   document.save(home+"/Downloads/"+title+".pdf");
   System.out.println("PDF created");
}

我尝试更改创建 PDF 文件的输出文件夹,但没有改变任何内容。

java javafx-8 pdfbox dmg
1个回答
0
投票

您应该考虑一种更清晰的方式来获取输出文件。我对 Apache PDFBox 本身没有任何经验,但您应该考虑添加基本的辅助代码来改进您的应用程序。

粗略的例子:

/// Other code here

// FileChooser needs a stage
// you need to set this somewhere,
// probably with a simple setter after instantiating your controller
private Stage stage;

private File getHomePath() {
    String homePath = System.getProperty("user.home");
    return new File(homePath);
}
private File getOutputFile(String suggestedName) {

    FileChooser fileChooser = new FileChooser();
    fileChooser.setInitialDirectory(getHomePath());
    fileChooser.setInitialFileName(suggestedName);
    fileChooser.setSelectedExtensionFilter(new FileChooser.ExtensionFilter("PDF files (*.pdf)", "*.pdf"));

    return fileChooser.showSaveDialog(stage);
}


public void  exportPdf(){

    File outputFile = getOutputFile("some.pdf");
    if (null == outputFile) {
        // optional: show dialog with a warning
        // about no output file selected
        return;
    }

    Thread exportThread = new Thread(() -> {

        try (FileOutputStream fileOutputStream = new FileOutputStream(outputFile)) {

             // The actual save() is here
             document.save(fileOutputStream);
        } catch (IOException e) {
            // This could be replaced with a warning dialog
            throw new RuntimeException(e);
        }

        Platform.runLater(() -> Notifications.create()
            .title("Finished")
            .text("PDF saved")
            .position(Pos.TOP_CENTER)
            .showInformation());
    });

    exportThread.start();
}

/// ...
/// more code

Notifications
类来自ControlsFX库。请随意替换为普通对话框。

© www.soinside.com 2019 - 2024. All rights reserved.