Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

DocX.cs 195KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Collections.ObjectModel;
  4. using System.IO;
  5. using System.IO.Packaging;
  6. using System.Linq;
  7. using System.Security.Cryptography;
  8. using System.Text;
  9. using System.Text.RegularExpressions;
  10. using System.Xml;
  11. using System.Xml.Linq;
  12. namespace Novacode
  13. {
  14. /// <summary>
  15. /// Represents a document.
  16. /// </summary>
  17. public class DocX : Container, IDisposable
  18. {
  19. #region Namespaces
  20. static internal XNamespace w = "http://schemas.openxmlformats.org/wordprocessingml/2006/main";
  21. static internal XNamespace rel = "http://schemas.openxmlformats.org/package/2006/relationships";
  22. static internal XNamespace r = "http://schemas.openxmlformats.org/officeDocument/2006/relationships";
  23. static internal XNamespace m = "http://schemas.openxmlformats.org/officeDocument/2006/math";
  24. static internal XNamespace customPropertiesSchema = "http://schemas.openxmlformats.org/officeDocument/2006/custom-properties";
  25. static internal XNamespace customVTypesSchema = "http://schemas.openxmlformats.org/officeDocument/2006/docPropsVTypes";
  26. static internal XNamespace wp = "http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing";
  27. static internal XNamespace a = "http://schemas.openxmlformats.org/drawingml/2006/main";
  28. static internal XNamespace c = "http://schemas.openxmlformats.org/drawingml/2006/chart";
  29. static internal XNamespace v = "urn:schemas-microsoft-com:vml";
  30. internal static XNamespace n = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/numbering";
  31. #endregion
  32. internal float getMarginAttribute(XName name)
  33. {
  34. XElement body = mainDoc.Root.Element(XName.Get("body", w.NamespaceName));
  35. XElement sectPr = body.Element(XName.Get("sectPr", w.NamespaceName));
  36. XElement pgMar = sectPr?.Element(XName.Get("pgMar", w.NamespaceName));
  37. XAttribute top = pgMar?.Attribute(name);
  38. if (top != null)
  39. {
  40. float f;
  41. if (float.TryParse(top.Value, out f))
  42. return (int)(f / 20.0f);
  43. }
  44. return 0;
  45. }
  46. internal void setMarginAttribute(XName xName, float value)
  47. {
  48. XElement body = mainDoc.Root.Element(XName.Get("body", w.NamespaceName));
  49. XElement sectPr = body.Element(XName.Get("sectPr", w.NamespaceName));
  50. XElement pgMar = sectPr?.Element(XName.Get("pgMar", w.NamespaceName));
  51. XAttribute top = pgMar?.Attribute(xName);
  52. top?.SetValue(value * 20);
  53. }
  54. public BookmarkCollection Bookmarks
  55. {
  56. get
  57. {
  58. BookmarkCollection bookmarks = new BookmarkCollection();
  59. foreach (Paragraph paragraph in Paragraphs)
  60. bookmarks.AddRange(paragraph.GetBookmarks());
  61. return bookmarks;
  62. }
  63. }
  64. /// <summary>
  65. /// Top margin value in points. 1pt = 1/72 of an inch. Word internally writes docx using units = 1/20th of a point.
  66. /// </summary>
  67. public float MarginTop
  68. {
  69. get
  70. {
  71. return getMarginAttribute(XName.Get("top", w.NamespaceName));
  72. }
  73. set
  74. {
  75. setMarginAttribute(XName.Get("top", w.NamespaceName), value);
  76. }
  77. }
  78. /// <summary>
  79. /// Bottom margin value in points. 1pt = 1/72 of an inch. Word internally writes docx using units = 1/20th of a point.
  80. /// </summary>
  81. public float MarginBottom
  82. {
  83. get
  84. {
  85. return getMarginAttribute(XName.Get("bottom", w.NamespaceName));
  86. }
  87. set
  88. {
  89. setMarginAttribute(XName.Get("bottom", w.NamespaceName), value);
  90. }
  91. }
  92. /// <summary>
  93. /// Left margin value in points. 1pt = 1/72 of an inch. Word internally writes docx using units = 1/20th of a point.
  94. /// </summary>
  95. public float MarginLeft
  96. {
  97. get
  98. {
  99. return getMarginAttribute(XName.Get("left", w.NamespaceName));
  100. }
  101. set
  102. {
  103. setMarginAttribute(XName.Get("left", w.NamespaceName), value);
  104. }
  105. }
  106. /// <summary>
  107. /// Right margin value in points. 1pt = 1/72 of an inch. Word internally writes docx using units = 1/20th of a point.
  108. /// </summary>
  109. public float MarginRight
  110. {
  111. get
  112. {
  113. return getMarginAttribute(XName.Get("right", w.NamespaceName));
  114. }
  115. set
  116. {
  117. setMarginAttribute(XName.Get("right", w.NamespaceName), value);
  118. }
  119. }
  120. /// <summary>
  121. /// Header margin value in points. 1pt = 1/72 of an inch. Word internally writes docx using units = 1/20th of a point.
  122. /// </summary>
  123. public float MarginHeader
  124. {
  125. get
  126. {
  127. return getMarginAttribute(XName.Get("header", w.NamespaceName));
  128. }
  129. set
  130. {
  131. setMarginAttribute(XName.Get("header", w.NamespaceName), value);
  132. }
  133. }
  134. /// <summary>
  135. /// Footer margin value in points. 1pt = 1/72 of an inch. Word internally writes docx using units = 1/20th of a point.
  136. /// </summary>
  137. public float MarginFooter
  138. {
  139. get
  140. {
  141. return getMarginAttribute(XName.Get("footer", w.NamespaceName));
  142. }
  143. set
  144. {
  145. setMarginAttribute(XName.Get("footer", w.NamespaceName), value);
  146. }
  147. }
  148. /// <summary>
  149. /// Mirror Margins boolean value. True when margins has to be mirrored.
  150. /// </summary>
  151. internal bool getMirrorMargins(XName name)
  152. {
  153. XElement body = mainDoc.Root.Element(XName.Get("body", DocX.w.NamespaceName));
  154. XElement sectPr = body.Element(XName.Get("sectPr", DocX.w.NamespaceName));
  155. if (sectPr != null)
  156. {
  157. XElement MarMirror = sectPr.Element(XName.Get("mirrorMargins", DocX.w.NamespaceName));
  158. if (MarMirror != null)
  159. {
  160. return true;
  161. }
  162. }
  163. return false;
  164. }
  165. internal void setMirrorMargins(XName name, bool value)
  166. {
  167. XElement body = mainDoc.Root.Element(XName.Get("body", DocX.w.NamespaceName));
  168. XElement sectPr = body.Element(XName.Get("sectPr", DocX.w.NamespaceName));
  169. if (sectPr != null)
  170. {
  171. XElement MarMirror = sectPr.Element(XName.Get("mirrorMargins", DocX.w.NamespaceName));
  172. if (MarMirror != null)
  173. {
  174. if (!value)
  175. {
  176. MarMirror.Remove();
  177. }
  178. }
  179. else
  180. {
  181. sectPr.Add(new XElement(w + "mirrorMargins", string.Empty));
  182. }
  183. }
  184. }
  185. public bool MirrorMargins
  186. {
  187. get
  188. {
  189. return getMirrorMargins(XName.Get("mirrorMargins", DocX.w.NamespaceName));
  190. }
  191. set
  192. {
  193. setMirrorMargins(XName.Get("mirrorMargins", DocX.w.NamespaceName), value);
  194. }
  195. }
  196. /// <summary>
  197. /// Page width value in points. 1pt = 1/72 of an inch. Word internally writes docx using units = 1/20th of a point.
  198. /// </summary>
  199. public float PageWidth
  200. {
  201. get
  202. {
  203. XElement body = mainDoc.Root.Element(XName.Get("body", w.NamespaceName));
  204. XElement sectPr = body.Element(XName.Get("sectPr", w.NamespaceName));
  205. XElement pgSz = sectPr?.Element(XName.Get("pgSz", w.NamespaceName));
  206. if (pgSz != null)
  207. {
  208. XAttribute w = pgSz.Attribute(XName.Get("w", DocX.w.NamespaceName));
  209. if (w != null)
  210. {
  211. float f;
  212. if (float.TryParse(w.Value, out f))
  213. return (int)(f / 20.0f);
  214. }
  215. }
  216. return (12240.0f / 20.0f);
  217. }
  218. set
  219. {
  220. XElement body = mainDoc.Root.Element(XName.Get("body", w.NamespaceName));
  221. XElement sectPr = body?.Element(XName.Get("sectPr", w.NamespaceName));
  222. XElement pgSz = sectPr?.Element(XName.Get("pgSz", w.NamespaceName));
  223. pgSz?.SetAttributeValue(XName.Get("w", w.NamespaceName), value * 20);
  224. }
  225. }
  226. /// <summary>
  227. /// Page height value in points. 1pt = 1/72 of an inch. Word internally writes docx using units = 1/20th of a point.
  228. /// </summary>
  229. public float PageHeight
  230. {
  231. get
  232. {
  233. XElement body = mainDoc.Root.Element(XName.Get("body", w.NamespaceName));
  234. XElement sectPr = body.Element(XName.Get("sectPr", w.NamespaceName));
  235. if (sectPr != null)
  236. {
  237. XElement pgSz = sectPr.Element(XName.Get("pgSz", w.NamespaceName));
  238. if (pgSz != null)
  239. {
  240. XAttribute w = pgSz.Attribute(XName.Get("h", DocX.w.NamespaceName));
  241. if (w != null)
  242. {
  243. float f;
  244. if (float.TryParse(w.Value, out f))
  245. return (int)(f / 20.0f);
  246. }
  247. }
  248. }
  249. return (15840.0f / 20.0f);
  250. }
  251. set
  252. {
  253. XElement body = mainDoc.Root.Element(XName.Get("body", w.NamespaceName));
  254. if (body != null)
  255. {
  256. XElement sectPr = body.Element(XName.Get("sectPr", w.NamespaceName));
  257. if (sectPr != null)
  258. {
  259. XElement pgSz = sectPr.Element(XName.Get("pgSz", w.NamespaceName));
  260. if (pgSz != null)
  261. {
  262. pgSz.SetAttributeValue(XName.Get("h", w.NamespaceName), value * 20);
  263. }
  264. }
  265. }
  266. }
  267. }
  268. /// <summary>
  269. /// Returns true if any editing restrictions are imposed on this document.
  270. /// </summary>
  271. /// <example>
  272. /// <code>
  273. /// // Create a new document.
  274. /// using (DocX document = DocX.Create(@"Test.docx"))
  275. /// {
  276. /// if(document.isProtected)
  277. /// Console.WriteLine("Protected");
  278. /// else
  279. /// Console.WriteLine("Not protected");
  280. ///
  281. /// // Save the document.
  282. /// document.Save();
  283. /// }
  284. /// </code>
  285. /// </example>
  286. /// <seealso cref="AddProtection(EditRestrictions)"/>
  287. /// <seealso cref="RemoveProtection"/>
  288. /// <seealso cref="GetProtectionType"/>
  289. public bool isProtected
  290. {
  291. get
  292. {
  293. return settings.Descendants(XName.Get("documentProtection", w.NamespaceName)).Count() > 0;
  294. }
  295. }
  296. /// <summary>
  297. /// Returns the type of editing protection imposed on this document.
  298. /// </summary>
  299. /// <returns>The type of editing protection imposed on this document.</returns>
  300. /// <example>
  301. /// <code>
  302. /// Create a new document.
  303. /// using (DocX document = DocX.Create(@"Test.docx"))
  304. /// {
  305. /// // Make sure the document is protected before checking the protection type.
  306. /// if (document.isProtected)
  307. /// {
  308. /// EditRestrictions protection = document.GetProtectionType();
  309. /// Console.WriteLine("Document is protected using " + protection.ToString());
  310. /// }
  311. ///
  312. /// else
  313. /// Console.WriteLine("Document is not protected.");
  314. ///
  315. /// // Save the document.
  316. /// document.Save();
  317. /// }
  318. /// </code>
  319. /// </example>
  320. /// <seealso cref="AddProtection(EditRestrictions)"/>
  321. /// <seealso cref="RemoveProtection"/>
  322. /// <seealso cref="isProtected"/>
  323. public EditRestrictions GetProtectionType()
  324. {
  325. if (isProtected)
  326. {
  327. XElement documentProtection = settings.Descendants(XName.Get("documentProtection", w.NamespaceName)).FirstOrDefault();
  328. string edit_type = documentProtection.Attribute(XName.Get("edit", w.NamespaceName)).Value;
  329. return (EditRestrictions)Enum.Parse(typeof(EditRestrictions), edit_type);
  330. }
  331. return EditRestrictions.none;
  332. }
  333. /// <summary>
  334. /// Add editing protection to this document.
  335. /// </summary>
  336. /// <param name="er">The type of protection to add to this document.</param>
  337. /// <example>
  338. /// <code>
  339. /// // Create a new document.
  340. /// using (DocX document = DocX.Create(@"Test.docx"))
  341. /// {
  342. /// // Allow no editing, only the adding of comment.
  343. /// document.AddProtection(EditRestrictions.comments);
  344. ///
  345. /// // Save the document.
  346. /// document.Save();
  347. /// }
  348. /// </code>
  349. /// </example>
  350. /// <seealso cref="RemoveProtection"/>
  351. /// <seealso cref="GetProtectionType"/>
  352. /// <seealso cref="isProtected"/>
  353. public void AddProtection(EditRestrictions er)
  354. {
  355. // Call remove protection before adding a new protection element.
  356. RemoveProtection();
  357. if (er == EditRestrictions.none)
  358. return;
  359. XElement documentProtection = new XElement(XName.Get("documentProtection", w.NamespaceName));
  360. documentProtection.Add(new XAttribute(XName.Get("edit", w.NamespaceName), er.ToString()));
  361. documentProtection.Add(new XAttribute(XName.Get("enforcement", w.NamespaceName), "1"));
  362. settings.Root.AddFirst(documentProtection);
  363. }
  364. public void AddProtection(EditRestrictions er, string strPassword)
  365. {
  366. // http://blogs.msdn.com/b/vsod/archive/2010/04/05/how-to-set-the-editing-restrictions-in-word-using-open-xml-sdk-2-0.aspx
  367. // Call remove protection before adding a new protection element.
  368. RemoveProtection();
  369. if (er == EditRestrictions.none)
  370. return;
  371. XElement documentProtection = new XElement(XName.Get("documentProtection", w.NamespaceName));
  372. documentProtection.Add(new XAttribute(XName.Get("edit", w.NamespaceName), er.ToString()));
  373. documentProtection.Add(new XAttribute(XName.Get("enforcement", w.NamespaceName), "1"));
  374. int[] InitialCodeArray = { 0xE1F0, 0x1D0F, 0xCC9C, 0x84C0, 0x110C, 0x0E10, 0xF1CE, 0x313E, 0x1872, 0xE139, 0xD40F, 0x84F9, 0x280C, 0xA96A, 0x4EC3 };
  375. int[,] EncryptionMatrix = new int[15, 7]
  376. {
  377. /* char 1 */ {0xAEFC, 0x4DD9, 0x9BB2, 0x2745, 0x4E8A, 0x9D14, 0x2A09},
  378. /* char 2 */ {0x7B61, 0xF6C2, 0xFDA5, 0xEB6B, 0xC6F7, 0x9DCF, 0x2BBF},
  379. /* char 3 */ {0x4563, 0x8AC6, 0x05AD, 0x0B5A, 0x16B4, 0x2D68, 0x5AD0},
  380. /* char 4 */ {0x0375, 0x06EA, 0x0DD4, 0x1BA8, 0x3750, 0x6EA0, 0xDD40},
  381. /* char 5 */ {0xD849, 0xA0B3, 0x5147, 0xA28E, 0x553D, 0xAA7A, 0x44D5},
  382. /* char 6 */ {0x6F45, 0xDE8A, 0xAD35, 0x4A4B, 0x9496, 0x390D, 0x721A},
  383. /* char 7 */ {0xEB23, 0xC667, 0x9CEF, 0x29FF, 0x53FE, 0xA7FC, 0x5FD9},
  384. /* char 8 */ {0x47D3, 0x8FA6, 0x0F6D, 0x1EDA, 0x3DB4, 0x7B68, 0xF6D0},
  385. /* char 9 */ {0xB861, 0x60E3, 0xC1C6, 0x93AD, 0x377B, 0x6EF6, 0xDDEC},
  386. /* char 10 */ {0x45A0, 0x8B40, 0x06A1, 0x0D42, 0x1A84, 0x3508, 0x6A10},
  387. /* char 11 */ {0xAA51, 0x4483, 0x8906, 0x022D, 0x045A, 0x08B4, 0x1168},
  388. /* char 12 */ {0x76B4, 0xED68, 0xCAF1, 0x85C3, 0x1BA7, 0x374E, 0x6E9C},
  389. /* char 13 */ {0x3730, 0x6E60, 0xDCC0, 0xA9A1, 0x4363, 0x86C6, 0x1DAD},
  390. /* char 14 */ {0x3331, 0x6662, 0xCCC4, 0x89A9, 0x0373, 0x06E6, 0x0DCC},
  391. /* char 15 */ {0x1021, 0x2042, 0x4084, 0x8108, 0x1231, 0x2462, 0x48C4}
  392. };
  393. // Generate the Salt
  394. byte[] arrSalt = new byte[16];
  395. RandomNumberGenerator rand = new RNGCryptoServiceProvider();
  396. rand.GetNonZeroBytes(arrSalt);
  397. //Array to hold Key Values
  398. byte[] generatedKey = new byte[4];
  399. //Maximum length of the password is 15 chars.
  400. int intMaxPasswordLength = 15;
  401. if (!String.IsNullOrEmpty(strPassword))
  402. {
  403. strPassword = strPassword.Substring(0, Math.Min(strPassword.Length, intMaxPasswordLength));
  404. byte[] arrByteChars = new byte[strPassword.Length];
  405. for (int intLoop = 0; intLoop < strPassword.Length; intLoop++)
  406. {
  407. int intTemp = Convert.ToInt32(strPassword[intLoop]);
  408. arrByteChars[intLoop] = Convert.ToByte(intTemp & 0x00FF);
  409. if (arrByteChars[intLoop] == 0)
  410. arrByteChars[intLoop] = Convert.ToByte((intTemp & 0xFF00) >> 8);
  411. }
  412. int intHighOrderWord = InitialCodeArray[arrByteChars.Length - 1];
  413. for (int intLoop = 0; intLoop < arrByteChars.Length; intLoop++)
  414. {
  415. int tmp = intMaxPasswordLength - arrByteChars.Length + intLoop;
  416. for (int intBit = 0; intBit < 7; intBit++)
  417. {
  418. if ((arrByteChars[intLoop] & (0x0001 << intBit)) != 0)
  419. {
  420. intHighOrderWord ^= EncryptionMatrix[tmp, intBit];
  421. }
  422. }
  423. }
  424. int intLowOrderWord = 0;
  425. // For each character in the strPassword, going backwards
  426. for (int intLoopChar = arrByteChars.Length - 1; intLoopChar >= 0; intLoopChar--)
  427. {
  428. intLowOrderWord = (((intLowOrderWord >> 14) & 0x0001) | ((intLowOrderWord << 1) & 0x7FFF)) ^ arrByteChars[intLoopChar];
  429. }
  430. intLowOrderWord = (((intLowOrderWord >> 14) & 0x0001) | ((intLowOrderWord << 1) & 0x7FFF)) ^ arrByteChars.Length ^ 0xCE4B;
  431. // Combine the Low and High Order Word
  432. int intCombinedkey = (intHighOrderWord << 16) + intLowOrderWord;
  433. // The byte order of the result shall be reversed [Example: 0x64CEED7E becomes 7EEDCE64. end example],
  434. // and that value shall be hashed as defined by the attribute values.
  435. for (int intTemp = 0; intTemp < 4; intTemp++)
  436. {
  437. generatedKey[intTemp] = Convert.ToByte(((uint)(intCombinedkey & (0x000000FF << (intTemp * 8)))) >> (intTemp * 8));
  438. }
  439. }
  440. StringBuilder sb = new StringBuilder();
  441. for (int intTemp = 0; intTemp < 4; intTemp++)
  442. {
  443. sb.Append(Convert.ToString(generatedKey[intTemp], 16));
  444. }
  445. generatedKey = Encoding.Unicode.GetBytes(sb.ToString().ToUpper());
  446. byte[] tmpArray1 = generatedKey;
  447. byte[] tmpArray2 = arrSalt;
  448. byte[] tempKey = new byte[tmpArray1.Length + tmpArray2.Length];
  449. Buffer.BlockCopy(tmpArray2, 0, tempKey, 0, tmpArray2.Length);
  450. Buffer.BlockCopy(tmpArray1, 0, tempKey, tmpArray2.Length, tmpArray1.Length);
  451. generatedKey = tempKey;
  452. int iterations = 100000;
  453. HashAlgorithm sha1 = new SHA1Managed();
  454. generatedKey = sha1.ComputeHash(generatedKey);
  455. byte[] iterator = new byte[4];
  456. for (int intTmp = 0; intTmp < iterations; intTmp++)
  457. {
  458. iterator[0] = Convert.ToByte((intTmp & 0x000000FF) >> 0);
  459. iterator[1] = Convert.ToByte((intTmp & 0x0000FF00) >> 8);
  460. iterator[2] = Convert.ToByte((intTmp & 0x00FF0000) >> 16);
  461. iterator[3] = Convert.ToByte((intTmp & 0xFF000000) >> 24);
  462. generatedKey = concatByteArrays(iterator, generatedKey);
  463. generatedKey = sha1.ComputeHash(generatedKey);
  464. }
  465. documentProtection.Add(new XAttribute(XName.Get("cryptProviderType", w.NamespaceName), "rsaFull"));
  466. documentProtection.Add(new XAttribute(XName.Get("cryptAlgorithmClass", w.NamespaceName), "hash"));
  467. documentProtection.Add(new XAttribute(XName.Get("cryptAlgorithmType", w.NamespaceName), "typeAny"));
  468. documentProtection.Add(new XAttribute(XName.Get("cryptAlgorithmSid", w.NamespaceName), "4")); // SHA1
  469. documentProtection.Add(new XAttribute(XName.Get("cryptSpinCount", w.NamespaceName), iterations.ToString()));
  470. documentProtection.Add(new XAttribute(XName.Get("hash", w.NamespaceName), Convert.ToBase64String(generatedKey)));
  471. documentProtection.Add(new XAttribute(XName.Get("salt", w.NamespaceName), Convert.ToBase64String(arrSalt)));
  472. settings.Root.AddFirst(documentProtection);
  473. }
  474. private byte[] concatByteArrays(byte[] array1, byte[] array2)
  475. {
  476. byte[] result = new byte[array1.Length + array2.Length];
  477. Buffer.BlockCopy(array2, 0, result, 0, array2.Length);
  478. Buffer.BlockCopy(array1, 0, result, array2.Length, array1.Length);
  479. return result;
  480. }
  481. /// <summary>
  482. /// Remove editing protection from this document.
  483. /// </summary>
  484. /// <example>
  485. /// <code>
  486. /// // Create a new document.
  487. /// using (DocX document = DocX.Create(@"Test.docx"))
  488. /// {
  489. /// // Remove any editing restrictions that are imposed on this document.
  490. /// document.RemoveProtection();
  491. ///
  492. /// // Save the document.
  493. /// document.Save();
  494. /// }
  495. /// </code>
  496. /// </example>
  497. /// <seealso cref="AddProtection(EditRestrictions)"/>
  498. /// <seealso cref="GetProtectionType"/>
  499. /// <seealso cref="isProtected"/>
  500. public void RemoveProtection()
  501. {
  502. // Remove every node of type documentProtection.
  503. settings.Descendants(XName.Get("documentProtection", w.NamespaceName)).Remove();
  504. }
  505. public PageLayout PageLayout
  506. {
  507. get
  508. {
  509. XElement sectPr = Xml.Element(XName.Get("sectPr", w.NamespaceName));
  510. if (sectPr == null)
  511. {
  512. Xml.SetElementValue(XName.Get("sectPr", w.NamespaceName), string.Empty);
  513. sectPr = Xml.Element(XName.Get("sectPr", w.NamespaceName));
  514. }
  515. return new PageLayout(this, sectPr);
  516. }
  517. }
  518. /// <summary>
  519. /// Returns a collection of Headers in this Document.
  520. /// A document typically contains three Headers.
  521. /// A default one (odd), one for the first page and one for even pages.
  522. /// </summary>
  523. /// <example>
  524. /// <code>
  525. /// // Create a document.
  526. /// using (DocX document = DocX.Create(@"Test.docx"))
  527. /// {
  528. /// // Add header support to this document.
  529. /// document.AddHeaders();
  530. ///
  531. /// // Get a collection of all headers in this document.
  532. /// Headers headers = document.Headers;
  533. ///
  534. /// // The header used for the first page of this document.
  535. /// Header first = headers.first;
  536. ///
  537. /// // The header used for odd pages of this document.
  538. /// Header odd = headers.odd;
  539. ///
  540. /// // The header used for even pages of this document.
  541. /// Header even = headers.even;
  542. /// }
  543. /// </code>
  544. /// </example>
  545. public Headers Headers
  546. {
  547. get
  548. {
  549. return headers;
  550. }
  551. }
  552. private Headers headers;
  553. /// <summary>
  554. /// Returns a collection of Footers in this Document.
  555. /// A document typically contains three Footers.
  556. /// A default one (odd), one for the first page and one for even pages.
  557. /// </summary>
  558. /// <example>
  559. /// <code>
  560. /// // Create a document.
  561. /// using (DocX document = DocX.Create(@"Test.docx"))
  562. /// {
  563. /// // Add footer support to this document.
  564. /// document.AddFooters();
  565. ///
  566. /// // Get a collection of all footers in this document.
  567. /// Footers footers = document.Footers;
  568. ///
  569. /// // The footer used for the first page of this document.
  570. /// Footer first = footers.first;
  571. ///
  572. /// // The footer used for odd pages of this document.
  573. /// Footer odd = footers.odd;
  574. ///
  575. /// // The footer used for even pages of this document.
  576. /// Footer even = footers.even;
  577. /// }
  578. /// </code>
  579. /// </example>
  580. public Footers Footers
  581. {
  582. get
  583. {
  584. return footers;
  585. }
  586. }
  587. private Footers footers;
  588. /// <summary>
  589. /// Should the Document use different Headers and Footers for odd and even pages?
  590. /// </summary>
  591. /// <example>
  592. /// <code>
  593. /// // Create a document.
  594. /// using (DocX document = DocX.Create(@"Test.docx"))
  595. /// {
  596. /// // Add header support to this document.
  597. /// document.AddHeaders();
  598. ///
  599. /// // Get a collection of all headers in this document.
  600. /// Headers headers = document.Headers;
  601. ///
  602. /// // The header used for odd pages of this document.
  603. /// Header odd = headers.odd;
  604. ///
  605. /// // The header used for even pages of this document.
  606. /// Header even = headers.even;
  607. ///
  608. /// // Force the document to use a different header for odd and even pages.
  609. /// document.DifferentOddAndEvenPages = true;
  610. ///
  611. /// // Content can be added to the Headers in the same manor that it would be added to the main document.
  612. /// Paragraph p1 = odd.InsertParagraph();
  613. /// p1.Append("This is the odd pages header.");
  614. ///
  615. /// Paragraph p2 = even.InsertParagraph();
  616. /// p2.Append("This is the even pages header.");
  617. ///
  618. /// // Save all changes to this document.
  619. /// document.Save();
  620. /// }// Release this document from memory.
  621. /// </code>
  622. /// </example>
  623. public bool DifferentOddAndEvenPages
  624. {
  625. get
  626. {
  627. XDocument settings;
  628. using (TextReader tr = new StreamReader(settingsPart.GetStream()))
  629. settings = XDocument.Load(tr);
  630. XElement evenAndOddHeaders = settings.Root.Element(w + "evenAndOddHeaders");
  631. return evenAndOddHeaders != null;
  632. }
  633. set
  634. {
  635. XDocument settings;
  636. using (TextReader tr = new StreamReader(settingsPart.GetStream()))
  637. settings = XDocument.Load(tr);
  638. XElement evenAndOddHeaders = settings.Root.Element(w + "evenAndOddHeaders");
  639. if (evenAndOddHeaders == null)
  640. {
  641. if (value)
  642. settings.Root.AddFirst(new XElement(w + "evenAndOddHeaders"));
  643. }
  644. else
  645. {
  646. if (!value)
  647. evenAndOddHeaders.Remove();
  648. }
  649. using (TextWriter tw = new StreamWriter(new PackagePartStream(settingsPart.GetStream())))
  650. settings.Save(tw);
  651. }
  652. }
  653. /// <summary>
  654. /// Should the Document use an independent Header and Footer for the first page?
  655. /// </summary>
  656. /// <example>
  657. /// // Create a document.
  658. /// using (DocX document = DocX.Create(@"Test.docx"))
  659. /// {
  660. /// // Add header support to this document.
  661. /// document.AddHeaders();
  662. ///
  663. /// // The header used for the first page of this document.
  664. /// Header first = document.Headers.first;
  665. ///
  666. /// // Force the document to use a different header for first page.
  667. /// document.DifferentFirstPage = true;
  668. ///
  669. /// // Content can be added to the Headers in the same manor that it would be added to the main document.
  670. /// Paragraph p = first.InsertParagraph();
  671. /// p.Append("This is the first pages header.");
  672. ///
  673. /// // Save all changes to this document.
  674. /// document.Save();
  675. /// }// Release this document from memory.
  676. /// </example>
  677. public bool DifferentFirstPage
  678. {
  679. get
  680. {
  681. XElement body = mainDoc.Root.Element(w + "body");
  682. XElement sectPr = body.Element(w + "sectPr");
  683. XElement titlePg = sectPr?.Element(w + "titlePg");
  684. return titlePg != null;
  685. }
  686. set
  687. {
  688. XElement body = mainDoc.Root.Element(w + "body");
  689. body.Add(new XElement(w + "sectPr", string.Empty));
  690. var sectPr = body.Element(w + "sectPr");
  691. var titlePg = sectPr.Element(w + "titlePg");
  692. if (titlePg == null)
  693. {
  694. if (value)
  695. sectPr.Add(new XElement(w + "titlePg", string.Empty));
  696. }
  697. else
  698. {
  699. if (!value)
  700. titlePg.Remove();
  701. }
  702. }
  703. }
  704. private Header GetHeaderByType(string type)
  705. {
  706. return (Header)GetHeaderOrFooterByType(type, true);
  707. }
  708. private Footer GetFooterByType(string type)
  709. {
  710. return (Footer)GetHeaderOrFooterByType(type, false);
  711. }
  712. private object GetHeaderOrFooterByType(string type, bool isHeader)
  713. {
  714. // Switch which handles either case Header\Footer, this just cuts down on code duplication.
  715. string reference = "footerReference";
  716. if (isHeader)
  717. reference = "headerReference";
  718. // Get the Id of the [default, even or first] [Header or Footer]
  719. string Id =
  720. (
  721. from e in mainDoc.Descendants(XName.Get("body", w.NamespaceName)).Descendants()
  722. where (e.Name.LocalName == reference) && (e.Attribute(w + "type").Value == type)
  723. select e.Attribute(r + "id").Value
  724. ).LastOrDefault();
  725. if (Id != null)
  726. {
  727. // Get the Xml file for this Header or Footer.
  728. Uri partUri = mainPart.GetRelationship(Id).TargetUri;
  729. // Weird problem with PackaePart API.
  730. if (!partUri.OriginalString.StartsWith("/word/"))
  731. partUri = new Uri("/word/" + partUri.OriginalString, UriKind.Relative);
  732. // Get the Part and open a stream to get the Xml file.
  733. PackagePart part = package.GetPart(partUri);
  734. using (TextReader tr = new StreamReader(part.GetStream()))
  735. {
  736. var doc = XDocument.Load(tr);
  737. // Header and Footer extend Container.
  738. Container c;
  739. if (isHeader)
  740. c = new Header(this, doc.Element(w + "hdr"), part);
  741. else
  742. c = new Footer(this, doc.Element(w + "ftr"), part);
  743. return c;
  744. }
  745. }
  746. // If we got this far something went wrong.
  747. return null;
  748. }
  749. public List<Section> GetSections()
  750. {
  751. var allParas = Paragraphs;
  752. var parasInASection = new List<Paragraph>();
  753. var sections = new List<Section>();
  754. foreach (var para in allParas)
  755. {
  756. var sectionInPara = para.Xml.Descendants().FirstOrDefault(s => s.Name.LocalName == "sectPr");
  757. if (sectionInPara == null)
  758. {
  759. parasInASection.Add(para);
  760. }
  761. else
  762. {
  763. parasInASection.Add(para);
  764. var section = new Section(Document, sectionInPara) { SectionParagraphs = parasInASection };
  765. sections.Add(section);
  766. parasInASection = new List<Paragraph>();
  767. }
  768. }
  769. XElement body = mainDoc.Root.Element(XName.Get("body", w.NamespaceName));
  770. XElement baseSectionXml = body.Element(XName.Get("sectPr", w.NamespaceName));
  771. var baseSection = new Section(Document, baseSectionXml) { SectionParagraphs = parasInASection };
  772. sections.Add(baseSection);
  773. return sections;
  774. }
  775. // Get the word\settings.xml part
  776. internal PackagePart settingsPart;
  777. internal PackagePart endnotesPart;
  778. internal PackagePart footnotesPart;
  779. internal PackagePart stylesPart;
  780. internal PackagePart stylesWithEffectsPart;
  781. internal PackagePart numberingPart;
  782. internal PackagePart fontTablePart;
  783. #region Internal variables defined foreach DocX object
  784. // Object representation of the .docx
  785. internal Package package;
  786. // The mainDocument is loaded into a XDocument object for easy querying and editing
  787. internal XDocument mainDoc;
  788. internal XDocument settings;
  789. internal XDocument endnotes;
  790. internal XDocument footnotes;
  791. internal XDocument styles;
  792. internal XDocument stylesWithEffects;
  793. internal XDocument numbering;
  794. internal XDocument fontTable;
  795. internal XDocument header1;
  796. internal XDocument header2;
  797. internal XDocument header3;
  798. // A lookup for the Paragraphs in this document.
  799. internal Dictionary<int, Paragraph> paragraphLookup = new Dictionary<int, Paragraph>();
  800. // Every document is stored in a MemoryStream, all edits made to a document are done in memory.
  801. internal MemoryStream memoryStream;
  802. // The filename that this document was loaded from
  803. internal string filename;
  804. // The stream that this document was loaded from
  805. internal Stream stream;
  806. #endregion
  807. internal DocX(DocX document, XElement xml)
  808. : base(document, xml)
  809. {
  810. }
  811. /// <summary>
  812. /// Returns a list of Images in this document.
  813. /// </summary>
  814. /// <example>
  815. /// Get the unique Id of every Image in this document.
  816. /// <code>
  817. /// // Load a document.
  818. /// DocX document = DocX.Load(@"C:\Example\Test.docx");
  819. ///
  820. /// // Loop through each Image in this document.
  821. /// foreach (Novacode.Image i in document.Images)
  822. /// {
  823. /// // Get the unique Id which identifies this Image.
  824. /// string uniqueId = i.Id;
  825. /// }
  826. ///
  827. /// </code>
  828. /// </example>
  829. /// <seealso cref="AddImage(string)"/>
  830. /// <seealso cref="AddImage(Stream)"/>
  831. /// <seealso cref="Paragraph.Pictures"/>
  832. /// <seealso cref="Paragraph.InsertPicture"/>
  833. public List<Image> Images
  834. {
  835. get
  836. {
  837. PackageRelationshipCollection imageRelationships = mainPart.GetRelationshipsByType("http://schemas.openxmlformats.org/officeDocument/2006/relationships/image");
  838. if (imageRelationships.Any())
  839. {
  840. return
  841. (
  842. from i in imageRelationships
  843. select new Image(this, i)
  844. ).ToList();
  845. }
  846. return new List<Image>();
  847. }
  848. }
  849. /// <summary>
  850. /// Returns a list of custom properties in this document.
  851. /// </summary>
  852. /// <example>
  853. /// Method 1: Get the name, type and value of each CustomProperty in this document.
  854. /// <code>
  855. /// // Load Example.docx
  856. /// DocX document = DocX.Load(@"C:\Example\Test.docx");
  857. ///
  858. /// /*
  859. /// * No two custom properties can have the same name,
  860. /// * so a Dictionary is the perfect data structure to store them in.
  861. /// * Each custom property can be accessed using its name.
  862. /// */
  863. /// foreach (string name in document.CustomProperties.Keys)
  864. /// {
  865. /// // Grab a custom property using its name.
  866. /// CustomProperty cp = document.CustomProperties[name];
  867. ///
  868. /// // Write this custom properties details to Console.
  869. /// Console.WriteLine(string.Format("Name: '{0}', Value: {1}", cp.Name, cp.Value));
  870. /// }
  871. ///
  872. /// Console.WriteLine("Press any key...");
  873. ///
  874. /// // Wait for the user to press a key before closing the Console.
  875. /// Console.ReadKey();
  876. /// </code>
  877. /// </example>
  878. /// <example>
  879. /// Method 2: Get the name, type and value of each CustomProperty in this document.
  880. /// <code>
  881. /// // Load Example.docx
  882. /// DocX document = DocX.Load(@"C:\Example\Test.docx");
  883. ///
  884. /// /*
  885. /// * No two custom properties can have the same name,
  886. /// * so a Dictionary is the perfect data structure to store them in.
  887. /// * The values of this Dictionary are CustomProperties.
  888. /// */
  889. /// foreach (CustomProperty cp in document.CustomProperties.Values)
  890. /// {
  891. /// // Write this custom properties details to Console.
  892. /// Console.WriteLine(string.Format("Name: '{0}', Value: {1}", cp.Name, cp.Value));
  893. /// }
  894. ///
  895. /// Console.WriteLine("Press any key...");
  896. ///
  897. /// // Wait for the user to press a key before closing the Console.
  898. /// Console.ReadKey();
  899. /// </code>
  900. /// </example>
  901. /// <seealso cref="AddCustomProperty"/>
  902. public Dictionary<string, CustomProperty> CustomProperties
  903. {
  904. get
  905. {
  906. if (package.PartExists(new Uri("/docProps/custom.xml", UriKind.Relative)))
  907. {
  908. PackagePart docProps_custom = package.GetPart(new Uri("/docProps/custom.xml", UriKind.Relative));
  909. XDocument customPropDoc;
  910. using (TextReader tr = new StreamReader(docProps_custom.GetStream(FileMode.Open, FileAccess.Read)))
  911. customPropDoc = XDocument.Load(tr, LoadOptions.PreserveWhitespace);
  912. // Get all of the custom properties in this document
  913. return
  914. (
  915. from p in customPropDoc.Descendants(XName.Get("property", customPropertiesSchema.NamespaceName))
  916. let Name = p.Attribute(XName.Get("name")).Value
  917. let Type = p.Descendants().Single().Name.LocalName
  918. let Value = p.Descendants().Single().Value
  919. select new CustomProperty(Name, Type, Value)
  920. ).ToDictionary(p => p.Name, StringComparer.CurrentCultureIgnoreCase);
  921. }
  922. return new Dictionary<string, CustomProperty>();
  923. }
  924. }
  925. ///<summary>
  926. /// Returns the list of document core properties with corresponding values.
  927. ///</summary>
  928. public Dictionary<string, string> CoreProperties
  929. {
  930. get
  931. {
  932. if (package.PartExists(new Uri("/docProps/core.xml", UriKind.Relative)))
  933. {
  934. PackagePart docProps_Core = package.GetPart(new Uri("/docProps/core.xml", UriKind.Relative));
  935. XDocument corePropDoc;
  936. using (TextReader tr = new StreamReader(docProps_Core.GetStream(FileMode.Open, FileAccess.Read)))
  937. corePropDoc = XDocument.Load(tr, LoadOptions.PreserveWhitespace);
  938. // Get all of the core properties in this document
  939. return (from docProperty in corePropDoc.Root.Elements()
  940. select
  941. new KeyValuePair<string, string>(
  942. string.Format(
  943. "{0}:{1}",
  944. corePropDoc.Root.GetPrefixOfNamespace(docProperty.Name.Namespace),
  945. docProperty.Name.LocalName),
  946. docProperty.Value)).ToDictionary(p => p.Key, v => v.Value);
  947. }
  948. return new Dictionary<string, string>();
  949. }
  950. }
  951. /// <summary>
  952. /// Get the Text of this document.
  953. /// </summary>
  954. /// <example>
  955. /// Write to Console the Text from this document.
  956. /// <code>
  957. /// // Load a document
  958. /// DocX document = DocX.Load(@"C:\Example\Test.docx");
  959. ///
  960. /// // Get the text of this document.
  961. /// string text = document.Text;
  962. ///
  963. /// // Write the text of this document to Console.
  964. /// Console.Write(text);
  965. ///
  966. /// // Wait for the user to press a key before closing the console window.
  967. /// Console.ReadKey();
  968. /// </code>
  969. /// </example>
  970. public string Text
  971. {
  972. get
  973. {
  974. return HelperFunctions.GetText(Xml);
  975. }
  976. }
  977. /// <summary>
  978. /// Get the text of each footnote from this document
  979. /// </summary>
  980. public IEnumerable<string> FootnotesText
  981. {
  982. get
  983. {
  984. foreach (XElement footnote in footnotes.Root.Elements(w + "footnote"))
  985. {
  986. yield return HelperFunctions.GetText(footnote);
  987. }
  988. }
  989. }
  990. /// <summary>
  991. /// Get the text of each endnote from this document
  992. /// </summary>
  993. public IEnumerable<string> EndnotesText
  994. {
  995. get
  996. {
  997. foreach (XElement endnote in endnotes.Root.Elements(w + "endnote"))
  998. {
  999. yield return HelperFunctions.GetText(endnote);
  1000. }
  1001. }
  1002. }
  1003. internal string GetCollectiveText(List<PackagePart> list)
  1004. {
  1005. string text = string.Empty;
  1006. foreach (var hp in list)
  1007. {
  1008. using (TextReader tr = new StreamReader(hp.GetStream()))
  1009. {
  1010. XDocument d = XDocument.Load(tr);
  1011. StringBuilder sb = new StringBuilder();
  1012. // Loop through each text item in this run
  1013. foreach (XElement descendant in d.Descendants())
  1014. {
  1015. switch (descendant.Name.LocalName)
  1016. {
  1017. case "tab":
  1018. sb.Append("\t");
  1019. break;
  1020. case "br":
  1021. sb.Append("\n");
  1022. break;
  1023. case "t":
  1024. goto case "delText";
  1025. case "delText":
  1026. sb.Append(descendant.Value);
  1027. break;
  1028. default: break;
  1029. }
  1030. }
  1031. text += "\n" + sb;
  1032. }
  1033. }
  1034. return text;
  1035. }
  1036. /// <summary>
  1037. /// Insert the contents of another document at the end of this document.
  1038. /// </summary>
  1039. /// <param name="remote_document">The document to insert at the end of this document.</param>
  1040. /// <param name="append">If true, document is inserted at the end, otherwise document is inserted at the beginning.</param>
  1041. /// <example>
  1042. /// Create a new document and insert an old document into it.
  1043. /// <code>
  1044. /// // Create a new document.
  1045. /// using (DocX newDocument = DocX.Create(@"NewDocument.docx"))
  1046. /// {
  1047. /// // Load an old document.
  1048. /// using (DocX oldDocument = DocX.Load(@"OldDocument.docx"))
  1049. /// {
  1050. /// // Insert the old document into the new document.
  1051. /// newDocument.InsertDocument(oldDocument);
  1052. ///
  1053. /// // Save the new document.
  1054. /// newDocument.Save();
  1055. /// }// Release the old document from memory.
  1056. /// }// Release the new document from memory.
  1057. /// </code>
  1058. /// <remarks>
  1059. /// If the document being inserted contains Images, CustomProperties and or custom styles, these will be correctly inserted into the new document. In the case of Images, new ID's are generated for the Images being inserted to avoid ID conflicts. CustomProperties with the same name will be ignored not replaced.
  1060. /// </remarks>
  1061. /// </example>
  1062. public void InsertDocument(DocX remote_document, bool append = true)
  1063. {
  1064. // We don't want to effect the origional XDocument, so create a new one from the old one.
  1065. XDocument remote_mainDoc = new XDocument(remote_document.mainDoc);
  1066. XDocument remote_footnotes = null;
  1067. if (remote_document.footnotes != null)
  1068. remote_footnotes = new XDocument(remote_document.footnotes);
  1069. XDocument remote_endnotes = null;
  1070. if (remote_document.endnotes != null)
  1071. remote_endnotes = new XDocument(remote_document.endnotes);
  1072. // Remove all header and footer references.
  1073. remote_mainDoc.Descendants(XName.Get("headerReference", w.NamespaceName)).Remove();
  1074. remote_mainDoc.Descendants(XName.Get("footerReference", w.NamespaceName)).Remove();
  1075. // Get the body of the remote document.
  1076. XElement remote_body = remote_mainDoc.Root.Element(XName.Get("body", w.NamespaceName));
  1077. // Every file that is missing from the local document will have to be copied, every file that already exists will have to be merged.
  1078. PackagePartCollection ppc = remote_document.package.GetParts();
  1079. List<String> ignoreContentTypes = new List<string>
  1080. {
  1081. "application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml",
  1082. "application/vnd.openxmlformats-officedocument.wordprocessingml.header+xml",
  1083. "application/vnd.openxmlformats-officedocument.wordprocessingml.footer+xml",
  1084. "application/vnd.openxmlformats-package.core-properties+xml",
  1085. "application/vnd.openxmlformats-officedocument.extended-properties+xml",
  1086. "application/vnd.openxmlformats-package.relationships+xml"
  1087. };
  1088. List<String> imageContentTypes = new List<string>
  1089. {
  1090. "image/jpeg",
  1091. "image/jpg",
  1092. "image/png",
  1093. "image/bmp",
  1094. "image/gif",
  1095. "image/tiff",
  1096. "image/icon",
  1097. "image/pcx",
  1098. "image/emf",
  1099. "image/wmf"
  1100. };
  1101. // Check if each PackagePart pp exists in this document.
  1102. foreach (PackagePart remote_pp in ppc)
  1103. {
  1104. if (ignoreContentTypes.Contains(remote_pp.ContentType) || imageContentTypes.Contains(remote_pp.ContentType))
  1105. continue;
  1106. // If this external PackagePart already exits then we must merge them.
  1107. if (package.PartExists(remote_pp.Uri))
  1108. {
  1109. PackagePart local_pp = package.GetPart(remote_pp.Uri);
  1110. switch (remote_pp.ContentType)
  1111. {
  1112. case "application/vnd.openxmlformats-officedocument.custom-properties+xml":
  1113. merge_customs(remote_pp, local_pp, remote_mainDoc);
  1114. break;
  1115. // Merge footnotes (and endnotes) before merging styles, then set the remote_footnotes to the just updated footnotes
  1116. case "application/vnd.openxmlformats-officedocument.wordprocessingml.footnotes+xml":
  1117. merge_footnotes(remote_pp, local_pp, remote_mainDoc, remote_document, remote_footnotes);
  1118. remote_footnotes = footnotes;
  1119. break;
  1120. case "application/vnd.openxmlformats-officedocument.wordprocessingml.endnotes+xml":
  1121. merge_endnotes(remote_pp, local_pp, remote_mainDoc, remote_document, remote_endnotes);
  1122. remote_endnotes = endnotes;
  1123. break;
  1124. case "application/vnd.openxmlformats-officedocument.wordprocessingml.styles+xml":
  1125. merge_styles(remote_pp, local_pp, remote_mainDoc, remote_document, remote_footnotes, remote_endnotes);
  1126. break;
  1127. // Merge styles after merging the footnotes, so the changes will be applied to the correct document/footnotes
  1128. case "application/vnd.ms-word.stylesWithEffects+xml":
  1129. merge_styles(remote_pp, local_pp, remote_mainDoc, remote_document, remote_footnotes, remote_endnotes);
  1130. break;
  1131. case "application/vnd.openxmlformats-officedocument.wordprocessingml.fontTable+xml":
  1132. merge_fonts(remote_pp, local_pp, remote_mainDoc, remote_document);
  1133. break;
  1134. case "application/vnd.openxmlformats-officedocument.wordprocessingml.numbering+xml":
  1135. merge_numbering(remote_pp, local_pp, remote_mainDoc, remote_document);
  1136. break;
  1137. }
  1138. }
  1139. // If this external PackagePart does not exits in the internal document then we can simply copy it.
  1140. else
  1141. {
  1142. var packagePart = clonePackagePart(remote_pp);
  1143. switch (remote_pp.ContentType)
  1144. {
  1145. case "application/vnd.openxmlformats-officedocument.wordprocessingml.endnotes+xml":
  1146. endnotesPart = packagePart;
  1147. endnotes = remote_endnotes;
  1148. break;
  1149. case "application/vnd.openxmlformats-officedocument.wordprocessingml.footnotes+xml":
  1150. footnotesPart = packagePart;
  1151. footnotes = remote_footnotes;
  1152. break;
  1153. case "application/vnd.openxmlformats-officedocument.custom-properties+xml":
  1154. break;
  1155. case "application/vnd.openxmlformats-officedocument.wordprocessingml.styles+xml":
  1156. stylesPart = packagePart;
  1157. using (TextReader tr = new StreamReader(stylesPart.GetStream()))
  1158. styles = XDocument.Load(tr);
  1159. break;
  1160. case "application/vnd.ms-word.stylesWithEffects+xml":
  1161. stylesWithEffectsPart = packagePart;
  1162. using (TextReader tr = new StreamReader(stylesWithEffectsPart.GetStream()))
  1163. stylesWithEffects = XDocument.Load(tr);
  1164. break;
  1165. case "application/vnd.openxmlformats-officedocument.wordprocessingml.fontTable+xml":
  1166. fontTablePart = packagePart;
  1167. using (TextReader tr = new StreamReader(fontTablePart.GetStream()))
  1168. fontTable = XDocument.Load(tr);
  1169. break;
  1170. case "application/vnd.openxmlformats-officedocument.wordprocessingml.numbering+xml":
  1171. numberingPart = packagePart;
  1172. using (TextReader tr = new StreamReader(numberingPart.GetStream()))
  1173. numbering = XDocument.Load(tr);
  1174. break;
  1175. }
  1176. clonePackageRelationship(remote_document, remote_pp, remote_mainDoc);
  1177. }
  1178. }
  1179. foreach (var hyperlink_rel in remote_document.mainPart.GetRelationshipsByType("http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink"))
  1180. {
  1181. var old_rel_Id = hyperlink_rel.Id;
  1182. var new_rel_Id = mainPart.CreateRelationship(hyperlink_rel.TargetUri, hyperlink_rel.TargetMode, hyperlink_rel.RelationshipType).Id;
  1183. var hyperlink_refs = remote_mainDoc.Descendants(XName.Get("hyperlink", w.NamespaceName));
  1184. foreach (var hyperlink_ref in hyperlink_refs)
  1185. {
  1186. XAttribute a0 = hyperlink_ref.Attribute(XName.Get("id", r.NamespaceName));
  1187. if (a0 != null && a0.Value == old_rel_Id)
  1188. {
  1189. a0.SetValue(new_rel_Id);
  1190. }
  1191. }
  1192. }
  1193. ////ole object links
  1194. foreach (var oleObject_rel in remote_document.mainPart.GetRelationshipsByType("http://schemas.openxmlformats.org/officeDocument/2006/relationships/oleObject"))
  1195. {
  1196. var old_rel_Id = oleObject_rel.Id;
  1197. var new_rel_Id = mainPart.CreateRelationship(oleObject_rel.TargetUri, oleObject_rel.TargetMode, oleObject_rel.RelationshipType).Id;
  1198. var oleObject_refs = remote_mainDoc.Descendants(XName.Get("OLEObject", "urn:schemas-microsoft-com:office:office"));
  1199. foreach (var oleObject_ref in oleObject_refs)
  1200. {
  1201. XAttribute a0 = oleObject_ref.Attribute(XName.Get("id", r.NamespaceName));
  1202. if (a0 != null && a0.Value == old_rel_Id)
  1203. {
  1204. a0.SetValue(new_rel_Id);
  1205. }
  1206. }
  1207. }
  1208. foreach (PackagePart remote_pp in ppc)
  1209. {
  1210. if (imageContentTypes.Contains(remote_pp.ContentType))
  1211. {
  1212. merge_images(remote_pp, remote_document, remote_mainDoc, remote_pp.ContentType);
  1213. }
  1214. }
  1215. int id = 0;
  1216. var local_docPrs = mainDoc.Root.Descendants(XName.Get("docPr", wp.NamespaceName));
  1217. foreach (var local_docPr in local_docPrs)
  1218. {
  1219. XAttribute a_id = local_docPr.Attribute(XName.Get("id"));
  1220. int a_id_value;
  1221. if (a_id != null && int.TryParse(a_id.Value, out a_id_value))
  1222. if (a_id_value > id)
  1223. id = a_id_value;
  1224. }
  1225. id++;
  1226. // docPr must be sequential
  1227. var docPrs = remote_body.Descendants(XName.Get("docPr", wp.NamespaceName));
  1228. foreach (var docPr in docPrs)
  1229. {
  1230. docPr.SetAttributeValue(XName.Get("id"), id);
  1231. id++;
  1232. }
  1233. // Add the remote documents contents to this document.
  1234. XElement local_body = mainDoc.Root.Element(XName.Get("body", w.NamespaceName));
  1235. if (append)
  1236. local_body.Add(remote_body.Elements());
  1237. else
  1238. local_body.AddFirst(remote_body.Elements());
  1239. // Copy any missing root attributes to the local document.
  1240. foreach (XAttribute a in remote_mainDoc.Root.Attributes())
  1241. {
  1242. if (mainDoc.Root.Attribute(a.Name) == null)
  1243. {
  1244. mainDoc.Root.SetAttributeValue(a.Name, a.Value);
  1245. }
  1246. }
  1247. }
  1248. private void merge_images(PackagePart remote_pp, DocX remote_document, XDocument remote_mainDoc, String contentType)
  1249. {
  1250. // Before doing any other work, check to see if this image is actually referenced in the document.
  1251. // In my testing I have found cases of Images inside documents that are not referenced
  1252. var remote_rel = remote_document.mainPart.GetRelationships().Where(r => r.TargetUri.OriginalString.Equals(remote_pp.Uri.OriginalString.Replace("/word/", ""))).FirstOrDefault();
  1253. if (remote_rel == null) {
  1254. remote_rel = remote_document.mainPart.GetRelationships().Where(r => r.TargetUri.OriginalString.Equals(remote_pp.Uri.OriginalString)).FirstOrDefault();
  1255. if (remote_rel == null)
  1256. return;
  1257. }
  1258. String remote_Id = remote_rel.Id;
  1259. String remote_hash = ComputeMD5HashString(remote_pp.GetStream());
  1260. var image_parts = package.GetParts().Where(pp => pp.ContentType.Equals(contentType));
  1261. bool found = false;
  1262. foreach (var part in image_parts)
  1263. {
  1264. String local_hash = ComputeMD5HashString(part.GetStream());
  1265. if (local_hash.Equals(remote_hash))
  1266. {
  1267. // This image already exists in this document.
  1268. found = true;
  1269. var local_rel = mainPart.GetRelationships().Where(r => r.TargetUri.OriginalString.Equals(part.Uri.OriginalString.Replace("/word/", ""))).FirstOrDefault();
  1270. if (local_rel == null)
  1271. {
  1272. local_rel = mainPart.GetRelationships().Where(r => r.TargetUri.OriginalString.Equals(part.Uri.OriginalString)).FirstOrDefault();
  1273. }
  1274. if (local_rel != null)
  1275. {
  1276. String new_Id = local_rel.Id;
  1277. // Replace all instances of remote_Id in the local document with local_Id
  1278. var elems = remote_mainDoc.Descendants(XName.Get("blip", a.NamespaceName));
  1279. foreach (var elem in elems)
  1280. {
  1281. XAttribute embed = elem.Attribute(XName.Get("embed", r.NamespaceName));
  1282. if (embed != null && embed.Value == remote_Id)
  1283. {
  1284. embed.SetValue(new_Id);
  1285. }
  1286. }
  1287. // Replace all instances of remote_Id in the local document with local_Id (for shapes as well)
  1288. var v_elems = remote_mainDoc.Descendants(XName.Get("imagedata", v.NamespaceName));
  1289. foreach (var elem in v_elems)
  1290. {
  1291. XAttribute id = elem.Attribute(XName.Get("id", r.NamespaceName));
  1292. if (id != null && id.Value == remote_Id)
  1293. {
  1294. id.SetValue(new_Id);
  1295. }
  1296. }
  1297. }
  1298. break;
  1299. }
  1300. }
  1301. // This image does not exist in this document.
  1302. if (!found)
  1303. {
  1304. String new_uri = remote_pp.Uri.OriginalString;
  1305. new_uri = new_uri.Remove(new_uri.LastIndexOf("/"));
  1306. //new_uri = new_uri.Replace("word/", "");
  1307. new_uri += "/" + Guid.NewGuid() + contentType.Replace("image/", ".");
  1308. if (!new_uri.StartsWith("/"))
  1309. new_uri = "/" + new_uri;
  1310. PackagePart new_pp = package.CreatePart(new Uri(new_uri, UriKind.Relative), remote_pp.ContentType, CompressionOption.Normal);
  1311. using (Stream s_read = remote_pp.GetStream())
  1312. {
  1313. using (Stream s_write = new PackagePartStream(new_pp.GetStream(FileMode.Create)))
  1314. {
  1315. byte[] buffer = new byte[32768];
  1316. int read;
  1317. while ((read = s_read.Read(buffer, 0, buffer.Length)) > 0)
  1318. {
  1319. s_write.Write(buffer, 0, read);
  1320. }
  1321. }
  1322. }
  1323. PackageRelationship pr = mainPart.CreateRelationship(new Uri(new_uri, UriKind.Relative), TargetMode.Internal, "http://schemas.openxmlformats.org/officeDocument/2006/relationships/image");
  1324. String new_Id = pr.Id;
  1325. //Check if the remote relationship id is a default rId from Word
  1326. Match defRelId = Regex.Match(remote_Id, @"rId\d+", RegexOptions.IgnoreCase);
  1327. // Replace all instances of remote_Id in the local document with local_Id
  1328. var elems = remote_mainDoc.Descendants(XName.Get("blip", a.NamespaceName));
  1329. foreach (var elem in elems)
  1330. {
  1331. XAttribute embed = elem.Attribute(XName.Get("embed", r.NamespaceName));
  1332. if (embed != null && embed.Value == remote_Id)
  1333. {
  1334. embed.SetValue(new_Id);
  1335. }
  1336. }
  1337. if (!defRelId.Success)
  1338. {
  1339. // Replace all instances of remote_Id in the local document with local_Id
  1340. var elems_local = mainDoc.Descendants(XName.Get("blip", a.NamespaceName));
  1341. foreach (var elem in elems_local)
  1342. {
  1343. XAttribute embed = elem.Attribute(XName.Get("embed", r.NamespaceName));
  1344. if (embed != null && embed.Value == remote_Id)
  1345. {
  1346. embed.SetValue(new_Id);
  1347. }
  1348. }
  1349. // Replace all instances of remote_Id in the local document with local_Id
  1350. var v_elems_local = mainDoc.Descendants(XName.Get("imagedata", v.NamespaceName));
  1351. foreach (var elem in v_elems_local)
  1352. {
  1353. XAttribute id = elem.Attribute(XName.Get("id", r.NamespaceName));
  1354. if (id != null && id.Value == remote_Id)
  1355. {
  1356. id.SetValue(new_Id);
  1357. }
  1358. }
  1359. }
  1360. // Replace all instances of remote_Id in the local document with local_Id (for shapes as well)
  1361. var v_elems = remote_mainDoc.Descendants(XName.Get("imagedata", v.NamespaceName));
  1362. foreach (var elem in v_elems)
  1363. {
  1364. XAttribute id = elem.Attribute(XName.Get("id", r.NamespaceName));
  1365. if (id != null && id.Value == remote_Id)
  1366. {
  1367. id.SetValue(new_Id);
  1368. }
  1369. }
  1370. }
  1371. }
  1372. private string ComputeMD5HashString(Stream stream)
  1373. {
  1374. MD5 md5 = MD5.Create();
  1375. byte[] hash = md5.ComputeHash(stream);
  1376. StringBuilder sb = new StringBuilder();
  1377. foreach (byte b in hash)
  1378. sb.Append(b.ToString("X2"));
  1379. return sb.ToString();
  1380. }
  1381. private void merge_endnotes(PackagePart remote_pp, PackagePart local_pp, XDocument remote_mainDoc, DocX remote, XDocument remote_endnotes)
  1382. {
  1383. IEnumerable<int> ids =
  1384. (
  1385. from d in endnotes.Root.Descendants()
  1386. where d.Name.LocalName == "endnote"
  1387. select int.Parse(d.Attribute(XName.Get("id", w.NamespaceName)).Value)
  1388. );
  1389. int max_id = ids.Max() + 1;
  1390. var endnoteReferences = remote_mainDoc.Descendants(XName.Get("endnoteReference", w.NamespaceName));
  1391. foreach (var endnote in remote_endnotes.Root.Elements().OrderBy(fr => fr.Attribute(XName.Get("id", r.NamespaceName))).Reverse())
  1392. {
  1393. XAttribute id = endnote.Attribute(XName.Get("id", w.NamespaceName));
  1394. int i;
  1395. if (id != null && int.TryParse(id.Value, out i))
  1396. {
  1397. if (i > 0)
  1398. {
  1399. foreach (var endnoteRef in endnoteReferences)
  1400. {
  1401. XAttribute a = endnoteRef.Attribute(XName.Get("id", w.NamespaceName));
  1402. if (a != null && int.Parse(a.Value).Equals(i))
  1403. {
  1404. a.SetValue(max_id);
  1405. }
  1406. }
  1407. // We care about copying this footnote.
  1408. endnote.SetAttributeValue(XName.Get("id", w.NamespaceName), max_id);
  1409. endnotes.Root.Add(endnote);
  1410. max_id++;
  1411. }
  1412. }
  1413. }
  1414. }
  1415. private void merge_footnotes(PackagePart remote_pp, PackagePart local_pp, XDocument remote_mainDoc, DocX remote, XDocument remote_footnotes)
  1416. {
  1417. IEnumerable<int> ids =
  1418. (
  1419. from d in footnotes.Root.Descendants()
  1420. where d.Name.LocalName == "footnote"
  1421. select int.Parse(d.Attribute(XName.Get("id", w.NamespaceName)).Value)
  1422. );
  1423. int max_id = ids.Max() + 1;
  1424. var footnoteReferences = remote_mainDoc.Descendants(XName.Get("footnoteReference", w.NamespaceName));
  1425. foreach (var footnote in remote_footnotes.Root.Elements().OrderBy(fr => fr.Attribute(XName.Get("id", r.NamespaceName))).Reverse())
  1426. {
  1427. XAttribute id = footnote.Attribute(XName.Get("id", w.NamespaceName));
  1428. int i;
  1429. if (id != null && int.TryParse(id.Value, out i))
  1430. {
  1431. if (i > 0)
  1432. {
  1433. foreach (var footnoteRef in footnoteReferences)
  1434. {
  1435. XAttribute a = footnoteRef.Attribute(XName.Get("id", w.NamespaceName));
  1436. if (a != null && int.Parse(a.Value).Equals(i))
  1437. {
  1438. a.SetValue(max_id);
  1439. }
  1440. }
  1441. // We care about copying this footnote.
  1442. footnote.SetAttributeValue(XName.Get("id", w.NamespaceName), max_id);
  1443. footnotes.Root.Add(footnote);
  1444. max_id++;
  1445. }
  1446. }
  1447. }
  1448. }
  1449. private void merge_customs(PackagePart remote_pp, PackagePart local_pp, XDocument remote_mainDoc)
  1450. {
  1451. // Get the remote documents custom.xml file.
  1452. XDocument remote_custom_document;
  1453. using (TextReader tr = new StreamReader(remote_pp.GetStream()))
  1454. remote_custom_document = XDocument.Load(tr);
  1455. // Get the local documents custom.xml file.
  1456. XDocument local_custom_document;
  1457. using (TextReader tr = new StreamReader(local_pp.GetStream()))
  1458. local_custom_document = XDocument.Load(tr);
  1459. IEnumerable<int> pids =
  1460. (
  1461. from d in remote_custom_document.Root.Descendants()
  1462. where d.Name.LocalName == "property"
  1463. select int.Parse(d.Attribute(XName.Get("pid")).Value)
  1464. );
  1465. int pid = pids.Max() + 1;
  1466. foreach (XElement remote_property in remote_custom_document.Root.Elements())
  1467. {
  1468. bool found = false;
  1469. foreach (XElement local_property in local_custom_document.Root.Elements())
  1470. {
  1471. XAttribute remote_property_name = remote_property.Attribute(XName.Get("name"));
  1472. XAttribute local_property_name = local_property.Attribute(XName.Get("name"));
  1473. if (remote_property != null && local_property_name != null && remote_property_name.Value.Equals(local_property_name.Value))
  1474. found = true;
  1475. }
  1476. if (!found)
  1477. {
  1478. remote_property.SetAttributeValue(XName.Get("pid"), pid);
  1479. local_custom_document.Root.Add(remote_property);
  1480. pid++;
  1481. }
  1482. }
  1483. // Save the modified local custom styles.xml file.
  1484. using (TextWriter tw = new StreamWriter(new PackagePartStream(local_pp.GetStream(FileMode.Create, FileAccess.Write))))
  1485. local_custom_document.Save(tw, SaveOptions.None);
  1486. }
  1487. private void merge_numbering(PackagePart remote_pp, PackagePart local_pp, XDocument remote_mainDoc, DocX remote)
  1488. {
  1489. // Add each remote numbering to this document.
  1490. IEnumerable<XElement> remote_abstractNums = remote.numbering.Root.Elements(XName.Get("abstractNum", w.NamespaceName));
  1491. int guidd = 0;
  1492. foreach (var an in remote_abstractNums)
  1493. {
  1494. XAttribute a = an.Attribute(XName.Get("abstractNumId", w.NamespaceName));
  1495. if (a != null)
  1496. {
  1497. int i;
  1498. if (int.TryParse(a.Value, out i))
  1499. {
  1500. if (i > guidd)
  1501. guidd = i;
  1502. }
  1503. }
  1504. }
  1505. guidd++;
  1506. IEnumerable<XElement> remote_nums = remote.numbering.Root.Elements(XName.Get("num", w.NamespaceName));
  1507. int guidd2 = 0;
  1508. foreach (var an in remote_nums)
  1509. {
  1510. XAttribute a = an.Attribute(XName.Get("numId", w.NamespaceName));
  1511. if (a != null)
  1512. {
  1513. int i;
  1514. if (int.TryParse(a.Value, out i))
  1515. {
  1516. if (i > guidd2)
  1517. guidd2 = i;
  1518. }
  1519. }
  1520. }
  1521. guidd2++;
  1522. foreach (XElement remote_abstractNum in remote_abstractNums)
  1523. {
  1524. XAttribute abstractNumId = remote_abstractNum.Attribute(XName.Get("abstractNumId", w.NamespaceName));
  1525. if (abstractNumId != null)
  1526. {
  1527. String abstractNumIdValue = abstractNumId.Value;
  1528. abstractNumId.SetValue(guidd);
  1529. foreach (XElement remote_num in remote_nums)
  1530. {
  1531. var numIds = remote_mainDoc.Descendants(XName.Get("numId", w.NamespaceName));
  1532. foreach (var numId in numIds)
  1533. {
  1534. XAttribute attr = numId.Attribute(XName.Get("val", w.NamespaceName));
  1535. if (attr != null && attr.Value.Equals(remote_num.Attribute(XName.Get("numId", w.NamespaceName)).Value))
  1536. {
  1537. attr.SetValue(guidd2);
  1538. }
  1539. }
  1540. remote_num.SetAttributeValue(XName.Get("numId", w.NamespaceName), guidd2);
  1541. XElement e = remote_num.Element(XName.Get("abstractNumId", w.NamespaceName));
  1542. XAttribute a2 = e?.Attribute(XName.Get("val", w.NamespaceName));
  1543. if (a2 != null && a2.Value.Equals(abstractNumIdValue))
  1544. a2.SetValue(guidd);
  1545. guidd2++;
  1546. }
  1547. }
  1548. guidd++;
  1549. }
  1550. // Checking whether there were more than 0 elements, helped me get rid of exceptions thrown while using InsertDocument
  1551. if (numbering.Root.Elements(XName.Get("abstractNum", w.NamespaceName)).Count() > 0)
  1552. numbering.Root.Elements(XName.Get("abstractNum", w.NamespaceName)).Last().AddAfterSelf(remote_abstractNums);
  1553. if (numbering.Root.Elements(XName.Get("num", w.NamespaceName)).Count() > 0)
  1554. numbering.Root.Elements(XName.Get("num", w.NamespaceName)).Last().AddAfterSelf(remote_nums);
  1555. }
  1556. private void merge_fonts(PackagePart remote_pp, PackagePart local_pp, XDocument remote_mainDoc, DocX remote)
  1557. {
  1558. // Add each remote font to this document.
  1559. IEnumerable<XElement> remote_fonts = remote.fontTable.Root.Elements(XName.Get("font", w.NamespaceName));
  1560. IEnumerable<XElement> local_fonts = fontTable.Root.Elements(XName.Get("font", w.NamespaceName));
  1561. foreach (XElement remote_font in remote_fonts)
  1562. {
  1563. bool flag_addFont = true;
  1564. foreach (XElement local_font in local_fonts)
  1565. {
  1566. if (local_font.Attribute(XName.Get("name", w.NamespaceName)).Value == remote_font.Attribute(XName.Get("name", w.NamespaceName)).Value)
  1567. {
  1568. flag_addFont = false;
  1569. break;
  1570. }
  1571. }
  1572. if (flag_addFont)
  1573. {
  1574. fontTable.Root.Add(remote_font);
  1575. }
  1576. }
  1577. }
  1578. private void merge_styles(PackagePart remote_pp, PackagePart local_pp, XDocument remote_mainDoc, DocX remote, XDocument remote_footnotes, XDocument remote_endnotes)
  1579. {
  1580. var local_styles = new Dictionary<string, string>();
  1581. foreach (XElement local_style in styles.Root.Elements(XName.Get("style", w.NamespaceName)))
  1582. {
  1583. XElement temp = new XElement(local_style);
  1584. XAttribute styleId = temp.Attribute(XName.Get("styleId", w.NamespaceName));
  1585. String value = styleId.Value;
  1586. styleId.Remove();
  1587. String key = Regex.Replace(temp.ToString(), @"\s+", "");
  1588. if (!local_styles.ContainsKey(key)) local_styles.Add(key, value);
  1589. }
  1590. // Add each remote style to this document.
  1591. IEnumerable<XElement> remote_styles = remote.styles.Root.Elements(XName.Get("style", w.NamespaceName));
  1592. foreach (XElement remote_style in remote_styles)
  1593. {
  1594. XElement temp = new XElement(remote_style);
  1595. XAttribute styleId = temp.Attribute(XName.Get("styleId", w.NamespaceName));
  1596. String value = styleId.Value;
  1597. styleId.Remove();
  1598. String key = Regex.Replace(temp.ToString(), @"\s+", "");
  1599. String guuid;
  1600. // Check to see if the local document already contains the remote style.
  1601. if (local_styles.ContainsKey(key))
  1602. {
  1603. String local_value;
  1604. local_styles.TryGetValue(key, out local_value);
  1605. // If the styleIds are the same then nothing needs to be done.
  1606. if (local_value == value)
  1607. continue;
  1608. // All we need to do is update the styleId.
  1609. guuid = local_value;
  1610. }
  1611. else
  1612. {
  1613. guuid = Guid.NewGuid().ToString();
  1614. // Set the styleId in the remote_style to this new Guid
  1615. // [Fixed the issue that my document referred to a new Guid while my styles still had the old value ("Titel")]
  1616. remote_style.SetAttributeValue(XName.Get("styleId", w.NamespaceName), guuid);
  1617. }
  1618. foreach (XElement e in remote_mainDoc.Root.Descendants(XName.Get("pStyle", w.NamespaceName)))
  1619. {
  1620. XAttribute e_styleId = e.Attribute(XName.Get("val", w.NamespaceName));
  1621. if (e_styleId != null && e_styleId.Value.Equals(styleId.Value))
  1622. {
  1623. e_styleId.SetValue(guuid);
  1624. }
  1625. }
  1626. foreach (XElement e in remote_mainDoc.Root.Descendants(XName.Get("rStyle", w.NamespaceName)))
  1627. {
  1628. XAttribute e_styleId = e.Attribute(XName.Get("val", w.NamespaceName));
  1629. if (e_styleId != null && e_styleId.Value.Equals(styleId.Value))
  1630. {
  1631. e_styleId.SetValue(guuid);
  1632. }
  1633. }
  1634. foreach (XElement e in remote_mainDoc.Root.Descendants(XName.Get("tblStyle", w.NamespaceName)))
  1635. {
  1636. XAttribute e_styleId = e.Attribute(XName.Get("val", w.NamespaceName));
  1637. if (e_styleId != null && e_styleId.Value.Equals(styleId.Value))
  1638. {
  1639. e_styleId.SetValue(guuid);
  1640. }
  1641. }
  1642. if (remote_endnotes != null)
  1643. {
  1644. foreach (XElement e in remote_endnotes.Root.Descendants(XName.Get("rStyle", w.NamespaceName)))
  1645. {
  1646. XAttribute e_styleId = e.Attribute(XName.Get("val", w.NamespaceName));
  1647. if (e_styleId != null && e_styleId.Value.Equals(styleId.Value))
  1648. {
  1649. e_styleId.SetValue(guuid);
  1650. }
  1651. }
  1652. foreach (XElement e in remote_endnotes.Root.Descendants(XName.Get("pStyle", w.NamespaceName)))
  1653. {
  1654. XAttribute e_styleId = e.Attribute(XName.Get("val", w.NamespaceName));
  1655. if (e_styleId != null && e_styleId.Value.Equals(styleId.Value))
  1656. {
  1657. e_styleId.SetValue(guuid);
  1658. }
  1659. }
  1660. }
  1661. if (remote_footnotes != null)
  1662. {
  1663. foreach (XElement e in remote_footnotes.Root.Descendants(XName.Get("rStyle", w.NamespaceName)))
  1664. {
  1665. XAttribute e_styleId = e.Attribute(XName.Get("val", w.NamespaceName));
  1666. if (e_styleId != null && e_styleId.Value.Equals(styleId.Value))
  1667. {
  1668. e_styleId.SetValue(guuid);
  1669. }
  1670. }
  1671. foreach (XElement e in remote_footnotes.Root.Descendants(XName.Get("pStyle", w.NamespaceName)))
  1672. {
  1673. XAttribute e_styleId = e.Attribute(XName.Get("val", w.NamespaceName));
  1674. if (e_styleId != null && e_styleId.Value.Equals(styleId.Value))
  1675. {
  1676. e_styleId.SetValue(guuid);
  1677. }
  1678. }
  1679. }
  1680. // Make sure they don't clash by using a uuid.
  1681. styleId.SetValue(guuid);
  1682. styles.Root.Add(remote_style);
  1683. }
  1684. }
  1685. protected void clonePackageRelationship(DocX remote_document, PackagePart pp, XDocument remote_mainDoc)
  1686. {
  1687. string url = pp.Uri.OriginalString.Replace("/", "");
  1688. var remote_rels = remote_document.mainPart.GetRelationships();
  1689. foreach (var remote_rel in remote_rels)
  1690. {
  1691. if (url.Equals("word" + remote_rel.TargetUri.OriginalString.Replace("/", "")))
  1692. {
  1693. String remote_Id = remote_rel.Id;
  1694. String local_Id = mainPart.CreateRelationship(remote_rel.TargetUri, remote_rel.TargetMode, remote_rel.RelationshipType).Id;
  1695. // Replace all instances of remote_Id in the local document with local_Id
  1696. var elems = remote_mainDoc.Descendants(XName.Get("blip", a.NamespaceName));
  1697. foreach (var elem in elems)
  1698. {
  1699. XAttribute embed = elem.Attribute(XName.Get("embed", r.NamespaceName));
  1700. if (embed != null && embed.Value == remote_Id)
  1701. {
  1702. embed.SetValue(local_Id);
  1703. }
  1704. }
  1705. // Replace all instances of remote_Id in the local document with local_Id (for shapes as well)
  1706. var v_elems = remote_mainDoc.Descendants(XName.Get("imagedata", v.NamespaceName));
  1707. foreach (var elem in v_elems)
  1708. {
  1709. XAttribute id = elem.Attribute(XName.Get("id", r.NamespaceName));
  1710. if (id != null && id.Value == remote_Id)
  1711. {
  1712. id.SetValue(local_Id);
  1713. }
  1714. }
  1715. break;
  1716. }
  1717. }
  1718. }
  1719. protected PackagePart clonePackagePart(PackagePart pp)
  1720. {
  1721. PackagePart new_pp = package.CreatePart(pp.Uri, pp.ContentType, CompressionOption.Normal);
  1722. using (Stream s_read = pp.GetStream())
  1723. {
  1724. using (Stream s_write = new PackagePartStream(new_pp.GetStream(FileMode.Create)))
  1725. {
  1726. byte[] buffer = new byte[32768];
  1727. int read;
  1728. while ((read = s_read.Read(buffer, 0, buffer.Length)) > 0)
  1729. {
  1730. s_write.Write(buffer, 0, read);
  1731. }
  1732. }
  1733. }
  1734. return new_pp;
  1735. }
  1736. protected string GetMD5HashFromStream(Stream stream)
  1737. {
  1738. MD5 md5 = new MD5CryptoServiceProvider();
  1739. byte[] retVal = md5.ComputeHash(stream);
  1740. StringBuilder sb = new StringBuilder();
  1741. for (int i = 0; i < retVal.Length; i++)
  1742. {
  1743. sb.Append(retVal[i].ToString("x2"));
  1744. }
  1745. return sb.ToString();
  1746. }
  1747. /// <summary>
  1748. /// Insert a new Table at the end of this document.
  1749. /// </summary>
  1750. /// <param name="columnCount">The number of columns to create.</param>
  1751. /// <param name="rowCount">The number of rows to create.</param>
  1752. /// <returns>A new Table.</returns>
  1753. /// <example>
  1754. /// Insert a new Table with 2 columns and 3 rows, at the end of a document.
  1755. /// <code>
  1756. /// // Create a document.
  1757. /// using (DocX document = DocX.Create(@"C:\Example\Test.docx"))
  1758. /// {
  1759. /// // Create a new Table with 2 columns and 3 rows.
  1760. /// Table newTable = document.InsertTable(2, 3);
  1761. ///
  1762. /// // Set the design of this Table.
  1763. /// newTable.Design = TableDesign.LightShadingAccent2;
  1764. ///
  1765. /// // Set the column names.
  1766. /// newTable.Rows[0].Cells[0].Paragraph.InsertText("Ice Cream", false);
  1767. /// newTable.Rows[0].Cells[1].Paragraph.InsertText("Price", false);
  1768. ///
  1769. /// // Fill row 1
  1770. /// newTable.Rows[1].Cells[0].Paragraph.InsertText("Chocolate", false);
  1771. /// newTable.Rows[1].Cells[1].Paragraph.InsertText("€3:50", false);
  1772. ///
  1773. /// // Fill row 2
  1774. /// newTable.Rows[2].Cells[0].Paragraph.InsertText("Vanilla", false);
  1775. /// newTable.Rows[2].Cells[1].Paragraph.InsertText("€3:00", false);
  1776. ///
  1777. /// // Save all changes made to document b.
  1778. /// document.Save();
  1779. /// }// Release this document from memory.
  1780. /// </code>
  1781. /// </example>
  1782. public new Table InsertTable(int rowCount, int columnCount)
  1783. {
  1784. if (rowCount < 1 || columnCount < 1)
  1785. throw new ArgumentOutOfRangeException("Row and Column count must be greater than zero.");
  1786. Table t = base.InsertTable(rowCount, columnCount);
  1787. t.mainPart = mainPart;
  1788. return t;
  1789. }
  1790. public Table AddTable(int rowCount, int columnCount)
  1791. {
  1792. if (rowCount < 1 || columnCount < 1)
  1793. throw new ArgumentOutOfRangeException("Row and Column count must be greater than zero.");
  1794. Table t = new Table(this, HelperFunctions.CreateTable(rowCount, columnCount));
  1795. t.mainPart = mainPart;
  1796. return t;
  1797. }
  1798. /// <summary>
  1799. /// Create a new list with a list item.
  1800. /// </summary>
  1801. /// <param name="listText">The text of the first element in the created list.</param>
  1802. /// <param name="level">The indentation level of the element in the list.</param>
  1803. /// <param name="listType">The type of list to be created: Bulleted or Numbered.</param>
  1804. /// <param name="startNumber">The number start number for the list. </param>
  1805. /// <param name="trackChanges">Enable change tracking</param>
  1806. /// <param name="continueNumbering">Set to true if you want to continue numbering from the previous numbered list</param>
  1807. /// <returns>
  1808. /// The created List. Call AddListItem(...) to add more elements to the list.
  1809. /// Write the list to the Document with InsertList(...) once the list has all the desired
  1810. /// elements, otherwise the list will not be included in the working Document.
  1811. /// </returns>
  1812. public List AddList(string listText = null, int level = 0, ListItemType listType = ListItemType.Numbered, int? startNumber = null, bool trackChanges = false, bool continueNumbering = false)
  1813. {
  1814. return AddListItem(new List(this, null), listText, level, listType, startNumber, trackChanges, continueNumbering);
  1815. }
  1816. /// <summary>
  1817. /// Add a list item to an already existing list.
  1818. /// </summary>
  1819. /// <param name="list">The list to add the new list item to.</param>
  1820. /// <param name="listText">The run text that should be in the new list item.</param>
  1821. /// <param name="level">The indentation level of the new list element.</param>
  1822. /// <param name="startNumber">The number start number for the list. </param>
  1823. /// <param name="trackChanges">Enable change tracking</param>
  1824. /// <param name="listType">Numbered or Bulleted list type. </param>
  1825. /// /// <param name="continueNumbering">Set to true if you want to continue numbering from the previous numbered list</param>
  1826. /// <returns>
  1827. /// The created List. Call AddListItem(...) to add more elements to the list.
  1828. /// Write the list to the Document with InsertList(...) once the list has all the desired
  1829. /// elements, otherwise the list will not be included in the working Document.
  1830. /// </returns>
  1831. public List AddListItem(List list, string listText, int level = 0, ListItemType listType = ListItemType.Numbered, int? startNumber = null, bool trackChanges = false, bool continueNumbering = false)
  1832. {
  1833. if (startNumber.HasValue && continueNumbering) throw new InvalidOperationException("Cannot specify a start number and at the same time continue numbering from another list");
  1834. var listToReturn = HelperFunctions.CreateItemInList(list, listText, level, listType, startNumber, trackChanges, continueNumbering);
  1835. var lastItem = listToReturn.Items.LastOrDefault();
  1836. if (lastItem != null)
  1837. {
  1838. lastItem.PackagePart = mainPart;
  1839. }
  1840. return listToReturn;
  1841. }
  1842. /// <summary>
  1843. /// Insert list into the document.
  1844. /// </summary>
  1845. /// <param name="list">The list to insert into the document.</param>
  1846. /// <returns>The list that was inserted into the document.</returns>
  1847. public new List InsertList(List list)
  1848. {
  1849. base.InsertList(list);
  1850. return list;
  1851. }
  1852. public new List InsertList(List list, Font fontFamily, double fontSize)
  1853. {
  1854. base.InsertList(list, fontFamily, fontSize);
  1855. return list;
  1856. }
  1857. public new List InsertList(List list, double fontSize)
  1858. {
  1859. base.InsertList(list, fontSize);
  1860. return list;
  1861. }
  1862. /// <summary>
  1863. /// Insert a list at an index location in the document.
  1864. /// </summary>
  1865. /// <param name="index">Index in document to insert the list.</param>
  1866. /// <param name="list">The list that was inserted into the document.</param>
  1867. /// <returns></returns>
  1868. public new List InsertList(int index, List list)
  1869. {
  1870. base.InsertList(index, list);
  1871. return list;
  1872. }
  1873. internal XDocument AddStylesForList()
  1874. {
  1875. var wordStylesUri = new Uri("/word/styles.xml", UriKind.Relative);
  1876. // If the internal document contains no /word/styles.xml create one.
  1877. if (!package.PartExists(wordStylesUri))
  1878. HelperFunctions.AddDefaultStylesXml(package);
  1879. // Load the styles.xml into memory.
  1880. XDocument wordStyles;
  1881. using (TextReader tr = new StreamReader(package.GetPart(wordStylesUri).GetStream()))
  1882. wordStyles = XDocument.Load(tr);
  1883. bool listStyleExists =
  1884. (
  1885. from s in wordStyles.Element(w + "styles").Elements()
  1886. let styleId = s.Attribute(XName.Get("styleId", w.NamespaceName))
  1887. where (styleId != null && styleId.Value == "ListParagraph")
  1888. select s
  1889. ).Any();
  1890. if (!listStyleExists)
  1891. {
  1892. var style = new XElement
  1893. (
  1894. w + "style",
  1895. new XAttribute(w + "type", "paragraph"),
  1896. new XAttribute(w + "styleId", "ListParagraph"),
  1897. new XElement(w + "name", new XAttribute(w + "val", "List Paragraph")),
  1898. new XElement(w + "basedOn", new XAttribute(w + "val", "Normal")),
  1899. new XElement(w + "uiPriority", new XAttribute(w + "val", "34")),
  1900. new XElement(w + "qformat"),
  1901. new XElement(w + "rsid", new XAttribute(w + "val", "00832EE1")),
  1902. new XElement
  1903. (
  1904. w + "rPr",
  1905. new XElement(w + "ind", new XAttribute(w + "left", "720")),
  1906. new XElement
  1907. (
  1908. w + "contextualSpacing"
  1909. )
  1910. )
  1911. );
  1912. wordStyles.Element(w + "styles").Add(style);
  1913. // Save the styles document.
  1914. using (TextWriter tw = new StreamWriter(new PackagePartStream(package.GetPart(wordStylesUri).GetStream())))
  1915. wordStyles.Save(tw);
  1916. }
  1917. return wordStyles;
  1918. }
  1919. /// <summary>
  1920. /// Insert a Table into this document. The Table's source can be a completely different document.
  1921. /// </summary>
  1922. /// <param name="t">The Table to insert.</param>
  1923. /// <param name="index">The index to insert this Table at.</param>
  1924. /// <returns>The Table now associated with this document.</returns>
  1925. /// <example>
  1926. /// Extract a Table from document a and insert it into document b, at index 10.
  1927. /// <code>
  1928. /// // Place holder for a Table.
  1929. /// Table t;
  1930. ///
  1931. /// // Load document a.
  1932. /// using (DocX documentA = DocX.Load(@"C:\Example\a.docx"))
  1933. /// {
  1934. /// // Get the first Table from this document.
  1935. /// t = documentA.Tables[0];
  1936. /// }
  1937. ///
  1938. /// // Load document b.
  1939. /// using (DocX documentB = DocX.Load(@"C:\Example\b.docx"))
  1940. /// {
  1941. /// /*
  1942. /// * Insert the Table that was extracted from document a, into document b.
  1943. /// * This creates a new Table that is now associated with document b.
  1944. /// */
  1945. /// Table newTable = documentB.InsertTable(10, t);
  1946. ///
  1947. /// // Save all changes made to document b.
  1948. /// documentB.Save();
  1949. /// }// Release this document from memory.
  1950. /// </code>
  1951. /// </example>
  1952. public new Table InsertTable(int index, Table t)
  1953. {
  1954. Table t2 = base.InsertTable(index, t);
  1955. t2.mainPart = mainPart;
  1956. return t2;
  1957. }
  1958. /// <summary>
  1959. /// Insert a Table into this document. The Table's source can be a completely different document.
  1960. /// </summary>
  1961. /// <param name="t">The Table to insert.</param>
  1962. /// <returns>The Table now associated with this document.</returns>
  1963. /// <example>
  1964. /// Extract a Table from document a and insert it at the end of document b.
  1965. /// <code>
  1966. /// // Place holder for a Table.
  1967. /// Table t;
  1968. ///
  1969. /// // Load document a.
  1970. /// using (DocX documentA = DocX.Load(@"C:\Example\a.docx"))
  1971. /// {
  1972. /// // Get the first Table from this document.
  1973. /// t = documentA.Tables[0];
  1974. /// }
  1975. ///
  1976. /// // Load document b.
  1977. /// using (DocX documentB = DocX.Load(@"C:\Example\b.docx"))
  1978. /// {
  1979. /// /*
  1980. /// * Insert the Table that was extracted from document a, into document b.
  1981. /// * This creates a new Table that is now associated with document b.
  1982. /// */
  1983. /// Table newTable = documentB.InsertTable(t);
  1984. ///
  1985. /// // Save all changes made to document b.
  1986. /// documentB.Save();
  1987. /// }// Release this document from memory.
  1988. /// </code>
  1989. /// </example>
  1990. public new Table InsertTable(Table t)
  1991. {
  1992. t = base.InsertTable(t);
  1993. t.mainPart = mainPart;
  1994. return t;
  1995. }
  1996. /// <summary>
  1997. /// Insert a new Table at the end of this document.
  1998. /// </summary>
  1999. /// <param name="columnCount">The number of columns to create.</param>
  2000. /// <param name="rowCount">The number of rows to create.</param>
  2001. /// <param name="index">The index to insert this Table at.</param>
  2002. /// <returns>A new Table.</returns>
  2003. /// <example>
  2004. /// Insert a new Table with 2 columns and 3 rows, at index 37 in this document.
  2005. /// <code>
  2006. /// // Create a document.
  2007. /// using (DocX document = DocX.Load(@"C:\Example\Test.docx"))
  2008. /// {
  2009. /// // Create a new Table with 3 rows and 2 columns. Insert this Table at index 37.
  2010. /// Table newTable = document.InsertTable(37, 3, 2);
  2011. ///
  2012. /// // Set the design of this Table.
  2013. /// newTable.Design = TableDesign.LightShadingAccent3;
  2014. ///
  2015. /// // Set the column names.
  2016. /// newTable.Rows[0].Cells[0].Paragraph.InsertText("Ice Cream", false);
  2017. /// newTable.Rows[0].Cells[1].Paragraph.InsertText("Price", false);
  2018. ///
  2019. /// // Fill row 1
  2020. /// newTable.Rows[1].Cells[0].Paragraph.InsertText("Chocolate", false);
  2021. /// newTable.Rows[1].Cells[1].Paragraph.InsertText("€3:50", false);
  2022. ///
  2023. /// // Fill row 2
  2024. /// newTable.Rows[2].Cells[0].Paragraph.InsertText("Vanilla", false);
  2025. /// newTable.Rows[2].Cells[1].Paragraph.InsertText("€3:00", false);
  2026. ///
  2027. /// // Save all changes made to document b.
  2028. /// document.Save();
  2029. /// }// Release this document from memory.
  2030. /// </code>
  2031. /// </example>
  2032. public new Table InsertTable(int index, int rowCount, int columnCount)
  2033. {
  2034. if (rowCount < 1 || columnCount < 1)
  2035. throw new ArgumentOutOfRangeException("Row and Column count must be greater than zero.");
  2036. Table t = base.InsertTable(index, rowCount, columnCount);
  2037. t.mainPart = mainPart;
  2038. return t;
  2039. }
  2040. /// <summary>
  2041. /// Creates a document using a Stream.
  2042. /// </summary>
  2043. /// <param name="stream">The Stream to create the document from.</param>
  2044. /// <param name="documentType"></param>
  2045. /// <returns>Returns a DocX object which represents the document.</returns>
  2046. /// <example>
  2047. /// Creating a document from a FileStream.
  2048. /// <code>
  2049. /// // Use a FileStream fs to create a new document.
  2050. /// using(FileStream fs = new FileStream(@"C:\Example\Test.docx", FileMode.Create))
  2051. /// {
  2052. /// // Load the document using fs
  2053. /// using (DocX document = DocX.Create(fs))
  2054. /// {
  2055. /// // Do something with the document here.
  2056. ///
  2057. /// // Save all changes made to this document.
  2058. /// document.Save();
  2059. /// }// Release this document from memory.
  2060. /// }
  2061. /// </code>
  2062. /// </example>
  2063. /// <example>
  2064. /// Creating a document in a SharePoint site.
  2065. /// <code>
  2066. /// using(SPSite mySite = new SPSite("http://server/sites/site"))
  2067. /// {
  2068. /// // Open a connection to the SharePoint site
  2069. /// using(SPWeb myWeb = mySite.OpenWeb())
  2070. /// {
  2071. /// // Create a MemoryStream ms.
  2072. /// using (MemoryStream ms = new MemoryStream())
  2073. /// {
  2074. /// // Create a document using ms.
  2075. /// using (DocX document = DocX.Create(ms))
  2076. /// {
  2077. /// // Do something with the document here.
  2078. ///
  2079. /// // Save all changes made to this document.
  2080. /// document.Save();
  2081. /// }// Release this document from memory
  2082. ///
  2083. /// // Add the document to the SharePoint site
  2084. /// web.Files.Add("filename", ms.ToArray(), true);
  2085. /// }
  2086. /// }
  2087. /// }
  2088. /// </code>
  2089. /// </example>
  2090. /// <seealso cref="DocX.Load(System.IO.Stream)"/>
  2091. /// <seealso cref="DocX.Load(string)"/>
  2092. /// <seealso cref="DocX.Save()"/>
  2093. public static DocX Create(Stream stream, DocumentTypes documentType = DocumentTypes.Document)
  2094. {
  2095. // Store this document in memory
  2096. MemoryStream ms = new MemoryStream();
  2097. // Create the docx package
  2098. Package package = Package.Open(ms, FileMode.Create, FileAccess.ReadWrite);
  2099. PostCreation(package, documentType);
  2100. DocX document = Load(ms);
  2101. document.stream = stream;
  2102. return document;
  2103. }
  2104. /// <summary>
  2105. /// Creates a document using a fully qualified or relative filename.
  2106. /// </summary>
  2107. /// <param name="filename">The fully qualified or relative filename.</param>
  2108. /// <param name="documentType"></param>
  2109. /// <returns>Returns a DocX object which represents the document.</returns>
  2110. /// <example>
  2111. /// <code>
  2112. /// // Create a document using a relative filename.
  2113. /// using (DocX document = DocX.Create(@"..\Test.docx"))
  2114. /// {
  2115. /// // Do something with the document here.
  2116. ///
  2117. /// // Save all changes made to this document.
  2118. /// document.Save();
  2119. /// }// Release this document from memory
  2120. /// </code>
  2121. /// <code>
  2122. /// // Create a document using a relative filename.
  2123. /// using (DocX document = DocX.Create(@"..\Test.docx"))
  2124. /// {
  2125. /// // Do something with the document here.
  2126. ///
  2127. /// // Save all changes made to this document.
  2128. /// document.Save();
  2129. /// }// Release this document from memory
  2130. /// </code>
  2131. /// <seealso cref="DocX.Load(System.IO.Stream)"/>
  2132. /// <seealso cref="DocX.Load(string)"/>
  2133. /// <seealso cref="DocX.Save()"/>
  2134. /// </example>
  2135. public static DocX Create(string filename, DocumentTypes documentType = DocumentTypes.Document)
  2136. {
  2137. // Store this document in memory
  2138. MemoryStream ms = new MemoryStream();
  2139. // Create the docx package
  2140. //WordprocessingDocument wdDoc = WordprocessingDocument.Create(ms, DocumentFormat.OpenXml.WordprocessingDocumentType.Document);
  2141. Package package = Package.Open(ms, FileMode.Create, FileAccess.ReadWrite);
  2142. PostCreation(package, documentType);
  2143. DocX document = Load(ms);
  2144. document.filename = filename;
  2145. return document;
  2146. }
  2147. internal static void PostCreation(Package package, DocumentTypes documentType = DocumentTypes.Document)
  2148. {
  2149. XDocument mainDoc, stylesDoc, numberingDoc;
  2150. #region MainDocumentPart
  2151. // Create the main document part for this package
  2152. PackagePart mainDocumentPart;
  2153. if (documentType == DocumentTypes.Document)
  2154. {
  2155. mainDocumentPart = package.CreatePart(new Uri("/word/document.xml", UriKind.Relative), "application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml", CompressionOption.Normal);
  2156. }
  2157. else
  2158. {
  2159. mainDocumentPart = package.CreatePart(new Uri("/word/document.xml", UriKind.Relative), "application/vnd.openxmlformats-officedocument.wordprocessingml.template.main+xml", CompressionOption.Normal);
  2160. }
  2161. package.CreateRelationship(mainDocumentPart.Uri, TargetMode.Internal, "http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument");
  2162. // Load the document part into a XDocument object
  2163. using (TextReader tr = new StreamReader(mainDocumentPart.GetStream(FileMode.Create, FileAccess.ReadWrite)))
  2164. {
  2165. mainDoc = XDocument.Parse
  2166. (@"<?xml version=""1.0"" encoding=""UTF-8"" standalone=""yes""?>
  2167. <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"" xmlns:a=""http://schemas.openxmlformats.org/drawingml/2006/main"" xmlns:c=""http://schemas.openxmlformats.org/drawingml/2006/chart"">
  2168. <w:body>
  2169. <w:sectPr w:rsidR=""003E25F4"" w:rsidSect=""00FC3028"">
  2170. <w:pgSz w:w=""11906"" w:h=""16838""/>
  2171. <w:pgMar w:top=""1440"" w:right=""1440"" w:bottom=""1440"" w:left=""1440"" w:header=""708"" w:footer=""708"" w:gutter=""0""/>
  2172. <w:cols w:space=""708""/>
  2173. <w:docGrid w:linePitch=""360""/>
  2174. </w:sectPr>
  2175. </w:body>
  2176. </w:document>"
  2177. );
  2178. }
  2179. // Save the main document
  2180. using (TextWriter tw = new StreamWriter(new PackagePartStream(mainDocumentPart.GetStream(FileMode.Create, FileAccess.Write))))
  2181. mainDoc.Save(tw, SaveOptions.None);
  2182. #endregion
  2183. #region StylePart
  2184. stylesDoc = HelperFunctions.AddDefaultStylesXml(package);
  2185. #endregion
  2186. #region NumberingPart
  2187. numberingDoc = HelperFunctions.AddDefaultNumberingXml(package);
  2188. #endregion
  2189. package.Close();
  2190. }
  2191. internal static DocX PostLoad(ref Package package)
  2192. {
  2193. DocX document = new DocX(null, null);
  2194. document.package = package;
  2195. document.Document = document;
  2196. #region MainDocumentPart
  2197. document.mainPart = package.GetParts().Where
  2198. (
  2199. p => p.ContentType.Equals(HelperFunctions.DOCUMENT_DOCUMENTTYPE, StringComparison.CurrentCultureIgnoreCase) ||
  2200. p.ContentType.Equals(HelperFunctions.TEMPLATE_DOCUMENTTYPE, StringComparison.CurrentCultureIgnoreCase)
  2201. ).Single();
  2202. using (TextReader tr = new StreamReader(document.mainPart.GetStream(FileMode.Open, FileAccess.Read)))
  2203. document.mainDoc = XDocument.Load(tr, LoadOptions.PreserveWhitespace);
  2204. #endregion
  2205. PopulateDocument(document, package);
  2206. using (TextReader tr = new StreamReader(document.settingsPart.GetStream()))
  2207. document.settings = XDocument.Load(tr);
  2208. document.paragraphLookup.Clear();
  2209. foreach (var paragraph in document.Paragraphs)
  2210. {
  2211. if (!document.paragraphLookup.ContainsKey(paragraph.endIndex))
  2212. document.paragraphLookup.Add(paragraph.endIndex, paragraph);
  2213. }
  2214. return document;
  2215. }
  2216. private static void PopulateDocument(DocX document, Package package)
  2217. {
  2218. Headers headers = new Headers();
  2219. headers.odd = document.GetHeaderByType("default");
  2220. headers.even = document.GetHeaderByType("even");
  2221. headers.first = document.GetHeaderByType("first");
  2222. Footers footers = new Footers();
  2223. footers.odd = document.GetFooterByType("default");
  2224. footers.even = document.GetFooterByType("even");
  2225. footers.first = document.GetFooterByType("first");
  2226. //// Get the sectPr for this document.
  2227. //XElement sect = document.mainDoc.Descendants(XName.Get("sectPr", DocX.w.NamespaceName)).Single();
  2228. //if (sectPr != null)
  2229. //{
  2230. // // Extract the even header reference
  2231. // var header_even_ref = sectPr.Elements().SingleOrDefault(x => x.Name.LocalName == "headerReference" && x.Attribute(XName.Get("type", DocX.w.NamespaceName)) != null && x.Attribute(XName.Get("type", DocX.w.NamespaceName)).Value == "even");
  2232. // string id = header_even_ref.Attribute(XName.Get("id", DocX.r.NamespaceName)).Value;
  2233. // var res = document.mainPart.GetRelationship(id);
  2234. // string ans = res.SourceUri.OriginalString;
  2235. // headers.even.xml_filename = ans;
  2236. // // Extract the odd header reference
  2237. // var header_odd_ref = sectPr.Elements().SingleOrDefault(x => x.Name.LocalName == "headerReference" && x.Attribute(XName.Get("type", DocX.w.NamespaceName)) != null && x.Attribute(XName.Get("type", DocX.w.NamespaceName)).Value == "default");
  2238. // string id2 = header_odd_ref.Attribute(XName.Get("id", DocX.r.NamespaceName)).Value;
  2239. // var res2 = document.mainPart.GetRelationship(id2);
  2240. // string ans2 = res2.SourceUri.OriginalString;
  2241. // headers.odd.xml_filename = ans2;
  2242. // // Extract the first header reference
  2243. // var header_first_ref = sectPr.Elements().SingleOrDefault(x => x.Name.LocalName == "h
  2244. //eaderReference" && x.Attribute(XName.Get("type", DocX.w.NamespaceName)) != null && x.Attribute(XName.Get("type", DocX.w.NamespaceName)).Value == "first");
  2245. // string id3 = header_first_ref.Attribute(XName.Get("id", DocX.r.NamespaceName)).Value;
  2246. // var res3 = document.mainPart.GetRelationship(id3);
  2247. // string ans3 = res3.SourceUri.OriginalString;
  2248. // headers.first.xml_filename = ans3;
  2249. // // Extract the even footer reference
  2250. // var footer_even_ref = sectPr.Elements().SingleOrDefault(x => x.Name.LocalName == "footerReference" && x.Attribute(XName.Get("type", DocX.w.NamespaceName)) != null && x.Attribute(XName.Get("type", DocX.w.NamespaceName)).Value == "even");
  2251. // string id4 = footer_even_ref.Attribute(XName.Get("id", DocX.r.NamespaceName)).Value;
  2252. // var res4 = document.mainPart.GetRelationship(id4);
  2253. // string ans4 = res4.SourceUri.OriginalString;
  2254. // footers.even.xml_filename = ans4;
  2255. // // Extract the odd footer reference
  2256. // var footer_odd_ref = sectPr.Elements().SingleOrDefault(x => x.Name.LocalName == "footerReference" && x.Attribute(XName.Get("type", DocX.w.NamespaceName)) != null && x.Attribute(XName.Get("type", DocX.w.NamespaceName)).Value == "default");
  2257. // string id5 = footer_odd_ref.Attribute(XName.Get("id", DocX.r.NamespaceName)).Value;
  2258. // var res5 = document.mainPart.GetRelationship(id5);
  2259. // string ans5 = res5.SourceUri.OriginalString;
  2260. // footers.odd.xml_filename = ans5;
  2261. // // Extract the first footer reference
  2262. // var footer_first_ref = sectPr.Elements().SingleOrDefault(x => x.Name.LocalName == "footerReference" && x.Attribute(XName.Get("type", DocX.w.NamespaceName)) != null && x.Attribute(XName.Get("type", DocX.w.NamespaceName)).Value == "first");
  2263. // string id6 = footer_first_ref.Attribute(XName.Get("id", DocX.r.NamespaceName)).Value;
  2264. // var res6 = document.mainPart.GetRelationship(id6);
  2265. // string ans6 = res6.SourceUri.OriginalString;
  2266. // footers.first.xml_filename = ans6;
  2267. //}
  2268. document.Xml = document.mainDoc.Root.Element(w + "body");
  2269. document.headers = headers;
  2270. document.footers = footers;
  2271. document.settingsPart = HelperFunctions.CreateOrGetSettingsPart(package);
  2272. var ps = package.GetParts();
  2273. //document.endnotesPart = HelperFunctions.GetPart();
  2274. foreach (var rel in document.mainPart.GetRelationships())
  2275. {
  2276. string url = "/word/" + rel.TargetUri.OriginalString.Replace("/word/", "").Replace("file://", "");
  2277. switch (rel.RelationshipType)
  2278. {
  2279. case "http://schemas.openxmlformats.org/officeDocument/2006/relationships/endnotes":
  2280. document.endnotesPart = package.GetPart(new Uri(url, UriKind.Relative));
  2281. using (TextReader tr = new StreamReader(document.endnotesPart.GetStream()))
  2282. document.endnotes = XDocument.Load(tr);
  2283. break;
  2284. case "http://schemas.openxmlformats.org/officeDocument/2006/relationships/footnotes":
  2285. document.footnotesPart = package.GetPart(new Uri(url, UriKind.Relative));
  2286. using (TextReader tr = new StreamReader(document.footnotesPart.GetStream()))
  2287. document.footnotes = XDocument.Load(tr);
  2288. break;
  2289. case "http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles":
  2290. document.stylesPart = package.GetPart(new Uri(url, UriKind.Relative));
  2291. using (TextReader tr = new StreamReader(document.stylesPart.GetStream()))
  2292. document.styles = XDocument.Load(tr);
  2293. break;
  2294. case "http://schemas.microsoft.com/office/2007/relationships/stylesWithEffects":
  2295. document.stylesWithEffectsPart = package.GetPart(new Uri(url, UriKind.Relative));
  2296. using (TextReader tr = new StreamReader(document.stylesWithEffectsPart.GetStream()))
  2297. document.stylesWithEffects = XDocument.Load(tr);
  2298. break;
  2299. case "http://schemas.openxmlformats.org/officeDocument/2006/relationships/fontTable":
  2300. document.fontTablePart = package.GetPart(new Uri(url, UriKind.Relative));
  2301. using (TextReader tr = new StreamReader(document.fontTablePart.GetStream()))
  2302. document.fontTable = XDocument.Load(tr);
  2303. break;
  2304. case "http://schemas.openxmlformats.org/officeDocument/2006/relationships/numbering":
  2305. document.numberingPart = package.GetPart(new Uri(url, UriKind.Relative));
  2306. using (TextReader tr = new StreamReader(document.numberingPart.GetStream()))
  2307. document.numbering = XDocument.Load(tr);
  2308. break;
  2309. default:
  2310. break;
  2311. }
  2312. }
  2313. }
  2314. /// <summary>
  2315. /// Saves and copies the document into a new DocX object
  2316. /// </summary>
  2317. /// <returns>
  2318. /// Returns a new DocX object with an identical document
  2319. /// </returns>
  2320. /// <example>
  2321. /// <seealso cref="DocX.Load(System.IO.Stream)"/>
  2322. /// <seealso cref="DocX.Save()"/>
  2323. /// </example>
  2324. public DocX Copy()
  2325. {
  2326. MemoryStream ms = new MemoryStream();
  2327. SaveAs(ms);
  2328. ms.Seek(0, SeekOrigin.Begin);
  2329. return Load(ms);
  2330. }
  2331. /// <summary>
  2332. /// Loads a document into a DocX object using a Stream.
  2333. /// </summary>
  2334. /// <param name="stream">The Stream to load the document from.</param>
  2335. /// <returns>
  2336. /// Returns a DocX object which represents the document.
  2337. /// </returns>
  2338. /// <example>
  2339. /// Loading a document from a FileStream.
  2340. /// <code>
  2341. /// // Open a FileStream fs to a document.
  2342. /// using (FileStream fs = new FileStream(@"C:\Example\Test.docx", FileMode.Open))
  2343. /// {
  2344. /// // Load the document using fs.
  2345. /// using (DocX document = DocX.Load(fs))
  2346. /// {
  2347. /// // Do something with the document here.
  2348. ///
  2349. /// // Save all changes made to the document.
  2350. /// document.Save();
  2351. /// }// Release this document from memory.
  2352. /// }
  2353. /// </code>
  2354. /// </example>
  2355. /// <example>
  2356. /// Loading a document from a SharePoint site.
  2357. /// <code>
  2358. /// // Get the SharePoint site that you want to access.
  2359. /// using (SPSite mySite = new SPSite("http://server/sites/site"))
  2360. /// {
  2361. /// // Open a connection to the SharePoint site
  2362. /// using (SPWeb myWeb = mySite.OpenWeb())
  2363. /// {
  2364. /// // Grab a document stored on this site.
  2365. /// SPFile file = web.GetFile("Source_Folder_Name/Source_File");
  2366. ///
  2367. /// // DocX.Load requires a Stream, so open a Stream to this document.
  2368. /// Stream str = new MemoryStream(file.OpenBinary());
  2369. ///
  2370. /// // Load the file using the Stream str.
  2371. /// using (DocX document = DocX.Load(str))
  2372. /// {
  2373. /// // Do something with the document here.
  2374. ///
  2375. /// // Save all changes made to the document.
  2376. /// document.Save();
  2377. /// }// Release this document from memory.
  2378. /// }
  2379. /// }
  2380. /// </code>
  2381. /// </example>
  2382. /// <seealso cref="DocX.Load(string)"/>
  2383. /// <seealso cref="DocX.Save()"/>
  2384. public static DocX Load(Stream stream)
  2385. {
  2386. MemoryStream ms = new MemoryStream();
  2387. stream.Position = 0;
  2388. byte[] data = new byte[stream.Length];
  2389. stream.Read(data, 0, (int)stream.Length);
  2390. ms.Write(data, 0, (int)stream.Length);
  2391. // Open the docx package
  2392. Package package = Package.Open(ms, FileMode.Open, FileAccess.ReadWrite);
  2393. DocX document = PostLoad(ref package);
  2394. document.package = package;
  2395. document.memoryStream = ms;
  2396. document.stream = stream;
  2397. return document;
  2398. }
  2399. /// <summary>
  2400. /// Loads a document into a DocX object using a fully qualified or relative filename.
  2401. /// </summary>
  2402. /// <param name="filename">The fully qualified or relative filename.</param>
  2403. /// <returns>
  2404. /// Returns a DocX object which represents the document.
  2405. /// </returns>
  2406. /// <example>
  2407. /// <code>
  2408. /// // Load a document using its fully qualified filename
  2409. /// using (DocX document = DocX.Load(@"C:\Example\Test.docx"))
  2410. /// {
  2411. /// // Do something with the document here
  2412. ///
  2413. /// // Save all changes made to document.
  2414. /// document.Save();
  2415. /// }// Release this document from memory.
  2416. /// </code>
  2417. /// <code>
  2418. /// // Load a document using its relative filename.
  2419. /// using(DocX document = DocX.Load(@"..\..\Test.docx"))
  2420. /// {
  2421. /// // Do something with the document here.
  2422. ///
  2423. /// // Save all changes made to document.
  2424. /// document.Save();
  2425. /// }// Release this document from memory.
  2426. /// </code>
  2427. /// <seealso cref="DocX.Load(System.IO.Stream)"/>
  2428. /// <seealso cref="DocX.Save()"/>
  2429. /// </example>
  2430. public static DocX Load(string filename)
  2431. {
  2432. if (!File.Exists(filename))
  2433. throw new FileNotFoundException(string.Format("File could not be found {0}", filename));
  2434. MemoryStream ms = new MemoryStream();
  2435. using (FileStream fs = new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.Read))
  2436. {
  2437. byte[] data = new byte[fs.Length];
  2438. fs.Read(data, 0, (int)fs.Length);
  2439. ms.Write(data, 0, (int)fs.Length);
  2440. }
  2441. // Open the docx package
  2442. Package package = Package.Open(ms, FileMode.Open, FileAccess.ReadWrite);
  2443. DocX document = PostLoad(ref package);
  2444. document.package = package;
  2445. document.filename = filename;
  2446. document.memoryStream = ms;
  2447. return document;
  2448. }
  2449. ///<summary>
  2450. /// Applies document template to the document. Document template may include styles, headers, footers, properties, etc. as well as text content.
  2451. ///</summary>
  2452. ///<param name="templateFilePath">The path to the document template file.</param>
  2453. ///<exception cref="FileNotFoundException">The document template file not found.</exception>
  2454. public void ApplyTemplate(string templateFilePath)
  2455. {
  2456. ApplyTemplate(templateFilePath, true);
  2457. }
  2458. ///<summary>
  2459. /// Applies document template to the document. Document template may include styles, headers, footers, properties, etc. as well as text content.
  2460. ///</summary>
  2461. ///<param name="templateFilePath">The path to the document template file.</param>
  2462. ///<param name="includeContent">Whether to copy the document template text content to document.</param>
  2463. ///<exception cref="FileNotFoundException">The document template file not found.</exception>
  2464. public void ApplyTemplate(string templateFilePath, bool includeContent)
  2465. {
  2466. if (!File.Exists(templateFilePath))
  2467. {
  2468. throw new FileNotFoundException(string.Format("File could not be found {0}", templateFilePath));
  2469. }
  2470. using (FileStream packageStream = new FileStream(templateFilePath, FileMode.Open, FileAccess.Read))
  2471. {
  2472. ApplyTemplate(packageStream, includeContent);
  2473. }
  2474. }
  2475. ///<summary>
  2476. /// Applies document template to the document. Document template may include styles, headers, footers, properties, etc. as well as text content.
  2477. ///</summary>
  2478. ///<param name="templateStream">The stream of the document template file.</param>
  2479. public void ApplyTemplate(Stream templateStream)
  2480. {
  2481. ApplyTemplate(templateStream, true);
  2482. }
  2483. ///<summary>
  2484. /// Applies document template to the document. Document template may include styles, headers, footers, properties, etc. as well as text content.
  2485. ///</summary>
  2486. ///<param name="templateStream">The stream of the document template file.</param>
  2487. ///<param name="includeContent">Whether to copy the document template text content to document.</param>
  2488. public void ApplyTemplate(Stream templateStream, bool includeContent)
  2489. {
  2490. Package templatePackage = Package.Open(templateStream);
  2491. try
  2492. {
  2493. PackagePart documentPart = null;
  2494. XDocument documentDoc = null;
  2495. foreach (PackagePart packagePart in templatePackage.GetParts())
  2496. {
  2497. switch (packagePart.Uri.ToString())
  2498. {
  2499. case "/word/document.xml":
  2500. documentPart = packagePart;
  2501. using (XmlReader xr = XmlReader.Create(packagePart.GetStream(FileMode.Open, FileAccess.Read)))
  2502. {
  2503. documentDoc = XDocument.Load(xr);
  2504. }
  2505. break;
  2506. case "/_rels/.rels":
  2507. if (!package.PartExists(packagePart.Uri))
  2508. {
  2509. package.CreatePart(packagePart.Uri, packagePart.ContentType, packagePart.CompressionOption);
  2510. }
  2511. PackagePart globalRelsPart = package.GetPart(packagePart.Uri);
  2512. using (
  2513. StreamReader tr = new StreamReader(
  2514. packagePart.GetStream(FileMode.Open, FileAccess.Read), Encoding.UTF8))
  2515. {
  2516. using (
  2517. StreamWriter tw = new StreamWriter(
  2518. new PackagePartStream(globalRelsPart.GetStream(FileMode.Create, FileAccess.Write)), Encoding.UTF8))
  2519. {
  2520. tw.Write(tr.ReadToEnd());
  2521. }
  2522. }
  2523. break;
  2524. case "/word/_rels/document.xml.rels":
  2525. break;
  2526. default:
  2527. if (!package.PartExists(packagePart.Uri))
  2528. {
  2529. package.CreatePart(packagePart.Uri, packagePart.ContentType, packagePart.CompressionOption);
  2530. }
  2531. Encoding packagePartEncoding = Encoding.Default;
  2532. if (packagePart.Uri.ToString().EndsWith(".xml") || packagePart.Uri.ToString().EndsWith(".rels"))
  2533. {
  2534. packagePartEncoding = Encoding.UTF8;
  2535. }
  2536. PackagePart nativePart = package.GetPart(packagePart.Uri);
  2537. using (
  2538. StreamReader tr = new StreamReader(
  2539. packagePart.GetStream(FileMode.Open, FileAccess.Read), packagePartEncoding))
  2540. {
  2541. using (
  2542. StreamWriter tw = new StreamWriter(
  2543. new PackagePartStream(nativePart.GetStream(FileMode.Create, FileAccess.Write)), tr.CurrentEncoding))
  2544. {
  2545. tw.Write(tr.ReadToEnd());
  2546. }
  2547. }
  2548. break;
  2549. }
  2550. }
  2551. if (documentPart != null)
  2552. {
  2553. string mainContentType = documentPart.ContentType.Replace("template.main", "document.main");
  2554. if (package.PartExists(documentPart.Uri))
  2555. {
  2556. package.DeletePart(documentPart.Uri);
  2557. }
  2558. PackagePart documentNewPart = package.CreatePart(
  2559. documentPart.Uri, mainContentType, documentPart.CompressionOption);
  2560. using (XmlWriter xw = XmlWriter.Create(new PackagePartStream(documentNewPart.GetStream(FileMode.Create, FileAccess.Write))))
  2561. {
  2562. documentDoc.WriteTo(xw);
  2563. }
  2564. foreach (PackageRelationship documentPartRel in documentPart.GetRelationships())
  2565. {
  2566. documentNewPart.CreateRelationship(
  2567. documentPartRel.TargetUri,
  2568. documentPartRel.TargetMode,
  2569. documentPartRel.RelationshipType,
  2570. documentPartRel.Id);
  2571. }
  2572. mainPart = documentNewPart;
  2573. mainDoc = documentDoc;
  2574. PopulateDocument(this, templatePackage);
  2575. // DragonFire: I added next line and recovered ApplyTemplate method.
  2576. // I do it, becouse PopulateDocument(...) writes into field "settingsPart" the part of Template's package
  2577. // and after line "templatePackage.Close();" in finally, field "settingsPart" becomes not available and method "Save" throw an exception...
  2578. // That's why I recreated settingsParts and unlinked it from Template's package =)
  2579. settingsPart = HelperFunctions.CreateOrGetSettingsPart(package);
  2580. }
  2581. if (!includeContent)
  2582. {
  2583. foreach (Paragraph paragraph in Paragraphs)
  2584. {
  2585. paragraph.Remove(false);
  2586. }
  2587. }
  2588. }
  2589. finally
  2590. {
  2591. package.Flush();
  2592. var documentRelsPart = package.GetPart(new Uri("/word/_rels/document.xml.rels", UriKind.Relative));
  2593. using (TextReader tr = new StreamReader(documentRelsPart.GetStream(FileMode.Open, FileAccess.Read)))
  2594. {
  2595. tr.Read();
  2596. }
  2597. templatePackage.Close();
  2598. PopulateDocument(Document, package);
  2599. }
  2600. }
  2601. /// <summary>
  2602. /// Add an Image into this document from a fully qualified or relative filename.
  2603. /// </summary>
  2604. /// <param name="filename">The fully qualified or relative filename.</param>
  2605. /// <returns>An Image file.</returns>
  2606. /// <example>
  2607. /// Add an Image into this document from a fully qualified filename.
  2608. /// <code>
  2609. /// // Load a document.
  2610. /// using (DocX document = DocX.Load(@"C:\Example\Test.docx"))
  2611. /// {
  2612. /// // Add an Image from a file.
  2613. /// document.AddImage(@"C:\Example\Image.png");
  2614. ///
  2615. /// // Save all changes made to this document.
  2616. /// document.Save();
  2617. /// }// Release this document from memory.
  2618. /// </code>
  2619. /// </example>
  2620. /// <seealso cref="AddImage(System.IO.Stream)"/>
  2621. /// <seealso cref="Paragraph.InsertPicture"/>
  2622. public Image AddImage(string filename)
  2623. {
  2624. string contentType = "";
  2625. // The extension this file has will be taken to be its format.
  2626. switch (Path.GetExtension(filename))
  2627. {
  2628. case ".tiff": contentType = "image/tif"; break;
  2629. case ".tif": contentType = "image/tif"; break;
  2630. case ".png": contentType = "image/png"; break;
  2631. case ".bmp": contentType = "image/png"; break;
  2632. case ".gif": contentType = "image/gif"; break;
  2633. case ".jpg": contentType = "image/jpg"; break;
  2634. case ".jpeg": contentType = "image/jpeg"; break;
  2635. default: contentType = "image/jpg"; break;
  2636. }
  2637. return AddImage(filename, contentType);
  2638. }
  2639. /// <summary>
  2640. /// Add an Image into this document from a Stream.
  2641. /// </summary>
  2642. /// <param name="stream">A Stream stream.</param>
  2643. /// <returns>An Image file.</returns>
  2644. /// <example>
  2645. /// Add an Image into a document using a Stream.
  2646. /// <code>
  2647. /// // Open a FileStream fs to an Image.
  2648. /// using (FileStream fs = new FileStream(@"C:\Example\Image.jpg", FileMode.Open))
  2649. /// {
  2650. /// // Load a document.
  2651. /// using (DocX document = DocX.Load(@"C:\Example\Test.docx"))
  2652. /// {
  2653. /// // Add an Image from a filestream fs.
  2654. /// document.AddImage(fs);
  2655. ///
  2656. /// // Save all changes made to this document.
  2657. /// document.Save();
  2658. /// }// Release this document from memory.
  2659. /// }
  2660. /// </code>
  2661. /// </example>
  2662. /// <seealso cref="AddImage(string)"/>
  2663. /// <seealso cref="Paragraph.InsertPicture"/>
  2664. public Image AddImage(Stream stream)
  2665. {
  2666. return AddImage(stream as object);
  2667. }
  2668. /// <summary>
  2669. /// Adds a hyperlink to a document and creates a Paragraph which uses it.
  2670. /// </summary>
  2671. /// <param name="text">The text as displayed by the hyperlink.</param>
  2672. /// <param name="uri">The hyperlink itself.</param>
  2673. /// <returns>Returns a hyperlink that can be inserted into a Paragraph.</returns>
  2674. /// <example>
  2675. /// Adds a hyperlink to a document and creates a Paragraph which uses it.
  2676. /// <code>
  2677. /// // Create a document.
  2678. /// using (DocX document = DocX.Create(@"Test.docx"))
  2679. /// {
  2680. /// // Add a hyperlink to this document.
  2681. /// Hyperlink h = document.AddHyperlink("Google", new Uri("http://www.google.com"));
  2682. ///
  2683. /// // Add a new Paragraph to this document.
  2684. /// Paragraph p = document.InsertParagraph();
  2685. /// p.Append("My favourite search engine is ");
  2686. /// p.AppendHyperlink(h);
  2687. /// p.Append(", I think it's great.");
  2688. ///
  2689. /// // Save all changes made to this document.
  2690. /// document.Save();
  2691. /// }
  2692. /// </code>
  2693. /// </example>
  2694. public Hyperlink AddHyperlink(string text, Uri uri)
  2695. {
  2696. XElement i = new XElement
  2697. (
  2698. XName.Get("hyperlink", w.NamespaceName),
  2699. new XAttribute(r + "id", string.Empty),
  2700. new XAttribute(w + "history", "1"),
  2701. new XElement(XName.Get("r", w.NamespaceName),
  2702. new XElement(XName.Get("rPr", w.NamespaceName),
  2703. new XElement(XName.Get("rStyle", w.NamespaceName),
  2704. new XAttribute(w + "val", "Hyperlink"))),
  2705. new XElement(XName.Get("t", w.NamespaceName), text))
  2706. );
  2707. Hyperlink h = new Hyperlink(this, mainPart, i);
  2708. h.text = text;
  2709. h.uri = uri;
  2710. AddHyperlinkStyleIfNotPresent();
  2711. return h;
  2712. }
  2713. internal void AddHyperlinkStyleIfNotPresent()
  2714. {
  2715. Uri word_styles_Uri = new Uri("/word/styles.xml", UriKind.Relative);
  2716. // If the internal document contains no /word/styles.xml create one.
  2717. if (!package.PartExists(word_styles_Uri))
  2718. HelperFunctions.AddDefaultStylesXml(package);
  2719. // Load the styles.xml into memory.
  2720. XDocument word_styles;
  2721. using (TextReader tr = new StreamReader(package.GetPart(word_styles_Uri).GetStream()))
  2722. word_styles = XDocument.Load(tr);
  2723. bool hyperlinkStyleExists =
  2724. (
  2725. from s in word_styles.Element(w + "styles").Elements()
  2726. let styleId = s.Attribute(XName.Get("styleId", w.NamespaceName))
  2727. where (styleId != null && styleId.Value == "Hyperlink")
  2728. select s
  2729. ).Count() > 0;
  2730. if (!hyperlinkStyleExists)
  2731. {
  2732. XElement style = new XElement
  2733. (
  2734. w + "style",
  2735. new XAttribute(w + "type", "character"),
  2736. new XAttribute(w + "styleId", "Hyperlink"),
  2737. new XElement(w + "name", new XAttribute(w + "val", "Hyperlink")),
  2738. new XElement(w + "basedOn", new XAttribute(w + "val", "DefaultParagraphFont")),
  2739. new XElement(w + "uiPriority", new XAttribute(w + "val", "99")),
  2740. new XElement(w + "unhideWhenUsed"),
  2741. new XElement(w + "rsid", new XAttribute(w + "val", "0005416C")),
  2742. new XElement
  2743. (
  2744. w + "rPr",
  2745. new XElement(w + "color", new XAttribute(w + "val", "0000FF"), new XAttribute(w + "themeColor", "hyperlink")),
  2746. new XElement
  2747. (
  2748. w + "u",
  2749. new XAttribute(w + "val", "single")
  2750. )
  2751. )
  2752. );
  2753. word_styles.Element(w + "styles").Add(style);
  2754. // Save the styles document.
  2755. using (TextWriter tw = new StreamWriter(new PackagePartStream(package.GetPart(word_styles_Uri).GetStream())))
  2756. word_styles.Save(tw);
  2757. }
  2758. }
  2759. private string GetNextFreeRelationshipID()
  2760. {
  2761. int id = (
  2762. from r in mainPart.GetRelationships()
  2763. where r.Id.Substring(0, 3).Equals("rId")
  2764. select int.Parse(r.Id.Substring(3))
  2765. ).DefaultIfEmpty().Max();
  2766. // The conventiom for ids is rid01, rid02, etc
  2767. string newId = id.ToString();
  2768. int result;
  2769. if (int.TryParse(newId, out result))
  2770. return ("rId" + (result + 1));
  2771. String guid = String.Empty;
  2772. do
  2773. {
  2774. guid = Guid.NewGuid().ToString();
  2775. } while (Char.IsDigit(guid[0]));
  2776. return guid;
  2777. }
  2778. /// <summary>
  2779. /// Adds three new Headers to this document. One for the first page, one for odd pages and one for even pages.
  2780. /// </summary>
  2781. /// <example>
  2782. /// // Create a document.
  2783. /// using (DocX document = DocX.Create(@"Test.docx"))
  2784. /// {
  2785. /// // Add header support to this document.
  2786. /// document.AddHeaders();
  2787. ///
  2788. /// // Get a collection of all headers in this document.
  2789. /// Headers headers = document.Headers;
  2790. ///
  2791. /// // The header used for the first page of this document.
  2792. /// Header first = headers.first;
  2793. ///
  2794. /// // The header used for odd pages of this document.
  2795. /// Header odd = headers.odd;
  2796. ///
  2797. /// // The header used for even pages of this document.
  2798. /// Header even = headers.even;
  2799. ///
  2800. /// // Force the document to use a different header for first, odd and even pages.
  2801. /// document.DifferentFirstPage = true;
  2802. /// document.DifferentOddAndEvenPages = true;
  2803. ///
  2804. /// // Content can be added to the Headers in the same manor that it would be added to the main document.
  2805. /// Paragraph p = first.InsertParagraph();
  2806. /// p.Append("This is the first pages header.");
  2807. ///
  2808. /// // Save all changes to this document.
  2809. /// document.Save();
  2810. /// }// Release this document from memory.
  2811. /// </example>
  2812. public void AddHeaders()
  2813. {
  2814. AddHeadersOrFooters(true);
  2815. headers.odd = Document.GetHeaderByType("default");
  2816. headers.even = Document.GetHeaderByType("even");
  2817. headers.first = Document.GetHeaderByType("first");
  2818. }
  2819. /// <summary>
  2820. /// Adds three new Footers to this document. One for the first page, one for odd pages and one for even pages.
  2821. /// </summary>
  2822. /// <example>
  2823. /// // Create a document.
  2824. /// using (DocX document = DocX.Create(@"Test.docx"))
  2825. /// {
  2826. /// // Add footer support to this document.
  2827. /// document.AddFooters();
  2828. ///
  2829. /// // Get a collection of all footers in this document.
  2830. /// Footers footers = document.Footers;
  2831. ///
  2832. /// // The footer used for the first page of this document.
  2833. /// Footer first = footers.first;
  2834. ///
  2835. /// // The footer used for odd pages of this document.
  2836. /// Footer odd = footers.odd;
  2837. ///
  2838. /// // The footer used for even pages of this document.
  2839. /// Footer even = footers.even;
  2840. ///
  2841. /// // Force the document to use a different footer for first, odd and even pages.
  2842. /// document.DifferentFirstPage = true;
  2843. /// document.DifferentOddAndEvenPages = true;
  2844. ///
  2845. /// // Content can be added to the Footers in the same manor that it would be added to the main document.
  2846. /// Paragraph p = first.InsertParagraph();
  2847. /// p.Append("This is the first pages footer.");
  2848. ///
  2849. /// // Save all changes to this document.
  2850. /// document.Save();
  2851. /// }// Release this document from memory.
  2852. /// </example>
  2853. public void AddFooters()
  2854. {
  2855. AddHeadersOrFooters(false);
  2856. footers.odd = Document.GetFooterByType("default");
  2857. footers.even = Document.GetFooterByType("even");
  2858. footers.first = Document.GetFooterByType("first");
  2859. }
  2860. /// <summary>
  2861. /// Adds a Header to a document.
  2862. /// If the document already contains a Header it will be replaced.
  2863. /// </summary>
  2864. /// <returns>The Header that was added to the document.</returns>
  2865. internal void AddHeadersOrFooters(bool b)
  2866. {
  2867. string element = "ftr";
  2868. string reference = "footer";
  2869. if (b)
  2870. {
  2871. element = "hdr";
  2872. reference = "header";
  2873. }
  2874. DeleteHeadersOrFooters(b);
  2875. XElement sectPr = mainDoc.Root.Element(w + "body").Element(w + "sectPr");
  2876. for (int i = 1; i < 4; i++)
  2877. {
  2878. string header_uri = string.Format("/word/{0}{1}.xml", reference, i);
  2879. PackagePart headerPart = package.CreatePart(new Uri(header_uri, UriKind.Relative), string.Format("application/vnd.openxmlformats-officedocument.wordprocessingml.{0}+xml", reference), CompressionOption.Normal);
  2880. PackageRelationship headerRelationship = mainPart.CreateRelationship(headerPart.Uri, TargetMode.Internal, string.Format("http://schemas.openxmlformats.org/officeDocument/2006/relationships/{0}", reference));
  2881. XDocument header;
  2882. // Load the document part into a XDocument object
  2883. using (TextReader tr = new StreamReader(headerPart.GetStream(FileMode.Create, FileAccess.ReadWrite)))
  2884. {
  2885. header = XDocument.Parse
  2886. (string.Format(@"<?xml version=""1.0"" encoding=""utf-16"" standalone=""yes""?>
  2887. <w:{0} 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"">
  2888. <w:p w:rsidR=""009D472B"" w:rsidRDefault=""009D472B"">
  2889. <w:pPr>
  2890. <w:pStyle w:val=""{1}"" />
  2891. </w:pPr>
  2892. </w:p>
  2893. </w:{0}>", element, reference)
  2894. );
  2895. }
  2896. // Save the main document
  2897. using (TextWriter tw = new StreamWriter(new PackagePartStream(headerPart.GetStream(FileMode.Create, FileAccess.Write))))
  2898. header.Save(tw, SaveOptions.None);
  2899. string type;
  2900. switch (i)
  2901. {
  2902. case 1: type = "default"; break;
  2903. case 2: type = "even"; break;
  2904. case 3: type = "first"; break;
  2905. default: throw new ArgumentOutOfRangeException();
  2906. }
  2907. sectPr.Add
  2908. (
  2909. new XElement
  2910. (
  2911. w + string.Format("{0}Reference", reference),
  2912. new XAttribute(w + "type", type),
  2913. new XAttribute(r + "id", headerRelationship.Id)
  2914. )
  2915. );
  2916. }
  2917. }
  2918. internal void DeleteHeadersOrFooters(bool b)
  2919. {
  2920. string reference = "footer";
  2921. if (b)
  2922. reference = "header";
  2923. // Get all header Relationships in this document.
  2924. var header_relationships = mainPart.GetRelationshipsByType(string.Format("http://schemas.openxmlformats.org/officeDocument/2006/relationships/{0}", reference));
  2925. foreach (PackageRelationship header_relationship in header_relationships)
  2926. {
  2927. // Get the TargetUri for this Part.
  2928. Uri header_uri = header_relationship.TargetUri;
  2929. // Check to see if the document actually contains the Part.
  2930. if (!header_uri.OriginalString.StartsWith("/word/"))
  2931. header_uri = new Uri("/word/" + header_uri.OriginalString, UriKind.Relative);
  2932. if (package.PartExists(header_uri))
  2933. {
  2934. // Delete the Part
  2935. package.DeletePart(header_uri);
  2936. // Get all references to this Relationship in the document.
  2937. var query =
  2938. (
  2939. from e in mainDoc.Descendants(XName.Get("body", w.NamespaceName)).Descendants()
  2940. where (e.Name.LocalName == string.Format("{0}Reference", reference)) && (e.Attribute(r + "id").Value == header_relationship.Id)
  2941. select e
  2942. );
  2943. // Remove all references to this Relationship in the document.
  2944. for (int i = 0; i < query.Count(); i++)
  2945. query.ElementAt(i).Remove();
  2946. // Delete the Relationship.
  2947. package.DeleteRelationship(header_relationship.Id);
  2948. }
  2949. }
  2950. }
  2951. internal Image AddImage(object o, string contentType = "image/jpeg")
  2952. {
  2953. // Open a Stream to the new image being added.
  2954. Stream newImageStream;
  2955. if (o is string)
  2956. newImageStream = new FileStream(o as string, FileMode.Open, FileAccess.Read);
  2957. else
  2958. newImageStream = o as Stream;
  2959. // Get all image parts in word\document.xml
  2960. PackageRelationshipCollection relationshipsByImages = mainPart.GetRelationshipsByType("http://schemas.openxmlformats.org/officeDocument/2006/relationships/image");
  2961. List<PackagePart> imageParts = relationshipsByImages.Select(ir => package.GetParts().FirstOrDefault(p => p.Uri.ToString().EndsWith(ir.TargetUri.ToString()))).Where(e => e != null).ToList();
  2962. foreach (PackagePart relsPart in package.GetParts().Where(part => part.Uri.ToString().Contains("/word/")).Where(part => part.ContentType.Equals("application/vnd.openxmlformats-package.relationships+xml")))
  2963. {
  2964. XDocument relsPartContent;
  2965. using (TextReader tr = new StreamReader(relsPart.GetStream(FileMode.Open, FileAccess.Read)))
  2966. relsPartContent = XDocument.Load(tr);
  2967. IEnumerable<XElement> imageRelationships =
  2968. relsPartContent.Root.Elements().Where
  2969. (
  2970. imageRel =>
  2971. imageRel.Attribute(XName.Get("Type")).Value.Equals("http://schemas.openxmlformats.org/officeDocument/2006/relationships/image")
  2972. );
  2973. foreach (XElement imageRelationship in imageRelationships)
  2974. {
  2975. if (imageRelationship.Attribute(XName.Get("Target")) != null)
  2976. {
  2977. string targetMode = string.Empty;
  2978. XAttribute targetModeAttibute = imageRelationship.Attribute(XName.Get("TargetMode"));
  2979. if (targetModeAttibute != null)
  2980. {
  2981. targetMode = targetModeAttibute.Value;
  2982. }
  2983. if (!targetMode.Equals("External"))
  2984. {
  2985. string imagePartUri = Path.Combine(Path.GetDirectoryName(relsPart.Uri.ToString()), imageRelationship.Attribute(XName.Get("Target")).Value);
  2986. imagePartUri = Path.GetFullPath(imagePartUri.Replace("\\_rels", string.Empty));
  2987. imagePartUri = imagePartUri.Replace(Path.GetFullPath("\\"), string.Empty).Replace("\\", "/");
  2988. if (!imagePartUri.StartsWith("/"))
  2989. imagePartUri = "/" + imagePartUri;
  2990. PackagePart imagePart = package.GetPart(new Uri(imagePartUri, UriKind.Relative));
  2991. imageParts.Add(imagePart);
  2992. }
  2993. }
  2994. }
  2995. }
  2996. // Loop through each image part in this document.
  2997. foreach (PackagePart pp in imageParts)
  2998. {
  2999. // Open a tempory Stream to this image part.
  3000. using (Stream tempStream = pp.GetStream(FileMode.Open, FileAccess.Read))
  3001. {
  3002. // Compare this image to the new image being added.
  3003. if (HelperFunctions.IsSameFile(tempStream, newImageStream))
  3004. {
  3005. // Get the image object for this image part
  3006. string id = mainPart.GetRelationshipsByType("http://schemas.openxmlformats.org/officeDocument/2006/relationships/image")
  3007. .Where(r => r.TargetUri == pp.Uri)
  3008. .Select(r => r.Id).First();
  3009. // Return the Image object
  3010. return Images.Where(i => i.Id == id).First();
  3011. }
  3012. }
  3013. }
  3014. string imgPartUriPath = string.Empty;
  3015. string extension = contentType.Substring(contentType.LastIndexOf("/") + 1);
  3016. do
  3017. {
  3018. // Create a new image part.
  3019. imgPartUriPath = string.Format
  3020. (
  3021. "/word/media/{0}.{1}",
  3022. Guid.NewGuid(), // The unique part.
  3023. extension
  3024. );
  3025. } while (package.PartExists(new Uri(imgPartUriPath, UriKind.Relative)));
  3026. // We are now guareenteed that imgPartUriPath is unique.
  3027. PackagePart img = package.CreatePart(new Uri(imgPartUriPath, UriKind.Relative), contentType, CompressionOption.Normal);
  3028. // Create a new image relationship
  3029. PackageRelationship rel = mainPart.CreateRelationship(img.Uri, TargetMode.Internal, "http://schemas.openxmlformats.org/officeDocument/2006/relationships/image");
  3030. // Open a Stream to the newly created Image part.
  3031. using (Stream stream = new PackagePartStream(img.GetStream(FileMode.Create, FileAccess.Write)))
  3032. {
  3033. // Using the Stream to the real image, copy this streams data into the newly create Image part.
  3034. using (newImageStream)
  3035. {
  3036. byte[] bytes = new byte[newImageStream.Length];
  3037. newImageStream.Read(bytes, 0, (int)newImageStream.Length);
  3038. stream.Write(bytes, 0, (int)newImageStream.Length);
  3039. }// Close the Stream to the new image.
  3040. }// Close the Stream to the new image part.
  3041. return new Image(this, rel);
  3042. }
  3043. /// <summary>
  3044. /// Save this document back to the location it was loaded from.
  3045. /// </summary>
  3046. /// <example>
  3047. /// <code>
  3048. /// // Load a document.
  3049. /// using (DocX document = DocX.Load(@"C:\Example\Test.docx"))
  3050. /// {
  3051. /// // Add an Image from a file.
  3052. /// document.AddImage(@"C:\Example\Image.jpg");
  3053. ///
  3054. /// // Save all changes made to this document.
  3055. /// document.Save();
  3056. /// }// Release this document from memory.
  3057. /// </code>
  3058. /// </example>
  3059. /// <seealso cref="DocX.SaveAs(string)"/>
  3060. /// <seealso cref="DocX.Load(System.IO.Stream)"/>
  3061. /// <seealso cref="DocX.Load(string)"/>
  3062. /// <!--
  3063. /// Bug found and fixed by krugs525 on August 12 2009.
  3064. /// Use TFS compare to see exact code change.
  3065. /// -->
  3066. public void Save()
  3067. {
  3068. Headers headers = Headers;
  3069. // Save the main document
  3070. using (TextWriter tw = new StreamWriter(new PackagePartStream(mainPart.GetStream(FileMode.Create, FileAccess.Write))))
  3071. mainDoc.Save(tw, SaveOptions.None);
  3072. if (settings == null)
  3073. {
  3074. using (TextReader tr = new StreamReader(settingsPart.GetStream()))
  3075. settings = XDocument.Load(tr);
  3076. }
  3077. XElement body = mainDoc.Root.Element(w + "body");
  3078. XElement sectPr = body.Descendants(w + "sectPr").FirstOrDefault();
  3079. if (sectPr != null)
  3080. {
  3081. var evenHeaderRef =
  3082. (
  3083. from e in mainDoc.Descendants(w + "headerReference")
  3084. let type = e.Attribute(w + "type")
  3085. where type != null && type.Value.Equals("even", StringComparison.CurrentCultureIgnoreCase)
  3086. select e.Attribute(r + "id").Value
  3087. ).LastOrDefault();
  3088. if (evenHeaderRef != null)
  3089. {
  3090. XElement even = headers.even.Xml;
  3091. Uri target = PackUriHelper.ResolvePartUri
  3092. (
  3093. mainPart.Uri,
  3094. mainPart.GetRelationship(evenHeaderRef).TargetUri
  3095. );
  3096. using (TextWriter tw = new StreamWriter(new PackagePartStream(package.GetPart(target).GetStream(FileMode.Create, FileAccess.Write))))
  3097. {
  3098. new XDocument
  3099. (
  3100. new XDeclaration("1.0", "UTF-8", "yes"),
  3101. even
  3102. ).Save(tw, SaveOptions.None);
  3103. }
  3104. }
  3105. var oddHeaderRef =
  3106. (
  3107. from e in mainDoc.Descendants(w + "headerReference")
  3108. let type = e.Attribute(w + "type")
  3109. where type != null && type.Value.Equals("default", StringComparison.CurrentCultureIgnoreCase)
  3110. select e.Attribute(r + "id").Value
  3111. ).LastOrDefault();
  3112. if (oddHeaderRef != null)
  3113. {
  3114. XElement odd = headers.odd.Xml;
  3115. Uri target = PackUriHelper.ResolvePartUri
  3116. (
  3117. mainPart.Uri,
  3118. mainPart.GetRelationship(oddHeaderRef).TargetUri
  3119. );
  3120. // Save header1
  3121. using (TextWriter tw = new StreamWriter(new PackagePartStream(package.GetPart(target).GetStream(FileMode.Create, FileAccess.Write))))
  3122. {
  3123. new XDocument
  3124. (
  3125. new XDeclaration("1.0", "UTF-8", "yes"),
  3126. odd
  3127. ).Save(tw, SaveOptions.None);
  3128. }
  3129. }
  3130. var firstHeaderRef =
  3131. (
  3132. from e in mainDoc.Descendants(w + "headerReference")
  3133. let type = e.Attribute(w + "type")
  3134. where type != null && type.Value.Equals("first", StringComparison.CurrentCultureIgnoreCase)
  3135. select e.Attribute(r + "id").Value
  3136. ).LastOrDefault();
  3137. if (firstHeaderRef != null)
  3138. {
  3139. XElement first = headers.first.Xml;
  3140. Uri target = PackUriHelper.ResolvePartUri
  3141. (
  3142. mainPart.Uri,
  3143. mainPart.GetRelationship(firstHeaderRef).TargetUri
  3144. );
  3145. // Save header3
  3146. using (TextWriter tw = new StreamWriter(new PackagePartStream(package.GetPart(target).GetStream(FileMode.Create, FileAccess.Write))))
  3147. {
  3148. new XDocument
  3149. (
  3150. new XDeclaration("1.0", "UTF-8", "yes"),
  3151. first
  3152. ).Save(tw, SaveOptions.None);
  3153. }
  3154. }
  3155. var oddFooterRef =
  3156. (
  3157. from e in mainDoc.Descendants(w + "footerReference")
  3158. let type = e.Attribute(w + "type")
  3159. where type != null && type.Value.Equals("default", StringComparison.CurrentCultureIgnoreCase)
  3160. select e.Attribute(r + "id").Value
  3161. ).LastOrDefault();
  3162. if (oddFooterRef != null)
  3163. {
  3164. XElement odd = footers.odd.Xml;
  3165. Uri target = PackUriHelper.ResolvePartUri
  3166. (
  3167. mainPart.Uri,
  3168. mainPart.GetRelationship(oddFooterRef).TargetUri
  3169. );
  3170. // Save header1
  3171. using (TextWriter tw = new StreamWriter(new PackagePartStream(package.GetPart(target).GetStream(FileMode.Create, FileAccess.Write))))
  3172. {
  3173. new XDocument
  3174. (
  3175. new XDeclaration("1.0", "UTF-8", "yes"),
  3176. odd
  3177. ).Save(tw, SaveOptions.None);
  3178. }
  3179. }
  3180. var evenFooterRef =
  3181. (
  3182. from e in mainDoc.Descendants(w + "footerReference")
  3183. let type = e.Attribute(w + "type")
  3184. where type != null && type.Value.Equals("even", StringComparison.CurrentCultureIgnoreCase)
  3185. select e.Attribute(r + "id").Value
  3186. ).LastOrDefault();
  3187. if (evenFooterRef != null)
  3188. {
  3189. XElement even = footers.even.Xml;
  3190. Uri target = PackUriHelper.ResolvePartUri
  3191. (
  3192. mainPart.Uri,
  3193. mainPart.GetRelationship(evenFooterRef).TargetUri
  3194. );
  3195. // Save header2
  3196. using (TextWriter tw = new StreamWriter(new PackagePartStream(package.GetPart(target).GetStream(FileMode.Create, FileAccess.Write))))
  3197. {
  3198. new XDocument
  3199. (
  3200. new XDeclaration("1.0", "UTF-8", "yes"),
  3201. even
  3202. ).Save(tw, SaveOptions.None);
  3203. }
  3204. }
  3205. var firstFooterRef =
  3206. (
  3207. from e in mainDoc.Descendants(w + "footerReference")
  3208. let type = e.Attribute(w + "type")
  3209. where type != null && type.Value.Equals("first", StringComparison.CurrentCultureIgnoreCase)
  3210. select e.Attribute(r + "id").Value
  3211. ).LastOrDefault();
  3212. if (firstFooterRef != null)
  3213. {
  3214. XElement first = footers.first.Xml;
  3215. Uri target = PackUriHelper.ResolvePartUri
  3216. (
  3217. mainPart.Uri,
  3218. mainPart.GetRelationship(firstFooterRef).TargetUri
  3219. );
  3220. // Save header3
  3221. using (TextWriter tw = new StreamWriter(new PackagePartStream(package.GetPart(target).GetStream(FileMode.Create, FileAccess.Write))))
  3222. {
  3223. new XDocument
  3224. (
  3225. new XDeclaration("1.0", "UTF-8", "yes"),
  3226. first
  3227. ).Save(tw, SaveOptions.None);
  3228. }
  3229. }
  3230. // Save the settings document.
  3231. using (TextWriter tw = new StreamWriter(new PackagePartStream(settingsPart.GetStream(FileMode.Create, FileAccess.Write))))
  3232. settings.Save(tw, SaveOptions.None);
  3233. if (endnotesPart != null)
  3234. {
  3235. using (TextWriter tw = new StreamWriter(new PackagePartStream(endnotesPart.GetStream(FileMode.Create, FileAccess.Write))))
  3236. endnotes.Save(tw, SaveOptions.None);
  3237. }
  3238. if (footnotesPart != null)
  3239. {
  3240. using (TextWriter tw = new StreamWriter(new PackagePartStream(footnotesPart.GetStream(FileMode.Create, FileAccess.Write))))
  3241. footnotes.Save(tw, SaveOptions.None);
  3242. }
  3243. if (stylesPart != null)
  3244. {
  3245. using (TextWriter tw = new StreamWriter(new PackagePartStream(stylesPart.GetStream(FileMode.Create, FileAccess.Write))))
  3246. styles.Save(tw, SaveOptions.None);
  3247. }
  3248. if (stylesWithEffectsPart != null)
  3249. {
  3250. using (TextWriter tw = new StreamWriter(new PackagePartStream(stylesWithEffectsPart.GetStream(FileMode.Create, FileAccess.Write))))
  3251. stylesWithEffects.Save(tw, SaveOptions.None);
  3252. }
  3253. if (numberingPart != null)
  3254. {
  3255. using (TextWriter tw = new StreamWriter(new PackagePartStream(numberingPart.GetStream(FileMode.Create, FileAccess.Write))))
  3256. numbering.Save(tw, SaveOptions.None);
  3257. }
  3258. if (fontTablePart != null)
  3259. {
  3260. using (TextWriter tw = new StreamWriter(new PackagePartStream(fontTablePart.GetStream(FileMode.Create, FileAccess.Write))))
  3261. fontTable.Save(tw, SaveOptions.None);
  3262. }
  3263. }
  3264. // Close the document so that it can be saved.
  3265. package.Flush();
  3266. #region Save this document back to a file or stream, that was specified by the user at save time.
  3267. if (filename != null)
  3268. {
  3269. using (FileStream fs = new FileStream(filename, FileMode.Create))
  3270. {
  3271. fs.Write(memoryStream.ToArray(), 0, (int)memoryStream.Length);
  3272. }
  3273. }
  3274. else
  3275. {
  3276. if (stream.CanSeek) // 2013-05-25: Check if stream can be seeked to support System.Web.HttpResponseStream
  3277. {
  3278. // Set the length of this stream to 0
  3279. stream.SetLength(0);
  3280. // Write to the beginning of the stream
  3281. stream.Position = 0;
  3282. }
  3283. memoryStream.WriteTo(stream);
  3284. memoryStream.Flush();
  3285. }
  3286. #endregion
  3287. }
  3288. /// <summary>
  3289. /// Save this document to a file.
  3290. /// </summary>
  3291. /// <param name="filename">The filename to save this document as.</param>
  3292. /// <example>
  3293. /// Load a document from one file and save it to another.
  3294. /// <code>
  3295. /// // Load a document using its fully qualified filename.
  3296. /// DocX document = DocX.Load(@"C:\Example\Test1.docx");
  3297. ///
  3298. /// // Insert a new Paragraph
  3299. /// document.InsertParagraph("Hello world!", false);
  3300. ///
  3301. /// // Save the document to a new location.
  3302. /// document.SaveAs(@"C:\Example\Test2.docx");
  3303. /// </code>
  3304. /// </example>
  3305. /// <example>
  3306. /// Load a document from a Stream and save it to a file.
  3307. /// <code>
  3308. /// DocX document;
  3309. /// using (FileStream fs1 = new FileStream(@"C:\Example\Test1.docx", FileMode.Open))
  3310. /// {
  3311. /// // Load a document using a stream.
  3312. /// document = DocX.Load(fs1);
  3313. ///
  3314. /// // Insert a new Paragraph
  3315. /// document.InsertParagraph("Hello world again!", false);
  3316. /// }
  3317. ///
  3318. /// // Save the document to a new location.
  3319. /// document.SaveAs(@"C:\Example\Test2.docx");
  3320. /// </code>
  3321. /// </example>
  3322. /// <seealso cref="DocX.Save()"/>
  3323. /// <seealso cref="DocX.Load(System.IO.Stream)"/>
  3324. /// <seealso cref="DocX.Load(string)"/>
  3325. public void SaveAs(string filename)
  3326. {
  3327. this.filename = filename;
  3328. stream = null;
  3329. Save();
  3330. }
  3331. /// <summary>
  3332. /// Save this document to a Stream.
  3333. /// </summary>
  3334. /// <param name="stream">The Stream to save this document to.</param>
  3335. /// <example>
  3336. /// Load a document from a file and save it to a Stream.
  3337. /// <code>
  3338. /// // Place holder for a document.
  3339. /// DocX document;
  3340. ///
  3341. /// using (FileStream fs1 = new FileStream(@"C:\Example\Test1.docx", FileMode.Open))
  3342. /// {
  3343. /// // Load a document using a stream.
  3344. /// document = DocX.Load(fs1);
  3345. ///
  3346. /// // Insert a new Paragraph
  3347. /// document.InsertParagraph("Hello world again!", false);
  3348. /// }
  3349. ///
  3350. /// using (FileStream fs2 = new FileStream(@"C:\Example\Test2.docx", FileMode.Create))
  3351. /// {
  3352. /// // Save the document to a different stream.
  3353. /// document.SaveAs(fs2);
  3354. /// }
  3355. ///
  3356. /// // Release this document from memory.
  3357. /// document.Dispose();
  3358. /// </code>
  3359. /// </example>
  3360. /// <example>
  3361. /// Load a document from one Stream and save it to another.
  3362. /// <code>
  3363. /// DocX document;
  3364. /// using (FileStream fs1 = new FileStream(@"C:\Example\Test1.docx", FileMode.Open))
  3365. /// {
  3366. /// // Load a document using a stream.
  3367. /// document = DocX.Load(fs1);
  3368. ///
  3369. /// // Insert a new Paragraph
  3370. /// document.InsertParagraph("Hello world again!", false);
  3371. /// }
  3372. ///
  3373. /// using (FileStream fs2 = new FileStream(@"C:\Example\Test2.docx", FileMode.Create))
  3374. /// {
  3375. /// // Save the document to a different stream.
  3376. /// document.SaveAs(fs2);
  3377. /// }
  3378. /// </code>
  3379. /// </example>
  3380. /// <seealso cref="DocX.Save()"/>
  3381. /// <seealso cref="DocX.Load(System.IO.Stream)"/>
  3382. /// <seealso cref="DocX.Load(string)"/>
  3383. public void SaveAs(Stream stream)
  3384. {
  3385. filename = null;
  3386. this.stream = stream;
  3387. Save();
  3388. }
  3389. /// <summary>
  3390. /// Add a core property to this document. If a core property already exists with the same name it will be replaced. Core property names are case insensitive.
  3391. /// </summary>
  3392. ///<param name="propertyName">The property name.</param>
  3393. ///<param name="propertyValue">The property value.</param>
  3394. ///<example>
  3395. /// Add a core properties of each type to a document.
  3396. /// <code>
  3397. /// // Load Example.docx
  3398. /// using (DocX document = DocX.Load(@"C:\Example\Test.docx"))
  3399. /// {
  3400. /// // If this document does not contain a core property called 'forename', create one.
  3401. /// if (!document.CoreProperties.ContainsKey("forename"))
  3402. /// {
  3403. /// // Create a new core property called 'forename' and set its value.
  3404. /// document.AddCoreProperty("forename", "Cathal");
  3405. /// }
  3406. ///
  3407. /// // Get this documents core property called 'forename'.
  3408. /// string forenameValue = document.CoreProperties["forename"];
  3409. ///
  3410. /// // Print all of the information about this core property to Console.
  3411. /// Console.WriteLine(string.Format("Name: '{0}', Value: '{1}'\nPress any key...", "forename", forenameValue));
  3412. ///
  3413. /// // Save all changes made to this document.
  3414. /// document.Save();
  3415. /// } // Release this document from memory.
  3416. ///
  3417. /// // Wait for the user to press a key before exiting.
  3418. /// Console.ReadKey();
  3419. /// </code>
  3420. /// </example>
  3421. /// <seealso cref="CoreProperties"/>
  3422. /// <seealso cref="CustomProperty"/>
  3423. /// <seealso cref="CustomProperties"/>
  3424. public void AddCoreProperty(string propertyName, string propertyValue)
  3425. {
  3426. string propertyNamespacePrefix = propertyName.Contains(":") ? propertyName.Split(':')[0] : "cp";
  3427. string propertyLocalName = propertyName.Contains(":") ? propertyName.Split(':')[1] : propertyName;
  3428. // If this document does not contain a coreFilePropertyPart create one.)
  3429. if (!package.PartExists(new Uri("/docProps/core.xml", UriKind.Relative)))
  3430. throw new Exception("Core properties part doesn't exist.");
  3431. XDocument corePropDoc;
  3432. PackagePart corePropPart = package.GetPart(new Uri("/docProps/core.xml", UriKind.Relative));
  3433. using (TextReader tr = new StreamReader(corePropPart.GetStream(FileMode.Open, FileAccess.Read)))
  3434. {
  3435. corePropDoc = XDocument.Load(tr);
  3436. }
  3437. XElement corePropElement =
  3438. (from propElement in corePropDoc.Root.Elements()
  3439. where (propElement.Name.LocalName.Equals(propertyLocalName))
  3440. select propElement).SingleOrDefault();
  3441. if (corePropElement != null)
  3442. {
  3443. corePropElement.SetValue(propertyValue);
  3444. }
  3445. else
  3446. {
  3447. var propertyNamespace = corePropDoc.Root.GetNamespaceOfPrefix(propertyNamespacePrefix);
  3448. corePropDoc.Root.Add(new XElement(XName.Get(propertyLocalName, propertyNamespace.NamespaceName), propertyValue));
  3449. }
  3450. using (TextWriter tw = new StreamWriter(new PackagePartStream(corePropPart.GetStream(FileMode.Create, FileAccess.Write))))
  3451. {
  3452. corePropDoc.Save(tw);
  3453. }
  3454. UpdateCorePropertyValue(this, propertyLocalName, propertyValue);
  3455. }
  3456. internal static void UpdateCorePropertyValue(DocX document, string corePropertyName, string corePropertyValue)
  3457. {
  3458. string matchPattern = string.Format(@"(DOCPROPERTY)?{0}\\\*MERGEFORMAT", corePropertyName).ToLower();
  3459. foreach (XElement e in document.mainDoc.Descendants(XName.Get("fldSimple", w.NamespaceName)))
  3460. {
  3461. string attr_value = e.Attribute(XName.Get("instr", w.NamespaceName)).Value.Replace(" ", string.Empty).Trim().ToLower();
  3462. if (Regex.IsMatch(attr_value, matchPattern))
  3463. {
  3464. XElement firstRun = e.Element(w + "r");
  3465. XElement firstText = firstRun.Element(w + "t");
  3466. XElement rPr = firstText.Element(w + "rPr");
  3467. // Delete everything and insert updated text value
  3468. e.RemoveNodes();
  3469. XElement t = new XElement(w + "t", rPr, corePropertyValue);
  3470. Novacode.Text.PreserveSpace(t);
  3471. e.Add(new XElement(firstRun.Name, firstRun.Attributes(), firstRun.Element(XName.Get("rPr", w.NamespaceName)), t));
  3472. }
  3473. }
  3474. #region Headers
  3475. IEnumerable<PackagePart> headerParts = from headerPart in document.package.GetParts()
  3476. where (Regex.IsMatch(headerPart.Uri.ToString(), @"/word/header\d?.xml"))
  3477. select headerPart;
  3478. foreach (PackagePart pp in headerParts)
  3479. {
  3480. XDocument header = XDocument.Load(new StreamReader(pp.GetStream()));
  3481. foreach (XElement e in header.Descendants(XName.Get("fldSimple", w.NamespaceName)))
  3482. {
  3483. string attr_value = e.Attribute(XName.Get("instr", w.NamespaceName)).Value.Replace(" ", string.Empty).Trim().ToLower();
  3484. if (Regex.IsMatch(attr_value, matchPattern))
  3485. {
  3486. XElement firstRun = e.Element(w + "r");
  3487. // Delete everything and insert updated text value
  3488. e.RemoveNodes();
  3489. XElement t = new XElement(w + "t", corePropertyValue);
  3490. Novacode.Text.PreserveSpace(t);
  3491. e.Add(new XElement(firstRun.Name, firstRun.Attributes(), firstRun.Element(XName.Get("rPr", w.NamespaceName)), t));
  3492. }
  3493. }
  3494. using (TextWriter tw = new StreamWriter(new PackagePartStream(pp.GetStream(FileMode.Create, FileAccess.Write))))
  3495. header.Save(tw);
  3496. }
  3497. #endregion
  3498. #region Footers
  3499. IEnumerable<PackagePart> footerParts = from footerPart in document.package.GetParts()
  3500. where (Regex.IsMatch(footerPart.Uri.ToString(), @"/word/footer\d?.xml"))
  3501. select footerPart;
  3502. foreach (PackagePart pp in footerParts)
  3503. {
  3504. XDocument footer = XDocument.Load(new StreamReader(pp.GetStream()));
  3505. foreach (XElement e in footer.Descendants(XName.Get("fldSimple", w.NamespaceName)))
  3506. {
  3507. string attr_value = e.Attribute(XName.Get("instr", w.NamespaceName)).Value.Replace(" ", string.Empty).Trim().ToLower();
  3508. if (Regex.IsMatch(attr_value, matchPattern))
  3509. {
  3510. XElement firstRun = e.Element(w + "r");
  3511. // Delete everything and insert updated text value
  3512. e.RemoveNodes();
  3513. XElement t = new XElement(w + "t", corePropertyValue);
  3514. Novacode.Text.PreserveSpace(t);
  3515. e.Add(new XElement(firstRun.Name, firstRun.Attributes(), firstRun.Element(XName.Get("rPr", w.NamespaceName)), t));
  3516. }
  3517. }
  3518. using (TextWriter tw = new StreamWriter(new PackagePartStream(pp.GetStream(FileMode.Create, FileAccess.Write))))
  3519. footer.Save(tw);
  3520. }
  3521. #endregion
  3522. PopulateDocument(document, document.package);
  3523. }
  3524. /// <summary>
  3525. /// 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.
  3526. /// </summary>
  3527. /// <param name="cp">The CustomProperty to add to this document.</param>
  3528. /// <example>
  3529. /// Add a custom properties of each type to a document.
  3530. /// <code>
  3531. /// // Load Example.docx
  3532. /// using (DocX document = DocX.Load(@"C:\Example\Test.docx"))
  3533. /// {
  3534. /// // A CustomProperty called forename which stores a string.
  3535. /// CustomProperty forename;
  3536. ///
  3537. /// // If this document does not contain a custom property called 'forename', create one.
  3538. /// if (!document.CustomProperties.ContainsKey("forename"))
  3539. /// {
  3540. /// // Create a new custom property called 'forename' and set its value.
  3541. /// document.AddCustomProperty(new CustomProperty("forename", "Cathal"));
  3542. /// }
  3543. ///
  3544. /// // Get this documents custom property called 'forename'.
  3545. /// forename = document.CustomProperties["forename"];
  3546. ///
  3547. /// // Print all of the information about this CustomProperty to Console.
  3548. /// Console.WriteLine(string.Format("Name: '{0}', Value: '{1}'\nPress any key...", forename.Name, forename.Value));
  3549. ///
  3550. /// // Save all changes made to this document.
  3551. /// document.Save();
  3552. /// } // Release this document from memory.
  3553. ///
  3554. /// // Wait for the user to press a key before exiting.
  3555. /// Console.ReadKey();
  3556. /// </code>
  3557. /// </example>
  3558. /// <seealso cref="CustomProperty"/>
  3559. /// <seealso cref="CustomProperties"/>
  3560. public void AddCustomProperty(CustomProperty cp)
  3561. {
  3562. // If this document does not contain a customFilePropertyPart create one.
  3563. if (!package.PartExists(new Uri("/docProps/custom.xml", UriKind.Relative)))
  3564. HelperFunctions.CreateCustomPropertiesPart(this);
  3565. XDocument customPropDoc;
  3566. PackagePart customPropPart = package.GetPart(new Uri("/docProps/custom.xml", UriKind.Relative));
  3567. using (TextReader tr = new StreamReader(customPropPart.GetStream(FileMode.Open, FileAccess.Read)))
  3568. customPropDoc = XDocument.Load(tr, LoadOptions.PreserveWhitespace);
  3569. // Each custom property has a PID, get the highest PID in this document.
  3570. IEnumerable<int> pids =
  3571. (
  3572. from d in customPropDoc.Descendants()
  3573. where d.Name.LocalName == "property"
  3574. select int.Parse(d.Attribute(XName.Get("pid")).Value)
  3575. );
  3576. int pid = 1;
  3577. if (pids.Count() > 0)
  3578. pid = pids.Max();
  3579. // Check if a custom property already exists with this name
  3580. // 2013-05-25: IgnoreCase while searching for custom property as it would produce a currupted docx.
  3581. var customProperty =
  3582. (
  3583. from d in customPropDoc.Descendants()
  3584. where (d.Name.LocalName == "property") && (d.Attribute(XName.Get("name")).Value.Equals(cp.Name, StringComparison.InvariantCultureIgnoreCase))
  3585. select d
  3586. ).SingleOrDefault();
  3587. // If a custom property with this name already exists remove it.
  3588. if (customProperty != null)
  3589. customProperty.Remove();
  3590. XElement propertiesElement = customPropDoc.Element(XName.Get("Properties", customPropertiesSchema.NamespaceName));
  3591. propertiesElement.Add
  3592. (
  3593. new XElement
  3594. (
  3595. XName.Get("property", customPropertiesSchema.NamespaceName),
  3596. new XAttribute("fmtid", "{D5CDD505-2E9C-101B-9397-08002B2CF9AE}"),
  3597. new XAttribute("pid", pid + 1),
  3598. new XAttribute("name", cp.Name),
  3599. new XElement(customVTypesSchema + cp.Type, cp.Value ?? "")
  3600. )
  3601. );
  3602. // Save the custom properties
  3603. using (TextWriter tw = new StreamWriter(new PackagePartStream(customPropPart.GetStream(FileMode.Create, FileAccess.Write))))
  3604. customPropDoc.Save(tw, SaveOptions.None);
  3605. // Refresh all fields in this document which display this custom property.
  3606. UpdateCustomPropertyValue(this, cp.Name, (cp.Value ?? "").ToString());
  3607. }
  3608. /// <summary>
  3609. /// Update the custom properties inside the document
  3610. /// </summary>
  3611. /// <param name="document">The DocX document</param>
  3612. /// <param name="customPropertyName">The property used inside the document</param>
  3613. /// <param name="customPropertyValue">The new value for the property</param>
  3614. /// <remarks>Different version of Word create different Document XML.</remarks>
  3615. internal static void UpdateCustomPropertyValue(DocX document, string customPropertyName, string customPropertyValue)
  3616. {
  3617. // A list of documents, which will contain, The Main Document and if they exist: header1, header2, header3, footer1, footer2, footer3.
  3618. List<XElement> documents = new List<XElement> { document.mainDoc.Root };
  3619. // Check if each header exists and add if if so.
  3620. #region Headers
  3621. Headers headers = document.Headers;
  3622. if (headers.first != null)
  3623. documents.Add(headers.first.Xml);
  3624. if (headers.odd != null)
  3625. documents.Add(headers.odd.Xml);
  3626. if (headers.even != null)
  3627. documents.Add(headers.even.Xml);
  3628. #endregion
  3629. // Check if each footer exists and add if if so.
  3630. #region Footers
  3631. Footers footers = document.Footers;
  3632. if (footers.first != null)
  3633. documents.Add(footers.first.Xml);
  3634. if (footers.odd != null)
  3635. documents.Add(footers.odd.Xml);
  3636. if (footers.even != null)
  3637. documents.Add(footers.even.Xml);
  3638. #endregion
  3639. var matchCustomPropertyName = customPropertyName;
  3640. if (customPropertyName.Contains(" ")) matchCustomPropertyName = "\"" + customPropertyName + "\"";
  3641. string match_value = string.Format(@"DOCPROPERTY {0} \* MERGEFORMAT", matchCustomPropertyName).Replace(" ", string.Empty);
  3642. // Process each document in the list.
  3643. foreach (XElement doc in documents)
  3644. {
  3645. #region Word 2010+
  3646. foreach (XElement e in doc.Descendants(XName.Get("instrText", w.NamespaceName)))
  3647. {
  3648. string attr_value = e.Value.Replace(" ", string.Empty).Trim();
  3649. if (attr_value.Equals(match_value, StringComparison.CurrentCultureIgnoreCase))
  3650. {
  3651. XNode node = e.Parent.NextNode;
  3652. bool found = false;
  3653. while (true)
  3654. {
  3655. if (node.NodeType == XmlNodeType.Element)
  3656. {
  3657. var ele = node as XElement;
  3658. var match = ele.Descendants(XName.Get("t", w.NamespaceName));
  3659. if (match.Any())
  3660. {
  3661. if (!found)
  3662. {
  3663. match.First().Value = customPropertyValue;
  3664. found = true;
  3665. }
  3666. else
  3667. {
  3668. ele.RemoveNodes();
  3669. }
  3670. }
  3671. else
  3672. {
  3673. match = ele.Descendants(XName.Get("fldChar", w.NamespaceName));
  3674. if (match.Any())
  3675. {
  3676. var endMatch = match.First().Attribute(XName.Get("fldCharType", w.NamespaceName));
  3677. if (endMatch != null && endMatch.Value == "end")
  3678. {
  3679. break;
  3680. }
  3681. }
  3682. }
  3683. }
  3684. node = node.NextNode;
  3685. }
  3686. }
  3687. }
  3688. #endregion
  3689. #region < Word 2010
  3690. foreach (XElement e in doc.Descendants(XName.Get("fldSimple", w.NamespaceName)))
  3691. {
  3692. string attr_value = e.Attribute(XName.Get("instr", w.NamespaceName)).Value.Replace(" ", string.Empty).Trim();
  3693. if (attr_value.Equals(match_value, StringComparison.CurrentCultureIgnoreCase))
  3694. {
  3695. XElement firstRun = e.Element(w + "r");
  3696. XElement firstText = firstRun.Element(w + "t");
  3697. XElement rPr = firstText.Element(w + "rPr");
  3698. // Delete everything and insert updated text value
  3699. e.RemoveNodes();
  3700. XElement t = new XElement(w + "t", rPr, customPropertyValue);
  3701. Novacode.Text.PreserveSpace(t);
  3702. e.Add(new XElement(firstRun.Name, firstRun.Attributes(), firstRun.Element(XName.Get("rPr", w.NamespaceName)), t));
  3703. }
  3704. }
  3705. #endregion
  3706. }
  3707. }
  3708. public override Paragraph InsertParagraph()
  3709. {
  3710. Paragraph p = base.InsertParagraph();
  3711. p.PackagePart = mainPart;
  3712. return p;
  3713. }
  3714. public override Paragraph InsertParagraph(int index, string text, bool trackChanges)
  3715. {
  3716. Paragraph p = base.InsertParagraph(index, text, trackChanges);
  3717. p.PackagePart = mainPart;
  3718. return p;
  3719. }
  3720. public override Paragraph InsertParagraph(Paragraph p)
  3721. {
  3722. p.PackagePart = mainPart;
  3723. return base.InsertParagraph(p);
  3724. }
  3725. public override Paragraph InsertParagraph(int index, Paragraph p)
  3726. {
  3727. p.PackagePart = mainPart;
  3728. return base.InsertParagraph(index, p);
  3729. }
  3730. public override Paragraph InsertParagraph(int index, string text, bool trackChanges, Formatting formatting)
  3731. {
  3732. Paragraph p = base.InsertParagraph(index, text, trackChanges, formatting);
  3733. p.PackagePart = mainPart;
  3734. return p;
  3735. }
  3736. public override Paragraph InsertParagraph(string text)
  3737. {
  3738. Paragraph p = base.InsertParagraph(text);
  3739. p.PackagePart = mainPart;
  3740. return p;
  3741. }
  3742. public override Paragraph InsertParagraph(string text, bool trackChanges)
  3743. {
  3744. Paragraph p = base.InsertParagraph(text, trackChanges);
  3745. p.PackagePart = mainPart;
  3746. return p;
  3747. }
  3748. public override Paragraph InsertParagraph(string text, bool trackChanges, Formatting formatting)
  3749. {
  3750. Paragraph p = base.InsertParagraph(text, trackChanges, formatting);
  3751. p.PackagePart = mainPart;
  3752. return p;
  3753. }
  3754. public Paragraph[] InsertParagraphs(string text)
  3755. {
  3756. String[] textArray = text.Split('\n');
  3757. List<Paragraph> paragraphs = new List<Paragraph>();
  3758. foreach (var textForParagraph in textArray)
  3759. {
  3760. Paragraph p = base.InsertParagraph(text);
  3761. p.PackagePart = mainPart;
  3762. paragraphs.Add(p);
  3763. }
  3764. return paragraphs.ToArray();
  3765. }
  3766. public override ReadOnlyCollection<Content> Contents
  3767. {
  3768. get
  3769. {
  3770. ReadOnlyCollection<Content> l = base.Contents;
  3771. foreach (var content in l)
  3772. {
  3773. content.PackagePart = mainPart;
  3774. }
  3775. return l;
  3776. }
  3777. }
  3778. public void SetContent(XElement el)
  3779. {
  3780. foreach (XElement e in el.Elements())
  3781. {
  3782. (from d in Document.Contents
  3783. where d.Name == e.Name
  3784. select d).First().SetText(e.Value);
  3785. }
  3786. }
  3787. public void SetContent(Dictionary<string, string> dict)
  3788. {
  3789. foreach (KeyValuePair<string, string> item in dict)
  3790. {
  3791. (from d in Document.Contents
  3792. where d.Name == item.Key
  3793. select d).First().SetText(item.Value);
  3794. }
  3795. }
  3796. public void SetContent(string path)
  3797. {
  3798. XDocument doc = XDocument.Load(path);
  3799. SetContent(doc);
  3800. }
  3801. public void SetContent(XDocument xmlDoc)
  3802. {
  3803. foreach (XElement e in xmlDoc.ElementsAfterSelf())
  3804. {
  3805. (from d in Document.Contents
  3806. where d.Name == e.Name
  3807. select d).First().SetText(e.Value);
  3808. }
  3809. }
  3810. public override ReadOnlyCollection<Paragraph> Paragraphs
  3811. {
  3812. get
  3813. {
  3814. ReadOnlyCollection<Paragraph> l = base.Paragraphs;
  3815. foreach (var paragraph in l)
  3816. {
  3817. paragraph.PackagePart = mainPart;
  3818. }
  3819. return l;
  3820. }
  3821. }
  3822. public override List<List> Lists
  3823. {
  3824. get
  3825. {
  3826. List<List> l = base.Lists;
  3827. l.ForEach(x => x.Items.ForEach(i => i.PackagePart = mainPart));
  3828. return l;
  3829. }
  3830. }
  3831. public override List<Table> Tables
  3832. {
  3833. get
  3834. {
  3835. List<Table> l = base.Tables;
  3836. l.ForEach(x => x.mainPart = mainPart);
  3837. return l;
  3838. }
  3839. }
  3840. /// <summary>
  3841. /// Create an equation and insert it in the new paragraph
  3842. /// </summary>
  3843. public override Paragraph InsertEquation(String equation)
  3844. {
  3845. Paragraph p = base.InsertEquation(equation);
  3846. p.PackagePart = mainPart;
  3847. return p;
  3848. }
  3849. /// <summary>
  3850. /// Insert a chart in document
  3851. /// </summary>
  3852. public void InsertChart(Chart chart)
  3853. {
  3854. // Create a new chart part uri.
  3855. String chartPartUriPath = String.Empty;
  3856. Int32 chartIndex = 1;
  3857. do
  3858. {
  3859. chartPartUriPath = String.Format
  3860. (
  3861. "/word/charts/chart{0}.xml",
  3862. chartIndex
  3863. );
  3864. chartIndex++;
  3865. } while (package.PartExists(new Uri(chartPartUriPath, UriKind.Relative)));
  3866. // Create chart part.
  3867. PackagePart chartPackagePart = package.CreatePart(new Uri(chartPartUriPath, UriKind.Relative), "application/vnd.openxmlformats-officedocument.drawingml.chart+xml", CompressionOption.Normal);
  3868. // Create a new chart relationship
  3869. String relID = GetNextFreeRelationshipID();
  3870. PackageRelationship rel = mainPart.CreateRelationship(chartPackagePart.Uri, TargetMode.Internal, "http://schemas.openxmlformats.org/officeDocument/2006/relationships/chart", relID);
  3871. // Save a chart info the chartPackagePart
  3872. using (TextWriter tw = new StreamWriter(new PackagePartStream(chartPackagePart.GetStream(FileMode.Create, FileAccess.Write))))
  3873. chart.Xml.Save(tw);
  3874. // Insert a new chart into a paragraph.
  3875. Paragraph p = InsertParagraph();
  3876. XElement chartElement = new XElement(
  3877. XName.Get("r", w.NamespaceName),
  3878. new XElement(
  3879. XName.Get("drawing", w.NamespaceName),
  3880. new XElement(
  3881. XName.Get("inline", wp.NamespaceName),
  3882. new XElement(XName.Get("extent", wp.NamespaceName), new XAttribute("cx", "5486400"), new XAttribute("cy", "3200400")),
  3883. new XElement(XName.Get("effectExtent", wp.NamespaceName), new XAttribute("l", "0"), new XAttribute("t", "0"), new XAttribute("r", "19050"), new XAttribute("b", "19050")),
  3884. new XElement(XName.Get("docPr", wp.NamespaceName), new XAttribute("id", "1"), new XAttribute("name", "chart")),
  3885. new XElement(
  3886. XName.Get("graphic", a.NamespaceName),
  3887. new XElement(
  3888. XName.Get("graphicData", a.NamespaceName),
  3889. new XAttribute("uri", c.NamespaceName),
  3890. new XElement(
  3891. XName.Get("chart", c.NamespaceName),
  3892. new XAttribute(XName.Get("id", r.NamespaceName), relID)
  3893. )
  3894. )
  3895. )
  3896. )
  3897. ));
  3898. p.Xml.Add(chartElement);
  3899. }
  3900. /// <summary>
  3901. /// Inserts a default TOC into the current document.
  3902. /// Title: Table of contents
  3903. /// Swithces will be: TOC \h \o '1-3' \u \z
  3904. /// </summary>
  3905. /// <returns>The inserted TableOfContents</returns>
  3906. public TableOfContents InsertDefaultTableOfContents()
  3907. {
  3908. return InsertTableOfContents("Table of contents", TableOfContentsSwitches.O | TableOfContentsSwitches.H | TableOfContentsSwitches.Z | TableOfContentsSwitches.U);
  3909. }
  3910. /// <summary>
  3911. /// Inserts a TOC into the current document.
  3912. /// </summary>
  3913. /// <param name="title">The title of the TOC</param>
  3914. /// <param name="switches">Switches to be applied, see: http://officeopenxml.com/WPtableOfContents.php </param>
  3915. /// <param name="headerStyle">Lets you set the style name of the TOC header</param>
  3916. /// <param name="maxIncludeLevel">Lets you specify how many header levels should be included - default is 1-3</param>
  3917. /// <param name="rightTabPos">Lets you override the right tab position - this is not common</param>
  3918. /// <returns>The inserted TableOfContents</returns>
  3919. public TableOfContents InsertTableOfContents(string title, TableOfContentsSwitches switches, string headerStyle = null, int maxIncludeLevel = 3, int? rightTabPos = null)
  3920. {
  3921. var toc = TableOfContents.CreateTableOfContents(this, title, switches, headerStyle, maxIncludeLevel, rightTabPos);
  3922. Xml.Add(toc.Xml);
  3923. return toc;
  3924. }
  3925. /// <summary>
  3926. /// Inserts at TOC into the current document before the provided <paramref name="reference"/>
  3927. /// </summary>
  3928. /// <param name="reference">The paragraph to use as reference</param>
  3929. /// <param name="title">The title of the TOC</param>
  3930. /// <param name="switches">Switches to be applied, see: http://officeopenxml.com/WPtableOfContents.php </param>
  3931. /// <param name="headerStyle">Lets you set the style name of the TOC header</param>
  3932. /// <param name="maxIncludeLevel">Lets you specify how many header levels should be included - default is 1-3</param>
  3933. /// <param name="rightTabPos">Lets you override the right tab position - this is not common</param>
  3934. /// <returns>The inserted TableOfContents</returns>
  3935. public TableOfContents InsertTableOfContents(Paragraph reference, string title, TableOfContentsSwitches switches, string headerStyle = null, int maxIncludeLevel = 3, int? rightTabPos = null)
  3936. {
  3937. var toc = TableOfContents.CreateTableOfContents(this, title, switches, headerStyle, maxIncludeLevel, rightTabPos);
  3938. reference.Xml.AddBeforeSelf(toc.Xml);
  3939. return toc;
  3940. }
  3941. #region IDisposable Members
  3942. /// <summary>
  3943. /// Releases all resources used by this document.
  3944. /// </summary>
  3945. /// <example>
  3946. /// If you take advantage of the using keyword, Dispose() is automatically called for you.
  3947. /// <code>
  3948. /// // Load document.
  3949. /// using (DocX document = DocX.Load(@"C:\Example\Test.docx"))
  3950. /// {
  3951. /// // The document is only in memory while in this scope.
  3952. ///
  3953. /// }// Dispose() is automatically called at this point.
  3954. /// </code>
  3955. /// </example>
  3956. /// <example>
  3957. /// This example is equilivant to the one above example.
  3958. /// <code>
  3959. /// // Load document.
  3960. /// DocX document = DocX.Load(@"C:\Example\Test.docx");
  3961. ///
  3962. /// // Do something with the document here.
  3963. ///
  3964. /// // Dispose of the document.
  3965. /// document.Dispose();
  3966. /// </code>
  3967. /// </example>
  3968. public void Dispose()
  3969. {
  3970. package.Close();
  3971. }
  3972. #endregion
  3973. }
  3974. }