itext7:样式“ display:block;”在<strong>中无效

时间:2019-02-12 07:43:05

标签: itext7

请帮助我,谢谢

hello.html:

<html>
    <head>
        <style type="text/css" media="print">
            body {font-family: sans-serif;}
        </style>
    </head>
    <body>
        <h1>Test</h1><div><strong style="display:block;color:green">Hello</strong>World</div>
    </body>
</html>

java代码:

ConverterProperties properties = new ConverterProperties();
properties.setBaseUri(baseUri);
PdfWriter writer = new PdfWriter("target/hello.pdf", new WriterProperties().setFullCompressionMode(true));
HtmlConverter.convertToPdf(new FileInputStream("html/hello.html"), writer, properties);

输出hello.pdf:  code "style='display:block;'" is invalid in tag 'strong'

输出Chrome:  2

1 个答案:

答案 0 :(得分:3)

默认情况下,iText将<strong>标记映射到<span>的标记工作器和CSS应用程序。您应该忽略此行为。

创建自定义标签工作者工厂:

class StrongTagWorkerFactory extends DefaultTagWorkerFactory {
@Override
public ITagWorker getCustomTagWorker(IElementNode tag, ProcessorContext context) {
    if (tag.name().equals(TagConstants.STRONG)) {
        if (CssConstants.BLOCK.equals(tag.getStyles().get(CssConstants.DISPLAY))) {
            return new DivTagWorker(tag, context);
        }
    }
    return null;
}

}

将其实例作为参数传递给用于转换html的ConverterProperties实例:

converterProperties.setCssApplierFactory(new StrongCssApplierFactory());

创建自定义CSS应用程序工厂:

class StrongCssApplierFactory extends DefaultCssApplierFactory {
@Override
public ICssApplier getCustomCssApplier(IElementNode tag) {
    if (tag.name().equals(TagConstants.STRONG)) {
        if (CssConstants.BLOCK.equals(tag.getStyles().get(CssConstants.DISPLAY))) {
            return new BlockCssApplier();
        }
    }
    return null;
}

将其实例作为参数传递给用于转换html的ConverterProperties实例:

converterProperties.setTagWorkerFactory(new StrongTagWorkerFactory())

现在只需使用该converterProperties处理您的html:

HtmlConverter.convertToPdf(new File(htmlSource), new File(pdfOutput), converterProperties);

生成的pdf如下所示: enter image description here