首页 > 解决方案 > 当我在属性内容中使用 CSS3 函数 target-counter 时,iText7 不起作用

问题描述

我对 iText7 很陌生。我正在尝试从动态 HTML 字符串创建 pdf。到目前为止,我已经能够使用 HtmlConverter.ConvertToPdf() 创建 pdf。但问题是我需要在文档开头有一个包含章节和页码的目录。为此,我在我的 CSS 文件中写道:

@page {
  margin: 40mm 17mm 17mm 17mm;
  size: A4 portrait;
  @top-center { 
    content: element(header); 
    width: 100%;
  }
  @bottom-right-corner {
    content: counter(page);
  }
}

a::after { 
  content: leader('.') target-counter(attr(href), page) 
}

我在我的 HTML 文件中写道:

<!DOCTYPE HTML>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">
<head>
    <title>Good Thymes Virtual Grocery</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <link rel="stylesheet" th:href="@{${baseUrl} + '/static/css/relatorio_fiscalizacao.css'}"/>
</head>
<body>
  <h1>ÍNDICE</h1>
  <ul style="page-break-after: always;">
    <li><a href="#ch1">STAFF</a></li>
    <li><a href="#ch2">OPERATION DATA</a></li>
  </ul>

  <h1 id="ch1" class="chapter">STAFF</h1>
  <p style="page-break-after: always;">....</p>

  <h1 id="ch3" class="chapter">OPERATION DATA</h1>
  <p style="page-break-after: always;">....</p>

</body>
</html>

最后,我的 Spring Boot 应用程序中有一个组件:

@Component
public class PdfGeneratorUtil {
@Autowired
private TemplateEngine templateEngine;

@Autowired
ServletContext servletContext;

@Autowired
private ApplicationContext context;

@Value("${baseUrl}")
private String baseUrl;

public ByteArrayOutputStream createPdf(String templateName, Map<String, Object> map, final HttpServletRequest request, final HttpServletResponse response) throws Exception {
    Assert.notNull(templateName, "The templateName can not be null");

    System.out.println(baseUrl);

    map.put("baseUrl", baseUrl);

    IWebContext ctx = new SpringWebContext(request, response, servletContext, LocaleContextHolder.getLocale(), map, context);


    String processedHtml = templateEngine.process(templateName, ctx);
    ByteArrayOutputStream os = new ByteArrayOutputStream();

    try {
        ConverterProperties converterProperties = new ConverterProperties();
        HtmlConverter.convertToPdf(processedHtml, os, converterProperties);
        System.out.println("PDF created successfully");
    }
    finally {
        if (os != null) {
            try {
                os.close();
            } catch (IOException e) { /*ignore*/ }
        }
    }

    return os;
    }
}

iText 可以很好地转换为 Pdf。但是目录中的章节没有页数。并且日志返回“内容属性目标计数器无效或使用不支持的功能。”

我看到了CssContentPropertyResolver.java文件,我意识到代码没有处理 CSS 函数“target-counter”。所以,我的问题是:还有另一种方法可以做到这一点,也许像本教程一样创建自定义 CSS 应用程序?或者也许是其他方式?如果没有,有人知道我可以使用任何其他库来代替 iTextPdf 吗?

标签: cssspring-bootitextthymeleafhtml2pdf

解决方案


这适用于 html2pdf 库的最新版本——当然是 3.0.3 及更高版本。


推荐阅读