itext7中带有pdfHtml的<fieldset>和<legend>标签

时间:2020-04-06 10:16:52

标签: itext7 pdfhtml

使用HTML文件,我使用iText pdfHTML生成了PDF文件。我想为内容提供标题,就像HTML <fieldset><legend>一样。

我在下面的HTML代码中使用过。在HTML页面中,它按预期显示。但是,当使用pdfHTML生成PDF文件时,“摘要”将出现在框中。不在框的边框中显示内容的标题。

<!DOCTYPE html>
<html>
<body>

 <fieldset>
  <legend>Summary</legend>
  <p>Some paragraph</p>  
 </fieldset>


</body>
</html>

我该如何解决?

1 个答案:

答案 0 :(得分:1)

pdfHTML目前还不支持fieldset标记,实际上您的样本已转换为以下形式:

current result

您可以将自定义实现插入pdfHTML中,尽管可以在某种程度上调整视觉外观(取决于您的需求)。这是一个有关如何通过大量假设调整视觉外观的基本示例:

private static class LegendTagWorker extends DivTagWorker {
    public LegendTagWorker(IElementNode element, ProcessorContext context) {
        super(element, context);
    }

    @Override
    public IPropertyContainer getElementResult() {
        IPropertyContainer result = super.getElementResult();
        // Shift the position of the legend a bit above
        result.setProperty(Property.POSITION, LayoutPosition.RELATIVE);
        result.setProperty(Property.TOP, -14);

        // Set the background of the text to white so that it does not overlap with the border of outer element
        if (result instanceof Div && ((Div) result).getChildren().get(0) instanceof Paragraph) {
            Paragraph p = (Paragraph) ((Div) result).getChildren().get(0);
            ((Text)p.getChildren().get(0)).setBackgroundColor(ColorConstants.WHITE);
        }
        return result;
    }
}

private static class CustomTagWorkerFactory extends DefaultTagWorkerFactory {
    @Override
    public ITagWorker getCustomTagWorker(IElementNode tag, ProcessorContext context) {
        if (tag.name().equals("legend")) {
            return new LegendTagWorker(tag, context);
        }
        return super.getCustomTagWorker(tag, context);
    }
}

然后,您只需要将标记工作器工厂传递给转换器属性即可:

ConverterProperties properties = new ConverterProperties();
properties.setTagWorkerFactory(new CustomTagWorkerFactory());
HtmlConverter.convertToPdf(inFile, outFile, properties);

现在我们得到以下结果:

result with tweak

请注意,这是一个非常基本的示例,您将需要对其进行调整。在pdfHTML中实现此功能之前,您将必须使用变通方法-按照我的建议在代码中进行调整,或者可以使用CSS进行一些调整,类似于我在Java代码中进行的调整