Hi<?xml:namespace prefix = o ns = "urn:schemas-microsoft-com:office:office" />
Thanks for your request. Yes, of course you can achieve this. Please try using the following code:
//Open document
Document doc = new Document("in.doc");
//Get collection of Paragraphs
NodeCollection paragraphs = doc.getChildNodes(NodeType.PARAGRAPH, true);
Paragraph par = null;
int docIndex = 0;
//Loop through all paragraphs in the document
for (int parIndex = 0; parIndex < paragraphs.getCount(); parIndex++)
{
par = (Paragraph)paragraphs.get(parIndex);
//If Paragraph style = HEADING_1 then copy content to the new document
if (par.getParagraphFormat().getStyleIdentifier() == StyleIdentifier.HEADING_1)
{
//Create new document
Document outDoc = new Document();
//Remove sections from document
outDoc.removeAllChildren();
Node currentNode = par;
//import section from src document without its children
Section srcSect = (Section)outDoc.importNode(currentNode.getAncestor(NodeType.SECTION), true, ImportFormatMode.KEEP_SOURCE_FORMATTING);
outDoc.appendChild(srcSect);
srcSect.getBody().removeAllChildren();
while (currentNode != null)
{
//Import Node
Node importedNode = outDoc.importNode(currentNode, true, ImportFormatMode.KEEP_SOURCE_FORMATTING);
//insert node into the new document
outDoc.getLastSection().getBody().appendChild(importedNode);
//If next node=null then move to the next section
if (currentNode.getNextSibling() == null)
{
//Get next section
Section currrentSection = (Section)currentNode.getAncestor(NodeType.SECTION).getNextSibling();
//If next section != null then get its first child
if (currrentSection != null)
{
Section newSect = (Section)outDoc.importNode(currrentSection, true, ImportFormatMode.KEEP_SOURCE_FORMATTING);
outDoc.appendChild(newSect);
newSect.getBody().removeAllChildren();
currentNode = currrentSection.getBody().getFirstChild();
}
else
{
break; //else exit from while
}
}
else
{
//Get next node
currentNode = currentNode.getNextSibling();
}
//Check if current node is paragraph
if (currentNode.getNodeType() == NodeType.PARAGRAPH)
{
//Check if its style is HEADING_1
if (((Paragraph)currentNode).getParagraphFormat().getStyleIdentifier() == StyleIdentifier.HEADING_1)
{
//If so then set par index and exit while
parIndex = paragraphs.indexOf(currentNode) - 1;
break;
}
}
}
//Save output document
outDoc.save("Section_" + String.valueOf(docIndex) + ".doc");
//increase docIndex
docIndex++;
}
}
I hope this could help you.
Best regards.