Aspose.PDF FOSS for Java 是一个 MIT 许可证的 Java 库,用于创建和处理 PDF 文档。它提供了一个全面的 Document 类作为中心入口点,并全面覆盖注释、交互式表单字段、页面操作、元数据以及 PDF/A 合规性验证。
该库公开了527个类,覆盖完整的PDF规范:通过 Document、Page 和 PageCollection 实现文档结构;通过 Annotation 层次结构(包括 WidgetAnnotation、FreeTextAnnotation 和 HighlightAnnotation)实现注释;使用 Form、ButtonField、CheckboxField 和 RadioButtonField 实现交互式表单;通过 BmpDevice 进行页面渲染;以及通过 ActionRules 和 ActionFixes 检查 PDF/A 合规性。加密通过 AESCipher 的 CBC 模式提供。
将 Aspose.PDF FOSS 添加到您的 Maven 项目中,使用 groupId org.aspose 和 artifactId aspose-pdf。该库需要 Java 11 或更高版本,并且完全采用 MIT 许可证。有关企业功能和支持,请参阅 Aspose.PDF for Java — Enterprise Product。
Document 类来创建新的 PDF 文档。可以通过 Document(filePath) 或 Document(stream) 构造函数访问现有文档。PageCollection 添加、访问和修改页面。每个 Page 暴露 MediaBox、CropBox、旋转、资源和内容操作符。DocumentInfo 和 XmpMetadata 读取和写入文档元数据。getParser()、getCatalog() 和 getTrailer() 访问底层 PDF 对象。getEmbeddedFiles() 管理嵌入式文件集合。Document 并填充页面,以编程方式构建文档。PdfFileEditor 和 Page API 调整大小、旋转或重新排序页面。Annotation 类是所有注释的基类;具体类型包括 WidgetAnnotation、FreeTextAnnotation、HighlightAnnotation 和 UnderlineAnnotation。Document.getForm() 访问文档表单,以枚举或创建 ButtonField、CheckboxField 和 RadioButtonField 实例。AppearanceCharacteristics 控制视觉属性 — 边框颜色、背景、旋转和标题。FormEditor 和 FormElement 进行更高级的表单操作。ActionRules 和 ActionFixes 验证并修复文档,以实现长期归档。AESCipher.encrypt(key, data) 和 AESCipher.decrypt(key, data))使用 AESCipher 加密和解密数据字节数组。Artifact 和 ArtifactCollection API 识别并操作页眉、页脚、水印和背景图像。PdfFileEditor.resizeContents() 和 ContentsResizeParameters 调整页面内容布局。AnnotationRules 和 ActionRules 对注释和操作规则进行 PDF/A 标准验证。AESCipher 加密嵌入文档流中的数据段。Artifact 对象,这些对象表示水印和页面装饰。ActionFixes 和 AnnotationFixes 以使现有文档符合 PDF/A-1b 归档标准。创建一个新文档,添加页面,并附加带样式的 widget annotation。
try (Document doc = new Document()) {
Page page = doc.getPages().add();
WidgetAnnotation w = new WidgetAnnotation(page, new Rectangle(0, 0, 100, 50));
w.getCharacteristics().setBorder(Color.fromRgb(1, 0, 0));
w.getCharacteristics().setCaption("Submit");
page.getAnnotations().add(w);
doc.save("output.pdf");
}
```java
try (Document doc = new Document()) {
Page page = doc.getPages().add();
WidgetAnnotation w = new WidgetAnnotation(page, new Rectangle(0, 0, 100, 50));
w.getCharacteristics().setBorder(Color.fromRgb(1, 0, 0));
w.getCharacteristics().setCaption("Submit");
page.getAnnotations().add(w);
doc.save("output.pdf");
}
向文档表单添加单选按钮组并以编程方式选择一个值。
try (Document doc = new Document()) {
Page page = doc.getPages().add();
RadioButtonField radio = new RadioButtonField(page);
radio.setPartialName("choice");
radio.addOption("Option1", new Rectangle(50, 50, 70, 70));
radio.addOption("Option2", new Rectangle(50, 80, 70, 100));
doc.getForm().add(radio, 1);
radio.setValue("Option2");
doc.save("form.pdf");
}
访问现有文档并读取第一页的媒体框尺寸。
try (Document doc = new Document("input.pdf")) {
double width = doc.getPages().get(1).getMediaBox().getWidth();
double height = doc.getPages().get(1).getMediaBox().getHeight();
System.out.println("Page size: " + width + " x " + height);
}