java poi替换word内容生成pdf文件

替换word文档内容

package com.docx.test;

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

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

public class DocxUnitl {

    /**
     * 用一个docx文档作为模板,然后替换其中的内容,再写入目标文档中。
     * @throws Exception
     */
    @Test
    public void testTemplateWrite() throws Exception {

        String pdfPath = "D:\\HHKJ\\project\\test\\lgwdha.pdf";
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("county", "桂林");
        params.put("time", "2019年1月15日");
        params.put("time2", "2019年1月16日");
        params.put("str", "具体整改要求,不管多少个字");
        params.put("time3", "2019年1月15日");

        String filePath = "D:\\HHKJ\\project\\test\\lgwdh.docx";
        InputStream is = new FileInputStream(filePath);
        XWPFDocument doc = new XWPFDocument(is);
        //替换段落里面的变量
        this.replaceInPara(doc, params);
        //替换表格里面的变量
//        this.replaceInTable(doc, params);
        OutputStream os = new FileOutputStream("D:\\HHKJ\\project\\test\\lgwdha.docx");
        doc.write(os);

        this.close(os);
        this.close(is);
    }




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

        while (iterator.hasNext()) {
            para = iterator.next();
//            CTPPr pr = para.getCTP().getPPr();
            this.replaceInPara(para, params);
        }
    }

    /**
     * 替换段落里面的变量
     * @param para 要替换的段落
     * @param params 参数
     */
    private void replaceInPara(XWPFParagraph para, Map<String, Object> params) {
        List<XWPFRun> runs;
        Matcher matcher;
        if (this.matcher(para.getParagraphText()).find()) {
            runs = para.getRuns();
            System.out.println("2:"+runs);
            for (int i=0; i<runs.size(); i++) {
                XWPFRun run = runs.get(i);
                String runText = run.toString();
                matcher = this.matcher(runText);
                if (matcher.find()) {
                    while ((matcher = this.matcher(runText)).find()) {
                        runText = matcher.replaceFirst(String.valueOf(params.get(matcher.group(1))));
                    }
                    //直接调用XWPFRun的setText()方法设置文本时,在底层会重新创建一个XWPFRun,把文本附加在当前文本后面,
                    //所以我们不能直接设值,需要先删除当前run,然后再自己手动插入一个新的run。

                    run.setText(runText,0);
//                    int fontSize = run.getFontSize();
//                    String fontFamily = run.getFontFamily();
//                    para.removeRun(i);
//                    para.insertNewRun(i).setText(runText);
//                    para.insertNewRun(i).setFontSize(fontSize);
//                    para.insertNewRun(i).setFontFamily(fontFamily);
                }
            }
        }
    }

    /**
     * 替换表格里面的变量
     * @param doc 要替换的文档
     * @param params 参数
     */
    private 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) {
                        this.replaceInPara(para, params);
                    }
                }
            }
        }
    }

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

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

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

}

word转pdf

package com.docx.test;

import java.io.*;
import org.apache.poi.xwpf.converter.pdf.PdfConverter;
import org.apache.poi.xwpf.converter.pdf.PdfOptions;
import org.apache.poi.xwpf.usermodel.XWPFDocument;

public class word2pdf {

    /**
     * @param args the command line arguments
     * @throws java.io.IOException
     */
    public static void main(String[] args) throws IOException {
        String docPath = "D:\\HHKJ\\project\\test\\lgwdha.docx";
        String pdfPath = "D:\\HHKJ\\project\\test\\lgwdha.pdf";

        XWPFDocument document;
        InputStream doc = new FileInputStream(docPath);
        document = new XWPFDocument(doc);
        PdfOptions options = PdfOptions.create();
        OutputStream out = new FileOutputStream(pdfPath);
        PdfConverter.getInstance().convert(document, out, options);

        doc.close();
        out.close();
    }

}

所需jar包

dom4j-1.6.1-hudson-1.jar
itext-4.2.0.jar
itext-asian-5.2.0.jar
itext-asiancmaps-5.1.1.jar
itextpdf-5.4.0.jar
jsoup-1.11.3.jar
ooxml-schemas-1.1.jar
org.apache.poi.xwpf.converter.core-1.0.4.jar
org.apache.poi.xwpf.converter.pdf-1.0.4.jar
xdocreport-2.0.1.jar
xmlbeans-5.3.0-rc1.jar
xmlgraphics-commons-2.2.jar

poi-3.9-20121203.jar
poi-examples-3.9-20121203.jar
poi-excelant-3.9-20121203.jar
poi-ooxml-3.9-20121203.jar
poi-scratchpad-3.9-20121203.jar

所遇问题

1.java.lang.ClassNotFoundException: org/openxmlformats/schemas/wordprocessingml/x2006/main/FontsDocument$Factory
原博地址:https://blog.csdn.net/lex1993/article/details/47062141
解决办法:导入ooxml-schemas-1.1.jar这个包,去掉poi-ooxml-3.9-20121203.jar
2.jar包版本问题
解决办法:因为项目环境需要用jdk1.6,按照上述所示版本下载即可

附jar包下载地址

https://mvnrepository.com/artifact/org.apache.poi/ooxml-schemas/1.1

  • 1
    点赞
  • 28
    收藏
    觉得还不错? 一键收藏
  • 17
    评论
您可以使用 Apache POI 库来实现在 Java 中根据 word 模板生成 pdf 文件POI 是 Apache 下的一个开源项目,提供了读写 Microsoft Office 格式文件的 API。 下面是一个简单的代码示例,它使用 POI 库将 word 模板中的占位符替换为动态参数,并将其换为 pdf 文件: ```java import java.io.FileInputStream; import java.io.FileOutputStream; import java.util.Map; import org.apache.poi.xwpf.usermodel.XWPFDocument; import org.apache.poi.xwpf.usermodel.XWPFParagraph; import org.apache.poi.xwpf.usermodel.XWPFRun; import com.itextpdf.text.Document; import com.itextpdf.text.pdf.PdfWriter; import com.itextpdf.text.pdf.PdfDocument; public class WordToPdf { public static void main(String[] args) { // 模板文件路径 String templatePath = "template.docx"; // 生成pdf 文件路径 String pdfPath = "output.pdf"; // 占位符对应的参数 Map<String, String> params = ...; try { // 读取模板文件 FileInputStream fis = new FileInputStream(templatePath); XWPFDocument doc = new XWPFDocument(fis); // 替换占位符 for (XWPFParagraph p : doc.getParagraphs()) { for (XWPFRun r : p.getRuns()) { String text = r.getText(0); if (text != null) { for (Map.Entry<String, String> entry : params.entrySet()) { text = text.replace("${" + entry.getKey() + "}", entry.getValue()); } r.setText(text, 0); } } } // 将 word 文档换为 pdf FileOutputStream out = new FileOutputStream(pdfPath); PdfWriter.getInstance(doc, out); doc.open(); doc.write(out); out.close(); doc.close(); } catch (Exception e) { e.printStackTrace(); } } } ``` 这段代码中

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 17
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值