java word模板内容替换并转pdf

功能:根据word模板替换模板中占位符生成新的word文件、将word文件转换成pdf文件。

maven依赖:

xml 复制代码
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-scratchpad</artifactId>
    <version>4.1.2</version>
</dependency>

<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi</artifactId>
    <version>4.1.2</version>
</dependency>

<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-ooxml-schemas</artifactId>
    <version>4.1.2</version>
</dependency>

<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-ooxml</artifactId>
    <version>4.1.2</version>
</dependency>

<dependency>
    <groupId>fr.opensagres.xdocreport</groupId>
    <artifactId>fr.opensagres.poi.xwpf.converter.pdf-gae</artifactId>
    <version>2.0.2</version>
</dependency>

工具类:CreatePdfUtils.java

java 复制代码
import com.lowagie.text.DocumentException;
import com.lowagie.text.Font;
import com.lowagie.text.pdf.BaseFont;
import fr.opensagres.poi.xwpf.converter.pdf.PdfConverter;
import fr.opensagres.poi.xwpf.converter.pdf.PdfOptions;
import org.apache.poi.xwpf.usermodel.*;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URISyntaxException;
import java.util.Map;

/**
 * CreatePdfUtils
 *  1:替换word内容
 *  2:word转pdf文件
 */
public class CreatePdfUtils {

    /**
     *替换文档内容
     */
    public static void replaceWords(String filePath, String outputFilePath, Map<String, String> replacements) throws IOException {
        try (FileInputStream fis = new FileInputStream(filePath);
             XWPFDocument document = new XWPFDocument(fis)) {

            // 替换段落中的占位符
            for (XWPFParagraph para : document.getParagraphs()) {
                replaceInParagraph(para, replacements);
            }

            // 替换表格中的占位符
            document.getTables().forEach(table -> {
                for (XWPFTableRow row : table.getRows()) {
                    for (XWPFTableCell cell : row.getTableCells()) {
                        for (XWPFParagraph paragraph : cell.getParagraphs()) {
                            replaceInParagraph(paragraph, replacements);
                        }
                    }
                }
            });

            // 输出新文档
            try (FileOutputStream fos = new FileOutputStream(outputFilePath)) {
                document.write(fos);
            }
        }
    }

    private static void replaceInParagraph(XWPFParagraph paragraph, Map<String, String> replacements) {
        for (XWPFRun run : paragraph.getRuns()) {
            String text = run.getText(0);
            if (text != null) {
                for (Map.Entry<String, String> entry : replacements.entrySet()) {
                    if (text.contains(entry.getKey())) {
                        text = text.replace(entry.getKey(), entry.getValue());
                        run.setText(text, 0);
                    }
                }
            }
        }
    }

    /**
     * word转pdf
     */
    public static String wordToPdf(String toPdf) {
        try {
            FileInputStream fis = new FileInputStream(toPdf);
            // 转换后pdf路径 与word同路径名称
            String tarPdf = toPdf.substring(0, toPdf.lastIndexOf(".")) + ".pdf";
            FileOutputStream fos = new FileOutputStream(tarPdf);
            XWPFDocument xwpfDocument = new XWPFDocument(fis);
            PdfOptions pdfOptions = PdfOptions.create();
            // 添加字体库 解决liunx环境word转pdf中文不显示
            pdfOptions.fontProvider((familyName, s1, size, style, color) -> {
                BaseFont bfChinese = null;
                try {
                    bfChinese = BaseFont.createFont(getFontPath(), BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
                } catch (DocumentException e) {
                    throw new RuntimeException(e);
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
                Font fontChinese = new Font(bfChinese, size, style, color);
                if (familyName != null) {
                    fontChinese.setFamily(familyName);
                }
                return fontChinese;
            });
            PdfConverter.getInstance().convert(xwpfDocument, fos, pdfOptions);
            // word转换后的pdf文件路径
            return tarPdf;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 获取中文宋体字体库资源路径
     */
    private static String getFontPath() {
        try {
            return CreatePdfUtils.class.getClassLoader().getResource("font/" + "simsun.ttf").toURI().toString();
        } catch (URISyntaxException e) {
            throw new RuntimeException(e);
        }
    }
}

字体库(宋体):simsun.ttf

下载字体库:pan.baidu.com/s/1vobIy1gt...

创建测试word模板: word模板.docx

工具类使用:

typescript 复制代码
public static void main(String[] args) {
    Map<String, String> replace = new HashMap<>();
    replace.put("name","李四");
    replace.put("age", "31");
    try {
        // word内容替换
        CreatePdfUtils.replaceWords("C:\Users\lisi\Desktop\word模板.docx",
                "C:\Users\lisi\Desktop\word版文档.docx", replace);
        // word转pdf
        CreatePdfUtils.wordToPdf("C:\Users\lisi\Desktop\word版文档.docx"); 
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

最终生成的word文档和转换后的pdf:

相关推荐
User_芊芊君子9 小时前
【Java】设计模式——单例、工厂、代理模式
java·设计模式·代理模式
2301_803554529 小时前
正向代理,反向代理,负载均衡还有nginx
java·nginx·负载均衡
要开心吖ZSH9 小时前
软件设计师备考-(十六)数据结构及算法应用(重要)
java·数据结构·算法·软考·软件设计师
向上的车轮10 小时前
基于Java Spring Boot的云原生TodoList Demo 项目,验证云原生核心特性
java·spring boot·云原生
程序员清风10 小时前
快手一面:为什么要求用Static来修饰ThreadLocal变量?
java·后端·面试
逍遥德10 小时前
Java8 Comparator接口 和 List Steam 排序使用案例
java·spring boot·list·排序算法
前行的小黑炭10 小时前
Android :如何快速让布局适配手机和平板?
android·java·kotlin
_BugMan11 小时前
【IDEA】干活?一个IDEA即可,集成开发平台打造攻略
java·ide·intellij-idea
YA33312 小时前
java设计模式二、工厂
java·开发语言·设计模式
金色天际线-12 小时前
Nginx 优化与防盗链配置指南
java·后端·spring