通过 Java 处理 PDF 中的水印

使用适用于 Java 库的 Aspose.PDF 以编程方式处理 PDF 文档中的水印

Java 中最受欢迎的带有水印的动作

使用 Java 库添加水印

若要為 PDF 檔案新增浮水印,我們將使用 Aspose.PDF for Java API,這是一個功能豐富、強大且易於使用的 Java 平台轉換 API。您可以直接從 Maven 下載其最新版本,並透過在 pom.xml 檔案中新增下列設定將其安裝至基於 Maven 的專案中。

Repository

<repository>
    <id>AsposeJavaAPI</id>
    <name>Aspose Java AP</name>
    <url>https://releases.aspose.com/java/repo/</url>
</repository>

Dependency

<dependency>
<groupId>com.aspose</groupId>
<artifactId>aspose-pdf</artifactId>
<version>version of aspose-pdf API</version>
</dependency>

使用 Java 添加水印


您需要 Aspose.PDF for Java 才能在您的環境中測試程式碼。

  1. 使用 Document 實例載入 PDF。
  2. 建立 WatermarkArtifact 實例。
  3. 設定 WatermarkArtifact 物件的屬性。
  4. 使用 Aspose.Pdf.Page.Artifacts 集合類別的 Add 方法新增浮水印。
  5. 儲存 PDF 文件

在 PDF 中添加水印-Java

此示例代码说明如何向 PDF 页面添加水印-Java

Input file:

File not added

Output format:

Output file:

// Open document
Document pdfDocument = new Document("sample.pdf");
FormattedText formattedText = new com.aspose.pdf.facades.FormattedText("Watermark Example");
WatermarkArtifact artifact = new WatermarkArtifact();
artifact.setText(formattedText);
artifact.setArtifactHorizontalAlignment(HorizontalAlignment.Center);
artifact.setArtifactVerticalAlignment(VerticalAlignment.Center);
artifact.setRotation(45);
artifact.setOpacity(0.5);
artifact.setBackground(true);
pdfDocument.getPages().get_Item(1).getArtifacts().add(artifact);
pdfDocument.save(DATA_DIR.resolve("watermark.pdf").toString());
pdfDocument.close();