Java insert text and image watermark to Excel worksheet

This article will demonstrate how to insert text and image watermark to Excel worksheet in Java applications. The watermark in Excel worksheet could only be viewed under layout view mode.

import com.spire.xls.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import static java.awt.image.BufferedImage.TYPE_INT_ARGB;

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

        //Initialize a new instance of workbook and load the test file
        Workbook workbook = new Workbook();

        //Set the text string and size
        Font font = new Font("Arial", Font.PLAIN, 40);
        String watermark = "Draft Version";

        for (Worksheet sheet : (Iterable) workbook.getWorksheets()) {
            //Call DrawText() method to insert the image
            BufferedImage imgWtrmrk = drawText(watermark, font,, Color.white, sheet.getPageSetup().getPageHeight(), sheet.getPageSetup().getPageWidth());

            //Set the image as header

            //Set the viewmode as Layout

        //Save the document
        workbook.saveToFile("Watermark.xlsx", ExcelVersion.Version2010);
    private static BufferedImage drawText (String text, Font font, Color textColor, Color backColor,double height, double width)
        //define the width and height of image
        BufferedImage img = new BufferedImage((int) width, (int) height, TYPE_INT_ARGB);
        Graphics2D loGraphic = img.createGraphics();

        //set the font size
        FontMetrics loFontMetrics = loGraphic.getFontMetrics(font);
        int liStrWidth = loFontMetrics.stringWidth(text);
        int liStrHeight = loFontMetrics.getHeight();

        //set the text format
        loGraphic.fillRect(0, 0, (int) width, (int) height);
        loGraphic.translate(((int) width - liStrWidth) / 2, ((int) height - liStrHeight) / 2);

        loGraphic.translate(-((int) width - liStrWidth) / 2, -((int) height - liStrHeight) / 2);
        loGraphic.drawString(text, ((int) width - liStrWidth) / 2, ((int) height - liStrHeight) / 2);
        return img;

Effective screenshot of Excel text watermark:

Java insert text and image watermark to Excel worksheet