Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add content control in a Word 2007 document using OpenXML

I want to create a word 2007 document without using object model. So I would prefer to create it using open xml format. So far I have been able to create the document. Now I want to add a content control in it and map it to xml. Can anybody guide me regarding the same???

like image 201
Anoop Avatar asked Dec 04 '09 08:12

Anoop


People also ask

How do you insert a content control field in Word?

Click File > Options > Customize Ribbon. In the list of tabs under Customize the Ribbon, select the Developer box and then click OK. Do one of the following: To add a control, click in the document where you want to add it, and then click the control you want to add on the Design tab.

How do I use the XML mapping pane in Word?

In Word, you open the custom XML part in the XML Mapping pane, and then use the pane to map elements to content controls in the Word document. The XML Mapping pane is accessible from the Developer tab (for more information, see Show the Developer Tab on the Ribbon).

How do you insert rich text content control in Word?

If the Controls task pane is not visible, click More Controls on the Insert menu, or press ALT+I, C. Under Insert controls, click Rich Text Box. In the Rich Text Box Binding dialog box, select the field in which you want to store rich text box data, and then click OK.


1 Answers

Anoop,

You said that you are able to creat the document using OpenXmlSdk. With that assumption, you can use the following code to create the content control to add to the Wordprocessing.Body element of your Document.

//praragraph to be added to the rich text content control
Run run = new Run(new Text("Insert any text Here") { Space = StaticTextConstants.Preserve });
Paragraph paragraph = new Paragraph(run);

SdtProperties sdtPr = new SdtProperties(
        new Alias { Val = "MyContentCotrol" },
        new Tag { Val = "_myContentControl" });
SdtContentBlock sdtCBlock = new SdtContentBlock(paragraph);
SdtBlock sdtBlock = new SdtBlock(sdtPr, sdtCBlock);

//add this content control to the body of the word document
WordprocessingDocument wDoc = WordprocessingDocument.Open(path, true); //path is where your word 2007 file is
Body mBody = wDoc.MainDocumentPart.Document.Body;
mBody.AppendChild(sdtBlock);

wDoc.MainDocumentPart.Document.Save();
wDoc.Dispose();

I hope this answers a part of your question. I did not understand what you ment by "Map it to XML". Did you mean to say you want to create CustomXmlBlock and add the ContentControl to it?

like image 196
Bijay Kusle Avatar answered Dec 10 '22 12:12

Bijay Kusle