My FeedDiscussionsHeadless CMS
New
Sign in
Log inSign up
Learn more about Hashnode Headless CMSHashnode Headless CMS
Collaborate seamlessly with Hashnode Headless CMS for Enterprise.
Upgrade ✨Learn more

Set Background Color and Background Image for PDF in Java

Tina's blog's photo
Tina's blog
·Feb 17, 2020

A background appears behind text or images on the page. The background can be as simple as a solid color, or you can use an image. In this article, I’ll show you how to set background color and background image for PDF by using Free Spire.PDF for Java .

Before getting started, please download the latest version of Free Spire.PDF for Java package from the link , unzip the package and then import Spire.Pdf.jar from lib folder into IntelliJ IDEA. The following screenshot is what it finally looks like.

image001.jpg

The original PDF file:

image002.jpg

Set Background Color

import com.spire.pdf.PdfDocument;
import com.spire.pdf.PdfPageBase;
import java.awt.*;

public class BackgroundColor {
    public static void main(String[] args) {
        //Load PDF file
        PdfDocument doc = new PdfDocument();
        doc.loadFromFile("D:\\Desktop\\Sample.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("output/BackgroundColor.pdf");

    }
}

Output

image003.jpg

Set Background Image

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

public class BackgroundImage {
    public static void main(String[] args) {
        //Load PDF file
        PdfDocument doc = new PdfDocument();
        doc.loadFromFile("D:\\Desktop\\Sample.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("D:\\Desktop\\Image.jpg");
        }

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

    }
}

Output

image004.jpg