PDF documents are a cornerstone of digital communication and record-keeping, but they often require additional measures to protect their content, convey ownership, or brand them effectively. Watermarking is a widely adopted technique for achieving these goals, providing a visual overlay that can be a company logo, a "Confidential" stamp, or copyright information.
This article serves as a comprehensive, step-by-step tutorial on how to implement PDF watermarking using Java. We will specifically leverage the Spire.PDF for Java library, a powerful and versatile tool for PDF manipulation. Our focus will be on adding both text and image watermarks, offering practical solutions for common business needs.
Setting Up Your Java Project with Spire.PDF for Java
Before we dive into watermarking, you need to set up your Java development environment to include the Spire.PDF for Java library. This library simplifies complex PDF operations, making watermarking straightforward.
Maven Dependency
If you are using Maven for dependency management, add the following to your pom.xml file:
<repositories>
<repository>
<id>com.e-iceblue</id>
<name>e-iceblue</name>
<url>https://repo.e-iceblue.com/nexus/content/groups/public/</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>e-iceblue</groupId>
<artifactId>spire.pdf</artifactId>
<version>11.9.6</version>
</dependency>
</dependencies>
If you are not using a build tool, you can download the Spire.PDF for Java JAR files directly from the official E-iceblue website and add them to your project's build path.
Adding Text Watermarks to PDF in Java with Spire.PDF
Adding a text watermark is a common requirement for marking documents as drafts, confidential, or simply to display copyright information. Spire.PDF for Java provides robust features to customize text watermarks extensively.
Here's how to add text watermark to PDF in Java:
- Load the PDF Document: Initialize a PdfDocument object and load your target PDF file.
- Create a Watermark Template: A PdfTemplate is used to define the visual appearance of the watermark. This allows for precise control over its properties.
- Define Watermark Text Properties: Set the font, size, color, opacity, and rotation of the text within the template.
- Draw Text onto the Template: Use the template's graphics object to draw the watermark text.
- Create Watermark Annotation: Instantiate a PdfWatermarkAnnotation with the defined template.
- Apply to Pages: Iterate through the desired pages (all or specific ones) and add the watermark annotation.
- Save the Document: Save the modified PDF to a new file.
import com.spire.pdf.*;
import com.spire.pdf.annotations.PdfWatermarkAnnotation;
import com.spire.pdf.graphics.*;
import java.awt.*;
import java.awt.geom.Rectangle2D;
public class TextWatermark {
public static void main(String[] args) {
// Load the PDF document
PdfDocument pdf = new PdfDocument();
pdf.loadFromFile("input.pdf"); // Replace with your input PDF file path
// Define watermark text and properties
String watermarkText = "CONFIDENTIAL";
PdfFont font = new PdfFont(PdfFontFamily.Helvetica, 48f, PdfFontStyle.Bold);
PdfRGBColor textColor = new PdfRGBColor(new Color(192, 192, 192)); // Light grey
float opacity = 0.3f; // 30% opaque
float rotation = 45f; // Rotate by 45 degrees
// Iterate through all pages
for (int i = 0; i < pdf.getPages().getCount(); i++) {
PdfPageBase page = pdf.getPages().get(i);
// Create a template with the same dimensions as the page
PdfTemplate template = new PdfTemplate(page.getClientSize().getWidth(), page.getClientSize().getHeight());
// Set graphics properties for the template
template.getGraphics().setTransparency(opacity);
template.getGraphics().save();
// Translate and rotate for positioning
template.getGraphics().translateTransform(
(float) template.getWidth() / 2,
(float) template.getHeight() / 2
);
template.getGraphics().rotateTransform(rotation);
template.getGraphics().translateTransform(
(float) -template.getWidth() / 2,
(float) -template.getHeight() / 2
);
// Calculate text size to center it
Dimension2D textSize = font.measureString(watermarkText);
float x = (float) (template.getWidth() - textSize.getWidth()) / 2;
float y = (float) (template.getHeight() - textSize.getHeight()) / 2;
// Draw the text onto the template
template.getGraphics().drawString(watermarkText, font, PdfBrushes.getLightGray(), x, y);
template.getGraphics().restore();
// Create a watermark annotation
Rectangle2D loRect = new Rectangle2D.Float(0, 0, (float) page.getClientSize().getWidth(), (float) page.getClientSize().getHeight());
PdfWatermarkAnnotation watermarkAnnotation = new PdfWatermarkAnnotation(loRect);
watermarkAnnotation.setAppearance(new PdfAppearance(watermarkAnnotation));
watermarkAnnotation.getAppearance().setNormal(template);
// Add the watermark annotation to the page
page.getAnnotations().add(watermarkAnnotation);
}
// Save the document
pdf.saveToFile("output_watermarked_text.pdf");
pdf.close();
}
}
This code snippet demonstrates how to add text watermark to PDF in Java with customization options for font, size, color, opacity, and rotation, applying it to all pages of the document.
Adding Image Watermarks to PDF in Java with Spire.PDF
For branding or specific visual indicators, an image watermark is often preferred. This could be a company logo, a "Draft" image, or a custom symbol. Let's explore how to add image watermark to PDF in Java using Spire.PDF.
- Load the PDF Document: As before, load your PDF file into a PdfDocument object.
- Load the Image: Load the desired image (e.g., PNG, JPG) using PdfImage.fromFile().
- Create a Watermark Template: Similar to text watermarks, use a PdfTemplate for the image.
- Draw Image onto the Template: Draw the loaded image onto the template's graphics object, specifying its position and size.
- Set Opacity: Adjust the opacity of the image using the template's graphics properties.
- Create Watermark Annotation: Create a PdfWatermarkAnnotation and assign the image template to its appearance.
- Apply to Pages: Add the watermark annotation to the desired pages.
- Save the Document: Save the modified PDF.
import com.spire.pdf.*;
import com.spire.pdf.annotations.PdfWatermarkAnnotation;
import com.spire.pdf.graphics.*;
import java.awt.geom.Rectangle2D;
public class ImageWatermark {
public static void main(String[] args) {
// Load the PDF document
PdfDocument pdf = new PdfDocument();
pdf.loadFromFile("input.pdf"); // Replace with your input PDF file path
// Load the image for the watermark
PdfImage image = PdfImage.fromFile("logo.png"); // Replace with your image file path
float opacity = 0.2f; // 20% opaque
// Iterate through all pages
for (int i = 0; i < pdf.getPages().getCount(); i++) {
PdfPageBase page = pdf.getPages().get(i);
// Create a template with the same dimensions as the page
PdfTemplate template = new PdfTemplate(page.getClientSize().getWidth(), page.getClientSize().getHeight());
// Set graphics properties for the template
template.getGraphics().setTransparency(opacity);
// Calculate image position to center it
float imgWidth = image.getWidth() * 0.5f; // Scale image to 50% of its original size
float imgHeight = image.getHeight() * 0.5f;
float x = (float) (template.getWidth() - imgWidth) / 2;
float y = (float) (template.getHeight() - imgHeight) / 2;
// Draw the image onto the template
template.getGraphics().drawImage(image, x, y, imgWidth, imgHeight);
// Create a watermark annotation
Rectangle2D loRect = new Rectangle2D.Float(0, 0, (float) page.getClientSize().getWidth(), (float) page.getClientSize().getHeight());
PdfWatermarkAnnotation watermarkAnnotation = new PdfWatermarkAnnotation(loRect);
watermarkAnnotation.setAppearance(new PdfAppearance(watermarkAnnotation));
watermarkAnnotation.getAppearance().setNormal(template);
// Add the watermark annotation to the page
page.getAnnotations().add(watermarkAnnotation);
}
// Save the document
pdf.saveToFile("output_watermarked_image.pdf");
pdf.close();
}
}
This example illustrates how to add image watermark to PDF in Java, demonstrating how to load an image, adjust its size, position, and opacity, and apply it across all pages of a PDF document.
Conclusion
Watermarking PDF documents is an essential practice for document security, brand reinforcement, and intellectual property protection. As demonstrated in this tutorial, Spire.PDF for Java offers a robust and straightforward solution for implementing both text and image watermarks within your Java applications.
By following the steps outlined, you can effectively add text watermark to PDF in Java and add image watermark to PDF in Java, customizing their appearance, position, and opacity to meet specific requirements. This powerful library simplifies complex PDF manipulation tasks, allowing developers to integrate sophisticated document processing capabilities with minimal effort. We encourage you to explore further features of Spire.PDF for Java to enhance your document management solutions.
Top comments (0)