Spire.Doc for Java支持为Word文档设置背景颜色和添加背景图片。该文将详细讲述如何使用Spire.Doc for Java给一个现有Word文档设置纯色背景颜色,渐变背景颜色以及添加背景图片。
设置背景图片
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);
}
}
设置纯色背景颜色
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);
}
}
设置渐变色背景颜色
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);
}
}