Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

DocXUnitTests.cs 150KB

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