Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

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