在 Spring Boot 中将 html 转换为 pdf 时内存未释放

问题描述

我正在将 html 转换为 Pdf,但在此过程中内存增加,完成后此过程内存未释放。Service 保留内存。我正在使用 Itext 将 html 转换为 pdf。

示例代码

依赖

       <dependency>
        <groupId>org.apache.veLocity</groupId>
        <artifactId>veLocity</artifactId>
        <version>1.7</version>
      </dependency>
   <dependency>
        <groupId>com.itextpdf</groupId>
        <artifactId>itext7-core</artifactId>
        <version>7.1.9</version>
        <type>pom</type>
    </dependency>

    <!-- iText pdfHTML add-on -->
    <dependency>
        <groupId>com.itextpdf</groupId>
        <artifactId>html2pdf</artifactId>
        <version>2.1.6</version>
    </dependency>

服务

    @Override
public String createDocument(DemandQuoteStatus demandQuoteStatus) {
    try {
        ByteArrayOutputStream target = new ByteArrayOutputStream();
        DemandQuote demandQuote = demandQuoteService.findByQuoteId(demandQuoteStatus.getQuoteId());
        VeLocityEngine ve = new VeLocityEngine();
        ve.setProperty(RuntimeConstants.RESOURCE_LOADER,"classpath");
        ve.setProperty("classpath.resource.loader.class",ClassPathResourceLoader.class.getName());
        ve.init();
        Template t = ve.getTemplate("templates/proposal-document.vm");
        VeLocityContext context = new VeLocityContext();
        Map<String,String> map = findValue(demandQuoteStatus,demandQuote);
        for (Map.Entry<String,String> t2 : map.entrySet()) {
            context.put(t2.getKey(),t2.getValue());
        }
        StringWriter writer = new StringWriter();
        t.merge(context,writer);


        HtmlConverter.convertToPdf(writer.toString(),target);
        byte[] bytes = target.toByteArray();
        InputStream inputStream = new ByteArrayInputStream(bytes);
        Users users = userService.findByUserId(demandQuote.getQuotes().getUserId());
        String url = amazonS3Service.uploadFiles(inputStream,users.getUserId(),ImageType.PROPOSAL_RAW,demandQuoteStatus.getQuoteId() + ".pdf",(long) bytes.length);
        if (Objects.isNull(url)) {
            throw new AppException(ExceptionMessage.FILE_GENERATION_ISSUE,HttpStatus.EXPECTATION_Failed);
        }

        inputStream.close();
        target.close();

        return url;
    } catch (Exception e) {
        e.printstacktrace();
        throw new AppException(ExceptionMessage.FILE_GENERATION_ISSUE,HttpStatus.EXPECTATION_Failed);
    }
}

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)