springboot~aspose操做word模板實現導出功能

事情是這樣的,系統有這樣一個需求,有一些單子供客戶下載打印,作爲憑證,而這些單子通常屬於word格式的,裏面的排版很是固定,只是上面的內容不一樣,這就屬於word模板的範疇了,目前比較很差的操做word的組件就是aspose了,下面我來講一下它的使用方法。java

word模板

主要使用了word裏的域,而後選擇「郵件合併」,在「域名」處輸入你的word變量名,而後在java代碼裏爲這個變量賦值就能夠了app

添加組件引用

把組件放到resource/lib目錄下測試

<dependency>
            <groupId>com.bdyh.common</groupId>
            <artifactId>common</artifactId>
            <version>0.0.1</version>
            <scope>system</scope>
            <systemPath>${project.basedir}/src/main/resources/lib/aspose-words-15.8.0-jdk16.jar</systemPath>
        </dependency>

代碼生成

aspose組件存在受權問題,沒有受權的會有水印出現code

private static InputStream license;
  private static InputStream fileInput;
 public static void generateApproveForm(HttpServletResponse response,
                                         List<CompanyLawyerEducationAddDTO> counterpartDetails) {
    // 驗證License
    if (!getLicense("templates/companyLawyerApprove.docx")) {
      return;
    }
    try {
      long old = System.currentTimeMillis();
      Document doc = new Document(fileInput);
      //主要調用aspose.words的郵件合併接口MailMerge
      //3.1 填充單個文本域
      String[] Flds = new String[]{"Title", "Name", "URL", "Note"}; //文本域
      Object[] Vals = new Object[]{"標題", "測試",  "http://test.com", word模板導出"}; //值
      doc.getMailMerge().execute(Flds, Vals); //調用接口
      response.setHeader("Content-Disposition", "attachment; filename=審批單.pdf");
      response.setContentType("application/octet-stream;charset=UTF-8");

      OutputStream output = response.getOutputStream();
      doc.save(output, SaveFormat.PDF);

      output.flush();
      output.close();
}

 public static boolean getLicense(String templateName) {
    boolean result = false;
    try {
      license = new ClassPathResource("lib/license.xml").getInputStream();
      fileInput = new ClassPathResource(templateName).getInputStream();

      License aposeLic = new License();
      aposeLic.setLicense(license);
      result = true;
    } catch (Exception e) {
      e.printStackTrace();
    }
    return result;
  }

以上模板是最簡單的文本域的,若是有興趣還能夠把表格域也放上去,實現列表的輸出等。orm

相關文章
相關標籤/搜索