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 149KB

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