List of usage examples for org.apache.poi.xwpf.usermodel XWPFDocument XWPFDocument
public XWPFDocument(InputStream is) throws IOException
From source file:org.obeonetwork.m2doc.tests.parser.RunProviderTests.java
License:Open Source License
@Test public void testNonEmptyDoc() throws InvalidFormatException, IOException { try (FileInputStream is = new FileInputStream("resources/document/notEmpty/notEmpty-template.docx"); OPCPackage oPackage = OPCPackage.open(is); XWPFDocument document = new XWPFDocument(oPackage);) { TokenProvider iterator = new TokenProvider(document); XWPFRun run = iterator.next().getRun(); assertEquals("P1Run1 ", run.getText(run.getTextPosition())); run = iterator.next().getRun();//from w w w .j a v a 2s . co m assertEquals("P1Run2", run.getText(run.getTextPosition())); run = iterator.next().getRun(); assertEquals(" P1Run3", run.getText(run.getTextPosition())); run = iterator.next().getRun(); assertEquals("P2Run1 ", run.getText(run.getTextPosition())); run = iterator.next().getRun(); assertEquals("P2Run2", run.getText(run.getTextPosition())); run = iterator.next().getRun(); assertEquals(" ", run.getText(run.getTextPosition())); run = iterator.next().getRun(); assertEquals("P2Run3", run.getText(run.getTextPosition())); run = iterator.next().getRun(); assertEquals("", run.getText(run.getTextPosition())); assertTrue(!iterator.hasNext()); } }
From source file:org.obeonetwork.m2doc.tests.parser.RunProviderTests.java
License:Open Source License
@Test(expected = NoSuchElementException.class) public void testAccessEmptyIterator() throws InvalidFormatException, IOException { try (FileInputStream is = new FileInputStream("resources/document/notEmpty/notEmpty-template.docx"); OPCPackage oPackage = OPCPackage.open(is); XWPFDocument document = new XWPFDocument(oPackage);) { TokenProvider iterator = new TokenProvider(document); iterator.next().getRun();/* ww w. j a v a2 s. com*/ iterator.next().getRun(); iterator.next().getRun(); iterator.next().getRun(); iterator.next().getRun(); iterator.next().getRun(); iterator.next().getRun(); iterator.next().getRun(); iterator.next().getRun(); } }
From source file:org.obeonetwork.m2doc.tests.parser.RunProviderTests.java
License:Open Source License
@Test public void testLookaheadEmptyIterator() throws InvalidFormatException, IOException { try (FileInputStream is = new FileInputStream("resources/document/notEmpty/notEmpty-template.docx"); OPCPackage oPackage = OPCPackage.open(is); XWPFDocument document = new XWPFDocument(oPackage);) { TokenProvider iterator = new TokenProvider(document); iterator.next().getRun();/* www. j a v a 2 s .co m*/ iterator.next().getRun(); iterator.next().getRun(); iterator.next().getRun(); iterator.next().getRun(); iterator.next().getRun(); iterator.next().getRun(); iterator.next().getRun(); assertNull(iterator.lookAhead(1)); } }
From source file:org.obeonetwork.m2doc.tests.parser.RunProviderTests.java
License:Open Source License
@Test public void testHasElements() throws InvalidFormatException, IOException { try (FileInputStream is = new FileInputStream("resources/document/notEmpty/notEmpty-template.docx"); OPCPackage oPackage = OPCPackage.open(is); XWPFDocument document = new XWPFDocument(oPackage);) { TokenProvider iterator = new TokenProvider(document); // CHECKSTYLE:OFF assertTrue(iterator.hasElements(7)); // CHECKSTYLE:ON XWPFRun run = iterator.next().getRun(); assertTrue(iterator.hasElements(6)); assertEquals("P1Run1 ", run.getText(run.getTextPosition())); run = iterator.next().getRun();/*from ww w. j a v a2s. com*/ assertTrue(iterator.hasElements(5)); assertEquals("P1Run2", run.getText(run.getTextPosition())); run = iterator.next().getRun(); assertTrue(iterator.hasElements(4)); assertEquals(" P1Run3", run.getText(run.getTextPosition())); run = iterator.next().getRun(); assertTrue(iterator.hasElements(3)); assertEquals("P2Run1 ", run.getText(run.getTextPosition())); run = iterator.next().getRun(); assertTrue(iterator.hasElements(2)); assertEquals("P2Run2", run.getText(run.getTextPosition())); run = iterator.next().getRun(); assertTrue(iterator.hasElements(1)); assertEquals(" ", run.getText(run.getTextPosition())); run = iterator.next().getRun(); assertTrue(iterator.hasElements(0)); assertEquals("P2Run3", run.getText(run.getTextPosition())); run = iterator.next().getRun(); assertEquals("", run.getText(run.getTextPosition())); assertTrue(!iterator.hasNext()); } }
From source file:org.obeonetwork.m2doc.tests.parser.RunProviderTests.java
License:Open Source License
@Test public void testLookAhead() throws InvalidFormatException, IOException { try (FileInputStream is = new FileInputStream("resources/document/notEmpty/notEmpty-template.docx"); OPCPackage oPackage = OPCPackage.open(is); XWPFDocument document = new XWPFDocument(oPackage);) { TokenProvider iterator = new TokenProvider(document); // CHECKSTYLE:OFF assertTrue(iterator.hasElements(7)); XWPFRun run;// w w w .j ava2 s .com run = iterator.lookAhead(1).getRun(); assertEquals("P1Run1 ", run.getText(run.getTextPosition())); run = iterator.lookAhead(2).getRun(); assertEquals("P1Run2", run.getText(run.getTextPosition())); run = iterator.lookAhead(3).getRun(); assertEquals(" P1Run3", run.getText(run.getTextPosition())); run = iterator.lookAhead(4).getRun(); assertEquals("P2Run1 ", run.getText(run.getTextPosition())); run = iterator.lookAhead(5).getRun(); assertEquals("P2Run2", run.getText(run.getTextPosition())); run = iterator.lookAhead(6).getRun(); assertEquals(" ", run.getText(run.getTextPosition())); run = iterator.lookAhead(7).getRun(); assertEquals("P2Run3", run.getText(run.getTextPosition())); assertTrue(iterator.hasElements(7)); // CHECKSTYLE:ON } }
From source file:org.obeonetwork.m2doc.tests.parser.RunProviderTests.java
License:Open Source License
@Test public void testNextWitLookAhead() throws InvalidFormatException, IOException { try (FileInputStream is = new FileInputStream("resources/document/notEmpty/notEmpty-template.docx"); OPCPackage oPackage = OPCPackage.open(is); XWPFDocument document = new XWPFDocument(oPackage);) { TokenProvider iterator = new TokenProvider(document); // CHECKSTYLE:OFF assertTrue(iterator.hasElements(7)); // CHECKSTYLE:ON XWPFRun run;/*from www .j av a 2s .com*/ run = iterator.lookAhead(1).getRun(); assertEquals("P1Run1 ", run.getText(run.getTextPosition())); run = iterator.next().getRun(); assertEquals("P1Run1 ", run.getText(run.getTextPosition())); run = iterator.lookAhead(1).getRun(); assertEquals("P1Run2", run.getText(run.getTextPosition())); run = iterator.lookAhead(2).getRun(); assertEquals(" P1Run3", run.getText(run.getTextPosition())); run = iterator.next().getRun(); assertEquals("P1Run2", run.getText(run.getTextPosition())); run = iterator.next().getRun(); assertEquals(" P1Run3", run.getText(run.getTextPosition())); assertTrue(iterator.hasElements(4)); } }
From source file:org.obeonetwork.m2doc.ui.popup.actions.GenerateDocumentation.java
License:Open Source License
/** * Launch the documentation generation./* w w w .j av a 2 s. co m*/ * * @param generation * the generation configuration object * @param definitions * the set of definitions associated to the generation * @throws IOException * if an I/O problem occurs * @throws DocumentParserException * if the document coulnd'nt be parsed. * @throws DocumentGenerationException * if the document couldn't be generated */ private void generate(Generation generation, Map<String, Object> definitions) throws IOException, DocumentParserException, DocumentGenerationException { IQueryEnvironment queryEnvironment = org.eclipse.acceleo.query.runtime.Query .newEnvironmentWithDefaultServices(null); registerServices(queryEnvironment); for (String nsURI : generation.getPackagesNSURI()) { EPackage p = EPackage.Registry.INSTANCE.getEPackage(nsURI); if (p == null) { Activator.getDefault().getLog().log(new Status(Status.WARNING, Activator.PLUGIN_ID, "Couldn't find package with nsURI " + nsURI)); } else { queryEnvironment.registerEPackage(p); } } IWorkspace workspace = ResourcesPlugin.getWorkspace(); workspace.getRoot().getLocation(); IContainer container = workspace.getRoot() .findMember(generation.eResource().getURI().toPlatformString(true)).getParent(); while (!(container instanceof IProject)) { container = container.getParent(); } if (generation.getTemplateFileName() == null) { throw new DocumentGenerationException("Template file name must be filled."); } if (generation.getResultFileName() == null) { throw new DocumentGenerationException("Generated file name must be filled."); } IFile templateFile = container.getFile(new Path(generation.getTemplateFileName())); IFile generatedFile = container.getFile(new Path(generation.getResultFileName())); String projectRoot = container.getLocation().toString(); if (!templateFile.exists()) { MessageDialog.openError(shell, "File not found", "Couldn't find file " + templateFile); return; } FileInputStream is = new FileInputStream(templateFile.getLocation().toFile()); OPCPackage oPackage; try { oPackage = OPCPackage.open(is); } catch (InvalidFormatException e) { throw new IllegalArgumentException("Couldn't open template", e); } XWPFDocument document = new XWPFDocument(oPackage); DocumentParser parser = new DocumentParser(document, queryEnvironment); DocumentTemplate template = parser.parseDocument(); DocumentGenerator generator = new DocumentGenerator(projectRoot, templateFile.getLocation().toFile().getAbsolutePath(), generatedFile.getLocation().toFile().getAbsolutePath(), template, definitions, queryEnvironment); generator.generate(); MessageDialog.openConfirm(shell, "M2Doc generation", "document " + generatedFile.getLocation().toString() + " generated"); }
From source file:org.roiderh.machinetoolconfsheet.CreateMachineToolConfSheetAction.java
License:Open Source License
@Override public void actionPerformed(ActionEvent e) { BaseDocument doc = null;/*from www . j a v a2 s .co m*/ JTextComponent ed = org.netbeans.api.editor.EditorRegistry.lastFocusedComponent(); if (ed == null) { JOptionPane.showMessageDialog(null, "Error: no open editor"); //NOI18N return; } FileObject fo = NbEditorUtilities.getFileObject(ed.getDocument()); String path = fo.getPath(); InputStream is = new ByteArrayInputStream(ed.getText().getBytes()); BufferedReader br; br = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8"))); //NOI18N ArrayList<String> lines = new ArrayList<>(); try { String line; while ((line = br.readLine()) != null) { lines.add(line); System.out.println(line); } } catch (IOException x) { JOptionPane.showMessageDialog(null, "Error: " + x.getLocalizedMessage()); //NOI18N } TreeMap<Integer, Tool> tools = new TreeMap<>(); ArrayList<String> programs = new ArrayList<>(); int activ_tool = -1; // Read all Tools with comments: for (int i = lines.size() - 1; i >= 0; i--) { String line = lines.get(i).trim(); Matcher tool_change_command = Pattern.compile("(T)([0-9])+").matcher(line); //NOI18N if (line.startsWith("(") || line.startsWith(";")) { //NOI18N if (activ_tool >= 0) { Tool t = tools.get(activ_tool); if (line.startsWith("(")) { //NOI18N line = line.substring(1, line.length() - 1); } else { line = line.substring(1, line.length()); } t.text.add(line); tools.put(activ_tool, t); } } else if (line.trim().startsWith("%")) { //NOI18N activ_tool = -1; } else if (tool_change_command.find()) { String ts = line.substring(tool_change_command.start() + 1, tool_change_command.end()); activ_tool = Integer.parseInt(ts); if (!tools.containsKey(activ_tool)) { tools.put(activ_tool, new Tool()); } } else if (line.contains("M30") || line.contains("M17") || line.contains("M2") || line.contains("M02") || line.contains("RET")) { //NOI18N activ_tool = -1; } else { activ_tool = -1; } //System.out.println("line=" + line); } boolean is_header = false; ArrayList<String> header = new ArrayList<>(); // Read the Comments at the beginning of the file: for (int i = 0; i < lines.size(); i++) { String line = lines.get(i).trim(); if (line.trim().startsWith("%")) { //NOI18N is_header = true; //programs.add(line.replaceAll(" ", "")); //NOI18N programs.add(this.parse_progname(line)); //header.add(line.replaceAll(" ", "")); //NOI18N } else if (line.trim().startsWith("(") || line.trim().startsWith(";")) { //NOI18N if (is_header) { if (line.trim().startsWith("(")) { //NOI18N line = line.trim().substring(1, line.length() - 1); } else { line = line.trim().substring(1, line.length()); } if (line.startsWith("$PATH=/_N_") || line.length() < 1) { //NOI18N } else { header.add(line.trim()); } } } else { is_header = false; } } try { Date dNow = new Date(); SimpleDateFormat ft = new SimpleDateFormat("dd.MM.yyyy"); //NOI18N System.out.println("Current Date: " + ft.format(dNow)); //NOI18N InputStream in = CreateMachineToolConfSheetAction.class .getResourceAsStream("/org/roiderh/machinetoolconfsheet/resources/base_document.docx"); //NOI18N XWPFDocument document = new XWPFDocument(in); //Write the Document in file system File tempFile = File.createTempFile("NcToolSettings_", ".docx"); //NOI18N try (FileOutputStream out = new FileOutputStream(tempFile)) { XWPFTable table = document.getTableArray(0); XWPFParagraph title = document.getParagraphArray(0); XWPFRun run = title.createRun(); run.setText(org.openide.util.NbBundle.getMessage(CreateMachineToolConfSheetAction.class, "MachineToolConfSheet")); title = document.getParagraphArray(1); run = title.createRun(); run.setText(org.openide.util.NbBundle.getMessage(CreateMachineToolConfSheetAction.class, "Tools")); String prog = String.join(", ", programs); //NOI18N table.getRow(0).getCell(0).setText( org.openide.util.NbBundle.getMessage(CreateMachineToolConfSheetAction.class, "ProgNr")); table.getRow(0).getCell(1).setText(prog); table.getRow(1).getCell(0).setText( org.openide.util.NbBundle.getMessage(CreateMachineToolConfSheetAction.class, "Filename")); table.getRow(1).getCell(1).setText(path); table.getRow(2).getCell(0).setText( org.openide.util.NbBundle.getMessage(CreateMachineToolConfSheetAction.class, "Date")); table.getRow(2).getCell(1).setText(ft.format(dNow)); ArrayList<ArrayList<String>> table_text = new ArrayList<>(); for (int i = 0; i < header.size(); i++) { ArrayList<String> line = new ArrayList<>(); String name; // first column String desc; // second column int splitpos = header.get(i).indexOf(":");//NOI18N if (splitpos > 1 && splitpos < 25) { name = header.get(i).substring(0, splitpos).trim(); desc = header.get(i).substring(splitpos + 1).trim(); } else { name = "";//NOI18N desc = header.get(i).trim(); } line.add(name); line.add(desc); table_text.add(line); } XWPFTableRow tableRowHeader; //tableRowHeader = table.createRow(); tableRowHeader = null; XWPFRun run_table; String prev_name = "dummy_1234567890sadfsaf"; //NOI18N for (int i = 0; i < table_text.size(); i++) { String name = table_text.get(i).get(0); String desc = table_text.get(i).get(1); if (name.length() > 0) { tableRowHeader = table.createRow(); run_table = tableRowHeader.getCell(1).getParagraphs().get(0).createRun(); tableRowHeader.getCell(0).setText(name); run_table.setText(desc); } else if (prev_name.length() > 0 && name.length() == 0) { tableRowHeader = table.createRow(); run_table = tableRowHeader.getCell(1).getParagraphs().get(0).createRun(); tableRowHeader.getCell(0).setText(""); //NOI18N run_table.setText(desc); } else if (prev_name.length() == 0 && name.length() == 0) { if (tableRowHeader == null) { tableRowHeader = table.createRow(); } run_table = tableRowHeader.getCell(1).getParagraphs().get(0).createRun(); run_table.addBreak(); run_table.setText(desc); } prev_name = name; } table = document.getTableArray(1); boolean first_line = true; Set keys = tools.keySet(); for (Iterator i = keys.iterator(); i.hasNext();) { int toolnr = (Integer) i.next(); Tool t = tools.get(toolnr); XWPFTableRow tableRowTwo; if (first_line) { tableRowTwo = table.getRow(0); first_line = false; } else { tableRowTwo = table.createRow(); } tableRowTwo.getCell(0).setText("T" + String.valueOf(toolnr)); //NOI18N // The lines are in the reverse order, therfore reordering: for (int j = t.text.size() - 1; j >= 0; j--) { XWPFRun run_tool = tableRowTwo.getCell(1).getParagraphs().get(0).createRun(); run_tool.setText(t.text.get(j)); if (j > 0) { run_tool.addBreak(); } } } document.write(out); } System.out.println("create_table.docx written successully"); //NOI18N Runtime rt = Runtime.getRuntime(); String os = System.getProperty("os.name").toLowerCase();//NOI18N String[] command = new String[2]; //command[0] = "soffice"; Preferences pref = NbPreferences.forModule(WordProcessingProgramPanel.class); command[0] = pref.get("executeable", "").trim();//NOI18N command[1] = tempFile.getCanonicalPath(); File f = new File(command[0]); if (!f.exists()) { JOptionPane.showMessageDialog(null, "Error: program not found: " + command[0]); //NOI18N return; } Process proc = rt.exec(command); //NOI18N //System.out.println("ready created: " + tempFile.getCanonicalPath()); //NOI18N } catch (IOException | MissingResourceException ex) { JOptionPane.showMessageDialog(null, "Error: " + ex.getLocalizedMessage()); //NOI18N } }
From source file:org.shareok.data.documentProcessor.WordHandler.java
private String[] readDocxFile(FileInputStream fs) throws IOException { String[] paragraphs = null;/* w ww .j a v a 2 s . c o m*/ try { // XWPFDocument doc = new XWPFDocument(); // XWPFParagraph p1 = doc.createParagraph(); // p1.setAlignment(ParagraphAlignment.CENTER); // p1.setBorderBottom(Borders.DOUBLE); // p1.setBorderTop(Borders.DOUBLE); // // p1.setBorderRight(Borders.DOUBLE); // p1.setBorderLeft(Borders.DOUBLE); // p1.setBorderBetween(Borders.SINGLE); // // p1.setVerticalAlignment(TextAlignment.TOP); // // XWPFRun r1 = p1.createRun(); // r1.setBold(true); // r1.setText("The quick brown fox"); // r1.setBold(true); // r1.setFontFamily("Courier"); // r1.setUnderline(UnderlinePatterns.DOT_DOT_DASH); // r1.setTextPosition(100); // // XWPFParagraph p2 = doc.createParagraph(); // p2.setAlignment(ParagraphAlignment.RIGHT); // // //BORDERS // p2.setBorderBottom(Borders.DOUBLE); // p2.setBorderTop(Borders.DOUBLE); // p2.setBorderRight(Borders.DOUBLE); // p2.setBorderLeft(Borders.DOUBLE); // p2.setBorderBetween(Borders.SINGLE); // // XWPFRun r2 = p2.createRun(); // r2.setText("jumped over the lazy dog"); // r2.setStrike(true); // r2.setFontSize(20); // // XWPFRun r3 = p2.createRun(); // r3.setText("and went away"); // r3.setStrike(true); // r3.setFontSize(20); // r3.setSubscript(VerticalAlign.SUPERSCRIPT); // // // XWPFParagraph p3 = doc.createParagraph(); // p3.setWordWrap(true); // p3.setPageBreak(true); // // //p3.setAlignment(ParagraphAlignment.DISTRIBUTE); // p3.setAlignment(ParagraphAlignment.BOTH); // p3.setSpacingLineRule(LineSpacingRule.EXACT); // // p3.setIndentationFirstLine(600); // // // XWPFRun r4 = p3.createRun(); // r4.setTextPosition(20); // r4.setText("To be, or not to be: that is the question: " // + "Whether 'tis nobler in the mind to suffer " // + "The slings and arrows of outrageous fortune, " // + "Or to take arms against a sea of troubles, " // + "And by opposing end them? To die: to sleep; "); // r4.addBreak(BreakType.PAGE); // r4.setText("No more; and by a sleep to say we end " // + "The heart-ache and the thousand natural shocks " // + "That flesh is heir to, 'tis a consummation " // + "Devoutly to be wish'd. To die, to sleep; " // + "To sleep: perchance to dream: ay, there's the rub; " // + "......."); // r4.setItalic(true); ////This would imply that this break shall be treated as a simple line break, and break the line after that word: // // XWPFRun r5 = p3.createRun(); // r5.setTextPosition(-10); // r5.setText("For in that sleep of death what dreams may come"); // r5.addCarriageReturn(); // r5.setText("When we have shuffled off this mortal coil," // + "Must give us pause: there's the respect" // + "That makes calamity of so long life;"); // r5.addBreak(); // r5.setText("For who would bear the whips and scorns of time," // + "The oppressor's wrong, the proud man's contumely,"); // // r5.addBreak(BreakClear.ALL); // r5.setText("The pangs of despised love, the law's delay," // + "The insolence of office and the spurns" + "......."); // // FileOutputStream out = new FileOutputStream("simple.docx"); // doc.write(out); // out.close(); XWPFDocument document = new XWPFDocument(OPCPackage.open("simple.docx")); List<XWPFParagraph> paragraphList = document.getParagraphs(); paragraphs = new String[paragraphList.size()]; int i = 0; for (XWPFParagraph para : paragraphList) { paragraphs[i] = para.getText(); } } catch (Exception e) { e.printStackTrace(); } finally { fs.close(); } return paragraphs; }
From source file:org.sleuthkit.autopsy.imageExtractor.ImageExtractor.java
private List<ExtractedImage> extractImagesFromDocx(AbstractFile af) { // check for BBArtifact ENCRYPTION_DETECTED? Might be detected elsewhere...? // TODO check for BBArtifact ENCRYPTION_DETECTED? Might be detected elsewhere...? List<ExtractedImage> listOfExtractedImages = new ArrayList<ExtractedImage>(); String parentFileName = getUniqueName(af); XWPFDocument docxA = null;//from w ww . j a va 2 s .c om try { docxA = new XWPFDocument(new ReadContentInputStream(af)); } catch (IOException ex) { logger.log(Level.WARNING, "XWPFDocument container could not be instantiated while reading " + af.getName(), ex); return null; } List<XWPFPictureData> listOfAllPictures = docxA.getAllPictures(); // if no images are extracted from the ppt, return null, else initialize // the output folder for image extraction. String outputFolderPath; if (listOfAllPictures.isEmpty()) { return null; } else { outputFolderPath = getOutputFolderPath(parentFileName); } if (outputFolderPath == null) { logger.log(Level.WARNING, "Could not get path for image extraction from AbstractFile: {0}", af.getName()); return null; } for (XWPFPictureData xwpfPicture : listOfAllPictures) { String fileName = xwpfPicture.getFileName(); FileOutputStream fos = null; try { fos = new FileOutputStream(outputFolderPath + File.separator + fileName); } catch (FileNotFoundException ex) { logger.log(Level.WARNING, "Invalid path provided for image extraction", ex); continue; } try { fos.write(xwpfPicture.getData()); fos.close(); } catch (IOException ex) { logger.log(Level.WARNING, "Could not write to the provided location", ex); continue; } String fileRelativePath = File.separator + moduleDirRelative + File.separator + parentFileName + File.separator + fileName; long size = xwpfPicture.getData().length; ExtractedImage extractedimage = new ExtractedImage(fileName, fileRelativePath, size, af); listOfExtractedImages.add(extractedimage); } return listOfExtractedImages; }