Adding a transparent image overlay to PDF pages serves the dual purpose of enhancing file security and enabling features such as encryption, copyright marking, and more. By selecting appropriate tools or software, you can effortlessly incorporate personalized image watermarks into PDF files, conveniently adjusting their position, size, and transparency according to your requirements. In this article, I will illustrate the step-by-step process of inserting image watermarks into PDF documents using a Java program. Below are the detailed steps.
Step 1, Download Free Spire.PDF for Java and unzip it.
This a the community version of Spire.PDF for Java and there are some limitations on pages during the process. If you want to get rid of the limitations, you can download the commercial product from this link and apply for a temporary license.
It supports create or edit PDF files independently on Java applications. What’s more, you can also convert PDF to Word, merge PDF files, print PDF files using this library.
Step 2, Create a new Java project.
Step 3, Import “Spire.Pdf.jar” to your project
Take IntelliJ IDEA 2018 (jdk 1.8.0) for example.
- Click “File”- “Project Structure”- “Modules”- “Dependencies” in turn.
- Choose the “JARs or Directories” under the green plus.
- Find the “Spire.Pdf.jar” in the lib folder of the decompressed package and import it to the project.
Step 4, Sample code
import com.spire.pdf.PdfDocument;
import com.spire.pdf.PdfPageBase;
import com.spire.pdf.graphics.PdfBrush;
import com.spire.pdf.graphics.PdfImage;
import java.awt.*;
import java.awt.image.BufferedImage;
public class insertSingleImageWatermark {
public static void main(String[] args) {
//Create a PdfDocument class instance
PdfDocument pdf = new PdfDocument();
//Load a PDF file
pdf.loadFromFile("sample.pdf");
//Load a picture
PdfImage image = PdfImage.fromFile("image.png");
//Get the width and height of the image
int imageWidth = image.getWidth();
int imageHeight = image.getHeight();
//Loop through the pages to insert watermark
for (int i = 0; i < pdf.getPages().getCount(); i++) {
//Get a page
PdfPageBase page = pdf.getPages().get(i);
//Get the width and height of the page
float pageWidth = (float) (page.getActualSize().getWidth());
float pageHeight = (float) (page.getActualSize().getHeight());
//Set the transparency of the watermark
page.getCanvas().setTransparency(0.6f);
//Draw the watermark picture at the middle of the page
page.getCanvas().drawImage(image, pageWidth/1.5 - imageWidth/2, pageHeight/1.5 - imageHeight/2, imageWidth, imageHeight);
}
//Save the file
pdf.saveToFile("ImageWatermark.pdf");
}
}

Top comments (0)