Wednesday, 1 April 2020

Set Background Color and Background Image for PDF in Java


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 share with you how to set background color and background image for PDF by using Free Spire.PDF for Java.



ADD SPIRE.PDF.JAR AS DEPENDENCY

Download the latest version of Free Spire.PDF for Java pack, unzip it and import the jar file located at the “lib” folder in your project as a dependency. The following screenshot is what it finally looks like.


The original PDF file:


Example 1 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("C:\\Users\\Test1\\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


Example 2 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("C:\\Users\\Test1\\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("C:\\Users\\Test1\\Desktop\\Image.jpg");

        }

        //Save the file

        doc.saveToFile("output/BackgroundImage.pdf");

    }

}

Output


 









No comments:

Post a Comment

Change PDF Versions in Java

In daily work, you might need to change the version of a PDF document you have in order to ensure compatibility with another version which a...