private void PublishPages(string directory) { Microsoft.Office.Interop.OneNote.Application app = new Microsoft.Office.Interop.OneNote.Application(); string xml; app.GetHierarchy("", HierarchyScope.hsNotebooks, out xml); XDocument doc = XDocument.Parse(xml); foreach (XElement e in doc.Root.Elements()) { string name = (string)e.Attribute("name"); if (name == "Money Specs") { // this is the one! string id = (string)e.Attribute("ID"); app.GetHierarchy(id, HierarchyScope.hsPages, out xml); doc = XDocument.Parse(xml); foreach (XElement section in doc.Root.Elements()) { string sectionName = (string)section.Attribute("name"); string sectionId = (string)section.Attribute("ID"); if (section.Name.LocalName == "Section" && sectionName == "Documentation") { pageIdMap = new Dictionary <string, PageInfo>(); foreach (XElement page in section.Elements()) { string pageName = (string)page.Attribute("name"); Console.Write("Publishing " + pageName + "..."); string pageId = (string)page.Attribute("ID"); string fileName = directory + "\\" + pageName + ".mht"; PageInfo info = new PageInfo() { Name = pageName, Id = pageId, FileName = fileName }; pageIdMap[pageName] = info; if (File.Exists(fileName)) { File.Delete(fileName); } app.Publish(pageId, fileName, PublishFormat.pfMHTML, ""); Console.WriteLine("done"); } } } } } }
public OneNotePageIndexer() { lucene = new NetLuceneProvider(); string outputXML; oneNote.GetHierarchy(null, HierarchyScope.hsPages, out outputXML); allPageInfo = XDocument.Parse(outputXML); }
/// <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 string GetCurrentPageViewed() { string strXML; var xdoc = new XmlDocument(); var onApp = new OneNote.Application(); onApp.GetHierarchy(null, OneNote.HierarchyScope.hsPages, out strXML); // Load the xml into a document xdoc.LoadXml(strXML); string OneNoteNamespace = "http://schemas.microsoft.com/office/onenote/2007/onenote"; var nsmgr = new XmlNamespaceManager(xdoc.NameTable); nsmgr.AddNamespace("one", OneNoteNamespace); // Find the page ID of the active page XmlElement xmlActivePage = (XmlElement)xdoc.SelectSingleNode("//one:Page[@isCurrentlyViewed=\"true\"]", nsmgr) ?? ((XmlElement)xdoc.SelectSingleNode("//one:Section[@isCurrentlyViewed=\"true\"]", nsmgr) ?? (XmlElement)xdoc.SelectSingleNode("//one:SectionGroup[@isCurrentlyViewed=\"true\"]", nsmgr)); string strActivePageID = xmlActivePage != null?xmlActivePage.GetAttribute("ID") : null; return(strActivePageID); }
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); }
/* * Updates the notebook xml */ public void updateNotebookData() { Microsoft.Office.Interop.OneNote.Application onApplication = new Microsoft.Office.Interop.OneNote.Application(); onApplication.GetHierarchy(System.String.Empty, Microsoft.Office.Interop.OneNote.HierarchyScope.hsSections, out strXML); xmlDoc.LoadXml(strXML); }
private void update_xml() { string onenote_xml; m_OneNoteApp.GetHierarchy(null, HierarchyScope.hsPages, out onenote_xml); m_OneNote_XML = XDocument.Parse(onenote_xml); m_namespace = m_OneNote_XML.Root.Name.NamespaceName; }
private string EnumNotebooks() { string notebookXml; _oneNoteApp.GetHierarchy(null, OneNote.HierarchyScope.hsNotebooks, out notebookXml); var doc = XDocument.Parse(notebookXml); var ns = doc.Root.Name.Namespace; StringBuilder sb = new StringBuilder(); foreach (var notebookNode in from node in doc.Descendants(ns + "Notebook") select node) { sb.AppendLine(notebookNode.Attribute("name").Value); } return(sb.ToString()); }
/// <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()); } }
private void oneToMht() { Microsoft.Office.Interop.OneNote.Application onenoteApp = new Microsoft.Office.Interop.OneNote.Application(); string sectionId; onenoteApp.OpenHierarchy(srcPath, null, out sectionId); try { //타이틀(제목) 확인을 위한 xml 생성. string xml; XmlDocument document = new XmlDocument(); onenoteApp.GetHierarchy(sectionId, HierarchyScope.hsPages, out xml); document.LoadXml(xml); XmlNodeList xnList = document.GetElementsByTagName("one:Page"); //접근할 노드 string pageId = ""; foreach (XmlNode xn in xnList) { title = xn.Attributes["name"].Value; // get page title pageId = xn.Attributes["ID"].Value; //get page id } document.RemoveAll(); onenoteApp.GetPageContent(pageId, out xml, PageInfo.piAll); document.LoadXml(xml); /*xnList = document.GetElementsByTagName("one:OEChildren/one:T"); //접근할 노드 * * contents = xnList[0].InnerText; * * foreach (XmlNode xn in xnList) * { * title = xn.Attributes["name"].Value; // get page title * pageId = xn.Attributes["ID"].Value; //get page id * * }*/ //document.Save(@"c:\1111.xml"); onenoteApp.Publish(sectionId, dstPath, Microsoft.Office.Interop.OneNote.PublishFormat.pfMHTML, ""); } catch { return; } }
private void initializeNotebookXmlDoc() { string notebookNodeId = getNotebookNodeId(_onenoteApp, NotebookName); string hierarchyXml; _onenoteApp.GetHierarchy(notebookNodeId, OneNote.HierarchyScope.hsPages, out hierarchyXml); _notebookXmlDoc = new XmlDocument(); _notebookXmlDoc.LoadXml(hierarchyXml); _nsManager = new XmlNamespaceManager(_notebookXmlDoc.NameTable); _nsManager.AddNamespace(@"one", OneNoteXmlNamespace); }
private void InsertSnipIntoSelectedObject(string oneNoteObjectId) { try { string hierarchyXml; _oneNoteApp.GetHierarchy(oneNoteObjectId, OneNote.HierarchyScope.hsSelf, out hierarchyXml, _oneNoteXmlSchema); OneNoteEntity entity = _oneNoteXml.GetEntity(hierarchyXml); if (entity is OneNoteSection) { InsertImageIntoSection((OneNoteSection)entity, _imageFilePath, _publishUrl); } else if (entity is OneNotePage) { InsertImageIntoPage((OneNotePage)entity, _imageFilePath, _publishUrl); } } catch (Exception ex) { _insertException = ex; // will be reported in InsertSnip() after this fcn returns } }
private XNamespace m_namespace; // OneNote Name Space ,用得还是挺多的 public OneNoteOperation() { // 构造函数,初始化Application m_OneNoteApp = null; m_OneNote_XML = null; string onenote_xml; try{ m_OneNoteApp = new Microsoft.Office.Interop.OneNote.Application(); m_OneNoteApp.GetHierarchy(null, HierarchyScope.hsPages, out onenote_xml); m_OneNote_XML = XDocument.Parse(onenote_xml); m_namespace = m_OneNote_XML.Root.Name.NamespaceName; }catch { MessageBox.Show("没有安装OneNote吗?还是安装一下吧。"); m_OneNoteApp = null; m_OneNote_XML = null; } }
public bool InitializeDataSet(string fileName) { try { dsOneNote = new DataSet("OneNoteHierarchy"); var onApp = new OneNote.Application(); string strONXml; onApp.GetHierarchy(null, OneNote.HierarchyScope.hsPages, out strONXml); var srONXml = new StringReader(strONXml); dsOneNote.ReadXml(srONXml); workingSet = new WorkingSet(fileName); } catch (Exception) { MessageBox.Show("Error accessing OneNote. Please make sure you have OneNote installed.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); Application.Exit(); } return(true); }
private static string getNotebookNodeId(OneNote.Application onenoteApp, string notebookName) { string notebooksXml; onenoteApp.GetHierarchy(null, OneNote.HierarchyScope.hsNotebooks, out notebooksXml); XmlDocument xmlDoc = new XmlDocument(); xmlDoc.LoadXml(notebooksXml); XmlNamespaceManager nsManager = new XmlNamespaceManager(xmlDoc.NameTable); nsManager.AddNamespace(@"one", OneNoteXmlNamespace); string notebookXpath = getNotebookXpath(notebookName); XmlNode notebookNode = xmlDoc.SelectSingleNode(notebookXpath, nsManager); if (notebookNode == null) { throw new ArgumentException(string.Format(@"Can not found ""{0}"" as notebook name.", notebookName), @"notebookName"); } return(notebookNode.Attributes[@"ID"].Value); }
static void Main(string[] args) { OneNote.Application oneApp; // Obtain reference to OneNote application try { oneApp = new OneNote.Application(); } catch (Exception e) { Log.Error(string.Format("Could not obtain reference to OneNote ({0})", e.Message)); return; } // get till page level oneApp.GetHierarchy(null, OneNote.HierarchyScope.hsPages, out string outputXML); ONNotebookListing onListing = new ONNotebookListing(outputXML); if (Config.Current.ShowHelp || Config.Current.Arguments.Count == 0) { HelpHandler hh = new HelpHandler(); Log.Information(hh.Print()); return; } if (Config.Current.ListAllNotebook) { string[] notebookNames = onListing.ListAllNotebook(); foreach (var nb in notebookNames) { Console.WriteLine(nb); } return; } if (!string.IsNullOrEmpty(Config.Current.NotebookName)) { Log.Information("Query notebook information"); ONNotebook notebook = onListing.GetNotebook(Config.Current.NotebookName); if (notebook == null) { Log.Error("Cannot get desired notebook"); return; } Log.Information(string.Format("Notebook name: {0}", notebook.Name)); Log.Information(string.Format("Notebook ID: {0}", notebook.ID)); Log.Information(string.Format("Number section: {0}", notebook.Sections.Count)); Log.Information("Begin exporting ..."); Export2PDF export2PDF = new Export2PDF(); export2PDF.BasedPath = Config.Current.CacheFolder; export2PDF.OneNoteApplication = oneApp; export2PDF.CreateCacheFolder(notebook); if (Config.Current.ExportNotebook) { Log.Information(string.Format("Exporting entire notebook [{0}]", notebook.Name)); export2PDF.Export(Config.Current.OutputPath, notebook); } if (!string.IsNullOrEmpty(Config.Current.ExportSection)) { OneNote2PDF.Library.Data.ONSection section = notebook.GetSection(Config.Current.ExportSection); if (section == null) { Log.Error("Cannot find the specified section"); } else { Log.Information(string.Format("Exporting section [{0}] ...", section.Name)); export2PDF.Export(Config.Current.OutputPath, section); } } return; } }
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); }
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); } }
/// <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(""); } }
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); }
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 async void ExportTasks(IRibbonControl control) { Window context = control.Context as Window; CWin32WindowWrapper owner = new CWin32WindowWrapper((IntPtr)context.WindowHandle); 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; String link; onenote.GetHyperlinkToObject(thisPage, System.String.Empty, out link); String xmlNotebooks; onenote.GetHierarchy(null, Microsoft.Office.Interop.OneNote.HierarchyScope.hsPages, out xmlNotebooks); var notebooks = XDocument.Parse(xmlNotebooks); var currentbook = from item in notebooks.Descendants(notebooks.Root.Name.Namespace + "Notebook") where item.Attribute("ID").Value == thisNoteBook select item; var notebook = currentbook.First().Attribute("name").Value; String xmlPage; onenote.GetPageContent(thisPage, out xmlPage); doc = XDocument.Parse(xmlPage); ns = doc.Root.Name.Namespace; var pageTitle = RemoveHtmlTags(doc.Descendants(ns + "Title").First().Value); var title = notebook + ": " + pageTitle; var tags = from tagDef in doc.Descendants(ns + "TagDef") where tagDef.Attribute("symbol").Value == "3" select tagDef; if (tags.Count() == 0) { MessageBox.Show(owner, "No tasks found on this page!", pageTitle, MessageBoxButtons.OK, MessageBoxIcon.Exclamation); } else { var index = tags.First().Attribute("index").Value; string[] allTags = new string[2]; int i = 0; foreach (var tag in tags) { allTags[i] = tag.Attribute("index").Value; i++; } var tasks = from oe in doc.Descendants(ns + "OE") from item in oe.Elements(ns + "Tag") //where item.Attribute("index").Value == index where allTags.Contains(item.Attribute("index").Value) where item.Attribute("completed").Value == "false" select oe; if (tasks.Count() == 0) { MessageBox.Show(owner, "No tasks found on this page!", pageTitle, MessageBoxButtons.OK, MessageBoxIcon.Exclamation); return; } string allTasks = ""; string prefix = title; string formTitle = "Tasks found: " + tasks.Count().ToString(); if (prefix.Length > 60) { prefix = prefix.Substring(0, 60); } int counter = 0; foreach (var task in tasks) { counter++; allTasks += "o " + prefix + "\n " + RemoveHtmlTags(task.Element(ns + "T").Value) + "\n\n"; if (counter > 4) { break; } } string taskas = RemoveHtmlTags(tasks.ElementAt(0).Value); LoginForm login = new LoginForm(); login.ShowDialog(owner); if (login.DialogResult == DialogResult.OK) { ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls; ITodoistTokenlessClient tokenlessClient = new TodoistTokenlessClient(); try { if (login.email.Contains("@") == false) { login.email += "@ardi.lt"; } ITodoistClient client = await tokenlessClient.LoginAsync(login.email, login.password); var projects = await client.Projects.GetAsync(); TasksForm confirm = new TasksForm(formTitle, title, prefix, taskas, projects); confirm.ShowDialog(owner); if (confirm.DialogResult == DialogResult.OK) { var transaction = client.CreateTransaction(); if (confirm.id > 0) { foreach (var item in projects) { if (item.Name == confirm.project) { foreach (var task in tasks) { var content = "[" + confirm.prefix + RemoveHtmlTags(task.Value) + "](" + link + ")"; var todo = new Todoist.Net.Models.Item(content); todo.ProjectId = item.Id; var taskId = await transaction.Items.AddAsync(todo); } } } } else { var projectId = await transaction.Project.AddAsync(new Todoist.Net.Models.Project(confirm.project)); foreach (var task in tasks) { var content = "[" + confirm.prefix + RemoveHtmlTags(task.Value) + "](" + link + ")"; var taskId = await transaction.Items.AddAsync(new Todoist.Net.Models.Item(content, projectId)); //await transaction.Notes.AddToItemAsync(new Todoist.Net.Models.Note("Task description"), taskId); } } await transaction.CommitAsync(); System.Diagnostics.Process.Start("https://todoist.com"); } confirm.Dispose(); confirm = null; } catch { MessageBox.Show(owner, "Bad user mail or password...", "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error); } } login.Dispose(); login = null; } }
public static List <TaskItem> ReadTaskList(string notebook, string section, string page) { List <TaskItem> taskList = new List <TaskItem>(); 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(taskList); } 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 = System.Xml.Linq.XDocument.Parse(pageXml); Dictionary <int, TaskItemClass> TagDefsDic = new Dictionary <int, TaskItemClass>(); var tagDefs = pageDoc.Descendants(ns + "TagDef"); foreach (var tagDef in tagDefs) { TaskItemClass ti = new TaskItemClass(); int value = 0; int.TryParse(tagDef.Attribute("index").Value, out value); ti.Index = value; ti.Name = tagDef.Attribute("name").Value; ti.Color = tagDef.Attribute("fontColor").Value; TagDefsDic.Add(ti.Index, ti); } 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[] cellValues = new string[5]; int index = 0; string strTaskId = ""; bool bTaskComplete = false; int tagDefIndex = -1; foreach (var taskCell in from cells in taskRow.Descendants(ns + "Cell") select cells) { if (index == 0) { var taskId = taskCell.Descendants(ns + "OutlookTask").FirstOrDefault(); if (taskId == null) { break; } strTaskId = taskId.Attribute("guidTask").Value; bTaskComplete = (taskId.Attribute("completed").Value == "true"); if (string.IsNullOrEmpty(strTaskId)) { break; } // Get TagDef var taskTag = taskCell.Descendants(ns + "Tag").FirstOrDefault(); if (taskTag != null) { int.TryParse(taskTag.Attribute("index").Value, out tagDefIndex); } } cellValues[index++] = NoHtml(taskCell.Value);//taskCell.Descendants(ns + "T").First().Value; } if (string.IsNullOrEmpty(strTaskId)) { continue; } // 新建任务 TaskItem newTask = new TaskItem(); newTask.NoteBookId = notebookNode.Attribute("ID").Value; newTask.NoteBookName = notebookNode.Attribute("name").Value; newTask.SectionId = sectionNode.Attribute("ID").Value; newTask.SectionName = sectionNode.Attribute("name").Value; newTask.PageId = pageNode.Attribute("ID").Value; newTask.PageName = pageNode.Attribute("name").Value; newTask.TaskOneNoteId = strTaskId; newTask.TaskComplete = bTaskComplete; newTask.TaskName = cellValues[0]; int value = 0; int.TryParse(cellValues[1], out value); newTask.TaskTimeEdit = value; value = 0; int.TryParse(cellValues[2], out value); newTask.TaskTimeUsage = value; value = 0; int.TryParse(cellValues[3], out value); newTask.TaskTimeInterrupt = value; newTask.TaskComment = cellValues[4]; if (tagDefIndex != -1) { newTask.TaskClass = TagDefsDic[tagDefIndex]; } taskList.Add(newTask); } } } } } return(taskList); }