Du kannst nicht mehr als 25 Themen auswählen Themen müssen mit entweder einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

DocXUnitTests.cs 139KB

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