i need to replace some fields in Word Document file in java.I am using Apache Poi library , i am using this code to replace words.
for (XWPFParagraph p : doc.getParagraphs()) {
List<XWPFRun> runs = p.getRuns();
if (runs != null) {
for (XWPFRun r : runs) {
String text = r.getText(0);
if (text != null) {
System.out.println(text);
if (text.contains("[Title]")) {
text = text.replace("[Title]", wordBody.getTitle());//your content
r.setText(text, 0);
}if(text.contains("[Ref_no]")){
text=text.replace("[Ref_no]",wordBody.getRefNumber());
r.setText(text,0);
}
if(text.contains("[In_date]")){
text=text.replace("[In_date]",wordBody.getDate());
r.setText(text,0);
}if(text.contains("[FirstName]")){
text=text.replace("[FirstName]",wordBody.getFirstName());
r.setText(text,0);
}if(text.contains("[MiddleName]")){
text=text.replace("[MiddleName]",wordBody.getMiddleName());
r.setText(text,0);
}if(text.contains("[Vehicle_Type]")){
text=text.replace("[Vehicle_Type]",wordBody.getVehicleType());
r.setText(text,0);
}if(text.contains("[Reg_No]")){
text=text.replace("[Reg_No]",wordBody.getRegNumber());
r.setText(text,0);
}if(text.contains("[Location]")){
text=text.replace("[Location]",wordBody.getLocation());
r.setText(text,0);
}if(text.contains("[Issuer_Name]")){
text=text.replace("[Issuer_Name]",wordBody.getLocation());
r.setText(text,0);
}
}
}
}
}
So i mentioned that not all words a replaced and i didn't know how to fix it , then i printed out all text what i get and i got something like that
This is to certify that [Title] [FirstName] [
MiddleName
] [Surname] has purchased [
Vehicle_Type
]
having registration [
Reg_No
] from our [Location] Showroom.
Issued By,
[
Issuer
So i need replace fields in [] brackets and some of them as [Surname] a printed okay but some of them as [MIddleName] are changing line and i think that s way its not working .
This - is my word text
I parsing docx file . Thank you