Class LayoutTaggingHelper

java.lang.Object
com.itextpdf.layout.tagging.LayoutTaggingHelper

public class LayoutTaggingHelper extends Object
The class is a helper which is used to correctly create structure tree for layout element (with keeping right order for tags).
  • Constructor Details

    • LayoutTaggingHelper

      public LayoutTaggingHelper (PdfDocument document, boolean immediateFlush)
      Instantiates a new LayoutTaggingHelper instance for managing layout-level tagging.

      This helper maintains a tree of tagging hints that represent the logical structure of a PDF document and coordinates tag creation in the PDF structure tree. It automatically registers default tagging rules for standard roles (e.g., TABLE, THEAD, TFOOT, TH) based on the PDF version.

      Parameters:
      document - the PDF document being created or modified
      immediateFlush - if true, parent tags will be flushed as soon as all their children are flushed; if false, tag flushing is deferred until explicitly requested
      See Also:
  • Method Details

    • addTreeHints

      public static void addTreeHints (LayoutTaggingHelper taggingHelper, IRenderer rootRenderer)
      Recursively registers tagging hints from a renderer tree, preserving the logical structure.

      This utility method traverses the renderer hierarchy and calls addKidsHint(IPropertyContainer, Iterable) for each renderer and its children, ensuring all parent-child relationships are captured in the tagging system.

      Parameters:
      taggingHelper - the helper instance managing tags
      rootRenderer - the root renderer of the tree to process recursively
      See Also:
    • getHintKey

      public static TaggingHintKey getHintKey (IPropertyContainer container)
      Retrieves an existing tagging hint key for the given container without creating one.

      If no hint key has been created for this container, returns null. Use getOrCreateHintKey(IPropertyContainer) if you need to ensure a hint exists.

      Parameters:
      container - the element or renderer to retrieve the hint for
      Returns:
      the TaggingHintKey associated with the container, or null if not yet created
      See Also:
    • getOrCreateHintKey

      public static TaggingHintKey getOrCreateHintKey (IPropertyContainer container)
      Gets or creates a tagging hint key for the given container.

      If a hint key already exists for this container, returns it. Otherwise, creates a new TaggingHintKey, stores it in the container's properties, and returns it.

      For ILargeElements that are not yet complete, the hint key is stored on the element itself rather than on the renderer, to preserve the hint across renderer recreation.

      If the container's role is StandardRoles.ARTIFACT, the created hint is automatically marked as artifact and finished.

      Parameters:
      container - the element or renderer to get or create a hint for
      Returns:
      the existing or newly created TaggingHintKey
      See Also:
    • addKidsHint

      public void addKidsHint (TagTreePointer parentPointer, IterableIPropertyContainer> newKids)
      Registers child hints for a pre-existing PDF tag (mapped via TagTreePointer).

      This method is used when you have a pre-existing tag structure element (from a PDF that already contains tags) and need to associate new children with it. The helper creates a TaggingDummyElement wrapper to manage the pre-existing tag and adds the new children under it.

      This is useful for merging external PDFs or handling documents that were partially tagged before layout processing.

      Parameters:
      parentPointer - the TagTreePointer pointing to the pre-existing parent tag
      newKids - the children to add under the parent tag
      See Also:
    • addKidsHint

      public void addKidsHint (IPropertyContainer parent, IterableIPropertyContainer> newKids)
      Registers children hints for a parent element or renderer (append mode).

      This method declares that the given children should appear as kids of the parent in the PDF structure tree. Children are appended to any existing children. This method creates TaggingHintKeys for each child if they don't already exist.

      Parameters:
      parent - the parent element or renderer
      newKids - the children to add under the parent (can be elements or renderers)
      See Also:
    • addKidsHint

      public void addKidsHint (IPropertyContainer parent, IterableIPropertyContainer> newKids, int insertIndex)
      Registers children hints for a parent element or renderer (with insert position).

      This method declares that the given children should appear as kids of the parent in the PDF structure tree, optionally at a specific position. If insertIndex is negative, children are appended.

      If the parent tag has already been created in the PDF structure tree, this method will relocate child tags into the parent.

      Parameters:
      parent - the parent element or renderer
      newKids - the children to add under the parent
      insertIndex - the position at which to insert the first child; negative means append at end
      See Also:
    • addKidsHint

      public void addKidsHint (TaggingHintKey parentKey, Collection<TaggingHintKey> newKidsKeys)
      Registers children hints using TaggingHintKeys directly (append mode).

      This variant works directly with TaggingHintKey objects instead of containers, useful when you already have the hint keys or when working with internal hint manipulation.

      Parameters:
      parentKey - the parent hint key
      newKidsKeys - the hint keys of children to add
      See Also:
    • addKidsHint

      public void addKidsHint (TaggingHintKey parentKey, Collection<TaggingHintKey> newKidsKeys, int insertIndex)
      Registers children hints using TaggingHintKeys directly (with insert position).

      This variant works directly with TaggingHintKey objects and supports specifying an insertion position. This is the core method that other addKidsHint overloads delegate to.

      Parameters:
      parentKey - the parent hint key
      newKidsKeys - the hint keys of children to add
      insertIndex - the position at which to insert the first child; negative means append at end
      See Also:
    • setRoleHint

      public void setRoleHint (IPropertyContainer hintOwner, String role)
      Overrides the PDF role for an element's tag in the structure tree.

      By default, a tag's role is determined from the element's accessibility properties. This method allows you to override that role at runtime. The override is applied when the tag is created.

      Important: Apply role overrides before calling finishTaggingHint(IPropertyContainer). Once tagging rules have been applied during finishing, re-applying the same rules for a new role will not occur.

      Parameters:
      hintOwner - the element or renderer whose tag role should be overridden
      role - the new PDF role (e.g., StandardRoles.SPAN, StandardRoles.STRONG)
      See Also:
    • isArtifact

      public boolean isArtifact (IPropertyContainer hintOwner)
      Checks whether the given container is marked as an artifact (non-accessible).

      An artifact is content that should not appear in the accessibility tree, such as decorative elements. Artifacts are not included in the PDF structure tree.

      This method checks:

      1. If a hint exists and is marked as artifact, returns true
      2. If the container's accessibility role is StandardRoles.ARTIFACT, returns true
      3. Otherwise returns false
      Parameters:
      hintOwner - the element or renderer to check
      Returns:
      true if the container is an artifact, false otherwise
      See Also:
    • markArtifactHint

      public void markArtifactHint (IPropertyContainer hintOwner)
      Marks an element or renderer as an artifact (non-accessible content).

      Artifacts are excluded from the PDF accessibility tree and are not exposed to assistive technologies. Use this for decorative elements, borders, backgrounds, or other non-semantic content.

      This method:

      • Marks the hint as artifact and finished
      • Recursively marks all children as artifacts
      • Removes the hint from its parent (orphaning it)
      • Logs an error if the artifact tag was already created in the PDF
      Parameters:
      hintOwner - the element or renderer to mark as artifact
      See Also:
    • markArtifactHint

      public void markArtifactHint (TaggingHintKey hintKey)
      Marks a hint key as an artifact (non-accessible content).

      This is the core implementation of artifact marking. It:

      • Sets the artifact and finished flags on the hint
      • Recursively marks all children as artifacts
      • Removes the hint from its parent
      • Flushes the artifact tag pointer if already created
      Parameters:
      hintKey - the hint key to mark as artifact
      See Also:
    • useAutoTaggingPointerAndRememberItsPosition

      public TagTreePointer useAutoTaggingPointerAndRememberItsPosition (IRenderer renderer)
      Saves the current auto-tagging pointer position and returns it for temporary use.

      This method is useful when a renderer needs to temporarily modify the auto-tagging pointer for custom tag creation or structure manipulation. The saved position can be restored later using restoreAutoTaggingPointerPosition(IRenderer).

      Usage pattern (with try-finally):

      
       TagTreePointer ptr = helper.useAutoTaggingPointerAndRememberItsPosition(renderer);
       try {
           ptr.addTag("CustomRole");
           // ... custom operations ...
       } finally {
           helper.restoreAutoTaggingPointerPosition(renderer);
       }
       
      Parameters:
      renderer - the renderer whose position should be saved (used as a key for restoration)
      Returns:
      the current auto-tagging pointer (position at the time of call)
      See Also:
    • restoreAutoTaggingPointerPosition

      public void restoreAutoTaggingPointerPosition (IRenderer renderer)
      Restores the auto-tagging pointer to a previously saved position.

      This method retrieves the pointer position saved by useAutoTaggingPointerAndRememberItsPosition(IRenderer) and moves the auto-tagging pointer back to that location. If no saved position exists for the renderer, does nothing.

      Important: Always call this in a finally block or error handling path to ensure the pointer is restored even if an exception occurs during custom tagging operations.

      Parameters:
      renderer - the renderer whose position should be restored
      See Also:
    • getKidsHint

      public List<TaggingHintKey> getKidsHint (TaggingHintKey parent)
      Gets the unmodifiable list of direct children for a parent hint.

      This method returns all direct children hints, including non-accessible intermediate nodes. For accessible children only, use getAccessibleKidsHint(TaggingHintKey).

      Returns an empty list if the parent has no children.

      Parameters:
      parent - the parent hint key
      Returns:
      an unmodifiable list of direct child hint keys
      See Also:
    • getAccessibleKidsHint

      public List<TaggingHintKey> getAccessibleKidsHint (TaggingHintKey parent)
      Gets the list of accessible children for a parent hint, flattening non-accessible intermediate nodes.

      This method returns only accessible children (those with a non-null role). Non-accessible intermediate nodes (grouping nodes) are recursively flattened, and their accessible descendants are included in the returned list.

      For example, if a parent has a non-accessible child that contains two accessible children, this method returns those two accessible children directly.

      Returns an empty list if the parent has no accessible children.

      Parameters:
      parent - the parent hint key
      Returns:
      an unmodifiable list of accessible child hint keys with non-accessible intermediates flattened
      See Also:
    • getParentHint

      public TaggingHintKey getParentHint (IPropertyContainer hintOwner)
      Gets the parent hint of a given element or renderer.

      This method retrieves the direct parent hint for the given container by first obtaining its hint key and then looking up the parent.

      Parameters:
      hintOwner - the element or renderer whose parent should be retrieved
      Returns:
      the parent TaggingHintKey, or null if this is a root or has no hint
      See Also:
    • getParentHint

      public TaggingHintKey getParentHint (TaggingHintKey hintKey)
      Gets the direct parent hint of a hint key.
      Parameters:
      hintKey - the child hint key
      Returns:
      the parent TaggingHintKey, or null if this is a root
      See Also:
    • getAccessibleParentHint

      public TaggingHintKey getAccessibleParentHint (TaggingHintKey hintKey)
      Gets the nearest accessible parent hint, skipping non-accessible intermediate nodes.

      This method traverses up the hint tree, skipping non-accessible hints (grouping nodes), and returns the first accessible parent found. Useful when you need to know the logical parent regardless of grouping structure.

      Parameters:
      hintKey - the child hint key
      Returns:
      the nearest accessible parent TaggingHintKey, or null if no accessible parent exists
      See Also:
    • releaseFinishedHints

      public void releaseFinishedHints()
      Incrementally finalizes and releases finished hints from the tagging structure.

      This method scans all hints and releases those that:

      • Are marked as finished
      • Are accessible (not non-accessible grouping nodes)
      • Have no unfinished parents (up the hierarchy)
      • Have no unfinished children
      • Are not followed by unfinished siblings

      When a hint is released:

      • It is removed from the hint trees
      • The associated PDF tag is finalized
      • If immediateFlush is enabled, parent tags are flushed if all kids are flushed

      This is an incremental operation useful for memory management. Call this periodically (e.g., at end of each page or logical boundary) to progressively finalize tags.

      See Also:
    • releaseAllHints

      public void releaseAllHints()
      Forces finalization and release of all hints, clearing the entire tagging structure.

      This is a comprehensive cleanup operation that:

      • Finishes all dummy elements (pre-existing tags)
      • Recursively finishes all dummy children
      • Calls releaseFinishedHints() to finalize any now-finished hints
      • Releases all remaining unfinished hints (orphaned hints)
      • Clears all internal maps

      Call this at the end of document layout or when discarding the layout state entirely. This method should leave all internal structures empty after completion.

      See Also:
    • createTag

      public boolean createTag (IRenderer renderer, TagTreePointer tagPointer)
      Creates or retrieves a PDF tag for a renderer, ensuring it exists in the structure tree.

      This method is typically called by a renderer before it writes marked content to ensure the tag is positioned correctly in the PDF structure tree. If the tag already exists, it is not recreated.

      For artifacts, returns false without creating a tag. For non-accessible hints, the pointer is positioned at the nearest accessible parent. For accessible hints, a tag is created with the correct sibling index.

      Parameters:
      renderer - the renderer whose tag should be created
      tagPointer - the tag tree pointer to use for positioning; the pointer may be moved during tag creation
      Returns:
      true if a tag was created, false if one already existed or hint is artifact/non-accessible
      See Also:
    • createTag

      public boolean createTag (TaggingHintKey hintKey, TagTreePointer tagPointer)
      Creates a PDF tag for a hint key, ensuring it exists in the structure tree.

      This is the core tag creation method. It:

      • Returns false if the hint is an artifact
      • Determines the correct parent tag and sibling index
      • Creates the tag via tagPointer.addTag(...)
      • Stores the pointer on the hint
      • Assigns waiting state to the tag
      • Recursively creates tags for dummy children

      The pointer may be modified during this method to position it at the correct parent and index. That's why if auto-tagging pointer is to be used, make sure to rely on useAutoTaggingPointerAndRememberItsPosition(com.itextpdf.layout.renderer.IRenderer) and restoreAutoTaggingPointerPosition(com.itextpdf.layout.renderer.IRenderer) functionality.

      Parameters:
      hintKey - the hint key to create a tag for
      tagPointer - the tag tree pointer to use for positioning
      Returns:
      true if a tag was created, false if artifact or already exists
      See Also:
    • finishTaggingHint

      public void finishTaggingHint (IPropertyContainer hintOwner)
      Marks an element or renderer as logically complete and applies tagging rules.

      Call this method when an element has finished its layout or rendering and will not receive new children. This triggers:

      • Lookup of applicable ITaggingRules for the element's role
      • Invocation of each rule's ITaggingRule.onTagFinish(LayoutTaggingHelper, TaggingHintKey) method
      • If all rules return true, the hint is marked as finished
      • If any rule returns false, the hint remains unfinished (rules can block finishing)

      Important: A hint cannot receive new children or be relocated after finishing. Always try to finish hints in parent-to-child order (or at least ensure children are finished before parents) if possible.

      For non-accessible hints, rules are bypassed and the hint is marked finished immediately. For artifacts, this method has no effect.

      Parameters:
      hintOwner - the element or renderer to finish
      See Also:
    • replaceKidHint

      public int replaceKidHint (TaggingHintKey kidHintKey, Collection<TaggingHintKey> newKidsHintKeys)
      Replaces one child hint with multiple new child hints.

      This method is useful when a single renderer needs to expand into multiple child tags. It removes the old child from its parent and inserts the new children at the same position.

      Errors are logged and the operation fails if:

      • The child hint is already finished
      • Any new child is already finished and either has no parent or the parent is already finished too.

      The method returns the index where the replacement occurred, which can be used for further hint tree manipulation if needed.

      Parameters:
      kidHintKey - the child hint to be replaced
      newKidsHintKeys - the new child hints to insert at the replacement position
      Returns:
      the index where the old child was removed, or -1 if replacement failed
      See Also:
    • moveKidHint

      public int moveKidHint (TaggingHintKey hintKeyOfKidToMove, TaggingHintKey newParent)
      Moves a child hint from its current parent to a new parent (appended).

      This method removes a child from its current parent and re-parents it to the new parent, appending it to the new parent's children list.

      For a specific insertion position in the new parent, use moveKidHint(TaggingHintKey, TaggingHintKey, int).

      Parameters:
      hintKeyOfKidToMove - the child hint to move
      newParent - the new parent hint
      Returns:
      the index where the child was removed from the old parent, or -1 if move failed
      See Also:
    • moveKidHint

      public int moveKidHint (TaggingHintKey hintKeyOfKidToMove, TaggingHintKey newParent, int insertIndex)
      Moves a child hint from its current parent to a new parent at a specific position.

      This method is similar to moveKidHint(TaggingHintKey, TaggingHintKey) but allows specifying the insertion index in the new parent's children list. Negative index means append.

      Errors are logged if:

      • The new parent is already finished
      • The child hint is already finished
      Parameters:
      hintKeyOfKidToMove - the child hint to move
      newParent - the new parent hint
      insertIndex - the position at which to insert the child; negative means append
      Returns:
      the index where the child was removed from the old parent, or -1 if move failed
      See Also:
    • createStructureElementId

      public String createStructureElementId (String prefix)
      Created a unique id for a structureElement.
      Parameters:
      prefix - a prefix to prepend to the id
      Returns:
      a unique id
    • getPdfDocument

      public PdfDocument getPdfDocument()
      Gets the PDF document associated with this helper.
      Returns:
      the PdfDocument passed to the constructor