使用spire工具类操作word文档向指定标签内插入图片和文字

一、依赖添加

建议使用本小编的依赖,下载地址方式见标题下,手动添加到本地依赖


        e-iceblue 
       spire.doc
       3.2.3

倘若你使用官网其他版本的话你需要加上maven库,以访问下载

    
        
            com.e-iceblue
            e-iceblue
            http://repo.e-iceblue.com/nexus/content/groups/public/
        
    

二、替换标签类

本小编将替换文本和图片的分成了两个方法,以及替换表格的替换的。可以参考本博进行代码修改一块保存。其中filepath是存储路径,docurl是文本路径,map是存的标签和要插入的内容,filename是与保存文件名称

import com.spire.doc.Document;
import com.spire.doc.FileFormat;
import com.spire.doc.Table;
import com.spire.doc.TableRow;
import com.spire.doc.documents.*;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import com.spire.doc.fields.TextRange;

public class WordUtil {
    //图片替换文档内标签
    public String ReplaceBookmarkWithImg (String filePath, String docUrl, Map con, String fileName) {
        //加载包含书签的文档
        Document doc = new Document();
        doc.loadFromFile(docUrl);

        Iterator iter = con.entrySet().iterator();
        while (iter.hasNext()) {
            Map.Entry entry = (Map.Entry) iter.next();
            String lable = entry.getKey().toString();
            String content = entry.getValue().toString();

        //定位到指定书签位置
        BookmarksNavigator bookmarksNavigator = new BookmarksNavigator(doc);
        bookmarksNavigator.moveToBookmark(lable, true, true);

        //添加图片,替换原有书签内容
        Paragraph para = new Paragraph(doc);
        para.appendPicture(content);
        TextBodyPart bodyPart = new TextBodyPart(doc);
        bodyPart.getBodyItems().add(para);
        bookmarksNavigator.replaceBookmarkContent(bodyPart);
        }

        //保存文档
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        String nowDate = format.format(new Date());
        String docInfo = filePath+"/"+ fileName + ".docx";
        String pdfInfo = filePath+"/"+ fileName+"123" + ".pdf";
        String pdfName = fileName + ".pdf";
        //保存doc文档
        doc.saveToFile(docInfo, FileFormat.Docx_2013);
        //保存pdf文档__需要花钱
        doc.saveToFile(pdfInfo, FileFormat.PDF);
        //word转pdf
        WordToPdf wordToPdf = new WordToPdf();
        wordToPdf.changeType(docInfo,pdfInfo);
        doc.dispose();
        return pdfName;
    }
    //文字替换标签
    public String ReplaceBookmarkContentWithNewContent(String filePath, String docUrl, Map con){
        //创建文档对象
        Document doc = new Document();
        //加载包含书签的Word文档
        doc.loadFromFile(docUrl);
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        String nowDate = format.format(new Date());
        String docInfo = filePath+"/"+nowDate + ".docx";

        Iterator iter = con.entrySet().iterator();
        while (iter.hasNext()) {
            Map.Entry entry = (Map.Entry) iter.next();
            String lable = entry.getKey().toString();
            String content = entry.getValue().toString();

        //定位到指定书签位置
        BookmarksNavigator bookmarksNavigator = new BookmarksNavigator(doc);
        bookmarksNavigator.moveToBookmark(lable);

        //用文本内容替换原有书签位置的文本,新替换的内容与原文格式一致
        bookmarksNavigator.replaceBookmarkContent(content, true);
        }
        //保存文档
        doc.saveToFile(docInfo,FileFormat.Docx_2013);

        doc.dispose();
        return docInfo;
    }

    //延伸方法:在标签处插入表格
    public void ReplaceBookmarkContentWithTable(String docUrl) {
        //加载包含书签的Word文档
        Document doc = new Document();
        doc.loadFromFile(docUrl);
        /***************公司基本信息-分支机构*****************/
        //声明数组内容
        String[][] data =
                {
                        new String[]{"分类", "等级", "编号"},
                        new String[]{"A", "一级", "01A"},
                        new String[]{"B", "二级", "02B"},
                        new String[]{"C", "三级", "03C"},
                };

        //创建表格
        Table table = new Table(doc, true);
        table.resetCells(4, 3);
        for (int i = 0; i < data.length; i++) {
            TableRow dataRow = table.getRows().get(i);
            for (int j = 0; j < data[i].length; j++) {
                TextRange range = dataRow.getCells().get(j).addParagraph().appendText(data[i][j]);
                range.getOwnerParagraph().getFormat().setHorizontalAlignment(HorizontalAlignment.Center);
                range.getCharacterFormat().setFontName("楷体");
                dataRow.getRowFormat().setHorizontalAlignment(RowAlignment.Center);
                dataRow.getCells().get(j).getCellFormat().setVerticalAlignment(VerticalAlignment.Middle);
            }
        }

        //创建TextBodyPart对象
        TextBodyPart bodyPart= new TextBodyPart(doc);
        bodyPart.getBodyItems().add(table);

        //定位到指定书签位置
        BookmarksNavigator bookmarkNavigator = new BookmarksNavigator(doc);
        bookmarkNavigator.moveToBookmark("bookmark1");

        //使用表格替换原书签的内容
        bookmarkNavigator.replaceBookmarkContent(bodyPart);

        //保存文档
        doc.saveToFile("replaceWithTable.docx", FileFormat.Docx);
        doc.dispose();
    }

    //在标签处插入表格
    public void ReplaceBookmarkContentWithTableCompany(String docUrl, Map>> tableListMap) {
        //加载包含书签的Word文档
        Document doc = new Document();
        doc.loadFromFile(docUrl);
        for(String key : tableListMap.keySet()){
            List> tableList = tableListMap.get(key);
            //创建表格
            Table table = new Table(doc, true);
            table.resetCells(tableList.size(), tableList.get(0).size());
            for (int i = 0; i < tableList.size(); i++) {
                TableRow dataRow = table.getRows().get(i);
                for (int j = 0; j < tableList.get(i).size(); j++) {
                    TextRange range = dataRow.getCells().get(j).addParagraph().appendText(tableList.get(i).get(j));
                    range.getOwnerParagraph().getFormat().setHorizontalAlignment(HorizontalAlignment.Center);
                    range.getCharacterFormat().setFontName("楷体");
                    dataRow.getRowFormat().setHorizontalAlignment(RowAlignment.Center);
                    dataRow.getCells().get(j).getCellFormat().setVerticalAlignment(VerticalAlignment.Middle);
                }
            }
            //创建TextBodyPart对象
            TextBodyPart bodyPart= new TextBodyPart(doc);
            bodyPart.getBodyItems().add(table);

            //定位到指定书签位置
            BookmarksNavigator bookmarkNavigator = new BookmarksNavigator(doc);
            bookmarkNavigator.moveToBookmark(key);
            //使用表格替换原书签的内容
            bookmarkNavigator.replaceBookmarkContent(bodyPart);

        }
        doc.saveToFile(docUrl, FileFormat.Docx);
        doc.dispose();
    }
}

 

你可能感兴趣的:(经验总结)