Issue formating bookmarked paragraphs

I have the attached docx file
sample.docx (12.0 KB)

that has few bookmarks. The bookmarks have the following format “italxxxx”. I want to implement a formating to bookmarked text. I am trying the code below:


import aspose.pydrawing as pydraw
import aspose.words as aw
import sys

def justify_text(filename):
    doc = aw.Document(filename)
    for bk in doc.range.bookmarks :
       bookmark_name = bk.name
       if "ital" in bookmark_name:
           print(bookmark_name)
           if bk is not None:
              current = bk.bookmark_start
              while current is not None and current != bk.bookmark_end:
                 if current.node_type == aw.NodeType.RUN:
                    current.as_run().font.highlight_color = pydraw.Color.yellow
                    current.as_run().font.name = "Arial"
                    current.as_run().font.size = 24
                    current = current.next_sibling
    builder = aw.DocumentBuilder(doc)
    for paragraph in doc.get_child_nodes(aw.NodeType.PARAGRAPH, True):
       builder.move_to(paragraph)
       builder.paragraph_format.alignment = aw.ParagraphAlignment.JUSTIFY

    doc.save(filename)

if __name__ == "__main__":
    if len(sys.argv) != 2:
        print("Usage: python program.py <filename>")
        sys.exit(1)

    filename = sys.argv[1]
    justify_text(filename)

When run, this code does not stop and no formating is implemented.
Any help is appreciated.

@ansar2024 You should move to the next node after the if statement not inside it. Please modify your code like this:

doc = aw.Document("C:\\Temp\\in.docx")

for bk in doc.range.bookmarks :
    bookmark_name = bk.name
    if "ital" in bookmark_name:
        print(bookmark_name)
        if bk is not None:
            current = bk.bookmark_start
            while current is not None and current != bk.bookmark_end:
                if current.node_type == aw.NodeType.RUN:
                    current.as_run().font.highlight_color = pydraw.Color.yellow
                    current.as_run().font.name = "Arial"
                    current.as_run().font.size = 24

                current = current.next_sibling

builder = aw.DocumentBuilder(doc)
for paragraph in doc.get_child_nodes(aw.NodeType.PARAGRAPH, True):
    builder.move_to(paragraph)
    builder.paragraph_format.alignment = aw.ParagraphAlignment.JUSTIFY

doc.save("C:\\Temp\\out.docx")
1 Like

I see! Thank you very much.

1 Like