This statement merges word documents in a Java application using two methods:
Method 1: Combined documents start from a new page Method 2: Merge the Word document that receives the preamble
You can use the Dockment class insertTextFroomFile () to merge different documents into the same document. When you combine documents in this way, the contents of the combined documents are displayed from a new page by default.
import com.spire.doc.Document;
import com.spire.doc.FileFormat;
public class MergeWordDocument {
public static void main(String[] args){
//Path to get the first document
String filePath1 = "merge1.docx";
//Get the path of the second document
String filePath2 = "merge2.docx";
//Read the first document
Document document = new Document(filePath1);
//Insert the contents of the second document into the first document
document.insertTextFromFile(filePath2, FileFormat.Docx_2013);
//Save document
document.saveToFile("Output.docx", FileFormat.Docx_2013);
}
}
If the newly added document appears after the end of the last paragraph of the previous document, use the following method to get the last selection of the first document and renew the paragraphs of the remaining combined documents. Add to the selection as a paragraph.
import com.spire.doc.Document;
import com.spire.doc.DocumentObject;
import com.spire.doc.FileFormat;
import com.spire.doc.Section;
public class MergeWordDocument {
public static void main(String[] args){
//Path to get the first document
String filePath1 = "merge1.docx";
//Get the path of the second document
String filePath2 = "merge2.docx";
//Read the first document
Document document1 = new Document(filePath1);
//Read the second document
Document document2 = new Document(filePath2);
//Get the last selection of the first document
Section lastSection = document1.getLastSection();
//Add the paragraph in the second document as a new paragraph to the last action in the first document
for (Section section:(Iterable <Section>)document2.getSections()) {
for (DocumentObject obj:(Iterable <DocumentObject>)section.getBody().getChildObjects()
) {
lastSection.getBody().getChildObjects().add(obj.deepClone());
}
}
//Save document
document1.saveToFile("Output.docx", FileFormat.Docx_2013);
}
}
Recommended Posts