Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

XSLFTextParagraph.java 40KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026
  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.xslf.usermodel;
  16. import org.apache.poi.util.Beta;
  17. import org.apache.poi.util.Internal;
  18. import org.apache.poi.util.Units;
  19. import org.apache.poi.xslf.model.ParagraphPropertyFetcher;
  20. import org.apache.xmlbeans.XmlObject;
  21. import org.openxmlformats.schemas.drawingml.x2006.main.CTRegularTextRun;
  22. import org.openxmlformats.schemas.drawingml.x2006.main.CTTextField;
  23. import org.openxmlformats.schemas.drawingml.x2006.main.CTTextParagraph;
  24. import org.openxmlformats.schemas.drawingml.x2006.main.CTTextParagraphProperties;
  25. import org.openxmlformats.schemas.drawingml.x2006.main.CTTextSpacing;
  26. import org.openxmlformats.schemas.drawingml.x2006.main.CTTextTabStop;
  27. import org.openxmlformats.schemas.drawingml.x2006.main.CTTextTabStopList;
  28. import org.openxmlformats.schemas.drawingml.x2006.main.STTextAlignType;
  29. import org.openxmlformats.schemas.drawingml.x2006.main.CTTextFont;
  30. import org.openxmlformats.schemas.drawingml.x2006.main.CTTextCharBullet;
  31. import org.openxmlformats.schemas.drawingml.x2006.main.CTColor;
  32. import org.openxmlformats.schemas.drawingml.x2006.main.CTSRgbColor;
  33. import org.openxmlformats.schemas.drawingml.x2006.main.CTTextBulletSizePoint;
  34. import org.openxmlformats.schemas.drawingml.x2006.main.CTTextLineBreak;
  35. import org.openxmlformats.schemas.drawingml.x2006.main.CTTextNormalAutofit;
  36. import org.openxmlformats.schemas.drawingml.x2006.main.CTTextCharacterProperties;
  37. import org.openxmlformats.schemas.presentationml.x2006.main.CTPlaceholder;
  38. import org.openxmlformats.schemas.presentationml.x2006.main.STPlaceholderType;
  39. import java.awt.Color;
  40. import java.awt.Graphics2D;
  41. import java.awt.font.LineBreakMeasurer;
  42. import java.awt.font.TextAttribute;
  43. import java.awt.font.TextLayout;
  44. import java.awt.geom.Rectangle2D;
  45. import java.text.AttributedCharacterIterator;
  46. import java.text.AttributedString;
  47. import java.util.ArrayList;
  48. import java.util.Iterator;
  49. import java.util.List;
  50. /**
  51. * Represents a paragraph of text within the containing text body.
  52. * The paragraph is the highest level text separation mechanism.
  53. *
  54. * @author Yegor Kozlov
  55. * @since POI-3.8
  56. */
  57. @Beta
  58. public class XSLFTextParagraph implements Iterable<XSLFTextRun>{
  59. private final CTTextParagraph _p;
  60. private final List<XSLFTextRun> _runs;
  61. private final XSLFTextShape _shape;
  62. private List<TextFragment> _lines;
  63. private TextFragment _bullet;
  64. /**
  65. * the highest line in this paragraph. Used for line spacing.
  66. */
  67. private double _maxLineHeight;
  68. XSLFTextParagraph(CTTextParagraph p, XSLFTextShape shape){
  69. _p = p;
  70. _runs = new ArrayList<XSLFTextRun>();
  71. _shape = shape;
  72. for(XmlObject ch : _p.selectPath("*")){
  73. if(ch instanceof CTRegularTextRun){
  74. CTRegularTextRun r = (CTRegularTextRun)ch;
  75. _runs.add(new XSLFTextRun(r, this));
  76. } else if (ch instanceof CTTextLineBreak){
  77. CTTextLineBreak br = (CTTextLineBreak)ch;
  78. CTRegularTextRun r = CTRegularTextRun.Factory.newInstance();
  79. r.setRPr(br.getRPr());
  80. r.setT("\n");
  81. _runs.add(new XSLFTextRun(r, this));
  82. } else if (ch instanceof CTTextField){
  83. CTTextField f = (CTTextField)ch;
  84. CTRegularTextRun r = CTRegularTextRun.Factory.newInstance();
  85. r.setRPr(f.getRPr());
  86. r.setT(f.getT());
  87. _runs.add(new XSLFTextRun(r, this));
  88. }
  89. }
  90. }
  91. public String getText(){
  92. StringBuilder out = new StringBuilder();
  93. for (XSLFTextRun r : _runs) {
  94. out.append(r.getText());
  95. }
  96. return out.toString();
  97. }
  98. String getRenderableText(){
  99. StringBuilder out = new StringBuilder();
  100. for (XSLFTextRun r : _runs) {
  101. out.append(r.getRenderableText());
  102. }
  103. return out.toString();
  104. }
  105. @Internal
  106. public CTTextParagraph getXmlObject(){
  107. return _p;
  108. }
  109. XSLFTextShape getParentShape() {
  110. return _shape;
  111. }
  112. public List<XSLFTextRun> getTextRuns(){
  113. return _runs;
  114. }
  115. public Iterator<XSLFTextRun> iterator(){
  116. return _runs.iterator();
  117. }
  118. public XSLFTextRun addNewTextRun(){
  119. CTRegularTextRun r = _p.addNewR();
  120. r.addNewRPr();
  121. XSLFTextRun run = new XSLFTextRun(r, this);
  122. _runs.add(run);
  123. return run;
  124. }
  125. public void addLineBreak(){
  126. _p.addNewBr();
  127. }
  128. /**
  129. * Returns the alignment that is applied to the paragraph.
  130. *
  131. * If this attribute is omitted, then a value of left is implied.
  132. * @return ??? alignment that is applied to the paragraph
  133. */
  134. public TextAlign getTextAlign(){
  135. ParagraphPropertyFetcher<TextAlign> fetcher = new ParagraphPropertyFetcher<TextAlign>(getLevel()){
  136. public boolean fetch(CTTextParagraphProperties props){
  137. if(props.isSetAlgn()){
  138. TextAlign val = TextAlign.values()[props.getAlgn().intValue() - 1];
  139. setValue(val);
  140. return true;
  141. }
  142. return false;
  143. }
  144. };
  145. fetchParagraphProperty(fetcher);
  146. return fetcher.getValue() == null ? TextAlign.LEFT : fetcher.getValue();
  147. }
  148. /**
  149. * Specifies the alignment that is to be applied to the paragraph.
  150. * Possible values for this include left, right, centered, justified and distributed,
  151. * see {@link org.apache.poi.xslf.usermodel.TextAlign}.
  152. *
  153. * @param align text align
  154. */
  155. public void setTextAlign(TextAlign align){
  156. CTTextParagraphProperties pr = _p.isSetPPr() ? _p.getPPr() : _p.addNewPPr();
  157. if(align == null) {
  158. if(pr.isSetAlgn()) pr.unsetAlgn();
  159. } else {
  160. pr.setAlgn(STTextAlignType.Enum.forInt(align.ordinal() + 1));
  161. }
  162. }
  163. /**
  164. * @return the font to be used on bullet characters within a given paragraph
  165. */
  166. public String getBulletFont(){
  167. ParagraphPropertyFetcher<String> fetcher = new ParagraphPropertyFetcher<String>(getLevel()){
  168. public boolean fetch(CTTextParagraphProperties props){
  169. if(props.isSetBuFont()){
  170. setValue(props.getBuFont().getTypeface());
  171. return true;
  172. }
  173. return false;
  174. }
  175. };
  176. fetchParagraphProperty(fetcher);
  177. return fetcher.getValue();
  178. }
  179. public void setBulletFont(String typeface){
  180. CTTextParagraphProperties pr = _p.isSetPPr() ? _p.getPPr() : _p.addNewPPr();
  181. CTTextFont font = pr.isSetBuFont() ? pr.getBuFont() : pr.addNewBuFont();
  182. font.setTypeface(typeface);
  183. }
  184. /**
  185. * @return the character to be used in place of the standard bullet point
  186. */
  187. public String getBulletCharacter(){
  188. ParagraphPropertyFetcher<String> fetcher = new ParagraphPropertyFetcher<String>(getLevel()){
  189. public boolean fetch(CTTextParagraphProperties props){
  190. if(props.isSetBuChar()){
  191. setValue(props.getBuChar().getChar());
  192. return true;
  193. }
  194. return false;
  195. }
  196. };
  197. fetchParagraphProperty(fetcher);
  198. return fetcher.getValue();
  199. }
  200. public void setBulletCharacter(String str){
  201. CTTextParagraphProperties pr = _p.isSetPPr() ? _p.getPPr() : _p.addNewPPr();
  202. CTTextCharBullet c = pr.isSetBuChar() ? pr.getBuChar() : pr.addNewBuChar();
  203. c.setChar(str);
  204. }
  205. public Color getBulletFontColor(){
  206. final XSLFTheme theme = getParentShape().getSheet().getTheme();
  207. ParagraphPropertyFetcher<Color> fetcher = new ParagraphPropertyFetcher<Color>(getLevel()){
  208. public boolean fetch(CTTextParagraphProperties props){
  209. if(props.isSetBuClr()){
  210. XSLFColor c = new XSLFColor(props.getBuClr(), theme, null);
  211. setValue(c.getColor());
  212. return true;
  213. }
  214. return false;
  215. }
  216. };
  217. fetchParagraphProperty(fetcher);
  218. return fetcher.getValue();
  219. }
  220. public void setBulletFontColor(Color color){
  221. CTTextParagraphProperties pr = _p.isSetPPr() ? _p.getPPr() : _p.addNewPPr();
  222. CTColor c = pr.isSetBuClr() ? pr.getBuClr() : pr.addNewBuClr();
  223. CTSRgbColor clr = c.isSetSrgbClr() ? c.getSrgbClr() : c.addNewSrgbClr();
  224. clr.setVal(new byte[]{(byte) color.getRed(), (byte) color.getGreen(), (byte) color.getBlue()});
  225. }
  226. public double getBulletFontSize(){
  227. ParagraphPropertyFetcher<Double> fetcher = new ParagraphPropertyFetcher<Double>(getLevel()){
  228. public boolean fetch(CTTextParagraphProperties props){
  229. if(props.isSetBuSzPct()){
  230. setValue(props.getBuSzPct().getVal() * 0.001);
  231. return true;
  232. }
  233. if(props.isSetBuSzPts()){
  234. setValue( - props.getBuSzPts().getVal() * 0.01);
  235. return true;
  236. }
  237. return false;
  238. }
  239. };
  240. fetchParagraphProperty(fetcher);
  241. return fetcher.getValue() == null ? 100 : fetcher.getValue();
  242. }
  243. public void setBulletFontSize(double size){
  244. CTTextParagraphProperties pr = _p.isSetPPr() ? _p.getPPr() : _p.addNewPPr();
  245. CTTextBulletSizePoint pt = pr.isSetBuSzPts() ? pr.getBuSzPts() : pr.addNewBuSzPts();
  246. pt.setVal((int)(size*1000));
  247. if(pr.isSetBuSzPct()) pr.unsetBuSzPct();
  248. }
  249. /**
  250. * Specifies the indent size that will be applied to the first line of text in the paragraph.
  251. *
  252. * @param value the indent in points.
  253. */
  254. public void setIndent(double value){
  255. CTTextParagraphProperties pr = _p.isSetPPr() ? _p.getPPr() : _p.addNewPPr();
  256. if(value == -1) {
  257. if(pr.isSetIndent()) pr.unsetIndent();
  258. } else {
  259. pr.setIndent(Units.toEMU(value));
  260. }
  261. }
  262. /**
  263. *
  264. * @return the indent applied to the first line of text in the paragraph.
  265. */
  266. public double getIndent(){
  267. ParagraphPropertyFetcher<Double> fetcher = new ParagraphPropertyFetcher<Double>(getLevel()){
  268. public boolean fetch(CTTextParagraphProperties props){
  269. if(props.isSetIndent()){
  270. setValue(Units.toPoints(props.getIndent()));
  271. return true;
  272. }
  273. return false;
  274. }
  275. };
  276. fetchParagraphProperty(fetcher);
  277. return fetcher.getValue() == null ? 0 : fetcher.getValue();
  278. }
  279. /**
  280. * Specifies the left margin of the paragraph. This is specified in addition to the text body
  281. * inset and applies only to this text paragraph. That is the text body Inset and the LeftMargin
  282. * attributes are additive with respect to the text position.
  283. *
  284. * @param value the left margin of the paragraph
  285. */
  286. public void setLeftMargin(double value){
  287. CTTextParagraphProperties pr = _p.isSetPPr() ? _p.getPPr() : _p.addNewPPr();
  288. pr.setMarL(Units.toEMU(value));
  289. }
  290. /**
  291. *
  292. * @return the left margin of the paragraph
  293. */
  294. public double getLeftMargin(){
  295. ParagraphPropertyFetcher<Double> fetcher = new ParagraphPropertyFetcher<Double>(getLevel()){
  296. public boolean fetch(CTTextParagraphProperties props){
  297. if(props.isSetMarL()){
  298. double val = Units.toPoints(props.getMarL());
  299. setValue(val);
  300. return true;
  301. }
  302. return false;
  303. }
  304. };
  305. fetchParagraphProperty(fetcher);
  306. // if the marL attribute is omitted, then a value of 347663 is implied
  307. return fetcher.getValue() == null ? 0 : fetcher.getValue();
  308. }
  309. /**
  310. *
  311. * @return the default size for a tab character within this paragraph
  312. */
  313. public double getDefaultTabSize(){
  314. ParagraphPropertyFetcher<Double> fetcher = new ParagraphPropertyFetcher<Double>(getLevel()){
  315. public boolean fetch(CTTextParagraphProperties props){
  316. if(props.isSetDefTabSz()){
  317. double val = Units.toPoints(props.getDefTabSz());
  318. setValue(val);
  319. return true;
  320. }
  321. return false;
  322. }
  323. };
  324. fetchParagraphProperty(fetcher);
  325. return fetcher.getValue() == null ? 0 : fetcher.getValue();
  326. }
  327. public double getTabStop(final int idx){
  328. ParagraphPropertyFetcher<Double> fetcher = new ParagraphPropertyFetcher<Double>(getLevel()){
  329. public boolean fetch(CTTextParagraphProperties props){
  330. if(props.isSetTabLst()){
  331. CTTextTabStopList tabStops = props.getTabLst();
  332. if(idx < tabStops.sizeOfTabArray() ) {
  333. CTTextTabStop ts = tabStops.getTabArray(idx);
  334. double val = Units.toPoints(ts.getPos());
  335. setValue(val);
  336. return true;
  337. }
  338. }
  339. return false;
  340. }
  341. };
  342. fetchParagraphProperty(fetcher);
  343. return fetcher.getValue() == null ? getDefaultTabSize() : fetcher.getValue();
  344. }
  345. /**
  346. * This element specifies the vertical line spacing that is to be used within a paragraph.
  347. * This may be specified in two different ways, percentage spacing and font point spacing:
  348. * <p>
  349. * If linespacing >= 0, then linespacing is a percentage of normal line height
  350. * If linespacing < 0, the absolute value of linespacing is the spacing in points
  351. * </p>
  352. * Examples:
  353. * <pre><code>
  354. * // spacing will be 120% of the size of the largest text on each line
  355. * paragraph.setLineSpacing(120);
  356. *
  357. * // spacing will be 200% of the size of the largest text on each line
  358. * paragraph.setLineSpacing(200);
  359. *
  360. * // spacing will be 48 points
  361. * paragraph.setLineSpacing(-48.0);
  362. * </code></pre>
  363. *
  364. * @param linespacing the vertical line spacing
  365. */
  366. public void setLineSpacing(double linespacing){
  367. CTTextParagraphProperties pr = _p.isSetPPr() ? _p.getPPr() : _p.addNewPPr();
  368. CTTextSpacing spc = CTTextSpacing.Factory.newInstance();
  369. if(linespacing >= 0) spc.addNewSpcPct().setVal((int)(linespacing*1000));
  370. else spc.addNewSpcPts().setVal((int)(-linespacing*100));
  371. pr.setLnSpc(spc);
  372. }
  373. /**
  374. * Returns the vertical line spacing that is to be used within a paragraph.
  375. * This may be specified in two different ways, percentage spacing and font point spacing:
  376. * <p>
  377. * If linespacing >= 0, then linespacing is a percentage of normal line height.
  378. * If linespacing < 0, the absolute value of linespacing is the spacing in points
  379. * </p>
  380. *
  381. * @return the vertical line spacing.
  382. */
  383. public double getLineSpacing(){
  384. ParagraphPropertyFetcher<Double> fetcher = new ParagraphPropertyFetcher<Double>(getLevel()){
  385. public boolean fetch(CTTextParagraphProperties props){
  386. if(props.isSetLnSpc()){
  387. CTTextSpacing spc = props.getLnSpc();
  388. if(spc.isSetSpcPct()) setValue( spc.getSpcPct().getVal()*0.001 );
  389. else if (spc.isSetSpcPts()) setValue( -spc.getSpcPts().getVal()*0.01 );
  390. return true;
  391. }
  392. return false;
  393. }
  394. };
  395. fetchParagraphProperty(fetcher);
  396. double lnSpc = fetcher.getValue() == null ? 100 : fetcher.getValue();
  397. if(lnSpc > 0) {
  398. // check if the percentage value is scaled
  399. CTTextNormalAutofit normAutofit = getParentShape().getTextBodyPr().getNormAutofit();
  400. if(normAutofit != null) {
  401. double scale = 1 - (double)normAutofit.getLnSpcReduction() / 100000;
  402. lnSpc *= scale;
  403. }
  404. }
  405. return lnSpc;
  406. }
  407. /**
  408. * Set the amount of vertical white space that will be present before the paragraph.
  409. * This space is specified in either percentage or points:
  410. * <p>
  411. * If spaceBefore >= 0, then space is a percentage of normal line height.
  412. * If spaceBefore < 0, the absolute value of linespacing is the spacing in points
  413. * </p>
  414. * Examples:
  415. * <pre><code>
  416. * // The paragraph will be formatted to have a spacing before the paragraph text.
  417. * // The spacing will be 200% of the size of the largest text on each line
  418. * paragraph.setSpaceBefore(200);
  419. *
  420. * // The spacing will be a size of 48 points
  421. * paragraph.setSpaceBefore(-48.0);
  422. * </code></pre>
  423. *
  424. * @param spaceBefore the vertical white space before the paragraph.
  425. */
  426. public void setSpaceBefore(double spaceBefore){
  427. CTTextParagraphProperties pr = _p.isSetPPr() ? _p.getPPr() : _p.addNewPPr();
  428. CTTextSpacing spc = CTTextSpacing.Factory.newInstance();
  429. if(spaceBefore >= 0) spc.addNewSpcPct().setVal((int)(spaceBefore*1000));
  430. else spc.addNewSpcPts().setVal((int)(-spaceBefore*100));
  431. pr.setSpcBef(spc);
  432. }
  433. /**
  434. * The amount of vertical white space before the paragraph
  435. * This may be specified in two different ways, percentage spacing and font point spacing:
  436. * <p>
  437. * If spaceBefore >= 0, then space is a percentage of normal line height.
  438. * If spaceBefore < 0, the absolute value of linespacing is the spacing in points
  439. * </p>
  440. *
  441. * @return the vertical white space before the paragraph
  442. */
  443. public double getSpaceBefore(){
  444. ParagraphPropertyFetcher<Double> fetcher = new ParagraphPropertyFetcher<Double>(getLevel()){
  445. public boolean fetch(CTTextParagraphProperties props){
  446. if(props.isSetSpcBef()){
  447. CTTextSpacing spc = props.getSpcBef();
  448. if(spc.isSetSpcPct()) setValue( spc.getSpcPct().getVal()*0.001 );
  449. else if (spc.isSetSpcPts()) setValue( -spc.getSpcPts().getVal()*0.01 );
  450. return true;
  451. }
  452. return false;
  453. }
  454. };
  455. fetchParagraphProperty(fetcher);
  456. double spcBef = fetcher.getValue() == null ? 0 : fetcher.getValue();
  457. return spcBef;
  458. }
  459. /**
  460. * Set the amount of vertical white space that will be present after the paragraph.
  461. * This space is specified in either percentage or points:
  462. * <p>
  463. * If spaceAfter >= 0, then space is a percentage of normal line height.
  464. * If spaceAfter < 0, the absolute value of linespacing is the spacing in points
  465. * </p>
  466. * Examples:
  467. * <pre><code>
  468. * // The paragraph will be formatted to have a spacing after the paragraph text.
  469. * // The spacing will be 200% of the size of the largest text on each line
  470. * paragraph.setSpaceAfter(200);
  471. *
  472. * // The spacing will be a size of 48 points
  473. * paragraph.setSpaceAfter(-48.0);
  474. * </code></pre>
  475. *
  476. * @param spaceAfter the vertical white space after the paragraph.
  477. */
  478. public void setSpaceAfter(double spaceAfter){
  479. CTTextParagraphProperties pr = _p.isSetPPr() ? _p.getPPr() : _p.addNewPPr();
  480. CTTextSpacing spc = CTTextSpacing.Factory.newInstance();
  481. if(spaceAfter >= 0) spc.addNewSpcPct().setVal((int)(spaceAfter*1000));
  482. else spc.addNewSpcPts().setVal((int)(-spaceAfter*100));
  483. pr.setSpcAft(spc);
  484. }
  485. /**
  486. * The amount of vertical white space after the paragraph
  487. * This may be specified in two different ways, percentage spacing and font point spacing:
  488. * <p>
  489. * If spaceBefore >= 0, then space is a percentage of normal line height.
  490. * If spaceBefore < 0, the absolute value of linespacing is the spacing in points
  491. * </p>
  492. *
  493. * @return the vertical white space after the paragraph
  494. */
  495. public double getSpaceAfter(){
  496. ParagraphPropertyFetcher<Double> fetcher = new ParagraphPropertyFetcher<Double>(getLevel()){
  497. public boolean fetch(CTTextParagraphProperties props){
  498. if(props.isSetSpcAft()){
  499. CTTextSpacing spc = props.getSpcAft();
  500. if(spc.isSetSpcPct()) setValue( spc.getSpcPct().getVal()*0.001 );
  501. else if (spc.isSetSpcPts()) setValue( -spc.getSpcPts().getVal()*0.01 );
  502. return true;
  503. }
  504. return false;
  505. }
  506. };
  507. fetchParagraphProperty(fetcher);
  508. return fetcher.getValue() == null ? 0 : fetcher.getValue();
  509. }
  510. /**
  511. * Specifies the particular level text properties that this paragraph will follow.
  512. * The value for this attribute formats the text according to the corresponding level
  513. * paragraph properties defined in the SlideMaster.
  514. *
  515. * @param level the level (0 ... 4)
  516. */
  517. public void setLevel(int level){
  518. CTTextParagraphProperties pr = _p.isSetPPr() ? _p.getPPr() : _p.addNewPPr();
  519. pr.setLvl(level);
  520. }
  521. /**
  522. *
  523. * @return the text level of this paragraph (0-based). Default is 0.
  524. */
  525. public int getLevel(){
  526. CTTextParagraphProperties pr = _p.getPPr();
  527. if(pr == null) return 0;
  528. return pr.getLvl();
  529. }
  530. /**
  531. * Returns whether this paragraph has bullets
  532. */
  533. public boolean isBullet() {
  534. ParagraphPropertyFetcher<Boolean> fetcher = new ParagraphPropertyFetcher<Boolean>(getLevel()){
  535. public boolean fetch(CTTextParagraphProperties props){
  536. if(props.isSetBuNone()) {
  537. setValue(false);
  538. return true;
  539. }
  540. if(props.isSetBuFont() || props.isSetBuChar()){
  541. setValue(true);
  542. return true;
  543. }
  544. return false;
  545. }
  546. };
  547. fetchParagraphProperty(fetcher);
  548. return fetcher.getValue() == null ? false : fetcher.getValue();
  549. }
  550. /**
  551. *
  552. * @param flag whether text in this paragraph has bullets
  553. */
  554. public void setBullet(boolean flag) {
  555. if(isBullet() == flag) return;
  556. CTTextParagraphProperties pr = _p.isSetPPr() ? _p.getPPr() : _p.addNewPPr();
  557. if(!flag) {
  558. pr.addNewBuNone();
  559. } else {
  560. pr.addNewBuFont().setTypeface("Arial");
  561. pr.addNewBuChar().setChar("\u2022");
  562. }
  563. }
  564. @Override
  565. public String toString(){
  566. return "[" + getClass() + "]" + getText();
  567. }
  568. List<TextFragment> getTextLines(){
  569. return _lines;
  570. }
  571. /**
  572. * Returns wrapping width to break lines in this paragraph
  573. *
  574. * @param firstLine whether the first line is breaking
  575. *
  576. * @return wrapping width in points
  577. */
  578. double getWrappingWidth(boolean firstLine){
  579. // internal margins for the text box
  580. double leftInset = _shape.getLeftInset();
  581. double rightInset = _shape.getRightInset();
  582. Rectangle2D anchor = _shape.getAnchor();
  583. double leftMargin = getLeftMargin();
  584. double indent = getIndent();
  585. double width;
  586. if(!_shape.getWordWrap()) {
  587. // if wordWrap == false then we return the advance to the right border of the sheet
  588. width = _shape.getSheet().getSlideShow().getPageSize().getWidth() - anchor.getX();
  589. } else {
  590. width = anchor.getWidth() - leftInset - rightInset - leftMargin;
  591. if(firstLine) {
  592. if(isBullet()){
  593. if(indent > 0) width -= indent;
  594. } else {
  595. if(indent > 0) width -= indent; // first line indentation
  596. else if (indent < 0) { // hanging indentation: the first line start at the left margin
  597. width += leftMargin;
  598. }
  599. }
  600. }
  601. }
  602. return width;
  603. }
  604. public double draw(Graphics2D graphics, double x, double y){
  605. double leftInset = _shape.getLeftInset();
  606. double rightInset = _shape.getRightInset();
  607. Rectangle2D anchor = _shape.getAnchor();
  608. double penY = y;
  609. double leftMargin = getLeftMargin();
  610. boolean firstLine = true;
  611. double indent = getIndent();
  612. //The vertical line spacing
  613. double spacing = getLineSpacing();
  614. for(TextFragment line : _lines){
  615. double penX = x + leftMargin;
  616. if(firstLine) {
  617. if(_bullet != null){
  618. if(indent < 0) {
  619. // a negative value means "Hanging" indentation and
  620. // indicates the position of the actual bullet character.
  621. // (the bullet is shifted to right relative to the text)
  622. _bullet.draw(graphics, penX + indent, penY);
  623. } else if(indent > 0){
  624. // a positive value means the "First Line" indentation:
  625. // the first line is indented and other lines start at the bullet ofset
  626. _bullet.draw(graphics, penX, penY);
  627. penX += indent;
  628. } else {
  629. // a zero indent means that the bullet and text have the same offset
  630. _bullet.draw(graphics, penX, penY);
  631. // don't let text overlay the bullet and advance by the bullet width
  632. penX += _bullet._layout.getAdvance() + 1;
  633. }
  634. } else {
  635. penX += indent;
  636. }
  637. }
  638. switch (getTextAlign()) {
  639. case CENTER:
  640. penX += (anchor.getWidth() - leftMargin - line.getWidth() - leftInset - rightInset) / 2;
  641. break;
  642. case RIGHT:
  643. penX += (anchor.getWidth() - line.getWidth() - leftInset - rightInset);
  644. break;
  645. default:
  646. break;
  647. }
  648. line.draw(graphics, penX, penY);
  649. if(spacing > 0) {
  650. // If linespacing >= 0, then linespacing is a percentage of normal line height.
  651. penY += spacing*0.01* line.getHeight();
  652. } else {
  653. // positive value means absolute spacing in points
  654. penY += -spacing;
  655. }
  656. firstLine = false;
  657. }
  658. return penY - y;
  659. }
  660. AttributedString getAttributedString(Graphics2D graphics){
  661. String text = getRenderableText();
  662. AttributedString string = new AttributedString(text);
  663. XSLFFontManager fontHandler = (XSLFFontManager)graphics.getRenderingHint(XSLFRenderingHint.FONT_HANDLER);
  664. int startIndex = 0;
  665. for (XSLFTextRun run : _runs){
  666. int length = run.getRenderableText().length();
  667. if(length == 0) {
  668. // skip empty runs
  669. continue;
  670. }
  671. int endIndex = startIndex + length;
  672. string.addAttribute(TextAttribute.FOREGROUND, run.getFontColor(), startIndex, endIndex);
  673. // user can pass an custom object to convert fonts
  674. String fontFamily = run.getFontFamily();
  675. if(fontHandler != null) {
  676. fontFamily = fontHandler.getRendererableFont(fontFamily, run.getPitchAndFamily());
  677. }
  678. string.addAttribute(TextAttribute.FAMILY, fontFamily, startIndex, endIndex);
  679. float fontSz = (float)run.getFontSize();
  680. Number fontScale = (Number)graphics.getRenderingHint(XSLFRenderingHint.GROUP_SCALE);
  681. if(fontScale != null) fontSz *= fontScale.floatValue();
  682. string.addAttribute(TextAttribute.SIZE, fontSz , startIndex, endIndex);
  683. if(run.isBold()) {
  684. string.addAttribute(TextAttribute.WEIGHT, TextAttribute.WEIGHT_BOLD, startIndex, endIndex);
  685. }
  686. if(run.isItalic()) {
  687. string.addAttribute(TextAttribute.POSTURE, TextAttribute.POSTURE_OBLIQUE, startIndex, endIndex);
  688. }
  689. if(run.isUnderline()) {
  690. string.addAttribute(TextAttribute.UNDERLINE, TextAttribute.UNDERLINE_ON, startIndex, endIndex);
  691. string.addAttribute(TextAttribute.INPUT_METHOD_UNDERLINE, TextAttribute.UNDERLINE_LOW_TWO_PIXEL, startIndex, endIndex);
  692. }
  693. if(run.isStrikethrough()) {
  694. string.addAttribute(TextAttribute.STRIKETHROUGH, TextAttribute.STRIKETHROUGH_ON, startIndex, endIndex);
  695. }
  696. if(run.isSubscript()) {
  697. string.addAttribute(TextAttribute.SUPERSCRIPT, TextAttribute.SUPERSCRIPT_SUB, startIndex, endIndex);
  698. }
  699. if(run.isSuperscript()) {
  700. string.addAttribute(TextAttribute.SUPERSCRIPT, TextAttribute.SUPERSCRIPT_SUPER, startIndex, endIndex);
  701. }
  702. startIndex = endIndex;
  703. }
  704. return string;
  705. }
  706. /**
  707. * ensure that the paragraph contains at least one character.
  708. * We need this trick to correctly measure text
  709. */
  710. private void ensureNotEmpty(){
  711. XSLFTextRun r = addNewTextRun();
  712. r.setText(" ");
  713. CTTextCharacterProperties endPr = _p.getEndParaRPr();
  714. if(endPr != null) {
  715. if(endPr.isSetSz()) r.setFontSize(endPr.getSz() / 100);
  716. }
  717. }
  718. /**
  719. * break text into lines
  720. *
  721. * @param graphics
  722. * @return array of text fragments,
  723. * each representing a line of text that fits in the wrapping width
  724. */
  725. List<TextFragment> breakText(Graphics2D graphics){
  726. _lines = new ArrayList<TextFragment>();
  727. // does this paragraph contain text?
  728. boolean emptyParagraph = _runs.size() == 0;
  729. // ensure that the paragraph contains at least one character
  730. if(_runs.size() == 0) ensureNotEmpty();
  731. String text = getRenderableText();
  732. if(text.length() == 0) return _lines;
  733. AttributedString at = getAttributedString(graphics);
  734. AttributedCharacterIterator it = at.getIterator();
  735. LineBreakMeasurer measurer = new LineBreakMeasurer(it, graphics.getFontRenderContext()) ;
  736. for (;;) {
  737. int startIndex = measurer.getPosition();
  738. double wrappingWidth = getWrappingWidth(_lines.size() == 0) + 1; // add a pixel to compensate rounding errors
  739. // shape width can be smaller that the sum of insets (this was proved by a test file)
  740. if(wrappingWidth < 0) wrappingWidth = 1;
  741. int nextBreak = text.indexOf('\n', startIndex + 1);
  742. if(nextBreak == -1) nextBreak = it.getEndIndex();
  743. TextLayout layout = measurer.nextLayout((float)wrappingWidth, nextBreak, true);
  744. if (layout == null) {
  745. // layout can be null if the entire word at the current position
  746. // does not fit within the wrapping width. Try with requireNextWord=false.
  747. layout = measurer.nextLayout((float)wrappingWidth, nextBreak, false);
  748. }
  749. if(layout == null) {
  750. // exit if can't break any more
  751. break;
  752. }
  753. int endIndex = measurer.getPosition();
  754. // skip over new line breaks (we paint 'clear' text runs not starting or ending with \n)
  755. if(endIndex < it.getEndIndex() && text.charAt(endIndex) == '\n'){
  756. measurer.setPosition(endIndex + 1);
  757. }
  758. TextAlign hAlign = getTextAlign();
  759. if(hAlign == TextAlign.JUSTIFY || hAlign == TextAlign.JUSTIFY_LOW) {
  760. layout = layout.getJustifiedLayout((float)wrappingWidth);
  761. }
  762. AttributedString str = new AttributedString(it, startIndex, endIndex);
  763. TextFragment line = new TextFragment(
  764. layout, // we will not paint empty paragraphs
  765. emptyParagraph ? null : str);
  766. _lines.add(line);
  767. _maxLineHeight = Math.max(_maxLineHeight, line.getHeight());
  768. if(endIndex == it.getEndIndex()) break;
  769. }
  770. if(isBullet() && !emptyParagraph) {
  771. String buCharacter = getBulletCharacter();
  772. String buFont = getBulletFont();
  773. if(buFont == null) buFont = getTextRuns().get(0).getFontFamily();
  774. if(buCharacter != null && buFont != null && _lines.size() > 0) {
  775. AttributedString str = new AttributedString(buCharacter);
  776. TextFragment firstLine = _lines.get(0);
  777. AttributedCharacterIterator bit = firstLine._str.getIterator();
  778. Color buColor = getBulletFontColor();
  779. str.addAttribute(TextAttribute.FOREGROUND, buColor == null ?
  780. bit.getAttribute(TextAttribute.FOREGROUND) : buColor);
  781. str.addAttribute(TextAttribute.FAMILY, buFont);
  782. float fontSize = (Float)bit.getAttribute(TextAttribute.SIZE);
  783. float buSz = (float)getBulletFontSize();
  784. if(buSz > 0) fontSize *= buSz* 0.01;
  785. else fontSize = -buSz;
  786. str.addAttribute(TextAttribute.SIZE, fontSize);
  787. TextLayout layout = new TextLayout(str.getIterator(), graphics.getFontRenderContext());
  788. _bullet = new TextFragment(layout, str);
  789. }
  790. }
  791. return _lines;
  792. }
  793. CTTextParagraphProperties getDefaultMasterStyle(){
  794. CTPlaceholder ph = _shape.getCTPlaceholder();
  795. String defaultStyleSelector;
  796. switch(ph.getType().intValue()){
  797. case STPlaceholderType.INT_TITLE:
  798. case STPlaceholderType.INT_CTR_TITLE:
  799. defaultStyleSelector = "titleStyle";
  800. break;
  801. case STPlaceholderType.INT_FTR:
  802. case STPlaceholderType.INT_SLD_NUM:
  803. case STPlaceholderType.INT_DT:
  804. defaultStyleSelector = "otherStyle";
  805. break;
  806. default:
  807. defaultStyleSelector = "bodyStyle";
  808. break;
  809. }
  810. int level = getLevel();
  811. // wind up and find the root master sheet which must be slide master
  812. XSLFSheet masterSheet = _shape.getSheet();
  813. while (masterSheet.getMasterSheet() != null){
  814. masterSheet = masterSheet.getMasterSheet();
  815. }
  816. XmlObject[] o = masterSheet.getXmlObject().selectPath(
  817. "declare namespace p='http://schemas.openxmlformats.org/presentationml/2006/main' " +
  818. "declare namespace a='http://schemas.openxmlformats.org/drawingml/2006/main' " +
  819. ".//p:txStyles/p:" + defaultStyleSelector +"/a:lvl" +(level+1)+ "pPr");
  820. if(o.length == 1){
  821. return (CTTextParagraphProperties)o[0];
  822. }
  823. throw new IllegalArgumentException("Failed to fetch default style for " +
  824. defaultStyleSelector + " and level=" + level);
  825. }
  826. private boolean fetchParagraphProperty(ParagraphPropertyFetcher visitor){
  827. boolean ok = false;
  828. if(_p.isSetPPr()) ok = visitor.fetch(_p.getPPr());
  829. if(!ok) {
  830. XSLFTextShape shape = getParentShape();
  831. ok = shape.fetchShapeProperty(visitor);
  832. if(!ok){
  833. CTPlaceholder ph = shape.getCTPlaceholder();
  834. if(ph == null){
  835. // if it is a plain text box then take defaults from presentation.xml
  836. XMLSlideShow ppt = getParentShape().getSheet().getSlideShow();
  837. CTTextParagraphProperties themeProps = ppt.getDefaultParagraphStyle(getLevel());
  838. if(themeProps != null) ok = visitor.fetch(themeProps);
  839. } else {
  840. // defaults for placeholders are defined in the slide master
  841. CTTextParagraphProperties defaultProps = getDefaultMasterStyle();
  842. if(defaultProps != null) ok = visitor.fetch(defaultProps);
  843. }
  844. }
  845. }
  846. return ok;
  847. }
  848. void copy(XSLFTextParagraph p){
  849. TextAlign srcAlign = p.getTextAlign();
  850. if(srcAlign != getTextAlign()){
  851. setTextAlign(srcAlign);
  852. }
  853. boolean isBullet = p.isBullet();
  854. if(isBullet != isBullet()){
  855. setBullet(isBullet);
  856. if(isBullet) {
  857. String buFont = p.getBulletFont();
  858. if(buFont != null && !buFont.equals(getBulletFont())){
  859. setBulletFont(buFont);
  860. }
  861. String buChar = p.getBulletCharacter();
  862. if(buChar != null && !buChar.equals(getBulletCharacter())){
  863. setBulletCharacter(buChar);
  864. }
  865. Color buColor = p.getBulletFontColor();
  866. if(buColor != null && !buColor.equals(getBulletFontColor())){
  867. setBulletFontColor(buColor);
  868. }
  869. double buSize = p.getBulletFontSize();
  870. if(buSize != getBulletFontSize()){
  871. setBulletFontSize(buSize);
  872. }
  873. }
  874. }
  875. double leftMargin = p.getLeftMargin();
  876. if(leftMargin != getLeftMargin()){
  877. setLeftMargin(leftMargin);
  878. }
  879. double indent = p.getIndent();
  880. if(indent != getIndent()){
  881. setIndent(indent);
  882. }
  883. double spaceAfter = p.getSpaceAfter();
  884. if(spaceAfter != getSpaceAfter()){
  885. setSpaceAfter(spaceAfter);
  886. }
  887. double spaceBefore = p.getSpaceBefore();
  888. if(spaceBefore != getSpaceBefore()){
  889. setSpaceBefore(spaceBefore);
  890. }
  891. double lineSpacing = p.getLineSpacing();
  892. if(lineSpacing != getLineSpacing()){
  893. setLineSpacing(lineSpacing);
  894. }
  895. List<XSLFTextRun> srcR = p.getTextRuns();
  896. List<XSLFTextRun> tgtR = getTextRuns();
  897. for(int i = 0; i < srcR.size(); i++){
  898. XSLFTextRun r1 = srcR.get(i);
  899. XSLFTextRun r2 = tgtR.get(i);
  900. r2.copy(r1);
  901. }
  902. }
  903. }