1秒钟实现Springboot 替换/写入 word文档里面的文字、图片功能

目录
  • 前言
  • 正文

前言

图片加水印:
Springboot 图片需要添加水印,怎么办? 1秒就实现

那么word文档替换文字、插入图片,当然也是1秒钟了(jar包引入,工具类代码复制粘贴,调试,完事)。

事不宜迟,开始敲代码。

正文

本篇内容:

1.word文档 替换内容里面的文字 (模板占位符方式传参替换)

2.word文档 插入图片 (指定位置传参插入)

① pom.xml 引入依赖:

<dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>3.15</version>
        </dependency>

        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-scratchpad</artifactId>
            <version>3.15</version>
        </dependency>

② 工具类  MyDocxUtil.java

import org.apache.poi.POIXMLDocument;
import org.apache.poi.xwpf.usermodel.*;
import java.io.FileOutputStream;
import java.util.*;
import java.util.Map.Entry;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class MyDocxUtil {
    /**
     * 文字替换
     * @param srcPath
     * @param destPath
     * @param map
     */
    public static void searchAndReplace(String srcPath, String destPath, Map<String, String> map) {
        try {
            //doc文件使用HWPFDocument读取,docx文件使用XWPFDocument读取。
            XWPFDocument document = new XWPFDocument(POIXMLDocument.openPackage(srcPath));
            /**
             * 替换段落中的指定文字
             */
            Iterator<XWPFParagraph> itPara = document.getParagraphsIterator();
            while (itPara.hasNext()) {
                XWPFParagraph paragraph = (XWPFParagraph) itPara.next();
                Set<String> set = map.keySet();
                Iterator<String> iterator = set.iterator();
                while (iterator.hasNext()) {
                    String key = iterator.next();
                    List<XWPFRun> run=paragraph.getRuns();
                    for(int i=0;i<run.size();i++)
                    {
                        if(run.get(i).getText(run.get(i).getTextPosition())!=null &&
                                run.get(i).getText(run.get(i).getTextPosition()).equals(key))
                        {
                            /**
                             * 参数0表示生成的文字是要从哪一个地方开始放置,设置文字从位置0开始
                             * 就可以把原来的文字全部替换掉了
                             */
                            run.get(i).setText(map.get(key),0);
                        }
                    }
                }
            }

            /**
             * 替换表格中的指定文字
             */
            Iterator<XWPFTable> itTable = document.getTablesIterator();
            while (itTable.hasNext()) {
                XWPFTable table = (XWPFTable) itTable.next();
                int count = table.getNumberOfRows();
                for (int i = 0; i < count; i++) {
                    XWPFTableRow row = table.getRow(i);
                    List<XWPFTableCell> cells = row.getTableCells();
                    for (XWPFTableCell cell : cells) {
                        for (Entry<String, String> e : map.entrySet()) {
                            if (cell.getText().equals(e.getKey())) {
                                cell.removeParagraph(0);
                                cell.setText(e.getValue());
                            }
                        }
                    }
                }
            }
            FileOutputStream outStream = null;
            outStream = new FileOutputStream(destPath);
            document.write(outStream);
            outStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    public static void main(String[] args) {
        Map<String, String> map = new HashMap<>();
        map.put("<v1>", "认可");
        map.put("<phone>", "136919xxxxx");
        map.put("<地址>", "中国广东省深圳市");
        String srcPath = "D:\\test.docx";
        String destPath = "D:\\mytestNew.docx";
        searchAndReplace(srcPath, destPath, map);
        System.out.println("操作完毕");
    }
}

③ 调试

准备一个简单的word内容文档, 假装这就是我们业务需求使用的模板内容:

可以看到 我这个模板内容里面,有三个类似站位符的内容(红色标识)

然后对照看下怎么用这个工具类,传参来替换这个模板内容的文字:

    public static void main(String[] args) {
        Map<String, String> map = new HashMap<>();
        map.put("<v1>", "认可");
        map.put("<phone>", "136919xxxxx");
        map.put("<地址>", "中国广东省深圳市");
        String srcPath = "D:\\test.docx";
        String destPath = "D:\\mytestNew.docx";
        searchAndReplace(srcPath, destPath, map);
        System.out.println("操作完毕");
    }

代码简析:

运行方法,看看效果:

效果:

好了文字替换玩了一下,接下来玩下插入图片:

先准备一张 ‘公章’图片:

然后在模板文档里面, 需要盖章的地方 ,设置一个占位标识 :

然后加下插入图片的函数代码:

    /**
     * <b> Word中添加图章
     * </b><br><br><i>Description</i> :
     * String srcPath, 源Word路径
     * String storePath, 添加图章后的路径
     * String sealPath, 图章路径(即图片)
     * tString abText, 在Word中盖图章的标识字符串,如:(签字/盖章)
     * int width, 图章宽度
     * int height, 图章高度
     * int leftOffset, 图章在编辑段落向左偏移量
     * int topOffset, 图章在编辑段落向上偏移量
     * boolean behind,图章是否在文字下面
     *
     * @return void
     * <br><br>Date: 2019/12/26 15:12     <br>Author : dxl
     */
    public static void sealInWord(String srcPath, String storePath, String sealPath, String tabText,
                                  int width, int height, int leftOffset, int topOffset, boolean behind) throws Exception {
        File fileTem = new File(srcPath);
        InputStream is = new FileInputStream(fileTem);
        XWPFDocument document = new XWPFDocument(is);
        List<XWPFParagraph> paragraphs = document.getParagraphs();
        XWPFRun targetRun = null;
        for (XWPFParagraph paragraph : paragraphs) {
            if (!"".equals(paragraph.getText()) && paragraph.getText().contains(tabText)) {
                List<XWPFRun> runs = paragraph.getRuns();
                targetRun = runs.get(runs.size() - 1);
            }
        }
        if (targetRun != null) {
            InputStream in = new FileInputStream(sealPath);//设置图片路径
            if (width <= 0) {
                width = 100;
            }
            if (height <= 0) {
                height = 100;
            }
            //创建Random类对象
            Random random = new Random();
            //产生随机数
            int number = random.nextInt(999) + 1;
            targetRun.addPicture(in, Document.PICTURE_TYPE_PNG, "Seal" + number, Units.toEMU(width), Units.toEMU(height));
            in.close();
            // 2. 获取到图片数据
            CTDrawing drawing = targetRun.getCTR().getDrawingArray(0);
            CTGraphicalObject graphicalobject = drawing.getInlineArray(0).getGraphic();

            //拿到新插入的图片替换添加CTAnchor 设置浮动属性 删除inline属性
            CTAnchor anchor = getAnchorWithGraphic(graphicalobject, "Seal" + number,
                    Units.toEMU(width), Units.toEMU(height),//图片大小
                    Units.toEMU(leftOffset), Units.toEMU(topOffset), behind);//相对当前段落位置 需要计算段落已有内容的左偏移
            drawing.setAnchorArray(new CTAnchor[]{anchor});//添加浮动属性
            drawing.removeInline(0);//删除行内属性
        }
        document.write(new FileOutputStream(storePath));
        document.close();
    }

    /**
     * @param ctGraphicalObject 图片数据
     * @param deskFileName      图片描述
     * @param width             宽
     * @param height            高
     * @param leftOffset        水平偏移 left
     * @param topOffset         垂直偏移 top
     * @param behind            文字上方,文字下方
     * @return
     * @throws Exception
     */
    public static CTAnchor getAnchorWithGraphic(CTGraphicalObject ctGraphicalObject,
                                                String deskFileName, int width, int height,
                                                int leftOffset, int topOffset, boolean behind) {
        System.out.println(">>width>>" + width + "; >>height>>>>" + height);
        String anchorXML =
                "<wp:anchor xmlns:wp=\"http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing\" "
                        + "simplePos=\"0\" relativeHeight=\"0\" behindDoc=\"" + ((behind) ? 1 : 0) + "\" locked=\"0\" layoutInCell=\"1\" allowOverlap=\"1\">"
                        + "<wp:simplePos x=\"0\" y=\"0\"/>"
                        + "<wp:positionH relativeFrom=\"column\">"
                        + "<wp:posOffset>" + leftOffset + "</wp:posOffset>"
                        + "</wp:positionH>"
                        + "<wp:positionV relativeFrom=\"paragraph\">"
                        + "<wp:posOffset>" + topOffset + "</wp:posOffset>" +
                        "</wp:positionV>"
                        + "<wp:extent cx=\"" + width + "\" cy=\"" + height + "\"/>"
                        + "<wp:effectExtent l=\"0\" t=\"0\" r=\"0\" b=\"0\"/>"
                        + "<wp:wrapNone/>"
                        + "<wp:docPr id=\"1\" name=\"Drawing 0\" descr=\"" + deskFileName + "\"/><wp:cNvGraphicFramePr/>"
                        + "</wp:anchor>";

        CTDrawing drawing = null;
        try {
            drawing = CTDrawing.Factory.parse(anchorXML);
        } catch (XmlException e) {
            e.printStackTrace();
        }
        CTAnchor anchor = drawing.getAnchorArray(0);
        anchor.setGraphic(ctGraphicalObject);
        return anchor;
    }

调用一下函数玩下:

    public static void main(String[] args) throws Exception {
        sealInWord("D:\\mytestNew.docx",
                "D:\\mytestWithImg.docx",
                "D:\\gz.png", "(印章)", 0, 0,
                310, 110, false);
    }

代码简析:

运行一下,打开新文件看看效果:

好了,该篇就到这吧。

到此这篇关于Springboot 替换/写入 word文档里面的文字、图片,1秒钟实现的文章就介绍到这了,更多相关Springboot 替换word文档文字内容请搜索我们以前的文章或继续浏览下面的相关文章希望大家以后多多支持我们!

(0)

相关推荐

  • springboot实现通过路径从磁盘直接读取图片

    目录 通过路径从磁盘直接读取图片 访问本地(磁盘)图片 通过路径从磁盘直接读取图片 这段时间在做Springboot和Vue的例子,读取图片给出路径直接可以读,太方便了,一直么有搞懂为什么. 后面看到原来是在配置文件MyWebConfigurer中addResourceHandlers方法中增加了 registry.addResourceHandler("/api/file/**").addResourceLocations("file:" + "d:/w

  • SpringBoot上传图片到指定位置并返回URL的实现

    目录 需求 前端部分(ElementUI+Vue.js) 后端部分(SpringBoot) 1.先配置application.yml文件 2.映射资源-重写WebMvcConfigurer接口,实现对资源的映射 3.Controller代码 想做一个上传图片的功能,来展示用户上传的图片. 在返回给前端的URL上弄了好久,前端一直无法访问到URL,结果一直显示404. 倒腾了一上午发现是 文件路径映射的问题,后端部分有讲解决办法,可供大家参考 需求 前端的图片上传到服务器指定的文件目录,并且将UR

  • 1秒实现Springboot 图片添加水印功能

    目录 前言 正文 前言 真的一秒就可以实现么? 是的,因为我们直接复制粘贴工具类拿来用就可以. 正文 工具类 WaterMarkUtil.java package com.example.dotest.util; import java.awt.AlphaComposite; import java.awt.Color; import java.awt.Font; import java.awt.Graphics2D; import java.awt.Image; import java.awt

  • SpringBoot接口中如何直接返回图片数据

    目录 接口直接返回图片数据 起因 类似这种 根据个人经验 优雅的实现图片返回 接口直接返回图片数据 起因 最近在做涉及到分享推广的业务,需要由业务员分享二维码进入推广页面,由于是新项目,前期预算和用量都有限,没有搭建对象存储服务,所以决定使用后台服务动态生成二维码图片直接图片数据并返回. 首先是二维码的生成,决定使用google的zxing,毕竟google的东西还是不错的,maven添加依赖如下: <!-- https://mvnrepository.com/artifact/com.goog

  • 1秒钟实现Springboot 替换/写入 word文档里面的文字、图片功能

    目录 前言 正文 前言 图片加水印:Springboot 图片需要添加水印,怎么办? 1秒就实现 那么word文档替换文字.插入图片,当然也是1秒钟了(jar包引入,工具类代码复制粘贴,调试,完事). 事不宜迟,开始敲代码. 正文 本篇内容: 1.word文档 替换内容里面的文字 (模板占位符方式传参替换) 2.word文档 插入图片 (指定位置传参插入) ① pom.xml 引入依赖: <dependency> <groupId>org.apache.poi</groupI

  • 在PHP中读取和写入WORD文档的代码

    复制代码 代码如下: <?  // 建立一个指向新COM组件的索引  $word = new COM("word.application") or die("Can't start Word!");  // 显示目前正在使用的Word的版本号  //echo "Loading Word, v. {$word->Version}<br>";  // 把它的可见性设置为0(假),如果要使它在最前端打开,使用1(真)  // t

  • SpringBoot如何实现word文档转pdf

    目录 一.背景 二.方案选择 1.Spire.Doc for Java方案 2.docx4j方案 3.jodconverter+LibreOffice 方案 4.其他 三.实操 1.docx4j 2.poi-tl+jodconverter+LibreOffice 方案 四.结论 1.docx4j方案 2.jodconverter+LibreOffice 方案 一.背景 项目中有个需求大体意思是,上传一个word模板,根据word模板合成word文件,再将word文件转为pdf. 二.方案选择 1

  • 如何基于python把文字图片写入word文档

    安装代码 pip install python-docx 1.批量化往word文件中添加大批量重复的数据 from docx import Document from docx.enum.text import WD_ALIGN_PARAGRAPH from docx.shared import Pt #磅数 from docx.oxml.ns import qn #中文格式 #以上是docx库中需要用到的部分 import time price = input('请输入今日价格:') comp

  • php在程序中将网页生成word文档并提供下载的代码

    在这篇文章中主要解决两个问题: 1:在php中如何把html中的内容生成到word文档中 2:php把html中的内容生成到word文档中时,不居中显示问题,即会默认按照web视图进行显示. 3:php把html中的内容生成到word文档中时,相关样式不兼容问题 正文: 复制代码 代码如下: echo '<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:w="urn:schemas-microso

  • 使用PHPWord生成word文档的方法详解

    本文实例讲述了使用PHPWord生成word文档的方法.分享给大家供大家参考,具体如下: 有时我们需要把网页内容保存为Word文档格式,以供其他人员查看和编辑.PHPWord是一个用纯PHP编写的库,使用PHPWord可以轻松处理word文档内容,生成你想要的word文档. 下载源码 安装 我们使用Composer 来安装PHPWord. composer require phpoffice/phpword 如何使用 自动加载 安装好phpword后,新建一个php文档,引入autoload.p

  • Java 如何将表格数据导入word文档中

    Java 表格数据导入word文档中 个人觉得这个功能实在搞笑,没什么意义,没办法提了需求就要实现,(太好说话了把我) 我的实现是再word中生成一个与 excel行,列 一样的一个表格,然后把从excel拿到的数据(exList参数)依次放到word表格中 public static void createFile(HttpServletResponse response, String fileName, List<List<String>> exList) { try { s

  • Java 替换word文档文字并指定位置插入图片

    先说下 需要的依赖包 <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-excelant</artifactId> <version>3.12</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <arti

  • 使用Python通过win32 COM实现Word文档的写入与保存方法

    通过win32 COM接口实现软件的操作本质上来看跟直接操作软件一致,这跟我之前经常用的通过各种扩展的组件或者库实现各种文件的处理有较大的差异.如果有过Windows下使用Word的经历,那么使用win32 COM应该说是更为便捷的一种方式. 先前通过拼凑网络上的代码实现过Word文档的处理,今天通过读文档从头开始做一次新的尝试.简单实现一个Word文件的创建.写入与存储. 实现的代码如下: #!/usr/bin/python import os from win32com.client imp

  • Java SpringBoot集成文件之如何使用POI导出Word文档

    目录 前言 知识准备 什么是POI 实现案例 Pom依赖 导出Word 前言 通过Apache POI导出excel,而Apache POI包含是操作Office Open XML(OOXML)标准和微软的OLE 2复合文档格式(OLE2)的Java API.所以也是可以通过POI来导出word的.本文主要介绍通过SpringBoot集成POI工具实现Word的导出功能. 知识准备 需要理解Apache POI遵循的标准(Office Open XML(OOXML)标准和微软的OLE 2复合文档

随机推荐