pom
xml
<dependency>
<groupId>org.apache.pdfbox</groupId>
<artifactId>pdfbox</artifactId>
<version>2.0.24</version>
</dependency>
读取属性
java
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDDocumentInformation;
import java.io.File;
import java.io.IOException;
public class ReadPDFProperties {
public static void main(String[] args) {
try {
// 加载PDF文件
File file = new File("example.pdf");
PDDocument document = PDDocument.load(file);
// 获取PDF文档信息
PDDocumentInformation info = document.getDocumentInformation();
// 读取属性
String title = info.getTitle();
String author = info.getAuthor();
String subject = info.getSubject();
String keywords = info.getKeywords();
String creator = info.getCreator();
String producer = info.getProducer();
String creationDate = info.getCreationDate().toString();
String modificationDate = info.getModificationDate().toString();
String trapped = info.getTrapped();
// 输出属性信息
System.out.println("Title: " + title);
System.out.println("Author: " + author);
System.out.println("Subject: " + subject);
System.out.println("Keywords: " + keywords);
System.out.println("Creator: " + creator);
System.out.println("Producer: " + producer);
System.out.println("Creation Date: " + creationDate);
System.out.println("Modification Date: " + modificationDate);
System.out.println("Trapped: " + trapped);
// 关闭文档
document.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
设置属性
java
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDDocumentInformation;
import java.io.File;
import java.io.IOException;
public class PDFPropertiesExample {
public static void main(String[] args) {
try (PDDocument document = PDDocument.load(new File("example.pdf"))) {
PDDocumentInformation info = document.getDocumentInformation();
// 设置文档属性
info.setAuthor("作者姓名");
info.setTitle("文档标题");
info.setSubject("文档主题");
// 可以设置更多属性,例如:
// info.setKeywords("关键词1, 关键词2");
// info.setCreator("创建者应用名");
// info.setProducer("生产者应用名");
// 保存属性
document.setDocumentInformation(info);
// 保存更改后的文档
document.save("updated_example.pdf");
} catch (IOException e) {
e.printStackTrace();
}
}
}