Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

DocXUnitTests.cs 136KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978
  1. using System;
  2. using Novacode;
  3. using System.IO;
  4. using System.Linq;
  5. using System.Drawing;
  6. using System.Xml.Linq;
  7. using System.Reflection;
  8. using System.Collections.Generic;
  9. using System.Text.RegularExpressions;
  10. using NUnit.Framework;
  11. using System.Collections.ObjectModel;
  12. using System.Xml;
  13. using Formatting = Novacode.Formatting;
  14. namespace UnitTests
  15. {
  16. /// <summary>
  17. /// Summary description for DocXUnitTest
  18. /// </summary>
  19. [TestFixture]
  20. public class DocXUnitTests
  21. {
  22. private readonly string _directoryDocuments;
  23. private readonly string _directoryWithFiles;
  24. private static Border BlankBorder = new Border(BorderStyle.Tcbs_none, 0, 0, Color.White);
  25. const string package_part_document = "/word/document.xml";
  26. public DocXUnitTests()
  27. {
  28. _directoryDocuments = Path.Combine(Path.GetTempPath(), "DocXTests", "documents");
  29. Setup(_directoryDocuments); // prepare temp documents directory
  30. _directoryWithFiles = TestHelper.DirectoryWithFiles;
  31. }
  32. private static void Setup(string path)
  33. {
  34. if (!Directory.Exists(path))
  35. {
  36. Directory.CreateDirectory(path);
  37. }
  38. }
  39. [Test]
  40. public void LargeTable()
  41. {
  42. using (var output = File.Open(Path.Combine(_directoryWithFiles, "LargeTable.docx"), FileMode.Create))
  43. {
  44. using (var doc = DocX.Create(output))
  45. {
  46. var tbl = doc.InsertTable(1, 18);
  47. var wholeWidth = doc.PageWidth - doc.MarginLeft - doc.MarginRight;
  48. var colWidth = wholeWidth / tbl.ColumnCount;
  49. var colWidths = new int[tbl.ColumnCount];
  50. tbl.AutoFit = AutoFit.Contents;
  51. var r = tbl.Rows[0];
  52. var cx = 0;
  53. foreach (var cell in r.Cells)
  54. {
  55. cell.Paragraphs.First().Append("Col " + cx);
  56. //cell.Width = colWidth;
  57. cell.MarginBottom = 0;
  58. cell.MarginLeft = 0;
  59. cell.MarginRight = 0;
  60. cell.MarginTop = 0;
  61. cx++;
  62. }
  63. tbl.SetBorder(TableBorderType.Bottom, BlankBorder);
  64. tbl.SetBorder(TableBorderType.Left, BlankBorder);
  65. tbl.SetBorder(TableBorderType.Right, BlankBorder);
  66. tbl.SetBorder(TableBorderType.Top, BlankBorder);
  67. tbl.SetBorder(TableBorderType.InsideV, BlankBorder);
  68. tbl.SetBorder(TableBorderType.InsideH, BlankBorder);
  69. doc.Save();
  70. }
  71. }
  72. }
  73. [Test]
  74. public void TableWithSpecifiedWidths()
  75. {
  76. using (var output = File.Open(Path.Combine(_directoryWithFiles, "TableSpecifiedWidths.docx"), FileMode.Create))
  77. {
  78. using (var doc = DocX.Create(output))
  79. {
  80. var widths = new float[] { 200f, 100f, 300f };
  81. var tbl = doc.InsertTable(1, widths.Length);
  82. tbl.SetWidths(widths);
  83. var wholeWidth = doc.PageWidth - doc.MarginLeft - doc.MarginRight;
  84. tbl.AutoFit = AutoFit.Contents;
  85. var r = tbl.Rows[0];
  86. var cx = 0;
  87. foreach (var cell in r.Cells)
  88. {
  89. cell.Paragraphs.First().Append("Col " + cx);
  90. //cell.Width = colWidth;
  91. cell.MarginBottom = 0;
  92. cell.MarginLeft = 0;
  93. cell.MarginRight = 0;
  94. cell.MarginTop = 0;
  95. cx++;
  96. }
  97. //add new rows
  98. for (var x = 0; x < 5; x++)
  99. {
  100. r = tbl.InsertRow();
  101. cx = 0;
  102. foreach (var cell in r.Cells)
  103. {
  104. cell.Paragraphs.First().Append("Col " + cx);
  105. //cell.Width = colWidth;
  106. cell.MarginBottom = 0;
  107. cell.MarginLeft = 0;
  108. cell.MarginRight = 0;
  109. cell.MarginTop = 0;
  110. cx++;
  111. }
  112. }
  113. tbl.SetBorder(TableBorderType.Bottom, BlankBorder);
  114. tbl.SetBorder(TableBorderType.Left, BlankBorder);
  115. tbl.SetBorder(TableBorderType.Right, BlankBorder);
  116. tbl.SetBorder(TableBorderType.Top, BlankBorder);
  117. tbl.SetBorder(TableBorderType.InsideV, BlankBorder);
  118. tbl.SetBorder(TableBorderType.InsideH, BlankBorder);
  119. doc.Save();
  120. }
  121. }
  122. }
  123. [Test]
  124. public void TestPatternFuncReplacement()
  125. {
  126. }
  127. public string ReplaceFunc(string findStr)
  128. {
  129. Dictionary<string, string> testPatterns = new Dictionary<string, string>()
  130. {
  131. {"COURT NAME","Fred Frump"},
  132. {"Case Number","cr-md-2011-1234567"}
  133. };
  134. if (testPatterns.ContainsKey(findStr))
  135. {
  136. return testPatterns[findStr];
  137. }
  138. return findStr;
  139. }
  140. [Test]
  141. public void RegexTest()
  142. {
  143. var findPattern = "<(.*?)>";
  144. var sample = "<Match This> text";
  145. var matchCollection = Regex.Matches(sample, findPattern, RegexOptions.IgnoreCase);
  146. int i = 1;
  147. }
  148. [Test]
  149. public void Test_Pattern_Replacement()
  150. {
  151. Dictionary<string, string> testPatterns = new Dictionary<string, string>()
  152. {
  153. {"COURT NAME","Fred Frump"},
  154. {"Case Number","cr-md-2011-1234567"}
  155. };
  156. using (DocX replaceDoc = DocX.Load(Path.Combine(_directoryWithFiles, "ReplaceTests.docx")))
  157. {
  158. foreach (var t in replaceDoc.Tables)
  159. { // each table has 1 row and 3 columns
  160. Assert.IsTrue(t.Rows[0].Cells.Count == 3);
  161. Assert.IsTrue(t.ColumnCount == 3);
  162. Assert.IsTrue(t.Rows.Count == 1);
  163. Assert.IsTrue(t.RowCount == 1);
  164. }
  165. // Make sure the origional strings are in the document.
  166. Assert.IsTrue(replaceDoc.FindAll("<COURT NAME>").Count == 2);
  167. Assert.IsTrue(replaceDoc.FindAll("<Case Number>").Count == 2);
  168. // There are only two patterns, even though each pattern is used more than once
  169. Assert.IsTrue(replaceDoc.FindUniqueByPattern(@"<[\w \=]{4,}>", RegexOptions.IgnoreCase).Count == 2);
  170. // Make sure the new strings are not in the document.
  171. Assert.IsTrue(replaceDoc.FindAll("Fred Frump").Count == 0);
  172. Assert.IsTrue(replaceDoc.FindAll("cr-md-2011-1234567").Count == 0);
  173. // Do the replacing
  174. foreach (var p in testPatterns)
  175. {
  176. replaceDoc.ReplaceText("<(.*?)>", ReplaceFunc, false, RegexOptions.IgnoreCase);
  177. //replaceDoc.ReplaceText("<" + p.Key + ">", p.Value, false, RegexOptions.IgnoreCase);
  178. }
  179. // Make sure the origional string are no longer in the document.
  180. Assert.IsTrue(replaceDoc.FindAll("<COURT NAME>").Count == 0);
  181. Assert.IsTrue(replaceDoc.FindAll("<Case Number>").Count == 0);
  182. // Make sure the new strings are now in the document.
  183. Assert.IsTrue(replaceDoc.FindAll("FRED FRUMP").Count == 2);
  184. Assert.IsTrue(replaceDoc.FindAll("cr-md-2011-1234567").Count == 2);
  185. // Make sure the replacement worked.
  186. Assert.IsTrue(replaceDoc.Text == "\t\t\t\t\t\t\t\t\t\t\t\t\t\tThese two tables should look identical:\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tSTATE OF IOWA,\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tPlaintiff,\t\t\t\t\t\t\t\t\t\t\t\t\t\tvs.\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tFRED FRUMP,\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tDefendant.\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tCase No.: cr-md-2011-1234567\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tORDER SETTING ASIDE DEFAULT JUDGMENT\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tSTATE OF IOWA,\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tPlaintiff,\t\t\t\t\t\t\t\t\t\t\t\t\t\tvs.\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tFRED FRUMP,\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tDefendant.\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tCase No.: cr-md-2011-1234567\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tORDER SETTING ASIDE DEFAULT JUDGMENT\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t");
  187. }
  188. }
  189. [Test]
  190. public void Test_CustomProperty_Add()
  191. {
  192. // Load a document.
  193. using (DocX document = DocX.Create("CustomProperty_Add.docx"))
  194. {
  195. Assert.IsTrue(document.CustomProperties.Count == 0);
  196. document.AddCustomProperty(new CustomProperty("fname", "cathal"));
  197. Assert.IsTrue(document.CustomProperties.Count == 1);
  198. Assert.IsTrue(document.CustomProperties.ContainsKey("fname"));
  199. Assert.IsTrue((String)document.CustomProperties["fname"].Value == "cathal");
  200. document.AddCustomProperty(new CustomProperty("age", 24));
  201. Assert.IsTrue(document.CustomProperties.Count == 2);
  202. Assert.IsTrue(document.CustomProperties.ContainsKey("age"));
  203. Assert.IsTrue((int)document.CustomProperties["age"].Value == 24);
  204. document.AddCustomProperty(new CustomProperty("male", true));
  205. Assert.IsTrue(document.CustomProperties.Count == 3);
  206. Assert.IsTrue(document.CustomProperties.ContainsKey("male"));
  207. Assert.IsTrue((bool)document.CustomProperties["male"].Value == true);
  208. document.AddCustomProperty(new CustomProperty("newyear2012", new DateTime(2012, 1, 1)));
  209. Assert.IsTrue(document.CustomProperties.Count == 4);
  210. Assert.IsTrue(document.CustomProperties.ContainsKey("newyear2012"));
  211. Assert.IsTrue((DateTime)document.CustomProperties["newyear2012"].Value == new DateTime(2012, 1, 1));
  212. document.AddCustomProperty(new CustomProperty("fav_num", 3.141592));
  213. Assert.IsTrue(document.CustomProperties.Count == 5);
  214. Assert.IsTrue(document.CustomProperties.ContainsKey("fav_num"));
  215. Assert.IsTrue((double)document.CustomProperties["fav_num"].Value == 3.141592);
  216. }
  217. }
  218. [Test]
  219. public void Test_EverybodyHasAHome_Loaded()
  220. {
  221. // Load a document.
  222. using (DocX document = DocX.Load(Path.Combine(_directoryWithFiles, "EverybodyHasAHome.docx")))
  223. {
  224. // Main document tests.
  225. string document_xml_file = document.mainPart.Uri.OriginalString;
  226. Assert.IsTrue(document.Paragraphs[0].mainPart.Uri.OriginalString.Equals(document_xml_file));
  227. Assert.IsTrue(document.Tables[0].mainPart.Uri.OriginalString.Equals(document_xml_file));
  228. Assert.IsTrue(document.Tables[0].Rows[0].mainPart.Uri.OriginalString.Equals(document_xml_file));
  229. Assert.IsTrue(document.Tables[0].Rows[0].Cells[0].mainPart.Uri.OriginalString.Equals(document_xml_file));
  230. Assert.IsTrue(document.Tables[0].Rows[0].Cells[0].Paragraphs[0].mainPart.Uri.OriginalString.Equals(document_xml_file));
  231. // header first
  232. Header header_first = document.Headers.first;
  233. string header_first_xml_file = header_first.mainPart.Uri.OriginalString;
  234. Assert.IsTrue(header_first.Paragraphs[0].mainPart.Uri.OriginalString.Equals(header_first_xml_file));
  235. Assert.IsTrue(header_first.Tables[0].mainPart.Uri.OriginalString.Equals(header_first_xml_file));
  236. Assert.IsTrue(header_first.Tables[0].Rows[0].mainPart.Uri.OriginalString.Equals(header_first_xml_file));
  237. Assert.IsTrue(header_first.Tables[0].Rows[0].Cells[0].mainPart.Uri.OriginalString.Equals(header_first_xml_file));
  238. Assert.IsTrue(header_first.Tables[0].Rows[0].Cells[0].Paragraphs[0].mainPart.Uri.OriginalString.Equals(header_first_xml_file));
  239. // header odd
  240. Header header_odd = document.Headers.odd;
  241. string header_odd_xml_file = header_odd.mainPart.Uri.OriginalString;
  242. Assert.IsTrue(header_odd.mainPart.Uri.OriginalString.Equals(header_odd_xml_file));
  243. Assert.IsTrue(header_odd.Paragraphs[0].mainPart.Uri.OriginalString.Equals(header_odd_xml_file));
  244. Assert.IsTrue(header_odd.Tables[0].mainPart.Uri.OriginalString.Equals(header_odd_xml_file));
  245. Assert.IsTrue(header_odd.Tables[0].Rows[0].mainPart.Uri.OriginalString.Equals(header_odd_xml_file));
  246. Assert.IsTrue(header_odd.Tables[0].Rows[0].Cells[0].mainPart.Uri.OriginalString.Equals(header_odd_xml_file));
  247. Assert.IsTrue(header_odd.Tables[0].Rows[0].Cells[0].Paragraphs[0].mainPart.Uri.OriginalString.Equals(header_odd_xml_file));
  248. // header even
  249. Header header_even = document.Headers.even;
  250. string header_even_xml_file = header_even.mainPart.Uri.OriginalString;
  251. Assert.IsTrue(header_even.mainPart.Uri.OriginalString.Equals(header_even_xml_file));
  252. Assert.IsTrue(header_even.Paragraphs[0].mainPart.Uri.OriginalString.Equals(header_even_xml_file));
  253. Assert.IsTrue(header_even.Tables[0].mainPart.Uri.OriginalString.Equals(header_even_xml_file));
  254. Assert.IsTrue(header_even.Tables[0].Rows[0].mainPart.Uri.OriginalString.Equals(header_even_xml_file));
  255. Assert.IsTrue(header_even.Tables[0].Rows[0].Cells[0].mainPart.Uri.OriginalString.Equals(header_even_xml_file));
  256. Assert.IsTrue(header_even.Tables[0].Rows[0].Cells[0].Paragraphs[0].mainPart.Uri.OriginalString.Equals(header_even_xml_file));
  257. // footer first
  258. Footer footer_first = document.Footers.first;
  259. string footer_first_xml_file = footer_first.mainPart.Uri.OriginalString;
  260. Assert.IsTrue(footer_first.mainPart.Uri.OriginalString.Equals(footer_first_xml_file));
  261. Assert.IsTrue(footer_first.Paragraphs[0].mainPart.Uri.OriginalString.Equals(footer_first_xml_file));
  262. Assert.IsTrue(footer_first.Tables[0].mainPart.Uri.OriginalString.Equals(footer_first_xml_file));
  263. Assert.IsTrue(footer_first.Tables[0].Rows[0].mainPart.Uri.OriginalString.Equals(footer_first_xml_file));
  264. Assert.IsTrue(footer_first.Tables[0].Rows[0].Cells[0].mainPart.Uri.OriginalString.Equals(footer_first_xml_file));
  265. Assert.IsTrue(footer_first.Tables[0].Rows[0].Cells[0].Paragraphs[0].mainPart.Uri.OriginalString.Equals(footer_first_xml_file));
  266. // footer odd
  267. Footer footer_odd = document.Footers.odd;
  268. string footer_odd_xml_file = footer_odd.mainPart.Uri.OriginalString;
  269. Assert.IsTrue(footer_odd.mainPart.Uri.OriginalString.Equals(footer_odd_xml_file));
  270. Assert.IsTrue(footer_odd.Paragraphs[0].mainPart.Uri.OriginalString.Equals(footer_odd_xml_file));
  271. Assert.IsTrue(footer_odd.Tables[0].mainPart.Uri.OriginalString.Equals(footer_odd_xml_file));
  272. Assert.IsTrue(footer_odd.Tables[0].Rows[0].mainPart.Uri.OriginalString.Equals(footer_odd_xml_file));
  273. Assert.IsTrue(footer_odd.Tables[0].Rows[0].Cells[0].mainPart.Uri.OriginalString.Equals(footer_odd_xml_file));
  274. Assert.IsTrue(footer_odd.Tables[0].Rows[0].Cells[0].Paragraphs[0].mainPart.Uri.OriginalString.Equals(footer_odd_xml_file));
  275. // footer even
  276. Footer footer_even = document.Footers.even;
  277. string footer_even_xml_file = footer_even.mainPart.Uri.OriginalString;
  278. Assert.IsTrue(footer_even.mainPart.Uri.OriginalString.Equals(footer_even_xml_file));
  279. Assert.IsTrue(footer_even.Paragraphs[0].mainPart.Uri.OriginalString.Equals(footer_even_xml_file));
  280. Assert.IsTrue(footer_even.Tables[0].mainPart.Uri.OriginalString.Equals(footer_even_xml_file));
  281. Assert.IsTrue(footer_even.Tables[0].Rows[0].mainPart.Uri.OriginalString.Equals(footer_even_xml_file));
  282. Assert.IsTrue(footer_even.Tables[0].Rows[0].Cells[0].mainPart.Uri.OriginalString.Equals(footer_even_xml_file));
  283. Assert.IsTrue(footer_even.Tables[0].Rows[0].Cells[0].Paragraphs[0].mainPart.Uri.OriginalString.Equals(footer_even_xml_file));
  284. }
  285. }
  286. [Test]
  287. public void Test_Insert_Picture_ParagraphBeforeSelf()
  288. {
  289. // Create test document.
  290. using (DocX document = DocX.Create(Path.Combine(_directoryDocuments, "Test.docx")))
  291. {
  292. // Add an Image to this document.
  293. Novacode.Image img = document.AddImage(Path.Combine(_directoryWithFiles, "purple.png"));
  294. // Create a Picture from this Image.
  295. Picture pic = img.CreatePicture();
  296. Assert.IsNotNull(pic);
  297. // Main document.
  298. Paragraph p0 = document.InsertParagraph("Hello");
  299. Paragraph p1 = p0.InsertParagraphBeforeSelf("again");
  300. p1.InsertPicture(pic, 3);
  301. // Save this document.
  302. document.Save();
  303. }
  304. }
  305. [Test]
  306. public void Test_Insert_Picture_ParagraphAfterSelf()
  307. {
  308. // Create test document.
  309. using (DocX document = DocX.Create(Path.Combine(_directoryDocuments, "Test.docx")))
  310. {
  311. // Add an Image to this document.
  312. Novacode.Image img = document.AddImage(Path.Combine(_directoryWithFiles, "purple.png"));
  313. // Create a Picture from this Image.
  314. Picture pic = img.CreatePicture();
  315. Assert.IsNotNull(pic);
  316. // Main document.
  317. Paragraph p0 = document.InsertParagraph("Hello");
  318. Paragraph p1 = p0.InsertParagraphAfterSelf("again");
  319. p1.InsertPicture(pic, 3);
  320. // Save this document.
  321. document.Save();
  322. }
  323. }
  324. [Test]
  325. public void Test_EverybodyHasAHome_Created()
  326. {
  327. // Create a new document.
  328. using (DocX document = DocX.Create("Test.docx"))
  329. {
  330. // Create a Table.
  331. Table t = document.AddTable(3, 3);
  332. t.Design = TableDesign.TableGrid;
  333. // Insert a Paragraph and a Table into the main document.
  334. document.InsertParagraph();
  335. document.InsertTable(t);
  336. // Insert a Paragraph and a Table into every Header.
  337. document.AddHeaders();
  338. document.Headers.odd.InsertParagraph();
  339. document.Headers.odd.InsertTable(t);
  340. document.Headers.even.InsertParagraph();
  341. document.Headers.even.InsertTable(t);
  342. document.Headers.first.InsertParagraph();
  343. document.Headers.first.InsertTable(t);
  344. // Insert a Paragraph and a Table into every Footer.
  345. document.AddFooters();
  346. document.Footers.odd.InsertParagraph();
  347. document.Footers.odd.InsertTable(t);
  348. document.Footers.even.InsertParagraph();
  349. document.Footers.even.InsertTable(t);
  350. document.Footers.first.InsertParagraph();
  351. document.Footers.first.InsertTable(t);
  352. // Main document tests.
  353. string document_xml_file = document.mainPart.Uri.OriginalString;
  354. Assert.IsTrue(document.Paragraphs[0].mainPart.Uri.OriginalString.Equals(document_xml_file));
  355. Assert.IsTrue(document.Tables[0].mainPart.Uri.OriginalString.Equals(document_xml_file));
  356. Assert.IsTrue(document.Tables[0].Rows[0].mainPart.Uri.OriginalString.Equals(document_xml_file));
  357. Assert.IsTrue(document.Tables[0].Rows[0].Cells[0].mainPart.Uri.OriginalString.Equals(document_xml_file));
  358. Assert.IsTrue(document.Tables[0].Rows[0].Cells[0].Paragraphs[0].mainPart.Uri.OriginalString.Equals(document_xml_file));
  359. // header first
  360. Header header_first = document.Headers.first;
  361. string header_first_xml_file = header_first.mainPart.Uri.OriginalString;
  362. Assert.IsTrue(header_first.Paragraphs[0].mainPart.Uri.OriginalString.Equals(header_first_xml_file));
  363. Assert.IsTrue(header_first.Tables[0].mainPart.Uri.OriginalString.Equals(header_first_xml_file));
  364. Assert.IsTrue(header_first.Tables[0].Rows[0].mainPart.Uri.OriginalString.Equals(header_first_xml_file));
  365. Assert.IsTrue(header_first.Tables[0].Rows[0].Cells[0].mainPart.Uri.OriginalString.Equals(header_first_xml_file));
  366. Assert.IsTrue(header_first.Tables[0].Rows[0].Cells[0].Paragraphs[0].mainPart.Uri.OriginalString.Equals(header_first_xml_file));
  367. // header odd
  368. Header header_odd = document.Headers.odd;
  369. string header_odd_xml_file = header_odd.mainPart.Uri.OriginalString;
  370. Assert.IsTrue(header_odd.mainPart.Uri.OriginalString.Equals(header_odd_xml_file));
  371. Assert.IsTrue(header_odd.Paragraphs[0].mainPart.Uri.OriginalString.Equals(header_odd_xml_file));
  372. Assert.IsTrue(header_odd.Tables[0].mainPart.Uri.OriginalString.Equals(header_odd_xml_file));
  373. Assert.IsTrue(header_odd.Tables[0].Rows[0].mainPart.Uri.OriginalString.Equals(header_odd_xml_file));
  374. Assert.IsTrue(header_odd.Tables[0].Rows[0].Cells[0].mainPart.Uri.OriginalString.Equals(header_odd_xml_file));
  375. Assert.IsTrue(header_odd.Tables[0].Rows[0].Cells[0].Paragraphs[0].mainPart.Uri.OriginalString.Equals(header_odd_xml_file));
  376. // header even
  377. Header header_even = document.Headers.even;
  378. string header_even_xml_file = header_even.mainPart.Uri.OriginalString;
  379. Assert.IsTrue(header_even.mainPart.Uri.OriginalString.Equals(header_even_xml_file));
  380. Assert.IsTrue(header_even.Paragraphs[0].mainPart.Uri.OriginalString.Equals(header_even_xml_file));
  381. Assert.IsTrue(header_even.Tables[0].mainPart.Uri.OriginalString.Equals(header_even_xml_file));
  382. Assert.IsTrue(header_even.Tables[0].Rows[0].mainPart.Uri.OriginalString.Equals(header_even_xml_file));
  383. Assert.IsTrue(header_even.Tables[0].Rows[0].Cells[0].mainPart.Uri.OriginalString.Equals(header_even_xml_file));
  384. Assert.IsTrue(header_even.Tables[0].Rows[0].Cells[0].Paragraphs[0].mainPart.Uri.OriginalString.Equals(header_even_xml_file));
  385. // footer first
  386. Footer footer_first = document.Footers.first;
  387. string footer_first_xml_file = footer_first.mainPart.Uri.OriginalString;
  388. Assert.IsTrue(footer_first.mainPart.Uri.OriginalString.Equals(footer_first_xml_file));
  389. Assert.IsTrue(footer_first.Paragraphs[0].mainPart.Uri.OriginalString.Equals(footer_first_xml_file));
  390. Assert.IsTrue(footer_first.Tables[0].mainPart.Uri.OriginalString.Equals(footer_first_xml_file));
  391. Assert.IsTrue(footer_first.Tables[0].Rows[0].mainPart.Uri.OriginalString.Equals(footer_first_xml_file));
  392. Assert.IsTrue(footer_first.Tables[0].Rows[0].Cells[0].mainPart.Uri.OriginalString.Equals(footer_first_xml_file));
  393. Assert.IsTrue(footer_first.Tables[0].Rows[0].Cells[0].Paragraphs[0].mainPart.Uri.OriginalString.Equals(footer_first_xml_file));
  394. // footer odd
  395. Footer footer_odd = document.Footers.odd;
  396. string footer_odd_xml_file = footer_odd.mainPart.Uri.OriginalString;
  397. Assert.IsTrue(footer_odd.mainPart.Uri.OriginalString.Equals(footer_odd_xml_file));
  398. Assert.IsTrue(footer_odd.Paragraphs[0].mainPart.Uri.OriginalString.Equals(footer_odd_xml_file));
  399. Assert.IsTrue(footer_odd.Tables[0].mainPart.Uri.OriginalString.Equals(footer_odd_xml_file));
  400. Assert.IsTrue(footer_odd.Tables[0].Rows[0].mainPart.Uri.OriginalString.Equals(footer_odd_xml_file));
  401. Assert.IsTrue(footer_odd.Tables[0].Rows[0].Cells[0].mainPart.Uri.OriginalString.Equals(footer_odd_xml_file));
  402. Assert.IsTrue(footer_odd.Tables[0].Rows[0].Cells[0].Paragraphs[0].mainPart.Uri.OriginalString.Equals(footer_odd_xml_file));
  403. // footer even
  404. Footer footer_even = document.Footers.even;
  405. string footer_even_xml_file = footer_even.mainPart.Uri.OriginalString;
  406. Assert.IsTrue(footer_even.mainPart.Uri.OriginalString.Equals(footer_even_xml_file));
  407. Assert.IsTrue(footer_even.Paragraphs[0].mainPart.Uri.OriginalString.Equals(footer_even_xml_file));
  408. Assert.IsTrue(footer_even.Tables[0].mainPart.Uri.OriginalString.Equals(footer_even_xml_file));
  409. Assert.IsTrue(footer_even.Tables[0].Rows[0].mainPart.Uri.OriginalString.Equals(footer_even_xml_file));
  410. Assert.IsTrue(footer_even.Tables[0].Rows[0].Cells[0].mainPart.Uri.OriginalString.Equals(footer_even_xml_file));
  411. Assert.IsTrue(footer_even.Tables[0].Rows[0].Cells[0].Paragraphs[0].mainPart.Uri.OriginalString.Equals(footer_even_xml_file));
  412. }
  413. }
  414. [Test]
  415. public void Test_Document_AddImage_FromDisk()
  416. {
  417. using (DocX document = DocX.Create(Path.Combine(_directoryDocuments, "test_add_images.docx")))
  418. {
  419. // Add a png to into this document
  420. Novacode.Image png = document.AddImage(Path.Combine(_directoryWithFiles, "purple.png"));
  421. Assert.IsTrue(document.Images.Count == 1);
  422. Assert.IsTrue(Path.GetExtension(png.pr.TargetUri.OriginalString) == ".png");
  423. // Add a tiff into to this document
  424. Novacode.Image tif = document.AddImage(Path.Combine(_directoryWithFiles, "yellow.tif"));
  425. Assert.IsTrue(document.Images.Count == 2);
  426. Assert.IsTrue(Path.GetExtension(tif.pr.TargetUri.OriginalString) == ".tif");
  427. // Add a gif into to this document
  428. Novacode.Image gif = document.AddImage(Path.Combine(_directoryWithFiles, "orange.gif"));
  429. Assert.IsTrue(document.Images.Count == 3);
  430. Assert.IsTrue(Path.GetExtension(gif.pr.TargetUri.OriginalString) == ".gif");
  431. // Add a jpg into to this document
  432. Novacode.Image jpg = document.AddImage(Path.Combine(_directoryWithFiles, "green.jpg"));
  433. Assert.IsTrue(document.Images.Count == 4);
  434. Assert.IsTrue(Path.GetExtension(jpg.pr.TargetUri.OriginalString) == ".jpg");
  435. // Add a bitmap to this document
  436. Novacode.Image bitmap = document.AddImage(Path.Combine(_directoryWithFiles, "red.bmp"));
  437. Assert.IsTrue(document.Images.Count == 5);
  438. // Word does not allow bmp make sure it was inserted as a png.
  439. Assert.IsTrue(Path.GetExtension(bitmap.pr.TargetUri.OriginalString) == ".png");
  440. }
  441. }
  442. [Test]
  443. public void Test_Document_AddImage_FromStream()
  444. {
  445. using (DocX document = DocX.Create(Path.Combine(_directoryDocuments, "test_add_images.docx")))
  446. {
  447. // DocX will always insert Images that come from Streams as jpeg.
  448. // Add a png to into this document
  449. Novacode.Image png = document.AddImage(new FileStream(Path.Combine(_directoryWithFiles, "purple.png"), FileMode.Open));
  450. Assert.IsTrue(document.Images.Count == 1);
  451. Assert.IsTrue(Path.GetExtension(png.pr.TargetUri.OriginalString) == ".jpeg");
  452. // Add a tiff into to this document
  453. Novacode.Image tif = document.AddImage(new FileStream(Path.Combine(_directoryWithFiles, "yellow.tif"), FileMode.Open));
  454. Assert.IsTrue(document.Images.Count == 2);
  455. Assert.IsTrue(Path.GetExtension(tif.pr.TargetUri.OriginalString) == ".jpeg");
  456. // Add a gif into to this document
  457. Novacode.Image gif = document.AddImage(new FileStream(Path.Combine(_directoryWithFiles, "orange.gif"), FileMode.Open));
  458. Assert.IsTrue(document.Images.Count == 3);
  459. Assert.IsTrue(Path.GetExtension(gif.pr.TargetUri.OriginalString) == ".jpeg");
  460. // Add a jpg into to this document
  461. Novacode.Image jpg = document.AddImage(new FileStream(Path.Combine(_directoryWithFiles, "green.jpg"), FileMode.Open));
  462. Assert.IsTrue(document.Images.Count == 4);
  463. Assert.IsTrue(Path.GetExtension(jpg.pr.TargetUri.OriginalString) == ".jpeg");
  464. // Add a bitmap to this document
  465. Novacode.Image bitmap = document.AddImage(new FileStream(Path.Combine(_directoryWithFiles, "red.bmp"), FileMode.Open));
  466. Assert.IsTrue(document.Images.Count == 5);
  467. // Word does not allow bmp make sure it was inserted as a png.
  468. Assert.IsTrue(Path.GetExtension(bitmap.pr.TargetUri.OriginalString) == ".jpeg");
  469. }
  470. }
  471. [Test]
  472. public void Test_Tables()
  473. {
  474. using (DocX document = DocX.Load(Path.Combine(_directoryWithFiles, "Tables.docx")))
  475. {
  476. // There is only one Paragraph at the document level.
  477. Assert.IsTrue(document.Paragraphs.Count() == 13);
  478. // There is only one Table in this document.
  479. Assert.IsTrue(document.Tables.Count() == 1);
  480. // Extract the only Table.
  481. Table t0 = document.Tables[0];
  482. // This table has 12 Paragraphs.
  483. Assert.IsTrue(t0.Paragraphs.Count() == 12);
  484. }
  485. }
  486. [Test]
  487. public void Test_Images()
  488. {
  489. using (DocX document = DocX.Load(Path.Combine(_directoryWithFiles, "Images.docx")))
  490. {
  491. // Extract Images from Document.
  492. List<Novacode.Image> document_images = document.Images;
  493. // Make sure there are 3 Images in this document.
  494. Assert.IsTrue(document_images.Count() == 3);
  495. // Extract the headers from this document.
  496. Headers headers = document.Headers;
  497. Header header_first = headers.first;
  498. Header header_odd = headers.odd;
  499. Header header_even = headers.even;
  500. #region Header_First
  501. // Extract Images from the first Header.
  502. List<Novacode.Image> header_first_images = header_first.Images;
  503. // Make sure there is 1 Image in the first header.
  504. Assert.IsTrue(header_first_images.Count() == 1);
  505. #endregion
  506. #region Header_Odd
  507. // Extract Images from the odd Header.
  508. List<Novacode.Image> header_odd_images = header_odd.Images;
  509. // Make sure there is 1 Image in the first header.
  510. Assert.IsTrue(header_odd_images.Count() == 1);
  511. #endregion
  512. #region Header_Even
  513. // Extract Images from the odd Header.
  514. List<Novacode.Image> header_even_images = header_even.Images;
  515. // Make sure there is 1 Image in the first header.
  516. Assert.IsTrue(header_even_images.Count() == 1);
  517. #endregion
  518. }
  519. }
  520. [Test]
  521. public void Test_Insert_Picture()
  522. {
  523. // Load test document.
  524. using (DocX document = DocX.Create(Path.Combine(_directoryDocuments, "Test.docx")))
  525. {
  526. // Add Headers and Footers into this document.
  527. document.AddHeaders();
  528. document.AddFooters();
  529. document.DifferentFirstPage = true;
  530. document.DifferentOddAndEvenPages = true;
  531. // Add an Image to this document.
  532. Novacode.Image img = document.AddImage(Path.Combine(_directoryWithFiles, "purple.png"));
  533. // Create a Picture from this Image.
  534. Picture pic = img.CreatePicture();
  535. // Main document.
  536. Paragraph p0 = document.InsertParagraph("Hello");
  537. p0.InsertPicture(pic, 3);
  538. // Header first.
  539. Paragraph p1 = document.Headers.first.InsertParagraph("----");
  540. p1.InsertPicture(pic, 2);
  541. // Header odd.
  542. Paragraph p2 = document.Headers.odd.InsertParagraph("----");
  543. p2.InsertPicture(pic, 2);
  544. // Header even.
  545. Paragraph p3 = document.Headers.even.InsertParagraph("----");
  546. p3.InsertPicture(pic, 2);
  547. // Footer first.
  548. Paragraph p4 = document.Footers.first.InsertParagraph("----");
  549. p4.InsertPicture(pic, 2);
  550. // Footer odd.
  551. Paragraph p5 = document.Footers.odd.InsertParagraph("----");
  552. p5.InsertPicture(pic, 2);
  553. // Footer even.
  554. Paragraph p6 = document.Footers.even.InsertParagraph("----");
  555. p6.InsertPicture(pic, 2);
  556. // Save this document.
  557. document.Save();
  558. }
  559. }
  560. [Test]
  561. public void Test_Insert_Hyperlink()
  562. {
  563. // Load test document.
  564. using (DocX document = DocX.Create(Path.Combine(_directoryDocuments, "Test.docx")))
  565. {
  566. // Add Headers and Footers into this document.
  567. document.AddHeaders();
  568. document.AddFooters();
  569. document.DifferentFirstPage = true;
  570. document.DifferentOddAndEvenPages = true;
  571. // Add a Hyperlink into this document.
  572. Hyperlink h = document.AddHyperlink("google", new Uri("http://www.google.com"));
  573. // Main document.
  574. Paragraph p0 = document.InsertParagraph("Hello");
  575. p0.InsertHyperlink(h, 3);
  576. // Header first.
  577. Paragraph p1 = document.Headers.first.InsertParagraph("----");
  578. p1.InsertHyperlink(h, 3);
  579. // Header odd.
  580. Paragraph p2 = document.Headers.odd.InsertParagraph("----");
  581. p2.InsertHyperlink(h, 3);
  582. // Header even.
  583. Paragraph p3 = document.Headers.even.InsertParagraph("----");
  584. p3.InsertHyperlink(h, 3);
  585. // Footer first.
  586. Paragraph p4 = document.Footers.first.InsertParagraph("----");
  587. p4.InsertHyperlink(h, 3);
  588. // Footer odd.
  589. Paragraph p5 = document.Footers.odd.InsertParagraph("----");
  590. p5.InsertHyperlink(h, 3);
  591. // Footer even.
  592. Paragraph p6 = document.Footers.even.InsertParagraph("----");
  593. p6.InsertHyperlink(h, 3);
  594. // Save this document.
  595. document.Save();
  596. }
  597. }
  598. [Test]
  599. public void Test_Get_Set_Hyperlink()
  600. {
  601. // Load test document.
  602. using (DocX document = DocX.Load(Path.Combine(_directoryWithFiles, "Hyperlinks.docx")))
  603. {
  604. // Hyperlinks in the document.
  605. Assert.IsTrue(document.Hyperlinks.Count == 3);
  606. Assert.IsTrue(document.Hyperlinks[0].Text == "page1");
  607. Assert.IsTrue(document.Hyperlinks[0].Uri.AbsoluteUri == "http://www.page1.com/");
  608. Assert.IsTrue(document.Hyperlinks[1].Text == "page2");
  609. Assert.IsTrue(document.Hyperlinks[1].Uri.AbsoluteUri == "http://www.page2.com/");
  610. Assert.IsTrue(document.Hyperlinks[2].Text == "page3");
  611. Assert.IsTrue(document.Hyperlinks[2].Uri.AbsoluteUri == "http://www.page3.com/");
  612. // Change the Hyperlinks and check that it has in fact changed.
  613. document.Hyperlinks[0].Text = "somethingnew";
  614. document.Hyperlinks[0].Uri = new Uri("http://www.google.com/");
  615. Assert.IsTrue(document.Hyperlinks[0].Text == "somethingnew");
  616. Assert.IsTrue(document.Hyperlinks[0].Uri.AbsoluteUri == "http://www.google.com/");
  617. document.Hyperlinks[1].Text = "somethingnew";
  618. document.Hyperlinks[1].Uri = new Uri("http://www.google.com/");
  619. Assert.IsTrue(document.Hyperlinks[1].Text == "somethingnew");
  620. Assert.IsTrue(document.Hyperlinks[1].Uri.AbsoluteUri == "http://www.google.com/");
  621. document.Hyperlinks[2].Text = "somethingnew";
  622. document.Hyperlinks[2].Uri = new Uri("http://www.google.com/");
  623. Assert.IsTrue(document.Hyperlinks[2].Text == "somethingnew");
  624. Assert.IsTrue(document.Hyperlinks[2].Uri.AbsoluteUri == "http://www.google.com/");
  625. Assert.IsTrue(document.Headers.first.Hyperlinks.Count == 1);
  626. Assert.IsTrue(document.Headers.first.Hyperlinks[0].Text == "header-first");
  627. Assert.IsTrue(document.Headers.first.Hyperlinks[0].Uri.AbsoluteUri == "http://www.header-first.com/");
  628. // Change the Hyperlinks and check that it has in fact changed.
  629. document.Headers.first.Hyperlinks[0].Text = "somethingnew";
  630. document.Headers.first.Hyperlinks[0].Uri = new Uri("http://www.google.com/");
  631. Assert.IsTrue(document.Headers.first.Hyperlinks[0].Text == "somethingnew");
  632. Assert.IsTrue(document.Headers.first.Hyperlinks[0].Uri.AbsoluteUri == "http://www.google.com/");
  633. Assert.IsTrue(document.Headers.odd.Hyperlinks.Count == 1);
  634. Assert.IsTrue(document.Headers.odd.Hyperlinks[0].Text == "header-odd");
  635. Assert.IsTrue(document.Headers.odd.Hyperlinks[0].Uri.AbsoluteUri == "http://www.header-odd.com/");
  636. // Change the Hyperlinks and check that it has in fact changed.
  637. document.Headers.odd.Hyperlinks[0].Text = "somethingnew";
  638. document.Headers.odd.Hyperlinks[0].Uri = new Uri("http://www.google.com/");
  639. Assert.IsTrue(document.Headers.odd.Hyperlinks[0].Text == "somethingnew");
  640. Assert.IsTrue(document.Headers.odd.Hyperlinks[0].Uri.AbsoluteUri == "http://www.google.com/");
  641. Assert.IsTrue(document.Headers.even.Hyperlinks.Count == 1);
  642. Assert.IsTrue(document.Headers.even.Hyperlinks[0].Text == "header-even");
  643. Assert.IsTrue(document.Headers.even.Hyperlinks[0].Uri.AbsoluteUri == "http://www.header-even.com/");
  644. // Change the Hyperlinks and check that it has in fact changed.
  645. document.Headers.even.Hyperlinks[0].Text = "somethingnew";
  646. document.Headers.even.Hyperlinks[0].Uri = new Uri("http://www.google.com/");
  647. Assert.IsTrue(document.Headers.even.Hyperlinks[0].Text == "somethingnew");
  648. Assert.IsTrue(document.Headers.even.Hyperlinks[0].Uri.AbsoluteUri == "http://www.google.com/");
  649. Assert.IsTrue(document.Footers.first.Hyperlinks.Count == 1);
  650. Assert.IsTrue(document.Footers.first.Hyperlinks[0].Text == "footer-first");
  651. Assert.IsTrue(document.Footers.first.Hyperlinks[0].Uri.AbsoluteUri == "http://www.footer-first.com/");
  652. // Change the Hyperlinks and check that it has in fact changed.
  653. document.Footers.first.Hyperlinks[0].Text = "somethingnew";
  654. document.Footers.first.Hyperlinks[0].Uri = new Uri("http://www.google.com/");
  655. Assert.IsTrue(document.Footers.first.Hyperlinks[0].Text == "somethingnew");
  656. Assert.IsTrue(document.Footers.first.Hyperlinks[0].Uri.AbsoluteUri == "http://www.google.com/");
  657. Assert.IsTrue(document.Footers.odd.Hyperlinks.Count == 1);
  658. Assert.IsTrue(document.Footers.odd.Hyperlinks[0].Text == "footer-odd");
  659. Assert.IsTrue(document.Footers.odd.Hyperlinks[0].Uri.AbsoluteUri == "http://www.footer-odd.com/");
  660. // Change the Hyperlinks and check that it has in fact changed.
  661. document.Footers.odd.Hyperlinks[0].Text = "somethingnew";
  662. document.Footers.odd.Hyperlinks[0].Uri = new Uri("http://www.google.com/");
  663. Assert.IsTrue(document.Footers.odd.Hyperlinks[0].Text == "somethingnew");
  664. Assert.IsTrue(document.Footers.odd.Hyperlinks[0].Uri.AbsoluteUri == "http://www.google.com/");
  665. Assert.IsTrue(document.Footers.even.Hyperlinks.Count == 1);
  666. Assert.IsTrue(document.Footers.even.Hyperlinks[0].Text == "footer-even");
  667. Assert.IsTrue(document.Footers.even.Hyperlinks[0].Uri.AbsoluteUri == "http://www.footer-even.com/");
  668. // Change the Hyperlinks and check that it has in fact changed.
  669. document.Footers.even.Hyperlinks[0].Text = "somethingnew";
  670. document.Footers.even.Hyperlinks[0].Uri = new Uri("http://www.google.com/");
  671. Assert.IsTrue(document.Footers.even.Hyperlinks[0].Text == "somethingnew");
  672. Assert.IsTrue(document.Footers.even.Hyperlinks[0].Uri.AbsoluteUri == "http://www.google.com/");
  673. }
  674. }
  675. [Test]
  676. public void Test_Append_Hyperlink()
  677. {
  678. // Load test document.
  679. using (DocX document = DocX.Create(Path.Combine(_directoryDocuments, "Test.docx")))
  680. {
  681. // Add Headers and Footers into this document.
  682. document.AddHeaders();
  683. document.AddFooters();
  684. document.DifferentFirstPage = true;
  685. document.DifferentOddAndEvenPages = true;
  686. // Add a Hyperlink to this document.
  687. Hyperlink h = document.AddHyperlink("google", new Uri("http://www.google.com"));
  688. // Main document.
  689. Paragraph p0 = document.InsertParagraph("----");
  690. p0.AppendHyperlink(h);
  691. Assert.IsTrue(p0.Text == "----google");
  692. // Header first.
  693. Paragraph p1 = document.Headers.first.InsertParagraph("----");
  694. p1.AppendHyperlink(h);
  695. Assert.IsTrue(p1.Text == "----google");
  696. // Header odd.
  697. Paragraph p2 = document.Headers.odd.InsertParagraph("----");
  698. p2.AppendHyperlink(h);
  699. Assert.IsTrue(p2.Text == "----google");
  700. // Header even.
  701. Paragraph p3 = document.Headers.even.InsertParagraph("----");
  702. p3.AppendHyperlink(h);
  703. Assert.IsTrue(p3.Text == "----google");
  704. // Footer first.
  705. Paragraph p4 = document.Footers.first.InsertParagraph("----");
  706. p4.AppendHyperlink(h);
  707. Assert.IsTrue(p4.Text == "----google");
  708. // Footer odd.
  709. Paragraph p5 = document.Footers.odd.InsertParagraph("----");
  710. p5.AppendHyperlink(h);
  711. Assert.IsTrue(p5.Text == "----google");
  712. // Footer even.
  713. Paragraph p6 = document.Footers.even.InsertParagraph("----");
  714. p6.AppendHyperlink(h);
  715. Assert.IsTrue(p6.Text == "----google");
  716. // Save the document.
  717. document.Save();
  718. }
  719. }
  720. [Test]
  721. public void Test_Append_Picture()
  722. {
  723. // Create test document.
  724. using (DocX document = DocX.Create(Path.Combine(_directoryDocuments, "Test.docx")))
  725. {
  726. // Add Headers and Footers into this document.
  727. document.AddHeaders();
  728. document.AddFooters();
  729. document.DifferentFirstPage = true;
  730. document.DifferentOddAndEvenPages = true;
  731. // Add an Image to this document.
  732. Novacode.Image img = document.AddImage(Path.Combine(_directoryWithFiles, "purple.png"));
  733. // Create a Picture from this Image.
  734. Picture pic = img.CreatePicture();
  735. // Main document.
  736. Paragraph p0 = document.InsertParagraph();
  737. p0.AppendPicture(pic);
  738. // Header first.
  739. Paragraph p1 = document.Headers.first.InsertParagraph();
  740. p1.AppendPicture(pic);
  741. // Header odd.
  742. Paragraph p2 = document.Headers.odd.InsertParagraph();
  743. p2.AppendPicture(pic);
  744. // Header even.
  745. Paragraph p3 = document.Headers.even.InsertParagraph();
  746. p3.AppendPicture(pic);
  747. // Footer first.
  748. Paragraph p4 = document.Footers.first.InsertParagraph();
  749. p4.AppendPicture(pic);
  750. // Footer odd.
  751. Paragraph p5 = document.Footers.odd.InsertParagraph();
  752. p5.AppendPicture(pic);
  753. // Footer even.
  754. Paragraph p6 = document.Footers.even.InsertParagraph();
  755. p6.AppendPicture(pic);
  756. // Save the document.
  757. document.Save();
  758. }
  759. }
  760. [Test]
  761. public void Test_Move_Picture_Load()
  762. {
  763. // Load test document.
  764. using (DocX document = DocX.Load(Path.Combine(_directoryWithFiles, "MovePicture.docx")))
  765. {
  766. // Extract the first Picture from the first Paragraph.
  767. Picture picture = document.Paragraphs.First().Pictures.First();
  768. // Move it into the first Header.
  769. Header header_first = document.Headers.first;
  770. header_first.Paragraphs.First().AppendPicture(picture);
  771. // Move it into the even Header.
  772. Header header_even = document.Headers.even;
  773. header_even.Paragraphs.First().AppendPicture(picture);
  774. // Move it into the odd Header.
  775. Header header_odd = document.Headers.odd;
  776. header_odd.Paragraphs.First().AppendPicture(picture);
  777. // Move it into the first Footer.
  778. Footer footer_first = document.Footers.first;
  779. footer_first.Paragraphs.First().AppendPicture(picture);
  780. // Move it into the even Footer.
  781. Footer footer_even = document.Footers.even;
  782. footer_even.Paragraphs.First().AppendPicture(picture);
  783. // Move it into the odd Footer.
  784. Footer footer_odd = document.Footers.odd;
  785. footer_odd.Paragraphs.First().AppendPicture(picture);
  786. // Save this as MovedPicture.docx
  787. document.SaveAs(Path.Combine(_directoryDocuments, "MovedPicture.docx"));
  788. }
  789. }
  790. [Test]
  791. public void Test_Paragraph_InsertHyperlink()
  792. {
  793. // Create a new document
  794. using (DocX document = DocX.Create("Test.docx"))
  795. {
  796. // Add a Hyperlink to this document.
  797. Hyperlink h = document.AddHyperlink("link", new Uri("http://www.google.com"));
  798. // Simple
  799. Paragraph p1 = document.InsertParagraph("AC");
  800. p1.InsertHyperlink(h); Assert.IsTrue(p1.Text == "linkAC");
  801. p1.InsertHyperlink(h, p1.Text.Length); Assert.IsTrue(p1.Text == "linkAClink");
  802. p1.InsertHyperlink(h, p1.Text.IndexOf("C")); Assert.IsTrue(p1.Text == "linkAlinkClink");
  803. // Difficult
  804. Paragraph p2 = document.InsertParagraph("\tA\tC\t");
  805. p2.InsertHyperlink(h); Assert.IsTrue(p2.Text == "link\tA\tC\t");
  806. p2.InsertHyperlink(h, p2.Text.Length); Assert.IsTrue(p2.Text == "link\tA\tC\tlink");
  807. p2.InsertHyperlink(h, p2.Text.IndexOf("C")); Assert.IsTrue(p2.Text == "link\tA\tlinkC\tlink");
  808. // Contrived
  809. // Add a contrived Hyperlink to this document.
  810. Hyperlink h2 = document.AddHyperlink("\tlink\t", new Uri("http://www.google.com"));
  811. Paragraph p3 = document.InsertParagraph("\tA\tC\t");
  812. p3.InsertHyperlink(h2); Assert.IsTrue(p3.Text == "\tlink\t\tA\tC\t");
  813. p3.InsertHyperlink(h2, p3.Text.Length); Assert.IsTrue(p3.Text == "\tlink\t\tA\tC\t\tlink\t");
  814. p3.InsertHyperlink(h2, p3.Text.IndexOf("C")); Assert.IsTrue(p3.Text == "\tlink\t\tA\t\tlink\tC\t\tlink\t");
  815. }
  816. }
  817. [Test]
  818. public void Test_Paragraph_RemoveHyperlink()
  819. {
  820. // Create a new document
  821. using (DocX document = DocX.Create("Test.docx"))
  822. {
  823. // Add a Hyperlink to this document.
  824. Hyperlink h = document.AddHyperlink("link", new Uri("http://www.google.com"));
  825. // Simple
  826. Paragraph p1 = document.InsertParagraph("AC");
  827. p1.InsertHyperlink(h); Assert.IsTrue(p1.Text == "linkAC");
  828. p1.InsertHyperlink(h, p1.Text.Length); Assert.IsTrue(p1.Text == "linkAClink");
  829. p1.InsertHyperlink(h, p1.Text.IndexOf("C")); Assert.IsTrue(p1.Text == "linkAlinkClink");
  830. // Try and remove a Hyperlink using a negative index.
  831. // This should throw an exception.
  832. try
  833. {
  834. p1.RemoveHyperlink(-1);
  835. Assert.Fail();
  836. }
  837. catch (ArgumentException) { }
  838. catch (Exception) { Assert.Fail(); }
  839. // Try and remove a Hyperlink at an index greater than the last.
  840. // This should throw an exception.
  841. try
  842. {
  843. p1.RemoveHyperlink(3);
  844. Assert.Fail();
  845. }
  846. catch (ArgumentException) { }
  847. catch (Exception) { Assert.Fail(); }
  848. p1.RemoveHyperlink(0); Assert.IsTrue(p1.Text == "AlinkClink");
  849. p1.RemoveHyperlink(1); Assert.IsTrue(p1.Text == "AlinkC");
  850. p1.RemoveHyperlink(0); Assert.IsTrue(p1.Text == "AC");
  851. }
  852. }
  853. [Test]
  854. public void Test_Paragraph_ReplaceText()
  855. {
  856. // Create a new document
  857. using (DocX document = DocX.Create("Test.docx"))
  858. {
  859. // Simple
  860. Paragraph p1 = document.InsertParagraph("Apple Pear Apple Apple Pear Apple");
  861. p1.ReplaceText("Apple", "Orange"); Assert.IsTrue(p1.Text == "Orange Pear Orange Orange Pear Orange");
  862. p1.ReplaceText("Pear", "Apple"); Assert.IsTrue(p1.Text == "Orange Apple Orange Orange Apple Orange");
  863. p1.ReplaceText("Orange", "Pear"); Assert.IsTrue(p1.Text == "Pear Apple Pear Pear Apple Pear");
  864. // Try and replace text that dosen't exist in the Paragraph.
  865. string old = p1.Text;
  866. p1.ReplaceText("foo", "bar"); Assert.IsTrue(p1.Text.Equals(old));
  867. // Difficult
  868. Paragraph p2 = document.InsertParagraph("Apple Pear Apple Apple Pear Apple");
  869. p2.ReplaceText(" ", "\t"); Assert.IsTrue(p2.Text == "Apple\tPear\tApple\tApple\tPear\tApple");
  870. p2.ReplaceText("\tApple\tApple", ""); Assert.IsTrue(p2.Text == "Apple\tPear\tPear\tApple");
  871. p2.ReplaceText("Apple\tPear\t", ""); Assert.IsTrue(p2.Text == "Pear\tApple");
  872. p2.ReplaceText("Pear\tApple", ""); Assert.IsTrue(p2.Text == "");
  873. }
  874. }
  875. [Test]
  876. public void Test_Paragraph_ReplaceTextInGivenFormat()
  877. {
  878. // Load a document.
  879. using (DocX document = DocX.Load(Path.Combine(_directoryWithFiles, "VariousTextFormatting.docx")))
  880. {
  881. // Removing red text highlighted with yellow
  882. var formatting = new Formatting();
  883. formatting.FontColor = Color.Blue;
  884. // IMPORTANT: default constructor of Formatting sets up language property - set it to NULL to be language independent
  885. var desiredFormat = new Formatting() { Language = null, FontColor = Color.FromArgb(255, 0, 0), Highlight = Highlight.yellow };
  886. var replaced = string.Empty;
  887. foreach (var p in document.Paragraphs)
  888. {
  889. if (p.Text == "Text highlighted with yellow")
  890. {
  891. p.ReplaceText("Text highlighted with yellow", "New text highlighted with yellow", false, RegexOptions.None, null, desiredFormat, MatchFormattingOptions.ExactMatch);
  892. replaced += p.Text;
  893. }
  894. }
  895. Assert.AreEqual("New text highlighted with yellow", replaced);
  896. // Removing red text with no other formatting (ExactMatch)
  897. desiredFormat = new Formatting() { Language = null, FontColor = Color.FromArgb(255, 0, 0) };
  898. var count = 0;
  899. foreach (var p in document.Paragraphs)
  900. {
  901. p.ReplaceText("Text", "Replaced text", false, RegexOptions.None, null, desiredFormat, MatchFormattingOptions.ExactMatch);
  902. if (p.Text.StartsWith("Replaced text"))
  903. {
  904. ++count;
  905. }
  906. }
  907. Assert.AreEqual(1, count);
  908. // Removing just red text with any other formatting (SubsetMatch)
  909. desiredFormat = new Formatting() { Language = null, FontColor = Color.FromArgb(255, 0, 0) };
  910. count = 0;
  911. foreach (var p in document.Paragraphs)
  912. {
  913. p.ReplaceText("Text", "Replaced text", false, RegexOptions.None, null, desiredFormat, MatchFormattingOptions.SubsetMatch);
  914. if (p.Text.StartsWith("Replaced text"))
  915. {
  916. ++count;
  917. }
  918. }
  919. Assert.AreEqual(2, count);
  920. }
  921. }
  922. [Test]
  923. public void Test_Paragraph_RemoveText()
  924. {
  925. // Create a new document
  926. using (DocX document = DocX.Create("Test.docx"))
  927. {
  928. // Simple
  929. //<p>
  930. // <r><t>HellWorld</t></r>
  931. //</p>
  932. Paragraph p1 = document.InsertParagraph("HelloWorld");
  933. p1.RemoveText(0, 1); Assert.IsTrue(p1.Text == "elloWorld");
  934. p1.RemoveText(p1.Text.Length - 1, 1); Assert.IsTrue(p1.Text == "elloWorl");
  935. p1.RemoveText(p1.Text.IndexOf("o"), 1); Assert.IsTrue(p1.Text == "ellWorl");
  936. // Try and remove text at an index greater than the last.
  937. // This should throw an exception.
  938. try
  939. {
  940. p1.RemoveText(p1.Text.Length, 1);
  941. Assert.Fail();
  942. }
  943. catch (ArgumentOutOfRangeException) { }
  944. catch (Exception) { Assert.Fail(); }
  945. // Try and remove text at a negative index.
  946. // This should throw an exception.
  947. try
  948. {
  949. p1.RemoveText(-1, 1);
  950. Assert.Fail();
  951. }
  952. catch (ArgumentOutOfRangeException) { }
  953. catch (Exception) { Assert.Fail(); }
  954. // Difficult
  955. //<p>
  956. // <r><t>A</t></r>
  957. // <r><t>B</t></r>
  958. // <r><t>C</t></r>
  959. //</p>
  960. Paragraph p2 = document.InsertParagraph("A\tB\tC");
  961. p2.RemoveText(0, 1); Assert.IsTrue(p2.Text == "\tB\tC");
  962. p2.RemoveText(p2.Text.Length - 1, 1); Assert.IsTrue(p2.Text == "\tB\t");
  963. p2.RemoveText(p2.Text.IndexOf("B"), 1); Assert.IsTrue(p2.Text == "\t\t");
  964. p2.RemoveText(0, 1); Assert.IsTrue(p2.Text == "\t");
  965. p2.RemoveText(0, 1); Assert.IsTrue(p2.Text == "");
  966. // Contrived 1
  967. //<p>
  968. // <r>
  969. // <t>A</t>
  970. // <t>B</t>
  971. // <t>C</t>
  972. // </r>
  973. //</p>
  974. Paragraph p3 = document.InsertParagraph("");
  975. p3.Xml = XElement.Parse
  976. (
  977. @"<w:p xmlns:w='http://schemas.openxmlformats.org/wordprocessingml/2006/main'>
  978. <w:pPr />
  979. <w:r>
  980. <w:rPr />
  981. <w:t>A</w:t>
  982. <w:t>B</w:t>
  983. <w:t>C</w:t>
  984. </w:r>
  985. </w:p>"
  986. );
  987. p3.RemoveText(0, 1); Assert.IsTrue(p3.Text == "BC");
  988. p3.RemoveText(p3.Text.Length - 1, 1); Assert.IsTrue(p3.Text == "B");
  989. p3.RemoveText(0, 1); Assert.IsTrue(p3.Text == "");
  990. // Contrived 2
  991. //<p>
  992. // <r>
  993. // <t>A</t>
  994. // <t>B</t>
  995. // <t>C</t>
  996. // </r>
  997. //</p>
  998. Paragraph p4 = document.InsertParagraph("");
  999. p4.Xml = XElement.Parse
  1000. (
  1001. @"<w:p xmlns:w='http://schemas.openxmlformats.org/wordprocessingml/2006/main'>
  1002. <w:pPr />
  1003. <w:r>
  1004. <w:rPr />
  1005. <tab />
  1006. <w:t>A</w:t>
  1007. <tab />
  1008. </w:r>
  1009. <w:r>
  1010. <w:rPr />
  1011. <tab />
  1012. <w:t>B</w:t>
  1013. <tab />
  1014. </w:r>
  1015. </w:p>"
  1016. );
  1017. p4.RemoveText(0, 1); Assert.IsTrue(p4.Text == "A\t\tB\t");
  1018. p4.RemoveText(1, 1); Assert.IsTrue(p4.Text == "A\tB\t");
  1019. p4.RemoveText(p4.Text.Length - 1, 1); Assert.IsTrue(p4.Text == "A\tB");
  1020. p4.RemoveText(1, 1); Assert.IsTrue(p4.Text == "AB");
  1021. p4.RemoveText(p4.Text.Length - 1, 1); Assert.IsTrue(p4.Text == "A");
  1022. p4.RemoveText(p4.Text.Length - 1, 1); Assert.IsTrue(p4.Text == "");
  1023. }
  1024. }
  1025. [Test]
  1026. public void Test_Document_RemoveTextInGivenFormat()
  1027. {
  1028. // Load a document.
  1029. using (DocX document = DocX.Load(Path.Combine(_directoryWithFiles, "VariousTextFormatting.docx")))
  1030. {
  1031. var formatting = new Formatting();
  1032. formatting.FontColor = Color.Blue;
  1033. // IMPORTANT: default constructor of Formatting sets up language property - set it to NULL to be language independent
  1034. formatting.Language = null;
  1035. var deletedCount = document.RemoveTextInGivenFormat(formatting);
  1036. Assert.AreEqual(2, deletedCount);
  1037. deletedCount = document.RemoveTextInGivenFormat(new Formatting() { Highlight = Highlight.yellow, Language = null });
  1038. Assert.AreEqual(2, deletedCount);
  1039. deletedCount = document.RemoveTextInGivenFormat(new Formatting() { Highlight = Highlight.blue, Language = null, FontColor = Color.FromArgb(0, 255, 0) });
  1040. Assert.AreEqual(1, deletedCount);
  1041. deletedCount = document.RemoveTextInGivenFormat(new Formatting() { Language = null, FontColor = Color.FromArgb(123, 123, 123) }, MatchFormattingOptions.ExactMatch);
  1042. Assert.AreEqual(2, deletedCount);
  1043. }
  1044. }
  1045. [Test]
  1046. public void Test_Paragraph_InsertText()
  1047. {
  1048. // Create a new document
  1049. using (DocX document = DocX.Create("Test.docx"))
  1050. {
  1051. // Simple
  1052. //<p>
  1053. // <r><t>HelloWorld</t></r>
  1054. //</p>
  1055. Paragraph p1 = document.InsertParagraph("HelloWorld");
  1056. p1.InsertText(0, "-"); Assert.IsTrue(p1.Text == "-HelloWorld");
  1057. p1.InsertText(p1.Text.Length, "-"); Assert.IsTrue(p1.Text == "-HelloWorld-");
  1058. p1.InsertText(p1.Text.IndexOf("W"), "-"); Assert.IsTrue(p1.Text == "-Hello-World-");
  1059. // Try and insert text at an index greater than the last + 1.
  1060. // This should throw an exception.
  1061. try
  1062. {
  1063. p1.InsertText(p1.Text.Length + 1, "-");
  1064. Assert.Fail();
  1065. }
  1066. catch (ArgumentOutOfRangeException) { }
  1067. catch (Exception) { Assert.Fail(); }
  1068. // Try and insert text at a negative index.
  1069. // This should throw an exception.
  1070. try
  1071. {
  1072. p1.InsertText(-1, "-");
  1073. Assert.Fail();
  1074. }
  1075. catch (ArgumentOutOfRangeException) { }
  1076. catch (Exception) { Assert.Fail(); }
  1077. // Difficult
  1078. //<p>
  1079. // <r><t>A</t></r>
  1080. // <r><t>B</t></r>
  1081. // <r><t>C</t></r>
  1082. //</p>
  1083. Paragraph p2 = document.InsertParagraph("A\tB\tC");
  1084. p2.InsertText(0, "-"); Assert.IsTrue(p2.Text == "-A\tB\tC");
  1085. p2.InsertText(p2.Text.Length, "-"); Assert.IsTrue(p2.Text == "-A\tB\tC-");
  1086. p2.InsertText(p2.Text.IndexOf("B"), "-"); Assert.IsTrue(p2.Text == "-A\t-B\tC-");
  1087. p2.InsertText(p2.Text.IndexOf("C"), "-"); Assert.IsTrue(p2.Text == "-A\t-B\t-C-");
  1088. // Contrived 1
  1089. //<p>
  1090. // <r>
  1091. // <t>A</t>
  1092. // <t>B</t>
  1093. // <t>C</t>
  1094. // </r>
  1095. //</p>
  1096. Paragraph p3 = document.InsertParagraph("");
  1097. p3.Xml = XElement.Parse
  1098. (
  1099. @"<w:p xmlns:w='http://schemas.openxmlformats.org/wordprocessingml/2006/main'>
  1100. <w:pPr />
  1101. <w:r>
  1102. <w:rPr />
  1103. <w:t>A</w:t>
  1104. <w:t>B</w:t>
  1105. <w:t>C</w:t>
  1106. </w:r>
  1107. </w:p>"
  1108. );
  1109. p3.InsertText(0, "-"); Assert.IsTrue(p3.Text == "-ABC");
  1110. p3.InsertText(p3.Text.Length, "-"); Assert.IsTrue(p3.Text == "-ABC-");
  1111. p3.InsertText(p3.Text.IndexOf("B"), "-"); Assert.IsTrue(p3.Text == "-A-BC-");
  1112. p3.InsertText(p3.Text.IndexOf("C"), "-"); Assert.IsTrue(p3.Text == "-A-B-C-");
  1113. // Contrived 2
  1114. //<p>
  1115. // <r>
  1116. // <t>A</t>
  1117. // <t>B</t>
  1118. // <t>C</t>
  1119. // </r>
  1120. //</p>
  1121. Paragraph p4 = document.InsertParagraph("");
  1122. p4.Xml = XElement.Parse
  1123. (
  1124. @"<w:p xmlns:w='http://schemas.openxmlformats.org/wordprocessingml/2006/main'>
  1125. <w:pPr />
  1126. <w:r>
  1127. <w:rPr />
  1128. <w:t>A</w:t>
  1129. <w:t>B</w:t>
  1130. <w:t>C</w:t>
  1131. </w:r>
  1132. </w:p>"
  1133. );
  1134. p4.InsertText(0, "\t"); Assert.IsTrue(p4.Text == "\tABC");
  1135. p4.InsertText(p4.Text.Length, "\t"); Assert.IsTrue(p4.Text == "\tABC\t");
  1136. p4.InsertText(p4.Text.IndexOf("B"), "\t"); Assert.IsTrue(p4.Text == "\tA\tBC\t");
  1137. p4.InsertText(p4.Text.IndexOf("C"), "\t"); Assert.IsTrue(p4.Text == "\tA\tB\tC\t");
  1138. }
  1139. }
  1140. [Test]
  1141. public void Test_Document_Paragraphs()
  1142. {
  1143. string temporaryFilePath = Path.Combine(_directoryDocuments, "temp.docx");
  1144. // Load the document 'Paragraphs.docx'
  1145. using (DocX document = DocX.Load(Path.Combine(_directoryWithFiles, "Paragraphs.docx")))
  1146. {
  1147. // Extract the Paragraphs from this document.
  1148. ReadOnlyCollection<Paragraph> paragraphs = document.Paragraphs;
  1149. // There should be 3 Paragraphs in this document.
  1150. Assert.IsTrue(paragraphs.Count() == 3);
  1151. // Extract the 3 Paragraphs.
  1152. Paragraph p1 = paragraphs[0];
  1153. Paragraph p2 = paragraphs[1];
  1154. Paragraph p3 = paragraphs[2];
  1155. // Extract their Text properties.
  1156. string p1_text = p1.Text;
  1157. string p2_text = p2.Text;
  1158. string p3_text = p3.Text;
  1159. // Test their Text properties against absolutes.
  1160. Assert.IsTrue(p1_text == "Paragraph 1");
  1161. Assert.IsTrue(p2_text == "Paragraph 2");
  1162. Assert.IsTrue(p3_text == "Paragraph 3");
  1163. // Its important that each Paragraph knows the PackagePart it belongs to.
  1164. foreach (var paragraph in document.Paragraphs)
  1165. {
  1166. Assert.IsTrue(paragraph.PackagePart.Uri.ToString() == package_part_document);
  1167. }
  1168. // Test the saving of the document.
  1169. document.SaveAs(temporaryFilePath);
  1170. }
  1171. // Delete the tempory file.
  1172. File.Delete(temporaryFilePath);
  1173. }
  1174. [Test]
  1175. public void Test_Table_mainPart_bug9526()
  1176. {
  1177. using (DocX document = DocX.Create("test.docx"))
  1178. {
  1179. Hyperlink h = document.AddHyperlink("follow me", new Uri("http://www.google.com"));
  1180. Table t = document.AddTable(2, 3);
  1181. int cc = t.ColumnCount;
  1182. Paragraph p = t.Rows[0].Cells[0].Paragraphs[0];
  1183. p.AppendHyperlink(h);
  1184. }
  1185. }
  1186. [Test]
  1187. public void Test_Table_RemoveColumnWithMergedCells()
  1188. {
  1189. using (DocX document = DocX.Create(Path.Combine(_directoryDocuments, "Tables3.docx")))
  1190. {
  1191. //Add A table
  1192. Table t = document.AddTable(2, 3);
  1193. t.Design = TableDesign.TableGrid;
  1194. Table t1 = document.InsertTable(t);
  1195. t1.Rows[0].MergeCells(1, 2);
  1196. t1.RemoveColumn();
  1197. document.Save();
  1198. }
  1199. }
  1200. [Test]
  1201. public void Test_Table_MergeRowMergedCellsWithColumnMergedCells()
  1202. {
  1203. using (DocX document = DocX.Create(Path.Combine(_directoryDocuments, "Tables3.docx")))
  1204. {
  1205. //Add A table
  1206. Table t = document.AddTable(3, 3);
  1207. t.Design = TableDesign.TableGrid;
  1208. Table t1 = document.InsertTable(t);
  1209. t1.Rows[0].MergeCells(0, 1);
  1210. t1.Rows[1].MergeCells(0, 1);
  1211. t1.MergeCellsInColumn(0, 0, 1);
  1212. document.Save();
  1213. }
  1214. }
  1215. [Test]
  1216. public void Test_Table_RemoveRowWithMergedCells()
  1217. {
  1218. using (DocX document = DocX.Create(Path.Combine(_directoryDocuments, "Tables3.docx")))
  1219. {
  1220. //Add A table
  1221. Table t = document.AddTable(3, 4);
  1222. t.Design = TableDesign.TableGrid;
  1223. Table t1 = document.InsertTable(t);
  1224. t1.Rows[0].MergeCells(1, 2);
  1225. t1.RemoveRow();
  1226. t1.MergeCellsInColumn(0, 0, 1);
  1227. t1.InsertRow();
  1228. t1.RemoveRow(1);
  1229. document.Save();
  1230. }
  1231. }
  1232. [Test]
  1233. public void Test_Table_InsertRow()
  1234. {
  1235. using (DocX document = DocX.Create(Path.Combine(_directoryDocuments, "Tables3.docx")))
  1236. {
  1237. //Add A table
  1238. Table t = document.AddTable(2, 3);
  1239. t.Design = TableDesign.TableGrid;
  1240. Table t1 = document.InsertTable(t);
  1241. t1.MergeCellsInColumn(1, 0, 1);
  1242. t1.InsertRow();
  1243. t1.Rows[2].MergeCells(1, 3);
  1244. t1.InsertRow(3);
  1245. document.Save();
  1246. }
  1247. }
  1248. [Test]
  1249. public void Test_Table_AddColumnWithCellDeleted()
  1250. {
  1251. using (DocX document = DocX.Create(Path.Combine(_directoryDocuments, "Tables3.docx")))
  1252. {
  1253. //Add A table
  1254. Table t = document.AddTable(2, 3);
  1255. t.Design = TableDesign.TableGrid;
  1256. Table t1 = document.InsertTable(t);
  1257. t1.DeleteAndShiftCellsLeft(0, 1);
  1258. // 4 columns
  1259. t1.InsertColumn();
  1260. t1.DeleteAndShiftCellsLeft(0, 1);
  1261. // 5 columns
  1262. t1.InsertColumn();
  1263. t1.DeleteAndShiftCellsLeft(0, 1);
  1264. document.Save();
  1265. }
  1266. }
  1267. [Test]
  1268. public void Test_Table_DeleteCellInRow()
  1269. {
  1270. using (DocX document = DocX.Create(Path.Combine(_directoryDocuments, "Tables3.docx")))
  1271. {
  1272. //Add A table
  1273. Table t = document.AddTable(2, 2);
  1274. t.Design = TableDesign.TableGrid;
  1275. Table t1 = document.InsertTable(t);
  1276. t1.DeleteAndShiftCellsLeft(0, 1);
  1277. document.Save();
  1278. document.Save();
  1279. }
  1280. }
  1281. [Test]
  1282. public void Test_Table_InsertColumnWithMergedCells()
  1283. {
  1284. using (DocX document = DocX.Create(Path.Combine(_directoryDocuments, "Tables3.docx")))
  1285. {
  1286. //Add A table
  1287. Table t = document.AddTable(2, 2);
  1288. t.Design = TableDesign.TableGrid;
  1289. Table t1 = document.InsertTable(t);
  1290. t1.InsertColumn(2, true);
  1291. t1.InsertColumn(2, true);
  1292. t1.InsertColumn(2, true);
  1293. t1.InsertColumn(2, true);
  1294. t1.Rows[0].MergeCells(1, 4);
  1295. Assert.AreEqual(t1.Rows[1].Cells.Count, 6);
  1296. Assert.AreEqual(t1.ColumnCount, 6);
  1297. foreach (Row r in t1.Rows)
  1298. {
  1299. foreach (Cell c in r.Cells)
  1300. {
  1301. c.Paragraphs[0].InsertText("Hello");
  1302. }
  1303. }
  1304. t1.InsertColumn(6, false);
  1305. t1.InsertColumn();
  1306. t1.InsertColumn(3, true);
  1307. t1.InsertColumn(6, true);
  1308. t1.InsertColumn(6, true);
  1309. t1.InsertColumn(5, true);
  1310. document.Save();
  1311. }
  1312. }
  1313. [Test]
  1314. public void Test_Table_InsertRowAndColumn()
  1315. {
  1316. // Create a table
  1317. using (DocX document = DocX.Create(Path.Combine(_directoryDocuments, "Tables2.docx")))
  1318. {
  1319. // Add a Table to a document.
  1320. Table t = document.AddTable(2, 2);
  1321. t.Design = TableDesign.TableGrid;
  1322. t.Rows[0].Cells[0].Paragraphs[0].InsertText("X");
  1323. t.Rows[0].Cells[1].Paragraphs[0].InsertText("X");
  1324. t.Rows[1].Cells[0].Paragraphs[0].InsertText("X");
  1325. t.Rows[1].Cells[1].Paragraphs[0].InsertText("X");
  1326. // Insert the Table into the main section of the document.
  1327. Table t1 = document.InsertTable(t);
  1328. // ... and add a column and a row
  1329. t1.InsertRow(1);
  1330. t1.InsertColumn(1, true);
  1331. // Save the document.
  1332. document.Save();
  1333. }
  1334. // Check table
  1335. using (DocX document = DocX.Load(Path.Combine(_directoryDocuments, "Tables2.docx")))
  1336. {
  1337. // Get a table from a document
  1338. Table t = document.Tables[0];
  1339. // Check that the table is equal this:
  1340. // X - X
  1341. // - - -
  1342. // X - X
  1343. Assert.AreEqual("X", t.Rows[0].Cells[0].Paragraphs[0].Text);
  1344. Assert.AreEqual("X", t.Rows[2].Cells[0].Paragraphs[0].Text);
  1345. Assert.AreEqual("X", t.Rows[0].Cells[2].Paragraphs[0].Text);
  1346. Assert.AreEqual("X", t.Rows[2].Cells[2].Paragraphs[0].Text);
  1347. Assert.IsTrue(String.IsNullOrEmpty(t.Rows[1].Cells[0].Paragraphs[0].Text));
  1348. Assert.IsTrue(String.IsNullOrEmpty(t.Rows[1].Cells[1].Paragraphs[0].Text));
  1349. Assert.IsTrue(String.IsNullOrEmpty(t.Rows[1].Cells[2].Paragraphs[0].Text));
  1350. Assert.IsTrue(String.IsNullOrEmpty(t.Rows[0].Cells[1].Paragraphs[0].Text));
  1351. Assert.IsTrue(String.IsNullOrEmpty(t.Rows[2].Cells[1].Paragraphs[0].Text));
  1352. }
  1353. }
  1354. [Test]
  1355. public void Test_Document_ApplyTemplate()
  1356. {
  1357. using (MemoryStream documentStream = new MemoryStream())
  1358. {
  1359. using (DocX document = DocX.Create(documentStream))
  1360. {
  1361. document.ApplyTemplate(Path.Combine(_directoryWithFiles, "Template.dotx"));
  1362. document.Save();
  1363. Header firstHeader = document.Headers.first;
  1364. Header oddHeader = document.Headers.odd;
  1365. Header evenHeader = document.Headers.even;
  1366. Footer firstFooter = document.Footers.first;
  1367. Footer oddFooter = document.Footers.odd;
  1368. Footer evenFooter = document.Footers.even;
  1369. Assert.IsTrue(firstHeader.Paragraphs.Count == 1, "More than one paragraph in header.");
  1370. Assert.IsTrue(firstHeader.Paragraphs[0].Text.Equals("First page header"), "Header isn't retrieved from template.");
  1371. Assert.IsTrue(oddHeader.Paragraphs.Count == 1, "More than one paragraph in header.");
  1372. Assert.IsTrue(oddHeader.Paragraphs[0].Text.Equals("Odd page header"), "Header isn't retrieved from template.");
  1373. Assert.IsTrue(evenHeader.Paragraphs.Count == 1, "More than one paragraph in header.");
  1374. Assert.IsTrue(evenHeader.Paragraphs[0].Text.Equals("Even page header"), "Header isn't retrieved from template.");
  1375. Assert.IsTrue(firstFooter.Paragraphs.Count == 1, "More than one paragraph in footer.");
  1376. Assert.IsTrue(firstFooter.Paragraphs[0].Text.Equals("First page footer"), "Footer isn't retrieved from template.");
  1377. Assert.IsTrue(oddFooter.Paragraphs.Count == 1, "More than one paragraph in footer.");
  1378. Assert.IsTrue(oddFooter.Paragraphs[0].Text.Equals("Odd page footer"), "Footer isn't retrieved from template.");
  1379. Assert.IsTrue(evenFooter.Paragraphs.Count == 1, "More than one paragraph in footer.");
  1380. Assert.IsTrue(evenFooter.Paragraphs[0].Text.Equals("Even page footer"), "Footer isn't retrieved from template.");
  1381. Paragraph firstParagraph = document.Paragraphs[0];
  1382. Assert.IsTrue(firstParagraph.StyleName.Equals("DocXSample"), "First paragraph isn't of style from template.");
  1383. }
  1384. }
  1385. }
  1386. [Test]
  1387. public void When_opening_a_template_no_error_should_be_thrown()
  1388. {
  1389. using (DocX document = DocX.Load(Path.Combine(_directoryWithFiles, "Template.dotx")))
  1390. {
  1391. Assert.IsTrue(document.Paragraphs.Count > 0);
  1392. }
  1393. }
  1394. [Test]
  1395. public void Saving_and_loading_a_template_should_work()
  1396. {
  1397. using (DocX document = DocX.Create(Path.Combine(_directoryDocuments, "test template.dotx"), DocumentTypes.Template))
  1398. {
  1399. document.InsertParagraph("hello, this is a paragraph");
  1400. document.Save();
  1401. }
  1402. using (DocX document = DocX.Load(Path.Combine(_directoryDocuments, "test template.dotx")))
  1403. {
  1404. Assert.IsTrue(document.Paragraphs.Count > 0);
  1405. }
  1406. }
  1407. [Test]
  1408. public void Test_ParentContainer_When_Creating_Doc()
  1409. {
  1410. using (DocX document = DocX.Create("Test.docx"))
  1411. {
  1412. document.AddHeaders();
  1413. Paragraph p1 = document.Headers.first.InsertParagraph("Test");
  1414. Assert.IsTrue(p1.ParentContainer == ContainerType.Header);
  1415. }
  1416. }
  1417. [Test]
  1418. public void Test_Section_Count_When_Creating_Doc()
  1419. {
  1420. //This adds a section break - so insert paragraphs, and follow it up by a section break/paragraph
  1421. using (DocX document = DocX.Create("TestSectionCount.docx"))
  1422. {
  1423. document.InsertSection();
  1424. var sections = document.GetSections();
  1425. Assert.AreEqual(sections.Count(), 2);
  1426. }
  1427. }
  1428. [Test]
  1429. public void Test_Sections_And_Paragraphs_When_Creating_Doc()
  1430. {
  1431. //This adds a section break - so insert paragraphs, and follow it up by a section break/paragraph
  1432. using (DocX document = DocX.Create("TestSectionAndParagraph.docx"))
  1433. {
  1434. //Add 2 paras and a break
  1435. document.InsertParagraph("First Para");
  1436. document.InsertParagraph("Second Para");
  1437. document.InsertSection();
  1438. document.InsertParagraph("This is default para");
  1439. var sections = document.GetSections();
  1440. Assert.AreEqual(sections.Count(), 2);
  1441. }
  1442. }
  1443. [Test]
  1444. public void Test_ParentContainer_When_Reading_Doc()
  1445. {
  1446. using (DocX document = DocX.Load(Path.Combine(_directoryWithFiles, "Tables.docx")))
  1447. {
  1448. ReadOnlyCollection<Paragraph> paragraphs = document.Paragraphs;
  1449. Paragraph p1 = paragraphs[0];
  1450. Assert.IsTrue(p1.ParentContainer == ContainerType.Cell);
  1451. }
  1452. }
  1453. [Test]
  1454. public void Test_Section_Count_When_Reading_Doc()
  1455. {
  1456. using (DocX document = DocX.Load(Path.Combine(_directoryWithFiles, "testdoc_SectionsWithSectionBreaks.docx")))
  1457. {
  1458. var sections = document.GetSections();
  1459. Assert.AreEqual(sections.Count(), 4);
  1460. }
  1461. }
  1462. [Test]
  1463. public void Test_Section_Paragraph_Count_Match_When_Reading_Doc()
  1464. {
  1465. using (DocX document = DocX.Load(Path.Combine(_directoryWithFiles, "testdoc_SectionsWithSectionBreaksMultiParagraph.docx")))
  1466. {
  1467. var sections = document.GetSections();
  1468. Assert.AreEqual(sections[0].SectionParagraphs.Count, 2);
  1469. Assert.AreEqual(sections[1].SectionParagraphs.Count, 1);
  1470. Assert.AreEqual(sections[2].SectionParagraphs.Count, 2);
  1471. Assert.AreEqual(sections[3].SectionParagraphs.Count, 1);
  1472. }
  1473. }
  1474. [Test]
  1475. public void Test_Section_Paragraph_Content_Match_When_Reading_Doc()
  1476. {
  1477. using (DocX document = DocX.Load(Path.Combine(_directoryWithFiles, "testdoc_SectionsWithSectionBreaks.docx")))
  1478. {
  1479. var sections = document.GetSections();
  1480. Assert.IsTrue(sections[0].SectionParagraphs[0].Text.Contains("Section 1"));
  1481. Assert.IsTrue(sections[1].SectionParagraphs[0].Text.Contains("Section 2"));
  1482. Assert.IsTrue(sections[2].SectionParagraphs[0].Text.Contains("Section 3"));
  1483. Assert.IsTrue(sections[3].SectionParagraphs[0].Text.Contains("Section 4"));
  1484. }
  1485. }
  1486. [Test]
  1487. public void Test_Ordered_List_When_Reading_Doc()
  1488. {
  1489. using (DocX document = DocX.Load(Path.Combine(_directoryWithFiles, "testdoc_OrderedList.docx")))
  1490. {
  1491. var sections = document.GetSections();
  1492. Assert.IsTrue(sections[0].SectionParagraphs[0].IsListItem);
  1493. Assert.IsTrue(sections[0].SectionParagraphs[1].IsListItem);
  1494. Assert.IsTrue(sections[0].SectionParagraphs[2].IsListItem);
  1495. Assert.AreEqual(sections[0].SectionParagraphs[0].ListItemType, ListItemType.Numbered);
  1496. Assert.AreEqual(sections[0].SectionParagraphs[1].ListItemType, ListItemType.Numbered);
  1497. Assert.AreEqual(sections[0].SectionParagraphs[2].ListItemType, ListItemType.Numbered);
  1498. }
  1499. }
  1500. [Test]
  1501. public void Test_Unordered_List_When_Reading_Doc()
  1502. {
  1503. using (DocX document = DocX.Load(Path.Combine(_directoryWithFiles, "testdoc_UnorderedList.docx")))
  1504. {
  1505. var sections = document.GetSections();
  1506. Assert.IsTrue(sections[0].SectionParagraphs[0].IsListItem);
  1507. Assert.IsTrue(sections[0].SectionParagraphs[1].IsListItem);
  1508. Assert.IsTrue(sections[0].SectionParagraphs[2].IsListItem);
  1509. Assert.AreEqual(sections[0].SectionParagraphs[0].ListItemType, ListItemType.Bulleted);
  1510. Assert.AreEqual(sections[0].SectionParagraphs[1].ListItemType, ListItemType.Bulleted);
  1511. Assert.AreEqual(sections[0].SectionParagraphs[2].ListItemType, ListItemType.Bulleted);
  1512. }
  1513. }
  1514. [Test]
  1515. public void Test_Ordered_Unordered_Lists_When_Reading_Doc()
  1516. {
  1517. using (DocX document = DocX.Load(Path.Combine(_directoryWithFiles, "testdoc_OrderedUnorderedLists.docx")))
  1518. {
  1519. var sections = document.GetSections();
  1520. Assert.IsTrue(sections[0].SectionParagraphs[0].IsListItem);
  1521. Assert.IsTrue(sections[0].SectionParagraphs[1].IsListItem);
  1522. Assert.IsTrue(sections[0].SectionParagraphs[2].IsListItem);
  1523. Assert.AreEqual(sections[0].SectionParagraphs[0].ListItemType, ListItemType.Numbered);
  1524. Assert.AreEqual(sections[0].SectionParagraphs[1].ListItemType, ListItemType.Numbered);
  1525. Assert.AreEqual(sections[0].SectionParagraphs[2].ListItemType, ListItemType.Numbered);
  1526. Assert.IsTrue(sections[0].SectionParagraphs[3].IsListItem);
  1527. Assert.IsTrue(sections[0].SectionParagraphs[4].IsListItem);
  1528. Assert.IsTrue(sections[0].SectionParagraphs[5].IsListItem);
  1529. Assert.AreEqual(sections[0].SectionParagraphs[3].ListItemType, ListItemType.Bulleted);
  1530. Assert.AreEqual(sections[0].SectionParagraphs[4].ListItemType, ListItemType.Bulleted);
  1531. Assert.AreEqual(sections[0].SectionParagraphs[5].ListItemType, ListItemType.Bulleted);
  1532. }
  1533. }
  1534. [Test]
  1535. public void WhenCreatingAnOrderedListTheListXmlShouldHaveNumberedListItemType()
  1536. {
  1537. using (DocX document = DocX.Create("TestListXmlNumbered.docx"))
  1538. {
  1539. const int level = 0;
  1540. XNamespace w = "http://schemas.openxmlformats.org/wordprocessingml/2006/main";
  1541. var list = document.AddList("First Item", level, ListItemType.Numbered);
  1542. document.InsertList(list);
  1543. var listNumPropNode = document.mainDoc.Descendants().First(s => s.Name.LocalName == "numPr");
  1544. var numId = listNumPropNode.Descendants().First(s => s.Name.LocalName == "numId");
  1545. var abstractNum = list.GetAbstractNum(int.Parse(numId.GetAttribute(w + "val")));
  1546. var lvl = abstractNum.Descendants().First(d => d.Name.LocalName == "lvl" && d.GetAttribute(w + "ilvl").Equals(level.ToString()));
  1547. var numFormat = lvl.Descendants().First(d => d.Name.LocalName == "numFmt");
  1548. Assert.AreEqual(numFormat.GetAttribute(w + "val").ToLower(), "decimal");
  1549. }
  1550. }
  1551. [Test]
  1552. public void WhenCreatingAnUnOrderedListTheListXmlShouldHaveBulletListItemType()
  1553. {
  1554. using (DocX document = DocX.Create("TestListXmlBullet.docx"))
  1555. {
  1556. var list = document.AddList("First Item", 0, ListItemType.Bulleted);
  1557. document.InsertList(list);
  1558. var listNumPropNode = document.mainDoc.Descendants().First(s => s.Name.LocalName == "numPr");
  1559. var numId = listNumPropNode.Descendants().First(s => s.Name.LocalName == "numId");
  1560. Assert.AreEqual(numId.Attribute(DocX.w + "val").Value, "1");
  1561. }
  1562. }
  1563. [Test]
  1564. public void WhenCreatingAListWithTextTheListXmlShouldHaveTheCorrectRunItemText()
  1565. {
  1566. using (DocX document = DocX.Create("TestListCreate.docx"))
  1567. {
  1568. const string listText = "RunText";
  1569. var list = document.AddList(listText, 0, ListItemType.Bulleted);
  1570. document.InsertList(list);
  1571. var listNumPropNode = document.mainDoc.Descendants().First(s => s.Name.LocalName == "numPr");
  1572. var runTextNode = document.mainDoc.Descendants().First(s => s.Name.LocalName == "t");
  1573. Assert.IsNotNull(listNumPropNode);
  1574. Assert.AreEqual(list.Items.First().runs.First().Value, runTextNode.Value);
  1575. Assert.AreEqual(listText, runTextNode.Value);
  1576. }
  1577. }
  1578. [Test]
  1579. public void WhenCreatingAnOrderedListTheListShouldHaveNumberedListItemType()
  1580. {
  1581. using (DocX document = DocX.Create("TestListCreateOrderedList.docx"))
  1582. {
  1583. var list = document.AddList("First Item");
  1584. Assert.AreEqual(list.ListType, ListItemType.Numbered);
  1585. }
  1586. }
  1587. [Test]
  1588. public void WhenCreatingAnUnOrderedListTheListShouldHaveBulletListItemType()
  1589. {
  1590. using (DocX document = DocX.Create("TestListCreateUnorderedList.docx"))
  1591. {
  1592. var list = document.AddList("First Item", 0, ListItemType.Bulleted);
  1593. Assert.AreEqual(list.ListType, ListItemType.Bulleted);
  1594. }
  1595. }
  1596. [Test]
  1597. public void WhenCreatingAListWithTextTheListShouldHaveTheCorrectRunItemText()
  1598. {
  1599. using (DocX document = DocX.Create("TestListCreateRunText.docx"))
  1600. {
  1601. var list = document.AddList("RunText", 0, ListItemType.Bulleted);
  1602. document.InsertList(list);
  1603. Assert.AreEqual(list.Items.First().runs.First().Value, "RunText");
  1604. }
  1605. }
  1606. [Test]
  1607. public void WhenCreatingAListTheNumberingShouldGetSaved()
  1608. {
  1609. }
  1610. [Test]
  1611. public void WhenCreatingAListTheListStyleShouldExistOrBeCreated()
  1612. {
  1613. using (DocX document = DocX.Create("TestListStyle.docx"))
  1614. {
  1615. var style = document.AddStylesForList();
  1616. XNamespace w = "http://schemas.openxmlformats.org/wordprocessingml/2006/main";
  1617. bool listStyleExists =
  1618. (
  1619. from s in style.Element(w + "styles").Elements()
  1620. let styleId = s.Attribute(XName.Get("styleId", w.NamespaceName))
  1621. where (styleId != null && styleId.Value == "ListParagraph")
  1622. select s
  1623. ).Any();
  1624. Assert.IsTrue(listStyleExists);
  1625. }
  1626. }
  1627. [Test]
  1628. public void ANewListItemShouldCreateAnAbstractNumberingEntry()
  1629. {
  1630. using (DocX document = DocX.Create("TestNumbering.docx"))
  1631. {
  1632. var numbering = document.numbering.Descendants().Where(d => d.Name.LocalName == "abstractNum");
  1633. Assert.IsFalse(numbering.Any());
  1634. document.AddList("List Text");
  1635. numbering = document.numbering.Descendants().Where(d => d.Name.LocalName == "abstractNum");
  1636. Assert.IsTrue(numbering.Any());
  1637. }
  1638. }
  1639. [Test]
  1640. public void ANewListItemShouldCreateANewNumEntry()
  1641. {
  1642. using (DocX document = DocX.Create("TestNumEntry.docx"))
  1643. {
  1644. var numbering = document.numbering.Descendants().Where(d => d.Name.LocalName == "num");
  1645. Assert.IsFalse(numbering.Any());
  1646. document.AddList("List Text");
  1647. numbering = document.numbering.Descendants().Where(d => d.Name.LocalName == "num");
  1648. Assert.IsTrue(numbering.Any());
  1649. }
  1650. }
  1651. [Test]
  1652. public void CreateNewNumberingNumIdShouldAddNumberingDataToTheDocument()
  1653. {
  1654. using (DocX document = DocX.Create("TestCreateNumbering.docx"))
  1655. {
  1656. var numbering = document.numbering.Descendants().Where(d => d.Name.LocalName == "num");
  1657. Assert.IsFalse(numbering.Any());
  1658. var list = document.AddList("", 0, ListItemType.Bulleted);
  1659. document.InsertList(list);
  1660. numbering = document.numbering.Descendants().Where(d => d.Name.LocalName == "num");
  1661. Assert.IsTrue(numbering.Any());
  1662. }
  1663. }
  1664. [Test]
  1665. public void CreateNewNumberingNumIdShouldAddNumberingAbstractDataToTheDocument()
  1666. {
  1667. using (DocX document = DocX.Create("TestCreateNumberingAbstract.docx"))
  1668. {
  1669. var numbering = document.numbering.Descendants().Where(d => d.Name.LocalName == "abstractNum");
  1670. Assert.IsFalse(numbering.Any());
  1671. var list = document.AddList("", 0, ListItemType.Bulleted);
  1672. document.InsertList(list);
  1673. numbering = document.numbering.Descendants().Where(d => d.Name.LocalName == "abstractNum");
  1674. Assert.IsTrue(numbering.Any());
  1675. }
  1676. }
  1677. [Test]
  1678. public void IfPreviousElementIsAListThenAddingANewListContinuesThePreviousList()
  1679. {
  1680. using (DocX document = DocX.Create(Path.Combine(_directoryDocuments, "TestAddListToPreviousList.docx")))
  1681. {
  1682. var list = document.AddList("List Text");
  1683. document.AddListItem(list, "List Text2");
  1684. document.InsertList(list);
  1685. var lvlNodes = document.mainDoc.Descendants().Where(s => s.Name.LocalName == "ilvl").ToList();
  1686. var numIdNodes = document.mainDoc.Descendants().Where(s => s.Name.LocalName == "numId").ToList();
  1687. Assert.AreEqual(lvlNodes.Count(), 2);
  1688. Assert.AreEqual(numIdNodes.Count(), 2);
  1689. var prevLvlNode = lvlNodes[0];
  1690. var newLvlNode = lvlNodes[1];
  1691. Assert.AreEqual(prevLvlNode.Attribute(DocX.w + "val").Value, newLvlNode.Attribute(DocX.w + "val").Value);
  1692. var prevNumIdNode = numIdNodes[0];
  1693. var newNumIdNode = numIdNodes[1];
  1694. Assert.AreEqual(prevNumIdNode.Attribute(DocX.w + "val").Value, newNumIdNode.Attribute(DocX.w + "val").Value);
  1695. document.Save();
  1696. }
  1697. }
  1698. [Test]
  1699. public void WhenADocumentHasListsTheListPropertyReturnsTheCorrectNumberOfLists()
  1700. {
  1701. using (DocX document = DocX.Load(Path.Combine(_directoryWithFiles, "testdoc_OrderedUnorderedLists.docx")))
  1702. {
  1703. var lists = document.Lists;
  1704. Assert.AreEqual(lists.Count, 2);
  1705. }
  1706. }
  1707. [Test]
  1708. public void WhenADocumentIsCreatedWithAListItemThatHasASpecifiedStartNumber()
  1709. {
  1710. using (DocX document = DocX.Create("CreateListItemFromDifferentStartValue.docx"))
  1711. {
  1712. var list = document.AddList("Test", 0, ListItemType.Numbered, 5);
  1713. document.AddListItem(list, "NewElement");
  1714. var numbering = document.numbering.Descendants().Where(d => d.Name.LocalName == "abstractNum");
  1715. var level = numbering.Descendants().First(el => el.Name.LocalName == "lvl");
  1716. var start = level.Descendants().First(el => el.Name.LocalName == "start");
  1717. Assert.AreEqual(start.GetAttribute(DocX.w + "val"), 5.ToString());
  1718. }
  1719. }
  1720. [Test]
  1721. public void WhenANumberedAndBulletedListIsCreatedThereShouldBeTwoNumberingXmls()
  1722. {
  1723. using (DocX document = DocX.Create("NumberAndBulletListInOne.docx"))
  1724. {
  1725. var numberList = document.AddList("Test");
  1726. document.AddListItem(numberList, "Second Numbered Item");
  1727. var bulletedList = document.AddList("Bullet", 0, ListItemType.Bulleted);
  1728. document.AddListItem(bulletedList, "Second bullet item");
  1729. document.InsertList(numberList);
  1730. document.InsertList(bulletedList);
  1731. var abstractNums = document.numbering.Descendants().Where(d => d.Name.LocalName == "abstractNum");
  1732. Assert.AreEqual(abstractNums.Count(), 2);
  1733. }
  1734. }
  1735. [Test]
  1736. public void WhenICreateAnEmptyListAndAddEntriesToIt()
  1737. {
  1738. using (DocX document = DocX.Create("CreateEmptyListAndAddItemsToIt.docx"))
  1739. {
  1740. var list = document.AddList();
  1741. Assert.AreEqual(list.Items.Count, 0);
  1742. document.AddListItem(list, "Test item 1.");
  1743. document.AddListItem(list, "Test item 2.");
  1744. Assert.AreEqual(list.Items.Count, 2);
  1745. }
  1746. }
  1747. [Test]
  1748. public void WhenICreateAHeaderItShouldHaveAStyle()
  1749. {
  1750. using (var document = DocX.Create(Path.Combine(_directoryDocuments, "CreateHeaderElement.docx")))
  1751. {
  1752. document.InsertParagraph("Header Text 1").StyleName = "Header1";
  1753. Assert.IsNotNull(document.styles.Root.Descendants().FirstOrDefault(d => d.GetAttribute(DocX.w + "styleId").ToLowerInvariant() == "heading1"));
  1754. document.Save();
  1755. }
  1756. }
  1757. [Test]
  1758. public void ParagraphAppendHyperLink_ParagraphIsListItem_ShouldNotThrow()
  1759. {
  1760. using (var document = DocX.Create(Path.Combine(_directoryDocuments, "HyperlinkList.docx")))
  1761. {
  1762. var list = document.AddList("Item 1", listType: ListItemType.Numbered);
  1763. document.AddListItem(list, "Item 2");
  1764. document.AddListItem(list, "Item 3");
  1765. Uri uri;
  1766. Uri.TryCreate("http://www.google.com", UriKind.RelativeOrAbsolute, out uri);
  1767. var hLink = document.AddHyperlink("Google", uri);
  1768. var item2 = list.Items[1];
  1769. item2.InsertText("\nMore text\n");
  1770. item2.AppendHyperlink(hLink);
  1771. item2.InsertText("\nEven more text");
  1772. document.InsertList(list);
  1773. document.Save();
  1774. }
  1775. }
  1776. [Test]
  1777. public void WhileReadingWhenTextIsBoldItalicUnderlineItShouldReadTheProperFormatting()
  1778. {
  1779. using (DocX document = DocX.Load(Path.Combine(_directoryWithFiles, "FontFormat.docx")))
  1780. {
  1781. var underlinedTextFormatting = document.Paragraphs[0].MagicText[0].formatting;
  1782. var boldTextFormatting = document.Paragraphs[0].MagicText[2].formatting;
  1783. var italicTextFormatting = document.Paragraphs[0].MagicText[4].formatting;
  1784. var boldItalicUnderlineTextFormatting = document.Paragraphs[0].MagicText[6].formatting;
  1785. Assert.IsTrue(boldTextFormatting.Bold.HasValue && boldTextFormatting.Bold.Value);
  1786. Assert.IsTrue(italicTextFormatting.Italic.HasValue && italicTextFormatting.Italic.Value);
  1787. Assert.AreEqual(underlinedTextFormatting.UnderlineStyle, UnderlineStyle.singleLine);
  1788. Assert.IsTrue(boldItalicUnderlineTextFormatting.Bold.HasValue && boldItalicUnderlineTextFormatting.Bold.Value);
  1789. Assert.IsTrue(boldItalicUnderlineTextFormatting.Italic.HasValue && boldItalicUnderlineTextFormatting.Italic.Value);
  1790. Assert.AreEqual(boldItalicUnderlineTextFormatting.UnderlineStyle, UnderlineStyle.singleLine);
  1791. }
  1792. }
  1793. [Test]
  1794. public void WhileWritingWhenTextIsBoldItalicUnderlineItShouldReadTheProperFormatting()
  1795. {
  1796. using (DocX document = DocX.Create("FontFormatWrite.docx"))
  1797. {
  1798. Paragraph p = document.InsertParagraph();
  1799. p.Append("This is bold.").Bold().Append("This is underlined.").UnderlineStyle(UnderlineStyle.singleLine).
  1800. Append("This is italic.").Italic().Append("This is boldItalicUnderlined").Italic().Bold().UnderlineStyle(UnderlineStyle.singleLine);
  1801. var boldTextFormatting = document.Paragraphs[0].MagicText[0].formatting;
  1802. var underlinedTextFormatting = document.Paragraphs[0].MagicText[1].formatting;
  1803. var italicTextFormatting = document.Paragraphs[0].MagicText[2].formatting;
  1804. var boldItalicUnderlineTextFormatting = document.Paragraphs[0].MagicText[3].formatting;
  1805. Assert.IsTrue(boldTextFormatting.Bold.HasValue && boldTextFormatting.Bold.Value);
  1806. Assert.IsTrue(italicTextFormatting.Italic.HasValue && italicTextFormatting.Italic.Value);
  1807. Assert.AreEqual(underlinedTextFormatting.UnderlineStyle, UnderlineStyle.singleLine);
  1808. Assert.IsTrue(boldItalicUnderlineTextFormatting.Bold.HasValue && boldItalicUnderlineTextFormatting.Bold.Value);
  1809. Assert.IsTrue(boldItalicUnderlineTextFormatting.Italic.HasValue && boldItalicUnderlineTextFormatting.Italic.Value);
  1810. Assert.AreEqual(boldItalicUnderlineTextFormatting.UnderlineStyle, UnderlineStyle.singleLine);
  1811. }
  1812. }
  1813. [Test]
  1814. public void InsertingANextPageBreakShouldAddADocumentSection()
  1815. {
  1816. using (DocX document = DocX.Create(Path.Combine(_directoryDocuments, "SectionPageBreak.docx")))
  1817. {
  1818. document.InsertSectionPageBreak();
  1819. var sections = document.GetSections();
  1820. Assert.AreEqual(sections.Count, 2);
  1821. document.Save();
  1822. }
  1823. }
  1824. [Test]
  1825. public void InsertANextPageBreakWithParagraphTextsShouldAddProperParagraphsToProperSections()
  1826. {
  1827. using (DocX document = DocX.Create(Path.Combine(_directoryDocuments, "SectionPageBreakWithParagraphs.docx")))
  1828. {
  1829. document.InsertParagraph("First paragraph.");
  1830. document.InsertParagraph("Second paragraph.");
  1831. document.InsertSectionPageBreak();
  1832. document.InsertParagraph("Third paragraph.");
  1833. document.InsertParagraph("Fourth paragraph.");
  1834. var sections = document.GetSections();
  1835. Assert.AreEqual(sections.Count, 2);
  1836. Assert.AreEqual(sections[0].SectionParagraphs.Count(p => !string.IsNullOrWhiteSpace(p.Text)), 2);
  1837. Assert.AreEqual(sections[1].SectionParagraphs.Count(p => !string.IsNullOrWhiteSpace(p.Text)), 2);
  1838. document.Save();
  1839. }
  1840. }
  1841. [Test]
  1842. public void WhenAFontFamilyIsSpecifiedForAParagraphItShouldSetTheFontOfTheParagraphTextToTheFontFamily()
  1843. {
  1844. using (DocX document = DocX.Create(Path.Combine(_directoryDocuments, "FontTest.docx")))
  1845. {
  1846. Paragraph p = document.InsertParagraph();
  1847. var fontFamily = new FontFamily("Symbol");
  1848. p.Append("Hello World").Font(fontFamily);
  1849. Assert.AreEqual(p.MagicText[0].formatting.FontFamily.Name, fontFamily.Name);
  1850. document.Save();
  1851. }
  1852. }
  1853. [Test]
  1854. public void Test_Paragraph_RemoveTextManyLetters()
  1855. {
  1856. using (DocX document = DocX.Create(@"HelloWorldRemovingManyLetters.docx"))
  1857. {
  1858. Paragraph p3 = document.InsertParagraph("");
  1859. p3.Xml = XElement.Parse(
  1860. @"<w:p xmlns:w=""http://schemas.openxmlformats.org/wordprocessingml/2006/main"">
  1861. <w:pPr>
  1862. <w:ind />
  1863. </w:pPr>
  1864. <w:r>
  1865. <w:t>Based on the previous screening criteria, you qualify to participate in this particular survey. At the completion of the survey, you will be notified that your responses have been received and honoraria information will be captured for future payment. Thank you in advance for taking the time to participate with us. ^f('xMinutes').get() == 'xx' ? """" : ""</w:t>
  1866. </w:r>
  1867. <w:r>
  1868. <w:rPr>
  1869. <w:lang w:val=""pl-PL"" />
  1870. </w:rPr>
  1871. <w:t xml:space=""preserve"">This survey should take </w:t>
  1872. </w:r>
  1873. <w:r>
  1874. <w:t>"" + f('xMinutes').get() + ""</w:t>
  1875. </w:r>
  1876. <w:r>
  1877. <w:rPr>
  1878. <w:lang w:val=""pl-PL"" />
  1879. </w:rPr>
  1880. <w:t xml:space=""preserve""> minutes. </w:t>
  1881. </w:r>
  1882. <w:r>
  1883. <w:t>""^Participants completing this survey will receive the honorarium designated in the invitation you have received. &lt;BR&gt;&lt;BR&gt;If you leave the survey prior to finishing it, you may return to your last question by visiting the same link provided in your email invitation (please be certain to use the same email that you used a moment ago to register for this study). If you have any questions or concerns about this study, please contact us at &lt;a href=""mailto:blabla@blabla.com?Subject=^f('sName')^ PD:^f('pdID')^""&gt;blabla@blabla.com&lt;/a&gt;. Thank you.</w:t>
  1884. </w:r>
  1885. </w:p>");
  1886. int l1 = p3.Text.Length; //960
  1887. p3.RemoveText(318, 99);
  1888. int l2 = p3.Text.Length; //should be 861
  1889. Assert.AreEqual(l1 - 99, l2);
  1890. }
  1891. }
  1892. [Test]
  1893. public void Test_Table_RemoveParagraphs()
  1894. {
  1895. MemoryStream memoryStream;
  1896. DocX document;
  1897. memoryStream = new MemoryStream();
  1898. document = DocX.Create(memoryStream);
  1899. // Add a Table into the document.
  1900. Table table = document.AddTable(1, 4); // 1 row, 4 cells
  1901. table.Design = TableDesign.TableGrid;
  1902. table.Alignment = Alignment.center;
  1903. // Edit row
  1904. var row = table.Rows[0];
  1905. // Fill 1st paragraph
  1906. row.Cells[0].Paragraphs.ElementAt(0).Append("Paragraph 1");
  1907. // Fill 2nd paragraph
  1908. var secondParagraph = row.Cells[0].InsertParagraph("Paragraph 2");
  1909. // Check number of paragraphs
  1910. Assert.AreEqual(2, row.Cells[0].Paragraphs.Count());
  1911. // Remove 1st paragraph
  1912. var deleted = row.Cells[0].RemoveParagraphAt(0);
  1913. Assert.IsTrue(deleted);
  1914. // Check number of paragraphs
  1915. Assert.AreEqual(1, row.Cells[0].Paragraphs.Count());
  1916. // Remove 3rd (nonexisting) paragraph
  1917. deleted = row.Cells[0].RemoveParagraphAt(3);
  1918. Assert.IsFalse(deleted);
  1919. //check number of paragraphs
  1920. Assert.AreEqual(1, row.Cells[0].Paragraphs.Count());
  1921. // Remove secondParagraph (this time the only one) paragraph
  1922. deleted = row.Cells[0].RemoveParagraph(secondParagraph);
  1923. Assert.IsTrue(deleted);
  1924. Assert.AreEqual(0, row.Cells[0].Paragraphs.Count());
  1925. // Remove last paragraph once again - this time this paragraph does not exists
  1926. deleted = row.Cells[0].RemoveParagraph(secondParagraph);
  1927. Assert.IsFalse(deleted);
  1928. Assert.AreEqual(0, row.Cells[0].Paragraphs.Count());
  1929. }
  1930. [Test]
  1931. public void GenerateHeadingTestDocument()
  1932. {
  1933. using (DocX document = DocX.Create(Path.Combine(_directoryDocuments, @"Document Header Test.docx")))
  1934. {
  1935. foreach (HeadingType heading in (HeadingType[])Enum.GetValues(typeof(HeadingType)))
  1936. {
  1937. string text = string.Format("{0} - The quick brown fox jumps over the lazy dog", heading.EnumDescription());
  1938. Paragraph p = document.InsertParagraph();
  1939. p.AppendLine(text).Heading(heading);
  1940. }
  1941. document.Save();
  1942. }
  1943. }
  1944. [Test]
  1945. public void CreateTableOfContents_WithTitleAndSwitches_SetsExpectedXml()
  1946. {
  1947. using (var document = DocX.Create("TableOfContents Test.docx"))
  1948. {
  1949. const string title = "TestTitle";
  1950. const int rightPos = 9350;
  1951. const TableOfContentsSwitches switches =
  1952. TableOfContentsSwitches.O | TableOfContentsSwitches.H | TableOfContentsSwitches.Z |
  1953. TableOfContentsSwitches.U;
  1954. var toc = TableOfContents.CreateTableOfContents(document, title, switches);
  1955. const string switchString = @"TOC \h \o '1-3' \u \z";
  1956. var expectedString = string.Format(XmlTemplateBases.TocXmlBase, "TOCHeading", title, rightPos, switchString);
  1957. var expectedReader = XmlReader.Create(new StringReader(expectedString));
  1958. var expected = XElement.Load(expectedReader);
  1959. Assert.IsTrue(XNode.DeepEquals(expected, toc.Xml));
  1960. }
  1961. }
  1962. [Test]
  1963. public void CreateTableOfContents_WithTitleSwitchesHeaderStyleLastIncludeLevelRightTabPos_SetsExpectedXml()
  1964. {
  1965. using (var document = DocX.Create("TableOfContents Test.docx"))
  1966. {
  1967. const string title = "TestTitle";
  1968. const int rightPos = 1337;
  1969. const string style = "TestStyle";
  1970. const TableOfContentsSwitches switches =
  1971. TableOfContentsSwitches.O | TableOfContentsSwitches.H | TableOfContentsSwitches.Z |
  1972. TableOfContentsSwitches.U;
  1973. var toc = TableOfContents.CreateTableOfContents(document, title, switches, style, 6, rightPos);
  1974. const string switchString = @"TOC \h \o '1-6' \u \z";
  1975. var expectedString = string.Format(XmlTemplateBases.TocXmlBase, style, title, rightPos, switchString);
  1976. var expectedReader = XmlReader.Create(new StringReader(expectedString));
  1977. var expected = XElement.Load(expectedReader);
  1978. Assert.IsTrue(XNode.DeepEquals(expected, toc.Xml));
  1979. }
  1980. }
  1981. [Test]
  1982. public void CreateTableOfContents_WhenCalled_AddsUpdateFieldsWithValueTrueToSettings()
  1983. {
  1984. using (var document = DocX.Create("TableOfContents Test.docx"))
  1985. {
  1986. const string title = "TestTitle";
  1987. const TableOfContentsSwitches switches =
  1988. TableOfContentsSwitches.O | TableOfContentsSwitches.H | TableOfContentsSwitches.Z |
  1989. TableOfContentsSwitches.U;
  1990. TableOfContents.CreateTableOfContents(document, title, switches);
  1991. var updateField = document.settings.Descendants().FirstOrDefault(x => x.Name == DocX.w + "updateFields");
  1992. Assert.IsNotNull(updateField);
  1993. Assert.AreEqual("true", updateField.Attribute(DocX.w + "val").Value);
  1994. }
  1995. }
  1996. [Test]
  1997. public void CreateTableOfContents_WhenCalledSettingsAlreadyHasUpdateFields_DoesNotAddUpdateFields()
  1998. {
  1999. using (var document = DocX.Create("TableOfContents Test.docx"))
  2000. {
  2001. var element = new XElement(XName.Get("updateFields", DocX.w.NamespaceName), new XAttribute(DocX.w + "val", true));
  2002. document.settings.Root.Add(element);
  2003. const string title = "TestTitle";
  2004. const TableOfContentsSwitches switches =
  2005. TableOfContentsSwitches.O | TableOfContentsSwitches.H | TableOfContentsSwitches.Z |
  2006. TableOfContentsSwitches.U;
  2007. TableOfContents.CreateTableOfContents(document, title, switches);
  2008. var updateFields = document.settings.Descendants().Single(x => x.Name == DocX.w + "updateFields");
  2009. Assert.AreSame(element, updateFields);
  2010. }
  2011. }
  2012. [Test]
  2013. public void CreteTableOfContents_TocHeadingStyleIsNotPresent_AddsTocHeaderStyle()
  2014. {
  2015. using (var document = DocX.Create("TableOfContents Test.docx"))
  2016. {
  2017. const string title = "TestTitle";
  2018. const string headerStyle = "TestStyle";
  2019. const TableOfContentsSwitches switches =
  2020. TableOfContentsSwitches.O | TableOfContentsSwitches.H | TableOfContentsSwitches.Z |
  2021. TableOfContentsSwitches.U;
  2022. TableOfContents.CreateTableOfContents(document, title, switches, headerStyle);
  2023. var expectedString = string.Format(XmlTemplateBases.TocHeadingStyleBase, headerStyle);
  2024. var expectedReader = XmlReader.Create(new StringReader(expectedString));
  2025. var expected = XElement.Load(expectedReader);
  2026. var actual = document.styles.Root.Descendants().FirstOrDefault(x =>
  2027. x.Name.Equals(DocX.w + "style") &&
  2028. x.Attribute(DocX.w + "type").Value.Equals("paragraph") &&
  2029. x.Attribute(DocX.w + "styleId").Value.Equals(headerStyle));
  2030. Assert.IsTrue(XNode.DeepEquals(expected, actual));
  2031. }
  2032. }
  2033. [Test]
  2034. public void CreteTableOfContents_Toc1StyleIsNotPresent_AddsToc1Style()
  2035. {
  2036. using (var document = DocX.Create("TableOfContents Test.docx"))
  2037. {
  2038. const string title = "TestTitle";
  2039. const TableOfContentsSwitches switches =
  2040. TableOfContentsSwitches.O | TableOfContentsSwitches.H | TableOfContentsSwitches.Z |
  2041. TableOfContentsSwitches.U;
  2042. TableOfContents.CreateTableOfContents(document, title, switches);
  2043. var expectedString = string.Format(XmlTemplateBases.TocElementStyleBase, "TOC1", "toc 1");
  2044. var expectedReader = XmlReader.Create(new StringReader(expectedString));
  2045. var expected = XElement.Load(expectedReader);
  2046. var actual = document.styles.Root.Descendants().FirstOrDefault(x =>
  2047. x.Name.Equals(DocX.w + "style") &&
  2048. x.Attribute(DocX.w + "type").Value.Equals("paragraph") &&
  2049. x.Attribute(DocX.w + "styleId").Value.Equals("TOC1"));
  2050. Assert.IsTrue(XNode.DeepEquals(expected, actual));
  2051. }
  2052. }
  2053. [Test]
  2054. public void CreteTableOfContents_Toc2StyleIsNotPresent_AddsToc2Style()
  2055. {
  2056. using (var document = DocX.Create("TableOfContents Test.docx"))
  2057. {
  2058. const string title = "TestTitle";
  2059. const TableOfContentsSwitches switches =
  2060. TableOfContentsSwitches.O | TableOfContentsSwitches.H | TableOfContentsSwitches.Z |
  2061. TableOfContentsSwitches.U;
  2062. TableOfContents.CreateTableOfContents(document, title, switches);
  2063. var expectedString = string.Format(XmlTemplateBases.TocElementStyleBase, "TOC2", "toc 2");
  2064. var expectedReader = XmlReader.Create(new StringReader(expectedString));
  2065. var expected = XElement.Load(expectedReader);
  2066. var actual = document.styles.Root.Descendants().FirstOrDefault(x =>
  2067. x.Name.Equals(DocX.w + "style") &&
  2068. x.Attribute(DocX.w + "type").Value.Equals("paragraph") &&
  2069. x.Attribute(DocX.w + "styleId").Value.Equals("TOC2"));
  2070. Assert.IsTrue(XNode.DeepEquals(expected, actual));
  2071. }
  2072. }
  2073. [Test]
  2074. public void CreteTableOfContents_Toc3StyleIsNotPresent_AddsToc3tyle()
  2075. {
  2076. using (var document = DocX.Create("TableOfContents Test.docx"))
  2077. {
  2078. const string title = "TestTitle";
  2079. const TableOfContentsSwitches switches =
  2080. TableOfContentsSwitches.O | TableOfContentsSwitches.H | TableOfContentsSwitches.Z |
  2081. TableOfContentsSwitches.U;
  2082. TableOfContents.CreateTableOfContents(document, title, switches);
  2083. var expectedString = string.Format(XmlTemplateBases.TocElementStyleBase, "TOC3", "toc 3");
  2084. var expectedReader = XmlReader.Create(new StringReader(expectedString));
  2085. var expected = XElement.Load(expectedReader);
  2086. var actual = document.styles.Root.Descendants().FirstOrDefault(x =>
  2087. x.Name.Equals(DocX.w + "style") &&
  2088. x.Attribute(DocX.w + "type").Value.Equals("paragraph") &&
  2089. x.Attribute(DocX.w + "styleId").Value.Equals("TOC3"));
  2090. Assert.IsTrue(XNode.DeepEquals(expected, actual));
  2091. }
  2092. }
  2093. [Test]
  2094. public void CreteTableOfContents_Toc4StyleIsNotPresent_AddsToc4Style()
  2095. {
  2096. using (var document = DocX.Create("TableOfContents Test.docx"))
  2097. {
  2098. const string title = "TestTitle";
  2099. const TableOfContentsSwitches switches =
  2100. TableOfContentsSwitches.O | TableOfContentsSwitches.H | TableOfContentsSwitches.Z |
  2101. TableOfContentsSwitches.U;
  2102. TableOfContents.CreateTableOfContents(document, title, switches);
  2103. var expectedString = string.Format(XmlTemplateBases.TocElementStyleBase, "TOC4", "toc 4");
  2104. var expectedReader = XmlReader.Create(new StringReader(expectedString));
  2105. var expected = XElement.Load(expectedReader);
  2106. var actual = document.styles.Root.Descendants().FirstOrDefault(x =>
  2107. x.Name.Equals(DocX.w + "style") &&
  2108. x.Attribute(DocX.w + "type").Value.Equals("paragraph") &&
  2109. x.Attribute(DocX.w + "styleId").Value.Equals("TOC4"));
  2110. Assert.IsTrue(XNode.DeepEquals(expected, actual));
  2111. }
  2112. }
  2113. [Test]
  2114. public void CreteTableOfContents_HyperlinkStyleIsNotPresent_AddsHyperlinkStyle()
  2115. {
  2116. using (var document = DocX.Create("TableOfContents Test.docx"))
  2117. {
  2118. const string title = "TestTitle";
  2119. const TableOfContentsSwitches switches =
  2120. TableOfContentsSwitches.O | TableOfContentsSwitches.H | TableOfContentsSwitches.Z |
  2121. TableOfContentsSwitches.U;
  2122. TableOfContents.CreateTableOfContents(document, title, switches);
  2123. var expectedString = XmlTemplateBases.TocHyperLinkStyleBase;
  2124. var expectedReader = XmlReader.Create(new StringReader(expectedString));
  2125. var expected = XElement.Load(expectedReader);
  2126. var actual = document.styles.Root.Descendants().FirstOrDefault(x =>
  2127. x.Name.Equals(DocX.w + "style") &&
  2128. x.Attribute(DocX.w + "type").Value.Equals("character") &&
  2129. x.Attribute(DocX.w + "styleId").Value.Equals("Hyperlink"));
  2130. Assert.IsTrue(XNode.DeepEquals(expected, actual));
  2131. }
  2132. }
  2133. [Test]
  2134. public void CreteTableOfContents_TocHeadingStyleIsPresent_DoesNotAddTocHeaderStyle()
  2135. {
  2136. using (var document = DocX.Create("TableOfContents Test.docx"))
  2137. {
  2138. const string title = "TestTitle";
  2139. const string headerStyle = "TestStyle";
  2140. const TableOfContentsSwitches switches =
  2141. TableOfContentsSwitches.O | TableOfContentsSwitches.H | TableOfContentsSwitches.Z |
  2142. TableOfContentsSwitches.U;
  2143. var xElement = XElement.Load(XmlReader.Create(new StringReader(string.Format(XmlTemplateBases.TocHeadingStyleBase, headerStyle))));
  2144. document.styles.Root.Add(xElement);
  2145. TableOfContents.CreateTableOfContents(document, title, switches, headerStyle);
  2146. var actual = document.styles.Root.Descendants().Single(x =>
  2147. x.Name.Equals(DocX.w + "style") &&
  2148. x.Attribute(DocX.w + "type").Value.Equals("paragraph") &&
  2149. x.Attribute(DocX.w + "styleId").Value.Equals(headerStyle));
  2150. Assert.AreSame(xElement, actual);
  2151. }
  2152. }
  2153. [Test]
  2154. public void CreteTableOfContents_Toc1StyleIsPresent_DoesNotAddToc1Style()
  2155. {
  2156. using (var document = DocX.Create("TableOfContents Test.docx"))
  2157. {
  2158. const string title = "TestTitle";
  2159. const string headerStyle = "TestStyle";
  2160. const TableOfContentsSwitches switches =
  2161. TableOfContentsSwitches.O | TableOfContentsSwitches.H | TableOfContentsSwitches.Z |
  2162. TableOfContentsSwitches.U;
  2163. var xElement = XElement.Load(XmlReader.Create(new StringReader(string.Format(XmlTemplateBases.TocElementStyleBase, "TOC1", "toc 1"))));
  2164. document.styles.Root.Add(xElement);
  2165. TableOfContents.CreateTableOfContents(document, title, switches, headerStyle);
  2166. var actual = document.styles.Root.Descendants().Single(x =>
  2167. x.Name.Equals(DocX.w + "style") &&
  2168. x.Attribute(DocX.w + "type").Value.Equals("paragraph") &&
  2169. x.Attribute(DocX.w + "styleId").Value.Equals("TOC1"));
  2170. Assert.AreSame(xElement, actual);
  2171. }
  2172. }
  2173. [Test]
  2174. public void CreteTableOfContents_Toc2StyleIsPresent_DoesNotAddToc2Style()
  2175. {
  2176. using (var document = DocX.Create("TableOfContents Test.docx"))
  2177. {
  2178. const string title = "TestTitle";
  2179. const string headerStyle = "TestStyle";
  2180. const TableOfContentsSwitches switches =
  2181. TableOfContentsSwitches.O | TableOfContentsSwitches.H | TableOfContentsSwitches.Z |
  2182. TableOfContentsSwitches.U;
  2183. var xElement = XElement.Load(XmlReader.Create(new StringReader(string.Format(XmlTemplateBases.TocElementStyleBase, "TOC2", "toc 2"))));
  2184. document.styles.Root.Add(xElement);
  2185. TableOfContents.CreateTableOfContents(document, title, switches, headerStyle);
  2186. var actual = document.styles.Root.Descendants().Single(x =>
  2187. x.Name.Equals(DocX.w + "style") &&
  2188. x.Attribute(DocX.w + "type").Value.Equals("paragraph") &&
  2189. x.Attribute(DocX.w + "styleId").Value.Equals("TOC2"));
  2190. Assert.AreSame(xElement, actual);
  2191. }
  2192. }
  2193. [Test]
  2194. public void CreteTableOfContents_Toc3StyleIsPresent_DoesNotAddToc3Style()
  2195. {
  2196. using (var document = DocX.Create("TableOfContents Test.docx"))
  2197. {
  2198. const string title = "TestTitle";
  2199. const string headerStyle = "TestStyle";
  2200. const TableOfContentsSwitches switches =
  2201. TableOfContentsSwitches.O | TableOfContentsSwitches.H | TableOfContentsSwitches.Z |
  2202. TableOfContentsSwitches.U;
  2203. var xElement = XElement.Load(XmlReader.Create(new StringReader(string.Format(XmlTemplateBases.TocElementStyleBase, "TOC3", "toc 3"))));
  2204. document.styles.Root.Add(xElement);
  2205. TableOfContents.CreateTableOfContents(document, title, switches, headerStyle);
  2206. var actual = document.styles.Root.Descendants().Single(x =>
  2207. x.Name.Equals(DocX.w + "style") &&
  2208. x.Attribute(DocX.w + "type").Value.Equals("paragraph") &&
  2209. x.Attribute(DocX.w + "styleId").Value.Equals("TOC3"));
  2210. Assert.AreSame(xElement, actual);
  2211. }
  2212. }
  2213. [Test]
  2214. public void CreteTableOfContents_Toc4StyleIsPresent_DoesNotAddToc4Style()
  2215. {
  2216. using (var document = DocX.Create("TableOfContents Test.docx"))
  2217. {
  2218. const string title = "TestTitle";
  2219. const string headerStyle = "TestStyle";
  2220. const TableOfContentsSwitches switches =
  2221. TableOfContentsSwitches.O | TableOfContentsSwitches.H | TableOfContentsSwitches.Z |
  2222. TableOfContentsSwitches.U;
  2223. var xElement = XElement.Load(XmlReader.Create(new StringReader(string.Format(XmlTemplateBases.TocElementStyleBase, "TOC4", "toc 4"))));
  2224. document.styles.Root.Add(xElement);
  2225. TableOfContents.CreateTableOfContents(document, title, switches, headerStyle);
  2226. var actual = document.styles.Root.Descendants().Single(x =>
  2227. x.Name.Equals(DocX.w + "style") &&
  2228. x.Attribute(DocX.w + "type").Value.Equals("paragraph") &&
  2229. x.Attribute(DocX.w + "styleId").Value.Equals("TOC4"));
  2230. Assert.AreSame(xElement, actual);
  2231. }
  2232. }
  2233. [Test]
  2234. public void CreteTableOfContents_HyperlinkStyleIsPresent_DoesNotAddHyperlinkStyle()
  2235. {
  2236. using (var document = DocX.Create("TableOfContents Test.docx"))
  2237. {
  2238. const string title = "TestTitle";
  2239. const TableOfContentsSwitches switches =
  2240. TableOfContentsSwitches.O | TableOfContentsSwitches.H | TableOfContentsSwitches.Z |
  2241. TableOfContentsSwitches.U;
  2242. var xElement = XElement.Load(XmlReader.Create(new StringReader(XmlTemplateBases.TocHyperLinkStyleBase)));
  2243. document.styles.Root.Add(xElement);
  2244. TableOfContents.CreateTableOfContents(document, title, switches);
  2245. var actual = document.styles.Root.Descendants().Single(x =>
  2246. x.Name.Equals(DocX.w + "style") &&
  2247. x.Attribute(DocX.w + "type").Value.Equals("character") &&
  2248. x.Attribute(DocX.w + "styleId").Value.Equals("Hyperlink"));
  2249. Assert.AreSame(xElement, actual);
  2250. }
  2251. }
  2252. [Test]
  2253. public void InsertDefaultTableOfContents_WhenCalled_AddsTocToDocument()
  2254. {
  2255. using (var document = DocX.Create("TableOfContents Test.docx"))
  2256. {
  2257. document.InsertDefaultTableOfContents();
  2258. var toc = TableOfContents.CreateTableOfContents(document, "Table of contents",
  2259. TableOfContentsSwitches.O | TableOfContentsSwitches.H | TableOfContentsSwitches.Z |
  2260. TableOfContentsSwitches.U);
  2261. Assert.IsTrue(document.Xml.Descendants().FirstOrDefault(x => XNode.DeepEquals(toc.Xml, x)) != null);
  2262. }
  2263. }
  2264. [Test]
  2265. public void InsertTableOfContents_WhenCalledWithTitleSwitchesHeaderStyleMaxIncludeLevelAndRightTabPos_AddsTocToDocument()
  2266. {
  2267. using (var document = DocX.Create("TableOfContents Test.docx"))
  2268. {
  2269. const string tableOfContentsTitle = "Table of contents";
  2270. const TableOfContentsSwitches tableOfContentsSwitches = TableOfContentsSwitches.O | TableOfContentsSwitches.A;
  2271. const string headerStyle = "HeaderStyle";
  2272. const int lastIncludeLevel = 4;
  2273. const int rightTabPos = 1337;
  2274. document.InsertTableOfContents(tableOfContentsTitle, tableOfContentsSwitches, headerStyle, lastIncludeLevel, rightTabPos);
  2275. var toc = TableOfContents.CreateTableOfContents(document, tableOfContentsTitle, tableOfContentsSwitches, headerStyle, lastIncludeLevel, rightTabPos);
  2276. Assert.IsTrue(document.Xml.Descendants().FirstOrDefault(x => XNode.DeepEquals(toc.Xml, x)) != null);
  2277. }
  2278. }
  2279. [Test]
  2280. public void InsertTableOfContents_WhenCalledWithReferenceTitleSwitchesHeaderStyleMaxIncludeLevelAndRightTabPos_AddsTocToDocumentAtExpectedLocation()
  2281. {
  2282. using (var document = DocX.Create("TableOfContents Test.docx"))
  2283. {
  2284. const string tableOfContentsTitle = "Table of contents";
  2285. const TableOfContentsSwitches tableOfContentsSwitches = TableOfContentsSwitches.O | TableOfContentsSwitches.A;
  2286. const string headerStyle = "HeaderStyle";
  2287. const int lastIncludeLevel = 4;
  2288. const int rightTabPos = 1337;
  2289. document.InsertParagraph("Paragraph1");
  2290. var p2 = document.InsertParagraph("Paragraph2");
  2291. var p3 = document.InsertParagraph("Paragraph3");
  2292. document.InsertTableOfContents(p3, tableOfContentsTitle, tableOfContentsSwitches, headerStyle, lastIncludeLevel, rightTabPos);
  2293. var toc = TableOfContents.CreateTableOfContents(document, tableOfContentsTitle, tableOfContentsSwitches, headerStyle, lastIncludeLevel, rightTabPos);
  2294. var tocElement = document.Xml.Descendants().FirstOrDefault(x => XNode.DeepEquals(toc.Xml, x));
  2295. Assert.IsTrue(p2.Xml.IsBefore(tocElement));
  2296. Assert.IsTrue(tocElement.IsAfter(p2.Xml));
  2297. Assert.IsTrue(tocElement.IsBefore(p3.Xml));
  2298. Assert.IsTrue(p3.Xml.IsAfter(tocElement));
  2299. }
  2300. }
  2301. [Test]
  2302. public void ValidateBookmark_WhenCalledWithNameOfNonMatchingBookmark_ReturnsFalse()
  2303. {
  2304. using (var document = DocX.Create("Bookmark validate.docx"))
  2305. {
  2306. var p = document.InsertParagraph("No bookmark here");
  2307. Assert.IsFalse(p.ValidateBookmark("Team Rubberduck"));
  2308. }
  2309. }
  2310. [Test]
  2311. public void ValidateBookmark_WhenCalledWithNameOfMatchingBookmark_ReturnsTrue()
  2312. {
  2313. using (var document = DocX.Create("Bookmark validate.docx"))
  2314. {
  2315. var p = document.InsertParagraph("Here's a bookmark!");
  2316. const string bookmarkName = "Team Rubberduck";
  2317. p.AppendBookmark(bookmarkName);
  2318. Assert.IsTrue(p.ValidateBookmark("Team Rubberduck"));
  2319. }
  2320. }
  2321. [Test]
  2322. public void ValidateBookmarks_WhenCalledWithMatchingBookmarkNameInHeader_ReturnsEmpty()
  2323. {
  2324. using (var document = DocX.Create("Bookmark validate.docx"))
  2325. {
  2326. document.AddHeaders();
  2327. var p = document.Headers.first.InsertParagraph("Here's a bookmark!");
  2328. const string bookmarkName = "Team Rubberduck";
  2329. p.AppendBookmark(bookmarkName);
  2330. Assert.IsTrue(document.ValidateBookmarks("Team Rubberduck").Length == 0);
  2331. }
  2332. }
  2333. [Test]
  2334. public void ValidateBookmarks_WhenCalledWithMatchingBookmarkNameInMainDocument_ReturnsEmpty()
  2335. {
  2336. using (var document = DocX.Create("Bookmark validate.docx"))
  2337. {
  2338. var p = document.InsertParagraph("Here's a bookmark!");
  2339. const string bookmarkName = "Team Rubberduck";
  2340. p.AppendBookmark(bookmarkName);
  2341. Assert.IsTrue(document.ValidateBookmarks("Team Rubberduck").Length == 0);
  2342. }
  2343. }
  2344. [Test]
  2345. public void ValidateBookmarks_WhenCalledWithMatchingBookmarkNameInFooters_ReturnsEmpty()
  2346. {
  2347. using (var document = DocX.Create("Bookmark validate.docx"))
  2348. {
  2349. document.AddFooters();
  2350. var p = document.Footers.first.InsertParagraph("Here's a bookmark!");
  2351. const string bookmarkName = "Team Rubberduck";
  2352. p.AppendBookmark(bookmarkName);
  2353. Assert.IsTrue(document.ValidateBookmarks("Team Rubberduck").Length == 0);
  2354. }
  2355. }
  2356. [Test]
  2357. public void ValidateBookmarks_WhenCalledWithNoMatchingBookmarkNames_ReturnsExpected()
  2358. {
  2359. using (var document = DocX.Create("Bookmark validate.docx"))
  2360. {
  2361. document.AddHeaders();
  2362. var p = document.Headers.first.InsertParagraph("Here's a bookmark!");
  2363. p.AppendBookmark("Not in search");
  2364. var bookmarkNames = new[] { "Team Rubberduck", "is", "the most", "awesome people" };
  2365. var result = document.ValidateBookmarks(bookmarkNames);
  2366. for (var i = 0; i < bookmarkNames.Length; i++)
  2367. {
  2368. Assert.AreEqual(bookmarkNames[i], result[i]);
  2369. }
  2370. }
  2371. }
  2372. [Test]
  2373. public void CreateTable_WhenCalledSetColumnWidth_ReturnsExpected()
  2374. {
  2375. using (var document = DocX.Create("Set column width.docx"))
  2376. {
  2377. var table = document.InsertTable(1, 2);
  2378. table.SetColumnWidth(0, 1000);
  2379. table.SetColumnWidth(1, 2000);
  2380. Assert.AreEqual(1000, table.GetColumnWidth(0));
  2381. Assert.AreEqual(2000, table.GetColumnWidth(1));
  2382. }
  2383. }
  2384. [Test]
  2385. public void UpdateParagraphFontSize_WhenSetFontSize_ReturnsExpected()
  2386. {
  2387. using (var document = DocX.Create("Update paragraph font size.docx"))
  2388. {
  2389. var paragraph = document.InsertParagraph().FontSize(9);
  2390. paragraph.FontSize(11);
  2391. string szValue = paragraph.Xml.Descendants(XName.Get("sz", DocX.w.NamespaceName))
  2392. .Attributes(XName.Get("val", DocX.w.NamespaceName)).First().Value;
  2393. string szCsValue = paragraph.Xml.Descendants(XName.Get("szCs", DocX.w.NamespaceName))
  2394. .Attributes(XName.Get("val", DocX.w.NamespaceName)).First().Value;
  2395. // the expected value is multiplied by 2
  2396. // and the last font size is 11*2 = 22
  2397. Assert.AreEqual("22", szValue);
  2398. Assert.AreEqual("22", szCsValue);
  2399. }
  2400. }
  2401. [Test]
  2402. public void SetTableCellMargin_WhenSetTwoCellMargins_ContainsTwoCellMargins()
  2403. {
  2404. using (var document = DocX.Create("Set table cell margins.docx"))
  2405. {
  2406. Table table = document.InsertTable(1, 1);
  2407. table.SetTableCellMargin(TableCellMarginType.left, 20);
  2408. table.SetTableCellMargin(TableCellMarginType.right, 40);
  2409. var elements = table.Xml.Descendants(XName.Get("tblCellMar", DocX.w.NamespaceName)).ToList();
  2410. // should contain only one element named tblCellMar
  2411. Assert.AreEqual(1, elements.Count);
  2412. var element = elements.First();
  2413. // should contain two elements defining the margins
  2414. Assert.AreEqual(2, element.Elements().Count());
  2415. var left = element.Element(XName.Get("left", DocX.w.NamespaceName));
  2416. var right = element.Element(XName.Get("right", DocX.w.NamespaceName));
  2417. Assert.IsNotNull(left);
  2418. Assert.IsNotNull(right);
  2419. Assert.AreEqual("20", left.Attribute(XName.Get("w", DocX.w.NamespaceName)).Value);
  2420. Assert.AreEqual("dxa", left.Attribute(XName.Get("type", DocX.w.NamespaceName)).Value);
  2421. Assert.AreEqual("40", right.Attribute(XName.Get("w", DocX.w.NamespaceName)).Value);
  2422. Assert.AreEqual("dxa", right.Attribute(XName.Get("type", DocX.w.NamespaceName)).Value);
  2423. }
  2424. }
  2425. [Test]
  2426. public void SetTableCellMargin_WhenReSetCellMargin_ContainsOneCellMargin()
  2427. {
  2428. using (var document = DocX.Create("Set table cell margin.docx"))
  2429. {
  2430. Table table = document.InsertTable(1, 1);
  2431. table.SetTableCellMargin(TableCellMarginType.left, 20);
  2432. // change the table cell margin
  2433. table.SetTableCellMargin(TableCellMarginType.left, 40);
  2434. var elements = table.Xml.Descendants(XName.Get("tblCellMar", DocX.w.NamespaceName)).ToList();
  2435. // should contain only one element named tblCellMar
  2436. Assert.AreEqual(1, elements.Count);
  2437. var element = elements.First();
  2438. // should contain two elements defining the margins
  2439. Assert.AreEqual(1, element.Elements().Count());
  2440. var left = element.Element(XName.Get("left", DocX.w.NamespaceName));
  2441. Assert.IsNotNull(left);
  2442. // check that the last value is taken
  2443. Assert.AreEqual("40", left.Attribute(XName.Get("w", DocX.w.NamespaceName)).Value);
  2444. Assert.AreEqual("dxa", left.Attribute(XName.Get("type", DocX.w.NamespaceName)).Value);
  2445. }
  2446. }
  2447. }
  2448. }