Advertisement
Guest User

Untitled

a guest
Jul 23rd, 2014
202
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 10.38 KB | None | 0 0
  1. import java.util.ArrayList;
  2. import java.util.List;
  3. import java.util.StringTokenizer;
  4.  
  5. import javax.xml.bind.JAXBElement;
  6. import javax.xml.bind.JAXBException;
  7.  
  8. import org.docx4j.XmlUtils;
  9. import org.docx4j.openpackaging.exceptions.Docx4JException;
  10. import org.docx4j.openpackaging.packages.WordprocessingMLPackage;
  11. import org.docx4j.wml.ContentAccessor;
  12.  
  13. import org.slf4j.impl.*;
  14.  
  15. import java.io.FileInputStream;
  16. import java.io.File;
  17. import java.io.FileNotFoundException;
  18. import java.io.IOException;
  19.  
  20. import org.docx4j.wml.*;
  21.  
  22. import org.apache.commons.lang3.StringUtils;
  23.  
  24. import java.util.Enumeration;
  25. import java.util.Map;
  26. import java.util.Iterator;
  27. import java.util.Vector;
  28.  
  29. import lotus.domino.Document;
  30. import lotus.domino.*;
  31.  
  32. public class JavaTemplateDocument {
  33.  
  34.  
  35. public void mainCode(Session session, Document currDoc, String empLang, String templateType, String sArt) throws Exception {
  36.  
  37. Database dbCurr = session.getCurrentDatabase();
  38. String viewName = "vieTemplateLookup";
  39. View tview = dbCurr.getView(viewName);
  40. Vector viewKey = new Vector();
  41. viewKey.addElement(empLang);
  42. viewKey.addElement(templateType);
  43. Document templateDoc = tview.getDocumentByKey(viewKey);
  44. if (tview.getDocumentByKey(viewKey) == null ) System.out.println("templateDoc is NULL");
  45.  
  46. Item itmNotesFields = templateDoc.getFirstItem("NotesFieldList");
  47. Item itmWordFields = templateDoc.getFirstItem("WordFieldList");
  48.  
  49. Vector<String[]> notesFields = itmNotesFields.getValues();
  50. Vector<String[]> wordFields = itmWordFields.getValues();
  51.  
  52. int z = notesFields.size();
  53. int x = wordFields.size();
  54.  
  55. Enumeration e1 = notesFields.elements();
  56.  
  57. Enumeration e2 = wordFields.elements();
  58.  
  59. WordprocessingMLPackage template = getTemplate("C:\Temp\AZG Sample Template.docx");
  60.  
  61. for (int y = 0; y < x; y++) {
  62. if (currDoc.hasItem(String.valueOf(notesFields.elementAt(y)))) {
  63. Item itmNotesName = currDoc.getFirstItem(String.valueOf(notesFields.elementAt(y)));
  64. replacePlaceholder(template, itmNotesName.getText(), String.valueOf(wordFields.elementAt(y))); }
  65. else {
  66. replacePlaceholder(template, "", String.valueOf(wordFields.elementAt(y)));
  67. }
  68. }
  69.  
  70. writeDocxToStream(template, "C:\Temp\AZG Sample Document.docx");
  71. createResponseDocument(dbCurr, currDoc, templateDoc, sArt);
  72. }
  73.  
  74. private void createResponseDocument(Database dbCurr, Document currDoc, Document templateDoc, String sArt) throws NotesException{
  75.  
  76. Document respDoc = dbCurr.createDocument(); // create the response document
  77. String refVal = currDoc.getUniversalID();
  78.  
  79. respDoc.appendItemValue("IsDocTemplate", "1");
  80. if (currDoc.hasItem("Name")) {
  81. respDoc.appendItemValue("Name", currDoc.getItemValue("Name"));}
  82. else {System.out.println("Name is not available"); }
  83. if (currDoc.hasItem("Firstname")) {
  84. respDoc.appendItemValue("Firstname", currDoc.getItemValue("Firstname"));}
  85. else {System.out.println("Firstname is not available"); }
  86. if (currDoc.hasItem("ReferenceTypeTexts")) {
  87. respDoc.appendItemValue("ReferenceTypeTexts", currDoc.getItemValue("ReferenceTypeTexts"));}
  88. else {System.out.println("ReferenceTypeTexts is not available"); }
  89. if (currDoc.hasItem("ReferenceType")) {
  90. respDoc.appendItemValue("ReferenceType", currDoc.getItemValue("ReferenceType"));}
  91. else {System.out.println("ReferenceType is not available"); }
  92. System.out.println("Append Form value");
  93. respDoc.appendItemValue("Form", "frmRespTempl");
  94.  
  95.  
  96. respDoc.makeResponse(currDoc);
  97. RichTextItem body = respDoc.createRichTextItem("Body");
  98. body.embedObject(1454, "", "C:\Temp\AZG Sample Document.docx", null);
  99. respDoc.save();
  100. }
  101.  
  102.  
  103. /*
  104. * Create a simple word document that we can use as a template.
  105. * For this just open Word, create a new document and save it as template.docx.
  106. * This is the word template we'll use to add content to.
  107. * The first thing we need to do is load this document with docx4j.
  108. */
  109.  
  110. private WordprocessingMLPackage getTemplate(String name) throws Docx4JException, FileNotFoundException {
  111. WordprocessingMLPackage template = WordprocessingMLPackage.load(new FileInputStream(new File(name)));
  112. return template;
  113. }
  114.  
  115. private static List<Object> getAllElementFromObject(Object obj, Class<?> toSearch) {
  116. List<Object> result = new ArrayList<Object>();
  117. if (obj instanceof JAXBElement) obj = ((JAXBElement<?>) obj).getValue();
  118.  
  119. if (obj.getClass().equals(toSearch))
  120. result.add(obj);
  121. else if (obj instanceof ContentAccessor) {
  122. List<?> children = ((ContentAccessor) obj).getContent();
  123. for (Object child : children) {
  124. result.addAll(getAllElementFromObject(child, toSearch));
  125. }
  126.  
  127. }
  128. return result;
  129. }
  130.  
  131. /*
  132. * This will look for all the Text elements in the document, and those that match are replaced with the value we specify.
  133. */
  134.  
  135. private void replacePlaceholder(WordprocessingMLPackage template, String name, String placeholder ) {
  136. List<Object> texts = getAllElementFromObject(template.getMainDocumentPart(), Text.class);
  137.  
  138. for (Object text : texts) {
  139. Text textElement = (Text) text;
  140. if (textElement.getValue().equals(placeholder)) {
  141. textElement.setValue(name);
  142. }
  143. }
  144. }
  145.  
  146. /*
  147. * write the document back to a file
  148. */
  149.  
  150. private void writeDocxToStream(WordprocessingMLPackage template, String target) throws IOException, Docx4JException {
  151. File f = new File(target);
  152. template.save(f);
  153. }
  154.  
  155. /*
  156. * Example code for replaceParagraph
  157. *
  158. String placeholder = "SJ_EX1";
  159. String toAdd = "josndirksen";
  160.  
  161. replaceParagraph(placeholder, toAdd, template, template.getMainDocumentPart());
  162. */
  163.  
  164. private void replaceParagraph(String placeholder, String textToAdd, WordprocessingMLPackage template, ContentAccessor addTo) {
  165. // 1. get the paragraph
  166. List<Object> paragraphs = getAllElementFromObject(template.getMainDocumentPart(), P.class);
  167.  
  168. P toReplace = null;
  169. for (Object p : paragraphs) {
  170. List<Object> texts = getAllElementFromObject(p, Text.class);
  171. for (Object t : texts) {
  172. Text content = (Text) t;
  173. if (content.getValue().equals(placeholder)) {
  174. toReplace = (P) p;
  175. break;
  176. }
  177. }
  178. }
  179.  
  180. // we now have the paragraph that contains our placeholder: toReplace
  181. // 2. split into seperate lines
  182. String as[] = StringUtils.splitPreserveAllTokens(textToAdd, 'n');
  183.  
  184. for (int i = 0; i < as.length; i++) {
  185. String ptext = as[i];
  186.  
  187. // 3. copy the found paragraph to keep styling correct
  188. P copy = (P) XmlUtils.deepCopy(toReplace);
  189.  
  190. // replace the text elements from the copy
  191. List<?> texts = getAllElementFromObject(copy, Text.class);
  192. if (texts.size() > 0) {
  193. Text textToReplace = (Text) texts.get(0);
  194. textToReplace.setValue(ptext);
  195. }
  196.  
  197. // add the paragraph to the document
  198. addTo.getContent().add(copy);
  199. }
  200.  
  201. // 4. remove the original one
  202. ((ContentAccessor)toReplace.getParent()).getContent().remove(toReplace);
  203.  
  204. }
  205.  
  206. /*
  207. * A set of hashmaps that contain the name of the placeholder to replace and the value to replace it with.
  208. *
  209. * Map<String,String> repl1 = new HashMap<String, String>();
  210. repl1.put("SJ_FUNCTION", "function1");
  211. repl1.put("SJ_DESC", "desc1");
  212. repl1.put("SJ_PERIOD", "period1");
  213.  
  214. Map<String,String> repl2 = new HashMap<String, String>();
  215. repl2.put("SJ_FUNCTION", "function2");
  216. repl2.put("SJ_DESC", "desc2");
  217. repl2.put("SJ_PERIOD", "period2");
  218.  
  219. Map<String,String> repl3 = new HashMap<String, String>();
  220. repl3.put("SJ_FUNCTION", "function3");
  221. repl3.put("SJ_DESC", "desc3");
  222. repl3.put("SJ_PERIOD", "period3");
  223.  
  224. replaceTable(new String[]{"SJ_FUNCTION","SJ_DESC","SJ_PERIOD"}, Arrays.asList(repl1,repl2,repl3), template);
  225. */
  226.  
  227. private void replaceTable(String[] placeholders, List<Map<String, String>> textToAdd,
  228. WordprocessingMLPackage template) throws Docx4JException, JAXBException {
  229. List<Object> tables = getAllElementFromObject(template.getMainDocumentPart(), Tbl.class);
  230.  
  231. // 1. find the table
  232. Tbl tempTable = getTemplateTable(tables, placeholders[0]);
  233. List<Object> rows = getAllElementFromObject(tempTable, Tr.class);
  234.  
  235. // first row is header, second row is content
  236. if (rows.size() == 2) {
  237. // this is our template row
  238. Tr templateRow = (Tr) rows.get(1);
  239.  
  240. for (Map<String, String> replacements : textToAdd) {
  241. // 2 and 3 are done in this method
  242. addRowToTable(tempTable, templateRow, replacements);
  243. }
  244.  
  245. // 4. remove the template row
  246. tempTable.getContent().remove(templateRow);
  247. }
  248. }
  249.  
  250. private Tbl getTemplateTable(List<Object> tables, String templateKey) throws Docx4JException, JAXBException {
  251. for (Iterator<Object> iterator = tables.iterator(); iterator.hasNext();) {
  252. Object tbl = iterator.next();
  253. List<?> textElements = getAllElementFromObject(tbl, Text.class);
  254. for (Object text : textElements) {
  255. Text textElement = (Text) text;
  256. if (textElement.getValue() != null && textElement.getValue().equals(templateKey))
  257. return (Tbl) tbl;
  258. }
  259. }
  260. return null;
  261. }
  262.  
  263. private static void addRowToTable(Tbl reviewtable, Tr templateRow, Map<String, String> replacements) {
  264. Tr workingRow = (Tr) XmlUtils.deepCopy(templateRow);
  265. List<?> textElements = getAllElementFromObject(workingRow, Text.class);
  266. for (Object object : textElements) {
  267. Text text = (Text) object;
  268. String replacementValue = (String) replacements.get(text.getValue());
  269. if (replacementValue != null)
  270. text.setValue(replacementValue);
  271. }
  272.  
  273. reviewtable.getContent().add(workingRow);
  274. }
  275.  
  276. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement