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.

Paragraph.cs 181KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542
  1. using System;
  2. using System.IO;
  3. using System.Linq;
  4. using System.Drawing;
  5. using System.Xml.Linq;
  6. using System.Collections;
  7. using System.IO.Packaging;
  8. using System.Globalization;
  9. using System.Security.Principal;
  10. using System.Collections.Generic;
  11. using System.Text.RegularExpressions;
  12. namespace Novacode
  13. {
  14. /// <summary>
  15. /// Represents a document paragraph.
  16. /// </summary>
  17. public class Paragraph : InsertBeforeOrAfter
  18. {
  19. // The Append family of functions use this List to apply style.
  20. internal List<XElement> runs;
  21. // This paragraphs text alignment
  22. private Alignment alignment;
  23. public ContainerType ParentContainer;
  24. private XElement ParagraphNumberPropertiesBacker { get; set; }
  25. /// <summary>
  26. /// Fetch the paragraph number properties for a list element.
  27. /// </summary>
  28. public XElement ParagraphNumberProperties
  29. {
  30. get
  31. {
  32. return ParagraphNumberPropertiesBacker ?? (ParagraphNumberPropertiesBacker = GetParagraphNumberProperties());
  33. }
  34. }
  35. private XElement GetParagraphNumberProperties()
  36. {
  37. var numPrNode = Xml.Descendants().FirstOrDefault(el => el.Name.LocalName == "numPr");
  38. if (numPrNode != null)
  39. {
  40. var numIdNode = numPrNode.Descendants().First(numId => numId.Name.LocalName == "numId");
  41. var numIdAttribute = numIdNode.Attribute(DocX.w + "val");
  42. if (numIdAttribute != null && numIdAttribute.Value.Equals("0"))
  43. {
  44. return null;
  45. }
  46. }
  47. return numPrNode;
  48. }
  49. private bool? IsListItemBacker { get; set; }
  50. /// <summary>
  51. /// Determine if this paragraph is a list element.
  52. /// </summary>
  53. public bool IsListItem
  54. {
  55. get
  56. {
  57. IsListItemBacker = IsListItemBacker ?? (ParagraphNumberProperties != null);
  58. return (bool)IsListItemBacker;
  59. }
  60. }
  61. private int? IndentLevelBacker { get; set; }
  62. /// <summary>
  63. /// If this element is a list item, get the indentation level of the list item.
  64. /// </summary>
  65. public int? IndentLevel
  66. {
  67. get
  68. {
  69. if (!IsListItem)
  70. {
  71. return null;
  72. }
  73. return IndentLevelBacker ?? (IndentLevelBacker = int.Parse(ParagraphNumberProperties.Descendants().First(el => el.Name.LocalName == "ilvl").GetAttribute(DocX.w + "val")));
  74. }
  75. }
  76. /// <summary>
  77. /// Determine if the list element is a numbered list of bulleted list element
  78. /// </summary>
  79. public ListItemType ListItemType;
  80. internal int startIndex, endIndex;
  81. /// <summary>
  82. /// Returns a list of all Pictures in a Paragraph.
  83. /// </summary>
  84. /// <example>
  85. /// Returns a list of all Pictures in a Paragraph.
  86. /// <code>
  87. /// // Create a document.
  88. /// using (DocX document = DocX.Load(@"Test.docx"))
  89. /// {
  90. /// // Get the first Paragraph in a document.
  91. /// Paragraph p = document.Paragraphs[0];
  92. ///
  93. /// // Get all of the Pictures in this Paragraph.
  94. /// List<Picture> pictures = p.Pictures;
  95. ///
  96. /// // Save this document.
  97. /// document.Save();
  98. /// }
  99. /// </code>
  100. /// </example>
  101. public List<Picture> Pictures
  102. {
  103. get
  104. {
  105. List<Picture> pictures =
  106. (
  107. from p in Xml.Descendants()
  108. where (p.Name.LocalName == "drawing")
  109. let id =
  110. (
  111. from e in p.Descendants()
  112. where e.Name.LocalName.Equals("blip")
  113. select e.Attribute(XName.Get("embed", "http://schemas.openxmlformats.org/officeDocument/2006/relationships")).Value
  114. ).SingleOrDefault()
  115. where id != null
  116. let img = new Image(Document, mainPart.GetRelationship(id))
  117. select new Picture(Document, p, img)
  118. ).ToList();
  119. List<Picture> shapes =
  120. (
  121. from p in Xml.Descendants()
  122. where (p.Name.LocalName == "pict")
  123. let id =
  124. (
  125. from e in p.Descendants()
  126. where e.Name.LocalName.Equals("imagedata")
  127. select e.Attribute(XName.Get("id", "http://schemas.openxmlformats.org/officeDocument/2006/relationships")).Value
  128. ).SingleOrDefault()
  129. where id != null
  130. let img = new Image(Document, mainPart.GetRelationship(id))
  131. select new Picture(Document, p, img)
  132. ).ToList();
  133. foreach (Picture p in shapes)
  134. pictures.Add(p);
  135. return pictures;
  136. }
  137. }
  138. /// <summary>
  139. /// Returns a list of Hyperlinks in this Paragraph.
  140. /// </summary>
  141. /// <example>
  142. /// <code>
  143. /// // Create a document.
  144. /// using (DocX document = DocX.Load(@"Test.docx"))
  145. /// {
  146. /// // Get the first Paragraph in this document.
  147. /// Paragraph p = document.Paragraphs[0];
  148. ///
  149. /// // Get all of the hyperlinks in this Paragraph.
  150. /// List<Hyperlink> hyperlinks = paragraph.Hyperlinks;
  151. ///
  152. /// // Change the first hyperlinks text and Uri
  153. /// Hyperlink h0 = hyperlinks[0];
  154. /// h0.Text = "DocX";
  155. /// h0.Uri = new Uri("http://docx.codeplex.com");
  156. ///
  157. /// // Save this document.
  158. /// document.Save();
  159. /// }
  160. /// </code>
  161. /// </example>
  162. public List<Hyperlink> Hyperlinks
  163. {
  164. get
  165. {
  166. List<Hyperlink> hyperlinks = new List<Hyperlink>();
  167. List<XElement> hyperlink_elements =
  168. (
  169. from h in Xml.Descendants()
  170. where (h.Name.LocalName == "hyperlink" || h.Name.LocalName == "instrText")
  171. select h
  172. ).ToList();
  173. foreach (XElement he in hyperlink_elements)
  174. {
  175. if (he.Name.LocalName == "hyperlink")
  176. {
  177. try
  178. {
  179. Hyperlink h = new Hyperlink(Document, mainPart, he);
  180. h.mainPart = mainPart;
  181. hyperlinks.Add(h);
  182. }
  183. catch (Exception) { }
  184. }
  185. else
  186. {
  187. // Find the parent run, no matter how deeply nested we are.
  188. XElement e = he;
  189. while (e.Name.LocalName != "r")
  190. e = e.Parent;
  191. // Take every element until we reach w:fldCharType="end"
  192. List<XElement> hyperlink_runs = new List<XElement>();
  193. foreach (XElement r in e.ElementsAfterSelf(XName.Get("r", DocX.w.NamespaceName)))
  194. {
  195. // Add this run to the list.
  196. hyperlink_runs.Add(r);
  197. XElement fldChar = r.Descendants(XName.Get("fldChar", DocX.w.NamespaceName)).SingleOrDefault<XElement>();
  198. if (fldChar != null)
  199. {
  200. XAttribute fldCharType = fldChar.Attribute(XName.Get("fldCharType", DocX.w.NamespaceName));
  201. if (fldCharType != null && fldCharType.Value.Equals("end", StringComparison.CurrentCultureIgnoreCase))
  202. {
  203. try
  204. {
  205. Hyperlink h = new Hyperlink(Document, he, hyperlink_runs);
  206. h.mainPart = mainPart;
  207. hyperlinks.Add(h);
  208. }
  209. catch (Exception) { }
  210. break;
  211. }
  212. }
  213. }
  214. }
  215. }
  216. return hyperlinks;
  217. }
  218. }
  219. ///<summary>
  220. /// The style name of the paragraph.
  221. ///</summary>
  222. public string StyleName
  223. {
  224. get
  225. {
  226. var element = this.GetOrCreate_pPr();
  227. var styleElement = element.Element(XName.Get("pStyle", DocX.w.NamespaceName));
  228. if (styleElement != null)
  229. {
  230. var attr = styleElement.Attribute(XName.Get("val", DocX.w.NamespaceName));
  231. if (attr != null && !string.IsNullOrEmpty(attr.Value))
  232. {
  233. return attr.Value;
  234. }
  235. }
  236. return "Normal";
  237. }
  238. set
  239. {
  240. if (string.IsNullOrEmpty(value))
  241. {
  242. value = "Normal";
  243. }
  244. var element = this.GetOrCreate_pPr();
  245. var styleElement = element.Element(XName.Get("pStyle", DocX.w.NamespaceName));
  246. if (styleElement == null)
  247. {
  248. element.Add(new XElement(XName.Get("pStyle", DocX.w.NamespaceName)));
  249. styleElement = element.Element(XName.Get("pStyle", DocX.w.NamespaceName));
  250. }
  251. styleElement.SetAttributeValue(XName.Get("val", DocX.w.NamespaceName), value);
  252. }
  253. }
  254. // A collection of field type DocProperty.
  255. private List<DocProperty> docProperties;
  256. internal List<XElement> styles = new List<XElement>();
  257. /// <summary>
  258. /// Returns a list of field type DocProperty in this document.
  259. /// </summary>
  260. public List<DocProperty> DocumentProperties
  261. {
  262. get { return docProperties; }
  263. }
  264. internal Paragraph(DocX document, XElement xml, int startIndex, ContainerType parent = ContainerType.None)
  265. : base(document, xml)
  266. {
  267. ParentContainer = parent;
  268. this.startIndex = startIndex;
  269. this.endIndex = startIndex + GetElementTextLength(xml);
  270. RebuildDocProperties();
  271. // As per Unused code affecting performance (Wiki Link: [discussion:454191]) and coffeycathal suggestion no longer requeried
  272. //#region It's possible that a Paragraph may have pStyle references
  273. //// Check if this Paragraph references any pStyle elements.
  274. //var stylesElements = xml.Descendants(XName.Get("pStyle", DocX.w.NamespaceName));
  275. //// If one or more pStyles are referenced.
  276. //if (stylesElements.Count() > 0)
  277. //{
  278. // Uri style_package_uri = new Uri("/word/styles.xml", UriKind.Relative);
  279. // PackagePart styles_document = document.package.GetPart(style_package_uri);
  280. // using (TextReader tr = new StreamReader(styles_document.GetStream()))
  281. // {
  282. // XDocument style_document = XDocument.Load(tr);
  283. // XElement styles_element = style_document.Element(XName.Get("styles", DocX.w.NamespaceName));
  284. // var styles_element_ids = stylesElements.Select(e => e.Attribute(XName.Get("val", DocX.w.NamespaceName)).Value);
  285. // //foreach(string id in styles_element_ids)
  286. // //{
  287. // // var style =
  288. // // (
  289. // // from d in styles_element.Descendants()
  290. // // let styleId = d.Attribute(XName.Get("styleId", DocX.w.NamespaceName))
  291. // // let type = d.Attribute(XName.Get("type", DocX.w.NamespaceName))
  292. // // where type != null && type.Value == "paragraph" && styleId != null && styleId.Value == id
  293. // // select d
  294. // // ).First();
  295. // // styles.Add(style);
  296. // //}
  297. // }
  298. //}
  299. //#endregion
  300. this.runs = Xml.Elements(XName.Get("r", DocX.w.NamespaceName)).ToList();
  301. }
  302. /// <summary>
  303. /// Insert a new Table before this Paragraph, this Table can be from this document or another document.
  304. /// </summary>
  305. /// <param name="t">The Table t to be inserted.</param>
  306. /// <returns>A new Table inserted before this Paragraph.</returns>
  307. /// <example>
  308. /// Insert a new Table before this Paragraph.
  309. /// <code>
  310. /// // Place holder for a Table.
  311. /// Table t;
  312. ///
  313. /// // Load document a.
  314. /// using (DocX documentA = DocX.Load(@"a.docx"))
  315. /// {
  316. /// // Get the first Table from this document.
  317. /// t = documentA.Tables[0];
  318. /// }
  319. ///
  320. /// // Load document b.
  321. /// using (DocX documentB = DocX.Load(@"b.docx"))
  322. /// {
  323. /// // Get the first Paragraph in document b.
  324. /// Paragraph p2 = documentB.Paragraphs[0];
  325. ///
  326. /// // Insert the Table from document a before this Paragraph.
  327. /// Table newTable = p2.InsertTableBeforeSelf(t);
  328. ///
  329. /// // Save all changes made to document b.
  330. /// documentB.Save();
  331. /// }// Release this document from memory.
  332. /// </code>
  333. /// </example>
  334. public override Table InsertTableBeforeSelf(Table t)
  335. {
  336. t = base.InsertTableBeforeSelf(t);
  337. t.mainPart = mainPart;
  338. return t;
  339. }
  340. private Direction direction;
  341. /// <summary>
  342. /// Gets or Sets the Direction of content in this Paragraph.
  343. /// <example>
  344. /// Create a Paragraph with content that flows right to left. Default is left to right.
  345. /// <code>
  346. /// // Create a new document.
  347. /// using (DocX document = DocX.Create("Test.docx"))
  348. /// {
  349. /// // Create a new Paragraph with the text "Hello World".
  350. /// Paragraph p = document.InsertParagraph("Hello World.");
  351. ///
  352. /// // Make this Paragraph flow right to left. Default is left to right.
  353. /// p.Direction = Direction.RightToLeft;
  354. ///
  355. /// // Save all changes made to this document.
  356. /// document.Save();
  357. /// }
  358. /// </code>
  359. /// </example>
  360. /// </summary>
  361. public Direction Direction
  362. {
  363. get
  364. {
  365. XElement pPr = GetOrCreate_pPr();
  366. XElement bidi = pPr.Element(XName.Get("bidi", DocX.w.NamespaceName));
  367. if (bidi == null)
  368. return Direction.LeftToRight;
  369. else
  370. return Direction.RightToLeft;
  371. }
  372. set
  373. {
  374. direction = value;
  375. XElement pPr = GetOrCreate_pPr();
  376. XElement bidi = pPr.Element(XName.Get("bidi", DocX.w.NamespaceName));
  377. if (direction == Direction.RightToLeft)
  378. {
  379. if (bidi == null)
  380. pPr.Add(new XElement(XName.Get("bidi", DocX.w.NamespaceName)));
  381. }
  382. else
  383. {
  384. if (bidi != null)
  385. bidi.Remove();
  386. }
  387. }
  388. }
  389. public bool IsKeepWithNext
  390. {
  391. get
  392. {
  393. var pPr = GetOrCreate_pPr();
  394. var keepWithNextE = pPr.Element(XName.Get("keepNext", DocX.w.NamespaceName));
  395. if (keepWithNextE == null)
  396. {
  397. return false;
  398. }
  399. return true;
  400. }
  401. }
  402. /// <summary>
  403. /// This paragraph will be kept on the same page as the next paragraph
  404. /// </summary>
  405. /// <example>
  406. /// Create a Paragraph that will stay on the same page as the paragraph that comes next
  407. /// <code>
  408. /// // Create a new document.
  409. /// using (DocX document = DocX.Create("Test.docx"))
  410. ///
  411. /// {
  412. /// // Create a new Paragraph with the text "Hello World".
  413. /// Paragraph p = document.InsertParagraph("Hello World.");
  414. /// p.KeepWithNext();
  415. /// document.InsertParagraph("Previous paragraph will appear on the same page as this paragraph");
  416. /// // Save all changes made to this document.
  417. /// document.Save();
  418. /// }
  419. /// </code>
  420. /// </example>
  421. /// <param name="keepWithNext"></param>
  422. /// <returns></returns>
  423. public Paragraph KeepWithNext(bool keepWithNext = true)
  424. {
  425. var pPr = GetOrCreate_pPr();
  426. var keepWithNextE = pPr.Element(XName.Get("keepNext", DocX.w.NamespaceName));
  427. if (keepWithNextE == null && keepWithNext)
  428. {
  429. pPr.Add(new XElement(XName.Get("keepNext", DocX.w.NamespaceName)));
  430. }
  431. if (!keepWithNext && keepWithNextE != null)
  432. {
  433. keepWithNextE.Remove();
  434. }
  435. return this;
  436. }
  437. /// <summary>
  438. /// Keep all lines in this paragraph together on a page
  439. /// </summary>
  440. /// <example>
  441. /// Create a Paragraph whose lines will stay together on a single page
  442. /// <code>
  443. /// // Create a new document.
  444. /// using (DocX document = DocX.Create("Test.docx"))
  445. /// {
  446. /// // Create a new Paragraph with the text "Hello World".
  447. /// Paragraph p = document.InsertParagraph("All lines of this paragraph will appear on the same page...\nLine 2\nLine 3\nLine 4\nLine 5\nLine 6...");
  448. /// p.KeepLinesTogether();
  449. /// // Save all changes made to this document.
  450. /// document.Save();
  451. /// }
  452. /// </code>
  453. /// </example>
  454. /// <param name="keepTogether"></param>
  455. /// <returns></returns>
  456. public Paragraph KeepLinesTogether(bool keepTogether = true)
  457. {
  458. var pPr = GetOrCreate_pPr();
  459. var keepLinesE = pPr.Element(XName.Get("keepLines", DocX.w.NamespaceName));
  460. if (keepLinesE == null && keepTogether)
  461. {
  462. pPr.Add(new XElement(XName.Get("keepLines", DocX.w.NamespaceName)));
  463. }
  464. if (!keepTogether && keepLinesE != null)
  465. {
  466. keepLinesE.Remove();
  467. }
  468. return this;
  469. }
  470. /// <summary>
  471. /// If the pPr element doesent exist it is created, either way it is returned by this function.
  472. /// </summary>
  473. /// <returns>The pPr element for this Paragraph.</returns>
  474. internal XElement GetOrCreate_pPr()
  475. {
  476. // Get the element.
  477. XElement pPr = Xml.Element(XName.Get("pPr", DocX.w.NamespaceName));
  478. // If it dosen't exist, create it.
  479. if (pPr == null)
  480. {
  481. Xml.AddFirst(new XElement(XName.Get("pPr", DocX.w.NamespaceName)));
  482. pPr = Xml.Element(XName.Get("pPr", DocX.w.NamespaceName));
  483. }
  484. // Return the pPr element for this Paragraph.
  485. return pPr;
  486. }
  487. /// <summary>
  488. /// If the ind element doesent exist it is created, either way it is returned by this function.
  489. /// </summary>
  490. /// <returns>The ind element for this Paragraphs pPr.</returns>
  491. internal XElement GetOrCreate_pPr_ind()
  492. {
  493. // Get the element.
  494. XElement pPr = GetOrCreate_pPr();
  495. XElement ind = pPr.Element(XName.Get("ind", DocX.w.NamespaceName));
  496. // If it dosen't exist, create it.
  497. if (ind == null)
  498. {
  499. pPr.Add(new XElement(XName.Get("ind", DocX.w.NamespaceName)));
  500. ind = pPr.Element(XName.Get("ind", DocX.w.NamespaceName));
  501. }
  502. // Return the pPr element for this Paragraph.
  503. return ind;
  504. }
  505. private float indentationFirstLine;
  506. /// <summary>
  507. /// Get or set the indentation of the first line of this Paragraph.
  508. /// </summary>
  509. /// <example>
  510. /// Indent only the first line of a Paragraph.
  511. /// <code>
  512. /// // Create a new document.
  513. /// using (DocX document = DocX.Create("Test.docx"))
  514. /// {
  515. /// // Create a new Paragraph.
  516. /// Paragraph p = document.InsertParagraph("Line 1\nLine 2\nLine 3");
  517. ///
  518. /// // Indent only the first line of the Paragraph.
  519. /// p.IndentationFirstLine = 2.0f;
  520. ///
  521. /// // Save all changes made to this document.
  522. /// document.Save();
  523. /// }
  524. /// </code>
  525. /// </example>
  526. public float IndentationFirstLine
  527. {
  528. get
  529. {
  530. XElement pPr = GetOrCreate_pPr();
  531. XElement ind = GetOrCreate_pPr_ind();
  532. XAttribute firstLine = ind.Attribute(XName.Get("firstLine", DocX.w.NamespaceName));
  533. if (firstLine != null)
  534. return float.Parse(firstLine.Value);
  535. return 0.0f;
  536. }
  537. set
  538. {
  539. if (IndentationFirstLine != value)
  540. {
  541. indentationFirstLine = value;
  542. XElement pPr = GetOrCreate_pPr();
  543. XElement ind = GetOrCreate_pPr_ind();
  544. // Paragraph can either be firstLine or hanging (Remove hanging).
  545. XAttribute hanging = ind.Attribute(XName.Get("hanging", DocX.w.NamespaceName));
  546. if (hanging != null)
  547. hanging.Remove();
  548. string indentation = ((indentationFirstLine / 0.1) * 57).ToString();
  549. XAttribute firstLine = ind.Attribute(XName.Get("firstLine", DocX.w.NamespaceName));
  550. if (firstLine != null)
  551. firstLine.Value = indentation;
  552. else
  553. ind.Add(new XAttribute(XName.Get("firstLine", DocX.w.NamespaceName), indentation));
  554. }
  555. }
  556. }
  557. private float indentationHanging;
  558. /// <summary>
  559. /// Get or set the indentation of all but the first line of this Paragraph.
  560. /// </summary>
  561. /// <example>
  562. /// Indent all but the first line of a Paragraph.
  563. /// <code>
  564. /// // Create a new document.
  565. /// using (DocX document = DocX.Create("Test.docx"))
  566. /// {
  567. /// // Create a new Paragraph.
  568. /// Paragraph p = document.InsertParagraph("Line 1\nLine 2\nLine 3");
  569. ///
  570. /// // Indent all but the first line of the Paragraph.
  571. /// p.IndentationHanging = 1.0f;
  572. ///
  573. /// // Save all changes made to this document.
  574. /// document.Save();
  575. /// }
  576. /// </code>
  577. /// </example>
  578. public float IndentationHanging
  579. {
  580. get
  581. {
  582. XElement pPr = GetOrCreate_pPr();
  583. XElement ind = GetOrCreate_pPr_ind();
  584. XAttribute hanging = ind.Attribute(XName.Get("hanging", DocX.w.NamespaceName));
  585. if (hanging != null)
  586. return float.Parse(hanging.Value) / (57 * 10);
  587. return 0.0f;
  588. }
  589. set
  590. {
  591. if (IndentationHanging != value)
  592. {
  593. indentationHanging = value;
  594. XElement pPr = GetOrCreate_pPr();
  595. XElement ind = GetOrCreate_pPr_ind();
  596. // Paragraph can either be firstLine or hanging (Remove firstLine).
  597. XAttribute firstLine = ind.Attribute(XName.Get("firstLine", DocX.w.NamespaceName));
  598. if (firstLine != null)
  599. firstLine.Remove();
  600. string indentation = ((indentationHanging / 0.1) * 57).ToString();
  601. XAttribute hanging = ind.Attribute(XName.Get("hanging", DocX.w.NamespaceName));
  602. if (hanging != null)
  603. hanging.Value = indentation;
  604. else
  605. ind.Add(new XAttribute(XName.Get("hanging", DocX.w.NamespaceName), indentation));
  606. }
  607. }
  608. }
  609. private float indentationBefore;
  610. /// <summary>
  611. /// Set the before indentation in cm for this Paragraph.
  612. /// </summary>
  613. /// <example>
  614. /// // Indent an entire Paragraph from the left.
  615. /// <code>
  616. /// // Create a new document.
  617. /// using (DocX document = DocX.Create("Test.docx"))
  618. /// {
  619. /// // Create a new Paragraph.
  620. /// Paragraph p = document.InsertParagraph("Line 1\nLine 2\nLine 3");
  621. ///
  622. /// // Indent this entire Paragraph from the left.
  623. /// p.IndentationBefore = 2.0f;
  624. ///
  625. /// // Save all changes made to this document.
  626. /// document.Save();
  627. ///}
  628. /// </code>
  629. /// </example>
  630. public float IndentationBefore
  631. {
  632. get
  633. {
  634. XElement pPr = GetOrCreate_pPr();
  635. XElement ind = GetOrCreate_pPr_ind();
  636. XAttribute left = ind.Attribute(XName.Get("left", DocX.w.NamespaceName));
  637. if (left != null)
  638. return float.Parse(left.Value) / (57 * 10);
  639. return 0.0f;
  640. }
  641. set
  642. {
  643. if (IndentationBefore != value)
  644. {
  645. indentationBefore = value;
  646. XElement pPr = GetOrCreate_pPr();
  647. XElement ind = GetOrCreate_pPr_ind();
  648. string indentation = ((indentationBefore / 0.1) * 57).ToString();
  649. XAttribute left = ind.Attribute(XName.Get("left", DocX.w.NamespaceName));
  650. if (left != null)
  651. left.Value = indentation;
  652. else
  653. ind.Add(new XAttribute(XName.Get("left", DocX.w.NamespaceName), indentation));
  654. }
  655. }
  656. }
  657. private float indentationAfter = 0.0f;
  658. /// <summary>
  659. /// Set the after indentation in cm for this Paragraph.
  660. /// </summary>
  661. /// <example>
  662. /// // Indent an entire Paragraph from the right.
  663. /// <code>
  664. /// // Create a new document.
  665. /// using (DocX document = DocX.Create("Test.docx"))
  666. /// {
  667. /// // Create a new Paragraph.
  668. /// Paragraph p = document.InsertParagraph("Line 1\nLine 2\nLine 3");
  669. ///
  670. /// // Make the content of this Paragraph flow right to left.
  671. /// p.Direction = Direction.RightToLeft;
  672. ///
  673. /// // Indent this entire Paragraph from the right.
  674. /// p.IndentationAfter = 2.0f;
  675. ///
  676. /// // Save all changes made to this document.
  677. /// document.Save();
  678. /// }
  679. /// </code>
  680. /// </example>
  681. public float IndentationAfter
  682. {
  683. get
  684. {
  685. XElement pPr = GetOrCreate_pPr();
  686. XElement ind = GetOrCreate_pPr_ind();
  687. XAttribute right = ind.Attribute(XName.Get("right", DocX.w.NamespaceName));
  688. if (right != null)
  689. return float.Parse(right.Value);
  690. return 0.0f;
  691. }
  692. set
  693. {
  694. if (IndentationAfter != value)
  695. {
  696. indentationAfter = value;
  697. XElement pPr = GetOrCreate_pPr();
  698. XElement ind = GetOrCreate_pPr_ind();
  699. string indentation = ((indentationAfter / 0.1) * 57).ToString();
  700. XAttribute right = ind.Attribute(XName.Get("right", DocX.w.NamespaceName));
  701. if (right != null)
  702. right.Value = indentation;
  703. else
  704. ind.Add(new XAttribute(XName.Get("right", DocX.w.NamespaceName), indentation));
  705. }
  706. }
  707. }
  708. /// <summary>
  709. /// Insert a new Table into this document before this Paragraph.
  710. /// </summary>
  711. /// <param name="rowCount">The number of rows this Table should have.</param>
  712. /// <param name="columnCount">The number of columns this Table should have.</param>
  713. /// <returns>A new Table inserted before this Paragraph.</returns>
  714. /// <example>
  715. /// <code>
  716. /// // Create a new document.
  717. /// using (DocX document = DocX.Create(@"Test.docx"))
  718. /// {
  719. /// //Insert a Paragraph into this document.
  720. /// Paragraph p = document.InsertParagraph("Hello World", false);
  721. ///
  722. /// // Insert a new Table before this Paragraph.
  723. /// Table newTable = p.InsertTableBeforeSelf(2, 2);
  724. /// newTable.Design = TableDesign.LightShadingAccent2;
  725. /// newTable.Alignment = Alignment.center;
  726. ///
  727. /// // Save all changes made to this document.
  728. /// document.Save();
  729. /// }// Release this document from memory.
  730. /// </code>
  731. /// </example>
  732. public override Table InsertTableBeforeSelf(int rowCount, int columnCount)
  733. {
  734. return base.InsertTableBeforeSelf(rowCount, columnCount);
  735. }
  736. /// <summary>
  737. /// Insert a new Table after this Paragraph.
  738. /// </summary>
  739. /// <param name="t">The Table t to be inserted.</param>
  740. /// <returns>A new Table inserted after this Paragraph.</returns>
  741. /// <example>
  742. /// Insert a new Table after this Paragraph.
  743. /// <code>
  744. /// // Place holder for a Table.
  745. /// Table t;
  746. ///
  747. /// // Load document a.
  748. /// using (DocX documentA = DocX.Load(@"a.docx"))
  749. /// {
  750. /// // Get the first Table from this document.
  751. /// t = documentA.Tables[0];
  752. /// }
  753. ///
  754. /// // Load document b.
  755. /// using (DocX documentB = DocX.Load(@"b.docx"))
  756. /// {
  757. /// // Get the first Paragraph in document b.
  758. /// Paragraph p2 = documentB.Paragraphs[0];
  759. ///
  760. /// // Insert the Table from document a after this Paragraph.
  761. /// Table newTable = p2.InsertTableAfterSelf(t);
  762. ///
  763. /// // Save all changes made to document b.
  764. /// documentB.Save();
  765. /// }// Release this document from memory.
  766. /// </code>
  767. /// </example>
  768. public override Table InsertTableAfterSelf(Table t)
  769. {
  770. t = base.InsertTableAfterSelf(t);
  771. t.mainPart = mainPart;
  772. return t;
  773. }
  774. /// <summary>
  775. /// Insert a new Table into this document after this Paragraph.
  776. /// </summary>
  777. /// <param name="rowCount">The number of rows this Table should have.</param>
  778. /// <param name="columnCount">The number of columns this Table should have.</param>
  779. /// <returns>A new Table inserted after this Paragraph.</returns>
  780. /// <example>
  781. /// <code>
  782. /// // Create a new document.
  783. /// using (DocX document = DocX.Create(@"Test.docx"))
  784. /// {
  785. /// //Insert a Paragraph into this document.
  786. /// Paragraph p = document.InsertParagraph("Hello World", false);
  787. ///
  788. /// // Insert a new Table after this Paragraph.
  789. /// Table newTable = p.InsertTableAfterSelf(2, 2);
  790. /// newTable.Design = TableDesign.LightShadingAccent2;
  791. /// newTable.Alignment = Alignment.center;
  792. ///
  793. /// // Save all changes made to this document.
  794. /// document.Save();
  795. /// }// Release this document from memory.
  796. /// </code>
  797. /// </example>
  798. public override Table InsertTableAfterSelf(int rowCount, int columnCount)
  799. {
  800. return base.InsertTableAfterSelf(rowCount, columnCount);
  801. }
  802. /// <summary>
  803. /// Insert a Paragraph before this Paragraph, this Paragraph may have come from the same or another document.
  804. /// </summary>
  805. /// <param name="p">The Paragraph to insert.</param>
  806. /// <returns>The Paragraph now associated with this document.</returns>
  807. /// <example>
  808. /// Take a Paragraph from document a, and insert it into document b before this Paragraph.
  809. /// <code>
  810. /// // Place holder for a Paragraph.
  811. /// Paragraph p;
  812. ///
  813. /// // Load document a.
  814. /// using (DocX documentA = DocX.Load(@"a.docx"))
  815. /// {
  816. /// // Get the first paragraph from this document.
  817. /// p = documentA.Paragraphs[0];
  818. /// }
  819. ///
  820. /// // Load document b.
  821. /// using (DocX documentB = DocX.Load(@"b.docx"))
  822. /// {
  823. /// // Get the first Paragraph in document b.
  824. /// Paragraph p2 = documentB.Paragraphs[0];
  825. ///
  826. /// // Insert the Paragraph from document a before this Paragraph.
  827. /// Paragraph newParagraph = p2.InsertParagraphBeforeSelf(p);
  828. ///
  829. /// // Save all changes made to document b.
  830. /// documentB.Save();
  831. /// }// Release this document from memory.
  832. /// </code>
  833. /// </example>
  834. public override Paragraph InsertParagraphBeforeSelf(Paragraph p)
  835. {
  836. Paragraph p2 = base.InsertParagraphBeforeSelf(p);
  837. p2.PackagePart = mainPart;
  838. return p2;
  839. }
  840. /// <summary>
  841. /// Insert a new Paragraph before this Paragraph.
  842. /// </summary>
  843. /// <param name="text">The initial text for this new Paragraph.</param>
  844. /// <returns>A new Paragraph inserted before this Paragraph.</returns>
  845. /// <example>
  846. /// Insert a new paragraph before the first Paragraph in this document.
  847. /// <code>
  848. /// // Create a new document.
  849. /// using (DocX document = DocX.Create(@"Test.docx"))
  850. /// {
  851. /// // Insert a Paragraph into this document.
  852. /// Paragraph p = document.InsertParagraph("I am a Paragraph", false);
  853. ///
  854. /// p.InsertParagraphBeforeSelf("I was inserted before the next Paragraph.");
  855. ///
  856. /// // Save all changes made to this new document.
  857. /// document.Save();
  858. /// }// Release this new document form memory.
  859. /// </code>
  860. /// </example>
  861. public override Paragraph InsertParagraphBeforeSelf(string text)
  862. {
  863. Paragraph p = base.InsertParagraphBeforeSelf(text);
  864. p.PackagePart = mainPart;
  865. return p;
  866. }
  867. /// <summary>
  868. /// Insert a new Paragraph before this Paragraph.
  869. /// </summary>
  870. /// <param name="text">The initial text for this new Paragraph.</param>
  871. /// <param name="trackChanges">Should this insertion be tracked as a change?</param>
  872. /// <returns>A new Paragraph inserted before this Paragraph.</returns>
  873. /// <example>
  874. /// Insert a new paragraph before the first Paragraph in this document.
  875. /// <code>
  876. /// // Create a new document.
  877. /// using (DocX document = DocX.Create(@"Test.docx"))
  878. /// {
  879. /// // Insert a Paragraph into this document.
  880. /// Paragraph p = document.InsertParagraph("I am a Paragraph", false);
  881. ///
  882. /// p.InsertParagraphBeforeSelf("I was inserted before the next Paragraph.", false);
  883. ///
  884. /// // Save all changes made to this new document.
  885. /// document.Save();
  886. /// }// Release this new document form memory.
  887. /// </code>
  888. /// </example>
  889. public override Paragraph InsertParagraphBeforeSelf(string text, bool trackChanges)
  890. {
  891. Paragraph p = base.InsertParagraphBeforeSelf(text, trackChanges);
  892. p.PackagePart = mainPart;
  893. return p;
  894. }
  895. /// <summary>
  896. /// Insert a new Paragraph before this Paragraph.
  897. /// </summary>
  898. /// <param name="text">The initial text for this new Paragraph.</param>
  899. /// <param name="trackChanges">Should this insertion be tracked as a change?</param>
  900. /// <param name="formatting">The formatting to apply to this insertion.</param>
  901. /// <returns>A new Paragraph inserted before this Paragraph.</returns>
  902. /// <example>
  903. /// Insert a new paragraph before the first Paragraph in this document.
  904. /// <code>
  905. /// // Create a new document.
  906. /// using (DocX document = DocX.Create(@"Test.docx"))
  907. /// {
  908. /// // Insert a Paragraph into this document.
  909. /// Paragraph p = document.InsertParagraph("I am a Paragraph", false);
  910. ///
  911. /// Formatting boldFormatting = new Formatting();
  912. /// boldFormatting.Bold = true;
  913. ///
  914. /// p.InsertParagraphBeforeSelf("I was inserted before the next Paragraph.", false, boldFormatting);
  915. ///
  916. /// // Save all changes made to this new document.
  917. /// document.Save();
  918. /// }// Release this new document form memory.
  919. /// </code>
  920. /// </example>
  921. public override Paragraph InsertParagraphBeforeSelf(string text, bool trackChanges, Formatting formatting)
  922. {
  923. Paragraph p = base.InsertParagraphBeforeSelf(text, trackChanges, formatting);
  924. p.PackagePart = mainPart;
  925. return p;
  926. }
  927. /// <summary>
  928. /// Insert a page break before a Paragraph.
  929. /// </summary>
  930. /// <example>
  931. /// Insert 2 Paragraphs into a document with a page break between them.
  932. /// <code>
  933. /// using (DocX document = DocX.Create(@"Test.docx"))
  934. /// {
  935. /// // Insert a new Paragraph.
  936. /// Paragraph p1 = document.InsertParagraph("Paragraph 1", false);
  937. ///
  938. /// // Insert a new Paragraph.
  939. /// Paragraph p2 = document.InsertParagraph("Paragraph 2", false);
  940. ///
  941. /// // Insert a page break before Paragraph two.
  942. /// p2.InsertPageBreakBeforeSelf();
  943. ///
  944. /// // Save this document.
  945. /// document.Save();
  946. /// }// Release this document from memory.
  947. /// </code>
  948. /// </example>
  949. public override void InsertPageBreakBeforeSelf()
  950. {
  951. base.InsertPageBreakBeforeSelf();
  952. }
  953. /// <summary>
  954. /// Insert a page break after a Paragraph.
  955. /// </summary>
  956. /// <example>
  957. /// Insert 2 Paragraphs into a document with a page break between them.
  958. /// <code>
  959. /// using (DocX document = DocX.Create(@"Test.docx"))
  960. /// {
  961. /// // Insert a new Paragraph.
  962. /// Paragraph p1 = document.InsertParagraph("Paragraph 1", false);
  963. ///
  964. /// // Insert a page break after this Paragraph.
  965. /// p1.InsertPageBreakAfterSelf();
  966. ///
  967. /// // Insert a new Paragraph.
  968. /// Paragraph p2 = document.InsertParagraph("Paragraph 2", false);
  969. ///
  970. /// // Save this document.
  971. /// document.Save();
  972. /// }// Release this document from memory.
  973. /// </code>
  974. /// </example>
  975. public override void InsertPageBreakAfterSelf()
  976. {
  977. base.InsertPageBreakAfterSelf();
  978. }
  979. [Obsolete("Instead use: InsertHyperlink(Hyperlink h, int index)")]
  980. public Paragraph InsertHyperlink(int index, Hyperlink h) { return InsertHyperlink(h, index); }
  981. /// <summary>
  982. /// This function inserts a hyperlink into a Paragraph at a specified character index.
  983. /// </summary>
  984. /// <param name="index">The index to insert at.</param>
  985. /// <param name="h">The hyperlink to insert.</param>
  986. /// <returns>The Paragraph with the Hyperlink inserted at the specified index.</returns>
  987. /// <!--
  988. /// This function was added by Brian Campbell aka chickendelicious on Jun 16 2010
  989. /// Thank you Brian.
  990. /// -->
  991. public Paragraph InsertHyperlink(Hyperlink h, int index = 0)
  992. {
  993. // Convert the path of this mainPart to its equilivant rels file path.
  994. string path = mainPart.Uri.OriginalString.Replace("/word/", "");
  995. Uri rels_path = new Uri(String.Format("/word/_rels/{0}.rels", path), UriKind.Relative);
  996. // Check to see if the rels file exists and create it if not.
  997. if (!Document.package.PartExists(rels_path))
  998. HelperFunctions.CreateRelsPackagePart(Document, rels_path);
  999. // Check to see if a rel for this Picture exists, create it if not.
  1000. var Id = GetOrGenerateRel(h);
  1001. XElement h_xml;
  1002. if (index == 0)
  1003. {
  1004. // Add this hyperlink as the last element.
  1005. Xml.AddFirst(h.Xml);
  1006. // Extract the picture back out of the DOM.
  1007. h_xml = (XElement)Xml.FirstNode;
  1008. }
  1009. else
  1010. {
  1011. // Get the first run effected by this Insert
  1012. Run run = GetFirstRunEffectedByEdit(index);
  1013. if (run == null)
  1014. {
  1015. // Add this hyperlink as the last element.
  1016. Xml.Add(h.Xml);
  1017. // Extract the picture back out of the DOM.
  1018. h_xml = (XElement)Xml.LastNode;
  1019. }
  1020. else
  1021. {
  1022. // Split this run at the point you want to insert
  1023. XElement[] splitRun = Run.SplitRun(run, index);
  1024. // Replace the origional run.
  1025. run.Xml.ReplaceWith
  1026. (
  1027. splitRun[0],
  1028. h.Xml,
  1029. splitRun[1]
  1030. );
  1031. // Get the first run effected by this Insert
  1032. run = GetFirstRunEffectedByEdit(index);
  1033. // The picture has to be the next element, extract it back out of the DOM.
  1034. h_xml = (XElement)run.Xml.NextNode;
  1035. }
  1036. h_xml.SetAttributeValue(DocX.r + "id", Id);
  1037. }
  1038. return this;
  1039. }
  1040. /// <summary>
  1041. /// Remove the Hyperlink at the provided index. The first hyperlink is at index 0.
  1042. /// Using a negative index or an index greater than the index of the last hyperlink will cause an ArgumentOutOfRangeException() to be thrown.
  1043. /// </summary>
  1044. /// <param name="index">The index of the hyperlink to be removed.</param>
  1045. /// <example>
  1046. /// <code>
  1047. /// // Crete a new document.
  1048. /// using (DocX document = DocX.Create("Test.docx"))
  1049. /// {
  1050. /// // Add a Hyperlink into this document.
  1051. /// Hyperlink h = document.AddHyperlink("link", new Uri("http://www.google.com"));
  1052. ///
  1053. /// // Insert a new Paragraph into the document.
  1054. /// Paragraph p1 = document.InsertParagraph("AC");
  1055. ///
  1056. /// // Insert the hyperlink into this Paragraph.
  1057. /// p1.InsertHyperlink(1, h);
  1058. /// Assert.IsTrue(p1.Text == "AlinkC"); // Make sure the hyperlink was inserted correctly;
  1059. ///
  1060. /// // Remove the hyperlink
  1061. /// p1.RemoveHyperlink(0);
  1062. /// Assert.IsTrue(p1.Text == "AC"); // Make sure the hyperlink was removed correctly;
  1063. /// }
  1064. /// </code>
  1065. /// </example>
  1066. public void RemoveHyperlink(int index)
  1067. {
  1068. // Dosen't make sense to remove a Hyperlink at a negative index.
  1069. if (index < 0)
  1070. throw new ArgumentOutOfRangeException();
  1071. // Need somewhere to store the count.
  1072. int count = 0;
  1073. bool found = false;
  1074. RemoveHyperlinkRecursive(Xml, index, ref count, ref found);
  1075. // If !found then the user tried to remove a hyperlink at an index greater than the last.
  1076. if (!found)
  1077. throw new ArgumentOutOfRangeException();
  1078. }
  1079. internal void RemoveHyperlinkRecursive(XElement xml, int index, ref int count, ref bool found)
  1080. {
  1081. if (xml.Name.LocalName.Equals("hyperlink", StringComparison.CurrentCultureIgnoreCase))
  1082. {
  1083. // This is the hyperlink to be removed.
  1084. if (count == index)
  1085. {
  1086. found = true;
  1087. xml.Remove();
  1088. }
  1089. else
  1090. count++;
  1091. }
  1092. if (xml.HasElements)
  1093. foreach (XElement e in xml.Elements())
  1094. if (!found)
  1095. RemoveHyperlinkRecursive(e, index, ref count, ref found);
  1096. }
  1097. /// <summary>
  1098. /// Insert a Paragraph after this Paragraph, this Paragraph may have come from the same or another document.
  1099. /// </summary>
  1100. /// <param name="p">The Paragraph to insert.</param>
  1101. /// <returns>The Paragraph now associated with this document.</returns>
  1102. /// <example>
  1103. /// Take a Paragraph from document a, and insert it into document b after this Paragraph.
  1104. /// <code>
  1105. /// // Place holder for a Paragraph.
  1106. /// Paragraph p;
  1107. ///
  1108. /// // Load document a.
  1109. /// using (DocX documentA = DocX.Load(@"a.docx"))
  1110. /// {
  1111. /// // Get the first paragraph from this document.
  1112. /// p = documentA.Paragraphs[0];
  1113. /// }
  1114. ///
  1115. /// // Load document b.
  1116. /// using (DocX documentB = DocX.Load(@"b.docx"))
  1117. /// {
  1118. /// // Get the first Paragraph in document b.
  1119. /// Paragraph p2 = documentB.Paragraphs[0];
  1120. ///
  1121. /// // Insert the Paragraph from document a after this Paragraph.
  1122. /// Paragraph newParagraph = p2.InsertParagraphAfterSelf(p);
  1123. ///
  1124. /// // Save all changes made to document b.
  1125. /// documentB.Save();
  1126. /// }// Release this document from memory.
  1127. /// </code>
  1128. /// </example>
  1129. public override Paragraph InsertParagraphAfterSelf(Paragraph p)
  1130. {
  1131. Paragraph p2 = base.InsertParagraphAfterSelf(p);
  1132. p2.PackagePart = mainPart;
  1133. return p2;
  1134. }
  1135. /// <summary>
  1136. /// Insert a new Paragraph after this Paragraph.
  1137. /// </summary>
  1138. /// <param name="text">The initial text for this new Paragraph.</param>
  1139. /// <param name="trackChanges">Should this insertion be tracked as a change?</param>
  1140. /// <param name="formatting">The formatting to apply to this insertion.</param>
  1141. /// <returns>A new Paragraph inserted after this Paragraph.</returns>
  1142. /// <example>
  1143. /// Insert a new paragraph after the first Paragraph in this document.
  1144. /// <code>
  1145. /// // Create a new document.
  1146. /// using (DocX document = DocX.Create(@"Test.docx"))
  1147. /// {
  1148. /// // Insert a Paragraph into this document.
  1149. /// Paragraph p = document.InsertParagraph("I am a Paragraph", false);
  1150. ///
  1151. /// Formatting boldFormatting = new Formatting();
  1152. /// boldFormatting.Bold = true;
  1153. ///
  1154. /// p.InsertParagraphAfterSelf("I was inserted after the previous Paragraph.", false, boldFormatting);
  1155. ///
  1156. /// // Save all changes made to this new document.
  1157. /// document.Save();
  1158. /// }// Release this new document form memory.
  1159. /// </code>
  1160. /// </example>
  1161. public override Paragraph InsertParagraphAfterSelf(string text, bool trackChanges, Formatting formatting)
  1162. {
  1163. Paragraph p = base.InsertParagraphAfterSelf(text, trackChanges, formatting);
  1164. p.PackagePart = mainPart;
  1165. return p;
  1166. }
  1167. /// <summary>
  1168. /// Insert a new Paragraph after this Paragraph.
  1169. /// </summary>
  1170. /// <param name="text">The initial text for this new Paragraph.</param>
  1171. /// <param name="trackChanges">Should this insertion be tracked as a change?</param>
  1172. /// <returns>A new Paragraph inserted after this Paragraph.</returns>
  1173. /// <example>
  1174. /// Insert a new paragraph after the first Paragraph in this document.
  1175. /// <code>
  1176. /// // Create a new document.
  1177. /// using (DocX document = DocX.Create(@"Test.docx"))
  1178. /// {
  1179. /// // Insert a Paragraph into this document.
  1180. /// Paragraph p = document.InsertParagraph("I am a Paragraph", false);
  1181. ///
  1182. /// p.InsertParagraphAfterSelf("I was inserted after the previous Paragraph.", false);
  1183. ///
  1184. /// // Save all changes made to this new document.
  1185. /// document.Save();
  1186. /// }// Release this new document form memory.
  1187. /// </code>
  1188. /// </example>
  1189. public override Paragraph InsertParagraphAfterSelf(string text, bool trackChanges)
  1190. {
  1191. Paragraph p = base.InsertParagraphAfterSelf(text, trackChanges);
  1192. p.PackagePart = mainPart;
  1193. return p;
  1194. }
  1195. /// <summary>
  1196. /// Insert a new Paragraph after this Paragraph.
  1197. /// </summary>
  1198. /// <param name="text">The initial text for this new Paragraph.</param>
  1199. /// <returns>A new Paragraph inserted after this Paragraph.</returns>
  1200. /// <example>
  1201. /// Insert a new paragraph after the first Paragraph in this document.
  1202. /// <code>
  1203. /// // Create a new document.
  1204. /// using (DocX document = DocX.Create(@"Test.docx"))
  1205. /// {
  1206. /// // Insert a Paragraph into this document.
  1207. /// Paragraph p = document.InsertParagraph("I am a Paragraph", false);
  1208. ///
  1209. /// p.InsertParagraphAfterSelf("I was inserted after the previous Paragraph.");
  1210. ///
  1211. /// // Save all changes made to this new document.
  1212. /// document.Save();
  1213. /// }// Release this new document form memory.
  1214. /// </code>
  1215. /// </example>
  1216. public override Paragraph InsertParagraphAfterSelf(string text)
  1217. {
  1218. Paragraph p = base.InsertParagraphAfterSelf(text);
  1219. p.PackagePart = mainPart;
  1220. return p;
  1221. }
  1222. private void RebuildDocProperties()
  1223. {
  1224. docProperties =
  1225. (
  1226. from xml in Xml.Descendants(XName.Get("fldSimple", DocX.w.NamespaceName))
  1227. select new DocProperty(Document, xml)
  1228. ).ToList();
  1229. }
  1230. /// <summary>
  1231. /// Gets or set this Paragraphs text alignment.
  1232. /// </summary>
  1233. public Alignment Alignment
  1234. {
  1235. get
  1236. {
  1237. XElement pPr = GetOrCreate_pPr();
  1238. XElement jc = pPr.Element(XName.Get("jc", DocX.w.NamespaceName));
  1239. if (jc != null)
  1240. {
  1241. XAttribute a = jc.Attribute(XName.Get("val", DocX.w.NamespaceName));
  1242. switch (a.Value.ToLower())
  1243. {
  1244. case "left": return Novacode.Alignment.left;
  1245. case "right": return Novacode.Alignment.right;
  1246. case "center": return Novacode.Alignment.center;
  1247. case "both": return Novacode.Alignment.both;
  1248. }
  1249. }
  1250. return Novacode.Alignment.left;
  1251. }
  1252. set
  1253. {
  1254. alignment = value;
  1255. XElement pPr = GetOrCreate_pPr();
  1256. XElement jc = pPr.Element(XName.Get("jc", DocX.w.NamespaceName));
  1257. if (alignment != Novacode.Alignment.left)
  1258. {
  1259. if (jc == null)
  1260. pPr.Add(new XElement(XName.Get("jc", DocX.w.NamespaceName), new XAttribute(XName.Get("val", DocX.w.NamespaceName), alignment.ToString())));
  1261. else
  1262. jc.Attribute(XName.Get("val", DocX.w.NamespaceName)).Value = alignment.ToString();
  1263. }
  1264. else
  1265. {
  1266. if (jc != null)
  1267. jc.Remove();
  1268. }
  1269. }
  1270. }
  1271. /// <summary>
  1272. /// Remove this Paragraph from the document.
  1273. /// </summary>
  1274. /// <param name="trackChanges">Should this remove be tracked as a change?</param>
  1275. /// <example>
  1276. /// Remove a Paragraph from a document and track it as a change.
  1277. /// <code>
  1278. /// // Create a document using a relative filename.
  1279. /// using (DocX document = DocX.Load(@"C:\Example\Test.docx"))
  1280. /// {
  1281. /// // Create and Insert a new Paragraph into this document.
  1282. /// Paragraph p = document.InsertParagraph("Hello", false);
  1283. ///
  1284. /// // Remove the Paragraph and track this as a change.
  1285. /// p.Remove(true);
  1286. ///
  1287. /// // Save all changes made to this document.
  1288. /// document.Save();
  1289. /// }// Release this document from memory.
  1290. /// </code>
  1291. /// </example>
  1292. public void Remove(bool trackChanges)
  1293. {
  1294. if (trackChanges)
  1295. {
  1296. DateTime now = DateTime.Now.ToUniversalTime();
  1297. List<XElement> elements = Xml.Elements().ToList();
  1298. List<XElement> temp = new List<XElement>();
  1299. for (int i = 0; i < elements.Count(); i++)
  1300. {
  1301. XElement e = elements[i];
  1302. if (e.Name.LocalName != "del")
  1303. {
  1304. temp.Add(e);
  1305. e.Remove();
  1306. }
  1307. else
  1308. {
  1309. if (temp.Count() > 0)
  1310. {
  1311. e.AddBeforeSelf(CreateEdit(EditType.del, now, temp.Elements()));
  1312. temp.Clear();
  1313. }
  1314. }
  1315. }
  1316. if (temp.Count() > 0)
  1317. Xml.Add(CreateEdit(EditType.del, now, temp));
  1318. }
  1319. else
  1320. {
  1321. // If this is the only Paragraph in the Cell then we cannot remove it.
  1322. if (Xml.Parent.Name.LocalName == "tc" && Xml.Parent.Elements(XName.Get("p", DocX.w.NamespaceName)).Count() == 1)
  1323. Xml.Value = string.Empty;
  1324. else
  1325. {
  1326. // Remove this paragraph from the document
  1327. Xml.Remove();
  1328. Xml = null;
  1329. }
  1330. }
  1331. }
  1332. /// <summary>
  1333. /// Gets the text value of this Paragraph.
  1334. /// </summary>
  1335. public string Text
  1336. {
  1337. // Returns the underlying XElement's Value property.
  1338. get
  1339. {
  1340. return HelperFunctions.GetText(Xml);
  1341. }
  1342. }
  1343. /// <summary>
  1344. /// Gets the formatted text value of this Paragraph.
  1345. /// </summary>
  1346. public List<FormattedText> MagicText
  1347. {
  1348. // Returns the underlying XElement's Value property.
  1349. get
  1350. {
  1351. try
  1352. {
  1353. return HelperFunctions.GetFormattedText(Xml);
  1354. }
  1355. catch (Exception)
  1356. {
  1357. return null;
  1358. }
  1359. }
  1360. }
  1361. //public Picture InsertPicture(Picture picture)
  1362. //{
  1363. // Picture newPicture = picture;
  1364. // newPicture.i = new XElement(picture.i);
  1365. // xml.Add(newPicture.i);
  1366. // pictures.Add(newPicture);
  1367. // return newPicture;
  1368. //}
  1369. /// <summary>
  1370. /// Insert a Picture at the end of this paragraph.
  1371. /// </summary>
  1372. /// <param name="description">A string to describe this Picture.</param>
  1373. /// <param name="imageID">The unique id that identifies the Image this Picture represents.</param>
  1374. /// <param name="name">The name of this image.</param>
  1375. /// <returns>A Picture.</returns>
  1376. /// <example>
  1377. /// <code>
  1378. /// // Create a document using a relative filename.
  1379. /// using (DocX document = DocX.Create(@"Test.docx"))
  1380. /// {
  1381. /// // Add a new Paragraph to this document.
  1382. /// Paragraph p = document.InsertParagraph("Here is Picture 1", false);
  1383. ///
  1384. /// // Add an Image to this document.
  1385. /// Novacode.Image img = document.AddImage(@"Image.jpg");
  1386. ///
  1387. /// // Insert pic at the end of Paragraph p.
  1388. /// Picture pic = p.InsertPicture(img.Id, "Photo 31415", "A pie I baked.");
  1389. ///
  1390. /// // Rotate the Picture clockwise by 30 degrees.
  1391. /// pic.Rotation = 30;
  1392. ///
  1393. /// // Resize the Picture.
  1394. /// pic.Width = 400;
  1395. /// pic.Height = 300;
  1396. ///
  1397. /// // Set the shape of this Picture to be a cube.
  1398. /// pic.SetPictureShape(BasicShapes.cube);
  1399. ///
  1400. /// // Flip the Picture Horizontally.
  1401. /// pic.FlipHorizontal = true;
  1402. ///
  1403. /// // Save all changes made to this document.
  1404. /// document.Save();
  1405. /// }// Release this document from memory.
  1406. /// </code>
  1407. /// </example>
  1408. /// Removed to simplify the API.
  1409. //public Picture InsertPicture(string imageID, string name, string description)
  1410. //{
  1411. // Picture p = CreatePicture(Document, imageID, name, description);
  1412. // Xml.Add(p.Xml);
  1413. // return p;
  1414. //}
  1415. // Removed because it confusses the API.
  1416. //public Picture InsertPicture(string imageID)
  1417. //{
  1418. // return InsertPicture(imageID, string.Empty, string.Empty);
  1419. //}
  1420. //public Picture InsertPicture(int index, Picture picture)
  1421. //{
  1422. // Picture p = picture;
  1423. // p.i = new XElement(picture.i);
  1424. // Run run = GetFirstRunEffectedByEdit(index);
  1425. // if (run == null)
  1426. // xml.Add(p.i);
  1427. // else
  1428. // {
  1429. // // Split this run at the point you want to insert
  1430. // XElement[] splitRun = Run.SplitRun(run, index);
  1431. // // Replace the origional run
  1432. // run.Xml.ReplaceWith
  1433. // (
  1434. // splitRun[0],
  1435. // p.i,
  1436. // splitRun[1]
  1437. // );
  1438. // }
  1439. // // Rebuild the run lookup for this paragraph
  1440. // runLookup.Clear();
  1441. // BuildRunLookup(xml);
  1442. // DocX.RenumberIDs(document);
  1443. // return p;
  1444. //}
  1445. /// <summary>
  1446. /// Insert a Picture into this Paragraph at a specified index.
  1447. /// </summary>
  1448. /// <param name="description">A string to describe this Picture.</param>
  1449. /// <param name="imageID">The unique id that identifies the Image this Picture represents.</param>
  1450. /// <param name="name">The name of this image.</param>
  1451. /// <param name="index">The index to insert this Picture at.</param>
  1452. /// <returns>A Picture.</returns>
  1453. /// <example>
  1454. /// <code>
  1455. /// // Create a document using a relative filename.
  1456. /// using (DocX document = DocX.Create(@"Test.docx"))
  1457. /// {
  1458. /// // Add a new Paragraph to this document.
  1459. /// Paragraph p = document.InsertParagraph("Here is Picture 1", false);
  1460. ///
  1461. /// // Add an Image to this document.
  1462. /// Novacode.Image img = document.AddImage(@"Image.jpg");
  1463. ///
  1464. /// // Insert pic at the start of Paragraph p.
  1465. /// Picture pic = p.InsertPicture(0, img.Id, "Photo 31415", "A pie I baked.");
  1466. ///
  1467. /// // Rotate the Picture clockwise by 30 degrees.
  1468. /// pic.Rotation = 30;
  1469. ///
  1470. /// // Resize the Picture.
  1471. /// pic.Width = 400;
  1472. /// pic.Height = 300;
  1473. ///
  1474. /// // Set the shape of this Picture to be a cube.
  1475. /// pic.SetPictureShape(BasicShapes.cube);
  1476. ///
  1477. /// // Flip the Picture Horizontally.
  1478. /// pic.FlipHorizontal = true;
  1479. ///
  1480. /// // Save all changes made to this document.
  1481. /// document.Save();
  1482. /// }// Release this document from memory.
  1483. /// </code>
  1484. /// </example>
  1485. /// Removed to simplify API.
  1486. //public Picture InsertPicture(int index, string imageID, string name, string description)
  1487. //{
  1488. // Picture picture = CreatePicture(Document, imageID, name, description);
  1489. // Run run = GetFirstRunEffectedByEdit(index);
  1490. // if (run == null)
  1491. // Xml.Add(picture.Xml);
  1492. // else
  1493. // {
  1494. // // Split this run at the point you want to insert
  1495. // XElement[] splitRun = Run.SplitRun(run, index);
  1496. // // Replace the origional run
  1497. // run.Xml.ReplaceWith
  1498. // (
  1499. // splitRun[0],
  1500. // picture.Xml,
  1501. // splitRun[1]
  1502. // );
  1503. // }
  1504. // HelperFunctions.RenumberIDs(Document);
  1505. // return picture;
  1506. //}
  1507. /// <summary>
  1508. /// Create a new Picture.
  1509. /// </summary>
  1510. /// <param name="id">A unique id that identifies an Image embedded in this document.</param>
  1511. /// <param name="name">The name of this Picture.</param>
  1512. /// <param name="descr">The description of this Picture.</param>
  1513. static internal Picture CreatePicture(DocX document, string id, string name, string descr)
  1514. {
  1515. PackagePart part = document.package.GetPart(document.mainPart.GetRelationship(id).TargetUri);
  1516. int newDocPrId = 1;
  1517. List<string> existingIds = new List<string>();
  1518. foreach (var bookmarkId in document.Xml.Descendants(XName.Get("bookmarkStart", DocX.w.NamespaceName)))
  1519. {
  1520. var idAtt = bookmarkId.Attributes().FirstOrDefault(x => x.Name.LocalName == "id");
  1521. if (idAtt != null)
  1522. existingIds.Add(idAtt.Value);
  1523. }
  1524. while (existingIds.Contains(newDocPrId.ToString()))
  1525. newDocPrId++;
  1526. int cx, cy;
  1527. using (System.Drawing.Image img = System.Drawing.Image.FromStream(part.GetStream()))
  1528. {
  1529. cx = img.Width * 9526;
  1530. cy = img.Height * 9526;
  1531. }
  1532. XElement e = new XElement(DocX.w + "drawing");
  1533. XElement xml = XElement.Parse
  1534. (string.Format(@"<w:r xmlns:w=""http://schemas.openxmlformats.org/wordprocessingml/2006/main"">
  1535. <w:drawing xmlns = ""http://schemas.openxmlformats.org/wordprocessingml/2006/main"">
  1536. <wp:inline distT=""0"" distB=""0"" distL=""0"" distR=""0"" xmlns:wp=""http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing"">
  1537. <wp:extent cx=""{0}"" cy=""{1}"" />
  1538. <wp:effectExtent l=""0"" t=""0"" r=""0"" b=""0"" />
  1539. <wp:docPr id=""{5}"" name=""{3}"" descr=""{4}"" />
  1540. <wp:cNvGraphicFramePr>
  1541. <a:graphicFrameLocks xmlns:a=""http://schemas.openxmlformats.org/drawingml/2006/main"" noChangeAspect=""1"" />
  1542. </wp:cNvGraphicFramePr>
  1543. <a:graphic xmlns:a=""http://schemas.openxmlformats.org/drawingml/2006/main"">
  1544. <a:graphicData uri=""http://schemas.openxmlformats.org/drawingml/2006/picture"">
  1545. <pic:pic xmlns:pic=""http://schemas.openxmlformats.org/drawingml/2006/picture"">
  1546. <pic:nvPicPr>
  1547. <pic:cNvPr id=""0"" name=""{3}"" />
  1548. <pic:cNvPicPr />
  1549. </pic:nvPicPr>
  1550. <pic:blipFill>
  1551. <a:blip r:embed=""{2}"" xmlns:r=""http://schemas.openxmlformats.org/officeDocument/2006/relationships""/>
  1552. <a:stretch>
  1553. <a:fillRect />
  1554. </a:stretch>
  1555. </pic:blipFill>
  1556. <pic:spPr>
  1557. <a:xfrm>
  1558. <a:off x=""0"" y=""0"" />
  1559. <a:ext cx=""{0}"" cy=""{1}"" />
  1560. </a:xfrm>
  1561. <a:prstGeom prst=""rect"">
  1562. <a:avLst />
  1563. </a:prstGeom>
  1564. </pic:spPr>
  1565. </pic:pic>
  1566. </a:graphicData>
  1567. </a:graphic>
  1568. </wp:inline>
  1569. </w:drawing></w:r>
  1570. ", cx, cy, id, name, descr, newDocPrId.ToString()));
  1571. return new Picture(document, xml, new Image(document, document.mainPart.GetRelationship(id)));
  1572. }
  1573. // Removed because it confusses the API.
  1574. //public Picture InsertPicture(int index, string imageID)
  1575. //{
  1576. // return InsertPicture(index, imageID, string.Empty, string.Empty);
  1577. //}
  1578. /// <summary>
  1579. /// Creates an Edit either a ins or a del with the specified content and date
  1580. /// </summary>
  1581. /// <param name="t">The type of this edit (ins or del)</param>
  1582. /// <param name="edit_time">The time stamp to use for this edit</param>
  1583. /// <param name="content">The initial content of this edit</param>
  1584. /// <returns></returns>
  1585. internal static XElement CreateEdit(EditType t, DateTime edit_time, object content)
  1586. {
  1587. if (t == EditType.del)
  1588. {
  1589. foreach (object o in (IEnumerable<XElement>)content)
  1590. {
  1591. if (o is XElement)
  1592. {
  1593. XElement e = (o as XElement);
  1594. IEnumerable<XElement> ts = e.DescendantsAndSelf(XName.Get("t", DocX.w.NamespaceName));
  1595. for (int i = 0; i < ts.Count(); i++)
  1596. {
  1597. XElement text = ts.ElementAt(i);
  1598. text.ReplaceWith(new XElement(DocX.w + "delText", text.Attributes(), text.Value));
  1599. }
  1600. }
  1601. }
  1602. }
  1603. return
  1604. (
  1605. new XElement(DocX.w + t.ToString(),
  1606. new XAttribute(DocX.w + "id", 0),
  1607. new XAttribute(DocX.w + "author", WindowsIdentity.GetCurrent().Name),
  1608. new XAttribute(DocX.w + "date", edit_time),
  1609. content)
  1610. );
  1611. }
  1612. internal Run GetFirstRunEffectedByEdit(int index, EditType type = EditType.ins)
  1613. {
  1614. int len = HelperFunctions.GetText(Xml).Length;
  1615. // Make sure we are looking within an acceptable index range.
  1616. if (index < 0 || ((type == EditType.ins && index > len) || (type == EditType.del && index >= len)))
  1617. throw new ArgumentOutOfRangeException();
  1618. // Need some memory that can be updated by the recursive search for the XElement to Split.
  1619. int count = 0;
  1620. Run theOne = null;
  1621. GetFirstRunEffectedByEditRecursive(Xml, index, ref count, ref theOne, type);
  1622. return theOne;
  1623. }
  1624. internal void GetFirstRunEffectedByEditRecursive(XElement Xml, int index, ref int count, ref Run theOne, EditType type)
  1625. {
  1626. count += HelperFunctions.GetSize(Xml);
  1627. // If the EditType is deletion then we must return the next blah
  1628. if (count > 0 && ((type == EditType.del && count > index) || (type == EditType.ins && count >= index)))
  1629. {
  1630. // Correct the index
  1631. foreach (XElement e in Xml.ElementsBeforeSelf())
  1632. count -= HelperFunctions.GetSize(e);
  1633. count -= HelperFunctions.GetSize(Xml);
  1634. // We have found the element, now find the run it belongs to.
  1635. while ((Xml.Name.LocalName != "r") && (Xml.Name.LocalName != "pPr"))
  1636. Xml = Xml.Parent;
  1637. theOne = new Run(Document, Xml, count);
  1638. return;
  1639. }
  1640. if (Xml.HasElements)
  1641. foreach (XElement e in Xml.Elements())
  1642. if (theOne == null)
  1643. GetFirstRunEffectedByEditRecursive(e, index, ref count, ref theOne, type);
  1644. }
  1645. /// <!--
  1646. /// Bug found and fixed by krugs525 on August 12 2009.
  1647. /// Use TFS compare to see exact code change.
  1648. /// -->
  1649. static internal int GetElementTextLength(XElement run)
  1650. {
  1651. int count = 0;
  1652. if (run == null)
  1653. return count;
  1654. foreach (var d in run.Descendants())
  1655. {
  1656. switch (d.Name.LocalName)
  1657. {
  1658. case "tab":
  1659. if (d.Parent.Name.LocalName != "tabs")
  1660. goto case "br"; break;
  1661. case "br": count++; break;
  1662. case "t": goto case "delText";
  1663. case "delText": count += d.Value.Length; break;
  1664. default: break;
  1665. }
  1666. }
  1667. return count;
  1668. }
  1669. internal XElement[] SplitEdit(XElement edit, int index, EditType type)
  1670. {
  1671. Run run = GetFirstRunEffectedByEdit(index, type);
  1672. XElement[] splitRun = Run.SplitRun(run, index, type);
  1673. XElement splitLeft = new XElement(edit.Name, edit.Attributes(), run.Xml.ElementsBeforeSelf(), splitRun[0]);
  1674. if (GetElementTextLength(splitLeft) == 0)
  1675. splitLeft = null;
  1676. XElement splitRight = new XElement(edit.Name, edit.Attributes(), splitRun[1], run.Xml.ElementsAfterSelf());
  1677. if (GetElementTextLength(splitRight) == 0)
  1678. splitRight = null;
  1679. return
  1680. (
  1681. new XElement[]
  1682. {
  1683. splitLeft,
  1684. splitRight
  1685. }
  1686. );
  1687. }
  1688. /// <summary>
  1689. /// Inserts a specified instance of System.String into a Novacode.DocX.Paragraph at a specified index position.
  1690. /// </summary>
  1691. /// <example>
  1692. /// <code>
  1693. /// // Create a document using a relative filename.
  1694. /// using (DocX document = DocX.Load(@"C:\Example\Test.docx"))
  1695. /// {
  1696. /// // Create a text formatting.
  1697. /// Formatting f = new Formatting();
  1698. /// f.FontColor = Color.Red;
  1699. /// f.Size = 30;
  1700. ///
  1701. /// // Iterate through the Paragraphs in this document.
  1702. /// foreach (Paragraph p in document.Paragraphs)
  1703. /// {
  1704. /// // Insert the string "Start: " at the begining of every Paragraph and flag it as a change.
  1705. /// p.InsertText("Start: ", true, f);
  1706. /// }
  1707. ///
  1708. /// // Save all changes made to this document.
  1709. /// document.Save();
  1710. /// }// Release this document from memory.
  1711. /// </code>
  1712. /// </example>
  1713. /// <example>
  1714. /// Inserting tabs using the \t switch.
  1715. /// <code>
  1716. /// // Create a document using a relative filename.
  1717. /// using (DocX document = DocX.Load(@"C:\Example\Test.docx"))
  1718. /// {
  1719. /// // Create a text formatting.
  1720. /// Formatting f = new Formatting();
  1721. /// f.FontColor = Color.Red;
  1722. /// f.Size = 30;
  1723. ///
  1724. /// // Iterate through the paragraphs in this document.
  1725. /// foreach (Paragraph p in document.Paragraphs)
  1726. /// {
  1727. /// // Insert the string "\tEnd" at the end of every paragraph and flag it as a change.
  1728. /// p.InsertText("\tEnd", true, f);
  1729. /// }
  1730. ///
  1731. /// // Save all changes made to this document.
  1732. /// document.Save();
  1733. /// }// Release this document from memory.
  1734. /// </code>
  1735. /// </example>
  1736. /// <seealso cref="Paragraph.RemoveText(int, bool)"/>
  1737. /// <seealso cref="Paragraph.RemoveText(int, int, bool)"/>
  1738. /// <seealso cref="Paragraph.ReplaceText(string, string, bool)"/>
  1739. /// <seealso cref="Paragraph.ReplaceText(string, string, bool, RegexOptions)"/>
  1740. /// <param name="value">The System.String to insert.</param>
  1741. /// <param name="trackChanges">Flag this insert as a change.</param>
  1742. /// <param name="formatting">The text formatting.</param>
  1743. public void InsertText(string value, bool trackChanges = false, Formatting formatting = null)
  1744. {
  1745. // Default values for optional parameters must be compile time constants.
  1746. // Would have like to write 'public void InsertText(string value, bool trackChanges = false, Formatting formatting = new Formatting())
  1747. if (formatting == null) formatting = new Formatting();
  1748. List<XElement> newRuns = HelperFunctions.FormatInput(value, formatting.Xml);
  1749. Xml.Add(newRuns);
  1750. HelperFunctions.RenumberIDs(Document);
  1751. }
  1752. /// <summary>
  1753. /// Inserts a specified instance of System.String into a Novacode.DocX.Paragraph at a specified index position.
  1754. /// </summary>
  1755. /// <example>
  1756. /// <code>
  1757. /// // Create a document using a relative filename.
  1758. /// using (DocX document = DocX.Load(@"C:\Example\Test.docx"))
  1759. /// {
  1760. /// // Create a text formatting.
  1761. /// Formatting f = new Formatting();
  1762. /// f.FontColor = Color.Red;
  1763. /// f.Size = 30;
  1764. ///
  1765. /// // Iterate through the Paragraphs in this document.
  1766. /// foreach (Paragraph p in document.Paragraphs)
  1767. /// {
  1768. /// // Insert the string "Start: " at the begining of every Paragraph and flag it as a change.
  1769. /// p.InsertText(0, "Start: ", true, f);
  1770. /// }
  1771. ///
  1772. /// // Save all changes made to this document.
  1773. /// document.Save();
  1774. /// }// Release this document from memory.
  1775. /// </code>
  1776. /// </example>
  1777. /// <example>
  1778. /// Inserting tabs using the \t switch.
  1779. /// <code>
  1780. /// // Create a document using a relative filename.
  1781. /// using (DocX document = DocX.Load(@"C:\Example\Test.docx"))
  1782. /// {
  1783. /// // Create a text formatting.
  1784. /// Formatting f = new Formatting();
  1785. /// f.FontColor = Color.Red;
  1786. /// f.Size = 30;
  1787. ///
  1788. /// // Iterate through the paragraphs in this document.
  1789. /// foreach (Paragraph p in document.Paragraphs)
  1790. /// {
  1791. /// // Insert the string "\tStart:\t" at the begining of every paragraph and flag it as a change.
  1792. /// p.InsertText(0, "\tStart:\t", true, f);
  1793. /// }
  1794. ///
  1795. /// // Save all changes made to this document.
  1796. /// document.Save();
  1797. /// }// Release this document from memory.
  1798. /// </code>
  1799. /// </example>
  1800. /// <seealso cref="Paragraph.RemoveText(int, bool)"/>
  1801. /// <seealso cref="Paragraph.RemoveText(int, int, bool)"/>
  1802. /// <seealso cref="Paragraph.ReplaceText(string, string, bool)"/>
  1803. /// <seealso cref="Paragraph.ReplaceText(string, string, bool, RegexOptions)"/>
  1804. /// <param name="index">The index position of the insertion.</param>
  1805. /// <param name="value">The System.String to insert.</param>
  1806. /// <param name="trackChanges">Flag this insert as a change.</param>
  1807. /// <param name="formatting">The text formatting.</param>
  1808. public void InsertText(int index, string value, bool trackChanges = false, Formatting formatting = null)
  1809. {
  1810. // Timestamp to mark the start of insert
  1811. DateTime now = DateTime.Now;
  1812. DateTime insert_datetime = new DateTime(now.Year, now.Month, now.Day, now.Hour, now.Minute, 0, DateTimeKind.Utc);
  1813. // Get the first run effected by this Insert
  1814. Run run = GetFirstRunEffectedByEdit(index);
  1815. if (run == null)
  1816. {
  1817. object insert;
  1818. if (formatting != null)
  1819. insert = HelperFunctions.FormatInput(value, formatting.Xml);
  1820. else
  1821. insert = HelperFunctions.FormatInput(value, null);
  1822. if (trackChanges)
  1823. insert = CreateEdit(EditType.ins, insert_datetime, insert);
  1824. Xml.Add(insert);
  1825. }
  1826. else
  1827. {
  1828. object newRuns;
  1829. if (formatting != null)
  1830. newRuns = HelperFunctions.FormatInput(value, formatting.Xml);
  1831. else
  1832. newRuns = HelperFunctions.FormatInput(value, run.Xml.Element(XName.Get("rPr", DocX.w.NamespaceName)));
  1833. // The parent of this Run
  1834. XElement parentElement = run.Xml.Parent;
  1835. switch (parentElement.Name.LocalName)
  1836. {
  1837. case "ins":
  1838. {
  1839. // The datetime that this ins was created
  1840. DateTime parent_ins_date = DateTime.Parse(parentElement.Attribute(XName.Get("date", DocX.w.NamespaceName)).Value);
  1841. /*
  1842. * Special case: You want to track changes,
  1843. * and the first Run effected by this insert
  1844. * has a datetime stamp equal to now.
  1845. */
  1846. if (trackChanges && parent_ins_date.CompareTo(insert_datetime) == 0)
  1847. {
  1848. /*
  1849. * Inserting into a non edit and this special case, is the same procedure.
  1850. */
  1851. goto default;
  1852. }
  1853. /*
  1854. * If not the special case above,
  1855. * then inserting into an ins or a del, is the same procedure.
  1856. */
  1857. goto case "del";
  1858. }
  1859. case "del":
  1860. {
  1861. object insert = newRuns;
  1862. if (trackChanges)
  1863. insert = CreateEdit(EditType.ins, insert_datetime, newRuns);
  1864. // Split this Edit at the point you want to insert
  1865. XElement[] splitEdit = SplitEdit(parentElement, index, EditType.ins);
  1866. // Replace the origional run
  1867. parentElement.ReplaceWith
  1868. (
  1869. splitEdit[0],
  1870. insert,
  1871. splitEdit[1]
  1872. );
  1873. break;
  1874. }
  1875. default:
  1876. {
  1877. object insert = newRuns;
  1878. if (trackChanges && !parentElement.Name.LocalName.Equals("ins"))
  1879. insert = CreateEdit(EditType.ins, insert_datetime, newRuns);
  1880. // Special case to deal with Page Number elements.
  1881. //if (parentElement.Name.LocalName.Equals("fldSimple"))
  1882. // parentElement.AddBeforeSelf(insert);
  1883. else
  1884. {
  1885. // Split this run at the point you want to insert
  1886. XElement[] splitRun = Run.SplitRun(run, index);
  1887. // Replace the origional run
  1888. run.Xml.ReplaceWith
  1889. (
  1890. splitRun[0],
  1891. insert,
  1892. splitRun[1]
  1893. );
  1894. }
  1895. break;
  1896. }
  1897. }
  1898. }
  1899. HelperFunctions.RenumberIDs(Document);
  1900. }
  1901. /// <summary>
  1902. /// For use with Append() and AppendLine()
  1903. /// </summary>
  1904. /// <returns>This Paragraph in curent culture</returns>
  1905. /// <example>
  1906. /// Add a new Paragraph with russian text to this document and then set language of text to local culture.
  1907. /// <code>
  1908. /// // Load a document.
  1909. /// using (DocX document = DocX.Create(@"Test.docx"))
  1910. /// {
  1911. /// // Insert a new Paragraph with russian text and set curent local culture to it.
  1912. /// Paragraph p = document.InsertParagraph("Привет мир!").CurentCulture();
  1913. ///
  1914. /// // Save this document.
  1915. /// document.Save();
  1916. /// }
  1917. /// </code>
  1918. /// </example>
  1919. public Paragraph CurentCulture()
  1920. {
  1921. ApplyTextFormattingProperty(XName.Get("lang", DocX.w.NamespaceName),
  1922. string.Empty,
  1923. new XAttribute(XName.Get("val", DocX.w.NamespaceName), CultureInfo.CurrentCulture.Name));
  1924. return this;
  1925. }
  1926. /// <summary>
  1927. /// For use with Append() and AppendLine()
  1928. /// </summary>
  1929. /// <param name="culture">The CultureInfo for text</param>
  1930. /// <returns>This Paragraph in curent culture</returns>
  1931. /// <example>
  1932. /// Add a new Paragraph with russian text to this document and then set language of text to local culture.
  1933. /// <code>
  1934. /// // Load a document.
  1935. /// using (DocX document = DocX.Create(@"Test.docx"))
  1936. /// {
  1937. /// // Insert a new Paragraph with russian text and set specific culture to it.
  1938. /// Paragraph p = document.InsertParagraph("Привет мир").Culture(CultureInfo.CreateSpecificCulture("ru-RU"));
  1939. ///
  1940. /// // Save this document.
  1941. /// document.Save();
  1942. /// }
  1943. /// </code>
  1944. /// </example>
  1945. public Paragraph Culture(CultureInfo culture)
  1946. {
  1947. ApplyTextFormattingProperty(XName.Get("lang", DocX.w.NamespaceName), string.Empty,
  1948. new XAttribute(XName.Get("val", DocX.w.NamespaceName), culture.Name));
  1949. return this;
  1950. }
  1951. /// <summary>
  1952. /// Append text to this Paragraph.
  1953. /// </summary>
  1954. /// <param name="text">The text to append.</param>
  1955. /// <returns>This Paragraph with the new text appened.</returns>
  1956. /// <example>
  1957. /// Add a new Paragraph to this document and then append some text to it.
  1958. /// <code>
  1959. /// // Load a document.
  1960. /// using (DocX document = DocX.Create(@"Test.docx"))
  1961. /// {
  1962. /// // Insert a new Paragraph and Append some text to it.
  1963. /// Paragraph p = document.InsertParagraph().Append("Hello World!!!");
  1964. ///
  1965. /// // Save this document.
  1966. /// document.Save();
  1967. /// }
  1968. /// </code>
  1969. /// </example>
  1970. public Paragraph Append(string text)
  1971. {
  1972. List<XElement> newRuns = HelperFunctions.FormatInput(text, null);
  1973. Xml.Add(newRuns);
  1974. this.runs = Xml.Elements(XName.Get("r", DocX.w.NamespaceName)).Reverse().Take(newRuns.Count()).ToList();
  1975. return this;
  1976. }
  1977. /// <summary>
  1978. /// Append a hyperlink to a Paragraph.
  1979. /// </summary>
  1980. /// <param name="h">The hyperlink to append.</param>
  1981. /// <returns>The Paragraph with the hyperlink appended.</returns>
  1982. /// <example>
  1983. /// Creates a Paragraph with some text and a hyperlink.
  1984. /// <code>
  1985. /// // Create a document.
  1986. /// using (DocX document = DocX.Create(@"Test.docx"))
  1987. /// {
  1988. /// // Add a hyperlink to this document.
  1989. /// Hyperlink h = document.AddHyperlink("Google", new Uri("http://www.google.com"));
  1990. ///
  1991. /// // Add a new Paragraph to this document.
  1992. /// Paragraph p = document.InsertParagraph();
  1993. /// p.Append("My favourite search engine is ");
  1994. /// p.AppendHyperlink(h);
  1995. /// p.Append(", I think it's great.");
  1996. ///
  1997. /// // Save all changes made to this document.
  1998. /// document.Save();
  1999. /// }
  2000. /// </code>
  2001. /// </example>
  2002. public Paragraph AppendHyperlink(Hyperlink h)
  2003. {
  2004. // Convert the path of this mainPart to its equilivant rels file path.
  2005. string path = mainPart.Uri.OriginalString.Replace("/word/", "");
  2006. Uri rels_path = new Uri("/word/_rels/" + path + ".rels", UriKind.Relative);
  2007. // Check to see if the rels file exists and create it if not.
  2008. if (!Document.package.PartExists(rels_path))
  2009. HelperFunctions.CreateRelsPackagePart(Document, rels_path);
  2010. // Check to see if a rel for this Hyperlink exists, create it if not.
  2011. var Id = GetOrGenerateRel(h);
  2012. Xml.Add(h.Xml);
  2013. Xml.Elements().Last().SetAttributeValue(DocX.r + "id", Id);
  2014. this.runs = Xml.Elements().Last().Elements(XName.Get("r", DocX.w.NamespaceName)).ToList();
  2015. return this;
  2016. }
  2017. /// <summary>
  2018. /// Add an image to a document, create a custom view of that image (picture) and then insert it into a Paragraph using append.
  2019. /// </summary>
  2020. /// <param name="p">The Picture to append.</param>
  2021. /// <returns>The Paragraph with the Picture now appended.</returns>
  2022. /// <example>
  2023. /// Add an image to a document, create a custom view of that image (picture) and then insert it into a Paragraph using append.
  2024. /// <code>
  2025. /// using (DocX document = DocX.Create("Test.docx"))
  2026. /// {
  2027. /// // Add an image to the document.
  2028. /// Image i = document.AddImage(@"Image.jpg");
  2029. ///
  2030. /// // Create a picture i.e. (A custom view of an image)
  2031. /// Picture p = i.CreatePicture();
  2032. /// p.FlipHorizontal = true;
  2033. /// p.Rotation = 10;
  2034. ///
  2035. /// // Create a new Paragraph.
  2036. /// Paragraph par = document.InsertParagraph();
  2037. ///
  2038. /// // Append content to the Paragraph.
  2039. /// par.Append("Here is a cool picture")
  2040. /// .AppendPicture(p)
  2041. /// .Append(" don't you think so?");
  2042. ///
  2043. /// // Save all changes made to this document.
  2044. /// document.Save();
  2045. /// }
  2046. /// </code>
  2047. /// </example>
  2048. public Paragraph AppendPicture(Picture p)
  2049. {
  2050. // Convert the path of this mainPart to its equilivant rels file path.
  2051. string path = mainPart.Uri.OriginalString.Replace("/word/", "");
  2052. Uri rels_path = new Uri("/word/_rels/" + path + ".rels", UriKind.Relative);
  2053. // Check to see if the rels file exists and create it if not.
  2054. if (!Document.package.PartExists(rels_path))
  2055. HelperFunctions.CreateRelsPackagePart(Document, rels_path);
  2056. // Check to see if a rel for this Picture exists, create it if not.
  2057. var Id = GetOrGenerateRel(p);
  2058. // Add the Picture Xml to the end of the Paragragraph Xml.
  2059. Xml.Add(p.Xml);
  2060. // Extract the attribute id from the Pictures Xml.
  2061. XAttribute a_id =
  2062. (
  2063. from e in Xml.Elements().Last().Descendants()
  2064. where e.Name.LocalName.Equals("blip")
  2065. select e.Attribute(XName.Get("embed", "http://schemas.openxmlformats.org/officeDocument/2006/relationships"))
  2066. ).Single();
  2067. // Set its value to the Pictures relationships id.
  2068. a_id.SetValue(Id);
  2069. // For formatting such as .Bold()
  2070. this.runs = Xml.Elements(XName.Get("r", DocX.w.NamespaceName)).Reverse().Take(p.Xml.Elements(XName.Get("r", DocX.w.NamespaceName)).Count()).ToList();
  2071. return this;
  2072. }
  2073. /// <summary>
  2074. /// Add an equation to a document.
  2075. /// </summary>
  2076. /// <param name="equation">The Equation to append.</param>
  2077. /// <returns>The Paragraph with the Equation now appended.</returns>
  2078. /// <example>
  2079. /// Add an equation to a document.
  2080. /// <code>
  2081. /// using (DocX document = DocX.Create("Test.docx"))
  2082. /// {
  2083. /// // Add an equation to the document.
  2084. /// document.AddEquation("x=y+z");
  2085. ///
  2086. /// // Save all changes made to this document.
  2087. /// document.Save();
  2088. /// }
  2089. /// </code>
  2090. /// </example>
  2091. public Paragraph AppendEquation(String equation)
  2092. {
  2093. // Create equation element
  2094. XElement oMathPara =
  2095. new XElement
  2096. (
  2097. XName.Get("oMathPara", DocX.m.NamespaceName),
  2098. new XElement
  2099. (
  2100. XName.Get("oMath", DocX.m.NamespaceName),
  2101. new XElement
  2102. (
  2103. XName.Get("r", DocX.w.NamespaceName),
  2104. new Formatting() { FontFamily = new System.Drawing.FontFamily("Cambria Math") }.Xml, // create formatting
  2105. new XElement(XName.Get("t", DocX.m.NamespaceName), equation) // create equation string
  2106. )
  2107. )
  2108. );
  2109. // Add equation element into paragraph xml and update runs collection
  2110. Xml.Add(oMathPara);
  2111. runs = Xml.Elements(XName.Get("oMathPara", DocX.m.NamespaceName)).ToList();
  2112. // Return paragraph with equation
  2113. return this;
  2114. }
  2115. public bool ValidateBookmark(string bookmarkName)
  2116. {
  2117. return GetBookmarks().Any(b => b.Name.Equals(bookmarkName));
  2118. }
  2119. public Paragraph AppendBookmark(String bookmarkName)
  2120. {
  2121. XElement wBookmarkStart = new XElement(
  2122. XName.Get("bookmarkStart", DocX.w.NamespaceName),
  2123. new XAttribute(XName.Get("id", DocX.w.NamespaceName), 0),
  2124. new XAttribute(XName.Get("name", DocX.w.NamespaceName), bookmarkName));
  2125. Xml.Add(wBookmarkStart);
  2126. XElement wBookmarkEnd = new XElement(
  2127. XName.Get("bookmarkEnd", DocX.w.NamespaceName),
  2128. new XAttribute(XName.Get("id", DocX.w.NamespaceName), 0),
  2129. new XAttribute(XName.Get("name", DocX.w.NamespaceName), bookmarkName));
  2130. Xml.Add(wBookmarkEnd);
  2131. return this;
  2132. }
  2133. public IEnumerable<Bookmark> GetBookmarks()
  2134. {
  2135. return Xml.Descendants(XName.Get("bookmarkStart", DocX.w.NamespaceName))
  2136. .Select(x => x.Attribute(XName.Get("name", DocX.w.NamespaceName)))
  2137. .Select(x => new Bookmark
  2138. {
  2139. Name = x.Value,
  2140. Paragraph = this
  2141. });
  2142. }
  2143. public void InsertAtBookmark(string toInsert, string bookmarkName)
  2144. {
  2145. var bookmark = Xml.Descendants(XName.Get("bookmarkStart", DocX.w.NamespaceName))
  2146. .Where(x => x.Attribute(XName.Get("name", DocX.w.NamespaceName)).Value == bookmarkName).SingleOrDefault();
  2147. if (bookmark != null)
  2148. {
  2149. var run = HelperFunctions.FormatInput(toInsert, null);
  2150. bookmark.AddBeforeSelf(run);
  2151. runs = Xml.Elements(XName.Get("r", DocX.w.NamespaceName)).ToList();
  2152. HelperFunctions.RenumberIDs(Document);
  2153. }
  2154. }
  2155. public void ReplaceAtBookmark(string toInsert, string bookmarkName)
  2156. {
  2157. XElement bookmark = Xml.Descendants(XName.Get("bookmarkStart", DocX.w.NamespaceName))
  2158. .Where(x => x.Attribute(XName.Get("name", DocX.w.NamespaceName)).Value == bookmarkName)
  2159. .SingleOrDefault();
  2160. if (bookmark == null)
  2161. return;
  2162. XNode nextNode = bookmark.NextNode;
  2163. XElement nextElement = nextNode as XElement;
  2164. while (nextElement == null || nextElement.Name.NamespaceName != DocX.w.NamespaceName || (nextElement.Name.LocalName != "r" && nextElement.Name.LocalName != "bookmarkEnd"))
  2165. {
  2166. nextNode = nextNode.NextNode;
  2167. nextElement = nextNode as XElement;
  2168. }
  2169. // Check if next element is a bookmarkEnd
  2170. if (nextElement.Name.LocalName == "bookmarkEnd")
  2171. {
  2172. ReplaceAtBookmark_Add(toInsert, bookmark);
  2173. return;
  2174. }
  2175. XElement contentElement = nextElement.Elements(XName.Get("t", DocX.w.NamespaceName)).FirstOrDefault();
  2176. if (contentElement == null)
  2177. {
  2178. ReplaceAtBookmark_Add(toInsert, bookmark);
  2179. return;
  2180. }
  2181. contentElement.Value = toInsert;
  2182. }
  2183. private void ReplaceAtBookmark_Add(string toInsert, XElement bookmark)
  2184. {
  2185. var run = HelperFunctions.FormatInput(toInsert, null);
  2186. bookmark.AddAfterSelf(run);
  2187. runs = Xml.Elements(XName.Get("r", DocX.w.NamespaceName)).ToList();
  2188. HelperFunctions.RenumberIDs(Document);
  2189. }
  2190. internal string GetOrGenerateRel(Picture p)
  2191. {
  2192. string image_uri_string = p.img.pr.TargetUri.OriginalString;
  2193. // Search for a relationship with a TargetUri that points at this Image.
  2194. var Id =
  2195. (
  2196. from r in mainPart.GetRelationshipsByType("http://schemas.openxmlformats.org/officeDocument/2006/relationships/image")
  2197. where r.TargetUri.OriginalString == image_uri_string
  2198. select r.Id
  2199. ).SingleOrDefault();
  2200. // If such a relation dosen't exist, create one.
  2201. if (Id == null)
  2202. {
  2203. // Check to see if a relationship for this Picture exists and create it if not.
  2204. PackageRelationship pr = mainPart.CreateRelationship(p.img.pr.TargetUri, TargetMode.Internal, "http://schemas.openxmlformats.org/officeDocument/2006/relationships/image");
  2205. Id = pr.Id;
  2206. }
  2207. return Id;
  2208. }
  2209. internal string GetOrGenerateRel(Hyperlink h)
  2210. {
  2211. string image_uri_string = h.Uri.OriginalString;
  2212. // Search for a relationship with a TargetUri that points at this Image.
  2213. var Id =
  2214. (
  2215. from r in mainPart.GetRelationshipsByType("http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink")
  2216. where r.TargetUri.OriginalString == image_uri_string
  2217. select r.Id
  2218. ).SingleOrDefault();
  2219. // If such a relation dosen't exist, create one.
  2220. if (Id == null)
  2221. {
  2222. // Check to see if a relationship for this Picture exists and create it if not.
  2223. PackageRelationship pr = mainPart.CreateRelationship(h.Uri, TargetMode.External, "http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink");
  2224. Id = pr.Id;
  2225. }
  2226. return Id;
  2227. }
  2228. /// <summary>
  2229. /// Insert a Picture into a Paragraph at the given text index.
  2230. /// If not index is provided defaults to 0.
  2231. /// </summary>
  2232. /// <param name="p">The Picture to insert.</param>
  2233. /// <param name="index">The text index to insert at.</param>
  2234. /// <returns>The modified Paragraph.</returns>
  2235. /// <example>
  2236. /// <code>
  2237. ///Load test document.
  2238. ///using (DocX document = DocX.Create("Test.docx"))
  2239. ///{
  2240. /// // Add Headers and Footers into this document.
  2241. /// document.AddHeaders();
  2242. /// document.AddFooters();
  2243. /// document.DifferentFirstPage = true;
  2244. /// document.DifferentOddAndEvenPages = true;
  2245. ///
  2246. /// // Add an Image to this document.
  2247. /// Novacode.Image img = document.AddImage(directory_documents + "purple.png");
  2248. ///
  2249. /// // Create a Picture from this Image.
  2250. /// Picture pic = img.CreatePicture();
  2251. ///
  2252. /// // Main document.
  2253. /// Paragraph p0 = document.InsertParagraph("Hello");
  2254. /// p0.InsertPicture(pic, 3);
  2255. ///
  2256. /// // Header first.
  2257. /// Paragraph p1 = document.Headers.first.InsertParagraph("----");
  2258. /// p1.InsertPicture(pic, 2);
  2259. ///
  2260. /// // Header odd.
  2261. /// Paragraph p2 = document.Headers.odd.InsertParagraph("----");
  2262. /// p2.InsertPicture(pic, 2);
  2263. ///
  2264. /// // Header even.
  2265. /// Paragraph p3 = document.Headers.even.InsertParagraph("----");
  2266. /// p3.InsertPicture(pic, 2);
  2267. ///
  2268. /// // Footer first.
  2269. /// Paragraph p4 = document.Footers.first.InsertParagraph("----");
  2270. /// p4.InsertPicture(pic, 2);
  2271. ///
  2272. /// // Footer odd.
  2273. /// Paragraph p5 = document.Footers.odd.InsertParagraph("----");
  2274. /// p5.InsertPicture(pic, 2);
  2275. ///
  2276. /// // Footer even.
  2277. /// Paragraph p6 = document.Footers.even.InsertParagraph("----");
  2278. /// p6.InsertPicture(pic, 2);
  2279. ///
  2280. /// // Save this document.
  2281. /// document.Save();
  2282. ///}
  2283. /// </code>
  2284. /// </example>
  2285. public Paragraph InsertPicture(Picture p, int index = 0)
  2286. {
  2287. // Convert the path of this mainPart to its equilivant rels file path.
  2288. string path = mainPart.Uri.OriginalString.Replace("/word/", "");
  2289. Uri rels_path = new Uri("/word/_rels/" + path + ".rels", UriKind.Relative);
  2290. // Check to see if the rels file exists and create it if not.
  2291. if (!Document.package.PartExists(rels_path))
  2292. HelperFunctions.CreateRelsPackagePart(Document, rels_path);
  2293. // Check to see if a rel for this Picture exists, create it if not.
  2294. var Id = GetOrGenerateRel(p);
  2295. XElement p_xml;
  2296. if (index == 0)
  2297. {
  2298. // Add this hyperlink as the last element.
  2299. Xml.AddFirst(p.Xml);
  2300. // Extract the picture back out of the DOM.
  2301. p_xml = (XElement)Xml.FirstNode;
  2302. }
  2303. else
  2304. {
  2305. // Get the first run effected by this Insert
  2306. Run run = GetFirstRunEffectedByEdit(index);
  2307. if (run == null)
  2308. {
  2309. // Add this picture as the last element.
  2310. Xml.Add(p.Xml);
  2311. // Extract the picture back out of the DOM.
  2312. p_xml = (XElement)Xml.LastNode;
  2313. }
  2314. else
  2315. {
  2316. // Split this run at the point you want to insert
  2317. XElement[] splitRun = Run.SplitRun(run, index);
  2318. // Replace the origional run.
  2319. run.Xml.ReplaceWith
  2320. (
  2321. splitRun[0],
  2322. p.Xml,
  2323. splitRun[1]
  2324. );
  2325. // Get the first run effected by this Insert
  2326. run = GetFirstRunEffectedByEdit(index);
  2327. // The picture has to be the next element, extract it back out of the DOM.
  2328. p_xml = (XElement)run.Xml.NextNode;
  2329. }
  2330. }
  2331. // Extract the attribute id from the Pictures Xml.
  2332. XAttribute a_id =
  2333. (
  2334. from e in p_xml.Descendants()
  2335. where e.Name.LocalName.Equals("blip")
  2336. select e.Attribute(XName.Get("embed", "http://schemas.openxmlformats.org/officeDocument/2006/relationships"))
  2337. ).Single();
  2338. // Set its value to the Pictures relationships id.
  2339. a_id.SetValue(Id);
  2340. return this;
  2341. }
  2342. /// <summary>
  2343. /// Append text on a new line to this Paragraph.
  2344. /// </summary>
  2345. /// <param name="text">The text to append.</param>
  2346. /// <returns>This Paragraph with the new text appened.</returns>
  2347. /// <example>
  2348. /// Add a new Paragraph to this document and then append a new line with some text to it.
  2349. /// <code>
  2350. /// // Load a document.
  2351. /// using (DocX document = DocX.Create(@"Test.docx"))
  2352. /// {
  2353. /// // Insert a new Paragraph and Append a new line with some text to it.
  2354. /// Paragraph p = document.InsertParagraph().AppendLine("Hello World!!!");
  2355. ///
  2356. /// // Save this document.
  2357. /// document.Save();
  2358. /// }
  2359. /// </code>
  2360. /// </example>
  2361. public Paragraph AppendLine(string text)
  2362. {
  2363. return Append("\n" + text);
  2364. }
  2365. /// <summary>
  2366. /// Append a new line to this Paragraph.
  2367. /// </summary>
  2368. /// <returns>This Paragraph with a new line appeneded.</returns>
  2369. /// <example>
  2370. /// Add a new Paragraph to this document and then append a new line to it.
  2371. /// <code>
  2372. /// // Load a document.
  2373. /// using (DocX document = DocX.Create(@"Test.docx"))
  2374. /// {
  2375. /// // Insert a new Paragraph and Append a new line with some text to it.
  2376. /// Paragraph p = document.InsertParagraph().AppendLine();
  2377. ///
  2378. /// // Save this document.
  2379. /// document.Save();
  2380. /// }
  2381. /// </code>
  2382. /// </example>
  2383. public Paragraph AppendLine()
  2384. {
  2385. return Append("\n");
  2386. }
  2387. internal void ApplyTextFormattingProperty(XName textFormatPropName, string value, object content)
  2388. {
  2389. XElement rPr = null;
  2390. if (runs.Count == 0)
  2391. {
  2392. XElement pPr = Xml.Element(XName.Get("pPr", DocX.w.NamespaceName));
  2393. if (pPr == null)
  2394. {
  2395. Xml.AddFirst(new XElement(XName.Get("pPr", DocX.w.NamespaceName)));
  2396. pPr = Xml.Element(XName.Get("pPr", DocX.w.NamespaceName));
  2397. }
  2398. rPr = pPr.Element(XName.Get("rPr", DocX.w.NamespaceName));
  2399. if (rPr == null)
  2400. {
  2401. pPr.AddFirst(new XElement(XName.Get("rPr", DocX.w.NamespaceName)));
  2402. rPr = pPr.Element(XName.Get("rPr", DocX.w.NamespaceName));
  2403. }
  2404. rPr.SetElementValue(textFormatPropName, value);
  2405. var last = rPr.Elements().Last();
  2406. if (content as System.Xml.Linq.XAttribute != null)//If content is an attribute
  2407. {
  2408. if (last.Attribute(((System.Xml.Linq.XAttribute)(content)).Name) == null)
  2409. {
  2410. last.Add(content); //Add this attribute if element doesn't have it
  2411. }
  2412. else
  2413. {
  2414. last.Attribute(((System.Xml.Linq.XAttribute)(content)).Name).Value = ((System.Xml.Linq.XAttribute)(content)).Value; //Apply value only if element already has it
  2415. }
  2416. }
  2417. return;
  2418. }
  2419. var contentIsListOfFontProperties = false;
  2420. var fontProps = content as IEnumerable;
  2421. if (fontProps != null)
  2422. {
  2423. foreach (object property in fontProps)
  2424. {
  2425. contentIsListOfFontProperties = (property as XAttribute != null);
  2426. }
  2427. }
  2428. foreach (XElement run in runs)
  2429. {
  2430. rPr = run.Element(XName.Get("rPr", DocX.w.NamespaceName));
  2431. if (rPr == null)
  2432. {
  2433. run.AddFirst(new XElement(XName.Get("rPr", DocX.w.NamespaceName)));
  2434. rPr = run.Element(XName.Get("rPr", DocX.w.NamespaceName));
  2435. }
  2436. rPr.SetElementValue(textFormatPropName, value);
  2437. XElement last = rPr.Elements().Last();
  2438. if (contentIsListOfFontProperties) //if content is a list of attributes, as in the case when specifying a font family
  2439. {
  2440. foreach (object property in fontProps)
  2441. {
  2442. if (last.Attribute(((System.Xml.Linq.XAttribute)(property)).Name) == null)
  2443. {
  2444. last.Add(property); //Add this attribute if element doesn't have it
  2445. }
  2446. else
  2447. {
  2448. last.Attribute(((System.Xml.Linq.XAttribute)(property)).Name).Value =
  2449. ((System.Xml.Linq.XAttribute)(property)).Value; //Apply value only if element already has it
  2450. }
  2451. }
  2452. }
  2453. if (content as System.Xml.Linq.XAttribute != null)//If content is an attribute
  2454. {
  2455. if (last.Attribute(((System.Xml.Linq.XAttribute)(content)).Name) == null)
  2456. {
  2457. last.Add(content); //Add this attribute if element doesn't have it
  2458. }
  2459. else
  2460. {
  2461. last.Attribute(((System.Xml.Linq.XAttribute)(content)).Name).Value = ((System.Xml.Linq.XAttribute)(content)).Value; //Apply value only if element already has it
  2462. }
  2463. }
  2464. else
  2465. {
  2466. //IMPORTANT
  2467. //But what to do if it is not?
  2468. }
  2469. }
  2470. }
  2471. /// <summary>
  2472. /// For use with Append() and AppendLine()
  2473. /// </summary>
  2474. /// <returns>This Paragraph with the last appended text bold.</returns>
  2475. /// <example>
  2476. /// Append text to this Paragraph and then make it bold.
  2477. /// <code>
  2478. /// // Create a document.
  2479. /// using (DocX document = DocX.Create(@"Test.docx"))
  2480. /// {
  2481. /// // Insert a new Paragraph.
  2482. /// Paragraph p = document.InsertParagraph();
  2483. ///
  2484. /// p.Append("I am ")
  2485. /// .Append("Bold").Bold()
  2486. /// .Append(" I am not");
  2487. ///
  2488. /// // Save this document.
  2489. /// document.Save();
  2490. /// }// Release this document from memory.
  2491. /// </code>
  2492. /// </example>
  2493. public Paragraph Bold()
  2494. {
  2495. ApplyTextFormattingProperty(XName.Get("b", DocX.w.NamespaceName), string.Empty, null);
  2496. return this;
  2497. }
  2498. /// <summary>
  2499. /// For use with Append() and AppendLine()
  2500. /// </summary>
  2501. /// <returns>This Paragraph with the last appended text italic.</returns>
  2502. /// <example>
  2503. /// Append text to this Paragraph and then make it italic.
  2504. /// <code>
  2505. /// // Create a document.
  2506. /// using (DocX document = DocX.Create(@"Test.docx"))
  2507. /// {
  2508. /// // Insert a new Paragraph.
  2509. /// Paragraph p = document.InsertParagraph();
  2510. ///
  2511. /// p.Append("I am ")
  2512. /// .Append("Italic").Italic()
  2513. /// .Append(" I am not");
  2514. ///
  2515. /// // Save this document.
  2516. /// document.Save();
  2517. /// }// Release this document from memory.
  2518. /// </code>
  2519. /// </example>
  2520. public Paragraph Italic()
  2521. {
  2522. ApplyTextFormattingProperty(XName.Get("i", DocX.w.NamespaceName), string.Empty, null);
  2523. return this;
  2524. }
  2525. /// <summary>
  2526. /// For use with Append() and AppendLine()
  2527. /// </summary>
  2528. /// <param name="c">A color to use on the appended text.</param>
  2529. /// <returns>This Paragraph with the last appended text colored.</returns>
  2530. /// <example>
  2531. /// Append text to this Paragraph and then color it.
  2532. /// <code>
  2533. /// // Create a document.
  2534. /// using (DocX document = DocX.Create(@"Test.docx"))
  2535. /// {
  2536. /// // Insert a new Paragraph.
  2537. /// Paragraph p = document.InsertParagraph();
  2538. ///
  2539. /// p.Append("I am ")
  2540. /// .Append("Blue").Color(Color.Blue)
  2541. /// .Append(" I am not");
  2542. ///
  2543. /// // Save this document.
  2544. /// document.Save();
  2545. /// }// Release this document from memory.
  2546. /// </code>
  2547. /// </example>
  2548. public Paragraph Color(Color c)
  2549. {
  2550. ApplyTextFormattingProperty(XName.Get("color", DocX.w.NamespaceName), string.Empty, new XAttribute(XName.Get("val", DocX.w.NamespaceName), c.ToHex()));
  2551. return this;
  2552. }
  2553. /// <summary>
  2554. /// For use with Append() and AppendLine()
  2555. /// </summary>
  2556. /// <param name="underlineStyle">The underline style to use for the appended text.</param>
  2557. /// <returns>This Paragraph with the last appended text underlined.</returns>
  2558. /// <example>
  2559. /// Append text to this Paragraph and then underline it.
  2560. /// <code>
  2561. /// // Create a document.
  2562. /// using (DocX document = DocX.Create(@"Test.docx"))
  2563. /// {
  2564. /// // Insert a new Paragraph.
  2565. /// Paragraph p = document.InsertParagraph();
  2566. ///
  2567. /// p.Append("I am ")
  2568. /// .Append("Underlined").UnderlineStyle(UnderlineStyle.doubleLine)
  2569. /// .Append(" I am not");
  2570. ///
  2571. /// // Save this document.
  2572. /// document.Save();
  2573. /// }// Release this document from memory.
  2574. /// </code>
  2575. /// </example>
  2576. public Paragraph UnderlineStyle(UnderlineStyle underlineStyle)
  2577. {
  2578. string value;
  2579. switch (underlineStyle)
  2580. {
  2581. case Novacode.UnderlineStyle.none: value = string.Empty; break;
  2582. case Novacode.UnderlineStyle.singleLine: value = "single"; break;
  2583. case Novacode.UnderlineStyle.doubleLine: value = "double"; break;
  2584. default: value = underlineStyle.ToString(); break;
  2585. }
  2586. ApplyTextFormattingProperty(XName.Get("u", DocX.w.NamespaceName), string.Empty, new XAttribute(XName.Get("val", DocX.w.NamespaceName), value));
  2587. return this;
  2588. }
  2589. private Table followingTable;
  2590. ///<summary>
  2591. /// Returns table following the paragraph. Null if the following element isn't table.
  2592. ///</summary>
  2593. public Table FollowingTable
  2594. {
  2595. get
  2596. {
  2597. return followingTable;
  2598. }
  2599. internal set
  2600. {
  2601. followingTable = value;
  2602. }
  2603. }
  2604. /// <summary>
  2605. /// For use with Append() and AppendLine()
  2606. /// </summary>
  2607. /// <param name="fontSize">The font size to use for the appended text.</param>
  2608. /// <returns>This Paragraph with the last appended text resized.</returns>
  2609. /// <example>
  2610. /// Append text to this Paragraph and then resize it.
  2611. /// <code>
  2612. /// // Create a document.
  2613. /// using (DocX document = DocX.Create(@"Test.docx"))
  2614. /// {
  2615. /// // Insert a new Paragraph.
  2616. /// Paragraph p = document.InsertParagraph();
  2617. ///
  2618. /// p.Append("I am ")
  2619. /// .Append("Big").FontSize(20)
  2620. /// .Append(" I am not");
  2621. ///
  2622. /// // Save this document.
  2623. /// document.Save();
  2624. /// }// Release this document from memory.
  2625. /// </code>
  2626. /// </example>
  2627. public Paragraph FontSize(double fontSize)
  2628. {
  2629. if (fontSize - (int)fontSize == 0)
  2630. {
  2631. if (!(fontSize > 0 && fontSize < 1639))
  2632. throw new ArgumentException("Size", "Value must be in the range 0 - 1638");
  2633. }
  2634. else
  2635. throw new ArgumentException("Size", "Value must be either a whole or half number, examples: 32, 32.5");
  2636. ApplyTextFormattingProperty(XName.Get("sz", DocX.w.NamespaceName), string.Empty, new XAttribute(XName.Get("val", DocX.w.NamespaceName), fontSize * 2));
  2637. ApplyTextFormattingProperty(XName.Get("szCs", DocX.w.NamespaceName), string.Empty, new XAttribute(XName.Get("val", DocX.w.NamespaceName), fontSize * 2));
  2638. return this;
  2639. }
  2640. /// <summary>
  2641. /// For use with Append() and AppendLine()
  2642. /// </summary>
  2643. /// <param name="fontFamily">The font to use for the appended text.</param>
  2644. /// <returns>This Paragraph with the last appended text's font changed.</returns>
  2645. /// <example>
  2646. /// Append text to this Paragraph and then change its font.
  2647. /// <code>
  2648. /// // Create a document.
  2649. /// using (DocX document = DocX.Create(@"Test.docx"))
  2650. /// {
  2651. /// // Insert a new Paragraph.
  2652. /// Paragraph p = document.InsertParagraph();
  2653. ///
  2654. /// p.Append("I am ")
  2655. /// .Append("Times new roman").Font(new FontFamily("Times new roman"))
  2656. /// .Append(" I am not");
  2657. ///
  2658. /// // Save this document.
  2659. /// document.Save();
  2660. /// }// Release this document from memory.
  2661. /// </code>
  2662. /// </example>
  2663. public Paragraph Font(FontFamily fontFamily)
  2664. {
  2665. ApplyTextFormattingProperty
  2666. (
  2667. XName.Get("rFonts", DocX.w.NamespaceName),
  2668. string.Empty,
  2669. new[]
  2670. {
  2671. new XAttribute(XName.Get("ascii", DocX.w.NamespaceName), fontFamily.Name),
  2672. new XAttribute(XName.Get("hAnsi", DocX.w.NamespaceName), fontFamily.Name), // Added by Maurits Elbers to support non-standard characters. See http://docx.codeplex.com/Thread/View.aspx?ThreadId=70097&ANCHOR#Post453865
  2673. new XAttribute(XName.Get("cs", DocX.w.NamespaceName), fontFamily.Name), // Added by Maurits Elbers to support non-standard characters. See http://docx.codeplex.com/Thread/View.aspx?ThreadId=70097&ANCHOR#Post453865
  2674. }
  2675. );
  2676. return this;
  2677. }
  2678. /// <summary>
  2679. /// For use with Append() and AppendLine()
  2680. /// </summary>
  2681. /// <param name="capsStyle">The caps style to apply to the last appended text.</param>
  2682. /// <returns>This Paragraph with the last appended text's caps style changed.</returns>
  2683. /// <example>
  2684. /// Append text to this Paragraph and then set it to full caps.
  2685. /// <code>
  2686. /// // Create a document.
  2687. /// using (DocX document = DocX.Create(@"Test.docx"))
  2688. /// {
  2689. /// // Insert a new Paragraph.
  2690. /// Paragraph p = document.InsertParagraph();
  2691. ///
  2692. /// p.Append("I am ")
  2693. /// .Append("Capitalized").CapsStyle(CapsStyle.caps)
  2694. /// .Append(" I am not");
  2695. ///
  2696. /// // Save this document.
  2697. /// document.Save();
  2698. /// }// Release this document from memory.
  2699. /// </code>
  2700. /// </example>
  2701. public Paragraph CapsStyle(CapsStyle capsStyle)
  2702. {
  2703. switch (capsStyle)
  2704. {
  2705. case Novacode.CapsStyle.none:
  2706. break;
  2707. default:
  2708. {
  2709. ApplyTextFormattingProperty(XName.Get(capsStyle.ToString(), DocX.w.NamespaceName), string.Empty, null);
  2710. break;
  2711. }
  2712. }
  2713. return this;
  2714. }
  2715. /// <summary>
  2716. /// For use with Append() and AppendLine()
  2717. /// </summary>
  2718. /// <param name="script">The script style to apply to the last appended text.</param>
  2719. /// <returns>This Paragraph with the last appended text's script style changed.</returns>
  2720. /// <example>
  2721. /// Append text to this Paragraph and then set it to superscript.
  2722. /// <code>
  2723. /// // Create a document.
  2724. /// using (DocX document = DocX.Create(@"Test.docx"))
  2725. /// {
  2726. /// // Insert a new Paragraph.
  2727. /// Paragraph p = document.InsertParagraph();
  2728. ///
  2729. /// p.Append("I am ")
  2730. /// .Append("superscript").Script(Script.superscript)
  2731. /// .Append(" I am not");
  2732. ///
  2733. /// // Save this document.
  2734. /// document.Save();
  2735. /// }// Release this document from memory.
  2736. /// </code>
  2737. /// </example>
  2738. public Paragraph Script(Script script)
  2739. {
  2740. switch (script)
  2741. {
  2742. case Novacode.Script.none:
  2743. break;
  2744. default:
  2745. {
  2746. ApplyTextFormattingProperty(XName.Get("vertAlign", DocX.w.NamespaceName), string.Empty, new XAttribute(XName.Get("val", DocX.w.NamespaceName), script.ToString()));
  2747. break;
  2748. }
  2749. }
  2750. return this;
  2751. }
  2752. /// <summary>
  2753. /// For use with Append() and AppendLine()
  2754. /// </summary>
  2755. ///<param name="highlight">The highlight to apply to the last appended text.</param>
  2756. /// <returns>This Paragraph with the last appended text highlighted.</returns>
  2757. /// <example>
  2758. /// Append text to this Paragraph and then highlight it.
  2759. /// <code>
  2760. /// // Create a document.
  2761. /// using (DocX document = DocX.Create(@"Test.docx"))
  2762. /// {
  2763. /// // Insert a new Paragraph.
  2764. /// Paragraph p = document.InsertParagraph();
  2765. ///
  2766. /// p.Append("I am ")
  2767. /// .Append("highlighted").Highlight(Highlight.green)
  2768. /// .Append(" I am not");
  2769. ///
  2770. /// // Save this document.
  2771. /// document.Save();
  2772. /// }// Release this document from memory.
  2773. /// </code>
  2774. /// </example>
  2775. public Paragraph Highlight(Highlight highlight)
  2776. {
  2777. switch (highlight)
  2778. {
  2779. case Novacode.Highlight.none:
  2780. break;
  2781. default:
  2782. {
  2783. ApplyTextFormattingProperty(XName.Get("highlight", DocX.w.NamespaceName), string.Empty, new XAttribute(XName.Get("val", DocX.w.NamespaceName), highlight.ToString()));
  2784. break;
  2785. }
  2786. }
  2787. return this;
  2788. }
  2789. /// <summary>
  2790. /// For use with Append() and AppendLine()
  2791. /// </summary>
  2792. /// <param name="misc">The miscellaneous property to set.</param>
  2793. /// <returns>This Paragraph with the last appended text changed by a miscellaneous property.</returns>
  2794. /// <example>
  2795. /// Append text to this Paragraph and then apply a miscellaneous property.
  2796. /// <code>
  2797. /// // Create a document.
  2798. /// using (DocX document = DocX.Create(@"Test.docx"))
  2799. /// {
  2800. /// // Insert a new Paragraph.
  2801. /// Paragraph p = document.InsertParagraph();
  2802. ///
  2803. /// p.Append("I am ")
  2804. /// .Append("outlined").Misc(Misc.outline)
  2805. /// .Append(" I am not");
  2806. ///
  2807. /// // Save this document.
  2808. /// document.Save();
  2809. /// }// Release this document from memory.
  2810. /// </code>
  2811. /// </example>
  2812. public Paragraph Misc(Misc misc)
  2813. {
  2814. switch (misc)
  2815. {
  2816. case Novacode.Misc.none:
  2817. break;
  2818. case Novacode.Misc.outlineShadow:
  2819. {
  2820. ApplyTextFormattingProperty(XName.Get("outline", DocX.w.NamespaceName), string.Empty, null);
  2821. ApplyTextFormattingProperty(XName.Get("shadow", DocX.w.NamespaceName), string.Empty, null);
  2822. break;
  2823. }
  2824. case Novacode.Misc.engrave:
  2825. {
  2826. ApplyTextFormattingProperty(XName.Get("imprint", DocX.w.NamespaceName), string.Empty, null);
  2827. break;
  2828. }
  2829. default:
  2830. {
  2831. ApplyTextFormattingProperty(XName.Get(misc.ToString(), DocX.w.NamespaceName), string.Empty, null);
  2832. break;
  2833. }
  2834. }
  2835. return this;
  2836. }
  2837. /// <summary>
  2838. /// For use with Append() and AppendLine()
  2839. /// </summary>
  2840. /// <param name="strikeThrough">The strike through style to used on the last appended text.</param>
  2841. /// <returns>This Paragraph with the last appended text striked.</returns>
  2842. /// <example>
  2843. /// Append text to this Paragraph and then strike it.
  2844. /// <code>
  2845. /// // Create a document.
  2846. /// using (DocX document = DocX.Create(@"Test.docx"))
  2847. /// {
  2848. /// // Insert a new Paragraph.
  2849. /// Paragraph p = document.InsertParagraph();
  2850. ///
  2851. /// p.Append("I am ")
  2852. /// .Append("striked").StrikeThrough(StrikeThrough.doubleStrike)
  2853. /// .Append(" I am not");
  2854. ///
  2855. /// // Save this document.
  2856. /// document.Save();
  2857. /// }// Release this document from memory.
  2858. /// </code>
  2859. /// </example>
  2860. public Paragraph StrikeThrough(StrikeThrough strikeThrough)
  2861. {
  2862. string value;
  2863. switch (strikeThrough)
  2864. {
  2865. case Novacode.StrikeThrough.strike: value = "strike"; break;
  2866. case Novacode.StrikeThrough.doubleStrike: value = "dstrike"; break;
  2867. default: return this;
  2868. }
  2869. ApplyTextFormattingProperty(XName.Get(value, DocX.w.NamespaceName), string.Empty, null);
  2870. return this;
  2871. }
  2872. /// <summary>
  2873. /// For use with Append() and AppendLine()
  2874. /// </summary>
  2875. /// <param name="underlineColor">The underline color to use, if no underline is set, a single line will be used.</param>
  2876. /// <returns>This Paragraph with the last appended text underlined in a color.</returns>
  2877. /// <example>
  2878. /// Append text to this Paragraph and then underline it using a color.
  2879. /// <code>
  2880. /// // Create a document.
  2881. /// using (DocX document = DocX.Create(@"Test.docx"))
  2882. /// {
  2883. /// // Insert a new Paragraph.
  2884. /// Paragraph p = document.InsertParagraph();
  2885. ///
  2886. /// p.Append("I am ")
  2887. /// .Append("color underlined").UnderlineStyle(UnderlineStyle.dotted).UnderlineColor(Color.Orange)
  2888. /// .Append(" I am not");
  2889. ///
  2890. /// // Save this document.
  2891. /// document.Save();
  2892. /// }// Release this document from memory.
  2893. /// </code>
  2894. /// </example>
  2895. public Paragraph UnderlineColor(Color underlineColor)
  2896. {
  2897. foreach (XElement run in runs)
  2898. {
  2899. XElement rPr = run.Element(XName.Get("rPr", DocX.w.NamespaceName));
  2900. if (rPr == null)
  2901. {
  2902. run.AddFirst(new XElement(XName.Get("rPr", DocX.w.NamespaceName)));
  2903. rPr = run.Element(XName.Get("rPr", DocX.w.NamespaceName));
  2904. }
  2905. XElement u = rPr.Element(XName.Get("u", DocX.w.NamespaceName));
  2906. if (u == null)
  2907. {
  2908. rPr.SetElementValue(XName.Get("u", DocX.w.NamespaceName), string.Empty);
  2909. u = rPr.Element(XName.Get("u", DocX.w.NamespaceName));
  2910. u.SetAttributeValue(XName.Get("val", DocX.w.NamespaceName), "single");
  2911. }
  2912. u.SetAttributeValue(XName.Get("color", DocX.w.NamespaceName), underlineColor.ToHex());
  2913. }
  2914. return this;
  2915. }
  2916. /// <summary>
  2917. /// For use with Append() and AppendLine()
  2918. /// </summary>
  2919. /// <returns>This Paragraph with the last appended text hidden.</returns>
  2920. /// <example>
  2921. /// Append text to this Paragraph and then hide it.
  2922. /// <code>
  2923. /// // Create a document.
  2924. /// using (DocX document = DocX.Create(@"Test.docx"))
  2925. /// {
  2926. /// // Insert a new Paragraph.
  2927. /// Paragraph p = document.InsertParagraph();
  2928. ///
  2929. /// p.Append("I am ")
  2930. /// .Append("hidden").Hide()
  2931. /// .Append(" I am not");
  2932. ///
  2933. /// // Save this document.
  2934. /// document.Save();
  2935. /// }// Release this document from memory.
  2936. /// </code>
  2937. /// </example>
  2938. public Paragraph Hide()
  2939. {
  2940. ApplyTextFormattingProperty(XName.Get("vanish", DocX.w.NamespaceName), string.Empty, null);
  2941. return this;
  2942. }
  2943. public float LineSpacing
  2944. {
  2945. get
  2946. {
  2947. XElement pPr = GetOrCreate_pPr();
  2948. XElement spacing = pPr.Element(XName.Get("spacing", DocX.w.NamespaceName));
  2949. if (spacing != null)
  2950. {
  2951. XAttribute line = spacing.Attribute(XName.Get("line", DocX.w.NamespaceName));
  2952. if (line != null)
  2953. {
  2954. float f;
  2955. if (float.TryParse(line.Value, out f))
  2956. return f / 20.0f;
  2957. }
  2958. }
  2959. return 1.1f * 20.0f;
  2960. }
  2961. set
  2962. {
  2963. Spacing(value);
  2964. }
  2965. }
  2966. /// <summary>
  2967. /// Set the linespacing for this paragraph manually.
  2968. /// </summary>
  2969. /// <param name="spacingType">The type of spacing to be set, can be either Before, After or Line (Standard line spacing).</param>
  2970. /// <param name="spacingFloat">A float value of the amount of spacing. Equals the value that van be set in Word using the "Line and Paragraph spacing" button.</param>
  2971. public void SetLineSpacing(LineSpacingType spacingType, float spacingFloat)
  2972. {
  2973. spacingFloat = spacingFloat * 240;
  2974. int spacingValue = (int)spacingFloat;
  2975. var pPr = this.GetOrCreate_pPr();
  2976. var spacing = pPr.Element(XName.Get("spacing", DocX.w.NamespaceName));
  2977. if (spacing == null)
  2978. {
  2979. pPr.Add(new XElement(XName.Get("spacing", DocX.w.NamespaceName)));
  2980. spacing = pPr.Element(XName.Get("spacing", DocX.w.NamespaceName));
  2981. }
  2982. string spacingTypeAttribute = "";
  2983. switch (spacingType)
  2984. {
  2985. case LineSpacingType.Line:
  2986. {
  2987. spacingTypeAttribute = "line";
  2988. break;
  2989. }
  2990. case LineSpacingType.Before:
  2991. {
  2992. spacingTypeAttribute = "before";
  2993. break;
  2994. }
  2995. case LineSpacingType.After:
  2996. {
  2997. spacingTypeAttribute = "after";
  2998. break;
  2999. }
  3000. }
  3001. spacing.SetAttributeValue(XName.Get(spacingTypeAttribute, DocX.w.NamespaceName), spacingValue);
  3002. }
  3003. /// <summary>
  3004. /// Set the linespacing for this paragraph using the Auto value.
  3005. /// </summary>
  3006. /// <param name="spacingType">The type of spacing to be set automatically. Using Auto will set both Before and After. None will remove any linespacing.</param>
  3007. public void SetLineSpacing(LineSpacingTypeAuto spacingType)
  3008. {
  3009. int spacingValue = 100;
  3010. var pPr = this.GetOrCreate_pPr();
  3011. var spacing = pPr.Element(XName.Get("spacing", DocX.w.NamespaceName));
  3012. if (spacingType.Equals(LineSpacingTypeAuto.None))
  3013. {
  3014. if (spacing != null)
  3015. {
  3016. spacing.Remove();
  3017. }
  3018. }
  3019. else
  3020. {
  3021. if (spacing == null)
  3022. {
  3023. pPr.Add(new XElement(XName.Get("spacing", DocX.w.NamespaceName)));
  3024. spacing = pPr.Element(XName.Get("spacing", DocX.w.NamespaceName));
  3025. }
  3026. string spacingTypeAttribute = "";
  3027. string autoSpacingTypeAttribute = "";
  3028. switch (spacingType)
  3029. {
  3030. case LineSpacingTypeAuto.AutoBefore:
  3031. {
  3032. spacingTypeAttribute = "before";
  3033. autoSpacingTypeAttribute = "beforeAutospacing";
  3034. break;
  3035. }
  3036. case LineSpacingTypeAuto.AutoAfter:
  3037. {
  3038. spacingTypeAttribute = "after";
  3039. autoSpacingTypeAttribute = "afterAutospacing";
  3040. break;
  3041. }
  3042. case LineSpacingTypeAuto.Auto:
  3043. {
  3044. spacingTypeAttribute = "before";
  3045. autoSpacingTypeAttribute = "beforeAutospacing";
  3046. spacing.SetAttributeValue(XName.Get("after", DocX.w.NamespaceName), spacingValue);
  3047. spacing.SetAttributeValue(XName.Get("afterAutospacing", DocX.w.NamespaceName), 1);
  3048. break;
  3049. }
  3050. }
  3051. spacing.SetAttributeValue(XName.Get(autoSpacingTypeAttribute, DocX.w.NamespaceName), 1);
  3052. spacing.SetAttributeValue(XName.Get(spacingTypeAttribute, DocX.w.NamespaceName), spacingValue);
  3053. }
  3054. }
  3055. public Paragraph Spacing(double spacing)
  3056. {
  3057. spacing *= 20;
  3058. if (spacing - (int)spacing == 0)
  3059. {
  3060. if (!(spacing > -1585 && spacing < 1585))
  3061. throw new ArgumentException("Spacing", "Value must be in the range: -1584 - 1584");
  3062. }
  3063. else
  3064. throw new ArgumentException("Spacing", "Value must be either a whole or acurate to one decimal, examples: 32, 32.1, 32.2, 32.9");
  3065. ApplyTextFormattingProperty(XName.Get("spacing", DocX.w.NamespaceName), string.Empty, new XAttribute(XName.Get("val", DocX.w.NamespaceName), spacing));
  3066. return this;
  3067. }
  3068. public Paragraph SpacingBefore(double spacingBefore)
  3069. {
  3070. spacingBefore *= 20;
  3071. var pPr = GetOrCreate_pPr();
  3072. var spacing = pPr.Element(XName.Get("spacing", DocX.w.NamespaceName));
  3073. if (spacingBefore > 0)
  3074. {
  3075. if (spacing == null)
  3076. {
  3077. spacing = new XElement(XName.Get("spacing", DocX.w.NamespaceName));
  3078. pPr.Add(spacing);
  3079. }
  3080. var attr = spacing.Attribute(XName.Get("before", DocX.w.NamespaceName));
  3081. if (attr == null)
  3082. spacing.SetAttributeValue(XName.Get("before", DocX.w.NamespaceName), spacingBefore);
  3083. else
  3084. attr.SetValue(spacingBefore);
  3085. }
  3086. if (Math.Abs(spacingBefore) < 0.1f && spacing != null)
  3087. {
  3088. var attr = spacing.Attribute(XName.Get("before", DocX.w.NamespaceName));
  3089. attr.Remove();
  3090. if (!spacing.HasAttributes)
  3091. spacing.Remove();
  3092. }
  3093. return this;
  3094. }
  3095. public Paragraph SpacingAfter(double spacingAfter)
  3096. {
  3097. spacingAfter *= 20;
  3098. var pPr = GetOrCreate_pPr();
  3099. var spacing = pPr.Element(XName.Get("spacing", DocX.w.NamespaceName));
  3100. if (spacingAfter > 0)
  3101. {
  3102. if (spacing == null)
  3103. {
  3104. spacing = new XElement(XName.Get("spacing", DocX.w.NamespaceName));
  3105. pPr.Add(spacing);
  3106. }
  3107. var attr = spacing.Attribute(XName.Get("after", DocX.w.NamespaceName));
  3108. if (attr == null)
  3109. spacing.SetAttributeValue(XName.Get("after", DocX.w.NamespaceName), spacingAfter);
  3110. else
  3111. attr.SetValue(spacingAfter);
  3112. }
  3113. if (Math.Abs(spacingAfter) < 0.1f && spacing != null)
  3114. {
  3115. var attr = spacing.Attribute(XName.Get("after", DocX.w.NamespaceName));
  3116. attr.Remove();
  3117. if (!spacing.HasAttributes)
  3118. spacing.Remove();
  3119. }
  3120. //ApplyTextFormattingProperty(XName.Get("after", DocX.w.NamespaceName), string.Empty, new XAttribute(XName.Get("val", DocX.w.NamespaceName), spacingAfter));
  3121. return this;
  3122. }
  3123. public Paragraph Kerning(int kerning)
  3124. {
  3125. if (!new int?[] { 8, 9, 10, 11, 12, 14, 16, 18, 20, 22, 24, 26, 28, 36, 48, 72 }.Contains(kerning))
  3126. throw new ArgumentOutOfRangeException("Kerning", "Value must be one of the following: 8, 9, 10, 11, 12, 14, 16, 18, 20, 22, 24, 26, 28, 36, 48 or 72");
  3127. ApplyTextFormattingProperty(XName.Get("kern", DocX.w.NamespaceName), string.Empty, new XAttribute(XName.Get("val", DocX.w.NamespaceName), kerning * 2));
  3128. return this;
  3129. }
  3130. public Paragraph Position(double position)
  3131. {
  3132. if (!(position > -1585 && position < 1585))
  3133. throw new ArgumentOutOfRangeException("Position", "Value must be in the range -1585 - 1585");
  3134. ApplyTextFormattingProperty(XName.Get("position", DocX.w.NamespaceName), string.Empty, new XAttribute(XName.Get("val", DocX.w.NamespaceName), position * 2));
  3135. return this;
  3136. }
  3137. public Paragraph PercentageScale(int percentageScale)
  3138. {
  3139. if (!(new int?[] { 200, 150, 100, 90, 80, 66, 50, 33 }).Contains(percentageScale))
  3140. throw new ArgumentOutOfRangeException("PercentageScale", "Value must be one of the following: 200, 150, 100, 90, 80, 66, 50 or 33");
  3141. ApplyTextFormattingProperty(XName.Get("w", DocX.w.NamespaceName), string.Empty, new XAttribute(XName.Get("val", DocX.w.NamespaceName), percentageScale));
  3142. return this;
  3143. }
  3144. /// <summary>
  3145. /// Append a field of type document property, this field will display the custom property cp, at the end of this paragraph.
  3146. /// </summary>
  3147. /// <param name="cp">The custom property to display.</param>
  3148. /// <param name="f">The formatting to use for this text.</param>
  3149. /// <example>
  3150. /// Create, add and display a custom property in a document.
  3151. /// <code>
  3152. ///// Load a document.
  3153. ///using (DocX document = DocX.Create("CustomProperty_Add.docx"))
  3154. ///{
  3155. /// // Add a few Custom Properties to this document.
  3156. /// document.AddCustomProperty(new CustomProperty("fname", "cathal"));
  3157. /// document.AddCustomProperty(new CustomProperty("age", 24));
  3158. /// document.AddCustomProperty(new CustomProperty("male", true));
  3159. /// document.AddCustomProperty(new CustomProperty("newyear2012", new DateTime(2012, 1, 1)));
  3160. /// document.AddCustomProperty(new CustomProperty("fav_num", 3.141592));
  3161. ///
  3162. /// // Insert a new Paragraph and append a load of DocProperties.
  3163. /// Paragraph p = document.InsertParagraph("fname: ")
  3164. /// .AppendDocProperty(document.CustomProperties["fname"])
  3165. /// .Append(", age: ")
  3166. /// .AppendDocProperty(document.CustomProperties["age"])
  3167. /// .Append(", male: ")
  3168. /// .AppendDocProperty(document.CustomProperties["male"])
  3169. /// .Append(", newyear2012: ")
  3170. /// .AppendDocProperty(document.CustomProperties["newyear2012"])
  3171. /// .Append(", fav_num: ")
  3172. /// .AppendDocProperty(document.CustomProperties["fav_num"]);
  3173. ///
  3174. /// // Save the changes to the document.
  3175. /// document.Save();
  3176. ///}
  3177. /// </code>
  3178. /// </example>
  3179. public Paragraph AppendDocProperty(CustomProperty cp, bool trackChanges = false, Formatting f = null)
  3180. {
  3181. this.InsertDocProperty(cp, trackChanges, f);
  3182. return this;
  3183. }
  3184. /// <summary>
  3185. /// Insert a field of type document property, this field will display the custom property cp, at the end of this paragraph.
  3186. /// </summary>
  3187. /// <param name="cp">The custom property to display.</param>
  3188. /// <param name="f">The formatting to use for this text.</param>
  3189. /// <example>
  3190. /// Create, add and display a custom property in a document.
  3191. /// <code>
  3192. /// // Load a document
  3193. /// using (DocX document = DocX.Create(@"Test.docx"))
  3194. /// {
  3195. /// // Create a custom property.
  3196. /// CustomProperty name = new CustomProperty("name", "Cathal Coffey");
  3197. ///
  3198. /// // Add this custom property to this document.
  3199. /// document.AddCustomProperty(name);
  3200. ///
  3201. /// // Create a text formatting.
  3202. /// Formatting f = new Formatting();
  3203. /// f.Bold = true;
  3204. /// f.Size = 14;
  3205. /// f.StrikeThrough = StrickThrough.strike;
  3206. ///
  3207. /// // Insert a new paragraph.
  3208. /// Paragraph p = document.InsertParagraph("Author: ", false, f);
  3209. ///
  3210. /// // Insert a field of type document property to display the custom property name and track this change.
  3211. /// p.InsertDocProperty(name, true, f);
  3212. ///
  3213. /// // Save all changes made to this document.
  3214. /// document.Save();
  3215. /// }// Release this document from memory.
  3216. /// </code>
  3217. /// </example>
  3218. public DocProperty InsertDocProperty(CustomProperty cp, bool trackChanges = false, Formatting f = null)
  3219. {
  3220. XElement f_xml = null;
  3221. if (f != null)
  3222. f_xml = f.Xml;
  3223. XElement e = new XElement
  3224. (
  3225. XName.Get("fldSimple", DocX.w.NamespaceName),
  3226. new XAttribute(XName.Get("instr", DocX.w.NamespaceName), string.Format(@"DOCPROPERTY {0} \* MERGEFORMAT", cp.Name)),
  3227. new XElement(XName.Get("r", DocX.w.NamespaceName),
  3228. new XElement(XName.Get("t", DocX.w.NamespaceName), f_xml, cp.Value))
  3229. );
  3230. XElement xml = e;
  3231. if (trackChanges)
  3232. {
  3233. DateTime now = DateTime.Now;
  3234. DateTime insert_datetime = new DateTime(now.Year, now.Month, now.Day, now.Hour, now.Minute, 0, DateTimeKind.Utc);
  3235. e = CreateEdit(EditType.ins, insert_datetime, e);
  3236. }
  3237. Xml.Add(e);
  3238. return new DocProperty(Document, xml);
  3239. }
  3240. /// <summary>
  3241. /// Removes characters from a Novacode.DocX.Paragraph.
  3242. /// </summary>
  3243. /// <example>
  3244. /// <code>
  3245. /// // Create a document using a relative filename.
  3246. /// using (DocX document = DocX.Load(@"C:\Example\Test.docx"))
  3247. /// {
  3248. /// // Iterate through the paragraphs
  3249. /// foreach (Paragraph p in document.Paragraphs)
  3250. /// {
  3251. /// // Remove the first two characters from every paragraph
  3252. /// p.RemoveText(0, 2, false);
  3253. /// }
  3254. ///
  3255. /// // Save all changes made to this document.
  3256. /// document.Save();
  3257. /// }// Release this document from memory.
  3258. /// </code>
  3259. /// </example>
  3260. /// <seealso cref="Paragraph.ReplaceText(string, string, bool)"/>
  3261. /// <seealso cref="Paragraph.ReplaceText(string, string, bool, RegexOptions)"/>
  3262. /// <seealso cref="Paragraph.InsertText(string, bool)"/>
  3263. /// <seealso cref="Paragraph.InsertText(int, string, bool)"/>
  3264. /// <seealso cref="Paragraph.InsertText(int, string, bool, Formatting)"/>
  3265. /// <seealso cref="Paragraph.InsertText(string, bool, Formatting)"/>
  3266. /// <param name="index">The position to begin deleting characters.</param>
  3267. /// <param name="count">The number of characters to delete</param>
  3268. /// <param name="trackChanges">Track changes</param>
  3269. public void RemoveText(int index, int count, bool trackChanges = false)
  3270. {
  3271. // Timestamp to mark the start of insert
  3272. DateTime now = DateTime.Now;
  3273. DateTime remove_datetime = new DateTime(now.Year, now.Month, now.Day, now.Hour, now.Minute, 0, DateTimeKind.Utc);
  3274. // The number of characters processed so far
  3275. int processed = 0;
  3276. do
  3277. {
  3278. // Get the first run effected by this Remove
  3279. Run run = GetFirstRunEffectedByEdit(index, EditType.del);
  3280. // The parent of this Run
  3281. XElement parentElement = run.Xml.Parent;
  3282. switch (parentElement.Name.LocalName)
  3283. {
  3284. case "ins":
  3285. {
  3286. XElement[] splitEditBefore = SplitEdit(parentElement, index, EditType.del);
  3287. int min = Math.Min(count - processed, run.Xml.ElementsAfterSelf().Sum(e => GetElementTextLength(e)));
  3288. XElement[] splitEditAfter = SplitEdit(parentElement, index + min, EditType.del);
  3289. XElement temp = SplitEdit(splitEditBefore[1], index + min, EditType.del)[0];
  3290. object middle = CreateEdit(EditType.del, remove_datetime, temp.Elements());
  3291. processed += GetElementTextLength(middle as XElement);
  3292. if (!trackChanges)
  3293. middle = null;
  3294. parentElement.ReplaceWith
  3295. (
  3296. splitEditBefore[0],
  3297. middle,
  3298. splitEditAfter[1]
  3299. );
  3300. processed += GetElementTextLength(middle as XElement);
  3301. break;
  3302. }
  3303. case "del":
  3304. {
  3305. if (trackChanges)
  3306. {
  3307. // You cannot delete from a deletion, advance processed to the end of this del
  3308. processed += GetElementTextLength(parentElement);
  3309. }
  3310. else
  3311. goto case "ins";
  3312. break;
  3313. }
  3314. default:
  3315. {
  3316. XElement[] splitRunBefore = Run.SplitRun(run, index, EditType.del);
  3317. //int min = Math.Min(index + processed + (count - processed), run.EndIndex);
  3318. int min = Math.Min(index + (count - processed), run.EndIndex);
  3319. XElement[] splitRunAfter = Run.SplitRun(run, min, EditType.del);
  3320. object middle = CreateEdit(EditType.del, remove_datetime, new List<XElement>() { Run.SplitRun(new Run(Document, splitRunBefore[1], run.StartIndex + GetElementTextLength(splitRunBefore[0])), min, EditType.del)[0] });
  3321. processed += GetElementTextLength(middle as XElement);
  3322. if (!trackChanges)
  3323. middle = null;
  3324. run.Xml.ReplaceWith
  3325. (
  3326. splitRunBefore[0],
  3327. middle,
  3328. splitRunAfter[1]
  3329. );
  3330. break;
  3331. }
  3332. }
  3333. // If after this remove the parent element is empty, remove it.
  3334. if (GetElementTextLength(parentElement) == 0)
  3335. {
  3336. if (parentElement.Parent != null && parentElement.Parent.Name.LocalName != "tc")
  3337. {
  3338. // Need to make sure there is no drawing element within the parent element.
  3339. // Picture elements contain no text length but they are still content.
  3340. if (parentElement.Descendants(XName.Get("drawing", DocX.w.NamespaceName)).Count() == 0)
  3341. parentElement.Remove();
  3342. }
  3343. }
  3344. }
  3345. while (processed < count);
  3346. HelperFunctions.RenumberIDs(Document);
  3347. }
  3348. /// <summary>
  3349. /// Removes characters from a Novacode.DocX.Paragraph.
  3350. /// </summary>
  3351. /// <example>
  3352. /// <code>
  3353. /// // Create a document using a relative filename.
  3354. /// using (DocX document = DocX.Load(@"C:\Example\Test.docx"))
  3355. /// {
  3356. /// // Iterate through the paragraphs
  3357. /// foreach (Paragraph p in document.Paragraphs)
  3358. /// {
  3359. /// // Remove all but the first 2 characters from this Paragraph.
  3360. /// p.RemoveText(2, false);
  3361. /// }
  3362. ///
  3363. /// // Save all changes made to this document.
  3364. /// document.Save();
  3365. /// }// Release this document from memory.
  3366. /// </code>
  3367. /// </example>
  3368. /// <seealso cref="Paragraph.ReplaceText(string, string, bool)"/>
  3369. /// <seealso cref="Paragraph.ReplaceText(string, string, bool, RegexOptions)"/>
  3370. /// <seealso cref="Paragraph.InsertText(int, string, bool, Formatting)"/>
  3371. /// <seealso cref="Paragraph.InsertText(string, bool, Formatting)"/>
  3372. /// <param name="index">The position to begin deleting characters.</param>
  3373. /// <param name="trackChanges">Track changes</param>
  3374. public void RemoveText(int index, bool trackChanges = false)
  3375. {
  3376. RemoveText(index, Text.Length - index, trackChanges);
  3377. }
  3378. /// <summary>
  3379. /// Replaces all occurrences of a specified System.String in this instance, with another specified System.String.
  3380. /// </summary>
  3381. /// <example>
  3382. /// <code>
  3383. /// // Load a document using a relative filename.
  3384. /// using (DocX document = DocX.Load(@"C:\Example\Test.docx"))
  3385. /// {
  3386. /// // The formatting to match.
  3387. /// Formatting matchFormatting = new Formatting();
  3388. /// matchFormatting.Size = 10;
  3389. /// matchFormatting.Italic = true;
  3390. /// matchFormatting.FontFamily = new FontFamily("Times New Roman");
  3391. ///
  3392. /// // The formatting to apply to the inserted text.
  3393. /// Formatting newFormatting = new Formatting();
  3394. /// newFormatting.Size = 22;
  3395. /// newFormatting.UnderlineStyle = UnderlineStyle.dotted;
  3396. /// newFormatting.Bold = true;
  3397. ///
  3398. /// // Iterate through the paragraphs in this document.
  3399. /// foreach (Paragraph p in document.Paragraphs)
  3400. /// {
  3401. /// /*
  3402. /// * Replace all instances of the string "wrong" with the string "right" and ignore case.
  3403. /// * Each inserted instance of "wrong" should use the Formatting newFormatting.
  3404. /// * Only replace an instance of "wrong" if it is Size 10, Italic and Times New Roman.
  3405. /// * SubsetMatch means that the formatting must contain all elements of the match formatting,
  3406. /// * but it can also contain additional formatting for example Color, UnderlineStyle, etc.
  3407. /// * ExactMatch means it must not contain additional formatting.
  3408. /// */
  3409. /// p.ReplaceText("wrong", "right", false, RegexOptions.IgnoreCase, newFormatting, matchFormatting, MatchFormattingOptions.SubsetMatch);
  3410. /// }
  3411. ///
  3412. /// // Save all changes made to this document.
  3413. /// document.Save();
  3414. /// }// Release this document from memory.
  3415. /// </code>
  3416. /// </example>
  3417. /// <seealso cref="Paragraph.RemoveText(int, int, bool)"/>
  3418. /// <seealso cref="Paragraph.RemoveText(int, bool)"/>
  3419. /// <seealso cref="Paragraph.InsertText(string, bool)"/>
  3420. /// <seealso cref="Paragraph.InsertText(int, string, bool)"/>
  3421. /// <seealso cref="Paragraph.InsertText(int, string, bool, Formatting)"/>
  3422. /// <seealso cref="Paragraph.InsertText(string, bool, Formatting)"/>
  3423. /// <param name="newValue">A System.String to replace all occurances of oldValue.</param>
  3424. /// <param name="oldValue">A System.String to be replaced.</param>
  3425. /// <param name="options">A bitwise OR combination of RegexOption enumeration options.</param>
  3426. /// <param name="trackChanges">Track changes</param>
  3427. /// <param name="newFormatting">The formatting to apply to the text being inserted.</param>
  3428. /// <param name="matchFormatting">The formatting that the text must match in order to be replaced.</param>
  3429. /// <param name="fo">How should formatting be matched?</param>
  3430. public void ReplaceText(string oldValue, string newValue, bool trackChanges = false, RegexOptions options = RegexOptions.None, Formatting newFormatting = null, Formatting matchFormatting = null, MatchFormattingOptions fo = MatchFormattingOptions.SubsetMatch)
  3431. {
  3432. MatchCollection mc = Regex.Matches(this.Text, Regex.Escape(oldValue), options);
  3433. // Loop through the matches in reverse order
  3434. foreach (Match m in mc.Cast<Match>().Reverse())
  3435. {
  3436. // Assume the formatting matches until proven otherwise.
  3437. bool formattingMatch = true;
  3438. // Does the user want to match formatting?
  3439. if (matchFormatting != null)
  3440. {
  3441. // The number of characters processed so far
  3442. int processed = 0;
  3443. do
  3444. {
  3445. // Get the next run effected
  3446. Run run = GetFirstRunEffectedByEdit(m.Index + processed);
  3447. // Get this runs properties
  3448. XElement rPr = run.Xml.Element(XName.Get("rPr", DocX.w.NamespaceName));
  3449. if (rPr == null)
  3450. rPr = new Formatting().Xml;
  3451. /*
  3452. * Make sure that every formatting element in f.xml is also in this run,
  3453. * if this is not true, then their formatting does not match.
  3454. */
  3455. if (!HelperFunctions.ContainsEveryChildOf(matchFormatting.Xml, rPr, fo))
  3456. {
  3457. formattingMatch = false;
  3458. break;
  3459. }
  3460. // We have processed some characters, so update the counter.
  3461. processed += run.Value.Length;
  3462. } while (processed < m.Length);
  3463. }
  3464. // If the formatting matches, do the replace.
  3465. if (formattingMatch)
  3466. {
  3467. InsertText(m.Index + oldValue.Length, newValue, trackChanges, newFormatting);
  3468. RemoveText(m.Index, m.Length, trackChanges);
  3469. }
  3470. }
  3471. }
  3472. /// <summary>
  3473. /// Find all instances of a string in this paragraph and return their indexes in a List.
  3474. /// </summary>
  3475. /// <param name="str">The string to find</param>
  3476. /// <returns>A list of indexes.</returns>
  3477. /// <example>
  3478. /// Find all instances of Hello in this document and insert 'don't' in frount of them.
  3479. /// <code>
  3480. /// // Load a document
  3481. /// using (DocX document = DocX.Load(@"Test.docx"))
  3482. /// {
  3483. /// // Loop through the paragraphs in this document.
  3484. /// foreach(Paragraph p in document.Paragraphs)
  3485. /// {
  3486. /// // Find all instances of 'go' in this paragraph.
  3487. /// List&lt;int&gt; gos = document.FindAll("go");
  3488. ///
  3489. /// /*
  3490. /// * Insert 'don't' in frount of every instance of 'go' in this document to produce 'don't go'.
  3491. /// * An important trick here is to do the inserting in reverse document order. If you inserted
  3492. /// * in document order, every insert would shift the index of the remaining matches.
  3493. /// */
  3494. /// gos.Reverse();
  3495. /// foreach (int index in gos)
  3496. /// {
  3497. /// p.InsertText(index, "don't ", false);
  3498. /// }
  3499. /// }
  3500. ///
  3501. /// // Save all changes made to this document.
  3502. /// document.Save();
  3503. /// }// Release this document from memory.
  3504. /// </code>
  3505. /// </example>
  3506. public List<int> FindAll(string str)
  3507. {
  3508. return FindAll(str, RegexOptions.None);
  3509. }
  3510. /// <summary>
  3511. /// Find all instances of a string in this paragraph and return their indexes in a List.
  3512. /// </summary>
  3513. /// <param name="str">The string to find</param>
  3514. /// <param name="options">The options to use when finding a string match.</param>
  3515. /// <returns>A list of indexes.</returns>
  3516. /// <example>
  3517. /// Find all instances of Hello in this document and insert 'don't' in frount of them.
  3518. /// <code>
  3519. /// // Load a document
  3520. /// using (DocX document = DocX.Load(@"Test.docx"))
  3521. /// {
  3522. /// // Loop through the paragraphs in this document.
  3523. /// foreach(Paragraph p in document.Paragraphs)
  3524. /// {
  3525. /// // Find all instances of 'go' in this paragraph (Ignore case).
  3526. /// List&lt;int&gt; gos = document.FindAll("go", RegexOptions.IgnoreCase);
  3527. ///
  3528. /// /*
  3529. /// * Insert 'don't' in frount of every instance of 'go' in this document to produce 'don't go'.
  3530. /// * An important trick here is to do the inserting in reverse document order. If you inserted
  3531. /// * in document order, every insert would shift the index of the remaining matches.
  3532. /// */
  3533. /// gos.Reverse();
  3534. /// foreach (int index in gos)
  3535. /// {
  3536. /// p.InsertText(index, "don't ", false);
  3537. /// }
  3538. /// }
  3539. ///
  3540. /// // Save all changes made to this document.
  3541. /// document.Save();
  3542. /// }// Release this document from memory.
  3543. /// </code>
  3544. /// </example>
  3545. public List<int> FindAll(string str, RegexOptions options)
  3546. {
  3547. MatchCollection mc = Regex.Matches(this.Text, Regex.Escape(str), options);
  3548. var query =
  3549. (
  3550. from m in mc.Cast<Match>()
  3551. select m.Index
  3552. ).ToList();
  3553. return query;
  3554. }
  3555. /// <summary>
  3556. /// Find all unique instances of the given Regex Pattern
  3557. /// </summary>
  3558. /// <param name="str"></param>
  3559. /// <param name="options"></param>
  3560. /// <returns></returns>
  3561. public List<string> FindAllByPattern(string str, RegexOptions options)
  3562. {
  3563. MatchCollection mc = Regex.Matches(this.Text, str, options);
  3564. var query =
  3565. (
  3566. from m in mc.Cast<Match>()
  3567. select m.Value
  3568. ).ToList();
  3569. return query;
  3570. }
  3571. /// <summary>
  3572. /// Insert a PageNumber place holder into a Paragraph.
  3573. /// This place holder should only be inserted into a Header or Footer Paragraph.
  3574. /// Word will not automatically update this field if it is inserted into a document level Paragraph.
  3575. /// </summary>
  3576. /// <param name="pnf">The PageNumberFormat can be normal: (1, 2, ...) or Roman: (I, II, ...)</param>
  3577. /// <param name="index">The text index to insert this PageNumber place holder at.</param>
  3578. /// <example>
  3579. /// <code>
  3580. /// // Create a new document.
  3581. /// using (DocX document = DocX.Create(@"Test.docx"))
  3582. /// {
  3583. /// // Add Headers to the document.
  3584. /// document.AddHeaders();
  3585. ///
  3586. /// // Get the default Header.
  3587. /// Header header = document.Headers.odd;
  3588. ///
  3589. /// // Insert a Paragraph into the Header.
  3590. /// Paragraph p0 = header.InsertParagraph("Page ( of )");
  3591. ///
  3592. /// // Insert place holders for PageNumber and PageCount into the Header.
  3593. /// // Word will replace these with the correct value for each Page.
  3594. /// p0.InsertPageNumber(PageNumberFormat.normal, 6);
  3595. /// p0.InsertPageCount(PageNumberFormat.normal, 11);
  3596. ///
  3597. /// // Save the document.
  3598. /// document.Save();
  3599. /// }
  3600. /// </code>
  3601. /// </example>
  3602. /// <seealso cref="AppendPageCount"/>
  3603. /// <seealso cref="AppendPageNumber"/>
  3604. /// <seealso cref="InsertPageCount"/>
  3605. public void InsertPageNumber(PageNumberFormat pnf, int index = 0)
  3606. {
  3607. XElement fldSimple = new XElement(XName.Get("fldSimple", DocX.w.NamespaceName));
  3608. if (pnf == PageNumberFormat.normal)
  3609. fldSimple.Add(new XAttribute(XName.Get("instr", DocX.w.NamespaceName), @" PAGE \* MERGEFORMAT "));
  3610. else
  3611. fldSimple.Add(new XAttribute(XName.Get("instr", DocX.w.NamespaceName), @" PAGE \* ROMAN \* MERGEFORMAT "));
  3612. XElement content = XElement.Parse
  3613. (
  3614. @"<w:r w:rsidR='001D0226' xmlns:w=""http://schemas.openxmlformats.org/wordprocessingml/2006/main"">
  3615. <w:rPr>
  3616. <w:noProof />
  3617. </w:rPr>
  3618. <w:t>1</w:t>
  3619. </w:r>"
  3620. );
  3621. fldSimple.Add(content);
  3622. if (index == 0)
  3623. Xml.AddFirst(fldSimple);
  3624. else
  3625. {
  3626. Run r = GetFirstRunEffectedByEdit(index, EditType.ins);
  3627. XElement[] splitEdit = SplitEdit(r.Xml, index, EditType.ins);
  3628. r.Xml.ReplaceWith
  3629. (
  3630. splitEdit[0],
  3631. fldSimple,
  3632. splitEdit[1]
  3633. );
  3634. }
  3635. }
  3636. /// <summary>
  3637. /// Append a PageNumber place holder onto the end of a Paragraph.
  3638. /// </summary>
  3639. /// <param name="pnf">The PageNumberFormat can be normal: (1, 2, ...) or Roman: (I, II, ...)</param>
  3640. /// <example>
  3641. /// <code>
  3642. /// // Create a new document.
  3643. /// using (DocX document = DocX.Create(@"Test.docx"))
  3644. /// {
  3645. /// // Add Headers to the document.
  3646. /// document.AddHeaders();
  3647. ///
  3648. /// // Get the default Header.
  3649. /// Header header = document.Headers.odd;
  3650. ///
  3651. /// // Insert a Paragraph into the Header.
  3652. /// Paragraph p0 = header.InsertParagraph();
  3653. ///
  3654. /// // Appemd place holders for PageNumber and PageCount into the Header.
  3655. /// // Word will replace these with the correct value for each Page.
  3656. /// p0.Append("Page (");
  3657. /// p0.AppendPageNumber(PageNumberFormat.normal);
  3658. /// p0.Append(" of ");
  3659. /// p0.AppendPageCount(PageNumberFormat.normal);
  3660. /// p0.Append(")");
  3661. ///
  3662. /// // Save the document.
  3663. /// document.Save();
  3664. /// }
  3665. /// </code>
  3666. /// </example>
  3667. /// <seealso cref="AppendPageCount"/>
  3668. /// <seealso cref="InsertPageNumber"/>
  3669. /// <seealso cref="InsertPageCount"/>
  3670. public void AppendPageNumber(PageNumberFormat pnf)
  3671. {
  3672. XElement fldSimple = new XElement(XName.Get("fldSimple", DocX.w.NamespaceName));
  3673. if (pnf == PageNumberFormat.normal)
  3674. fldSimple.Add(new XAttribute(XName.Get("instr", DocX.w.NamespaceName), @" PAGE \* MERGEFORMAT "));
  3675. else
  3676. fldSimple.Add(new XAttribute(XName.Get("instr", DocX.w.NamespaceName), @" PAGE \* ROMAN \* MERGEFORMAT "));
  3677. XElement content = XElement.Parse
  3678. (
  3679. @"<w:r w:rsidR='001D0226' xmlns:w=""http://schemas.openxmlformats.org/wordprocessingml/2006/main"">
  3680. <w:rPr>
  3681. <w:noProof />
  3682. </w:rPr>
  3683. <w:t>1</w:t>
  3684. </w:r>"
  3685. );
  3686. fldSimple.Add(content);
  3687. Xml.Add(fldSimple);
  3688. }
  3689. /// <summary>
  3690. /// Insert a PageCount place holder into a Paragraph.
  3691. /// This place holder should only be inserted into a Header or Footer Paragraph.
  3692. /// Word will not automatically update this field if it is inserted into a document level Paragraph.
  3693. /// </summary>
  3694. /// <param name="pnf">The PageNumberFormat can be normal: (1, 2, ...) or Roman: (I, II, ...)</param>
  3695. /// <param name="index">The text index to insert this PageCount place holder at.</param>
  3696. /// <example>
  3697. /// <code>
  3698. /// // Create a new document.
  3699. /// using (DocX document = DocX.Create(@"Test.docx"))
  3700. /// {
  3701. /// // Add Headers to the document.
  3702. /// document.AddHeaders();
  3703. ///
  3704. /// // Get the default Header.
  3705. /// Header header = document.Headers.odd;
  3706. ///
  3707. /// // Insert a Paragraph into the Header.
  3708. /// Paragraph p0 = header.InsertParagraph("Page ( of )");
  3709. ///
  3710. /// // Insert place holders for PageNumber and PageCount into the Header.
  3711. /// // Word will replace these with the correct value for each Page.
  3712. /// p0.InsertPageNumber(PageNumberFormat.normal, 6);
  3713. /// p0.InsertPageCount(PageNumberFormat.normal, 11);
  3714. ///
  3715. /// // Save the document.
  3716. /// document.Save();
  3717. /// }
  3718. /// </code>
  3719. /// </example>
  3720. /// <seealso cref="AppendPageCount"/>
  3721. /// <seealso cref="AppendPageNumber"/>
  3722. /// <seealso cref="InsertPageNumber"/>
  3723. public void InsertPageCount(PageNumberFormat pnf, int index = 0)
  3724. {
  3725. XElement fldSimple = new XElement(XName.Get("fldSimple", DocX.w.NamespaceName));
  3726. if (pnf == PageNumberFormat.normal)
  3727. fldSimple.Add(new XAttribute(XName.Get("instr", DocX.w.NamespaceName), @" NUMPAGES \* MERGEFORMAT "));
  3728. else
  3729. fldSimple.Add(new XAttribute(XName.Get("instr", DocX.w.NamespaceName), @" NUMPAGES \* ROMAN \* MERGEFORMAT "));
  3730. XElement content = XElement.Parse
  3731. (
  3732. @"<w:r w:rsidR='001D0226' xmlns:w=""http://schemas.openxmlformats.org/wordprocessingml/2006/main"">
  3733. <w:rPr>
  3734. <w:noProof />
  3735. </w:rPr>
  3736. <w:t>1</w:t>
  3737. </w:r>"
  3738. );
  3739. fldSimple.Add(content);
  3740. if (index == 0)
  3741. Xml.AddFirst(fldSimple);
  3742. else
  3743. {
  3744. Run r = GetFirstRunEffectedByEdit(index, EditType.ins);
  3745. XElement[] splitEdit = SplitEdit(r.Xml, index, EditType.ins);
  3746. r.Xml.ReplaceWith
  3747. (
  3748. splitEdit[0],
  3749. fldSimple,
  3750. splitEdit[1]
  3751. );
  3752. }
  3753. }
  3754. /// <summary>
  3755. /// Append a PageCount place holder onto the end of a Paragraph.
  3756. /// </summary>
  3757. /// <param name="pnf">The PageNumberFormat can be normal: (1, 2, ...) or Roman: (I, II, ...)</param>
  3758. /// <example>
  3759. /// <code>
  3760. /// // Create a new document.
  3761. /// using (DocX document = DocX.Create(@"Test.docx"))
  3762. /// {
  3763. /// // Add Headers to the document.
  3764. /// document.AddHeaders();
  3765. ///
  3766. /// // Get the default Header.
  3767. /// Header header = document.Headers.odd;
  3768. ///
  3769. /// // Insert a Paragraph into the Header.
  3770. /// Paragraph p0 = header.InsertParagraph();
  3771. ///
  3772. /// // Appemd place holders for PageNumber and PageCount into the Header.
  3773. /// // Word will replace these with the correct value for each Page.
  3774. /// p0.Append("Page (");
  3775. /// p0.AppendPageNumber(PageNumberFormat.normal);
  3776. /// p0.Append(" of ");
  3777. /// p0.AppendPageCount(PageNumberFormat.normal);
  3778. /// p0.Append(")");
  3779. ///
  3780. /// // Save the document.
  3781. /// document.Save();
  3782. /// }
  3783. /// </code>
  3784. /// </example>
  3785. /// <seealso cref="AppendPageNumber"/>
  3786. /// <seealso cref="InsertPageNumber"/>
  3787. /// <seealso cref="InsertPageCount"/>
  3788. public void AppendPageCount(PageNumberFormat pnf)
  3789. {
  3790. XElement fldSimple = new XElement(XName.Get("fldSimple", DocX.w.NamespaceName));
  3791. if (pnf == PageNumberFormat.normal)
  3792. fldSimple.Add(new XAttribute(XName.Get("instr", DocX.w.NamespaceName), @" NUMPAGES \* MERGEFORMAT "));
  3793. else
  3794. fldSimple.Add(new XAttribute(XName.Get("instr", DocX.w.NamespaceName), @" NUMPAGES \* ROMAN \* MERGEFORMAT "));
  3795. XElement content = XElement.Parse
  3796. (
  3797. @"<w:r w:rsidR='001D0226' xmlns:w=""http://schemas.openxmlformats.org/wordprocessingml/2006/main"">
  3798. <w:rPr>
  3799. <w:noProof />
  3800. </w:rPr>
  3801. <w:t>1</w:t>
  3802. </w:r>"
  3803. );
  3804. fldSimple.Add(content);
  3805. Xml.Add(fldSimple);
  3806. }
  3807. public float LineSpacingBefore
  3808. {
  3809. get
  3810. {
  3811. XElement pPr = GetOrCreate_pPr();
  3812. XElement spacing = pPr.Element(XName.Get("spacing", DocX.w.NamespaceName));
  3813. if (spacing != null)
  3814. {
  3815. XAttribute line = spacing.Attribute(XName.Get("before", DocX.w.NamespaceName));
  3816. if (line != null)
  3817. {
  3818. float f;
  3819. if (float.TryParse(line.Value, out f))
  3820. return f / 20.0f;
  3821. }
  3822. }
  3823. return 0.0f;
  3824. }
  3825. set
  3826. {
  3827. SpacingBefore(value);
  3828. }
  3829. }
  3830. public float LineSpacingAfter
  3831. {
  3832. get
  3833. {
  3834. XElement pPr = GetOrCreate_pPr();
  3835. XElement spacing = pPr.Element(XName.Get("spacing", DocX.w.NamespaceName));
  3836. if (spacing != null)
  3837. {
  3838. XAttribute line = spacing.Attribute(XName.Get("after", DocX.w.NamespaceName));
  3839. if (line != null)
  3840. {
  3841. float f;
  3842. if (float.TryParse(line.Value, out f))
  3843. return f / 20.0f;
  3844. }
  3845. }
  3846. return 10.0f;
  3847. }
  3848. set
  3849. {
  3850. SpacingAfter(value);
  3851. }
  3852. }
  3853. }
  3854. public class Run : DocXElement
  3855. {
  3856. // A lookup for the text elements in this paragraph
  3857. Dictionary<int, Text> textLookup = new Dictionary<int, Text>();
  3858. private int startIndex;
  3859. private int endIndex;
  3860. private string text;
  3861. /// <summary>
  3862. /// Gets the start index of this Text (text length before this text)
  3863. /// </summary>
  3864. public int StartIndex { get { return startIndex; } }
  3865. /// <summary>
  3866. /// Gets the end index of this Text (text length before this text + this texts length)
  3867. /// </summary>
  3868. public int EndIndex { get { return endIndex; } }
  3869. /// <summary>
  3870. /// The text value of this text element
  3871. /// </summary>
  3872. internal string Value { set { text = value; } get { return text; } }
  3873. internal Run(DocX document, XElement xml, int startIndex)
  3874. : base(document, xml)
  3875. {
  3876. this.startIndex = startIndex;
  3877. // Get the text elements in this run
  3878. IEnumerable<XElement> texts = xml.Descendants();
  3879. int start = startIndex;
  3880. // Loop through each text in this run
  3881. foreach (XElement te in texts)
  3882. {
  3883. switch (te.Name.LocalName)
  3884. {
  3885. case "tab":
  3886. {
  3887. textLookup.Add(start + 1, new Text(Document, te, start));
  3888. text += "\t";
  3889. start++;
  3890. break;
  3891. }
  3892. case "br":
  3893. {
  3894. textLookup.Add(start + 1, new Text(Document, te, start));
  3895. text += "\n";
  3896. start++;
  3897. break;
  3898. }
  3899. case "t": goto case "delText";
  3900. case "delText":
  3901. {
  3902. // Only add strings which are not empty
  3903. if (te.Value.Length > 0)
  3904. {
  3905. textLookup.Add(start + te.Value.Length, new Text(Document, te, start));
  3906. text += te.Value;
  3907. start += te.Value.Length;
  3908. }
  3909. break;
  3910. }
  3911. default: break;
  3912. }
  3913. }
  3914. endIndex = start;
  3915. }
  3916. static internal XElement[] SplitRun(Run r, int index, EditType type = EditType.ins)
  3917. {
  3918. index = index - r.StartIndex;
  3919. Text t = r.GetFirstTextEffectedByEdit(index, type);
  3920. XElement[] splitText = Text.SplitText(t, index);
  3921. XElement splitLeft = new XElement(r.Xml.Name, r.Xml.Attributes(), r.Xml.Element(XName.Get("rPr", DocX.w.NamespaceName)), t.Xml.ElementsBeforeSelf().Where(n => n.Name.LocalName != "rPr"), splitText[0]);
  3922. if (Paragraph.GetElementTextLength(splitLeft) == 0)
  3923. splitLeft = null;
  3924. XElement splitRight = new XElement(r.Xml.Name, r.Xml.Attributes(), r.Xml.Element(XName.Get("rPr", DocX.w.NamespaceName)), splitText[1], t.Xml.ElementsAfterSelf().Where(n => n.Name.LocalName != "rPr"));
  3925. if (Paragraph.GetElementTextLength(splitRight) == 0)
  3926. splitRight = null;
  3927. return
  3928. (
  3929. new XElement[]
  3930. {
  3931. splitLeft,
  3932. splitRight
  3933. }
  3934. );
  3935. }
  3936. internal Text GetFirstTextEffectedByEdit(int index, EditType type = EditType.ins)
  3937. {
  3938. // Make sure we are looking within an acceptable index range.
  3939. if (index < 0 || index > HelperFunctions.GetText(Xml).Length)
  3940. throw new ArgumentOutOfRangeException();
  3941. // Need some memory that can be updated by the recursive search for the XElement to Split.
  3942. int count = 0;
  3943. Text theOne = null;
  3944. GetFirstTextEffectedByEditRecursive(Xml, index, ref count, ref theOne, type);
  3945. return theOne;
  3946. }
  3947. internal void GetFirstTextEffectedByEditRecursive(XElement Xml, int index, ref int count, ref Text theOne, EditType type = EditType.ins)
  3948. {
  3949. count += HelperFunctions.GetSize(Xml);
  3950. if (count > 0 && ((type == EditType.del && count > index) || (type == EditType.ins && count >= index)))
  3951. {
  3952. theOne = new Text(Document, Xml, count - HelperFunctions.GetSize(Xml));
  3953. return;
  3954. }
  3955. if (Xml.HasElements)
  3956. foreach (XElement e in Xml.Elements())
  3957. if (theOne == null)
  3958. GetFirstTextEffectedByEditRecursive(e, index, ref count, ref theOne);
  3959. }
  3960. }
  3961. internal class Text : DocXElement
  3962. {
  3963. private int startIndex;
  3964. private int endIndex;
  3965. private string text;
  3966. /// <summary>
  3967. /// Gets the start index of this Text (text length before this text)
  3968. /// </summary>
  3969. public int StartIndex { get { return startIndex; } }
  3970. /// <summary>
  3971. /// Gets the end index of this Text (text length before this text + this texts length)
  3972. /// </summary>
  3973. public int EndIndex { get { return endIndex; } }
  3974. /// <summary>
  3975. /// The text value of this text element
  3976. /// </summary>
  3977. public string Value { get { return text; } }
  3978. internal Text(DocX document, XElement xml, int startIndex)
  3979. : base(document, xml)
  3980. {
  3981. this.startIndex = startIndex;
  3982. switch (Xml.Name.LocalName)
  3983. {
  3984. case "t":
  3985. {
  3986. goto case "delText";
  3987. }
  3988. case "delText":
  3989. {
  3990. endIndex = startIndex + xml.Value.Length;
  3991. text = xml.Value;
  3992. break;
  3993. }
  3994. case "br":
  3995. {
  3996. text = "\n";
  3997. endIndex = startIndex + 1;
  3998. break;
  3999. }
  4000. case "tab":
  4001. {
  4002. text = "\t";
  4003. endIndex = startIndex + 1;
  4004. break;
  4005. }
  4006. default:
  4007. {
  4008. break;
  4009. }
  4010. }
  4011. }
  4012. internal static XElement[] SplitText(Text t, int index)
  4013. {
  4014. if (index < t.startIndex || index > t.EndIndex)
  4015. throw new ArgumentOutOfRangeException("index");
  4016. XElement splitLeft = null, splitRight = null;
  4017. if (t.Xml.Name.LocalName == "t" || t.Xml.Name.LocalName == "delText")
  4018. {
  4019. // The origional text element, now containing only the text before the index point.
  4020. splitLeft = new XElement(t.Xml.Name, t.Xml.Attributes(), t.Xml.Value.Substring(0, index - t.startIndex));
  4021. if (splitLeft.Value.Length == 0)
  4022. splitLeft = null;
  4023. else
  4024. PreserveSpace(splitLeft);
  4025. // The origional text element, now containing only the text after the index point.
  4026. splitRight = new XElement(t.Xml.Name, t.Xml.Attributes(), t.Xml.Value.Substring(index - t.startIndex, t.Xml.Value.Length - (index - t.startIndex)));
  4027. if (splitRight.Value.Length == 0)
  4028. splitRight = null;
  4029. else
  4030. PreserveSpace(splitRight);
  4031. }
  4032. else
  4033. {
  4034. if (index == t.EndIndex)
  4035. splitLeft = t.Xml;
  4036. else
  4037. splitRight = t.Xml;
  4038. }
  4039. return
  4040. (
  4041. new XElement[]
  4042. {
  4043. splitLeft,
  4044. splitRight
  4045. }
  4046. );
  4047. }
  4048. /// <summary>
  4049. /// If a text element or delText element, starts or ends with a space,
  4050. /// it must have the attribute space, otherwise it must not have it.
  4051. /// </summary>
  4052. /// <param name="e">The (t or delText) element check</param>
  4053. public static void PreserveSpace(XElement e)
  4054. {
  4055. // PreserveSpace should only be used on (t or delText) elements
  4056. if (!e.Name.Equals(DocX.w + "t") && !e.Name.Equals(DocX.w + "delText"))
  4057. throw new ArgumentException("SplitText can only split elements of type t or delText", "e");
  4058. // Check if this w:t contains a space atribute
  4059. XAttribute space = e.Attributes().Where(a => a.Name.Equals(XNamespace.Xml + "space")).SingleOrDefault();
  4060. // This w:t's text begins or ends with whitespace
  4061. if (e.Value.StartsWith(" ") || e.Value.EndsWith(" "))
  4062. {
  4063. // If this w:t contains no space attribute, add one.
  4064. if (space == null)
  4065. e.Add(new XAttribute(XNamespace.Xml + "space", "preserve"));
  4066. }
  4067. // This w:t's text does not begin or end with a space
  4068. else
  4069. {
  4070. // If this w:r contains a space attribute, remove it.
  4071. if (space != null)
  4072. space.Remove();
  4073. }
  4074. }
  4075. }
  4076. }