java操作word,添加页眉,页眉图片,替换书签,添加水印(全)

java操作word文档,添加页眉文本,页眉图片,替换书签,水印

原模板截图:
java操作word,添加页眉,页眉图片,替换书签,添加水印(全)_第1张图片
生成后的文档效果截图:
java操作word,添加页眉,页眉图片,替换书签,添加水印(全)_第2张图片

第一步:引入maven

<dependency>
    <groupId>spire.doc</groupId>
    <artifactId>spire.doc</artifactId>
    <version>2.6.2</version>
</dependency>

第二步:编写操作类,直接上代码,方法都有说明

package com.example.poi_test.util;

import com.spire.doc.*;
import com.spire.doc.documents.*;
import com.spire.doc.fields.DocPicture;
import com.spire.doc.fields.TextRange;
import lombok.Data;

import java.io.FileInputStream;
import java.io.IOException;
import java.util.Map;

/**
 * @author ShenGuiSong
 * @create 2020-03-09 17:35
 */
@Data
public class WordUtil0309 {

    private Document doc = null;


    /**
     * 替换书签
     * @param bookMarks
     */
    public void replaceBookMark(Map<String,String> bookMarks){
        //定位到书签"SimpleBookmark"
        BookmarksNavigator bookmarkNavigator = new BookmarksNavigator(doc);
        if(bookMarks==null || bookMarks.size()<1) return;
        for(Map.Entry<String,String> entry:bookMarks.entrySet()){
            String key=entry.getKey();
            bookmarkNavigator.moveToBookmark(key);
            String value=entry.getValue();
            //使用文本替换原书签的内容, false表示不保留原来的格式
            bookmarkNavigator.replaceBookmarkContent(value, false);
        }

    }

    /**
     * 设置页边距
     * @param top
     * @param bottom
     * @param left
     * @param right
     */
    public void setMargin(Float top,Float bottom,Float left,Float right){
        Section section = doc.getSections().get(0);
        //设置页边距
        if (top != null) {
            section.getPageSetup().getMargins().setTop(top);
        }
        if (bottom != null) {
            section.getPageSetup().getMargins().setBottom(bottom);
        }
        if (left != null) {
            section.getPageSetup().getMargins().setLeft(left);
        }
        if (right != null) {
            section.getPageSetup().getMargins().setRight(right);
        }
    }

    /**
     * 添加图片到页眉
     * @param pic               图片地址
     * @param horizontalOffset  水平偏移量
     * @param verticalPosition  垂直偏移量
     * @param align             图片依左右边距/上下边距对齐方式
     * @param picWidth          图片宽度
     * @param picHeigth         图片高度
     */
    public void addPicToHeader(String pic,Float horizontalOffset,Float verticalPosition,ShapeHorizontalAlignment align,Float picWidth,Float picHeigth ) {
        Section section = doc.getSections().get(0);
        HeaderFooter header = section.getHeadersFooters().getHeader();
        DocPicture headerPicture=null;
        //添加段落到页眉
        //插入图片到页眉的段落
        if(header.getLastParagraph()!=null){
            headerPicture=header.getFirstParagraph().appendPicture(pic);
        }else{
            headerPicture=header.addParagraph().appendPicture(pic);
        }
        headerPicture.setWidth(picWidth);
        headerPicture.setHeight( picHeigth );
        //设置图片水平位置
        if(horizontalOffset !=null && verticalPosition!=null ){
            headerPicture.setHorizontalPosition(horizontalOffset);
            headerPicture.setVerticalPosition(verticalPosition);
        }else{
            headerPicture.setHorizontalAlignment(align);
        }
        //设置文字环绕方式
        headerPicture.setTextWrappingStyle(TextWrappingStyle.Behind);
    }


    /**
     * 添加水印
     * @param pic
     * @param horizontalOffset
     * @param verticalPosition
     * @param picWidth
     * @param picHeigth
     */
    public void addWater(String pic,Float horizontalOffset,Float verticalPosition,Float picWidth,Float picHeigth ) {
        Section section = doc.getSections().get(0);
        HeaderFooter header = section.getHeadersFooters().getHeader();
        DocPicture headerPicture=null;
        if(header.getLastParagraph()!=null){
            headerPicture=header.getFirstParagraph().appendPicture(pic);
        }else{
            headerPicture=header.addParagraph().appendPicture(pic);
        }
        headerPicture.setWidth(picWidth);
        headerPicture.setHeight( picHeigth );
        //设置图片水平位置
        headerPicture.setHorizontalPosition(horizontalOffset);
        headerPicture.setVerticalPosition(verticalPosition);
        //设置文字环绕方式
        headerPicture.setTextWrappingStyle(TextWrappingStyle.Behind);
    }

    /**
     * 添加文本到页眉
     * @param headerContent
     */
    public void addTextToHeader(String headerContent) {
        Section section = doc.getSections().get(0);
        HeaderFooter header = section.getHeadersFooters().getHeader();
        //添加段落到页眉
        Paragraph headerParagraph = header.addParagraph();
        //添加文字到页眉的段落
        TextRange text = headerParagraph.appendText(headerContent);
        text.getCharacterFormat().setFontName("宋体");
        text.getCharacterFormat().setFontSize(11);
        headerParagraph.getFormat().setHorizontalAlignment(HorizontalAlignment.Left);
    }



    /**
     * 获取WordUtil工具类实例
     * @param filePath
     * @return
     */
    public static WordUtil0309 getInstance(String filePath){
        WordUtil0309 wordUtil=new WordUtil0309();
        try {
            //加载word示例文档
            wordUtil.doc = new Document();
            wordUtil.doc.loadFromFile(filePath);
        }catch (Exception e){
            System.out.println("读取文档失败");
            e.printStackTrace();
        }
        return wordUtil;
    }



    /**
     * 保存文档
     * @param outFilePath
     */
    public void saveDocument(String outFilePath){
        try {
            doc.saveToFile(outFilePath);
        } catch (Exception e) {
            System.out.println("保存文档失败");
            e.printStackTrace();
        }
    }

    /**
     * 关闭流
     */
    public void close(){
        try {
            if(doc!=null){
                doc.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


}

第三步 .测试调用

package com.example.poi_test.util;

import com.spire.doc.Document;
import com.spire.doc.Section;
import com.spire.doc.ShapeHorizontalAlignment;
import com.spire.doc.documents.BookmarksNavigator;
import com.spire.doc.documents.Paragraph;
import com.spire.doc.documents.TextBodyPart;
import com.spire.doc.fields.TextRange;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author ShenGuiSong
 * @create 2019-10-19 16:33
 */
public class Test {



    /**
     * 测试
     * @param args
     */
    public static void main(String[] args) {
	WordUtil0309wordUtil=WordUtil0309.getInstance("C:/template/boke.docx");

        Map<String,String> map=new HashMap<>();
        map.put("天气","晴");
        map.put("巡视主要工作内容","测试巡视主要工作内容");
        map.put("巡视施工管理人员情况","imya fdskfjsdkfjsdkfjsdf");
        map.put("日期","2020-03-09");

        wordUtil.replaceBookMark(map);

        wordUtil.setMargin(75f,null,null,null);
        //添加页头logo
        wordUtil.addPicToHeader("c:/template/logo1.jpg",-25f,8f,null,25f,25f);
        //项目名称
        wordUtil.addTextToHeader("测试项目名称");
        //页头二维码
        Float width=wordUtil.getDoc().getSections().get(0).getPageSetup().getClientWidth();
        wordUtil.addPicToHeader("c:/template/qr.jpg",width-50f,-20f,null,60f,60f);

        //添加水印
        wordUtil.addWater("c:/template/water1.jpg",50f,100f,60f,60f);

        wordUtil.saveDocument("C:/template/0219/boke"+
                new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()).substring(8,14)+".docx");
        wordUtil.close();
          }
}

你可能感兴趣的:(java,word)