In Word, you can set the background color according to different document layout design requirements. Common settings include setting a single color, gradient, or loading a specified picture to set it as a background. Next, use Java to set the above three kinds of Word page background colors.
Using tool: Spire.Doc for Java v2.2.0
Jar file import method
Method 1: Pass Download official website . Create a new directory under the program and name it (lib in this example); copy the jar under the lib folder of the control package (as shown in Figure 1 below) directly to the new directory in the program. After copying the jar file, right-click the jar file and select Add as Library. Complete the import (as shown in Figure 2 below).
Fig. 1:
Fig. 2:
Method 2: import through maven. Reference import method( https://www.e-iceblue.cn/licensing/install-spirepdf-for-java-from-maven-repository.html).
Java code example (for reference)
[example 1] add a single color background color
import com.spire.doc.*; import com.spire.doc.documents.BackgroundType; import java.awt.*; import java.io.IOException; public class BackgroundColor_Doc { public static void main (String[] args) throws IOException{ //Load test file String input="test.docx"; String output="backgroundcolor.docx"; Document doc = new Document(input); //Set monochrome background doc.getBackground().setType(BackgroundType.Color); doc.getBackground().setColor(Color.PINK); //Save document doc.saveToFile(output,FileFormat.Docx_2013); } }
[example 2] add a gradient background color
import com.spire.doc.*; import com.spire.doc.documents.BackgroundType; import com.spire.doc.documents.GradientShadingStyle; import com.spire.doc.documents.GradientShadingVariant; import java.awt.*; import java.io.IOException; public class GradientBackground_Doc { public static void main(String[] arg) throws IOException{ //Load test document String input= "test.docx"; String output="GradientBackgound.docx"; Document doc = new Document(input); //Set gradient doc.getBackground().setType(BackgroundType.Gradient); doc.getBackground().getGradient().setColor1(Color.white); doc.getBackground().getGradient().setColor2(Color.green); doc.getBackground().getGradient().setShadingVariant(GradientShadingVariant.Shading_Middle); doc.getBackground().getGradient().setShadingStyle(GradientShadingStyle.Horizontal); //Save document doc.saveToFile(output, FileFormat.Docx_2010); } }
[example 3] loading picture set as background
import com.spire.doc.*; import com.spire.doc.documents.BackgroundType; import java.io.IOException; public class ImgBackground_Doc { public static void main(String[] arg) throws IOException { //load file String input= "test.docx"; String output="ImgBackgound.docx"; String img= "lye.png"; Document doc = new Document(input); //Set picture background doc.getBackground().setType(BackgroundType.Picture); doc.getBackground().setPicture(img); //Save document doc.saveToFile(output, FileFormat.Docx); } }
(end of this paper)