如何避免<TD>使用 Itext 5 将空的 <TR 单元格标记为 PDF



I 使用 i text 5 从 html 生成 PDF 作为输入。 作为 PDF 可访问性的一部分,添加 pdfwriter.settagged((。

但是在这里,所有空标签和非空标签都在标记.您能否帮助避免标记非空的html标签

我想解决它的一种方法是遍历输出PDF文档上的StructTree,并尝试找到您要查找的标签,没有任何孩子,并将其从父级中删除。我不再使用 iText 5,因为它已被弃用(仅发布安全修复程序(,但是使用 iText 7,您可以执行以下操作:

private void removeEmptyTag() throws IOException {
final PdfDocument pdfDoc = new PdfDocument(new PdfReader(ORIG),
new PdfWriter(DEST));
PdfDictionary catalog = pdfDoc.getCatalog().getPdfObject();
// Gets the root dictionary
PdfDictionary structTreeRoot = catalog.getAsDictionary(PdfName.StructTreeRoot);
manipulate(structTreeRoot);
pdfDoc.close();
}
public boolean manipulate(PdfDictionary element) {
if (element == null)
return false;
if (PdfName.TD.equals(element.get(PdfName.S))) {
if (!element.containsKey(PdfName.K)) {
return true;
}
}
PdfArray kids = element.getAsArray(PdfName.K);
if (kids == null) return false;
for (int i = 0; i < kids.size(); i++) {
if (manipulate(kids.getAsDictionary(i))) {
kids.remove(i);
}
}
return false;
}

这不是最优雅的事情,但我使用pdfHTML创建了一个HTML文件,其中我有一个空的td

<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>Age</th>
</tr>
<tr>
<td>Jill</td>
<td>Smith</td>
<td></td>
</tr>
<tr>
<td>Eve</td>
<td>Jackson</td>
<td>94</td>
</tr>

然后我使用代码来浏览它并删除空标签(或者更确切地说,没有子标签的标签(。也许有一个解决方案可以直接使用 xmlWorker 来做到这一点(我假设这是您用来创建 HTML 文档的方法(,或者更好的后处理替代方案来替代我的建议。

你可以直接使用pdfHTML(基本上是iText 7中HTML到PDF转换的解决方案(。

ConverterProperties props = new ConverterProperties();
props.setTagWorkerFactory(new DefaultTagWorkerFactory() {
@Override
public ITagWorker getCustomTagWorker(
IElementNode tag, ProcessorContext context) {
if (tag.name().equals(TagConstants.TD)) {
if (!tag.childNodes().isEmpty()) {
return new TdTagWorker(tag, context);
} else {
return new SpanTagWorker(tag, context);
}
}

return null;
}
});

PdfDocument doc = new PdfDocument(new PdfWriter(DEST));
doc.setTagged();
HtmlConverter.convertToPdf(new FileInputStream(ORIG), doc, props);

在上面的代码中,您可以使用 setTagWorkerFactory 为您的标签设置自定义行为,如文档中所述。在这种特定情况下,我只是将空的TD标签更改为Span元素,从而实现所需的行为(多余的TD标签消失(。

(老实说,这依赖于 TR 工作线程无法解析 SPAN 标签,所以它只是跳槽。如果我想出一个更优雅的解决方案,我会更新答案(

相关内容

最新更新