Example #1
0
        /// <summary>
        /// 插入 HighLight Code 至滑鼠游標的位置
        /// Insert HighLight Code To Mouse Position
        /// </summary>
        private void InsertHighLightCodeToCurrentSide(string fileName)
        {
            string htmlContent = File.ReadAllText(fileName, Encoding.UTF8);

            string notebookXml;

            onApp.GetHierarchy(null, HierarchyScope.hsPages, out notebookXml);

            var doc = XDocument.Parse(notebookXml);

            ns = doc.Root.Name.Namespace;

            var pageNode = doc.Descendants(ns + "Page")
                           .Where(n => n.Attribute("isCurrentlyViewed") != null && n.Attribute("isCurrentlyViewed").Value == "true")
                           .FirstOrDefault();

            if (pageNode != null)
            {
                var existingPageId = pageNode.Attribute("ID").Value;

                string[] position = GetMousePointPosition(existingPageId);

                var page = InsertHighLightCode(htmlContent, position);
                page.Root.SetAttributeValue("ID", existingPageId);

                onApp.UpdatePageContent(page.ToString(), DateTime.MinValue);
            }
        }
        public static void CreateTaskItem()
        {
            string notebookXml;
            var    onenoteApp = new Microsoft.Office.Interop.OneNote.Application();

            onenoteApp.GetHierarchy(null, HierarchyScope.hsPages, out notebookXml);

            var doc = System.Xml.Linq.XDocument.Parse(notebookXml);
            var ns  = doc.Root.Name.Namespace;

            XElement oe = new XElement(ns + "OE");

            oe.SetAttributeValue("objectID", "{1070E934-A60F-0F9F-3352-98A3F112008F}{46}{B0}");
            oe.Add(new XElement(ns + "T",
                                new XCData("123")));

            var page = new XDocument(new XElement(ns + "Page",
                                                  new XElement(ns + "Outline",
                                                               new XElement(ns + "OEChildren",
                                                                            oe))));

            //var page = new XDocument(new XElement(ns + "Page",
            //                            new XElement(ns + "OEChildren",
            //                              oe)));

            page.Root.SetAttributeValue("ID", "{60FE03D2-2EB9-4049-971D-00AE34EAAD3B}{1}{E178567790977931809320135678447047691353931}");
            page.Root.Element(ns + "Outline").SetAttributeValue("objectID", "{1070E934-A60F-0F9F-3352-98A3F112008F}{15}{B0}");
            onenoteApp.UpdatePageContent(page.ToString(), DateTime.MinValue);
        }
Example #3
0
        /// <summary>
        /// 插入代码到当前光标位置
        /// </summary>
        /// <param name="fileName">代码渲染后的文件位置</param>
        private void insertCodeToCurrentSide(string fileName)
        {
            string noteBookXml;

            onApp.GetHierarchy(null, HierarchyScope.hsPages, out noteBookXml);

            var doc = XDocument.Parse(noteBookXml);

            _ns = doc.Root.Name.Namespace;//获取OneNote XML文件的命名空间

            var pageNode = doc.Descendants(_ns + "Page")
                           .Where(n => n.Attribute("isCurrentlyViewed") != null && n.Attribute("isCurrentlyViewed").Value == "true")
                           .FirstOrDefault();

            string SelectedPageID = pageNode.Attribute("ID").Value;

            string SelectedPageContent;

            //获取当前页面的XML内容
            onApp.GetPageContent(SelectedPageID, out SelectedPageContent, PageInfo.piSelection);
            var SelectedPageXml = XDocument.Parse(SelectedPageContent);

            pageNode = SelectedPageXml.Descendants(_ns + "Page").FirstOrDefault();
            XElement pointNow = pageNode
                                .Descendants(_ns + "T").Where(n => n.Attribute("selected") != null && n.Attribute("selected").Value == "all")
                                .First();

            if (pointNow != null)
            {
                var isTitle = pointNow.Ancestors(_ns + "Title").FirstOrDefault();

                if (isTitle != null)
                {
                    MessageBox.Show("代码不能插入标题中");
                    return;
                }
            }
            else
            {
                return;
            }

            try
            {
                //将html内容转化为XML内容
                //更新当前页面的XML内容
                XmlBuild builder = new XmlBuild(fileName, _ns);
                builder.XmlReBuilding(ref pageNode, ref pointNow);

                onApp.UpdatePageContent(pageNode.ToString(), DateTime.MinValue);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }
Example #4
0
        //将高亮代码插入到光标所在位置
        private void insertHighLightCodeAtCursor(string htmlContent, string pageId)
        {
            string pageXml;

            onApp.GetPageContent(pageId, out pageXml, PageInfo.piSelection);
            var doc      = XDocument.Parse(pageXml);
            var selected = doc.Descendants(ns + "Outline").Descendants(ns + "T")
                           .Where(n => n.Attribute("selected") != null && n.Attribute("selected").Value == "all")
                           .FirstOrDefault();

            selected.ReplaceNodes(new XCData(htmlContent));
            onApp.UpdatePageContent(doc.ToString(), DateTime.MinValue);
        }
Example #5
0
        internal void InsertImageIntoPage(OneNotePage page, string imageFilePath, string publishUrl, bool addTitle = false)
        {
            string xmlToInsert = _oneNoteXml.GetInsertSnipXml(page, GetBase64ImageString(imageFilePath), publishUrl, addTitle);

            _oneNoteApp.UpdatePageContent(xmlToInsert, System.DateTime.MinValue, _oneNoteXmlSchema);

            // navigate to inserted Snip
            string pageContentXmlAfterInsert;

            _oneNoteApp.GetPageContent(page.Id, out pageContentXmlAfterInsert, OneNote.PageInfo.piBasic, _oneNoteXmlSchema);

            string insertedSnipObjectId = _oneNoteXml.GetInsertedSnipObjectId(pageContentXmlAfterInsert);

            _oneNoteApp.NavigateTo(page.Id, insertedSnipObjectId);
        }
Example #6
0
        private string UpdatePageContent()
        {
            string notebookXml;

            _oneNoteApp.GetHierarchy(null, OneNote.HierarchyScope.hsPages, out notebookXml);

            var doc            = XDocument.Parse(notebookXml);
            var ns             = doc.Root.Name.Namespace;
            var pageNode       = doc.Descendants(ns + "Page").FirstOrDefault(n => n.Attribute("name").Value == GetPageTitle());
            var existingPageId = pageNode.Attribute("ID").Value;

            var page = new XDocument(new XElement(ns + "Page",
                                                  new XElement(ns + "Outline",
                                                               new XElement(ns + "OEChildren",
                                                                            new XElement(ns + "OE",
                                                                                         new XElement(ns + "T",
                                                                                                      new XCData("Current date/time: " +
                                                                                                                 DateTime.Now)))))));

            page.Root.SetAttributeValue("ID", existingPageId);
            _oneNoteApp.UpdatePageContent(page.ToString(), DateTime.MinValue);

            return("Update Complete");
        }
Example #7
0
        private void fnOCR(string v_strImgPath)
        {
            //获取图片的Base64编码
            FileInfo file = new FileInfo(v_strImgPath);

            using (MemoryStream ms = new MemoryStream())
            {
                Bitmap bp = new Bitmap(v_strImgPath);

                switch (file.Extension.ToLower())
                {
                    case ".jpg":
                        bp.Save(ms, ImageFormat.Jpeg);
                        break;
                    case ".jpeg":
                        bp.Save(ms, ImageFormat.Jpeg);
                        break;
                    case ".gif":
                        bp.Save(ms, ImageFormat.Gif);
                        break;
                    case ".bmp":
                        bp.Save(ms, ImageFormat.Bmp);
                        break;
                    case ".tiff":
                        bp.Save(ms, ImageFormat.Tiff);
                        break;
                    case ".png":
                        bp.Save(ms, ImageFormat.Png);
                        break;
                    case ".emf":
                        bp.Save(ms, ImageFormat.Emf);
                        break;
                    default:
                        this.labMsg.Content = "不支持的图片格式。";
                        return;
                }

                byte[] buffer = ms.GetBuffer();
                string _Base64 = Convert.ToBase64String(buffer);

                //向Onenote2010中插入图片
                var onenoteApp = new Microsoft.Office.Interop.OneNote.Application();


                /*string sectionID; Console.WriteLine("wang");
                onenoteApp.OpenHierarchy(AppDomain.CurrentDomain.BaseDirectory + "tmpPath/" + "newfile.one", 
                    null, out sectionID, Microsoft.Office.Interop.OneNote.CreateFileType.cftSection);
                string pageID = "{A975EE72-19C3-4C80-9C0E-EDA576DAB5C6}{1}{B0}";  // 格式 {guid}{tab}{??}
                onenoteApp.CreateNewPage(sectionID, out pageID, Microsoft.Office.Interop.OneNote.NewPageStyle.npsBlankPageNoTitle);
                */

                var existingPageId = "";
                //var pageNode;
                string notebookXml;
                if (existingPageId == "")
                {
                    onenoteApp.GetHierarchy(null, Microsoft.Office.Interop.OneNote.HierarchyScope.hsPages, out notebookXml);
                    //onenoteApp.GetHierarchy(pageID, HierarchyScope.hsPages, out notebookXml);

                    var doc = XDocument.Parse(notebookXml);
                    var ns = doc.Root.Name.Namespace;
                    var sectionNode = doc.Descendants(ns + "Section").FirstOrDefault();
                    var sectionID = sectionNode.Attribute("ID").Value;
                    onenoteApp.CreateNewPage(sectionID, out existingPageId);
                    var pageNode = doc.Descendants(ns + "Page").FirstOrDefault();
                    if (pageNode != null)
                    {
                        //Image Type 只支持这些类型:auto|png|emf|jpg
                        string ImgExtension = file.Extension.ToLower().Substring(1);
                        switch (ImgExtension)
                        {
                            case "jpg":
                                ImgExtension = "jpg";
                                break;
                            case "png":
                                ImgExtension = "png";
                                break;
                            case "emf":
                                ImgExtension = "emf";
                                break;
                            default:
                                ImgExtension = "auto";
                                break;
                        }


                        var page = new XDocument(new XElement(ns + "Page", new XAttribute("ID", existingPageId),
                                         new XElement(ns + "Outline",
                                           new XElement(ns + "OEChildren",
                                             new XElement(ns + "OE",
                                               new XElement(ns + "Image",
                                                 new XAttribute("format", ImgExtension), new XAttribute("originalPageNumber", "0"),
                                                 new XElement(ns + "Position",
                                                        new XAttribute("x", "0"), new XAttribute("y", "0"), new XAttribute("z", "0")),
                                                 new XElement(ns + "Size",
                                                        new XAttribute("width", bp.Width.ToString()), new XAttribute("height", bp.Height.ToString())),
                                                    new XElement(ns + "Data", _Base64)))))));
                        //page.Root.SetAttributeValue("ID", existingPageId);
                        onenoteApp.UpdatePageContent(page.ToString(), DateTime.MinValue);

                        //线程休眠时间,单位毫秒,若图片很大,则延长休眠时间,保证Onenote OCR完毕
                        System.Threading.Thread.Sleep(Int32.Parse(System.Configuration.ConfigurationManager.AppSettings["WaitTIme"]));

                        string pageXml;
                        onenoteApp.GetPageContent(existingPageId, out pageXml, Microsoft.Office.Interop.OneNote.PageInfo.piBinaryData);//piAll

                        //获取OCR后的内容
                        FileStream tmpXml = new FileStream(System.Configuration.ConfigurationManager.AppSettings["tmpPath"] + @"\tmp.xml", FileMode.Create, FileAccess.ReadWrite);
                        StreamWriter sw = new StreamWriter(tmpXml);
                        sw.Write(pageXml);
                        sw.Flush();
                        sw.Close();
                        tmpXml.Close();

                        FileStream tmpOnenote = new FileStream(System.Configuration.ConfigurationManager.AppSettings["tmpPath"] + @"\tmp.xml", FileMode.Open, FileAccess.ReadWrite);
                        XmlReader reader = XmlReader.Create(tmpOnenote);
                        XElement rdlc = XElement.Load(reader);

                        XmlNameTable nameTable = reader.NameTable;
                        XmlNamespaceManager mgr = new XmlNamespaceManager(nameTable);
                        mgr.AddNamespace("one", ns.ToString());

                        StringReader sr = new StringReader(pageXml);
                        XElement onenote = XElement.Load(sr);

                        var xml = from o in onenote.XPathSelectElements("//one:Image", mgr)
                                  select o.XPathSelectElement("//one:OCRText", mgr).Value;
                        this.txtOCRed.Text = (xml.First().ToString()).Replace(" ", "");

                        sr.Close();
                        reader.Close();
                        tmpOnenote.Close();
                        onenoteApp.DeleteHierarchy(existingPageId);
                        //onenoteApp.DeleteHierarchy(sectionID, DateTime.MinValue, true);  // 摧毁原始页面
                    }
                }

                /*Onenote 2010 中图片的XML格式
                   <one:Image format="" originalPageNumber="0" lastModifiedTime="" objectID="">
                        <one:Position x="" y="" z=""/>
                        <one:Size width="" height=""/>
                        <one:Data>Base64</one:Data>
                  
                        //以下标签由Onenote 2010自动生成,不要在程序中处理,目标是获取OCRText中的内容。
                        <one:OCRData lang="en-US">
                        <one:OCRText>
                            <![CDATA[   OCR后的文字   ]]>
                        </one:OCRText>
                        <one:OCRToken startPos="0" region="0" line="0" x="4.251968383789062" y="3.685039281845092" width="31.18110275268555" height="7.370078563690185"/>
                        <one:OCRToken startPos="7" region="0" line="0" x="39.40157318115234" y="3.685039281845092" width="13.32283401489258" height="8.78740119934082"/>
                        <one:OCRToken startPos="12" region="0" line="1" x="4.251968383789062" y="17.85826683044434" width="23.52755928039551" height="6.803150177001953"/>
                        <one:OCRToken startPos="18" region="0" line="1" x="32.031494140625" y="17.85826683044434" width="41.10236358642578" height="6.803150177001953"/>
                        <one:OCRToken startPos="28" region="0" line="1" x="77.66928863525391" y="17.85826683044434" width="31.46456718444824" height="6.803150177001953"/>
                        ................
                   </one:Image>      
                */


                /*ObjectID格式
                  The representation of an object to be used for identification of objects on a page. Not unique through OneNote, but unique on the page and the hierarchy. 
                   <xsd:simpleType name="ObjectID" ">
                      <xsd:restriction base="xsd:string">
                         <xsd:pattern value="\{[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12}\}\{[0-9]+\}\{[A-Z][0-9]+\}" />
                      </xsd:restriction>
                   </xsd:simpleType>
                */

                
            }
        }
        private void ImageRead(object sender, RoutedEventArgs e)
        {
            string strID, strXML, notebookXml;
            string pageToBeChange = "SandboxPage";

            Microsoft.Office.Interop.OneNote.Application app = new Microsoft.Office.Interop.OneNote.Application();
            //app.OpenHierarchy(@"C:\Users\kjlue_000\Documents\OneNote Notebooks\OCRSandbox\Ocr.one",
            //    System.String.Empty, out strID, CreateFileType.cftNone);
            app.GetHierarchy(null, HierarchyScope.hsPages, out notebookXml);
            var doc            = XDocument.Parse(notebookXml);
            var ns             = doc.Root.Name.Namespace;
            var pageNode       = doc.Descendants(ns + "Page").Where(n => n.Attribute("name").Value == pageToBeChange).FirstOrDefault();
            var existingPageId = pageNode.Attribute("ID").Value;

            Bitmap bitmap = ScreenCapture();

            MemoryStream stream = new MemoryStream();

            bitmap.Save(stream, ImageFormat.Jpeg);
            string fileString = Convert.ToBase64String(stream.ToArray());

            String strImportXML;

            strImportXML = "<?xml version=\"1.0\"?>" +
                           "<one:Page xmlns:one=\"http://schemas.microsoft.com/office/onenote/2013/onenote\" ID=\"" + existingPageId + "\">" + //{D2954871-2111-06B9-1AB9-882CD62848AA}{1}{E1833485368852652557020163191444754720811741}\">" +
                           "    <one:PageSettings RTL=\"false\" color=\"automatic\">" +
                           "        <one:PageSize>" +
                           "            <one:Automatic/>" +
                           "        </one:PageSize>" +
                           "        <one:RuleLines visible=\"false\"/>" +
                           "    </one:PageSettings>" +
                           "    <one:Title style=\"font-family:Calibri;font-size:17.0pt\" lang=\"en-US\">" +
                           "        <one:OE alignment=\"left\">" +
                           "            <one:T>" +
                           "                <![CDATA[SandboxPage]]>" +
                           "            </one:T>" +
                           "        </one:OE>" +
                           "    </one:Title>" +
                           "    <one:Outline >" +
                           "        <one:Position x=\"20\" y=\"50\"/>" +
                           "        <one:Size width=\"" + bitmap.Width + "\" height=\"" + bitmap.Height + "\"  isSetByUser=\"true\"/>" +
                           "        <one:OEChildren>" +
                           "            <one:OE alignment=\"left\">" +
                           //"                <one:T>" +
                           "    <one:Image> <one:Data>" + fileString + "</one:Data></one:Image>" +
                           //"                    <![CDATA[Sample Text]]>" +
                           //"                </one:T>" +
                           "            </one:OE>" +
                           "        </one:OEChildren>" +
                           "    </one:Outline>" +
                           "</one:Page>";
            app.UpdatePageContent(strImportXML);

            //app.SyncHierarchy(strID);

            //Give one note some time to ocr the texts
            app.GetPageContent(existingPageId, out strXML);
            doc = XDocument.Parse(strXML);
            int timeoutCounter = 0;

            while (doc.Descendants(ns + "OCRText").FirstOrDefault() == null)
            {
                System.Threading.Thread.Sleep(200);
                app.GetPageContent(existingPageId, out strXML);
                doc = XDocument.Parse(strXML);
                timeoutCounter++;
                if (timeoutCounter > 30)
                {
                    textbox.Text = "OneNote timed out texify-ing image! try again? maybe?...";
                    return;
                }
            }
            string readText = doc.Descendants(ns + "OCRText").FirstOrDefault().Value;

            if (savedEnd != null)
            {
                readText = savedEnd + " " + readText;
                savedEnd = null;
            }

            Filters.CombineLines(ref readText);
            readText = readText.Replace('¡', 'i');

            Filters.PsychologyFilter(ref readText);

            textbox.Text = readText;

            //Empty Page (I.E. Cleanup)
            doc = XDocument.Parse(strXML);
            var imageXML = doc.Descendants(ns + "Outline");

            foreach (var item in imageXML)
            {
                string outlineID = item.Attribute("objectID").Value;
                if (outlineID != null)
                {
                    app.DeletePageContent(existingPageId, outlineID);
                }
            }

            //Minimize then read
            this.WindowState = System.Windows.WindowState.Minimized;
            this.ReadText(sender, e);
        }
Example #9
0
        private string GetOCRText(string base64img)
        {
            byte[]       imageBytes = Convert.FromBase64String(base64img);
            MemoryStream stream     = new MemoryStream(imageBytes, 0, imageBytes.Length);

            stream.Write(imageBytes, 0, imageBytes.Length);
            Image bitmap = Image.FromStream(stream, true);

            Console.WriteLine(bitmap.Width);
            Console.WriteLine(bitmap.Height);

            string pageToBeChange = "ocr";

            string strNamespace = "http://schemas.microsoft.com/office/onenote/2010/onenote";

            OneNote.Application onApplication = new OneNote.Application();
            string notebookXml;

            onApplication.GetHierarchy(null, HierarchyScope.hsPages, out notebookXml);
            XDocument  doc            = XDocument.Parse(notebookXml);
            XNamespace ns             = doc.Root.Name.Namespace;
            XElement   pageNode       = doc.Descendants(ns + "Page").FirstOrDefault();
            string     existingPageId = pageNode.Attribute("ID").Value;
            string     origPageXML;

            onApplication.GetPageContent(existingPageId, out origPageXML, OneNote.PageInfo.piAll);
            XmlDocument xmlDoc = new XmlDocument();

            xmlDoc.LoadXml(origPageXML);
            XmlNamespaceManager nsmgr = new XmlNamespaceManager(xmlDoc.NameTable);

            nsmgr.AddNamespace("one", strNamespace);
            XmlNodeList imageNodes = xmlDoc.SelectNodes("//one:Image", nsmgr);

            for (int i = 0; i < imageNodes.Count; i++)
            {
                if (imageNodes[i].Attributes["objectID"] != null)
                {
                    onApplication.DeletePageContent(existingPageId, imageNodes[i].Attributes["objectID"].Value);
                }
            }


            string m_xmlImageContent =
                "<one:Image><one:Size width=\"{1}\" height=\"{2}\" isSetByUser=\"true\" /><one:Data>{0}</one:Data>" +
                //"<one:OCRData lang=\"zh-TW\">" +
                //"<one:OCRToken startPos=\"0\" region=\"0\" line=\"0\" x=\"5.27999973297119\" y=\"4.800000190734863\" width=\"48.72000122070312\" height=\"51.8400001525879\"/>" +
                //"</one:OCRData>" +
                "</one:Image>";
            string m_xmlNewOutline =
                "<?xml version=\"1.0\"?><one:Page xmlns:one=\"{2}\" ID=\"{1}\"><one:Title><one:OE><one:T><![CDATA[{3}]]></one:T></one:OE></one:Title>{0}</one:Page>";

            if (pageNode != null)
            {
                string imageXmlStr    = string.Format(m_xmlImageContent, base64img, bitmap.Width, bitmap.Height);
                string pageChangesXml = string.Format(m_xmlNewOutline, new object[] { imageXmlStr, existingPageId, strNamespace, pageToBeChange });
                onApplication.UpdatePageContent(pageChangesXml.ToString(), DateTime.MinValue);
                //onenoteApp.UpdateHierarchy(pageChangesXml);
            }

            long   startTime      = currentUnixTime();
            string strPageContent = "";

            while (strPageContent == "")
            {
                string strHierarchy;
                string strXML;
                var    onApp = onApplication;
                // Get the hierarchy from the root to pages
                onApp.GetHierarchy(System.String.Empty, OneNote.HierarchyScope.hsPages, out strHierarchy);

                // Load the xml into a document
                xmlDoc = new XmlDocument();
                xmlDoc.LoadXml(strHierarchy);

                //Create an XmlNamespaceManager for resolving namespaces.
                nsmgr = new XmlNamespaceManager(xmlDoc.NameTable);
                nsmgr.AddNamespace("one", strNamespace);

                // Find the page ID of the active page
                XmlElement xmlActivePage   = (XmlElement)xmlDoc.SelectSingleNode("//one:Page", nsmgr);
                string     strActivePageID = xmlActivePage.GetAttribute("ID");

                // Get the content from the active page
                onApp.GetPageContent(strActivePageID, out strXML, OneNote.PageInfo.piBinaryData);
                xmlDoc.LoadXml(strXML);

                //Get the data in the T nodes
                string strOcrContent = "";
                strPageContent = "";
                XmlNodeList elemList = xmlDoc.GetElementsByTagName("one:OCRText");
                for (int i = 0; i < elemList.Count; i++)
                {
                    strOcrContent  = elemList[i].InnerText; //Get the contents of the <![CDATA[]] block
                    strPageContent = strPageContent + strOcrContent;
                }
                if (currentUnixTime() > startTime + 3)
                {
                    break;
                }
            }
            if (strPageContent == "")
            {
                return("<No OCR content on this page>");
            }
            else
            {
                return(strPageContent);
            }
        }
Example #10
0
        public void SimpleGantt(IRibbonControl control)
        {
            String xml;

            Microsoft.Office.Interop.OneNote.Application onenote = new Microsoft.Office.Interop.OneNote.Application();
            string thisNoteBook = onenote.Windows.CurrentWindow.CurrentNotebookId;
            string thisSection  = onenote.Windows.CurrentWindow.CurrentSectionId;
            string thisPage     = onenote.Windows.CurrentWindow.CurrentPageId;

            onenote.GetPageContent(thisPage, out xml);

            doc   = XDocument.Parse(xml);
            ns    = doc.Root.Name.Namespace;
            style = "font-family:Calibri;font-size:9.0pt;";

            //doc.Save("D:/one.xml");

            var gantts = from oe in doc.Descendants(ns + "OE")
                         from item in oe.Elements(ns + "Meta")
                         where item.Attribute("name").Value == "SimpleGanttTable"
                         select oe;

            if (gantts.Count() == 0)
            {
                var outline = new XElement(ns + "Outline",
                                           new XElement(ns + "Position",
                                                        new XAttribute("x", "36.0"),
                                                        new XAttribute("y", "80.0")
                                                        ),
                                           new XElement(ns + "Size",
                                                        new XAttribute("width", "600.0"),
                                                        new XAttribute("height", "100.0"),
                                                        new XAttribute("isSetByUser", "true")
                                                        ),
                                           new XElement(ns + "OEChildren",
                                                        new XElement(ns + "OE",
                                                                     new XElement(ns + "Meta",
                                                                                  new XAttribute("name", "SimpleGanttStart"),
                                                                                  new XAttribute("content", "")
                                                                                  ),
                                                                     new XElement(ns + "T", new XCData("Startas: ")) //DateTime.Now.ToString("yyyy.MM.dd")
                                                                     ),
                                                        new XElement(ns + "OE",
                                                                     new XElement(ns + "Meta",
                                                                                  new XAttribute("name", "SimpleGanttFinish"),
                                                                                  new XAttribute("content", "")
                                                                                  ),
                                                                     new XElement(ns + "T", new XCData("Terminas: "))
                                                                     ),
                                                        new XElement(ns + "OE",
                                                                     new XElement(ns + "T", new XCData(""))
                                                                     ),
                                                        new XElement(ns + "OE",
                                                                     new XElement(ns + "Meta",
                                                                                  new XAttribute("name", "SimpleGanttTable"),
                                                                                  new XAttribute("content", "")
                                                                                  ),
                                                                     new XElement(ns + "Table",
                                                                                  new XAttribute("bordersVisible", "true"),
                                                                                  new XAttribute("hasHeaderRow", "true"),

                                                                                  new XElement(ns + "Columns",
                                                                                               new XElement(ns + "Column",
                                                                                                            new XAttribute("index", "0"),
                                                                                                            new XAttribute("width", "140.0"),
                                                                                                            new XAttribute("isLocked", "true")
                                                                                                            ),
                                                                                               new XElement(ns + "Column",
                                                                                                            new XAttribute("index", "1"),
                                                                                                            new XAttribute("width", "40.0"),
                                                                                                            new XAttribute("isLocked", "true")
                                                                                                            ),
                                                                                               new XElement(ns + "Column",
                                                                                                            new XAttribute("index", "2"),
                                                                                                            new XAttribute("width", "40.0"),
                                                                                                            new XAttribute("isLocked", "true")
                                                                                                            ),
                                                                                               new XElement(ns + "Column",
                                                                                                            new XAttribute("index", "3"),
                                                                                                            new XAttribute("width", "80.0"),
                                                                                                            new XAttribute("isLocked", "true")
                                                                                                            )
                                                                                               ),

                                                                                  new XElement(ns + "Row",
                                                                                               new XElement(ns + "Cell",
                                                                                                            new XElement(ns + "OEChildren",
                                                                                                                         new XElement(ns + "OE",
                                                                                                                                      new XAttribute("style", style),
                                                                                                                                      new XAttribute("alignment", "center"),
                                                                                                                                      new XElement(ns + "T", new XCData("UŽDUOTIS"))
                                                                                                                                      )
                                                                                                                         )
                                                                                                            ),
                                                                                               new XElement(ns + "Cell",
                                                                                                            new XElement(ns + "OEChildren",
                                                                                                                         new XElement(ns + "OE",
                                                                                                                                      new XAttribute("style", style),
                                                                                                                                      new XAttribute("alignment", "center"),
                                                                                                                                      new XElement(ns + "T", new XCData("STARTAS"))
                                                                                                                                      )
                                                                                                                         )
                                                                                                            ),
                                                                                               new XElement(ns + "Cell",
                                                                                                            new XElement(ns + "OEChildren",
                                                                                                                         new XElement(ns + "OE",
                                                                                                                                      new XAttribute("style", style),
                                                                                                                                      new XAttribute("alignment", "center"),
                                                                                                                                      new XElement(ns + "T", new XCData("TRUKMĖ"))
                                                                                                                                      )
                                                                                                                         )
                                                                                                            ),
                                                                                               new XElement(ns + "Cell",
                                                                                                            new XElement(ns + "OEChildren",
                                                                                                                         new XElement(ns + "OE",
                                                                                                                                      new XAttribute("style", style),
                                                                                                                                      new XAttribute("alignment", "center"),
                                                                                                                                      new XElement(ns + "T", new XCData("KAS?"))
                                                                                                                                      )
                                                                                                                         )
                                                                                                            )
                                                                                               ),

                                                                                  new XElement(ns + "Row",
                                                                                               new XElement(ns + "Cell",
                                                                                                            new XElement(ns + "OEChildren",
                                                                                                                         new XElement(ns + "OE",
                                                                                                                                      new XElement(ns + "T", new XCData("Užduotis 1"))
                                                                                                                                      )
                                                                                                                         )
                                                                                                            ),
                                                                                               new XElement(ns + "Cell",
                                                                                                            new XElement(ns + "OEChildren",
                                                                                                                         new XElement(ns + "OE",
                                                                                                                                      new XElement(ns + "T", new XCData("1"))
                                                                                                                                      )
                                                                                                                         )
                                                                                                            ),
                                                                                               new XElement(ns + "Cell",
                                                                                                            new XElement(ns + "OEChildren",
                                                                                                                         new XElement(ns + "OE",
                                                                                                                                      new XElement(ns + "T", new XCData("1"))
                                                                                                                                      )
                                                                                                                         )
                                                                                                            ),
                                                                                               new XElement(ns + "Cell",
                                                                                                            new XElement(ns + "OEChildren",
                                                                                                                         new XElement(ns + "OE",
                                                                                                                                      new XElement(ns + "T", new XCData(""))
                                                                                                                                      )
                                                                                                                         )
                                                                                                            )
                                                                                               ),


                                                                                  new XElement(ns + "Row",
                                                                                               new XElement(ns + "Cell",
                                                                                                            new XElement(ns + "OEChildren",
                                                                                                                         new XElement(ns + "OE",
                                                                                                                                      new XElement(ns + "T", new XCData(""))
                                                                                                                                      )
                                                                                                                         )
                                                                                                            ),
                                                                                               new XElement(ns + "Cell",
                                                                                                            new XElement(ns + "OEChildren",
                                                                                                                         new XElement(ns + "OE",
                                                                                                                                      new XElement(ns + "T", new XCData(""))
                                                                                                                                      )
                                                                                                                         )
                                                                                                            ),
                                                                                               new XElement(ns + "Cell",
                                                                                                            new XElement(ns + "OEChildren",
                                                                                                                         new XElement(ns + "OE",
                                                                                                                                      new XElement(ns + "T", new XCData(""))
                                                                                                                                      )
                                                                                                                         )
                                                                                                            ),
                                                                                               new XElement(ns + "Cell",
                                                                                                            new XElement(ns + "OEChildren",
                                                                                                                         new XElement(ns + "OE",
                                                                                                                                      new XElement(ns + "T", new XCData(""))
                                                                                                                                      )
                                                                                                                         )
                                                                                                            )
                                                                                               )


                                                                                  )
                                                                     )
                                                        )
                                           );

                var page = doc.Descendants(ns + "Page").First();
                page.Add(outline);

                gantts = from oe in doc.Descendants(ns + "OE")
                         from item in oe.Elements(ns + "Meta")
                         where item.Attribute("name").Value == "SimpleGanttTable"
                         select oe;
            }

            gantt = gantts.ElementAt(0);

            var dates = from oe in doc.Descendants(ns + "OEChildren")
                        from item in oe.Descendants(ns + "Meta")
                        where item.Attribute("name").Value == "SimpleGanttTable"
                        select oe; //.Descendants(ns + "T");

            if (dates.Count() > 0)
            {
                //var startas = RemoveHtmlTags(dates.ElementAt(0).Value).Substring(8).Trim();
                var startas = RemoveHtmlTags(dates.Descendants(ns + "T").First().Value).Substring(8).Trim();
                DateTime.TryParse(startas, out ganttStart);
                //MessageBox.Show("Start: " + ganttStart);
            }


            // CALC COLUMNS //

            int    taskColumn     = 1;
            int    startColumn    = 2;
            int    durationColumn = 3;
            string taskName       = "";
            int    start          = 0;
            int    duration       = 0;
            int    maxPeriod      = 0;

            var items = gantt.Elements(ns + "Table").First().Descendants(ns + "Cell");
            int cols  = gantt.Elements(ns + "Table").First().Descendants(ns + "Column").Count();
            int _cols = cols;
            int col   = 0;

            foreach (var item in items)
            {
                col++;
                if (col == startColumn)
                {
                    Int32.TryParse(item.Value, out start);
                }
                if (col == durationColumn & start > 0 & Int32.TryParse(item.Value, out duration))
                {
                    if (start + duration - 1 > maxPeriod)
                    {
                        maxPeriod = start + duration - 1;
                    }
                }
                if (col == _cols)
                {
                    col = 0;
                }
            }

            // ADD COLUMNS //

            addGanttColumns(maxPeriod + 4 - cols);
            cols = gantt.Elements(ns + "Table").First().Descendants(ns + "Column").Count();

            // SET HEADER ROW //

            var headers = gantt.Descendants(ns + "Row").First().Descendants(ns + "Cell");

            foreach (var header in headers)
            {
                col++;
                if (col > 4)
                {
                    var    index = col - 4;
                    String txt   = index.ToString();
                    if (ganttStart != new DateTime())
                    {
                        var date = ganttStart.AddDays(col - 5);
                        txt = Right("0" + date.Month.ToString(), 2) + "." + Right("0" + date.Day.ToString(), 2);
                    }
                    header.Descendants(ns + "T").First().Value = txt;
                }
            }
            col = 0;

            // ADD COLORS //

            var cells = gantt.Elements(ns + "Table").First().Descendants(ns + "Cell");

            foreach (var cell in cells)
            {
                col++;
                if (col == taskColumn)
                {
                    taskName = cell.Value;
                }
                if (col == startColumn)
                {
                    Int32.TryParse(cell.Value, out start);
                }
                if (col == durationColumn)
                {
                    Int32.TryParse(cell.Value, out duration);
                }
                var color = cell.Attribute("shadingColor");
                if (color != null)
                {
                    cell.Attribute("shadingColor").Remove();
                }
                var finish  = start + duration - 1;
                var current = col - 4;
                if (col > 4 & current >= start & current <= finish)
                {
                    if (taskName == taskName.ToUpper())
                    {
                        cell.Add(new XAttribute("shadingColor", "#5F497A"));
                    }
                    else
                    {
                        cell.Add(new XAttribute("shadingColor", "#CCC1D9"));
                    }
                }
                else if (col > 4)
                {
                    if (col % 2 > 0)
                    {
                        cell.Add(new XAttribute("shadingColor", "#FAFAFA"));
                    }
                }
                if (col == cols)
                {
                    col = 0;
                }
            }

            //doc.Save("D:/doc.xml");
            onenote.UpdatePageContent(doc.ToString());
        }
Example #11
0
        public static void Main()
        {
            //Create New Instance of OneNote Application
            var oneNote = new Application();


            //Get current active page (see commented for current NoteBook/Section)

            /* string thisNoteBook = oneNote.Windows.CurrentWindow.CurrentNotebookId;
             * string thisSection  = oneNote.Windows.CurrentWindow.CurrentSectionId;    */
            string thisPage = oneNote.Windows.CurrentWindow.CurrentPageId;


            //Get the content of the page
            string xmlPage;

            oneNote.GetPageContent(thisPage, out xmlPage);


            //Declarations for paste
            string returnStringText = null;
            string Pasteresult      = null;


            //Set Namespace from our page
            string ns = xmlPage.Substring(xmlPage.IndexOf("xmlns:") + 6, xmlPage.IndexOf("=\"http://") - (xmlPage.IndexOf("xmlns:") + 6)) + @":";


            //Find the start and end of the page so that we can insert
            //a new section in between for our pasted content
            int    start    = xmlPage.LastIndexOf("</" + ns + "Page>");
            string startstr = xmlPage.Substring(0, start);
            string endstr   = xmlPage.Substring(start, xmlPage.Length - start);


            //New section for our content
            //(this is essential when the page in OneNote is currently empty)
            string outline =
                "<" + ns + "Outline >" +
                "<" + ns + "Position x=\"35.0\" y=\"60.0\"/>" +                              //This puts it just under title
                "<" + ns + "Size width=\"750.75\" height=\"13.50\" isSetByUser=\"true\"/>" + //Makes the box nice and big
                "<" + ns + "OEChildren>" +
                "<" + ns + "OE>" +
                "<" + ns + "T>" +
                "<![CDATA[]]>" +
                "</" + ns + "T>" +
                "</" + ns + "OE>" +
                "</" + ns + "OEChildren>" +
                "</" + ns + "Outline>";


            //Form the new page and replace our original page
            string newpage = startstr + outline + endstr;

            xmlPage = newpage;


/*         (Below I've specifically opened a new STAThread to show you the code,
 *          if you are using a console project then you only need [STAThread])                                                                    */

            //Get Text in Clipboard using full STAThread

            //Declarations to get out of the thread
            string    PastedText   = null;
            bool      containsRTF  = false;
            bool      containsHTML = false;
            bool      containsTEXT = false;
            bool      skipReplaces = false;
            Exception threadEx     = null;

            //Open new Thread
            Thread staThread = new Thread(
                delegate()
            {
                try
                {
                    //Query our clipboard
                    containsRTF  = Clipboard.ContainsText(TextDataFormat.Rtf);
                    containsHTML = Clipboard.ContainsText(TextDataFormat.Html);
                    containsTEXT = Clipboard.ContainsText(TextDataFormat.Text);

                    //Get relevant data
                    if (containsRTF == true && containsHTML == false)
                    {
                        PastedText = Clipboard.GetText(TextDataFormat.Rtf);
                    }
                    else if (containsHTML == true)
                    {
                        PastedText = Clipboard.GetText(TextDataFormat.Html);
                    }
                    else if (containsTEXT == true)
                    {
                        PastedText = Clipboard.GetText(TextDataFormat.Text);
                    }
                }

                catch (Exception ex)
                {
                    threadEx = ex;
                }
            });

            staThread.SetApartmentState(ApartmentState.STA);
            staThread.Start();
            staThread.Join();


            //Does the clipboard contain Rich Text? (we put an extra && just to be sure it isn't html as they can sometimes get confused)
            if (containsRTF == true && containsHTML == false)
            {
                string XAML = ConvertRtfToXaml(PastedText);

                //Get HTML from Rich Text
                Pasteresult = ConvertXAMLtoHTML.convert(XAML);
            }

            //Does the clipboard contain HTML?
            else if (containsHTML == true)
            {
                //Get HTML from Clipboard
                returnStringText = PastedText;

                //Get rid of everything before <body> or the first <span>
                int pFrom = returnStringText.IndexOf("<BODY");
                if (pFrom == -1)
                {
                    pFrom = returnStringText.IndexOf("<body");
                }
                if (pFrom == -1)
                {
                    pFrom = returnStringText.IndexOf("<SPAN");
                }
                if (pFrom == -1)
                {
                    pFrom = returnStringText.IndexOf("<span");
                }

                //Get rid of everything after </body> or the last </span>
                int pTo = returnStringText.LastIndexOf("</BODY>");
                if (pTo == -1)
                {
                    pTo = returnStringText.LastIndexOf("</body>");
                }
                if (pTo == -1)
                {
                    pTo = returnStringText.LastIndexOf("</SPAN>");
                }
                if (pTo == -1)
                {
                    pTo = returnStringText.LastIndexOf("</span>");
                }

                Pasteresult = returnStringText.Substring(pFrom, pTo - pFrom + 7);
            }

            //Does the clipboard contain Plain Text?
            else if (containsTEXT == true)
            {
                //Get the Text
                Pasteresult = PastedText;

                //Replace any "<" or ">" to ensure that it isn't read as HTML
                Pasteresult = Pasteresult.Replace("<", "&lt;").Replace(">", "&gt;");

                //Skip the block of HTML tag replacements
                skipReplaces = true;
            }

            if (skipReplaces == false)
            {
                //Remove all un-supported HTML tags (leaving pretty much just <span>'s)
                //Also make sure the HTML tags that remain are all lower case or onenote will complain
                Pasteresult = Pasteresult.Replace("<body", "<span").Replace("</body", "</span").Replace("<BODY", "<span").Replace("</BODY", "</span");
                Pasteresult = Pasteresult.Replace("<div", "<span").Replace("</div", "</span").Replace("</LI", "</li");
                Pasteresult = Pasteresult.Replace("<DIV", "<span").Replace("</DIV", "</span").Replace("<LI", "<li");
                Pasteresult = Pasteresult.Replace("<SPAN", "<span").Replace("</SPAN", "</span").Replace("</DIV", "</span");
                Pasteresult = Pasteresult.Replace("STYLE=", "style=").Replace("<UL", "<ul").Replace("</UL", "</ul");
                Pasteresult = Pasteresult.Replace("<!--EndFragment-->", "").Replace("<!--StartFragment-->", "");
                Pasteresult = Pasteresult.Replace("class=MsoNormal", "").Replace("mso-fareast-language:EN-US", "");
                Pasteresult = Pasteresult.Replace("<o:p>", "").Replace("</o:p>", "");
                Pasteresult = Pasteresult.Replace(System.Environment.NewLine, " ");
                Pasteresult = Pasteresult.Replace("</b>", "</span>").Replace("</B>", "</span>");
                Pasteresult = Pasteresult.Replace("</i>", "</span>").Replace("</I>", "</span>");
                Pasteresult = Pasteresult.Replace("<br>", "<p>").Replace("<BR>", "<p>");

                //Do we have any paragraphs? If we do then we need to replace them with new XML CDATA sections
                int containsBs = Regex.Matches(Pasteresult, "<[b,B]").Count;

                //For each <b>
                while (containsBs > 0)
                {
                    string replace = "<span style='font-weight:bold'>";

                    //find the position of the <p>
                    int    pos    = Pasteresult.IndexOf("<B", StringComparison.CurrentCultureIgnoreCase);
                    string afterB = Pasteresult.Substring(pos);
                    int    end    = afterB.IndexOf(">") + 1;


                    //If there isn't any left then break
                    if (pos < 0)
                    {
                        break;
                    }
                    else
                    {
                        //Else replace the <p> with the new block
                        Pasteresult = Pasteresult.Substring(0, pos) + replace + Pasteresult.Substring(pos + end);
                    }

                    containsBs -= 1;
                }

                //Do we have any paragraphs? If we do then we need to replace them with new XML CDATA sections
                int containsIs = Regex.Matches(Pasteresult, "<[i,I]").Count;

                //For each <i>
                while (containsIs > 0)
                {
                    string replace = "<span style='font-style:italic'>";

                    //find the position of the <p>
                    int    pos    = Pasteresult.IndexOf("<I", StringComparison.CurrentCultureIgnoreCase);
                    string afterI = Pasteresult.Substring(pos);
                    int    end    = afterI.IndexOf(">") + 1;


                    //If there isn't any left then break
                    if (pos < 0)
                    {
                        break;
                    }
                    else
                    {
                        //Else replace the <p> with the new block
                        Pasteresult = Pasteresult.Substring(0, pos) + replace + Pasteresult.Substring(pos + end);
                    }

                    containsIs -= 1;
                }
                //Do we have any paragraphs? If we do then we need to replace them with new XML CDATA sections
                int containsPs = Regex.Matches(Pasteresult, "<[p,P]").Count;


                //For each <p>
                while (containsPs > 0)
                {
                    //This is the text we will replace the <p>s with, it adds a new block
                    string replace = " ]]></" + ns + "T></" + ns + "OE><" + ns + "OE><" + ns + "T><![CDATA[<span";  //Start current block (this starts a new line)

                    //find the position of the <p>
                    int pos = Pasteresult.IndexOf("<P", StringComparison.CurrentCultureIgnoreCase);

                    //If there isn't any left then break
                    if (pos < 0)
                    {
                        break;
                    }
                    else
                    {
                        //Else replace the <p> with the new block
                        Pasteresult = Pasteresult.Substring(0, pos) + replace + Pasteresult.Substring(pos + "<P".Length);
                    }

                    containsPs -= 1;
                }

                //Remove the orphaned </p> tags
                Pasteresult = Pasteresult.Replace("</P>", "").Replace("</p>", "");
            }


            //Plain text will now re-join here


            //Get the position of the end of the last code block
            int    PageContent = xmlPage.LastIndexOf("]]></" + ns + "T>");
            string startofPage = xmlPage.Substring(0, PageContent);
            string endofPage   = xmlPage.Substring(PageContent, xmlPage.Length - PageContent);

            //Insert out pasted text into the current page
            string NewPage = startofPage + Pasteresult + endofPage;


            try
            {
                //Update the onenote page
                oneNote.UpdatePageContent(NewPage);

                //Just check that the encoding hasn't created any unwanted Â's
                oneNote.GetPageContent(thisPage, out xmlPage);

                int areThereAnyÂs = Regex.Matches(xmlPage, @"Â").Count;;

                if (areThereAnyÂs > 0)
                {
                    while (areThereAnyÂs > 0)
                    {
                        int pos = xmlPage.IndexOf(@"Â", StringComparison.CurrentCultureIgnoreCase);

                        string replace = "";
                        //If there isn't any left then break
                        if (pos < 0)
                        {
                            break;
                        }
                        else
                        {
                            //Else replace the <p> with the new block
                            xmlPage = xmlPage.Substring(0, pos) + replace + xmlPage.Substring(pos + 1);
                        }

                        //Increment numbers
                        areThereAnyÂs -= 1;
                    }

                    oneNote.UpdatePageContent(xmlPage);
                }
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message + Environment.NewLine + Environment.NewLine + "Try using Ctrl + P", "Error Message");
            }


            oneNote = null;
            GC.Collect();
            GC.WaitForPendingFinalizers();
        }
        public static bool UpdateTaskList(string notebook, string section, string page, TaskItem newTask)
        {
            string notebookXml;
            var    onenoteApp = new Microsoft.Office.Interop.OneNote.Application();

            onenoteApp.GetHierarchy(null, HierarchyScope.hsPages, out notebookXml);

            var doc = System.Xml.Linq.XDocument.Parse(notebookXml);
            var ns  = doc.Root.Name.Namespace;

            var notebookNodeList = doc.Descendants(ns + "Notebook").Where(n =>
                                                                          n.Attribute("name").Value.Contains(notebook));

            if (notebookNodeList == null)
            {
                return(false);
            }

            foreach (var notebookNode in notebookNodeList)
            {
                var sectionNode = notebookNode.Descendants(ns + "Section").Where(n =>
                                                                                 n.Attribute("name").Value.Contains(section)).FirstOrDefault();
                if (sectionNode != null)
                {
                    var pageNode = sectionNode.Descendants(ns + "Page")
                                   .Where(n => n.Attribute("name").Value.Contains(page))
                                   .FirstOrDefault();
                    if (pageNode != null)
                    {
                        string pageXml;
                        onenoteApp.GetPageContent(pageNode.Attribute("ID").Value, out pageXml);
                        var pageDoc   = XDocument.Parse(pageXml);
                        var taskTable = pageDoc.Descendants(ns + "Table").FirstOrDefault();
                        if (taskTable != null)
                        {
                            bool bfirst = true;
                            foreach (var taskRow in from row in taskTable.Descendants(ns + "Row") select row)
                            {
                                if (bfirst)
                                {
                                    bfirst = false;
                                    continue;
                                }

                                string strTaskId = "";
                                var    taskCells = taskRow.Descendants(ns + "Cell");
                                if (taskCells.Count() == 5)
                                {
                                    var taskId = taskCells.ElementAt(0).Descendants(ns + "OutlookTask").FirstOrDefault();
                                    if (taskId == null)
                                    {
                                        continue;
                                    }
                                    strTaskId = taskId.Attribute("guidTask").Value;
                                    if (strTaskId != newTask.TaskOneNoteId)
                                    {
                                        continue;
                                    }

                                    if (newTask.TaskTimeEdit > 0)
                                    {
                                        taskCells.ElementAt(1).Value = newTask.TaskTimeEdit.ToString();
                                    }
                                    if (newTask.TaskTimeUsage > 0)
                                    {
                                        taskCells.ElementAt(2).Value = newTask.TaskTimeUsage.ToString();
                                    }

                                    string strModifiedPage = pageDoc.ToString();

                                    onenoteApp.UpdatePageContent(strModifiedPage, DateTime.MinValue);
                                    return(true);
                                }
                            }
                        }
                    }
                }
            }

            return(false);
        }
        public static bool UpdateTaskItem(TaskItem newTask)
        {
            string notebookXml;
            var    onenoteApp = new Microsoft.Office.Interop.OneNote.Application();

            onenoteApp.GetHierarchy(null, HierarchyScope.hsPages, out notebookXml);

            var doc = System.Xml.Linq.XDocument.Parse(notebookXml);
            var ns  = doc.Root.Name.Namespace;

            var notebookNode = doc.Descendants(ns + "Notebook").Where(n =>
                                                                      n.Attribute("ID").Value.Equals(newTask.NoteBookId)).FirstOrDefault();

            if (notebookNode == null)
            {
                return(false);
            }

            var sectionNode = notebookNode.Descendants(ns + "Section").Where(n =>
                                                                             n.Attribute("ID").Value.Equals(newTask.SectionId)).FirstOrDefault();

            if (sectionNode == null)
            {
                return(false);
            }

            var pageNode = sectionNode.Descendants(ns + "Page")
                           .Where(n => n.Attribute("ID").Value.Equals(newTask.PageId))
                           .FirstOrDefault();

            if (pageNode != null)
            {
                string pageXml;
                onenoteApp.GetPageContent(pageNode.Attribute("ID").Value, out pageXml);
                var pageDoc   = System.Xml.Linq.XDocument.Parse(pageXml);
                var taskTable = pageDoc.Descendants(ns + "Table").FirstOrDefault();
                if (taskTable != null)
                {
                    bool bfirst = true;
                    foreach (var taskRow in from row in taskTable.Descendants(ns + "Row") select row)
                    {
                        if (bfirst)
                        {
                            bfirst = false;
                            continue;
                        }

                        string strTaskId = "";
                        var    taskCells = taskRow.Descendants(ns + "Cell");
                        if (taskCells.Count() != 5)
                        {
                            continue;
                        }

                        // 判断任务ID是否相同
                        var taskId = taskCells.ElementAt(0).Descendants(ns + "OutlookTask").FirstOrDefault();
                        if (taskId == null)
                        {
                            continue;
                        }

                        strTaskId = taskId.Attribute("guidTask").Value;
                        if (strTaskId != newTask.TaskOneNoteId)
                        {
                            continue;
                        }

                        // 更新任务信息到OneNote文件中
                        //taskCells.ElementAt(0).SetValue(newTask.TaskName);
                        taskId.SetAttributeValue("completed", newTask.TaskComplete);
                        if (newTask.TaskTimeEdit > 0)
                        {
                            taskCells.ElementAt(1).Descendants(ns + "T").FirstOrDefault().SetValue(
                                new XCData(newTask.TaskTimeEdit.ToString()).Value);
                        }

                        if (newTask.TaskTimeUsage > 0)
                        {
                            taskCells.ElementAt(2).Descendants(ns + "T").FirstOrDefault().SetValue(
                                new XCData(newTask.TaskTimeUsage.ToString()).Value);
                        }

                        if (newTask.TaskTimeInterrupt > 0)
                        {
                            taskCells.ElementAt(3).Descendants(ns + "T").FirstOrDefault().SetValue(
                                new XCData(newTask.TaskTimeInterrupt.ToString()).Value);
                        }

                        taskCells.ElementAt(4).Descendants(ns + "T").FirstOrDefault().SetValue(
                            new XCData(newTask.TaskComment).Value);
                        onenoteApp.UpdatePageContent(pageDoc.ToString(), DateTime.MinValue);
                        return(true);
                    }
                }
            }

            return(false);
        }
        /// <summary>
        /// onenote 2010,注意需要先在onenote中创建笔记本,并且将至转换为onenote2007格式
        /// 推荐使用onenote2016(个人版即可),API与2010类似,(去掉XMLSchema.xs2007参数即可)其他可参考API参数命名。
        /// 注意1:一定要将dll属性中的“嵌入互操作类型”属性关闭
        /// </summary>
        /// <param name="imgPath"></param>
        /// <returns></returns>
        public string Ocr_2010(string imgPath)
        {
            try
            {
                #region 确定section_path存在
                section_path = @"C:\Users\zhensheng\Desktop\打杂\ocr\ocr.one";
                if (string.IsNullOrEmpty(section_path))
                {
                    Console.WriteLine("请先建立笔记本");
                    File.AppendAllText(AppDomain.CurrentDomain.BaseDirectory + @"\log.txt", "需要先在onenote中创建笔记本,并且将至转换为onenote2007格式,且将.one文件得路径赋值给section_path");
                    return("");
                }
                #endregion

                #region 准备数据
                //后缀
                var imgType = Path.GetExtension(imgPath);
                imgPath = imgPath.Replace(".", "");

                var data = File.ReadAllBytes(imgPath);
                //根据大小确定重试次数
                int fileSize = Convert.ToInt32(data.Length / 1024 / 1024); // 文件大小 单位M

                string guid   = Guid.NewGuid().ToString();
                string pageID = "{" + guid + "}{1}{B0}";  // 格式 {guid}{tab}{??}

                string     pageXml;
                XNamespace ns;

                var onenoteApp = new Microsoft.Office.Interop.OneNote.Application();  //onenote提供的API
                if (onenoteApp == null)
                {
                    File.AppendAllText(AppDomain.CurrentDomain.BaseDirectory + @"\log.txt", "Microsoft.Office.Interop.OneNote.Application()创建失败");
                    return("");
                }

                //重试使用
                XmlNode xmlNode;
                int     retry = 0;

                #endregion

                do
                {
                    #region 创建页面并返回pageID
                    string sectionID;
                    onenoteApp.OpenHierarchy(section_path, null, out sectionID, CreateFileType.cftSection);
                    onenoteApp.CreateNewPage(sectionID, out pageID);
                    #endregion

                    #region 获取onenote页面xml结构格式
                    string notebookXml;
                    onenoteApp.GetHierarchy(null, HierarchyScope.hsPages, out notebookXml, XMLSchema.xs2007);
                    var doc = XDocument.Parse(notebookXml);
                    ns = doc.Root.Name.Namespace;

                    #endregion

                    #region 将图片插入页面
                    Tuple <string, int, int> imgInfo = this.GetBase64(data, imgType);
                    var page = new XDocument(new XElement(ns + "Page",
                                                          new XElement(ns + "Outline",
                                                                       new XElement(ns + "OEChildren",
                                                                                    new XElement(ns + "OE",
                                                                                                 new XElement(ns + "Image",
                                                                                                              new XAttribute("format", imgType), new XAttribute("originalPageNumber", "0"),
                                                                                                              new XElement(ns + "Position",
                                                                                                                           new XAttribute("x", "0"), new XAttribute("y", "0"), new XAttribute("z", "0")),
                                                                                                              new XElement(ns + "Size",
                                                                                                                           new XAttribute("width", imgInfo.Item2), new XAttribute("height", imgInfo.Item3)),
                                                                                                              new XElement(ns + "Data", imgInfo.Item1)))))));

                    page.Root.SetAttributeValue("ID", pageID);
                    onenoteApp.UpdatePageContent(page.ToString(), DateTime.MinValue, XMLSchema.xs2007);
                    #endregion

                    #region 通过轮询访问获取OCR识别的结果,轮询超时次数为6次
                    int count = 0;
                    do
                    {
                        System.Threading.Thread.Sleep(waitTime * (fileSize > 1 ? fileSize : 1)); // 小于1M的都默认1M
                        onenoteApp.GetPageContent(pageID, out pageXml, PageInfo.piBinaryData, XMLSchema.xs2007);
                    }while (pageXml == "" && count++ < 6);
                    #endregion

                    #region  除页面
                    onenoteApp.DeleteHierarchy(pageID, DateTime.MinValue);
                    //onenoteApp = null;
                    #endregion

                    #region 从xml中提取OCR识别后的文档信息,然后输出到string中
                    XmlDocument xmlDoc = new XmlDocument();
                    xmlDoc.LoadXml(pageXml);
                    XmlNamespaceManager nsmgr = new XmlNamespaceManager(xmlDoc.NameTable);
                    nsmgr.AddNamespace("one", ns.ToString());
                    xmlNode = xmlDoc.SelectSingleNode("//one:Image//one:OCRText", nsmgr);
                    #endregion
                }
                //如果OCR没有识别出信息,则重试三次(个人测试2010失败率为0.2~0.3)
                while (xmlNode == null && retry++ < 3);
                if (xmlNode == null)
                {
                    File.AppendAllText(AppDomain.CurrentDomain.BaseDirectory + @"\log.txt", "OCR没有识别出值");
                    return("");
                }
                var localFilePath = AppDomain.CurrentDomain.BaseDirectory + @"\" + Guid.NewGuid().ToString() + ".txt";
                File.WriteAllText(localFilePath, xmlNode.InnerText.ToString());
                Console.WriteLine(xmlNode.InnerText.ToString());

                return(localFilePath);
            }
            catch (Exception e)
            {
                File.AppendAllText(AppDomain.CurrentDomain.BaseDirectory + @"\log.txt", e.ToString());
                return("");
            }
        }
Example #15
0
        private void HighlightPage(Application application, string pageId, WordMatcher matcher)
        {
            string pageXml;
            application.GetPageContent(pageId, out pageXml);
            Debug.WriteLine(pageXml);
            XElement page = XElement.Parse(pageXml);
            XNamespace oneNS = page.Name.Namespace;
            XElement title = page.Element(oneNS + "Title");
            XElement titleOE = title.Element(oneNS + "OE");
            Debug.WriteLine("page:{0} by {1}", titleOE.Element(oneNS + "T").Value, titleOE.Attribute("author"));

            StatisticsDataSet.HighlightStatisticsRow statRow = null; // frmStatistics.BeforeProcessing();

            foreach (XElement outline in page.Elements(oneNS + "Outline"))
            {
                foreach (XElement oeChildren in outline.Elements(oneNS + "OEChildren"))
                {
                    foreach (XElement oe in oeChildren.Elements(oneNS + "OE"))
                    {
                        foreach (XElement t in oe.Elements(oneNS + "T"))
                        {
                            //Debug.WriteLine("before:  ");
                            //Debug.WriteLine(t.Value);

                            string process = ProcessingWords(t.Value, matcher, statRow);

                            t.RemoveNodes();
                            t.Add(new XCData(process));

                        }
                    }
                }
            }

            //frmStatistics.AfterProcessing();
            application.UpdatePageContent(page.ToString(SaveOptions.None));
        }