The following code snippets demonstrate how to use Spire.Doc for Java to set the background for word document in Java programs, including how to set background image, background solid color and background gradient color.
Java set background image for word document:
import com.spire.doc.*; import com.spire.doc.documents.BackgroundType; import java.awt.*; import java.io.*; public class WordBackground { public static void main(String[] args) throws IOException { String inputFile="Sample.docx"; String backgroundImg="background.png"; String outputFile="out/result.docx"; //load a word document Document document= new Document(inputFile); //set the background type as picture document.getBackground().setType(BackgroundType.Picture); //set the background picture document.getBackground().setPicture(backgroundImg); //save the file document.saveToFile(outputFile, FileFormat.Docx); } }
Java set background solid color for word document:
import com.spire.doc.*; import com.spire.doc.documents.BackgroundType; import java.awt.*; import java.io.*; public class WordBackground { public static void main(String[] args) throws IOException { String inputFile="Sample.docx"; String outputFile="out/result2.docx"; //load a word document Document document= new Document(inputFile); document.getBackground().setType(BackgroundType.Color); document.getBackground().setColor(Color.lightGray); //save the file document.saveToFile(outputFile, FileFormat.Docx); } }
Java set background gradient color for word document:
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.*; public class WordBackground { public static void main(String[] args) throws IOException { String inputFile="Sample.docx"; String outputFile="out/result3.docx"; //load a word document Document document= new Document(inputFile); document.getBackground().setType(BackgroundType.Gradient); document.getBackground().getGradient().setColor1(Color.white); document.getBackground().getGradient().setColor2(Color.green); document.getBackground().getGradient().setShadingVariant(GradientShadingVariant.Shading_Down); document.getBackground().getGradient().setShadingStyle(GradientShadingStyle.Horizontal); //save the file document.saveToFile(outputFile, FileFormat.Docx_2013); } }