Highlight and add comment to text

Is it possible to add a condition like I want to highlight a text but it should not highlight if it is in the table. ex- “Decsription” is the word that I want to highlight and it should highlight this only if it’s not a text from table.
Document.docx (7.2 KB)

@harshitha112000 You can check the node’s ancestor to skip nodes, which are inside the table. For example see the following code:

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

lists = ['Supported business process(es)','Project Life Cycle','User Requirement Specification (URS)','Functional Specification (FS)','Training','books', 'Description']

options = aw.replacing.FindReplaceOptions()
options.apply_font.highlight_color = pydraw.Color.blue
options.use_substitutions = True

for r in doc.get_child_nodes(aw.NodeType.RUN, True):
    run = r.as_run()
    # skip runs from the table.
    if run.get_ancestor(aw.NodeType.TABLE) == None:
        if run.font.bold:
            for list1 in lists:
                run.range.replace(list1, "$0", options)

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

Thanks, that worked.
Is it possible to add comments with new line. ex-
“comment - Header/Subheader added in document.
(Newline)
Recommendation - 1.Table of Content should have all sections with the document listed. 2. If any sections is Not Applicable: - Explicitly write “Not Applicable” followed with a Justification. - Do Not delete the section”

@harshitha112000 Sure you can create multiline comments. You can either use soft line break (see ControlChar.LINE_BREAK) or put several paragraphs into the comment.
Please see our documentation to learn how to work with comments:
https://docs.aspose.com/words/python-net/working-with-comments/

Ok thanks, I’ll check.

1 Like

Is it possible to make few words in comment appear bold?

@harshitha112000 Sure, you should simply specify formatting of the Run. the following simple code demonstrates how to create comment with different formatting and with two paragraphs in it:

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

comment = aw.Comment(doc, "John Doe", "JD", datetime.date.today())

comment_paragraph = aw.Paragraph(doc)
comment.append_child(comment_paragraph)
bold_run = aw.Run(doc, "bold text ")
bold_run.font.bold = True
comment_paragraph.append_child(bold_run)

italic_run = aw.Run(doc, "italic text ")
italic_run.font.italic = True
comment_paragraph.append_child(italic_run)

normal_run = aw.Run(doc, "normal text")
comment_paragraph.append_child(normal_run)

comment_paragraph2 = aw.Paragraph(doc)
comment.append_child(comment_paragraph2)
comment_paragraph2.append_child(aw.Run(doc, "This is another paragraph in the comment"))

doc.first_section.body.first_paragraph.append_child(comment)

doc.save("C:\\Temp\\out.docx")
comment = aw.Comment(document, "Harshitha", "S", datetime.now())
comment.paragraphs.add(aw.Paragraph(document))

comment.first_paragraph.runs.add(aw.Run(document, "Review the spellings of highlighted words. Ignore if the spellings are valid." + aw.ControlChar.LINE_BREAK + "Recommendation:" + aw.ControlChar.LINE_BREAK+"Table of Content should have all sections with the document listed"))
           
run.parent_node.insert_before(aw.CommentRangeStart(document, comment.id), run)
run.parent_node.insert_after(aw.CommentRangeEnd(document, comment.id), run)
     
run.parent_node.insert_after(comment, run)

This is my code, in this I want to make “Recommendation” as bold

@harshitha112000 Please modify your code like this:

comment = aw.Comment(document, "Harshitha", "S", datetime.date.today())
comment.paragraphs.add(aw.Paragraph(document))

comment.first_paragraph.append_child(aw.Run(document, "Review the spellings of highlighted words. Ignore if the spellings are valid." + aw.ControlChar.LINE_BREAK))
bold_text = aw.Run(document, "Recommendation:")
bold_text.font.bold = True
comment.first_paragraph.append_child(bold_text)
comment.first_paragraph.append_child(aw.Run(document, aw.ControlChar.LINE_BREAK+"Table of Content should have all sections with the document listed"))

ok, thanks I’ll do this

1 Like
import your_libraries_here  # Import the necessary libraries/modules

def invalid_url_highlight(df, document1):

    try:
        links = []

        for field in document1.range.fields:
            if field.type == FieldType.FIELD_HYPERLINK:
                hyperlink = field.as_field_hyperlink()
                links.append(hyperlink)

        options = aw.replacing.FindReplaceOptions()
        options.apply_font.highlight_color = ad.Color.pink

        for key, row in df.iterrows():
            if row["RESPONSE_CODE"] == 200:  
                for link in links:
                    if row['URL'] == link.address:
                        document1.range.replace(link.display_result, link.display_result, options)

        # Loop to find highlighted runs
        for node in document1.get_child_nodes(NodeType.RUN, True):
            run = node.as_run()
            if run.font.highlight_color == ad.Color.pink:
                # Create and add a comment
                comment = aw.Comment(document1, "Doc Review", "DR", datetime.now())
                comment.paragraphs.add(aw.Paragraph(document1))
                comment.first_paragraph.append_child(aw.Run(document1, "Invalid URL"))
                comment.first_paragraph.append_child(aw.Run(document1, "Recommendation:"))
                bold_text = aw.Run(document1, "Recommendation:")
                bold_text.font.bold = True
                comment.first_paragraph.append_child(bold_text)
                comment.first_paragraph.append_child(aw.Run(document1, "\n\nURL's listed should be verified and ensured that it points to the right document/material."))
                
                # Wrap the Run with CommentRangeStart and CommentRangeEnd
                run.parent_node.insert_before(aw.CommentRangeStart(document1, comment.id), run)
                run.parent_node.insert_after(aw.CommentRangeEnd(document1, comment.id), run)
                
                # Add a comment
                run.parent_node.insert_after(comment, run)
        
        return document1  # Return the modified document
    
    except Exception as e:
        print("Error:", e)

Hi @alexey.noskov, @denis.shvydkiy actually when I execute this code the comments are adding twice for the same word I couldn’t understand why, can you please help me . In the code df is the dataframe which contains url and responsecode. Please find the document which contains the url.

ThanksDocument.docx (7.2 KB)

@harshitha112000 The problem occurs because hyperlink url can be in both field code and field value. To avoid such kind of duplication, please ignore field codes. You can achieve this by specifying FindReplaceOptions.ignore_field_codes option.

Will this solve the problem of comments appearing twice?

@harshitha112000 Yes, in this case url that appears in the field code will be ignored by find/replace operation.

I am confused how exactly to use this with my code can you please help

@harshitha112000 If you specify the option like this:

options = aw.replacing.FindReplaceOptions()
options.apply_font.highlight_color = ad.Color.pink
options.ignore_field_codes = True

Aspose.Words will ignore field codes and comment will not be added to the url in the field code.

But if go further, it is actually is not required to use find/replace functionality to add comments around hyperlink fields. You can simplify your code like the following:

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

for field in doc.range.fields:
    if field.type == aw.fields.FieldType.FIELD_HYPERLINK:
        hyperlink = field.as_field_hyperlink()
        # Check whether hyperlink is valid
        # ......

        # Add comment around hyperlink
        comment = aw.Comment(doc, "Doc Review", "DR", datetime.date.today())
        comment.paragraphs.add(aw.Paragraph(doc))
        comment.first_paragraph.append_child(aw.Run(doc, "Invalid URL"))
        comment.first_paragraph.append_child(aw.Run(doc, "Recommendation:"))
        bold_text = aw.Run(doc, "Recommendation:")
        bold_text.font.bold = True
        comment.first_paragraph.append_child(bold_text)
        comment.first_paragraph.append_child(aw.Run(doc, "\n\nURL's listed should be verified and ensured that it points to the right document/material."))
                
        # Wrap the Hyperlink with CommentRangeStart and CommentRangeEnd
        field.start.parent_node.insert_before(aw.CommentRangeStart(doc, comment.id),  field.start)
        field.end.parent_node.insert_after(aw.CommentRangeEnd(doc, comment.id), field.end)
                
        # Add a comment
        field.end.parent_node.insert_after(comment, field.end)


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

Got it, thanks

1 Like

Error: Proxy error(ArgumentException): Cannot insert a node of this type at this location.

@alexey.noskov I am getting above error for below code. what might be the issue?

I am getting error exactly at this line comment.append_child(bold_text)

try:
        opt = aw.replacing.FindReplaceOptions()
        opt.use_substitutions = True
        if len(invalid_dates_unique) != 0:
            dates_list = list(invalid_dates_unique)
            for word in dates_list:
                #for word in dates:
                document1.range.replace(word, "$0", opt)
                # Get all runs
                runs = document1.get_child_nodes(aw.NodeType.RUN, True)
                for r in runs :
                    run = r.as_run()
                    if word in run.text:
                        run.font.highlight_color = ad.Color.green
                        # Crete a comment
                        comment = aw.Comment(document1, "Harshitha", "S", datetime.now())
                        comment.paragraphs.add(aw.Paragraph(document1))
                        comment.first_paragraph.runs.add(aw.Run(document1, "Invalid Date in paragraphs, Date Format: MM/DD/YYYY. For example, 12/31/2022 or 1/8/2023 are valid formats."+ aw.ControlChar.LINE_BREAK +aw.ControlChar.LINE_BREAK))
                        bold_text = aw.Run(document1, "Recommendation:")
                        bold_text.font.bold = True
                        comment.append_child(bold_text)
                    
                        # Wrap the Run with CommentRangeStart and CommentRangeEnd
                        run.parent_node.insert_before(aw.CommentRangeStart(document1, comment.id), run)
                        run.parent_node.insert_after(aw.CommentRangeEnd(document1, comment.id), run)
                        # Add a comment.
                        run.parent_node.insert_after(comment, run)

@harshitha112000 Run node cannot be a direct child of Comment. So the following line of code throws:

comment.append_child(bold_text)

Please change it to

comment.first_paragraph.append_child(bold_text)

oh, ok. Thankyou.

1 Like