WmlToHtmlConverter.cs 186 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200
  1. // Copyright (c) Microsoft. All rights reserved.
  2. // Licensed under the MIT license. See LICENSE file in the project root for full license information.
  3. using System;
  4. using System.Collections.Generic;
  5. using System.Diagnostics.CodeAnalysis;
  6. using System.Drawing;
  7. using System.Drawing.Imaging;
  8. using System.Globalization;
  9. using System.IO;
  10. using System.Linq;
  11. using System.Text;
  12. using System.Xml;
  13. using System.Xml.Linq;
  14. using System.Xml.Xsl;
  15. using DocumentFormat.OpenXml;
  16. using DocumentFormat.OpenXml.Drawing;
  17. using DocumentFormat.OpenXml.Drawing.Charts;
  18. using DocumentFormat.OpenXml.Office2010.Word.DrawingShape;
  19. using DocumentFormat.OpenXml.Packaging;
  20. using HTEXLib.COMM.Helpers;
  21. using HTEXLib.DOCX.OpenXmlTool;
  22. using HTEXLib.Helpers;
  23. using HTEXLib.Helpers.ShapeHelpers;
  24. using HTEXLib.Models.Inner;
  25. // 200e lrm - LTR
  26. // 200f rlm - RTL
  27. // todo need to set the HTTP "Content-Language" header, for instance:
  28. // Content-Language: en-US
  29. // Content-Language: fr-FR
  30. namespace OpenXmlPowerTools
  31. {
  32. public partial class WmlDocument
  33. {
  34. [SuppressMessage("ReSharper", "UnusedMember.Global")]
  35. public XElement ConvertToHtml(WmlToHtmlConverterSettings htmlConverterSettings)
  36. {
  37. return WmlToHtmlConverter.ConvertToHtml(this, htmlConverterSettings);
  38. }
  39. [SuppressMessage("ReSharper", "UnusedMember.Global")]
  40. public XElement ConvertToHtml(HtmlConverterSettings htmlConverterSettings)
  41. {
  42. WmlToHtmlConverterSettings settings = new WmlToHtmlConverterSettings(htmlConverterSettings);
  43. return WmlToHtmlConverter.ConvertToHtml(this, settings);
  44. }
  45. }
  46. [SuppressMessage("ReSharper", "FieldCanBeMadeReadOnly.Global")]
  47. public class WmlToHtmlConverterSettings
  48. {
  49. public string PageTitle;
  50. public bool TableInnerCss;
  51. public string CssClassPrefix;
  52. public bool FabricateCssClasses;
  53. public string GeneralCss;
  54. public string AdditionalCss;
  55. public bool RestrictToSupportedLanguages;
  56. public bool RestrictToSupportedNumberingFormats;
  57. public Dictionary<string, Func<string, int, string, string>> ListItemImplementations;
  58. public Func<ImageInfo, XElement> ImageHandler;
  59. public WmlToHtmlConverterSettings()
  60. {
  61. PageTitle = "";
  62. CssClassPrefix = "pt-";
  63. TableInnerCss = true;
  64. FabricateCssClasses = true;
  65. GeneralCss = "span {/* white-space: pre-wrap;*/ }";
  66. AdditionalCss = "";
  67. RestrictToSupportedLanguages = false;
  68. RestrictToSupportedNumberingFormats = false;
  69. ListItemImplementations = ListItemRetrieverSettings.DefaultListItemTextImplementations;
  70. }
  71. public WmlToHtmlConverterSettings(HtmlConverterSettings htmlConverterSettings)
  72. {
  73. TableInnerCss = htmlConverterSettings.TableInnerCss;
  74. PageTitle = htmlConverterSettings.PageTitle;
  75. CssClassPrefix = htmlConverterSettings.CssClassPrefix;
  76. FabricateCssClasses = htmlConverterSettings.FabricateCssClasses;
  77. GeneralCss = htmlConverterSettings.GeneralCss;
  78. AdditionalCss = htmlConverterSettings.AdditionalCss;
  79. RestrictToSupportedLanguages = htmlConverterSettings.RestrictToSupportedLanguages;
  80. RestrictToSupportedNumberingFormats = htmlConverterSettings.RestrictToSupportedNumberingFormats;
  81. ListItemImplementations = htmlConverterSettings.ListItemImplementations;
  82. ImageHandler = htmlConverterSettings.ImageHandler;
  83. }
  84. }
  85. [SuppressMessage("ReSharper", "FieldCanBeMadeReadOnly.Global")]
  86. public class HtmlConverterSettings
  87. {
  88. public bool TableInnerCss;
  89. public string PageTitle;
  90. public string CssClassPrefix;
  91. public bool FabricateCssClasses;
  92. public string GeneralCss;
  93. public string AdditionalCss;
  94. public bool RestrictToSupportedLanguages;
  95. public bool RestrictToSupportedNumberingFormats;
  96. public Dictionary<string, Func<string, int, string, string>> ListItemImplementations;
  97. public Func<ImageInfo, XElement> ImageHandler;
  98. public HtmlConverterSettings()
  99. {
  100. TableInnerCss = true;
  101. PageTitle = "";
  102. CssClassPrefix = "pt-";
  103. FabricateCssClasses = true;
  104. GeneralCss = "span { /*white-space: pre-wrap;*/ }";
  105. AdditionalCss = "";
  106. RestrictToSupportedLanguages = false;
  107. RestrictToSupportedNumberingFormats = false;
  108. ListItemImplementations = ListItemRetrieverSettings.DefaultListItemTextImplementations;
  109. }
  110. }
  111. public static class HtmlConverter
  112. {
  113. public static XElement ConvertToHtml(WmlDocument wmlDoc, HtmlConverterSettings htmlConverterSettings)
  114. {
  115. WmlToHtmlConverterSettings settings = new WmlToHtmlConverterSettings(htmlConverterSettings);
  116. return WmlToHtmlConverter.ConvertToHtml(wmlDoc, settings);
  117. }
  118. public static XElement ConvertToHtml(WordprocessingDocument wDoc, HtmlConverterSettings htmlConverterSettings)
  119. {
  120. WmlToHtmlConverterSettings settings = new WmlToHtmlConverterSettings(htmlConverterSettings);
  121. return WmlToHtmlConverter.ConvertToHtml(wDoc, settings);
  122. }
  123. }
  124. [SuppressMessage("ReSharper", "NotAccessedField.Global")]
  125. [SuppressMessage("ReSharper", "UnusedMember.Global")]
  126. public class ImageInfo
  127. {
  128. public string base64;
  129. public Bitmap Bitmap;
  130. public XAttribute ImgStyleAttribute;
  131. public string ContentType;
  132. public XElement DrawingElement;
  133. public string AltText;
  134. public string Mathxml;
  135. public const int EmusPerInch = 914400;
  136. public const int EmusPerCm = 360000;
  137. }
  138. public static class WmlToHtmlConverter
  139. {
  140. public static XElement ConvertToHtml(WmlDocument doc, WmlToHtmlConverterSettings htmlConverterSettings)
  141. {
  142. using (OpenXmlMemoryStreamDocument streamDoc = new OpenXmlMemoryStreamDocument(doc))
  143. {
  144. using (WordprocessingDocument document = streamDoc.GetWordprocessingDocument())
  145. {
  146. return ConvertToHtml(document, htmlConverterSettings);
  147. }
  148. }
  149. }
  150. public static XElement ConvertToHtml(WordprocessingDocument wordDoc, WmlToHtmlConverterSettings htmlConverterSettings)
  151. {
  152. RevisionAccepter.AcceptRevisions(wordDoc);
  153. SimplifyMarkupSettings simplifyMarkupSettings = new SimplifyMarkupSettings
  154. {
  155. RemoveComments = true,
  156. RemoveContentControls = true,
  157. RemoveEndAndFootNotes = true,
  158. RemoveFieldCodes = false,
  159. RemoveLastRenderedPageBreak = true,
  160. RemovePermissions = true,
  161. RemoveProof = true,
  162. RemoveRsidInfo = true,
  163. RemoveSmartTags = true,
  164. RemoveSoftHyphens = true,
  165. RemoveGoBackBookmark = true,
  166. ReplaceTabsWithSpaces = false,
  167. };
  168. MarkupSimplifier.SimplifyMarkup(wordDoc, simplifyMarkupSettings);
  169. FormattingAssemblerSettings formattingAssemblerSettings = new FormattingAssemblerSettings
  170. {
  171. RemoveStyleNamesFromParagraphAndRunProperties = false,
  172. ClearStyles = false,
  173. RestrictToSupportedLanguages = htmlConverterSettings.RestrictToSupportedLanguages,
  174. RestrictToSupportedNumberingFormats = htmlConverterSettings.RestrictToSupportedNumberingFormats,
  175. CreateHtmlConverterAnnotationAttributes = true,
  176. OrderElementsPerStandard = false,
  177. ListItemRetrieverSettings =
  178. htmlConverterSettings.ListItemImplementations == null ?
  179. new ListItemRetrieverSettings()
  180. {
  181. ListItemTextImplementations = ListItemRetrieverSettings.DefaultListItemTextImplementations,
  182. } :
  183. new ListItemRetrieverSettings()
  184. {
  185. ListItemTextImplementations = htmlConverterSettings.ListItemImplementations,
  186. },
  187. };
  188. FormattingAssembler.AssembleFormatting(wordDoc, formattingAssemblerSettings);
  189. InsertAppropriateNonbreakingSpaces(wordDoc);
  190. CalculateSpanWidthForTabs(wordDoc);
  191. ReverseTableBordersForRtlTables(wordDoc);
  192. AdjustTableBorders(wordDoc);
  193. XElement rootElement = wordDoc.MainDocumentPart.GetXDocument().Root;
  194. FieldRetriever.AnnotateWithFieldInfo(wordDoc.MainDocumentPart);
  195. AnnotateForSections(wordDoc);
  196. XElement xhtml = (XElement)ConvertToHtmlTransform(wordDoc, htmlConverterSettings,
  197. rootElement, false, 0m);
  198. ReifyStylesAndClasses(htmlConverterSettings, xhtml);
  199. // Note: the xhtml returned by ConvertToHtmlTransform contains objects of type
  200. // XEntity. PtOpenXmlUtil.cs define the XEntity class. See
  201. // http://blogs.msdn.com/ericwhite/archive/2010/01/21/writing-entity-references-using-linq-to-xml.aspx
  202. // for detailed explanation.
  203. //
  204. // If you further transform the XML tree returned by ConvertToHtmlTransform, you
  205. // must do it correctly, or entities will not be serialized properly.
  206. return xhtml;
  207. }
  208. private static void ReverseTableBordersForRtlTables(WordprocessingDocument wordDoc)
  209. {
  210. XDocument xd = wordDoc.MainDocumentPart.GetXDocument();
  211. foreach (var tbl in xd.Descendants(W.tbl))
  212. {
  213. var bidiVisual = tbl.Elements(W.tblPr).Elements(W.bidiVisual).FirstOrDefault();
  214. if (bidiVisual == null)
  215. continue;
  216. var tblBorders = tbl.Elements(W.tblPr).Elements(W.tblBorders).FirstOrDefault();
  217. if (tblBorders != null)
  218. {
  219. var left = tblBorders.Element(W.left);
  220. if (left != null)
  221. left = new XElement(W.right, left.Attributes());
  222. var right = tblBorders.Element(W.right);
  223. if (right != null)
  224. right = new XElement(W.left, right.Attributes());
  225. var newTblBorders = new XElement(W.tblBorders,
  226. tblBorders.Element(W.top),
  227. left,
  228. tblBorders.Element(W.bottom),
  229. right);
  230. tblBorders.ReplaceWith(newTblBorders);
  231. }
  232. foreach (var tc in tbl.Elements(W.tr).Elements(W.tc))
  233. {
  234. var tcBorders = tc.Elements(W.tcPr).Elements(W.tcBorders).FirstOrDefault();
  235. if (tcBorders != null)
  236. {
  237. var left = tcBorders.Element(W.left);
  238. if (left != null)
  239. left = new XElement(W.right, left.Attributes());
  240. var right = tcBorders.Element(W.right);
  241. if (right != null)
  242. right = new XElement(W.left, right.Attributes());
  243. var newTcBorders = new XElement(W.tcBorders,
  244. tcBorders.Element(W.top),
  245. left,
  246. tcBorders.Element(W.bottom),
  247. right);
  248. tcBorders.ReplaceWith(newTcBorders);
  249. }
  250. }
  251. }
  252. }
  253. private static void ReifyStylesAndClasses(WmlToHtmlConverterSettings htmlConverterSettings, XElement xhtml)
  254. {
  255. if (htmlConverterSettings.FabricateCssClasses)
  256. {
  257. var usedCssClassNames = new HashSet<string>();
  258. var elementsThatNeedClasses = xhtml
  259. .DescendantsAndSelf()
  260. .Select(d => new
  261. {
  262. Element = d,
  263. Styles = d.Annotation<Dictionary<string, string>>(),
  264. })
  265. .Where(z => z.Styles != null);
  266. var augmented = elementsThatNeedClasses
  267. .Select(p => new
  268. {
  269. p.Element,
  270. p.Styles,
  271. StylesString = p.Element.Name.LocalName + "|" + p.Styles.OrderBy(k => k.Key).Select(s => string.Format("{0}: {1};", s.Key, s.Value)).StringConcatenate(),
  272. })
  273. .GroupBy(p => p.StylesString)
  274. .ToList();
  275. int classCounter = 1000000;
  276. var sb = new StringBuilder();
  277. sb.Append(Environment.NewLine);
  278. foreach (var grp in augmented)
  279. {
  280. string classNameToUse;
  281. var firstOne = grp.First();
  282. var styles = firstOne.Styles;
  283. if (styles.ContainsKey("PtStyleName"))
  284. {
  285. classNameToUse = htmlConverterSettings.CssClassPrefix + styles["PtStyleName"];
  286. if (usedCssClassNames.Contains(classNameToUse))
  287. {
  288. classNameToUse = htmlConverterSettings.CssClassPrefix +
  289. styles["PtStyleName"] + "-" +
  290. classCounter.ToString().Substring(1);
  291. classCounter++;
  292. }
  293. }
  294. else
  295. {
  296. classNameToUse = htmlConverterSettings.CssClassPrefix +
  297. classCounter.ToString().Substring(1);
  298. classCounter++;
  299. }
  300. usedCssClassNames.Add(classNameToUse);
  301. sb.Append(firstOne.Element.Name.LocalName + "." + classNameToUse + " {" + Environment.NewLine);
  302. foreach (var st in firstOne.Styles.Where(s => s.Key != "PtStyleName"))
  303. {
  304. var s = " " + st.Key + ": " + st.Value + ";" + Environment.NewLine;
  305. sb.Append(s);
  306. }
  307. sb.Append("}" + Environment.NewLine);
  308. var classAtt = new XAttribute("class", classNameToUse);
  309. foreach (var gc in grp)
  310. gc.Element.Add(classAtt);
  311. }
  312. var styleValue = htmlConverterSettings.GeneralCss + sb + htmlConverterSettings.AdditionalCss;
  313. SetStyleElementValue(xhtml, styleValue);
  314. }
  315. else
  316. {
  317. // Previously, the h:style element was not added at this point. However,
  318. // at least the General CSS will contain important settings.
  319. SetStyleElementValue(xhtml, htmlConverterSettings.GeneralCss + htmlConverterSettings.AdditionalCss);
  320. foreach (var d in xhtml.DescendantsAndSelf())
  321. {
  322. var style = d.Annotation<Dictionary<string, string>>();
  323. if (style == null)
  324. continue;
  325. var styleValue =
  326. style
  327. .Where(p => p.Key != "PtStyleName")
  328. .OrderBy(p => p.Key)
  329. .Select(e => string.Format("{0}: {1};", e.Key, e.Value))
  330. .StringConcatenate();
  331. XAttribute st = new XAttribute("style", styleValue);
  332. if (d.Attribute("style") != null)
  333. d.Attribute("style").Value += styleValue;
  334. else
  335. d.Add(st);
  336. }
  337. }
  338. if (htmlConverterSettings.TableInnerCss) {
  339. SetStyleElementValue(xhtml, htmlConverterSettings.GeneralCss + htmlConverterSettings.AdditionalCss);
  340. foreach (var d in xhtml.DescendantsAndSelf())
  341. {
  342. if (d.Name.LocalName.ToString().Equals("table") || d.Name.LocalName.ToString().Equals("tr") ||d.Name.LocalName.ToString().Equals("td")) {
  343. var style = d.Annotation<Dictionary<string, string>>();
  344. if (style == null)
  345. continue;
  346. var styleValue =
  347. style
  348. .Where(p => p.Key != "PtStyleName")
  349. .OrderBy(p => p.Key)
  350. .Select(e => string.Format("{0}: {1};", e.Key, e.Value))
  351. .StringConcatenate();
  352. XAttribute st = new XAttribute("style", styleValue);
  353. if (d.Attribute("style") != null)
  354. d.Attribute("style").Value += styleValue;
  355. else
  356. d.Add(st);
  357. }
  358. }
  359. }
  360. }
  361. private static void SetStyleElementValue(XElement xhtml, string styleValue)
  362. {
  363. var styleElement = xhtml
  364. .Descendants(Xhtml.style)
  365. .FirstOrDefault();
  366. if (styleElement != null)
  367. styleElement.Value = styleValue;
  368. else
  369. {
  370. styleElement = new XElement(Xhtml.style, styleValue);
  371. var head = xhtml.Element(Xhtml.head);
  372. if (head != null)
  373. head.Add(styleElement);
  374. }
  375. }
  376. private static object ConvertToHtmlTransform(WordprocessingDocument wordDoc,
  377. WmlToHtmlConverterSettings settings, XNode node,
  378. bool suppressTrailingWhiteSpace,
  379. decimal currentMarginLeft)
  380. {
  381. var element = node as XElement;
  382. if (element == null) return null;
  383. // Transform the w:document element to the XHTML h:html element.
  384. // The h:head element is laid out based on the W3C's recommended layout, i.e.,
  385. // the charset (using the HTML5-compliant form), the title (which is always
  386. // there but possibly empty), and other meta tags.
  387. if (element.Name == W.document)
  388. {
  389. return new XElement(Xhtml.html,
  390. new XElement(Xhtml.head,
  391. new XElement(Xhtml.meta, new XAttribute("charset", "UTF-8")),
  392. settings.PageTitle != null
  393. ? new XElement(Xhtml.title, new XText(settings.PageTitle))
  394. : new XElement(Xhtml.title, new XText(string.Empty)),
  395. new XElement(Xhtml.meta,
  396. new XAttribute("name", "Generator"),
  397. new XAttribute("content", "PowerTools for Open XML"))),
  398. element.Elements()
  399. .Select(e => ConvertToHtmlTransform(wordDoc, settings, e, false, currentMarginLeft)));
  400. }
  401. // Transform the w:body element to the XHTML h:body element.
  402. if (element.Name == W.body)
  403. {
  404. return new XElement(Xhtml.body, CreateSectionDivs(wordDoc, settings, element));
  405. }
  406. // Transform the w:p element to the XHTML h:h1-h6 or h:p element (if the previous paragraph does not
  407. // have a style separator).
  408. if (element.Name == W.p)
  409. {
  410. return ProcessParagraph(wordDoc, settings, element, suppressTrailingWhiteSpace, currentMarginLeft);
  411. }
  412. // Transform hyperlinks to the XHTML h:a element.
  413. if (element.Name == W.hyperlink && element.Attribute(R.id) != null)
  414. {
  415. try
  416. {
  417. var a = new XElement(Xhtml.a,
  418. new XAttribute("href",
  419. wordDoc.MainDocumentPart
  420. .HyperlinkRelationships
  421. .First(x => x.Id == (string)element.Attribute(R.id))
  422. .Uri
  423. ),
  424. element.Elements(W.r).Select(run => ConvertRun(wordDoc, settings, run))
  425. );
  426. if (!a.Nodes().Any())
  427. a.Add(new XText(""));
  428. return a;
  429. }
  430. catch (UriFormatException)
  431. {
  432. return element.Elements().Select(e => ConvertToHtmlTransform(wordDoc, settings, e, false, currentMarginLeft));
  433. }
  434. }
  435. // Transform hyperlinks to bookmarks to the XHTML h:a element.
  436. if (element.Name == W.hyperlink && element.Attribute(W.anchor) != null)
  437. {
  438. return ProcessHyperlinkToBookmark(wordDoc, settings, element);
  439. }
  440. // Transform contents of runs.
  441. if (element.Name == W.r)
  442. {
  443. return ConvertRun(wordDoc, settings, element);
  444. }
  445. // Transform w:bookmarkStart into anchor
  446. if (element.Name == W.bookmarkStart)
  447. {
  448. return ProcessBookmarkStart(element);
  449. }
  450. // Transform every w:t element to a text node.
  451. if (element.Name == W.t)
  452. {
  453. // We don't need to convert characters to entities in a UTF-8 document.
  454. // Further, we don't need &nbsp; entities for significant whitespace
  455. // because we are wrapping the text nodes in <span> elements within
  456. // which all whitespace is significant.
  457. return new XText(element.Value);
  458. }
  459. // Transform symbols to spans
  460. if (element.Name == W.sym)
  461. {
  462. var cs = (string)element.Attribute(W._char);
  463. var c = Convert.ToInt32(cs, 16);
  464. return new XElement(Xhtml.span, new XEntity(string.Format("#{0}", c)));
  465. }
  466. // Transform tabs that have the pt:TabWidth attribute set
  467. if (element.Name == W.tab)
  468. {
  469. return ProcessTab(element);
  470. }
  471. // Transform w:br to h:br.
  472. if (element.Name == W.br || element.Name == W.cr)
  473. {
  474. return ProcessBreak(element);
  475. }
  476. // Transform w:noBreakHyphen to '-'
  477. if (element.Name == W.noBreakHyphen)
  478. {
  479. return new XText("-");
  480. }
  481. // Transform w:tbl to h:tbl.
  482. if (element.Name == W.tbl)
  483. {
  484. return ProcessTable(wordDoc, settings, element, currentMarginLeft);
  485. }
  486. // Transform w:tr to h:tr.
  487. if (element.Name == W.tr)
  488. {
  489. return ProcessTableRow(wordDoc, settings, element, currentMarginLeft);
  490. }
  491. // Transform w:tc to h:td.
  492. if (element.Name == W.tc)
  493. {
  494. return ProcessTableCell(wordDoc, settings, element);
  495. }
  496. // Transform images
  497. if (element.Name == W.drawing || element.Name == W.pict || element.Name == W._object)
  498. {
  499. XElement xElement = ProcessImage(wordDoc, element, settings.ImageHandler);
  500. return xElement;
  501. }
  502. // Transform content controls.
  503. if (element.Name == W.sdt)
  504. {
  505. return ProcessContentControl(wordDoc, settings, element, currentMarginLeft);
  506. }
  507. // Transform smart tags and simple fields.
  508. if (element.Name == W.smartTag || element.Name == W.fldSimple)
  509. {
  510. return CreateBorderDivs(wordDoc, settings, element.Elements());
  511. }
  512. //处理 数学公式
  513. if (element.Name == M.oMath)
  514. {
  515. return ProcessOMath(element);
  516. }
  517. if (element.Name == M.oMathPara)
  518. {
  519. return element.Elements().Select(e => ConvertToHtmlTransform(wordDoc, settings, e, false, currentMarginLeft));
  520. }
  521. //处理形状
  522. if (element.Name == MC.AlternateContent)
  523. {
  524. return ProcessAlternateContent(wordDoc, element,settings.ImageHandler);
  525. }
  526. //if (element.Name == MC.Choice)
  527. //{
  528. // return ProcessOMath(element);
  529. //}
  530. //if (element.Name == W.drawing &&element.Parent.Name==MC.Choice)
  531. //{
  532. // return ProcessOMath(element);
  533. //}
  534. // Ignore element.
  535. return null;
  536. }
  537. public static XElement ProcessAlternateContent(WordprocessingDocument wordDoc, XElement element, Func<ImageInfo, XElement> imageHandler) {
  538. var drawing = element.Element(MC.Choice).Element(W.drawing).Element(WP.inline);
  539. if (drawing == null) {
  540. drawing = element.Element(MC.Choice).Element(W.drawing).Element(WP.anchor);
  541. }
  542. var graphicData = drawing.Element(A.graphic).Element(A.graphicData).Elements() ;
  543. foreach (var elm in graphicData) {
  544. if (elm.Name==WPS.wsp)
  545. {
  546. var html = ProcessWps(wordDoc, elm, imageHandler);
  547. XElement elmt = XElement.Parse(html);
  548. return elmt;
  549. }
  550. else if (elm.Name==WPG.wgp)
  551. {
  552. return ProcessWgp(wordDoc, elm, imageHandler);
  553. }
  554. }
  555. return null;
  556. }
  557. public static XElement ProcessWgp(WordprocessingDocument wordDoc, XElement element, Func<ImageInfo, XElement> imageHandler) {
  558. var extentCx = (int?)element.Elements(WP.extent)
  559. .Attributes(NoNamespace.cx).FirstOrDefault();
  560. var extentCy = (int?)element.Elements(WP.extent)
  561. .Attributes(NoNamespace.cy).FirstOrDefault();
  562. var elms= element.Descendants(WPS.wsp);
  563. StringBuilder stringBuilder = new StringBuilder();
  564. foreach (var elm in elms) {
  565. var emlt= ProcessWps(wordDoc, elm, imageHandler);
  566. stringBuilder.Append(emlt);
  567. }
  568. XElement elmt = XElement.Parse(stringBuilder.ToString());
  569. return elmt;
  570. }
  571. public static XElement ProcessChart(WordprocessingDocument wordDoc, XElement containerElement, Func<ImageInfo, XElement> imageHandler,
  572. int? extentCx, int? extentCy, string altText, XElement element, string hyperlinkUri)
  573. {
  574. var ird= element.Attribute(R.id);
  575. var chartird= wordDoc.MainDocumentPart.Parts.FirstOrDefault(pp => pp.RelationshipId == ird.Value);
  576. ChartPart chartPart= wordDoc.MainDocumentPart.ChartParts.Where(x => x.Uri.ToString() == chartird.OpenXmlPart.Uri.ToString()).FirstOrDefault<ChartPart>();
  577. if (chartPart != null)
  578. {
  579. ChartColorStylePart ChartColorStylePart = null;
  580. ChartStylePart ChartStylePart = null;
  581. foreach (var idp in chartPart.Parts)
  582. {
  583. if (idp.OpenXmlPart is ChartColorStylePart ChartColorStyleParts)
  584. {
  585. ChartColorStylePart = ChartColorStyleParts;
  586. }
  587. if (idp.OpenXmlPart is ChartStylePart ChartStyleParts)
  588. {
  589. ChartStylePart = ChartStyleParts;
  590. }
  591. }
  592. if (ChartStylePart != null)
  593. {
  594. var ChartStyleChildren = ChartStylePart.ChartStyle.ChildElements;
  595. foreach (var child in ChartStyleChildren)
  596. {
  597. if (child is DocumentFormat.OpenXml.Office2013.Drawing.ChartStyle.StyleEntry StyleEntry)
  598. {
  599. // DoStyleEntry(StyleEntry);
  600. }
  601. ///OfficeArtExtensionList cs: extLst
  602. // MarkerLayoutProperties cs: dataPointMarkerLayout
  603. }
  604. }
  605. HTEXLib. Chart charts = DrawChart(wordDoc,chartPart.ChartSpace,element,imageHandler,null);
  606. // charts.links = slide.hyperlinks;
  607. // return new List<Item> { charts };
  608. }
  609. return null;
  610. }
  611. public static HTEXLib.Chart DrawChart(WordprocessingDocument wordDoc, DocumentFormat.OpenXml.Drawing.Charts.ChartSpace chartSpace,XElement element, Func<ImageInfo, XElement> ImageHandler, HTEXLib.Position positionc)
  612. {
  613. var Chart = chartSpace.GetFirstChild<DocumentFormat.OpenXml.Drawing.Charts.Chart>();
  614. var ShapeProperties = chartSpace.GetFirstChild<DocumentFormat.OpenXml.Drawing.Charts.ShapeProperties>();
  615. HTEXLib.Models.HTEX.ShapeStyle shapeStyleChart = WORDHelper.DoShapeProperties(wordDoc ,ShapeProperties, element, ImageHandler, positionc);
  616. var TextProperties = chartSpace.GetFirstChild<TextProperties>();
  617. var style = chartSpace.GetFirstChild<DocumentFormat.OpenXml.Drawing.Charts.Style>();
  618. var ColorMapOverride = chartSpace.GetFirstChild<DocumentFormat.OpenXml.Drawing.Charts.ColorMapOverride>();
  619. var style2010 = chartSpace.GetFirstChild<DocumentFormat.OpenXml.Office2010.Drawing.Charts.Style>();
  620. var UserShapesReference = chartSpace.GetFirstChild<UserShapesReference>();
  621. var charts = DoPlotArea(Chart.PlotArea,wordDoc,element, ImageHandler,positionc);
  622. HTEXLib.Models.HTEX. ShapeStyle shapeStyle = null;
  623. if (Chart.Title != null)
  624. {
  625. var ChartShapeProperties = Chart.Title.ChartShapeProperties;
  626. shapeStyle = WORDHelper.DoShapeProperties(wordDoc, ChartShapeProperties, element, ImageHandler, positionc);
  627. }
  628. // var (PPTParagraphs, tBody) = DoChartTitle(Chart.Title);
  629. //TextBody textBody = DrawText(PPTParagraphs, tBody);
  630. //Shape shape= new Shape { type = "Sp",uid ="Sp-" +ShaHashHelper.GetSHA1(slide.slideIndex + "-" + (Chart.Title.GetType().Name + Chart.Title.OuterXml).Trim().ToLower()), shapeType = "rect",
  631. // textBody = textBody , sid = sid + "titel" };
  632. HTEXLib. Shape shape = new HTEXLib.Shape
  633. {
  634. type = "Sp",
  635. uid = Guid.NewGuid().ToString(),
  636. shapeType = "rect",
  637. // textBody = textBody,
  638. // sid = sid + "titel"
  639. };
  640. shape.style.fill = shapeStyle != null ? shapeStyle.fill : null;
  641. shape.style.border = shapeStyle != null ? shapeStyle.border : null;
  642. //var chart= new Chart {sid=sid,charts =charts,title=shape,type=type,uid = type+"-"+ ShaHashHelper.GetSHA1(slide.slideIndex + "-" + (Chart.GetType().Name + Chart.OuterXml).Trim().ToLower()) };
  643. var chart = new HTEXLib.Chart
  644. {
  645. // sid = sid,
  646. charts = charts,
  647. title = shape,
  648. // type = type,
  649. uid = Guid.NewGuid().ToString(),
  650. };
  651. HTEXLib.Position position = new HTEXLib.Position { /*cx = width, cy = height, x = left, y = top, rot = rot */};
  652. chart.style.position = position;
  653. chart.style.fill = shapeStyleChart != null ? shapeStyleChart.fill : null;
  654. chart.style.border = shapeStyleChart != null ? shapeStyleChart.border : null;
  655. chart.style.effect = shapeStyleChart != null ? shapeStyleChart.effect : null;
  656. chart.svg = new HTEXLib.Svg
  657. {
  658. type = "path",
  659. d = "M" + 0 + " " + 0 + ",L" + position.cx + " " + 0 + ",L" + position.cx + " " + position.cy + ",L" + 0 + " " + position.cy + " z",
  660. close = true
  661. //new Rect {
  662. // x=position.x,
  663. // y = position.y,
  664. // width=position.cx,
  665. // height=position.cy,
  666. // type="rect"
  667. // }
  668. };
  669. if (chart.style != null)
  670. {
  671. if (chart.style.fill.type == -1 || chart.style.fill.type == 0)
  672. {
  673. chart.style.fill = null;
  674. }
  675. if (chart.style.border != null && chart.style.border.type == "none")
  676. {
  677. chart.style.border = null;
  678. }
  679. }
  680. return chart;
  681. }
  682. public static List<HTEXLib. CommonChart> DoPlotArea(PlotArea plotArea, WordprocessingDocument wordDoc, XElement element, Func<ImageInfo, XElement> ImageHandler, HTEXLib.Position positionc)
  683. {
  684. List<HTEXLib.CommonChart> charts = new List<HTEXLib.CommonChart>();
  685. foreach (var child in plotArea.ChildElements)
  686. {
  687. string key = child.LocalName;
  688. IEnumerable<XElement> serNodes = null;
  689. switch (key)
  690. {
  691. //break块中不可以随意更换,此条件用于归类不同从Chart
  692. case "pieChart":
  693. case "ofPieChart":
  694. case "pie3DChart":
  695. case "doughnutChart":
  696. HTEXLib.PieChart pieChart = new HTEXLib.PieChart { chartType = "pie" };
  697. if (key.Equals("pie3DChart"))
  698. {
  699. pieChart.is3D = true;
  700. }
  701. pieChart.pieType = key;
  702. if (key.Equals("ofPieChart"))
  703. {
  704. var ofPieType = HTEXLib.ShapeHelper.GetPPTXNodeByPath(child, "c:ofPieType");
  705. if (ofPieType != null)
  706. {
  707. //ofPieChart-pie ofPieChart-bar 子母饼图
  708. pieChart.pieType += "-" + ofPieType.Attribute("val").Value;
  709. }
  710. }
  711. serNodes = HTEXLib.ShapeHelper.GetPPTXNodeListByPath(child, "c:ser") ;
  712. pieChart.datas = ExtractChartData(serNodes,wordDoc,element, ImageHandler, positionc);
  713. charts.Add(pieChart);
  714. break;
  715. case "lineChart":
  716. case "line3DChart":
  717. HTEXLib.LineChart lineChart = new HTEXLib.LineChart { chartType = "line" };
  718. if (key.Equals("line3DChart"))
  719. {
  720. lineChart.is3D = true;
  721. }
  722. lineChart.lineType = key;
  723. var LineGrouping = HTEXLib.ShapeHelper.GetPPTXNodeByPath(child, "c:grouping");
  724. if (LineGrouping != null)
  725. {
  726. //standard stacked percentStacked
  727. lineChart.lineType += "-" + LineGrouping.Attribute("val").Value;
  728. }
  729. serNodes = HTEXLib.ShapeHelper.GetPPTXNodeListByPath(child, "c:ser");
  730. lineChart.datas = ExtractChartData(serNodes, wordDoc, element, ImageHandler, positionc);
  731. charts.Add(lineChart);
  732. break;
  733. case "barChart":
  734. case "bar3DChart":
  735. var barDir = HTEXLib.ShapeHelper.GetPPTXNodeByPath(child, "c:barDir");
  736. if (barDir != null)
  737. {
  738. if (barDir.Attribute("val").Value.Equals("bar"))
  739. {
  740. HTEXLib.BarChart barChart = new HTEXLib.BarChart { chartType = "bar" };
  741. charts.Add(barChart);
  742. if (key.Equals("bar3DChart"))
  743. {
  744. barChart.is3D = true;
  745. }
  746. barChart.barType = key;
  747. var BarGrouping = HTEXLib.ShapeHelper.GetPPTXNodeByPath(child, "c:grouping");
  748. if (BarGrouping != null)
  749. {
  750. //standard stacked percentStacked
  751. barChart.barType += "-" + BarGrouping.Attribute("val").Value;
  752. }
  753. serNodes = HTEXLib.ShapeHelper.GetPPTXNodeListByPath(child, "c:ser");
  754. barChart.datas = ExtractChartData(serNodes, wordDoc, element, ImageHandler, positionc);
  755. charts.Add(barChart);
  756. }
  757. else if (barDir.Attribute("val").Value.Equals("col"))
  758. {
  759. HTEXLib.ColChart colChart = new HTEXLib.ColChart { chartType = "col" };
  760. if (key.Equals("bar3DChart"))
  761. {
  762. colChart.is3D = true;
  763. }
  764. colChart.colType = key.Replace("bar", "col");
  765. var ColGrouping = HTEXLib.ShapeHelper.GetPPTXNodeByPath(child, "c:grouping");
  766. if (ColGrouping != null)
  767. {
  768. //standard stacked percentStacked
  769. colChart.colType += "-" + ColGrouping.Attribute("val").Value;
  770. }
  771. serNodes = HTEXLib.ShapeHelper.GetPPTXNodeListByPath(child, "c:ser");
  772. colChart.datas = ExtractChartData(serNodes, wordDoc, element, ImageHandler, positionc);
  773. charts.Add(colChart);
  774. }
  775. }
  776. break;
  777. case "areaChart":
  778. case "area3DChart":
  779. HTEXLib.AreaChart areaChart = new HTEXLib.AreaChart { chartType = "area" };
  780. if (key.Equals("area3DChart"))
  781. {
  782. areaChart.is3D = true;
  783. }
  784. areaChart.areaType = key;
  785. var AreaGrouping = HTEXLib.ShapeHelper.GetPPTXNodeByPath(child, "c:grouping");
  786. if (AreaGrouping != null)
  787. {
  788. //standard stacked percentStacked
  789. areaChart.areaType += "-" + AreaGrouping.Attribute("val").Value;
  790. }
  791. serNodes = HTEXLib.ShapeHelper.GetPPTXNodeListByPath(child, "c:ser");
  792. areaChart.datas = ExtractChartData(serNodes, wordDoc, element, ImageHandler, positionc);
  793. charts.Add(areaChart);
  794. break;
  795. case "scatterChart":
  796. case "bubbleChart":
  797. HTEXLib.ScatterChart scatterChart = new HTEXLib.ScatterChart { chartType = "scatter" };
  798. scatterChart.scatterType = key;
  799. if (key.Equals("scatterChart"))
  800. {
  801. var ScatterStyle = HTEXLib.ShapeHelper.GetPPTXNodeByPath(child, "c:scatterStyle");
  802. if (ScatterStyle != null)
  803. {
  804. scatterChart.scatterType += "-" + ScatterStyle.Attribute("val").Value.Replace("Marker", "");
  805. }
  806. }
  807. serNodes = HTEXLib.ShapeHelper.GetPPTXNodeListByPath(child, "c:ser");
  808. scatterChart.datas = ExtractChartData(serNodes, wordDoc, element, ImageHandler, positionc);
  809. charts.Add(scatterChart);
  810. break;
  811. case "radarChart":
  812. HTEXLib.RadarChart radarChart = new HTEXLib.RadarChart { chartType = "radar" };
  813. radarChart.radarType = key;
  814. var RadarStyle = HTEXLib.ShapeHelper.GetPPTXNodeByPath(child, "c:radarStyle");
  815. if (RadarStyle != null)
  816. {
  817. radarChart.radarType += "-" + RadarStyle.Attribute("val").Value;
  818. }
  819. serNodes = HTEXLib.ShapeHelper.GetPPTXNodeListByPath(child, "c:ser");
  820. radarChart.datas = ExtractChartData(serNodes, wordDoc, element, ImageHandler, positionc);
  821. charts.Add(radarChart);
  822. break;
  823. case "plotAreaRegion":
  824. HTEXLib.PlotAreaChart plotAreaChart = new HTEXLib.PlotAreaChart { chartType = "plotArea" };
  825. plotAreaChart.plotAreaType = key;
  826. var PlotSeries = HTEXLib.ShapeHelper.GetPPTXNodeByPath(child, "cx:series");
  827. if (PlotSeries != null)
  828. {
  829. plotAreaChart.plotAreaType += "-" + PlotSeries.Attribute("val").Value;
  830. }
  831. serNodes = HTEXLib.ShapeHelper.GetPPTXNodeListByPath(child, "c:ser");
  832. plotAreaChart.datas = ExtractChartData(serNodes, wordDoc, element, ImageHandler, positionc);
  833. charts.Add(plotAreaChart);
  834. break;
  835. case "stockChart":
  836. HTEXLib.StockChart stockChart = new HTEXLib.StockChart { chartType = "stock" };
  837. stockChart.stockType = key;
  838. serNodes = HTEXLib.ShapeHelper.GetPPTXNodeListByPath(child, "c:ser");
  839. stockChart.datas = ExtractChartData(serNodes, wordDoc, element, ImageHandler, positionc);
  840. charts.Add(stockChart);
  841. break;
  842. case "surfaceChart":
  843. case "surface3DChart":
  844. HTEXLib.SurfaceChart surfaceChart = new HTEXLib.SurfaceChart { chartType = "surface" };
  845. if (key.Equals("surface3DChart"))
  846. {
  847. surfaceChart.is3D = true;
  848. }
  849. surfaceChart.surfaceType = key;
  850. var Wireframe = HTEXLib.ShapeHelper.GetPPTXNodeByPath(child, "c:wireframe");
  851. if (Wireframe != null)
  852. {
  853. surfaceChart.surfaceType += "-" + Wireframe.Attribute("val").Value;
  854. }
  855. serNodes = HTEXLib.ShapeHelper.GetPPTXNodeListByPath(child, "c:ser");
  856. surfaceChart.datas = ExtractChartData(serNodes, wordDoc, element, ImageHandler, positionc);
  857. charts.Add(surfaceChart);
  858. break;
  859. }
  860. }
  861. return charts;
  862. }
  863. public static List<Dictionary<string, object>> ExtractChartData(IEnumerable<XElement> nodes, WordprocessingDocument wordDoc, XElement element, Func<ImageInfo, XElement> ImageHandler, HTEXLib.Position positionc)
  864. {
  865. if (nodes != null)
  866. {
  867. List<Dictionary<string, object>> listDict = new List<Dictionary<string, object>>();
  868. foreach (XElement node in nodes)
  869. {
  870. if (HTEXLib.ShapeHelper.GetPPTXNodeByPath(node, "c:xVal") != null)
  871. {
  872. Dictionary<string, object> dict = new Dictionary<string, object>();
  873. var xCvNodes = HTEXLib.ShapeHelper.GetPPTXNodeListByPath(node, "c:xVal/c:numRef/c:numCache/c:pt/c:v");
  874. if (xCvNodes != null)
  875. {
  876. List<string> list = new List<string>();
  877. foreach (XElement cvNode in xCvNodes)
  878. {
  879. list.Add(cvNode.Value);
  880. }
  881. dict.Add("xAxis", list);
  882. }
  883. var yCvNodes = HTEXLib.ShapeHelper.GetPPTXNodeListByPath(node, "c:yVal/c:numRef/c:numCache/c:pt/c:v");
  884. if (yCvNodes != null)
  885. {
  886. List<string> list = new List<string>();
  887. foreach (XElement cvNode in yCvNodes)
  888. {
  889. list.Add(cvNode.Value);
  890. }
  891. dict.Add("yAxis", list);
  892. }
  893. dict.Add("colName", "-");
  894. listDict.Add(dict);
  895. }
  896. else
  897. {
  898. Dictionary<string, object> dict = new Dictionary<string, object>();
  899. var spPr = HTEXLib.ShapeHelper.GetPPTXNodeByPath(node, "c:spPr");
  900. if (spPr != null)
  901. {
  902. var ChartShapeProperties = new ChartShapeProperties(spPr.ToString());
  903. HTEXLib.Models.HTEX. ShapeStyle shapeStyle = WORDHelper.DoShapeProperties(wordDoc,ChartShapeProperties,element, ImageHandler, positionc);
  904. dict.Add("colStyle", shapeStyle);
  905. }
  906. else
  907. {
  908. dict.Add("colStyle", null);
  909. }
  910. var colNameNode = HTEXLib.ShapeHelper.GetPPTXNodeByPath(node,"c:tx/c:strRef/c:strCache/c:pt/c:v");
  911. if (colNameNode != null)
  912. {
  913. dict.Add("colName", colNameNode.Value);
  914. }
  915. //name
  916. var catNodes = HTEXLib.ShapeHelper.GetPPTXNodeListByPath(node, "c:cat/c:strRef/c:strCache/c:pt/c:v");
  917. if (catNodes == null)
  918. {
  919. catNodes = HTEXLib.ShapeHelper.GetPPTXNodeListByPath(node, "c:cat/c:numRef/c:numCache/c:pt/c:v");
  920. }
  921. if (catNodes != null)
  922. {
  923. List<string> list = new List<string>();
  924. foreach (XElement cvNode in catNodes)
  925. {
  926. list.Add(cvNode.Value);
  927. }
  928. dict.Add("xAxis", list);
  929. }
  930. //value
  931. var valNodes = HTEXLib.ShapeHelper.GetPPTXNodeListByPath(node, "c:val/c:numRef/c:numCache/c:pt/c:v");
  932. if (valNodes != null)
  933. {
  934. List<string> list = new List<string>();
  935. foreach (XElement cvNode in valNodes)
  936. {
  937. list.Add(cvNode.Value);
  938. }
  939. dict.Add("yAxis", list);
  940. }
  941. listDict.Add(dict);
  942. }
  943. }
  944. return listDict;
  945. }
  946. return null;
  947. }
  948. public static XElement ProcessDgm(WordprocessingDocument wordDoc, XElement containerElement, Func<ImageInfo, XElement> imageHandler,
  949. int? extentCx, int? extentCy, string altText, XElement element, string hyperlinkUri)
  950. {
  951. var rdm = element.Attribute(R.dm);
  952. var dgm = wordDoc.MainDocumentPart.Parts.FirstOrDefault(pp => pp.RelationshipId == rdm.Value);
  953. return null;
  954. }
  955. public static string ProcessWps(WordprocessingDocument wordDoc, XElement element, Func<ImageInfo, XElement> imageHandler) {
  956. // var wps = element.Element(MC.Choice).Element(W.drawing).Element(WP.anchor).Element(A.graphic).Element(A.graphicData).Element(WPS.wsp);
  957. WordprocessingShape wsp = new WordprocessingShape(element.ToString());
  958. var ext = element.GetWordNodeByPath("wps:spPr/a:xfrm/a:ext");
  959. var cx = ext.Attribute("cx").Value;
  960. var cy = ext.Attribute("cy").Value;
  961. HTEXLib.Shape shape = new HTEXLib.Shape();
  962. HTEXLib.Position position = new HTEXLib.Position { x = 0, y = 0, cx = double.Parse(cx) * 96.0 / 914400, cy = double.Parse(cy) * 96.0 / 914400 };
  963. shape.style.position = position;
  964. var ShapeStyle = WORDHelper.DoShapeProperties(wordDoc, wsp.GetFirstChild<DocumentFormat.OpenXml.Office2010.Word.DrawingShape.ShapeProperties>(), element, imageHandler, position);
  965. SlideColor slideColor = WORDHelper.DoShapeStyle(wsp.GetFirstChild<DocumentFormat.OpenXml.Office2010.Word.DrawingShape.ShapeStyle>(), wordDoc);
  966. if (ShapeStyle.border != null) {
  967. shape.style.border = ShapeStyle.border;
  968. }
  969. //从ShapeProperties 获取 p:spPr
  970. //再从 ShapeStyle 获取 p:spPr
  971. if (ShapeStyle.border == null || ShapeStyle.border.color == null || ShapeStyle.border.color.type == -1)
  972. {
  973. if (slideColor != null)
  974. {
  975. shape.style.border.color.solidFill = slideColor.LineColor;
  976. shape.style.border.color.type = 2;
  977. shape.style.border.outline = ShapeStyle.border != null && ShapeStyle.border.outline != null ? ShapeStyle.border.outline : null;
  978. }
  979. }
  980. else
  981. {
  982. shape.style.border = ShapeStyle.border;
  983. shape.style.border.outline = ShapeStyle.border != null && ShapeStyle.border.outline != null ? ShapeStyle.border.outline : ShapeStyle.border.outline != null? ShapeStyle.border.outline:null;
  984. }
  985. if (ShapeStyle.fill == null || ShapeStyle.fill.type == -1)
  986. {
  987. if (slideColor != null)
  988. {
  989. shape.style.fill.solidFill = slideColor.FillColor;
  990. shape.style.fill.type = 2;
  991. }
  992. }
  993. else
  994. {
  995. shape.style.fill = ShapeStyle.fill;
  996. }
  997. var wpars = element.GetWordNodeListByPath("wps:txbx/w:txbxContent/w:p");
  998. List<string> pars = new List<string>();
  999. if (wpars != null)
  1000. {
  1001. foreach (var wpar in wpars)
  1002. {
  1003. if (wpar.Value != null)
  1004. {
  1005. pars.Add(wpar.Value);
  1006. }
  1007. }
  1008. }
  1009. var prstGeom = element.GetWordNodeByPath("wps:spPr/a:prstGeom");
  1010. if (prstGeom != null)
  1011. {
  1012. var shapeType = prstGeom.Attribute("prst").Value;
  1013. var svg = SvgHelper.GenShapeSvg(new PresetGeometry(prstGeom.ToString()), shapeType, position, null);
  1014. shape.svg = svg;
  1015. }
  1016. else
  1017. {
  1018. var custGeom = element.GetWordNodeByPath("wps:spPr/a:custGeom");
  1019. if (custGeom != null)
  1020. {
  1021. DocumentFormat.OpenXml.Drawing.CustomGeometry shapeTypeCustom = new CustomGeometry(custGeom.ToString());
  1022. shape = PPTXHelper.DoCustomGeometry(shapeTypeCustom, shape);
  1023. }
  1024. }
  1025. return DrawingShape(shape);
  1026. }
  1027. public static string DrawingShape(HTEXLib.Shape shape) {
  1028. StringBuilder builder = new StringBuilder();
  1029. if (shape.svg != null)
  1030. {
  1031. builder.Append($"<svg xmlns='http://www.w3.org/2000/svg' style='width:{shape.style.position.cx}px;height:{shape.style.position.cy}px;rotate({shape.style.position.rot}deg); overflow: visible;'>");
  1032. string bdc = shape.style.border != null && shape.style.border.color != null && shape.style.border.color.solidFill != null ? shape.style.border.color.solidFill : "none";
  1033. string bds = shape.style.border != null && shape.style.border.stroke != null ? shape.style.border.stroke : "0";
  1034. double? bdw = shape.style.border != null && shape.style.border.outline != null && shape.style.border.outline.width != null ? shape.style.border.outline.width : 0;
  1035. string bgc = shape.style.fill != null && shape.style.fill != null && shape.style.fill.solidFill != null ? shape.style.fill.solidFill : "none";
  1036. if (shape.style.border!=null&&(shape.style.border.tailEnd != null || shape.style.border.headEnd != null)) {
  1037. builder.Append("<defs xmlns='http://www.w3.org/2000/svg'>");
  1038. builder.Append($"<marker id='marker{shape.uid}' viewBox='0 0 20 20' refX='1' refY='10' markerWidth='10' markerHeight='20' stroke='{bdc}' fill='{bdc}' orient='auto-start-reverse' markerUnits='strokeWidth'><path d='M 0 0 L 20 10 L 0 20 z' /></marker>");
  1039. builder.Append("</defs>");
  1040. }
  1041. string stm = "";
  1042. string edm = "";
  1043. if (shape.style.border!=null&&shape.style.border.headEnd != null) {
  1044. stm= $" marker-start='url(#marker{ shape.uid})'" ;
  1045. }
  1046. if (shape.style.border != null && shape.style.border.tailEnd != null)
  1047. {
  1048. edm = $" marker-end='url(#marker{ shape.uid})'";
  1049. }
  1050. builder.Append($"<path xmlns='http://www.w3.org/2000/svg' d='{shape.svg.d}' fill='{bgc}' stroke='{bdc}' stroke-width='{bdw}' stroke-dasharray='{bds}' {stm} {edm} />");
  1051. builder.Append("</svg>");
  1052. }
  1053. return builder.ToString() ;
  1054. }
  1055. public static XElement ProcessOMath(XElement element)
  1056. {
  1057. //XslCompiledTransform xslTransform = new XslCompiledTransform();
  1058. // xslTransform.Load(BaseConfigModel.ContentRootPath + "/Config/Core/OMML2MML.XSL");
  1059. XmlReader OMML2MML = XmlReader.Create(new StringReader(Globals.OMML2MML));
  1060. XslCompiledTransform xslTransform = new XslCompiledTransform();
  1061. xslTransform.Load(OMML2MML);
  1062. string mathXml = element.ToString();
  1063. string officeML = string.Empty;
  1064. using (TextReader tr = new StringReader(mathXml))
  1065. {
  1066. using (XmlReader reader = XmlReader.Create(tr))
  1067. {
  1068. using (MemoryStream ms = new MemoryStream())
  1069. {
  1070. XmlWriterSettings settings = xslTransform.OutputSettings.Clone();
  1071. settings.ConformanceLevel = ConformanceLevel.Fragment;
  1072. settings.OmitXmlDeclaration = true;
  1073. XmlWriter xw = XmlWriter.Create(ms, settings);
  1074. xslTransform.Transform(reader, xw);
  1075. ms.Seek(0, SeekOrigin.Begin);
  1076. using (StreamReader sr = new StreamReader(ms, Encoding.UTF8))
  1077. {
  1078. officeML = sr.ReadToEnd();
  1079. // Console.Out.WriteLine(officeML);
  1080. }
  1081. }
  1082. }
  1083. }
  1084. officeML= officeML.Replace("mml:", "");
  1085. XElement officeElement = XElement.Load(new StringReader(officeML));
  1086. return officeElement;
  1087. }
  1088. private static object ProcessHyperlinkToBookmark(WordprocessingDocument wordDoc, WmlToHtmlConverterSettings settings, XElement element)
  1089. {
  1090. var style = new Dictionary<string, string>();
  1091. var a = new XElement(Xhtml.a,
  1092. new XAttribute("href", "#" + (string)element.Attribute(W.anchor)),
  1093. element.Elements(W.r).Select(run => ConvertRun(wordDoc, settings, run)));
  1094. if (!a.Nodes().Any())
  1095. a.Add(new XText(""));
  1096. style.Add("text-decoration", "none");
  1097. a.AddAnnotation(style);
  1098. return a;
  1099. }
  1100. private static object ProcessBookmarkStart(XElement element)
  1101. {
  1102. var name = (string)element.Attribute(W.name);
  1103. if (name == null) return null;
  1104. var style = new Dictionary<string, string>();
  1105. var a = new XElement(Xhtml.a,
  1106. new XAttribute("id", name),
  1107. new XText(""));
  1108. if (!a.Nodes().Any())
  1109. a.Add(new XText(""));
  1110. style.Add("text-decoration", "none");
  1111. a.AddAnnotation(style);
  1112. return a;
  1113. }
  1114. private static object ProcessTab(XElement element)
  1115. {
  1116. var tabWidthAtt = element.Attribute(PtOpenXml.TabWidth);
  1117. if (tabWidthAtt == null) return null;
  1118. var leader = (string)element.Attribute(PtOpenXml.Leader);
  1119. var tabWidth = (decimal)tabWidthAtt;
  1120. var style = new Dictionary<string, string>();
  1121. XElement span;
  1122. if (leader != null)
  1123. {
  1124. var leaderChar = ".";
  1125. if (leader == "hyphen")
  1126. leaderChar = "-";
  1127. else if (leader == "dot")
  1128. leaderChar = ".";
  1129. else if (leader == "underscore")
  1130. leaderChar = "_";
  1131. var runContainingTabToReplace = element.Ancestors(W.r).First();
  1132. var fontNameAtt = runContainingTabToReplace.Attribute(PtOpenXml.pt + "FontName") ??
  1133. runContainingTabToReplace.Ancestors(W.p).First().Attribute(PtOpenXml.pt + "FontName");
  1134. var dummyRun = new XElement(W.r,
  1135. fontNameAtt,
  1136. runContainingTabToReplace.Elements(W.rPr),
  1137. new XElement(W.t, leaderChar));
  1138. var widthOfLeaderChar = CalcWidthOfRunInTwips(dummyRun);
  1139. bool forceArial = false;
  1140. if (widthOfLeaderChar == 0)
  1141. {
  1142. dummyRun = new XElement(W.r,
  1143. new XAttribute(PtOpenXml.FontName, "Arial"),
  1144. runContainingTabToReplace.Elements(W.rPr),
  1145. new XElement(W.t, leaderChar));
  1146. widthOfLeaderChar = CalcWidthOfRunInTwips(dummyRun);
  1147. forceArial = true;
  1148. }
  1149. if (widthOfLeaderChar != 0)
  1150. {
  1151. var numberOfLeaderChars = (int)(Math.Floor((tabWidth * 1440) / widthOfLeaderChar));
  1152. if (numberOfLeaderChars < 0)
  1153. numberOfLeaderChars = 0;
  1154. span = new XElement(Xhtml.span,
  1155. new XAttribute(XNamespace.Xml + "space", "preserve"),
  1156. " " + "".PadRight(numberOfLeaderChars, leaderChar[0]) + " ");
  1157. style.Add("margin", "0 0 0 0");
  1158. style.Add("padding", "0 0 0 0");
  1159. style.Add("width", string.Format(NumberFormatInfo.InvariantInfo, "{0:0.00}in", tabWidth));
  1160. style.Add("text-align", "center");
  1161. if (forceArial)
  1162. style.Add("font-family", "Arial");
  1163. }
  1164. else
  1165. {
  1166. span = new XElement(Xhtml.span, new XAttribute(XNamespace.Xml + "space", "preserve"), " ");
  1167. style.Add("margin", "0 0 0 0");
  1168. style.Add("padding", "0 0 0 0");
  1169. style.Add("width", string.Format(NumberFormatInfo.InvariantInfo, "{0:0.00}in", tabWidth));
  1170. style.Add("text-align", "center");
  1171. if (leader == "underscore")
  1172. {
  1173. style.Add("text-decoration", "underline");
  1174. }
  1175. }
  1176. }
  1177. else
  1178. {
  1179. #if false
  1180. var bidi = element
  1181. .Ancestors(W.p)
  1182. .Take(1)
  1183. .Elements(W.pPr)
  1184. .Elements(W.bidi)
  1185. .Where(b => b.Attribute(W.val) == null || b.Attribute(W.val).ToBoolean() == true)
  1186. .FirstOrDefault();
  1187. var isBidi = bidi != null;
  1188. if (isBidi)
  1189. span = new XElement(Xhtml.span, new XEntity("#x200f")); // RLM
  1190. else
  1191. span = new XElement(Xhtml.span, new XEntity("#x200e")); // LRM
  1192. #else
  1193. span = new XElement(Xhtml.span, new XEntity("#x00a0"));
  1194. #endif
  1195. style.Add("margin", string.Format(NumberFormatInfo.InvariantInfo, "0 0 0 {0:0.00}in", tabWidth));
  1196. style.Add("padding", "0 0 0 0");
  1197. }
  1198. span.AddAnnotation(style);
  1199. return span;
  1200. }
  1201. private static object ProcessBreak(XElement element)
  1202. {
  1203. XElement span = null;
  1204. var tabWidth = (decimal?)element.Attribute(PtOpenXml.TabWidth);
  1205. if (tabWidth != null)
  1206. {
  1207. span = new XElement(Xhtml.span);
  1208. span.AddAnnotation(new Dictionary<string, string>
  1209. {
  1210. { "margin", string.Format(NumberFormatInfo.InvariantInfo, "0 0 0 {0:0.00}in", tabWidth) },
  1211. { "padding", "0 0 0 0" }
  1212. });
  1213. }
  1214. var paragraph = element.Ancestors(W.p).FirstOrDefault();
  1215. var isBidi = paragraph != null &&
  1216. paragraph.Elements(W.pPr).Elements(W.bidi).Any(b => b.Attribute(W.val) == null ||
  1217. b.Attribute(W.val).ToBoolean() == true);
  1218. var zeroWidthChar = isBidi ? new XEntity("#x200f") : new XEntity("#x200e");
  1219. return new object[]
  1220. {
  1221. new XElement(Xhtml.br),
  1222. zeroWidthChar,
  1223. span,
  1224. };
  1225. }
  1226. private static object ProcessContentControl(WordprocessingDocument wordDoc, WmlToHtmlConverterSettings settings,
  1227. XElement element, decimal currentMarginLeft)
  1228. {
  1229. var relevantAncestors = element.Ancestors().TakeWhile(a => a.Name != W.txbxContent);
  1230. var isRunLevelContentControl = relevantAncestors.Any(a => a.Name == W.p);
  1231. if (isRunLevelContentControl)
  1232. {
  1233. return element.Elements(W.sdtContent).Elements()
  1234. .Select(e => ConvertToHtmlTransform(wordDoc, settings, e, false, currentMarginLeft))
  1235. .ToList();
  1236. }
  1237. return CreateBorderDivs(wordDoc, settings, element.Elements(W.sdtContent).Elements());
  1238. }
  1239. // Transform the w:p element, including the following sibling w:p element(s)
  1240. // in case the w:p element has a style separator. The sibling(s) will be
  1241. // transformed to h:span elements rather than h:p elements and added to
  1242. // the element (e.g., h:h2) created from the w:p element having the (first)
  1243. // style separator (i.e., a w:specVanish element).
  1244. private static object ProcessParagraph(WordprocessingDocument wordDoc, WmlToHtmlConverterSettings settings,
  1245. XElement element, bool suppressTrailingWhiteSpace, decimal currentMarginLeft)
  1246. {
  1247. // Ignore this paragraph if the previous paragraph has a style separator.
  1248. // We have already transformed this one together with the previous one.
  1249. var previousParagraph = element.ElementsBeforeSelf(W.p).LastOrDefault();
  1250. if (HasStyleSeparator(previousParagraph)) return null;
  1251. var elementName = GetParagraphElementName(element, wordDoc);
  1252. var isBidi = IsBidi(element);
  1253. var paragraph = (XElement)ConvertParagraph(wordDoc, settings, element, elementName,
  1254. suppressTrailingWhiteSpace, currentMarginLeft, isBidi);
  1255. // The paragraph conversion might have created empty spans.
  1256. // These can and should be removed because empty spans are
  1257. // invalid in HTML5.
  1258. paragraph.Elements(Xhtml.span).Where(e => e.IsEmpty).Remove();
  1259. foreach (var span in paragraph.Elements(Xhtml.span).ToList())
  1260. {
  1261. var v = span.Value;
  1262. if (v.Length > 0 && (char.IsWhiteSpace(v[0]) || char.IsWhiteSpace(v[v.Length - 1])) && span.Attribute(XNamespace.Xml + "space") == null)
  1263. span.Add(new XAttribute(XNamespace.Xml + "space", "preserve"));
  1264. }
  1265. while (HasStyleSeparator(element))
  1266. {
  1267. element = element.ElementsAfterSelf(W.p).FirstOrDefault();
  1268. if (element == null) break;
  1269. elementName = Xhtml.span;
  1270. isBidi = IsBidi(element);
  1271. var span = (XElement)ConvertParagraph(wordDoc, settings, element, elementName,
  1272. suppressTrailingWhiteSpace, currentMarginLeft, isBidi);
  1273. var v = span.Value;
  1274. if (v.Length > 0 && (char.IsWhiteSpace(v[0]) || char.IsWhiteSpace(v[v.Length - 1])) && span.Attribute(XNamespace.Xml + "space") == null)
  1275. span.Add(new XAttribute(XNamespace.Xml + "space", "preserve"));
  1276. paragraph.Add(span);
  1277. }
  1278. return paragraph;
  1279. }
  1280. private static object ProcessTable(WordprocessingDocument wordDoc, WmlToHtmlConverterSettings settings, XElement element, decimal currentMarginLeft)
  1281. {
  1282. var style = new Dictionary<string, string>();
  1283. style.AddIfMissing("border-collapse", "collapse");
  1284. style.AddIfMissing("border", "none");
  1285. var bidiVisual = element.Elements(W.tblPr).Elements(W.bidiVisual).FirstOrDefault();
  1286. var tblW = element.Elements(W.tblPr).Elements(W.tblW).FirstOrDefault();
  1287. if (tblW != null)
  1288. {
  1289. var type = (string)tblW.Attribute(W.type);
  1290. if (type != null && type == "pct")
  1291. {
  1292. var w = (int)tblW.Attribute(W._w);
  1293. style.AddIfMissing("width", (w / 50) + "%");
  1294. }
  1295. }
  1296. var tblInd = element.Elements(W.tblPr).Elements(W.tblInd).FirstOrDefault();
  1297. if (tblInd != null)
  1298. {
  1299. var tblIndType = (string)tblInd.Attribute(W.type);
  1300. if (tblIndType != null)
  1301. {
  1302. if (tblIndType == "dxa")
  1303. {
  1304. var width = (decimal?)tblInd.Attribute(W._w);
  1305. if (width != null)
  1306. {
  1307. style.AddIfMissing("margin-left",
  1308. width > 0m
  1309. ? string.Format(NumberFormatInfo.InvariantInfo, "{0}pt", width / 20m)
  1310. : "0");
  1311. }
  1312. }
  1313. }
  1314. }
  1315. var tableDirection = bidiVisual != null ? new XAttribute("dir", "rtl") : new XAttribute("dir", "ltr");
  1316. style.AddIfMissing("margin-bottom", ".001pt");
  1317. var table = new XElement(Xhtml.table,
  1318. // TODO: Revisit and make sure the omission is covered by appropriate CSS.
  1319. // new XAttribute("border", "1"),
  1320. // new XAttribute("cellspacing", 0),
  1321. // new XAttribute("cellpadding", 0),
  1322. tableDirection,
  1323. element.Elements().Select(e => ConvertToHtmlTransform(wordDoc, settings, e, false, currentMarginLeft)));
  1324. table.AddAnnotation(style);
  1325. var jc = (string)element.Elements(W.tblPr).Elements(W.jc).Attributes(W.val).FirstOrDefault() ?? "left";
  1326. XAttribute dir = null;
  1327. XAttribute jcToUse = null;
  1328. if (bidiVisual != null)
  1329. {
  1330. dir = new XAttribute("dir", "rtl");
  1331. if (jc == "left")
  1332. jcToUse = new XAttribute("align", "right");
  1333. else if (jc == "right")
  1334. jcToUse = new XAttribute("align", "left");
  1335. else if (jc == "center")
  1336. jcToUse = new XAttribute("align", "center");
  1337. }
  1338. else
  1339. {
  1340. jcToUse = new XAttribute("align", jc);
  1341. }
  1342. var tableDiv = new XElement(Xhtml.div,
  1343. dir,
  1344. jcToUse,
  1345. table);
  1346. return tableDiv;
  1347. }
  1348. [SuppressMessage("ReSharper", "PossibleNullReferenceException")]
  1349. private static object ProcessTableCell(WordprocessingDocument wordDoc, WmlToHtmlConverterSettings settings, XElement element)
  1350. {
  1351. var style = new Dictionary<string, string>();
  1352. XAttribute colSpan = null;
  1353. XAttribute rowSpan = null;
  1354. var tcPr = element.Element(W.tcPr);
  1355. if (tcPr != null)
  1356. {
  1357. if ((string)tcPr.Elements(W.vMerge).Attributes(W.val).FirstOrDefault() == "restart")
  1358. {
  1359. var currentRow = element.Parent.ElementsBeforeSelf(W.tr).Count();
  1360. var currentCell = element.ElementsBeforeSelf(W.tc).Count();
  1361. var tbl = element.Parent.Parent;
  1362. int rowSpanCount = 1;
  1363. currentRow += 1;
  1364. while (true)
  1365. {
  1366. var row = tbl.Elements(W.tr).Skip(currentRow).FirstOrDefault();
  1367. if (row == null)
  1368. break;
  1369. var cell2 = row.Elements(W.tc).Skip(currentCell).FirstOrDefault();
  1370. if (cell2 == null)
  1371. break;
  1372. if (cell2.Elements(W.tcPr).Elements(W.vMerge).FirstOrDefault() == null)
  1373. break;
  1374. if ((string)cell2.Elements(W.tcPr).Elements(W.vMerge).Attributes(W.val).FirstOrDefault() == "restart")
  1375. break;
  1376. currentRow += 1;
  1377. rowSpanCount += 1;
  1378. }
  1379. rowSpan = new XAttribute("rowspan", rowSpanCount);
  1380. }
  1381. if (tcPr.Element(W.vMerge) != null &&
  1382. (string)tcPr.Elements(W.vMerge).Attributes(W.val).FirstOrDefault() != "restart")
  1383. return null;
  1384. if (tcPr.Element(W.vAlign) != null)
  1385. {
  1386. var vAlignVal = (string)tcPr.Elements(W.vAlign).Attributes(W.val).FirstOrDefault();
  1387. if (vAlignVal == "00")
  1388. style.AddIfMissing("vertical-align", "top");
  1389. else if (vAlignVal == "center")
  1390. style.AddIfMissing("vertical-align", "middle");
  1391. else if (vAlignVal == "bottom")
  1392. style.AddIfMissing("vertical-align", "bottom");
  1393. else
  1394. style.AddIfMissing("vertical-align", "middle");
  1395. }
  1396. style.AddIfMissing("vertical-align", "top");
  1397. if ((string)tcPr.Elements(W.tcW).Attributes(W.type).FirstOrDefault() == "dxa")
  1398. {
  1399. decimal width = (int)tcPr.Elements(W.tcW).Attributes(W._w).FirstOrDefault();
  1400. style.AddIfMissing("width", string.Format(NumberFormatInfo.InvariantInfo, "{0}pt", width / 20m));
  1401. }
  1402. if ((string)tcPr.Elements(W.tcW).Attributes(W.type).FirstOrDefault() == "pct")
  1403. {
  1404. decimal width = (int)tcPr.Elements(W.tcW).Attributes(W._w).FirstOrDefault();
  1405. style.AddIfMissing("width", string.Format(NumberFormatInfo.InvariantInfo, "{0:0.0}%", width / 50m));
  1406. }
  1407. var tcBorders = tcPr.Element(W.tcBorders);
  1408. GenerateBorderStyle(tcBorders, W.top, style, BorderType.Cell);
  1409. GenerateBorderStyle(tcBorders, W.right, style, BorderType.Cell);
  1410. GenerateBorderStyle(tcBorders, W.bottom, style, BorderType.Cell);
  1411. GenerateBorderStyle(tcBorders, W.left, style, BorderType.Cell);
  1412. CreateStyleFromShd(style, tcPr.Element(W.shd));
  1413. var gridSpan = tcPr.Elements(W.gridSpan).Attributes(W.val).Select(a => (int?)a).FirstOrDefault();
  1414. if (gridSpan != null)
  1415. colSpan = new XAttribute("colspan", (int)gridSpan);
  1416. }
  1417. style.AddIfMissing("padding-top", "0");
  1418. style.AddIfMissing("padding-bottom", "0");
  1419. var cell = new XElement(Xhtml.td,
  1420. rowSpan,
  1421. colSpan,
  1422. CreateBorderDivs(wordDoc, settings, element.Elements()));
  1423. cell.AddAnnotation(style);
  1424. return cell;
  1425. }
  1426. private static object ProcessTableRow(WordprocessingDocument wordDoc, WmlToHtmlConverterSettings settings, XElement element,
  1427. decimal currentMarginLeft)
  1428. {
  1429. var style = new Dictionary<string, string>();
  1430. int? trHeight = (int?)element.Elements(W.trPr).Elements(W.trHeight).Attributes(W.val).FirstOrDefault();
  1431. if (trHeight != null)
  1432. style.AddIfMissing("height",
  1433. string.Format(NumberFormatInfo.InvariantInfo, "{0:0.00}in", (decimal)trHeight / 1440m));
  1434. var htmlRow = new XElement(Xhtml.tr,
  1435. element.Elements().Select(e => ConvertToHtmlTransform(wordDoc, settings, e, false, currentMarginLeft)));
  1436. if (style.Any())
  1437. htmlRow.AddAnnotation(style);
  1438. return htmlRow;
  1439. }
  1440. private static bool HasStyleSeparator(XElement element)
  1441. {
  1442. return element != null && element.Elements(W.pPr).Elements(W.rPr).Any(e => GetBoolProp(e, W.specVanish));
  1443. }
  1444. private static bool IsBidi(XElement element)
  1445. {
  1446. return element
  1447. .Elements(W.pPr)
  1448. .Elements(W.bidi)
  1449. .Any(b => b.Attribute(W.val) == null || b.Attribute(W.val).ToBoolean() == true);
  1450. }
  1451. private static XName GetParagraphElementName(XElement element, WordprocessingDocument wordDoc)
  1452. {
  1453. var elementName = Xhtml.p;
  1454. var styleId = (string)element.Elements(W.pPr).Elements(W.pStyle).Attributes(W.val).FirstOrDefault();
  1455. if (styleId == null) return elementName;
  1456. var style = GetStyle(styleId, wordDoc);
  1457. if (style == null) return elementName;
  1458. var outlineLevel =
  1459. (int?)style.Elements(W.pPr).Elements(W.outlineLvl).Attributes(W.val).FirstOrDefault();
  1460. if (outlineLevel != null && outlineLevel <= 5)
  1461. {
  1462. elementName = Xhtml.xhtml + string.Format("h{0}", outlineLevel + 1);
  1463. }
  1464. return elementName;
  1465. }
  1466. private static XElement GetStyle(string styleId, WordprocessingDocument wordDoc)
  1467. {
  1468. var stylesPart = wordDoc.MainDocumentPart.StyleDefinitionsPart;
  1469. if (stylesPart == null) return null;
  1470. var styles = stylesPart.GetXDocument().Root;
  1471. return styles != null
  1472. ? styles.Elements(W.style).FirstOrDefault(s => (string)s.Attribute(W.styleId) == styleId)
  1473. : null;
  1474. }
  1475. private static object CreateSectionDivs(WordprocessingDocument wordDoc, WmlToHtmlConverterSettings settings, XElement element)
  1476. {
  1477. // note: when building a paging html converter, need to attend to new sections with page breaks here.
  1478. // This code conflates adjacent sections if they have identical formatting, which is not an issue
  1479. // for the non-paging transform.
  1480. var groupedIntoDivs = element
  1481. .Elements()
  1482. .GroupAdjacent(e =>
  1483. {
  1484. var sectAnnotation = e.Annotation<SectionAnnotation>();
  1485. return sectAnnotation != null ? sectAnnotation.SectionElement.ToString() : "";
  1486. });
  1487. // note: when creating a paging html converter, need to pay attention to w:rtlGutter element.
  1488. var divList = groupedIntoDivs
  1489. .Select(g =>
  1490. {
  1491. var sectPr = g.First().Annotation<SectionAnnotation>();
  1492. XElement bidi = null;
  1493. if (sectPr != null)
  1494. {
  1495. bidi = sectPr
  1496. .SectionElement
  1497. .Elements(W.bidi)
  1498. .FirstOrDefault(b => b.Attribute(W.val) == null || b.Attribute(W.val).ToBoolean() == true);
  1499. }
  1500. if (sectPr == null || bidi == null)
  1501. {
  1502. var div = new XElement(Xhtml.div, CreateBorderDivs(wordDoc, settings, g));
  1503. return div;
  1504. }
  1505. else
  1506. {
  1507. var div = new XElement(Xhtml.div,
  1508. new XAttribute("dir", "rtl"),
  1509. CreateBorderDivs(wordDoc, settings, g));
  1510. return div;
  1511. }
  1512. });
  1513. return divList;
  1514. }
  1515. private enum BorderType
  1516. {
  1517. Paragraph,
  1518. Cell,
  1519. };
  1520. /*
  1521. * Notes on line spacing
  1522. *
  1523. * the w:line and w:lineRule attributes control spacing between lines - including between lines within a paragraph
  1524. *
  1525. * If w:spacing w:lineRule="auto" then
  1526. * w:spacing w:line is a percentage where 240 == 100%
  1527. *
  1528. * (line value / 240) * 100 = percentage of line
  1529. *
  1530. * If w:spacing w:lineRule="exact" or w:lineRule="atLeast" then
  1531. * w:spacing w:line is in twips
  1532. * 1440 = exactly one inch from line to line
  1533. *
  1534. * Handle
  1535. * - ind
  1536. * - jc
  1537. * - numPr
  1538. * - pBdr
  1539. * - shd
  1540. * - spacing
  1541. * - textAlignment
  1542. *
  1543. * Don't Handle (yet)
  1544. * - adjustRightInd?
  1545. * - autoSpaceDE
  1546. * - autoSpaceDN
  1547. * - bidi
  1548. * - contextualSpacing
  1549. * - divId
  1550. * - framePr
  1551. * - keepLines
  1552. * - keepNext
  1553. * - kinsoku
  1554. * - mirrorIndents
  1555. * - overflowPunct
  1556. * - pageBreakBefore
  1557. * - snapToGrid
  1558. * - suppressAutoHyphens
  1559. * - suppressLineNumbers
  1560. * - suppressOverlap
  1561. * - tabs
  1562. * - textBoxTightWrap
  1563. * - textDirection
  1564. * - topLinePunct
  1565. * - widowControl
  1566. * - wordWrap
  1567. *
  1568. */
  1569. private static object ConvertParagraph(WordprocessingDocument wordDoc, WmlToHtmlConverterSettings settings,
  1570. XElement paragraph, XName elementName, bool suppressTrailingWhiteSpace, decimal currentMarginLeft, bool isBidi)
  1571. {
  1572. var style = DefineParagraphStyle(paragraph, elementName, suppressTrailingWhiteSpace, currentMarginLeft, isBidi);
  1573. var rtl = isBidi ? new XAttribute("dir", "rtl") : new XAttribute("dir", "ltr");
  1574. var firstMark = isBidi ? new XEntity("#x200f") : null;
  1575. // Analyze initial runs to see whether we have a tab, in which case we will render
  1576. // a span with a defined width and ignore the tab rather than rendering the text
  1577. // preceding the tab and the tab as a span with a computed width.
  1578. var firstTabRun = paragraph
  1579. .Elements(W.r)
  1580. .FirstOrDefault(run => run.Elements(W.tab).Any());
  1581. var elementsPrecedingTab = firstTabRun != null
  1582. ? paragraph.Elements(W.r).TakeWhile(e => e != firstTabRun)
  1583. .Where(e => e.Elements().Any(c => c.Attributes(PtOpenXml.TabWidth).Any())).ToList()
  1584. : Enumerable.Empty<XElement>().ToList();
  1585. // TODO: Revisit
  1586. // For the time being, if a hyperlink field precedes the tab, we'll render it as before.
  1587. var hyperlinkPrecedesTab = elementsPrecedingTab
  1588. .Elements(W.r)
  1589. .Elements(W.instrText)
  1590. .Select(e => e.Value)
  1591. .Any(value => value != null && value.TrimStart().ToUpper().StartsWith("HYPERLINK"));
  1592. if (hyperlinkPrecedesTab)
  1593. {
  1594. var paraElement1 = new XElement(elementName,
  1595. rtl,
  1596. firstMark,
  1597. ConvertContentThatCanContainFields(wordDoc, settings, paragraph.Elements()));
  1598. paraElement1.AddAnnotation(style);
  1599. return paraElement1;
  1600. }
  1601. var txElementsPrecedingTab = TransformElementsPrecedingTab(wordDoc, settings, elementsPrecedingTab, firstTabRun);
  1602. var elementsSucceedingTab = firstTabRun != null
  1603. ? paragraph.Elements().SkipWhile(e => e != firstTabRun).Skip(1)
  1604. : paragraph.Elements();
  1605. var paraElement = new XElement(elementName,
  1606. rtl,
  1607. firstMark,
  1608. txElementsPrecedingTab,
  1609. ConvertContentThatCanContainFields(wordDoc, settings, elementsSucceedingTab));
  1610. paraElement.AddAnnotation(style);
  1611. return paraElement;
  1612. }
  1613. private static List<object> TransformElementsPrecedingTab(WordprocessingDocument wordDoc, WmlToHtmlConverterSettings settings,
  1614. List<XElement> elementsPrecedingTab, XElement firstTabRun)
  1615. {
  1616. var tabWidth = firstTabRun != null
  1617. ? (decimal?)firstTabRun.Elements(W.tab).Attributes(PtOpenXml.TabWidth).FirstOrDefault() ?? 0m
  1618. : 0m;
  1619. var precedingElementsWidth = elementsPrecedingTab
  1620. .Elements()
  1621. .Where(c => c.Attributes(PtOpenXml.TabWidth).Any())
  1622. .Select(e => (decimal)e.Attribute(PtOpenXml.TabWidth))
  1623. .Sum();
  1624. var totalWidth = precedingElementsWidth + tabWidth;
  1625. var txElementsPrecedingTab = elementsPrecedingTab
  1626. .Select(e => ConvertToHtmlTransform(wordDoc, settings, e, false, 0m))
  1627. .ToList();
  1628. if (txElementsPrecedingTab.Count > 1)
  1629. {
  1630. var span = new XElement(Xhtml.span, txElementsPrecedingTab);
  1631. var spanStyle = new Dictionary<string, string>
  1632. {
  1633. { "display", "inline-block" },
  1634. { "text-indent", "0" },
  1635. { "width", string.Format(NumberFormatInfo.InvariantInfo, "{0:0.000}in", totalWidth) }
  1636. };
  1637. span.AddAnnotation(spanStyle);
  1638. }
  1639. else if (txElementsPrecedingTab.Count == 1)
  1640. {
  1641. var element = txElementsPrecedingTab.First() as XElement;
  1642. if (element != null)
  1643. {
  1644. var spanStyle = element.Annotation<Dictionary<string, string>>();
  1645. spanStyle.AddIfMissing("display", "inline-block");
  1646. spanStyle.AddIfMissing("text-indent", "0");
  1647. spanStyle.AddIfMissing("width", string.Format(NumberFormatInfo.InvariantInfo, "{0:0.000}in", totalWidth));
  1648. }
  1649. }
  1650. return txElementsPrecedingTab;
  1651. }
  1652. private static Dictionary<string, string> DefineParagraphStyle(XElement paragraph, XName elementName,
  1653. bool suppressTrailingWhiteSpace, decimal currentMarginLeft, bool isBidi)
  1654. {
  1655. var style = new Dictionary<string, string>();
  1656. var styleName = (string)paragraph.Attribute(PtOpenXml.StyleName);
  1657. if (styleName != null)
  1658. style.Add("PtStyleName", styleName);
  1659. var pPr = paragraph.Element(W.pPr);
  1660. if (pPr == null) return style;
  1661. CreateStyleFromSpacing(style, pPr.Element(W.spacing), elementName, suppressTrailingWhiteSpace);
  1662. CreateStyleFromInd(style, pPr.Element(W.ind), elementName, currentMarginLeft, isBidi);
  1663. // todo need to handle
  1664. // - both
  1665. // - mediumKashida
  1666. // - distribute
  1667. // - numTab
  1668. // - highKashida
  1669. // - lowKashida
  1670. // - thaiDistribute
  1671. CreateStyleFromJc(style, pPr.Element(W.jc), isBidi);
  1672. CreateStyleFromShd(style, pPr.Element(W.shd));
  1673. // Pt.FontName
  1674. var font = (string)paragraph.Attributes(PtOpenXml.FontName).FirstOrDefault();
  1675. if (font != null)
  1676. CreateFontCssProperty(font, style);
  1677. DefineFontSize(style, paragraph);
  1678. DefineLineHeight(style, paragraph);
  1679. // vertical text alignment as of December 2013 does not work in any major browsers.
  1680. CreateStyleFromTextAlignment(style, pPr.Element(W.textAlignment));
  1681. style.AddIfMissing("margin-top", "0");
  1682. style.AddIfMissing("margin-left", "0");
  1683. style.AddIfMissing("margin-right", "0");
  1684. style.AddIfMissing("margin-bottom", ".001pt");
  1685. return style;
  1686. }
  1687. private static void CreateStyleFromInd(Dictionary<string, string> style, XElement ind, XName elementName,
  1688. decimal currentMarginLeft, bool isBidi)
  1689. {
  1690. if (ind == null) return;
  1691. var left = (decimal?)ind.Attribute(W.left);
  1692. if (left != null && elementName != Xhtml.span)
  1693. {
  1694. var leftInInches = (decimal)left / 1440 - currentMarginLeft;
  1695. style.AddIfMissing(isBidi ? "margin-right" : "margin-left",
  1696. leftInInches > 0m
  1697. ? string.Format(NumberFormatInfo.InvariantInfo, "{0:0.00}in", leftInInches)
  1698. : "0");
  1699. }
  1700. var right = (decimal?)ind.Attribute(W.right);
  1701. if (right != null)
  1702. {
  1703. var rightInInches = (decimal)right / 1440;
  1704. style.AddIfMissing(isBidi ? "margin-left" : "margin-right",
  1705. rightInInches > 0m
  1706. ? string.Format(NumberFormatInfo.InvariantInfo, "{0:0.00}in", rightInInches)
  1707. : "0");
  1708. }
  1709. var firstLine = (decimal?)ind.Attribute(W.firstLine);
  1710. if (firstLine != null && elementName != Xhtml.span)
  1711. {
  1712. var firstLineInInches = (decimal)firstLine / 1440m;
  1713. style.AddIfMissing("text-indent",
  1714. string.Format(NumberFormatInfo.InvariantInfo, "{0:0.00}in", firstLineInInches));
  1715. }
  1716. var hanging = (decimal?)ind.Attribute(W.hanging);
  1717. if (hanging != null && elementName != Xhtml.span)
  1718. {
  1719. var hangingInInches = (decimal)-hanging / 1440m;
  1720. style.AddIfMissing("text-indent",
  1721. string.Format(NumberFormatInfo.InvariantInfo, "{0:0.00}in", hangingInInches));
  1722. }
  1723. }
  1724. private static void CreateStyleFromJc(Dictionary<string, string> style, XElement jc, bool isBidi)
  1725. {
  1726. if (jc != null)
  1727. {
  1728. var jcVal = (string)jc.Attributes(W.val).FirstOrDefault() ?? "left";
  1729. if (jcVal == "left")
  1730. style.AddIfMissing("text-align", isBidi ? "right" : "left");
  1731. else if (jcVal == "right")
  1732. style.AddIfMissing("text-align", isBidi ? "left" : "right");
  1733. else if (jcVal == "center")
  1734. style.AddIfMissing("text-align", "center");
  1735. else if (jcVal == "both")
  1736. style.AddIfMissing("text-align", "justify");
  1737. }
  1738. }
  1739. private static void CreateStyleFromSpacing(Dictionary<string, string> style, XElement spacing, XName elementName,
  1740. bool suppressTrailingWhiteSpace)
  1741. {
  1742. if (spacing == null) return;
  1743. var spacingBefore = (decimal?)spacing.Attribute(W.before);
  1744. if (spacingBefore != null && elementName != Xhtml.span)
  1745. style.AddIfMissing("margin-top",
  1746. spacingBefore > 0m
  1747. ? string.Format(NumberFormatInfo.InvariantInfo, "{0}pt", spacingBefore / 20.0m)
  1748. : "0");
  1749. var lineRule = (string)spacing.Attribute(W.lineRule);
  1750. if (lineRule == "auto")
  1751. {
  1752. var line = (decimal)spacing.Attribute(W.line);
  1753. if (line != 240m)
  1754. {
  1755. var pct = (line / 240m) * 100m;
  1756. style.Add("line-height", string.Format(NumberFormatInfo.InvariantInfo, "{0:0.0}%", pct));
  1757. }
  1758. }
  1759. if (lineRule == "exact")
  1760. {
  1761. var line = (decimal)spacing.Attribute(W.line);
  1762. var points = line / 20m;
  1763. style.Add("line-height", string.Format(NumberFormatInfo.InvariantInfo, "{0:0.0}pt", points));
  1764. }
  1765. if (lineRule == "atLeast")
  1766. {
  1767. var line = (decimal)spacing.Attribute(W.line);
  1768. var points = line / 20m;
  1769. if (points >= 14m)
  1770. style.Add("line-height", string.Format(NumberFormatInfo.InvariantInfo, "{0:0.0}pt", points));
  1771. }
  1772. var spacingAfter = suppressTrailingWhiteSpace ? 0m : (decimal?)spacing.Attribute(W.after);
  1773. if (spacingAfter != null)
  1774. style.AddIfMissing("margin-bottom",
  1775. spacingAfter > 0m
  1776. ? string.Format(NumberFormatInfo.InvariantInfo, "{0}pt", spacingAfter / 20.0m)
  1777. : "0");
  1778. }
  1779. private static void CreateStyleFromTextAlignment(Dictionary<string, string> style, XElement textAlignment)
  1780. {
  1781. if (textAlignment == null) return;
  1782. var verticalTextAlignment = (string)textAlignment.Attributes(W.val).FirstOrDefault();
  1783. if (verticalTextAlignment == null || verticalTextAlignment == "auto") return;
  1784. if (verticalTextAlignment == "top")
  1785. style.AddIfMissing("vertical-align", "top");
  1786. else if (verticalTextAlignment == "center")
  1787. style.AddIfMissing("vertical-align", "middle");
  1788. else if (verticalTextAlignment == "baseline")
  1789. style.AddIfMissing("vertical-align", "baseline");
  1790. else if (verticalTextAlignment == "bottom")
  1791. style.AddIfMissing("vertical-align", "bottom");
  1792. }
  1793. private static void DefineFontSize(Dictionary<string, string> style, XElement paragraph)
  1794. {
  1795. var sz = paragraph
  1796. .DescendantsTrimmed(W.txbxContent)
  1797. .Where(e => e.Name == W.r)
  1798. .Select(r => GetFontSize(r))
  1799. .Max();
  1800. if (sz != null)
  1801. style.AddIfMissing("font-size", string.Format(NumberFormatInfo.InvariantInfo, "{0}pt", sz / 2.0m));
  1802. }
  1803. private static void DefineLineHeight(Dictionary<string, string> style, XElement paragraph)
  1804. {
  1805. var allRunsAreUniDirectional = paragraph
  1806. .DescendantsTrimmed(W.txbxContent)
  1807. .Where(e => e.Name == W.r)
  1808. .Select(run => (string)run.Attribute(PtOpenXml.LanguageType))
  1809. .All(lt => lt != "bidi");
  1810. if (allRunsAreUniDirectional)
  1811. style.AddIfMissing("line-height", "108%");
  1812. }
  1813. /*
  1814. * Handle:
  1815. * - b
  1816. * - bdr
  1817. * - caps
  1818. * - color
  1819. * - dstrike
  1820. * - highlight
  1821. * - i
  1822. * - position
  1823. * - rFonts
  1824. * - shd
  1825. * - smallCaps
  1826. * - spacing
  1827. * - strike
  1828. * - sz
  1829. * - u
  1830. * - vanish
  1831. * - vertAlign
  1832. *
  1833. * Don't handle:
  1834. * - em
  1835. * - emboss
  1836. * - fitText
  1837. * - imprint
  1838. * - kern
  1839. * - outline
  1840. * - shadow
  1841. * - w
  1842. *
  1843. */
  1844. private static object ConvertRun(WordprocessingDocument wordDoc, WmlToHtmlConverterSettings settings, XElement run)
  1845. {
  1846. var rPr = run.Element(W.rPr);
  1847. if (rPr == null)
  1848. return run.Elements().Select(e => ConvertToHtmlTransform(wordDoc, settings, e, false, 0m));
  1849. // hide all content that contains the w:rPr/w:webHidden element
  1850. if (rPr.Element(W.webHidden) != null)
  1851. return null;
  1852. var style = DefineRunStyle(run);
  1853. object content = run.Elements().Select(e => ConvertToHtmlTransform(wordDoc, settings, e, false, 0m));
  1854. // Wrap content in h:sup or h:sub elements as necessary.
  1855. if (rPr.Element(W.vertAlign) != null)
  1856. {
  1857. XElement newContent = null;
  1858. var vertAlignVal = (string)rPr.Elements(W.vertAlign).Attributes(W.val).FirstOrDefault();
  1859. switch (vertAlignVal)
  1860. {
  1861. case "superscript":
  1862. newContent = new XElement(Xhtml.sup, content);
  1863. break;
  1864. case "subscript":
  1865. newContent = new XElement(Xhtml.sub, content);
  1866. break;
  1867. }
  1868. if (newContent != null && newContent.Nodes().Any())
  1869. content = newContent;
  1870. }
  1871. var langAttribute = GetLangAttribute(run);
  1872. XEntity runStartMark;
  1873. XEntity runEndMark;
  1874. DetermineRunMarks(run, rPr, style, out runStartMark, out runEndMark);
  1875. if (style.Any() || langAttribute != null || runStartMark != null)
  1876. {
  1877. style.AddIfMissing("margin", "0");
  1878. style.AddIfMissing("padding", "0");
  1879. var xe = new XElement(Xhtml.span,
  1880. langAttribute,
  1881. runStartMark,
  1882. content,
  1883. runEndMark);
  1884. xe.AddAnnotation(style);
  1885. content = xe;
  1886. }
  1887. return content;
  1888. }
  1889. [SuppressMessage("ReSharper", "FunctionComplexityOverflow")]
  1890. private static Dictionary<string, string> DefineRunStyle(XElement run)
  1891. {
  1892. var style = new Dictionary<string, string>();
  1893. var rPr = run.Elements(W.rPr).First();
  1894. var styleName = (string)run.Attribute(PtOpenXml.StyleName);
  1895. if (styleName != null)
  1896. style.Add("PtStyleName", styleName);
  1897. // W.bdr
  1898. if (rPr.Element(W.bdr) != null && (string)rPr.Elements(W.bdr).Attributes(W.val).FirstOrDefault() != "none")
  1899. {
  1900. style.AddIfMissing("border", "solid windowtext 1.0pt");
  1901. style.AddIfMissing("padding", "0");
  1902. }
  1903. // W.color
  1904. var color = (string)rPr.Elements(W.color).Attributes(W.val).FirstOrDefault();
  1905. if (color != null)
  1906. CreateColorProperty("color", color, style);
  1907. // W.highlight
  1908. var highlight = (string)rPr.Elements(W.highlight).Attributes(W.val).FirstOrDefault();
  1909. if (highlight != null)
  1910. CreateColorProperty("background", highlight, style);
  1911. // W.shd
  1912. var shade = (string)rPr.Elements(W.shd).Attributes(W.fill).FirstOrDefault();
  1913. if (shade != null)
  1914. CreateColorProperty("background", shade, style);
  1915. // Pt.FontName
  1916. var sym = run.Element(W.sym);
  1917. var font = sym != null
  1918. ? (string)sym.Attributes(W.font).FirstOrDefault()
  1919. : (string)run.Attributes(PtOpenXml.FontName).FirstOrDefault();
  1920. if (font != null)
  1921. CreateFontCssProperty(font, style);
  1922. // W.sz
  1923. var languageType = (string)run.Attribute(PtOpenXml.LanguageType);
  1924. var sz = GetFontSize(languageType, rPr);
  1925. if (sz != null)
  1926. style.AddIfMissing("font-size", string.Format(NumberFormatInfo.InvariantInfo, "{0}pt", sz / 2.0m));
  1927. // W.caps
  1928. if (GetBoolProp(rPr, W.caps))
  1929. style.AddIfMissing("text-transform", "uppercase");
  1930. // W.smallCaps
  1931. if (GetBoolProp(rPr, W.smallCaps))
  1932. style.AddIfMissing("font-variant", "small-caps");
  1933. // W.spacing
  1934. var spacingInTwips = (decimal?)rPr.Elements(W.spacing).Attributes(W.val).FirstOrDefault();
  1935. if (spacingInTwips != null)
  1936. style.AddIfMissing("letter-spacing",
  1937. spacingInTwips > 0m
  1938. ? string.Format(NumberFormatInfo.InvariantInfo, "{0}pt", spacingInTwips / 20)
  1939. : "0");
  1940. // W.position
  1941. var position = (decimal?)rPr.Elements(W.position).Attributes(W.val).FirstOrDefault();
  1942. if (position != null)
  1943. {
  1944. style.AddIfMissing("position", "relative");
  1945. style.AddIfMissing("top", string.Format(NumberFormatInfo.InvariantInfo, "{0}pt", -(position / 2)));
  1946. }
  1947. // W.vanish
  1948. if (GetBoolProp(rPr, W.vanish) && !GetBoolProp(rPr, W.specVanish))
  1949. style.AddIfMissing("display", "none");
  1950. // W.u
  1951. if (rPr.Element(W.u) != null && (string)rPr.Elements(W.u).Attributes(W.val).FirstOrDefault() != "none")
  1952. style.AddIfMissing("text-decoration", "underline");
  1953. // W.i
  1954. style.AddIfMissing("font-style", GetBoolProp(rPr, W.i) ? "italic" : "normal");
  1955. // W.b
  1956. style.AddIfMissing("font-weight", GetBoolProp(rPr, W.b) ? "bold" : "normal");
  1957. // W.strike
  1958. if (GetBoolProp(rPr, W.strike) || GetBoolProp(rPr, W.dstrike))
  1959. style.AddIfMissing("text-decoration", "line-through");
  1960. return style;
  1961. }
  1962. private static decimal? GetFontSize(XElement e)
  1963. {
  1964. var languageType = (string)e.Attribute(PtOpenXml.LanguageType);
  1965. if (e.Name == W.p)
  1966. {
  1967. return GetFontSize(languageType, e.Elements(W.pPr).Elements(W.rPr).FirstOrDefault());
  1968. }
  1969. if (e.Name == W.r)
  1970. {
  1971. return GetFontSize(languageType, e.Element(W.rPr));
  1972. }
  1973. return null;
  1974. }
  1975. private static decimal? GetFontSize(string languageType, XElement rPr)
  1976. {
  1977. if (rPr == null) return null;
  1978. return languageType == "bidi"
  1979. ? (decimal?)rPr.Elements(W.szCs).Attributes(W.val).FirstOrDefault()
  1980. : (decimal?)rPr.Elements(W.sz).Attributes(W.val).FirstOrDefault();
  1981. }
  1982. private static void DetermineRunMarks(XElement run, XElement rPr, Dictionary<string, string> style, out XEntity runStartMark, out XEntity runEndMark)
  1983. {
  1984. runStartMark = null;
  1985. runEndMark = null;
  1986. // Only do the following for text runs.
  1987. if (run.Element(W.t) == null) return;
  1988. // Can't add directional marks if the font-family is symbol - they are visible, and display as a ?
  1989. var addDirectionalMarks = true;
  1990. if (style.ContainsKey("font-family"))
  1991. {
  1992. if (style["font-family"].ToLower() == "symbol")
  1993. addDirectionalMarks = false;
  1994. }
  1995. if (!addDirectionalMarks) return;
  1996. var isRtl = rPr.Element(W.rtl) != null;
  1997. if (isRtl)
  1998. {
  1999. runStartMark = new XEntity("#x200f"); // RLM
  2000. runEndMark = new XEntity("#x200f"); // RLM
  2001. }
  2002. else
  2003. {
  2004. var paragraph = run.Ancestors(W.p).First();
  2005. var paraIsBidi = paragraph
  2006. .Elements(W.pPr)
  2007. .Elements(W.bidi)
  2008. .Any(b => b.Attribute(W.val) == null || b.Attribute(W.val).ToBoolean() == true);
  2009. if (paraIsBidi)
  2010. {
  2011. runStartMark = new XEntity("#x200e"); // LRM
  2012. runEndMark = new XEntity("#x200e"); // LRM
  2013. }
  2014. }
  2015. }
  2016. private static XAttribute GetLangAttribute(XElement run)
  2017. {
  2018. const string defaultLanguage = "en-US"; // todo need to get defaultLanguage
  2019. var rPr = run.Elements(W.rPr).First();
  2020. var languageType = (string)run.Attribute(PtOpenXml.LanguageType);
  2021. string lang = null;
  2022. if (languageType == "western")
  2023. lang = (string)rPr.Elements(W.lang).Attributes(W.val).FirstOrDefault();
  2024. else if (languageType == "bidi")
  2025. lang = (string)rPr.Elements(W.lang).Attributes(W.bidi).FirstOrDefault();
  2026. else if (languageType == "eastAsia")
  2027. lang = (string)rPr.Elements(W.lang).Attributes(W.eastAsia).FirstOrDefault();
  2028. if (lang == null)
  2029. lang = defaultLanguage;
  2030. return lang != defaultLanguage ? new XAttribute("lang", lang) : null;
  2031. }
  2032. private static void AdjustTableBorders(WordprocessingDocument wordDoc)
  2033. {
  2034. // Note: when implementing a paging version of the HTML transform, this needs to be done
  2035. // for all content parts, not just the main document part.
  2036. var xd = wordDoc.MainDocumentPart.GetXDocument();
  2037. foreach (var tbl in xd.Descendants(W.tbl))
  2038. AdjustTableBorders(tbl);
  2039. wordDoc.MainDocumentPart.PutXDocument();
  2040. }
  2041. private static void AdjustTableBorders(XElement tbl)
  2042. {
  2043. var ta = tbl
  2044. .Elements(W.tr)
  2045. .Select(r => r
  2046. .Elements(W.tc)
  2047. .SelectMany(c =>
  2048. Enumerable.Repeat(c,
  2049. (int?)c.Elements(W.tcPr).Elements(W.gridSpan).Attributes(W.val).FirstOrDefault() ?? 1))
  2050. .ToArray())
  2051. .ToArray();
  2052. for (var y = 0; y < ta.Length; y++)
  2053. {
  2054. for (var x = 0; x < ta[y].Length; x++)
  2055. {
  2056. var thisCell = ta[y][x];
  2057. FixTopBorder(ta, thisCell, x, y);
  2058. FixLeftBorder(ta, thisCell, x, y);
  2059. FixBottomBorder(ta, thisCell, x, y);
  2060. FixRightBorder(ta, thisCell, x, y);
  2061. }
  2062. }
  2063. }
  2064. private static void FixTopBorder(XElement[][] ta, XElement thisCell, int x, int y)
  2065. {
  2066. if (y > 0)
  2067. {
  2068. var rowAbove = ta[y - 1];
  2069. if (x < rowAbove.Length - 1)
  2070. {
  2071. XElement cellAbove = ta[y - 1][x];
  2072. if (cellAbove != null &&
  2073. thisCell.Elements(W.tcPr).Elements(W.tcBorders).FirstOrDefault() != null &&
  2074. cellAbove.Elements(W.tcPr).Elements(W.tcBorders).FirstOrDefault() != null)
  2075. {
  2076. ResolveCellBorder(
  2077. thisCell.Elements(W.tcPr).Elements(W.tcBorders).Elements(W.top).FirstOrDefault(),
  2078. cellAbove.Elements(W.tcPr).Elements(W.tcBorders).Elements(W.bottom).FirstOrDefault());
  2079. }
  2080. }
  2081. }
  2082. }
  2083. private static void FixLeftBorder(XElement[][] ta, XElement thisCell, int x, int y)
  2084. {
  2085. if (x > 0)
  2086. {
  2087. XElement cellLeft = ta[y][x - 1];
  2088. if (cellLeft != null &&
  2089. thisCell.Elements(W.tcPr).Elements(W.tcBorders).FirstOrDefault() != null &&
  2090. cellLeft.Elements(W.tcPr).Elements(W.tcBorders).FirstOrDefault() != null)
  2091. {
  2092. ResolveCellBorder(
  2093. thisCell.Elements(W.tcPr).Elements(W.tcBorders).Elements(W.left).FirstOrDefault(),
  2094. cellLeft.Elements(W.tcPr).Elements(W.tcBorders).Elements(W.right).FirstOrDefault());
  2095. }
  2096. }
  2097. }
  2098. private static void FixBottomBorder(XElement[][] ta, XElement thisCell, int x, int y)
  2099. {
  2100. if (y < ta.Length - 1)
  2101. {
  2102. var rowBelow = ta[y + 1];
  2103. if (x < rowBelow.Length - 1)
  2104. {
  2105. XElement cellBelow = ta[y + 1][x];
  2106. if (cellBelow != null &&
  2107. thisCell.Elements(W.tcPr).Elements(W.tcBorders).FirstOrDefault() != null &&
  2108. cellBelow.Elements(W.tcPr).Elements(W.tcBorders).FirstOrDefault() != null)
  2109. {
  2110. ResolveCellBorder(
  2111. thisCell.Elements(W.tcPr).Elements(W.tcBorders).Elements(W.bottom).FirstOrDefault(),
  2112. cellBelow.Elements(W.tcPr).Elements(W.tcBorders).Elements(W.top).FirstOrDefault());
  2113. }
  2114. }
  2115. }
  2116. }
  2117. private static void FixRightBorder(XElement[][] ta, XElement thisCell, int x, int y)
  2118. {
  2119. if (x < ta[y].Length - 1)
  2120. {
  2121. XElement cellRight = ta[y][x + 1];
  2122. if (cellRight != null &&
  2123. thisCell.Elements(W.tcPr).Elements(W.tcBorders).FirstOrDefault() != null &&
  2124. cellRight.Elements(W.tcPr).Elements(W.tcBorders).FirstOrDefault() != null)
  2125. {
  2126. ResolveCellBorder(
  2127. thisCell.Elements(W.tcPr).Elements(W.tcBorders).Elements(W.right).FirstOrDefault(),
  2128. cellRight.Elements(W.tcPr).Elements(W.tcBorders).Elements(W.left).FirstOrDefault());
  2129. }
  2130. }
  2131. }
  2132. private static readonly Dictionary<string, int> BorderTypePriority = new Dictionary<string, int>()
  2133. {
  2134. { "single", 1 },
  2135. { "thick", 2 },
  2136. { "double", 3 },
  2137. { "dotted", 4 },
  2138. };
  2139. private static readonly Dictionary<string, int> BorderNumber = new Dictionary<string, int>()
  2140. {
  2141. {"single", 1 },
  2142. {"thick", 2 },
  2143. {"double", 3 },
  2144. {"dotted", 4 },
  2145. {"dashed", 5 },
  2146. {"dotDash", 5 },
  2147. {"dotDotDash", 5 },
  2148. {"triple", 6 },
  2149. {"thinThickSmallGap", 6 },
  2150. {"thickThinSmallGap", 6 },
  2151. {"thinThickThinSmallGap", 6 },
  2152. {"thinThickMediumGap", 6 },
  2153. {"thickThinMediumGap", 6 },
  2154. {"thinThickThinMediumGap", 6 },
  2155. {"thinThickLargeGap", 6 },
  2156. {"thickThinLargeGap", 6 },
  2157. {"thinThickThinLargeGap", 6 },
  2158. {"wave", 7 },
  2159. {"doubleWave", 7 },
  2160. {"dashSmallGap", 5 },
  2161. {"dashDotStroked", 5 },
  2162. {"threeDEmboss", 7 },
  2163. {"threeDEngrave", 7 },
  2164. {"outset", 7 },
  2165. {"inset", 7 },
  2166. };
  2167. private static void ResolveCellBorder(XElement border1, XElement border2)
  2168. {
  2169. if (border1 == null || border2 == null)
  2170. return;
  2171. if ((string)border1.Attribute(W.val) == "nil" || (string)border2.Attribute(W.val) == "nil")
  2172. return;
  2173. if ((string)border1.Attribute(W.sz) == "nil" || (string)border2.Attribute(W.sz) == "nil")
  2174. return;
  2175. var border1Val = (string)border1.Attribute(W.val);
  2176. var border1Weight = 1;
  2177. if (BorderNumber.ContainsKey(border1Val))
  2178. border1Weight = BorderNumber[border1Val];
  2179. var border2Val = (string)border2.Attribute(W.val);
  2180. var border2Weight = 1;
  2181. if (BorderNumber.ContainsKey(border2Val))
  2182. border2Weight = BorderNumber[border2Val];
  2183. if (border1Weight != border2Weight)
  2184. {
  2185. if (border1Weight < border2Weight)
  2186. BorderOverride(border2, border1);
  2187. else
  2188. BorderOverride(border1, border2);
  2189. }
  2190. if ((decimal)border1.Attribute(W.sz) > (decimal)border2.Attribute(W.sz))
  2191. {
  2192. BorderOverride(border1, border2);
  2193. return;
  2194. }
  2195. if ((decimal)border1.Attribute(W.sz) < (decimal)border2.Attribute(W.sz))
  2196. {
  2197. BorderOverride(border2, border1);
  2198. return;
  2199. }
  2200. var border1Type = (string)border1.Attribute(W.val);
  2201. var border2Type = (string)border2.Attribute(W.val);
  2202. if (BorderTypePriority.ContainsKey(border1Type) &&
  2203. BorderTypePriority.ContainsKey(border2Type))
  2204. {
  2205. var border1Pri = BorderTypePriority[border1Type];
  2206. var border2Pri = BorderTypePriority[border2Type];
  2207. if (border1Pri < border2Pri)
  2208. {
  2209. BorderOverride(border2, border1);
  2210. return;
  2211. }
  2212. if (border2Pri < border1Pri)
  2213. {
  2214. BorderOverride(border1, border2);
  2215. return;
  2216. }
  2217. }
  2218. var color1Str = (string)border1.Attribute(W.color);
  2219. if (color1Str == "auto")
  2220. color1Str = "000000";
  2221. var color2Str = (string)border2.Attribute(W.color);
  2222. if (color2Str == "auto")
  2223. color2Str = "000000";
  2224. if (color1Str != null && color2Str != null && color1Str != color2Str)
  2225. {
  2226. try
  2227. {
  2228. var color1 = Convert.ToInt32(color1Str, 16);
  2229. var color2 = Convert.ToInt32(color2Str, 16);
  2230. if (color1 < color2)
  2231. {
  2232. BorderOverride(border1, border2);
  2233. return;
  2234. }
  2235. if (color2 < color1)
  2236. {
  2237. BorderOverride(border2, border1);
  2238. }
  2239. }
  2240. // if the above throws ArgumentException, FormatException, or OverflowException, then abort
  2241. catch (Exception)
  2242. {
  2243. // Ignore
  2244. }
  2245. }
  2246. }
  2247. private static void BorderOverride(XElement fromBorder, XElement toBorder)
  2248. {
  2249. toBorder.Attribute(W.val).Value = fromBorder.Attribute(W.val).Value;
  2250. if (fromBorder.Attribute(W.color) != null)
  2251. toBorder.SetAttributeValue(W.color, fromBorder.Attribute(W.color).Value);
  2252. if (fromBorder.Attribute(W.sz) != null)
  2253. toBorder.SetAttributeValue(W.sz, fromBorder.Attribute(W.sz).Value);
  2254. if (fromBorder.Attribute(W.themeColor) != null)
  2255. toBorder.SetAttributeValue(W.themeColor, fromBorder.Attribute(W.themeColor).Value);
  2256. if (fromBorder.Attribute(W.themeTint) != null)
  2257. toBorder.SetAttributeValue(W.themeTint, fromBorder.Attribute(W.themeTint).Value);
  2258. }
  2259. private static void CalculateSpanWidthForTabs(WordprocessingDocument wordDoc)
  2260. {
  2261. // Note: when implementing a paging version of the HTML transform, this needs to be done
  2262. // for all content parts, not just the main document part.
  2263. // w:defaultTabStop in settings
  2264. var sxd = wordDoc.MainDocumentPart.DocumentSettingsPart.GetXDocument();
  2265. var defaultTabStop = (int?)sxd.Descendants(W.defaultTabStop).Attributes(W.val).FirstOrDefault() ?? 720;
  2266. var pxd = wordDoc.MainDocumentPart.GetXDocument();
  2267. var root = pxd.Root;
  2268. if (root == null) return;
  2269. var newRoot = (XElement)CalculateSpanWidthTransform(root, defaultTabStop);
  2270. root.ReplaceWith(newRoot);
  2271. wordDoc.MainDocumentPart.PutXDocument();
  2272. }
  2273. // TODO: Refactor. This method is way too long.
  2274. [SuppressMessage("ReSharper", "FunctionComplexityOverflow")]
  2275. private static object CalculateSpanWidthTransform(XNode node, int defaultTabStop)
  2276. {
  2277. var element = node as XElement;
  2278. if (element == null) return node;
  2279. // if it is not a paragraph or if there are no tabs in the paragraph,
  2280. // then no need to continue processing.
  2281. if (element.Name != W.p ||
  2282. !element.DescendantsTrimmed(W.txbxContent).Where(d => d.Name == W.r).Elements(W.tab).Any())
  2283. {
  2284. // TODO: Revisit. Can we just return the node if it is a paragraph that does not have any tab?
  2285. return new XElement(element.Name,
  2286. element.Attributes(),
  2287. element.Nodes().Select(n => CalculateSpanWidthTransform(n, defaultTabStop)));
  2288. }
  2289. var clonedPara = new XElement(element);
  2290. var leftInTwips = 0;
  2291. var firstInTwips = 0;
  2292. var ind = clonedPara.Elements(W.pPr).Elements(W.ind).FirstOrDefault();
  2293. if (ind != null)
  2294. {
  2295. // todo need to handle start and end attributes
  2296. var left = (int?)ind.Attribute(W.left);
  2297. if (left != null)
  2298. leftInTwips = (int)left;
  2299. var firstLine = 0;
  2300. var firstLineAtt = (int?)ind.Attribute(W.firstLine);
  2301. if (firstLineAtt != null)
  2302. firstLine = (int)firstLineAtt;
  2303. var hangingAtt = (int?)ind.Attribute(W.hanging);
  2304. if (hangingAtt != null)
  2305. firstLine = -(int)hangingAtt;
  2306. firstInTwips = leftInTwips + firstLine;
  2307. }
  2308. // calculate the tab stops, in twips
  2309. var tabs = clonedPara
  2310. .Elements(W.pPr)
  2311. .Elements(W.tabs)
  2312. .FirstOrDefault();
  2313. if (tabs == null)
  2314. {
  2315. if (leftInTwips == 0)
  2316. {
  2317. tabs = new XElement(W.tabs,
  2318. Enumerable.Range(1, 100)
  2319. .Select(r => new XElement(W.tab,
  2320. new XAttribute(W.val, "left"),
  2321. new XAttribute(W.pos, r * defaultTabStop))));
  2322. }
  2323. else
  2324. {
  2325. tabs = new XElement(W.tabs,
  2326. new XElement(W.tab,
  2327. new XAttribute(W.val, "left"),
  2328. new XAttribute(W.pos, leftInTwips)));
  2329. tabs = AddDefaultTabsAfterLastTab(tabs, defaultTabStop);
  2330. }
  2331. }
  2332. else
  2333. {
  2334. if (leftInTwips != 0)
  2335. {
  2336. tabs.Add(
  2337. new XElement(W.tab,
  2338. new XAttribute(W.val, "left"),
  2339. new XAttribute(W.pos, leftInTwips)));
  2340. }
  2341. tabs = AddDefaultTabsAfterLastTab(tabs, defaultTabStop);
  2342. }
  2343. var twipCounter = firstInTwips;
  2344. var contentToMeasure = element.DescendantsTrimmed(z => z.Name == W.txbxContent || z.Name == W.pPr || z.Name == W.rPr).ToArray();
  2345. var currentElementIdx = 0;
  2346. while (true)
  2347. {
  2348. var currentElement = contentToMeasure[currentElementIdx];
  2349. if (currentElement.Name == W.br)
  2350. {
  2351. twipCounter = leftInTwips;
  2352. currentElement.Add(new XAttribute(PtOpenXml.TabWidth,
  2353. string.Format(NumberFormatInfo.InvariantInfo,
  2354. "{0:0.000}", (decimal)firstInTwips / 1440m)));
  2355. currentElementIdx++;
  2356. if (currentElementIdx >= contentToMeasure.Length)
  2357. break; // we're done
  2358. }
  2359. if (currentElement.Name == W.tab)
  2360. {
  2361. var runContainingTabToReplace = currentElement.Parent;
  2362. var fontNameAtt = runContainingTabToReplace.Attribute(PtOpenXml.pt + "FontName") ??
  2363. runContainingTabToReplace.Ancestors(W.p).First().Attribute(PtOpenXml.pt + "FontName");
  2364. var testAmount = twipCounter;
  2365. var tabAfterText = tabs
  2366. .Elements(W.tab)
  2367. .FirstOrDefault(t => (int)t.Attribute(W.pos) > testAmount);
  2368. if (tabAfterText == null)
  2369. {
  2370. // something has gone wrong, so put 1/2 inch in
  2371. if (currentElement.Attribute(PtOpenXml.TabWidth) == null)
  2372. currentElement.Add(
  2373. new XAttribute(PtOpenXml.TabWidth, 720m));
  2374. break;
  2375. }
  2376. var tabVal = (string)tabAfterText.Attribute(W.val);
  2377. if (tabVal == "right" || tabVal == "end")
  2378. {
  2379. var textAfterElements = contentToMeasure
  2380. .Skip(currentElementIdx + 1);
  2381. // take all the content until another tab, br, or cr
  2382. var textElementsToMeasure = textAfterElements
  2383. .TakeWhile(z =>
  2384. z.Name != W.tab &&
  2385. z.Name != W.br &&
  2386. z.Name != W.cr)
  2387. .ToList();
  2388. var textAfterTab = textElementsToMeasure
  2389. .Where(z => z.Name == W.t)
  2390. .Select(t => (string)t)
  2391. .StringConcatenate();
  2392. var dummyRun2 = new XElement(W.r,
  2393. fontNameAtt,
  2394. runContainingTabToReplace.Elements(W.rPr),
  2395. new XElement(W.t, textAfterTab));
  2396. var widthOfTextAfterTab = CalcWidthOfRunInTwips(dummyRun2);
  2397. var delta2 = (int)tabAfterText.Attribute(W.pos) - widthOfTextAfterTab - twipCounter;
  2398. if (delta2 < 0)
  2399. delta2 = 0;
  2400. currentElement.Add(
  2401. new XAttribute(PtOpenXml.TabWidth,
  2402. string.Format(NumberFormatInfo.InvariantInfo, "{0:0.000}", (decimal)delta2 / 1440m)),
  2403. GetLeader(tabAfterText));
  2404. twipCounter = Math.Max((int)tabAfterText.Attribute(W.pos), twipCounter + widthOfTextAfterTab);
  2405. var lastElement = textElementsToMeasure.LastOrDefault();
  2406. if (lastElement == null)
  2407. break; // we're done
  2408. currentElementIdx = Array.IndexOf(contentToMeasure, lastElement) + 1;
  2409. if (currentElementIdx >= contentToMeasure.Length)
  2410. break; // we're done
  2411. continue;
  2412. }
  2413. if (tabVal == "decimal")
  2414. {
  2415. var textAfterElements = contentToMeasure
  2416. .Skip(currentElementIdx + 1);
  2417. // take all the content until another tab, br, or cr
  2418. var textElementsToMeasure = textAfterElements
  2419. .TakeWhile(z =>
  2420. z.Name != W.tab &&
  2421. z.Name != W.br &&
  2422. z.Name != W.cr)
  2423. .ToList();
  2424. var textAfterTab = textElementsToMeasure
  2425. .Where(z => z.Name == W.t)
  2426. .Select(t => (string)t)
  2427. .StringConcatenate();
  2428. if (textAfterTab.Contains("."))
  2429. {
  2430. var mantissa = textAfterTab.Split('.')[0];
  2431. var dummyRun4 = new XElement(W.r,
  2432. fontNameAtt,
  2433. runContainingTabToReplace.Elements(W.rPr),
  2434. new XElement(W.t, mantissa));
  2435. var widthOfMantissa = CalcWidthOfRunInTwips(dummyRun4);
  2436. var delta2 = (int)tabAfterText.Attribute(W.pos) - widthOfMantissa - twipCounter;
  2437. if (delta2 < 0)
  2438. delta2 = 0;
  2439. currentElement.Add(
  2440. new XAttribute(PtOpenXml.TabWidth,
  2441. string.Format(NumberFormatInfo.InvariantInfo, "{0:0.000}", (decimal)delta2 / 1440m)),
  2442. GetLeader(tabAfterText));
  2443. var decims = textAfterTab.Substring(textAfterTab.IndexOf('.'));
  2444. dummyRun4 = new XElement(W.r,
  2445. fontNameAtt,
  2446. runContainingTabToReplace.Elements(W.rPr),
  2447. new XElement(W.t, decims));
  2448. var widthOfDecims = CalcWidthOfRunInTwips(dummyRun4);
  2449. twipCounter = Math.Max((int)tabAfterText.Attribute(W.pos) + widthOfDecims, twipCounter + widthOfMantissa + widthOfDecims);
  2450. var lastElement = textElementsToMeasure.LastOrDefault();
  2451. if (lastElement == null)
  2452. break; // we're done
  2453. currentElementIdx = Array.IndexOf(contentToMeasure, lastElement) + 1;
  2454. if (currentElementIdx >= contentToMeasure.Length)
  2455. break; // we're done
  2456. continue;
  2457. }
  2458. else
  2459. {
  2460. var dummyRun2 = new XElement(W.r,
  2461. fontNameAtt,
  2462. runContainingTabToReplace.Elements(W.rPr),
  2463. new XElement(W.t, textAfterTab));
  2464. var widthOfTextAfterTab = CalcWidthOfRunInTwips(dummyRun2);
  2465. var delta2 = (int)tabAfterText.Attribute(W.pos) - widthOfTextAfterTab - twipCounter;
  2466. if (delta2 < 0)
  2467. delta2 = 0;
  2468. currentElement.Add(
  2469. new XAttribute(PtOpenXml.TabWidth,
  2470. string.Format(NumberFormatInfo.InvariantInfo, "{0:0.000}", (decimal)delta2 / 1440m)),
  2471. GetLeader(tabAfterText));
  2472. twipCounter = Math.Max((int)tabAfterText.Attribute(W.pos), twipCounter + widthOfTextAfterTab);
  2473. var lastElement = textElementsToMeasure.LastOrDefault();
  2474. if (lastElement == null)
  2475. break; // we're done
  2476. currentElementIdx = Array.IndexOf(contentToMeasure, lastElement) + 1;
  2477. if (currentElementIdx >= contentToMeasure.Length)
  2478. break; // we're done
  2479. continue;
  2480. }
  2481. }
  2482. if ((string)tabAfterText.Attribute(W.val) == "center")
  2483. {
  2484. var textAfterElements = contentToMeasure
  2485. .Skip(currentElementIdx + 1);
  2486. // take all the content until another tab, br, or cr
  2487. var textElementsToMeasure = textAfterElements
  2488. .TakeWhile(z =>
  2489. z.Name != W.tab &&
  2490. z.Name != W.br &&
  2491. z.Name != W.cr)
  2492. .ToList();
  2493. var textAfterTab = textElementsToMeasure
  2494. .Where(z => z.Name == W.t)
  2495. .Select(t => (string)t)
  2496. .StringConcatenate();
  2497. var dummyRun4 = new XElement(W.r,
  2498. fontNameAtt,
  2499. runContainingTabToReplace.Elements(W.rPr),
  2500. new XElement(W.t, textAfterTab));
  2501. var widthOfText = CalcWidthOfRunInTwips(dummyRun4);
  2502. var delta2 = (int)tabAfterText.Attribute(W.pos) - (widthOfText / 2) - twipCounter;
  2503. if (delta2 < 0)
  2504. delta2 = 0;
  2505. currentElement.Add(
  2506. new XAttribute(PtOpenXml.TabWidth,
  2507. string.Format(NumberFormatInfo.InvariantInfo, "{0:0.000}", (decimal)delta2 / 1440m)),
  2508. GetLeader(tabAfterText));
  2509. twipCounter = Math.Max((int)tabAfterText.Attribute(W.pos) + widthOfText / 2, twipCounter + widthOfText);
  2510. var lastElement = textElementsToMeasure.LastOrDefault();
  2511. if (lastElement == null)
  2512. break; // we're done
  2513. currentElementIdx = Array.IndexOf(contentToMeasure, lastElement) + 1;
  2514. if (currentElementIdx >= contentToMeasure.Length)
  2515. break; // we're done
  2516. continue;
  2517. }
  2518. if (tabVal == "left" || tabVal == "start" || tabVal == "num")
  2519. {
  2520. var delta = (int)tabAfterText.Attribute(W.pos) - twipCounter;
  2521. currentElement.Add(
  2522. new XAttribute(PtOpenXml.TabWidth,
  2523. string.Format(NumberFormatInfo.InvariantInfo, "{0:0.000}", (decimal)delta / 1440m)),
  2524. GetLeader(tabAfterText));
  2525. twipCounter = (int)tabAfterText.Attribute(W.pos);
  2526. currentElementIdx++;
  2527. if (currentElementIdx >= contentToMeasure.Length)
  2528. break; // we're done
  2529. continue;
  2530. }
  2531. }
  2532. if (currentElement.Name == W.t)
  2533. {
  2534. // TODO: Revisit. This is a quick fix because it doesn't work on Azure.
  2535. // Given the changes we've made elsewhere, though, this is not required
  2536. // for the first tab at least. We could also enhance that other change
  2537. // to deal with all tabs.
  2538. //var runContainingTabToReplace = currentElement.Parent;
  2539. //var paragraphForRun = runContainingTabToReplace.Ancestors(W.p).First();
  2540. //var fontNameAtt = runContainingTabToReplace.Attribute(PtOpenXml.FontName) ??
  2541. // paragraphForRun.Attribute(PtOpenXml.FontName);
  2542. //var languageTypeAtt = runContainingTabToReplace.Attribute(PtOpenXml.LanguageType) ??
  2543. // paragraphForRun.Attribute(PtOpenXml.LanguageType);
  2544. //var dummyRun3 = new XElement(W.r, fontNameAtt, languageTypeAtt,
  2545. // runContainingTabToReplace.Elements(W.rPr),
  2546. // currentElement);
  2547. //var widthOfText = CalcWidthOfRunInTwips(dummyRun3);
  2548. const int widthOfText = 0;
  2549. currentElement.Add(new XAttribute(PtOpenXml.TabWidth,
  2550. string.Format(NumberFormatInfo.InvariantInfo, "{0:0.000}", (decimal)widthOfText / 1440m)));
  2551. twipCounter += widthOfText;
  2552. currentElementIdx++;
  2553. if (currentElementIdx >= contentToMeasure.Length)
  2554. break; // we're done
  2555. continue;
  2556. }
  2557. currentElementIdx++;
  2558. if (currentElementIdx >= contentToMeasure.Length)
  2559. break; // we're done
  2560. }
  2561. return new XElement(element.Name,
  2562. element.Attributes(),
  2563. element.Nodes().Select(n => CalculateSpanWidthTransform(n, defaultTabStop)));
  2564. }
  2565. private static XAttribute GetLeader(XElement tabAfterText)
  2566. {
  2567. var leader = (string)tabAfterText.Attribute(W.leader);
  2568. if (leader == null)
  2569. return null;
  2570. return new XAttribute(PtOpenXml.Leader, leader);
  2571. }
  2572. private static XElement AddDefaultTabsAfterLastTab(XElement tabs, int defaultTabStop)
  2573. {
  2574. var lastTabElement = tabs
  2575. .Elements(W.tab)
  2576. .Where(t => (string)t.Attribute(W.val) != "clear" && (string)t.Attribute(W.val) != "bar")
  2577. .OrderBy(t => (int)t.Attribute(W.pos))
  2578. .LastOrDefault();
  2579. if (lastTabElement != null)
  2580. {
  2581. if (defaultTabStop == 0)
  2582. defaultTabStop = 720;
  2583. var rangeStart = (int)lastTabElement.Attribute(W.pos) / defaultTabStop + 1;
  2584. var tempTabs = new XElement(W.tabs,
  2585. tabs.Elements().Where(t => (string)t.Attribute(W.val) != "clear" && (string)t.Attribute(W.val) != "bar"),
  2586. Enumerable.Range(rangeStart, 100)
  2587. .Select(r => new XElement(W.tab,
  2588. new XAttribute(W.val, "left"),
  2589. new XAttribute(W.pos, r * defaultTabStop))));
  2590. tempTabs = new XElement(W.tabs,
  2591. tempTabs.Elements().OrderBy(t => (int)t.Attribute(W.pos)));
  2592. return tempTabs;
  2593. }
  2594. else
  2595. {
  2596. tabs = new XElement(W.tabs,
  2597. Enumerable.Range(1, 100)
  2598. .Select(r => new XElement(W.tab,
  2599. new XAttribute(W.val, "left"),
  2600. new XAttribute(W.pos, r * defaultTabStop))));
  2601. }
  2602. return tabs;
  2603. }
  2604. private static readonly HashSet<string> UnknownFonts = new HashSet<string>();
  2605. private static HashSet<string> _knownFamilies;
  2606. private static HashSet<string> KnownFamilies
  2607. {
  2608. get
  2609. {
  2610. if (_knownFamilies == null)
  2611. {
  2612. _knownFamilies = new HashSet<string>();
  2613. var families = FontFamily.Families;
  2614. foreach (var fam in families)
  2615. _knownFamilies.Add(fam.Name);
  2616. }
  2617. return _knownFamilies;
  2618. }
  2619. }
  2620. private static int CalcWidthOfRunInTwips(XElement r)
  2621. {
  2622. var fontName = (string)r.Attribute(PtOpenXml.pt + "FontName") ??
  2623. (string)r.Ancestors(W.p).First().Attribute(PtOpenXml.pt + "FontName");
  2624. if (fontName == null)
  2625. throw new OpenXmlPowerToolsException("Internal Error, should have FontName attribute");
  2626. if (UnknownFonts.Contains(fontName))
  2627. return 0;
  2628. var rPr = r.Element(W.rPr);
  2629. if (rPr == null)
  2630. throw new OpenXmlPowerToolsException("Internal Error, should have run properties");
  2631. var sz = GetFontSize(r) ?? 22m;
  2632. // unknown font families will throw ArgumentException, in which case just return 0
  2633. if (!KnownFamilies.Contains(fontName))
  2634. return 0;
  2635. // in theory, all unknown fonts are found by the above test, but if not...
  2636. FontFamily ff;
  2637. try
  2638. {
  2639. ff = new FontFamily(fontName);
  2640. }
  2641. catch (ArgumentException)
  2642. {
  2643. UnknownFonts.Add(fontName);
  2644. return 0;
  2645. }
  2646. var fs = FontStyle.Regular;
  2647. if (GetBoolProp(rPr, W.b) || GetBoolProp(rPr, W.bCs))
  2648. fs |= FontStyle.Bold;
  2649. if (GetBoolProp(rPr, W.i) || GetBoolProp(rPr, W.iCs))
  2650. fs |= FontStyle.Italic;
  2651. // Appended blank as a quick fix to accommodate &nbsp; that will get
  2652. // appended to some layout-critical runs such as list item numbers.
  2653. // In some cases, this might not be required or even wrong, so this
  2654. // must be revisited.
  2655. // TODO: Revisit.
  2656. var runText = r.DescendantsTrimmed(W.txbxContent)
  2657. .Where(e => e.Name == W.t)
  2658. .Select(t => (string)t)
  2659. .StringConcatenate() + " ";
  2660. var tabLength = r.DescendantsTrimmed(W.txbxContent)
  2661. .Where(e => e.Name == W.tab)
  2662. .Select(t => (decimal)t.Attribute(PtOpenXml.TabWidth))
  2663. .Sum();
  2664. if (runText.Length == 0 && tabLength == 0)
  2665. return 0;
  2666. int multiplier = 1;
  2667. if (runText.Length <= 2)
  2668. multiplier = 100;
  2669. else if (runText.Length <= 4)
  2670. multiplier = 50;
  2671. else if (runText.Length <= 8)
  2672. multiplier = 25;
  2673. else if (runText.Length <= 16)
  2674. multiplier = 12;
  2675. else if (runText.Length <= 32)
  2676. multiplier = 6;
  2677. if (multiplier != 1)
  2678. {
  2679. StringBuilder sb = new StringBuilder();
  2680. for (int i = 0; i < multiplier; i++)
  2681. sb.Append(runText);
  2682. runText = sb.ToString();
  2683. }
  2684. var w = MetricsGetter.GetTextWidth(ff, fs, sz, runText);
  2685. return (int)(w / 96m * 1440m / multiplier + tabLength * 1440m);
  2686. }
  2687. private static void InsertAppropriateNonbreakingSpaces(WordprocessingDocument wordDoc)
  2688. {
  2689. foreach (var part in wordDoc.ContentParts())
  2690. {
  2691. var pxd = part.GetXDocument();
  2692. var root = pxd.Root;
  2693. if (root == null) return;
  2694. var newRoot = (XElement)InsertAppropriateNonbreakingSpacesTransform(root);
  2695. root.ReplaceWith(newRoot);
  2696. part.PutXDocument();
  2697. }
  2698. }
  2699. // Non-breaking spaces are not required if we use appropriate CSS, i.e., "white-space: pre-wrap;".
  2700. // We only need to make sure that empty w:p elements are translated into non-empty h:p elements,
  2701. // because empty h:p elements would be ignored by browsers.
  2702. // Further, in addition to not being required, non-breaking spaces would change the layout behavior
  2703. // of spans having consecutive spaces. Therefore, avoiding non-breaking spaces has the additional
  2704. // benefit of leading to a more faithful representation of the Word document in HTML.
  2705. private static object InsertAppropriateNonbreakingSpacesTransform(XNode node)
  2706. {
  2707. XElement element = node as XElement;
  2708. if (element != null)
  2709. {
  2710. // child content of run to look for
  2711. // W.br
  2712. // W.cr
  2713. // W.dayLong
  2714. // W.dayShort
  2715. // W.drawing
  2716. // W.monthLong
  2717. // W.monthShort
  2718. // W.noBreakHyphen
  2719. // W.object
  2720. // W.pgNum
  2721. // W.pTab
  2722. // W.separator
  2723. // W.softHyphen
  2724. // W.sym
  2725. // W.t
  2726. // W.tab
  2727. // W.yearLong
  2728. // W.yearShort
  2729. if (element.Name == W.p)
  2730. {
  2731. // Translate empty paragraphs to paragraphs having one run with
  2732. // a normal space. A non-breaking space, i.e., \x00A0, is not
  2733. // required if we use appropriate CSS.
  2734. bool hasContent = element
  2735. .Elements()
  2736. .Where(e => e.Name != W.pPr)
  2737. .DescendantsAndSelf()
  2738. .Any(e =>
  2739. e.Name == W.dayLong ||
  2740. e.Name == W.dayShort ||
  2741. e.Name == W.drawing ||
  2742. e.Name == W.monthLong ||
  2743. e.Name == W.monthShort ||
  2744. e.Name == W.noBreakHyphen ||
  2745. e.Name == W._object ||
  2746. e.Name == W.pgNum ||
  2747. e.Name == W.ptab ||
  2748. e.Name == W.separator ||
  2749. e.Name == W.softHyphen ||
  2750. e.Name == W.sym ||
  2751. e.Name == W.t ||
  2752. e.Name == W.tab ||
  2753. e.Name == W.yearLong ||
  2754. e.Name == W.yearShort
  2755. );
  2756. if (hasContent == false)
  2757. return new XElement(element.Name,
  2758. element.Attributes(),
  2759. element.Nodes().Select(n => InsertAppropriateNonbreakingSpacesTransform(n)),
  2760. new XElement(W.r,
  2761. element.Elements(W.pPr).Elements(W.rPr),
  2762. new XElement(W.t, " ")));
  2763. }
  2764. return new XElement(element.Name,
  2765. element.Attributes(),
  2766. element.Nodes().Select(n => InsertAppropriateNonbreakingSpacesTransform(n)));
  2767. }
  2768. return node;
  2769. }
  2770. private class SectionAnnotation
  2771. {
  2772. public XElement SectionElement;
  2773. }
  2774. private static void AnnotateForSections(WordprocessingDocument wordDoc)
  2775. {
  2776. var xd = wordDoc.MainDocumentPart.GetXDocument();
  2777. var document = xd.Root;
  2778. if (document == null) return;
  2779. var body = document.Element(W.body);
  2780. if (body == null) return;
  2781. // move last sectPr into last paragraph
  2782. var lastSectPr = body.Elements(W.sectPr).LastOrDefault();
  2783. if (lastSectPr != null)
  2784. {
  2785. // if the last thing in the document is a table, Word will always insert a paragraph following that.
  2786. var lastPara = body
  2787. .DescendantsTrimmed(W.txbxContent)
  2788. .LastOrDefault(p => p.Name == W.p);
  2789. if (lastPara != null)
  2790. {
  2791. var lastParaProps = lastPara.Element(W.pPr);
  2792. if (lastParaProps != null)
  2793. lastParaProps.Add(lastSectPr);
  2794. else
  2795. lastPara.Add(new XElement(W.pPr, lastSectPr));
  2796. lastSectPr.Remove();
  2797. }
  2798. }
  2799. var reverseDescendants = xd.Descendants().Reverse().ToList();
  2800. var currentSection = InitializeSectionAnnotation(reverseDescendants);
  2801. foreach (var d in reverseDescendants)
  2802. {
  2803. if (d.Name == W.sectPr)
  2804. {
  2805. if (d.Attribute(XNamespace.Xmlns + "w") == null)
  2806. d.Add(new XAttribute(XNamespace.Xmlns + "w", W.w));
  2807. currentSection = new SectionAnnotation()
  2808. {
  2809. SectionElement = d
  2810. };
  2811. }
  2812. else
  2813. d.AddAnnotation(currentSection);
  2814. }
  2815. }
  2816. private static SectionAnnotation InitializeSectionAnnotation(IEnumerable<XElement> reverseDescendants)
  2817. {
  2818. var currentSection = new SectionAnnotation()
  2819. {
  2820. SectionElement = reverseDescendants.FirstOrDefault(e => e.Name == W.sectPr)
  2821. };
  2822. if (currentSection.SectionElement != null &&
  2823. currentSection.SectionElement.Attribute(XNamespace.Xmlns + "w") == null)
  2824. currentSection.SectionElement.Add(new XAttribute(XNamespace.Xmlns + "w", W.w));
  2825. // todo what should the default section props be?
  2826. if (currentSection.SectionElement == null)
  2827. currentSection = new SectionAnnotation()
  2828. {
  2829. SectionElement = new XElement(W.sectPr,
  2830. new XAttribute(XNamespace.Xmlns + "w", W.w),
  2831. new XElement(W.pgSz,
  2832. new XAttribute(W._w, 12240),
  2833. new XAttribute(W.h, 15840)),
  2834. new XElement(W.pgMar,
  2835. new XAttribute(W.top, 1440),
  2836. new XAttribute(W.right, 1440),
  2837. new XAttribute(W.bottom, 1440),
  2838. new XAttribute(W.left, 1440),
  2839. new XAttribute(W.header, 720),
  2840. new XAttribute(W.footer, 720),
  2841. new XAttribute(W.gutter, 0)),
  2842. new XElement(W.cols,
  2843. new XAttribute(W.space, 720)),
  2844. new XElement(W.docGrid,
  2845. new XAttribute(W.linePitch, 360)))
  2846. };
  2847. return currentSection;
  2848. }
  2849. private static object CreateBorderDivs(WordprocessingDocument wordDoc, WmlToHtmlConverterSettings settings, IEnumerable<XElement> elements)
  2850. {
  2851. return elements.GroupAdjacent(e =>
  2852. {
  2853. var pBdr = e.Elements(W.pPr).Elements(W.pBdr).FirstOrDefault();
  2854. if (pBdr != null)
  2855. {
  2856. var indStr = string.Empty;
  2857. var ind = e.Elements(W.pPr).Elements(W.ind).FirstOrDefault();
  2858. if (ind != null)
  2859. indStr = ind.ToString(SaveOptions.DisableFormatting);
  2860. return pBdr.ToString(SaveOptions.DisableFormatting) + indStr;
  2861. }
  2862. return e.Name == W.tbl ? "table" : string.Empty;
  2863. })
  2864. .Select(g =>
  2865. {
  2866. if (g.Key == string.Empty)
  2867. {
  2868. return (object)GroupAndVerticallySpaceNumberedParagraphs(wordDoc, settings, g, 0m);
  2869. }
  2870. if (g.Key == "table")
  2871. {
  2872. return g.Select(gc => ConvertToHtmlTransform(wordDoc, settings, gc, false, 0));
  2873. }
  2874. var pPr = g.First().Elements(W.pPr).First();
  2875. var pBdr = pPr.Element(W.pBdr);
  2876. var style = new Dictionary<string, string>();
  2877. GenerateBorderStyle(pBdr, W.top, style, BorderType.Paragraph);
  2878. GenerateBorderStyle(pBdr, W.right, style, BorderType.Paragraph);
  2879. GenerateBorderStyle(pBdr, W.bottom, style, BorderType.Paragraph);
  2880. GenerateBorderStyle(pBdr, W.left, style, BorderType.Paragraph);
  2881. var currentMarginLeft = 0m;
  2882. var ind = pPr.Element(W.ind);
  2883. if (ind != null)
  2884. {
  2885. var leftInInches = (decimal?)ind.Attribute(W.left) / 1440m ?? 0;
  2886. var hangingInInches = -(decimal?)ind.Attribute(W.hanging) / 1440m ?? 0;
  2887. currentMarginLeft = leftInInches + hangingInInches;
  2888. style.AddIfMissing("margin-left",
  2889. currentMarginLeft > 0m
  2890. ? string.Format(NumberFormatInfo.InvariantInfo, "{0:0.00}in", currentMarginLeft)
  2891. : "0");
  2892. }
  2893. var div = new XElement(Xhtml.div,
  2894. GroupAndVerticallySpaceNumberedParagraphs(wordDoc, settings, g, currentMarginLeft));
  2895. div.AddAnnotation(style);
  2896. return div;
  2897. })
  2898. .ToList();
  2899. }
  2900. private static IEnumerable<object> GroupAndVerticallySpaceNumberedParagraphs(WordprocessingDocument wordDoc, WmlToHtmlConverterSettings settings,
  2901. IEnumerable<XElement> elements, decimal currentMarginLeft)
  2902. {
  2903. var grouped = elements
  2904. .GroupAdjacent(e =>
  2905. {
  2906. var abstractNumId = (string)e.Attribute(PtOpenXml.pt + "AbstractNumId");
  2907. if (abstractNumId != null)
  2908. return "num:" + abstractNumId;
  2909. var contextualSpacing = e.Elements(W.pPr).Elements(W.contextualSpacing).FirstOrDefault();
  2910. if (contextualSpacing != null)
  2911. {
  2912. var styleName = (string)e.Elements(W.pPr).Elements(W.pStyle).Attributes(W.val).FirstOrDefault();
  2913. if (styleName == null)
  2914. return "";
  2915. return "sty:" + styleName;
  2916. }
  2917. return "";
  2918. })
  2919. .ToList();
  2920. var newContent = grouped
  2921. .Select(g =>
  2922. {
  2923. if (g.Key == "")
  2924. return g.Select(e => ConvertToHtmlTransform(wordDoc, settings, e, false, currentMarginLeft));
  2925. var last = g.Count() - 1;
  2926. return g.Select((e, i) => ConvertToHtmlTransform(wordDoc, settings, e, i != last, currentMarginLeft));
  2927. });
  2928. return (IEnumerable<object>)newContent;
  2929. }
  2930. private class BorderMappingInfo
  2931. {
  2932. public string CssName;
  2933. public decimal CssSize;
  2934. }
  2935. private static readonly Dictionary<string, BorderMappingInfo> BorderStyleMap = new Dictionary<string, BorderMappingInfo>()
  2936. {
  2937. { "single", new BorderMappingInfo() { CssName = "solid", CssSize = 1.0m }},
  2938. { "dotted", new BorderMappingInfo() { CssName = "dotted", CssSize = 1.0m }},
  2939. { "dashSmallGap", new BorderMappingInfo() { CssName = "dashed", CssSize = 1.0m }},
  2940. { "dashed", new BorderMappingInfo() { CssName = "dashed", CssSize = 1.0m }},
  2941. { "dotDash", new BorderMappingInfo() { CssName = "dashed", CssSize = 1.0m }},
  2942. { "dotDotDash", new BorderMappingInfo() { CssName = "dashed", CssSize = 1.0m }},
  2943. { "double", new BorderMappingInfo() { CssName = "double", CssSize = 2.5m }},
  2944. { "triple", new BorderMappingInfo() { CssName = "double", CssSize = 2.5m }},
  2945. { "thinThickSmallGap", new BorderMappingInfo() { CssName = "double", CssSize = 4.5m }},
  2946. { "thickThinSmallGap", new BorderMappingInfo() { CssName = "double", CssSize = 4.5m }},
  2947. { "thinThickThinSmallGap", new BorderMappingInfo() { CssName = "double", CssSize = 6.0m }},
  2948. { "thickThinMediumGap", new BorderMappingInfo() { CssName = "double", CssSize = 6.0m }},
  2949. { "thinThickMediumGap", new BorderMappingInfo() { CssName = "double", CssSize = 6.0m }},
  2950. { "thinThickThinMediumGap", new BorderMappingInfo() { CssName = "double", CssSize = 9.0m }},
  2951. { "thinThickLargeGap", new BorderMappingInfo() { CssName = "double", CssSize = 5.25m }},
  2952. { "thickThinLargeGap", new BorderMappingInfo() { CssName = "double", CssSize = 5.25m }},
  2953. { "thinThickThinLargeGap", new BorderMappingInfo() { CssName = "double", CssSize = 9.0m }},
  2954. { "wave", new BorderMappingInfo() { CssName = "solid", CssSize = 3.0m }},
  2955. { "doubleWave", new BorderMappingInfo() { CssName = "double", CssSize = 5.25m }},
  2956. { "dashDotStroked", new BorderMappingInfo() { CssName = "solid", CssSize = 3.0m }},
  2957. { "threeDEmboss", new BorderMappingInfo() { CssName = "ridge", CssSize = 6.0m }},
  2958. { "threeDEngrave", new BorderMappingInfo() { CssName = "groove", CssSize = 6.0m }},
  2959. { "outset", new BorderMappingInfo() { CssName = "outset", CssSize = 4.5m }},
  2960. { "inset", new BorderMappingInfo() { CssName = "inset", CssSize = 4.5m }},
  2961. };
  2962. private static void GenerateBorderStyle(XElement pBdr, XName sideXName, Dictionary<string, string> style, BorderType borderType)
  2963. {
  2964. string whichSide;
  2965. if (sideXName == W.top)
  2966. whichSide = "top";
  2967. else if (sideXName == W.right)
  2968. whichSide = "right";
  2969. else if (sideXName == W.bottom)
  2970. whichSide = "bottom";
  2971. else
  2972. whichSide = "left";
  2973. if (pBdr == null)
  2974. {
  2975. style.Add("border-" + whichSide, "none");
  2976. if (borderType == BorderType.Cell &&
  2977. (whichSide == "left" || whichSide == "right"))
  2978. style.Add("padding-" + whichSide, "5.4pt");
  2979. return;
  2980. }
  2981. var side = pBdr.Element(sideXName);
  2982. if (side == null)
  2983. {
  2984. style.Add("border-" + whichSide, "none");
  2985. if (borderType == BorderType.Cell &&
  2986. (whichSide == "left" || whichSide == "right"))
  2987. style.Add("padding-" + whichSide, "5.4pt");
  2988. return;
  2989. }
  2990. var type = (string)side.Attribute(W.val);
  2991. if (type == "nil" || type == "none")
  2992. {
  2993. style.Add("border-" + whichSide + "-style", "none");
  2994. var space = (decimal?)side.Attribute(W.space) ?? 0;
  2995. if (borderType == BorderType.Cell &&
  2996. (whichSide == "left" || whichSide == "right"))
  2997. if (space < 5.4m)
  2998. space = 5.4m;
  2999. style.Add("padding-" + whichSide,
  3000. space == 0 ? "0" : string.Format(NumberFormatInfo.InvariantInfo, "{0:0.0}pt", space));
  3001. }
  3002. else
  3003. {
  3004. var sz = (int)side.Attribute(W.sz);
  3005. var space = (decimal?)side.Attribute(W.space) ?? 0;
  3006. var color = (string)side.Attribute(W.color);
  3007. if (color == null || color == "auto")
  3008. color = "windowtext";
  3009. else
  3010. color = ConvertColor(color);
  3011. decimal borderWidthInPoints = Math.Max(1m, Math.Min(96m, Math.Max(2m, sz)) / 8m);
  3012. var borderStyle = "solid";
  3013. if (BorderStyleMap.ContainsKey(type))
  3014. {
  3015. var borderInfo = BorderStyleMap[type];
  3016. borderStyle = borderInfo.CssName;
  3017. if (type == "double")
  3018. {
  3019. if (sz <= 8)
  3020. borderWidthInPoints = 2.5m;
  3021. else if (sz <= 18)
  3022. borderWidthInPoints = 6.75m;
  3023. else
  3024. borderWidthInPoints = sz / 3m;
  3025. }
  3026. else if (type == "triple")
  3027. {
  3028. if (sz <= 8)
  3029. borderWidthInPoints = 8m;
  3030. else if (sz <= 18)
  3031. borderWidthInPoints = 11.25m;
  3032. else
  3033. borderWidthInPoints = 11.25m;
  3034. }
  3035. else if (type.ToLower().Contains("dash"))
  3036. {
  3037. if (sz <= 4)
  3038. borderWidthInPoints = 1m;
  3039. else if (sz <= 12)
  3040. borderWidthInPoints = 1.5m;
  3041. else
  3042. borderWidthInPoints = 2m;
  3043. }
  3044. else if (type != "single")
  3045. borderWidthInPoints = borderInfo.CssSize;
  3046. }
  3047. if (type == "outset" || type == "inset")
  3048. color = "";
  3049. var borderWidth = string.Format(NumberFormatInfo.InvariantInfo, "{0:0.0}pt", borderWidthInPoints);
  3050. style.Add("border-" + whichSide, borderStyle + " " + color + " " + borderWidth);
  3051. if (borderType == BorderType.Cell &&
  3052. (whichSide == "left" || whichSide == "right"))
  3053. if (space < 5.4m)
  3054. space = 5.4m;
  3055. style.Add("padding-" + whichSide,
  3056. space == 0 ? "0" : string.Format(NumberFormatInfo.InvariantInfo, "{0:0.0}pt", space));
  3057. }
  3058. }
  3059. private static readonly Dictionary<string, Func<string, string, string>> ShadeMapper = new Dictionary<string, Func<string, string, string>>()
  3060. {
  3061. { "auto", (c, f) => c },
  3062. { "clear", (c, f) => f },
  3063. { "nil", (c, f) => f },
  3064. { "solid", (c, f) => c },
  3065. { "diagCross", (c, f) => ConvertColorFillPct(c, f, .75) },
  3066. { "diagStripe", (c, f) => ConvertColorFillPct(c, f, .75) },
  3067. { "horzCross", (c, f) => ConvertColorFillPct(c, f, .5) },
  3068. { "horzStripe", (c, f) => ConvertColorFillPct(c, f, .5) },
  3069. { "pct10", (c, f) => ConvertColorFillPct(c, f, .1) },
  3070. { "pct12", (c, f) => ConvertColorFillPct(c, f, .125) },
  3071. { "pct15", (c, f) => ConvertColorFillPct(c, f, .15) },
  3072. { "pct20", (c, f) => ConvertColorFillPct(c, f, .2) },
  3073. { "pct25", (c, f) => ConvertColorFillPct(c, f, .25) },
  3074. { "pct30", (c, f) => ConvertColorFillPct(c, f, .3) },
  3075. { "pct35", (c, f) => ConvertColorFillPct(c, f, .35) },
  3076. { "pct37", (c, f) => ConvertColorFillPct(c, f, .375) },
  3077. { "pct40", (c, f) => ConvertColorFillPct(c, f, .4) },
  3078. { "pct45", (c, f) => ConvertColorFillPct(c, f, .45) },
  3079. { "pct50", (c, f) => ConvertColorFillPct(c, f, .50) },
  3080. { "pct55", (c, f) => ConvertColorFillPct(c, f, .55) },
  3081. { "pct60", (c, f) => ConvertColorFillPct(c, f, .60) },
  3082. { "pct62", (c, f) => ConvertColorFillPct(c, f, .625) },
  3083. { "pct65", (c, f) => ConvertColorFillPct(c, f, .65) },
  3084. { "pct70", (c, f) => ConvertColorFillPct(c, f, .7) },
  3085. { "pct75", (c, f) => ConvertColorFillPct(c, f, .75) },
  3086. { "pct80", (c, f) => ConvertColorFillPct(c, f, .8) },
  3087. { "pct85", (c, f) => ConvertColorFillPct(c, f, .85) },
  3088. { "pct87", (c, f) => ConvertColorFillPct(c, f, .875) },
  3089. { "pct90", (c, f) => ConvertColorFillPct(c, f, .9) },
  3090. { "pct95", (c, f) => ConvertColorFillPct(c, f, .95) },
  3091. { "reverseDiagStripe", (c, f) => ConvertColorFillPct(c, f, .5) },
  3092. { "thinDiagCross", (c, f) => ConvertColorFillPct(c, f, .5) },
  3093. { "thinDiagStripe", (c, f) => ConvertColorFillPct(c, f, .25) },
  3094. { "thinHorzCross", (c, f) => ConvertColorFillPct(c, f, .3) },
  3095. { "thinHorzStripe", (c, f) => ConvertColorFillPct(c, f, .25) },
  3096. { "thinReverseDiagStripe", (c, f) => ConvertColorFillPct(c, f, .25) },
  3097. { "thinVertStripe", (c, f) => ConvertColorFillPct(c, f, .25) },
  3098. };
  3099. private static readonly Dictionary<string, string> ShadeCache = new Dictionary<string, string>();
  3100. // fill is the background, color is the foreground
  3101. private static string ConvertColorFillPct(string color, string fill, double pct)
  3102. {
  3103. if (color == "auto")
  3104. color = "000000";
  3105. if (fill == "auto")
  3106. fill = "ffffff";
  3107. var key = color + fill + pct.ToString(CultureInfo.InvariantCulture);
  3108. if (ShadeCache.ContainsKey(key))
  3109. return ShadeCache[key];
  3110. var fillRed = Convert.ToInt32(fill.Substring(0, 2), 16);
  3111. var fillGreen = Convert.ToInt32(fill.Substring(2, 2), 16);
  3112. var fillBlue = Convert.ToInt32(fill.Substring(4, 2), 16);
  3113. var colorRed = Convert.ToInt32(color.Substring(0, 2), 16);
  3114. var colorGreen = Convert.ToInt32(color.Substring(2, 2), 16);
  3115. var colorBlue = Convert.ToInt32(color.Substring(4, 2), 16);
  3116. var finalRed = (int)(fillRed - (fillRed - colorRed) * pct);
  3117. var finalGreen = (int)(fillGreen - (fillGreen - colorGreen) * pct);
  3118. var finalBlue = (int)(fillBlue - (fillBlue - colorBlue) * pct);
  3119. var returnValue = string.Format("{0:x2}{1:x2}{2:x2}", finalRed, finalGreen, finalBlue);
  3120. ShadeCache.Add(key, returnValue);
  3121. return returnValue;
  3122. }
  3123. private static void CreateStyleFromShd(Dictionary<string, string> style, XElement shd)
  3124. {
  3125. if (shd == null)
  3126. return;
  3127. var shadeType = (string)shd.Attribute(W.val);
  3128. var color = (string)shd.Attribute(W.color);
  3129. var fill = (string)shd.Attribute(W.fill);
  3130. if (ShadeMapper.ContainsKey(shadeType))
  3131. {
  3132. color = ShadeMapper[shadeType](color, fill);
  3133. }
  3134. if (color != null)
  3135. {
  3136. var cvtColor = ConvertColor(color);
  3137. if (!string.IsNullOrEmpty(cvtColor))
  3138. style.AddIfMissing("background", cvtColor);
  3139. }
  3140. }
  3141. private static readonly Dictionary<string, string> NamedColors = new Dictionary<string, string>()
  3142. {
  3143. {"black", "black"},
  3144. {"blue", "blue" },
  3145. {"cyan", "aqua" },
  3146. {"green", "green" },
  3147. {"magenta", "fuchsia" },
  3148. {"red", "red" },
  3149. {"yellow", "yellow" },
  3150. {"white", "white" },
  3151. {"darkBlue", "#00008B" },
  3152. {"darkCyan", "#008B8B" },
  3153. {"darkGreen", "#006400" },
  3154. {"darkMagenta", "#800080" },
  3155. {"darkRed", "#8B0000" },
  3156. {"darkYellow", "#808000" },
  3157. {"darkGray", "#A9A9A9" },
  3158. {"lightGray", "#D3D3D3" },
  3159. {"none", "" },
  3160. };
  3161. private static void CreateColorProperty(string propertyName, string color, Dictionary<string, string> style)
  3162. {
  3163. if (color == null)
  3164. return;
  3165. // "auto" color is black for "color" and white for "background" property.
  3166. if (color == "auto")
  3167. color = propertyName == "color" ? "black" : "white";
  3168. if (NamedColors.ContainsKey(color))
  3169. {
  3170. var lc = NamedColors[color];
  3171. if (lc == "")
  3172. return;
  3173. style.AddIfMissing(propertyName, lc);
  3174. return;
  3175. }
  3176. style.AddIfMissing(propertyName, "#" + color);
  3177. }
  3178. private static string ConvertColor(string color)
  3179. {
  3180. // "auto" color is black for "color" and white for "background" property.
  3181. // As this method is only called for "background" colors, "auto" is translated
  3182. // to "white" and never "black".
  3183. if (color == "auto")
  3184. color = "white";
  3185. if (NamedColors.ContainsKey(color))
  3186. {
  3187. var lc = NamedColors[color];
  3188. if (lc == "")
  3189. return "black";
  3190. return lc;
  3191. }
  3192. return "#" + color;
  3193. }
  3194. private static readonly Dictionary<string, string> FontFallback = new Dictionary<string, string>()
  3195. {
  3196. { "Arial", @"'{0}', 'sans-serif'" },
  3197. { "Arial Narrow", @"'{0}', 'sans-serif'" },
  3198. { "Arial Rounded MT Bold", @"'{0}', 'sans-serif'" },
  3199. { "Arial Unicode MS", @"'{0}', 'sans-serif'" },
  3200. { "Baskerville Old Face", @"'{0}', 'serif'" },
  3201. { "Berlin Sans FB", @"'{0}', 'sans-serif'" },
  3202. { "Berlin Sans FB Demi", @"'{0}', 'sans-serif'" },
  3203. { "Calibri Light", @"'{0}', 'sans-serif'" },
  3204. { "Gill Sans MT", @"'{0}', 'sans-serif'" },
  3205. { "Gill Sans MT Condensed", @"'{0}', 'sans-serif'" },
  3206. { "Lucida Sans", @"'{0}', 'sans-serif'" },
  3207. { "Lucida Sans Unicode", @"'{0}', 'sans-serif'" },
  3208. { "Segoe UI", @"'{0}', 'sans-serif'" },
  3209. { "Segoe UI Light", @"'{0}', 'sans-serif'" },
  3210. { "Segoe UI Semibold", @"'{0}', 'sans-serif'" },
  3211. { "Tahoma", @"'{0}', 'sans-serif'" },
  3212. { "Trebuchet MS", @"'{0}', 'sans-serif'" },
  3213. { "Verdana", @"'{0}', 'sans-serif'" },
  3214. { "Book Antiqua", @"'{0}', 'serif'" },
  3215. { "Bookman Old Style", @"'{0}', 'serif'" },
  3216. { "Californian FB", @"'{0}', 'serif'" },
  3217. { "Cambria", @"'{0}', 'serif'" },
  3218. { "Constantia", @"'{0}', 'serif'" },
  3219. { "Garamond", @"'{0}', 'serif'" },
  3220. { "Lucida Bright", @"'{0}', 'serif'" },
  3221. { "Lucida Fax", @"'{0}', 'serif'" },
  3222. { "Palatino Linotype", @"'{0}', 'serif'" },
  3223. { "Times New Roman", @"'{0}', 'serif'" },
  3224. { "Wide Latin", @"'{0}', 'serif'" },
  3225. { "Courier New", @"'{0}'" },
  3226. { "Lucida Console", @"'{0}'" },
  3227. };
  3228. private static void CreateFontCssProperty(string font, Dictionary<string, string> style)
  3229. {
  3230. if (FontFallback.ContainsKey(font))
  3231. {
  3232. style.AddIfMissing("font-family", string.Format(FontFallback[font], font));
  3233. return;
  3234. }
  3235. style.AddIfMissing("font-family", font);
  3236. }
  3237. private static bool GetBoolProp(XElement runProps, XName xName)
  3238. {
  3239. var p = runProps.Element(xName);
  3240. if (p == null)
  3241. return false;
  3242. var v = p.Attribute(W.val);
  3243. if (v == null)
  3244. return true;
  3245. var s = v.Value.ToLower();
  3246. if (s == "0" || s == "false")
  3247. return false;
  3248. if (s == "1" || s == "true")
  3249. return true;
  3250. return false;
  3251. }
  3252. private static object ConvertContentThatCanContainFields(WordprocessingDocument wordDoc, WmlToHtmlConverterSettings settings,
  3253. IEnumerable<XElement> elements)
  3254. {
  3255. var grouped = elements
  3256. .GroupAdjacent(e =>
  3257. {
  3258. var stack = e.Annotation<Stack<FieldRetriever.FieldElementTypeInfo>>();
  3259. return stack == null || !stack.Any() ? (int?)null : stack.Select(st => st.Id).Min();
  3260. })
  3261. .ToList();
  3262. var txformed = grouped
  3263. .Select(g =>
  3264. {
  3265. var key = g.Key;
  3266. if (key == null)
  3267. return (object)g.Select(n => ConvertToHtmlTransform(wordDoc, settings, n, false, 0m));
  3268. var instrText = FieldRetriever.InstrText(g.First().Ancestors().Last(), (int)key)
  3269. .TrimStart('{').TrimEnd('}');
  3270. var parsed = FieldRetriever.ParseField(instrText);
  3271. if (parsed.FieldType != "HYPERLINK")
  3272. return g.Select(n => ConvertToHtmlTransform(wordDoc, settings, n, false, 0m));
  3273. var content = g.DescendantsAndSelf(W.r).Select(run => ConvertRun(wordDoc, settings, run));
  3274. var a = parsed.Arguments.Length > 0
  3275. ? new XElement(Xhtml.a, new XAttribute("href", parsed.Arguments[0]), content)
  3276. : new XElement(Xhtml.a, content);
  3277. var a2 = a as XElement;
  3278. if (!a2.Nodes().Any())
  3279. {
  3280. a2.Add(new XText(""));
  3281. return a2;
  3282. }
  3283. return a;
  3284. })
  3285. .ToList();
  3286. return txformed;
  3287. }
  3288. #region Image Processing
  3289. // Don't process wmf files (with contentType == "image/x-wmf") because GDI consumes huge amounts
  3290. // of memory when dealing with wmf perhaps because it loads a DLL to do the rendering?
  3291. // It actually works, but is not recommended.
  3292. public static readonly List<string> ImageContentTypes = new List<string>
  3293. {
  3294. "image/png", "image/gif", "image/tiff", "image/jpeg","image/x-wmf","image/x-emf","application/vnd.openxmlformats-officedocument.oleObject"
  3295. };
  3296. public static XElement ProcessImage(WordprocessingDocument wordDoc,
  3297. XElement element, Func<ImageInfo, XElement> imageHandler)
  3298. {
  3299. if (imageHandler == null)
  3300. {
  3301. return null;
  3302. }
  3303. if (element.Name == W.drawing)
  3304. {
  3305. return ProcessDrawing(wordDoc, element, imageHandler);
  3306. }
  3307. if (element.Name == W.pict || element.Name == W._object)
  3308. {
  3309. return ProcessPictureOrObject(wordDoc, element , imageHandler);
  3310. }
  3311. return null;
  3312. }
  3313. private static XElement ProcessDrawing(WordprocessingDocument wordDoc,
  3314. XElement element, Func<ImageInfo, XElement> imageHandler)
  3315. {
  3316. var containerElement = element.Elements()
  3317. .FirstOrDefault(e => e.Name == WP.inline || e.Name == WP.anchor);
  3318. if (containerElement == null) return null;
  3319. string hyperlinkUri = null;
  3320. var hyperlinkElement = element
  3321. .Elements(WP.inline)
  3322. .Elements(WP.docPr)
  3323. .Elements(A.hlinkClick)
  3324. .FirstOrDefault();
  3325. if (hyperlinkElement != null)
  3326. {
  3327. var rId = (string)hyperlinkElement.Attribute(R.id);
  3328. if (rId != null)
  3329. {
  3330. var hyperlinkRel = wordDoc.MainDocumentPart.HyperlinkRelationships.FirstOrDefault(hlr => hlr.Id == rId);
  3331. if (hyperlinkRel != null)
  3332. {
  3333. hyperlinkUri = hyperlinkRel.Uri.ToString();
  3334. }
  3335. }
  3336. }
  3337. var extentCx = (int?)containerElement.Elements(WP.extent)
  3338. .Attributes(NoNamespace.cx).FirstOrDefault();
  3339. var extentCy = (int?)containerElement.Elements(WP.extent)
  3340. .Attributes(NoNamespace.cy).FirstOrDefault();
  3341. var altText = (string)containerElement.Elements(WP.docPr).Attributes(NoNamespace.descr).FirstOrDefault() ??
  3342. ((string)containerElement.Elements(WP.docPr).Attributes(NoNamespace.name).FirstOrDefault() ?? "");
  3343. if (containerElement.Elements(A.graphic)
  3344. .Elements(A.graphicData) != null)
  3345. {
  3346. XElement rest = null;
  3347. var elms = containerElement.Elements(A.graphic)
  3348. .Elements(A.graphicData).Elements();
  3349. foreach (var elm in elms)
  3350. {
  3351. if (elm.Name == Pic._pic)
  3352. {
  3353. rest= ProcessPic(wordDoc, containerElement, imageHandler, extentCx, extentCy, altText, elm, hyperlinkUri);
  3354. break;
  3355. }
  3356. if (elm.Name == C.chart)
  3357. {
  3358. rest = ProcessChart(wordDoc, containerElement, imageHandler, extentCx, extentCy, altText, elm, hyperlinkUri);
  3359. break;
  3360. }
  3361. if (elm.Name == DGM.relIds)
  3362. {
  3363. rest = ProcessDgm(wordDoc, containerElement, imageHandler, extentCx, extentCy, altText, elm, hyperlinkUri);
  3364. break;
  3365. }
  3366. }
  3367. return rest;
  3368. }
  3369. else {
  3370. return null;
  3371. }
  3372. }
  3373. public static XElement ProcessPic(WordprocessingDocument wordDoc, XElement containerElement, Func<ImageInfo, XElement> imageHandler,
  3374. int? extentCx,int? extentCy,string altText, XElement element,string hyperlinkUri) {
  3375. var blipFill = containerElement.Elements(A.graphic)
  3376. .Elements(A.graphicData)
  3377. .Elements(Pic._pic).Elements(Pic.blipFill).FirstOrDefault();
  3378. if (blipFill == null) return null;
  3379. var imageRid = (string)blipFill.Elements(A.blip).Attributes(R.embed).FirstOrDefault();
  3380. if (imageRid == null) return null;
  3381. var pp3 = wordDoc.MainDocumentPart.Parts.FirstOrDefault(pp => pp.RelationshipId == imageRid);
  3382. if (pp3 == null) return null;
  3383. var imagePart = (ImagePart)pp3.OpenXmlPart;
  3384. if (imagePart == null) return null;
  3385. // If the image markup points to a NULL image, then following will throw an ArgumentOutOfRangeException
  3386. try
  3387. {
  3388. imagePart = (ImagePart)wordDoc.MainDocumentPart.GetPartById(imageRid);
  3389. }
  3390. catch (ArgumentOutOfRangeException)
  3391. {
  3392. return null;
  3393. }
  3394. var contentType = imagePart.ContentType;
  3395. if (!ImageContentTypes.Contains(contentType))
  3396. return null;
  3397. var uil= imagePart.Uri;
  3398. //WORDHelper.GetWordNodeByPath(wordDoc,"");
  3399. var Stream = imagePart.GetStream();
  3400. try
  3401. {
  3402. if (contentType == "image/x-wmf" || contentType == "image/x-emf")
  3403. {
  3404. return ProcessWmf(Stream, contentType, element, hyperlinkUri, imageHandler);
  3405. }
  3406. else
  3407. {
  3408. using (var bitmap = new Bitmap(Stream))
  3409. {
  3410. if (extentCx != null && extentCy != null)
  3411. {
  3412. var imageInfo = new ImageInfo()
  3413. {
  3414. Bitmap = bitmap,
  3415. ImgStyleAttribute = new XAttribute("style",
  3416. string.Format(NumberFormatInfo.InvariantInfo,
  3417. "width: {0}px; ",
  3418. // "height: {1}in",
  3419. (float)extentCx * 96.0 / (float)ImageInfo.EmusPerInch
  3420. // ,
  3421. //(float)extentCy*96.0 / (float)ImageInfo.EmusPerInch
  3422. )),
  3423. ContentType = contentType,
  3424. DrawingElement = element,
  3425. AltText = altText,
  3426. };
  3427. var imgElement2 = imageHandler(imageInfo);
  3428. if (hyperlinkUri != null)
  3429. {
  3430. return new XElement(XhtmlNoNamespace.a,
  3431. new XAttribute(XhtmlNoNamespace.href, hyperlinkUri),
  3432. imgElement2);
  3433. }
  3434. return imgElement2;
  3435. }
  3436. var imageInfo2 = new ImageInfo()
  3437. {
  3438. Bitmap = bitmap,
  3439. ContentType = contentType,
  3440. DrawingElement = element,
  3441. AltText = altText,
  3442. };
  3443. var imgElement = imageHandler(imageInfo2);
  3444. if (hyperlinkUri != null)
  3445. {
  3446. return new XElement(XhtmlNoNamespace.a,
  3447. new XAttribute(XhtmlNoNamespace.href, hyperlinkUri),
  3448. imgElement);
  3449. }
  3450. return imgElement;
  3451. }
  3452. }
  3453. }
  3454. catch
  3455. {
  3456. XElement img = null;
  3457. byte[] bytes = new byte[Stream.Length];
  3458. Stream.Read(bytes, 0, bytes.Length);
  3459. // 设置当前流的位置为流的开始
  3460. Stream.Seek(0, SeekOrigin.Begin);
  3461. string url = System.Convert.ToBase64String(bytes);
  3462. img = new XElement(Xhtml.img,
  3463. new XAttribute(NoNamespace.src, "data:" + contentType + ";base64," + url),
  3464. new XAttribute(NoNamespace.alt, "wrong image"));
  3465. return img;
  3466. }
  3467. finally {
  3468. Stream.Close();
  3469. }
  3470. }
  3471. public static XElement ProcessWmf(Stream stream,string contentType, XElement element, string hyperlinkUri ,Func<ImageInfo, XElement> imageHandler)
  3472. {
  3473. XElement img = null;
  3474. string mathxml = "";
  3475. if (contentType.Equals("image/x-wmf"))
  3476. {
  3477. bool compatible = false;
  3478. bool replaceSymbolFont = false;
  3479. WMFConverter.Wmf.WmfParser parser = new WMFConverter.Wmf.WmfParser();
  3480. WMFConverter.Svg.SvgGdi gdi = new WMFConverter.Svg.SvgGdi(compatible);
  3481. gdi.ReplaceSymbolFont = replaceSymbolFont;
  3482. parser.Parse(stream, gdi);
  3483. mathxml = gdi.Document.InnerXml;
  3484. }
  3485. else if (contentType.Equals("image/x-emf"))
  3486. {
  3487. MemoryStream memoryStream = new MemoryStream();
  3488. //Metafile inFile = new Metafile(stream);
  3489. ////Metafile outFile = new Metafile(memoryStream, Graphics.FromHwnd(IntPtr.Zero).GetHdc(), EmfType.EmfOnly);
  3490. //inFile.Save(memoryStream, ImageFormat.Png);
  3491. //var ba = memoryStream.ToArray();
  3492. //mathxml = System.Convert.ToBase64String(ba);
  3493. //System.Drawing.Bitmap inFile = new System.Drawing.Bitmap(stream);
  3494. //Graphics graphics = Graphics.FromImage(inFile);
  3495. //graphics.Save();
  3496. //graphics.Dispose();
  3497. //inFile.Save(memoryStream, System.Drawing.Imaging.ImageFormat.Png);
  3498. //byte[] arr = new byte[memoryStream.Length];
  3499. //memoryStream.Position = 0;
  3500. //memoryStream.Read(arr, 0, (int)memoryStream.Length);
  3501. //memoryStream.Close();
  3502. //memoryStream.Dispose();
  3503. //mathxml = Convert.ToBase64String(arr);
  3504. mathxml = "EmfBase64ConvertError";
  3505. }
  3506. try
  3507. {
  3508. var imageInfo = new ImageInfo()
  3509. {
  3510. ContentType = contentType,
  3511. DrawingElement = element,
  3512. AltText = "",
  3513. Mathxml = mathxml
  3514. };
  3515. var style = (string)element.Elements(VML.shape).Attributes("style").FirstOrDefault();
  3516. img =imageHandler(imageInfo);
  3517. var tokens = style.Split(';');
  3518. var widthInPoints = WidthInPoints(tokens);
  3519. var heightInPoints = HeightInPoints(tokens);
  3520. //var imgElement2 = imageHandler(imageInfo);
  3521. if (widthInPoints != null && heightInPoints != null)
  3522. {
  3523. //imageInfo.ImgStyleAttribute = new XAttribute("style",
  3524. // string.Format(NumberFormatInfo.InvariantInfo,
  3525. // "width: {0}pt; height: {1}pt ; vertical-align: bottom;", widthInPoints, heightInPoints));
  3526. img.SetAttributeValue("style", string.Format(NumberFormatInfo.InvariantInfo,
  3527. "width: {0}pt; height: {1}pt ; vertical-align: bottom;", widthInPoints, heightInPoints));
  3528. }
  3529. else
  3530. {
  3531. //imageInfo.ImgStyleAttribute = new XAttribute("style",
  3532. // string.Format(NumberFormatInfo.InvariantInfo,
  3533. // "vertical-align: middle;"));
  3534. img.SetAttributeValue("style", string.Format(NumberFormatInfo.InvariantInfo,
  3535. "vertical-align: middle;"));
  3536. }
  3537. if (hyperlinkUri != null)
  3538. {
  3539. return new XElement(XhtmlNoNamespace.a,
  3540. new XAttribute(XhtmlNoNamespace.href, hyperlinkUri),
  3541. img);
  3542. }
  3543. return img;
  3544. }
  3545. catch (OutOfMemoryException)
  3546. {
  3547. // the Bitmap class can throw OutOfMemoryException, which means the bitmap is messed up, so punt.
  3548. return null;
  3549. }
  3550. catch (ArgumentException e)
  3551. {
  3552. throw new Exception(e.StackTrace);
  3553. }
  3554. }
  3555. private static XElement ProcessPictureOrObject(WordprocessingDocument wordDoc,
  3556. XElement element, Func<ImageInfo, XElement> imageHandler)
  3557. {
  3558. var imageRid = (string)element.Elements(VML.shape).Elements(VML.imagedata).Attributes(R.id).FirstOrDefault();
  3559. if (imageRid == null) return null;
  3560. var pp = wordDoc.MainDocumentPart.Parts.FirstOrDefault(pp2 => pp2.RelationshipId == imageRid);
  3561. Stream stream = null ;
  3562. try
  3563. {
  3564. if (pp == null) return null;
  3565. if (!pp.OpenXmlPart.ContentType.Equals("image/x-wmf") && !pp.OpenXmlPart.ContentType.Equals("image/x-emf"))
  3566. {
  3567. return ProcessObject(wordDoc, element, imageHandler);
  3568. }
  3569. string mathxml = "";
  3570. if (pp.OpenXmlPart.ContentType.Equals("image/x-wmf"))
  3571. {
  3572. stream= pp.OpenXmlPart.GetStream();
  3573. bool compatible = false;
  3574. bool replaceSymbolFont = false;
  3575. WMFConverter.Wmf.WmfParser parser = new WMFConverter.Wmf.WmfParser();
  3576. WMFConverter.Svg.SvgGdi gdi = new WMFConverter.Svg.SvgGdi(compatible);
  3577. gdi.ReplaceSymbolFont = replaceSymbolFont;
  3578. parser.Parse(stream, gdi);
  3579. mathxml = gdi.Document.InnerXml;
  3580. }
  3581. else if (pp.OpenXmlPart.ContentType.Equals("image/x-emf"))
  3582. {
  3583. ////var image= SixLabors.ImageSharp.Image.Load(pp.OpenXmlPart.GetStream());
  3584. ////image.Save(memoryStream, new SixLabors.ImageSharp.Formats.Png.PngEncoder());
  3585. //var stm= pp.OpenXmlPart.GetStream();
  3586. //var parser = new EMF2StringParser();
  3587. //parser.LineBreakCandidates = new[] { EmfPlusRecordType.EmfSelectObject, EmfPlusRecordType.EmfDeleteObject };
  3588. //parser.SpaceCandidates = new[] { EmfPlusRecordType.EmfIntersectClipRect };
  3589. //Metafile inFile = new Metafile(stm);
  3590. //parser.LoadMetaFile(inFile);
  3591. //parser.IsParseFailedLoggingEnabled = true;
  3592. //var expected = parser.GetCombinedStringFromLoadedMetaFile();
  3593. ////MemoryStream memoryStream = new MemoryStream();
  3594. ////byte[] bytes = new byte[stm.Length];
  3595. ////stm.Read(bytes, 0, bytes.Length);
  3596. ////stm.Seek(0, SeekOrigin.Begin);
  3597. ////
  3598. ////Metafile outFile = new Metafile(memoryStream, Graphics.FromHwnd(IntPtr.Zero).GetHdc(), EmfType.EmfOnly);
  3599. //// inFile.Save(memoryStream, ImageFormat.Png);
  3600. ////var ba = memoryStream.ToArray();
  3601. //application.EnablePartialTrustCode = true;
  3602. //mathxml = expected;
  3603. // MemoryStream memoryStream = new MemoryStream();
  3604. //Metafile inFile = new Metafile(pp.OpenXmlPart.GetStream());
  3605. ////Metafile outFile = new Metafile(memoryStream, Graphics.FromHwnd(IntPtr.Zero).GetHdc(), EmfType.EmfOnly);
  3606. //inFile.Save(memoryStream, ImageFormat.Png);
  3607. //var ba = memoryStream.ToArray();
  3608. //mathxml = System.Convert.ToBase64String(ba);
  3609. //System.Drawing.Bitmap inFile = new System.Drawing.Bitmap(pp.OpenXmlPart.GetStream());
  3610. //Graphics graphics = Graphics.FromImage(inFile);
  3611. //graphics.Save();
  3612. //graphics.Dispose();
  3613. //inFile.Save(memoryStream, System.Drawing.Imaging.ImageFormat.Png);
  3614. //byte[] arr = new byte[memoryStream.Length];
  3615. //memoryStream.Position = 0;
  3616. //memoryStream.Read(arr, 0, (int)memoryStream.Length);
  3617. //memoryStream.Close();
  3618. //memoryStream.Dispose();
  3619. // mathxml = Convert.ToBase64String(arr);
  3620. mathxml = "EmfBase64ConvertError";
  3621. }
  3622. string hyperlinkUri = null;
  3623. var contentType = pp.OpenXmlPart.ContentType;
  3624. if (!ImageContentTypes.Contains(contentType))
  3625. return null;
  3626. try
  3627. {
  3628. XElement img = null;
  3629. var imageInfo = new ImageInfo()
  3630. {
  3631. ContentType = contentType,
  3632. DrawingElement = element,
  3633. AltText = "",
  3634. Mathxml = mathxml,
  3635. };
  3636. var style = (string)element.Elements(VML.shape).Attributes("style").FirstOrDefault();
  3637. // if (style == null) {
  3638. // return imageHandler(imageInfo);
  3639. img = imageHandler(imageInfo);
  3640. // }
  3641. var tokens = style.Split(';');
  3642. var widthInPoints = WidthInPoints(tokens);
  3643. var heightInPoints = HeightInPoints(tokens);
  3644. // var imgElement2 = imageHandler(imageInfo);
  3645. if (widthInPoints != null && heightInPoints != null)
  3646. {
  3647. //imageInfo.ImgStyleAttribute = new XAttribute("style",
  3648. // string.Format(NumberFormatInfo.InvariantInfo,
  3649. // "width: {0}pt; height: {1}pt ; vertical-align: bottom;", widthInPoints, heightInPoints));
  3650. img.SetAttributeValue("style", string.Format(NumberFormatInfo.InvariantInfo,
  3651. "width: {0}pt; height: {1}pt ; vertical-align: bottom;", widthInPoints, heightInPoints));
  3652. }
  3653. else
  3654. {
  3655. //imageInfo.ImgStyleAttribute = new XAttribute("style",
  3656. // string.Format(NumberFormatInfo.InvariantInfo,
  3657. // "vertical-align: middle;"));
  3658. img.SetAttributeValue("style", string.Format(NumberFormatInfo.InvariantInfo,
  3659. "vertical-align: middle;"));
  3660. }
  3661. if (hyperlinkUri != null)
  3662. {
  3663. return new XElement(XhtmlNoNamespace.a,
  3664. new XAttribute(XhtmlNoNamespace.href, hyperlinkUri),
  3665. img);
  3666. }
  3667. return img;
  3668. }
  3669. catch (OutOfMemoryException)
  3670. {
  3671. // the Bitmap class can throw OutOfMemoryException, which means the bitmap is messed up, so punt.
  3672. return null;
  3673. }
  3674. catch (ArgumentException e)
  3675. {
  3676. throw new Exception(e.StackTrace);
  3677. }
  3678. }
  3679. catch (ArgumentOutOfRangeException)
  3680. {
  3681. return null;
  3682. }
  3683. finally {
  3684. if(stream!=null)
  3685. stream.Close();
  3686. }
  3687. }
  3688. private static XElement ProcessObject(WordprocessingDocument wordDoc,
  3689. XElement element, Func<ImageInfo, XElement> imageHandler)
  3690. {
  3691. var imageRid = (string)element.Elements(VML.shape).Elements(VML.imagedata).Attributes(R.id).FirstOrDefault();
  3692. if (imageRid == null) return null;
  3693. try
  3694. {
  3695. var pp = wordDoc.MainDocumentPart.Parts.FirstOrDefault(pp2 => pp2.RelationshipId == imageRid);
  3696. if (pp == null) return null;
  3697. var imagePart = (ImagePart)pp.OpenXmlPart;
  3698. if (imagePart == null) return null;
  3699. string hyperlinkUri = null;
  3700. // WORDHelper.GetWordNodeByPath(wordDoc.MainDocumentPart.GetXDocument(), "//[@name='"+imagePart.Uri+"']");
  3701. using (var partStream = imagePart.GetStream())
  3702. {
  3703. var contentType = imagePart.ContentType;
  3704. if (!ImageContentTypes.Contains(contentType))
  3705. return null;
  3706. try
  3707. {
  3708. using (var bitmap = new Bitmap(partStream))
  3709. {
  3710. var imageInfo = new ImageInfo()
  3711. {
  3712. Bitmap = bitmap,
  3713. ContentType = contentType,
  3714. DrawingElement = element,
  3715. AltText = ""
  3716. };
  3717. var style = (string)element.Elements(VML.shape).Attributes("style").FirstOrDefault();
  3718. if (style == null) return imageHandler(imageInfo);
  3719. var tokens = style.Split(';');
  3720. var widthInPoints = WidthInPoints(tokens);
  3721. var heightInPoints = HeightInPoints(tokens);
  3722. if (widthInPoints != null && heightInPoints != null)
  3723. {
  3724. imageInfo.ImgStyleAttribute = new XAttribute("style",
  3725. string.Format(NumberFormatInfo.InvariantInfo,
  3726. "width: {0}pt; height: {1}pt", widthInPoints, heightInPoints));
  3727. }
  3728. var imgElement2 = imageHandler(imageInfo);
  3729. if (hyperlinkUri != null)
  3730. {
  3731. return new XElement(XhtmlNoNamespace.a,
  3732. new XAttribute(XhtmlNoNamespace.href, hyperlinkUri),
  3733. imgElement2);
  3734. }
  3735. return imgElement2;
  3736. }
  3737. }
  3738. catch (OutOfMemoryException)
  3739. {
  3740. return null;
  3741. }
  3742. catch (ArgumentException e)
  3743. {
  3744. return null; //throw new Exception(e.StackTrace);
  3745. }
  3746. finally { partStream.Close(); }
  3747. }
  3748. }
  3749. catch (ArgumentOutOfRangeException)
  3750. {
  3751. return null;
  3752. }
  3753. }
  3754. private static float? HeightInPoints(IEnumerable<string> tokens)
  3755. {
  3756. return SizeInPoints(tokens, "height");
  3757. }
  3758. private static float? WidthInPoints(IEnumerable<string> tokens)
  3759. {
  3760. return SizeInPoints(tokens, "width");
  3761. }
  3762. private static float? SizeInPoints(IEnumerable<string> tokens, string name)
  3763. {
  3764. var sizeString = tokens
  3765. .Select(t => new
  3766. {
  3767. Name = t.Split(':').First(),
  3768. Value = t.Split(':').Skip(1).Take(1).FirstOrDefault()
  3769. })
  3770. .Where(p => p.Name == name)
  3771. .Select(p => p.Value)
  3772. .FirstOrDefault();
  3773. if (sizeString != null &&
  3774. sizeString.Length > 2 &&
  3775. sizeString.Substring(sizeString.Length - 2) == "pt")
  3776. {
  3777. float size;
  3778. if (float.TryParse(sizeString.Substring(0, sizeString.Length - 2), out size))
  3779. return size;
  3780. }
  3781. return null;
  3782. }
  3783. #endregion
  3784. }
  3785. public static class HtmlConverterExtensions
  3786. {
  3787. public static void AddIfMissing(this Dictionary<string, string> style, string propName, string value)
  3788. {
  3789. if (style.ContainsKey(propName))
  3790. return;
  3791. style.Add(propName, value);
  3792. }
  3793. }
  3794. }