Java 给word模板赋值并生成pdf

1.编写word模板。

        将word模板格式调整好,将word中需要赋值的地方用${name}表示。(name可以随意取名)

如果有图片,就先临时拿一个图片放上去,格式位置调整好。

2.将word转成.xml格式。(格式会乱,可以格式化一下或者直接点开.xml能看到规整的代码)

        图片会生成编码,将编码换成${img}就可以。

3.将.xml转成.ftl格式。

4.代码。(可以重新定义方法,或者写入现有方法中)

---------------------------------第一步

         //定义我们的编码方式
          Configuration configuration = new Configuration();
          configuration.setDefaultEncoding("UTF-8");
          //指定我们word的目录(pdfpath为存放.ftl目录不包含.ftl文件名称)。
          configuration.setDirectoryForTemplateLoading(new File(pdfpath));
          //指定我们要使用的word模板.ftl
          Template template = configuration.getTemplate("证明.ftl", "UTF-8");
          //指定输出流到的位置
          BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(new           FileOutputStream(wordpath+name+".doc"), "UTF-8"));
          //执行填充输出
          template.process(this.dataMap(),bufferedWriter);
          //关闭io流
          bufferedWriter.flush();
          bufferedWriter.close();

    -----------------------------第二步-赋值

  public Map<String,Object> dataMap() throws IOException {
          File file;
          String encode = "";
          Date date = new Date();
          SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
          String currentDateTime = sdf.format(date);
          Map<String , Object> map = new HashMap<>();
     
          //救助类型
          if("1".equals(type)){
              file = new File(ShiroUtils.getRealPath() + Constant.UPLOAD_PATH_VEDIO+"xz.png");
              FileInputStream fileInputStream = new FileInputStream(file);
              encode = inputStream(fileInputStream);
              map.put("type1",encode);
              map.put("yl",jiuzhuLogModel.getYl());
          }
          String y = "";
          String m = "";    
          String d = "";
          y = currentDateTime.substring(0, 4);
          m = currentDateTime.substring(4, 6);
          d = currentDateTime.substring(6, 8);
          //获取基础数据
          map.put("y",y);
          map.put("m",m);
          map.put("d",d);
          map.put("kg"," ");
          map.put("str",jiuzhuLogModel.getStr());
         //获取图片流且进行base64转码
          file = new File(“图片路径”);
          FileInputStream fileInputStream1 = new FileInputStream(file);
          encode = inputStream(fileInputStream1);
          map.put("ewm",encode);
          map.put("img",encode);
          //关闭流
          fileInputStream.close();
          return map;
        }    

-------------------------------转码

      /**
       * 图片路径转为二进制
       * @param file
       * @return
       */
    @SuppressWarnings("resource")
    public String inputStream(FileInputStream fileInputStream){
          byte[] bytes;
          String encode = null;
        try {
            
            bytes = new byte[fileInputStream.available()];
            fileInputStream.read(bytes);
            BASE64Encoder base64Encoder = new BASE64Encoder();
            encode = base64Encoder.encode(bytes);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
          return encode;
      }

---------------------------word转pdf(这里面需要用到很多jar包在下面介绍)。

      public void wordTpdf(String docFileName,String path,String pdfP) throws IOException {
          HttpClientDemo httpClienDemo = new HttpClientDemo();
          System.out.println("启动Word...");
          String sfileName = path + docFileName + ".doc";
          String toFileName = path + pdfP;
            InputStream docxInputStream = null;
            OutputStream outputStream = null;
            try {
                //sfileName- 原word地址包括文件名称
                docxInputStream = new FileInputStream(sfileName);
                // toFileName-转换后pdf生成地址包括文件名称
                outputStream = new FileOutputStream(toFileName);
                IConverter converter = LocalConverter.builder().build();
                converter.convert(docxInputStream)
                        .as(DocumentType.DOC)
                        .to(outputStream)
                        .as(DocumentType.PDF).execute();
                // 关闭
                converter.shutDown();
                // 关闭
                outputStream.close();
                // 关闭
                docxInputStream.close();
                httpClienDemo.signfile(Constant.UPLOAD_URL,pdfP);
            } catch (Exception e) {
                System.out.println("[documents4J] word转pdf失败:" + e.toString());
            } finally {
                if (outputStream != null) {
                    outputStream.close();
                }
                if (docxInputStream != null) {
                    docxInputStream.close();
                }
            }
  }

---------------------------------jar包;主要jar包documents.

首先给大家一个地址:可以下载jar包;这里面需要下载很多包,我就不一一截图了,大家将每个jar包下面的依赖包(图二)也下载到项目中,不然调用方法时会报错。Maven Repository: Search/Browse/Explore (mvnrepository.com)icon-default.png?t=N7T8https://mvnrepository.com/

-------------------------------- 

  • 18
    点赞
  • 21
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值