之前项目有个需求,需要先动态生成word内容,然后再预览生成word的内容(不能修改).整理一下,方便以后使用.

网上参考了好多大神的博客.具体也忘了参考谁的了,如有侵权,请告知修改.

思路一:

将目标word文件另存为xml文件,将里面的需要动态生成的内容用freemarker的表达式${}替换.

用freemarker生成word的工具类,动态生成word. 这样生成的word实际上是xml文件,用办公软件能正常打开使用.

但是转PDF的时候发现转不成功.转过之后的PDF显示的不是word的格式字符,而是像xml文件的标签及字符,失败!

思路二:

word的docx文件其实属于zip的一种. 这里只需要对它的核心内容部分进行操作.其他数据不动.具体做法为:

1.用办公软件(wps/office)打开模板文件,将需要修改的内容,用freemarker的表达式${}替换.

(注意:需要循环展示的内容还需要在xml文件中处理)如下:

2.将模板docx文件重命名为.zip的压缩文件.

3.用解压工具打开,取出word/document.xml 文件.

4.此时用文本工具打开document.xml,内容不太好看,将文件格式化一下.(我这里没找到好的格式化工具,使用notepad没格好,最后用idea还行).格式化后如下.

5.在xml中需要循环的内容前增加如下标签:

6.说明

word中要填充的数据为map格式,${}中为map的key.如果还需要循环填充可以如下操作:

map1   map2   list

map1.put("userName",name);

list.add(map1);

map2.put("list",list);

map2.put("title",title);

map2即为要填充的所有数据.这样给list一个别名listKey 后,${}中如下填写即可.

7.将模板文件与xml文件保存到一个固定位置.我这里保存到了项目中:

8.准备工作完成,生成word工具类如下:

import freemarker.template.TemplateException;

import java.io.*;
import java.util.Enumeration;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipException;
import java.util.zip.ZipFile;
import java.util.zip.ZipOutputStream;

/**
* 其实docx属于zip的一种,这里只需要操作word/document.xml中的数据,其他的数据不用动
*
* @author
*
*/
public class XmlToDocx {

/**
*
* @param xmlTemplate xml的文件名
* @param docxTemplate docx的路径和文件名
* @param xmlTemp 填充完数据的临时xml
* @param toFilePath 目标文件名
* @param map 需要动态传入的数据
* @throws IOException
* @throws TemplateException
*/
public static void toDocx(String xmlTemplate,String docxTemplate,String xmlTemp ,String toFilePath,Map map) {
try {
// 1.map是动态传入的数据
// 这个地方不能使用FileWriter因为需要指定编码类型否则生成的Word文档会因为有无法识别的编码而无法打开
Writer w1 = new OutputStreamWriter(new FileOutputStream(xmlTemp), "gb2312");
// 2.把map中的数据动态由freemarker传给xml
XmlTplUtil.process(xmlTemplate, map, w1);
// 3.把填充完成的xml写入到docx中
XmlToDocx xtd = new XmlToDocx();
xtd.outDocx(new File(xmlTemp), docxTemplate, toFilePath);
}catch (Exception e) {
e.printStackTrace();
}
}
/**
*
* @param documentFile 动态生成数据的docunment.xml文件
* @param docxTemplate docx的模板
* @param toFilePath 需要导出的文件路径
* @throws ZipException
* @throws IOException
*/

public void outDocx(File documentFile, String docxTemplate, String toFilePath) throws ZipException, IOException {

try {
File docxFile = new File(docxTemplate);
ZipFile zipFile = new ZipFile(docxFile);
Enumeration<? extends ZipEntry> zipEntrys = zipFile.entries();
ZipOutputStream zipout = new ZipOutputStream(new FileOutputStream(toFilePath));
int len = -1;
byte[] buffer = new byte[1024];
while (zipEntrys.hasMoreElements()) {
ZipEntry next = zipEntrys.nextElement();
InputStream is = zipFile.getInputStream(next);
// 把输入流的文件传到输出流中 如果是word/document.xml由我们输入
zipout.putNextEntry(new ZipEntry(next.toString()));
if ("word/document.xml".equals(next.toString())) {
InputStream in = new FileInputStream(documentFile);
while ((len = in.read(buffer)) != -1) {
zipout.write(buffer, 0, len);
}
in.close();
} else {
while ((len = is.read(buffer)) != -1) {
zipout.write(buffer, 0, len);
}
is.close();
}
}
zipout.close();

} catch (Exception e) {
e.printStackTrace();
}
}
}
9.生成PDF工具类

import com.artofsolving.jodconverter.DocumentConverter;
import com.artofsolving.jodconverter.openoffice.connection.OpenOfficeConnection;
import com.artofsolving.jodconverter.openoffice.connection.SocketOpenOfficeConnection;
import com.artofsolving.jodconverter.openoffice.converter.OpenOfficeDocumentConverter;
import org.apache.poi.xwpf.converter.pdf.PdfConverter;
import org.apache.poi.xwpf.converter.pdf.PdfOptions;
import org.apache.poi.xwpf.usermodel.XWPFDocument;

import java.io.*;

public class XMlToDoc {

/**
* 生成pdf
*/
public static String makePdfByXcode(String docx) {
String filename = null;
File outFile = null;
try {

// document.setParagraph(new Pa );
if (docx.contains(".docx")) {
XWPFDocument document=new XWPFDocument(new FileInputStream(new File(docx)));
outFile=new File(docx.replace(".docx",".pdf"));
filename=docx.replace(".docx",".pdf");

outFile.getParentFile().mkdirs();
OutputStream out=new FileOutputStream(outFile);
// IFontProvider fontProvider = new AbstractFontRegistry();
PdfOptions options= PdfOptions.create(); //gb2312
PdfConverter.getInstance().convert(document,out,options);

} else {
File inputFile = new File(docx);
outFile = new File(docx.replace(".doc", ".pdf"));
filename = docx.replace(".doc", ".pdf");
outFile.getParentFile().mkdirs();

OpenOfficeConnection connection = new SocketOpenOfficeConnection(8100);
connection.connect();

// convert
DocumentConverter converter = new OpenOfficeDocumentConverter(connection);
converter.convert(inputFile, outFile);

// close the connection
connection.disconnect();
}

}catch (IllegalArgumentException e){
System.err.println("未知文件格式");
}
catch (Exception e) {
e.printStackTrace();
}
return filename;

}

}
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;

import java.io.File;
import java.io.IOException;
import java.io.Writer;
import java.util.Map;

public class XmlTplUtil {

private static XmlTplUtil tplm = null;
private Configuration cfg = null;

private XmlTplUtil() {
cfg = new Configuration();
try {
// 注册tmlplate的load路径
// 这的路径是xml的路径
String pathName = XmlTplUtil.class.getClassLoader().getResource("").getPath();
String path = pathName.substring(1, pathName.lastIndexOf("/"));
String parentPath1 = new File(path).getParent();//获取项目的上一级目录
String parentPath2 = new File(parentPath1).getParent();//获取项目的上一级目录
String xmlPath = parentPath2 + "/static/excelModel";
cfg.setDirectoryForTemplateLoading(new File(xmlPath));
} catch (Exception e) {
e.printStackTrace();
}
}

private static Template getTemplate(String name) throws IOException {
if (tplm == null) {
tplm = new XmlTplUtil();
}
Template template = tplm.cfg.getTemplate(name);
return template;
}

/**
*
* @param templatefile 模板文件
* @param param 需要填充的内容
* @param out 填充完成输出的文件
* @throws IOException
* @throws TemplateException
*/
public static void process(String templatefile, Map param, Writer out) throws IOException, TemplateException {
// 获取模板
Template template = XmlTplUtil.getTemplate(templatefile);
template.setOutputEncoding("GBK");
// 合并数据
template.process(param, out);
if (out != null) {
out.close();
}
}
}
注意:生成PDF需要安装openoffice 软件,安装完成后,

cd openoffice目录下有个OpenOffice 4\program

然后输入命令

soffice -headless -accept="socket,host=127.0.0.1,port=8100;urp;" -nofirststartwizard

就ok了.

10.用到的maven包

<dependency>
<groupId>com.artofsolving</groupId>
<artifactId>jodconverter</artifactId>
<version>2.2.1</version>
</dependency>
<!--openoffice-->
<dependency>
<groupId>org.openoffice</groupId>
<artifactId>jurt</artifactId>
<version>3.0.1</version>
</dependency>
<dependency>
<groupId>org.openoffice</groupId>
<artifactId>ridl</artifactId>
<version>3.0.1</version>
</dependency>
<dependency>
<groupId>org.openoffice</groupId>
<artifactId>juh</artifactId>
<version>3.0.1</version>
</dependency>
<dependency>
<groupId>org.openoffice</groupId>
<artifactId>unoil</artifactId>
<version>3.0.1</version>
</dependency>
<dependency>
<groupId>fr.opensagres.xdocreport</groupId>
<artifactId>org.apache.poi.xwpf.converter.pdf</artifactId>
<version>1.0.6</version>
</dependency>
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.22</version>
</dependency>
---------------------
作者:菜鸟-也-想飞
来源:CSDN
原文:https://blog.csdn.net/qq_21306669/article/details/84313569

注意:springboot打成jar无法放入webapp下生成,

freemarker动态生成word并将生成的word转为PDF,openoffice转换word乱码的更多相关文章

  1. java 将word转为PDF (100%与word软件转换一样)

    jdk环境:jdk_8.0.1310.11_64    (64位) 1.引入pom文件 <!-- word转pdf(依赖windows本地的wps) --> <dependency& ...

  2. Java 将Word转为PDF、PNG、SVG、RTF、XPS、TXT、XML

    同一文档在不同的编译或阅读环境中,需要使用特定的文档格式来打开,通常需要通过转换文档格式的方式来实现.下面将介绍在Java程序中如何来转换Word文档为其他几种常见文档格式,如PDF.图片png.sv ...

  3. 如何在Mac OS X上将PDF转换为Microsoft Word

    Lighten PDF to Word Converter for Mac是一个简单但功能强大的应用程序,可将PDF文件准确,轻松地转换为Microsoft Word.它可以保留原始内容的布局,格式, ...

  4. .net mvc 站点自带简易SSL加密传输 Word报告自动生成(例如 导出数据库结构) 微信小程序:动画(Animation) SignalR 设计理念(一) ASP.NET -- WebForm -- ViewState ASP.NET -- 一般处理程序ashx 常用到的一些js方法,记录一下 CryptoJS与C#AES加解密互转

    .net mvc 站点自带简易SSL加密传输   因项目需要,传输数据需要加密,因此有了一些经验,现简易抽出来分享! 请求:前端cryptojs用rsa/aes 或 rsa/des加密,后端.net ...

  5. 【EMV L2】CDA复合动态数据认证/应用密文生成

    复合动态数据认证/应用密文生成处理流程:对于复合动态数据认证/应用密文生成,终端执行标准动态数据认证的步骤1到3:1.认证中心公钥的获取终端使用认证中心公钥索引(PKI)以及卡片中的注册的应用提供商标 ...

  6. 使用NPOI按照word模板文件生成新的word文件

    /// <summary> /// 按照word模板文件 生成新word文件 /// </summary> /// <param name="tempFile& ...

  7. java代码操作word模板并生成PDF

    这个博客自己现在没时间写,等后面有时间了,自己再写. 这中需求是在实际的项目开发中是会经常遇到的. 下面我们先从简单入手一步一步开始. 1.首先,使用word创建一个6行两列的表格. 点击插入-6行2 ...

  8. JAVA Asponse.Word Office 操作神器,借助 word 模板生成 word 文档,并转化为 pdf,png 等多种格式的文件

    一,由于该 jar 包不是免费的, maven 仓库一般不会有,需要我们去官网下载并安装到本地 maven 仓库 1,用地址   https://www-evget-com/product/564  ...

  9. Office Word文件批量生成软件

    一.软件用途 如果Word文件模板固定,只是要素信息不同,则可以使用本软件批量生成Word文件. 软件下载地址(2020-12-6更新):https://files.cnblogs.com/files ...

随机推荐

  1. JQuery制作基础的无缝轮播与左右点击效果

    在网页中我们想要的无缝轮播左右循环有好多好多中,这是我第一个轮播效果,也是最基础的,和大家分享一下,对于初学者希望你们能有所借鉴,对于大神我想让你们尽情的虐我给我宝贵的意见. 这个是我要的效果 进入正 ...

  2. Python_排版函数

    import textwrap doc='''Beautiful is better than ugly. Explicit is better than implicit. Simple is be ...

  3. post 和 get 的区别,直指本质

    在我们初入java编程之路的时候,面试往往会有一个面试题:get和post的区别是什么?那么你真的知道他们的区别吗?接下来抽丝剥茧,让我们看看get和post到底什么东西,首先从本质的角度看get和p ...

  4. Linux内核架构与底层--读书笔记

    linux中管道符"|"的作用 命令格式:命令A|命令B,即命令1的正确输出作为命令B的操作对象(下图应用别人的图片) 1. 例如: ps aux | grep "tes ...

  5. PAT1070:Mooncake

    1070. Mooncake (25) 时间限制 100 ms 内存限制 65536 kB 代码长度限制 16000 B 判题程序 Standard 作者 CHEN, Yue Mooncake is ...

  6. cmd登录远程Oracle数据库

    在cmd中输入  user/password@Ip:port/sid    例如:  laoda/123@192.168.4.161:1521/orcl      laoda是用户名,123是密码.

  7. C++/C实现各种排序算法(持续更新)--冒泡排序,选择排序,归并排序

    2018 3 17 今日总结一下C++中的排序算法: 1冒泡排序 它重复地走访过要排序的数列,一次比较两个元素,如果他们的顺序错误就把他们交换过来.走访数列的工作是重复地进行直到没有再需要交换,也就是 ...

  8. RCTF 2018线上赛 writeup

    苦逼的RCTF,只进行了两天,刚好第二天是5.20,出去xxx了,没法打比赛,难受.比赛结束了,还不准继续提交flag进行正确校验了,更难受. 下面是本次ctf解题思路流程 后面我解出的题会陆续更新上 ...

  9. java中Collection容器

    1.容器(Collection)也称为集合, 在java中就是指对象的集合. 容器里存放的都只能是对象. 实际上是存放对象的指针(头部地址): 这里对于八种基本数据类型,在集合中实际存的是对应的包装类 ...

  10. Celery beat实现定时/轮询任务

    Celery定时任务 配置 启用Celery的定时任务需要设置CELERYBEAT_SCHEDULE .  Celery的定时任务都由celery beat来进行调度.celery beat默认按照s ...