Bookmark Paragraph

Fine Tahir. Thank You.

@Vadivel_S_S,

Please feel free to ask if you have any question about Aspose.Words, we will be happy to help you.

Hi Tahir,

I request to skip the bookmark for all bold font para in word document. kindly please give solution for this one.

Input : inp.zip (22.6 KB)

Current OP : Current_OP.zip (22.0 KB)

Expected OP : Exp_OP.zip (22.6 KB)

@Vadivel_S_S,

Thanks for your inquiry. In bookmark method, you can use following if condition to ignore the paragraph that has bold font formatting. Hope this helps you.

if (para.getParagraphFormat().getStyle().getFont().getBold()
        || (para.getRuns().getCount() > 0 && para.getRuns().get(0).getFont().getBold()))
    continue;

Thank you tahir, Its working fine.

I have one more query about skip the bookmarks. i have used following code for skip the bookmarks in keywords para section. But some of scenario is not working. Please give solution for this one.

This is code for skip the bookmarks in keywords para section.

if (para.toString(SaveFormat.TEXT).trim().startsWith(“Keywords:”))
Continue;

I have attached documents please find.
Input : input.zip (70.4 KB)

Current OP: Current OP.zip (74.3 KB)

Expected OP : Expected_OP.zip (74.6 KB)

FYI : In this current output doc the Abstract para was not bookmarked please kindly give solution for this also.

@Vadivel_S_S,

Thanks for your inquiry. Unfortunately, your requirement is not clear enough therefore we request you to please elaborate your inquiry further. The output and expected output documents are same. Please share the page number of document that contains the keyword you want to skip.

Dear Tahir,

In that current OP document, third page keywords para are bookmarked. I need to skip that part. Also second page abstract part is need to bookmark. I have attached current output with highlighted issues.

Current OP : Find.zip (73.4 KB)

@Vadivel_S_S,

Thanks for sharing the detail. We have modified the if conditions in following method. Please check it. Hope this helps you.

private static void bookmark(Document inputdoc)
{
    try
    {
        DocumentBuilder builder = new DocumentBuilder(inputdoc);
        int i = 0;
        for(Paragraph para : (Iterable<Paragraph>) inputdoc.getChildNodes(NodeType.PARAGRAPH, true))
        {
            if(para.getParagraphFormat().getStyleName().equals("Title") ||
                    para.getParagraphFormat().getStyleName().equals("Item-Info") ||
                    para.getParagraphFormat().getStyleName().equals("Author Group") ||
                    para.getParagraphFormat().getStyleName().equals("References") ||
                    para.getParagraphFormat().getStyleName().equals("Affiliation") ||
                    para.getParagraphFormat().getStyleName().equals("Keywords"))
            {
                continue;
            }

        if (para.getRuns().getCount() > 0 && para.getRuns().get(0).getFont().getBold())
        {
            continue;
        }


            if (para.getAncestor(NodeType.TABLE) != null)
                continue;
            if (para.getChildNodes(NodeType.SHAPE, true).getCount() > 0 )
                continue;
            if (para.getChildNodes().getCount() == 0 || para.toString(SaveFormat.TEXT).trim().equals(""))
                continue;
            if (para.getChildNodes(NodeType.OFFICE_MATH, true).getCount() > 0)
                continue;

            builder.moveTo(para);
            BookmarkStart start = new BookmarkStart(inputdoc, "LEBookMark" + i);
            BookmarkEnd end = new BookmarkEnd(inputdoc, "LEBookMark" + i);
            if (para.hasChildNodes())
            {
                para.insertBefore(start, para.getFirstChild());
                para.appendChild(end);
            }
            i++;
        }
        inputdoc.save(MyDir + "out.docx");
        convertText(MyDir + "out.docx");
        System.out.println("Successfully Applyed Bookmark!!!");
    }
    catch (Exception e)
    {
        e.printStackTrace();

    }
}
1 Like

Thanks for your update tahir, Its working fine. But in document para was not applied style as keyword mean it’s not skip the bookmark in document.

I have attached document for your reference.

Input : CAFI.zip (205.0 KB)

@Vadivel_S_S,

Thanks for your inquiry. In this case, you can use the following if condition.

if(para.toString(SaveFormat.TEXT).trim().equals("Keywords"))
    continue;

If you want to skip following text, you can use the same approach to skip them.

Keywords
Colonial film
post-colonialism
resistance
identities
rhodesia

Fine,Thank you.

Dear @tahir.manzoor

We need to insert comment for particular sentence in word document. I have attached input and expected output. Please give solution for this scenario.

Input : input.zip (13.0 KB)

Expected OP: Exp_Output.zip (15.5 KB)

@ssvel,

Thanks for your inquiry. Please refer to the following article.
Working with Comments

Please check the following code example to add comment to a specific Run node. Hope this helps you.

Document doc = new Document(MyDir + "input.docx");
Node[] nodes =doc.getChildNodes(NodeType.PARAGRAPH, true).toArray();
Paragraph paragraph = (Paragraph)nodes[6];

for(Run run : paragraph.getRuns())
{
    if(run.toString(SaveFormat.TEXT).contains("Therefore"))
    {
        // Create CommentRangeStart and CommentRangeEnd.
        Comment comment = new Comment(doc, "Aspose.Words", "AW", new Date());
        int commentId = 0;
        CommentRangeStart start = new CommentRangeStart(doc, commentId);
        CommentRangeEnd end = new CommentRangeEnd(doc, commentId);

        paragraph.insertBefore(comment, run);
        paragraph.insertBefore(start, run);
        paragraph.insertAfter(end, run);
         
    }
}

doc.save(MyDir + "output.docx");

Thank you @tahir.manzoor .

Further to the inquiry, could you assist us to comment on a particular text inside a bookmark based on start and end values taking bookmark start position as 0.

Attached Sample scenario.
Start - 9
End - 22
Sample text:
image.png (5.2 KB)

Regards
Vadivel

@ssvel,

Thanks for your inquiry. Please ZIP and attach your expected output Word document here for our reference. We will then provide you more information about your query along with code.

Dear @tahir.manzoor

Thanks for your quick replying. I have attached sample document, In that document I need to comment for start range 308 to end range 316 in LEBookmark3. Please give solution for this scenario. ASAP

input: input.zip (13.0 KB)
Expected OP: input.zip (15.5 KB)

FYI : I need to comment using that range values in bookmark.

@ssvel,

Thanks for your inquiry. In your case, we suggest you following solution.

  1. Get the bookmark “LEBookmark3” using Document.Range.Bookmarks.
  2. Get the paragraph node of this bookmark using BookmarkStart.ParentNode.
  3. Implement IReplacingCallback and find the desired text using Range.Replace method. Please refer to the following article.
    Find and Repalce
  4. Use the same approach to insert the comment shared in my previous post. Please write the code to add comment in IReplacingCallback.replacing method.

Hope this helps you.

Thank u for your quick replying tahir. Please give example code for this scenario.

@ssvel,

Thanks for your inquiry. Please use the following code example to get the desired output.

Document doc = new Document(MyDir + "input.docx");
Bookmark bm = doc.getRange().getBookmarks().get("LEBookmark3");
Paragraph paragraph = (Paragraph) bm.getBookmarkStart().getParentNode();

FindAndInsertBM insertBM = new FindAndInsertBM();
FindReplaceOptions options = new FindReplaceOptions();
options.setReplacingCallback(insertBM);
paragraph.getRange().replace("Therefore", "", options);
doc.save(MyDir + "output.docx");

----
class FindAndInsertBM implements IReplacingCallback {

    public int replacing(ReplacingArgs e) throws Exception {
        // This is a Run node that contains either the beginning or the complete match.
        Node currentNode = e.getMatchNode();

        // The first (and may be the only) run can contain text before the match,
        // in this case it is necessary to split the run.
        if (e.getMatchOffset() > 0)
            currentNode = splitRun((Run) currentNode, e.getMatchOffset());

        ArrayList runs = new ArrayList();

        // Find all runs that contain parts of the match string.
        int remainingLength = e.getMatch().group().length();
        while ((remainingLength > 0) && (currentNode != null) && (currentNode.getText().length() <= remainingLength)) {
            runs.add(currentNode);
            remainingLength = remainingLength - currentNode.getText().length();

            // Select the next Run node.
            // Have to loop because there could be other nodes such as BookmarkStart etc.
            do {
                currentNode = currentNode.getNextSibling();
            } while ((currentNode != null) && (currentNode.getNodeType() != NodeType.RUN));
        }

        // Split the last run that contains the match if there is any text left.
        if ((currentNode != null) && (remainingLength > 0)) {
            splitRun((Run) currentNode, remainingLength);
            runs.add(currentNode);
        }

        Document document = (Document) e.getMatchNode().getDocument();
        DocumentBuilder builder = new DocumentBuilder(document);
        Run run = (Run)runs.get(0);
        
        if(run.toString(SaveFormat.TEXT).contains("Therefore"))
        { 
            // Create CommentRangeStart and CommentRangeEnd.
            Comment comment = new Comment(document, "Aspose.Words", "AW", new Date());
            int commentId = 0;
            CommentRangeStart start = new CommentRangeStart(document, commentId);
            CommentRangeEnd end = new CommentRangeEnd(document, commentId);

            run.getParentParagraph().insertBefore(comment, run);
            run.getParentParagraph().insertBefore(start, run);
            run.getParentParagraph().insertAfter(end, run);

        }

       return ReplaceAction.SKIP;
    }

    /**
     * Splits text of the specified run into two runs. Inserts the new run just
     * after the specified run.
     */
    private  Run splitRun(Run run, int position) throws Exception {
        Run afterRun = (Run) run.deepClone(true);
        afterRun.setText(run.getText().substring(position));
        run.setText(run.getText().substring((0), (0) + (position)));
        run.getParentNode().insertAfter(afterRun, run);
        return afterRun;
    }
}

Thank you for replying tahir.

I need to insert comment for more sentences,how to insert the comments for given ranges in that word position.

I mentioned ranges in attached comment. Kindly please provide solution for this.

Expected OP : input.zip (16.0 KB)

Code for comment : new.zip (851 Bytes)

Please find text file : output.zip (520 Bytes)