java poi 操作word模板生成文件 去除word水印图片+文中图片+边框

package com.zvalley.epp.test;

import com.deepoove.poi.XWPFTemplate;
import com.deepoove.poi.data.PictureRenderData;
import com.zvalley.epp.util.ImageUtil;
import io.jsonwebtoken.lang.Assert;
import lombok.SneakyThrows;
import org.apache.poi.xwpf.model.XWPFHeaderFooterPolicy;
import org.apache.poi.xwpf.usermodel.*;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTSectPr;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.STHdrFtr;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class TestWordFomatAndDeleteWaterMarkAnd2Pdf {


    @SneakyThrows
    public static void main(String[] args) {
        press("55");
//        press("11");
    }


    @SneakyThrows
    public static void press(String fileName) {
        Map params = new HashMap<>();

        params.put("qrCode", new PictureRenderData(60, 60, ".png", ImageUtil.createQrCode("http://mds.zvos.zoomlion.com/#/login?redirect=%2Fhome", 60)));
        params.put("barCode", new PictureRenderData(160, 40, ".png", ImageUtil.createBarCodeWithLabel("12345678235523")));
        params.put("no", "12345678");
        params.put("y", "2022");
        params.put("m", "01");
        params.put("d", "03");
        String templatePath = "C:\\Users\\zhangnayi\\Desktop\\model\\" + fileName + ".docx";
        String fileDir = "C:\\Users\\zhangnayi\\Desktop\\model\\";
        String wordPath = TestWordTemplate.createWord(templatePath, fileDir, fileName + "-format", params);
        System.out.println("生成文档路径:" + wordPath);

        InputStream is = new FileInputStream("C:\\Users\\zhangnayi\\Desktop\\model\\" + fileName + "-format.docx");
        XWPFDocument doc = new XWPFDocument(is);

        // 除去边框
        CTSectPr sectPr = doc.getDocument().getBody().getSectPr();
        sectPr.setPgBorders(null);

        doc.getHeaderList().forEach(hd -> {
            hd.getListParagraph().forEach(pg -> {
                removeParagraphPicture(pg);
            });
        });
        // 出去水印
        removeHeadPicture(doc, STHdrFtr.DEFAULT);
        // 去除印章
        doc.getParagraphs().forEach(pg -> {
            removeParagraphPicture(pg);
        });

        // 去除印章
        doc.getTables().forEach(tbl -> {
            tbl.getRows().forEach(row -> {
                row.getTableCells().forEach(cell -> {
                    cell.getParagraphs().forEach(pg -> {
                        removeParagraphPicture(pg);
                    });
                });
            });
        });

        FileOutputStream outStream = new FileOutputStream("C:\\Users\\zhangnayi\\Desktop\\model\\" + fileName + "-delete-watermark.docx");
        doc.write(outStream);
    }

    /**
     * 根据模板填充内容生成word
     * 调用方法参考下面的main方法,详细文档参考官方文档
     * Poi-tl模板引擎官方文档:http://deepoove.com/poi-tl/
     *
     * @param templatePath word模板文件路径
     * @param fileDir      生成的文件存放地址
     * @param fileName     生成的文件名,不带格式。假如要生成abc.docx,则fileName传入abc即可
     * @param paramMap     替换的参数集合
     * @return 生成word成功返回生成的文件的路径,失败返回空字符串
     */
    public static String createWord(String templatePath, String fileDir, String fileName, Map paramMap) {
        Assert.notNull(templatePath, "word模板文件路径不能为空");
        Assert.notNull(fileDir, "生成的文件存放地址不能为空");
        Assert.notNull(fileName, "生成的文件名不能为空");

        // 生成的word格式
        String formatSuffix = ".docx";
        // 拼接后的文件名
        fileName = fileName + formatSuffix;

        // 生成的文件的存放路径
        if (!fileDir.endsWith("/")) {
            fileDir = fileDir + File.separator;
        }

        File dir = new File(fileDir);
        if (!dir.exists()) {
            dir.mkdirs();
        }

        String filePath = fileDir + fileName;
        // 读取模板templatePath并将paramMap的内容填充进模板,即编辑模板+渲染数据
        XWPFTemplate template = XWPFTemplate.compile(templatePath).render(paramMap);
        try {
            // 将填充之后的模板写入filePath
            template.writeToFile(filePath);
            template.close();
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
        return filePath;
    }

    private static void removeParagraphPicture(XWPFParagraph paragraph) {
        List runs = paragraph.getRuns();
        for (int i = 0; i < runs.size(); i++) {
            List pics = runs.get(i).getEmbeddedPictures();
            if (pics.size() > 0) {
                paragraph.removeRun(i);
            }
        }
    }

    private static void removeHeadPicture(XWPFDocument doc, STHdrFtr.Enum enu) {
        XWPFHeaderFooterPolicy headerFooterPolicy = doc.getHeaderFooterPolicy();
        XWPFHeader header = headerFooterPolicy.getHeader(enu);
        if (header != null && header.getListParagraph() != null && header.getListParagraph().size() > 0) {
            for (int i = 0, len = header.getListParagraph().size(); i < len; i++) {
                XWPFParagraph paragraph = header.getParagraphArray(i);
                removeParagraphPicture(paragraph);
            }
        }
    }
}
package com.zvalley.epp.util;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.oned.Code128Writer;
import com.google.zxing.qrcode.QRCodeWriter;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import org.krysalis.barcode4j.impl.code128.Code128Bean;
import org.krysalis.barcode4j.output.bitmap.BitmapCanvasProvider;
import org.krysalis.barcode4j.tools.UnitConv;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.util.Hashtable;

public class ImageUtil {

    /**
     * 生成包含字符串信息的二维码图片
     *
     * @param content    二维码携带信息
     * @param qrCodeSize 二维码图片大小
     * @throws WriterException
     */
    public static BufferedImage createQrCode(String content, int qrCodeSize) throws WriterException {
        //设置二维码纠错级别MAP
        Hashtable hintMap = new Hashtable<>();
        // 矫错级别
        hintMap.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L);
        hintMap.put(EncodeHintType.MARGIN, 0);
        QRCodeWriter qrCodeWriter = new QRCodeWriter();
        //创建比特矩阵(位矩阵)的QR码编码的字符串
        BitMatrix byteMatrix = qrCodeWriter.encode(content, BarcodeFormat.QR_CODE, qrCodeSize, qrCodeSize, hintMap);
        // 使BufferedImage勾画QRCode  (matrixWidth 是行二维码像素点)
        int matrixWidth = byteMatrix.getWidth();
        BufferedImage image = new BufferedImage(matrixWidth, matrixWidth, BufferedImage.TYPE_INT_RGB);
        image.createGraphics();
        Graphics2D graphics = (Graphics2D) image.getGraphics();
        graphics.setColor(Color.WHITE);
        graphics.fillRect(0, 0, matrixWidth, matrixWidth);
        // 使用比特矩阵画并保存图像
        graphics.setColor(Color.BLACK);
        for (int i = 0; i < matrixWidth; i++) {
            for (int j = 0; j < matrixWidth; j++) {
                if (byteMatrix.get(i, j)) {
                    graphics.fillRect(i, j, 1, 1);
                }
            }
        }
        return image;
    }

    /**
     * 生成包含字符串信息的条形码图片
     *
     * @param strCode128
     * @return
     * @throws WriterException
     */
    public static BufferedImage createBarCode(String strCode128) throws WriterException {
        BitMatrix bitMatrix = new Code128Writer().encode(strCode128, BarcodeFormat.CODE_128, 96, 40, null);
        return MatrixToImageWriter.toBufferedImage(bitMatrix);
    }


    /**
     * 生成到流
     *
     * @param msg
     */
    public static BufferedImage createBarCodeWithLabel(String msg) {
        ByteArrayOutputStream ous = new ByteArrayOutputStream();
        Code128Bean bean = new Code128Bean();
        // 精细度
        final int dpi = 150;
        // module宽度
        final double moduleWidth = UnitConv.in2mm(2.0f / dpi);
        // 配置对象
        bean.setModuleWidth(moduleWidth);
        bean.doQuietZone(false);
        String format = "image/png";
        try {
            BitmapCanvasProvider canvas = new BitmapCanvasProvider(ous, format, dpi, BufferedImage.TYPE_BYTE_BINARY, false, 0);
            bean.generateBarcode(canvas, msg);
            canvas.finish();
            ous.close();
            ByteArrayInputStream in = new ByteArrayInputStream(ous.toByteArray());
            BufferedImage image = ImageIO.read(in);
            return image;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 测试代码
     *
     * @throws WriterException
     */
    public static void main(String[] args) throws IOException, WriterException {
        File f1 = new File("f1.png");
        File f2 = new File("f2.png");
        ImageIO.write(createQrCode("http://xxgk.vecc.org.cn/vin/SDFDSAGDGDSGDSGSS", 116), "jpg", f1);
        ImageIO.write(createBarCodeWithLabel("SDFDSAGDGDSGDSGSS"), "jpg", f2);

    }
}

 

maven依赖

       
            org.apache.poi
            poi-ooxml-schemas
            4.1.1
        
        
            org.apache.poi
            ooxml-schemas
            1.1
        
        
            com.deepoove
            poi-tl
            1.8.0
        
       
            com.google.zxing
            core
            3.3.0
        
        
            com.google.zxing
            javase
            3.0.0
        
        
            net.sf.barcode4j
            barcode4j-light
            2.0
        

 

你可能感兴趣的:(java poi 操作word模板生成文件 去除word水印图片+文中图片+边框)