gpt4 book ai didi

java - 在 Java 中生成 PDF

转载 作者:行者123 更新时间:2023-11-29 09:42:17 25 4
gpt4 key购买 nike

我正在尝试用 Java 编写一个 PDF 文件来说出单词 hello neckbeards 但是当我运行我的程序时,Adobe Reader 打开但出现错误提示:

There was an error opening this document.
The file is already open or in use by another application.

这是我的代码:

import java.awt.Desktop;
import java.io.*;

public class count10 {

public static void main(String[] args) throws Exception {

File tempfile = File.createTempFile("report", ".pdf");
FileWriter pfile = new FileWriter(tempfile);
pfile.write("hello neckbeards");

Desktop dtop = null;

if (Desktop.isDesktopSupported()) {
dtop = Desktop.getDesktop();
}
if (dtop.isSupported(Desktop.Action.OPEN)){
String path = tempfile.getPath();
dtop.open(new File(path));
}
}
}

最佳答案

这里有很多错误:

  • 您正在编写纯文本。 Adobe Reader 将抛出错误,因为该文件不是有效的 PDF!
    要编写 PDF,请使用类似 iText 的库或 PDFBox。

  • 在您可以写入或读取文件之前,您打开从您的程序到文件的连接。
    因此,当您结束写入/读取文件时,不要忘记关闭连接,以便其他程序(例如 Adob​​e Reader)也可以读取该文件!要关闭文件,只需执行以下操作:

    pfile.close();
  • main 方法不应抛出任何异常。相反,如果发生错误,它必须被捕获并执行适当的操作(告诉用户,退出,...)。要读/写文件(或任何东西),这是推荐的结构:

    FileReader reader = null;
    try {
    reader = new FileReader("file.txt"); //open the file

    //read or write the file

    } catch (IOException ex) {
    //warn the user, log the error, ...
    } finally {
    if (reader != null) reader.close(); //always close the file when finished
    }
  • 最后的 if 有一个不好的地方。正确的代码是:

    if (Desktop.isDesktopSupported()) {
    Desktop dtop = Desktop.getDesktop();
    if (dtop.isSupported(Desktop.Action.OPEN)) {
    dtop.open(tempfile);
    }
    }

    另外,请注意,我调用 open 方法直接传递文件。
    无需复制它。

关于java - 在 Java 中生成 PDF,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5705383/

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