Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

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