如何使用 itext7 从标记的 pdf 中的结构元素中提取文本

How to extract text from structure elements in a tagged pdf using itext7

我想读取一个带标签的 pdf,遍历结构树,并提取每个元素的文本,最终输出类似于

- document
  - div
    - H1
      - "The title of the document"
    - P
      - "The contents of the paragraph"

我可以使用这段代码遍历树:

if (doc.IsTagged())
{
    var root = doc.GetStructTreeRoot();
    var stack = new Stack<iText.Kernel.Pdf.Tagging.IStructureNode>();
    var stack2 = new Stack<iText.Kernel.Pdf.Tagging.IStructureNode>();
    stack.Push(root);


    while (stack.Count > 0)
    {
        var currentNode = stack.Pop();
        stack2.Push(currentNode);
        var kids = currentNode.GetKids();


        if (kids != null)
        {
            foreach (var kid in kids)
            {
                stack.Push(kid);
            }
        }
    }

    while (stack2.Count > 0)
    {
        var currentNode = stack2.Pop();
        var role = currentNode.GetRole()?.ToString();
        if (currentNode is iText.Kernel.Pdf.Tagging.PdfMcrDictionary mcr) {
          // this is where I want to extract the text from the structured node
        }
    }
}

我不确定如何获取结构节点内的实际文本,例如H1、P等标签的内容。

有一个用于读取文档标签结构的现成解决方案 - 它称为 TaggedPdfReaderTool。它允许您解析包含元素文本内容的标签结构,并使用该内容创建一个 XML。

有关如何使用该工具的示例:

FileOutputStream xmlOut = new FileOutputStream(outXmlPath);
new TaggedPdfReaderTool(pdfDocument).setRootTag("root").convertToXml(xmlOut);

如果 XML 结构不适合您,那么您可以查看 implementation 以获取灵感 - class 是 self-contained 并包含以下逻辑从标签中提取文本。