├── LICENSE ├── README.md ├── autodoc-v1.5.jar ├── example_docx_template.docx ├── example_pptx_template.pptx ├── example_textfile.txt ├── lib ├── commons-codec-1.3.jar ├── commons-io-1.3.1.jar ├── commons-lang-2.4.jar ├── commons-logging-1.1.1.jar ├── docx4j-2.8.1.jar ├── log4j-1.2.15.jar └── xmlgraphics-commons-1.4.jar ├── readme.pdf └── src ├── DocxGenerator.java ├── Functions.java ├── GUI.java ├── Main.java └── ProcessThread.java /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | 203 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | autodoc 2 | ======= 3 | 4 | Create Microsoft Documents automatically using Text and Template files. 5 | 6 | Autodoc was designed as a means to automate reports and alleviate the effort needed to generate routine documents. 7 | Given a docx, pptx or xlsx file along with a text file of desired content Autodoc can output a 8 | document of the same format with the desired content inserted into the template. 9 | 10 | Autodoc replaces key values in a document with a desired value stated in a textfile. 11 | It can be used in both graphical and command-line environments. The application 12 | takes in the three following inputs: 13 | 14 | Text file with key words and desired values (tab or space delimitted) 15 | Template file. This can be a docx, pptx or xlsx file with included keywords to be replaced 16 | Output path. This is the desired path where you would like your desired output document 17 | saved to. 18 | -------------------------------------------------------------------------------- /autodoc-v1.5.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nasa/autodoc/fa6807b80d9bfe7c340272361a77ec8eb5ce6513/autodoc-v1.5.jar -------------------------------------------------------------------------------- /example_docx_template.docx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nasa/autodoc/fa6807b80d9bfe7c340272361a77ec8eb5ce6513/example_docx_template.docx -------------------------------------------------------------------------------- /example_pptx_template.pptx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nasa/autodoc/fa6807b80d9bfe7c340272361a77ec8eb5ce6513/example_pptx_template.pptx -------------------------------------------------------------------------------- /example_textfile.txt: -------------------------------------------------------------------------------- 1 | ${title} Autodoc example 2 | ${date} 1/1/2013 3 | ${author} Delvison Castillo 4 | 5 | # Lines starting with a pound are comments 6 | 7 | # Key values with a value of null are replaced with a space in the output 8 | ${key} null 9 | -------------------------------------------------------------------------------- /lib/commons-codec-1.3.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nasa/autodoc/fa6807b80d9bfe7c340272361a77ec8eb5ce6513/lib/commons-codec-1.3.jar -------------------------------------------------------------------------------- /lib/commons-io-1.3.1.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nasa/autodoc/fa6807b80d9bfe7c340272361a77ec8eb5ce6513/lib/commons-io-1.3.1.jar -------------------------------------------------------------------------------- /lib/commons-lang-2.4.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nasa/autodoc/fa6807b80d9bfe7c340272361a77ec8eb5ce6513/lib/commons-lang-2.4.jar -------------------------------------------------------------------------------- /lib/commons-logging-1.1.1.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nasa/autodoc/fa6807b80d9bfe7c340272361a77ec8eb5ce6513/lib/commons-logging-1.1.1.jar -------------------------------------------------------------------------------- /lib/docx4j-2.8.1.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nasa/autodoc/fa6807b80d9bfe7c340272361a77ec8eb5ce6513/lib/docx4j-2.8.1.jar -------------------------------------------------------------------------------- /lib/log4j-1.2.15.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nasa/autodoc/fa6807b80d9bfe7c340272361a77ec8eb5ce6513/lib/log4j-1.2.15.jar -------------------------------------------------------------------------------- /lib/xmlgraphics-commons-1.4.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nasa/autodoc/fa6807b80d9bfe7c340272361a77ec8eb5ce6513/lib/xmlgraphics-commons-1.4.jar -------------------------------------------------------------------------------- /readme.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nasa/autodoc/fa6807b80d9bfe7c340272361a77ec8eb5ce6513/readme.pdf -------------------------------------------------------------------------------- /src/DocxGenerator.java: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nasa/autodoc/fa6807b80d9bfe7c340272361a77ec8eb5ce6513/src/DocxGenerator.java -------------------------------------------------------------------------------- /src/Functions.java: -------------------------------------------------------------------------------- 1 | // @Author Delvison Castillo 2 | // NOTE: A Lot of this code can be refactored making this class a lot smaller 3 | // than its current size. Though, due to time constraints, it will remain this 4 | // way. 5 | 6 | package gov.nasa.cassini; 7 | 8 | //JAVA IMPORTS 9 | import java.io.BufferedReader; 10 | import java.io.FileReader; 11 | import java.io.File; 12 | import java.io.PrintWriter; 13 | import java.io.IOException; 14 | import java.util.HashMap; 15 | import java.util.ArrayList; 16 | import java.util.List; 17 | import javax.xml.bind.JAXBElement; 18 | import javax.xml.bind.JAXBException; 19 | import java.awt.Desktop; 20 | 21 | //DOCX4J IMPORTS 22 | import org.docx4j.openpackaging.packages.*; 23 | import org.docx4j.openpackaging.exceptions.*; 24 | import org.docx4j.openpackaging.parts.JaxbXmlPart; 25 | import org.docx4j.wml.CTBookmark; 26 | import org.docx4j.wml.CTBookmarkRange; 27 | import org.docx4j.wml.ContentAccessor; 28 | import org.docx4j.wml.P; 29 | import org.docx4j.wml.Tc; 30 | import org.docx4j.wml.Tr; 31 | import org.docx4j.TraversalUtil.CallbackImpl; 32 | import org.docx4j.TraversalUtil; 33 | import org.docx4j.XmlUtils; 34 | import org.docx4j.openpackaging.parts.WordprocessingML.MainDocumentPart; 35 | import org.docx4j.openpackaging.parts.SpreadsheetML.WorkbookPart; 36 | import org.docx4j.openpackaging.parts.SpreadsheetML.WorksheetPart; 37 | import org.docx4j.openpackaging.parts.PresentationML.MainPresentationPart; 38 | import org.docx4j.openpackaging.parts.SpreadsheetML.SharedStrings; 39 | import org.docx4j.openpackaging.parts.PresentationML.SlidePart; 40 | import org.docx4j.dml.CTRegularTextRun; 41 | import org.docx4j.dml.CTTextBody; 42 | import org.docx4j.dml.CTTextParagraph; 43 | import org.pptx4j.pml.Shape; 44 | import org.docx4j.fonts.IdentityPlusMapper; 45 | import org.docx4j.fonts.Mapper; 46 | import org.docx4j.fonts.*; 47 | import org.docx4j.openpackaging.parts.relationships.Namespaces; 48 | import org.docx4j.openpackaging.parts.relationships.RelationshipsPart; 49 | import org.docx4j.relationships.Relationship; 50 | import org.docx4j.openpackaging.parts.WordprocessingML.FooterPart; 51 | import org.docx4j.openpackaging.parts.WordprocessingML.HeaderPart; 52 | 53 | public class Functions 54 | { 55 | private static Functions instance; 56 | private String extension; 57 | protected String targetName; 58 | protected boolean term; 59 | //FOR DOCX 60 | private MainDocumentPart docxDocumentPart; 61 | private List docxBodyContent; 62 | //FOR XLSX 63 | private WorkbookPart workbookPart; 64 | private SpreadsheetMLPackage xlsMLPackage; 65 | private List siElements; 66 | //FOR PPTX 67 | MainPresentationPart presentationPart; 68 | PresentationMLPackage pptMLPackage; 69 | ArrayList pptSlideParts; 70 | //FOR ALL 71 | private GUI gui; 72 | private boolean debug; 73 | //FOR ERRORS 74 | private boolean errorFound = false; 75 | private ArrayList errors = new ArrayList(); 76 | 77 | Functions(boolean terminalMode) 78 | { 79 | this.term = terminalMode; 80 | } 81 | 82 | /** 83 | * Prints out debugging messages 84 | * @param msg The debugging message 85 | */ 86 | protected void debugger(String msg) 87 | { 88 | if (gui != null) 89 | { 90 | this.debug = gui.debug; 91 | if (this.debug){ 92 | System.out.println("Debug------------------"); 93 | System.out.println(msg); 94 | if (!term) gui.setStatus(msg); 95 | } 96 | } 97 | } 98 | 99 | /** 100 | * Main function that gets called. Determines what file is to be generated and 101 | * calls the appropriate function to do so. 102 | * @param textFilePath the path of the text file 103 | * @param templatePath the path of the template file 104 | * @param targetName the path of the intended output file 105 | */ 106 | protected boolean generateDocument(String textFilePath, String templatePath, 107 | String targetName) 108 | { 109 | if (!term) gui = GUI.getInstance(); 110 | if (!term) gui.getDebug(); 111 | boolean is_success = false; 112 | //DETERMINE THE FILETYPE BY EXTENSION 113 | extension = 114 | templatePath.substring(templatePath.lastIndexOf('.'),templatePath.length()); 115 | //STRIP EXTENSION 116 | this.extensionFix(targetName); 117 | 118 | if (!term) gui.progress(); //progress scrollbar 119 | 120 | //.DOCX 121 | if ( extension.equals(".docx") ) 122 | { 123 | is_success = this.generateDOCX(textFilePath, templatePath); 124 | } 125 | 126 | //.PPTX 127 | if ( extension.equals(".pptx") ) 128 | { 129 | is_success = this.generatePPTX(textFilePath, templatePath); 130 | } 131 | 132 | //.XLSX 133 | if ( extension.equals(".xlsx") ) 134 | { 135 | debugger("Excel file found"); 136 | is_success = this.generateXLSX(textFilePath, templatePath); 137 | } 138 | 139 | //CHECK FOR ERRORS 140 | if (errorFound) 141 | { 142 | String[] er = errors.toArray( new String[errors.size()] ); 143 | if (!term) gui.showErrors(er); 144 | if (term) { 145 | System.out.println("======================================="); 146 | System.out.println("THE FOLLOWING KEYWORDS WERE NOT FOUND:"); 147 | for (int i=0; i< er.length; i++) 148 | System.out.println(er[i]); 149 | System.out.println("END OF KEYWORDS NOT FOUND=============="); 150 | } 151 | } 152 | 153 | if (!term) gui.progress(); //progress scrollbar 154 | /* 155 | //IF SUCCESSFUL, OPEN THE DOC 156 | if ( !term ) 157 | { 158 | if (is_success && gui.checkOpen()) 159 | { 160 | try 161 | { 162 | Desktop.getDesktop().open(new java.io.File(this.targetName+extension)); 163 | } catch (java.io.IOException e) 164 | { 165 | e.printStackTrace(); 166 | } 167 | } 168 | } 169 | */ 170 | //RETURN BOOLEAN 171 | return is_success; 172 | } 173 | 174 | /** 175 | * Strips the extension of a file 176 | * @param t string of file path 177 | */ 178 | protected void extensionFix(String t) 179 | { 180 | if (t.endsWith(".docx") || t.endsWith(".pptx") || t.endsWith(".xlsx")) 181 | { 182 | this.targetName = t.substring(0, t.lastIndexOf('.')); 183 | if (targetName.endsWith(".docx") || targetName.endsWith(".pptx") || 184 | targetName.endsWith(".xlsx")) 185 | { 186 | this.extensionFix(this.targetName); 187 | } 188 | } else 189 | { 190 | this.targetName = t; 191 | } 192 | } 193 | 194 | /** 195 | * Function that is responsible for generating .docx files 196 | * @param textFilePath path for text file 197 | * @param templatePath path for original .docx template file 198 | */ 199 | protected boolean generateDOCX(String textFilePath, String templatePath) 200 | { 201 | boolean is_success = false; 202 | try 203 | { 204 | //OPEN TEMPLATE FILE 205 | WordprocessingMLPackage templateFile = WordprocessingMLPackage.load(new 206 | java.io.File(templatePath)); 207 | if (!term) gui.progress(); //progress scrollbar 208 | 209 | //GET MAIN DOCUMENT PART 210 | docxDocumentPart = templateFile.getMainDocumentPart(); 211 | if (!term) gui.progress(); //progress scrollbar 212 | 213 | //GET DOCUMENT BODY 214 | this.docxBodyContent = docxDocumentPart.getJaxbElement().getBody() 215 | .getContent(); 216 | if (!term) gui.progress(); //progress scrollbar 217 | 218 | //PARSE TEXTFILE 219 | if (!term) gui.setStatus("Parsing textfile.."); 220 | this.parseTextFile(textFilePath); 221 | 222 | //SAVE THE FILE 223 | if (!term) gui.setStatus("Saving file.."); 224 | templateFile.save(new java.io.File(targetName+".docx")); 225 | if (!term) gui.progressBar.setString("90%"); 226 | if (!term) gui.progressBar.setValue(90); 227 | 228 | //PROCESSING WAS SUCCESSFUL 229 | is_success = true; 230 | } 231 | catch ( Docx4JException e ) 232 | { 233 | debugger("DOCX4JERROR"); 234 | is_success = false; 235 | } 236 | return is_success; 237 | } 238 | 239 | /** 240 | * Function that is responsible for generating .pptx files 241 | * @param textFilePath path for text file 242 | * @param templatePath path for original .pptx template file 243 | */ 244 | protected boolean generatePPTX(String textFilePath, String templatePath){ 245 | boolean is_success = false; 246 | try 247 | { 248 | // Create the wordprocessingmlpackage 249 | pptMLPackage = 250 | PresentationMLPackage.load(new java.io.File(templatePath)); 251 | if (!term) gui.progress(); //progress scrollbar 252 | 253 | //GET PART 254 | debugger("presentationPart"); 255 | presentationPart = pptMLPackage.getMainPresentationPart(); 256 | if (!term) gui.progress(); //progress scrollbar 257 | 258 | //GET SLIDE PARTS 259 | debugger("slidePart"); 260 | pptSlideParts = this.getpptSlideParts(); 261 | if (!term) gui.progress(); //progress scrollbar 262 | 263 | //PARSE TEXTFILE 264 | debugger("parse textfile"); 265 | this.parseTextFile(textFilePath); 266 | 267 | //SAVE FILE 268 | pptMLPackage.save(new java.io.File(this.targetName+".pptx") ); 269 | is_success = true; 270 | } 271 | catch (Docx4JException e){ 272 | debugger("DOCX4JERROR"); 273 | } 274 | return is_success; 275 | } 276 | 277 | /** 278 | * Function that is responsible for generating .xlsx files 279 | * @param textFilePath path for text file 280 | * @param templatePath path for original .xlsx template file 281 | */ 282 | protected boolean generateXLSX(String textFilePath, String templatePath){ 283 | boolean is_success = false; 284 | try 285 | { 286 | // Create the wordprocessingmlpackage 287 | debugger(templatePath); 288 | debugger("Opening template file"); 289 | xlsMLPackage = SpreadsheetMLPackage.load(new java.io.File(templatePath)); 290 | if (!term) gui.progress(); //progress scrollbar 291 | 292 | //GET MAIN WORKBOOK PART 293 | debugger("GET WorkbookPart"); 294 | workbookPart = xlsMLPackage.getWorkbookPart(); 295 | if (!term) gui.progressBar.setString("25%"); 296 | if (!term) gui.progressBar.setValue(25); 297 | if (!term) gui.progress(); //progress scrollbar 298 | 299 | //GET SHARED STRINGS 300 | debugger("GET SharedStrings"); 301 | SharedStrings ss = workbookPart.getSharedStrings(); 302 | org.xlsx4j.sml.CTSst cts = ss.getJaxbElement(); 303 | siElements = cts.getSi(); 304 | if (!term) gui.progressBar.setString("30%"); 305 | if (!term) gui.progressBar.setValue(30); 306 | if (!term) gui.progress(); //progress scrollbar 307 | 308 | //PARSE TEXTFILE 309 | debugger("parseTextFile"); 310 | this.parseTextFile(textFilePath); 311 | if (!term) gui.progressBar.setString("50"); 312 | if (!term) gui.progressBar.setValue(50); 313 | if (!term) gui.progress(); //progress scrollbar 314 | 315 | // RESET VALUES FOR FORMULAS 316 | removeXLSXFormulaValues(); 317 | 318 | //SAVE IT 319 | xlsMLPackage.save(new java.io.File(this.targetName+".xlsx") ); 320 | is_success = true; 321 | } 322 | catch ( Docx4JException e ) 323 | { 324 | debugger("Docx4JException"); 325 | } 326 | return is_success; 327 | } 328 | 329 | /** 330 | * Parses text file. Calls appropriate replace function depending on what file 331 | * is being used. 332 | * @param textFilePath path for the text file 333 | */ 334 | protected void parseTextFile(String textFilePath) 335 | { 336 | try 337 | { 338 | //READ IN THE TEXT FILE 339 | java.util.Scanner sc = new java.util.Scanner( 340 | new java.io.File(textFilePath)); 341 | String line = ""; 342 | while( sc.hasNext() ) 343 | { 344 | //READ NEXT LINE 345 | line = sc.nextLine(); 346 | if (!term) this.gui.progress(); //increase progress bar 347 | 348 | // PARSE LINE INTO TWO PARTS -- BOOKMARK & VALUE 349 | String[] temp = line.split("\\s+",2); 350 | //ASSURE THAT LINE HAS CONTENT 351 | if (temp.length == 2) 352 | { 353 | String bookmark = temp[0]; 354 | String value = temp[1]; 355 | 356 | //IGNORE LINES STARTING WITH # (COMMENTS) 357 | if ( !line.startsWith("#") ) 358 | { 359 | debugger("oye! el bookmark es "+bookmark); 360 | //LOG WHEN BOOKMARKS ARE NOT FOUND IN DOCUMENT 361 | if ( !replaceInit(bookmark, value) ) 362 | { 363 | this.errorFound = true; 364 | this.errors.add(bookmark); 365 | } 366 | } else { debugger("comment found"); } 367 | } 368 | } 369 | } 370 | catch( java.io.FileNotFoundException e ) 371 | { 372 | debugger("FAIL FILENOTFOUNDEXCEPTION"); 373 | } 374 | catch( java.io.IOException e ) 375 | { 376 | debugger("FAIL IOEXCEPTION"); 377 | } 378 | } 379 | 380 | /** 381 | * Inititalizes replace function. Considers file extension and forwards to the 382 | * appropriate replace function. 383 | * @param bookmark the name of the bookmark 384 | * @param value the value to be inserted in place of the bookmark 385 | */ 386 | protected boolean replaceInit(String bookmark, String value) 387 | { 388 | boolean success = true; 389 | //DOCX 390 | if ( extension.equals(".docx") ) 391 | { 392 | success = this.replaceForDocx(bookmark, value); 393 | } 394 | //PPTX 395 | if ( extension.equals(".pptx") ) 396 | { 397 | success = this.replaceForPptx(bookmark, value); 398 | } 399 | //XLSX 400 | if ( extension.equals(".xlsx") ) 401 | { 402 | success = this.replaceForXlsx(bookmark, value); 403 | } 404 | return success; 405 | } 406 | 407 | /** 408 | * Responsible for replacing text for .docx files 409 | * @param bookmark the name of the bookmark 410 | * @param value the value to be inserted in place of the bookmark 411 | */ 412 | protected boolean replaceForDocx(final String bookmark, final String value) 413 | { 414 | boolean found = false; 415 | boolean f; 416 | P para; 417 | // REPLACE BOOKMARKS IN HEADER FOOTER 418 | List headFoots = getDocxHeaderFooterParts(); 419 | for ( JaxbXmlPart jx : headFoots) 420 | { 421 | List contents = jx.getJaxbElement().getContent(); 422 | f = changeDocxParagraph( contents, bookmark, value, false ); 423 | if (!found) { found = f; } 424 | if (found){ debugger("WAS FOUND ON "+bookmark);} 425 | } 426 | 427 | // REPLACE BOOKMARKS IN MAIN DOCUMENT 428 | f = changeDocxParagraph( this.docxBodyContent, bookmark, value, false ); 429 | if (!found) { found = f; } 430 | if (found){ debugger("WAS FOUND ON "+bookmark);} 431 | return found; 432 | } 433 | 434 | /** 435 | * Responsible for replacing text for .xlsx files 436 | * @param bookmark the name of the bookmark 437 | * @param value the value to be inserted in place of the bookmark 438 | */ 439 | private boolean replaceForXlsx(String bookmark, String value) 440 | { 441 | boolean found = false; 442 | //REPLACE EXCEL TEXT 443 | for( org.xlsx4j.sml.CTRst si : siElements ) 444 | { 445 | String siValue = si.getT(); 446 | if ( siValue.equals(bookmark) ) 447 | { 448 | if (value.equals("null")) 449 | { 450 | si.setT(" "); 451 | } else { 452 | si.setT(value); 453 | } 454 | found = true; 455 | } 456 | } 457 | return found; 458 | } 459 | 460 | /** 461 | * Responsible for replacing text for .pptx files 462 | * @param bookmark the name of the bookmark 463 | * @param value the value to be inserted in place of the bookmark 464 | */ 465 | private boolean replaceForPptx(String bookmark, String value) 466 | { 467 | debugger("entering replaceForPptx"); 468 | String OGbkmk = bookmark; 469 | boolean found = false; 470 | //ITERATE THROUGH EACH SLIDEPART 471 | for ( SlidePart sld : pptSlideParts ) 472 | { 473 | List lst = 474 | sld.getJaxbElement().getCSld().getSpTree().getSpOrGrpSpOrGraphicFrame(); 475 | for ( Object o : lst ) 476 | { 477 | if ( o instanceof org.pptx4j.pml.Shape ){ 478 | Shape shp = (Shape)o; 479 | //GET TEXTBODY 480 | CTTextBody ctText = shp.getTxBody(); 481 | //GET PARAGRAPHS 482 | List CtParas = ctText.getP(); 483 | //ITERATE THROUGH PARAGRAPHS 484 | for (CTTextParagraph ctPara : CtParas) 485 | { 486 | //GET RUN OBJECTS 487 | List txtRuns = ctPara.getEGTextRun(); 488 | //ITERATE THROUGH RUNS 489 | for ( Object o1 : txtRuns ) 490 | { 491 | CTRegularTextRun ctr = (CTRegularTextRun)o1; 492 | //GET TEXT 493 | String current = ctr.getT(); 494 | 495 | //REPLACE SORROUNDERS 496 | if ( current.trim().equals("[") || current.trim().equals("]") || 497 | current.trim().equals("${") || current.trim().equals("}") || 498 | current.trim().equals("{") || current.trim().equals("$")) 499 | { 500 | debugger("[sorrounder replaced]"); 501 | ctr.setT(""); 502 | } 503 | bookmark = removeSurrounders(bookmark); 504 | current = removeSurrounders(current); 505 | debugger(current+ " IS CURRENT && "+bookmark+" IS BOOKMARK"); 506 | 507 | // EXACT MATCH 508 | if ( current.equals(bookmark) ) 509 | { 510 | //REPLACE SORROUNDERS 511 | debugger(value+ " FOUND+++++++"); 512 | if (value.toLowerCase().equals("null")){ 513 | ctr.setT(" "); 514 | } else { 515 | ctr.setT( removeSurrounders(ctr.getT()) ); 516 | ctr.setT(value); 517 | debugger("set T to .."+ ctr.getT()); 518 | } 519 | //ctr.setT( removeSurrounders(ctr.getT()) ); 520 | found = true; 521 | debugger(current+" replaced with "+value); 522 | } 523 | 524 | //CATCH $ ON END OF RUN 525 | if (ctr.getT().endsWith("$")){ 526 | ctr.setT( ctr.getT().substring( 0,ctr.getT().length()-1) ); 527 | } 528 | 529 | // PARTIAL MATCHES 530 | if (ctr.getT().contains( "{"+bookmark+"}" )) 531 | { 532 | ctr.setT( current.replace( "{"+bookmark+"}", value ) ); 533 | debugger("set T to 562 "+ ctr.getT()); 534 | found = true; 535 | } 536 | if (ctr.getT().contains( "${"+bookmark )) 537 | { 538 | ctr.setT( current.replace( "${"+bookmark, value ) ); 539 | debugger("set T to 530 "+ ctr.getT()); 540 | found = true; 541 | } 542 | if (ctr.getT().contains( bookmark+"]" )) 543 | { 544 | int pos = ctr.getT().indexOf(bookmark); 545 | ctr.setT( current.replace( bookmark+"]", value ) ); 546 | int before = 0; 547 | if (pos > 0) before = pos - 1; 548 | if ( ctr.getT().charAt(before) == '[' ) 549 | { 550 | debugger("meoow1"); 551 | current = ctr.getT(); 552 | ctr.setT( current.substring(0,before) + 553 | current.substring( before+1, current.length() )); 554 | } 555 | debugger("set T to 536 "+ ctr.getT()); 556 | found = true; 557 | } 558 | if (ctr.getT().contains( bookmark+"}" )) 559 | { 560 | int pos = ctr.getT().indexOf(bookmark); 561 | ctr.setT( current.replace( bookmark+"}", value ) ); 562 | int before = 0; 563 | if (pos > 0) before = pos - 1; 564 | if ( ctr.getT().charAt(before) == '{' ) 565 | { 566 | debugger("meoow2"); 567 | current = ctr.getT(); 568 | ctr.setT( current.substring(0,before) + 569 | current.substring( before+1, current.length() )); 570 | } 571 | debugger("set T to 542 "+ ctr.getT()); 572 | found = true; 573 | } 574 | if (ctr.getT().contains( "["+bookmark )) 575 | { 576 | ctr.setT( current.replace( "["+bookmark, value ) ); 577 | debugger("set T to 518 "+ ctr.getT()); 578 | found = true; 579 | } 580 | if (ctr.getT().contains( "{"+bookmark )) 581 | { 582 | ctr.setT( current.replace( "{"+bookmark, value ) ); 583 | debugger("set T to 524 "+ ctr.getT()); 584 | found = true; 585 | } 586 | if (ctr.getT().startsWith("]") || current.startsWith("}")) 587 | { 588 | ctr.setT( current.substring( 1,current.length() )); 589 | debugger("set T to 548 "+ ctr.getT()); 590 | } 591 | } 592 | } 593 | } 594 | } 595 | } 596 | return found; 597 | } 598 | 599 | /** 600 | * Returns an arraylist of SlideParts (for use with .PPT files) 601 | */ 602 | private ArrayList getpptSlideParts() 603 | { 604 | ArrayList slides = new ArrayList(); 605 | org.docx4j.openpackaging.parts.Parts parts = pptMLPackage.getParts(); 606 | HashMap hashmaps = parts.getParts(); 608 | 609 | for (org.docx4j.openpackaging.parts.PartName o : hashmaps.keySet() ) 610 | { 611 | if ( o.getName().startsWith("/ppt/slides/") ) 612 | { 613 | SlidePart temp = (SlidePart) hashmaps.get(o); 614 | slides.add(temp); 615 | } 616 | } 617 | return slides; 618 | } 619 | 620 | /** 621 | * Returns an arraylist of SlideParts (for use with .PPT files) 622 | */ 623 | private ArrayList getWorksheets() 624 | { 625 | ArrayList sheets = new ArrayList(); 626 | org.docx4j.openpackaging.parts.Parts parts = xlsMLPackage.getParts(); 627 | HashMap hashmaps = parts.getParts(); 629 | 630 | for (org.docx4j.openpackaging.parts.PartName o : hashmaps.keySet() ) 631 | { 632 | if ( o.getName().startsWith("/xl/worksheets/") ) 633 | { 634 | WorksheetPart temp = (WorksheetPart) hashmaps.get(o); 635 | sheets.add(temp); 636 | } 637 | } 638 | return sheets; 639 | } 640 | 641 | /** 642 | * Returns paragraph parent for bookmark found 643 | * @param parent the current parent node of the tree representation of the 644 | * document 645 | * @param bookmark the name of the bookmark being considered 646 | */ 647 | private boolean changeDocxParagraph(Object parent, String bookmark, 648 | String value, boolean found) 649 | { 650 | boolean f; 651 | debugger("entering changeDocxParagraph with "+bookmark); 652 | if ( parent == null ) 653 | { 654 | debugger("PARENT WAS NULL WITHIN getDocxBookmarkParent"); 655 | throw new RuntimeException("Parent node was null"); 656 | } 657 | P p = null; 658 | // GET ALL CHILDREN OF PARENT 659 | List children = TraversalUtil.getChildrenImpl(parent); 660 | if ( children != null ) 661 | { 662 | // LOOP THROUGH EACH CHILD ELEMENT 663 | for ( Object o : children ) 664 | { 665 | o = XmlUtils.unwrap(o); 666 | if (parent instanceof org.docx4j.wml.P) 667 | { 668 | // CHECK IF BOOKMARK WAS FOUND 669 | f = processDocxRuns(children, ((P)parent), bookmark, value); 670 | if (!found) { found = f; } 671 | } 672 | //RECURSE FARTHER DOWN THE TREE FOR A MATCH 673 | f = changeDocxParagraph(o, bookmark, value, found); 674 | if (!found) { found = f; } 675 | } 676 | } 677 | return found; 678 | } 679 | 680 | /** 681 | * Takes in a list of runs pertaining to a docx file. Checks if the bookmark in 682 | * question is located somewhere in the run. If so, it forwards to 683 | * collectDocxBookmarkedRuns. After the bookmark has been replaced it checks 684 | * again for more bookmarks in the parts list. 685 | * @param runs The list of runs pertaining to a paragraph in question 686 | * @param parentParagraph The parent paragraph of the list of runs in question 687 | * @param bookmark The bookmark in question 688 | * @param value The value of the bookmark in question to be replaced 689 | */ 690 | private boolean processDocxRuns(List runs, P parentParagraph, 691 | String bookmark, String value) 692 | { 693 | debugger("entering processDocxRuns"); 694 | boolean found = false; 695 | String collectiveContent = checkForDocxBookmark(runs, bookmark); 696 | if (collectiveContent.contains(bookmark)) 697 | { 698 | debugger("Match made with "+bookmark); 699 | found = true; 700 | 701 | // FIND INDICES OF BOOKMARK 702 | int startIndex = collectiveContent.indexOf(bookmark); 703 | int endIndex = startIndex + bookmark.length()-1; 704 | collectDocxBookmarkedRuns( startIndex, endIndex, runs, bookmark, value, 705 | parentParagraph); 706 | 707 | // CHECK FOR MORE BOOKMARKS IN PARAGRAPH 708 | collectiveContent = checkForDocxBookmark(runs, bookmark); 709 | if ( !collectiveContent.equals("false") ){ 710 | processDocxRuns(runs, parentParagraph, bookmark, value); 711 | } 712 | } 713 | return found; 714 | } 715 | 716 | /** 717 | * Takes in a list of runs pertaining to a docx file. Checks if the bookmark in 718 | * question is contained within one of the runs. If so, it will return a 719 | * concatenated String of all of the runs. If not, it will return a String that 720 | * reads "false". 721 | * @param runs The list of runs pertaining to a paragraph in question 722 | * @param bookmark The bookmark in question 723 | */ 724 | private String checkForDocxBookmark(List runs, String bookmark) 725 | { 726 | String collectiveContent=""; 727 | for ( Object o: runs ) 728 | { 729 | // CHILDREN OF RUNS 730 | List children = TraversalUtil.getChildrenImpl(o); 731 | if ( children != null ) 732 | { 733 | // LOOP THROUGH CHILDREN OF THE RUN 734 | for ( Object o2 : children ) 735 | { 736 | // UNWRAP OBJECT 737 | o2 = XmlUtils.unwrap(o2); 738 | // CHECK IF CURRENT OBJECT IS A TEXT OBJECT 739 | if ( o2 instanceof org.docx4j.wml.Text ) 740 | { 741 | collectiveContent = collectiveContent + 742 | ((org.docx4j.wml.Text)o2).getValue(); 743 | } 744 | } 745 | } 746 | } 747 | debugger("collective string is "+collectiveContent); 748 | if (!collectiveContent.contains(bookmark)) 749 | { 750 | collectiveContent = "false"; 751 | } 752 | return collectiveContent; 753 | } 754 | 755 | /** 756 | * Takes in a list of runs, iterates through them and determines which runs 757 | * contain any portion of the bookmark in question. 758 | * @param r The list of runs pertaining to a paragraph in question 759 | * @param bookmark The bookmark in question 760 | * @param value The value of the bookmark in question to be replaced 761 | * @param parentParagraph The parent paragraph of the list of runs in question 762 | */ 763 | private void collectDocxBookmarkedRuns(int startIndex, 764 | int endIndex, List r, String bookmark, String value, 765 | P parentParagraph) 766 | { 767 | debugger("enter collectDocxBookmarkedRuns"); 768 | boolean inBookmark = false; 769 | boolean endFound = false; 770 | boolean startFound = false; 771 | List runs = new ArrayList(); 772 | // LOOP THROUGH CHILDREN OF THE RUN 773 | for ( Object o : r ) 774 | { 775 | debugger("entered new run -- in collectDocxBookmarkedRuns"); 776 | List children = TraversalUtil.getChildrenImpl(o); 777 | if ( children != null && !endFound) 778 | { 779 | for ( Object o2 : children ) 780 | { 781 | debugger("entered new text object -- in collectDocxBookmarkedRuns"); 782 | // UNWRAP OBJECT 783 | o2 = XmlUtils.unwrap(o2); 784 | // CHECK IF CURRENT OBJECT IS A TEXT OBJECT 785 | if ( o2 instanceof org.docx4j.wml.Text ) 786 | { 787 | String t = ((org.docx4j.wml.Text) o2).getValue(); 788 | debugger("looking at string "+t); 789 | if (inBookmark) { debugger("CURRENTLY IN A BOOKMARK"); } 790 | int len = t.length(); 791 | debugger("startIndex is "+startIndex+" endIndex is "+endIndex+ 792 | " current length is "+len); 793 | if ( !inBookmark && startIndex <= len-1 ) 794 | { 795 | //runs.add(((org.docx4j.wml.R)o)); 796 | if (!inBookmark){ 797 | inBookmark = true; 798 | startFound = true; 799 | } 800 | } 801 | if (inBookmark){ 802 | debugger("run added with string "+t); 803 | runs.add(o); 804 | } 805 | if ( inBookmark && endIndex <= len-1) { 806 | endFound = true; 807 | inBookmark = false; 808 | debugger("end of bookmark found"); 809 | } 810 | if (!endFound) { 811 | endIndex -= len; 812 | debugger("endIndex is now"+endIndex); 813 | } 814 | if (!startFound){ 815 | startIndex -= len; 816 | debugger("startIndex is now"+startIndex); 817 | } 818 | } 819 | } 820 | } 821 | } 822 | if ( !runs.isEmpty() ) { 823 | debugger("startIndex is "+startIndex+" endIndex is "+endIndex); 824 | editDocxRuns(runs, startIndex, endIndex, bookmark, value,parentParagraph); 825 | } else { debugger("RUNS IS EMPTY!"); } 826 | } 827 | 828 | /** 829 | * Takes in a list of runs, the index of where the bookmark starts, the index 830 | * of where the bookmark ends and edits the runs accordingly. This method is 831 | * responsible for replacing bookmarks with their corresponding values in docx. 832 | * @param runs The list of runs pertaining to a paragraph in question 833 | * @param startIndex The index of where the bookmark starts in the 834 | * concatenation of the runs 835 | * @param endIndex The index of where the bookmark ends in the 836 | * concatenation of the runs 837 | * @param bookmark The bookmark in question 838 | * @param value The value of the bookmark in question to be replaced 839 | * @param parentParagraph The parent paragraph of the list of runs in question 840 | */ 841 | private void editDocxRuns(List runs, int startIndex, int endIndex, 842 | String bookmark, String value, P parentParagraph) 843 | { 844 | List parentNodes = parentParagraph.getContent(); 845 | debugger("enter editDocxRuns$$$$$$$$$$$$$$$$$$$"); 846 | boolean fixed = false; 847 | // ALTER FIRST RUN IN LIST 848 | Object first = runs.get(0); 849 | Object last = runs.get( runs.size()-1 ); 850 | org.docx4j.wml.R firstRun = (org.docx4j.wml.R)first; 851 | 852 | List children = TraversalUtil.getChildrenImpl(firstRun); 853 | if ( children != null ) 854 | { 855 | debugger("in first run"); 856 | for ( Object o : children ) 857 | { 858 | // UNWRAP OBJECT 859 | o = XmlUtils.unwrap(o); 860 | if ( o instanceof org.docx4j.wml.Text && !fixed ) 861 | { 862 | debugger("in new text element"); 863 | String content = ((org.docx4j.wml.Text)o).getValue(); 864 | if ( runs.size() == 1 && !value.toLowerCase().trim().equals("null")) 865 | { 866 | ((org.docx4j.wml.Text)o).setValue( content.replace(bookmark, 867 | value)); 868 | fixed = true; 869 | debugger("RUN WAS FIXED. CONTENT WAS "+content); 870 | debugger("Content is now "+((org.docx4j.wml.Text)o).getValue()); 871 | break; 872 | } else { 873 | if (value.toLowerCase().trim().equals("null")) 874 | { 875 | int spaceFiller = bookmark.length(); 876 | String filler = ""; 877 | for (int i=0;i children2 = TraversalUtil.getChildrenImpl(lastRun); 908 | if ( children2 != null ) 909 | { 910 | debugger("in last run"); 911 | for ( Object o : children2 ) 912 | { 913 | // UNWRAP OBJECT 914 | o = XmlUtils.unwrap(o); 915 | if ( o instanceof org.docx4j.wml.Text ) 916 | { 917 | debugger("in last run. text element"); 918 | String content = ((org.docx4j.wml.Text)o).getValue(); 919 | if ( content.length() > 0 ) 920 | { 921 | content = content.substring(endIndex+1, content.length()); 922 | if (endIndex == content.length()-1) 923 | { 924 | //((org.docx4j.wml.Text)o).setValue(""); 925 | parentNodes.remove(o); 926 | } else { 927 | ((org.docx4j.wml.Text)o).setValue(content); 928 | } 929 | fixed = true; 930 | debugger("RUN WAS FIXED. CONTENT WAS "+content); 931 | debugger("CONTENT IS "+((org.docx4j.wml.Text)o).getValue()); 932 | } 933 | } 934 | } 935 | } 936 | } 937 | 938 | // REMOVE EXTRA RUNS IN BETWEEN 939 | if (first!=null) {runs.remove(first);} 940 | if (last!=null) {runs.remove(last);} 941 | if (!runs.isEmpty()) 942 | { 943 | for ( Object x : runs) 944 | { 945 | List childrenX = TraversalUtil.getChildrenImpl(x); 946 | if ( childrenX != null) 947 | { 948 | for ( Object x2 : childrenX ) 949 | { 950 | x2 = XmlUtils.unwrap(x2); 951 | if ( x2 instanceof org.docx4j.wml.Text ) 952 | { 953 | if (((org.docx4j.wml.Text)x2) != first && 954 | ((org.docx4j.wml.Text )x2) != last) 955 | { 956 | ((org.docx4j.wml.Text)x2).setValue(""); 957 | docxBodyContent.remove(x2); 958 | } 959 | } 960 | } 961 | } 962 | } 963 | } 964 | } 965 | 966 | /** 967 | * Removes all of the calculated values belonging to formulas so that they are 968 | * recalculated when the document is opened. 969 | */ 970 | private void removeXLSXFormulaValues() 971 | { 972 | // PREPARE COLLECTION OF WORKSHEETS IN DOCUMENT 973 | ArrayList sheets = getWorksheets(); 974 | 975 | // ITERATE THROUGH EACH WORKSHEET 976 | for (WorksheetPart sheet : sheets ) 977 | { 978 | org.xlsx4j.sml.SheetData sData = sheet.getJaxbElement().getSheetData(); 979 | List rows = sData.getRow(); 980 | // ITERATE THROUGH THE ROWS 981 | for (org.xlsx4j.sml.Row row : rows) 982 | { 983 | // GET CELLS 984 | List cells = row.getC(); 985 | // ITERATE THROUGH THE CELLS 986 | for (org.xlsx4j.sml.Cell cell : cells) 987 | { 988 | org.xlsx4j.sml.STCellType a = cell.getT(); 989 | if (a == org.xlsx4j.sml.STCellType.E ) 990 | { 991 | String formula = cell.getF().getValue(); 992 | cell.setV(null); 993 | } 994 | } 995 | } 996 | } 997 | } 998 | 999 | /** 1000 | * Returns the HeaderParts and FooterParts of a docx file 1001 | */ 1002 | private List getDocxHeaderFooterParts() 1003 | { 1004 | debugger("in getDocxHeaderFooterParts"); 1005 | // Add headers/footers 1006 | RelationshipsPart rp = docxDocumentPart.getRelationshipsPart(); 1007 | List parts = new ArrayList(); 1008 | for ( Relationship r : rp.getJaxbElement().getRelationship() ) 1009 | { 1010 | if (r.getType().equals(Namespaces.HEADER) || 1011 | r.getType().equals(Namespaces.FOOTER) ) 1012 | { 1013 | JaxbXmlPart part = (JaxbXmlPart)rp.getPart(r); 1014 | parts.add( (part) ); 1015 | } 1016 | 1017 | debugger("GOT RelationshipsPart"); 1018 | } 1019 | return parts; 1020 | } 1021 | 1022 | /** 1023 | * Cleans up a string by removing its surrounders (Used for PPT Only) 1024 | */ 1025 | private String removeSurrounders(String s) 1026 | { 1027 | if ( s.startsWith("${") ) 1028 | { s = s.substring( 2, s.length() ); } 1029 | 1030 | if ( s.startsWith("$[") ) 1031 | { s = s.substring( 2, s.length() ); } 1032 | 1033 | if ( s.startsWith("![") ) 1034 | { s = s.substring( 2, s.length() ); } 1035 | 1036 | if ( s.startsWith("[") ) 1037 | { s = s.substring( 1, s.length() ); } 1038 | 1039 | if (s.endsWith("]")) 1040 | { s = s.substring( 0, s.length()-1 ); } 1041 | 1042 | if (s.endsWith("}")) 1043 | { s = s.substring( 0, s.length()-1 ); } 1044 | 1045 | if (s.endsWith("$")) 1046 | { s = s.substring( 0, s.length()-1 ); } 1047 | 1048 | return s; 1049 | } 1050 | 1051 | /** 1052 | * Turn off log4j logging 1053 | */ 1054 | protected void turnOffLogging() 1055 | { 1056 | org.docx4j.Docx4jProperties.getProperties().setProperty( 1057 | "docx4j.Log4j.Configurator.disabled", "true"); 1058 | org.docx4j.utils.Log4jConfigurator.configure(); 1059 | } 1060 | } 1061 | -------------------------------------------------------------------------------- /src/GUI.java: -------------------------------------------------------------------------------- 1 | // @Author Delvison Castillo 2 | 3 | package gov.nasa.cassini; 4 | 5 | import javax.swing.*; 6 | import java.awt.*; 7 | import java.awt.event.*; 8 | import java.util.*; 9 | import java.io.File; 10 | import javax.swing.filechooser.FileFilter; 11 | import java.io.BufferedReader; 12 | import javax.swing.border.EmptyBorder; 13 | import java.io.InputStreamReader; 14 | import java.io.Reader; 15 | import java.awt.datatransfer.DataFlavor; 16 | import java.awt.dnd.DnDConstants; 17 | import java.awt.dnd.DropTarget; 18 | import java.awt.dnd.DropTargetDropEvent; 19 | 20 | class GUI 21 | { 22 | //FRAMES 23 | JFrame frm; 24 | JFrame errorLog; 25 | //TEXTFIELDS 26 | final JTextField textField; 27 | final JTextField templateField; 28 | JComboBox fileType; 29 | //BUTTONS 30 | JButton gen; 31 | JButton templateBrowse; 32 | JButton textBrowse; 33 | JButton help; 34 | JProgressBar progressBar; 35 | //CHECKBOXES 36 | JCheckBox openCheck; 37 | //LABELS 38 | JLabel status; 39 | //LAYOUT 40 | GridBagLayout gbag = new GridBagLayout(); 41 | GridBagConstraints gbc = new GridBagConstraints(); 42 | File fileChosen; 43 | static final boolean debug = false; //FOR DEBUGGING PURPOSES 44 | private static GUI instance; //SINGLETON 45 | 46 | GUI() 47 | { 48 | //JFrame 49 | frm = new JFrame("AutoDoc (Microsoft Office Document Automator) v 1.5"); 50 | frm.setLayout(gbag); 51 | frm.setSize(640, 220); //give the frame a size 52 | frm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 53 | frm.setLocationRelativeTo( null ); //centers window on screen 54 | frm.setResizable(false); //restricts resizing 55 | 56 | // TEXTFILE INPUTS 57 | JPanel textFile = new JPanel(); 58 | textFile.setLayout(new FlowLayout()); 59 | textFile.setBorder(BorderFactory.createTitledBorder("Text file")); 60 | textField = new JTextField(15); 61 | textFile.add(textField); 62 | textBrowse = new JButton("Browse"); 63 | textFile.add(textBrowse); 64 | gbc.gridx = 0; 65 | gbc.gridy = 0; 66 | gbag.setConstraints(textFile, gbc); 67 | frm.add(textFile,gbc); 68 | 69 | // TEMPLATE FILE INPUTS 70 | JPanel templateFile = new JPanel(); 71 | templateFile.setLayout(new FlowLayout()); 72 | templateFile.setBorder(BorderFactory.createTitledBorder("Template file")); 73 | templateField = new JTextField(15); 74 | templateFile.add(templateField); 75 | templateBrowse = new JButton("Browse"); 76 | templateFile.add(templateBrowse); 77 | gbc.gridx = 1; 78 | gbc.gridy = 0; 79 | gbag.setConstraints(templateFile, gbc); 80 | frm.add(templateFile,gbc); 81 | 82 | // BUTTON PANEL 83 | JPanel btns = new JPanel(); 84 | btns.setLayout(new FlowLayout()); 85 | 86 | // HELP BUTTON 87 | help = new JButton("?"); 88 | 89 | // GENERATE BUTTON 90 | gen = new JButton("Generate"); 91 | 92 | // ADD HELP & GENERATE BTNS TO PANEL 93 | btns.add(help); 94 | help.setPreferredSize(new Dimension(35,20)); 95 | btns.add(gen); 96 | gbc.gridx = 1; 97 | gbc.gridy = 1; 98 | frm.add(new JLabel(" "),gbc); 99 | gbc.anchor = GridBagConstraints.EAST; 100 | gbc.gridx = 1; 101 | gbc.gridy = 3; 102 | frm.add(btns,gbc); 103 | 104 | // PROGRESS BAR 105 | progressBar = new JProgressBar(0, 100); 106 | progressBar.setValue(0); 107 | progressBar.setStringPainted(true); 108 | gbc.anchor = GridBagConstraints.CENTER; 109 | gbc.gridx = 0; 110 | gbc.gridy = 3; 111 | frm.add(progressBar,gbc); 112 | progressBar.setPreferredSize(new Dimension(200,30)); 113 | progressBar.setVisible(false); 114 | progressBar.setString("0%"); 115 | 116 | // STATUS LABEL 117 | status = new JLabel(" "); 118 | status.setMaximumSize(new Dimension(6,6)); 119 | status.setPreferredSize(new Dimension(200,30)); 120 | gbc.anchor = GridBagConstraints.CENTER; 121 | gbc.gridx = 0; 122 | gbc.gridy = 4; 123 | frm.add(status,gbc); 124 | if (debug) { status.setText("DEBUG MODE");} 125 | 126 | // AUTO OPEN CHECKBOX 127 | openCheck = new JCheckBox("Auto-open", true); 128 | gbc.anchor = GridBagConstraints.EAST; 129 | gbc.gridx = 1; 130 | gbc.gridy = 4; 131 | frm.add(openCheck,gbc); 132 | 133 | initDragDrop(); 134 | gbc.gridx = 0; 135 | gbc.gridy = 1; 136 | frm.setVisible(true); 137 | 138 | // ActionListener for Text File Field 139 | textBrowse.addActionListener(new ActionListener() 140 | { 141 | public void actionPerformed(ActionEvent e) 142 | { 143 | JFileChooser chooser= new JFileChooser(); 144 | chooser.setAcceptAllFileFilterUsed(false); 145 | chooser.addChoosableFileFilter(new FileFilter() 146 | { 147 | public boolean accept(File f) 148 | { 149 | // Allow directories to be seen. 150 | if ( f.isDirectory() ) 151 | { 152 | return true; 153 | } 154 | if (f.getName().toLowerCase().endsWith(".txt")) 155 | return true; 156 | return false; 157 | } 158 | public String getDescription() 159 | { 160 | return "*.txt"; 161 | } 162 | }); 163 | int choice = chooser.showOpenDialog(frm); 164 | if (choice != JFileChooser.APPROVE_OPTION) return; 165 | textField.setText(chooser.getSelectedFile().getPath()); 166 | } 167 | }); 168 | 169 | // ACTIONLISTENER FOR TEMPLATE FILE FIELD 170 | templateBrowse.addActionListener(new ActionListener() 171 | { 172 | public void actionPerformed(ActionEvent e) 173 | { 174 | JFileChooser chooser= new JFileChooser(); 175 | chooser.addChoosableFileFilter(new FileFilter() 176 | { 177 | public boolean accept(File f) 178 | { 179 | if (f.isDirectory()) { 180 | return true; 181 | } 182 | if (f.getName().toLowerCase().endsWith(".docx")) 183 | return true; 184 | if (f.getName().toLowerCase().endsWith(".pptx")) 185 | return true; 186 | if (f.getName().toLowerCase().endsWith(".xlsx")) 187 | return true; 188 | return false; 189 | } 190 | public String getDescription() 191 | { 192 | return "*.docx, *.pptx, *.xlsx"; 193 | } 194 | }); 195 | int choice = chooser.showOpenDialog(frm); 196 | if (choice != JFileChooser.APPROVE_OPTION) return; 197 | //chooser.setVisible(true); 198 | templateField.setText(chooser.getSelectedFile().getPath()); 199 | } 200 | }); 201 | 202 | // ACTIONLISTENER FOR GENERATE BUTTON 203 | gen.addActionListener(new ActionListener() 204 | { 205 | public void actionPerformed(ActionEvent thing) 206 | { 207 | status.setForeground(Color.BLACK); 208 | String templatePath=""; 209 | String textFilePath=""; 210 | progressBar.setValue(0); 211 | templatePath = templateField.getText(); 212 | textFilePath = textField.getText(); 213 | if (!templatePath.equals("") && !textFilePath.equals("")) 214 | { 215 | //SAVE FILECHOOSER 216 | JFileChooser chooser = new JFileChooser(); 217 | chooser.setDialogTitle("Specify where to save file"); 218 | chooser.addChoosableFileFilter(new FileFilter() 219 | { 220 | public boolean accept(File f) 221 | { 222 | if (f.isDirectory()) 223 | { 224 | return true; 225 | } 226 | return false; 227 | } 228 | 229 | public String getDescription() 230 | { 231 | String templatePath = templateField.getText(); 232 | return templatePath.substring(templatePath.lastIndexOf('.'), 233 | templatePath.length()); 234 | } 235 | }); 236 | 237 | int userSelection = chooser.showSaveDialog(frm); 238 | String targetPath = ""; 239 | if (userSelection == JFileChooser.APPROVE_OPTION) 240 | { 241 | progressBar.setVisible(true); 242 | status.setText("Generating file..."); 243 | File fileToSave = chooser.getSelectedFile(); 244 | targetPath = fileToSave.getAbsolutePath(); 245 | ProcessThread pt = new ProcessThread(textFilePath, templatePath, 246 | targetPath, false, checkOpen() ); 247 | pt.start(); 248 | } 249 | } else { setStatus("Error: Choose files."); } 250 | } 251 | }); 252 | 253 | // HELP ACTION LISTENER 254 | help.addActionListener(new ActionListener() 255 | { 256 | public void actionPerformed(ActionEvent thing) 257 | { 258 | JFrame hf = new JFrame("Instructions"); 259 | hf.setSize(300,480); 260 | hf.setLocationRelativeTo( frm ); //centers window on screen 261 | hf.setResizable(false); //restricts resizing 262 | JLabel ja = new JLabel( ""+renderInstructions()+"" ); 263 | ja.setPreferredSize(new Dimension(90,48)); 264 | JScrollPane sc = new JScrollPane(ja); 265 | sc.setPreferredSize(new Dimension(950,500)); 266 | 267 | java.net.URL p = getClass().getResource("/jpl_logo.png" ); 268 | JLabel about = new JLabel( ""+ 269 | renderAbout()+"" ); 270 | 271 | //TABBED PANE 272 | JTabbedPane tab = new JTabbedPane(); 273 | tab.addTab("Instructions",sc); 274 | tab.addTab("About",about); 275 | 276 | hf.add(tab); 277 | hf.setVisible(true); 278 | } 279 | }); 280 | } 281 | // SINGLETON DESIGN 282 | protected static GUI getInstance() 283 | { 284 | if(instance == null) { 285 | instance = new GUI(); 286 | } 287 | return instance; 288 | } 289 | 290 | // DISPLAYS SUCCESS MESSAGE 291 | protected void success() 292 | { 293 | status.setForeground(new Color(7,85,10)); 294 | status.setText("File successfully generated."); 295 | } 296 | 297 | // DISPLAYS FAILURE MESSAGE 298 | protected void fail() 299 | { 300 | status.setForeground(new Color(7,85,10)); 301 | status.setText("Generation was unsuccesful."); 302 | } 303 | 304 | // DISABLES BUTTONS 305 | protected void disableButton() 306 | { 307 | gen.setText("Generating.."); 308 | gen.setEnabled(false); 309 | textField.setEnabled(false); 310 | templateField.setEnabled(false); 311 | textBrowse.setEnabled(false); 312 | templateBrowse.setEnabled(false); 313 | } 314 | 315 | // ENABLES BUTTONS 316 | protected void enableButton() 317 | { 318 | gen.setText("Generate"); 319 | gen.setEnabled(true); 320 | textField.setEnabled(true); 321 | templateField.setEnabled(true); 322 | textBrowse.setEnabled(true); 323 | templateBrowse.setEnabled(true); 324 | } 325 | 326 | // RETURNS DEBUG VALUE 327 | protected boolean getDebug() 328 | { 329 | return debug; 330 | } 331 | 332 | // SET STATUS 333 | protected void setStatus(String stat) 334 | { 335 | this.status.setText(stat); 336 | } 337 | 338 | // INCREASE PROGRESS BAR 339 | protected void progress() 340 | { 341 | int i = progressBar.getValue(); 342 | if (i<90){ 343 | int j = i+2; 344 | progressBar.setValue(j); 345 | progressBar.setString(j+"%"); 346 | } 347 | } 348 | 349 | // SHOW ERRORS PANE 350 | protected void showErrors(String[] errors){ 351 | errorLog = new JFrame("Error log"); 352 | errorLog.setLayout(gbag); 353 | errorLog.setSize(310, 360); //give the frame a size 354 | errorLog.setLocationRelativeTo( null ); //centers window on screen 355 | gbc.anchor = GridBagConstraints.CENTER; 356 | gbc.gridx = 0; 357 | gbc.gridy = 0; 358 | 359 | //ERROR MESSAGE 360 | JPanel jp = new JPanel(); 361 | jp.setPreferredSize(new Dimension(200,80)); 362 | JLabel n = new JLabel("These keywords were "+ 363 | "not found in document:"); 364 | n.setMaximumSize(new Dimension(190, 50)); 365 | n.setFont(new Font( n.getFont().getFontName(), Font.BOLD, 366 | n.getFont().getSize() )); 367 | n.setForeground(Color.RED); 368 | gbag.setConstraints(n, gbc); 369 | jp.add(n); 370 | errorLog.add(n); 371 | 372 | //Add Scrollpane 373 | JList lis = new JList(errors); 374 | JScrollPane scroll = new JScrollPane(lis); 375 | scroll.setPreferredSize(new Dimension(230,250)); 376 | //lis.setPreferredSize(new Dimension(230,250)); 377 | gbag.setConstraints(scroll, gbc); 378 | gbc.anchor = GridBagConstraints.CENTER; 379 | gbc.gridx = 0; 380 | gbc.gridy = 1; 381 | errorLog.add(scroll,gbc); 382 | 383 | //OK button 384 | JButton ok = new JButton("Ok"); 385 | ok.registerKeyboardAction(ok.getActionForKeyStroke( 386 | KeyStroke.getKeyStroke(KeyEvent.VK_SPACE, 0, false)), 387 | KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0, false), 388 | JComponent.WHEN_FOCUSED); 389 | ok.registerKeyboardAction(ok.getActionForKeyStroke( 390 | KeyStroke.getKeyStroke(KeyEvent.VK_SPACE, 0, true)), 391 | KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0, true), 392 | JComponent.WHEN_FOCUSED); 393 | gbc.anchor = GridBagConstraints.CENTER; 394 | gbc.gridx = 0; 395 | gbc.gridy = 2; 396 | errorLog.add(ok,gbc); 397 | errorLog.getRootPane().setDefaultButton(ok); 398 | ok.requestFocus(); 399 | //ok.requestFocusInWindow(); 400 | //ok.setSelected(true); 401 | 402 | //OK button listener 403 | ok.addActionListener(new ActionListener() 404 | { 405 | public void actionPerformed(ActionEvent thing) 406 | { 407 | errorLog.dispose(); 408 | } 409 | }); 410 | 411 | //Display frame 412 | //errorLog.setResizable(false); //restricts resizing 413 | errorLog.setVisible(true); 414 | } 415 | 416 | // CHECK THE AUTO OPEN 417 | protected boolean checkOpen() 418 | { 419 | return openCheck.isSelected(); 420 | } 421 | 422 | // SHOW INSTRUCTIONS WINDOW 423 | protected String renderInstructions() 424 | { 425 | StringBuilder contentBuilder = new StringBuilder(); 426 | try 427 | { 428 | Reader rd = new InputStreamReader(getClass().getResourceAsStream("/instr"+ 429 | "uctions.html")); 430 | BufferedReader in = new BufferedReader(rd); 431 | String str; 432 | while ((str = in.readLine()) != null) 433 | { 434 | contentBuilder.append(str); 435 | } 436 | in.close(); 437 | }catch (java.io.IOException e) { 438 | } 439 | return contentBuilder.toString(); 440 | } 441 | 442 | protected String renderAbout() 443 | { 444 | StringBuilder contentBuilder = new StringBuilder(); 445 | try 446 | { 447 | Reader rd = new InputStreamReader(getClass().getResourceAsStream( 448 | "/about.html")); 449 | BufferedReader in = new BufferedReader(rd); 450 | String str; 451 | while ((str = in.readLine()) != null) 452 | { 453 | contentBuilder.append(str); 454 | } 455 | in.close(); 456 | }catch (java.io.IOException e) { 457 | } 458 | return contentBuilder.toString(); 459 | } 460 | 461 | // INITIALIZE DRAG N DROP 462 | protected void initDragDrop(){ 463 | //DRAG & DROP FOR TEXTFILE 464 | textField.setDropTarget(new DropTarget() 465 | { 466 | public synchronized void drop(DropTargetDropEvent e) 467 | { 468 | try 469 | { 470 | e.acceptDrop(DnDConstants.ACTION_COPY); 471 | java.util.List dropfiles = 472 | (java.util.List)e.getTransferable() 473 | .getTransferData( DataFlavor.javaFileListFlavor ); 474 | for ( File file : dropfiles ) 475 | { 476 | textField.setText( file.getAbsolutePath() ); 477 | } 478 | } catch (Exception ex) { 479 | ex.printStackTrace(); 480 | } 481 | } 482 | }); 483 | 484 | //DRAG & DROP FOR TEMPLATEFILE 485 | templateField.setDropTarget(new DropTarget() 486 | { 487 | public synchronized void drop(DropTargetDropEvent e) 488 | { 489 | try 490 | { 491 | e.acceptDrop(DnDConstants.ACTION_COPY); 492 | java.util.List dropfiles =(java.util.List)e 493 | .getTransferable().getTransferData( DataFlavor.javaFileListFlavor ); 494 | for ( File file : dropfiles ) 495 | { 496 | templateField.setText( file.getAbsolutePath() ); 497 | } 498 | } catch (Exception ex) { 499 | ex.printStackTrace(); 500 | } 501 | } 502 | }); 503 | } 504 | } 505 | -------------------------------------------------------------------------------- /src/Main.java: -------------------------------------------------------------------------------- 1 | // @Author Delvison Castillo 2 | 3 | package gov.nasa.cassini; 4 | 5 | import javax.swing.SwingUtilities; 6 | import javax.swing.UIManager.*; 7 | import javax.swing.UIManager; 8 | import org.docx4j.openpackaging.exceptions.Docx4JException; 9 | 10 | public class Main{ 11 | public static void main(final String[] args) 12 | { 13 | // TURN OFF LOG4j 14 | org.docx4j.Docx4jProperties.getProperties().setProperty( 15 | "docx4j.Log4j.Configurator.disabled", "true"); 16 | org.docx4j.utils.Log4jConfigurator.configure(); 17 | // INITIALIZE DOCx4j 18 | javax.xml.bind.JAXBContext c = org.docx4j.jaxb.Context.jc; 19 | 20 | SwingUtilities.invokeLater(new Runnable() 21 | { 22 | public void run() 23 | { 24 | try { 25 | for (LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) 26 | { 27 | if ("Nimbus".equals(info.getName())) 28 | { 29 | UIManager.setLookAndFeel(info.getClassName()); 30 | break; 31 | } 32 | } 33 | } catch (Exception e) { 34 | try { 35 | UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); 36 | } catch (Exception ex){ 37 | 38 | } 39 | } 40 | final String textfile; 41 | final String templatefile; 42 | final String savefile; 43 | boolean shouldOpen = false; 44 | boolean fourArgs = false; 45 | 46 | if (args.length == 4) 47 | { 48 | fourArgs = true; 49 | if (args[3].equals("true")) shouldOpen = true; 50 | if (args[3].equals("false")) shouldOpen = false; 51 | } 52 | 53 | if (args.length >= 3) 54 | { 55 | //TERMINAL MODE 56 | System.out.println("\nWelcome to Autodoc..."); 57 | textfile = args[0]; 58 | templatefile = args[1]; 59 | savefile = args[2]; 60 | final ProcessThread pt; 61 | 62 | // IF AUTOOPEN OPTION IS INPUT 63 | if (fourArgs){ 64 | pt = new ProcessThread(textfile,templatefile,savefile,true, 65 | shouldOpen); 66 | }else{ 67 | pt = new ProcessThread(textfile,templatefile, savefile,true,false); 68 | } 69 | pt.run(); 70 | }else{ 71 | // GUI MODE 72 | GUI.getInstance(); 73 | } 74 | } 75 | }); 76 | } 77 | } 78 | -------------------------------------------------------------------------------- /src/ProcessThread.java: -------------------------------------------------------------------------------- 1 | // @Author Delvison Castillo 2 | 3 | package gov.nasa.cassini; 4 | 5 | import java.util.ArrayList; 6 | import java.awt.Desktop; 7 | 8 | public class ProcessThread extends Thread 9 | { 10 | protected String textfilePath; 11 | protected String templatefilePath; 12 | protected String targetPath; 13 | protected String extension; 14 | protected boolean terminalMode; 15 | protected boolean shouldOpen; 16 | protected GUI gui; 17 | 18 | ProcessThread(String textfilePath, String templatefilePath, String 19 | targetPath, boolean terminalMode, boolean shouldOpen) 20 | { 21 | this.textfilePath = textfilePath; 22 | this.templatefilePath = templatefilePath; 23 | this.targetPath = targetPath; 24 | this.terminalMode = terminalMode; 25 | this.shouldOpen = shouldOpen; 26 | extension = 27 | extension = templatefilePath.substring( templatefilePath.lastIndexOf('.') 28 | ,templatefilePath.length() ); 29 | } 30 | 31 | /** 32 | * Initiates all of the backend processes. 33 | */ 34 | public void run() 35 | { 36 | if (!terminalMode) { gui = GUI.getInstance(); } 37 | if (!terminalMode) gui.disableButton(); 38 | if (!terminalMode) gui.progressBar.setVisible(true); 39 | if (!terminalMode) gui.progress(); //increase progressbar 40 | if (terminalMode) System.out.println("\nGenerating your doc..."); 41 | Functions f = new Functions(terminalMode); 42 | boolean is_success = f.generateDocument(textfilePath, templatefilePath, 43 | targetPath); 44 | if (is_success) 45 | { 46 | if (!terminalMode) gui.success(); 47 | if (!terminalMode) gui.enableButton(); 48 | if (!terminalMode) gui.progressBar.setValue(100); 49 | if (!terminalMode) gui.progressBar.setString("Complete"); 50 | if (terminalMode) System.out.println("\nDocument successfully generated"+ 51 | " at "+targetPath); 52 | this.openDocument(targetPath, shouldOpen); 53 | } 54 | else { 55 | if (!terminalMode) gui.fail(); 56 | if (!terminalMode) System.out.println("\nDocument generation failed."); 57 | } 58 | return; 59 | } 60 | 61 | protected void openDocument(String target, boolean shouldOpen) 62 | { 63 | if (shouldOpen) 64 | { 65 | try 66 | { 67 | if (target.contains(".")){ target = 68 | target.substring( 0,target.lastIndexOf('.') ); 69 | } 70 | System.out.println("Opening document...."); 71 | Desktop.getDesktop().open(new java.io.File(target+extension)); 72 | System.out.println("Done."); 73 | } catch (java.io.IOException e) 74 | { 75 | e.printStackTrace(); 76 | } 77 | } 78 | } 79 | 80 | } 81 | 82 | --------------------------------------------------------------------------------