我正在开发一个 Java 应用程序,用于捕获网站屏幕截图,将其转换为 PDF,然后尝试删除临时文件。我遇到一个问题,即 PDF 文件在创建后无法删除,即使我在 Document 对象上调用 .close() 也是如此。这是我的代码的相关部分:
void createDesktopPrint(String commonPath, String formattedDate, String url, String URI, int i) throws IOException, DocumentException, InterruptedException {
// ... (code for taking screenshot with Selenium and AShot)
String pdfTargetCreationName = commonPath + "\\pdfDesktop" + "-" + URI + "-" + formattedDate + ".pdf";
Document document = new Document();
PdfWriter.getInstance(document, new FileOutputStream(pdfTargetCreationName));
document.setPageSize(new com.itextpdf.text.Rectangle(bufferedImage.getWidth(), bufferedImage.getHeight()));
document.setMargins(0, 0, 0, 0);
document.open();
Image img = Image.getInstance(pngTargetCreationWithName);
img.scaleToFit(bufferedImage.getWidth(), bufferedImage.getHeight());
document.add(img);
document.close(); // Attempting to close the document here
driver.quit();
}
// In main method, after generating PDFs:
void deleteFiles(String... filePaths) {
for (String filePath : filePaths) {
File file = new File(filePath);
if (file.exists()) {
boolean deleted = file.delete();
if (!deleted) {
System.out.println("Failed to delete: " + filePath);
}
}
}
}
// Usage
sc.deleteFiles(desktopPngPath, mobilePngPath, desktopPdfPath, mobilePdfPath);
PNG 文件已成功删除,但 PDF 文件仍然存在且无法删除。即使尝试通过 Windows 资源管理器手动删除 PDF 文件时,我也会收到一条错误消息,指出该文件已在“Java(TM) Platform SE Binary”中打开。
我确保在将图像添加到 PDF 后调用 document.close(),我认为这会释放文件锁。然而,这似乎并不能解决问题。 PDF 保持锁定且不可删除。
我错过了什么?如何确保 PDF 文件被正确关闭并在不再需要后可以删除?
保存您获得的 PDFWriter 实例,并在完成文档编写后将其关闭。
示例
PdfWriter writer = PdfWriter.getInstance(..);
...
writer.close();
如果您的 itext 版本支持的话,最好使用 try-with-resource。