微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决在 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 举报,一经查实,本站将立刻删除。