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.

XWPFDocument.java 63KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814
  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.OutputStream;
  20. import java.util.ArrayList;
  21. import java.util.Arrays;
  22. import java.util.Collection;
  23. import java.util.Collections;
  24. import java.util.HashMap;
  25. import java.util.Iterator;
  26. import java.util.LinkedList;
  27. import java.util.List;
  28. import java.util.Map;
  29. import java.util.Spliterator;
  30. import javax.xml.namespace.QName;
  31. import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream;
  32. import org.apache.logging.log4j.LogManager;
  33. import org.apache.logging.log4j.Logger;
  34. import org.apache.poi.ooxml.POIXMLDocument;
  35. import org.apache.poi.ooxml.POIXMLDocumentPart;
  36. import org.apache.poi.ooxml.POIXMLException;
  37. import org.apache.poi.ooxml.POIXMLProperties;
  38. import org.apache.poi.ooxml.POIXMLRelation;
  39. import org.apache.poi.ooxml.util.IdentifierManager;
  40. import org.apache.poi.ooxml.util.PackageHelper;
  41. import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
  42. import org.apache.poi.openxml4j.exceptions.OpenXML4JException;
  43. import org.apache.poi.openxml4j.opc.OPCPackage;
  44. import org.apache.poi.openxml4j.opc.PackagePart;
  45. import org.apache.poi.openxml4j.opc.PackagePartName;
  46. import org.apache.poi.openxml4j.opc.PackageRelationship;
  47. import org.apache.poi.openxml4j.opc.PackageRelationshipTypes;
  48. import org.apache.poi.openxml4j.opc.PackagingURIHelper;
  49. import org.apache.poi.openxml4j.opc.TargetMode;
  50. import org.apache.poi.poifs.crypt.HashAlgorithm;
  51. import org.apache.poi.util.IOUtils;
  52. import org.apache.poi.util.Internal;
  53. import org.apache.poi.wp.usermodel.HeaderFooterType;
  54. import org.apache.poi.xddf.usermodel.chart.XDDFChart;
  55. import org.apache.poi.xwpf.model.XWPFHeaderFooterPolicy;
  56. import org.apache.xmlbeans.XmlCursor;
  57. import org.apache.xmlbeans.XmlException;
  58. import org.apache.xmlbeans.XmlObject;
  59. import org.apache.xmlbeans.XmlOptions;
  60. import org.openxmlformats.schemas.officeDocument.x2006.sharedTypes.STOnOff1;
  61. import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTBody;
  62. import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTDocument1;
  63. import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTFtnEdn;
  64. import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTOnOff;
  65. import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTP;
  66. import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTRow;
  67. import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTSdtBlock;
  68. import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTSectPr;
  69. import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTStyles;
  70. import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTbl;
  71. import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTc;
  72. import org.openxmlformats.schemas.wordprocessingml.x2006.main.CommentsDocument;
  73. import org.openxmlformats.schemas.wordprocessingml.x2006.main.DocumentDocument;
  74. import org.openxmlformats.schemas.wordprocessingml.x2006.main.EndnotesDocument;
  75. import org.openxmlformats.schemas.wordprocessingml.x2006.main.FootnotesDocument;
  76. import org.openxmlformats.schemas.wordprocessingml.x2006.main.NumberingDocument;
  77. import org.openxmlformats.schemas.wordprocessingml.x2006.main.STDocProtect;
  78. import org.openxmlformats.schemas.wordprocessingml.x2006.main.STHdrFtr;
  79. import org.openxmlformats.schemas.wordprocessingml.x2006.main.StylesDocument;
  80. /**
  81. * High(ish) level class for working with .docx files.
  82. * <p>
  83. * This class tries to hide some of the complexity
  84. * of the underlying file format, but as it's not a
  85. * mature and stable API yet, certain parts of the
  86. * XML structure come through. You'll therefore almost
  87. * certainly need to refer to the OOXML specifications
  88. * from
  89. * http://www.ecma-international.org/publications/standards/Ecma-376.htm
  90. * at some point in your use.
  91. */
  92. @SuppressWarnings("unused")
  93. public class XWPFDocument extends POIXMLDocument implements Document, IBody {
  94. private static final Logger LOG = LogManager.getLogger(XWPFDocument.class);
  95. protected List<XWPFFooter> footers = new ArrayList<>();
  96. protected List<XWPFHeader> headers = new ArrayList<>();
  97. protected List<XWPFHyperlink> hyperlinks = new ArrayList<>();
  98. protected List<XWPFParagraph> paragraphs = new ArrayList<>();
  99. protected List<XWPFTable> tables = new ArrayList<>();
  100. protected List<XWPFSDT> contentControls = new ArrayList<>();
  101. protected List<IBodyElement> bodyElements = new ArrayList<>();
  102. protected List<XWPFPictureData> pictures = new ArrayList<>();
  103. protected Map<Long, List<XWPFPictureData>> packagePictures = new HashMap<>();
  104. protected XWPFEndnotes endnotes;
  105. protected XWPFNumbering numbering;
  106. protected XWPFStyles styles;
  107. protected XWPFFootnotes footnotes;
  108. private CTDocument1 ctDocument;
  109. private XWPFSettings settings;
  110. private XWPFComments comments;
  111. protected final List<XWPFChart> charts = new ArrayList<>();
  112. /**
  113. * Keeps track on all id-values used in this document and included parts, like headers, footers, etc.
  114. */
  115. private final IdentifierManager drawingIdManager = new IdentifierManager(0L, 4294967295L);
  116. private final FootnoteEndnoteIdManager footnoteIdManager = new FootnoteEndnoteIdManager(this);
  117. /**
  118. * Handles the joy of different headers/footers for different pages
  119. */
  120. private XWPFHeaderFooterPolicy headerFooterPolicy;
  121. /**
  122. * @param pkg OPC package
  123. * @throws IOException
  124. * @throws POIXMLException a RuntimeException that can be caused by invalid OOXML data
  125. * @throws RuntimeException a number of other runtime exceptions can be thrown, especially if there are problems with the
  126. * input format
  127. */
  128. public XWPFDocument(OPCPackage pkg) throws IOException {
  129. super(pkg);
  130. //build a tree of POIXMLDocumentParts, this document being the root
  131. load(XWPFFactory.getInstance());
  132. }
  133. /**
  134. * @param is InputStream
  135. * @throws IOException
  136. * @throws POIXMLException a RuntimeException that can be caused by invalid OOXML data
  137. * @throws RuntimeException a number of other runtime exceptions can be thrown, especially if there are problems with the
  138. * input format
  139. */
  140. public XWPFDocument(InputStream is) throws IOException {
  141. super(PackageHelper.open(is));
  142. //build a tree of POIXMLDocumentParts, this workbook being the root
  143. load(XWPFFactory.getInstance());
  144. }
  145. public XWPFDocument() {
  146. super(newPackage());
  147. onDocumentCreate();
  148. }
  149. /**
  150. * Create a new WordProcessingML package and setup the default minimal content
  151. */
  152. protected static OPCPackage newPackage() {
  153. OPCPackage pkg = null;
  154. try {
  155. pkg = OPCPackage.create(new UnsynchronizedByteArrayOutputStream()); // NOSONAR - we do not want to close this here
  156. // Main part
  157. PackagePartName corePartName = PackagingURIHelper.createPartName(XWPFRelation.DOCUMENT.getDefaultFileName());
  158. // Create main part relationship
  159. pkg.addRelationship(corePartName, TargetMode.INTERNAL, PackageRelationshipTypes.CORE_DOCUMENT);
  160. // Create main document part
  161. pkg.createPart(corePartName, XWPFRelation.DOCUMENT.getContentType());
  162. pkg.getPackageProperties().setCreatorProperty(DOCUMENT_CREATOR);
  163. return pkg;
  164. } catch (Exception e) {
  165. IOUtils.closeQuietly(pkg);
  166. throw new POIXMLException(e);
  167. }
  168. }
  169. @SuppressWarnings("deprecation")
  170. @Override
  171. protected void onDocumentRead() throws IOException {
  172. try {
  173. DocumentDocument doc = DocumentDocument.Factory.parse(getPackagePart().getInputStream(), DEFAULT_XML_OPTIONS);
  174. ctDocument = doc.getDocument();
  175. initFootnotes();
  176. // parse the document with cursor and add
  177. // the XmlObject to its lists
  178. XmlCursor docCursor = ctDocument.newCursor();
  179. docCursor.selectPath("./*");
  180. while (docCursor.toNextSelection()) {
  181. XmlObject o = docCursor.getObject();
  182. if (o instanceof CTBody) {
  183. XmlCursor bodyCursor = o.newCursor();
  184. bodyCursor.selectPath("./*");
  185. while (bodyCursor.toNextSelection()) {
  186. XmlObject bodyObj = bodyCursor.getObject();
  187. if (bodyObj instanceof CTP) {
  188. XWPFParagraph p = new XWPFParagraph((CTP) bodyObj,
  189. this);
  190. bodyElements.add(p);
  191. paragraphs.add(p);
  192. } else if (bodyObj instanceof CTTbl) {
  193. XWPFTable t = new XWPFTable((CTTbl) bodyObj, this);
  194. bodyElements.add(t);
  195. tables.add(t);
  196. } else if (bodyObj instanceof CTSdtBlock) {
  197. XWPFSDT c = new XWPFSDT((CTSdtBlock) bodyObj, this);
  198. bodyElements.add(c);
  199. contentControls.add(c);
  200. }
  201. }
  202. bodyCursor.dispose();
  203. }
  204. }
  205. docCursor.dispose();
  206. // Sort out headers and footers
  207. if (doc.getDocument().getBody().getSectPr() != null) {
  208. headerFooterPolicy = new XWPFHeaderFooterPolicy(this);
  209. }
  210. // Create for each XML-part in the Package a PartClass
  211. for (RelationPart rp : getRelationParts()) {
  212. POIXMLDocumentPart p = rp.getDocumentPart();
  213. String relation = rp.getRelationship().getRelationshipType();
  214. if (relation.equals(XWPFRelation.STYLES.getRelation())) {
  215. this.styles = (XWPFStyles) p;
  216. this.styles.onDocumentRead();
  217. } else if (relation.equals(XWPFRelation.NUMBERING.getRelation())) {
  218. this.numbering = (XWPFNumbering) p;
  219. this.numbering.onDocumentRead();
  220. } else if (relation.equals(XWPFRelation.FOOTER.getRelation())) {
  221. XWPFFooter footer = (XWPFFooter) p;
  222. footers.add(footer);
  223. footer.onDocumentRead();
  224. } else if (relation.equals(XWPFRelation.HEADER.getRelation())) {
  225. XWPFHeader header = (XWPFHeader) p;
  226. headers.add(header);
  227. header.onDocumentRead();
  228. } else if (relation.equals(XWPFRelation.COMMENT.getRelation())) {
  229. this.comments = (XWPFComments) p;
  230. this.comments.onDocumentRead();
  231. } else if (relation.equals(XWPFRelation.SETTINGS.getRelation())) {
  232. settings = (XWPFSettings) p;
  233. settings.onDocumentRead();
  234. } else if (relation.equals(XWPFRelation.IMAGES.getRelation())) {
  235. XWPFPictureData picData = (XWPFPictureData) p;
  236. picData.onDocumentRead();
  237. registerPackagePictureData(picData);
  238. pictures.add(picData);
  239. } else if (relation.equals(XWPFRelation.CHART.getRelation())) {
  240. //now we can use all methods to modify charts in XWPFDocument
  241. XWPFChart chartData = (XWPFChart) p;
  242. charts.add(chartData);
  243. } else if (relation.equals(XWPFRelation.GLOSSARY_DOCUMENT.getRelation())) {
  244. // We don't currently process the glossary itself
  245. // Until we do, we do need to load the glossary child parts of it
  246. for (POIXMLDocumentPart gp : p.getRelations()) {
  247. // Trigger the onDocumentRead for all the child parts
  248. // Otherwise we'll hit issues on Styles, Settings etc on save
  249. // TODO: Refactor this to not need to access protected method
  250. // from other package! Remove the static helper method once fixed!!!
  251. POIXMLDocumentPart._invokeOnDocumentRead(gp);
  252. }
  253. }
  254. }
  255. initHyperlinks();
  256. } catch (XmlException e) {
  257. throw new POIXMLException(e);
  258. }
  259. }
  260. private void initHyperlinks() {
  261. // Get the hyperlinks
  262. // TODO: make me optional/separated in private function
  263. try {
  264. hyperlinks = new ArrayList<>();
  265. for (PackageRelationship rel : getPackagePart().getRelationshipsByType(XWPFRelation.HYPERLINK.getRelation())) {
  266. hyperlinks.add(new XWPFHyperlink(rel.getId(), rel.getTargetURI().toString()));
  267. }
  268. } catch (InvalidFormatException e) {
  269. throw new POIXMLException(e);
  270. }
  271. }
  272. private void initFootnotes() throws XmlException, IOException {
  273. for (RelationPart rp : getRelationParts()) {
  274. POIXMLDocumentPart p = rp.getDocumentPart();
  275. String relation = rp.getRelationship().getRelationshipType();
  276. if (relation.equals(XWPFRelation.FOOTNOTE.getRelation())) {
  277. this.footnotes = (XWPFFootnotes) p;
  278. this.footnotes.onDocumentRead();
  279. this.footnotes.setIdManager(footnoteIdManager);
  280. } else if (relation.equals(XWPFRelation.ENDNOTE.getRelation())) {
  281. this.endnotes = (XWPFEndnotes) p;
  282. this.endnotes.onDocumentRead();
  283. this.endnotes.setIdManager(footnoteIdManager);
  284. }
  285. }
  286. }
  287. /**
  288. * Create a new CTWorkbook with all values set to default
  289. */
  290. @Override
  291. protected void onDocumentCreate() {
  292. ctDocument = CTDocument1.Factory.newInstance();
  293. ctDocument.addNewBody();
  294. settings = (XWPFSettings) createRelationship(XWPFRelation.SETTINGS, XWPFFactory.getInstance());
  295. POIXMLProperties.ExtendedProperties expProps = getProperties().getExtendedProperties();
  296. expProps.getUnderlyingProperties().setApplication(DOCUMENT_CREATOR);
  297. }
  298. /**
  299. * Returns the low level document base object
  300. */
  301. @Internal
  302. public CTDocument1 getDocument() {
  303. return ctDocument;
  304. }
  305. IdentifierManager getDrawingIdManager() {
  306. return drawingIdManager;
  307. }
  308. /**
  309. * returns an Iterator with paragraphs and tables
  310. */
  311. @Override
  312. public List<IBodyElement> getBodyElements() {
  313. return Collections.unmodifiableList(bodyElements);
  314. }
  315. public Iterator<IBodyElement> getBodyElementsIterator() {
  316. return bodyElements.iterator();
  317. }
  318. /**
  319. * returns a Spliterator with paragraphs and tables
  320. *
  321. * @since POI 5.2.0
  322. */
  323. public Spliterator<IBodyElement> getBodyElementsSpliterator() {
  324. return bodyElements.spliterator();
  325. }
  326. @Override
  327. public List<XWPFParagraph> getParagraphs() {
  328. return Collections.unmodifiableList(paragraphs);
  329. }
  330. @Override
  331. public List<XWPFTable> getTables() {
  332. return Collections.unmodifiableList(tables);
  333. }
  334. /**
  335. * @return list of XWPFCharts in this document
  336. */
  337. public List<XWPFChart> getCharts() {
  338. return Collections.unmodifiableList(charts);
  339. }
  340. @Override
  341. public XWPFTable getTableArray(int pos) {
  342. if (pos >= 0 && pos < tables.size()) {
  343. return tables.get(pos);
  344. }
  345. return null;
  346. }
  347. /**
  348. * @return the list of footers
  349. */
  350. public List<XWPFFooter> getFooterList() {
  351. return Collections.unmodifiableList(footers);
  352. }
  353. public XWPFFooter getFooterArray(int pos) {
  354. if (pos >= 0 && pos < footers.size()) {
  355. return footers.get(pos);
  356. }
  357. return null;
  358. }
  359. /**
  360. * @return the list of headers
  361. */
  362. public List<XWPFHeader> getHeaderList() {
  363. return Collections.unmodifiableList(headers);
  364. }
  365. public XWPFHeader getHeaderArray(int pos) {
  366. if (pos >= 0 && pos < headers.size()) {
  367. return headers.get(pos);
  368. }
  369. return null;
  370. }
  371. public String getTblStyle(XWPFTable table) {
  372. return table.getStyleID();
  373. }
  374. public XWPFHyperlink getHyperlinkByID(String id) {
  375. for (XWPFHyperlink link : hyperlinks) {
  376. if (link.getId().equals(id)) {
  377. return link;
  378. }
  379. }
  380. // If the link was not found, rebuild the list (maybe a new link was added into the document) and check again.
  381. initHyperlinks();
  382. for (XWPFHyperlink link : hyperlinks) {
  383. if (link.getId().equals(id)) {
  384. return link;
  385. }
  386. }
  387. // Link still not there? Giving up.
  388. return null;
  389. }
  390. public XWPFFootnote getFootnoteByID(int id) {
  391. if (footnotes == null) {
  392. return null;
  393. }
  394. return (XWPFFootnote)footnotes.getFootnoteById(id);
  395. }
  396. public XWPFEndnote getEndnoteByID(int id) {
  397. if (endnotes == null) {
  398. return null;
  399. }
  400. return endnotes.getFootnoteById(id);
  401. }
  402. public List<XWPFFootnote> getFootnotes() {
  403. if (footnotes == null) {
  404. return Collections.emptyList();
  405. }
  406. return footnotes.getFootnotesList();
  407. }
  408. public XWPFHyperlink[] getHyperlinks() {
  409. return hyperlinks.toArray(new XWPFHyperlink[0]);
  410. }
  411. /**
  412. * Get Comments
  413. *
  414. * @return comments
  415. */
  416. public XWPFComments getDocComments() {
  417. return comments;
  418. }
  419. public XWPFComment getCommentByID(String id) {
  420. if (null == comments) {
  421. return null;
  422. }
  423. return comments.getCommentByID(id);
  424. }
  425. public XWPFComment[] getComments() {
  426. if (null == comments) {
  427. return null;
  428. }
  429. return comments.getComments().toArray(new XWPFComment[0]);
  430. }
  431. /**
  432. * Get the document part that's defined as the
  433. * given relationship of the core document.
  434. */
  435. public PackagePart getPartById(String id) {
  436. try {
  437. PackagePart corePart = getCorePart();
  438. return corePart.getRelatedPart(corePart.getRelationship(id));
  439. } catch (InvalidFormatException e) {
  440. throw new IllegalArgumentException(e);
  441. }
  442. }
  443. /**
  444. * Returns the policy on headers and footers, which
  445. * also provides a way to get at them.
  446. */
  447. public XWPFHeaderFooterPolicy getHeaderFooterPolicy() {
  448. return headerFooterPolicy;
  449. }
  450. public XWPFHeaderFooterPolicy createHeaderFooterPolicy() {
  451. if (headerFooterPolicy == null) {
  452. // if (! ctDocument.getBody().isSetSectPr()) {
  453. // ctDocument.getBody().addNewSectPr();
  454. // }
  455. headerFooterPolicy = new XWPFHeaderFooterPolicy(this);
  456. }
  457. return headerFooterPolicy;
  458. }
  459. /**
  460. * Create a header of the given type
  461. *
  462. * @param type {@link HeaderFooterType} enum
  463. * @return object of type {@link XWPFHeader}
  464. */
  465. public XWPFHeader createHeader(HeaderFooterType type) {
  466. XWPFHeaderFooterPolicy hfPolicy = createHeaderFooterPolicy();
  467. // TODO this needs to be migrated out into section code
  468. if (type == HeaderFooterType.FIRST) {
  469. CTSectPr ctSectPr = getSection();
  470. if (!ctSectPr.isSetTitlePg()) {
  471. CTOnOff titlePg = ctSectPr.addNewTitlePg();
  472. titlePg.setVal(STOnOff1.ON);
  473. }
  474. // } else if (type == HeaderFooterType.EVEN) {
  475. // TODO Add support for Even/Odd headings and footers
  476. }
  477. return hfPolicy.createHeader(STHdrFtr.Enum.forInt(type.toInt()));
  478. }
  479. /**
  480. * Create a footer of the given type
  481. *
  482. * @param type {@link HeaderFooterType} enum
  483. * @return object of type {@link XWPFFooter}
  484. */
  485. public XWPFFooter createFooter(HeaderFooterType type) {
  486. XWPFHeaderFooterPolicy hfPolicy = createHeaderFooterPolicy();
  487. // TODO this needs to be migrated out into section code
  488. if (type == HeaderFooterType.FIRST) {
  489. CTSectPr ctSectPr = getSection();
  490. if (!ctSectPr.isSetTitlePg()) {
  491. CTOnOff titlePg = ctSectPr.addNewTitlePg();
  492. titlePg.setVal(STOnOff1.ON);
  493. }
  494. // } else if (type == HeaderFooterType.EVEN) {
  495. // TODO Add support for Even/Odd headings and footers
  496. }
  497. return hfPolicy.createFooter(STHdrFtr.Enum.forInt(type.toInt()));
  498. }
  499. /**
  500. * Return the {@link CTSectPr} object that corresponds with the
  501. * last section in this document.
  502. *
  503. * @return {@link CTSectPr} object
  504. */
  505. private CTSectPr getSection() {
  506. CTBody ctBody = getDocument().getBody();
  507. return (ctBody.isSetSectPr() ?
  508. ctBody.getSectPr() :
  509. ctBody.addNewSectPr());
  510. }
  511. /**
  512. * Returns the styles object used
  513. */
  514. @Internal
  515. public CTStyles getStyle() throws XmlException, IOException {
  516. PackagePart[] parts;
  517. try {
  518. parts = getRelatedByType(XWPFRelation.STYLES.getRelation());
  519. } catch (InvalidFormatException e) {
  520. throw new IllegalStateException(e);
  521. }
  522. if (parts.length != 1) {
  523. throw new IllegalStateException("Expecting one Styles document part, but found " + parts.length);
  524. }
  525. StylesDocument sd = StylesDocument.Factory.parse(parts[0].getInputStream(), DEFAULT_XML_OPTIONS);
  526. return sd.getStyles();
  527. }
  528. /**
  529. * Get the document's embedded files.
  530. */
  531. @Override
  532. public List<PackagePart> getAllEmbeddedParts() throws OpenXML4JException {
  533. List<PackagePart> embedds = new LinkedList<>();
  534. // Get the embeddings for the workbook
  535. PackagePart part = getPackagePart();
  536. for (PackageRelationship rel : getPackagePart().getRelationshipsByType(OLE_OBJECT_REL_TYPE)) {
  537. embedds.add(part.getRelatedPart(rel));
  538. }
  539. for (PackageRelationship rel : getPackagePart().getRelationshipsByType(PACK_OBJECT_REL_TYPE)) {
  540. embedds.add(part.getRelatedPart(rel));
  541. }
  542. return embedds;
  543. }
  544. /**
  545. * Finds that for example the 2nd entry in the body list is the 1st paragraph
  546. */
  547. private int getBodyElementSpecificPos(int pos, List<? extends IBodyElement> list) {
  548. // If there's nothing to find, skip it
  549. if (list.size() == 0) {
  550. return -1;
  551. }
  552. if (pos >= 0 && pos < bodyElements.size()) {
  553. // Ensure the type is correct
  554. IBodyElement needle = bodyElements.get(pos);
  555. if (needle.getElementType() != list.get(0).getElementType()) {
  556. // Wrong type
  557. return -1;
  558. }
  559. // Work back until we find it
  560. int startPos = Math.min(pos, list.size() - 1);
  561. for (int i = startPos; i >= 0; i--) {
  562. if (list.get(i) == needle) {
  563. return i;
  564. }
  565. }
  566. }
  567. // Couldn't be found
  568. return -1;
  569. }
  570. /**
  571. * Look up the paragraph at the specified position in the body elements list
  572. * and return this paragraphs position in the paragraphs list
  573. *
  574. * @param pos The position of the relevant paragraph in the body elements
  575. * list
  576. * @return the position of the paragraph in the paragraphs list, if there is
  577. * a paragraph at the position in the bodyelements list. Else it
  578. * will return -1
  579. */
  580. public int getParagraphPos(int pos) {
  581. return getBodyElementSpecificPos(pos, paragraphs);
  582. }
  583. /**
  584. * get with the position of a table in the bodyelement array list
  585. * the position of this table in the table array list
  586. *
  587. * @param pos position of the table in the bodyelement array list
  588. * @return if there is a table at the position in the bodyelement array list,
  589. * else it will return null.
  590. */
  591. public int getTablePos(int pos) {
  592. return getBodyElementSpecificPos(pos, tables);
  593. }
  594. /**
  595. * Add a new paragraph at position of the cursor. The cursor must be on the
  596. * {@link XmlCursor.TokenType#START} tag of an subelement
  597. * of the documents body. When this method is done, the cursor passed as
  598. * parameter points to the {@link XmlCursor.TokenType#END}
  599. * of the newly inserted paragraph.
  600. *
  601. * @param cursor The cursor-position where the new paragraph should be added.
  602. * @return the {@link XWPFParagraph} object representing the newly inserted
  603. * CTP object
  604. */
  605. @Override
  606. public XWPFParagraph insertNewParagraph(XmlCursor cursor) {
  607. if (isCursorInBody(cursor)) {
  608. String uri = CTP.type.getName().getNamespaceURI();
  609. /*
  610. * TODO DO not use a coded constant, find the constant in the OOXML
  611. * classes instead, as the child of type CT_Paragraph is defined in the
  612. * OOXML schema as 'p'
  613. */
  614. String localPart = "p";
  615. // creates a new Paragraph, cursor is positioned inside the new
  616. // element
  617. cursor.beginElement(localPart, uri);
  618. // move the cursor to the START token to the paragraph just created
  619. cursor.toParent();
  620. CTP p = (CTP) cursor.getObject();
  621. XWPFParagraph newP = new XWPFParagraph(p, this);
  622. XmlObject o = null;
  623. /*
  624. * move the cursor to the previous element until a) the next
  625. * paragraph is found or b) all elements have been passed
  626. */
  627. while (!(o instanceof CTP) && (cursor.toPrevSibling())) {
  628. o = cursor.getObject();
  629. }
  630. /*
  631. * if the object that has been found is a) not a paragraph or b) is
  632. * the paragraph that has just been inserted, as the cursor in the
  633. * while loop above was not moved as there were no other siblings,
  634. * then the paragraph that was just inserted is the first paragraph
  635. * in the body. Otherwise, take the previous paragraph and calculate
  636. * the new index for the new paragraph.
  637. */
  638. if ((!(o instanceof CTP)) || o == p) {
  639. paragraphs.add(0, newP);
  640. } else {
  641. int pos = paragraphs.indexOf(getParagraph((CTP) o)) + 1;
  642. paragraphs.add(pos, newP);
  643. }
  644. /*
  645. * create a new cursor, that points to the START token of the just
  646. * inserted paragraph
  647. */
  648. XmlCursor newParaPos = p.newCursor();
  649. try {
  650. /*
  651. * Calculate the paragraphs index in the list of all body
  652. * elements
  653. */
  654. int i = 0;
  655. cursor.toCursor(newParaPos);
  656. while (cursor.toPrevSibling()) {
  657. o = cursor.getObject();
  658. if (o instanceof CTP || o instanceof CTTbl) {
  659. i++;
  660. }
  661. }
  662. bodyElements.add(i, newP);
  663. cursor.toCursor(newParaPos);
  664. cursor.toEndToken();
  665. return newP;
  666. } finally {
  667. newParaPos.dispose();
  668. }
  669. }
  670. return null;
  671. }
  672. @Override
  673. public XWPFTable insertNewTbl(XmlCursor cursor) {
  674. if (isCursorInBody(cursor)) {
  675. String uri = CTTbl.type.getName().getNamespaceURI();
  676. String localPart = "tbl";
  677. cursor.beginElement(localPart, uri);
  678. cursor.toParent();
  679. CTTbl t = (CTTbl) cursor.getObject();
  680. XWPFTable newT = new XWPFTable(t, this);
  681. XmlObject o = null;
  682. while (!(o instanceof CTTbl) && (cursor.toPrevSibling())) {
  683. o = cursor.getObject();
  684. }
  685. if (!(o instanceof CTTbl)) {
  686. tables.add(0, newT);
  687. } else {
  688. int pos = tables.indexOf(getTable((CTTbl) o)) + 1;
  689. tables.add(pos, newT);
  690. }
  691. int i = 0;
  692. XmlCursor tableCursor = t.newCursor();
  693. try {
  694. cursor.toCursor(tableCursor);
  695. while (cursor.toPrevSibling()) {
  696. o = cursor.getObject();
  697. if (o instanceof CTP || o instanceof CTTbl) {
  698. i++;
  699. }
  700. }
  701. bodyElements.add(i, newT);
  702. cursor.toCursor(tableCursor);
  703. cursor.toEndToken();
  704. return newT;
  705. } finally {
  706. tableCursor.dispose();
  707. }
  708. }
  709. return null;
  710. }
  711. /**
  712. * verifies that cursor is on the right position
  713. */
  714. private boolean isCursorInBody(XmlCursor cursor) {
  715. XmlCursor verify = cursor.newCursor();
  716. verify.toParent();
  717. boolean result = (verify.getObject() == this.ctDocument.getBody());
  718. verify.dispose();
  719. return result;
  720. }
  721. private int getPosOfBodyElement(IBodyElement needle) {
  722. BodyElementType type = needle.getElementType();
  723. IBodyElement current;
  724. for (int i = 0; i < bodyElements.size(); i++) {
  725. current = bodyElements.get(i);
  726. if (current.getElementType() == type) {
  727. if (current.equals(needle)) {
  728. return i;
  729. }
  730. }
  731. }
  732. return -1;
  733. }
  734. /**
  735. * Get the position of the paragraph, within the list
  736. * of all the body elements.
  737. *
  738. * @param p The paragraph to find
  739. * @return The location, or -1 if the paragraph couldn't be found
  740. */
  741. public int getPosOfParagraph(XWPFParagraph p) {
  742. return getPosOfBodyElement(p);
  743. }
  744. /**
  745. * Get the position of the table, within the list of
  746. * all the body elements.
  747. *
  748. * @param t The table to find
  749. * @return The location, or -1 if the table couldn't be found
  750. */
  751. public int getPosOfTable(XWPFTable t) {
  752. return getPosOfBodyElement(t);
  753. }
  754. /**
  755. * commit and saves the document
  756. */
  757. @Override
  758. protected void commit() throws IOException {
  759. XmlOptions xmlOptions = new XmlOptions(DEFAULT_XML_OPTIONS);
  760. xmlOptions.setSaveSyntheticDocumentElement(new QName(CTDocument1.type.getName().getNamespaceURI(), "document"));
  761. PackagePart part = getPackagePart();
  762. try (OutputStream out = part.getOutputStream()) {
  763. ctDocument.save(out, xmlOptions);
  764. }
  765. }
  766. /**
  767. * Gets the index of the relation we're trying to create
  768. */
  769. private int getRelationIndex(XWPFRelation relation) {
  770. int i = 1;
  771. for (RelationPart rp : getRelationParts()) {
  772. if (rp.getRelationship().getRelationshipType().equals(relation.getRelation())) {
  773. i++;
  774. }
  775. }
  776. return i;
  777. }
  778. /**
  779. * Appends a new paragraph to this document
  780. *
  781. * @return a new paragraph
  782. */
  783. public XWPFParagraph createParagraph() {
  784. XWPFParagraph p = new XWPFParagraph(ctDocument.getBody().addNewP(), this);
  785. bodyElements.add(p);
  786. paragraphs.add(p);
  787. return p;
  788. }
  789. /**
  790. * Creates an empty comments for the document if one does not already exist
  791. *
  792. * @return comments
  793. */
  794. public XWPFComments createComments() {
  795. if (comments == null) {
  796. CommentsDocument commentsDoc = CommentsDocument.Factory.newInstance();
  797. XWPFRelation relation = XWPFRelation.COMMENT;
  798. int i = getRelationIndex(relation);
  799. XWPFComments wrapper = (XWPFComments) createRelationship(relation, XWPFFactory.getInstance(), i);
  800. wrapper.setCtComments(commentsDoc.addNewComments());
  801. wrapper.setXWPFDocument(getXWPFDocument());
  802. comments = wrapper;
  803. }
  804. return comments;
  805. }
  806. /**
  807. * Creates an empty numbering if one does not already exist and sets the numbering member
  808. *
  809. * @return numbering
  810. */
  811. public XWPFNumbering createNumbering() {
  812. if (numbering == null) {
  813. NumberingDocument numberingDoc = NumberingDocument.Factory.newInstance();
  814. XWPFRelation relation = XWPFRelation.NUMBERING;
  815. int i = getRelationIndex(relation);
  816. XWPFNumbering wrapper = (XWPFNumbering) createRelationship(relation, XWPFFactory.getInstance(), i);
  817. wrapper.setNumbering(numberingDoc.addNewNumbering());
  818. numbering = wrapper;
  819. }
  820. return numbering;
  821. }
  822. /**
  823. * Creates an empty styles for the document if one does not already exist
  824. *
  825. * @return styles
  826. */
  827. public XWPFStyles createStyles() {
  828. if (styles == null) {
  829. StylesDocument stylesDoc = StylesDocument.Factory.newInstance();
  830. XWPFRelation relation = XWPFRelation.STYLES;
  831. int i = getRelationIndex(relation);
  832. XWPFStyles wrapper = (XWPFStyles) createRelationship(relation, XWPFFactory.getInstance(), i);
  833. wrapper.setStyles(stylesDoc.addNewStyles());
  834. styles = wrapper;
  835. }
  836. return styles;
  837. }
  838. /**
  839. * Creates an empty footnotes element for the document if one does not already exist
  840. *
  841. * @return footnotes
  842. */
  843. public XWPFFootnotes createFootnotes() {
  844. if (footnotes == null) {
  845. FootnotesDocument footnotesDoc = FootnotesDocument.Factory.newInstance();
  846. XWPFRelation relation = XWPFRelation.FOOTNOTE;
  847. int i = getRelationIndex(relation);
  848. XWPFFootnotes wrapper = (XWPFFootnotes) createRelationship(relation, XWPFFactory.getInstance(), i);
  849. wrapper.setFootnotes(footnotesDoc.addNewFootnotes());
  850. wrapper.setIdManager(this.footnoteIdManager);
  851. footnotes = wrapper;
  852. }
  853. return footnotes;
  854. }
  855. /**
  856. * Add a CTFtnEdn footnote to the document.
  857. *
  858. * @param note CTFtnEnd to be added.
  859. * @return New {@link XWPFFootnote}
  860. */
  861. @Internal
  862. public XWPFFootnote addFootnote(CTFtnEdn note) {
  863. return footnotes.addFootnote(note);
  864. }
  865. /**
  866. * Add a CTFtnEdn endnote to the document.
  867. *
  868. * @param note CTFtnEnd to be added.
  869. * @return New {@link XWPFEndnote}
  870. */
  871. @Internal
  872. public XWPFEndnote addEndnote(CTFtnEdn note) {
  873. XWPFEndnote endnote = new XWPFEndnote(this, note);
  874. endnotes.addEndnote(note);
  875. return endnote;
  876. }
  877. /**
  878. * remove a BodyElement from bodyElements array list
  879. *
  880. * @return true if removing was successfully, else return false
  881. */
  882. public boolean removeBodyElement(int pos) {
  883. if (pos >= 0 && pos < bodyElements.size()) {
  884. BodyElementType type = bodyElements.get(pos).getElementType();
  885. if (type == BodyElementType.TABLE) {
  886. int tablePos = getTablePos(pos);
  887. tables.remove(tablePos);
  888. ctDocument.getBody().removeTbl(tablePos);
  889. }
  890. if (type == BodyElementType.PARAGRAPH) {
  891. int paraPos = getParagraphPos(pos);
  892. paragraphs.remove(paraPos);
  893. ctDocument.getBody().removeP(paraPos);
  894. }
  895. bodyElements.remove(pos);
  896. return true;
  897. }
  898. return false;
  899. }
  900. /**
  901. * copies content of a paragraph to a existing paragraph in the list paragraphs at position pos
  902. */
  903. public void setParagraph(XWPFParagraph paragraph, int pos) {
  904. paragraphs.set(pos, paragraph);
  905. ctDocument.getBody().setPArray(pos, paragraph.getCTP());
  906. /* TODO update body element, update xwpf element, verify that
  907. * incoming paragraph belongs to this document or if not, XML was
  908. * copied properly (namespace-abbreviations, etc.)
  909. */
  910. }
  911. /**
  912. * @return the LastParagraph of the document
  913. */
  914. public XWPFParagraph getLastParagraph() {
  915. int lastPos = paragraphs.toArray().length - 1;
  916. return paragraphs.get(lastPos);
  917. }
  918. /**
  919. * Create an empty table with one row and one column as default.
  920. *
  921. * @return a new table
  922. */
  923. public XWPFTable createTable() {
  924. XWPFTable table = new XWPFTable(ctDocument.getBody().addNewTbl(), this);
  925. bodyElements.add(table);
  926. tables.add(table);
  927. return table;
  928. }
  929. /**
  930. * Create an empty table with a number of rows and cols specified
  931. */
  932. public XWPFTable createTable(int rows, int cols) {
  933. XWPFTable table = new XWPFTable(ctDocument.getBody().addNewTbl(), this, rows, cols);
  934. bodyElements.add(table);
  935. tables.add(table);
  936. return table;
  937. }
  938. /**
  939. *
  940. */
  941. public void createTOC() {
  942. CTSdtBlock block = this.getDocument().getBody().addNewSdt();
  943. TOC toc = new TOC(block);
  944. for (XWPFParagraph par : paragraphs) {
  945. String parStyle = par.getStyle();
  946. if (parStyle != null && parStyle.startsWith("Heading")) {
  947. try {
  948. int level = Integer.parseInt(parStyle.substring("Heading".length()));
  949. toc.addRow(level, par.getText(), 1, "112723803");
  950. } catch (NumberFormatException e) {
  951. LOG.atError().withThrowable(e).log("can't format number in TOC heading");
  952. }
  953. }
  954. }
  955. }
  956. /**
  957. * Replace content of table in array tables at position pos with a
  958. */
  959. public void setTable(int pos, XWPFTable table) {
  960. tables.set(pos, table);
  961. ctDocument.getBody().setTblArray(pos, table.getCTTbl());
  962. }
  963. /**
  964. * Verifies that the documentProtection tag in settings.xml file <br>
  965. * specifies that the protection is enforced (w:enforcement="1") <br>
  966. * <br>
  967. * sample snippet from settings.xml
  968. * <pre>
  969. * &lt;w:settings ... &gt;
  970. * &lt;w:documentProtection w:edit=&quot;readOnly&quot; w:enforcement=&quot;1&quot;/&gt;
  971. * </pre>
  972. *
  973. * @return true if documentProtection is enforced with option any
  974. */
  975. public boolean isEnforcedProtection() {
  976. return settings.isEnforcedWith();
  977. }
  978. /**
  979. * Verifies that the documentProtection tag in settings.xml file <br>
  980. * specifies that the protection is enforced (w:enforcement="1") <br>
  981. * and that the kind of protection is readOnly (w:edit="readOnly")<br>
  982. * <br>
  983. * sample snippet from settings.xml
  984. * <pre>
  985. * &lt;w:settings ... &gt;
  986. * &lt;w:documentProtection w:edit=&quot;readOnly&quot; w:enforcement=&quot;1&quot;/&gt;
  987. * </pre>
  988. *
  989. * @return true if documentProtection is enforced with option readOnly
  990. */
  991. public boolean isEnforcedReadonlyProtection() {
  992. return settings.isEnforcedWith(STDocProtect.READ_ONLY);
  993. }
  994. /**
  995. * Verifies that the documentProtection tag in settings.xml file <br>
  996. * specifies that the protection is enforced (w:enforcement="1") <br>
  997. * and that the kind of protection is forms (w:edit="forms")<br>
  998. * <br>
  999. * sample snippet from settings.xml
  1000. * <pre>
  1001. * &lt;w:settings ... &gt;
  1002. * &lt;w:documentProtection w:edit=&quot;forms&quot; w:enforcement=&quot;1&quot;/&gt;
  1003. * </pre>
  1004. *
  1005. * @return true if documentProtection is enforced with option forms
  1006. */
  1007. public boolean isEnforcedFillingFormsProtection() {
  1008. return settings.isEnforcedWith(STDocProtect.FORMS);
  1009. }
  1010. /**
  1011. * Verifies that the documentProtection tag in settings.xml file <br>
  1012. * specifies that the protection is enforced (w:enforcement="1") <br>
  1013. * and that the kind of protection is comments (w:edit="comments")<br>
  1014. * <br>
  1015. * sample snippet from settings.xml
  1016. * <pre>
  1017. * &lt;w:settings ... &gt;
  1018. * &lt;w:documentProtection w:edit=&quot;comments&quot; w:enforcement=&quot;1&quot;/&gt;
  1019. * </pre>
  1020. *
  1021. * @return true if documentProtection is enforced with option comments
  1022. */
  1023. public boolean isEnforcedCommentsProtection() {
  1024. return settings.isEnforcedWith(STDocProtect.COMMENTS);
  1025. }
  1026. /**
  1027. * Verifies that the documentProtection tag in settings.xml file <br>
  1028. * specifies that the protection is enforced (w:enforcement="1") <br>
  1029. * and that the kind of protection is trackedChanges (w:edit="trackedChanges")<br>
  1030. * <br>
  1031. * sample snippet from settings.xml
  1032. * <pre>
  1033. * &lt;w:settings ... &gt;
  1034. * &lt;w:documentProtection w:edit=&quot;trackedChanges&quot; w:enforcement=&quot;1&quot;/&gt;
  1035. * </pre>
  1036. *
  1037. * @return true if documentProtection is enforced with option trackedChanges
  1038. */
  1039. public boolean isEnforcedTrackedChangesProtection() {
  1040. return settings.isEnforcedWith(STDocProtect.TRACKED_CHANGES);
  1041. }
  1042. public boolean isEnforcedUpdateFields() {
  1043. return settings.isUpdateFields();
  1044. }
  1045. /**
  1046. * Enforces the readOnly protection.<br>
  1047. * In the documentProtection tag inside settings.xml file, <br>
  1048. * it sets the value of enforcement to "1" (w:enforcement="1") <br>
  1049. * and the value of edit to readOnly (w:edit="readOnly")<br>
  1050. * <br>
  1051. * sample snippet from settings.xml
  1052. * <pre>
  1053. * &lt;w:settings ... &gt;
  1054. * &lt;w:documentProtection w:edit=&quot;readOnly&quot; w:enforcement=&quot;1&quot;/&gt;
  1055. * </pre>
  1056. */
  1057. public void enforceReadonlyProtection() {
  1058. settings.setEnforcementEditValue(STDocProtect.READ_ONLY);
  1059. }
  1060. /**
  1061. * Enforces the readOnly protection with a password.<br>
  1062. * <br>
  1063. * sample snippet from settings.xml
  1064. * <pre>
  1065. * &lt;w:documentProtection w:edit=&quot;readOnly&quot; w:enforcement=&quot;1&quot;
  1066. * w:cryptProviderType=&quot;rsaAES&quot; w:cryptAlgorithmClass=&quot;hash&quot;
  1067. * w:cryptAlgorithmType=&quot;typeAny&quot; w:cryptAlgorithmSid=&quot;14&quot;
  1068. * w:cryptSpinCount=&quot;100000&quot; w:hash=&quot;...&quot; w:salt=&quot;....&quot;
  1069. * /&gt;
  1070. * </pre>
  1071. *
  1072. * @param password the plaintext password, if null no password will be applied
  1073. * @param hashAlgo the hash algorithm - only md2, m5, sha1, sha256, sha384 and sha512 are supported.
  1074. * if null, it will default default to sha1
  1075. */
  1076. public void enforceReadonlyProtection(String password, HashAlgorithm hashAlgo) {
  1077. settings.setEnforcementEditValue(STDocProtect.READ_ONLY, password, hashAlgo);
  1078. }
  1079. /**
  1080. * Enforce the Filling Forms protection.<br>
  1081. * In the documentProtection tag inside settings.xml file, <br>
  1082. * it sets the value of enforcement to "1" (w:enforcement="1") <br>
  1083. * and the value of edit to forms (w:edit="forms")<br>
  1084. * <br>
  1085. * sample snippet from settings.xml
  1086. * <pre>
  1087. * &lt;w:settings ... &gt;
  1088. * &lt;w:documentProtection w:edit=&quot;forms&quot; w:enforcement=&quot;1&quot;/&gt;
  1089. * </pre>
  1090. */
  1091. public void enforceFillingFormsProtection() {
  1092. settings.setEnforcementEditValue(STDocProtect.FORMS);
  1093. }
  1094. /**
  1095. * Enforce the Filling Forms protection.<br>
  1096. * <br>
  1097. * sample snippet from settings.xml
  1098. * <pre>
  1099. * &lt;w:documentProtection w:edit=&quot;forms&quot; w:enforcement=&quot;1&quot;
  1100. * w:cryptProviderType=&quot;rsaAES&quot; w:cryptAlgorithmClass=&quot;hash&quot;
  1101. * w:cryptAlgorithmType=&quot;typeAny&quot; w:cryptAlgorithmSid=&quot;14&quot;
  1102. * w:cryptSpinCount=&quot;100000&quot; w:hash=&quot;...&quot; w:salt=&quot;....&quot;
  1103. * /&gt;
  1104. * </pre>
  1105. *
  1106. * @param password the plaintext password, if null no password will be applied
  1107. * @param hashAlgo the hash algorithm - only md2, m5, sha1, sha256, sha384 and sha512 are supported.
  1108. * if null, it will default default to sha1
  1109. */
  1110. public void enforceFillingFormsProtection(String password, HashAlgorithm hashAlgo) {
  1111. settings.setEnforcementEditValue(STDocProtect.FORMS, password, hashAlgo);
  1112. }
  1113. /**
  1114. * Enforce the Comments protection.<br>
  1115. * In the documentProtection tag inside settings.xml file,<br>
  1116. * it sets the value of enforcement to "1" (w:enforcement="1") <br>
  1117. * and the value of edit to comments (w:edit="comments")<br>
  1118. * <br>
  1119. * sample snippet from settings.xml
  1120. * <pre>
  1121. * &lt;w:settings ... &gt;
  1122. * &lt;w:documentProtection w:edit=&quot;comments&quot; w:enforcement=&quot;1&quot;/&gt;
  1123. * </pre>
  1124. */
  1125. public void enforceCommentsProtection() {
  1126. settings.setEnforcementEditValue(STDocProtect.COMMENTS);
  1127. }
  1128. /**
  1129. * Enforce the Comments protection.<br>
  1130. * <br>
  1131. * sample snippet from settings.xml
  1132. * <pre>
  1133. * &lt;w:documentProtection w:edit=&quot;comments&quot; w:enforcement=&quot;1&quot;
  1134. * w:cryptProviderType=&quot;rsaAES&quot; w:cryptAlgorithmClass=&quot;hash&quot;
  1135. * w:cryptAlgorithmType=&quot;typeAny&quot; w:cryptAlgorithmSid=&quot;14&quot;
  1136. * w:cryptSpinCount=&quot;100000&quot; w:hash=&quot;...&quot; w:salt=&quot;....&quot;
  1137. * /&gt;
  1138. * </pre>
  1139. *
  1140. * @param password the plaintext password, if null no password will be applied
  1141. * @param hashAlgo the hash algorithm - only md2, m5, sha1, sha256, sha384 and sha512 are supported.
  1142. * if null, it will default default to sha1
  1143. */
  1144. public void enforceCommentsProtection(String password, HashAlgorithm hashAlgo) {
  1145. settings.setEnforcementEditValue(STDocProtect.COMMENTS, password, hashAlgo);
  1146. }
  1147. /**
  1148. * Enforce the Tracked Changes protection.<br>
  1149. * In the documentProtection tag inside settings.xml file, <br>
  1150. * it sets the value of enforcement to "1" (w:enforcement="1") <br>
  1151. * and the value of edit to trackedChanges (w:edit="trackedChanges")<br>
  1152. * <br>
  1153. * sample snippet from settings.xml
  1154. * <pre>
  1155. * &lt;w:settings ... &gt;
  1156. * &lt;w:documentProtection w:edit=&quot;trackedChanges&quot; w:enforcement=&quot;1&quot;/&gt;
  1157. * </pre>
  1158. */
  1159. public void enforceTrackedChangesProtection() {
  1160. settings.setEnforcementEditValue(STDocProtect.TRACKED_CHANGES);
  1161. }
  1162. /**
  1163. * Enforce the Tracked Changes protection.<br>
  1164. * <br>
  1165. * sample snippet from settings.xml
  1166. * <pre>
  1167. * &lt;w:documentProtection w:edit=&quot;trackedChanges&quot; w:enforcement=&quot;1&quot;
  1168. * w:cryptProviderType=&quot;rsaAES&quot; w:cryptAlgorithmClass=&quot;hash&quot;
  1169. * w:cryptAlgorithmType=&quot;typeAny&quot; w:cryptAlgorithmSid=&quot;14&quot;
  1170. * w:cryptSpinCount=&quot;100000&quot; w:hash=&quot;...&quot; w:salt=&quot;....&quot;
  1171. * /&gt;
  1172. * </pre>
  1173. *
  1174. * @param password the plaintext password, if null no password will be applied
  1175. * @param hashAlgo the hash algorithm - only md2, m5, sha1, sha256, sha384 and sha512 are supported.
  1176. * if null, it will default default to sha1
  1177. */
  1178. public void enforceTrackedChangesProtection(String password, HashAlgorithm hashAlgo) {
  1179. settings.setEnforcementEditValue(STDocProtect.TRACKED_CHANGES, password, hashAlgo);
  1180. }
  1181. /**
  1182. * Validates the existing password
  1183. *
  1184. * @return true, only if password was set and equals, false otherwise
  1185. */
  1186. public boolean validateProtectionPassword(String password) {
  1187. return settings.validateProtectionPassword(password);
  1188. }
  1189. /**
  1190. * Remove protection enforcement.<br>
  1191. * In the documentProtection tag inside settings.xml file <br>
  1192. * it sets the value of enforcement to "0" (w:enforcement="0") <br>
  1193. */
  1194. public void removeProtectionEnforcement() {
  1195. settings.removeEnforcement();
  1196. }
  1197. /**
  1198. * Enforces fields update on document open (in Word).
  1199. * In the settings.xml file <br>
  1200. * sets the updateSettings value to true (w:updateSettings w:val="true")
  1201. * <p>
  1202. * NOTICES:
  1203. * <ul>
  1204. * <li>Causing Word to ask on open: "This document contains fields that may refer to other files. Do you want to update the fields in this document?"
  1205. * (if "Update automatic links at open" is enabled)</li>
  1206. * <li>Flag is removed after saving with changes in Word </li>
  1207. * </ul>
  1208. */
  1209. public void enforceUpdateFields() {
  1210. settings.setUpdateFields();
  1211. }
  1212. /**
  1213. * Check if revision tracking is turned on.
  1214. *
  1215. * @return {@code true} if revision tracking is turned on
  1216. */
  1217. public boolean isTrackRevisions() {
  1218. return settings.isTrackRevisions();
  1219. }
  1220. /**
  1221. * Enable or disable revision tracking.
  1222. *
  1223. * @param enable {@code true} to turn on revision tracking, {@code false} to turn off revision tracking
  1224. */
  1225. public void setTrackRevisions(boolean enable) {
  1226. settings.setTrackRevisions(enable);
  1227. }
  1228. /**
  1229. * Returns the current zoom factor in percent values, i.e. 100 is normal zoom.
  1230. *
  1231. * @return A percent value denoting the current zoom setting of this document.
  1232. */
  1233. public long getZoomPercent() {
  1234. return settings.getZoomPercent();
  1235. }
  1236. /**
  1237. * Set the zoom setting as percent value, i.e. 100 is normal zoom.
  1238. *
  1239. * @param zoomPercent A percent value denoting the zoom setting for this document.
  1240. */
  1241. public void setZoomPercent(long zoomPercent) {
  1242. settings.setZoomPercent(zoomPercent);
  1243. }
  1244. /**
  1245. * Returns the even-and-odd-headings setting
  1246. *
  1247. * @return True or false indicating whether or not separate even and odd headings is turned on.
  1248. */
  1249. public boolean getEvenAndOddHeadings() {
  1250. return settings.getEvenAndOddHeadings();
  1251. }
  1252. /**
  1253. * Sets the even-and-odd-headings setting
  1254. * @param enable Set to true to turn on separate even and odd headings.
  1255. */
  1256. public void setEvenAndOddHeadings(boolean enable) {
  1257. settings.setEvenAndOddHeadings(enable);
  1258. }
  1259. /**
  1260. * Returns the mirror margins setting
  1261. *
  1262. * @return True or false indicating whether or not mirror margins is turned on.
  1263. */
  1264. public boolean getMirrorMargins() {
  1265. return settings.getMirrorMargins();
  1266. }
  1267. /**
  1268. * Sets the mirror margins setting
  1269. * @param enable Set to true to turn on mirror margins.
  1270. */
  1271. public void setMirrorMargins(boolean enable) {
  1272. settings.setMirrorMargins(enable);
  1273. }
  1274. /**
  1275. * inserts an existing XWPFTable to the arrays bodyElements and tables
  1276. */
  1277. @Override
  1278. public void insertTable(int pos, XWPFTable table) {
  1279. bodyElements.add(pos, table);
  1280. int i = 0;
  1281. for (CTTbl tbl : ctDocument.getBody().getTblArray()) {
  1282. if (tbl == table.getCTTbl()) {
  1283. break;
  1284. }
  1285. i++;
  1286. }
  1287. tables.add(i, table);
  1288. }
  1289. /**
  1290. * Returns all Pictures, which are referenced from the document itself.
  1291. *
  1292. * @return a {@link List} of {@link XWPFPictureData}. The returned {@link List} is unmodifiable. Use #a
  1293. */
  1294. public List<XWPFPictureData> getAllPictures() {
  1295. return Collections.unmodifiableList(pictures);
  1296. }
  1297. /**
  1298. * @return all Pictures in this package
  1299. */
  1300. public List<XWPFPictureData> getAllPackagePictures() {
  1301. List<XWPFPictureData> result = new ArrayList<>();
  1302. Collection<List<XWPFPictureData>> values = packagePictures.values();
  1303. for (List<XWPFPictureData> list : values) {
  1304. result.addAll(list);
  1305. }
  1306. return Collections.unmodifiableList(result);
  1307. }
  1308. void registerPackagePictureData(XWPFPictureData picData) {
  1309. List<XWPFPictureData> list = packagePictures.computeIfAbsent(picData.getChecksum(), k -> new ArrayList<>(1));
  1310. if (!list.contains(picData)) {
  1311. list.add(picData);
  1312. }
  1313. }
  1314. XWPFPictureData findPackagePictureData(byte[] pictureData, int format) {
  1315. long checksum = IOUtils.calculateChecksum(pictureData);
  1316. XWPFPictureData xwpfPicData = null;
  1317. /*
  1318. * Try to find PictureData with this checksum. Create new, if none
  1319. * exists.
  1320. */
  1321. List<XWPFPictureData> xwpfPicDataList = packagePictures.get(checksum);
  1322. if (xwpfPicDataList != null) {
  1323. Iterator<XWPFPictureData> iter = xwpfPicDataList.iterator();
  1324. while (iter.hasNext() && xwpfPicData == null) {
  1325. XWPFPictureData curElem = iter.next();
  1326. if (Arrays.equals(pictureData, curElem.getData())) {
  1327. xwpfPicData = curElem;
  1328. }
  1329. }
  1330. }
  1331. return xwpfPicData;
  1332. }
  1333. public String addPictureData(byte[] pictureData, int format) throws InvalidFormatException {
  1334. XWPFPictureData xwpfPicData = findPackagePictureData(pictureData, format);
  1335. POIXMLRelation relDesc = XWPFPictureData.RELATIONS[format];
  1336. if (xwpfPicData == null) {
  1337. /* Part doesn't exist, create a new one */
  1338. int idx = getNextPicNameNumber(format);
  1339. xwpfPicData = (XWPFPictureData) createRelationship(relDesc, XWPFFactory.getInstance(), idx);
  1340. /* write bytes to new part */
  1341. PackagePart picDataPart = xwpfPicData.getPackagePart();
  1342. try (OutputStream out = picDataPart.getOutputStream()) {
  1343. out.write(pictureData);
  1344. } catch (IOException e) {
  1345. throw new POIXMLException(e);
  1346. }
  1347. registerPackagePictureData(xwpfPicData);
  1348. pictures.add(xwpfPicData);
  1349. return getRelationId(xwpfPicData);
  1350. } else if (!getRelations().contains(xwpfPicData)) {
  1351. /*
  1352. * Part already existed, but was not related so far. Create
  1353. * relationship to the already existing part and update
  1354. * POIXMLDocumentPart data.
  1355. */
  1356. // TODO add support for TargetMode.EXTERNAL relations.
  1357. RelationPart rp = addRelation(null, XWPFRelation.IMAGES, xwpfPicData);
  1358. return rp.getRelationship().getId();
  1359. } else {
  1360. /* Part already existed, get relation id and return it */
  1361. return getRelationId(xwpfPicData);
  1362. }
  1363. }
  1364. public String addPictureData(InputStream is, int format) throws InvalidFormatException {
  1365. try {
  1366. byte[] data = IOUtils.toByteArray(is);
  1367. return addPictureData(data, format);
  1368. } catch (IOException e) {
  1369. throw new POIXMLException(e);
  1370. }
  1371. }
  1372. /**
  1373. * get the next free ImageNumber
  1374. *
  1375. * @return the next free ImageNumber
  1376. * @throws InvalidFormatException If the format of the picture is not known.
  1377. */
  1378. public int getNextPicNameNumber(int format) throws InvalidFormatException {
  1379. int img = getAllPackagePictures().size() + 1;
  1380. String proposal = XWPFPictureData.RELATIONS[format].getFileName(img);
  1381. PackagePartName createPartName = PackagingURIHelper.createPartName(proposal);
  1382. while (this.getPackage().getPart(createPartName) != null) {
  1383. img++;
  1384. proposal = XWPFPictureData.RELATIONS[format].getFileName(img);
  1385. createPartName = PackagingURIHelper.createPartName(proposal);
  1386. }
  1387. return img;
  1388. }
  1389. /**
  1390. * returns the PictureData by blipID
  1391. *
  1392. * @return XWPFPictureData of a specificID
  1393. */
  1394. public XWPFPictureData getPictureDataByID(String blipID) {
  1395. POIXMLDocumentPart relatedPart = getRelationById(blipID);
  1396. if (relatedPart instanceof XWPFPictureData) {
  1397. return (XWPFPictureData) relatedPart;
  1398. }
  1399. return null;
  1400. }
  1401. /**
  1402. * getNumbering
  1403. *
  1404. * @return numbering
  1405. */
  1406. public XWPFNumbering getNumbering() {
  1407. return numbering;
  1408. }
  1409. /**
  1410. * get Styles
  1411. *
  1412. * @return styles for this document
  1413. */
  1414. public XWPFStyles getStyles() {
  1415. return styles;
  1416. }
  1417. @Override
  1418. public XWPFParagraph getParagraph(CTP p) {
  1419. for (XWPFParagraph paragraph : paragraphs) {
  1420. if (paragraph.getCTP() == p) {
  1421. return paragraph;
  1422. }
  1423. }
  1424. return null;
  1425. }
  1426. /**
  1427. * get a table by its CTTbl-Object
  1428. *
  1429. * @return a table by its CTTbl-Object or null
  1430. */
  1431. @Override
  1432. public XWPFTable getTable(CTTbl ctTbl) {
  1433. for (int i = 0; i < tables.size(); i++) {
  1434. if (getTables().get(i).getCTTbl() == ctTbl) {
  1435. return getTables().get(i);
  1436. }
  1437. }
  1438. return null;
  1439. }
  1440. public Iterator<XWPFTable> getTablesIterator() {
  1441. return tables.iterator();
  1442. }
  1443. /**
  1444. * @since POI 5.2.0
  1445. */
  1446. public Spliterator<XWPFTable> getTablesSpliterator() {
  1447. return tables.spliterator();
  1448. }
  1449. public Iterator<XWPFParagraph> getParagraphsIterator() {
  1450. return paragraphs.iterator();
  1451. }
  1452. /**
  1453. * @since POI 5.2.0
  1454. */
  1455. public Spliterator<XWPFParagraph> getParagraphsSpliterator() {
  1456. return paragraphs.spliterator();
  1457. }
  1458. /**
  1459. * Returns the paragraph that of position pos
  1460. */
  1461. @Override
  1462. public XWPFParagraph getParagraphArray(int pos) {
  1463. if (pos >= 0 && pos < paragraphs.size()) {
  1464. return paragraphs.get(pos);
  1465. }
  1466. return null;
  1467. }
  1468. /**
  1469. * returns the Part, to which the body belongs, which you need for adding relationship to other parts
  1470. * Actually it is needed of the class XWPFTableCell. Because you have to know to which part the tableCell
  1471. * belongs.
  1472. */
  1473. @Override
  1474. public POIXMLDocumentPart getPart() {
  1475. return this;
  1476. }
  1477. /**
  1478. * get the PartType of the body, for example
  1479. * DOCUMENT, HEADER, FOOTER, FOOTNOTE,
  1480. */
  1481. @Override
  1482. public BodyType getPartType() {
  1483. return BodyType.DOCUMENT;
  1484. }
  1485. /**
  1486. * get the TableCell which belongs to the TableCell
  1487. */
  1488. @Override
  1489. public XWPFTableCell getTableCell(CTTc cell) {
  1490. XmlCursor cursor = cell.newCursor();
  1491. cursor.toParent();
  1492. XmlObject o = cursor.getObject();
  1493. if (!(o instanceof CTRow)) {
  1494. return null;
  1495. }
  1496. CTRow row = (CTRow) o;
  1497. cursor.toParent();
  1498. o = cursor.getObject();
  1499. cursor.dispose();
  1500. if (!(o instanceof CTTbl)) {
  1501. return null;
  1502. }
  1503. CTTbl tbl = (CTTbl) o;
  1504. XWPFTable table = getTable(tbl);
  1505. if (table == null) {
  1506. return null;
  1507. }
  1508. XWPFTableRow tableRow = table.getRow(row);
  1509. if (tableRow == null) {
  1510. return null;
  1511. }
  1512. return tableRow.getTableCell(cell);
  1513. }
  1514. @Override
  1515. public XWPFDocument getXWPFDocument() {
  1516. return this;
  1517. }
  1518. /**
  1519. * This method is used to create template for chart XML
  1520. * no need to read MS-Word file and modify charts
  1521. *
  1522. * @return This method return object of XWPFChart Object with default height and width
  1523. * @since POI 4.0.0
  1524. */
  1525. public XWPFChart createChart() throws InvalidFormatException, IOException {
  1526. return createChart(XDDFChart.DEFAULT_WIDTH, XDDFChart.DEFAULT_HEIGHT);
  1527. }
  1528. /**
  1529. * This method is used to create template for chart XML
  1530. * no need to read MS-Word file and modify charts
  1531. *
  1532. * @param width width of chart in document
  1533. * @param height height of chart in document
  1534. * @return This method return object of XWPFChart
  1535. * @since POI 4.0.0
  1536. */
  1537. public XWPFChart createChart(int width, int height) throws InvalidFormatException, IOException {
  1538. return createChart(createParagraph().createRun(), width, height);
  1539. }
  1540. /**
  1541. *
  1542. * @param run in which the chart will be attached.
  1543. * @param width in EMU.
  1544. * @param height in EMU.
  1545. * @return the new chart.
  1546. * @since POI 4.1.2
  1547. */
  1548. public XWPFChart createChart(XWPFRun run, int width, int height) throws InvalidFormatException, IOException {
  1549. //get chart number
  1550. int chartNumber = getNextPartNumber(XWPFRelation.CHART, charts.size() + 1);
  1551. //create relationship in document for new chart
  1552. RelationPart rp = createRelationship(
  1553. XWPFRelation.CHART, XWPFFactory.getInstance(), chartNumber, false);
  1554. // initialize xwpfchart object
  1555. XWPFChart xwpfChart = rp.getDocumentPart();
  1556. xwpfChart.setChartIndex(chartNumber);
  1557. xwpfChart.attach(rp.getRelationship().getId(), run);
  1558. xwpfChart.setChartBoundingBox(width, height);
  1559. //add chart object to chart list
  1560. charts.add(xwpfChart);
  1561. return xwpfChart;
  1562. }
  1563. /**
  1564. * Create a new footnote and add it to the document.
  1565. *
  1566. * @return New XWPFFootnote.
  1567. * @since 4.0.0
  1568. */
  1569. public XWPFFootnote createFootnote() {
  1570. XWPFFootnotes footnotes = this.createFootnotes();
  1571. return footnotes.createFootnote();
  1572. }
  1573. /**
  1574. * Remove the specified footnote if present.
  1575. *
  1576. * @param pos Array position of the footnote to be removed.
  1577. * @return True if the footnote was removed.
  1578. * @since 4.0.0
  1579. */
  1580. public boolean removeFootnote(int pos) {
  1581. if (null != footnotes) {
  1582. return footnotes.removeFootnote(pos);
  1583. } else {
  1584. return false;
  1585. }
  1586. }
  1587. /**
  1588. * Create a new end note and add it to the document.
  1589. *
  1590. * @return New {@link XWPFEndnote}.
  1591. * @since 4.0.0
  1592. */
  1593. public XWPFEndnote createEndnote() {
  1594. XWPFEndnotes endnotes = this.createEndnotes();
  1595. return endnotes.createEndnote();
  1596. }
  1597. public XWPFEndnotes createEndnotes() {
  1598. if (endnotes == null) {
  1599. EndnotesDocument endnotesDoc = EndnotesDocument.Factory.newInstance();
  1600. XWPFRelation relation = XWPFRelation.ENDNOTE;
  1601. int i = getRelationIndex(relation);
  1602. XWPFEndnotes wrapper = (XWPFEndnotes) createRelationship(relation, XWPFFactory.getInstance(), i);
  1603. wrapper.setEndnotes(endnotesDoc.addNewEndnotes());
  1604. wrapper.setIdManager(footnoteIdManager);
  1605. endnotes = wrapper;
  1606. }
  1607. return endnotes;
  1608. }
  1609. /**
  1610. * Gets the list of end notes for the document.
  1611. *
  1612. * @return List, possibly empty, of {@link XWPFEndnote}s.
  1613. */
  1614. public List<XWPFEndnote> getEndnotes() {
  1615. if (endnotes == null) {
  1616. return Collections.emptyList();
  1617. }
  1618. return endnotes.getEndnotesList();
  1619. }
  1620. /**
  1621. * Remove the specified end note if present.
  1622. *
  1623. * @param pos Array position of the end note to be removed.
  1624. * @return True if the end note was removed.
  1625. * @since 4.0.0
  1626. */
  1627. public boolean removeEndnote(int pos) {
  1628. if (null != endnotes) {
  1629. return endnotes.removeEndnote(pos);
  1630. } else {
  1631. return false;
  1632. }
  1633. }
  1634. }