Set Background Color and Background Image for PDF in Java

This article is going to demonstrate how to set background color and background image for a PDF file using Spire.PDF for Java.

The original PDF file:

Set Background Color and Background Image for PDF in Java

Set background color

import com.spire.pdf.PdfDocument;
import com.spire.pdf.PdfPageBase;

import java.awt.*;

public class SetBackgroundColor {
    public static void main(String[] args) {
        
        //Load PDF file
        PdfDocument doc = new PdfDocument();
        doc.loadFromFile("original.pdf");

        PdfPageBase page;
        int pageCount = doc.getPages().getCount();

        //Set Background color
        for(int i = 0; i < pageCount; i ++) {
            page = doc.getPages().get(i);
            page.setBackgroundColor(Color.yellow);
        }

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

Output:

Set Background Color and Background Image for PDF in Java

Set background image

import com.spire.pdf.PdfDocument;
import com.spire.pdf.PdfPageBase;

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

        //Load PDF file
        PdfDocument doc = new PdfDocument();
        doc.loadFromFile("original.pdf");
        
        PdfPageBase page;
        int pageCount = doc.getPages().getCount();

        //Set background image
        for(int i = 0; i < pageCount; i ++) {
            page = doc.getPages().get(i);
            page.setBackgroundImage("Background.jpg");
        }

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

Output:

Set Background Color and Background Image for PDF in Java