You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

HelperFunctions.cs 31KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729
  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(new PackagePartStream(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(new PackagePartStream(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(new PackagePartStream(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. /// <returns></returns>
  294. internal static XDocument AddDefaultNumberingXml(Package package)
  295. {
  296. XDocument numberingDoc;
  297. // Create the main document part for this package
  298. PackagePart wordNumbering = package.CreatePart(new Uri("/word/numbering.xml", UriKind.Relative), "application/vnd.openxmlformats-officedocument.wordprocessingml.numbering+xml", CompressionOption.Maximum);
  299. numberingDoc = DecompressXMLResource("Novacode.Resources.numbering.xml.gz");
  300. // Save /word/numbering.xml
  301. using (TextWriter tw = new StreamWriter(new PackagePartStream(wordNumbering.GetStream(FileMode.Create, FileAccess.Write))))
  302. numberingDoc.Save(tw, SaveOptions.None);
  303. PackagePart mainDocumentPart = package.GetParts().Single(p => p.ContentType.Equals(DOCUMENT_DOCUMENTTYPE, StringComparison.CurrentCultureIgnoreCase) ||
  304. p.ContentType.Equals(TEMPLATE_DOCUMENTTYPE, StringComparison.CurrentCultureIgnoreCase));
  305. mainDocumentPart.CreateRelationship(wordNumbering.Uri, TargetMode.Internal, "http://schemas.openxmlformats.org/officeDocument/2006/relationships/numbering");
  306. return numberingDoc;
  307. }
  308. /// <summary>
  309. /// If this document does not contain a /word/styles.xml add the default one generated by Microsoft Word.
  310. /// </summary>
  311. /// <param name="package"></param>
  312. /// <returns></returns>
  313. internal static XDocument AddDefaultStylesXml(Package package)
  314. {
  315. XDocument stylesDoc;
  316. // Create the main document part for this package
  317. PackagePart word_styles = package.CreatePart(new Uri("/word/styles.xml", UriKind.Relative), "application/vnd.openxmlformats-officedocument.wordprocessingml.styles+xml", CompressionOption.Maximum);
  318. stylesDoc = HelperFunctions.DecompressXMLResource("Novacode.Resources.default_styles.xml.gz");
  319. 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));
  320. lang.SetAttributeValue(XName.Get("val", DocX.w.NamespaceName), CultureInfo.CurrentCulture);
  321. // Save /word/styles.xml
  322. using (TextWriter tw = new StreamWriter(new PackagePartStream(word_styles.GetStream(FileMode.Create, FileAccess.Write))))
  323. stylesDoc.Save(tw, SaveOptions.None);
  324. PackagePart mainDocumentPart = package.GetParts().Where
  325. (
  326. p => p.ContentType.Equals(DOCUMENT_DOCUMENTTYPE, StringComparison.CurrentCultureIgnoreCase)||p.ContentType.Equals(TEMPLATE_DOCUMENTTYPE, StringComparison.CurrentCultureIgnoreCase)
  327. ).Single();
  328. mainDocumentPart.CreateRelationship(word_styles.Uri, TargetMode.Internal, "http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles");
  329. return stylesDoc;
  330. }
  331. internal static XElement CreateEdit(EditType t, DateTime edit_time, object content)
  332. {
  333. if (t == EditType.del)
  334. {
  335. foreach (object o in (IEnumerable<XElement>)content)
  336. {
  337. if (o is XElement)
  338. {
  339. XElement e = (o as XElement);
  340. IEnumerable<XElement> ts = e.DescendantsAndSelf(XName.Get("t", DocX.w.NamespaceName));
  341. for (int i = 0; i < ts.Count(); i++)
  342. {
  343. XElement text = ts.ElementAt(i);
  344. text.ReplaceWith(new XElement(DocX.w + "delText", text.Attributes(), text.Value));
  345. }
  346. }
  347. }
  348. }
  349. return
  350. (
  351. new XElement(DocX.w + t.ToString(),
  352. new XAttribute(DocX.w + "id", 0),
  353. new XAttribute(DocX.w + "author", WindowsIdentity.GetCurrent().Name),
  354. new XAttribute(DocX.w + "date", edit_time),
  355. content)
  356. );
  357. }
  358. internal static XElement CreateTable(int rowCount, int columnCount)
  359. {
  360. int[] columnWidths = new int[columnCount];
  361. for (int i = 0; i < columnCount; i++)
  362. {
  363. columnWidths[i] = 2310;
  364. }
  365. return CreateTable(rowCount, columnWidths);
  366. }
  367. internal static XElement CreateTable(int rowCount, int[] columnWidths)
  368. {
  369. XElement newTable =
  370. new XElement
  371. (
  372. XName.Get("tbl", DocX.w.NamespaceName),
  373. new XElement
  374. (
  375. XName.Get("tblPr", DocX.w.NamespaceName),
  376. new XElement(XName.Get("tblStyle", DocX.w.NamespaceName), new XAttribute(XName.Get("val", DocX.w.NamespaceName), "TableGrid")),
  377. 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")),
  378. new XElement(XName.Get("tblLook", DocX.w.NamespaceName), new XAttribute(XName.Get("val", DocX.w.NamespaceName), "04A0"))
  379. )
  380. );
  381. /*XElement tableGrid = new XElement(XName.Get("tblGrid", DocX.w.NamespaceName));
  382. for (int i = 0; i < columnWidths.Length; i++)
  383. tableGrid.Add(new XElement(XName.Get("gridCol", DocX.w.NamespaceName), new XAttribute(XName.Get("w", DocX.w.NamespaceName), XmlConvert.ToString(columnWidths[i]))));
  384. newTable.Add(tableGrid);*/
  385. for (int i = 0; i < rowCount; i++)
  386. {
  387. XElement row = new XElement(XName.Get("tr", DocX.w.NamespaceName));
  388. for (int j = 0; j < columnWidths.Length; j++)
  389. {
  390. XElement cell = CreateTableCell();
  391. row.Add(cell);
  392. }
  393. newTable.Add(row);
  394. }
  395. return newTable;
  396. }
  397. /// <summary>
  398. /// Create and return a cell of a table
  399. /// </summary>
  400. internal static XElement CreateTableCell(double w = 2310)
  401. {
  402. return new XElement
  403. (
  404. XName.Get("tc", DocX.w.NamespaceName),
  405. new XElement(XName.Get("tcPr", DocX.w.NamespaceName),
  406. new XElement(XName.Get("tcW", DocX.w.NamespaceName),
  407. new XAttribute(XName.Get("w", DocX.w.NamespaceName), w),
  408. new XAttribute(XName.Get("type", DocX.w.NamespaceName), "dxa"))),
  409. new XElement(XName.Get("p", DocX.w.NamespaceName),
  410. new XElement(XName.Get("pPr", DocX.w.NamespaceName)))
  411. );
  412. }
  413. internal static List CreateItemInList(List list, string listText, int level = 0, ListItemType listType = ListItemType.Numbered, int? startNumber = null, bool trackChanges = false, bool continueNumbering = false)
  414. {
  415. if (list.NumId == 0)
  416. {
  417. list.CreateNewNumberingNumId(level, listType, startNumber, continueNumbering);
  418. }
  419. if (listText != null) //I see no reason why you shouldn't be able to insert an empty element. It simplifies tasks such as populating an item from html.
  420. {
  421. var newParagraphSection = new XElement
  422. (
  423. XName.Get("p", DocX.w.NamespaceName),
  424. new XElement(XName.Get("pPr", DocX.w.NamespaceName),
  425. new XElement(XName.Get("numPr", DocX.w.NamespaceName),
  426. new XElement(XName.Get("ilvl", DocX.w.NamespaceName), new XAttribute(DocX.w + "val", level)),
  427. new XElement(XName.Get("numId", DocX.w.NamespaceName), new XAttribute(DocX.w + "val", list.NumId)))),
  428. new XElement(XName.Get("r", DocX.w.NamespaceName), new XElement(XName.Get("t", DocX.w.NamespaceName), listText))
  429. );
  430. if (trackChanges)
  431. newParagraphSection = CreateEdit(EditType.ins, DateTime.Now, newParagraphSection);
  432. if (startNumber == null)
  433. {
  434. list.AddItem(new Paragraph(list.Document, newParagraphSection, 0, ContainerType.Paragraph));
  435. }
  436. else
  437. {
  438. list.AddItemWithStartValue(new Paragraph(list.Document, newParagraphSection, 0, ContainerType.Paragraph), (int)startNumber);
  439. }
  440. }
  441. return list;
  442. }
  443. internal static void RenumberIDs(DocX document)
  444. {
  445. IEnumerable<XAttribute> trackerIDs =
  446. (from d in document.mainDoc.Descendants()
  447. where d.Name.LocalName == "ins" || d.Name.LocalName == "del"
  448. select d.Attribute(XName.Get("id", "http://schemas.openxmlformats.org/wordprocessingml/2006/main")));
  449. for (int i = 0; i < trackerIDs.Count(); i++)
  450. trackerIDs.ElementAt(i).Value = i.ToString();
  451. }
  452. internal static Paragraph GetFirstParagraphEffectedByInsert(DocX document, int index)
  453. {
  454. // This document contains no Paragraphs and insertion is at index 0
  455. if (document.paragraphLookup.Keys.Count() == 0 && index == 0)
  456. return null;
  457. foreach (int paragraphEndIndex in document.paragraphLookup.Keys)
  458. {
  459. if (paragraphEndIndex >= index)
  460. return document.paragraphLookup[paragraphEndIndex];
  461. }
  462. throw new ArgumentOutOfRangeException();
  463. }
  464. internal static List<XElement> FormatInput(string text, XElement rPr)
  465. {
  466. List<XElement> newRuns = new List<XElement>();
  467. XElement tabRun = new XElement(DocX.w + "tab");
  468. XElement breakRun = new XElement(DocX.w + "br");
  469. StringBuilder sb = new StringBuilder();
  470. if (string.IsNullOrEmpty(text))
  471. {
  472. return newRuns; //I dont wanna get an exception if text == null, so just return empy list
  473. }
  474. char lastChar = '\0';
  475. foreach (char c in text)
  476. {
  477. switch (c)
  478. {
  479. case '\t':
  480. if (sb.Length > 0)
  481. {
  482. XElement t = new XElement(DocX.w + "t", sb.ToString());
  483. Novacode.Text.PreserveSpace(t);
  484. newRuns.Add(new XElement(DocX.w + "r", rPr, t));
  485. sb = new StringBuilder();
  486. }
  487. newRuns.Add(new XElement(DocX.w + "r", rPr, tabRun));
  488. break;
  489. case '\r':
  490. if (sb.Length > 0)
  491. {
  492. XElement t = new XElement(DocX.w + "t", sb.ToString());
  493. Novacode.Text.PreserveSpace(t);
  494. newRuns.Add(new XElement(DocX.w + "r", rPr, t));
  495. sb = new StringBuilder();
  496. }
  497. newRuns.Add(new XElement(DocX.w + "r", rPr, breakRun));
  498. break;
  499. case '\n':
  500. if (lastChar == '\r') break;
  501. if (sb.Length > 0)
  502. {
  503. XElement t = new XElement(DocX.w + "t", sb.ToString());
  504. Novacode.Text.PreserveSpace(t);
  505. newRuns.Add(new XElement(DocX.w + "r", rPr, t));
  506. sb = new StringBuilder();
  507. }
  508. newRuns.Add(new XElement(DocX.w + "r", rPr, breakRun));
  509. break;
  510. default:
  511. sb.Append(c);
  512. break;
  513. }
  514. lastChar = c;
  515. }
  516. if (sb.Length > 0)
  517. {
  518. XElement t = new XElement(DocX.w + "t", sb.ToString());
  519. Novacode.Text.PreserveSpace(t);
  520. newRuns.Add(new XElement(DocX.w + "r", rPr, t));
  521. }
  522. return newRuns;
  523. }
  524. internal static XElement[] SplitParagraph(Paragraph p, int index)
  525. {
  526. // In this case edit dosent really matter, you have a choice.
  527. Run r = p.GetFirstRunEffectedByEdit(index, EditType.ins);
  528. XElement[] split;
  529. XElement before, after;
  530. if (r.Xml.Parent.Name.LocalName == "ins")
  531. {
  532. split = p.SplitEdit(r.Xml.Parent, index, EditType.ins);
  533. before = new XElement(p.Xml.Name, p.Xml.Attributes(), r.Xml.Parent.ElementsBeforeSelf(), split[0]);
  534. after = new XElement(p.Xml.Name, p.Xml.Attributes(), r.Xml.Parent.ElementsAfterSelf(), split[1]);
  535. }
  536. else if (r.Xml.Parent.Name.LocalName == "del")
  537. {
  538. split = p.SplitEdit(r.Xml.Parent, index, EditType.del);
  539. before = new XElement(p.Xml.Name, p.Xml.Attributes(), r.Xml.Parent.ElementsBeforeSelf(), split[0]);
  540. after = new XElement(p.Xml.Name, p.Xml.Attributes(), r.Xml.Parent.ElementsAfterSelf(), split[1]);
  541. }
  542. else
  543. {
  544. split = Run.SplitRun(r, index);
  545. before = new XElement(p.Xml.Name, p.Xml.Attributes(), r.Xml.ElementsBeforeSelf(), split[0]);
  546. after = new XElement(p.Xml.Name, p.Xml.Attributes(), split[1], r.Xml.ElementsAfterSelf());
  547. }
  548. if (before.Elements().Count() == 0)
  549. before = null;
  550. if (after.Elements().Count() == 0)
  551. after = null;
  552. return new XElement[] { before, after };
  553. }
  554. /// <!--
  555. /// Bug found and fixed by trnilse. To see the change,
  556. /// please compare this release to the previous release using TFS compare.
  557. /// -->
  558. internal static bool IsSameFile(Stream streamOne, Stream streamTwo)
  559. {
  560. int file1byte, file2byte;
  561. if (streamOne.Length != streamTwo.Length)
  562. {
  563. // Return false to indicate files are different
  564. return false;
  565. }
  566. // Read and compare a byte from each file until either a
  567. // non-matching set of bytes is found or until the end of
  568. // file1 is reached.
  569. do
  570. {
  571. // Read one byte from each file.
  572. file1byte = streamOne.ReadByte();
  573. file2byte = streamTwo.ReadByte();
  574. }
  575. while ((file1byte == file2byte) && (file1byte != -1));
  576. // Return the success of the comparison. "file1byte" is
  577. // equal to "file2byte" at this point only if the files are
  578. // the same.
  579. streamOne.Position = 0;
  580. streamTwo.Position = 0;
  581. return ((file1byte - file2byte) == 0);
  582. }
  583. internal static UnderlineStyle GetUnderlineStyle(string underlineStyle)
  584. {
  585. switch (underlineStyle)
  586. {
  587. case "single":
  588. return UnderlineStyle.singleLine;
  589. case "double":
  590. return UnderlineStyle.doubleLine;
  591. case "thick":
  592. return UnderlineStyle.thick;
  593. case "dotted":
  594. return UnderlineStyle.dotted;
  595. case "dottedHeavy":
  596. return UnderlineStyle.dottedHeavy;
  597. case "dash":
  598. return UnderlineStyle.dash;
  599. case "dashedHeavy":
  600. return UnderlineStyle.dashedHeavy;
  601. case "dashLong":
  602. return UnderlineStyle.dashLong;
  603. case "dashLongHeavy":
  604. return UnderlineStyle.dashLongHeavy;
  605. case "dotDash":
  606. return UnderlineStyle.dotDash;
  607. case "dashDotHeavy":
  608. return UnderlineStyle.dashDotHeavy;
  609. case "dotDotDash":
  610. return UnderlineStyle.dotDotDash;
  611. case "dashDotDotHeavy":
  612. return UnderlineStyle.dashDotDotHeavy;
  613. case "wave":
  614. return UnderlineStyle.wave;
  615. case "wavyHeavy":
  616. return UnderlineStyle.wavyHeavy;
  617. case "wavyDouble":
  618. return UnderlineStyle.wavyDouble;
  619. case "words":
  620. return UnderlineStyle.words;
  621. default:
  622. return UnderlineStyle.none;
  623. }
  624. }
  625. }
  626. }