We have the following code snippet that normalizes a search string, finds it within the document and then replaces it. This all happens with track changes enabled at the start of the loop and stopped at the end of the loop. What ends up happening however is, that it replaces the block entirely since the replacement text also contains the full text and thus now it appears that the whole block/paragraph was replaced rather than a portion of it was added to the original block or removed from the original block.
How do we address this issue as we require the document to be markedup with changes rather than replaced with the changes.
public String processSteps(List<Step> steps, Metadata metadata) throws Exception {
String s3Url = metadata.getS3BinaryUrl();
// Download from S3 and load the document into Aspose.Words
Document document = s3Service.downloadAndPrepareDocument(s3Url);
// Get paragraphs as a parameterized collection
NodeCollection<Paragraph> paragraphs = document.getChildNodes(NodeType.PARAGRAPH, true);
// Iterate through each step and replace text in paragraphs
for (Step step : steps) {
if (step.getLocations() != null && step.getOriginalProvision() != null
&& step.getMarkedUpProvision() != null) {
logger.info("Processing step: {}", step.getProvisionName());
String searchText = step.getOriginalProvision();
if (searchText == null || searchText.isEmpty()) {
logger.warn("Skipping step '{}' with empty search text.", step.getProvisionName());
continue; // Skip if search text is empty
}
String replacementText = step.getMarkedUpProvision();
// String regex = buildFlexibleRegex(searchText);
String normalizedSearch = normalizeText(searchText);
for (Paragraph para : paragraphs) {
String paraText = para.getText().trim();
String normalizedParaText = normalizeText(paraText);
// Check if the normalized paragraph text contains the normalized search text
if (normalizedParaText.contains(normalizedSearch)) {
FindReplaceOptions options = new FindReplaceOptions();
options.setMatchCase(false);
options.setUseSubstitutions(true);
logger.info("Text to be replaced: {}", searchText);
logger.info("Para before replacement: {}", para.getText());
// Replace the text in the paragraph
para.getRange().replace(searchText, replacementText, options);
logger.info("Para after replacement: {}", para.getText());
}
}
}
}
Servient developer on behalf of Ian.