Add Text Watermarks to PDF
Watermark plays an important role in a lot of scenarios, and adding watermarks to PDF files can effectively protect your documents from unauthorized use. This article will share how to programmatically add a single-line text watermark to PDF using Free Spire.PDF for Java.
Installation (2 methods)
Method 1: Download the free library and unzip it. Then add the Spire.Pdf.jar file to your project as dependency.
Method 2: Directly add the jar dependency to maven project by adding the following configurations to the pom.xml.
<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.free</artifactId>
<version>5.1.0</version>
</dependency>
</dependencies>
Samle Code
Free Spire.PDF for Java does not provide a direct interface or class to add watermarks to PDF files. But you can draw text into a PDF page and set transparency to the text to mimic a watermark effect. The complete sample code is shown as below.
import com.spire.pdf.*;
import com.spire.pdf.graphics.*;
import java.awt.*;
import java.lang.Math;
public class TextWatermark {
public static void main(String[] args) {
//create a PdfDocument instance
PdfDocument pdf = new PdfDocument();
//load the sample document
pdf.loadFromFile("E:\\Files\\template.pdf");
PdfPageBase page = pdf.getPages().get(0);
// Create a PdfTrueTypeFont object
PdfTrueTypeFont font = new PdfTrueTypeFont(new Font("Arial", Font.PLAIN, 50), true);
// Set the watermark text
String text = "CONFIDENTIAL";
// Measure the text size
// Calculate the values of two offset variables,
// which will be used to calculate the translation amount of the coordinate system
float offset1 = ((float) ((font.measureString(text).getWidth()
* (Math.sqrt(2) / 4))));
float offset2 = ((float) ((font.measureString(text).getHeight()
* (Math.sqrt(2) / 4))));
// Set the page transparency
page.getCanvas().setTransparency(0.5);
// Translate the coordinate system by specified coordinates
page.getCanvas().translateTransform(((page.getCanvas().getSize().getWidth() / 2)
- (offset1 - offset2)), ((page.getCanvas().getSize().getHeight() / 2)
+ (offset1 - offset2)));
// Rotate the coordinate system 45 degrees counterclockwise
page.getCanvas().rotateTransform(-45);
// Draw watermark text on the page
page.getCanvas().drawString(text, font, PdfBrushes.getDarkGray(), 0, 0);
// Save the changes to another file
pdf.saveToFile("TextWatermark.pdf");
}
}