poi实现word内容替换并且转pdf和制作模版

1,制作模版(请把模版制作好,尤其是下面的解决方法,一定要去修改)

(请把模版制作好,尤其是下面的解决方法,一定要去修改)
(请把模版制作好,尤其是下面的解决方法,一定要去修改)
(重要的问题说三遍!!!)
制作模版

2,在项目打成jar包上线以后,只能在jar包同级替换文档和pdf,这是个坑,大家伙注意,要用这种方式


ApplicationHome h = new ApplicationHome(this.getClass());
            File jarF = h.getSource();
            jarF.getParent()+File.separator+wordName.toString()

3,替换方法

先通过步骤2中的方法获取到模版,模版可以放在数据库,或者项目中,有文件服务器的就请忽略第二步



Map<String, String> params = new LinkedHashMap<>();
params.put("${项目名称}", dbglZbtzs.getZbxmmc());
params.put("${项目负责人}", dbglZbtzs.getXmfzr());
 XWPFDocument document = DocxUtil.getDocument(fileContent);
 //poi模版替换
DocxUtil.replaceWord(document, params);
 //poi实现讲替换后的docx生成到某个路径下面
DocxUtil.exportDocx(document,jarF.getParent()+"/",wordName.toString());


4,word转pdf

PdfOptions options = PdfOptions.create();
//替换过数据的docx的路径
 inputStream1 = new FileInputStream(new File(wordPath1.toString()));
 //pdf生成路径
 FileOutputStream outputStream = new FileOutputStream(new File(rootPath.toString()));
//word转pdf          WordToPDF.wordConverterToPdf(inputStream1,outputStream,options);

5,DocxUtil

public class DocxUtil {

    /*
     * @description: 获取word模板数据源
     * @param srcPath 路径
     * @return XWPFDocument
     * @author xuweiqiang
     * @date 2019/8/14
     */
    public static XWPFDocument getDocument(String srcPath) throws IOException {
        return new XWPFDocument(POIXMLDocument.openPackage(srcPath));
    }

    /*
     * @description: 获取word模板数据源
     * @param srcPath 路径
     * @return XWPFDocument
     * @author xuweiqiang
     * @date 2019/8/14
     */
    public static XWPFDocument getDocument(byte[] buf) throws IOException {
        InputStream in = null;
        try {
            in = new ByteArrayInputStream(buf);
            return new XWPFDocument(in);
        } catch (Exception e) {

        } finally {
            if (in != null) {
                in.close();
            }
        }
        return null;
    }

    /*
     * @description: 导出docx
     * @param document word模板数据源
     *        destPath 文件路径
     *        fileName 文件名
     * @return
     * @author xuweiqiang
     * @date 2019/8/14
     */
    public static byte[] exportDocx(XWPFDocument document, String wordFilepath, String fileName) {
        FileOutputStream out = null;
        try {
            File file = new File(wordFilepath);
            if (!file.exists()) {
                boolean flag = file.mkdirs();
                if (!flag) {
                    return null;
                }
            }
            File f = new File(wordFilepath + fileName);
            out = new FileOutputStream(f);
            document.write(out);
            out.flush();
        } catch (IOException e) {
            return null;
        } finally {
            try {
                if (out != null) {
                    out.close();
                }
            } catch (Exception e) {
                return null;
            }
        }

        return null;
    }

    public static byte[] localWJToIo(String pathName) {
        File file = new File(pathName);
        byte[] by = new byte[(int) file.length()];
        InputStream is = null;
        try {
            is = new FileInputStream(file);
            ByteArrayOutputStream bytestream = new ByteArrayOutputStream();
            byte[] bb = new byte[2048];
            int ch;
            ch = is.read(bb);
            while (ch != -1) {
                bytestream.write(bb, 0, ch);
                ch = is.read(bb);
            }
            by = bytestream.toByteArray();
        } catch (IOException ex) {
            return by;
        } finally {
            try {
                if (is != null) {
                    is.close();
                }
            } catch (IOException e) {
                return null;
            }
        }
        return by;
    }

    /*
     * @description: 替换段落中的指定文字
     * @param document word模板数据源
     * @param map 关键字键值对映射
     * @return
     * @author xuweiqiang
     * @date 2019/8/14
     */
    public static void replaceWord(XWPFDocument document, Map<String, String> map) {
        Iterator<XWPFParagraph> itPara = document.getParagraphsIterator();
        while (itPara.hasNext()) {
            XWPFParagraph paragraph = itPara.next();
            List<XWPFRun> runs = paragraph.getRuns();
            for (XWPFRun run : runs) {
                String oneparaString = run.getText(run.getTextPosition());
                if (StringUtils.isBlank(oneparaString)) {
                    continue;
                }
                for (Map.Entry<String, String> entry :
                        map.entrySet()) {
                    oneparaString = oneparaString.replace(entry.getKey(), entry.getValue());
                }
                run.setText(oneparaString, 0);
            }
        }
    }


    /*
     * @description: 增加表格行数据
     * @param document word模板数据源
     *        list 行数据
     *        tabNum 表格顺序
     *        colNum 列数
     *        fontName 字体名
     *        fontSize 字号
     * @return
     * @author xuweiqiang
     * @date 2019/8/14
     */
    public static void addTableRow(XWPFDocument document, List<Map<String, String>> list, int tabNum, int colNum, String fontName, int fontSize) {
        // 替换表格中的指定文字
        Iterator<XWPFTable> itTable = document.getTablesIterator();//获得Word的表格
        int tableNumber = 0;
        while (itTable.hasNext()) { //遍历表格
            tableNumber++;
            XWPFTable table = itTable.next();
            int count = table.getNumberOfRows();//获得表格总行数
            List<XWPFTableCell> cells = table.getRow(0).getTableCells();//获得表格的第一行下的列数
            if (tableNumber == tabNum && colNum == cells.size()) {
                for (int i = list.size() - 1; i > 1; i--) {
                    XWPFTableRow row = table.getRow(1);
                    table.addRow(row);
                }
                XWPFParagraph xp;
                for (int t = 0; t < list.size(); t++) {
                    XWPFTableRow nrow = table.getRow(t + 1);
                    List<XWPFTableCell> celln = nrow.getTableCells();//在行元素中,获得表格的单元格

                    int numb = 0;
                    for (Map.Entry<String, String> entry : list.get(t).entrySet()) {
//                        celln.get(numb).removeParagraph(0);//删除无用的段落
                        xp = celln.get(numb).getParagraphs().get(0);
                        xp.getAlignment();
                        XWPFRun title = xp.createRun();
//                        title.setFontSize(fontSize);
//                        CTFonts font = title.getCTR().addNewRPr().addNewRFonts();
//                        font.setEastAsia(fontName);
//                        font.setAscii(fontName);
                        title.setText(entry.getValue());
                        numb++;
                    }
                }
            }
        }
    }
    public static byte[] toByteArray(InputStream input) throws IOException {
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024*4];
        int n = 0;
        while (-1 != (n = input.read(buffer))) {
            output.write(buffer, 0, n);
        }
        return output.toByteArray();
    }
}

6,WordToPDF

public class WordToPDF {

    /**
     * 将word文档, 转换成pdf, 中间替换掉变量
     *
     * @param source  源为word文档, 必须为docx文档
     * @param target  目标输出
     * @param options PdfOptions.create().fontEncoding( "windows-1250" ) 或者其他
     * @throws Exception
     */
    public static void wordConverterToPdf(InputStream source, OutputStream target,
                                          PdfOptions options) throws Exception {

        XWPFDocument doc = new XWPFDocument(source);
        PdfConverter.getInstance().convert(doc, target, options);
    }

    /**
     * 替换段落中内容
     */
    private static void paragraphReplace(List<XWPFParagraph> paragraphs, Map<String, String> params) {
        if (params != null && !params.isEmpty()) {
            for (XWPFParagraph p : paragraphs) {
                for (XWPFRun r : p.getRuns()) {
                    String content = r.getText(r.getTextPosition());
                    if (StringUtils.isNotEmpty(content) && params.containsKey(content)) {
                        r.setText(params.get(content), 0);
                    }
                }
            }
        }
    }
}
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
当使用Poi-tl库根据Word模板填充内容生成Word文档时,可以使用Poi-tl提供的模板语法来处理空值。以下是一个示例代码: ```java import org.apache.poi.xwpf.usermodel.XWPFDocument; import org.apache.poi.xwpf.usermodel.XWPFRun; import org.apache.poi.xwpf.usermodel.XWPFParagraph; import org.apache.poi.xwpf.usermodel.ParagraphAlignment; import org.apache.poi.xwpf.usermodel.TextAlignment; import fr.opensagres.poi.xwpf.converter.pdf.PdfConverter; import fr.opensagres.poi.xwpf.converter.pdf.PdfOptions; import org.apache.poi.util.Units; import org.apache.poi.xwpf.usermodel.Document; import org.apache.poi.xwpf.usermodel.HeaderFooterType; import org.apache.poi.xwpf.usermodel.IBodyElement; import org.apache.poi.xwpf.usermodel.XWPFTable; import org.apache.poi.xwpf.usermodel.XWPFTableRow; import org.apache.poi.xwpf.usermodel.XWPFTableCell; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.util.HashMap; import java.util.Map; public class WordTemplateFiller { public static void main(String[] args) { try { // 加载Word模板文件 FileInputStream templateStream = new FileInputStream("template.docx"); XWPFDocument document = new XWPFDocument(templateStream); // 填充内容 Map<String, Object> placeholders = new HashMap<>(); placeholders.put("name", "John Doe"); placeholders.put("age", "30"); placeholders.put("address", ""); replacePlaceholders(document, placeholders); // 保存填充后的文档 FileOutputStream outputStream = new FileOutputStream("filled_template.docx"); document.write(outputStream); outputStream.close(); System.out.println("Word文档生成成功!"); } catch (IOException e) { e.printStackTrace(); } } private static void replacePlaceholders(XWPFDocument document, Map<String, Object> placeholders) { for (XWPFParagraph paragraph : document.getParagraphs()) { for (XWPFRun run : paragraph.getRuns()) { String text = run.getText(0); if (text != null) { for (Map.Entry<String, Object> entry : placeholders.entrySet()) { String placeholder = "${" + entry.getKey() + "}"; if (text.contains(placeholder)) { Object value = entry.getValue(); if (value != null && !value.toString().isEmpty()) { text = text.replace(placeholder, value.toString()); } else { text = text.replace(placeholder, ""); // 替换为空字符串 } run.setText(text, 0); } } } } } } } ``` 在上述代码中,我们首先加载Word模板文件,然后定义了一个`placeholders`的映射,其中包含了要替换的占位符和对应的值。接下来,我们调用`replacePlaceholders`方法来替换文档中的占位符。 在`replacePlaceholders`方法中,我们遍历文档中的每个段落和文本运行,通过检查文本内容中是否包含占位符来确定是否需要替换。如果找到了匹配的占位符,则根据占位符对应的值来进行替换。如果值不为空且非空字符串,则将占位符替换为对应的值;如果值为空或空字符串,则将占位符替换为空字符串。 请注意,上述代码中使用的占位符格式为`${placeholder}`,你可以根据实际情况修改为其他格式。 以上是一个基本示例,你可以根据自己的需求进行修改和扩展。同时,需要确保在项目中添加了Poi-tl的依赖库。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值