From: Mark Murphy Date: Mon, 7 Nov 2016 05:35:18 +0000 (+0000) Subject: Move XWPF examples to new package to clean up code coverage X-Git-Tag: REL_3_16_BETA1~18 X-Git-Url: https://source.dussan.org/?a=commitdiff_plain;h=9c527e133f20370f662f7c8c9e7f6f7915b0ce09;p=poi.git Move XWPF examples to new package to clean up code coverage git-svn-id: https://svn.apache.org/repos/asf/poi/trunk@1768437 13f79535-47bb-0310-9956-ffa450edef68 --- diff --git a/src/examples/src/org/apache/poi/xwpf/usermodel/BetterHeaderFooterExample.java b/src/examples/src/org/apache/poi/xwpf/usermodel/BetterHeaderFooterExample.java deleted file mode 100644 index 99e7dd1ba5..0000000000 --- a/src/examples/src/org/apache/poi/xwpf/usermodel/BetterHeaderFooterExample.java +++ /dev/null @@ -1,55 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.xwpf.usermodel; - -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.OutputStream; - -import org.apache.poi.wp.usermodel.HeaderFooterType; - -public class BetterHeaderFooterExample { - - public static void main(String[] args) { - XWPFDocument doc = new XWPFDocument(); - - XWPFParagraph p = doc.createParagraph(); - - XWPFRun r = p.createRun(); - r.setText("Some Text"); - r.setBold(true); - r = p.createRun(); - r.setText("Goodbye"); - - // create header/footer functions insert an empty paragraph - XWPFHeader head = doc.createHeader(HeaderFooterType.DEFAULT); - head.createParagraph().createRun().setText("header"); - - XWPFFooter foot = doc.createFooter(HeaderFooterType.DEFAULT); - foot.createParagraph().createRun().setText("footer"); - - try { - OutputStream os = new FileOutputStream(new File("header2.docx")); - doc.write(os); - doc.close(); - } catch (IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } -} diff --git a/src/examples/src/org/apache/poi/xwpf/usermodel/HeaderFooterTable.java b/src/examples/src/org/apache/poi/xwpf/usermodel/HeaderFooterTable.java deleted file mode 100644 index cd1d21f48e..0000000000 --- a/src/examples/src/org/apache/poi/xwpf/usermodel/HeaderFooterTable.java +++ /dev/null @@ -1,97 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.xwpf.usermodel; - -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.OutputStream; -import java.math.BigInteger; - -import org.apache.poi.wp.usermodel.HeaderFooterType; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTbl; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTblGrid; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTblGridCol; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTblLayoutType; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTblPr; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.STTblLayoutType; - -public class HeaderFooterTable { - - public static void main(String[] args) throws IOException { - XWPFDocument doc = new XWPFDocument(); - - // Create a header with a 1 row, 3 column table - // changes made for issue 57366 allow a new header or footer - // to be created empty. This is a change. You will have to add - // either a paragraph or a table to the header or footer for - // the document to be considered valid. - XWPFHeader hdr = doc.createHeader(HeaderFooterType.DEFAULT); - XWPFTable tbl = hdr.createTable(1, 3); - - // Set the padding around text in the cells to 1/10th of an inch - int pad = (int) (.1 * 1440); - tbl.setCellMargins(pad, pad, pad, pad); - - // Set table width to 6.5 inches in 1440ths of a point - tbl.setWidth((int)(6.5 * 1440)); - // Can not yet set table or cell width properly, tables default to - // autofit layout, and this requires fixed layout - CTTbl ctTbl = tbl.getCTTbl(); - CTTblPr ctTblPr = ctTbl.addNewTblPr(); - CTTblLayoutType layoutType = ctTblPr.addNewTblLayout(); - layoutType.setType(STTblLayoutType.FIXED); - - // Now set up a grid for the table, cells will fit into the grid - // Each cell width is 3120 in 1440ths of an inch, or 1/3rd of 6.5" - BigInteger w = new BigInteger("3120"); - CTTblGrid grid = ctTbl.addNewTblGrid(); - for (int i = 0; i < 3; i++) { - CTTblGridCol gridCol = grid.addNewGridCol(); - gridCol.setW(w); - } - - // Add paragraphs to the cells - XWPFTableRow row = tbl.getRow(0); - XWPFTableCell cell = row.getCell(0); - XWPFParagraph p = cell.getParagraphArray(0); - XWPFRun r = p.createRun(); - r.setText("header left cell"); - - cell = row.getCell(1); - p = cell.getParagraphArray(0); - r = p.createRun(); - r.setText("header center cell"); - - cell = row.getCell(2); - p = cell.getParagraphArray(0); - r = p.createRun(); - r.setText("header right cell"); - - // Create a footer with a Paragraph - XWPFFooter ftr = doc.createFooter(HeaderFooterType.DEFAULT); - p = ftr.createParagraph(); - - r = p.createRun(); - r.setText("footer text"); - - OutputStream os = new FileOutputStream(new File("headertable.docx")); - doc.write(os); - doc.close(); - } - -} diff --git a/src/examples/src/org/apache/poi/xwpf/usermodel/SimpleDocument.java b/src/examples/src/org/apache/poi/xwpf/usermodel/SimpleDocument.java deleted file mode 100644 index b7e4da2d4e..0000000000 --- a/src/examples/src/org/apache/poi/xwpf/usermodel/SimpleDocument.java +++ /dev/null @@ -1,120 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.xwpf.usermodel; - -import java.io.FileOutputStream; - -/** - * A simple WOrdprocessingML document created by POI XWPF API - * - * @author Yegor Kozlov - */ -public class SimpleDocument { - - public static void main(String[] args) throws Exception { - 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(); - - } -} diff --git a/src/examples/src/org/apache/poi/xwpf/usermodel/SimpleDocumentWithHeader.java b/src/examples/src/org/apache/poi/xwpf/usermodel/SimpleDocumentWithHeader.java deleted file mode 100644 index 68660733e6..0000000000 --- a/src/examples/src/org/apache/poi/xwpf/usermodel/SimpleDocumentWithHeader.java +++ /dev/null @@ -1,76 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.xwpf.usermodel; - -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.OutputStream; - -import org.apache.poi.xwpf.model.XWPFHeaderFooterPolicy; -import org.apache.poi.xwpf.usermodel.XWPFDocument; -import org.apache.poi.xwpf.usermodel.XWPFParagraph; -import org.apache.poi.xwpf.usermodel.XWPFRun; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTP; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTText; - -/** - * - * @author Richard Ngo - * - */ -public class SimpleDocumentWithHeader { - - private static XWPFParagraph[] pars; - - public static void main(String[] args) { - XWPFDocument doc = new XWPFDocument(); - - XWPFParagraph p = doc.createParagraph(); - - XWPFRun r = p.createRun(); - r.setText("Some Text"); - r.setBold(true); - r = p.createRun(); - r.setText("Goodbye"); - - CTP ctP = CTP.Factory.newInstance(); - CTText t = ctP.addNewR().addNewT(); - t.setStringValue("header"); - pars = new XWPFParagraph[1]; - p = new XWPFParagraph(ctP, doc); - pars[0] = p; - - XWPFHeaderFooterPolicy hfPolicy = doc.createHeaderFooterPolicy(); - hfPolicy.createHeader(XWPFHeaderFooterPolicy.DEFAULT, pars); - - ctP = CTP.Factory.newInstance(); - t = ctP.addNewR().addNewT(); - t.setStringValue("My Footer"); - pars[0] = new XWPFParagraph(ctP, doc); - hfPolicy.createFooter(XWPFHeaderFooterPolicy.DEFAULT, pars); - - try { - OutputStream os = new FileOutputStream(new File("header.docx")); - doc.write(os); - } catch (IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - - } -} \ No newline at end of file diff --git a/src/examples/src/org/apache/poi/xwpf/usermodel/SimpleImages.java b/src/examples/src/org/apache/poi/xwpf/usermodel/SimpleImages.java deleted file mode 100644 index 10e48d1aed..0000000000 --- a/src/examples/src/org/apache/poi/xwpf/usermodel/SimpleImages.java +++ /dev/null @@ -1,71 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ -package org.apache.poi.xwpf.usermodel; - -import org.apache.poi.util.Units; - -import java.io.FileInputStream; -import java.io.FileOutputStream; - -/** - * Demonstrates how to add pictures in a .docx document - * - * @author Yegor Kozlov - */ -public class SimpleImages { - - public static void main(String[] args) throws Exception { - XWPFDocument doc = new XWPFDocument(); - XWPFParagraph p = doc.createParagraph(); - - XWPFRun r = p.createRun(); - - for(String imgFile : args) { - int format; - - if(imgFile.endsWith(".emf")) format = XWPFDocument.PICTURE_TYPE_EMF; - else if(imgFile.endsWith(".wmf")) format = XWPFDocument.PICTURE_TYPE_WMF; - else if(imgFile.endsWith(".pict")) format = XWPFDocument.PICTURE_TYPE_PICT; - else if(imgFile.endsWith(".jpeg") || imgFile.endsWith(".jpg")) format = XWPFDocument.PICTURE_TYPE_JPEG; - else if(imgFile.endsWith(".png")) format = XWPFDocument.PICTURE_TYPE_PNG; - else if(imgFile.endsWith(".dib")) format = XWPFDocument.PICTURE_TYPE_DIB; - else if(imgFile.endsWith(".gif")) format = XWPFDocument.PICTURE_TYPE_GIF; - else if(imgFile.endsWith(".tiff")) format = XWPFDocument.PICTURE_TYPE_TIFF; - else if(imgFile.endsWith(".eps")) format = XWPFDocument.PICTURE_TYPE_EPS; - else if(imgFile.endsWith(".bmp")) format = XWPFDocument.PICTURE_TYPE_BMP; - else if(imgFile.endsWith(".wpg")) format = XWPFDocument.PICTURE_TYPE_WPG; - else { - System.err.println("Unsupported picture: " + imgFile + - ". Expected emf|wmf|pict|jpeg|png|dib|gif|tiff|eps|bmp|wpg"); - continue; - } - - r.setText(imgFile); - r.addBreak(); - r.addPicture(new FileInputStream(imgFile), format, imgFile, Units.toEMU(200), Units.toEMU(200)); // 200x200 pixels - r.addBreak(BreakType.PAGE); - } - - FileOutputStream out = new FileOutputStream("images.docx"); - doc.write(out); - out.close(); - } - - -} diff --git a/src/examples/src/org/apache/poi/xwpf/usermodel/SimpleTable.java b/src/examples/src/org/apache/poi/xwpf/usermodel/SimpleTable.java deleted file mode 100644 index 387ab449b0..0000000000 --- a/src/examples/src/org/apache/poi/xwpf/usermodel/SimpleTable.java +++ /dev/null @@ -1,206 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.xwpf.usermodel; - -import java.io.FileOutputStream; -import java.io.OutputStream; -import java.math.BigInteger; -import java.util.List; - -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTHeight; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTShd; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTString; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTblPr; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTcPr; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTrPr; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTVerticalJc; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.STShd; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.STVerticalJc; - -/** - * This program creates a simple WordprocessingML table using POI XWPF API, and - * a more complex, styled table using both XWPF and ooxml-schema. It's possible - * that not all referenced wordprocessingml classes are defined in - * poi-ooxml-schemas-3.8-beta4. If this is the case, you'll need to use the full - * ooxml-schemas.jar library. - * - * @author gisella bronzetti (original) - * @author Gregg Morris (styled table) - */ -public class SimpleTable { - - public static void main(String[] args) throws Exception { - try { - createSimpleTable(); - } - catch(Exception e) { - System.out.println("Error trying to create simple table."); - throw(e); - } - try { - createStyledTable(); - } - catch(Exception e) { - System.out.println("Error trying to create styled table."); - throw(e); - } - } - - public static void createSimpleTable() throws Exception { - XWPFDocument doc = new XWPFDocument(); - - try { - XWPFTable table = doc.createTable(3, 3); - - table.getRow(1).getCell(1).setText("EXAMPLE OF TABLE"); - - // table cells have a list of paragraphs; there is an initial - // paragraph created when the cell is created. If you create a - // paragraph in the document to put in the cell, it will also - // appear in the document following the table, which is probably - // not the desired result. - XWPFParagraph p1 = table.getRow(0).getCell(0).getParagraphs().get(0); - - XWPFRun r1 = p1.createRun(); - r1.setBold(true); - r1.setText("The quick brown fox"); - r1.setItalic(true); - r1.setFontFamily("Courier"); - r1.setUnderline(UnderlinePatterns.DOT_DOT_DASH); - r1.setTextPosition(100); - - table.getRow(2).getCell(2).setText("only text"); - - OutputStream out = new FileOutputStream("simpleTable.docx"); - try { - doc.write(out); - } finally { - out.close(); - } - } finally { - doc.close(); - } - } - - /** - * Create a table with some row and column styling. I "manually" add the - * style name to the table, but don't check to see if the style actually - * exists in the document. Since I'm creating it from scratch, it obviously - * won't exist. When opened in MS Word, the table style becomes "Normal". - * I manually set alternating row colors. This could be done using Themes, - * but that's left as an exercise for the reader. The cells in the last - * column of the table have 10pt. "Courier" font. - * I make no claims that this is the "right" way to do it, but it worked - * for me. Given the scarcity of XWPF examples, I thought this may prove - * instructive and give you ideas for your own solutions. - - * @throws Exception - */ - public static void createStyledTable() throws Exception { - // Create a new document from scratch - XWPFDocument doc = new XWPFDocument(); - - try { - // -- OR -- - // open an existing empty document with styles already defined - //XWPFDocument doc = new XWPFDocument(new FileInputStream("base_document.docx")); - - // Create a new table with 6 rows and 3 columns - int nRows = 6; - int nCols = 3; - XWPFTable table = doc.createTable(nRows, nCols); - - // Set the table style. If the style is not defined, the table style - // will become "Normal". - CTTblPr tblPr = table.getCTTbl().getTblPr(); - CTString styleStr = tblPr.addNewTblStyle(); - styleStr.setVal("StyledTable"); - - // Get a list of the rows in the table - List rows = table.getRows(); - int rowCt = 0; - int colCt = 0; - for (XWPFTableRow row : rows) { - // get table row properties (trPr) - CTTrPr trPr = row.getCtRow().addNewTrPr(); - // set row height; units = twentieth of a point, 360 = 0.25" - CTHeight ht = trPr.addNewTrHeight(); - ht.setVal(BigInteger.valueOf(360)); - - // get the cells in this row - List cells = row.getTableCells(); - // add content to each cell - for (XWPFTableCell cell : cells) { - // get a table cell properties element (tcPr) - CTTcPr tcpr = cell.getCTTc().addNewTcPr(); - // set vertical alignment to "center" - CTVerticalJc va = tcpr.addNewVAlign(); - va.setVal(STVerticalJc.CENTER); - - // create cell color element - CTShd ctshd = tcpr.addNewShd(); - ctshd.setColor("auto"); - ctshd.setVal(STShd.CLEAR); - if (rowCt == 0) { - // header row - ctshd.setFill("A7BFDE"); - } else if (rowCt % 2 == 0) { - // even row - ctshd.setFill("D3DFEE"); - } else { - // odd row - ctshd.setFill("EDF2F8"); - } - - // get 1st paragraph in cell's paragraph list - XWPFParagraph para = cell.getParagraphs().get(0); - // create a run to contain the content - XWPFRun rh = para.createRun(); - // style cell as desired - if (colCt == nCols - 1) { - // last column is 10pt Courier - rh.setFontSize(10); - rh.setFontFamily("Courier"); - } - if (rowCt == 0) { - // header row - rh.setText("header row, col " + colCt); - rh.setBold(true); - para.setAlignment(ParagraphAlignment.CENTER); - } else { - // other rows - rh.setText("row " + rowCt + ", col " + colCt); - para.setAlignment(ParagraphAlignment.LEFT); - } - colCt++; - } // for cell - colCt = 0; - rowCt++; - } // for row - - // write the file - OutputStream out = new FileOutputStream("styledTable.docx"); - try { - doc.write(out); - } finally { - out.close(); - } - } finally { - doc.close(); - } - } -} diff --git a/src/examples/src/org/apache/poi/xwpf/usermodel/UpdateEmbeddedDoc.java b/src/examples/src/org/apache/poi/xwpf/usermodel/UpdateEmbeddedDoc.java deleted file mode 100644 index 06493ce356..0000000000 --- a/src/examples/src/org/apache/poi/xwpf/usermodel/UpdateEmbeddedDoc.java +++ /dev/null @@ -1,220 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.apache.poi.xwpf.usermodel; - -import static org.junit.Assert.assertEquals; - -import java.io.File; -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.util.List; -import java.util.Iterator; - -import org.apache.poi.openxml4j.opc.PackagePart; -import org.apache.poi.openxml4j.exceptions.OpenXML4JException; -import org.apache.poi.ss.usermodel.WorkbookFactory; -import org.apache.poi.ss.usermodel.Workbook; -import org.apache.poi.ss.usermodel.Sheet; -import org.apache.poi.ss.usermodel.Row; -import org.apache.poi.ss.usermodel.Cell; - -/** - * Tests whether it is possible to successfully update an Excel workbook that is - * embedded into a WordprocessingML document. Note that the test has currently - * only been conducted with a binary Excel workbook and NOT yet with a - * SpreadsheetML workbook embedded into the document. - * - *

- * This code was successfully tested with the following file from the POI test collection: - * http://svn.apache.org/repos/asf/poi/trunk/test-data/document/EmbeddedDocument.docx - *

- * - * @author Mark B - */ -public class UpdateEmbeddedDoc { - - private XWPFDocument doc = null; - private File docFile = null; - - private static final int SHEET_NUM = 0; - private static final int ROW_NUM = 0; - private static final int CELL_NUM = 0; - private static final double NEW_VALUE = 100.98D; - private static final String BINARY_EXTENSION = "xls"; - private static final String OPENXML_EXTENSION = "xlsx"; - - /** - * Create a new instance of the UpdateEmbeddedDoc class using the following - * parameters; - * - * @param filename An instance of the String class that encapsulates the name - * of and path to a WordprocessingML Word document that contains an - * embedded binary Excel workbook. - * @throws java.io.FileNotFoundException Thrown if the file cannot be found - * on the underlying file system. - * @throws java.io.IOException Thrown if a problem occurs in the underlying - * file system. - */ - public UpdateEmbeddedDoc(String filename) throws FileNotFoundException, IOException { - this.docFile = new File(filename); - FileInputStream fis = null; - if (!this.docFile.exists()) { - throw new FileNotFoundException("The Word dcoument " + - filename + - " does not exist."); - } - try { - - // Open the Word document file and instantiate the XWPFDocument - // class. - fis = new FileInputStream(this.docFile); - this.doc = new XWPFDocument(fis); - } finally { - if (fis != null) { - try { - fis.close(); - fis = null; - } catch (IOException ioEx) { - System.out.println("IOException caught trying to close " + - "FileInputStream in the constructor of " + - "UpdateEmbeddedDoc."); - } - } - } - } - - /** - * Called to update the embedded Excel workbook. As the format and structire - * of the workbook are known in advance, all this code attempts to do is - * write a new value into the first cell on the first row of the first - * worksheet. Prior to executing this method, that cell will contain the - * value 1. - * - * @throws org.apache.poi.openxml4j.exceptions.OpenXML4JException - * Rather - * than use the specific classes (HSSF/XSSF) to handle the embedded - * workbook this method uses those defeined in the SS stream. As - * a result, it might be the case that a SpreadsheetML file is - * opened for processing, throwing this exception if that file is - * invalid. - * @throws java.io.IOException Thrown if a problem occurs in the underlying - * file system. - */ - public void updateEmbeddedDoc() throws OpenXML4JException, IOException { - Workbook workbook = null; - Sheet sheet = null; - Row row = null; - Cell cell = null; - PackagePart pPart = null; - Iterator pIter = null; - List embeddedDocs = this.doc.getAllEmbedds(); - if (embeddedDocs != null && !embeddedDocs.isEmpty()) { - pIter = embeddedDocs.iterator(); - while (pIter.hasNext()) { - pPart = pIter.next(); - if (pPart.getPartName().getExtension().equals(BINARY_EXTENSION) || - pPart.getPartName().getExtension().equals(OPENXML_EXTENSION)) { - - // Get an InputStream from the pacage part and pass that - // to the create method of the WorkbookFactory class. Update - // the resulting Workbook and then stream that out again - // using an OutputStream obtained from the same PackagePart. - workbook = WorkbookFactory.create(pPart.getInputStream()); - sheet = workbook.getSheetAt(SHEET_NUM); - row = sheet.getRow(ROW_NUM); - cell = row.getCell(CELL_NUM); - cell.setCellValue(NEW_VALUE); - workbook.write(pPart.getOutputStream()); - } - } - - // Finally, write the newly modified Word document out to file. - this.doc.write(new FileOutputStream(this.docFile)); - } - } - - /** - * Called to test whether or not the embedded workbook was correctly - * updated. This method simply recovers the first cell from the first row - * of the first workbook and tests the value it contains. - *

- * Note that execution will not continue up to the assertion as the - * embedded workbook is now corrupted and causes an IllegalArgumentException - * with the following message - *

- * java.lang.IllegalArgumentException: Your InputStream was neither an - * OLE2 stream, nor an OOXML stream - *

- * to be thrown when the WorkbookFactory.createWorkbook(InputStream) method - * is executed. - * - * @throws org.apache.poi.openxml4j.exceptions.OpenXML4JException - * Rather - * than use the specific classes (HSSF/XSSF) to handle the embedded - * workbook this method uses those defeined in the SS stream. As - * a result, it might be the case that a SpreadsheetML file is - * opened for processing, throwing this exception if that file is - * invalid. - * @throws java.io.IOException Thrown if a problem occurs in the underlying - * file system. - */ - public void checkUpdatedDoc() throws OpenXML4JException, IOException { - Workbook workbook = null; - Sheet sheet = null; - Row row = null; - Cell cell = null; - PackagePart pPart = null; - Iterator pIter = null; - List embeddedDocs = this.doc.getAllEmbedds(); - if (embeddedDocs != null && !embeddedDocs.isEmpty()) { - pIter = embeddedDocs.iterator(); - while (pIter.hasNext()) { - pPart = pIter.next(); - if (pPart.getPartName().getExtension().equals(BINARY_EXTENSION) || - pPart.getPartName().getExtension().equals(OPENXML_EXTENSION)) { - workbook = WorkbookFactory.create(pPart.getInputStream()); - sheet = workbook.getSheetAt(SHEET_NUM); - row = sheet.getRow(ROW_NUM); - cell = row.getCell(CELL_NUM); - assertEquals(cell.getNumericCellValue(), NEW_VALUE, 0.0001); - } - } - } - } - - /** - * Code to test updating of the embedded Excel workbook. - * - * @param args - */ - public static void main(String[] args) { - try { - UpdateEmbeddedDoc ued = new UpdateEmbeddedDoc(args[0]); - ued.updateEmbeddedDoc(); - ued.checkUpdatedDoc(); - } catch (Exception ex) { - System.out.println(ex.getClass().getName()); - System.out.println(ex.getMessage()); - ex.printStackTrace(System.out); - } - } -} diff --git a/src/examples/src/org/apache/poi/xwpf/usermodel/examples/BetterHeaderFooterExample.java b/src/examples/src/org/apache/poi/xwpf/usermodel/examples/BetterHeaderFooterExample.java new file mode 100644 index 0000000000..fe5f5ad44a --- /dev/null +++ b/src/examples/src/org/apache/poi/xwpf/usermodel/examples/BetterHeaderFooterExample.java @@ -0,0 +1,60 @@ +/* ==================================================================== + Licensed to the Apache Software Foundation (ASF) under one or more + contributor license agreements. See the NOTICE file distributed with + this work for additional information regarding copyright ownership. + The ASF licenses this file to You under the Apache License, Version 2.0 + (the "License"); you may not use this file except in compliance with + the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +==================================================================== */ +package org.apache.poi.xwpf.usermodel.examples; + +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.OutputStream; + +import org.apache.poi.wp.usermodel.HeaderFooterType; +import org.apache.poi.xwpf.usermodel.XWPFDocument; +import org.apache.poi.xwpf.usermodel.XWPFFooter; +import org.apache.poi.xwpf.usermodel.XWPFHeader; +import org.apache.poi.xwpf.usermodel.XWPFParagraph; +import org.apache.poi.xwpf.usermodel.XWPFRun; + +public class BetterHeaderFooterExample { + + public static void main(String[] args) { + XWPFDocument doc = new XWPFDocument(); + + XWPFParagraph p = doc.createParagraph(); + + XWPFRun r = p.createRun(); + r.setText("Some Text"); + r.setBold(true); + r = p.createRun(); + r.setText("Goodbye"); + + // create header/footer functions insert an empty paragraph + XWPFHeader head = doc.createHeader(HeaderFooterType.DEFAULT); + head.createParagraph().createRun().setText("header"); + + XWPFFooter foot = doc.createFooter(HeaderFooterType.DEFAULT); + foot.createParagraph().createRun().setText("footer"); + + try { + OutputStream os = new FileOutputStream(new File("header2.docx")); + doc.write(os); + doc.close(); + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } +} diff --git a/src/examples/src/org/apache/poi/xwpf/usermodel/examples/HeaderFooterTable.java b/src/examples/src/org/apache/poi/xwpf/usermodel/examples/HeaderFooterTable.java new file mode 100644 index 0000000000..a2b9103a47 --- /dev/null +++ b/src/examples/src/org/apache/poi/xwpf/usermodel/examples/HeaderFooterTable.java @@ -0,0 +1,105 @@ +/* ==================================================================== + Licensed to the Apache Software Foundation (ASF) under one or more + contributor license agreements. See the NOTICE file distributed with + this work for additional information regarding copyright ownership. + The ASF licenses this file to You under the Apache License, Version 2.0 + (the "License"); you may not use this file except in compliance with + the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +==================================================================== */ +package org.apache.poi.xwpf.usermodel.examples; + +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.OutputStream; +import java.math.BigInteger; + +import org.apache.poi.wp.usermodel.HeaderFooterType; +import org.apache.poi.xwpf.usermodel.XWPFDocument; +import org.apache.poi.xwpf.usermodel.XWPFFooter; +import org.apache.poi.xwpf.usermodel.XWPFHeader; +import org.apache.poi.xwpf.usermodel.XWPFParagraph; +import org.apache.poi.xwpf.usermodel.XWPFRun; +import org.apache.poi.xwpf.usermodel.XWPFTable; +import org.apache.poi.xwpf.usermodel.XWPFTableCell; +import org.apache.poi.xwpf.usermodel.XWPFTableRow; +import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTbl; +import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTblGrid; +import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTblGridCol; +import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTblLayoutType; +import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTblPr; +import org.openxmlformats.schemas.wordprocessingml.x2006.main.STTblLayoutType; + +public class HeaderFooterTable { + + public static void main(String[] args) throws IOException { + XWPFDocument doc = new XWPFDocument(); + + // Create a header with a 1 row, 3 column table + // changes made for issue 57366 allow a new header or footer + // to be created empty. This is a change. You will have to add + // either a paragraph or a table to the header or footer for + // the document to be considered valid. + XWPFHeader hdr = doc.createHeader(HeaderFooterType.DEFAULT); + XWPFTable tbl = hdr.createTable(1, 3); + + // Set the padding around text in the cells to 1/10th of an inch + int pad = (int) (.1 * 1440); + tbl.setCellMargins(pad, pad, pad, pad); + + // Set table width to 6.5 inches in 1440ths of a point + tbl.setWidth((int)(6.5 * 1440)); + // Can not yet set table or cell width properly, tables default to + // autofit layout, and this requires fixed layout + CTTbl ctTbl = tbl.getCTTbl(); + CTTblPr ctTblPr = ctTbl.addNewTblPr(); + CTTblLayoutType layoutType = ctTblPr.addNewTblLayout(); + layoutType.setType(STTblLayoutType.FIXED); + + // Now set up a grid for the table, cells will fit into the grid + // Each cell width is 3120 in 1440ths of an inch, or 1/3rd of 6.5" + BigInteger w = new BigInteger("3120"); + CTTblGrid grid = ctTbl.addNewTblGrid(); + for (int i = 0; i < 3; i++) { + CTTblGridCol gridCol = grid.addNewGridCol(); + gridCol.setW(w); + } + + // Add paragraphs to the cells + XWPFTableRow row = tbl.getRow(0); + XWPFTableCell cell = row.getCell(0); + XWPFParagraph p = cell.getParagraphArray(0); + XWPFRun r = p.createRun(); + r.setText("header left cell"); + + cell = row.getCell(1); + p = cell.getParagraphArray(0); + r = p.createRun(); + r.setText("header center cell"); + + cell = row.getCell(2); + p = cell.getParagraphArray(0); + r = p.createRun(); + r.setText("header right cell"); + + // Create a footer with a Paragraph + XWPFFooter ftr = doc.createFooter(HeaderFooterType.DEFAULT); + p = ftr.createParagraph(); + + r = p.createRun(); + r.setText("footer text"); + + OutputStream os = new FileOutputStream(new File("headertable.docx")); + doc.write(os); + doc.close(); + } + +} diff --git a/src/examples/src/org/apache/poi/xwpf/usermodel/examples/SimpleDocument.java b/src/examples/src/org/apache/poi/xwpf/usermodel/examples/SimpleDocument.java new file mode 100644 index 0000000000..1553321cd4 --- /dev/null +++ b/src/examples/src/org/apache/poi/xwpf/usermodel/examples/SimpleDocument.java @@ -0,0 +1,132 @@ +/* ==================================================================== + Licensed to the Apache Software Foundation (ASF) under one or more + contributor license agreements. See the NOTICE file distributed with + this work for additional information regarding copyright ownership. + The ASF licenses this file to You under the Apache License, Version 2.0 + (the "License"); you may not use this file except in compliance with + the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +==================================================================== */ +package org.apache.poi.xwpf.usermodel.examples; + +import java.io.FileOutputStream; + +import org.apache.poi.xwpf.usermodel.Borders; +import org.apache.poi.xwpf.usermodel.BreakClear; +import org.apache.poi.xwpf.usermodel.BreakType; +import org.apache.poi.xwpf.usermodel.LineSpacingRule; +import org.apache.poi.xwpf.usermodel.ParagraphAlignment; +import org.apache.poi.xwpf.usermodel.TextAlignment; +import org.apache.poi.xwpf.usermodel.UnderlinePatterns; +import org.apache.poi.xwpf.usermodel.VerticalAlign; +import org.apache.poi.xwpf.usermodel.XWPFDocument; +import org.apache.poi.xwpf.usermodel.XWPFParagraph; +import org.apache.poi.xwpf.usermodel.XWPFRun; + +/** + * A simple WOrdprocessingML document created by POI XWPF API + * + * @author Yegor Kozlov + */ +public class SimpleDocument { + + public static void main(String[] args) throws Exception { + 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(); + + } +} diff --git a/src/examples/src/org/apache/poi/xwpf/usermodel/examples/SimpleDocumentWithHeader.java b/src/examples/src/org/apache/poi/xwpf/usermodel/examples/SimpleDocumentWithHeader.java new file mode 100644 index 0000000000..a798ebd431 --- /dev/null +++ b/src/examples/src/org/apache/poi/xwpf/usermodel/examples/SimpleDocumentWithHeader.java @@ -0,0 +1,76 @@ +/* ==================================================================== + Licensed to the Apache Software Foundation (ASF) under one or more + contributor license agreements. See the NOTICE file distributed with + this work for additional information regarding copyright ownership. + The ASF licenses this file to You under the Apache License, Version 2.0 + (the "License"); you may not use this file except in compliance with + the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +==================================================================== */ +package org.apache.poi.xwpf.usermodel.examples; + +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.OutputStream; + +import org.apache.poi.xwpf.model.XWPFHeaderFooterPolicy; +import org.apache.poi.xwpf.usermodel.XWPFDocument; +import org.apache.poi.xwpf.usermodel.XWPFParagraph; +import org.apache.poi.xwpf.usermodel.XWPFRun; +import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTP; +import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTText; + +/** + * + * @author Richard Ngo + * + */ +public class SimpleDocumentWithHeader { + + private static XWPFParagraph[] pars; + + public static void main(String[] args) { + XWPFDocument doc = new XWPFDocument(); + + XWPFParagraph p = doc.createParagraph(); + + XWPFRun r = p.createRun(); + r.setText("Some Text"); + r.setBold(true); + r = p.createRun(); + r.setText("Goodbye"); + + CTP ctP = CTP.Factory.newInstance(); + CTText t = ctP.addNewR().addNewT(); + t.setStringValue("header"); + pars = new XWPFParagraph[1]; + p = new XWPFParagraph(ctP, doc); + pars[0] = p; + + XWPFHeaderFooterPolicy hfPolicy = doc.createHeaderFooterPolicy(); + hfPolicy.createHeader(XWPFHeaderFooterPolicy.DEFAULT, pars); + + ctP = CTP.Factory.newInstance(); + t = ctP.addNewR().addNewT(); + t.setStringValue("My Footer"); + pars[0] = new XWPFParagraph(ctP, doc); + hfPolicy.createFooter(XWPFHeaderFooterPolicy.DEFAULT, pars); + + try { + OutputStream os = new FileOutputStream(new File("header.docx")); + doc.write(os); + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + } +} \ No newline at end of file diff --git a/src/examples/src/org/apache/poi/xwpf/usermodel/examples/SimpleImages.java b/src/examples/src/org/apache/poi/xwpf/usermodel/examples/SimpleImages.java new file mode 100644 index 0000000000..7e95c7a7f3 --- /dev/null +++ b/src/examples/src/org/apache/poi/xwpf/usermodel/examples/SimpleImages.java @@ -0,0 +1,75 @@ +/* + * ==================================================================== + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ==================================================================== + */ +package org.apache.poi.xwpf.usermodel.examples; + +import org.apache.poi.util.Units; +import org.apache.poi.xwpf.usermodel.BreakType; +import org.apache.poi.xwpf.usermodel.XWPFDocument; +import org.apache.poi.xwpf.usermodel.XWPFParagraph; +import org.apache.poi.xwpf.usermodel.XWPFRun; + +import java.io.FileInputStream; +import java.io.FileOutputStream; + +/** + * Demonstrates how to add pictures in a .docx document + * + * @author Yegor Kozlov + */ +public class SimpleImages { + + public static void main(String[] args) throws Exception { + XWPFDocument doc = new XWPFDocument(); + XWPFParagraph p = doc.createParagraph(); + + XWPFRun r = p.createRun(); + + for(String imgFile : args) { + int format; + + if(imgFile.endsWith(".emf")) format = XWPFDocument.PICTURE_TYPE_EMF; + else if(imgFile.endsWith(".wmf")) format = XWPFDocument.PICTURE_TYPE_WMF; + else if(imgFile.endsWith(".pict")) format = XWPFDocument.PICTURE_TYPE_PICT; + else if(imgFile.endsWith(".jpeg") || imgFile.endsWith(".jpg")) format = XWPFDocument.PICTURE_TYPE_JPEG; + else if(imgFile.endsWith(".png")) format = XWPFDocument.PICTURE_TYPE_PNG; + else if(imgFile.endsWith(".dib")) format = XWPFDocument.PICTURE_TYPE_DIB; + else if(imgFile.endsWith(".gif")) format = XWPFDocument.PICTURE_TYPE_GIF; + else if(imgFile.endsWith(".tiff")) format = XWPFDocument.PICTURE_TYPE_TIFF; + else if(imgFile.endsWith(".eps")) format = XWPFDocument.PICTURE_TYPE_EPS; + else if(imgFile.endsWith(".bmp")) format = XWPFDocument.PICTURE_TYPE_BMP; + else if(imgFile.endsWith(".wpg")) format = XWPFDocument.PICTURE_TYPE_WPG; + else { + System.err.println("Unsupported picture: " + imgFile + + ". Expected emf|wmf|pict|jpeg|png|dib|gif|tiff|eps|bmp|wpg"); + continue; + } + + r.setText(imgFile); + r.addBreak(); + r.addPicture(new FileInputStream(imgFile), format, imgFile, Units.toEMU(200), Units.toEMU(200)); // 200x200 pixels + r.addBreak(BreakType.PAGE); + } + + FileOutputStream out = new FileOutputStream("images.docx"); + doc.write(out); + out.close(); + } + + +} diff --git a/src/examples/src/org/apache/poi/xwpf/usermodel/examples/SimpleTable.java b/src/examples/src/org/apache/poi/xwpf/usermodel/examples/SimpleTable.java new file mode 100644 index 0000000000..a3857ff2e7 --- /dev/null +++ b/src/examples/src/org/apache/poi/xwpf/usermodel/examples/SimpleTable.java @@ -0,0 +1,214 @@ +/* ==================================================================== + Licensed to the Apache Software Foundation (ASF) under one or more + contributor license agreements. See the NOTICE file distributed with + this work for additional information regarding copyright ownership. + The ASF licenses this file to You under the Apache License, Version 2.0 + (the "License"); you may not use this file except in compliance with + the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +==================================================================== */ +package org.apache.poi.xwpf.usermodel.examples; + +import java.io.FileOutputStream; +import java.io.OutputStream; +import java.math.BigInteger; +import java.util.List; + +import org.apache.poi.xwpf.usermodel.ParagraphAlignment; +import org.apache.poi.xwpf.usermodel.UnderlinePatterns; +import org.apache.poi.xwpf.usermodel.XWPFDocument; +import org.apache.poi.xwpf.usermodel.XWPFParagraph; +import org.apache.poi.xwpf.usermodel.XWPFRun; +import org.apache.poi.xwpf.usermodel.XWPFTable; +import org.apache.poi.xwpf.usermodel.XWPFTableCell; +import org.apache.poi.xwpf.usermodel.XWPFTableRow; +import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTHeight; +import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTShd; +import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTString; +import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTblPr; +import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTcPr; +import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTrPr; +import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTVerticalJc; +import org.openxmlformats.schemas.wordprocessingml.x2006.main.STShd; +import org.openxmlformats.schemas.wordprocessingml.x2006.main.STVerticalJc; + +/** + * This program creates a simple WordprocessingML table using POI XWPF API, and + * a more complex, styled table using both XWPF and ooxml-schema. It's possible + * that not all referenced wordprocessingml classes are defined in + * poi-ooxml-schemas-3.8-beta4. If this is the case, you'll need to use the full + * ooxml-schemas.jar library. + * + * @author gisella bronzetti (original) + * @author Gregg Morris (styled table) + */ +public class SimpleTable { + + public static void main(String[] args) throws Exception { + try { + createSimpleTable(); + } + catch(Exception e) { + System.out.println("Error trying to create simple table."); + throw(e); + } + try { + createStyledTable(); + } + catch(Exception e) { + System.out.println("Error trying to create styled table."); + throw(e); + } + } + + public static void createSimpleTable() throws Exception { + XWPFDocument doc = new XWPFDocument(); + + try { + XWPFTable table = doc.createTable(3, 3); + + table.getRow(1).getCell(1).setText("EXAMPLE OF TABLE"); + + // table cells have a list of paragraphs; there is an initial + // paragraph created when the cell is created. If you create a + // paragraph in the document to put in the cell, it will also + // appear in the document following the table, which is probably + // not the desired result. + XWPFParagraph p1 = table.getRow(0).getCell(0).getParagraphs().get(0); + + XWPFRun r1 = p1.createRun(); + r1.setBold(true); + r1.setText("The quick brown fox"); + r1.setItalic(true); + r1.setFontFamily("Courier"); + r1.setUnderline(UnderlinePatterns.DOT_DOT_DASH); + r1.setTextPosition(100); + + table.getRow(2).getCell(2).setText("only text"); + + OutputStream out = new FileOutputStream("simpleTable.docx"); + try { + doc.write(out); + } finally { + out.close(); + } + } finally { + doc.close(); + } + } + + /** + * Create a table with some row and column styling. I "manually" add the + * style name to the table, but don't check to see if the style actually + * exists in the document. Since I'm creating it from scratch, it obviously + * won't exist. When opened in MS Word, the table style becomes "Normal". + * I manually set alternating row colors. This could be done using Themes, + * but that's left as an exercise for the reader. The cells in the last + * column of the table have 10pt. "Courier" font. + * I make no claims that this is the "right" way to do it, but it worked + * for me. Given the scarcity of XWPF examples, I thought this may prove + * instructive and give you ideas for your own solutions. + + * @throws Exception + */ + public static void createStyledTable() throws Exception { + // Create a new document from scratch + XWPFDocument doc = new XWPFDocument(); + + try { + // -- OR -- + // open an existing empty document with styles already defined + //XWPFDocument doc = new XWPFDocument(new FileInputStream("base_document.docx")); + + // Create a new table with 6 rows and 3 columns + int nRows = 6; + int nCols = 3; + XWPFTable table = doc.createTable(nRows, nCols); + + // Set the table style. If the style is not defined, the table style + // will become "Normal". + CTTblPr tblPr = table.getCTTbl().getTblPr(); + CTString styleStr = tblPr.addNewTblStyle(); + styleStr.setVal("StyledTable"); + + // Get a list of the rows in the table + List rows = table.getRows(); + int rowCt = 0; + int colCt = 0; + for (XWPFTableRow row : rows) { + // get table row properties (trPr) + CTTrPr trPr = row.getCtRow().addNewTrPr(); + // set row height; units = twentieth of a point, 360 = 0.25" + CTHeight ht = trPr.addNewTrHeight(); + ht.setVal(BigInteger.valueOf(360)); + + // get the cells in this row + List cells = row.getTableCells(); + // add content to each cell + for (XWPFTableCell cell : cells) { + // get a table cell properties element (tcPr) + CTTcPr tcpr = cell.getCTTc().addNewTcPr(); + // set vertical alignment to "center" + CTVerticalJc va = tcpr.addNewVAlign(); + va.setVal(STVerticalJc.CENTER); + + // create cell color element + CTShd ctshd = tcpr.addNewShd(); + ctshd.setColor("auto"); + ctshd.setVal(STShd.CLEAR); + if (rowCt == 0) { + // header row + ctshd.setFill("A7BFDE"); + } else if (rowCt % 2 == 0) { + // even row + ctshd.setFill("D3DFEE"); + } else { + // odd row + ctshd.setFill("EDF2F8"); + } + + // get 1st paragraph in cell's paragraph list + XWPFParagraph para = cell.getParagraphs().get(0); + // create a run to contain the content + XWPFRun rh = para.createRun(); + // style cell as desired + if (colCt == nCols - 1) { + // last column is 10pt Courier + rh.setFontSize(10); + rh.setFontFamily("Courier"); + } + if (rowCt == 0) { + // header row + rh.setText("header row, col " + colCt); + rh.setBold(true); + para.setAlignment(ParagraphAlignment.CENTER); + } else { + // other rows + rh.setText("row " + rowCt + ", col " + colCt); + para.setAlignment(ParagraphAlignment.LEFT); + } + colCt++; + } // for cell + colCt = 0; + rowCt++; + } // for row + + // write the file + OutputStream out = new FileOutputStream("styledTable.docx"); + try { + doc.write(out); + } finally { + out.close(); + } + } finally { + doc.close(); + } + } +} diff --git a/src/examples/src/org/apache/poi/xwpf/usermodel/examples/UpdateEmbeddedDoc.java b/src/examples/src/org/apache/poi/xwpf/usermodel/examples/UpdateEmbeddedDoc.java new file mode 100644 index 0000000000..410f3c62f7 --- /dev/null +++ b/src/examples/src/org/apache/poi/xwpf/usermodel/examples/UpdateEmbeddedDoc.java @@ -0,0 +1,221 @@ +/* + * ==================================================================== + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ==================================================================== + */ + +package org.apache.poi.xwpf.usermodel.examples; + +import static org.junit.Assert.assertEquals; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.util.List; +import java.util.Iterator; + +import org.apache.poi.openxml4j.opc.PackagePart; +import org.apache.poi.openxml4j.exceptions.OpenXML4JException; +import org.apache.poi.ss.usermodel.WorkbookFactory; +import org.apache.poi.xwpf.usermodel.XWPFDocument; +import org.apache.poi.ss.usermodel.Workbook; +import org.apache.poi.ss.usermodel.Sheet; +import org.apache.poi.ss.usermodel.Row; +import org.apache.poi.ss.usermodel.Cell; + +/** + * Tests whether it is possible to successfully update an Excel workbook that is + * embedded into a WordprocessingML document. Note that the test has currently + * only been conducted with a binary Excel workbook and NOT yet with a + * SpreadsheetML workbook embedded into the document. + * + *

+ * This code was successfully tested with the following file from the POI test collection: + * http://svn.apache.org/repos/asf/poi/trunk/test-data/document/EmbeddedDocument.docx + *

+ * + * @author Mark B + */ +public class UpdateEmbeddedDoc { + + private XWPFDocument doc = null; + private File docFile = null; + + private static final int SHEET_NUM = 0; + private static final int ROW_NUM = 0; + private static final int CELL_NUM = 0; + private static final double NEW_VALUE = 100.98D; + private static final String BINARY_EXTENSION = "xls"; + private static final String OPENXML_EXTENSION = "xlsx"; + + /** + * Create a new instance of the UpdateEmbeddedDoc class using the following + * parameters; + * + * @param filename An instance of the String class that encapsulates the name + * of and path to a WordprocessingML Word document that contains an + * embedded binary Excel workbook. + * @throws java.io.FileNotFoundException Thrown if the file cannot be found + * on the underlying file system. + * @throws java.io.IOException Thrown if a problem occurs in the underlying + * file system. + */ + public UpdateEmbeddedDoc(String filename) throws FileNotFoundException, IOException { + this.docFile = new File(filename); + FileInputStream fis = null; + if (!this.docFile.exists()) { + throw new FileNotFoundException("The Word dcoument " + + filename + + " does not exist."); + } + try { + + // Open the Word document file and instantiate the XWPFDocument + // class. + fis = new FileInputStream(this.docFile); + this.doc = new XWPFDocument(fis); + } finally { + if (fis != null) { + try { + fis.close(); + fis = null; + } catch (IOException ioEx) { + System.out.println("IOException caught trying to close " + + "FileInputStream in the constructor of " + + "UpdateEmbeddedDoc."); + } + } + } + } + + /** + * Called to update the embedded Excel workbook. As the format and structire + * of the workbook are known in advance, all this code attempts to do is + * write a new value into the first cell on the first row of the first + * worksheet. Prior to executing this method, that cell will contain the + * value 1. + * + * @throws org.apache.poi.openxml4j.exceptions.OpenXML4JException + * Rather + * than use the specific classes (HSSF/XSSF) to handle the embedded + * workbook this method uses those defeined in the SS stream. As + * a result, it might be the case that a SpreadsheetML file is + * opened for processing, throwing this exception if that file is + * invalid. + * @throws java.io.IOException Thrown if a problem occurs in the underlying + * file system. + */ + public void updateEmbeddedDoc() throws OpenXML4JException, IOException { + Workbook workbook = null; + Sheet sheet = null; + Row row = null; + Cell cell = null; + PackagePart pPart = null; + Iterator pIter = null; + List embeddedDocs = this.doc.getAllEmbedds(); + if (embeddedDocs != null && !embeddedDocs.isEmpty()) { + pIter = embeddedDocs.iterator(); + while (pIter.hasNext()) { + pPart = pIter.next(); + if (pPart.getPartName().getExtension().equals(BINARY_EXTENSION) || + pPart.getPartName().getExtension().equals(OPENXML_EXTENSION)) { + + // Get an InputStream from the pacage part and pass that + // to the create method of the WorkbookFactory class. Update + // the resulting Workbook and then stream that out again + // using an OutputStream obtained from the same PackagePart. + workbook = WorkbookFactory.create(pPart.getInputStream()); + sheet = workbook.getSheetAt(SHEET_NUM); + row = sheet.getRow(ROW_NUM); + cell = row.getCell(CELL_NUM); + cell.setCellValue(NEW_VALUE); + workbook.write(pPart.getOutputStream()); + } + } + + // Finally, write the newly modified Word document out to file. + this.doc.write(new FileOutputStream(this.docFile)); + } + } + + /** + * Called to test whether or not the embedded workbook was correctly + * updated. This method simply recovers the first cell from the first row + * of the first workbook and tests the value it contains. + *

+ * Note that execution will not continue up to the assertion as the + * embedded workbook is now corrupted and causes an IllegalArgumentException + * with the following message + *

+ * java.lang.IllegalArgumentException: Your InputStream was neither an + * OLE2 stream, nor an OOXML stream + *

+ * to be thrown when the WorkbookFactory.createWorkbook(InputStream) method + * is executed. + * + * @throws org.apache.poi.openxml4j.exceptions.OpenXML4JException + * Rather + * than use the specific classes (HSSF/XSSF) to handle the embedded + * workbook this method uses those defeined in the SS stream. As + * a result, it might be the case that a SpreadsheetML file is + * opened for processing, throwing this exception if that file is + * invalid. + * @throws java.io.IOException Thrown if a problem occurs in the underlying + * file system. + */ + public void checkUpdatedDoc() throws OpenXML4JException, IOException { + Workbook workbook = null; + Sheet sheet = null; + Row row = null; + Cell cell = null; + PackagePart pPart = null; + Iterator pIter = null; + List embeddedDocs = this.doc.getAllEmbedds(); + if (embeddedDocs != null && !embeddedDocs.isEmpty()) { + pIter = embeddedDocs.iterator(); + while (pIter.hasNext()) { + pPart = pIter.next(); + if (pPart.getPartName().getExtension().equals(BINARY_EXTENSION) || + pPart.getPartName().getExtension().equals(OPENXML_EXTENSION)) { + workbook = WorkbookFactory.create(pPart.getInputStream()); + sheet = workbook.getSheetAt(SHEET_NUM); + row = sheet.getRow(ROW_NUM); + cell = row.getCell(CELL_NUM); + assertEquals(cell.getNumericCellValue(), NEW_VALUE, 0.0001); + } + } + } + } + + /** + * Code to test updating of the embedded Excel workbook. + * + * @param args + */ + public static void main(String[] args) { + try { + UpdateEmbeddedDoc ued = new UpdateEmbeddedDoc(args[0]); + ued.updateEmbeddedDoc(); + ued.checkUpdatedDoc(); + } catch (Exception ex) { + System.out.println(ex.getClass().getName()); + System.out.println(ex.getMessage()); + ex.printStackTrace(System.out); + } + } +}