Skip to content

Officia.Words — Word 转 PDF 与模板填充

能力摘要(AI 友好)OfficiaWords 把 Word/DOCX 转 PDF(toPdf),并支持 docx 模板占位符填充与邮件合并(fillTemplate*)。门面静态方法,byte[]byte[] 出,纯 JDK 实现。

将 Word 文档(DOCX,及部分 DOC)转换为 PDF,或以 docx 为模板做数据填充与邮件合并。中文/CJK 通过 CID 子集嵌入正确显示且可复制。

引入

xml
<dependency>
  <groupId>plus.ruoyi</groupId>
  <artifactId>officia-all</artifactId>
  <version>1.0.0</version>
</dependency>

仅需 Word 能力时可单独引 officia-words

Word → PDF

最小示例:

java
import plus.ruoyi.officia.words.OfficiaWords;

byte[] pdf = OfficiaWords.toPdf(docxBytes);

来源重载 —— 字节 / 输入流 / 文件都能直接调:

java
OfficiaWords.toPdf(byte[] docx);
OfficiaWords.toPdf(InputStream in);
OfficiaWords.toPdf(File file);

需要页数等元信息时用 convert 拿富结果:

java
ConvertResult r = OfficiaWords.convert(docxBytes, ConvertOptions.defaults());
byte[] pdf = r.getData();
int pages  = r.getPageCount();

模板填充

以 docx 为模板,用占位符 + 数据生成填充后的 docx 或直接出 PDF。在 OOXML DOM 上就地替换、保留原样式。

java
// 单份填充 → docx
byte[] docx = OfficiaWords.fillTemplate(templateBytes, data);
// 单份填充 → 直接出 PDF
byte[] pdf  = OfficiaWords.fillTemplateToPdf(templateBytes, data);

邮件合并(一模板多数据)

java
// 每条数据各出一份,返回多份 docx
List<byte[]> docs = OfficiaWords.fillTemplateEach(templateBytes, dataList);
// 每条各出一份并转 PDF
List<byte[]> pdfs = OfficiaWords.fillTemplateEachToPdf(templateBytes, dataList);

// 多条数据合并进一份文档(连续多页)
byte[] mergedDocx = OfficiaWords.fillTemplateMerged(templateBytes, dataList);
byte[] mergedPdf  = OfficiaWords.fillTemplateMergedToPdf(templateBytes, dataList);

方法一览

方法说明返回
toPdf(docx)Word → PDF(字节 / 流 / 文件重载)byte[]
convert(docx, options)转换并返回富结果(含页数)ConvertResult
fillTemplate(tpl, data)单份模板填充byte[] (docx)
fillTemplateToPdf(tpl, data)单份填充并转 PDFbyte[] (pdf)
fillTemplateEach(tpl, list)每条数据各出一份List<byte[]> (docx)
fillTemplateEachToPdf(tpl, list)每条各出一份并转 PDFList<byte[]> (pdf)
fillTemplateMerged(tpl, list)多条合并进一份byte[] (docx)
fillTemplateMergedToPdf(tpl, list)多条合并并转 PDFbyte[] (pdf)

常见问题

  • 中文变方块 / 不可复制:Officia 通过 CID Identity-H 子集嵌入字体,正常不会出现;若自定义字体缺字,确认字体覆盖了所需字符集。
  • 未授权水印:评估态输出带水印并限页,加载 officia.lic 后消失(见 授权与加载)。
  • 异常:入参为空或格式非法抛 OfficiaException(非受检),不会向外抛底层 IOException