例如
xxxxx[]xxxxx
期望效果
1、转换成 xxxxx___xxxxx
2、xxxxx部分为锁定状态不可编辑 , ____ 部分为可编辑状态
@chazz, 请看这个例子:
String documentName = "原文档.docx";
Document doc = new Document(documentName);
FindReplaceOptions options = new FindReplaceOptions();
options.setReplacingCallback(new FindReplaceHandler());
String stringPattern = "[]";
String replacement = "_____";
doc.getRange().replace(stringPattern, replacement, options);
doc.protect(ProtectionType.READ_ONLY);
doc.save("protected.docx");
static class FindReplaceHandler implements IReplacingCallback {
public int replacing(ReplacingArgs e) throws Exception {
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());
// This array is used to store all nodes of the match for further removing.
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 doc = (Document)e.getMatchNode().getDocument();
DocumentBuilder builder = new DocumentBuilder(doc);
Run startRun = (Run) runs.get(0);
builder.moveTo(startRun);
// Insert editable text.
builder.startEditableRange();
builder.write(e.getReplacement());
builder.endEditableRange();
// Removes nodes containing the search string.
for (Node node : (Iterable<Node>)runs)
{
node.remove();
}
return ReplaceAction.SKIP;
}
private static Run SplitRun(Run run, int position) {
((Document) run.getDocument()).stopTrackRevisions();
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;
}
}
请参考我们的文档:
https://docs.aspose.com/words/java/restrict-document-editing/
1 Like