Importing Content into OneNote 2003 SP1


Andrew May
Saul Candib
Microsoft Corporation

Updated: July 2005

Applies to:
    Microsoft® Office OneNote™ 2003 SP1

Summary: Learn about the new extensibility features available for developers in Microsoft Office OneNote 2003 SP1. The new OneNote 1.1 Type Library includes functionality that enables you to programmatically import images, ink, and HTML into OneNote. (21 printed pages)


Using the CSimpleImporterClass


Microsoft® Office OneNote™ 2003 Service Pack 1 (SP1) enables your applications to interoperate with OneNote in an important, fundamental way——you can add content programmatically to OneNote notebooks that includes HTML, images, and ink (such as from a Tablet PC). You can even create the folder, section, or page onto which you want to place your content.

Note   These extensibility features are available only in OneNote 2003 SP1. You can download a copy of OneNote 2003 Service Pack 1 from Office Online.

Using the CSimpleImporterClass

OneNote SP1 exposes a single class, CSimpleImporterClass, which enables you to add content to a OneNote notebook programmatically. You can add text in HTML format, images, and even ink from a Tablet PC. The CSimpleImporterClass enables you to specify where in the notebook you want to place the content; you can even create folders, sections, and pages for content, and then programmatically display the desired page. The import functionality of OneNote also lets you later delete the content you import.

The CSimpleImporterClass consists of two methods:

  • Import. Enables you to add, update, or delete images, ink, and HTML content to a specific page in a OneNote folder and section.
  • NavigateToPage. Enables you to display a specified page.

To use the CSimpleImporterClass, you must add a reference to the OneNote 1.1 Type Library to your project. To add a reference in Visual Studio .NET, in the Solution Explorer window, right-click References and then click Add Reference. On the COM tab, select OneNote 1.1 Type Library in the list, click Select, and then click OK.

While this article focuses on using .NET-based languages to implement the import functionality in OneNote, you can also use the OneNote 1.1 Type Library with unmanaged code, such as Microsoft Visual Basic® 6.0 or the Microsoft Visual C++® development system.

The Import Method

The Import method has the following signature:

Import (bstrXml as String)

The method takes an XML string that describes the content object(s) you want to import as well as the location in the notebook where you want them placed. You can also use the Import method to delete objects you have previously placed in the notebook.

When your application calls the Import method, OneNote executes it with minimal intrusion on the user. If OneNote is not already running, it opens, displaying the splash screen. But if OneNote is already running, importing content does not change the user's location in the notebook. To change the focus of OneNote to the page containing the new content, use the NavigateToPage method, discussed later in this article.

If the Import method fails, OneNote does not display an error to the user. However, the COM interface does return one of the following errors to the application making the call:

Error Name Error Type

OneNote parses the XML string that you pass to the Import method linearly. If OneNote encounters an error, it terminates the import and does not process any subsequent content in the string. Any previous, successful imports from the string are not rolled back.

For example, suppose you generate an XML string that contains two EnsurePage elements and two PlaceObjects elements. Furthermore, suppose that the first PlaceObjects element passes a non-existent GUID for its pageGUID attribute. In this case, OneNote retains any folders, sections, and pages already created by the EnsurePage elements. The first PlaceObjects element fails, and once it does, OneNote terminates the import and doesn't read the rest of the string, whether or not the second PlaceObjects element is well-formed and contains a valid GUID.

The Data Import Schema

The following figures outline the XML schema to which the import string must adhere.

Figure 1. XML Schema Structure of the Root <Import> Element

Figure 2. Schema Structure of the <PlaceObjects> Element

The OneNote data import schema can be found at The OneNote 1.1 SimpleImport XML Schema.

Creating folders and pages for content

The OneNote data import schema is included as part of the download, Microsoft Office 2003 XML Reference Schemas.

There are two elements directly below the root Import element. Use the first element, EnsurePage, to make sure the folder, section, and page on which you want to place content exists. Use the second element, PlaceObjects, to place or delete objects from the page. The schema requires that the root element contain either at least one EnsurePage or PlaceObjects element.

Creating Folders and Pages for Content

Before you can import content, the target page(s) for that content must exist in the OneNote notebook. You can either import content to an existing page, or you can create a new page dynamically.

There are two elements directly below the root Import element, EnsurePage and PlaceObjects. The first element, EnsurePage, determines if the folder, section, and page on which you want to place content exists. The second element, PlaceObjects, places objects on a page or deletes them from the page. The schema requires that the root element contain at least one of either element.

You use the EnsurePage element to verify the existence of or to create the target pages for your content. For each page you specify in an EnsurePage element, OneNote checks to determine if the page exists, and if not, creates it. You can even create notebook folders and sections by specifying folders or sections that don't exist.

You are required to pass OneNote a string representing the path to the desired page, as well as a GUID for that page. If the path is not fully qualified, OneNote assumes the string starts from the notebook root location for the user. Additionally, you can specify the title, date, reading direction, and page placement relative to other pages in the notebook.

**Note   **All GUIDs passed to OneNote methods must be in registry format, which includes being surrounded by curly braces ({}).

By default, OneNote inserts each new page at the end of the specified section. If you specify a page GUID for the insertAfter attribute, OneNote inserts the new page as a sub-page of the page for which you specified a GUID. In such cases, the sub-page shares the title and date with the other pages in the page series. If the page you specify does not exist (for example, if it was never added, or if the user deleted it), OneNote inserts the new page at the end of the specified section along with any specified title and date values.

Consider the following example. This EnsurePage element specifies a page in the OneNote section "Negotiations", in the folder "Johnson Contract", in the user's root notebook folder. The page is titled "Budget Concerns".

<EnsurePage path="Johnson Contract\"
            title="Budget Concerns"/>

**Note   **Be sure to include the .one file extension for the path attribute, as shown above. If you fail to include that extension, OneNote does not recognize the imported content after you close and then reopen the application. The sample application included with this article checks for the file extension and supplies it if it is missing.

OneNote uses the optional attributes of the EnsurePage element when it creates a new page. If you specify attributes for an existing page, OneNote leaves the page attributes unchanged. For example, if you use a GUID for an existing page and you specify a title that differs from that page's current title, OneNote does not change the page title.

Additionally, OneNote searches only the path you specify for the desired page GUID. If the page GUID you specify does not exist in the specified section, OneNote creates it; it does not look for the GUID in other sections of the notebook.

You can use multiple EnsurePage elements to create multiple pages within the OneNote notebook. You are not required to include an EnsurePage element for each page on which you want to place content. However, if you use the PlaceObjects element to place objects on a page that does not exist, the Import method fails. In some cases, this may be the outcome you want: for example, you might use this method if you want to update content on a page only if the page still exists, but not if the page has been deleted by the user.

Placing Content on Pages

Once you ensure that the pages onto which you want to import data exist in the OneNote notebook, you can start placing objects on them by using the PlaceObjects element. You can import multiple objects to multiple pages by creating a PlaceObjects element for each page on which you want to place content. Like the EnsurePage element, PlaceObjects has two required attributes: the path to the page, and the GUID assigned to the page. You must include at least one Object element in each PlaceObjects element.

To create the XML string that describes the content you want to import into OneNote, follow these general steps:

  1. If you want to make sure the page exists to place content onto, create an EnsurePage to verify or create the folder, section, and page as necessary.
  2. Create a PlaceObjects element for the page to which you want to add or delete content.
  3. Create an Object element for the first object you want to alter (add, update, or delete) on the page.
  4. To delete an object, add the Delete element to that object.
  5. To import an object, add a Position element and use its x and y attributes to specify where on the page to place the object.
  6. Specify the type of object to import to the page by using the appropriate element, Image, Ink, or Outline, and setting the appropriate optional attributes, if desired.
  7. If you're importing an outline object, specify the sub-objects the outline contains in the order in which you want them to appear in the outline. You can specify any number and order of Image, Ink, and Html elements. However, you are required to specify at least one Image, Ink, or Html element for the outline.
  8. Repeat this procedure for all objects you want to alter on the page. Then repeat this procedure for all pages on which you want to alter content.

Some other technical requirements to remember as you create the XML string:

  • OneNote positions objects based on absolute x and y coordinates, where x and y represent measurements in points. Seventy-two points equal one inch.
  • You must describe Ink objects in Ink Serialized Format (ISF), base-64 encoded, or else by specifying a path to the source file. If you specify a file path, the source file should be a plain file with the byte stream containing the ISF. If you include the ink as data in the XML, it should be base-64 encoded. For more information on programmatically capturing and manipulating ink, see this Ink Serialization Sample.
  • You can describe image objects by specifying a path to a source file, or by using base-64 encoded data.
  • You must describe text objects in HTML, either within a CDATA block or by specifying a path to a source file. In a CDATA block, all characters are treated as a literal part of the element's character data, rather than as XML markup. XML and HTML use some of the same characters to designate special processing instructions. Using the CDATA block prevents OneNote from misinterpreting HTML content as XML instructions. Inserted HTML should be valid and complete.
  • Although the schema does not currently support importing audio or video files, you can include links to these files within the HTML content you import.

Updating Content

To update objects that are already in a notebook, simply re-import the objects to the same page, using the same GUIDs. Be aware, however, that re-importing an object overwrites that object without notifying the user. Any changes made to the content since it was last imported are lost.

Deleting Content

To delete an object, place the Delete element within the Object element. To delete an object, you must be able to identify it by its GUID and path. In practical terms, this generally means an application can only delete objects it places in OneNote to begin with. However, if the application stores the GUID across sessions, it can delete objects it imported into OneNote in previous sessions. You cannot delete folders, sections, or pages, even those you created.

Sample XML String

Below is an example of a typical XML string that you might pass to the Import method. Note that the string contains all the elements necessary to create a complete, well-formed XML document. This XML string places three new objects onto an existing page and deletes an object already contained on that page.

<?xml version="1.0"?>
<Import xmlns="">

   <EnsurePage path="MSN Instant Messenger\"

   <PlaceObjects pagePath="MSN Instant Messenger\" 

      <Object guid="{5FCFD7F9-02C2-42fc-B6AF-7A8450D43C2D}">
         <Position x="72" y="72"/>
         <Image backgroundImage="true">
            <File path="c:\image.png"/>

      <Object guid="{F6FC4149-1092-48ea-806D-0067C8661A18}">
         <Position x="72" y="72"/>
            <File path="c:\ink.isf"/>

      <Object guid="{7EA551C4-F778-40ce-9181-21A3DB6D33CA}">
         <Position x="72" y="432"/>
         <Outline width="360">
                     <html><body><p>Sample text here.</p></body></html>

      <Object guid="{1A6648BA-D792-48f1-AC6A-43DF6E258851}">



Sample Implementation

The following Visual Basic .NET example demonstrates a basic implementation of the OneNote import functionality. The code displays a dialog box that enables the user to specify an XML file, and then passes the contents of that XML file to the Import method.

This example assumes that the specified XML file conforms to the OneNote data import schema. This example also assumes that the project contains a reference to the OneNote 1.1 Type Library.

Dim strFileName As String
Dim XmlFileStream As StreamReader
Dim strImportXml As String
Dim objOneNote As OneNote.CSimpleImporterClass

OpenFileDialog1.Filter = "XML files (*.XML)|*.XML|Text files (*.TXT)|*.TXT"
strFileName = OpenFileDialog1.FileName()

objOneNote = New OneNote.CSimpleImporterClass
XmlFileStream = New StreamReader(strFileName)
strImportXml = XmlFileStream.ReadToEnd


Sample Implementation That Generates an XML String Programmatically

For the sake of simplicity and to highlight how the Import method is implemented, the previous example assumes that an XML file already exists to provide the string to pass the Import method. In most cases, however, the application that calls the Import method first creates the XML string itself, as shown in the following example. For more information about using the .NET Framework to create XML, see Well-Formed XML Creation with the XMLTextWriter.

In addition, most applications need to create and assign GUIDs to the pages and objects they create. Use the NewGuid method to create a new GUID, and the ToString method to get the string representation of the value of the GUID, which the XML string requires. For more information, see GUID Structure in the .NET Framework Class Library.

The following sample application, written in both Visual Basic .NET and C#, shows how you can programmatically generate XML strings and object GUIDs for use with the OneNote import functionality. In this example, the user specifies a section name and, optionally, a file location and a title, for a new page that the application then creates by using the CSimpleImporterClass.Import method. Figure 3 shows the Windows Form user interface that you must create as part of the sample application.

Figure 3. Sample Application User Interface

When the user clicks the CreatePage button, the btnCreate_Click event handler runs the sample code. Once the sample has stored the user input in two variables, it calls the NewGuid method to generate a new GUID for the page to create. Note that because the NewGuid method is a shared method, you do not have to instantiate a Guid object in order to call it. OneNote only accepts GUIDs in registry format, which includes curly braces ({}). However, the NewGuid method does not generate GUIDs in registry format. In order for OneNote to correctly process it, you must first wrap the generated GUID in curly braces.

The sample then constructs the simple XML document required for the Import method. The code employs an XMLTextWriter object and its various methods to generate an XML stream. The code creates Import and EnsurePage elements and their required attributes. Then the code creates a PlaceObjects element, along with its required attributes. Within the PlaceObjects element, the code creates an Object element that in turn contains a Position element and nested Outline, Html, and Data elements to import a simple text string and place it at an arbitrary position on the page the user specifies.

If the user specifies a path to an existing section or the path to a new section, OneNote creates the section in the location specified. Otherwise, if the user specifies no path, OneNote creates a new section in the default location set in the Options dialog box. If the user fails to enter a value for the section name, or if the value entered is invalid (for example, if it contains illegal characters, such as “>”), the sample program throws an exception, and the exception handler displays a message box notifying the user that the name or path entered is unacceptable. At the point, the user has the option of re-entering the path or closing the sample application.

If the user specifies a section name but fails to append the .one file extension, the application adds it.

If the user specifies a page title, the code creates the optional title attribute of the EnsurePage element as well. Once it has created the XML stream, it flushes the XMLTextWriter and moves the position back to the beginning of the stream.

At this point, the code uses a StreamReader object to write the contents of the XML stream to the console, to show what the XML generated looks like. Because the Import method takes a string and not a stream, the code uses the StreamReader.ReadToEnd method to get a string representing the contents of the XML stream. The code then passes this string as the required argument to the Import method, thereby creating the desired page. Finally, the code calls the NavigateToPage method, and passes it the page path and page GUID variables set earlier based on user input, in order to navigate to the new page in OneNote.

[Visual Basic .NET]

Imports System.Xml
Imports System.IO
Imports System.Runtime.InteropServices
. . .
    Private Sub btnCreate_Click(ByVal sender As System.Object, _
        ByVal e As System.EventArgs) Handles btnCreate.Click
        Dim sectionPath As String
        Dim pageTitle As String
        Dim pageGuid As String
        Dim XmlImportStream As MemoryStream = New MemoryStream
        Dim XmlImportWriter As XmlTextWriter = _
            New XmlTextWriter(XmlImportStream, Nothing)
        Dim strEnsurePage As String
        Dim OneNoteImporter As OneNote.CSimpleImporterClass

        'Store user input for path and optional page title
        sectionPath = Me.txtSectionPath.Text.ToString
        pageTitle = Me.txtPageTitle.Text.ToString

        While (sectionPath = "")

        'Check for missing section name
            MessageBox.Show("Please include path", "No Path", _

        End While

        'Check for .one file extension, and add if missing
        If Not (sectionPath.EndsWith(".one")) Then

            sectionPath = sectionPath + ".one"

        End If

        'Generate a new GUID for the page to be created
        pageGuid = "{" & Guid.NewGuid.ToString & "}"

        'Generate the XML as a stream
        With XmlImportWriter

            'Write opening (root) Import element tag
            'and specify OneNote schema namespace
            .WriteAttributeString("xmlns", _
            'Write opening EnsurePage element tag

            'Write required path attribute
            .WriteAttributeString("path", sectionPath)

            'Write required guid attribute
            .WriteAttributeString("guid", pageGuid)

            'Write optional title attribute, if title was specified
            If Not pageTitle = "" Then
                .WriteAttributeString("title", pageTitle)
            End If

            'Write closing EnsurePages element tag

            'Write opening PlaceObjects element and attributes
            .WriteAttributeString("pagePath", sectionPath)
            .WriteAttributeString("pageGuid", pageGuid)

            'Write opening Object element tag and attributes
            .WriteAttributeString("guid", objectGuid)

            'Write opening Position element tag and attributes
            .WriteAttributeString("x", "72")
            .WriteAttributeString("y", "72")

            'Write closing Position element tag

            'Write opening Outline element tag and attributes
            .WriteAttributeString("width", "360")

            'Write opening Html element tag

            'Write opening Data element tag

            'Write CData
            .WriteCData("<html><body><p>my sample text</p></body></html>")

            'Write closing Data element tag

            'Write closing Html element tag

            'Write closing Outline element tag

            'Write closing Object element tag

            'Write closing PlaceObjects element tag

            'Write closing Import element tag

            'Write closing Document element tag
        End With

        'Flush the XmlTextWriter

        'Move to the start of the XML stream
        XmlImportStream.Position = 0

        'Create a StreamReader for the XML stream
        Dim XmlImportReader As StreamReader = New _

        'Write the XML stream to the console

        'Move back to the start of the XML stream
        XmlImportStream.Position = 0

        'Store entire XML stream in variable as a string
        strEnsurePage = XmlImportReader.ReadToEnd

        'Create instance of OneNote Simple Importer
        OneNoteImporter = New OneNote.CSimpleImporterClass

        'Pass XML string to Import method to create page

        Catch ex As COMException
            If (ex.ErrorCode = &H80041002) Then
                MessageBox.Show("Invalid character in section name", _
                  "Invalid Character", MessageBoxButtons.OK)
            ElseIf (ex.ErrorCode = &H80041001) Then
                MessageBox.Show("Please enter a section name.", _
                  "No Section Name", MessageBoxButtons.OK)
                MessageBox.Show("Please enter a valid section name.", _
                  "Invalid Name", MessageBoxButtons.OK)
            End If

        End Try
        'Navigate to new page, based on path and GUID variables
        OneNoteImporter.NavigateToPage(sectionPath, pageGuid)

    End Sub

[Visual C# .NET]

using System;
using System.IO;
using System.Runtime.InteropServices;
using System.Windows.Forms;
using System.Xml;

private void btnCreate_Click(object sender, System.EventArgs e)
   string sectionPath;
   string pageTitle;
   string pageGuid;
   string objectGuid;
   string strEnsurePage;

   MemoryStream XmlImportStream = new MemoryStream();
   XmlTextWriter XmlImportWriter = new XmlTextWriter(XmlImportStream,

   // Declare instance of CSimpleImporterClass
   OneNote.CSimpleImporterClass OneNoteImporter;

   // Store user input for section name (required) and path (optional)
   sectionPath = this.txtSectionPath.Text.ToString();

   // Check for missing section name
   if (sectionPath == "")
      MessageBox.Show("Please enter the section name.", "No section name", MessageBoxButtons.OK);

   // Check for .one file extension, and add if missing
   if (!sectionPath.EndsWith(".one"))
      sectionPath = sectionPath + ".one";

   pageTitle = this.txtPageTitle.Text.ToString();

   // Generate a new GUID for the page to be created
   pageGuid = "{" + Guid.NewGuid().ToString() + "}";

   // Generate a new GUID for the object to be created
   objectGuid = "{" + Guid.NewGuid().ToString() + "}";
   // Generate the XML as a stream

   // Write opening (root) Import element tag
   // and specify OneNote schema namespace

   // Write opening EnsurePage element tag

   // Write required path attribute
   XmlImportWriter.WriteAttributeString("path", sectionPath);

   // Write required guid attribute
   XmlImportWriter.WriteAttributeString("guid", pageGuid);

   // Write optional pageTitle attribute, 
   // if page title was specified by user
   if(pageTitle != "" )
      XmlImportWriter.WriteAttributeString("title", pageTitle);
   // Write closing EnsurePage element tag

   // Write opening PlaceObjects element tag and attributes
   XmlImportWriter.WriteAttributeString("pagePath", sectionPath);
   XmlImportWriter.WriteAttributeString("pageGuid", pageGuid);

   // Write opening Object element tag and attributes
   XmlImportWriter.WriteAttributeString("guid", objectGuid);

   // Write opening Position element tag and attributes
   XmlImportWriter.WriteAttributeString("x", "72");
   XmlImportWriter.WriteAttributeString("y", "72");

   // Write closing Position element tag

   // Write opening Outline element tag and attributes
   XmlImportWriter.WriteAttributeString("width", "360");

   // Write opening Html element tag

   // Write opening Data element tag

   // Write CData
            <p>my sample text</p></body></html>");

   // Write closing Data element tag
   // Write closing Html element tag

   // Write closing Outline element tag

   // Write closing Object element tag

   // Write closing PlaceObjects element tag

   // Write closing Import element tag

   // Write closing Document tag

   // Flush the XMLTextWriter

   // Move to the start of the XML stream
   XmlImportStream.Position = 0;

   // Create a streamreader for the XML stream
   StreamReader XmlImportReader = new StreamReader(XmlImportStream);

   // Write the XML stream to the console

   // Move back to the start of the XML stream
   XmlImportStream.Position = 0;

   // Store entire XML stream in variable as a string
   strEnsurePage = XmlImportReader.ReadToEnd();

   // Create instance of OneNote Simple Importer
   OneNoteImporter = new OneNote.CSimpleImporterClass();

   // Pass XML string to Import method to create page

   catch (COMException ex)
      switch ((uint) ex.ErrorCode)
         case 0x80041001:

               // Handle missing section name
               MessageBox.Show("Please enter a section name.", 
                  "No Section Name", MessageBoxButtons.OK);

         case 0x80041002:

               // Handle invalid character in section name
               MessageBox.Show("Invalid character in section name.",
                  "Invalid Character", MessageBoxButtons.OK);


               // Handle other errors
               MessageBox.Show("Please enter a valid section name.",
                  "Invalid Section Name", MessageBoxButtons.OK);


   // Navigate to new page, based on path and GUID variables
   OneNoteImporter.NavigateToPage(sectionPath, pageGuid);

Displaying a Specific Page

By design, when the Import method is executed, users are not distracted by OneNote displaying data they may not want to see, or worse, directed away from the OneNote page currently in use. Also, in the cases where you import multiple objects to multiple pages, OneNote does not have to make assumptions about which page the user wants to see, if any.

To display a specific page, use the NavigateToPage method. If OneNote is not open, this method opens OneNote to the specified page. If OneNote is already open, the method navigates to the specified page in the current instance of OneNote.

To select the page to display, you must specify the path to the page, as well as the GUID for that page. If you specify a page that does not exist, OneNote returns an error.

The NavigateToPage method has the following signature:

NavigateToPage(bstrPath as String, bstrGuid as string)


The new import functionality in OneNote opens up exciting possibilities for interacting with other applications. Any application you create that can save data (either its own or another application's) as HTML text, images, or ISF can now push that content into OneNote and place it wherever you want. And as long as the application retains the GUIDs used, it can update or delete the content it pushed whenever necessary.