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.

XSSFVMLDrawing.java 10KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261
  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.xssf.usermodel;
  16. import org.apache.poi.POIXMLDocumentPart;
  17. import org.apache.poi.openxml4j.opc.PackagePart;
  18. import org.apache.poi.openxml4j.opc.PackageRelationship;
  19. import org.apache.poi.xssf.util.EvilUnclosedBRFixingInputStream;
  20. import org.apache.xmlbeans.XmlException;
  21. import org.apache.xmlbeans.XmlOptions;
  22. import org.apache.xmlbeans.XmlObject;
  23. import org.apache.xmlbeans.XmlCursor;
  24. import org.w3c.dom.Node;
  25. import schemasMicrosoftComOfficeOffice.*;
  26. import javax.xml.namespace.QName;
  27. import java.io.*;
  28. import java.util.*;
  29. import java.util.regex.Pattern;
  30. import java.util.regex.Matcher;
  31. import java.math.BigInteger;
  32. import schemasMicrosoftComVml.*;
  33. import schemasMicrosoftComVml.STTrueFalse;
  34. import schemasMicrosoftComOfficeExcel.CTClientData;
  35. import schemasMicrosoftComOfficeExcel.STObjectType;
  36. /**
  37. * Represents a SpreadsheetML VML drawing.
  38. *
  39. * <p>
  40. * In Excel 2007 VML drawings are used to describe properties of cell comments,
  41. * although the spec says that VML is deprecated:
  42. * </p>
  43. * <p>
  44. * The VML format is a legacy format originally introduced with Office 2000 and is included and fully defined
  45. * in this Standard for backwards compatibility reasons. The DrawingML format is a newer and richer format
  46. * created with the goal of eventually replacing any uses of VML in the Office Open XML formats. VML should be
  47. * considered a deprecated format included in Office Open XML for legacy reasons only and new applications that
  48. * need a file format for drawings are strongly encouraged to use preferentially DrawingML
  49. * </p>
  50. *
  51. * <p>
  52. * Warning - Excel is known to put invalid XML into these files!
  53. * For example, &gt;br&lt; without being closed or escaped crops up.
  54. * </p>
  55. *
  56. * See 6.4 VML - SpreadsheetML Drawing in Office Open XML Part 4 - Markup Language Reference.pdf
  57. *
  58. * @author Yegor Kozlov
  59. */
  60. public final class XSSFVMLDrawing extends POIXMLDocumentPart {
  61. private static final QName QNAME_SHAPE_LAYOUT = new QName("urn:schemas-microsoft-com:office:office", "shapelayout");
  62. private static final QName QNAME_SHAPE_TYPE = new QName("urn:schemas-microsoft-com:vml", "shapetype");
  63. private static final QName QNAME_SHAPE = new QName("urn:schemas-microsoft-com:vml", "shape");
  64. /**
  65. * regexp to parse shape ids, in VML they have weird form of id="_x0000_s1026"
  66. */
  67. private static final Pattern ptrn_shapeId = Pattern.compile("_x0000_s(\\d+)");
  68. private List<QName> _qnames = new ArrayList<QName>();
  69. private List<XmlObject> _items = new ArrayList<XmlObject>();
  70. private String _shapeTypeId;
  71. private int _shapeId = 1024;
  72. /**
  73. * Create a new SpreadsheetML drawing
  74. *
  75. * @see XSSFSheet#createDrawingPatriarch()
  76. */
  77. protected XSSFVMLDrawing() {
  78. super();
  79. newDrawing();
  80. }
  81. /**
  82. * Construct a SpreadsheetML drawing from a package part
  83. *
  84. * @param part the package part holding the drawing data,
  85. * the content type must be <code>application/vnd.openxmlformats-officedocument.drawing+xml</code>
  86. * @param rel the package relationship holding this drawing,
  87. * the relationship type must be http://schemas.openxmlformats.org/officeDocument/2006/relationships/drawing
  88. */
  89. protected XSSFVMLDrawing(PackagePart part, PackageRelationship rel) throws IOException, XmlException {
  90. super(part, rel);
  91. read(getPackagePart().getInputStream());
  92. }
  93. protected void read(InputStream is) throws IOException, XmlException {
  94. XmlObject root = XmlObject.Factory.parse(
  95. new EvilUnclosedBRFixingInputStream(is)
  96. );
  97. _qnames = new ArrayList<QName>();
  98. _items = new ArrayList<XmlObject>();
  99. for(XmlObject obj : root.selectPath("$this/xml/*")) {
  100. Node nd = obj.getDomNode();
  101. QName qname = new QName(nd.getNamespaceURI(), nd.getLocalName());
  102. if (qname.equals(QNAME_SHAPE_LAYOUT)) {
  103. _items.add(CTShapeLayout.Factory.parse(obj.xmlText()));
  104. } else if (qname.equals(QNAME_SHAPE_TYPE)) {
  105. CTShapetype st = CTShapetype.Factory.parse(obj.xmlText());
  106. _items.add(st);
  107. _shapeTypeId = st.getId();
  108. } else if (qname.equals(QNAME_SHAPE)) {
  109. CTShape shape = CTShape.Factory.parse(obj.xmlText());
  110. String id = shape.getId();
  111. if(id != null) {
  112. Matcher m = ptrn_shapeId.matcher(id);
  113. if(m.find()) _shapeId = Math.max(_shapeId, Integer.parseInt(m.group(1)));
  114. }
  115. _items.add(shape);
  116. } else {
  117. _items.add(XmlObject.Factory.parse(obj.xmlText()));
  118. }
  119. _qnames.add(qname);
  120. }
  121. }
  122. protected List<XmlObject> getItems(){
  123. return _items;
  124. }
  125. protected void write(OutputStream out) throws IOException {
  126. XmlObject rootObject = XmlObject.Factory.newInstance();
  127. XmlCursor rootCursor = rootObject.newCursor();
  128. rootCursor.toNextToken();
  129. rootCursor.beginElement("xml");
  130. for(int i=0; i < _items.size(); i++){
  131. XmlCursor xc = _items.get(i).newCursor();
  132. rootCursor.beginElement(_qnames.get(i));
  133. while(xc.toNextToken() == XmlCursor.TokenType.ATTR) {
  134. Node anode = xc.getDomNode();
  135. rootCursor.insertAttributeWithValue(anode.getLocalName(), anode.getNamespaceURI(), anode.getNodeValue());
  136. }
  137. xc.toStartDoc();
  138. xc.copyXmlContents(rootCursor);
  139. rootCursor.toNextToken();
  140. xc.dispose();
  141. }
  142. rootCursor.dispose();
  143. XmlOptions xmlOptions = new XmlOptions(DEFAULT_XML_OPTIONS);
  144. xmlOptions.setSavePrettyPrint();
  145. HashMap<String, String> map = new HashMap<String, String>();
  146. map.put("urn:schemas-microsoft-com:vml", "v");
  147. map.put("urn:schemas-microsoft-com:office:office", "o");
  148. map.put("urn:schemas-microsoft-com:office:excel", "x");
  149. xmlOptions.setSaveSuggestedPrefixes(map);
  150. rootObject.save(out, xmlOptions);
  151. }
  152. @Override
  153. protected void commit() throws IOException {
  154. PackagePart part = getPackagePart();
  155. OutputStream out = part.getOutputStream();
  156. write(out);
  157. out.close();
  158. }
  159. /**
  160. * Initialize a new Speadsheet VML drawing
  161. */
  162. private void newDrawing(){
  163. CTShapeLayout layout = CTShapeLayout.Factory.newInstance();
  164. layout.setExt(STExt.EDIT);
  165. CTIdMap idmap = layout.addNewIdmap();
  166. idmap.setExt(STExt.EDIT);
  167. idmap.setData("1");
  168. _items.add(layout);
  169. _qnames.add(QNAME_SHAPE_LAYOUT);
  170. CTShapetype shapetype = CTShapetype.Factory.newInstance();
  171. _shapeTypeId = "_xssf_cell_comment";
  172. shapetype.setId(_shapeTypeId);
  173. shapetype.setCoordsize("21600,21600");
  174. shapetype.setSpt(202);
  175. shapetype.setPath2("m,l,21600r21600,l21600,xe");
  176. shapetype.addNewStroke().setJoinstyle(STStrokeJoinStyle.MITER);
  177. CTPath path = shapetype.addNewPath();
  178. path.setGradientshapeok(STTrueFalse.T);
  179. path.setConnecttype(STConnectType.RECT);
  180. _items.add(shapetype);
  181. _qnames.add(QNAME_SHAPE_TYPE);
  182. }
  183. protected CTShape newCommentShape(){
  184. CTShape shape = CTShape.Factory.newInstance();
  185. shape.setId("_x0000_s" + (++_shapeId));
  186. shape.setType("#" + _shapeTypeId);
  187. shape.setStyle("position:absolute; visibility:hidden");
  188. shape.setFillcolor("#ffffe1");
  189. shape.setInsetmode(STInsetMode.AUTO);
  190. shape.addNewFill().setColor("#ffffe1");
  191. CTShadow shadow = shape.addNewShadow();
  192. shadow.setOn(STTrueFalse.T);
  193. shadow.setColor("black");
  194. shadow.setObscured(STTrueFalse.T);
  195. shape.addNewPath().setConnecttype(STConnectType.NONE);
  196. shape.addNewTextbox().setStyle("mso-direction-alt:auto");
  197. CTClientData cldata = shape.addNewClientData();
  198. cldata.setObjectType(STObjectType.NOTE);
  199. cldata.addNewMoveWithCells();
  200. cldata.addNewSizeWithCells();
  201. cldata.addNewAnchor().setStringValue("1, 15, 0, 2, 3, 15, 3, 16");
  202. cldata.addNewAutoFill().setStringValue("False");
  203. cldata.addNewRow().setBigIntegerValue(new BigInteger("0"));
  204. cldata.addNewColumn().setBigIntegerValue(new BigInteger("0"));
  205. _items.add(shape);
  206. _qnames.add(QNAME_SHAPE);
  207. return shape;
  208. }
  209. /**
  210. * Find a shape with ClientData of type "NOTE" and the specified row and column
  211. *
  212. * @return the comment shape or <code>null</code>
  213. */
  214. protected CTShape findCommentShape(int row, int col){
  215. for(XmlObject itm : _items){
  216. if(itm instanceof CTShape){
  217. CTShape sh = (CTShape)itm;
  218. if(sh.sizeOfClientDataArray() > 0){
  219. CTClientData cldata = sh.getClientDataArray(0);
  220. if(cldata.getObjectType() == STObjectType.NOTE){
  221. int crow = cldata.getRowArray(0).intValue();
  222. int ccol = cldata.getColumnArray(0).intValue();
  223. if(crow == row && ccol == col) {
  224. return sh;
  225. }
  226. }
  227. }
  228. }
  229. }
  230. return null;
  231. }
  232. protected boolean removeCommentShape(int row, int col){
  233. CTShape shape = findCommentShape(row, col);
  234. return shape != null && _items.remove(shape);
  235. }
  236. }