Apache PDFBox 拒绝打开临时创建的 PDF 文件

Apache PDFBox refuses to open temporary created PDF file

我正在创建用于查看 PDF 文件的桌面 JavaFX 应用程序。 PDF 位于资源文件夹中。我将资源文件作为流读取,然后创建临时文件并使用它将内容转换为图像并显示到 ImageView 中。

       currentPdf =  new File("current.pdf");
        if (!currentPdf.exists()) {
            // In JAR
            InputStream inputStream = ClassLoader.getSystemClassLoader()
                    .getResourceAsStream("PDFSample.pdf");
            // Copy file
            OutputStream outputStream;
            try {
                outputStream = new FileOutputStream(currentPdf);
            } catch (FileNotFoundException e) {
                throw new RuntimeException(e);
            }
            byte[] buffer = new byte[1024];
            int length;
            try {
                while ((length = inputStream.read(buffer)) > 0) {
                    outputStream.write(buffer, 0, length);
                }
                outputStream.close();
                inputStream.close();
            } catch(IOException e) {
                throw new RuntimeException(e);
            }
        }

问题是:当我使用

创建常规文件时
currentPdf =  new File("current.pdf");

一切都按预期工作(我在 jar 所在的目录中创建了 current.pdf)。但我希望文件在系统临时文件夹中创建并在退出应用程序时删除。我试过这个:

try {
    currentPdf =  File.createTempFile("current",".pdf");
} catch (IOException e) {
    throw new RuntimeException(e);
}
currentPdf.deleteOnExit();//also tried to comment this line

并得到异常:

Caused by: java.io.IOException: Error: End-of-File, expected line
    at org.apache.pdfbox.pdfparser.BaseParser.readLine(BaseParser.java:1517)
    at org.apache.pdfbox.pdfparser.PDFParser.parseHeader(PDFParser.java:360)
    at org.apache.pdfbox.pdfparser.PDFParser.parse(PDFParser.java:186)
    at org.apache.pdfbox.pdmodel.PDDocument.load(PDDocument.java:1227)
    at org.apache.pdfbox.pdmodel.PDDocument.load(PDDocument.java:1194)
    at org.apache.pdfbox.pdmodel.PDDocument.load(PDDocument.java:1165)
    at ua.com.ethereal.pdfquiz.Controller.getPdfPageAsImage(Controller.java:147)

在这个方法中:

@SuppressWarnings("unchecked")
public static Image getPdfPageAsImage(File pdfFile, int pageNum) {
    Image convertedImage;
    try {
        PDDocument document = PDDocument.load(pdfFile);
        List<PDPage> list = document.getDocumentCatalog().getAllPages();
        PDPage page = list.get(pageNum);
        BufferedImage image = page.convertToImage(BufferedImage.TYPE_INT_RGB, 128);
        convertedImage = SwingFXUtils.toFXImage(image, null);
        document.close();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
    return convertedImage;
}

希望能帮助解决这个问题或指导我直接从 jar 中读取文件以避免创建临时副本。

如何创建临时文件?

通常的方法在文件系统中创建一个空文件。这会触发你的逻辑:

if (!currentPdf.exists()) {

该检查应该是为了避免覆盖现有文件,但在这种情况下,您必须删除它。实际上,您跳过 PDF 生成代码并尝试读取一个空文件。