Java 設置Word頁面背景色


Word中可以針對不同文檔排版設計要求來設置背景設置顏色。常見的可設置單一顏色、漸變色或加載指定圖片來設置成背景。下面通過Java來設置以上3種Word頁面背景色。

使用工具:Spire.Doc for Java v2.2.0

Jar文件導入方法

方法1:通過官網下載。在程序下新建一個directory目錄,並命名(本示例中命名為lib);將控件包lib文件夾下的jar(如下圖1)直接復制到程序中新建的目錄下。復制jar文件后,鼠標右鍵點擊jar文件,選擇”Add as Library”。完成導入(如下圖2)。

1

2

方法2:通過maven導入。參考導入方法(https://www.e-iceblue.cn/licensing/install-spirepdf-for-java-from-maven-repository.html)。

Java代碼示例(供參考)

【示例1】添加單一顏色的背景色

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{
        //加載測試文
        String input="test.docx";
        String output="backgroundcolor.docx";
        Document doc = new Document(input);

        //設置單色背景
        doc.getBackground().setType(BackgroundType.Color);
        doc.getBackground().setColor(Color.PINK);

        //保存文檔
        doc.saveToFile(output,FileFormat.Docx_2013);
    }
}

【示例2】添加漸變背景色

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{
        //加載測試文檔
        String input= "test.docx";
        String output="GradientBackgound.docx";
        Document doc = new Document(input);

        //設置漸變色
        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);

        //保存文檔
        doc.saveToFile(output, FileFormat.Docx_2010);
    }
}

【示例3】加載圖片設置成背景

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 {
        //加載文件
        String input= "test.docx";
        String output="ImgBackgound.docx";
        String img= "lye.png";
        Document doc = new Document(input);

        //設置圖片背景
        doc.getBackground().setType(BackgroundType.Picture);
        doc.getBackground().setPicture(img);

        //保存文檔
        doc.saveToFile(output, FileFormat.Docx);
    }
}

(本文完)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM