insertDocument

Document enTemp =new Document("x.docx");
DocumentBuilder resultBuilder = new DocumentBuilder(document);
resultBuilder.moveToDocumentStart();
resultBuilder.insertDocument(enTemp, ImportFormatMode.KEEP_SOURCE_FORMATTING);
resultBuilder.insertBreak(BreakType.SECTION_BREAK_NEW_PAGE);

Why do the page margins of pageSetup change after enTemp is inserted into the document?

@Crane If the document is inserted into the last empty section (or in a newly created empty document), all imported sections are formatted as specified in the source document, i.e. page setup from the source document are applied to the target section.
If possible, could you please attach your destination and source documents along with current and expected output documents here for our reference? We will check them and provide you more information.

@alexey.noskov

Document document = new Document("src/main/resources/docx/templates/test.docx");
DocumentBuilder documentBuilder = new DocumentBuilder(document);
documentBuilder.insertBreak(BreakType.SECTION_BREAK_NEW_PAGE);
documentBuilder.moveToDocumentStart();
documentBuilder.insertDocument(new Document("src/main/resources/docx/templates/insert.docx"),
        ImportFormatMode.KEEP_SOURCE_FORMATTING);
documentBuilder.insertBreak(BreakType.SECTION_BREAK_NEW_PAGE);
document.save("0226.docx");

insert.docx (10.1 KB)

test.docx (10.1 KB)

I hope that after insert.docx is inserted into test.docx, the page margins will still remain 3 cm.

@Crane If you would like to keep the original documents’ page setup, I would suggest you to use Document.appendDocument method instead of DocumentBuilder.insertDocument method. In this case entire section are copied into the destination document and page setup are preserted:

Document doc1 = new Document("C:\\Temp\\insert.docx");
Document doc2 = new Document("C:\\Temp\\test.docx");
doc1.appendDocument(doc2, ImportFormatMode.KEEP_SOURCE_FORMATTING);
doc1.save("C:\\Temp\\out.docx");

out.docx (9.5 KB)

谢谢,解决了我的问题,我要将其再移动到最前方,这样做可以吧?

document.getSections().insert(0, document.getLastSection());

@Crane You can simply append documents in another order.

That’s okay, my original text is too big, I’m afraid there will be problems, so it’s fine as it is.

1 Like