Set Background Color and Background Image for PDF in Java
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.
The original PDF file:
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
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