PageRenderTime 94ms CodeModel.GetById 29ms RepoModel.GetById 0ms app.codeStats 0ms

/pptx/src/org/apache/poi/xslf/usermodel/XSLFSheet.java

https://github.com/minstrelsy/POI-Android
Java | 555 lines | 362 code | 72 blank | 121 comment | 69 complexity | 06c77456c926d8545168347abe70a1d6 MD5 | raw file
  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 java.io.IOException;
  17. import java.io.OutputStream;
  18. import java.util.ArrayList;
  19. import java.util.HashMap;
  20. import java.util.Iterator;
  21. import java.util.List;
  22. import java.util.Map;
  23. import java.util.concurrent.atomic.AtomicBoolean;
  24. import java.util.regex.Pattern;
  25. import javax.xml.namespace.QName;
  26. import net.pbdavey.awt.Graphics2D;
  27. import org.apache.poi.POIXMLDocumentPart;
  28. import org.apache.poi.POIXMLException;
  29. import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
  30. import org.apache.poi.openxml4j.opc.PackagePart;
  31. import org.apache.poi.openxml4j.opc.PackageRelationship;
  32. import org.apache.poi.openxml4j.opc.TargetMode;
  33. import org.apache.poi.util.Beta;
  34. import org.apache.poi.util.Internal;
  35. import org.apache.xmlbeans.XmlObject;
  36. import org.apache.xmlbeans.XmlOptions;
  37. import org.openxmlformats.schemas.officeDocument.x2006.relationships.STRelationshipId;
  38. import org.openxmlformats.schemas.presentationml.x2006.main.CTCommonSlideData;
  39. import org.openxmlformats.schemas.presentationml.x2006.main.CTConnector;
  40. import org.openxmlformats.schemas.presentationml.x2006.main.CTGraphicalObjectFrame;
  41. import org.openxmlformats.schemas.presentationml.x2006.main.CTGroupShape;
  42. import org.openxmlformats.schemas.presentationml.x2006.main.CTPicture;
  43. import org.openxmlformats.schemas.presentationml.x2006.main.CTPlaceholder;
  44. import org.openxmlformats.schemas.presentationml.x2006.main.CTShape;
  45. import and.awt.geom.AffineTransform;
  46. import android.os.Handler;
  47. import android.os.Message;
  48. import android.util.Log;
  49. @Beta
  50. public abstract class XSLFSheet extends POIXMLDocumentPart implements XSLFShapeContainer {
  51. private XSLFCommonSlideData _commonSlideData;
  52. private XSLFDrawing _drawing;
  53. private List<XSLFShape> _shapes;
  54. private CTGroupShape _spTree;
  55. private List<XSLFTextShape>_placeholders;
  56. private Map<Integer, XSLFSimpleShape> _placeholderByIdMap;
  57. private Map<Integer, XSLFSimpleShape> _placeholderByTypeMap;
  58. public XSLFSheet() {
  59. super();
  60. }
  61. public XSLFSheet(PackagePart part, PackageRelationship rel){
  62. super(part, rel);
  63. }
  64. /**
  65. *
  66. * @return the XMLSlideShow this sheet belongs to
  67. */
  68. public XMLSlideShow getSlideShow() {
  69. POIXMLDocumentPart p = getParent();
  70. while(p != null) {
  71. if(p instanceof XMLSlideShow){
  72. return (XMLSlideShow)p;
  73. }
  74. p = p.getParent();
  75. }
  76. throw new IllegalStateException("SlideShow was not found");
  77. }
  78. protected List<XSLFShape> buildShapes(CTGroupShape spTree){
  79. List<XSLFShape> shapes = new ArrayList<XSLFShape>();
  80. for(XmlObject ch : spTree.selectPath("*")){
  81. if(ch instanceof CTShape){ // simple shape
  82. XSLFAutoShape shape = XSLFAutoShape.create((CTShape)ch, this);
  83. Log.d("textInset", "buildShapes: " + shape.getText() + ", x: " + shape.getAnchor().getX());
  84. shapes.add(shape);
  85. } else if (ch instanceof CTGroupShape){
  86. shapes.add(new XSLFGroupShape((CTGroupShape)ch, this));
  87. } else if (ch instanceof CTConnector){
  88. shapes.add(new XSLFConnectorShape((CTConnector)ch, this));
  89. } else if (ch instanceof CTPicture){
  90. shapes.add(new XSLFPictureShape((CTPicture)ch, this));
  91. } else if (ch instanceof CTGraphicalObjectFrame){
  92. XSLFGraphicFrame shape = XSLFGraphicFrame.create((CTGraphicalObjectFrame)ch, this);
  93. shapes.add(shape);
  94. }
  95. }
  96. return shapes;
  97. }
  98. /**
  99. * @return top-level Xml bean representing this sheet
  100. */
  101. public abstract XmlObject getXmlObject();
  102. @Internal
  103. public XSLFCommonSlideData getCommonSlideData() {
  104. return _commonSlideData;
  105. }
  106. protected void setCommonSlideData(CTCommonSlideData data) {
  107. if(data == null) {
  108. _commonSlideData = null;
  109. } else {
  110. _commonSlideData = new XSLFCommonSlideData(data);
  111. }
  112. }
  113. private XSLFDrawing getDrawing(){
  114. if(_drawing == null) {
  115. _drawing = new XSLFDrawing(this, getSpTree());
  116. }
  117. return _drawing;
  118. }
  119. private List<XSLFShape> getShapeList(){
  120. if(_shapes == null){
  121. _shapes = buildShapes(getSpTree());
  122. }
  123. return _shapes;
  124. }
  125. // shape factory methods
  126. public XSLFAutoShape createAutoShape(){
  127. List<XSLFShape> shapes = getShapeList();
  128. XSLFAutoShape sh = getDrawing().createAutoShape();
  129. shapes.add(sh);
  130. return sh;
  131. }
  132. public XSLFFreeformShape createFreeform(){
  133. List<XSLFShape> shapes = getShapeList();
  134. XSLFFreeformShape sh = getDrawing().createFreeform();
  135. shapes.add(sh);
  136. return sh;
  137. }
  138. public XSLFTextBox createTextBox(){
  139. List<XSLFShape> shapes = getShapeList();
  140. XSLFTextBox sh = getDrawing().createTextBox();
  141. shapes.add(sh);
  142. return sh;
  143. }
  144. public XSLFConnectorShape createConnector(){
  145. List<XSLFShape> shapes = getShapeList();
  146. XSLFConnectorShape sh = getDrawing().createConnector();
  147. shapes.add(sh);
  148. return sh;
  149. }
  150. public XSLFGroupShape createGroup(){
  151. List<XSLFShape> shapes = getShapeList();
  152. XSLFGroupShape sh = getDrawing().createGroup();
  153. shapes.add(sh);
  154. return sh;
  155. }
  156. public XSLFPictureShape createPicture(int pictureIndex){
  157. List<PackagePart> pics = getPackagePart().getPackage()
  158. .getPartsByName(Pattern.compile("/ppt/media/image" + (pictureIndex + 1) + ".*?"));
  159. if(pics.size() == 0) {
  160. throw new IllegalArgumentException("Picture with index=" + pictureIndex + " was not found");
  161. }
  162. PackagePart pic = pics.get(0);
  163. PackageRelationship rel = getPackagePart().addRelationship(
  164. pic.getPartName(), TargetMode.INTERNAL, XSLFRelation.IMAGES.getRelation());
  165. addRelation(rel.getId(), new XSLFPictureData(pic, rel));
  166. XSLFPictureShape sh = getDrawing().createPicture(rel.getId());
  167. sh.resize();
  168. getShapeList().add(sh);
  169. return sh;
  170. }
  171. public XSLFTable createTable(){
  172. List<XSLFShape> shapes = getShapeList();
  173. XSLFTable sh = getDrawing().createTable();
  174. shapes.add(sh);
  175. return sh;
  176. }
  177. /**
  178. * Returns an array containing all of the shapes in this sheet
  179. *
  180. * @return an array of all shapes in this sheet
  181. */
  182. public XSLFShape[] getShapes(){
  183. return getShapeList().toArray(new XSLFShape[_shapes.size()]);
  184. }
  185. /**
  186. * Returns an iterator over the shapes in this sheet
  187. *
  188. * @return an iterator over the shapes in this sheet
  189. */
  190. public Iterator<XSLFShape> iterator(){
  191. return getShapeList().iterator();
  192. }
  193. /**
  194. * Removes the specified shape from this sheet, if it is present
  195. * (optional operation). If this sheet does not contain the element,
  196. * it is unchanged.
  197. *
  198. * @param xShape shape to be removed from this sheet, if present
  199. * @return <tt>true</tt> if this sheet contained the specified element
  200. * @throws IllegalArgumentException if the type of the specified shape
  201. * is incompatible with this sheet (optional)
  202. */
  203. public boolean removeShape(XSLFShape xShape) {
  204. XmlObject obj = xShape.getXmlObject();
  205. CTGroupShape spTree = getSpTree();
  206. if(obj instanceof CTShape){
  207. spTree.getSpList().remove(obj);
  208. } else if (obj instanceof CTGroupShape){
  209. spTree.getGrpSpList().remove(obj);
  210. } else if (obj instanceof CTConnector){
  211. spTree.getCxnSpList().remove(obj);
  212. } else {
  213. throw new IllegalArgumentException("Unsupported shape: " + xShape);
  214. }
  215. return getShapeList().remove(xShape);
  216. }
  217. /**
  218. * Removes all of the elements from this container (optional operation).
  219. * The container will be empty after this call returns.
  220. */
  221. public void clear() {
  222. for(XSLFShape shape : getShapes()){
  223. removeShape(shape);
  224. }
  225. }
  226. protected abstract String getRootElementName();
  227. protected CTGroupShape getSpTree(){
  228. if(_spTree == null) {
  229. XmlObject root = getXmlObject();
  230. XmlObject[] sp = root.selectPath(
  231. "declare namespace p='http://schemas.openxmlformats.org/presentationml/2006/main' .//*/p:spTree");
  232. if(sp.length == 0) throw new IllegalStateException("CTGroupShape was not found");
  233. _spTree = (CTGroupShape)sp[0];
  234. }
  235. return _spTree;
  236. }
  237. protected final void commit() throws IOException {
  238. XmlOptions xmlOptions = new XmlOptions(DEFAULT_XML_OPTIONS);
  239. Map<String, String> map = new HashMap<String, String>();
  240. map.put(STRelationshipId.type.getName().getNamespaceURI(), "r");
  241. map.put("http://schemas.openxmlformats.org/drawingml/2006/main", "a");
  242. map.put("http://schemas.openxmlformats.org/presentationml/2006/main", "p");
  243. xmlOptions.setSaveSuggestedPrefixes(map);
  244. String docName = getRootElementName();
  245. if(docName != null) {
  246. xmlOptions.setSaveSyntheticDocumentElement(
  247. new QName("http://schemas.openxmlformats.org/presentationml/2006/main", docName));
  248. }
  249. PackagePart part = getPackagePart();
  250. OutputStream out = part.getOutputStream();
  251. getXmlObject().save(out, xmlOptions);
  252. out.close();
  253. }
  254. /**
  255. * Set the contents of this sheet to be a copy of the source sheet.
  256. * This method erases any existing shapes and replaces them with
  257. * object from the source sheet.
  258. *
  259. * @param src the source sheet to copy data from
  260. * @return modified 'this'
  261. */
  262. public XSLFSheet importContent(XSLFSheet src){
  263. _shapes = null;
  264. _spTree = null;
  265. _drawing = null;
  266. _spTree = null;
  267. // first copy the source xml
  268. getSpTree().set(src.getSpTree());
  269. // recursively update each shape
  270. List<XSLFShape> tgtShapes = getShapeList();
  271. List<XSLFShape> srcShapes = src.getShapeList();
  272. for(int i = 0; i < tgtShapes.size(); i++){
  273. XSLFShape s1 = srcShapes.get(i);
  274. XSLFShape s2 = tgtShapes.get(i);
  275. s2.copy(s1);
  276. }
  277. return this;
  278. }
  279. /**
  280. * Append content to this sheet.
  281. *
  282. * @param src the source sheet
  283. * @return modified <code>this</code>.
  284. */
  285. public XSLFSheet appendContent(XSLFSheet src){
  286. CTGroupShape spTree = getSpTree();
  287. int numShapes = getShapeList().size();
  288. CTGroupShape srcTree = src.getSpTree();
  289. for(XmlObject ch : srcTree.selectPath("*")){
  290. if(ch instanceof CTShape){ // simple shape
  291. spTree.addNewSp().set(ch);
  292. } else if (ch instanceof CTGroupShape){
  293. spTree.addNewGrpSp().set(ch);
  294. } else if (ch instanceof CTConnector){
  295. spTree.addNewCxnSp().set(ch);
  296. } else if (ch instanceof CTPicture){
  297. spTree.addNewPic().set(ch);
  298. } else if (ch instanceof CTGraphicalObjectFrame){
  299. spTree.addNewGraphicFrame().set(ch);
  300. }
  301. }
  302. _shapes = null;
  303. _spTree = null;
  304. _drawing = null;
  305. _spTree = null;
  306. // recursively update each shape
  307. List<XSLFShape> tgtShapes = getShapeList();
  308. List<XSLFShape> srcShapes = src.getShapeList();
  309. for(int i = 0; i < srcShapes.size(); i++){
  310. XSLFShape s1 = srcShapes.get(i);
  311. XSLFShape s2 = tgtShapes.get(numShapes + i);
  312. s2.copy(s1);
  313. }
  314. return this;
  315. }
  316. /**
  317. * @return theme (shared styles) associated with this theme.
  318. * By default returns <code>null</code> which means that this sheet is theme-less.
  319. * Sheets that support the notion of themes (slides, masters, layouts, etc.) should override this
  320. * method and return the corresponding package part.
  321. */
  322. XSLFTheme getTheme(){
  323. return null;
  324. }
  325. /**
  326. *
  327. * @return master of this sheet.
  328. */
  329. public abstract XSLFSheet getMasterSheet();
  330. protected XSLFTextShape getTextShapeByType(Placeholder type){
  331. for(XSLFShape shape : this.getShapes()){
  332. if(shape instanceof XSLFTextShape) {
  333. XSLFTextShape txt = (XSLFTextShape)shape;
  334. if(txt.getTextType() == type) {
  335. return txt;
  336. }
  337. }
  338. }
  339. return null;
  340. }
  341. XSLFSimpleShape getPlaceholder(CTPlaceholder ph) {
  342. XSLFSimpleShape shape = null;
  343. if(ph.isSetIdx()) shape = getPlaceholderById((int)ph.getIdx());
  344. if (shape == null && ph.isSetType()) {
  345. shape = getPlaceholderByType(ph.getType().intValue());
  346. }
  347. return shape;
  348. }
  349. void initPlaceholders() {
  350. if(_placeholders == null) {
  351. _placeholders = new ArrayList<XSLFTextShape>();
  352. _placeholderByIdMap = new HashMap<Integer, XSLFSimpleShape>();
  353. _placeholderByTypeMap = new HashMap<Integer, XSLFSimpleShape>();
  354. for(XSLFShape sh : getShapes()){
  355. if(sh instanceof XSLFTextShape){
  356. XSLFTextShape sShape = (XSLFTextShape)sh;
  357. CTPlaceholder ph = sShape.getCTPlaceholder();
  358. if(ph != null) {
  359. _placeholders.add(sShape);
  360. if(ph.isSetIdx()) {
  361. int idx = (int)ph.getIdx();
  362. _placeholderByIdMap.put(idx, sShape);
  363. }
  364. if(ph.isSetType()){
  365. _placeholderByTypeMap.put(ph.getType().intValue(), sShape);
  366. }
  367. }
  368. }
  369. }
  370. }
  371. }
  372. XSLFSimpleShape getPlaceholderById(int id) {
  373. initPlaceholders();
  374. return _placeholderByIdMap.get(id);
  375. }
  376. XSLFSimpleShape getPlaceholderByType(int ordinal) {
  377. initPlaceholders();
  378. return _placeholderByTypeMap.get(ordinal);
  379. }
  380. /**
  381. *
  382. * @param idx 0-based index of a placeholder in the sheet
  383. * @return placeholder
  384. */
  385. public XSLFTextShape getPlaceholder(int idx) {
  386. initPlaceholders();
  387. return _placeholders.get(idx);
  388. }
  389. /**
  390. *
  391. * @return all placeholder shapes in this sheet
  392. */
  393. public XSLFTextShape[] getPlaceholders() {
  394. initPlaceholders();
  395. return _placeholders.toArray(new XSLFTextShape[_placeholders.size()]);
  396. }
  397. /**
  398. * Checks if this <code>sheet</code> displays the specified shape.
  399. *
  400. * Subclasses can override it and skip certain shapes from drawings,
  401. * for instance, slide masters and layouts don't display placeholders
  402. */
  403. protected boolean canDraw(XSLFShape shape){
  404. return true;
  405. }
  406. /**
  407. *
  408. * @return whether shapes on the master sheet should be shown. By default master graphics is turned off.
  409. * Sheets that support the notion of master (slide, slideLayout) should override it and
  410. * check this setting in the sheet XML
  411. */
  412. public boolean getFollowMasterGraphics(){
  413. return false;
  414. }
  415. /**
  416. *
  417. * @return background for this sheet
  418. */
  419. public XSLFBackground getBackground() {
  420. return null;
  421. }
  422. /**
  423. * Render this sheet into the supplied graphics object
  424. *
  425. * @param graphics
  426. * @param position
  427. * @param handler
  428. * @param isCanceled
  429. */
  430. public void draw(Graphics2D graphics, AtomicBoolean isCanceled, Handler handler, int position){
  431. XSLFSheet master = getMasterSheet();
  432. if(getFollowMasterGraphics() && master != null) master.draw(graphics, isCanceled, handler, position);
  433. graphics.setRenderingHint(XSLFRenderingHint.GROUP_TRANSFORM, new AffineTransform());
  434. int i = 0;
  435. for(XSLFShape shape : getShapeList()) {
  436. if (isCanceled.get()) {
  437. Log.d("Slide", "Thread.Canceled");
  438. return;
  439. } else {
  440. handler.sendMessage(Message.obtain(handler, 1, i++, getShapeList().size(), Integer.valueOf(position)));
  441. }
  442. if(!canDraw(shape)) continue;
  443. // remember the initial transform and restore it after we are done with drawing
  444. AffineTransform at = graphics.getTransform();
  445. // concrete implementations can make sense of this hint,
  446. // for example PSGraphics2D or PDFGraphics2D would call gsave() / grestore
  447. graphics.setRenderingHint(XSLFRenderingHint.GSAVE, true);
  448. // apply rotation and flipping
  449. shape.applyTransform(graphics);
  450. // draw stuff
  451. shape.draw(graphics);
  452. // restore the coordinate system
  453. graphics.setTransform(at);
  454. graphics.setRenderingHint(XSLFRenderingHint.GRESTORE, true);
  455. }
  456. }
  457. /**
  458. * Import a picture data from another document.
  459. *
  460. * @param blipId ID of the package relationship to retrieve.
  461. * @param packagePart package part containing the data to import
  462. * @return ID of the created relationship
  463. */
  464. String importBlip(String blipId, PackagePart packagePart) {
  465. PackageRelationship blipRel = packagePart.getRelationship(blipId);
  466. PackagePart blipPart;
  467. try {
  468. blipPart = packagePart.getRelatedPart(blipRel);
  469. } catch (InvalidFormatException e){
  470. throw new POIXMLException(e);
  471. }
  472. XSLFPictureData data = new XSLFPictureData(blipPart, null);
  473. XMLSlideShow ppt = getSlideShow();
  474. int pictureIdx = ppt.addPicture(data.getData(), data.getPictureType());
  475. PackagePart pic = ppt.getAllPictures().get(pictureIdx).getPackagePart();
  476. PackageRelationship rel = getPackagePart().addRelationship(
  477. pic.getPartName(), TargetMode.INTERNAL, blipRel.getRelationshipType());
  478. addRelation(rel.getId(), new XSLFPictureData(pic, rel));
  479. return rel.getId();
  480. }
  481. }