Search code examples
c#onenote

Unable to publish OneNote document as PDF programmatically


I am attempting to convert a Microsoft OneNote document to a PDF file:

        Microsoft.Office.Interop.OneNote.Application oneNote;
        oneNote = new Microsoft.Office.Interop.OneNote.Application();

        string noteBookXML;
        oneNote.GetHierarchy(null, HierarchyScope.hsNotebooks, out noteBookXML);

        XDocument doc = XDocument.Parse(noteBookXML);
        XNamespace ns = doc.Root.Name.Namespace;

        foreach (var noteBookNode in from node in doc.Descendants(ns + "Notebook") select node)
        {
            string id = noteBookNode.Attribute("ID").Value;
            string path = "C:\\convert.pdf";
            if (File.Exists(path))
                File.Delete(path);
            try
            {
                oneNote.Publish(id, path, PublishFormat.pfPDF, "");
            }
            catch(Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }

With the above code I am currently getting to the publish call, stepping over it causes Microsoft OneNote to stop working (generic windows "X has stopped working please wait") followed by this exception:

{System.Runtime.InteropServices.COMException (0x800706BE): The remote procedure call failed. (Exception from HRESULT: 0x800706BE)
    at Microsoft.Office.Interop.OneNote.ApplicationClass.Publish(String bstrHierarchyID, String bstrTargetFilePath, PublishFormat pfPublishFormat, String bstrCLSIDofExporter)
    at Conversion.OneNoteConverter.run() in G:\Code\OneNoteConversion\Conversion\OneNoteConverter.cs:line 34}

Has anyone been able to get this working? Am I doing something obviously wrong?

Thanks in advance.

Resources I've been trying to follow:

http://msdn.microsoft.com/en-us/library/ms788684.aspx

http://social.technet.microsoft.com/Forums/en/office2010/thread/900dd92b-6e5c-40e5-86ec-f18c1a1fc050

http://www.technologyquestions.com/community/threads/api-onenote-2007-publish.117776/


Solution

  • It turns out when using the .publish call you need OneNote open in order for it to work (or you will get an exception).

    Opening OneNote before the call allowed it to perform and convert the document from .one to .pdf