Inserting a Bibliography Citation in Word 2007

Summary: Programmatically insert bibliography sources and citations into a document by using the Microsoft Office Word 2007 object model. (6 printed pages)

Office Visual How To

Applies to: 2007 Microsoft Office System, Microsoft Office Word 2007

Joel Krist, Akona Systems

August 2007

Overview

The Microsoft Office Word 2007 object model includes several objects designed for automating the creation of bibliographies. By using these objects, and additional properties and methods in the Word 2007 object model, you can add sources to the source lists, cite sources in a document, and manage sources. This Visual How-to article shows how to use bibliography-related objects in Word to programmatically insert a bibliography source and citation into a Word 2007 document.

See It Inserting Bibliography Citations into Word 2007

Watch the Video

Length: 05:42 | Size: 5.25 MB | Type: WMV file

Code It | Read It | Explore It

Code It

Download the Code Sample

To show how to programmatically insert bibliography citations in Word 2007, this section walks through five key steps:

  1. Creating a Windows Console Application project in Microsoft Visual Studio 2005.

  2. Adding a reference to the Word 12.0 Object Library.

  3. Importing the Word interop assembly namespace.

  4. Declaring the appropriate variables.

  5. Implementing the bibliography citation insertion code.

Create a Windows Console Application in Visual Studio 2005

The first step is to create a Windows console application to show how to insert bibliography citations. However, the following code is not specific to a Windows console application. You could use it in a variety of application types.

To create a Windows Console Application project in Visual Studio 2005

  1. Start Visual Studio.

  2. On the File menu, select NewProject. The New Project dialog box appears.

  3. In the Project Types pane, select Visual C# or Visual Basic, and then select the Windows category.

  4. In the Templates pane, select Console Application.

  5. Specify a name for the project.

  6. Specify a location for the project and click OK.

    Visual Studio generates a Windows Console Application project with a single source file in it called Program.cs or Module1.vb, depending on the language selected previously in Step 3.

Add a Reference to the Word 12.0 Object Library

You must add a reference to the Microsoft Word 12.0 Object Library to the Visual Studio project in order to program against the Word object model.

To add the reference

  1. On the Project menu, select the Add Reference menu item. The Add Reference dialog box is displayed as shown in Figure 1.

  2. Click the COM tab in the Add Reference dialog box, then locate and select the Microsoft Word 12.0 Object Library component.

  3. Click OK to add the reference.

Figure 1. Adding a reference

Add Reference Dialog Box

Import the Word Interop Namespace

Import the Microsoft.Office.Interop.Word namespace to use the objects defined in the namespace without having to specify the fully qualified namespace path. To import the namespace, open the Program.cs or Module1.vb source file and add the following line to the top of the source file. For a Microsoft Visual Basic project, add the code to the very top of the source file, above the Module statement. For a Microsoft Visual C# project, add the code before the namespace statement and right after the default using statement created by Visual Studio.

Imports Microsoft.Office.Interop.Word
using Microsoft.Office.Interop.Word;

Declare Appropriate Variables

For a Visual Basic project, place all of the following variable declarations within Sub Main(). For a Visual C# project, place all of the following variable declarations within the Main() function.

Declare the following variables to hold references to the Word objects used in the bibliography citation insertion code.

Dim wordApplication As ApplicationClass = Nothing
Dim wordDocument As Document = Nothing
ApplicationClass wordApplication = null;
Document wordDocument = null;

Now, add the following code to declare variables for the parameters passed to methods in the bibliography citation insertion code. You can use the paramDocumentPath variable to specify the path and file name of the Word document to be created. Replace the Path placeholder in the paramDocumentPath variable with a path to an appropriate folder.

Dim paramDocumentPath As String = Path\Biblio Citation.docx
object paramDocumentPath = @"Path\Biblio Citation.docx";
object paramMissing = Type.Missing;
object paramWdUnits = WdUnits.wdStory;
object paramWdMovementType = WdMovementType.wdMove;
object paramWdBreakType = WdBreakType.wdPageBreak;
object paramWdFieldTypeCitation = WdFieldType.wdFieldCitation;
object paramWdFieldTypeBiblio = WdFieldType.wdFieldBibliography;
object paramBiblioSourceTag = "Mor01";

The paramMissing variable is used to call methods that accept optional parameters.

NoteNote

Optional parameters are optional only when using Visual Basic. You must specify a value for optional parameters when using Visual C#. If you use Type.Missing as the value for an optional parameter, this alerts the method being called that you did not specify the parameter and that the method should use the parameter's default value.

The remaining variables declared in the Visual C# code example are used to call the methods on Word objects. Many of the methods in the Word object model accept parameters of type object passed by reference. For methods called by the citation insertion code, most of the parameter values are enumerated type values which cannot be passed by reference in Visual C#. By declaring the variables for the parameters as objects and initializing them to a value from the enumerated type, it is possible to pass the value by reference. The paramWdUnits and paramWdMovementType variables are used with the Selection.EndKey method when positioning the insertion point in the document. The paramWdBreakType variable is used when inserting a page break in the document. The paramWdFieldTypeCitation, paramWdFieldTypeBiblio, and paramBiblioSourceTag variables are used when inserting a bibliography source, citation, and bibliography in the document.

Implement the Bibliography Citation Insertion Code

Next, add code that inserts a bibliography citation into a Word document, as shown in the following code:

  1. Starts Word and creates a document.

  2. Inserts a bibliography source into the document.

  3. Inserts some text into the document.

  4. Inserts a citation to the bibliography source added previously.

  5. Inserts a page break after the citation, and then adds a bibliography to the document.

  6. Saves the document and closes Word.

The shutdown related code closes the Word document, quits the Word application, releases references to the underlying Word COM objects, and makes calls to the .NET garbage collector. For more information about releasing COM objects when using managed code, see Chapter 2: Basics of Office Interoperability (Part 2 of 3) from the book, Microsoft .NET Development for Microsoft Office.

Try
    ' Start an instance of Word.
    wordApplication = New ApplicationClass()

    ' Create a new document.
    wordDocument = wordApplication.Documents.Add()

    ' Insert a bibliography source into the document.
    Dim strXml As String = _
        "<b:Source xmlns:b=""http://schemas.microsoft.com/" & _
        "office/word/2004/10/bibliography""><b:Tag>Mor01</b:Tag>" & _
        "<b:SourceType>Book</b:SourceType><b:Author><b:Author>" & _
        "<b:NameList><b:Person><b:Last>Hezi</b:Last>" & _
        "<b:First>Mor</b:First></b:Person></b:NameList></b:Author>" & _
        "</b:Author><b:Title>The New Office</b:Title>" & _
        "<b:Year>2006</b:Year><b:City>Seattle</b:City>" & _
        "<b:Publisher>Adventure Works Press</b:Publisher>" & _
        "</b:Source>"

        wordDocument.Bibliography.Sources.Add(strXml)

    ' Insert some text into the document.
    wordDocument.Content.InsertAfter( _
        "Here is a reference needing a citation.")

    ' Insert a citation after the text just inserted to the bibliography.
    ' source added previously.
    wordApplication.Selection.EndKey(WdUnits.wdStory, WdMovementType.wdMove)
    wordApplication.Selection.Fields.Add(wordApplication.Selection.Range, _
        WdFieldType.wdFieldCitation, "Mor01")

    ' Insert a page break after the citation added previously and then
    ' add a bibliography to the document.
    wordApplication.Selection.EndKey(WdUnits.wdStory, WdMovementType.wdMove)
    wordApplication.Selection.InsertBreak(WdBreakType.wdPageBreak)
    wordApplication.Selection.Fields.Add(wordApplication.Selection.Range, _
        WdFieldType.wdFieldBibliography)

    ' Save the document.
    wordDocument.SaveAs(paramDocumentPath)
Catch ex As Exception
    ' Respond to the error.
Finally
    ' Close and release the Document object.
    If Not wordDocument Is Nothing Then
        wordDocument.Close(False)
        wordDocument = Nothing
    End If

    ' Quit Word and release the ApplicationClass object.
    If Not wordApplication Is Nothing Then
        wordApplication.Quit()
        wordApplication = Nothing
    End If

    GC.Collect()
    GC.WaitForPendingFinalizers()
    GC.Collect()
    GC.WaitForPendingFinalizers()
End Try
try
{
    // Start an instance of Word.
    wordApplication = new ApplicationClass();

    // Create the new document.
    wordDocument = wordApplication.Documents.Add(ref paramMissing,
        ref paramMissing, ref paramMissing, ref paramMissing);

    // Insert a bibliography source into the document.
    string strXml =
        @"<b:Source xmlns:b=""http://schemas.microsoft.com/" +
        @"office/word/2004/10/bibliography""><b:Tag>Mor01</b:Tag>" +
        "<b:SourceType>Book</b:SourceType><b:Author><b:Author>" + 
        "<b:NameList><b:Person><b:Last>Hezi</b:Last>" +
        "<b:First>Mor</b:First></b:Person></b:NameList></b:Author>" +
        "</b:Author><b:Title>The New Office</b:Title>" + 
        "<b:Year>2006</b:Year><b:City>Seattle</b:City>" + 
        "<b:Publisher>Adventure Works Press</b:Publisher>" + 
        "</b:Source>";

    wordDocument.Bibliography.Sources.Add(strXml);

    // Insert some text into the document.
    wordDocument.Content.InsertAfter(
        "Here is a reference needing a citation.");

    // Insert a citation after the text just inserted to the bibliography
    // source added previously.
    wordApplication.Selection.EndKey(ref paramWdUnits,
        ref paramWdMovementType);
    wordApplication.Selection.Fields.Add(wordApplication.Selection.Range,
        ref paramWdFieldTypeCitation, ref paramBiblioSourceTag,
        ref paramMissing);

    // Insert a page break after the citation added previously and then
    // add a bibliography to the document.
    wordApplication.Selection.EndKey(ref paramWdUnits,
        ref paramWdMovementType);
    wordApplication.Selection.InsertBreak(ref paramWdBreakType);
    wordApplication.Selection.Fields.Add(wordApplication.Selection.Range,
        ref paramWdFieldTypeBiblio, ref paramMissing, ref paramMissing);

    // Save the document.
    wordDocument.SaveAs(ref paramDocumentPath, ref paramMissing,
        ref paramMissing, ref paramMissing, ref paramMissing,
        ref paramMissing, ref paramMissing, ref paramMissing,
        ref paramMissing, ref paramMissing, ref paramMissing,
        ref paramMissing, ref paramMissing, ref paramMissing,
        ref paramMissing, ref paramMissing);
}
catch (Exception ex)
{
    // Respond to the error.
}
finally
{
    // Close and release the Document object.
    if (wordDocument != null)
    {
        wordDocument.Close(ref paramMissing, ref paramMissing,
            ref paramMissing);
        wordDocument = null;
    }

    // Quit Word and release the ApplicationClass object.
    if (wordApplication != null)
    {
        wordApplication.Quit(ref paramMissing, ref paramMissing,
            ref paramMissing);
        wordApplication = null;
    }
    
    GC.Collect();
    GC.WaitForPendingFinalizers();
    GC.Collect();
    GC.WaitForPendingFinalizers();
}

Read It

You might want to extend the bibliography functionality in Microsoft Office Word 2007. The Word 2007 object model includes several objects designed to help automate the creation of bibliographies. Using these objects, and additional properties and methods in the Word 2007 object model, you can add sources to the source lists, cite sources in a document, and manage sources. This How-to article explores how to programmatically insert a bibliography citation into a Word 2007 document through these key steps:

  1. Creating a Windows Console Application project in Visual Studio 2005.

  2. Adding a reference to the Word 12.0 Object Library to the project.

    This marks the project as using the Word 12.0 Object Library.

  3. Importing the Microsoft.Office.Interop.Word namespace.

    This allows code to use the classes and types exposed as part of the Microsoft.Office.Interop.Word namespace without having to specify the fully qualified namespace path.

  4. Declaring variables to help with method calls.

  5. Implementing the bibliography citation insertion code.

NoteNote

The example Visual C# code shown earlier uses the Type.Missing object to specify that an optional parameter was not provided and that the default parameter value should be used. To change the behavior to use a value other than the defaults, specify the appropriate parameter types and values. For more information about the methods used in the example code and the parameters they accept, see the Word 2007 Object Model Reference.

Explore It