zoukankan      html  css  js  c++  java
  • java根据模板生成word文档,兼容富文本、图片

    Java自动生成带图片、富文本、表格等的word文档

       

    • 使用技术 freemark+jsoup 生成mht格式的伪word文档,已经应用项目中,确实是可行的,无论是富文本中是图片还是表格,都能在word中展现出来 

    使用jsoup解析富文本框,将其中的图片进行Base64位转码,

    使用freemark替换模板的占位符,将变量以及图片资源放入模板中在输出文件

     

     

    • maven地址

     

    <!--freemarker-->

    <!--https://mvnrepository.com/artifact/org.freemarker/freemarker-->

    <dependency>

      <groupId>org.freemarker</groupId>

      <artifactId>freemarker</artifactId>

      <version>2.3.23</version>

    </dependency>

    <!--JavaHTMLParser-->

    <!--https://mvnrepository.com/artifact/org.jsoup/jsoup-->

    <dependency>

      <groupId>org.jsoup</groupId>

      <artifactId>jsoup</artifactId>

      <version>1.10.2</version>

    </dependency>

     

     

    • 制作word的freemark模板
    1. 先将wrod的格式内容定义好,如果需要插入参数的地方以${xxx}为表示,例:${product}

    模板例子:

       

     

     

      2. 将模板另存为mht格式的文件,打开该文件检查每个变量(${product})是否完整,有可能在${}中出现其他代码,需要删除。

      3. 将mht文件变更文件类型,改成ftl为结尾的文件,引入到项目中

      4. 修改ftl模板文件,在文件中加上图片资源占位符${imagesBase64String}${imagesXmlHrefString}

    具体位置如下图所示:

     

     

     

      5. ftl文件中由几个关键配置需要引入到代码中:

     

    docSrcParent = word.files

    docSrcLocationPrex = file:///C:/268D4AA4

    nextPartId = 01D2C8DD.BC13AF60

    上面三个参数,在模板文件中可以找到,需要进行配置,如果配置错误,图片文件将不会显示

    下面这三个参数固定,切换模板也不会改变

    shapeidPrex = _x56fe__x7247__x0020

    typeid = #_x0000_t75

    spidPrex = _x0000_i

     

     

      6. 模板引入之后进行代码编辑

    源码地址为:https://gitee.com/zhengweishan/export_word_plugin

     

    下载源码后需要进行调整下内容:

    1. 录入步骤5中的6个参数
    2. 修改freemark获取模板方式

    下面这种方式能获取模板,但是在项目打包之后无法获取jar包内的文件

    Configuration configuration=newConfiguration(Configuration.getVersion());

    configuration.setDefaultEncoding(StandardCharsets.UTF_8.toString());

    configuration.setDirectoryForTemplateLoading(newFile(templatePath));

    Template template=configuration.getTemplate("xxx.ftl");

     

    通过流的形式直接创建模板对象

    Configuration configuration=newConfiguration(Configuration.getVersion());

    configuration.setDefaultEncoding(StandardCharsets.UTF_8.toString());

    configuration.setDirectoryForTemplateLoading(newFile(templatePath));

    InputStream inputStream=newFileInputStream(newFile(templatePath+"/"+templateName));

    InputStreamReader inputStreamReader=newInputStreamReader(inputStream,StandardCharsets.UTF_8);

    Template template=newTemplate(templateName,inputStreamReader,configuration);

     

     

  • 相关阅读:
    c# 图像转化成灰度图
    文件操作 流
    GBK UTF8 GB2312 流
    助力奥巴马,拯救大气层
    ASP.NET 缓存技术
    GridView 和 ViewState 来实现条件查寻
    把日期按指定格式输出
    创业灵感淘宝网
    文件_上传_下载
    java23种设计模式与追MM
  • 原文地址:https://www.cnblogs.com/LeachBlog/p/12738585.html
Copyright © 2011-2022 走看看