DEV Community

Gia
Gia

Posted on

How to Add Text Watermark to PDF Programmatically

Adding image watermarks to PDF files is a widely practiced method. It allows for overlaying transparent images onto PDF pages in order to safeguard the document's copyright. Image watermarking not only enhances security but also imparts a sense of professionalism and brand value, thereby making PDF documents more visually appealing and distinctive. Apart from using software, image watermarks can also be added programmatically. Taking Java as an example, this article elucidates the precise technique of incorporating text-based watermarks into PDF files.

Step 1: Install a PDF Library

I highly recommend Free Spire.PDF for Java, which is a totally standalone PDF Library. It supports a wide range of features such as creating, editing and converting of PDF files effortlessly within Java applications.
You can download it from this link to local and unzip it.

Step 2: Import JAR file to your project

Take IntelliJ IDEA 2018 as an example

  • Create a new project in IntelliJ IDEA.
  • Click “File”- “Project Structure” - “Modules” - “Dependencies” in turn.
  • Choose the “JARs or Directories” under the right green plus.
  • Find the “Spire.Pdf.jar” in the lib folder of the decompressed package and import it to the project.

Step 3: Code:

Here is a sample code:

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

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

        //Create a PdfDocument class instance
        PdfDocument pdf = new PdfDocument();

        //Load a PDF document
        pdf.loadFromFile("sample.pdf");

        //Loop through all pages in the PDF document to insert watermarks
        String text = "CONFIDENTIAL";
        PdfTrueTypeFont font = new PdfTrueTypeFont(new Font("Arial", Font.BOLD, 50));
        float set1 = (float) (font.measureString(text).getWidth() * Math.sqrt(2)/4);
        float set2 = (float) (font.measureString(text).getHeight() * Math.sqrt(2)/4);
        for (int i = 0; i < pdf.getPages().getCount(); i++){

            //Get a page
            PdfPageBase page = pdf.getPages().get(i);

            //Set the transparency of the watermark
            page.getCanvas().setTransparency(0.8f);

            //Set translation amount of the coordinate
            page.getCanvas().translateTransform(page.getCanvas().getSize().getWidth()/2 - set1 - set2, page.getCanvas().getSize().getHeight()/2 + set1 - set2);

            //Set the rotation angle
            page.getCanvas().rotateTransform(-45);

            //Draw the watermark text on the page
            page.getCanvas().drawString(text, font, PdfBrushes.getDarkGray(), 0, 0);
        }

        //Save the document
        pdf.saveToFile("SingleTextWatermark.pdf");
    }
}
Enter fullscreen mode Exit fullscreen mode

This code will help you add a single text watermark to PDF file. If you want insert a tiled text watermark to PDF, please refer to the following one:

import com.spire.pdf.*;
import com.spire.pdf.graphics.*;
import com.spire.pdf.htmlconverter.qt.Size;
import java.awt.*;
import java.awt.geom.*;

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

        //Create a PdfDocument class instance
        PdfDocument pdf = new PdfDocument();

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

        //Loop through the pages to insert watermarks
        PdfTrueTypeFont font = new PdfTrueTypeFont(new Font("Arial", Font.BOLD, 20));
        for (int i = 0; i < pdf.getPages().getCount(); i++){
            PdfPageBase pageBase = pdf.getPages().get(i);
            insertTextWatermark(pageBase, font, "CONFIDENTIAL", 3, 3);
        }

        //Save the document
        pdf.saveToFile("TiledTextWatermark.pdf");
    }

    static void insertTextWatermark(PdfPageBase page, PdfTrueTypeFont font, String watermark, int row, int column) {

        //Calculate the values of two offset variables to be used to calculate the translation amount of the coordinate
        float set1 = (float)(font.measureString(watermark).getWidth() * Math.sqrt(2)/4);
        float set2 = (float)(font.measureString(watermark).getHeight() * Math.sqrt(2)/4);

        //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 - set1 - set2, brush.getSize().getHeight()/2 + set1 - set2);
        brush.getGraphics().rotateTransform(-45);

        //Draw watermark text on the tile brush
        brush.getGraphics().drawString(watermark, font, PdfBrushes.getViolet(), 0, 0);
        brush.getGraphics().restore();

        //Draw watermark with the tile brush
        page.getCanvas().drawRectangle(brush, new Rectangle(new Point(0, 0), new Dimension((int)(page.getActualSize().getWidth()), (int)(page.getActualSize().getHeight()))));
    }
}
Enter fullscreen mode Exit fullscreen mode

Image description

Referring to the above method, you can also use this PDF component to convert PDF to Word, or print PDF files.

Top comments (0)