PDF是数字文档世界中的主要文件格式之一。PDF格式允许将文件作为附件嵌入PDF文件中。这些附件类似于您添加到电子邮件中的附件。为了自动执行PDF附件操作,本文提供了一些使用Java在PDF文件中添加和删除附件的简单方法。
- 使用Java获取PDF附件信息
- 在Java中将附件添加到PDF
- 在Java中从PDF删除附件
下载Aspose.PDF for Java(qun:761297826)https://www.evget.com/product/4202/download
使用Java获取PDF附件信息
首先,让我们检查一下如何检索PDF文件中的附件信息。该信息包含附件的名称,描述,MIME类型和其他参数,例如校验和,修改日期等。以下是在PDF文件中获取有关附件信息的步骤。
- 使用Document类加载PDF文件。
- 使用FileSpecification类通过Document.getEmbeddedFiles()。get_Item(int)方法检索PDF附件。
- 使用FileSpecification对象检索附件的信息。
下面的代码示例演示如何使用Java获取PDF附件的信息。
// Open document Document pdfDocument = new Document("input.pdf"); // Get particular embedded file FileSpecification fileSpecification = pdfDocument.getEmbeddedFiles().get_Item(1); // Get the file properties System.out.println("Name:-" + fileSpecification.getName()); System.out.println("Description:- " + fileSpecification.getDescription()); System.out.println("Mime Type:-" + fileSpecification.getMIMEType()); // Check if parameter object contains the parameters if (fileSpecification.getParams() != null) { System.out.println("CheckSum:- " + fileSpecification.getParams().getCheckSum()); System.out.println("Creation Date:- " + fileSpecification.getParams().getCreationDate()); System.out.println("Modification Date:- " + fileSpecification.getParams().getModDate()); System.out.println("Size:- " + fileSpecification.getParams().getSize()); }
在Java中将附件添加到PDF
以下是将附件添加到PDF文档的步骤。
- 使用Document类加载PDF文件。
- 创建FileSpecification类的对象以加载附件文件。
- 使用Document.getEmbeddedFiles()。add(FileSpecificatio)方法添加附件。
- 使用Document.save(String)方法保存PDF文件。
以下代码示例显示了如何使用Java将附件添加到PDF。
// Open a document Document pdfDocument = new Document("input.pdf"); // Set up a new file to be added as attachment FileSpecification fileSpecification = new FileSpecification("sample.txt", "Sample text file"); // Add an attachment to document's attachment collection pdfDocument.getEmbeddedFiles().add(fileSpecification); // Save the updated document pdfDocument.save("output.pdf");
在Java中从PDF删除附件
可以使用名称删除特定附件,也可以一次删除所有附件。以下是从PDF文档中删除附件的步骤。
- 使用Document类加载PDF文件。
- 使用Document.getEmbeddedFiles()。delete()和Document.getEmbeddedFiles()。delete(String)分别删除所有或特定附件。
- 使用Document.save(String)方法保存PDF文件。
以下代码示例显示了如何使用Java删除PDF附件。
// Open a document Document pdfDocument = new Document("input.pdf"); // Delete all attachments pdfDocument.getEmbeddedFiles().delete(); // Save the updated file pdfDocument.save("output.pdf");