Wednesday, 08 February 2023 08:48

Java: Insert Image Watermarks to PDF

A PDF image watermark is a semi-transparent picture integrated into a PDF page as a fixed element. It is often used to protect the copyright and other rights of the document owner since it can't be removed easily. What's more, for famous PDF publishers, image watermarks are also used to increase the credibility of their documents. With an image watermark of their logo, the readers of documents can identify them at a glance. This article will show how to insert image watermarks into PDF documents using Spire.PDF for Java with simple code.

Install Spire.PDF for Java

First of all, you're required to add the Spire.Pdf.jar file as a dependency in your Java program. The JAR file can be downloaded from this link. If you use Maven, you can easily import the JAR file in your application by adding the following code to your project's 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.11.11</version>
    </dependency>
</dependencies>

Insert a Single Picture Watermark into PDF

A single image watermark is usually placed at the center of a PDF page. The detailed steps for inserting a single image watermark are as follows.

  • Create a PdfDocument class instance.
  • Load a PDF document using PdfDocument.loadFromFile() method.
  • Load a picture using PdfImage.fromFile() method.
  • Get the width and height of the picture using PdfImage.getWidth() and PdfImage.getHeight() methods.
  • Loop through the pages in the PDF document to insert watermarks
  • Get a page using PdfDocument.getPages().get() method.
  • Get the width and height of the page using PdfPageBase.getActualSize().getWidth() and PdfPageBase.getActualSize().getHeight() methods.
  • Set the transparency of the watermark picture using PdfPageBase.getCanvas().setTransparency() method.
  • Draw the watermark picture at the center of the page using PdfPageBase.getCanvas().drawImage() method.
  • Save the document using PdfDocument.saveToFile() method.
  • Java
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("Goodbye Pixel.pdf");

        //Load a picture
        PdfImage image = PdfImage.fromFile("Logo.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.3f);
            //Draw the watermark picture at the middle of the page
            page.getCanvas().drawImage(image, pageWidth/2 - imageWidth/2, pageHeight/2 - imageHeight/2, imageWidth, imageHeight);
        }

        //Save the file
        pdf.saveToFile("SingleImageWatermark.pdf");
    }
}

Java: Insert Image Watermarks to PDF

Insert Tiled Picture Watermarks into PDF

Tiled image watermarks contain a picture that is displayed multiple times on one PDF page. When inserting a tiled image watermark, we can set the number of repetitions of its picture. The detailed steps for inserting a tiled image watermark are as follow.

  • Create a PdfDocument class instance.
  • Load a PDF document using PdfDocument.loadFromFile() method.
  • Load a picture using PdfImage.fromFile() method.
  • Loop through the pages to insert watermarks.
  • Get a specific page using PdfDocument.getPages().get() method.
  • Use the custom method insertImageWatermark() to insert a tiled image watermark.
  • Save the document using PdfDocument.saveToFile() method.
  • Java
import com.spire.pdf.PdfDocument;
import com.spire.pdf.PdfPageBase;
import com.spire.pdf.graphics.PdfBrush;
import com.spire.pdf.graphics.PdfImage;
import com.spire.pdf.graphics.PdfTilingBrush;

import java.awt.*;

public class insertTiledImageWatermark {
    public static void main(String[] args) {
        //Create a PdfDocument class instance
        PdfDocument pdf = new PdfDocument();

        //Load a PDF file
        pdf.loadFromFile("Goodbye Pixel.pdf");

        //Load a picture
        PdfImage image = PdfImage.fromFile("Logo.png");

        //Loop through the pages in the PDF document to insert watermark
        for (int i = 0; i < pdf.getPages().getCount(); i++ ) {
            //Get a Page
            PdfPageBase page = pdf.getPages().get(i);
            //Use the custom method to insert a tiled image watermark
            insertImageWatermark(page, image, 3, 3);
        }

        //Save the file
        pdf.saveToFile("TiledImageWatermark.pdf");
    }
    static void insertImageWatermark(PdfPageBase page, PdfImage image, int row, int column) {
        //Create a tile brush
        PdfTilingBrush brush = new PdfTilingBrush(new Dimension((int) (page.getActualSize().getWidth()/column), (int) (page.getActualSize().getHeight()/row)));
        brush.getGraphics().setTransparency(0.3f);
        brush.getGraphics().save();
        brush.getGraphics().translateTransform(brush.getSize().getWidth()/2 - image.getWidth()/2, brush.getSize().getHeight()/2 - image.getHeight()/2);
        //Draw the watermark image at the center of the page
        brush.getGraphics().drawImage(image, 0, 0);
        brush.getGraphics().restore();
        //Use the tile brush to draw the watermark picture
        page.getCanvas().drawRectangle(brush, new Rectangle(new Point(0, 0), new Dimension((int) (page.getActualSize().getWidth()), (int) (page.getActualSize().getHeight()))));
    }
}

Java: Insert Image Watermarks to PDF

Apply for a Temporary License

If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.

Published in Watermark

 Java Add Watermarks to PDF

Watermarking PDF documents serves as an essential measure for intellectual property protection, document status identification, and brand reinforcement. Java developers can efficiently automate this process using specialized libraries like Spire.PDF for Java, which offers comprehensive solutions for applying both text-based watermarks (such as "CONFIDENTIAL" labels) and graphical watermarks (including corporate logos).

This practical guide provides step-by-step instructions for implementing PDF watermarking in Java using Spire.PDF. You'll learn proven techniques to enhance document security and professional presentation through effective watermark implementation.

Java Library for Watermarking PDF

Spire.PDF for Java is a versatile library that simplifies PDF manipulation, including watermarking. Its intuitive API allows developers to add watermarks with minimal code while offering fine-grained control over appearance and placement.

To get started, download Spire.PDF for Java and reference it in your project. For Maven users, include the following in your 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</artifactId>
        <version>11.11.11</version>
    </dependency>
</dependencies>

Steps to Add a Watermark to PDF in Java

  1. Load the PDF using PdfDocument.
  2. Define the watermark (text with font/style or an image file).
  3. Set transparency (e.g., 0.3 for faint, 0.7 for stronger visibility).
  4. Calculate position (e.g., centered, custom location).
  5. Apply the watermark to all pages or specific ones.
  6. Save the modified document to a new file.

Add a Text Watermark to PDF

Text watermarks are ideal for adding labels like "DRAFT", "CONFIDENTIAL", or copyright notices. The implementation involves loading the PDF using PdfDocument , defining the font and brush for styling, and iterating through each page to apply the watermark text using a dedicated method that manages transparency, positioning, and drawing.

import com.spire.pdf.*;
import com.spire.pdf.graphics.*;
import java.awt.*;
import java.awt.geom.Dimension2D;

public class AddTextWatermark {
    public static void main(String[] args) {

        // Create a PdfDocument object
        PdfDocument doc = new PdfDocument();

        // Load a PDF document
        doc.loadFromFile("C:\\Users\\Administrator\\Desktop\\AI.pdf");

        // Create a font and a brush
        PdfTrueTypeFont font = new PdfTrueTypeFont(new Font("Arial Black", Font.PLAIN, 50), true);
        PdfBrush brush = PdfBrushes.getBlue();

        // Specify the watermark text
        String watermarkText = "DO NOT COPY";

        // Specify the opacity level
        float opacity = 0.6f;

        // Iterate through the pages
        for (int i = 0; i < doc.getPages().getCount(); i++) {
            PdfPageBase page = doc.getPages().get(i);
            // Draw watermark text on the page
            addTextWatermark(page, watermarkText, font, brush, opacity);
        }

        // Save the changes to another file
        doc.saveToFile("output/Watermark.pdf");

        // Dispose resources
        doc.dispose();
    }

    // Method to add a text watermark to a given page
    private static void addTextWatermark(PdfPageBase page, String watermarkText, PdfTrueTypeFont font, PdfBrush brush, float opacity) {

        // Set the transparency level for the watermark
        page.getCanvas().setTransparency(opacity);

        // Measure the size of the watermark text
        Dimension2D textSize = font.measureString(watermarkText);

        // Get the width and height of the page
        double pageWidth = page.getActualSize().getWidth();
        double pageHeight = page.getActualSize().getHeight();

        // Calculate the position to center the watermark on the page
        double x = (pageWidth - textSize.getWidth()) / 2;
        double y = (pageHeight - textSize.getHeight()) / 2;

        // Draw the watermark text on the page at the calculated position
        page.getCanvas().drawString(watermarkText, font, brush, x, y);
    }
}

Output:

 Output PDF file with a centered text watermark.

Add an Image Watermark to PDF

Image watermarks, such as logos, can elevate the professionalism of a document. This process begins by loading the PDF and specifying the image path and opacity. We then iterate through each page, calling a method that loads the image, calculates its position, and draws it on the page with the specified transparency.

import com.spire.pdf.*;
import com.spire.pdf.graphics.*;

public class AddImageWatermark {
    public static void main(String[] args) {

        // Create a PdfDocument object
        PdfDocument doc = new PdfDocument();

        // Load a PDF document
        doc.loadFromFile("C:\\Users\\Administrator\\Desktop\\AI.pdf");

        // Specify the image path
        String imagePath = "C:\\Users\\Administrator\\Desktop\\logo2.png";

        // Specify the opacity level
        float opacity = 0.3f;

        // Iterate through the pages
        for (int i = 0; i < doc.getPages().getCount(); i++) {

            // Draw watermark text on the current page
            addImageWatermark(doc.getPages().get(i), imagePath, opacity);
        }

        // Save the changes to another file
        doc.saveToFile("output/Watermark.pdf");

        // Dispose resources
        doc.dispose();
    }

    // Method to add an Image watermark to a given page
    private static void addImageWatermark(PdfPageBase page, String imagePath, float opacity) {

        // Load the image
        PdfImage image = PdfImage.fromFile(imagePath);

        // Get the width and height of the image
        double imageWidth = (double)image.getWidth();
        double imageHeight = (double)image.getHeight();

        // Get the width and height of the page
        double pageWidth = page.getActualSize().getWidth();
        double pageHeight = page.getActualSize().getHeight();

        // Calculate the position to center the watermark on the page
        double x = (pageWidth - imageWidth) / 2;
        double y = (pageHeight - imageHeight) / 2;

        // Set the transparency level for the watermark
        page.getCanvas().setTransparency(opacity);

        // Draw the image on the page at the calculated position
        page.getCanvas().drawImage(image, x, y);
    }
}

Output:

 Output PDF file with a centered image watermark

Conclusion

In conclusion, adding watermarks to PDF documents in Java is a straightforward task with the right tools and techniques. By leveraging the Spire.PDF for Java library, developers can seamlessly integrate dynamic text watermarks (like copyright notices) or high-resolution image logos while maintaining optimal file performance.

This guide provided a step-by-step approach, from initial setup to final implementation, ensuring that you can protect your documents effectively. Whether for personal use or professional needs, watermarking is an essential skill that adds a layer of professionalism and integrity to your work.

FAQs

Q1. Can I rotate the watermark text?

Yes, use page.getCanvas().rotateTransform(angle) before drawing the text.

Q2. How do I adjust the position of the watermark?

You can modify the x and y coordinates in the addTextWatermark and addImageWatermark methods to change the watermark position.

Q3. Is it possible to add multiple watermarks to the same PDF?

Yes, by calling drawString() or drawImage() multiple times with different parameters.

Q4. Can I use a transparent PNG as a watermark?

Yes, Spire.PDF preserves the transparency of PNG images.

Q5. How do I apply watermarks to specific pages only?

Modify the loop to target specific pages, e.g., if (i == 0) applies the watermark only to the first page.

Get a Free License

To fully experience the capabilities of Spire.PDF for Java without any evaluation limitations, you can request a free 30-day trial license.

Published in Watermark