Free Support Forum - aspose.com

Create a new DOCX from another one

Hello,

I want to create a document from another one using the source code below.

String path = "C:\\test.docx";
String pathOut = "C:\\testNew.docx";
Document doc = new Document(path);
Document docOut = new Document();
SectionCollection docSections = doc.getSections();
for (Section section : docSections) {
com.aspose.words.Body body= section.getBody();
NodeCollection nodes = body.getChildNodes(NodeType.PARAGRAPH, true);
for(int i = 0; i< nodes.getCount(); i++){
docOut.importNode(nodes.get(i), true, ImportFormatMode.KEEP_SOURCE_FORMATTING);
}
}
docOut.save(pathOut);

The output document is empty. How can I perform this operation ?
I have joined the source file to this topic, named "test.docx".

Thanks for your response,

Regards,

Benoît Hénaud

Hello

Thanks for your inquiry. You can use the Clone method of your Document object to create a deep clone of the document into memory. Please see the following link to learn more:

http://www.aspose.com/documentation/.net-components/aspose.words-for-.net/aspose.words.document.clone_overload_2.html

Best regards,

Thanks for your answer.


My example is too simple, I don’t really want to clone the document.

What can I do if I want to copy only the last paragraph (which contains “Test 2”) in the generated document ?

Regards.

Hello

Thanks for your request. Actually, the last paragraph of your document is empty. Please see the attached screenshot.

But if you would like to move the last paragraph of your document to the new document, you should use the code like the following:

Document doc = new Document("C:\\Temp\\test.docx");

// Create an empty intermediate document.

Document temp = new Document();

// Copy the last paragraph of source document into temp document.

temp.FirstSection.Body.AppendChild(temp.ImportNode(doc.FirstSection.Body.LastParagraph, true, ImportFormatMode.KeepSourceFormatting));

temp.Save("C:\\Temp\\out.docx");

Best regards,

Thanks for your answer. It works well.


I have a new question about the creation of a document from another one : is it possible to create a new paragraph in the new document (which not exists in the first one) using a style defined in the first document ?
In fact, is it possible to import a style into a document from an other document ?

Thanks for your answer,

Regards.

Hello

Thanks for your inquiry. Yes of course it is possible. In this case you should create clone of the original document and then remove all content (using RemoveAllChildren method). After these manipulations you will get new empty document with all styles from the original.

Also please follow the link to learn how to insert elements into the document:

http://www.aspose.com/documentation/.net-components/aspose.words-for-.net/inserting-document-elements.html

Best regards,