Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

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