请问怎么给一个文档中的段落中的一个Run中的某个指定的字符串设置Font中的格式

请问怎么给一个文档中的段落中的一个Run中的某个指定的字符串设置Font中的格式?
例如:“这是一个Run”,给其中的“Run”设置字体为 Times new Roman,设置为粗体、设置字号为 11

@ouchli 如果需要更改文档中特定文本的字体,您可以使用查找/替换功能轻松实现:

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

FindReplaceOptions opt = new FindReplaceOptions();
opt.getApplyFont().setName("Times New Roman");
opt.getApplyFont().setSize(11);
opt.setUseSubstitutions(true);

doc.getRange().replace("Find Me", "$0", opt);

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

这种查找/替换的方式,是对文档中所有搜索到的文本生效,如果只想对其中的某个文本生效,怎么做到呢?

@ouchli 您只能在特定节点上执行查找/替换操作。 例如,以下代码仅在第一段中执行相同的操作。

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

FindReplaceOptions opt = new FindReplaceOptions();
opt.getApplyFont().setName("Times New Roman");
opt.getApplyFont().setSize(11);
opt.setUseSubstitutions(true);

doc.getFirstSection().getBody().getFirstParagraph().getRange().replace("Find Me", "$0", opt);

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

那如果第一段中就会找到重复的文本,是不是就无法定位了

@ouchli 你是什​​么意思? 上面的代码处理整个段落,即该段落中所有出现的搜索文本都将被处理。

那如果我只想处理搜索到的其中某个指定位置的文本呢

@ouchli 您能否详细说明您的要求并提供您的输入和预期输出文件? 不幸的是,你的要求还不够明确。

好的。
假设有一个段落:
Aspose.Words main advantages are Great performance main.
这个段落中,main 这个本文有两个,只需要给后面的这个 main 设置格式,怎么可以做到。

@ouchli 在您的情况下,您可以实现 IReplacingCallback 来跳过处理第二次出现的情况。 例如看下面的代码:

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

FindReplaceOptions opt = new FindReplaceOptions();
opt.getApplyFont().setName("Times New Roman");
opt.getApplyFont().setSize(11);
opt.setUseSubstitutions(true);
opt.setReplacingCallback(new ProcessFirstOccurrenceOnlyCallback());

doc.getRange().replace("Find Me", "$0", opt);

doc.save("C:\\Temp\\out.docx");
private static class ProcessFirstOccurrenceOnlyCallback implements IReplacingCallback
{
    int mOccurrences = 0;
    
    @Override
    public int replacing(ReplacingArgs replacingArgs) throws Exception {
        if(mOccurrences > 0)
            return ReplaceAction.STOP;
            
        mOccurrences++;
        return ReplaceAction.REPLACE;
    }
}