Hi Team,
I want to merge two documents ,
Scenario - Search a text in document1 and from that location insert document2.
How to do it use it Apose Word.
Thanks
Hi Team,
I want to merge two documents ,
Scenario - Search a text in document1 and from that location insert document2.
How to do it use it Apose Word.
Thanks
EmptyTempX.docx (31.6 KB)
ris2.docx (119.2 KB)
In ris2.docx , above section heading “BENCHMARQ (BMQ) (Short)” I want to merge EmptyTempX.docx
@nisha1990 you can use the following code to achieve what you want:
Document doc = new Document("C:\\Temp\\input.docx");
Document clonDoc = (Document)doc.Clone(true);
Document insertDoc = new Document("C:\\Temp\\insert.docx");
var findElem = new FindElementsCallback();
FindReplaceOptions opt = new FindReplaceOptions()
{
ReplacingCallback = findElem
};
clonDoc.FirstSection.Body.Range.Replace("BENCHMARQ (BMQ) (Short)", string.Empty, opt);
findElem.MatchNodes.Prepend(insertDoc);
clonDoc.Save("C:\\Temp\\output.docx");
public class FindElementsCallback : IReplacingCallback
{
private readonly List<Node> _matchNodes;
public List<Node> MatchNodes { get => _matchNodes; }
public FindElementsCallback()
{
_matchNodes = new List<Node>();
}
public ReplaceAction Replacing(ReplacingArgs args)
{
_matchNodes.Add(args.MatchNode);
return ReplaceAction.Skip;
}
}
Thank you for your support ,
I need the code in java.
I was converting the code snippet you provided in C# to java , but was facing difficulty in this part
clonDoc.FirstSection.Body.Range.Replace("BENCHMARQ (BMQ) (Short)", string.Empty, opt);
findElem.MatchNodes.Prepend(insertDoc);
It would be a great help If I can get java Code
Thanks
@nisha1990 this is an improved version of the previous code, it use DocumentBiulder to append the document which make safer this operation, as you requested the code is in Java (the code of he Java class is the same, but if you found any issue converting it don’t hesitate to ask for help):
Document doc = new Document("C:\\Temp\\input.docx");
Document clonDoc = (Document)doc.deepClone(true);
DocumentBuilder builder = new DocumentBuilder(clonDoc);
Document insertDoc = new Document("C:\\Temp\\insert.docx");
FindElementsCallback findElem = new FindElementsCallback();
FindReplaceOptions opt = new FindReplaceOptions();
opt.setReplacingCallback(findElem);
clonDoc.getRange().replace("BENCHMARQ (BMQ) (Short)", "", opt);
builder.moveTo(findElem.getMatchNodes().get(0));
builder.insertDocument(insertDoc, ImportFormatMode.KEEP_SOURCE_FORMATTING);
clonDoc.save("C:\\Temp\\output.docx");