天天看點

word轉換為pdf,對指定内容文本替換

/**
     * 将word文檔, 轉換成pdf, 中間替換掉變量
     *
     * @param source 源為word文檔, 必須為docx文檔
     * @param target 目标輸出
     * @param params 需要替換的變量
     * @throws Exception
     */
    public static void wordConverterToPdf(InputStream source, OutputStream target, Map<String, Object> params)
            throws Exception {

        wordConverterToPdf(source, target, null, params);
    }

    /**
     * 将word文檔, 轉換成pdf, 中間替換掉變量
     *
     * @param source  源為word文檔, 必須為docx文檔
     * @param target  目标輸出
     * @param params  需要替換的變量
     * @param options PdfOptions.create().fontEncoding( "windows-1250" ) 或者其他
     * @throws Exception
     */
    public static void wordConverterToPdf(InputStream source, OutputStream target, PdfOptions options,
                                          Map<String, Object> params) throws Exception {
        XWPFDocument doc = new XWPFDocument(source);
        paragraphReplace(doc.getParagraphs(), params);
        for (XWPFTable table : doc.getTables()) {
            for (XWPFTableRow row : table.getRows()) {
                for (XWPFTableCell cell : row.getTableCells()) {
                    paragraphReplace(cell.getParagraphs(), params);
                }
            }
        }
        PdfConverter.getInstance().convert(doc, target, options);
        System.out.println("轉換完成");
    }

    /**
     * 替換段落中内容
     */
    private static void paragraphReplace(List<XWPFParagraph> paragraphs, Map<String, Object> params) {
        if (MapUtils.isNotEmpty(params)) {
            for (XWPFParagraph p : paragraphs) {
                for (XWPFRun r : p.getRuns()) {
                    String content = r.getText(r.getTextPosition());
                    if (org.apache.poi.xwpf.converter.core.utils.StringUtils.isNotEmpty(content) && params.containsKey(content)) {
                        r.setText(params.get(content).toString(), 0);
                    }
                }
            }
        }
    }

}