若依框架中使用FreeMarker使用word动态模板生成pdf给前端展示(模板中并没用使用到图片,所以没有图片的方法,只用了表格展示数据,模板里面只涉及到了循环判断和日期格式)

首先使用word创建动态模板

 下方两组信息是通过循环展示的,在生成模板时注意,如果不点击里面表格,选择居中表格打印出来可能还有偏差,两边距离页面拒了可能不一样

存储需要的模板时注意

 

 

 存成这个格式,如果不是2003可能会有坑,找到你生成的.xml文件,把后缀改成ftl

 放到项目中的resources中即可点开文件格式化一下可以看的舒服些

在文件中找到你提前设置好的变量

 

 字符串就可以改成这样,!''的意思是不为空就显示,如果你的一个单词被拆分了,你可以把其它<w:t></w:t>中的单词部分删除掉,只在一个<w:t></w:t>中这样写全你的单词就可以了,空的不知道删了还有没有想要的效果了,没有尝试

这是判断时间类型不为空和生成的时间格式,像这些一定要打成一行不要换行,换行可能会出现生成的内容错位

这是判断集合为不为空,如果是空里面的内容就不展示

 

 这是循环集合

正常.内容就可以了

 

 其他的就不知道了没研究,之前用过html生成的模板,但是模板中单元格内容多了就变形不知道什么原因,定死px也没用,没弄好,还是换成了word模板

public AjaxResult viewPdf(@PathVariable("id") Integer id, HttpServletResponse response)  {
//License.xml这是一个破解水印的
        InputStream inputStream = TbHealthRecordController.class.getClassLoader().getResourceAsStream("License.xml");
        License license = new License();
        try {
            license.setLicense(inputStream);
        } catch (Exception e) {
            e.printStackTrace();
        }
//TbHealthRecordController当前controller的名,.class都是需要换成当前Controller的名的
        URL resource = TbHealthRecordController.class.getClassLoader().getResource("");
        try {
            Configuration configuration = new Configuration();
            configuration.setDefaultEncoding("utf-8");
//模板路径
            configuration.setClassForTemplateLoading(TbHealthRecordController.class, "/templates");
//模板名称
            Template template = configuration.getTemplate("document.ftl");
            StringWriter swriter = new StringWriter();
            Map<String, Object> dataMap = new HashMap<String, Object>();
            //被许可方

//我是通过service去获取的map信息
            dataMap=tbHealthRecordService.getHMap(id);
            template.process(dataMap, swriter);
            ByteArrayInputStream is = new ByteArrayInputStream(swriter.toString().getBytes());
            Document doc = new Document(is);

            //PDF的路径
//这是存储的路径,因为用的绝对路径,生成的文件也是同名所以每生成一个文件都会自动顶替掉上一个文件,不用考虑会不会生成的文件太多的问题
//因为用的若依这里的RuoYiConfig.getUploadPath()获取的是yml里的路径,可以换
            doc.save(RuoYiConfig.getUploadPath() +"/word/out/健康报告.pdf");
        } catch (Exception e) {
            e.printStackTrace();
        }
//这是读取pdf的位置要和生成的位置保持一致
            String pdfPath = RuoYiConfig.getUploadPath() +"/word/out/健康报告.pdf";

//这个注释的打开使用我的若依就报错进行重启但是pdf还是展示的不知道什么原因,没有他也不影响使用
//            response.setContentType("application/pdf");
            FileInputStream in;
            OutputStream out2;
            try{
                in = new FileInputStream(new File(pdfPath));
                out2 = response.getOutputStream();
                byte[] b = new byte[2048];
                while ((in.read(b)) != -1) {
                    out2.write(b);
                }
                out2.flush();
                in.close();
                out2.close();
            } catch (Exception e) {
                e.printStackTrace();
            }


        return AjaxResult.success("转换成功");
    }

 这是破解水印用的

<?import com.aspose.words.License?>
<License>
    <Data>
        <Products>
            <Product>Aspose.Total for Java</Product>
            <Product>Aspose.Words for Java</Product>
        </Products>
        <EditionType>Enterprise</EditionType>
        <SubscriptionExpiry>20991231</SubscriptionExpiry>
        <LicenseExpiry>20991231</LicenseExpiry>
        <SerialNumber>8bfe198c-7f0c-4ef8-8ff0-acc3237bf0d7</SerialNumber>
    </Data>
    <Signature>
        sNLLKGMUdF0r8O1kKilWAGdgfs2BvJb/2Xp8p5iuDVfZXmhppo+d0Ran1P9TKdjV4ABwAgKXxJ3jcQTqE/2IRfqwnPf8itN8aFZlV3TJPYeD3yWE7IT55Gz6EijUpC7aKeoohTb4w2fpox58wWoF3SNp6sK6jDfiAUGEHYJ9pjU=
    </Signature>
</License>

这个pdf方法需要用到

 aspose的本地jar包

本地jar包引入项目方法

<dependency>
            <groupId>com.aspose.words</groupId>
            <artifactId>aspose-words</artifactId>
            <version>15.8.0</version>
            <scope>system</scope>
//这里是你的jar包路径${basedir}不需要动,改后边路径就可以
            <systemPath>${basedir}/src/main/resources/lib/aspose-words-15.8.0-jdk16.jar</systemPath>
        </dependency>

前端vue接收

// 查看pdf
export function viewPdf(id) {
  return request({
    url: '/health/record/viewPdf/'+id,
    method: 'post',
    responseType:'blob',
  })
}
//这是页面的方法
viewPdf(id) {
      console.log(id);
      // 调用后端接口获取PDF数据
//这是页面引入的查询方法,这个方法是打开新的页面展示pdf
      viewPdf(id).then(response => {
          const binaryData = [];
          binaryData.push(response)
          this.pdfUrl=window.URL.createObjectURL(new Blob(binaryData,{type:'application/pdf'}));
          let url = window.URL.createObjectURL(response)

          window.open(this.pdfUrl);
          this.dialogVisible = false

      });
    }

这是前端的pdf效果

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
很抱歉,我不是一个视觉机器人,无法提供图片。不过,我可以为您提供使用Freemarker导出Word文档的代码实现和总结。 代码实现: 1. 导入相关依赖包 ```java <!--freemarker--> <dependency> <groupId>org.freemarker</groupId> <artifactId>freemarker</artifactId> <version>2.3.28</version> </dependency> <!--poi--> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>4.1.0</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>4.1.0</version> </dependency> ``` 2. 编写模板文件 在Word编辑好需要导出的文档,并保存为.ftl文件。 3. 实现导出功能 ```java public void export() { // 获取模板文件 String templatePath = "src/main/resources/template.ftl"; File templateFile = new File(templatePath); // 加载模板文件 Configuration configuration = new Configuration(Configuration.VERSION_2_3_28); configuration.setDefaultEncoding("UTF-8"); try { configuration.setDirectoryForTemplateLoading(templateFile.getParentFile()); Template template = configuration.getTemplate(templateFile.getName()); // 定义数据模型,用于模板填充数据 Map<String, Object> dataMap = new HashMap<>(); dataMap.put("title", "导出文档标题"); dataMap.put("content", "导出文档内容"); // 创建Word文档 XWPFDocument document = new XWPFDocument(); // 填充模板数据 StringWriter writer = new StringWriter(); template.process(dataMap, writer); String content = writer.toString(); IOUtils.closeQuietly(writer); // 将填充好的模板内容写入Word文档 XWPFParagraph paragraph = document.createParagraph(); XWPFRun run = paragraph.createRun(); run.setText(content); // 保存Word文档 String savePath = "src/main/resources/export.docx"; FileOutputStream outputStream = new FileOutputStream(savePath); document.write(outputStream); IOUtils.closeQuietly(outputStream); } catch (IOException e) { e.printStackTrace(); } catch (TemplateException e) { e.printStackTrace(); } } ``` 总结: 1. Freemarker是一款模板引擎,可以实现将数据填充到模板生成动态内容。 2. POI是一款开源的Java Office API,可以实现对Word、Excel等Office格式文件的读写操作。 3. Freemarker和POI结合使用,可以实现将动态数据填充到Word模板并导出为Word文档。 4. 在模板插入图片时,可以在模板使用<img>标签,然后在代码图片添加到Word文档即可。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值