Copying document portions

C

Chris Ellis

Hi,

I'm writing an add-in for Word 2007 in C#. I saw an add-ins newsgroup,
but I'm a beginner at this, and I think my question more pertains to the
object model for Word, etc... I am trying to copy a section of a document to
a new document, formatting and all. This is the code I currently have:

public static Document[] SplitDocsOnSectionBreaks( Document doc )
{
Application app = Globals.ThisAddIn.Application;
Sections sections = doc.Sections;
object missing = Type.Missing;
Document[] ret = new Document[ sections.Count ];
int x = 0;

// walk through the separate sections of the document copying the entire
contents of
// the section into a new document
foreach( Section curSec in sections )
{
Document newDoc = app.Documents.Add( ref missing, ref missing, ref
missing, ref missing );
object zero = (int)0;

newDoc.Range( ref zero, ref zero ).FormattedText =
curSec.Range.FormattedText;
ret[ x++ ] = newDoc;
}

return ret;
}

On some documents this works perfectly, but on other documents the
formatting is incorrect in the new documents (wrong font and font size). Am
I going about this the wrong way? I could use the clipboard I suppose, but
I would prefer not to if it can be avoided.

Thank you in advance for your help,
Chris
 
C

Chris Ellis

Thank you so much Shauna,

I simply used my source document as the template for the new document in
the Documents.Add method. Then I copied over the entire text in the new
document with the portion of the source, and that seems to have worked like
a charm. If this is not an acceptable way to do this, please let me know.
Otherwise it appears that I am back up and running. Thank you again for
your help.

Chris
 
S

Shauna Kelly

Hi Chris

Yes, that method should work for your purposes.

As a more general principle, I don't like creating a new document based
on an old one (and I don't like creating a template based on an old
document, either). The reason is that documents tend to acquire 'junk'
over time. The best solution is to base every document on a really nice,
clean template. Then your documents don't inherit junk. (A place I once
worked had a template with a problem in it. The template had been used
to produce hundreds of procedures. Every procedure document had the same
problem. Ouch.)

But in your case, this sounds like a good solution.

Hope this helps.

Shauna Kelly. Microsoft MVP.
http://www.shaunakelly.com/word
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top