java动态替换word中的变量,同时将word转pdf

该博客介绍了一个Java方法,通过Apache POI库动态替换docx模板文件中的内容,并将其转换为PDF。首先,使用POI读取模板文件,遍历段落和表格替换变量,然后保存为新的docx文件。接着,使用转换工具将docx文件转换为PDF,处理中文字体以确保显示正确。此过程适用于自动化文档生成和定制。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

模板图

 word效果

pdf效果图 

 

第一步:java动态生成模板

package com.xio.emp.util;

import org.apache.poi.xwpf.usermodel.*;

import java.io.*;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class POIUtil {

    /**
     * 用一个docx文档作为模板,然后替换其中的内容,再写入目标文档中。
     * @throws Exception
     */
    public static OutputStream templateWrite(String filePath, String outFilePath, Map<String, Object> params) throws Exception {
        InputStream is = new FileInputStream(filePath);
        XWPFDocument doc = new XWPFDocument(is);
        //替换段落里面的变量
        replaceInPara(doc, params);
        //替换表格里面的变量
        replaceInTable(doc, params);
        OutputStream os = new FileOutputStream(outFilePath);
        doc.write(os);
        close(os);
        close(is);
        return os;
    }

    /**
     * 替换段落里面的变量
     * @param doc 要替换的文档
     * @param params 参数
     */
    private static void replaceInPara(XWPFDocument doc, Map<String, Object> params) {
        Iterator<XWPFParagraph> iterator = doc.getParagraphsIterator();
        XWPFParagraph para;
        while (iterator.hasNext()) {
            para = iterator.next();
            replaceInPara(para, params);
        }
    }

    /**
     * 替换段落里面的变量
     *
     * @param para   要替换的段落
     * @param params 参数
     */
    private static void replaceInPara(XWPFParagraph para, Map<String, Object> params) {
        List<XWPFRun> runs;
        Matcher matcher;
        String runText = "";
        int fontSize = 0;
        UnderlinePatterns underlinePatterns = null;
        if (matcher(para.getParagraphText()).find()) {
            runs = para.getRuns();
            if (runs.size() > 0) {
                int j = runs.size();
                for (int i = 0; i < j; i++) {
                    XWPFRun run = runs.get(0);
                    if (fontSize == 0) {
                        fontSize = run.getFontSize();
                    }
                    if(underlinePatterns==null){
                        underlinePatterns=run.getUnderline();
                    }
                    String i1 = run.toString();
                    runText += i1;
                    para.removeRun(0);
                }
            }
            matcher = matcher(runText);
            if (matcher.find()) {
                while ((matcher = matcher(runText)).find()) {
                    runText = matcher.replaceFirst(String.valueOf(params.get(matcher.group(1))));
                }
                //直接调用XWPFRun的setText()方法设置文本时,在底层会重新创建一个XWPFRun,把文本附加在当前文本后面,
                //所以我们不能直接设值,需要先删除当前run,然后再自己手动插入一个新的run。
                //para.insertNewRun(0).setText(runText);//新增的没有样式
                XWPFRun run = para.createRun();
                run.setText(runText,0);
                run.setFontSize(fontSize);
                run.setUnderline(underlinePatterns);
                run.setFontFamily("仿宋");//字体
                run.setFontSize(16);//字体大小
                //run.setBold(true); //加粗
                //run.setColor("FF0000");
                //默认:宋体(wps)/等线(office2016) 5号 两端对齐 单倍间距
                //run.setBold(false);//加粗
                //run.setCapitalized(false);//我也不知道这个属性做啥的
                //run.setCharacterSpacing(5);//这个属性报错
                //run.setColor("BED4F1");//设置颜色--十六进制
                //run.setDoubleStrikethrough(false);//双删除线
                //run.setEmbossed(false);//浮雕字体----效果和印记(悬浮阴影)类似
                //run.setFontFamily("宋体");//字体
                //run.setFontFamily("华文新魏", FontCharRange.cs);//字体,范围----效果不详
                //run.setFontSize(14);//字体大小
                //run.setImprinted(false);//印迹(悬浮阴影)---效果和浮雕类似
                //run.setItalic(false);//斜体(字体倾斜)
                //run.setKerning(1);//字距调整----这个好像没有效果
                //run.setShadow(true);//阴影---稍微有点效果(阴影不明显)
                //run.setSmallCaps(true);//小型股------效果不清楚
                //run.setStrike(true);//单删除线(废弃)
                //run.setStrikeThrough(false);//单删除线(新的替换Strike)
                //run.setSubscript(VerticalAlign.SUBSCRIPT);//下标(吧当前这个run变成下标)---枚举
                //run.setTextPosition(20);//设置两行之间的行间距
                //run.setUnderline(UnderlinePatterns.DASH_LONG);//各种类型的下划线(枚举)
                //run0.addBreak();//类似换行的操作(html的  br标签)
                //run0.addTab();//tab键
                //run0.addCarriageReturn();//回车键
                //注意:addTab()和addCarriageReturn() 对setText()的使用先后顺序有关:比如先执行addTab,再写Text这是对当前这个Text的Table,反之是对下一个run的Text的Tab效果


            }
        }

    }


    /**
     * 替换表格里面的变量
     * @param doc 要替换的文档
     * @param params 参数
     */
    private static void replaceInTable(XWPFDocument doc, Map<String, Object> params) {
        Iterator<XWPFTable> iterator = doc.getTablesIterator();
        XWPFTable table;
        List<XWPFTableRow> rows;
        List<XWPFTableCell> cells;
        List<XWPFParagraph> paras;
        while (iterator.hasNext()) {
            table = iterator.next();
            rows = table.getRows();
            for (XWPFTableRow row : rows) {
                cells = row.getTableCells();
                for (XWPFTableCell cell : cells) {
                    paras = cell.getParagraphs();
                    for (XWPFParagraph para : paras) {
                        replaceInPara(para, params);
                    }
                }
            }
        }
    }

    /**
     * 正则匹配字符串
     * @param str
     * @return
     */
    private static Matcher matcher(String str) {
        Pattern pattern = Pattern.compile("\\$\\{(.+?)\\}", Pattern.CASE_INSENSITIVE);
        Matcher matcher = pattern.matcher(str);
        return matcher;
    }

    /**
     * 关闭输入流
     * @param is
     */
    private static void close(InputStream is) {
        if (is != null) {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 关闭输出流
     * @param os
     */
    private static void close(OutputStream os) {
        if (os != null) {
            try {
                os.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}

 @SneakyThrows
    @Override
    public void printModelToPDF(TrustInstrumentBody body,HttpServletResponse httpServletResponse) {

// 小tips:支持换行数据展示效果
 String liftTypeJoin = "";
        String spmEquipIdJoin = "";
        for(int i=0;i<3;i++){
            String test1 = "测试" +i +"型号";
            String test2 = "测试" +i +"KG";
            String test3 = "测试" +i +"m/s";
            String test4 = "SPM测试" +i;
            liftTypeJoin += org.apache.commons.lang3.StringUtils.join(test1, "  ",test2, "  ",test3,"\n");
            spmEquipIdJoin += org.apache.commons.lang3.StringUtils.join(test4, ",");
        }
        liftTypeJoin = liftTypeJoin.substring(0,liftTypeJoin.length()-1);
        spmEquipIdJoin = spmEquipIdJoin.substring(0,spmEquipIdJoin.length()-1);

       Map<String, Object> params = new HashMap<String, Object>();
        params.put("projectId", "编号123");//项目编号
        params.put("partnerName", "代理商甲");//经销代理
        params.put("installPartaName", "用户丙");//用户名称
        params.put("ladderType", liftTypeJoin);//类型
        params.put("spmEquipId", spmEquipIdJoin);//出厂编号
        params.put("warrantTime", DateUtils.format(new Date(), DateUtils.ISO8601_DATE_PATTERN));//委托时间为当前时间
        params.put("projectName", "用户丙");//项目名称

        // 模板word文件真实路径
        // 模板word文件真实路径
        String wordSrcPath = "E:\\批量下载文件夹\\安装委托书模版.docx";

        // 使用该办件编号作为文件名称
        String wordDestPath = "E:\\批量下载文件夹\\生成委托书模版.docx";
        POIUtil.templateWrite(wordSrcPath, wordDestPath, params);
    }
  

第二步,将word转pdf,其中涉及poi的jar自行导入项目中才可运行

链接:https://pan.baidu.com/s/1N5DG7yZXu-FgJmBwWIqbsA 
提取码:f2tf

 @SneakyThrows
    @ApiOperation("打印委托书-PDF")
    @PostMapping("/printBookInPDF")
    public void printBookInPDF(HttpServletResponse httpServletResponse) {
        String wordDestPath = "E:\\批量下载文件夹\\安装委托书.docx";
        File outPdfFile = new File("E:\\批量下载文件夹\\生成模板-安装委托书-滨州模版123.pdf");
        OutputStream outputStream = new FileOutputStream(outPdfFile);
        FileInputStream fileInputStream = new FileInputStream(wordDestPath);
        try {
            XWPFDocument document = new XWPFDocument(fileInputStream);
            PdfOptions options = PdfOptions.create();
            //linux下中文字体处理,下面暂时切中文换
//            String fontUrl = "/tmp/officeTemplate/simsun.ttc";
            String fontUrl = "C:\\Windows\\Fonts\\simsun.ttc";
//            logger.info("处理字体文件路径");
            File file = new File("/tmp/officeTemplate");
            if (!file.exists()) {
//                logger.info("没有找到字体文件,从同级目录下找");
                fontUrl = "officeTemplate/simsun.ttc";
            }
            String finalFontUrl = fontUrl;
            options.fontProvider(new IFontProvider() {
                @Override
                public com.lowagie.text.Font getFont(String familyName, String encoding, float size, int style, Color color) {
                    try {
                        com.lowagie.text.pdf.BaseFont bfChinese = com.lowagie.text.pdf.BaseFont.createFont(finalFontUrl + ",0", com.lowagie.text.pdf.BaseFont.IDENTITY_H, com.lowagie.text.pdf.BaseFont.NOT_EMBEDDED);
                        com.lowagie.text.Font fontChinese = new com.lowagie.text.Font(bfChinese, size, style, color);
                        if (familyName != null) {
                            fontChinese.setFamily(familyName);
                        }
                        return fontChinese;
                    } catch (Exception e) {
                        e.printStackTrace();
                        return null;
                    }
                }
            });

            PdfConverter.getInstance().convert(document, outputStream, options);

        } catch (
                IOException e) {
            e.printStackTrace();
        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            if (fileInputStream != null) {
                try {
                    fileInputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值