您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

HelperFunctions.cs 30KB

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