You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

XWPFRun.java 56KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556
  1. /* ====================================================================
  2. Licensed to the Apache Software Foundation (ASF) under one or more
  3. contributor license agreements. See the NOTICE file distributed with
  4. this work for additional information regarding copyright ownership.
  5. The ASF licenses this file to You under the Apache License, Version 2.0
  6. (the "License"); you may not use this file except in compliance with
  7. the License. You may obtain a copy of the License at
  8. http://www.apache.org/licenses/LICENSE-2.0
  9. Unless required by applicable law or agreed to in writing, software
  10. distributed under the License is distributed on an "AS IS" BASIS,
  11. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. See the License for the specific language governing permissions and
  13. limitations under the License.
  14. ==================================================================== */
  15. package org.apache.poi.xwpf.usermodel;
  16. import static org.apache.poi.ooxml.POIXMLTypeLoader.DEFAULT_XML_OPTIONS;
  17. import java.io.IOException;
  18. import java.io.InputStream;
  19. import java.io.StringReader;
  20. import java.math.BigInteger;
  21. import java.util.ArrayList;
  22. import java.util.Arrays;
  23. import java.util.List;
  24. import javax.xml.namespace.QName;
  25. import org.apache.poi.ooxml.POIXMLException;
  26. import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
  27. import org.apache.poi.ooxml.util.DocumentHelper;
  28. import org.apache.poi.util.HexDump;
  29. import org.apache.poi.util.Internal;
  30. import org.apache.poi.util.Removal;
  31. import org.apache.poi.wp.usermodel.CharacterRun;
  32. import org.apache.xmlbeans.SimpleValue;
  33. import org.apache.xmlbeans.XmlCursor;
  34. import org.apache.xmlbeans.XmlException;
  35. import org.apache.xmlbeans.XmlObject;
  36. import org.apache.xmlbeans.XmlString;
  37. import org.apache.xmlbeans.XmlToken;
  38. import org.apache.xmlbeans.impl.values.XmlAnyTypeImpl;
  39. import org.openxmlformats.schemas.drawingml.x2006.chart.CTChart;
  40. import org.openxmlformats.schemas.drawingml.x2006.main.CTBlip;
  41. import org.openxmlformats.schemas.drawingml.x2006.main.CTBlipFillProperties;
  42. import org.openxmlformats.schemas.drawingml.x2006.main.CTGraphicalObject;
  43. import org.openxmlformats.schemas.drawingml.x2006.main.CTGraphicalObjectData;
  44. import org.openxmlformats.schemas.drawingml.x2006.main.CTNonVisualDrawingProps;
  45. import org.openxmlformats.schemas.drawingml.x2006.main.CTNonVisualPictureProperties;
  46. import org.openxmlformats.schemas.drawingml.x2006.main.CTPoint2D;
  47. import org.openxmlformats.schemas.drawingml.x2006.main.CTPositiveSize2D;
  48. import org.openxmlformats.schemas.drawingml.x2006.main.CTPresetGeometry2D;
  49. import org.openxmlformats.schemas.drawingml.x2006.main.CTShapeProperties;
  50. import org.openxmlformats.schemas.drawingml.x2006.main.CTTransform2D;
  51. import org.openxmlformats.schemas.drawingml.x2006.main.STShapeType;
  52. import org.openxmlformats.schemas.drawingml.x2006.picture.CTPicture;
  53. import org.openxmlformats.schemas.drawingml.x2006.picture.CTPictureNonVisual;
  54. import org.openxmlformats.schemas.drawingml.x2006.wordprocessingDrawing.CTAnchor;
  55. import org.openxmlformats.schemas.drawingml.x2006.wordprocessingDrawing.CTInline;
  56. import org.openxmlformats.schemas.wordprocessingml.x2006.main.*;
  57. import org.w3c.dom.NodeList;
  58. import org.w3c.dom.Text;
  59. import org.xml.sax.InputSource;
  60. import org.xml.sax.SAXException;
  61. /**
  62. * XWPFRun object defines a region of text with a common set of properties
  63. */
  64. public class XWPFRun implements ISDTContents, IRunElement, CharacterRun {
  65. private CTR run;
  66. private String pictureText;
  67. private IRunBody parent;
  68. private List<XWPFPicture> pictures;
  69. /**
  70. * @param r the CTR bean which holds the run attributes
  71. * @param p the parent paragraph
  72. */
  73. public XWPFRun(CTR r, IRunBody p) {
  74. this.run = r;
  75. this.parent = p;
  76. /*
  77. * reserve already occupied drawing ids, so reserving new ids later will
  78. * not corrupt the document
  79. */
  80. for (CTDrawing ctDrawing : r.getDrawingArray()) {
  81. for (CTAnchor anchor : ctDrawing.getAnchorArray()) {
  82. if (anchor.getDocPr() != null) {
  83. getDocument().getDrawingIdManager().reserve(anchor.getDocPr().getId());
  84. }
  85. }
  86. for (CTInline inline : ctDrawing.getInlineArray()) {
  87. if (inline.getDocPr() != null) {
  88. getDocument().getDrawingIdManager().reserve(inline.getDocPr().getId());
  89. }
  90. }
  91. }
  92. // Look for any text in any of our pictures or drawings
  93. StringBuilder text = new StringBuilder();
  94. List<XmlObject> pictTextObjs = new ArrayList<>();
  95. pictTextObjs.addAll(Arrays.asList(r.getPictArray()));
  96. pictTextObjs.addAll(Arrays.asList(r.getDrawingArray()));
  97. for (XmlObject o : pictTextObjs) {
  98. XmlObject[] ts = o.selectPath("declare namespace w='http://schemas.openxmlformats.org/wordprocessingml/2006/main' .//w:t");
  99. for (XmlObject t : ts) {
  100. NodeList kids = t.getDomNode().getChildNodes();
  101. for (int n = 0; n < kids.getLength(); n++) {
  102. if (kids.item(n) instanceof Text) {
  103. if (text.length() > 0) {
  104. text.append("\n");
  105. }
  106. text.append(kids.item(n).getNodeValue());
  107. }
  108. }
  109. }
  110. }
  111. pictureText = text.toString();
  112. // Do we have any embedded pictures?
  113. // (They're a different CTPicture, under the drawingml namespace)
  114. pictures = new ArrayList<>();
  115. for (XmlObject o : pictTextObjs) {
  116. for (CTPicture pict : getCTPictures(o)) {
  117. XWPFPicture picture = new XWPFPicture(pict, this);
  118. pictures.add(picture);
  119. }
  120. }
  121. }
  122. /**
  123. * @deprecated Use {@link XWPFRun#XWPFRun(CTR, IRunBody)}
  124. */
  125. @Deprecated
  126. public XWPFRun(CTR r, XWPFParagraph p) {
  127. this(r, (IRunBody) p);
  128. }
  129. /**
  130. * Add the xml:spaces="preserve" attribute if the string has leading or trailing white spaces
  131. *
  132. * @param xs the string to check
  133. */
  134. static void preserveSpaces(XmlString xs) {
  135. String text = xs.getStringValue();
  136. if (text != null && (text.startsWith(" ") || text.endsWith(" "))) {
  137. XmlCursor c = xs.newCursor();
  138. c.toNextToken();
  139. c.insertAttributeWithValue(new QName("http://www.w3.org/XML/1998/namespace", "space"), "preserve");
  140. c.dispose();
  141. }
  142. }
  143. private List<CTPicture> getCTPictures(XmlObject o) {
  144. List<CTPicture> pics = new ArrayList<>();
  145. XmlObject[] picts = o.selectPath("declare namespace pic='" + CTPicture.type.getName().getNamespaceURI() + "' .//pic:pic");
  146. for (XmlObject pict : picts) {
  147. if (pict instanceof XmlAnyTypeImpl) {
  148. // Pesky XmlBeans bug - see Bugzilla #49934
  149. try {
  150. pict = CTPicture.Factory.parse(pict.toString(), DEFAULT_XML_OPTIONS);
  151. } catch (XmlException e) {
  152. throw new POIXMLException(e);
  153. }
  154. }
  155. if (pict instanceof CTPicture) {
  156. pics.add((CTPicture) pict);
  157. }
  158. }
  159. return pics;
  160. }
  161. /**
  162. * Get the currently used CTR object
  163. *
  164. * @return ctr object
  165. */
  166. @Internal
  167. public CTR getCTR() {
  168. return run;
  169. }
  170. /**
  171. * Get the currently referenced paragraph/SDT object
  172. *
  173. * @return current parent
  174. */
  175. public IRunBody getParent() {
  176. return parent;
  177. }
  178. /**
  179. * Get the currently referenced paragraph, or null if a SDT object
  180. *
  181. * @deprecated use {@link XWPFRun#getParent()} instead
  182. */
  183. @Deprecated
  184. public XWPFParagraph getParagraph() {
  185. if (parent instanceof XWPFParagraph) {
  186. return (XWPFParagraph) parent;
  187. }
  188. return null;
  189. }
  190. /**
  191. * @return The {@link XWPFDocument} instance, this run belongs to, or
  192. * <code>null</code> if parent structure (paragraph > document) is not properly set.
  193. */
  194. public XWPFDocument getDocument() {
  195. if (parent != null) {
  196. return parent.getDocument();
  197. }
  198. return null;
  199. }
  200. /**
  201. * For isBold, isItalic etc
  202. */
  203. private static boolean isCTOnOff(CTOnOff onoff) {
  204. if (!onoff.isSetVal()) {
  205. return true;
  206. }
  207. final STOnOff.Enum val = onoff.getVal();
  208. return (
  209. (STOnOff.TRUE == val) ||
  210. (STOnOff.X_1 == val) ||
  211. (STOnOff.ON == val)
  212. );
  213. }
  214. /**
  215. * Get the language tag associated with this run, if any.
  216. *
  217. * @return the language tag associated with this run, if any
  218. */
  219. public String getLang() {
  220. CTRPr pr = getRunProperties(false);
  221. Object lang = pr == null || !pr.isSetLang() ? null : pr.getLang().getVal();
  222. return (String) lang;
  223. }
  224. /**
  225. * Whether the bold property shall be applied to all non-complex script
  226. * characters in the contents of this run when displayed in a document
  227. *
  228. * @return <code>true</code> if the bold property is applied
  229. */
  230. @Override
  231. public boolean isBold() {
  232. CTRPr pr = getRunProperties(false);
  233. return pr != null && pr.isSetB() && isCTOnOff(pr.getB());
  234. }
  235. /**
  236. * Whether the bold property shall be applied to all non-complex script
  237. * characters in the contents of this run when displayed in a document.
  238. * <p>
  239. * This formatting property is a toggle property, which specifies that its
  240. * behavior differs between its use within a style definition and its use as
  241. * direct formatting. When used as part of a style definition, setting this
  242. * property shall toggle the current state of that property as specified up
  243. * to this point in the hierarchy (i.e. applied to not applied, and vice
  244. * versa). Setting it to <code>false</code> (or an equivalent) shall
  245. * result in the current setting remaining unchanged. However, when used as
  246. * direct formatting, setting this property to true or false shall set the
  247. * absolute state of the resulting property.
  248. * </p>
  249. * <p>
  250. * If this element is not present, the default value is to leave the
  251. * formatting applied at previous level in the style hierarchy. If this
  252. * element is never applied in the style hierarchy, then bold shall not be
  253. * applied to non-complex script characters.
  254. * </p>
  255. *
  256. * @param value <code>true</code> if the bold property is applied to
  257. * this run
  258. */
  259. @Override
  260. public void setBold(boolean value) {
  261. CTRPr pr = getRunProperties(true);
  262. CTOnOff bold = pr.isSetB() ? pr.getB() : pr.addNewB();
  263. bold.setVal(value ? STOnOff.TRUE : STOnOff.FALSE);
  264. }
  265. /**
  266. * Get text color. The returned value is a string in the hex form "RRGGBB".
  267. */
  268. public String getColor() {
  269. String color = null;
  270. if (run.isSetRPr()) {
  271. CTRPr pr = getRunProperties(false);
  272. if (pr != null && pr.isSetColor()) {
  273. CTColor clr = pr.getColor();
  274. color = clr.xgetVal().getStringValue();
  275. }
  276. }
  277. return color;
  278. }
  279. /**
  280. * Set text color.
  281. *
  282. * @param rgbStr - the desired color, in the hex form "RRGGBB".
  283. */
  284. public void setColor(String rgbStr) {
  285. CTRPr pr = getRunProperties(true);
  286. CTColor color = pr.isSetColor() ? pr.getColor() : pr.addNewColor();
  287. color.setVal(rgbStr);
  288. }
  289. /**
  290. * Return the string content of this text run
  291. *
  292. * @return the text of this text run or <code>null</code> if not set
  293. */
  294. public String getText(int pos) {
  295. return run.sizeOfTArray() == 0 ? null : run.getTArray(pos)
  296. .getStringValue();
  297. }
  298. /**
  299. * Returns text embedded in pictures
  300. */
  301. public String getPictureText() {
  302. return pictureText;
  303. }
  304. /**
  305. * Sets the text of this text run
  306. *
  307. * @param value the literal text which shall be displayed in the document
  308. */
  309. public void setText(String value) {
  310. setText(value, run.sizeOfTArray());
  311. }
  312. /**
  313. * Sets the text of this text run in the
  314. *
  315. * @param value the literal text which shall be displayed in the document
  316. * @param pos - position in the text array (NB: 0 based)
  317. */
  318. public void setText(String value, int pos) {
  319. if (pos > run.sizeOfTArray()) {
  320. throw new ArrayIndexOutOfBoundsException("Value too large for the parameter position in XWPFRun.setText(String value,int pos)");
  321. }
  322. CTText t = (pos < run.sizeOfTArray() && pos >= 0) ? run.getTArray(pos) : run.addNewT();
  323. t.setStringValue(value);
  324. preserveSpaces(t);
  325. }
  326. /**
  327. * Whether the italic property should be applied to all non-complex script
  328. * characters in the contents of this run when displayed in a document.
  329. *
  330. * @return <code>true</code> if the italic property is applied
  331. */
  332. @Override
  333. public boolean isItalic() {
  334. CTRPr pr = getRunProperties(false);
  335. return pr != null && pr.isSetI() && isCTOnOff(pr.getI());
  336. }
  337. /**
  338. * Whether the bold property shall be applied to all non-complex script
  339. * characters in the contents of this run when displayed in a document
  340. * <p>
  341. * <p>
  342. * This formatting property is a toggle property, which specifies that its
  343. * behavior differs between its use within a style definition and its use as
  344. * direct formatting. When used as part of a style definition, setting this
  345. * property shall toggle the current state of that property as specified up
  346. * to this point in the hierarchy (i.e. applied to not applied, and vice
  347. * versa). Setting it to <code>false</code> (or an equivalent) shall
  348. * result in the current setting remaining unchanged. However, when used as
  349. * direct formatting, setting this property to true or false shall set the
  350. * absolute state of the resulting property.
  351. * </p>
  352. * <p>
  353. * If this element is not present, the default value is to leave the
  354. * formatting applied at previous level in the style hierarchy. If this
  355. * element is never applied in the style hierarchy, then bold shall not be
  356. * applied to non-complex script characters.
  357. * </p>
  358. *
  359. * @param value <code>true</code> if the italic property is applied to
  360. * this run
  361. */
  362. @Override
  363. public void setItalic(boolean value) {
  364. CTRPr pr = getRunProperties(true);
  365. CTOnOff italic = pr.isSetI() ? pr.getI() : pr.addNewI();
  366. italic.setVal(value ? STOnOff.TRUE : STOnOff.FALSE);
  367. }
  368. /**
  369. * Get the underline setting for the run.
  370. *
  371. * @return the Underline pattern applied to this run
  372. * @see (@link UnderlinePatterns}
  373. */
  374. public UnderlinePatterns getUnderline() {
  375. UnderlinePatterns value = UnderlinePatterns.NONE;
  376. CTUnderline underline = getCTUnderline(false);
  377. if (underline != null) {
  378. STUnderline.Enum baseValue = underline.getVal();
  379. if (baseValue != null) {
  380. value = UnderlinePatterns.valueOf(baseValue.intValue());
  381. }
  382. }
  383. return value;
  384. }
  385. /**
  386. * Specifies that the contents of this run should be displayed along with an
  387. * underline appearing directly below the character height.
  388. * <p>
  389. * If this element is not present, the default value is to leave the
  390. * formatting applied at previous level in the style hierarchy. If this
  391. * element is never applied in the style hierarchy, then an underline shall
  392. * not be applied to the contents of this run.
  393. * </p>
  394. *
  395. * @param value -
  396. * underline type
  397. * @see {@link UnderlinePatterns} : all possible patterns that could be applied
  398. */
  399. public void setUnderline(UnderlinePatterns value) {
  400. CTUnderline underline = getCTUnderline(true);
  401. underline.setVal(STUnderline.Enum.forInt(value.getValue()));
  402. }
  403. /**
  404. * Get the CTUnderline for the run.
  405. * @param create Create a new underline if necessary
  406. * @return The underline, or null create is false and there is no underline.
  407. */
  408. private CTUnderline getCTUnderline(boolean create) {
  409. CTRPr pr = getRunProperties(true);
  410. CTUnderline underline = pr.getU();
  411. if (create && underline == null) {
  412. underline = pr.addNewU();
  413. }
  414. return underline;
  415. }
  416. /**
  417. * Set the underline color for the run's underline, if any.
  418. *
  419. * @param color An RGB color value (e.g, "a0C6F3") or "auto".
  420. * @since 4.0.0
  421. */
  422. public void setUnderlineColor(String color) {
  423. CTUnderline underline = getCTUnderline(true);
  424. SimpleValue svColor = null;
  425. if (color.equals("auto")) {
  426. STHexColorAuto hexColor = STHexColorAuto.Factory.newInstance();
  427. hexColor.set(STHexColorAuto.Enum.forString(color));
  428. svColor = (SimpleValue) hexColor;
  429. } else {
  430. STHexColorRGB rgbColor = STHexColorRGB.Factory.newInstance();
  431. rgbColor.setStringValue(color);
  432. svColor = (SimpleValue) rgbColor;
  433. }
  434. underline.setColor(svColor);
  435. }
  436. /**
  437. * Set the underline theme color for the run's underline, if any.
  438. *
  439. * @param themeColor A theme color name (see {@link STThemeColor.Enum}).
  440. * @since 4.0.0
  441. */
  442. public void setUnderlineThemeColor(String themeColor) {
  443. CTUnderline underline = getCTUnderline(true);
  444. STThemeColor.Enum val = STThemeColor.Enum.forString(themeColor);
  445. if (val != null) {
  446. underline.setThemeColor(val);
  447. }
  448. }
  449. /**
  450. * Get the underline theme color for the run's underline, if any.
  451. *
  452. * @return The {@link STThemeColor.Enum}.
  453. * @since 4.0.0
  454. */
  455. public STThemeColor.Enum getUnderlineThemeColor() {
  456. CTUnderline underline = getCTUnderline(false);
  457. STThemeColor.Enum color = STThemeColor.NONE;
  458. if (underline != null) {
  459. color = underline.getThemeColor();
  460. }
  461. return color;
  462. }
  463. /**
  464. * Get the underline color for the run's underline, if any.
  465. *
  466. * @return The RGB color value as as a string of hexadecimal digits (e.g., "A0B2F1") or "auto".
  467. * @since 4.0.0
  468. */
  469. public String getUnderlineColor() {
  470. CTUnderline underline = getCTUnderline(true);
  471. String colorName = "auto";
  472. Object rawValue = underline.getColor();
  473. if (rawValue != null) {
  474. if (rawValue instanceof String) {
  475. colorName = (String)rawValue;
  476. } else {
  477. byte[] rgbColor = (byte[])rawValue;
  478. colorName = HexDump.toHex(rgbColor[0]) + HexDump.toHex(rgbColor[1]) + HexDump.toHex(rgbColor[2]);
  479. }
  480. }
  481. return colorName;
  482. }
  483. /**
  484. * Specifies that the contents of this run shall be displayed with a single
  485. * horizontal line through the center of the line.
  486. *
  487. * @return <code>true</code> if the strike property is applied
  488. */
  489. @Override
  490. public boolean isStrikeThrough() {
  491. CTRPr pr = getRunProperties(false);
  492. return pr != null && pr.isSetStrike() && isCTOnOff(pr.getStrike());
  493. }
  494. /**
  495. * Specifies that the contents of this run shall be displayed with a single
  496. * horizontal line through the center of the line.
  497. * <p>
  498. * This formatting property is a toggle property, which specifies that its
  499. * behaviour differs between its use within a style definition and its use as
  500. * direct formatting. When used as part of a style definition, setting this
  501. * property shall toggle the current state of that property as specified up
  502. * to this point in the hierarchy (i.e. applied to not applied, and vice
  503. * versa). Setting it to false (or an equivalent) shall result in the
  504. * current setting remaining unchanged. However, when used as direct
  505. * formatting, setting this property to true or false shall set the absolute
  506. * state of the resulting property.
  507. * </p>
  508. * <p>
  509. * If this element is not present, the default value is to leave the
  510. * formatting applied at previous level in the style hierarchy. If this
  511. * element is never applied in the style hierarchy, then strikethrough shall
  512. * not be applied to the contents of this run.
  513. * </p>
  514. *
  515. * @param value <code>true</code> if the strike property is applied to
  516. * this run
  517. */
  518. @Override
  519. public void setStrikeThrough(boolean value) {
  520. CTRPr pr = getRunProperties(true);
  521. CTOnOff strike = pr.isSetStrike() ? pr.getStrike() : pr.addNewStrike();
  522. strike.setVal(value ? STOnOff.TRUE : STOnOff.FALSE);
  523. }
  524. @Deprecated
  525. public boolean isStrike() {
  526. return isStrikeThrough();
  527. }
  528. @Deprecated
  529. public void setStrike(boolean value) {
  530. setStrikeThrough(value);
  531. }
  532. /**
  533. * Specifies that the contents of this run shall be displayed with a double
  534. * horizontal line through the center of the line.
  535. *
  536. * @return <code>true</code> if the double strike property is applied
  537. */
  538. @Override
  539. public boolean isDoubleStrikeThrough() {
  540. CTRPr pr = getRunProperties(false);
  541. return pr != null && pr.isSetDstrike() && isCTOnOff(pr.getDstrike());
  542. }
  543. /**
  544. * Specifies that the contents of this run shall be displayed with a
  545. * double horizontal line through the center of the line.
  546. *
  547. * @see #setStrikeThrough(boolean) for the rules about this
  548. */
  549. @Override
  550. public void setDoubleStrikethrough(boolean value) {
  551. CTRPr pr = getRunProperties(true);
  552. CTOnOff dstrike = pr.isSetDstrike() ? pr.getDstrike() : pr.addNewDstrike();
  553. dstrike.setVal(value ? STOnOff.TRUE : STOnOff.FALSE);
  554. }
  555. @Override
  556. public boolean isSmallCaps() {
  557. CTRPr pr = getRunProperties(false);
  558. return pr != null && pr.isSetSmallCaps() && isCTOnOff(pr.getSmallCaps());
  559. }
  560. @Override
  561. public void setSmallCaps(boolean value) {
  562. CTRPr pr = getRunProperties(true);
  563. CTOnOff caps = pr.isSetSmallCaps() ? pr.getSmallCaps() : pr.addNewSmallCaps();
  564. caps.setVal(value ? STOnOff.TRUE : STOnOff.FALSE);
  565. }
  566. @Override
  567. public boolean isCapitalized() {
  568. CTRPr pr = getRunProperties(false);
  569. return pr != null && pr.isSetCaps() && isCTOnOff(pr.getCaps());
  570. }
  571. @Override
  572. public void setCapitalized(boolean value) {
  573. CTRPr pr = getRunProperties(true);
  574. CTOnOff caps = pr.isSetCaps() ? pr.getCaps() : pr.addNewCaps();
  575. caps.setVal(value ? STOnOff.TRUE : STOnOff.FALSE);
  576. }
  577. @Override
  578. public boolean isShadowed() {
  579. CTRPr pr = getRunProperties(false);
  580. return pr != null && pr.isSetShadow() && isCTOnOff(pr.getShadow());
  581. }
  582. @Override
  583. public void setShadow(boolean value) {
  584. CTRPr pr = getRunProperties(true);
  585. CTOnOff shadow = pr.isSetShadow() ? pr.getShadow() : pr.addNewShadow();
  586. shadow.setVal(value ? STOnOff.TRUE : STOnOff.FALSE);
  587. }
  588. @Override
  589. public boolean isImprinted() {
  590. CTRPr pr = getRunProperties(false);
  591. return pr != null && pr.isSetImprint() && isCTOnOff(pr.getImprint());
  592. }
  593. @Override
  594. public void setImprinted(boolean value) {
  595. CTRPr pr = getRunProperties(true);
  596. CTOnOff imprinted = pr.isSetImprint() ? pr.getImprint() : pr.addNewImprint();
  597. imprinted.setVal(value ? STOnOff.TRUE : STOnOff.FALSE);
  598. }
  599. @Override
  600. public boolean isEmbossed() {
  601. CTRPr pr = getRunProperties(false);
  602. return pr != null && pr.isSetEmboss() && isCTOnOff(pr.getEmboss());
  603. }
  604. @Override
  605. public void setEmbossed(boolean value) {
  606. CTRPr pr = getRunProperties(true);
  607. CTOnOff emboss = pr.isSetEmboss() ? pr.getEmboss() : pr.addNewEmboss();
  608. emboss.setVal(value ? STOnOff.TRUE : STOnOff.FALSE);
  609. }
  610. /**
  611. * Specifies the alignment which shall be applied to the contents of this
  612. * run in relation to the default appearance of the run's text.
  613. * This allows the text to be repositioned as subscript or superscript without
  614. * altering the font size of the run properties.
  615. *
  616. * @return VerticalAlign
  617. * @see {@link VerticalAlign} all possible value that could be applyed to this run
  618. * @deprecated use {@link XWPFRun.getVerticalAlignment}
  619. */
  620. @Removal(version = "4.2")
  621. public VerticalAlign getSubscript() {
  622. CTRPr pr = getRunProperties(false);
  623. return (pr != null && pr.isSetVertAlign()) ? VerticalAlign.valueOf(pr.getVertAlign().getVal().intValue()) : VerticalAlign.BASELINE;
  624. }
  625. /**
  626. * Specifies the alignment which shall be applied to the contents of this
  627. * run in relation to the default appearance of the run's text. This allows
  628. * the text to be repositioned as subscript or superscript without altering
  629. * the font size of the run properties.
  630. * <p>
  631. * If this element is not present, the default value is to leave the
  632. * formatting applied at previous level in the style hierarchy. If this
  633. * element is never applied in the style hierarchy, then the text shall not
  634. * be subscript or superscript relative to the default baseline location for
  635. * the contents of this run.
  636. * </p>
  637. *
  638. * @param valign Type of vertical align to apply
  639. * @see VerticalAlign
  640. */
  641. public void setSubscript(VerticalAlign valign) {
  642. CTRPr pr = getRunProperties(true);
  643. CTVerticalAlignRun ctValign = pr.isSetVertAlign() ? pr.getVertAlign() : pr.addNewVertAlign();
  644. ctValign.setVal(STVerticalAlignRun.Enum.forInt(valign.getValue()));
  645. }
  646. @Override
  647. public int getKerning() {
  648. CTRPr pr = getRunProperties(false);
  649. if (pr == null || !pr.isSetKern()) {
  650. return 0;
  651. }
  652. return pr.getKern().getVal().intValue();
  653. }
  654. @Override
  655. public void setKerning(int kern) {
  656. CTRPr pr = getRunProperties(true);
  657. CTHpsMeasure kernmes = pr.isSetKern() ? pr.getKern() : pr.addNewKern();
  658. kernmes.setVal(BigInteger.valueOf(kern));
  659. }
  660. @Override
  661. public boolean isHighlighted() {
  662. CTRPr pr = getRunProperties(false);
  663. if (pr == null || !pr.isSetHighlight()) {
  664. return false;
  665. }
  666. STHighlightColor.Enum val = pr.getHighlight().getVal();
  667. if (val == null || val == STHighlightColor.NONE) {
  668. return false;
  669. }
  670. return true;
  671. }
  672. // TODO Provide a wrapper round STHighlightColor, then expose getter/setter
  673. // for the highlight colour. Ideally also then add to CharacterRun interface
  674. @Override
  675. public int getCharacterSpacing() {
  676. CTRPr pr = getRunProperties(false);
  677. if (pr == null || !pr.isSetSpacing()) {
  678. return 0;
  679. }
  680. return pr.getSpacing().getVal().intValue();
  681. }
  682. @Override
  683. public void setCharacterSpacing(int twips) {
  684. CTRPr pr = getRunProperties(true);
  685. CTSignedTwipsMeasure spc = pr.isSetSpacing() ? pr.getSpacing() : pr.addNewSpacing();
  686. spc.setVal(BigInteger.valueOf(twips));
  687. }
  688. /**
  689. * Gets the fonts which shall be used to display the text contents of
  690. * this run. Specifies a font which shall be used to format all characters
  691. * in the ASCII range (0 - 127) within the parent run
  692. *
  693. * @return a string representing the font family
  694. */
  695. public String getFontFamily() {
  696. return getFontFamily(null);
  697. }
  698. /**
  699. * Specifies the fonts which shall be used to display the text contents of
  700. * this run. Specifies a font which shall be used to format all characters
  701. * in the ASCII range (0 - 127) within the parent run.
  702. * <p>
  703. * Also sets the other font ranges, if they haven't been set before
  704. *
  705. * @param fontFamily The font family to apply
  706. * @see FontCharRange
  707. */
  708. public void setFontFamily(String fontFamily) {
  709. setFontFamily(fontFamily, null);
  710. }
  711. /**
  712. * Alias for {@link #getFontFamily()}
  713. */
  714. @Override
  715. public String getFontName() {
  716. return getFontFamily();
  717. }
  718. /**
  719. * Gets the font family for the specified font char range.
  720. * If fcr is null, the font char range "ascii" is used
  721. *
  722. * @param fcr the font char range, defaults to "ansi"
  723. * @return a string representing the font famil
  724. */
  725. public String getFontFamily(FontCharRange fcr) {
  726. CTRPr pr = getRunProperties(false);
  727. if (pr == null || !pr.isSetRFonts()) {
  728. return null;
  729. }
  730. CTFonts fonts = pr.getRFonts();
  731. switch (fcr == null ? FontCharRange.ascii : fcr) {
  732. default:
  733. case ascii:
  734. return fonts.getAscii();
  735. case cs:
  736. return fonts.getCs();
  737. case eastAsia:
  738. return fonts.getEastAsia();
  739. case hAnsi:
  740. return fonts.getHAnsi();
  741. }
  742. }
  743. /**
  744. * Specifies the fonts which shall be used to display the text contents of
  745. * this run. The default handling for fcr == null is to overwrite the
  746. * ascii font char range with the given font family and also set all not
  747. * specified font ranges
  748. *
  749. * @param fontFamily The font family to apply
  750. * @param fcr FontCharRange or null for default handling
  751. */
  752. public void setFontFamily(String fontFamily, FontCharRange fcr) {
  753. CTRPr pr = getRunProperties(true);
  754. CTFonts fonts = pr.isSetRFonts() ? pr.getRFonts() : pr.addNewRFonts();
  755. if (fcr == null) {
  756. fonts.setAscii(fontFamily);
  757. if (!fonts.isSetHAnsi()) {
  758. fonts.setHAnsi(fontFamily);
  759. }
  760. if (!fonts.isSetCs()) {
  761. fonts.setCs(fontFamily);
  762. }
  763. if (!fonts.isSetEastAsia()) {
  764. fonts.setEastAsia(fontFamily);
  765. }
  766. } else {
  767. switch (fcr) {
  768. case ascii:
  769. fonts.setAscii(fontFamily);
  770. break;
  771. case cs:
  772. fonts.setCs(fontFamily);
  773. break;
  774. case eastAsia:
  775. fonts.setEastAsia(fontFamily);
  776. break;
  777. case hAnsi:
  778. fonts.setHAnsi(fontFamily);
  779. break;
  780. }
  781. }
  782. }
  783. /**
  784. * Specifies the font size which shall be applied to all non complex script
  785. * characters in the contents of this run when displayed.
  786. *
  787. * @return value representing the font size
  788. */
  789. @Override
  790. public int getFontSize() {
  791. CTRPr pr = getRunProperties(false);
  792. return (pr != null && pr.isSetSz()) ? pr.getSz().getVal().divide(new BigInteger("2")).intValue() : -1;
  793. }
  794. /**
  795. * Specifies the font size which shall be applied to all non complex script
  796. * characters in the contents of this run when displayed.
  797. * <p>
  798. * If this element is not present, the default value is to leave the value
  799. * applied at previous level in the style hierarchy. If this element is
  800. * never applied in the style hierarchy, then any appropriate font size may
  801. * be used for non complex script characters.
  802. * </p>
  803. *
  804. * @param size The font size as number of point measurements.
  805. */
  806. @Override
  807. public void setFontSize(int size) {
  808. BigInteger bint = new BigInteger(Integer.toString(size));
  809. CTRPr pr = getRunProperties(true);
  810. CTHpsMeasure ctSize = pr.isSetSz() ? pr.getSz() : pr.addNewSz();
  811. ctSize.setVal(bint.multiply(new BigInteger("2")));
  812. }
  813. /**
  814. * This element specifies the amount by which text shall be raised or
  815. * lowered for this run in relation to the default baseline of the
  816. * surrounding non-positioned text. This allows the text to be repositioned
  817. * without altering the font size of the contents.
  818. *
  819. * @return a big integer representing the amount of text shall be "moved"
  820. */
  821. public int getTextPosition() {
  822. CTRPr pr = getRunProperties(false);
  823. return (pr != null && pr.isSetPosition()) ? pr.getPosition().getVal().intValue()
  824. : -1;
  825. }
  826. /**
  827. * This element specifies the amount by which text shall be raised or
  828. * lowered for this run in relation to the default baseline of the
  829. * surrounding non-positioned text. This allows the text to be repositioned
  830. * without altering the font size of the contents.
  831. * <p>
  832. * If the val attribute is positive, then the parent run shall be raised
  833. * above the baseline of the surrounding text by the specified number of
  834. * half-points. If the val attribute is negative, then the parent run shall
  835. * be lowered below the baseline of the surrounding text by the specified
  836. * number of half-points.
  837. * </p>
  838. * <p>
  839. * If this element is not present, the default value is to leave the
  840. * formatting applied at previous level in the style hierarchy. If this
  841. * element is never applied in the style hierarchy, then the text shall not
  842. * be raised or lowered relative to the default baseline location for the
  843. * contents of this run.
  844. * </p>
  845. *
  846. * @param val Positive values will raise the baseline of the text, negative
  847. * values will lower it.
  848. */
  849. public void setTextPosition(int val) {
  850. BigInteger bint = new BigInteger(Integer.toString(val));
  851. CTRPr pr = getRunProperties(true);
  852. CTSignedHpsMeasure position = pr.isSetPosition() ? pr.getPosition() : pr.addNewPosition();
  853. position.setVal(bint);
  854. }
  855. /**
  856. *
  857. */
  858. public void removeBreak() {
  859. // TODO
  860. }
  861. /**
  862. * Specifies that a break shall be placed at the current location in the run
  863. * content.
  864. * A break is a special character which is used to override the
  865. * normal line breaking that would be performed based on the normal layout
  866. * of the document's contents.
  867. *
  868. * @see #addCarriageReturn()
  869. */
  870. public void addBreak() {
  871. run.addNewBr();
  872. }
  873. /**
  874. * Specifies that a break shall be placed at the current location in the run
  875. * content.
  876. * A break is a special character which is used to override the
  877. * normal line breaking that would be performed based on the normal layout
  878. * of the document's contents.
  879. * <p>
  880. * The behavior of this break character (the
  881. * location where text shall be restarted after this break) shall be
  882. * determined by its type values.
  883. * </p>
  884. *
  885. * @see BreakType
  886. */
  887. public void addBreak(BreakType type) {
  888. CTBr br = run.addNewBr();
  889. br.setType(STBrType.Enum.forInt(type.getValue()));
  890. }
  891. /**
  892. * Specifies that a break shall be placed at the current location in the run
  893. * content. A break is a special character which is used to override the
  894. * normal line breaking that would be performed based on the normal layout
  895. * of the document's contents.
  896. * <p>
  897. * The behavior of this break character (the
  898. * location where text shall be restarted after this break) shall be
  899. * determined by its type (in this case is BreakType.TEXT_WRAPPING as default) and clear attribute values.
  900. * </p>
  901. *
  902. * @see BreakClear
  903. */
  904. public void addBreak(BreakClear clear) {
  905. CTBr br = run.addNewBr();
  906. br.setType(STBrType.Enum.forInt(BreakType.TEXT_WRAPPING.getValue()));
  907. br.setClear(STBrClear.Enum.forInt(clear.getValue()));
  908. }
  909. /**
  910. * Specifies that a tab shall be placed at the current location in
  911. * the run content.
  912. */
  913. public void addTab() {
  914. run.addNewTab();
  915. }
  916. public void removeTab() {
  917. //TODO
  918. }
  919. /**
  920. * Specifies that a carriage return shall be placed at the
  921. * current location in the run content.
  922. * A carriage return is used to end the current line of text in
  923. * Wordprocess.
  924. * The behavior of a carriage return in run content shall be
  925. * identical to a break character with null type and clear attributes, which
  926. * shall end the current line and find the next available line on which to
  927. * continue.
  928. * The carriage return character forced the following text to be
  929. * restarted on the next available line in the document.
  930. */
  931. public void addCarriageReturn() {
  932. run.addNewCr();
  933. }
  934. public void removeCarriageReturn() {
  935. //TODO
  936. }
  937. /**
  938. * Adds a picture to the run. This method handles
  939. * attaching the picture data to the overall file.
  940. *
  941. * @param pictureData The raw picture data
  942. * @param pictureType The type of the picture, eg {@link Document#PICTURE_TYPE_JPEG}
  943. * @param width width in EMUs. To convert to / from points use {@link org.apache.poi.util.Units}
  944. * @param height height in EMUs. To convert to / from points use {@link org.apache.poi.util.Units}
  945. * @throws InvalidFormatException If the format of the picture is not known.
  946. * @throws IOException If reading the picture-data from the stream fails.
  947. * @see org.apache.poi.xwpf.usermodel.Document#PICTURE_TYPE_EMF
  948. * @see org.apache.poi.xwpf.usermodel.Document#PICTURE_TYPE_WMF
  949. * @see org.apache.poi.xwpf.usermodel.Document#PICTURE_TYPE_PICT
  950. * @see org.apache.poi.xwpf.usermodel.Document#PICTURE_TYPE_JPEG
  951. * @see org.apache.poi.xwpf.usermodel.Document#PICTURE_TYPE_PNG
  952. * @see org.apache.poi.xwpf.usermodel.Document#PICTURE_TYPE_DIB
  953. */
  954. public XWPFPicture addPicture(InputStream pictureData, int pictureType, String filename, int width, int height)
  955. throws InvalidFormatException, IOException {
  956. String relationId;
  957. XWPFPictureData picData;
  958. // Work out what to add the picture to, then add both the
  959. // picture and the relationship for it
  960. // TODO Should we have an interface for this sort of thing?
  961. if (parent.getPart() instanceof XWPFHeaderFooter) {
  962. XWPFHeaderFooter headerFooter = (XWPFHeaderFooter) parent.getPart();
  963. relationId = headerFooter.addPictureData(pictureData, pictureType);
  964. picData = (XWPFPictureData) headerFooter.getRelationById(relationId);
  965. } else {
  966. @SuppressWarnings("resource")
  967. XWPFDocument doc = parent.getDocument();
  968. relationId = doc.addPictureData(pictureData, pictureType);
  969. picData = (XWPFPictureData) doc.getRelationById(relationId);
  970. }
  971. // Create the drawing entry for it
  972. try {
  973. CTDrawing drawing = run.addNewDrawing();
  974. CTInline inline = drawing.addNewInline();
  975. // Do the fiddly namespace bits on the inline
  976. // (We need full control of what goes where and as what)
  977. String xml =
  978. "<a:graphic xmlns:a=\"" + CTGraphicalObject.type.getName().getNamespaceURI() + "\">" +
  979. "<a:graphicData uri=\"" + CTPicture.type.getName().getNamespaceURI() + "\">" +
  980. "<pic:pic xmlns:pic=\"" + CTPicture.type.getName().getNamespaceURI() + "\" />" +
  981. "</a:graphicData>" +
  982. "</a:graphic>";
  983. InputSource is = new InputSource(new StringReader(xml));
  984. org.w3c.dom.Document doc = DocumentHelper.readDocument(is);
  985. inline.set(XmlToken.Factory.parse(doc.getDocumentElement(), DEFAULT_XML_OPTIONS));
  986. // Setup the inline
  987. inline.setDistT(0);
  988. inline.setDistR(0);
  989. inline.setDistB(0);
  990. inline.setDistL(0);
  991. CTNonVisualDrawingProps docPr = inline.addNewDocPr();
  992. long id = getParent().getDocument().getDrawingIdManager().reserveNew();
  993. docPr.setId(id);
  994. /* This name is not visible in Word 2010 anywhere. */
  995. docPr.setName("Drawing " + id);
  996. docPr.setDescr(filename);
  997. CTPositiveSize2D extent = inline.addNewExtent();
  998. extent.setCx(width);
  999. extent.setCy(height);
  1000. // Grab the picture object
  1001. CTGraphicalObject graphic = inline.getGraphic();
  1002. CTGraphicalObjectData graphicData = graphic.getGraphicData();
  1003. CTPicture pic = getCTPictures(graphicData).get(0);
  1004. // Set it up
  1005. CTPictureNonVisual nvPicPr = pic.addNewNvPicPr();
  1006. CTNonVisualDrawingProps cNvPr = nvPicPr.addNewCNvPr();
  1007. /* use "0" for the id. See ECM-576, 20.2.2.3 */
  1008. cNvPr.setId(0L);
  1009. /* This name is not visible in Word 2010 anywhere */
  1010. cNvPr.setName("Picture " + id);
  1011. cNvPr.setDescr(filename);
  1012. CTNonVisualPictureProperties cNvPicPr = nvPicPr.addNewCNvPicPr();
  1013. cNvPicPr.addNewPicLocks().setNoChangeAspect(true);
  1014. CTBlipFillProperties blipFill = pic.addNewBlipFill();
  1015. CTBlip blip = blipFill.addNewBlip();
  1016. blip.setEmbed(parent.getPart().getRelationId(picData));
  1017. blipFill.addNewStretch().addNewFillRect();
  1018. CTShapeProperties spPr = pic.addNewSpPr();
  1019. CTTransform2D xfrm = spPr.addNewXfrm();
  1020. CTPoint2D off = xfrm.addNewOff();
  1021. off.setX(0);
  1022. off.setY(0);
  1023. CTPositiveSize2D ext = xfrm.addNewExt();
  1024. ext.setCx(width);
  1025. ext.setCy(height);
  1026. CTPresetGeometry2D prstGeom = spPr.addNewPrstGeom();
  1027. prstGeom.setPrst(STShapeType.RECT);
  1028. prstGeom.addNewAvLst();
  1029. // Finish up
  1030. XWPFPicture xwpfPicture = new XWPFPicture(pic, this);
  1031. pictures.add(xwpfPicture);
  1032. return xwpfPicture;
  1033. } catch (XmlException | SAXException e) {
  1034. throw new IllegalStateException(e);
  1035. }
  1036. }
  1037. /**
  1038. * this method add chart template into document
  1039. *
  1040. * @param chartRelId relation id of chart in document relation file
  1041. * @throws InvalidFormatException
  1042. * @throws IOException
  1043. * @since POI 4.0.0
  1044. */
  1045. @Internal
  1046. public CTInline addChart(String chartRelId)
  1047. throws InvalidFormatException, IOException {
  1048. try {
  1049. CTInline inline = run.addNewDrawing().addNewInline();
  1050. //xml part of chart in document
  1051. String xml =
  1052. "<a:graphic xmlns:a=\"" + CTGraphicalObject.type.getName().getNamespaceURI() + "\">" +
  1053. "<a:graphicData uri=\"" + CTChart.type.getName().getNamespaceURI() + "\">" +
  1054. "<c:chart xmlns:c=\"" + CTChart.type.getName().getNamespaceURI() + "\" xmlns:r=\"http://schemas.openxmlformats.org/officeDocument/2006/relationships\" r:id=\"" + chartRelId + "\" />" +
  1055. "</a:graphicData>" +
  1056. "</a:graphic>";
  1057. InputSource is = new InputSource(new StringReader(xml));
  1058. org.w3c.dom.Document doc = DocumentHelper.readDocument(is);
  1059. inline.set(XmlToken.Factory.parse(doc.getDocumentElement(), DEFAULT_XML_OPTIONS));
  1060. // Setup the inline with 0 margin
  1061. inline.setDistT(0);
  1062. inline.setDistR(0);
  1063. inline.setDistB(0);
  1064. inline.setDistL(0);
  1065. CTNonVisualDrawingProps docPr = inline.addNewDocPr();
  1066. long id = getParent().getDocument().getDrawingIdManager().reserveNew();
  1067. docPr.setId(id);
  1068. //This name is not visible in Word anywhere.
  1069. docPr.setName("chart " + id);
  1070. return inline;
  1071. } catch (XmlException e) {
  1072. throw new IllegalStateException(e);
  1073. } catch (SAXException e) {
  1074. throw new IllegalStateException(e);
  1075. }
  1076. }
  1077. /**
  1078. * Returns the embedded pictures of the run. These
  1079. * are pictures which reference an external,
  1080. * embedded picture image such as a .png or .jpg
  1081. */
  1082. public List<XWPFPicture> getEmbeddedPictures() {
  1083. return pictures;
  1084. }
  1085. /**
  1086. * Set the style ID for the run.
  1087. *
  1088. * @param styleId ID (not name) of the style to set for the run, e.g. "BoldItalic" (not "Bold Italic").
  1089. */
  1090. public void setStyle(String styleId) {
  1091. CTRPr pr = getCTR().getRPr();
  1092. if (null == pr) {
  1093. pr = getCTR().addNewRPr();
  1094. }
  1095. CTString style = pr.getRStyle() != null ? pr.getRStyle() : pr.addNewRStyle();
  1096. style.setVal(styleId);
  1097. }
  1098. /**
  1099. * Returns the string version of the text and the phonetic string
  1100. */
  1101. @Override
  1102. public String toString() {
  1103. String phonetic = getPhonetic();
  1104. if (phonetic.length() > 0) {
  1105. return text() + " (" + phonetic + ")";
  1106. } else {
  1107. return text();
  1108. }
  1109. }
  1110. /**
  1111. * Returns the string version of the text, with tabs and
  1112. * carriage returns in place of their xml equivalents.
  1113. */
  1114. @Override
  1115. public String text() {
  1116. StringBuilder text = new StringBuilder(64);
  1117. // Grab the text and tabs of the text run
  1118. // Do so in a way that preserves the ordering
  1119. XmlCursor c = run.newCursor();
  1120. c.selectPath("./*");
  1121. while (c.toNextSelection()) {
  1122. XmlObject o = c.getObject();
  1123. if (o instanceof CTRuby) {
  1124. handleRuby(o, text, false);
  1125. continue;
  1126. }
  1127. _getText(o, text);
  1128. }
  1129. c.dispose();
  1130. return text.toString();
  1131. }
  1132. /**
  1133. * @return the phonetic (ruby) string associated with this run or an empty String if none exists
  1134. */
  1135. public String getPhonetic() {
  1136. StringBuilder text = new StringBuilder(64);
  1137. // Grab the text and tabs of the text run
  1138. // Do so in a way that preserves the ordering
  1139. XmlCursor c = run.newCursor();
  1140. c.selectPath("./*");
  1141. while (c.toNextSelection()) {
  1142. XmlObject o = c.getObject();
  1143. if (o instanceof CTRuby) {
  1144. handleRuby(o, text, true);
  1145. }
  1146. }
  1147. // Any picture text?
  1148. if (pictureText != null && pictureText.length() > 0) {
  1149. text.append("\n").append(pictureText).append("\n");
  1150. }
  1151. c.dispose();
  1152. return text.toString();
  1153. }
  1154. /**
  1155. * @param rubyObj rubyobject
  1156. * @param text buffer to which to append the content
  1157. * @param extractPhonetic extract the phonetic (rt) component or the base component
  1158. */
  1159. private void handleRuby(XmlObject rubyObj, StringBuilder text, boolean extractPhonetic) {
  1160. XmlCursor c = rubyObj.newCursor();
  1161. //according to the spec, a ruby object
  1162. //has the phonetic (rt) first, then the actual text (base)
  1163. //second.
  1164. c.selectPath(".//*");
  1165. boolean inRT = false;
  1166. boolean inBase = false;
  1167. while (c.toNextSelection()) {
  1168. XmlObject o = c.getObject();
  1169. if (o instanceof CTRubyContent) {
  1170. String tagName = o.getDomNode().getNodeName();
  1171. if ("w:rt".equals(tagName)) {
  1172. inRT = true;
  1173. } else if ("w:rubyBase".equals(tagName)) {
  1174. inRT = false;
  1175. inBase = true;
  1176. }
  1177. } else {
  1178. if (extractPhonetic && inRT) {
  1179. _getText(o, text);
  1180. } else if (!extractPhonetic && inBase) {
  1181. _getText(o, text);
  1182. }
  1183. }
  1184. }
  1185. c.dispose();
  1186. }
  1187. private void _getText(XmlObject o, StringBuilder text) {
  1188. if (o instanceof CTText) {
  1189. String tagName = o.getDomNode().getNodeName();
  1190. // Field Codes (w:instrText, defined in spec sec. 17.16.23)
  1191. // come up as instances of CTText, but we don't want them
  1192. // in the normal text output
  1193. if (!"w:instrText".equals(tagName)) {
  1194. text.append(((CTText) o).getStringValue());
  1195. }
  1196. }
  1197. // Complex type evaluation (currently only for extraction of check boxes)
  1198. if (o instanceof CTFldChar) {
  1199. CTFldChar ctfldChar = ((CTFldChar) o);
  1200. if (ctfldChar.getFldCharType() == STFldCharType.BEGIN) {
  1201. if (ctfldChar.getFfData() != null) {
  1202. for (CTFFCheckBox checkBox : ctfldChar.getFfData().getCheckBoxList()) {
  1203. if (checkBox.getDefault() != null && checkBox.getDefault().getVal() == STOnOff.X_1) {
  1204. text.append("|X|");
  1205. } else {
  1206. text.append("|_|");
  1207. }
  1208. }
  1209. }
  1210. }
  1211. }
  1212. if (o instanceof CTPTab) {
  1213. text.append('\t');
  1214. }
  1215. if (o instanceof CTBr) {
  1216. text.append('\n');
  1217. }
  1218. if (o instanceof CTEmpty) {
  1219. // Some inline text elements get returned not as
  1220. // themselves, but as CTEmpty, owing to some odd
  1221. // definitions around line 5642 of the XSDs
  1222. // This bit works around it, and replicates the above
  1223. // rules for that case
  1224. String tagName = o.getDomNode().getNodeName();
  1225. if ("w:tab".equals(tagName) || "tab".equals(tagName)) {
  1226. text.append('\t');
  1227. }
  1228. if ("w:br".equals(tagName) || "br".equals(tagName)) {
  1229. text.append('\n');
  1230. }
  1231. if ("w:cr".equals(tagName) || "cr".equals(tagName)) {
  1232. text.append('\n');
  1233. }
  1234. }
  1235. if (o instanceof CTFtnEdnRef) {
  1236. CTFtnEdnRef ftn = (CTFtnEdnRef) o;
  1237. String footnoteRef = ftn.getDomNode().getLocalName().equals("footnoteReference") ?
  1238. "[footnoteRef:" + ftn.getId().intValue() + "]" : "[endnoteRef:" + ftn.getId().intValue() + "]";
  1239. text.append(footnoteRef);
  1240. }
  1241. }
  1242. /**
  1243. * @see <a href="http://msdn.microsoft.com/en-us/library/ff533743(v=office.12).aspx">[MS-OI29500] Run Fonts</a>
  1244. */
  1245. public static enum FontCharRange {
  1246. ascii /* char 0-127 */,
  1247. cs /* complex symbol */,
  1248. eastAsia /* east asia */,
  1249. hAnsi /* high ansi */
  1250. }
  1251. /**
  1252. * Set the text expand/collapse scale value.
  1253. *
  1254. * @param percentage The percentage to expand or compress the text
  1255. * @since 4.0.0
  1256. */
  1257. public void setTextScale(int percentage) {
  1258. CTRPr pr = getRunProperties(true);
  1259. CTTextScale scale = pr.isSetW() ? pr.getW() : pr.addNewW();
  1260. scale.setVal(percentage);
  1261. }
  1262. /**
  1263. * Gets the current text scale value.
  1264. *
  1265. * @return Value is an integer percentage
  1266. * @since 4.0.0
  1267. */
  1268. public int getTextScale() {
  1269. CTRPr pr = getRunProperties(true);
  1270. CTTextScale scale = pr.isSetW() ? pr.getW() : pr.addNewW();
  1271. int value = scale.getVal();
  1272. if (value == 0) {
  1273. value = 100; // 100% scaling, that is, no change. See 17.3.2.43 w (Expanded/Compressed Text)
  1274. }
  1275. return value;
  1276. }
  1277. /**
  1278. * Set the highlight color for the run. Silently does nothing of colorName is not a recognized value.
  1279. *
  1280. * @param colorName The name of the color as defined in the ST_HighlightColor simple type ({@link STHightlightColor})
  1281. * @since 4.0.0
  1282. */
  1283. public void setTextHighlightColor(String colorName) {
  1284. CTRPr pr = getRunProperties(true);
  1285. CTHighlight highlight = pr.isSetHighlight() ? pr.getHighlight() : pr.addNewHighlight();
  1286. STHighlightColor color = highlight.xgetVal();
  1287. if (color == null) {
  1288. color = STHighlightColor.Factory.newInstance();
  1289. }
  1290. STHighlightColor.Enum val = STHighlightColor.Enum.forString(colorName);
  1291. if (val != null) {
  1292. color.setStringValue(val.toString());
  1293. highlight.xsetVal(color);
  1294. }
  1295. }
  1296. /**
  1297. * Gets the highlight color for the run
  1298. *
  1299. * @return {@link STHighlightColor} for the run.
  1300. * @since 4.0.0
  1301. */
  1302. public STHighlightColor.Enum getTextHightlightColor() {
  1303. CTRPr pr = getRunProperties(true);
  1304. CTHighlight highlight = pr.isSetHighlight() ? pr.getHighlight() : pr.addNewHighlight();
  1305. STHighlightColor color = highlight.xgetVal();
  1306. if (color == null) {
  1307. color = STHighlightColor.Factory.newInstance();
  1308. color.set(STHighlightColor.NONE);
  1309. }
  1310. return (STHighlightColor.Enum)(color.enumValue());
  1311. }
  1312. /**
  1313. * Get the vanish (hidden text) value
  1314. *
  1315. * @return True if the run is hidden text.
  1316. * @since 4.0.0
  1317. */
  1318. public boolean isVanish() {
  1319. CTRPr pr = getRunProperties(true);
  1320. return pr != null && pr.isSetVanish() && isCTOnOff(pr.getVanish());
  1321. }
  1322. /**
  1323. * The vanish (hidden text) property for the run.
  1324. *
  1325. * @param value Set to true to make the run hidden text.
  1326. * @since 4.0.0
  1327. */
  1328. public void setVanish(boolean value) {
  1329. CTRPr pr = getRunProperties(true);
  1330. CTOnOff vanish = pr.isSetVanish() ? pr.getVanish() : pr.addNewVanish();
  1331. vanish.setVal(value ? STOnOff.TRUE : STOnOff.FALSE);
  1332. }
  1333. /**
  1334. * Get the vertical alignment value
  1335. *
  1336. * @return {@link STVerticalAlignRun.Enum} value (see 22.9.2.17 ST_VerticalAlignRun (Vertical Positioning Location))
  1337. * @since 4.0.0
  1338. */
  1339. public STVerticalAlignRun.Enum getVerticalAlignment() {
  1340. CTRPr pr = getRunProperties(true);
  1341. CTVerticalAlignRun vertAlign = pr.isSetVertAlign() ? pr.getVertAlign() : pr.addNewVertAlign();
  1342. STVerticalAlignRun.Enum val = vertAlign.getVal();
  1343. if (val == null) {
  1344. val = STVerticalAlignRun.BASELINE;
  1345. }
  1346. return val;
  1347. }
  1348. /**
  1349. * Set the vertical alignment of the run.
  1350. *
  1351. * @param verticalAlignment Vertical alignment value, one of "baseline", "superscript", or "subscript".
  1352. * @since 4.0.0
  1353. */
  1354. public void setVerticalAlignment(String verticalAlignment) {
  1355. CTRPr pr = getRunProperties(true);
  1356. CTVerticalAlignRun vertAlign = pr.isSetVertAlign() ? pr.getVertAlign() : pr.addNewVertAlign();
  1357. STVerticalAlignRun align = vertAlign.xgetVal();
  1358. if (align == null) {
  1359. align = STVerticalAlignRun.Factory.newInstance();
  1360. }
  1361. STVerticalAlignRun.Enum val = STVerticalAlignRun.Enum.forString(verticalAlignment);
  1362. if (val != null) {
  1363. align.setStringValue(val.toString());
  1364. vertAlign.xsetVal(align);
  1365. }
  1366. }
  1367. /**
  1368. * Get the emphasis mark value for the run.
  1369. *
  1370. * @return {@link STEm.Enum} emphasis mark type enumeration. See 17.18.24 ST_Em (Emphasis Mark Type).
  1371. * @since 4.0.0
  1372. */
  1373. public STEm.Enum getEmphasisMark() {
  1374. CTRPr pr = getRunProperties(true);
  1375. CTEm emphasis = pr.isSetEm() ? pr.getEm() : pr.addNewEm();
  1376. STEm.Enum val = emphasis.getVal();
  1377. if (val == null) {
  1378. val = STEm.NONE;
  1379. }
  1380. return val;
  1381. }
  1382. /**
  1383. * Set the emphasis mark for the run. The emphasis mark goes above or below the run
  1384. * text.
  1385. *
  1386. * @param markType Emphasis mark type name, e.g., "dot" or "none". See 17.18.24 ST_Em (Emphasis Mark Type)
  1387. * @since 4.0.0
  1388. */
  1389. public void setEmphasisMark(String markType) {
  1390. CTRPr pr = getRunProperties(true);
  1391. CTEm emphasisMark = pr.isSetEm() ? pr.getEm() : pr.addNewEm();
  1392. STEm mark = emphasisMark.xgetVal();
  1393. if (mark == null) {
  1394. mark = STEm.Factory.newInstance();
  1395. }
  1396. STEm.Enum val = STEm.Enum.forString(markType);
  1397. if (val != null) {
  1398. mark.setStringValue(val.toString());
  1399. emphasisMark.xsetVal(mark);
  1400. }
  1401. }
  1402. /**
  1403. * Get the run properties for the run.
  1404. *
  1405. * @param create If true, create the properties, if false, do not.
  1406. * @return The run properties or null if there are no properties and create is false.
  1407. */
  1408. private CTRPr getRunProperties(boolean create) {
  1409. CTRPr pr = run.isSetRPr() ? run.getRPr() : null;
  1410. if (create && pr == null) {
  1411. pr = run.addNewRPr();
  1412. }
  1413. return pr;
  1414. }
  1415. }