Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

HelperFunctions.cs 30KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Globalization;
  4. using System.IO;
  5. using System.IO.Compression;
  6. using System.IO.Packaging;
  7. using System.Linq;
  8. using System.Reflection;
  9. using System.Security.Principal;
  10. using System.Text;
  11. using System.Xml.Linq;
  12. using System.Xml;
  13. namespace Novacode
  14. {
  15. internal static class HelperFunctions
  16. {
  17. public const string DOCUMENT_DOCUMENTTYPE = "application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml";
  18. public const string TEMPLATE_DOCUMENTTYPE = "application/vnd.openxmlformats-officedocument.wordprocessingml.template.main+xml";
  19. public static bool IsNullOrWhiteSpace(this string value)
  20. {
  21. if (value == null) return true;
  22. return string.IsNullOrEmpty(value.Trim());
  23. }
  24. /// <summary>
  25. /// Checks whether 'toCheck' has all children that 'desired' has and values of 'val' attributes are the same
  26. /// </summary>
  27. /// <param name="desired"></param>
  28. /// <param name="toCheck"></param>
  29. /// <param name="fo">Matching options whether check if desired attributes are inder a, or a has exactly and only these attributes as b has.</param>
  30. /// <returns></returns>
  31. internal static bool ContainsEveryChildOf(XElement desired, XElement toCheck, MatchFormattingOptions fo)
  32. {
  33. foreach (XElement e in desired.Elements())
  34. {
  35. // If a formatting property has the same name and 'val' attribute's value, its considered to be equivalent.
  36. if (!toCheck.Elements(e.Name).Where(bElement => bElement.GetAttribute(XName.Get("val", DocX.w.NamespaceName)) == e.GetAttribute(XName.Get("val", DocX.w.NamespaceName))).Any())
  37. return false;
  38. }
  39. // If the formatting has to be exact, no additionaly formatting must exist.
  40. if (fo == MatchFormattingOptions.ExactMatch)
  41. return desired.Elements().Count() == toCheck.Elements().Count();
  42. return true;
  43. }
  44. internal static void CreateRelsPackagePart(DocX Document, Uri uri)
  45. {
  46. PackagePart pp = Document.package.CreatePart(uri, "application/vnd.openxmlformats-package.relationships+xml", CompressionOption.Maximum);
  47. using (TextWriter tw = new StreamWriter(pp.GetStream()))
  48. {
  49. XDocument d = new XDocument
  50. (
  51. new XDeclaration("1.0", "UTF-8", "yes"),
  52. new XElement(XName.Get("Relationships", DocX.rel.NamespaceName))
  53. );
  54. var root = d.Root;
  55. d.Save(tw);
  56. }
  57. }
  58. internal static int GetSize(XElement Xml)
  59. {
  60. switch (Xml.Name.LocalName)
  61. {
  62. case "tab":
  63. return 1;
  64. case "br":
  65. return 1;
  66. case "t":
  67. goto case "delText";
  68. case "delText":
  69. return Xml.Value.Length;
  70. case "tr":
  71. goto case "br";
  72. case "tc":
  73. goto case "br";
  74. default:
  75. return 0;
  76. }
  77. }
  78. internal static string GetText(XElement e)
  79. {
  80. StringBuilder sb = new StringBuilder();
  81. GetTextRecursive(e, ref sb);
  82. return sb.ToString();
  83. }
  84. internal static void GetTextRecursive(XElement Xml, ref StringBuilder sb)
  85. {
  86. sb.Append(ToText(Xml));
  87. if (Xml.HasElements)
  88. foreach (XElement e in Xml.Elements())
  89. GetTextRecursive(e, ref sb);
  90. }
  91. internal static List<FormattedText> GetFormattedText(XElement e)
  92. {
  93. List<FormattedText> alist = new List<FormattedText>();
  94. GetFormattedTextRecursive(e, ref alist);
  95. return alist;
  96. }
  97. internal static void GetFormattedTextRecursive(XElement Xml, ref List<FormattedText> alist)
  98. {
  99. FormattedText ft = ToFormattedText(Xml);
  100. FormattedText last = null;
  101. if (ft != null)
  102. {
  103. if (alist.Count() > 0)
  104. last = alist.Last();
  105. if (last != null && last.CompareTo(ft) == 0)
  106. {
  107. // Update text of last entry.
  108. last.text += ft.text;
  109. }
  110. else
  111. {
  112. if (last != null)
  113. ft.index = last.index + last.text.Length;
  114. alist.Add(ft);
  115. }
  116. }
  117. if (Xml.HasElements)
  118. foreach (XElement e in Xml.Elements())
  119. GetFormattedTextRecursive(e, ref alist);
  120. }
  121. internal static FormattedText ToFormattedText(XElement e)
  122. {
  123. // The text representation of e.
  124. String text = ToText(e);
  125. if (text == String.Empty)
  126. return null;
  127. // e is a w:t element, it must exist inside a w:r element or a w:tabs, lets climb until we find it.
  128. while (!e.Name.Equals(XName.Get("r", DocX.w.NamespaceName)) &&
  129. !e.Name.Equals(XName.Get("tabs", DocX.w.NamespaceName)))
  130. e = e.Parent;
  131. // e is a w:r element, lets find the rPr element.
  132. XElement rPr = e.Element(XName.Get("rPr", DocX.w.NamespaceName));
  133. FormattedText ft = new FormattedText();
  134. ft.text = text;
  135. ft.index = 0;
  136. ft.formatting = null;
  137. // Return text with formatting.
  138. if (rPr != null)
  139. ft.formatting = Formatting.Parse(rPr);
  140. return ft;
  141. }
  142. internal static string ToText(XElement e)
  143. {
  144. switch (e.Name.LocalName)
  145. {
  146. case "tab":
  147. return "\t";
  148. case "br":
  149. return "\n";
  150. case "t":
  151. goto case "delText";
  152. case "delText":
  153. {
  154. if (e.Parent != null && e.Parent.Name.LocalName == "r")
  155. {
  156. XElement run = e.Parent;
  157. var rPr = run.Elements().FirstOrDefault(a => a.Name.LocalName == "rPr");
  158. if (rPr != null)
  159. {
  160. var caps = rPr.Elements().FirstOrDefault(a => a.Name.LocalName == "caps");
  161. if (caps != null)
  162. return e.Value.ToUpper();
  163. }
  164. }
  165. return e.Value;
  166. }
  167. case "tr":
  168. goto case "br";
  169. case "tc":
  170. goto case "tab";
  171. default: return "";
  172. }
  173. }
  174. internal static XElement CloneElement(XElement element)
  175. {
  176. return new XElement
  177. (
  178. element.Name,
  179. element.Attributes(),
  180. element.Nodes().Select
  181. (
  182. n =>
  183. {
  184. XElement e = n as XElement;
  185. if (e != null)
  186. return CloneElement(e);
  187. return n;
  188. }
  189. )
  190. );
  191. }
  192. internal static PackagePart CreateOrGetSettingsPart(Package package)
  193. {
  194. PackagePart settingsPart;
  195. Uri settingsUri = new Uri("/word/settings.xml", UriKind.Relative);
  196. if (!package.PartExists(settingsUri))
  197. {
  198. settingsPart = package.CreatePart(settingsUri, "application/vnd.openxmlformats-officedocument.wordprocessingml.settings+xml", CompressionOption.Maximum);
  199. PackagePart mainDocumentPart = package.GetParts().Single(p => p.ContentType.Equals(DOCUMENT_DOCUMENTTYPE, StringComparison.CurrentCultureIgnoreCase) ||
  200. p.ContentType.Equals(TEMPLATE_DOCUMENTTYPE, StringComparison.CurrentCultureIgnoreCase));
  201. mainDocumentPart.CreateRelationship(settingsUri, TargetMode.Internal, "http://schemas.openxmlformats.org/officeDocument/2006/relationships/settings");
  202. XDocument settings = XDocument.Parse
  203. (@"<?xml version='1.0' encoding='utf-8' standalone='yes'?>
  204. <w:settings xmlns:o='urn:schemas-microsoft-com:office:office' xmlns:r='http://schemas.openxmlformats.org/officeDocument/2006/relationships' xmlns:m='http://schemas.openxmlformats.org/officeDocument/2006/math' xmlns:v='urn:schemas-microsoft-com:vml' xmlns:w10='urn:schemas-microsoft-com:office:word' xmlns:w='http://schemas.openxmlformats.org/wordprocessingml/2006/main' xmlns:sl='http://schemas.openxmlformats.org/schemaLibrary/2006/main'>
  205. <w:zoom w:percent='100' />
  206. <w:defaultTabStop w:val='720' />
  207. <w:characterSpacingControl w:val='doNotCompress' />
  208. <w:compat />
  209. <w:rsids>
  210. <w:rsidRoot w:val='00217F62' />
  211. <w:rsid w:val='001915A3' />
  212. <w:rsid w:val='00217F62' />
  213. <w:rsid w:val='00A906D8' />
  214. <w:rsid w:val='00AB5A74' />
  215. <w:rsid w:val='00F071AE' />
  216. </w:rsids>
  217. <m:mathPr>
  218. <m:mathFont m:val='Cambria Math' />
  219. <m:brkBin m:val='before' />
  220. <m:brkBinSub m:val='--' />
  221. <m:smallFrac m:val='off' />
  222. <m:dispDef />
  223. <m:lMargin m:val='0' />
  224. <m:rMargin m:val='0' />
  225. <m:defJc m:val='centerGroup' />
  226. <m:wrapIndent m:val='1440' />
  227. <m:intLim m:val='subSup' />
  228. <m:naryLim m:val='undOvr' />
  229. </m:mathPr>
  230. <w:themeFontLang w:val='en-IE' w:bidi='ar-SA' />
  231. <w:clrSchemeMapping w:bg1='light1' w:t1='dark1' w:bg2='light2' w:t2='dark2' w:accent1='accent1' w:accent2='accent2' w:accent3='accent3' w:accent4='accent4' w:accent5='accent5' w:accent6='accent6' w:hyperlink='hyperlink' w:followedHyperlink='followedHyperlink' />
  232. <w:shapeDefaults>
  233. <o:shapedefaults v:ext='edit' spidmax='2050' />
  234. <o:shapelayout v:ext='edit'>
  235. <o:idmap v:ext='edit' data='1' />
  236. </o:shapelayout>
  237. </w:shapeDefaults>
  238. <w:decimalSymbol w:val='.' />
  239. <w:listSeparator w:val=',' />
  240. </w:settings>"
  241. );
  242. XElement themeFontLang = settings.Root.Element(XName.Get("themeFontLang", DocX.w.NamespaceName));
  243. themeFontLang.SetAttributeValue(XName.Get("val", DocX.w.NamespaceName), CultureInfo.CurrentCulture);
  244. // Save the settings document.
  245. using (TextWriter tw = new StreamWriter(settingsPart.GetStream()))
  246. settings.Save(tw);
  247. }
  248. else
  249. settingsPart = package.GetPart(settingsUri);
  250. return settingsPart;
  251. }
  252. internal static void CreateCustomPropertiesPart(DocX document)
  253. {
  254. PackagePart customPropertiesPart = document.package.CreatePart(new Uri("/docProps/custom.xml", UriKind.Relative), "application/vnd.openxmlformats-officedocument.custom-properties+xml", CompressionOption.Maximum);
  255. XDocument customPropDoc = new XDocument
  256. (
  257. new XDeclaration("1.0", "UTF-8", "yes"),
  258. new XElement
  259. (
  260. XName.Get("Properties", DocX.customPropertiesSchema.NamespaceName),
  261. new XAttribute(XNamespace.Xmlns + "vt", DocX.customVTypesSchema)
  262. )
  263. );
  264. using (TextWriter tw = new StreamWriter(customPropertiesPart.GetStream(FileMode.Create, FileAccess.Write)))
  265. customPropDoc.Save(tw, SaveOptions.None);
  266. document.package.CreateRelationship(customPropertiesPart.Uri, TargetMode.Internal, "http://schemas.openxmlformats.org/officeDocument/2006/relationships/custom-properties");
  267. }
  268. internal static XDocument DecompressXMLResource(string manifest_resource_name)
  269. {
  270. // XDocument to load the compressed Xml resource into.
  271. XDocument document;
  272. // Get a reference to the executing assembly.
  273. Assembly assembly = Assembly.GetExecutingAssembly();
  274. // Open a Stream to the embedded resource.
  275. Stream stream = assembly.GetManifestResourceStream(manifest_resource_name);
  276. // Decompress the embedded resource.
  277. using (GZipStream zip = new GZipStream(stream, CompressionMode.Decompress))
  278. {
  279. // Load this decompressed embedded resource into an XDocument using a TextReader.
  280. using (TextReader sr = new StreamReader(zip))
  281. {
  282. document = XDocument.Load(sr);
  283. }
  284. }
  285. // Return the decompressed Xml as an XDocument.
  286. return document;
  287. }
  288. /// <summary>
  289. /// If this document does not contain a /word/numbering.xml add the default one generated by Microsoft Word
  290. /// when the default bullet, numbered and multilevel lists are added to a blank document
  291. /// </summary>
  292. /// <param name="package"></param>
  293. /// <param name="mainDocumentPart"></param>
  294. /// <returns></returns>
  295. internal static XDocument AddDefaultNumberingXml(Package package)
  296. {
  297. XDocument numberingDoc;
  298. // Create the main document part for this package
  299. PackagePart wordNumbering = package.CreatePart(new Uri("/word/numbering.xml", UriKind.Relative), "application/vnd.openxmlformats-officedocument.wordprocessingml.numbering+xml", CompressionOption.Maximum);
  300. numberingDoc = DecompressXMLResource("Novacode.Resources.numbering.xml.gz");
  301. // Save /word/numbering.xml
  302. using (TextWriter tw = new StreamWriter(wordNumbering.GetStream(FileMode.Create, FileAccess.Write)))
  303. numberingDoc.Save(tw, SaveOptions.None);
  304. PackagePart mainDocumentPart = package.GetParts().Single(p => p.ContentType.Equals(DOCUMENT_DOCUMENTTYPE, StringComparison.CurrentCultureIgnoreCase) ||
  305. p.ContentType.Equals(TEMPLATE_DOCUMENTTYPE, StringComparison.CurrentCultureIgnoreCase));
  306. mainDocumentPart.CreateRelationship(wordNumbering.Uri, TargetMode.Internal, "http://schemas.openxmlformats.org/officeDocument/2006/relationships/numbering");
  307. return numberingDoc;
  308. }
  309. /// <summary>
  310. /// If this document does not contain a /word/styles.xml add the default one generated by Microsoft Word.
  311. /// </summary>
  312. /// <param name="package"></param>
  313. /// <param name="mainDocumentPart"></param>
  314. /// <returns></returns>
  315. internal static XDocument AddDefaultStylesXml(Package package)
  316. {
  317. XDocument stylesDoc;
  318. // Create the main document part for this package
  319. PackagePart word_styles = package.CreatePart(new Uri("/word/styles.xml", UriKind.Relative), "application/vnd.openxmlformats-officedocument.wordprocessingml.styles+xml", CompressionOption.Maximum);
  320. stylesDoc = HelperFunctions.DecompressXMLResource("Novacode.Resources.default_styles.xml.gz");
  321. XElement lang = stylesDoc.Root.Element(XName.Get("docDefaults", DocX.w.NamespaceName)).Element(XName.Get("rPrDefault", DocX.w.NamespaceName)).Element(XName.Get("rPr", DocX.w.NamespaceName)).Element(XName.Get("lang", DocX.w.NamespaceName));
  322. lang.SetAttributeValue(XName.Get("val", DocX.w.NamespaceName), CultureInfo.CurrentCulture);
  323. // Save /word/styles.xml
  324. using (TextWriter tw = new StreamWriter(word_styles.GetStream(FileMode.Create, FileAccess.Write)))
  325. stylesDoc.Save(tw, SaveOptions.None);
  326. PackagePart mainDocumentPart = package.GetParts().Where
  327. (
  328. p => p.ContentType.Equals(DOCUMENT_DOCUMENTTYPE, StringComparison.CurrentCultureIgnoreCase)||p.ContentType.Equals(TEMPLATE_DOCUMENTTYPE, StringComparison.CurrentCultureIgnoreCase)
  329. ).Single();
  330. mainDocumentPart.CreateRelationship(word_styles.Uri, TargetMode.Internal, "http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles");
  331. return stylesDoc;
  332. }
  333. internal static XElement CreateEdit(EditType t, DateTime edit_time, object content)
  334. {
  335. if (t == EditType.del)
  336. {
  337. foreach (object o in (IEnumerable<XElement>)content)
  338. {
  339. if (o is XElement)
  340. {
  341. XElement e = (o as XElement);
  342. IEnumerable<XElement> ts = e.DescendantsAndSelf(XName.Get("t", DocX.w.NamespaceName));
  343. for (int i = 0; i < ts.Count(); i++)
  344. {
  345. XElement text = ts.ElementAt(i);
  346. text.ReplaceWith(new XElement(DocX.w + "delText", text.Attributes(), text.Value));
  347. }
  348. }
  349. }
  350. }
  351. return
  352. (
  353. new XElement(DocX.w + t.ToString(),
  354. new XAttribute(DocX.w + "id", 0),
  355. new XAttribute(DocX.w + "author", WindowsIdentity.GetCurrent().Name),
  356. new XAttribute(DocX.w + "date", edit_time),
  357. content)
  358. );
  359. }
  360. internal static XElement CreateTable(int rowCount, int columnCount)
  361. {
  362. int[] columnWidths = new int[columnCount];
  363. for (int i = 0; i < columnCount; i++)
  364. {
  365. columnWidths[i] = 2310;
  366. }
  367. return CreateTable(rowCount, columnWidths);
  368. }
  369. internal static XElement CreateTable(int rowCount, int[] columnWidths)
  370. {
  371. XElement newTable =
  372. new XElement
  373. (
  374. XName.Get("tbl", DocX.w.NamespaceName),
  375. new XElement
  376. (
  377. XName.Get("tblPr", DocX.w.NamespaceName),
  378. new XElement(XName.Get("tblStyle", DocX.w.NamespaceName), new XAttribute(XName.Get("val", DocX.w.NamespaceName), "TableGrid")),
  379. new XElement(XName.Get("tblW", DocX.w.NamespaceName), new XAttribute(XName.Get("w", DocX.w.NamespaceName), "5000"), new XAttribute(XName.Get("type", DocX.w.NamespaceName), "auto")),
  380. new XElement(XName.Get("tblLook", DocX.w.NamespaceName), new XAttribute(XName.Get("val", DocX.w.NamespaceName), "04A0"))
  381. )
  382. );
  383. XElement tableGrid = new XElement(XName.Get("tblGrid", DocX.w.NamespaceName));
  384. for (int i = 0; i < columnWidths.Length; i++)
  385. tableGrid.Add(new XElement(XName.Get("gridCol", DocX.w.NamespaceName), new XAttribute(XName.Get("w", DocX.w.NamespaceName), XmlConvert.ToString(columnWidths[i]))));
  386. newTable.Add(tableGrid);
  387. for (int i = 0; i < rowCount; i++)
  388. {
  389. XElement row = new XElement(XName.Get("tr", DocX.w.NamespaceName));
  390. for (int j = 0; j < columnWidths.Length; j++)
  391. {
  392. XElement cell = CreateTableCell();
  393. row.Add(cell);
  394. }
  395. newTable.Add(row);
  396. }
  397. return newTable;
  398. }
  399. /// <summary>
  400. /// Create and return a cell of a table
  401. /// </summary>
  402. internal static XElement CreateTableCell()
  403. {
  404. return new XElement
  405. (
  406. XName.Get("tc", DocX.w.NamespaceName),
  407. new XElement(XName.Get("tcPr", DocX.w.NamespaceName),
  408. new XElement(XName.Get("tcW", DocX.w.NamespaceName),
  409. new XAttribute(XName.Get("w", DocX.w.NamespaceName), "2310"),
  410. new XAttribute(XName.Get("type", DocX.w.NamespaceName), "dxa"))),
  411. new XElement(XName.Get("p", DocX.w.NamespaceName),
  412. new XElement(XName.Get("pPr", DocX.w.NamespaceName)))
  413. );
  414. }
  415. internal static List CreateItemInList(List list, string listText, int level = 0, ListItemType listType = ListItemType.Numbered, int? startNumber = null, bool trackChanges = false)
  416. {
  417. if (list.NumId == 0)
  418. {
  419. list.CreateNewNumberingNumId(level, listType);
  420. }
  421. if (!string.IsNullOrEmpty(listText))
  422. {
  423. var newParagraphSection = new XElement
  424. (
  425. XName.Get("p", DocX.w.NamespaceName),
  426. new XElement(XName.Get("pPr", DocX.w.NamespaceName),
  427. new XElement(XName.Get("numPr", DocX.w.NamespaceName),
  428. new XElement(XName.Get("ilvl", DocX.w.NamespaceName), new XAttribute(DocX.w + "val", level)),
  429. new XElement(XName.Get("numId", DocX.w.NamespaceName), new XAttribute(DocX.w + "val", list.NumId)))),
  430. new XElement(XName.Get("r", DocX.w.NamespaceName), new XElement(XName.Get("t", DocX.w.NamespaceName), listText))
  431. );
  432. if (trackChanges)
  433. newParagraphSection = CreateEdit(EditType.ins, DateTime.Now, newParagraphSection);
  434. if (startNumber == null)
  435. {
  436. list.AddItem(new Paragraph(list.Document, newParagraphSection, 0, ContainerType.Paragraph));
  437. }
  438. else
  439. {
  440. list.AddItemWithStartValue(new Paragraph(list.Document, newParagraphSection, 0, ContainerType.Paragraph), (int)startNumber);
  441. }
  442. }
  443. return list;
  444. }
  445. internal static void RenumberIDs(DocX document)
  446. {
  447. IEnumerable<XAttribute> trackerIDs =
  448. (from d in document.mainDoc.Descendants()
  449. where d.Name.LocalName == "ins" || d.Name.LocalName == "del"
  450. select d.Attribute(XName.Get("id", "http://schemas.openxmlformats.org/wordprocessingml/2006/main")));
  451. for (int i = 0; i < trackerIDs.Count(); i++)
  452. trackerIDs.ElementAt(i).Value = i.ToString();
  453. }
  454. internal static Paragraph GetFirstParagraphEffectedByInsert(DocX document, int index)
  455. {
  456. // This document contains no Paragraphs and insertion is at index 0
  457. if (document.paragraphLookup.Keys.Count() == 0 && index == 0)
  458. return null;
  459. foreach (int paragraphEndIndex in document.paragraphLookup.Keys)
  460. {
  461. if (paragraphEndIndex >= index)
  462. return document.paragraphLookup[paragraphEndIndex];
  463. }
  464. throw new ArgumentOutOfRangeException();
  465. }
  466. internal static List<XElement> FormatInput(string text, XElement rPr)
  467. {
  468. List<XElement> newRuns = new List<XElement>();
  469. XElement tabRun = new XElement(DocX.w + "tab");
  470. XElement breakRun = new XElement(DocX.w + "br");
  471. StringBuilder sb = new StringBuilder();
  472. if (string.IsNullOrEmpty(text))
  473. {
  474. return newRuns; //I dont wanna get an exception if text == null, so just return empy list
  475. }
  476. foreach (char c in text)
  477. {
  478. switch (c)
  479. {
  480. case '\t':
  481. if (sb.Length > 0)
  482. {
  483. XElement t = new XElement(DocX.w + "t", sb.ToString());
  484. Novacode.Text.PreserveSpace(t);
  485. newRuns.Add(new XElement(DocX.w + "r", rPr, t));
  486. sb = new StringBuilder();
  487. }
  488. newRuns.Add(new XElement(DocX.w + "r", rPr, tabRun));
  489. break;
  490. case '\n':
  491. if (sb.Length > 0)
  492. {
  493. XElement t = new XElement(DocX.w + "t", sb.ToString());
  494. Novacode.Text.PreserveSpace(t);
  495. newRuns.Add(new XElement(DocX.w + "r", rPr, t));
  496. sb = new StringBuilder();
  497. }
  498. newRuns.Add(new XElement(DocX.w + "r", rPr, breakRun));
  499. break;
  500. default:
  501. sb.Append(c);
  502. break;
  503. }
  504. }
  505. if (sb.Length > 0)
  506. {
  507. XElement t = new XElement(DocX.w + "t", sb.ToString());
  508. Novacode.Text.PreserveSpace(t);
  509. newRuns.Add(new XElement(DocX.w + "r", rPr, t));
  510. }
  511. return newRuns;
  512. }
  513. internal static XElement[] SplitParagraph(Paragraph p, int index)
  514. {
  515. // In this case edit dosent really matter, you have a choice.
  516. Run r = p.GetFirstRunEffectedByEdit(index, EditType.ins);
  517. XElement[] split;
  518. XElement before, after;
  519. if (r.Xml.Parent.Name.LocalName == "ins")
  520. {
  521. split = p.SplitEdit(r.Xml.Parent, index, EditType.ins);
  522. before = new XElement(p.Xml.Name, p.Xml.Attributes(), r.Xml.Parent.ElementsBeforeSelf(), split[0]);
  523. after = new XElement(p.Xml.Name, p.Xml.Attributes(), r.Xml.Parent.ElementsAfterSelf(), split[1]);
  524. }
  525. else if (r.Xml.Parent.Name.LocalName == "del")
  526. {
  527. split = p.SplitEdit(r.Xml.Parent, index, EditType.del);
  528. before = new XElement(p.Xml.Name, p.Xml.Attributes(), r.Xml.Parent.ElementsBeforeSelf(), split[0]);
  529. after = new XElement(p.Xml.Name, p.Xml.Attributes(), r.Xml.Parent.ElementsAfterSelf(), split[1]);
  530. }
  531. else
  532. {
  533. split = Run.SplitRun(r, index);
  534. before = new XElement(p.Xml.Name, p.Xml.Attributes(), r.Xml.ElementsBeforeSelf(), split[0]);
  535. after = new XElement(p.Xml.Name, p.Xml.Attributes(), split[1], r.Xml.ElementsAfterSelf());
  536. }
  537. if (before.Elements().Count() == 0)
  538. before = null;
  539. if (after.Elements().Count() == 0)
  540. after = null;
  541. return new XElement[] { before, after };
  542. }
  543. /// <!--
  544. /// Bug found and fixed by trnilse. To see the change,
  545. /// please compare this release to the previous release using TFS compare.
  546. /// -->
  547. internal static bool IsSameFile(Stream streamOne, Stream streamTwo)
  548. {
  549. int file1byte, file2byte;
  550. if (streamOne.Length != streamOne.Length)
  551. {
  552. // Return false to indicate files are different
  553. return false;
  554. }
  555. // Read and compare a byte from each file until either a
  556. // non-matching set of bytes is found or until the end of
  557. // file1 is reached.
  558. do
  559. {
  560. // Read one byte from each file.
  561. file1byte = streamOne.ReadByte();
  562. file2byte = streamTwo.ReadByte();
  563. }
  564. while ((file1byte == file2byte) && (file1byte != -1));
  565. // Return the success of the comparison. "file1byte" is
  566. // equal to "file2byte" at this point only if the files are
  567. // the same.
  568. streamOne.Position = 0;
  569. streamTwo.Position = 0;
  570. return ((file1byte - file2byte) == 0);
  571. }
  572. internal static UnderlineStyle GetUnderlineStyle(string underlineStyle)
  573. {
  574. switch (underlineStyle)
  575. {
  576. case "single":
  577. return UnderlineStyle.singleLine;
  578. case "double":
  579. return UnderlineStyle.doubleLine;
  580. case "thick":
  581. return UnderlineStyle.thick;
  582. case "dotted":
  583. return UnderlineStyle.dotted;
  584. case "dottedHeavy":
  585. return UnderlineStyle.dottedHeavy;
  586. case "dash":
  587. return UnderlineStyle.dash;
  588. case "dashedHeavy":
  589. return UnderlineStyle.dashedHeavy;
  590. case "dashLong":
  591. return UnderlineStyle.dashLong;
  592. case "dashLongHeavy":
  593. return UnderlineStyle.dashLongHeavy;
  594. case "dotDash":
  595. return UnderlineStyle.dotDash;
  596. case "dashDotHeavy":
  597. return UnderlineStyle.dashDotHeavy;
  598. case "dotDotDash":
  599. return UnderlineStyle.dotDotDash;
  600. case "dashDotDotHeavy":
  601. return UnderlineStyle.dashDotDotHeavy;
  602. case "wave":
  603. return UnderlineStyle.wave;
  604. case "wavyHeavy":
  605. return UnderlineStyle.wavyHeavy;
  606. case "wavyDouble":
  607. return UnderlineStyle.wavyDouble;
  608. case "words":
  609. return UnderlineStyle.words;
  610. default:
  611. return UnderlineStyle.none;
  612. }
  613. }
  614. }
  615. }