Generally, the default document background color of the generated PDF document is white. We can change the background color of the document by some methods to beautify the document and protect the eyes. The following provides Java programming to set the PDF background color. Include:
- Set solid background color
- Set picture background color
Using tools
- Free Spire.PDF for Java 2.0.0 (free version)
Note: compared with the previous version 1.1.0, version 2.0.0 has greatly improved its functions, and supports all the functions of the charging version.
Jar file reference:
Step 1: create a new folder in the Java program to be named lib. After downloading the installation package, unzip it, and copy the Spire.Pdf.jar and Spire.Common.jar files in the subfolder lib under the unzipped folder to the new folder, as shown below:
Step 2: after creating the folder, reference two files: select the two jar files, right-click, and select "Build Path" – "Add to Build Path".
Java example code 1 -- set solid background color
import com.spire.pdf.PdfDocument; import com.spire.pdf.PdfPageBase; import java.awt.*; public class SetBackgroundColor1 { public static void main(String[] args) { //Load PDF File PdfDocument doc = new PdfDocument(); doc.loadFromFile("test.pdf"); PdfPageBase page; //Get the total number of pages of the document int pageCount = doc.getPages().getCount(); //Traverse the page and set the background color for(int i = 0; i < pageCount; i ++) { page = doc.getPages().get(i); page.setBackgroundColor(Color.yellow); } //Save document doc.saveToFile("BackgroundColor.pdf"); } }
Solid background add effect:
Java example code 2 -- set the background color of the picture
import com.spire.pdf.PdfDocument; import com.spire.pdf.PdfPageBase; public class SetBackgroundColor2 { public static void main(String[] args) { //Load PDF File PdfDocument doc = new PdfDocument(); doc.loadFromFile("test.pdf"); PdfPageBase page; //Get the total number of pages of the document int pageCount = doc.getPages().getCount(); //Traverse the page and set the background picture for(int i = 0; i < pageCount; i ++) { page = doc.getPages().get(i); page.setBackgroundImage("tp.png"); } //Save document doc.saveToFile("BackgroundImage2.pdf"); } }
Picture background color fill effect:
(end of this paper)
Please indicate the source of reprint.