用Java生成PDF

nec*_*d69 1 java pdf io pdf-generation

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

There was an error opening this document.
The file is already open or in use by another application.
Run Code Online (Sandbox Code Playgroud)

这是我的代码:

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));
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Alb*_*dez 5

这里有很多错误:

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

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

    pfile.close();
    
    Run Code Online (Sandbox Code Playgroud)
  • 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
    }
    
    Run Code Online (Sandbox Code Playgroud)
  • 决赛if有一个糟糕的地方.正确的代码是:

    if (Desktop.isDesktopSupported()) {
        Desktop dtop = Desktop.getDesktop();
        if (dtop.isSupported(Desktop.Action.OPEN)) {
            dtop.open(tempfile);
        }
    }
    
    Run Code Online (Sandbox Code Playgroud)

    另外,请注意我调用直接open传递文件的方法. 没有必要复制它.