Free Support Forum - aspose.com

Is there a way to preserve formatting on a document when it is imported?

Is there a way to preserve formating on a document when it is imported?

I downloaded the sample code for InsertDocument, but it states that the section breaks and section formatting of the inserted document are ignored.

The document I need to insert has been formated into two columns, but when I use the code mentioned above the formatting is lost.

Is there a way to do this?

Hi Darel,

Thanks for your inquiry.

Sure this is possible with a little extra coding. Please see the implementation below. The method is called in the same way as the original.

public static void InsertDocumentWithSectionFormatting(Node insertAfterNode, Document srcDoc)<?xml:namespace prefix = o ns = "urn:schemas-microsoft-com:office:office" />

{

// Make sure that the node is either a pargraph or table.

if ((!insertAfterNode.NodeType.Equals(NodeType.Paragraph)) &

(!insertAfterNode.NodeType.Equals(NodeType.Table)))

throw new ArgumentException("The destination node should be either a paragraph or table.");

// Document to insert srcDoc into.

Document dstDoc = (Document)insertAfterNode.Document;

// To retain section formatting, split the current section into two at the marker node and then import the content from srcDoc as whole sections.

// The section of the node which the insert marker node belongs to

Section currentSection = (Section)insertAfterNode.GetAncestor(NodeType.Section);

// Don't clone the content inside the section, we just want the properties of the section retained.

Section cloneSection = (Section)currentSection.Clone(false);

// However make sure the clone section has a body, but no empty first paragraph.

cloneSection.EnsureMinimum();

cloneSection.Body.FirstParagraph.Remove();

// Insert the cloned section into the document after the original section.

insertAfterNode.Document.InsertAfter(cloneSection, currentSection);

// Append all nodes after the marker node to the new section. This will split the content at the section level at

// the marker so the sections from the other document can be inserted directly.

Node currentNode = insertAfterNode.NextSibling;

while (currentNode != null)

{

Node nextNode = currentNode.NextSibling;

cloneSection.Body.AppendChild(currentNode);

currentNode = nextNode;

}

// This object will be translating styles and lists during the import.

NodeImporter importer = new NodeImporter(srcDoc, dstDoc, ImportFormatMode.UseDestinationStyles);

// Loop through all sections in the source document.

foreach (Section srcSection in srcDoc.Sections)

{

Node newNode = importer.ImportNode(srcSection, true);

// Append each section to the destination document. Start by inserting it after the split section.

dstDoc.InsertAfter(newNode, currentSection);

currentSection = (Section)newNode;

}

}

If you need any further assitance, please feel free to ask.

Thanks,