You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

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