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

你可能感兴趣的:(java)