Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

DocX.cs 72KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Xml.Linq;
  6. using System.Xml;
  7. using System.IO;
  8. using System.Text.RegularExpressions;
  9. using System.IO.Packaging;
  10. namespace Novacode
  11. {
  12. /// <summary>
  13. /// Represents a document.
  14. /// </summary>
  15. public class DocX: IDisposable
  16. {
  17. #region Namespaces
  18. static internal XNamespace w = "http://schemas.openxmlformats.org/wordprocessingml/2006/main";
  19. static internal XNamespace customPropertiesSchema = "http://schemas.openxmlformats.org/officeDocument/2006/custom-properties";
  20. static internal XNamespace customVTypesSchema = "http://schemas.openxmlformats.org/officeDocument/2006/docPropsVTypes";
  21. #endregion
  22. #region Private instance variables defined foreach DocX object
  23. // The collection of Paragraphs in this document.
  24. private List<Paragraph> paragraphs = new List<Paragraph>();
  25. // A dictionary of CustomProperties in this document.
  26. private Dictionary<string, CustomProperty> customProperties;
  27. // A list of Images in this document.
  28. private List<Image> images;
  29. // A collection of Tables in this Paragraph
  30. private List<Table> tables;
  31. #endregion
  32. #region Internal variables defined foreach DocX object
  33. // Object representation of the .docx
  34. internal Package package;
  35. // The mainDocument is loaded into a XDocument object for easy querying and editing
  36. internal XDocument mainDoc;
  37. // A lookup for the Paragraphs in this document.
  38. internal Dictionary<int, Paragraph> paragraphLookup = new Dictionary<int, Paragraph>();
  39. // Every document is stored in a MemoryStream, all edits made to a document are done in memory.
  40. internal MemoryStream memoryStream;
  41. // The filename that this document was loaded from
  42. internal string filename;
  43. // The stream that this document was loaded from
  44. internal Stream stream;
  45. #endregion
  46. internal DocX()
  47. {
  48. }
  49. /// <summary>
  50. /// Returns a list of Paragraphs in this document.
  51. /// </summary>
  52. /// <example>
  53. /// Write to Console the Text from each Paragraph in this document.
  54. /// <code>
  55. /// // Load a document
  56. /// DocX document = DocX.Load(@"C:\Example\Test.docx");
  57. ///
  58. /// // Loop through each Paragraph in this document.
  59. /// foreach (Paragraph p in document.Paragraphs)
  60. /// {
  61. /// // Write this Paragraphs Text to Console.
  62. /// Console.WriteLine(p.Text);
  63. /// }
  64. ///
  65. /// // Wait for the user to press a key before closing the console window.
  66. /// Console.ReadKey();
  67. /// </code>
  68. /// </example>
  69. /// <seealso cref="Paragraph.InsertText(string, bool)"/>
  70. /// <seealso cref="Paragraph.InsertText(int, string, bool)"/>
  71. /// <seealso cref="Paragraph.InsertText(string, bool, Formatting)"/>
  72. /// <seealso cref="Paragraph.InsertText(int, string, bool, Formatting)"/>
  73. /// <seealso cref="Paragraph.RemoveText(int, bool)"/>
  74. /// <seealso cref="Paragraph.RemoveText(int, int, bool)"/>
  75. /// <seealso cref="Paragraph.ReplaceText(string, string, bool)"/>
  76. /// <seealso cref="Paragraph.ReplaceText(string, string, bool, RegexOptions)"/>
  77. /// <seealso cref="Paragraph.InsertPicture"/>
  78. public List<Paragraph> Paragraphs
  79. {
  80. get { return paragraphs; }
  81. }
  82. /// <summary>
  83. /// Returns a list of Tables in this Paragraph.
  84. /// </summary>
  85. public List<Table> Tables
  86. {
  87. get { return tables; }
  88. }
  89. /// <summary>
  90. /// Returns a list of Images in this document.
  91. /// </summary>
  92. /// <example>
  93. /// Get the unique Id of every Image in this document.
  94. /// <code>
  95. /// // Load a document.
  96. /// DocX document = DocX.Load(@"C:\Example\Test.docx");
  97. ///
  98. /// // Loop through each Image in this document.
  99. /// foreach (Novacode.Image i in document.Images)
  100. /// {
  101. /// // Get the unique Id which identifies this Image.
  102. /// string uniqueId = i.Id;
  103. /// }
  104. ///
  105. /// </code>
  106. /// </example>
  107. /// <seealso cref="AddImage(string)"/>
  108. /// <seealso cref="AddImage(Stream)"/>
  109. /// <seealso cref="Paragraph.Pictures"/>
  110. /// <seealso cref="Paragraph.InsertPicture"/>
  111. public List<Image> Images
  112. {
  113. get { return images; }
  114. }
  115. /// <summary>
  116. /// Returns a list of custom properties in this document.
  117. /// </summary>
  118. /// <example>
  119. /// Method 1: Get the name, type and value of each CustomProperty in this document.
  120. /// <code>
  121. /// // Load Example.docx
  122. /// DocX document = DocX.Load(@"C:\Example\Test.docx");
  123. ///
  124. /// /*
  125. /// * No two custom properties can have the same name,
  126. /// * so a Dictionary is the perfect data structure to store them in.
  127. /// * Each custom property can be accessed using its name.
  128. /// */
  129. /// foreach (string name in document.CustomProperties.Keys)
  130. /// {
  131. /// // Grab a custom property using its name.
  132. /// CustomProperty cp = document.CustomProperties[name];
  133. ///
  134. /// // Write this custom properties details to Console.
  135. /// Console.WriteLine(string.Format("Name: '{0}', Value: {1}", cp.Name, cp.Value));
  136. /// }
  137. ///
  138. /// Console.WriteLine("Press any key...");
  139. ///
  140. /// // Wait for the user to press a key before closing the Console.
  141. /// Console.ReadKey();
  142. /// </code>
  143. /// </example>
  144. /// <example>
  145. /// Method 2: Get the name, type and value of each CustomProperty in this document.
  146. /// <code>
  147. /// // Load Example.docx
  148. /// DocX document = DocX.Load(@"C:\Example\Test.docx");
  149. ///
  150. /// /*
  151. /// * No two custom properties can have the same name,
  152. /// * so a Dictionary is the perfect data structure to store them in.
  153. /// * The values of this Dictionary are CustomProperties.
  154. /// */
  155. /// foreach (CustomProperty cp in document.CustomProperties.Values)
  156. /// {
  157. /// // Write this custom properties details to Console.
  158. /// Console.WriteLine(string.Format("Name: '{0}', Value: {1}", cp.Name, cp.Value));
  159. /// }
  160. ///
  161. /// Console.WriteLine("Press any key...");
  162. ///
  163. /// // Wait for the user to press a key before closing the Console.
  164. /// Console.ReadKey();
  165. /// </code>
  166. /// </example>
  167. /// <seealso cref="AddCustomProperty"/>
  168. public Dictionary<string, CustomProperty> CustomProperties
  169. {
  170. get { return customProperties; }
  171. }
  172. static internal void RebuildParagraphs(DocX document)
  173. {
  174. document.paragraphLookup.Clear();
  175. document.paragraphs.Clear();
  176. // Get the runs in this paragraph
  177. IEnumerable<XElement> paras = document.mainDoc.Descendants(XName.Get("p", "http://schemas.openxmlformats.org/wordprocessingml/2006/main"));
  178. int startIndex = 0;
  179. // Loop through each run in this paragraph
  180. foreach (XElement par in paras)
  181. {
  182. Paragraph xp = new Paragraph(document, startIndex, par);
  183. // Add to paragraph list
  184. document.paragraphs.Add(xp);
  185. // Only add runs which contain text
  186. if (Paragraph.GetElementTextLength(par) > 0)
  187. {
  188. document.paragraphLookup.Add(xp.endIndex, xp);
  189. startIndex = xp.endIndex;
  190. }
  191. }
  192. }
  193. /// <summary>
  194. /// Insert a new Paragraph at the end of this document.
  195. /// </summary>
  196. /// <param name="text">The text of this Paragraph.</param>
  197. /// <param name="trackChanges">Should this insertion be tracked as a change?</param>
  198. /// <returns>A new Paragraph.</returns>
  199. /// <example>
  200. /// Inserting a new Paragraph at the end of a document with text formatting.
  201. /// <code>
  202. /// // Load a document.
  203. /// using (DocX document = DocX.Load(@"C:\Example\Test.docx"))
  204. /// {
  205. /// // Insert a new Paragraph at the end of this document.
  206. /// document.InsertParagraph("New text", false);
  207. ///
  208. /// // Save all changes made to this document.
  209. /// document.Save();
  210. /// }// Release this document from memory
  211. /// </code>
  212. /// </example>
  213. public Paragraph InsertParagraph(string text, bool trackChanges)
  214. {
  215. int index = 0;
  216. if (paragraphLookup.Keys.Count() > 0)
  217. index = paragraphLookup.Last().Key;
  218. return InsertParagraph(index, text, trackChanges, null);
  219. }
  220. /// <summary>
  221. /// Insert a new Paragraph at the end of a document with text formatting.
  222. /// </summary>
  223. /// <param name="text">The text of this Paragraph.</param>
  224. /// <param name="trackChanges">Should this insertion be tracked as a change?</param>
  225. /// <param name="formatting">The formatting for the text of this Paragraph.</param>
  226. /// <returns>A new Paragraph.</returns>
  227. /// <example>
  228. /// Inserting a new Paragraph at the end of a document with text formatting.
  229. /// <code>
  230. /// // Load a document.
  231. /// using (DocX document = DocX.Load(@"C:\Example\Test.docx"))
  232. /// {
  233. /// // Create a Formatting object
  234. /// Formatting formatting = new Formatting();
  235. /// formatting.Bold = true;
  236. /// formatting.FontColor = Color.Red;
  237. /// formatting.Size = 30;
  238. ///
  239. /// // Insert a new Paragraph at the end of this document with text formatting.
  240. /// document.InsertParagraph("New text", false, formatting);
  241. ///
  242. /// // Save all changes made to this document.
  243. /// document.Save();
  244. /// }// Release this document from memory
  245. /// </code>
  246. /// </example>
  247. public Paragraph InsertParagraph(string text, bool trackChanges, Formatting formatting)
  248. {
  249. int index = 0;
  250. if (paragraphLookup.Keys.Count() > 0)
  251. index = paragraphLookup.Last().Key;
  252. return InsertParagraph(index, text, trackChanges, formatting);
  253. }
  254. /// <summary>
  255. /// Get the Text of this document.
  256. /// </summary>
  257. /// <example>
  258. /// Write to Console the Text from this document.
  259. /// <code>
  260. /// // Load a document
  261. /// DocX document = DocX.Load(@"C:\Example\Test.docx");
  262. ///
  263. /// // Get the text of this document.
  264. /// string text = document.Text;
  265. ///
  266. /// // Write the text of this document to Console.
  267. /// Console.Write(text);
  268. ///
  269. /// // Wait for the user to press a key before closing the console window.
  270. /// Console.ReadKey();
  271. /// </code>
  272. /// </example>
  273. public string Text
  274. {
  275. get
  276. {
  277. string text = string.Empty;
  278. foreach (Paragraph p in paragraphs)
  279. {
  280. text += p.Text + "\n";
  281. }
  282. return text;
  283. }
  284. }
  285. /// <summary>
  286. /// Insert a new Paragraph into this document at a specified index.
  287. /// </summary>
  288. /// <param name="index">The character index to insert this document at.</param>
  289. /// <param name="text">The text of this Paragraph.</param>
  290. /// <param name="trackChanges">Should this insertion be tracked as a change?</param>
  291. /// <returns>A new Paragraph.</returns>
  292. /// <example>
  293. /// Insert a new Paragraph into the middle of a document.
  294. /// <code>
  295. /// // Load a document.
  296. /// using (DocX document = DocX.Load(@"C:\Example\Test.docx"))
  297. /// {
  298. /// // Find the middle character index of this document.
  299. /// int index = document.Text.Length / 2;
  300. ///
  301. /// // Insert a new Paragraph at the middle of this document.
  302. /// document.InsertParagraph(index, "New text", false);
  303. ///
  304. /// // Save all changes made to this document.
  305. /// document.Save();
  306. ///}// Release this document from memory
  307. /// </code>
  308. /// </example>
  309. public Paragraph InsertParagraph(int index, string text, bool trackChanges)
  310. {
  311. return InsertParagraph(index, text, trackChanges, null);
  312. }
  313. /// <summary>
  314. /// Insert a Paragraph into this document, this Paragraph may have come from the same or another document.
  315. /// </summary>
  316. /// <param name="index">The index to insert this Paragragraph at.</param>
  317. /// <param name="p">The Paragraph to insert.</param>
  318. /// <returns>The Paragraph now associated with this document.</returns>
  319. /// <example>
  320. /// Take a Paragraph from document a, and insert it into document b at a specified position.
  321. /// <code>
  322. /// // Place holder for a Paragraph.
  323. /// Paragraph p;
  324. ///
  325. /// // Load document a.
  326. /// using (DocX documentA = DocX.Load(@"C:\Example\a.docx"))
  327. /// {
  328. /// // Get the first paragraph from this document.
  329. /// p = documentA.Paragraphs[0];
  330. /// }
  331. ///
  332. /// // Load document b.
  333. /// using (DocX documentB = DocX.Load(@"C:\Example\b.docx"))
  334. /// {
  335. /// /*
  336. /// * Insert the Paragraph that was extracted from document a, into docment b.
  337. /// * This creates a new Paragraph that is now associated with document b.
  338. /// */
  339. /// Paragraph newParagraph = documentB.InsertParagraph(0, p);
  340. ///
  341. /// // Save all changes made to document b.
  342. /// documentB.Save();
  343. /// }// Release this document from memory.
  344. /// </code>
  345. /// </example>
  346. public Paragraph InsertParagraph(int index, Paragraph p)
  347. {
  348. XElement newXElement = new XElement(p.xml);
  349. p.xml = newXElement;
  350. Paragraph paragraph = GetFirstParagraphEffectedByInsert(this, index);
  351. if (paragraph == null)
  352. mainDoc.Descendants(XName.Get("body", DocX.w.NamespaceName)).First().Add(p.xml);
  353. else
  354. {
  355. XElement[] split = SplitParagraph(paragraph, index - paragraph.startIndex);
  356. paragraph.xml.ReplaceWith
  357. (
  358. split[0],
  359. newXElement,
  360. split[1]
  361. );
  362. }
  363. RebuildParagraphs(this);
  364. return p;
  365. }
  366. /// <summary>
  367. /// Insert a Paragraph into this document, this Paragraph may have come from the same or another document.
  368. /// </summary>
  369. /// <param name="p">The Paragraph to insert.</param>
  370. /// <returns>The Paragraph now associated with this document.</returns>
  371. /// <example>
  372. /// Take a Paragraph from document a, and insert it into the end of document b.
  373. /// <code>
  374. /// // Place holder for a Paragraph.
  375. /// Paragraph p;
  376. ///
  377. /// // Load document a.
  378. /// using (DocX documentA = DocX.Load(@"C:\Example\a.docx"))
  379. /// {
  380. /// // Get the first paragraph from this document.
  381. /// p = documentA.Paragraphs[0];
  382. /// }
  383. ///
  384. /// // Load document b.
  385. /// using (DocX documentB = DocX.Load(@"C:\Example\b.docx"))
  386. /// {
  387. /// /*
  388. /// * Insert the Paragraph that was extracted from document a, into docment b.
  389. /// * This creates a new Paragraph that is now associated with document b.
  390. /// */
  391. /// Paragraph newParagraph = documentB.InsertParagraph(p);
  392. ///
  393. /// // Save all changes made to document b.
  394. /// documentB.Save();
  395. /// }// Release this document from memory.
  396. /// </code>
  397. /// </example>
  398. public Paragraph InsertParagraph(Paragraph p)
  399. {
  400. XElement newXElement = new XElement(p.xml);
  401. mainDoc.Descendants(XName.Get("body", DocX.w.NamespaceName)).First().Add(newXElement);
  402. int index = 0;
  403. if (paragraphLookup.Keys.Count() > 0)
  404. index = paragraphLookup.Last().Key + paragraphLookup.Last().Value.Text.Length;
  405. Paragraph newParagraph = new Paragraph(this, index, newXElement);
  406. paragraphLookup.Add(index, newParagraph);
  407. return newParagraph;
  408. }
  409. /// <summary>
  410. /// Insert a new Table at the end of this document.
  411. /// </summary>
  412. /// <param name="coloumnCount">The number of coloumns to create.</param>
  413. /// <param name="rowCount">The number of rows to create.</param>
  414. /// <returns>A new Table.</returns>
  415. /// <example>
  416. /// Insert a new Table with 2 coloumns and 3 rows, at the end of a document.
  417. /// <code>
  418. /// // Create a document.
  419. /// using (DocX document = DocX.Create(@"C:\Example\Test.docx"))
  420. /// {
  421. /// // Create a new Table with 2 coloumns and 3 rows.
  422. /// Table newTable = document.InsertTable(2, 3);
  423. ///
  424. /// // Set the design of this Table.
  425. /// newTable.Design = TableDesign.LightShadingAccent2;
  426. ///
  427. /// // Set the coloumn names.
  428. /// newTable.Rows[0].Cells[0].Paragraph.InsertText("Ice Cream", false);
  429. /// newTable.Rows[0].Cells[1].Paragraph.InsertText("Price", false);
  430. ///
  431. /// // Fill row 1
  432. /// newTable.Rows[1].Cells[0].Paragraph.InsertText("Chocolate", false);
  433. /// newTable.Rows[1].Cells[1].Paragraph.InsertText("€3:50", false);
  434. ///
  435. /// // Fill row 2
  436. /// newTable.Rows[2].Cells[0].Paragraph.InsertText("Vanilla", false);
  437. /// newTable.Rows[2].Cells[1].Paragraph.InsertText("€3:00", false);
  438. ///
  439. /// // Save all changes made to document b.
  440. /// document.Save();
  441. /// }// Release this document from memory.
  442. /// </code>
  443. /// </example>
  444. public Table InsertTable(int coloumnCount, int rowCount)
  445. {
  446. XElement newTable = CreateTable(rowCount, coloumnCount);
  447. mainDoc.Descendants(XName.Get("body", DocX.w.NamespaceName)).First().Add(newTable);
  448. RebuildTables();
  449. RebuildParagraphs(this);
  450. return new Table(this, newTable);
  451. }
  452. internal static XElement CreateTable(int rowCount, int coloumnCount)
  453. {
  454. XElement newTable =
  455. new XElement
  456. (
  457. XName.Get("tbl", DocX.w.NamespaceName),
  458. new XElement
  459. (
  460. XName.Get("tblPr", DocX.w.NamespaceName),
  461. new XElement(XName.Get("tblStyle", DocX.w.NamespaceName), new XAttribute(XName.Get("val", DocX.w.NamespaceName), "TableGrid")),
  462. new XElement(XName.Get("tblW", DocX.w.NamespaceName), new XAttribute(XName.Get("w", DocX.w.NamespaceName), "0"), new XAttribute(XName.Get("type", DocX.w.NamespaceName), "auto")),
  463. new XElement(XName.Get("tblLook", DocX.w.NamespaceName), new XAttribute(XName.Get("val", DocX.w.NamespaceName), "04A0"))
  464. )
  465. );
  466. XElement tableGrid = new XElement(XName.Get("tblGrid", DocX.w.NamespaceName));
  467. for (int i = 0; i < coloumnCount; i++)
  468. tableGrid.Add(new XElement(XName.Get("gridCol", DocX.w.NamespaceName), new XAttribute(XName.Get("w", DocX.w.NamespaceName), "2310")));
  469. newTable.Add(tableGrid);
  470. for (int i = 0; i < rowCount; i++)
  471. {
  472. XElement row = new XElement(XName.Get("tr", DocX.w.NamespaceName));
  473. for (int j = 0; j < coloumnCount; j++)
  474. {
  475. XElement cell =
  476. new XElement
  477. (
  478. XName.Get("tc", DocX.w.NamespaceName),
  479. new XElement(XName.Get("tcPr", DocX.w.NamespaceName),
  480. new XElement(XName.Get("tcW", DocX.w.NamespaceName), new XAttribute(XName.Get("w", DocX.w.NamespaceName), "2310"), new XAttribute(XName.Get("type", DocX.w.NamespaceName), "dxa"))),
  481. new XElement(XName.Get("p", DocX.w.NamespaceName))
  482. );
  483. row.Add(cell);
  484. }
  485. newTable.Add(row);
  486. }
  487. return newTable;
  488. }
  489. /// <summary>
  490. /// Insert a Table into this document. The Table's source can be a completely different document.
  491. /// </summary>
  492. /// <param name="t">The Table to insert.</param>
  493. /// <param name="index">The index to insert this Table at.</param>
  494. /// <returns>The Table now associated with this document.</returns>
  495. /// <example>
  496. /// Extract a Table from document a and insert it into document b, at index 10.
  497. /// <code>
  498. /// // Place holder for a Table.
  499. /// Table t;
  500. ///
  501. /// // Load document a.
  502. /// using (DocX documentA = DocX.Load(@"C:\Example\a.docx"))
  503. /// {
  504. /// // Get the first Table from this document.
  505. /// t = documentA.Tables[0];
  506. /// }
  507. ///
  508. /// // Load document b.
  509. /// using (DocX documentB = DocX.Load(@"C:\Example\b.docx"))
  510. /// {
  511. /// /*
  512. /// * Insert the Table that was extracted from document a, into document b.
  513. /// * This creates a new Table that is now associated with document b.
  514. /// */
  515. /// Table newTable = documentB.InsertTable(10, t);
  516. ///
  517. /// // Save all changes made to document b.
  518. /// documentB.Save();
  519. /// }// Release this document from memory.
  520. /// </code>
  521. /// </example>
  522. public Table InsertTable(int index, Table t)
  523. {
  524. Paragraph p = GetFirstParagraphEffectedByInsert(this, index);
  525. XElement[] split = SplitParagraph(p, index - p.startIndex);
  526. XElement newXElement = new XElement(t.xml);
  527. p.xml.ReplaceWith
  528. (
  529. split[0],
  530. newXElement,
  531. split[1]
  532. );
  533. Table newTable = new Table(this, newXElement);
  534. newTable.Design = t.Design;
  535. RebuildTables();
  536. RebuildParagraphs(this);
  537. return newTable;
  538. }
  539. /// <summary>
  540. /// Insert a Table into this document. The Table's source can be a completely different document.
  541. /// </summary>
  542. /// <param name="t">The Table to insert.</param>
  543. /// <returns>The Table now associated with this document.</returns>
  544. /// <example>
  545. /// Extract a Table from document a and insert it at the end of document b.
  546. /// <code>
  547. /// // Place holder for a Table.
  548. /// Table t;
  549. ///
  550. /// // Load document a.
  551. /// using (DocX documentA = DocX.Load(@"C:\Example\a.docx"))
  552. /// {
  553. /// // Get the first Table from this document.
  554. /// t = documentA.Tables[0];
  555. /// }
  556. ///
  557. /// // Load document b.
  558. /// using (DocX documentB = DocX.Load(@"C:\Example\b.docx"))
  559. /// {
  560. /// /*
  561. /// * Insert the Table that was extracted from document a, into document b.
  562. /// * This creates a new Table that is now associated with document b.
  563. /// */
  564. /// Table newTable = documentB.InsertTable(t);
  565. ///
  566. /// // Save all changes made to document b.
  567. /// documentB.Save();
  568. /// }// Release this document from memory.
  569. /// </code>
  570. /// </example>
  571. public Table InsertTable(Table t)
  572. {
  573. XElement newXElement = new XElement(t.xml);
  574. mainDoc.Descendants(XName.Get("body", DocX.w.NamespaceName)).First().Add(newXElement);
  575. Table newTable = new Table(this, newXElement);
  576. newTable.Design = t.Design;
  577. tables.Add(newTable);
  578. return newTable;
  579. }
  580. /// <summary>
  581. /// Insert a new Table at the end of this document.
  582. /// </summary>
  583. /// <param name="coloumnCount">The number of coloumns to create.</param>
  584. /// <param name="rowCount">The number of rows to create.</param>
  585. /// <param name="index">The index to insert this Table at.</param>
  586. /// <returns>A new Table.</returns>
  587. /// <example>
  588. /// Insert a new Table with 2 coloumns and 3 rows, at index 37 in this document.
  589. /// <code>
  590. /// // Create a document.
  591. /// using (DocX document = DocX.Load(@"C:\Example\Test.docx"))
  592. /// {
  593. /// // Create a new Table with 2 coloumns and 3 rows. Insert this Table at index 37.
  594. /// Table newTable = document.InsertTable(37, 2, 3);
  595. ///
  596. /// // Set the design of this Table.
  597. /// newTable.Design = TableDesign.LightShadingAccent3;
  598. ///
  599. /// // Set the coloumn names.
  600. /// newTable.Rows[0].Cells[0].Paragraph.InsertText("Ice Cream", false);
  601. /// newTable.Rows[0].Cells[1].Paragraph.InsertText("Price", false);
  602. ///
  603. /// // Fill row 1
  604. /// newTable.Rows[1].Cells[0].Paragraph.InsertText("Chocolate", false);
  605. /// newTable.Rows[1].Cells[1].Paragraph.InsertText("€3:50", false);
  606. ///
  607. /// // Fill row 2
  608. /// newTable.Rows[2].Cells[0].Paragraph.InsertText("Vanilla", false);
  609. /// newTable.Rows[2].Cells[1].Paragraph.InsertText("€3:00", false);
  610. ///
  611. /// // Save all changes made to document b.
  612. /// document.Save();
  613. /// }// Release this document from memory.
  614. /// </code>
  615. /// </example>
  616. public Table InsertTable(int index, int coloumnCount, int rowCount)
  617. {
  618. XElement newTable = CreateTable(rowCount, coloumnCount);
  619. Paragraph p = GetFirstParagraphEffectedByInsert(this, index);
  620. if (p == null)
  621. mainDoc.Descendants(XName.Get("body", DocX.w.NamespaceName)).First().AddFirst(newTable);
  622. else
  623. {
  624. XElement[] split = SplitParagraph(p, index - p.startIndex);
  625. p.xml.ReplaceWith
  626. (
  627. split[0],
  628. newTable,
  629. split[1]
  630. );
  631. }
  632. RebuildParagraphs(this);
  633. RebuildTables();
  634. return new Table(this, newTable);
  635. }
  636. internal void RebuildTables()
  637. {
  638. tables =
  639. (
  640. from t in mainDoc.Descendants(XName.Get("tbl", DocX.w.NamespaceName))
  641. select new Table(this, t)
  642. ).ToList();
  643. }
  644. /// <summary>
  645. /// Insert a new Paragraph into this document at a specified index with text formatting.
  646. /// </summary>
  647. /// <param name="index">The character index to insert this document at.</param>
  648. /// <param name="text">The text of this Paragraph.</param>
  649. /// <param name="trackChanges">Should this insertion be tracked as a change?</param>
  650. /// <param name="formatting">The formatting for the text of this Paragraph.</param>
  651. /// <returns>A new Paragraph.</returns>
  652. /// /// <example>
  653. /// Insert a new Paragraph into the middle of a document with text formatting.
  654. /// <code>
  655. /// // Load a document.
  656. /// using (DocX document = DocX.Load(@"C:\Example\Test.docx"))
  657. /// {
  658. /// // Create a Formatting object
  659. /// Formatting formatting = new Formatting();
  660. /// formatting.Bold = true;
  661. /// formatting.FontColor = Color.Red;
  662. /// formatting.Size = 30;
  663. ///
  664. /// // Middle character index of this document.
  665. /// int index = document.Text.Length / 2;
  666. ///
  667. /// // Insert a new Paragraph in the middle of this document.
  668. /// document.InsertParagraph(index, "New text", false, formatting);
  669. ///
  670. /// // Save all changes made to this document.
  671. /// document.Save();
  672. /// }// Release this document from memory
  673. /// </code>
  674. /// <remarks>You must add a reference to System.Drawing in order to use Color.Red.</remarks>
  675. /// </example>
  676. public Paragraph InsertParagraph(int index, string text, bool trackChanges, Formatting formatting)
  677. {
  678. Paragraph newParagraph = new Paragraph(this, index, new XElement(w + "p"));
  679. newParagraph.InsertText(0, text, trackChanges, formatting);
  680. Paragraph firstPar = GetFirstParagraphEffectedByInsert(this, index);
  681. if (firstPar != null)
  682. {
  683. XElement[] splitParagraph = SplitParagraph(firstPar, index - firstPar.startIndex);
  684. firstPar.xml.ReplaceWith
  685. (
  686. splitParagraph[0],
  687. newParagraph.xml,
  688. splitParagraph[1]
  689. );
  690. }
  691. else
  692. mainDoc.Descendants(XName.Get("body", DocX.w.NamespaceName)).First().Add(newParagraph.xml);
  693. DocX.RebuildParagraphs(this);
  694. return newParagraph;
  695. }
  696. static internal Paragraph GetFirstParagraphEffectedByInsert(DocX document, int index)
  697. {
  698. // This document contains no Paragraphs and insertion is at index 0
  699. if (document.paragraphLookup.Keys.Count() == 0 && index == 0)
  700. return null;
  701. foreach (int paragraphEndIndex in document.paragraphLookup.Keys)
  702. {
  703. if (paragraphEndIndex >= index)
  704. return document.paragraphLookup[paragraphEndIndex];
  705. }
  706. throw new ArgumentOutOfRangeException();
  707. }
  708. internal XElement[] SplitParagraph(Paragraph p, int index)
  709. {
  710. Run r = p.GetFirstRunEffectedByInsert(index);
  711. XElement[] split;
  712. XElement before, after;
  713. if (r.xml.Parent.Name.LocalName == "ins")
  714. {
  715. split = p.SplitEdit(r.xml.Parent, index, EditType.ins);
  716. before = new XElement(p.xml.Name, p.xml.Attributes(), r.xml.Parent.ElementsBeforeSelf(), split[0]);
  717. after = new XElement(p.xml.Name, p.xml.Attributes(), r.xml.Parent.ElementsAfterSelf(), split[1]);
  718. }
  719. else if (r.xml.Parent.Name.LocalName == "del")
  720. {
  721. split = p.SplitEdit(r.xml.Parent, index, EditType.del);
  722. before = new XElement(p.xml.Name, p.xml.Attributes(), r.xml.Parent.ElementsBeforeSelf(), split[0]);
  723. after = new XElement(p.xml.Name, p.xml.Attributes(), r.xml.Parent.ElementsAfterSelf(), split[1]);
  724. }
  725. else
  726. {
  727. split = Run.SplitRun(r, index);
  728. before = new XElement(p.xml.Name, p.xml.Attributes(), r.xml.ElementsBeforeSelf(), split[0]);
  729. after = new XElement(p.xml.Name, p.xml.Attributes(), r.xml.ElementsAfterSelf(), split[1]);
  730. }
  731. if (before.Elements().Count() == 0)
  732. before = null;
  733. if (after.Elements().Count() == 0)
  734. after = null;
  735. return new XElement[] { before, after };
  736. }
  737. /// <summary>
  738. /// Creates a document using a Stream.
  739. /// </summary>
  740. /// <param name="stream">The Stream to create the document from.</param>
  741. /// <returns>Returns a DocX object which represents the document.</returns>
  742. /// <example>
  743. /// Creating a document from a FileStream.
  744. /// <code>
  745. /// // Use a FileStream fs to create a new document.
  746. /// using(FileStream fs = new FileStream(@"C:\Example\Test.docx", FileMode.Create))
  747. /// {
  748. /// // Load the document using fs
  749. /// using (DocX document = DocX.Create(fs))
  750. /// {
  751. /// // Do something with the document here.
  752. ///
  753. /// // Save all changes made to this document.
  754. /// document.Save();
  755. /// }// Release this document from memory.
  756. /// }
  757. /// </code>
  758. /// </example>
  759. /// <example>
  760. /// Creating a document in a SharePoint site.
  761. /// <code>
  762. /// using(SPSite mySite = new SPSite("http://server/sites/site"))
  763. /// {
  764. /// // Open a connection to the SharePoint site
  765. /// using(SPWeb myWeb = mySite.OpenWeb())
  766. /// {
  767. /// // Create a MemoryStream ms.
  768. /// using (MemoryStream ms = new MemoryStream())
  769. /// {
  770. /// // Create a document using ms.
  771. /// using (DocX document = DocX.Create(ms))
  772. /// {
  773. /// // Do something with the document here.
  774. ///
  775. /// // Save all changes made to this document.
  776. /// document.Save();
  777. /// }// Release this document from memory
  778. ///
  779. /// // Add the document to the SharePoint site
  780. /// web.Files.Add("filename", ms.ToArray(), true);
  781. /// }
  782. /// }
  783. /// }
  784. /// </code>
  785. /// </example>
  786. /// <seealso cref="DocX.Create(string)"/>
  787. /// <seealso cref="DocX.Load(System.IO.Stream)"/>
  788. /// <seealso cref="DocX.Load(string)"/>
  789. /// <seealso cref="DocX.Save()"/>
  790. public static DocX Create(Stream stream)
  791. {
  792. // Store this document in memory
  793. MemoryStream ms = new MemoryStream();
  794. // Create the docx package
  795. Package package = Package.Open(ms, FileMode.Create, FileAccess.ReadWrite);
  796. PostCreation(ref package);
  797. DocX document = DocX.Load(ms);
  798. document.stream = stream;
  799. return document;
  800. }
  801. /// <summary>
  802. /// Creates a document using a fully qualified or relative filename.
  803. /// </summary>
  804. /// <param name="filename">The fully qualified or relative filename.</param>
  805. /// <returns>Returns a DocX object which represents the document.</returns>
  806. /// <example>
  807. /// <code>
  808. /// // Create a document using a relative filename.
  809. /// using (DocX document = DocX.Create(@"..\Test.docx"))
  810. /// {
  811. /// // Do something with the document here.
  812. ///
  813. /// // Save all changes made to this document.
  814. /// document.Save();
  815. /// }// Release this document from memory
  816. /// </code>
  817. /// <code>
  818. /// // Create a document using a relative filename.
  819. /// using (DocX document = DocX.Create(@"..\Test.docx"))
  820. /// {
  821. /// // Do something with the document here.
  822. ///
  823. /// // Save all changes made to this document.
  824. /// document.Save();
  825. /// }// Release this document from memory
  826. /// </code>
  827. /// <seealso cref="DocX.Create(System.IO.Stream)"/>
  828. /// <seealso cref="DocX.Load(System.IO.Stream)"/>
  829. /// <seealso cref="DocX.Load(string)"/>
  830. /// <seealso cref="DocX.Save()"/>
  831. /// </example>
  832. public static DocX Create(string filename)
  833. {
  834. // Store this document in memory
  835. MemoryStream ms = new MemoryStream();
  836. // Create the docx package
  837. //WordprocessingDocument wdDoc = WordprocessingDocument.Create(ms, DocumentFormat.OpenXml.WordprocessingDocumentType.Document);
  838. Package package = Package.Open(ms, FileMode.Create, FileAccess.ReadWrite);
  839. PostCreation(ref package);
  840. DocX document = DocX.Load(ms);
  841. document.filename = filename;
  842. return document;
  843. }
  844. private static void PostCreation(ref Package package)
  845. {
  846. XDocument mainDoc, stylesDoc;
  847. #region MainDocumentPart
  848. // Create the main document part for this package
  849. PackagePart mainDocumentPart = package.CreatePart(new Uri("/word/document.xml", UriKind.Relative), "application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml");
  850. package.CreateRelationship(mainDocumentPart.Uri, TargetMode.Internal, "http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument");
  851. // Load the document part into a XDocument object
  852. using (TextReader tr = new StreamReader(mainDocumentPart.GetStream(FileMode.Create, FileAccess.ReadWrite)))
  853. {
  854. mainDoc = XDocument.Parse
  855. (@"<?xml version=""1.0"" encoding=""UTF-8"" standalone=""yes""?>
  856. <w:document xmlns:ve=""http://schemas.openxmlformats.org/markup-compatibility/2006"" xmlns:o=""urn:schemas-microsoft-com:office:office"" xmlns:r=""http://schemas.openxmlformats.org/officeDocument/2006/relationships"" xmlns:m=""http://schemas.openxmlformats.org/officeDocument/2006/math"" xmlns:v=""urn:schemas-microsoft-com:vml"" xmlns:wp=""http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing"" xmlns:w10=""urn:schemas-microsoft-com:office:word"" xmlns:w=""http://schemas.openxmlformats.org/wordprocessingml/2006/main"" xmlns:wne=""http://schemas.microsoft.com/office/word/2006/wordml"">
  857. <w:body>
  858. <w:sectPr w:rsidR=""003E25F4"" w:rsidSect=""00FC3028"">
  859. <w:pgSz w:w=""11906"" w:h=""16838""/>
  860. <w:pgMar w:top=""1440"" w:right=""1440"" w:bottom=""1440"" w:left=""1440"" w:header=""708"" w:footer=""708"" w:gutter=""0""/>
  861. <w:cols w:space=""708""/>
  862. <w:docGrid w:linePitch=""360""/>
  863. </w:sectPr>
  864. </w:body>
  865. </w:document>"
  866. );
  867. }
  868. // Save the main document
  869. using (TextWriter tw = new StreamWriter(mainDocumentPart.GetStream(FileMode.Create, FileAccess.Write)))
  870. mainDoc.Save(tw, SaveOptions.DisableFormatting);
  871. #endregion
  872. #region MainDocumentPart
  873. // Create the main document part for this package
  874. PackagePart word_styles = package.CreatePart(new Uri("/word/styles.xml", UriKind.Relative), "application/vnd.openxmlformats-officedocument.wordprocessingml.styles+xml");
  875. stylesDoc =
  876. XDocument.Parse
  877. (
  878. @"<?xml version='1.0' encoding='utf-8' standalone='yes'?>
  879. <w:styles xmlns:r='http://schemas.openxmlformats.org/officeDocument/2006/relationships' xmlns:w='http://schemas.openxmlformats.org/wordprocessingml/2006/main'>
  880. </w:styles>"
  881. );
  882. // Save the main document
  883. using (TextWriter tw = new StreamWriter(word_styles.GetStream(FileMode.Create, FileAccess.Write)))
  884. stylesDoc.Save(tw, SaveOptions.DisableFormatting);
  885. mainDocumentPart.CreateRelationship(word_styles.Uri, TargetMode.Internal, "http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles");
  886. #endregion
  887. package.Close();
  888. }
  889. private static DocX PostLoad(ref Package package)
  890. {
  891. DocX document = new DocX();
  892. document.package = package;
  893. #region MainDocumentPart
  894. // Load the document part into a XDocument object
  895. PackagePart word_document = package.GetPart(new Uri("/word/document.xml", UriKind.Relative));
  896. using (TextReader tr = new StreamReader(word_document.GetStream(FileMode.Open, FileAccess.Read)))
  897. document.mainDoc = XDocument.Load(tr, LoadOptions.PreserveWhitespace);
  898. RebuildParagraphs(document);
  899. document.images = new List<Image>();
  900. PackageRelationshipCollection imageRelationships = package.GetRelationshipsByType("http://schemas.openxmlformats.org/officeDocument/2006/relationships/image");
  901. if (imageRelationships.Count() > 0)
  902. {
  903. document.images =
  904. (
  905. from i in imageRelationships
  906. select new Image(document, i)
  907. ).ToList();
  908. }
  909. document.RebuildTables();
  910. #endregion
  911. #region CustomFilePropertiesPart
  912. ExtractCustomProperties(document);
  913. #endregion
  914. return document;
  915. }
  916. private static void ExtractCustomProperties(DocX document)
  917. {
  918. if(document.package.PartExists(new Uri("/docProps/custom.xml", UriKind.Relative)))
  919. {
  920. PackagePart docProps_custom = document.package.GetPart(new Uri("/docProps/custom.xml", UriKind.Relative));
  921. XDocument customPropDoc;
  922. using (TextReader tr = new StreamReader(docProps_custom.GetStream(FileMode.Open, FileAccess.Read)))
  923. customPropDoc = XDocument.Load(tr, LoadOptions.PreserveWhitespace);
  924. // Get all of the custom properties in this document
  925. document.customProperties =
  926. (
  927. from p in customPropDoc.Descendants(XName.Get("property", customPropertiesSchema.NamespaceName))
  928. let Name = p.Attribute(XName.Get("name")).Value
  929. let Type = p.Descendants().Single().Name.LocalName
  930. let Value = p.Descendants().Single().Value
  931. select new CustomProperty(Name, Type, Value)
  932. ).ToDictionary(p => p.Name, StringComparer.CurrentCultureIgnoreCase);
  933. }
  934. }
  935. /// <summary>
  936. /// Loads a document into a DocX object using a Stream.
  937. /// </summary>
  938. /// <param name="stream">The Stream to load the document from.</param>
  939. /// <returns>
  940. /// Returns a DocX object which represents the document.
  941. /// </returns>
  942. /// <example>
  943. /// Loading a document from a FileStream.
  944. /// <code>
  945. /// // Open a FileStream fs to a document.
  946. /// using (FileStream fs = new FileStream(@"C:\Example\Test.docx", FileMode.Open))
  947. /// {
  948. /// // Load the document using fs.
  949. /// using (DocX document = DocX.Load(fs))
  950. /// {
  951. /// // Do something with the document here.
  952. ///
  953. /// // Save all changes made to the document.
  954. /// document.Save();
  955. /// }// Release this document from memory.
  956. /// }
  957. /// </code>
  958. /// </example>
  959. /// <example>
  960. /// Loading a document from a SharePoint site.
  961. /// <code>
  962. /// // Get the SharePoint site that you want to access.
  963. /// using (SPSite mySite = new SPSite("http://server/sites/site"))
  964. /// {
  965. /// // Open a connection to the SharePoint site
  966. /// using (SPWeb myWeb = mySite.OpenWeb())
  967. /// {
  968. /// // Grab a document stored on this site.
  969. /// SPFile file = web.GetFile("Source_Folder_Name/Source_File");
  970. ///
  971. /// // DocX.Load requires a Stream, so open a Stream to this document.
  972. /// Stream str = new MemoryStream(file.OpenBinary());
  973. ///
  974. /// // Load the file using the Stream str.
  975. /// using (DocX document = DocX.Load(str))
  976. /// {
  977. /// // Do something with the document here.
  978. ///
  979. /// // Save all changes made to the document.
  980. /// document.Save();
  981. /// }// Release this document from memory.
  982. /// }
  983. /// }
  984. /// </code>
  985. /// </example>
  986. /// <seealso cref="DocX.Load(string)"/>
  987. /// <seealso cref="DocX.Create(System.IO.Stream)"/>
  988. /// <seealso cref="DocX.Create(string)"/>
  989. /// <seealso cref="DocX.Save()"/>
  990. public static DocX Load(Stream stream)
  991. {
  992. MemoryStream ms = new MemoryStream();
  993. stream.Position = 0;
  994. byte[] data = new byte[stream.Length];
  995. stream.Read(data, 0, (int)stream.Length);
  996. ms.Write(data, 0, (int)stream.Length);
  997. // Open the docx package
  998. Package package = Package.Open(ms, FileMode.Open, FileAccess.ReadWrite);
  999. DocX document = PostLoad(ref package);
  1000. document.package = package;
  1001. document.memoryStream = ms;
  1002. return document;
  1003. }
  1004. /// <summary>
  1005. /// Loads a document into a DocX object using a fully qualified or relative filename.
  1006. /// </summary>
  1007. /// <param name="filename">The fully qualified or relative filename.</param>
  1008. /// <returns>
  1009. /// Returns a DocX object which represents the document.
  1010. /// </returns>
  1011. /// <example>
  1012. /// <code>
  1013. /// // Load a document using its fully qualified filename
  1014. /// using (DocX document = DocX.Load(@"C:\Example\Test.docx"))
  1015. /// {
  1016. /// // Do something with the document here
  1017. ///
  1018. /// // Save all changes made to document.
  1019. /// document.Save();
  1020. /// }// Release this document from memory.
  1021. /// </code>
  1022. /// <code>
  1023. /// // Load a document using its relative filename.
  1024. /// using(DocX document = DocX.Load(@"..\..\Test.docx"))
  1025. /// {
  1026. /// // Do something with the document here.
  1027. ///
  1028. /// // Save all changes made to document.
  1029. /// document.Save();
  1030. /// }// Release this document from memory.
  1031. /// </code>
  1032. /// <seealso cref="DocX.Load(System.IO.Stream)"/>
  1033. /// <seealso cref="DocX.Create(System.IO.Stream)"/>
  1034. /// <seealso cref="DocX.Create(string)"/>
  1035. /// <seealso cref="DocX.Save()"/>
  1036. /// </example>
  1037. public static DocX Load(string filename)
  1038. {
  1039. if (!File.Exists(filename))
  1040. throw new FileNotFoundException(string.Format("File could not be found {0}", filename));
  1041. MemoryStream ms = new MemoryStream();
  1042. using (FileStream fs = new FileStream(filename, FileMode.Open))
  1043. {
  1044. byte[] data = new byte[fs.Length];
  1045. fs.Read(data, 0, (int)fs.Length);
  1046. ms.Write(data, 0, (int)fs.Length);
  1047. }
  1048. // Open the docx package
  1049. Package package = Package.Open(ms, FileMode.Open, FileAccess.ReadWrite);
  1050. DocX document = PostLoad(ref package);
  1051. document.package = package;
  1052. document.filename = filename;
  1053. document.memoryStream = ms;
  1054. return document;
  1055. }
  1056. /// <summary>
  1057. /// Add an Image into this document from a fully qualified or relative filename.
  1058. /// </summary>
  1059. /// <param name="filename">The fully qualified or relative filename.</param>
  1060. /// <returns>An Image file.</returns>
  1061. /// <example>
  1062. /// Add an Image into this document from a fully qualified filename.
  1063. /// <code>
  1064. /// // Load a document.
  1065. /// using (DocX document = DocX.Load(@"C:\Example\Test.docx"))
  1066. /// {
  1067. /// // Add an Image from a file.
  1068. /// document.AddImage(@"C:\Example\Image.png");
  1069. ///
  1070. /// // Save all changes made to this document.
  1071. /// document.Save();
  1072. /// }// Release this document from memory.
  1073. /// </code>
  1074. /// </example>
  1075. /// <seealso cref="AddImage(System.IO.Stream)"/>
  1076. /// <seealso cref="Paragraph.InsertPicture"/>
  1077. public Image AddImage(string filename)
  1078. {
  1079. return AddImage(filename as object);
  1080. }
  1081. private bool IsSameFile(Stream streamOne, Stream streamTwo)
  1082. {
  1083. int file1byte, file2byte;
  1084. if (streamOne.Length != streamOne.Length)
  1085. {
  1086. // Close the files
  1087. streamOne.Close();
  1088. streamTwo.Close();
  1089. // Return false to indicate files are different
  1090. return false;
  1091. }
  1092. // Read and compare a byte from each file until either a
  1093. // non-matching set of bytes is found or until the end of
  1094. // file1 is reached.
  1095. do
  1096. {
  1097. // Read one byte from each file.
  1098. file1byte = streamOne.ReadByte();
  1099. file2byte = streamTwo.ReadByte();
  1100. }
  1101. while ((file1byte == file2byte) && (file1byte != -1));
  1102. // Close the files.
  1103. streamOne.Close();
  1104. streamTwo.Close();
  1105. // Return the success of the comparison. "file1byte" is
  1106. // equal to "file2byte" at this point only if the files are
  1107. // the same.
  1108. return ((file1byte - file2byte) == 0);
  1109. }
  1110. /// <summary>
  1111. /// Add an Image into this document from a Stream.
  1112. /// </summary>
  1113. /// <param name="stream">A Stream stream.</param>
  1114. /// <returns>An Image file.</returns>
  1115. /// <example>
  1116. /// Add an Image into a document using a Stream.
  1117. /// <code>
  1118. /// // Open a FileStream fs to an Image.
  1119. /// using (FileStream fs = new FileStream(@"C:\Example\Image.jpg", FileMode.Open))
  1120. /// {
  1121. /// // Load a document.
  1122. /// using (DocX document = DocX.Load(@"C:\Example\Test.docx"))
  1123. /// {
  1124. /// // Add an Image from a filestream fs.
  1125. /// document.AddImage(fs);
  1126. ///
  1127. /// // Save all changes made to this document.
  1128. /// document.Save();
  1129. /// }// Release this document from memory.
  1130. /// }
  1131. /// </code>
  1132. /// </example>
  1133. /// <seealso cref="AddImage(string)"/>
  1134. /// <seealso cref="Paragraph.InsertPicture"/>
  1135. public Image AddImage(Stream stream)
  1136. {
  1137. return AddImage(stream as object);
  1138. }
  1139. internal Image AddImage(object o)
  1140. {
  1141. PackagePart word_document = package.GetPart(new Uri("/word/document.xml", UriKind.Relative));
  1142. var imageParts = word_document.GetRelationshipsByType("http://schemas.openxmlformats.org/officeDocument/2006/relationships/image").Select(ir => package.GetPart(ir.TargetUri));
  1143. foreach (PackagePart pp in imageParts)
  1144. {
  1145. Stream s;
  1146. if (o is string)
  1147. s = new FileStream(o as string, FileMode.Open);
  1148. else
  1149. s = o as Stream;
  1150. if (IsSameFile(pp.GetStream(), s))
  1151. {
  1152. string id = word_document.GetRelationshipsByType("http://schemas.openxmlformats.org/officeDocument/2006/relationships/image")
  1153. .Where(r => r.TargetUri == pp.Uri)
  1154. .Select(r => r.Id).First();
  1155. return images.Where(i => i.Id == id).First();
  1156. }
  1157. }
  1158. int max = 0;
  1159. var values =
  1160. (
  1161. from ip in imageParts
  1162. let Name = Path.GetFileNameWithoutExtension(ip.Uri.ToString())
  1163. let Number = Regex.Match(Name, @"\d+$").Value
  1164. select Number != string.Empty ? int.Parse(Number) : 0
  1165. );
  1166. if (values.Count() > 0)
  1167. max = Math.Max(max, values.Max());
  1168. PackagePart img = package.CreatePart(new Uri(string.Format("/word/media/image{0}.jpeg", max + 1), UriKind.Relative), System.Net.Mime.MediaTypeNames.Image.Jpeg);
  1169. PackageRelationship rel = word_document.CreateRelationship(img.Uri, TargetMode.Internal, "http://schemas.openxmlformats.org/officeDocument/2006/relationships/image");
  1170. using (Stream stream = img.GetStream(FileMode.Create, FileAccess.Write))
  1171. {
  1172. Stream s;
  1173. if (o is string)
  1174. s = new FileStream(o as string, FileMode.Open);
  1175. else
  1176. s = o as Stream;
  1177. using (s)
  1178. {
  1179. byte[] bytes = new byte[s.Length];
  1180. s.Read(bytes, 0, (int)s.Length);
  1181. stream.Write(bytes, 0, (int)s.Length);
  1182. }
  1183. }
  1184. Image newImg = new Image(this, rel);
  1185. images.Add(newImg);
  1186. return newImg;
  1187. }
  1188. /// <summary>
  1189. /// Save this document back to the location it was loaded from.
  1190. /// </summary>
  1191. /// <example>
  1192. /// <code>
  1193. /// // Load a document.
  1194. /// using (DocX document = DocX.Load(@"C:\Example\Test.docx"))
  1195. /// {
  1196. /// // Add an Image from a file.
  1197. /// document.AddImage(@"C:\Example\Image.jpg");
  1198. ///
  1199. /// // Save all changes made to this document.
  1200. /// document.Save();
  1201. /// }// Release this document from memory.
  1202. /// </code>
  1203. /// </example>
  1204. /// <seealso cref="DocX.SaveAs(string)"/>
  1205. /// <seealso cref="DocX.Create(System.IO.Stream)"/>
  1206. /// <seealso cref="DocX.Create(string)"/>
  1207. /// <seealso cref="DocX.Load(System.IO.Stream)"/>
  1208. /// <seealso cref="DocX.Load(string)"/>
  1209. public void Save()
  1210. {
  1211. if (package.PartExists(new Uri("/word/document.xml", UriKind.Relative)))
  1212. {
  1213. // Save the main document
  1214. using (TextWriter tw = new StreamWriter(package.GetPart(new Uri("/word/document.xml", UriKind.Relative)).GetStream(FileMode.Create, FileAccess.Write)))
  1215. mainDoc.Save(tw, SaveOptions.DisableFormatting);
  1216. }
  1217. // Close the document so that it can be saved.
  1218. Dispose();
  1219. #region Save this document back to a file or stream, that was specified by the user at save time.
  1220. if (filename != null)
  1221. {
  1222. using (FileStream fs = new FileStream(filename, FileMode.Create))
  1223. fs.Write(memoryStream.ToArray(), 0, (int)memoryStream.Length);
  1224. }
  1225. else
  1226. {
  1227. // Set the length of this stream to 0
  1228. stream.SetLength(0);
  1229. // Write to the beginning of the stream
  1230. stream.Position = 0;
  1231. memoryStream.WriteTo(stream);
  1232. stream.Close();
  1233. }
  1234. #endregion
  1235. // Re-open the document
  1236. package = Package.Open(memoryStream, FileMode.Open, FileAccess.ReadWrite);
  1237. }
  1238. /// <summary>
  1239. /// Save this document to a file.
  1240. /// </summary>
  1241. /// <param name="filename">The filename to save this document as.</param>
  1242. /// <example>
  1243. /// Load a document from one file and save it to another.
  1244. /// <code>
  1245. /// // Load a document using its fully qualified filename.
  1246. /// DocX document = DocX.Load(@"C:\Example\Test1.docx");
  1247. ///
  1248. /// // Insert a new Paragraph
  1249. /// document.InsertParagraph("Hello world!", false);
  1250. ///
  1251. /// // Save the document to a new location.
  1252. /// document.SaveAs(@"C:\Example\Test2.docx");
  1253. /// </code>
  1254. /// </example>
  1255. /// <example>
  1256. /// Load a document from a Stream and save it to a file.
  1257. /// <code>
  1258. /// DocX document;
  1259. /// using (FileStream fs1 = new FileStream(@"C:\Example\Test1.docx", FileMode.Open))
  1260. /// {
  1261. /// // Load a document using a stream.
  1262. /// document = DocX.Load(fs1);
  1263. ///
  1264. /// // Insert a new Paragraph
  1265. /// document.InsertParagraph("Hello world again!", false);
  1266. /// }
  1267. ///
  1268. /// // Save the document to a new location.
  1269. /// document.SaveAs(@"C:\Example\Test2.docx");
  1270. /// </code>
  1271. /// </example>
  1272. /// <seealso cref="DocX.Save()"/>
  1273. /// <seealso cref="DocX.Create(System.IO.Stream)"/>
  1274. /// <seealso cref="DocX.Create(string)"/>
  1275. /// <seealso cref="DocX.Load(System.IO.Stream)"/>
  1276. /// <seealso cref="DocX.Load(string)"/>
  1277. public void SaveAs(string filename)
  1278. {
  1279. this.filename = filename;
  1280. this.stream = null;
  1281. Save();
  1282. }
  1283. /// <summary>
  1284. /// Save this document to a Stream.
  1285. /// </summary>
  1286. /// <param name="stream">The Stream to save this document to.</param>
  1287. /// <example>
  1288. /// Load a document from a file and save it to a Stream.
  1289. /// <code>
  1290. /// // Place holder for a document.
  1291. /// DocX document;
  1292. ///
  1293. /// using (FileStream fs1 = new FileStream(@"C:\Example\Test1.docx", FileMode.Open))
  1294. /// {
  1295. /// // Load a document using a stream.
  1296. /// document = DocX.Load(fs1);
  1297. ///
  1298. /// // Insert a new Paragraph
  1299. /// document.InsertParagraph("Hello world again!", false);
  1300. /// }
  1301. ///
  1302. /// using (FileStream fs2 = new FileStream(@"C:\Example\Test2.docx", FileMode.Create))
  1303. /// {
  1304. /// // Save the document to a different stream.
  1305. /// document.SaveAs(fs2);
  1306. /// }
  1307. ///
  1308. /// // Release this document from memory.
  1309. /// document.Dispose();
  1310. /// </code>
  1311. /// </example>
  1312. /// <example>
  1313. /// Load a document from one Stream and save it to another.
  1314. /// <code>
  1315. /// DocX document;
  1316. /// using (FileStream fs1 = new FileStream(@"C:\Example\Test1.docx", FileMode.Open))
  1317. /// {
  1318. /// // Load a document using a stream.
  1319. /// document = DocX.Load(fs1);
  1320. ///
  1321. /// // Insert a new Paragraph
  1322. /// document.InsertParagraph("Hello world again!", false);
  1323. /// }
  1324. ///
  1325. /// using (FileStream fs2 = new FileStream(@"C:\Example\Test2.docx", FileMode.Create))
  1326. /// {
  1327. /// // Save the document to a different stream.
  1328. /// document.SaveAs(fs2);
  1329. /// }
  1330. /// </code>
  1331. /// </example>
  1332. /// <seealso cref="DocX.Save()"/>
  1333. /// <seealso cref="DocX.Create(System.IO.Stream)"/>
  1334. /// <seealso cref="DocX.Create(string)"/>
  1335. /// <seealso cref="DocX.Load(System.IO.Stream)"/>
  1336. /// <seealso cref="DocX.Load(string)"/>
  1337. public void SaveAs(Stream stream)
  1338. {
  1339. this.filename = null;
  1340. this.stream = stream;
  1341. Save();
  1342. }
  1343. /// <summary>
  1344. /// Add a custom property to this document. If a custom property already exists with the same name it will be replace. CustomProperty names are case insensitive.
  1345. /// </summary>
  1346. /// <param name="cp">The CustomProperty to add to this document.</param>
  1347. /// <example>
  1348. /// Add a custom properties of each type to a document.
  1349. /// <code>
  1350. /// // Load Example.docx
  1351. /// using (DocX document = DocX.Load(@"C:\Example\Test.docx"))
  1352. /// {
  1353. /// // A CustomProperty called forename which stores a string.
  1354. /// CustomProperty forename;
  1355. ///
  1356. /// // If this document does not contain a custom property called 'forename', create one.
  1357. /// if (!document.CustomProperties.ContainsKey("forename"))
  1358. /// {
  1359. /// // Create a new custom property called 'forename' and set its value.
  1360. /// document.AddCustomProperty(new CustomProperty("forename", "Cathal"));
  1361. /// }
  1362. ///
  1363. /// // Get this documents custom property called 'forename'.
  1364. /// forename = document.CustomProperties["forename"];
  1365. ///
  1366. /// // Print all of the information about this CustomProperty to Console.
  1367. /// Console.WriteLine(string.Format("Name: '{0}', Value: '{1}'\nPress any key...", forename.Name, forename.Value));
  1368. ///
  1369. /// // Save all changes made to this document.
  1370. /// document.Save();
  1371. /// } // Release this document from memory.
  1372. ///
  1373. /// // Wait for the user to press a key before exiting.
  1374. /// Console.ReadKey();
  1375. /// </code>
  1376. /// </example>
  1377. /// <example>
  1378. /// Extract a CustomProperty from a document called 'forname'. If it doesn't exist, create it. Finally print this custom properties details to Console.
  1379. /// <code>
  1380. /// using (DocX document = DocX.Load(@"C:\Example\Test.docx"))
  1381. /// {
  1382. /// // A CustomProperty called forename which stores a string.
  1383. /// CustomProperty forename;
  1384. ///
  1385. /// // If this document does not contain a custom property called 'forename', create one.
  1386. /// if (!document.CustomProperties.ContainsKey("forename"))
  1387. /// {
  1388. /// // Create a new custom property called 'forename' and set its value.
  1389. /// document.AddCustomProperty(new CustomProperty("forename", "Cathal"));
  1390. /// }
  1391. ///
  1392. /// // Get this documents custom property called 'forename'.
  1393. /// forename = document.CustomProperties["forename"];
  1394. ///
  1395. /// // Print all of the information about this CustomProperty to Console.
  1396. /// Console.WriteLine(string.Format("Name: '{0}', Value: '{1}'\nPress any key...", forename.Name, forename.Value));
  1397. ///
  1398. /// // Save all changes made to this document.
  1399. /// document.Save();
  1400. /// }// Release this document from memory.
  1401. ///
  1402. /// // Wait for the user to press a key before exiting.
  1403. /// Console.ReadKey();
  1404. /// </code>
  1405. /// </example>
  1406. /// <seealso cref="CustomProperty"/>
  1407. /// <seealso cref="CustomProperties"/>
  1408. public void AddCustomProperty(CustomProperty cp)
  1409. {
  1410. // If this document does not contain a customFilePropertyPart create one.
  1411. if(!package.PartExists(new Uri("/docProps/custom.xml", UriKind.Relative)))
  1412. CreateCustomPropertiesPart(this);
  1413. XDocument customPropDoc;
  1414. PackagePart customPropPart = package.GetPart(new Uri("/docProps/custom.xml", UriKind.Relative));
  1415. using (TextReader tr = new StreamReader(customPropPart.GetStream(FileMode.Open, FileAccess.Read)))
  1416. customPropDoc = XDocument.Load(tr, LoadOptions.PreserveWhitespace);
  1417. // Each custom property has a PID, get the highest PID in this document.
  1418. IEnumerable<int> pids =
  1419. (
  1420. from d in customPropDoc.Descendants()
  1421. where d.Name.LocalName == "property"
  1422. select int.Parse(d.Attribute(XName.Get("pid")).Value)
  1423. );
  1424. int pid = 1;
  1425. if (pids.Count() > 0)
  1426. pid = pids.Max();
  1427. // Check if a custom property already exists with this name
  1428. var customProperty =
  1429. (
  1430. from d in customPropDoc.Descendants()
  1431. where (d.Name.LocalName == "property") && (d.Attribute(XName.Get("name")).Value == cp.Name)
  1432. select d
  1433. ).SingleOrDefault();
  1434. // If a custom property with this name already exists remove it.
  1435. if (customProperty != null)
  1436. customProperty.Remove();
  1437. XElement propertiesElement = customPropDoc.Element(XName.Get("Properties", customPropertiesSchema.NamespaceName));
  1438. propertiesElement.Add
  1439. (
  1440. new XElement
  1441. (
  1442. XName.Get("property", customPropertiesSchema.NamespaceName),
  1443. new XAttribute("fmtid", "{D5CDD505-2E9C-101B-9397-08002B2CF9AE}"),
  1444. new XAttribute("pid", pid + 1),
  1445. new XAttribute("name", cp.Name),
  1446. new XElement(customVTypesSchema + cp.Type, cp.Value)
  1447. )
  1448. );
  1449. // Save the custom properties
  1450. using (TextWriter tw = new StreamWriter(customPropPart.GetStream(FileMode.Create, FileAccess.Write)))
  1451. customPropDoc.Save(tw, SaveOptions.DisableFormatting);
  1452. // Refresh all fields in this document which display this custom property.
  1453. UpdateCustomPropertyValue(this, cp.Name, cp.Value.ToString());
  1454. // Get all of the custom properties in this document
  1455. customProperties =
  1456. (
  1457. from p in customPropDoc.Descendants(XName.Get("property", customPropertiesSchema.NamespaceName))
  1458. let Name = p.Attribute(XName.Get("name")).Value
  1459. let Type = p.Descendants().Single().Name.LocalName
  1460. let Value = p.Descendants().Single().Value
  1461. select new CustomProperty(Name, Type, Value)
  1462. ).ToDictionary(p => p.Name, StringComparer.CurrentCultureIgnoreCase);
  1463. }
  1464. internal static void CreateCustomPropertiesPart(DocX document)
  1465. {
  1466. PackagePart customPropertiesPart = document.package.CreatePart(new Uri("/docProps/custom.xml", UriKind.Relative), "application/vnd.openxmlformats-officedocument.custom-properties+xml");
  1467. XDocument customPropDoc = new XDocument
  1468. (
  1469. new XDeclaration("1.0", "UTF-8", "yes"),
  1470. new XElement
  1471. (
  1472. XName.Get("Properties", customPropertiesSchema.NamespaceName),
  1473. new XAttribute(XNamespace.Xmlns + "vt", customVTypesSchema)
  1474. )
  1475. );
  1476. using (TextWriter tw = new StreamWriter(customPropertiesPart.GetStream(FileMode.Create, FileAccess.Write)))
  1477. customPropDoc.Save(tw, SaveOptions.DisableFormatting);
  1478. document.package.CreateRelationship(customPropertiesPart.Uri, TargetMode.Internal, "http://schemas.openxmlformats.org/officeDocument/2006/relationships/custom-properties");
  1479. }
  1480. internal static void UpdateCustomPropertyValue(DocX document, string customPropertyName, string customPropertyValue)
  1481. {
  1482. foreach (XElement e in document.mainDoc.Descendants(XName.Get("fldSimple", w.NamespaceName)))
  1483. {
  1484. if (e.Attribute(XName.Get("instr", w.NamespaceName)).Value.Equals(string.Format(@" DOCPROPERTY {0} \* MERGEFORMAT ", customPropertyName), StringComparison.CurrentCultureIgnoreCase))
  1485. {
  1486. XElement firstRun = e.Element(w + "r");
  1487. // Delete everything and insert updated text value
  1488. e.RemoveNodes();
  1489. XElement t = new XElement(w + "t", customPropertyValue);
  1490. Novacode.Text.PreserveSpace(t);
  1491. e.Add(new XElement(firstRun.Name, firstRun.Attributes(), firstRun.Element(XName.Get("rPr", w.NamespaceName)), t));
  1492. }
  1493. }
  1494. }
  1495. internal static void RenumberIDs(DocX document)
  1496. {
  1497. IEnumerable<XAttribute> trackerIDs =
  1498. (from d in document.mainDoc.Descendants()
  1499. where d.Name.LocalName == "ins" || d.Name.LocalName == "del"
  1500. select d.Attribute(XName.Get("id", "http://schemas.openxmlformats.org/wordprocessingml/2006/main")));
  1501. for (int i = 0; i < trackerIDs.Count(); i++)
  1502. trackerIDs.ElementAt(i).Value = i.ToString();
  1503. }
  1504. /// <summary>
  1505. /// Replace text in this document, not case sensetive.
  1506. /// </summary>
  1507. /// <example>
  1508. /// Replace every instance of "old" in this document with "new".
  1509. /// <code>
  1510. /// // Load a document.
  1511. /// using (DocX document = DocX.Load(@"C:\Example\Test.docx"))
  1512. /// {
  1513. /// // Replace every instance of "old" in this document with "new".
  1514. /// document.ReplaceText("old", "new", false, RegexOptions.IgnoreCase);
  1515. ///
  1516. /// // Save all changes made to this document.
  1517. /// document.Save();
  1518. /// }// Release this document from memory.
  1519. /// </code>
  1520. /// </example>
  1521. /// <param name="oldValue">The text to replace.</param>
  1522. /// <param name="newValue">The new text to insert.</param>
  1523. /// <param name="trackChanges">Should this change be tracked?</param>
  1524. /// <param name="options">RegexOptions to use for this text replace.</param>
  1525. public void ReplaceText(string oldValue, string newValue, bool trackChanges, RegexOptions options)
  1526. {
  1527. foreach (Paragraph p in paragraphs)
  1528. p.ReplaceText(oldValue, newValue, trackChanges, options);
  1529. }
  1530. /// <summary>
  1531. /// Replace text in this document, case sensetive.
  1532. /// </summary>
  1533. /// <example>
  1534. /// Replace every instance of "old" in this document with "new".
  1535. /// <code>
  1536. /// // Load a document.
  1537. /// using (DocX document = DocX.Load(@"C:\Example\Test.docx"))
  1538. /// {
  1539. /// // Replace every instance of "old" in this document with "new".
  1540. /// document.ReplaceText("old", "new", false);
  1541. ///
  1542. /// // Save all changes made to this document.
  1543. /// document.Save();
  1544. /// }// Release this document from memory.
  1545. /// </code>
  1546. /// </example>
  1547. /// <param name="oldValue">The text to replace.</param>
  1548. /// <param name="newValue">The new text to insert.</param>
  1549. /// <param name="trackChanges">Should this change be tracked?</param>
  1550. /// <param name="options">RegexOptions to use for this text replace.</param>
  1551. public void ReplaceText(string oldValue, string newValue, bool trackChanges)
  1552. {
  1553. ReplaceText(oldValue, newValue, trackChanges, RegexOptions.None);
  1554. }
  1555. #region IDisposable Members
  1556. /// <summary>
  1557. /// Releases all resources used by this document.
  1558. /// </summary>
  1559. /// <example>
  1560. /// If you take advantage of the using keyword, Dispose() is automatically called for you.
  1561. /// <code>
  1562. /// // Load document.
  1563. /// using (DocX document = DocX.Load(@"C:\Example\Test.docx"))
  1564. /// {
  1565. /// // The document is only in memory while in this scope.
  1566. ///
  1567. /// }// Dispose() is automatically called at this point.
  1568. /// </code>
  1569. /// </example>
  1570. /// <example>
  1571. /// This example is equilivant to the one above example.
  1572. /// <code>
  1573. /// // Load document.
  1574. /// DocX document = DocX.Load(@"C:\Example\Test.docx");
  1575. ///
  1576. /// // Do something with the document here.
  1577. ///
  1578. /// // Dispose of the document.
  1579. /// document.Dispose();
  1580. /// </code>
  1581. /// </example>
  1582. public void Dispose()
  1583. {
  1584. package.Close();
  1585. }
  1586. #endregion
  1587. }
  1588. }