I am new to POI. when I merge more than one docx with same fontFamily (Airal, Calibri, Times New Roman), there is no issue on combined docx. For example, If I have two docx with the same Calibri fontFamily, there is no issue on combined docx. It keeps and comes out with original formatting. However, merging different docx with different fontFaimly messed up. For example, if I more then one docx, Airal, Calibri, it doesn’t keep the original formatting. especially second docx. First one is okay on combined docx 1 – what am I doing wrong and how can I prevent that from happening?
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTBody;
import org.apache.xmlbeans.XmlOptions;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class ClearCTBodyAndAppend {
public static void main(String[] args) {
try (FileInputStream fis1 = new FileInputStream("path/to/your/first_document.docx");
XWPFDocument document1 = new XWPFDocument(fis1);
FileInputStream fis2 = new FileInputStream("path/to/your/second_document.docx");
XWPFDocument document2 = new XWPFDocument(fis2)) {
// Append the body of the second document to the first
CTBody ctBody1 = document1.getDocument().getBody();
CTBody ctBody2 = document2.getDocument().getBody();
appendBody(ctBody1, ctBody2);
// Save the modified document
try (FileOutputStream fos = new FileOutputStream("path/to/your/combined_document.docx")) {
document1.write(fos);
}
} catch (IOException e) {
e.printStackTrace();
}
}
private static void appendBody(CTBody src, CTBody append) {
try {
XmlOptions optionsOuter = new XmlOptions();
optionsOuter.setSaveOuter();
String appendString = append.xmlText(optionsOuter);
String srcString = src.xmlText();
String prefix = srcString.substring(0, srcString.indexOf(">") + 1);
String mainPart = srcString.substring(srcString.indexOf(">") + 1, srcString.lastIndexOf("<"));
String suffix = srcString.substring(srcString.lastIndexOf("<"));
String addPart = appendString.substring(appendString.indexOf(">") + 1, appendString.lastIndexOf("<"));
CTBody makeBody = CTBody.Factory.parse(prefix + mainPart + addPart + suffix);
src.set(makeBody);
} catch (Exception e) {
e.printStackTrace();
}
}
}
AI_techno is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.