import java.util.Vector;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
-import java.util.regex.Pattern;
-
-import junit.framework.TestCase;
-
-import org.junit.Test;
-import org.junit.internal.TextListener;
-import org.junit.runner.JUnitCore;
-import org.junit.runner.Result;
+import java.util.regex.Pattern;\r
+\r
+import junit.framework.TestCase;\r
+import org.junit.Test;\r
+import org.junit.internal.TextListener;\r
+import org.junit.runner.JUnitCore;import org.junit.runner.Result;
/**
* Build a 'lite' version of the ooxml-schemas.jar
* Helper class to extract text from an OOXML Word file
*/
public class XWPFWordExtractor extends POIXMLTextExtractor {
- public static final XWPFRelation[] SUPPORTED_TYPES = new XWPFRelation[] {
- XWPFRelation.DOCUMENT, XWPFRelation.TEMPLATE,
- XWPFRelation.MACRO_DOCUMENT,
- XWPFRelation.MACRO_TEMPLATE_DOCUMENT
- };
-
- private XWPFDocument document;
- private boolean fetchHyperlinks = false;
-
- public XWPFWordExtractor(OPCPackage container) throws XmlException, OpenXML4JException, IOException {
- this(new XWPFDocument(container));
- }
- public XWPFWordExtractor(XWPFDocument document) {
- super(document);
- this.document = document;
- }
-
- /**
- * Should we also fetch the hyperlinks, when fetching
- * the text content? Default is to only output the
- * hyperlink label, and not the contents
- */
- public void setFetchHyperlinks(boolean fetch) {
- fetchHyperlinks = fetch;
- }
-
- public static void main(String[] args) throws Exception {
- if(args.length < 1) {
- System.err.println("Use:");
- System.err.println(" XWPFWordExtractor <filename.docx>");
- System.exit(1);
- }
- POIXMLTextExtractor extractor =
- new XWPFWordExtractor(POIXMLDocument.openPackage(
- args[0]
- ));
- System.out.println(extractor.getText());
- extractor.close();
- }
-
+ public static final XWPFRelation[] SUPPORTED_TYPES = new XWPFRelation[]{
+ XWPFRelation.DOCUMENT, XWPFRelation.TEMPLATE,
+ XWPFRelation.MACRO_DOCUMENT,
+ XWPFRelation.MACRO_TEMPLATE_DOCUMENT
+ };
+
+ private XWPFDocument document;
+ private boolean fetchHyperlinks = false;
+
+ public XWPFWordExtractor(OPCPackage container) throws XmlException, OpenXML4JException, IOException {
+ this(new XWPFDocument(container));
+ }
+
+ public XWPFWordExtractor(XWPFDocument document) {
+ super(document);
+ this.document = document;
+ }
+
+ public static void main(String[] args) throws Exception {
+ if (args.length < 1) {
+ System.err.println("Use:");
+ System.err.println(" XWPFWordExtractor <filename.docx>");
+ System.exit(1);
+ }
+ POIXMLTextExtractor extractor =
+ new XWPFWordExtractor(POIXMLDocument.openPackage(
+ args[0]
+ ));
+ System.out.println(extractor.getText());
+ extractor.close();
+ }
+
+ /**
+ * Should we also fetch the hyperlinks, when fetching
+ * the text content? Default is to only output the
+ * hyperlink label, and not the contents
+ */
+ public void setFetchHyperlinks(boolean fetch) {
+ fetchHyperlinks = fetch;
+ }
+
public String getText() {
StringBuffer text = new StringBuffer();
XWPFHeaderFooterPolicy hfPolicy = document.getHeaderFooterPolicy();
extractHeaders(text, hfPolicy);
// Process all body elements
- for (IBodyElement e : document.getBodyElements()){
- appendBodyElementText(text, e);
- text.append('\n');
+ for (IBodyElement e : document.getBodyElements()) {
+ appendBodyElementText(text, e);
+ text.append('\n');
}
// Finish up with all the footers
return text.toString();
}
- public void appendBodyElementText(StringBuffer text, IBodyElement e){
- if (e instanceof XWPFParagraph){
- appendParagraphText(text, (XWPFParagraph)e);
- } else if (e instanceof XWPFTable){
- appendTableText(text, (XWPFTable)e);
- } else if (e instanceof XWPFSDT){
- text.append(((XWPFSDT)e).getContent().getText());
- }
- }
-
- public void appendParagraphText(StringBuffer text, XWPFParagraph paragraph){
- try {
- CTSectPr ctSectPr = null;
- if (paragraph.getCTP().getPPr()!=null) {
- ctSectPr = paragraph.getCTP().getPPr().getSectPr();
- }
-
- XWPFHeaderFooterPolicy headerFooterPolicy = null;
-
- if (ctSectPr!=null) {
- headerFooterPolicy = new XWPFHeaderFooterPolicy(document, ctSectPr);
- extractHeaders(text, headerFooterPolicy);
- }
-
-
- for(IRunElement run : paragraph.getRuns()) {
- text.append(run.toString());
- if(run instanceof XWPFHyperlinkRun && fetchHyperlinks) {
- XWPFHyperlink link = ((XWPFHyperlinkRun)run).getHyperlink(document);
- if(link != null)
- text.append(" <" + link.getURL() + ">");
- }
- }
-
- // Add comments
- XWPFCommentsDecorator decorator = new XWPFCommentsDecorator(paragraph, null);
- String commentText = decorator.getCommentText();
- if (commentText.length() > 0){
- text.append(commentText).append('\n');
- }
-
- // Do endnotes and footnotes
- String footnameText = paragraph.getFootnoteText();
- if(footnameText != null && footnameText.length() > 0) {
- text.append(footnameText + '\n');
- }
-
- if (ctSectPr!=null) {
- extractFooters(text, headerFooterPolicy);
- }
- } catch (IOException e) {
- throw new POIXMLException(e);
- } catch (XmlException e) {
- throw new POIXMLException(e);
- }
-
- }
-
- private void appendTableText(StringBuffer text, XWPFTable table) {
- //this works recursively to pull embedded tables from tables
- for (XWPFTableRow row : table.getRows()) {
- List<ICell> cells = row.getTableICells();
- for (int i = 0; i < cells.size(); i++) {
- ICell cell = cells.get(i);
- if (cell instanceof XWPFTableCell) {
- text.append(((XWPFTableCell)cell).getTextRecursively());
- } else if (cell instanceof XWPFSDTCell) {
- text.append(((XWPFSDTCell)cell).getContent().getText());
- }
- if (i < cells.size()-1) {
- text.append("\t");
- }
- }
- text.append('\n');
- }
- }
-
- private void extractFooters(StringBuffer text, XWPFHeaderFooterPolicy hfPolicy) {
- if (hfPolicy == null) return;
-
- if(hfPolicy.getFirstPageFooter() != null) {
- text.append( hfPolicy.getFirstPageFooter().getText() );
- }
- if(hfPolicy.getEvenPageFooter() != null) {
- text.append( hfPolicy.getEvenPageFooter().getText() );
- }
- if(hfPolicy.getDefaultFooter() != null) {
- text.append( hfPolicy.getDefaultFooter().getText() );
- }
- }
-
- private void extractHeaders(StringBuffer text, XWPFHeaderFooterPolicy hfPolicy) {
- if (hfPolicy == null) return;
-
- if(hfPolicy.getFirstPageHeader() != null) {
- text.append( hfPolicy.getFirstPageHeader().getText() );
- }
- if(hfPolicy.getEvenPageHeader() != null) {
- text.append( hfPolicy.getEvenPageHeader().getText() );
- }
- if(hfPolicy.getDefaultHeader() != null) {
- text.append( hfPolicy.getDefaultHeader().getText() );
- }
- }
+ public void appendBodyElementText(StringBuffer text, IBodyElement e) {
+ if (e instanceof XWPFParagraph) {
+ appendParagraphText(text, (XWPFParagraph) e);
+ } else if (e instanceof XWPFTable) {
+ appendTableText(text, (XWPFTable) e);
+ } else if (e instanceof XWPFSDT) {
+ text.append(((XWPFSDT) e).getContent().getText());
+ }
+ }
+
+ public void appendParagraphText(StringBuffer text, XWPFParagraph paragraph) {
+ try {
+ CTSectPr ctSectPr = null;
+ if (paragraph.getCTP().getPPr() != null) {
+ ctSectPr = paragraph.getCTP().getPPr().getSectPr();
+ }
+
+ XWPFHeaderFooterPolicy headerFooterPolicy = null;
+
+ if (ctSectPr != null) {
+ headerFooterPolicy = new XWPFHeaderFooterPolicy(document, ctSectPr);
+ extractHeaders(text, headerFooterPolicy);
+ }
+
+
+ for (IRunElement run : paragraph.getRuns()) {
+ text.append(run.toString());
+ if (run instanceof XWPFHyperlinkRun && fetchHyperlinks) {
+ XWPFHyperlink link = ((XWPFHyperlinkRun) run).getHyperlink(document);
+ if (link != null)
+ text.append(" <" + link.getURL() + ">");
+ }
+ }
+
+ // Add comments
+ XWPFCommentsDecorator decorator = new XWPFCommentsDecorator(paragraph, null);
+ String commentText = decorator.getCommentText();
+ if (commentText.length() > 0) {
+ text.append(commentText).append('\n');
+ }
+
+ // Do endnotes and footnotes
+ String footnameText = paragraph.getFootnoteText();
+ if (footnameText != null && footnameText.length() > 0) {
+ text.append(footnameText + '\n');
+ }
+
+ if (ctSectPr != null) {
+ extractFooters(text, headerFooterPolicy);
+ }
+ } catch (IOException e) {
+ throw new POIXMLException(e);
+ } catch (XmlException e) {
+ throw new POIXMLException(e);
+ }
+
+ }
+
+ private void appendTableText(StringBuffer text, XWPFTable table) {
+ //this works recursively to pull embedded tables from tables
+ for (XWPFTableRow row : table.getRows()) {
+ List<ICell> cells = row.getTableICells();
+ for (int i = 0; i < cells.size(); i++) {
+ ICell cell = cells.get(i);
+ if (cell instanceof XWPFTableCell) {
+ text.append(((XWPFTableCell) cell).getTextRecursively());
+ } else if (cell instanceof XWPFSDTCell) {
+ text.append(((XWPFSDTCell) cell).getContent().getText());
+ }
+ if (i < cells.size() - 1) {
+ text.append("\t");
+ }
+ }
+ text.append('\n');
+ }
+ }
+
+ private void extractFooters(StringBuffer text, XWPFHeaderFooterPolicy hfPolicy) {
+ if (hfPolicy == null) return;
+
+ if (hfPolicy.getFirstPageFooter() != null) {
+ text.append(hfPolicy.getFirstPageFooter().getText());
+ }
+ if (hfPolicy.getEvenPageFooter() != null) {
+ text.append(hfPolicy.getEvenPageFooter().getText());
+ }
+ if (hfPolicy.getDefaultFooter() != null) {
+ text.append(hfPolicy.getDefaultFooter().getText());
+ }
+ }
+
+ private void extractHeaders(StringBuffer text, XWPFHeaderFooterPolicy hfPolicy) {
+ if (hfPolicy == null) return;
+
+ if (hfPolicy.getFirstPageHeader() != null) {
+ text.append(hfPolicy.getFirstPageHeader().getText());
+ }
+ if (hfPolicy.getEvenPageHeader() != null) {
+ text.append(hfPolicy.getEvenPageHeader().getText());
+ }
+ if (hfPolicy.getDefaultHeader() != null) {
+ text.append(hfPolicy.getDefaultHeader().getText());
+ }
+ }
}
* Base class for XWPF paragraphs
*
* @author Yury Batrakov (batrakov at gmail.com)
- *
*/
public class XMLParagraph {
- protected CTP paragraph;
-
- public XMLParagraph(CTP paragraph) {
- this.paragraph = paragraph;
- }
+ protected CTP paragraph;
- public CTP getCTP() {
- return paragraph;
- }
+ public XMLParagraph(CTP paragraph) {
+ this.paragraph = paragraph;
+ }
+
+ public CTP getCTP() {
+ return paragraph;
+ }
}
\ No newline at end of file
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTMarkupRange;
/**
- * Decorator class for XWPFParagraph allowing to add comments
+ * Decorator class for XWPFParagraph allowing to add comments
* found in paragraph to its text
*
* @author Yury Batrakov (batrakov at gmail.com)
- *
*/
public class XWPFCommentsDecorator extends XWPFParagraphDecorator {
- private StringBuffer commentText;
-
- public XWPFCommentsDecorator(XWPFParagraphDecorator nextDecorator) {
- this(nextDecorator.paragraph, nextDecorator);
- }
-
- @SuppressWarnings("deprecation")
- public XWPFCommentsDecorator(XWPFParagraph paragraph, XWPFParagraphDecorator nextDecorator) {
- super(paragraph, nextDecorator);
-
- XWPFComment comment;
- commentText = new StringBuffer();
-
- for(CTMarkupRange anchor : paragraph.getCTP().getCommentRangeStartArray())
- {
- if((comment = paragraph.getDocument().getCommentByID(anchor.getId().toString())) != null)
- commentText.append("\tComment by " + comment.getAuthor()+": "+comment.getText());
- }
- }
-
- public String getCommentText() {
- return commentText.toString();
- }
-
- public String getText() {
- return super.getText() + commentText;
- }
+ private StringBuffer commentText;
+
+ public XWPFCommentsDecorator(XWPFParagraphDecorator nextDecorator) {
+ this(nextDecorator.paragraph, nextDecorator);
+ }
+
+ @SuppressWarnings("deprecation")
+ public XWPFCommentsDecorator(XWPFParagraph paragraph, XWPFParagraphDecorator nextDecorator) {
+ super(paragraph, nextDecorator);
+
+ XWPFComment comment;
+ commentText = new StringBuffer();
+
+ for (CTMarkupRange anchor : paragraph.getCTP().getCommentRangeStartArray()) {
+ if ((comment = paragraph.getDocument().getCommentByID(anchor.getId().toString())) != null)
+ commentText.append("\tComment by " + comment.getAuthor() + ": " + comment.getText());
+ }
+ }
+
+ public String getCommentText() {
+ return commentText.toString();
+ }
+
+ public String getText() {
+ return super.getText() + commentText;
+ }
}
import org.openxmlformats.schemas.wordprocessingml.x2006.main.HdrDocument;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.STHdrFtr;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.STHdrFtr.Enum;
-
import schemasMicrosoftComOfficeOffice.CTLock;
import schemasMicrosoftComOfficeOffice.STConnectType;
import schemasMicrosoftComVml.CTFormulas;
/**
* A .docx file can have no headers/footers, the same header/footer
- * on each page, odd/even page footers, and optionally also
- * a different header/footer on the first page.
+ * on each page, odd/even page footers, and optionally also
+ * a different header/footer on the first page.
* This class handles sorting out what there is, and giving you
- * the right headers and footers for the document.
+ * the right headers and footers for the document.
*/
public class XWPFHeaderFooterPolicy {
public static final Enum DEFAULT = STHdrFtr.DEFAULT;
/**
* Figures out the policy for the given document,
- * and creates any header and footer objects
- * as required.
+ * and creates any header and footer objects
+ * as required.
*/
public XWPFHeaderFooterPolicy(XWPFDocument doc) throws IOException, XmlException {
this(doc, doc.getDocument().getBody().getSectPr());
/**
* Figures out the policy for the given document,
- * and creates any header and footer objects
- * as required.
+ * and creates any header and footer objects
+ * as required.
*/
public XWPFHeaderFooterPolicy(XWPFDocument doc, CTSectPr sectPr) throws IOException, XmlException {
// Grab what headers and footers have been defined
// doesn't seem that .docx properly supports that
// feature of the file format yet
this.doc = doc;
- for(int i=0; i<sectPr.sizeOfHeaderReferenceArray(); i++) {
+ for (int i = 0; i < sectPr.sizeOfHeaderReferenceArray(); i++) {
// Get the header
CTHdrFtrRef ref = sectPr.getHeaderReferenceArray(i);
POIXMLDocumentPart relatedPart = doc.getRelationById(ref.getId());
Enum type = ref.getType();
assignHeader(hdr, type);
}
- for(int i=0; i<sectPr.sizeOfFooterReferenceArray(); i++) {
+ for (int i = 0; i < sectPr.sizeOfFooterReferenceArray(); i++) {
// Get the footer
CTHdrFtrRef ref = sectPr.getFooterReferenceArray(i);
POIXMLDocumentPart relatedPart = doc.getRelationById(ref.getId());
XWPFFooter ftr = null;
- if (relatedPart != null && relatedPart instanceof XWPFFooter)
- {
+ if (relatedPart != null && relatedPart instanceof XWPFFooter) {
ftr = (XWPFFooter) relatedPart;
}
// Assign it
}
private void assignFooter(XWPFFooter ftr, Enum type) {
- if(type == STHdrFtr.FIRST) {
+ if (type == STHdrFtr.FIRST) {
firstPageFooter = ftr;
- } else if(type == STHdrFtr.EVEN) {
+ } else if (type == STHdrFtr.EVEN) {
evenPageFooter = ftr;
} else {
defaultFooter = ftr;
}
private void assignHeader(XWPFHeader hdr, Enum type) {
- if(type == STHdrFtr.FIRST) {
+ if (type == STHdrFtr.FIRST) {
firstPageHeader = hdr;
- } else if(type == STHdrFtr.EVEN) {
+ } else if (type == STHdrFtr.EVEN) {
evenPageHeader = hdr;
} else {
defaultHeader = hdr;
/**
* Creates a new header of the specified type, to which the
- * supplied (and previously unattached!) paragraphs are
- * added to.
+ * supplied (and previously unattached!) paragraphs are
+ * added to.
*/
public XWPFHeader createHeader(Enum type, XWPFParagraph[] pars) throws IOException {
XWPFRelation relation = XWPFRelation.HEADER;
String pStyle = "Header";
int i = getRelationIndex(relation);
HdrDocument hdrDoc = HdrDocument.Factory.newInstance();
- XWPFHeader wrapper = (XWPFHeader)doc.createRelationship(relation, XWPFFactory.getInstance(), i);
+ XWPFHeader wrapper = (XWPFHeader) doc.createRelationship(relation, XWPFFactory.getInstance(), i);
CTHdrFtr hdr = buildHdr(type, pStyle, wrapper, pars);
wrapper.setHeaderFooter(hdr);
/**
* Creates a new footer of the specified type, to which the
- * supplied (and previously unattached!) paragraphs are
- * added to.
+ * supplied (and previously unattached!) paragraphs are
+ * added to.
*/
public XWPFFooter createFooter(Enum type, XWPFParagraph[] pars) throws IOException {
XWPFRelation relation = XWPFRelation.FOOTER;
String pStyle = "Footer";
int i = getRelationIndex(relation);
FtrDocument ftrDoc = FtrDocument.Factory.newInstance();
- XWPFFooter wrapper = (XWPFFooter)doc.createRelationship(relation, XWPFFactory.getInstance(), i);
+ XWPFFooter wrapper = (XWPFFooter) doc.createRelationship(relation, XWPFFactory.getInstance(), i);
CTHdrFtr ftr = buildFtr(type, pStyle, wrapper, pars);
wrapper.setHeaderFooter(ftr);
private int getRelationIndex(XWPFRelation relation) {
List<POIXMLDocumentPart> relations = doc.getRelations();
int i = 1;
- for (Iterator<POIXMLDocumentPart> it = relations.iterator(); it.hasNext() ; ) {
+ for (Iterator<POIXMLDocumentPart> it = relations.iterator(); it.hasNext(); ) {
POIXMLDocumentPart item = it.next();
if (item.getPackageRelationship().getRelationshipType().equals(relation.getRelation())) {
- i++;
+ i++;
}
}
return i;
private CTHdrFtr buildFtr(Enum type, String pStyle, XWPFHeaderFooter wrapper, XWPFParagraph[] pars) {
//CTHdrFtr ftr = buildHdrFtr(pStyle, pars); // MB 24 May 2010
- CTHdrFtr ftr = buildHdrFtr(pStyle, pars, wrapper); // MB 24 May 2010
+ CTHdrFtr ftr = buildHdrFtr(pStyle, pars, wrapper); // MB 24 May 2010
setFooterReference(type, wrapper);
return ftr;
}
private CTHdrFtr buildHdr(Enum type, String pStyle, XWPFHeaderFooter wrapper, XWPFParagraph[] pars) {
//CTHdrFtr hdr = buildHdrFtr(pStyle, pars); // MB 24 May 2010
- CTHdrFtr hdr = buildHdrFtr(pStyle, pars, wrapper); // MB 24 May 2010
+ CTHdrFtr hdr = buildHdrFtr(pStyle, pars, wrapper); // MB 24 May 2010
setHeaderReference(type, wrapper);
return hdr;
}
private CTHdrFtr buildHdrFtr(String pStyle, XWPFParagraph[] paragraphs) {
CTHdrFtr ftr = CTHdrFtr.Factory.newInstance();
if (paragraphs != null) {
- for (int i = 0 ; i < paragraphs.length ; i++) {
+ for (int i = 0; i < paragraphs.length; i++) {
CTP p = ftr.addNewP();
//ftr.setPArray(0, paragraphs[i].getCTP()); // MB 23 May 2010
- ftr.setPArray(i, paragraphs[i].getCTP()); // MB 23 May 2010
+ ftr.setPArray(i, paragraphs[i].getCTP()); // MB 23 May 2010
}
- }
- else {
+ } else {
CTP p = ftr.addNewP();
byte[] rsidr = doc.getDocument().getBody().getPArray(0).getRsidR();
byte[] rsidrdefault = doc.getDocument().getBody().getPArray(0).getRsidRDefault();
* and createFooter(int, XWPFParagraph[]) methods or the getXXXXXHeader/Footer methods where
* headers or footers had been added to a document since it had been created/opened, returned
* an object that contained no XWPFParagraph objects even if the header/footer itself did contain
- * text. The reason was that this line of code; CTHdrFtr ftr = CTHdrFtr.Factory.newInstance();
+ * text. The reason was that this line of code; CTHdrFtr ftr = CTHdrFtr.Factory.newInstance();
* created a brand new instance of the CTHDRFtr class which was then populated with data when
* it should have recovered the CTHdrFtr object encapsulated within the XWPFHeaderFooter object
- * that had previoulsy been instantiated in the createHeader(int, XWPFParagraph[]) or
+ * that had previoulsy been instantiated in the createHeader(int, XWPFParagraph[]) or
* createFooter(int, XWPFParagraph[]) methods.
*/
private CTHdrFtr buildHdrFtr(String pStyle, XWPFParagraph[] paragraphs, XWPFHeaderFooter wrapper) {
CTHdrFtr ftr = wrapper._getHdrFtr();
if (paragraphs != null) {
- for (int i = 0 ; i < paragraphs.length ; i++) {
+ for (int i = 0; i < paragraphs.length; i++) {
CTP p = ftr.addNewP();
ftr.setPArray(i, paragraphs[i].getCTP());
}
- }
- else {
+ } else {
CTP p = ftr.addNewP();
byte[] rsidr = doc.getDocument().getBody().getPArray(0).getRsidR();
byte[] rsidrdefault = doc.getDocument().getBody().getPArray(0).getRsidRDefault();
public XWPFHeader getFirstPageHeader() {
return firstPageHeader;
}
+
public XWPFFooter getFirstPageFooter() {
return firstPageFooter;
}
+
/**
* Returns the odd page header. This is
- * also the same as the default one...
+ * also the same as the default one...
*/
public XWPFHeader getOddPageHeader() {
return defaultHeader;
}
+
/**
* Returns the odd page footer. This is
- * also the same as the default one...
+ * also the same as the default one...
*/
public XWPFFooter getOddPageFooter() {
return defaultFooter;
}
+
public XWPFHeader getEvenPageHeader() {
return evenPageHeader;
}
+
public XWPFFooter getEvenPageFooter() {
return evenPageFooter;
}
+
public XWPFHeader getDefaultHeader() {
return defaultHeader;
}
+
public XWPFFooter getDefaultFooter() {
return defaultFooter;
}
/**
* Get the header that applies to the given
- * (1 based) page.
+ * (1 based) page.
+ *
* @param pageNumber The one based page number
*/
public XWPFHeader getHeader(int pageNumber) {
- if(pageNumber == 1 && firstPageHeader != null) {
+ if (pageNumber == 1 && firstPageHeader != null) {
return firstPageHeader;
}
- if(pageNumber % 2 == 0 && evenPageHeader != null) {
+ if (pageNumber % 2 == 0 && evenPageHeader != null) {
return evenPageHeader;
}
return defaultHeader;
}
+
/**
* Get the footer that applies to the given
- * (1 based) page.
+ * (1 based) page.
+ *
* @param pageNumber The one based page number
*/
public XWPFFooter getFooter(int pageNumber) {
- if(pageNumber == 1 && firstPageFooter != null) {
+ if (pageNumber == 1 && firstPageFooter != null) {
return firstPageFooter;
}
- if(pageNumber % 2 == 0 && evenPageFooter != null) {
+ if (pageNumber % 2 == 0 && evenPageFooter != null) {
return evenPageFooter;
}
return defaultFooter;
lock.setExt(STExt.EDIT);
CTShape shape = group.addNewShape();
shape.setId("PowerPlusWaterMarkObject" + idx);
- shape.setSpid("_x0000_s102" + (4+idx));
+ shape.setSpid("_x0000_s102" + (4 + idx));
shape.setType("#_x0000_t136");
shape.setStyle("position:absolute;margin-left:0;margin-top:0;width:415pt;height:207.5pt;z-index:-251654144;mso-wrap-edited:f;mso-position-horizontal:center;mso-position-horizontal-relative:margin;mso-position-vertical:center;mso-position-vertical-relative:margin");
shape.setWrapcoords("616 5068 390 16297 39 16921 -39 17155 7265 17545 7186 17467 -39 17467 18904 17467 10507 17467 8710 17545 18904 17077 18787 16843 18358 16297 18279 12554 19178 12476 20701 11774 20779 11228 21131 10059 21248 8811 21248 7563 20975 6316 20935 5380 19490 5146 14022 5068 2616 5068");
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTText;
/**
- * Decorator class for XWPFParagraph allowing to add hyperlinks
- * found in paragraph to its text.
- *
+ * Decorator class for XWPFParagraph allowing to add hyperlinks
+ * found in paragraph to its text.
+ * <p/>
* Note - adds the hyperlink at the end, not in the right place...
- *
+ *
* @deprecated Use {@link XWPFHyperlinkRun} instead
*/
@Deprecated
public class XWPFHyperlinkDecorator extends XWPFParagraphDecorator {
- private StringBuffer hyperlinkText;
-
- /**
- * @param nextDecorator The next decorator to use
- * @param outputHyperlinkUrls Should we output the links too, or just the link text?
- */
- public XWPFHyperlinkDecorator(XWPFParagraphDecorator nextDecorator, boolean outputHyperlinkUrls) {
- this(nextDecorator.paragraph, nextDecorator, outputHyperlinkUrls);
- }
-
- /**
- * @param prgrph The paragraph of text to work on
- * @param outputHyperlinkUrls Should we output the links too, or just the link text?
- */
- public XWPFHyperlinkDecorator(XWPFParagraph prgrph, XWPFParagraphDecorator nextDecorator, boolean outputHyperlinkUrls) {
- super(prgrph, nextDecorator);
-
- hyperlinkText = new StringBuffer();
-
- // loop over hyperlink anchors
- for(CTHyperlink link : paragraph.getCTP().getHyperlinkArray()){
- for (CTR r : link.getRArray()) {
- // Loop over text runs
- for (CTText text : r.getTArray()){
- hyperlinkText.append(text.getStringValue());
- }
- }
- if(outputHyperlinkUrls && paragraph.getDocument().getHyperlinkByID(link.getId()) != null) {
- hyperlinkText.append(" <"+paragraph.getDocument().getHyperlinkByID(link.getId()).getURL()+">");
- }
- }
- }
-
- public String getText()
- {
- return super.getText() + hyperlinkText;
- }
+ private StringBuffer hyperlinkText;
+
+ /**
+ * @param nextDecorator The next decorator to use
+ * @param outputHyperlinkUrls Should we output the links too, or just the link text?
+ */
+ public XWPFHyperlinkDecorator(XWPFParagraphDecorator nextDecorator, boolean outputHyperlinkUrls) {
+ this(nextDecorator.paragraph, nextDecorator, outputHyperlinkUrls);
+ }
+
+ /**
+ * @param prgrph The paragraph of text to work on
+ * @param outputHyperlinkUrls Should we output the links too, or just the link text?
+ */
+ public XWPFHyperlinkDecorator(XWPFParagraph prgrph, XWPFParagraphDecorator nextDecorator, boolean outputHyperlinkUrls) {
+ super(prgrph, nextDecorator);
+
+ hyperlinkText = new StringBuffer();
+
+ // loop over hyperlink anchors
+ for (CTHyperlink link : paragraph.getCTP().getHyperlinkArray()) {
+ for (CTR r : link.getRArray()) {
+ // Loop over text runs
+ for (CTText text : r.getTArray()) {
+ hyperlinkText.append(text.getStringValue());
+ }
+ }
+ if (outputHyperlinkUrls && paragraph.getDocument().getHyperlinkByID(link.getId()) != null) {
+ hyperlinkText.append(" <" + paragraph.getDocument().getHyperlinkByID(link.getId()).getURL() + ">");
+ }
+ }
+ }
+
+ public String getText() {
+ return super.getText() + hyperlinkText;
+ }
}
* Base decorator class for XWPFParagraph
*/
public abstract class XWPFParagraphDecorator {
- protected XWPFParagraph paragraph;
- protected XWPFParagraphDecorator nextDecorator;
-
- public XWPFParagraphDecorator(XWPFParagraph paragraph) {
- this(paragraph, null);
- }
-
- public XWPFParagraphDecorator(XWPFParagraph paragraph, XWPFParagraphDecorator nextDecorator) {
- this.paragraph = paragraph;
- this.nextDecorator = nextDecorator;
- }
-
- public String getText() {
- if(nextDecorator != null) {
- return nextDecorator.getText();
- }
- return paragraph.getText();
- }
+ protected XWPFParagraph paragraph;
+ protected XWPFParagraphDecorator nextDecorator;
+
+ public XWPFParagraphDecorator(XWPFParagraph paragraph) {
+ this(paragraph, null);
+ }
+
+ public XWPFParagraphDecorator(XWPFParagraph paragraph, XWPFParagraphDecorator nextDecorator) {
+ this.paragraph = paragraph;
+ this.nextDecorator = nextDecorator;
+ }
+
+ public String getText() {
+ if (nextDecorator != null) {
+ return nextDecorator.getText();
+ }
+ return paragraph.getText();
+ }
}
-->
<html>
<body>
- <p>This package contains classes for handling Microsoft .docx
- Word Processing files, known in POI as XWPF (XML Word Processing
- Format).
- </p>
+<p>This package contains classes for handling Microsoft .docx
+ Word Processing files, known in POI as XWPF (XML Word Processing
+ Format).
+</p>
</body>
</html>
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.util.List;
-
-import org.apache.poi.POIXMLDocumentPart;
-import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTSdtPr;
-import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTString;
-
-/**
- * Experimental abstract class that is a base for XWPFSDT and XWPFSDTCell
- *
- * WARNING - APIs expected to change rapidly.
- *
- * These classes have so far been built only for read-only processing.
- *
- */
-public abstract class AbstractXWPFSDT implements ISDTContents {
- private final String title;
- private final String tag;
- private final IBody part;
-
- @SuppressWarnings("deprecation")
- public AbstractXWPFSDT(CTSdtPr pr, IBody part){
-
- CTString[] aliases = pr.getAliasArray();
- if (aliases != null && aliases.length > 0){
- title = aliases[0].getVal();
- } else {
- title = "";
- }
- CTString[] tags = pr.getTagArray();
- if (tags != null && tags.length > 0){
- tag = tags[0].getVal();
- } else {
- tag = "";
- }
- this.part = part;
-
- }
-
- /**
- *
- * @return first SDT Title
- */
- public String getTitle(){
- return title;
- }
-
- /**
- *
- * @return first SDT Tag
- */
- public String getTag(){
- return tag;
- }
-
- /**
- *
- * @return the content object
- */
- public abstract ISDTContent getContent();
-
- /**
- *
- * @return null
- */
- public IBody getBody() {
- return null;
- }
-
- /**
- *
- * @return document part
- */
- public POIXMLDocumentPart getPart() {
- return part.getPart();
- }
-
- /**
- *
- * @return partType
- */
- public BodyType getPartType() {
- return BodyType.CONTENTCONTROL;
- }
-
- /**
- *
- * @return element type
- */
- public BodyElementType getElementType() {
- return BodyElementType.CONTENTCONTROL;
- }
-
- public XWPFDocument getDocument() {
- return part.getXWPFDocument();
- }
-}
+==================================================================== */\r
+package org.apache.poi.xwpf.usermodel;\r
+\r
+import org.apache.poi.POIXMLDocumentPart;\r
+import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTSdtPr;\r
+import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTString;\r
+\r
+/**\r
+ * Experimental abstract class that is a base for XWPFSDT and XWPFSDTCell\r
+ * <p/>\r
+ * WARNING - APIs expected to change rapidly.\r
+ * <p/>\r
+ * These classes have so far been built only for read-only processing.\r
+ */\r
+public abstract class AbstractXWPFSDT implements ISDTContents {\r
+ private final String title;\r
+ private final String tag;\r
+ private final IBody part;\r
+\r
+ @SuppressWarnings("deprecation")\r
+ public AbstractXWPFSDT(CTSdtPr pr, IBody part) {\r
+\r
+ CTString[] aliases = pr.getAliasArray();\r
+ if (aliases != null && aliases.length > 0) {\r
+ title = aliases[0].getVal();\r
+ } else {\r
+ title = "";\r
+ }\r
+ CTString[] tags = pr.getTagArray();\r
+ if (tags != null && tags.length > 0) {\r
+ tag = tags[0].getVal();\r
+ } else {\r
+ tag = "";\r
+ }\r
+ this.part = part;\r
+\r
+ }\r
+\r
+ /**\r
+ * @return first SDT Title\r
+ */\r
+ public String getTitle() {\r
+ return title;\r
+ }\r
+\r
+ /**\r
+ * @return first SDT Tag\r
+ */\r
+ public String getTag() {\r
+ return tag;\r
+ }\r
+\r
+ /**\r
+ * @return the content object\r
+ */\r
+ public abstract ISDTContent getContent();\r
+\r
+ /**\r
+ * @return null\r
+ */\r
+ public IBody getBody() {\r
+ return null;\r
+ }\r
+\r
+ /**\r
+ * @return document part\r
+ */\r
+ public POIXMLDocumentPart getPart() {\r
+ return part.getPart();\r
+ }\r
+\r
+ /**\r
+ * @return partType\r
+ */\r
+ public BodyType getPartType() {\r
+ return BodyType.CONTENTCONTROL;\r
+ }\r
+\r
+ /**\r
+ * @return element type\r
+ */\r
+ public BodyElementType getElementType() {\r
+ return BodyElementType.CONTENTCONTROL;\r
+ }\r
+\r
+ public XWPFDocument getDocument() {\r
+ return part.getXWPFDocument();\r
+ }\r
+}\r
* <p>
* 9 Jan 2010
* </p>
- * <p>
- * // TODO insert Javadoc here!
- * </p>
- * @author epp
- *
- */
-public enum BodyElementType {
- CONTENTCONTROL,
- PARAGRAPH,
- TABLE,
-
-}
+ * <p>\r
+ * // TODO insert Javadoc here!\r
+ * </p>\r
+ *\r
+ * @author epp\r
+ */\r
+public enum BodyElementType {\r
+ CONTENTCONTROL,\r
+ PARAGRAPH,\r
+ TABLE,\r
+}\r
* </li>
* <li> Art borders: which specify a repeated image to be used
* when drawing a border around the specified object. Line borders may be
- * specified on any object which allows a border, however, art borders may only
- * be used as a border at the page level - the borders under the pgBorders
- * element
- *</li>
- * </ul>
- * @author Gisella Bronzetti
- */
-public enum Borders {
+ * specified on any object which allows a border, however, art borders may only\r
+ * be used as a border at the page level - the borders under the pgBorders\r
+ * element\r
+ * </li>\r
+ * </ul>\r
+ *\r
+ * @author Gisella Bronzetti\r
+ */\r
+public enum Borders {\r
NIL(1),
ZANY_TRIANGLES(189),
ZIG_ZAG(190),
-
- ZIG_ZAG_STITCH(191);
-
- private final int value;
-
- private Borders(int val) {
- value = val;
- }
-
- public int getValue() {
- return value;
- }
-
- private static Map<Integer, Borders> imap = new HashMap<Integer, Borders>();
- static {
- for (Borders p : values()) {
- imap.put(Integer.valueOf(p.getValue()), p);
- }
- }
-
- public static Borders valueOf(int type) {
- Borders pBorder = imap.get(Integer.valueOf(type));
- if (pBorder == null) {
- throw new IllegalArgumentException("Unknown paragraph border: " + type);
- }
- return pBorder;
- }
-}
+\r
+ ZIG_ZAG_STITCH(191);\r
+\r
+ private static Map<Integer, Borders> imap = new HashMap<Integer, Borders>();\r
+\r
+ static {\r
+ for (Borders p : values()) {\r
+ imap.put(Integer.valueOf(p.getValue()), p);\r
+ }\r
+ }\r
+\r
+ private final int value;\r
+\r
+ private Borders(int val) {\r
+ value = val;\r
+ }\r
+\r
+ public static Borders valueOf(int type) {\r
+ Borders pBorder = imap.get(Integer.valueOf(type));\r
+ if (pBorder == null) {\r
+ throw new IllegalArgumentException("Unknown paragraph border: " + type);\r
+ }\r
+ return pBorder;\r
+ }\r
+\r
+ public int getValue() {\r
+ return value;\r
+ }\r
+}\r
import java.util.Map;
/**
- * Specifies the set of possible restart locations which may be used as to
- * determine the next available line when a break's type attribute has a value
- * of textWrapping.
- *
- * @author Gisella Bronzetti
- */
-public enum BreakClear {
+ * Specifies the set of possible restart locations which may be used as to\r
+ * determine the next available line when a break's type attribute has a value\r
+ * of textWrapping.\r
+ *\r
+ * @author Gisella Bronzetti\r
+ */\r
+public enum BreakClear {\r
/**
* Specifies that the text wrapping break shall advance the text to the next
- * line in the WordprocessingML document, regardless of its position left to
- * right or the presence of any floating objects which intersect with the
- * line,
- *
- * This is the setting for a typical line break in a document.
- */
-
+ * line in the WordprocessingML document, regardless of its position left to\r
+ * right or the presence of any floating objects which intersect with the\r
+ * line,\r
+ * <p/>\r
+ * This is the setting for a typical line break in a document.\r
+ */\r
+\r
NONE(1),
/**
* Specifies that the text wrapping break shall advance the text to the next
* line in the WordprocessingML document which spans the full width of the
* line.
- */
- ALL(4);
-
- private final int value;
-
- private BreakClear(int val) {
- value = val;
- }
-
- public int getValue() {
- return value;
- }
-
- private static Map<Integer, BreakClear> imap = new HashMap<Integer, BreakClear>();
- static {
- for (BreakClear p : values()) {
- imap.put(new Integer(p.getValue()), p);
- }
- }
-
- public static BreakClear valueOf(int type) {
- BreakClear bType = imap.get(new Integer(type));
- if (bType == null)
- throw new IllegalArgumentException("Unknown break clear type: "
- + type);
- return bType;
- }
-}
+ */\r
+ ALL(4);\r
+\r
+ private static Map<Integer, BreakClear> imap = new HashMap<Integer, BreakClear>();\r
+\r
+ static {\r
+ for (BreakClear p : values()) {\r
+ imap.put(new Integer(p.getValue()), p);\r
+ }\r
+ }\r
+\r
+ private final int value;\r
+\r
+ private BreakClear(int val) {\r
+ value = val;\r
+ }\r
+\r
+ public static BreakClear valueOf(int type) {\r
+ BreakClear bType = imap.get(new Integer(type));\r
+ if (bType == null)\r
+ throw new IllegalArgumentException("Unknown break clear type: "\r
+ + type);\r
+ return bType;\r
+ }\r
+\r
+ public int getValue() {\r
+ return value;\r
+ }\r
+}\r
/**
* Specifies the possible types of break characters in a WordprocessingML
- * document.
- * The break type determines the next location where text shall be
- * placed after this manual break is applied to the text contents
- *
- * @author Gisella Bronzetti
- */
-public enum BreakType {
-
-
- /**
- * Specifies that the current break shall restart itself on the next page of
- * the document when the document is displayed in page view.
+ * document.\r
+ * The break type determines the next location where text shall be\r
+ * placed after this manual break is applied to the text contents\r
+ *\r
+ * @author Gisella Bronzetti\r
+ */\r
+public enum BreakType {\r
+\r
+\r
+ /**\r
+ * Specifies that the current break shall restart itself on the next page of\r
+ * the document when the document is displayed in page view.\r
*/
PAGE(1),
* the document when the document is displayed in page view.
* The determine of the next line shall be done subject to the value of the clear
* attribute on the specified break character.
- */
- TEXT_WRAPPING(3);
-
- private final int value;
-
- private BreakType(int val) {
- value = val;
- }
-
- public int getValue() {
- return value;
- }
-
- private static Map<Integer, BreakType> imap = new HashMap<Integer, BreakType>();
- static {
- for (BreakType p : values()) {
- imap.put(new Integer(p.getValue()), p);
- }
- }
-
- public static BreakType valueOf(int type) {
- BreakType bType = imap.get(new Integer(type));
- if (bType == null)
- throw new IllegalArgumentException("Unknown break type: "
- + type);
- return bType;
- }
-}
+ */\r
+ TEXT_WRAPPING(3);\r
+\r
+ private static Map<Integer, BreakType> imap = new HashMap<Integer, BreakType>();\r
+\r
+ static {\r
+ for (BreakType p : values()) {\r
+ imap.put(new Integer(p.getValue()), p);\r
+ }\r
+ }\r
+\r
+ private final int value;\r
+\r
+ private BreakType(int val) {\r
+ value = val;\r
+ }\r
+\r
+ public static BreakType valueOf(int type) {\r
+ BreakType bType = imap.get(new Integer(type));\r
+ if (bType == null)\r
+ throw new IllegalArgumentException("Unknown break type: "\r
+ + type);\r
+ return bType;\r
+ }\r
+\r
+ public int getValue() {\r
+ return value;\r
+ }\r
+}\r
See the License for the specific language governing permissions and
limitations under the License.
==================================================================== */
-package org.apache.poi.xwpf.usermodel;
-
-public interface Document {
- /** Extended windows meta file */
- public static final int PICTURE_TYPE_EMF = 2;
-
- /** Windows Meta File */
- public static final int PICTURE_TYPE_WMF = 3;
-
- /** Mac PICT format */
- public static final int PICTURE_TYPE_PICT = 4;
-
- /** JPEG format */
- public static final int PICTURE_TYPE_JPEG = 5;
-
- /** PNG format */
- public static final int PICTURE_TYPE_PNG = 6;
-
- /** Device independent bitmap */
- public static final int PICTURE_TYPE_DIB = 7;
-
- /** GIF image format */
- public static final int PICTURE_TYPE_GIF = 8;
-
- /**
+package org.apache.poi.xwpf.usermodel;\r
+\r
+public interface Document {\r
+ /**\r
+ * Extended windows meta file\r
+ */\r
+ public static final int PICTURE_TYPE_EMF = 2;\r
+\r
+ /**\r
+ * Windows Meta File\r
+ */\r
+ public static final int PICTURE_TYPE_WMF = 3;\r
+\r
+ /**\r
+ * Mac PICT format\r
+ */\r
+ public static final int PICTURE_TYPE_PICT = 4;\r
+\r
+ /**\r
+ * JPEG format\r
+ */\r
+ public static final int PICTURE_TYPE_JPEG = 5;\r
+\r
+ /**\r
+ * PNG format\r
+ */\r
+ public static final int PICTURE_TYPE_PNG = 6;\r
+\r
+ /**\r
+ * Device independent bitmap\r
+ */\r
+ public static final int PICTURE_TYPE_DIB = 7;\r
+\r
+ /**\r
+ * GIF image format\r
+ */\r
+ public static final int PICTURE_TYPE_GIF = 8;\r
+\r
+ /**\r
* Tag Image File (.tiff)
*/
public static final int PICTURE_TYPE_TIFF = 9;
/**
* <p>An IBody represents the different parts of the document which
- * can contain collections of Paragraphs and Tables. It provides a
- * common way to work with these and their contents.</p>
- * <p>Typically, this is something like a XWPFDocument, or one of
- * the parts in it like XWPFHeader, XWPFFooter, XWPFTableCell
- * </p>
- */
-public interface IBody {
+ * can contain collections of Paragraphs and Tables. It provides a\r
+ * common way to work with these and their contents.</p>\r
+ * <p>Typically, this is something like a XWPFDocument, or one of\r
+ * the parts in it like XWPFHeader, XWPFFooter, XWPFTableCell\r
+ * </p>\r
+ */\r
+public interface IBody {\r
/**
- * returns the Part, to which the body belongs, which you need for adding relationship to other parts
- * Actually it is needed of the class XWPFTableCell. Because you have to know to which part the tableCell
- * belongs.
- * @return the Part, to which the body belongs
- */
- public POIXMLDocumentPart getPart();
-
- /**
- * get the PartType of the body, for example
- * DOCUMENT, HEADER, FOOTER, FOOTNOTE,
- * @return the PartType of the body
- */
- public BodyType getPartType();
-
- /**
- * Returns an Iterator with paragraphs and tables,
- * in the order that they occur in the text.
- */
- public List<IBodyElement> getBodyElements();
-
- /**
- * Returns the paragraph(s) that holds
- * the text of the header or footer.
- */
- public List<XWPFParagraph> getParagraphs();
-
- /**
- * Return the table(s) that holds the text
- * of the IBodyPart, for complex cases
- * where a paragraph isn't used.
- */
- public List<XWPFTable> getTables();
-
- /**
- * if there is a corresponding {@link XWPFParagraph} of the parameter ctTable in the paragraphList of this header or footer
- * the method will return this paragraph
- * if there is no corresponding {@link XWPFParagraph} the method will return null
- * @param p is instance of CTP and is searching for an XWPFParagraph
- * @return null if there is no XWPFParagraph with an corresponding CTPparagraph in the paragraphList of this header or footer
- * XWPFParagraph with the correspondig CTP p
- */
- public XWPFParagraph getParagraph(CTP p);
-
- /**
- * if there is a corresponding {@link XWPFTable} of the parameter ctTable in the tableList of this header
- * the method will return this table
- * if there is no corresponding {@link XWPFTable} the method will return null
- * @param ctTable
- */
- public XWPFTable getTable(CTTbl ctTable);
+ * returns the Part, to which the body belongs, which you need for adding relationship to other parts\r
+ * Actually it is needed of the class XWPFTableCell. Because you have to know to which part the tableCell\r
+ * belongs.\r
+ *\r
+ * @return the Part, to which the body belongs\r
+ */\r
+ public POIXMLDocumentPart getPart();\r
+\r
+ /**\r
+ * get the PartType of the body, for example\r
+ * DOCUMENT, HEADER, FOOTER, FOOTNOTE,\r
+ *\r
+ * @return the PartType of the body\r
+ */\r
+ public BodyType getPartType();\r
+\r
+ /**\r
+ * Returns an Iterator with paragraphs and tables,\r
+ * in the order that they occur in the text.\r
+ */\r
+ public List<IBodyElement> getBodyElements();\r
+\r
+ /**\r
+ * Returns the paragraph(s) that holds\r
+ * the text of the header or footer.\r
+ */\r
+ public List<XWPFParagraph> getParagraphs();\r
+\r
+ /**\r
+ * Return the table(s) that holds the text\r
+ * of the IBodyPart, for complex cases\r
+ * where a paragraph isn't used.\r
+ */\r
+ public List<XWPFTable> getTables();\r
+\r
+ /**\r
+ * if there is a corresponding {@link XWPFParagraph} of the parameter ctTable in the paragraphList of this header or footer\r
+ * the method will return this paragraph\r
+ * if there is no corresponding {@link XWPFParagraph} the method will return null\r
+ *\r
+ * @param p is instance of CTP and is searching for an XWPFParagraph\r
+ * @return null if there is no XWPFParagraph with an corresponding CTPparagraph in the paragraphList of this header or footer\r
+ * XWPFParagraph with the correspondig CTP p\r
+ */\r
+ public XWPFParagraph getParagraph(CTP p);\r
+\r
+ /**\r
+ * if there is a corresponding {@link XWPFTable} of the parameter ctTable in the tableList of this header\r
+ * the method will return this table\r
+ * if there is no corresponding {@link XWPFTable} the method will return null\r
+ *\r
+ * @param ctTable\r
+ */\r
+ public XWPFTable getTable(CTTbl ctTable);\r
/**
* Returns the paragraph that of position pos
/**
* Returns the table at position pos
*/
- public XWPFTable getTableArray(int pos);
-
- /**
- *inserts a new paragraph at position of the cursor
- * @param cursor
- */
- public XWPFParagraph insertNewParagraph(XmlCursor cursor);
-
- /**
- * inserts a new Table at the cursor position.
- * @param cursor
- */
- public XWPFTable insertNewTbl(XmlCursor cursor);
-
- /**
- * inserts a new Table at position pos
- * @param pos
- * @param table
- */
+ public XWPFTable getTableArray(int pos);\r
+\r
+ /**\r
+ * inserts a new paragraph at position of the cursor\r
+ *\r
+ * @param cursor\r
+ */\r
+ public XWPFParagraph insertNewParagraph(XmlCursor cursor);\r
+\r
+ /**\r
+ * inserts a new Table at the cursor position.\r
+ *\r
+ * @param cursor\r
+ */\r
+ public XWPFTable insertNewTbl(XmlCursor cursor);\r
+\r
+ /**\r
+ * inserts a new Table at position pos\r
+ *\r
+ * @param pos\r
+ * @param table\r
+ */\r
void insertTable(int pos, XWPFTable table);
-
- /**
- * returns the TableCell to which the Table belongs
- * @param cell
- */
- public XWPFTableCell getTableCell(CTTc cell);
+\r
+ /**\r
+ * returns the TableCell to which the Table belongs\r
+ *\r
+ * @param cell\r
+ */\r
+ public XWPFTableCell getTableCell(CTTc cell);\r
/**
* Return XWPFDocument
package org.apache.poi.xwpf.usermodel;
import org.apache.poi.POIXMLDocumentPart;
-
-/**
- * 9 Jan 2010
- * @author Philipp Epp
- *
- */
-public interface IBodyElement{
- IBody getBody();
- POIXMLDocumentPart getPart();
- BodyType getPartType();
- BodyElementType getElementType();
-}
+\r
+/**\r
+ * 9 Jan 2010\r
+ *\r
+ * @author Philipp Epp\r
+ */\r
+public interface IBodyElement {\r
+ IBody getBody();\r
+\r
+ POIXMLDocumentPart getPart();\r
+\r
+ BodyType getPartType();\r
+\r
+ BodyElementType getElementType();\r
+}\r
limitations under the License.
==================================================================== */
package org.apache.poi.xwpf.usermodel;
-
-/**
- * Interface for anything that can be at a table cell level:
- * {@link XWPFTableCell}, {@link XWPFSDTCell}
- * <p>
- * Schematically something like this:
- * <tr><tc/><tc/><sdt><tc/></sdt></tr>
- */
-public interface ICell {
-}
+\r
+/**\r
+ * Interface for anything that can be at a table cell level:\r
+ * {@link XWPFTableCell}, {@link XWPFSDTCell}\r
+ * <p/>\r
+ * Schematically something like this:\r
+ * <tr><tc/><tc/><sdt><tc/></sdt></tr>\r
+ */\r
+public interface ICell {\r
+}\r
/**
* Simple interface describing both {@link XWPFParagraph}
* and {@link XWPFSDT}
- *
+ * <p/>
* TODO Should this be based on / extend {@link Paragraph}?
*/
public interface IRunBody {
- public XWPFDocument getDocument();
- public POIXMLDocumentPart getPart();
+ public XWPFDocument getDocument();
+
+ public POIXMLDocumentPart getPart();
}
/**
* Common interface for things that can occur
- * where a run (text with common stylings) can,
- * eg {@link XWPFRun} or {@link XWPFSDT}.
+ * where a run (text with common stylings) can,
+ * eg {@link XWPFRun} or {@link XWPFSDT}.
* TODO More methods to follow shortly!
- *
+ * <p/>
* TODO Make this based on {@link CharacterRun}
*/
-public interface IRunElement {
-}
\ No newline at end of file
+public interface IRunElement {}
\ No newline at end of file
limitations under the License.
==================================================================== */
package org.apache.poi.xwpf.usermodel;
-
-
-/**
- * Experimental interface to offer rudimentary read-only processing of
- * of the contentblock of an SDT/ContentControl.
- *
- *
- *
- * WARNING - APIs expected to change rapidly
- *
- */
-public interface ISDTContent {
-
- public String getText();
-
- public String toString();
-
+\r
+\r
+/**\r
+ * Experimental interface to offer rudimentary read-only processing of\r
+ * of the contentblock of an SDT/ContentControl.\r
+ * <p/>\r
+ * <p/>\r
+ * <p/>\r
+ * WARNING - APIs expected to change rapidly\r
+ */\r
+public interface ISDTContent {\r
+\r
+ public String getText();\r
+\r
+ public String toString();\r
+\r
}\r
/**
* Interface for anything that can be within an SDT:
- * {@link XWPFRun}, {@link XWPFTable}, {@link XWPFParagraph},
- * {@link XWPFSDT} etc
+ * {@link XWPFRun}, {@link XWPFTable}, {@link XWPFParagraph},
+ * {@link XWPFSDT} etc
*/
public interface ISDTContents {
}
import java.util.HashMap;
import java.util.Map;
-/**
- * Specifies the logic which shall be used to calculate the line spacing of the
- * parent object when it is displayed in the document.
- *
- * @author Gisella Bronzetti
- */
-public enum LineSpacingRule {
+/**\r
+ * Specifies the logic which shall be used to calculate the line spacing of the\r
+ * parent object when it is displayed in the document.\r
+ *\r
+ * @author Gisella Bronzetti\r
+ */\r
+public enum LineSpacingRule {\r
/**
* Specifies that the line spacing of the parent object shall be
/**
* Specifies that the height of the line shall be at least the value
* specified, but may be expanded to fit its content as needed.
- */
- AT_LEAST(3);
-
-
- private final int value;
-
- private LineSpacingRule(int val) {
- value = val;
- }
-
- public int getValue() {
- return value;
- }
-
- private static Map<Integer, LineSpacingRule> imap = new HashMap<Integer, LineSpacingRule>();
- static {
- for (LineSpacingRule p : values()) {
- imap.put(new Integer(p.getValue()), p);
- }
- }
-
- public static LineSpacingRule valueOf(int type) {
- LineSpacingRule lineType = imap.get(new Integer(type));
- if (lineType == null)
- throw new IllegalArgumentException("Unknown line type: " + type);
- return lineType;
- }
-}
+ */\r
+ AT_LEAST(3);\r
+\r
+\r
+ private static Map<Integer, LineSpacingRule> imap = new HashMap<Integer, LineSpacingRule>();\r
+\r
+ static {\r
+ for (LineSpacingRule p : values()) {\r
+ imap.put(new Integer(p.getValue()), p);\r
+ }\r
+ }\r
+\r
+ private final int value;\r
+\r
+ private LineSpacingRule(int val) {\r
+ value = val;\r
+ }\r
+\r
+ public static LineSpacingRule valueOf(int type) {\r
+ LineSpacingRule lineType = imap.get(new Integer(type));\r
+ if (lineType == null)\r
+ throw new IllegalArgumentException("Unknown line type: " + type);\r
+ return lineType;\r
+ }\r
+\r
+ public int getValue() {\r
+ return value;\r
+ }\r
+}\r
DISTRIBUTE(6),
NUM_TAB(7),
HIGH_KASHIDA(8),
- LOW_KASHIDA(9),
- THAI_DISTRIBUTE(10);
-
- private final int value;
-
- private ParagraphAlignment(int val){
- value = val;
- }
-
- public int getValue(){
- return value;
- }
-
- private static Map<Integer, ParagraphAlignment> imap = new HashMap<Integer, ParagraphAlignment>();
- static{
- for (ParagraphAlignment p : values()) {
- imap.put(new Integer(p.getValue()), p);
- }
- }
-
- public static ParagraphAlignment valueOf(int type){
- ParagraphAlignment err = imap.get(new Integer(type));
- if(err == null) throw new IllegalArgumentException("Unknown paragraph alignment: " + type);
- return err;
- }
-
-}
+ LOW_KASHIDA(9),\r
+ THAI_DISTRIBUTE(10);\r
+\r
+ private static Map<Integer, ParagraphAlignment> imap = new HashMap<Integer, ParagraphAlignment>();\r
+\r
+ static {\r
+ for (ParagraphAlignment p : values()) {\r
+ imap.put(new Integer(p.getValue()), p);\r
+ }\r
+ }\r
+\r
+ private final int value;\r
+\r
+ private ParagraphAlignment(int val) {\r
+ value = val;\r
+ }\r
+\r
+ public static ParagraphAlignment valueOf(int type) {\r
+ ParagraphAlignment err = imap.get(new Integer(type));\r
+ if (err == null) throw new IllegalArgumentException("Unknown paragraph alignment: " + type);\r
+ return err;\r
+ }\r
+\r
+ public int getValue() {\r
+ return value;\r
+ }\r
+\r
+}\r
package org.apache.poi.xwpf.usermodel;
-
-/**
- * postion of a character in a paragrapho
-* 1st RunPositon
-* 2nd TextPosition
-* 3rd CharacterPosition
-*
-*
-*/
-public class PositionInParagraph {
- private int posRun = 0, posText = 0, posChar = 0;
-
- public PositionInParagraph(){
- }
-
- public PositionInParagraph(int posRun, int posText, int posChar){
- this.posRun=posRun;
- this.posChar=posChar;
- this.posText= posText;
- }
-
- public int getRun() {
- return posRun;
- }
-
- public void setRun(int beginRun) {
- this.posRun = beginRun;
- }
-
- public int getText() {
- return posText;
- }
-
- public void setText(int beginText) {
- this.posText = beginText;
- }
-
- public int getChar() {
- return posChar;
- }
-
- public void setChar(int beginChar) {
- this.posChar = beginChar;
- }
-
-}
+\r
+/**\r
+ * postion of a character in a paragrapho\r
+ * 1st RunPositon\r
+ * 2nd TextPosition\r
+ * 3rd CharacterPosition\r
+ */\r
+public class PositionInParagraph {\r
+ private int posRun = 0, posText = 0, posChar = 0;\r
+\r
+ public PositionInParagraph() {\r
+ }\r
+\r
+ public PositionInParagraph(int posRun, int posText, int posChar) {\r
+ this.posRun = posRun;\r
+ this.posChar = posChar;\r
+ this.posText = posText;\r
+ }\r
+\r
+ public int getRun() {\r
+ return posRun;\r
+ }\r
+\r
+ public void setRun(int beginRun) {\r
+ this.posRun = beginRun;\r
+ }\r
+\r
+ public int getText() {\r
+ return posText;\r
+ }\r
+\r
+ public void setText(int beginText) {\r
+ this.posText = beginText;\r
+ }\r
+\r
+ public int getChar() {\r
+ return posChar;\r
+ }\r
+\r
+ public void setChar(int beginChar) {\r
+ this.posChar = beginChar;\r
+ }\r
+\r
+}\r
import org.openxmlformats.schemas.wordprocessingml.x2006.main.STTabJc;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.STTabTlc;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.STTheme;
-
-public class TOC {
-
- CTSdtBlock block;
-
- public TOC() {
- this(CTSdtBlock.Factory.newInstance());
- }
-
- public TOC(CTSdtBlock block) {
- this.block = block;
- CTSdtPr sdtPr = block.addNewSdtPr();
- CTDecimalNumber id = sdtPr.addNewId();
- id.setVal(new BigInteger("4844945"));
- sdtPr.addNewDocPartObj().addNewDocPartGallery().setVal("Table of contents");
- CTSdtEndPr sdtEndPr = block.addNewSdtEndPr();
- CTRPr rPr = sdtEndPr.addNewRPr();
- CTFonts fonts = rPr.addNewRFonts();
- fonts.setAsciiTheme(STTheme.MINOR_H_ANSI);
- fonts.setEastAsiaTheme(STTheme.MINOR_H_ANSI);
- fonts.setHAnsiTheme(STTheme.MINOR_H_ANSI);
- fonts.setCstheme(STTheme.MINOR_BIDI);
- rPr.addNewB().setVal(STOnOff.OFF);
- rPr.addNewBCs().setVal(STOnOff.OFF);
- rPr.addNewColor().setVal("auto");
- rPr.addNewSz().setVal(new BigInteger("24"));
- rPr.addNewSzCs().setVal(new BigInteger("24"));
- CTSdtContentBlock content = block.addNewSdtContent();
- CTP p = content.addNewP();
- p.setRsidR("00EF7E24".getBytes());
- p.setRsidRDefault("00EF7E24".getBytes());
- p.addNewPPr().addNewPStyle().setVal("TOCHeading");
- p.addNewR().addNewT().setStringValue("Table of Contents");
- }
-
- @Internal
- public CTSdtBlock getBlock() {
- return this.block;
- }
-
- public void addRow(int level, String title, int page, String bookmarkRef) {
- CTSdtContentBlock contentBlock = this.block.getSdtContent();
- CTP p = contentBlock.addNewP();
- p.setRsidR("00EF7E24".getBytes());
- p.setRsidRDefault("00EF7E24".getBytes());
- CTPPr pPr = p.addNewPPr();
- pPr.addNewPStyle().setVal("TOC" + level);
- CTTabs tabs = pPr.addNewTabs();
- CTTabStop tab = tabs.addNewTab();
- tab.setVal(STTabJc.RIGHT);
- tab.setLeader(STTabTlc.DOT);
- tab.setPos(new BigInteger("8290"));
- pPr.addNewRPr().addNewNoProof();
- CTR run = p.addNewR();
- run.addNewRPr().addNewNoProof();
- run.addNewT().setStringValue(title);
- run = p.addNewR();
- run.addNewRPr().addNewNoProof();
- run.addNewTab();
- run = p.addNewR();
- run.addNewRPr().addNewNoProof();
- run.addNewFldChar().setFldCharType(STFldCharType.BEGIN);
- // pageref run
- run = p.addNewR();
- run.addNewRPr().addNewNoProof();
- CTText text = run.addNewInstrText();
- text.setSpace(Space.PRESERVE);
- // bookmark reference
- text.setStringValue(" PAGEREF _Toc" + bookmarkRef + " \\h ");
- p.addNewR().addNewRPr().addNewNoProof();
- run = p.addNewR();
- run.addNewRPr().addNewNoProof();
- run.addNewFldChar().setFldCharType(STFldCharType.SEPARATE);
- // page number run
- run = p.addNewR();
- run.addNewRPr().addNewNoProof();
- run.addNewT().setStringValue(Integer.valueOf(page).toString());
- run = p.addNewR();
- run.addNewRPr().addNewNoProof();
- run.addNewFldChar().setFldCharType(STFldCharType.END);
- }
-}
+\r
+public class TOC {\r
+\r
+ CTSdtBlock block;\r
+\r
+ public TOC() {\r
+ this(CTSdtBlock.Factory.newInstance());\r
+ }\r
+\r
+ public TOC(CTSdtBlock block) {\r
+ this.block = block;\r
+ CTSdtPr sdtPr = block.addNewSdtPr();\r
+ CTDecimalNumber id = sdtPr.addNewId();\r
+ id.setVal(new BigInteger("4844945"));\r
+ sdtPr.addNewDocPartObj().addNewDocPartGallery().setVal("Table of contents");\r
+ CTSdtEndPr sdtEndPr = block.addNewSdtEndPr();\r
+ CTRPr rPr = sdtEndPr.addNewRPr();\r
+ CTFonts fonts = rPr.addNewRFonts();\r
+ fonts.setAsciiTheme(STTheme.MINOR_H_ANSI);\r
+ fonts.setEastAsiaTheme(STTheme.MINOR_H_ANSI);\r
+ fonts.setHAnsiTheme(STTheme.MINOR_H_ANSI);\r
+ fonts.setCstheme(STTheme.MINOR_BIDI);\r
+ rPr.addNewB().setVal(STOnOff.OFF);\r
+ rPr.addNewBCs().setVal(STOnOff.OFF);\r
+ rPr.addNewColor().setVal("auto");\r
+ rPr.addNewSz().setVal(new BigInteger("24"));\r
+ rPr.addNewSzCs().setVal(new BigInteger("24"));\r
+ CTSdtContentBlock content = block.addNewSdtContent();\r
+ CTP p = content.addNewP();\r
+ p.setRsidR("00EF7E24".getBytes());\r
+ p.setRsidRDefault("00EF7E24".getBytes());\r
+ p.addNewPPr().addNewPStyle().setVal("TOCHeading");\r
+ p.addNewR().addNewT().setStringValue("Table of Contents");\r
+ }\r
+\r
+ @Internal\r
+ public CTSdtBlock getBlock() {\r
+ return this.block;\r
+ }\r
+\r
+ public void addRow(int level, String title, int page, String bookmarkRef) {\r
+ CTSdtContentBlock contentBlock = this.block.getSdtContent();\r
+ CTP p = contentBlock.addNewP();\r
+ p.setRsidR("00EF7E24".getBytes());\r
+ p.setRsidRDefault("00EF7E24".getBytes());\r
+ CTPPr pPr = p.addNewPPr();\r
+ pPr.addNewPStyle().setVal("TOC" + level);\r
+ CTTabs tabs = pPr.addNewTabs();\r
+ CTTabStop tab = tabs.addNewTab();\r
+ tab.setVal(STTabJc.RIGHT);\r
+ tab.setLeader(STTabTlc.DOT);\r
+ tab.setPos(new BigInteger("8290"));\r
+ pPr.addNewRPr().addNewNoProof();\r
+ CTR run = p.addNewR();\r
+ run.addNewRPr().addNewNoProof();\r
+ run.addNewT().setStringValue(title);\r
+ run = p.addNewR();\r
+ run.addNewRPr().addNewNoProof();\r
+ run.addNewTab();\r
+ run = p.addNewR();\r
+ run.addNewRPr().addNewNoProof();\r
+ run.addNewFldChar().setFldCharType(STFldCharType.BEGIN);\r
+ // pageref run\r
+ run = p.addNewR();\r
+ run.addNewRPr().addNewNoProof();\r
+ CTText text = run.addNewInstrText();\r
+ text.setSpace(Space.PRESERVE);\r
+ // bookmark reference\r
+ text.setStringValue(" PAGEREF _Toc" + bookmarkRef + " \\h ");\r
+ p.addNewR().addNewRPr().addNewNoProof();\r
+ run = p.addNewR();\r
+ run.addNewRPr().addNewNoProof();\r
+ run.addNewFldChar().setFldCharType(STFldCharType.SEPARATE);\r
+ // page number run\r
+ run = p.addNewR();\r
+ run.addNewRPr().addNewNoProof();\r
+ run.addNewT().setStringValue(Integer.valueOf(page).toString());\r
+ run = p.addNewR();\r
+ run.addNewRPr().addNewNoProof();\r
+ run.addNewFldChar().setFldCharType(STFldCharType.END);\r
+ }\r
+}\r
package org.apache.poi.xwpf.usermodel;
import java.util.HashMap;
-import java.util.Map;
-
-/**
- * Specifies all types of vertical alignment which are available to be applied to of all text
- * on each line displayed within a paragraph.
- *
- * @author Gisella Bronzetti
- */
-public enum TextAlignment {
- /**
- * Specifies that all text in the parent object shall be
- * aligned to the top of each character when displayed
- */
- TOP(1),
- /**
- * Specifies that all text in the parent object shall be
- * aligned to the center of each character when displayed.
- */
- CENTER(2),
+import java.util.Map;\r
+\r
+/**\r
+ * Specifies all types of vertical alignment which are available to be applied to of all text\r
+ * on each line displayed within a paragraph.\r
+ *\r
+ * @author Gisella Bronzetti\r
+ */\r
+public enum TextAlignment {\r
+ /**\r
+ * Specifies that all text in the parent object shall be\r
+ * aligned to the top of each character when displayed\r
+ */\r
+ TOP(1),\r
+ /**\r
+ * Specifies that all text in the parent object shall be\r
+ * aligned to the center of each character when displayed.\r
+ */\r
+ CENTER(2),\r
/**
* Specifies that all text in the parent object shall be
* aligned to the baseline of each character when displayed.
/**
* Specifies that all text in the parent object shall be
* aligned to the bottom of each character when displayed.
- */
- BOTTOM(4),
- /**
- * Specifies that all text in the parent object shall be
- * aligned automatically when displayed.
- */
- AUTO(5);
-
- private final int value;
-
- private TextAlignment(int val){
- value = val;
- }
-
- public int getValue(){
- return value;
- }
-
- private static Map<Integer, TextAlignment> imap = new HashMap<Integer, TextAlignment>();
- static{
- for (TextAlignment p : values()) {
- imap.put(new Integer(p.getValue()), p);
- }
- }
-
- public static TextAlignment valueOf(int type){
- TextAlignment align = imap.get(new Integer(type));
- if(align == null) throw new IllegalArgumentException("Unknown text alignment: " + type);
- return align;
- }
-}
+ */\r
+ BOTTOM(4),\r
+ /**\r
+ * Specifies that all text in the parent object shall be\r
+ * aligned automatically when displayed.\r
+ */\r
+ AUTO(5);\r
+\r
+ private static Map<Integer, TextAlignment> imap = new HashMap<Integer, TextAlignment>();\r
+\r
+ static {\r
+ for (TextAlignment p : values()) {\r
+ imap.put(new Integer(p.getValue()), p);\r
+ }\r
+ }\r
+\r
+ private final int value;\r
+\r
+ private TextAlignment(int val) {\r
+ value = val;\r
+ }\r
+\r
+ public static TextAlignment valueOf(int type) {\r
+ TextAlignment align = imap.get(new Integer(type));\r
+ if (align == null) throw new IllegalArgumentException("Unknown text alignment: " + type);\r
+ return align;\r
+ }\r
+\r
+ public int getValue() {\r
+ return value;\r
+ }\r
+}\r
==================================================================== */
package org.apache.poi.xwpf.usermodel;
-
-/**
- * saves the begin and end position of a text in a Paragraph
-*/
-public class TextSegement {
- private PositionInParagraph beginPos;
- private PositionInParagraph endPos;
-
- public TextSegement(){
- this.beginPos = new PositionInParagraph();
- this. endPos = new PositionInParagraph();
- }
-
- public TextSegement(int beginRun, int endRun, int beginText, int endText, int beginChar, int endChar){
- PositionInParagraph beginPos = new PositionInParagraph(beginRun, beginText, beginChar);
- PositionInParagraph endPos = new PositionInParagraph(endRun, endText, endChar);
- this.beginPos = beginPos;
- this.endPos = endPos;
- }
-
- public TextSegement(PositionInParagraph beginPos, PositionInParagraph endPos){
- this.beginPos = beginPos;
- this.endPos = endPos;
- }
-
- public PositionInParagraph getBeginPos(){
- return beginPos;
- }
-
- public PositionInParagraph getEndPos(){
- return endPos;
- }
-
- public int getBeginRun(){
- return beginPos.getRun();
- }
-
- public void setBeginRun(int beginRun){
- beginPos.setRun(beginRun);
- }
-
- public int getBeginText(){
- return beginPos.getText();
- }
-
- public void setBeginText(int beginText){
- beginPos.setText(beginText);
- }
-
- public int getBeginChar(){
- return beginPos.getChar();
- }
-
- public void setBeginChar(int beginChar){
- beginPos.setChar(beginChar);
- }
- public int getEndRun(){
- return endPos.getRun();
- }
-
- public void setEndRun(int endRun){
- endPos.setRun(endRun);
- }
-
- public int getEndText(){
- return endPos.getText();
- }
-
- public void setEndText(int endText){
- endPos.setText(endText);
- }
-
- public int getEndChar(){
- return endPos.getChar();
- }
-
- public void setEndChar(int endChar){
- endPos.setChar(endChar);
- }
-}
+\r
+/**\r
+ * saves the begin and end position of a text in a Paragraph\r
+ */\r
+public class TextSegement {\r
+ private PositionInParagraph beginPos;\r
+ private PositionInParagraph endPos;\r
+\r
+ public TextSegement() {\r
+ this.beginPos = new PositionInParagraph();\r
+ this.endPos = new PositionInParagraph();\r
+ }\r
+\r
+ public TextSegement(int beginRun, int endRun, int beginText, int endText, int beginChar, int endChar) {\r
+ PositionInParagraph beginPos = new PositionInParagraph(beginRun, beginText, beginChar);\r
+ PositionInParagraph endPos = new PositionInParagraph(endRun, endText, endChar);\r
+ this.beginPos = beginPos;\r
+ this.endPos = endPos;\r
+ }\r
+\r
+ public TextSegement(PositionInParagraph beginPos, PositionInParagraph endPos) {\r
+ this.beginPos = beginPos;\r
+ this.endPos = endPos;\r
+ }\r
+\r
+ public PositionInParagraph getBeginPos() {\r
+ return beginPos;\r
+ }\r
+\r
+ public PositionInParagraph getEndPos() {\r
+ return endPos;\r
+ }\r
+\r
+ public int getBeginRun() {\r
+ return beginPos.getRun();\r
+ }\r
+\r
+ public void setBeginRun(int beginRun) {\r
+ beginPos.setRun(beginRun);\r
+ }\r
+\r
+ public int getBeginText() {\r
+ return beginPos.getText();\r
+ }\r
+\r
+ public void setBeginText(int beginText) {\r
+ beginPos.setText(beginText);\r
+ }\r
+\r
+ public int getBeginChar() {\r
+ return beginPos.getChar();\r
+ }\r
+\r
+ public void setBeginChar(int beginChar) {\r
+ beginPos.setChar(beginChar);\r
+ }\r
+\r
+ public int getEndRun() {\r
+ return endPos.getRun();\r
+ }\r
+\r
+ public void setEndRun(int endRun) {\r
+ endPos.setRun(endRun);\r
+ }\r
+\r
+ public int getEndText() {\r
+ return endPos.getText();\r
+ }\r
+\r
+ public void setEndText(int endText) {\r
+ endPos.setText(endText);\r
+ }\r
+\r
+ public int getEndChar() {\r
+ return endPos.getChar();\r
+ }\r
+\r
+ public void setEndChar(int endChar) {\r
+ endPos.setChar(endChar);\r
+ }\r
+}\r
import java.util.HashMap;
import java.util.Map;
-/**
- * Specifies the types of patterns which may be used to create the underline
- * applied beneath the text in a run.
- *
- * @author Gisella Bronzetti
- */
-public enum UnderlinePatterns {
+/**\r
+ * Specifies the types of patterns which may be used to create the underline\r
+ * applied beneath the text in a run.\r
+ *\r
+ * @author Gisella Bronzetti\r
+ */\r
+public enum UnderlinePatterns {\r
/**
* Specifies an underline consisting of a single line beneath all characters
/**
* Specifies no underline beneath this run.
- */
- NONE(18);
-
- private final int value;
-
- private UnderlinePatterns(int val) {
- value = val;
- }
-
- public int getValue() {
- return value;
- }
-
- private static Map<Integer, UnderlinePatterns> imap = new HashMap<Integer, UnderlinePatterns>();
- static {
- for (UnderlinePatterns p : values()) {
- imap.put(new Integer(p.getValue()), p);
- }
- }
-
- public static UnderlinePatterns valueOf(int type) {
- UnderlinePatterns align = imap.get(new Integer(type));
- if (align == null)
- throw new IllegalArgumentException("Unknown underline pattern: "
- + type);
- return align;
- }
-}
+ */\r
+ NONE(18);\r
+\r
+ private static Map<Integer, UnderlinePatterns> imap = new HashMap<Integer, UnderlinePatterns>();\r
+\r
+ static {\r
+ for (UnderlinePatterns p : values()) {\r
+ imap.put(new Integer(p.getValue()), p);\r
+ }\r
+ }\r
+\r
+ private final int value;\r
+\r
+ private UnderlinePatterns(int val) {\r
+ value = val;\r
+ }\r
+\r
+ public static UnderlinePatterns valueOf(int type) {\r
+ UnderlinePatterns align = imap.get(new Integer(type));\r
+ if (align == null)\r
+ throw new IllegalArgumentException("Unknown underline pattern: "\r
+ + type);\r
+ return align;\r
+ }\r
+\r
+ public int getValue() {\r
+ return value;\r
+ }\r
+}\r
/**
* Specifies possible values for the alignment of the contents of this run in
- * relation to the default appearance of the run's text. This allows the text to
- * be repositioned as subscript or superscript without altering the font size of
- * the run properties.
- *
- * @author Gisella Bronzetti
- */
-public enum VerticalAlign {
+ * relation to the default appearance of the run's text. This allows the text to\r
+ * be repositioned as subscript or superscript without altering the font size of\r
+ * the run properties.\r
+ *\r
+ * @author Gisella Bronzetti\r
+ */\r
+public enum VerticalAlign {\r
/**
* Specifies that the text in the parent run shall be located at the
* Specifies that this text should be superscript. This setting shall raise
* the text in this run above the baseline and change it to a smaller size,
* if a smaller size is available.
- */
- SUBSCRIPT(3);
-
- private final int value;
-
- private VerticalAlign(int val) {
- value = val;
- }
-
- public int getValue() {
- return value;
- }
-
- private static Map<Integer, VerticalAlign> imap = new HashMap<Integer, VerticalAlign>();
- static {
- for (VerticalAlign p : values()) {
- imap.put(new Integer(p.getValue()), p);
- }
- }
-
- public static VerticalAlign valueOf(int type) {
- VerticalAlign align = imap.get(new Integer(type));
- if (align == null)
- throw new IllegalArgumentException("Unknown vertical alignment: "
- + type);
- return align;
- }
-}
+ */\r
+ SUBSCRIPT(3);\r
+\r
+ private static Map<Integer, VerticalAlign> imap = new HashMap<Integer, VerticalAlign>();\r
+\r
+ static {\r
+ for (VerticalAlign p : values()) {\r
+ imap.put(new Integer(p.getValue()), p);\r
+ }\r
+ }\r
+\r
+ private final int value;\r
+\r
+ private VerticalAlign(int val) {\r
+ value = val;\r
+ }\r
+\r
+ public static VerticalAlign valueOf(int type) {\r
+ VerticalAlign align = imap.get(new Integer(type));\r
+ if (align == null)\r
+ throw new IllegalArgumentException("Unknown vertical alignment: "\r
+ + type);\r
+ return align;\r
+ }\r
+\r
+ public int getValue() {\r
+ return value;\r
+ }\r
+}\r
package org.apache.poi.xwpf.usermodel;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTAbstractNum;
-
-/**
- * @author Philipp Epp
- *
- */
-public class XWPFAbstractNum {
- private CTAbstractNum ctAbstractNum;
- protected XWPFNumbering numbering;
-
- protected XWPFAbstractNum() {
- this.ctAbstractNum = null;
- this.numbering = null;
-
- }
- public XWPFAbstractNum(CTAbstractNum abstractNum){
- this.ctAbstractNum = abstractNum;
- }
-
- public XWPFAbstractNum(CTAbstractNum ctAbstractNum, XWPFNumbering numbering){
- this.ctAbstractNum = ctAbstractNum;
- this.numbering = numbering;
- }
- public CTAbstractNum getAbstractNum(){
- return ctAbstractNum;
- }
-
- public XWPFNumbering getNumbering(){
- return numbering;
- }
-
- public CTAbstractNum getCTAbstractNum(){
- return ctAbstractNum;
- }
-
- public void setNumbering(XWPFNumbering numbering){
- this.numbering = numbering;
- }
-
-}
+\r
+/**\r
+ * @author Philipp Epp\r
+ */\r
+public class XWPFAbstractNum {\r
+ protected XWPFNumbering numbering;\r
+ private CTAbstractNum ctAbstractNum;\r
+\r
+ protected XWPFAbstractNum() {\r
+ this.ctAbstractNum = null;\r
+ this.numbering = null;\r
+\r
+ }\r
+\r
+ public XWPFAbstractNum(CTAbstractNum abstractNum) {\r
+ this.ctAbstractNum = abstractNum;\r
+ }\r
+\r
+ public XWPFAbstractNum(CTAbstractNum ctAbstractNum, XWPFNumbering numbering) {\r
+ this.ctAbstractNum = ctAbstractNum;\r
+ this.numbering = numbering;\r
+ }\r
+\r
+ public CTAbstractNum getAbstractNum() {\r
+ return ctAbstractNum;\r
+ }\r
+\r
+ public XWPFNumbering getNumbering() {\r
+ return numbering;\r
+ }\r
+\r
+ public void setNumbering(XWPFNumbering numbering) {\r
+ this.numbering = numbering;\r
+ }\r
+\r
+ public CTAbstractNum getCTAbstractNum() {\r
+ return ctAbstractNum;\r
+ }\r
+\r
+}\r
/**
* Sketch of XWPF comment class
- *
-* @author Yury Batrakov (batrakov at gmail.com)
- *
+ *
+ * @author Yury Batrakov (batrakov at gmail.com)
*/
-public class XWPFComment
-{
+public class XWPFComment {
protected String id;
protected String author;
protected StringBuffer text;
-
+
@SuppressWarnings("deprecation")
- public XWPFComment(CTComment comment, XWPFDocument document)
- {
+ public XWPFComment(CTComment comment, XWPFDocument document) {
text = new StringBuffer();
id = comment.getId().toString();
author = comment.getAuthor();
-
- for(CTP ctp : comment.getPArray())
- {
+
+ for (CTP ctp : comment.getPArray()) {
XWPFParagraph p = new XWPFParagraph(ctp, document);
text.append(p.getText());
}
}
-
- public String getId()
- {
+
+ public String getId() {
return id;
}
-
- public String getAuthor()
- {
+
+ public String getAuthor() {
return author;
}
-
- public String getText()
- {
+
+ public String getText() {
return text.toString();
}
}
/**
* Default Paragraph style, from which other styles will override
* TODO Share logic with {@link XWPFParagraph} which also uses CTPPr
- */
-public class XWPFDefaultParagraphStyle {
- private CTPPr ppr;
-
- public XWPFDefaultParagraphStyle(CTPPr ppr) {
- this.ppr = ppr;
- }
-
- protected CTPPr getPPr() {
- return ppr;
- }
-
- public int getSpacingAfter() {
- if (ppr.isSetSpacing())
- return ppr.getSpacing().getAfter().intValue();
+ */\r
+public class XWPFDefaultParagraphStyle {\r
+ private CTPPr ppr;\r
+\r
+ public XWPFDefaultParagraphStyle(CTPPr ppr) {\r
+ this.ppr = ppr;\r
+ }\r
+\r
+ protected CTPPr getPPr() {\r
+ return ppr;\r
+ }\r
+\r
+ public int getSpacingAfter() {\r
+ if (ppr.isSetSpacing())\r
+ return ppr.getSpacing().getAfter().intValue();\r
return -1;
}
}
/**
* Default Character Run style, from which other styles will override
* TODO Share logic with {@link XWPFRun} which also uses CTRPr
- */
-public class XWPFDefaultRunStyle {
- private CTRPr rpr;
-
- public XWPFDefaultRunStyle(CTRPr rpr) {
- this.rpr = rpr;
- }
-
- protected CTRPr getRPr() {
- return rpr;
- }
-
- public int getFontSize() {
- if (rpr.isSetSz())
- return rpr.getSz().getVal().intValue() / 2;
+ */\r
+public class XWPFDefaultRunStyle {\r
+ private CTRPr rpr;\r
+\r
+ public XWPFDefaultRunStyle(CTRPr rpr) {\r
+ this.rpr = rpr;\r
+ }\r
+\r
+ protected CTRPr getRPr() {\r
+ return rpr;\r
+ }\r
+\r
+ public int getFontSize() {\r
+ if (rpr.isSetSz())\r
+ return rpr.getSz().getVal().intValue() / 2;\r
return -1;
}
}
/**
* <p>High(ish) level class for working with .docx files.</p>
- *
+ * <p/>
* <p>This class tries to hide some of the complexity
- * of the underlying file format, but as it's not a
- * mature and stable API yet, certain parts of the
- * XML structure come through. You'll therefore almost
- * certainly need to refer to the OOXML specifications
- * from
- * http://www.ecma-international.org/publications/standards/Ecma-376.htm
- * at some point in your use.</p>
+ * of the underlying file format, but as it's not a
+ * mature and stable API yet, certain parts of the
+ * XML structure come through. You'll therefore almost
+ * certainly need to refer to the OOXML specifications
+ * from
+ * http://www.ecma-international.org/publications/standards/Ecma-376.htm
+ * at some point in your use.</p>
*/
public class XWPFDocument extends POIXMLDocument implements Document, IBody {
- private CTDocument1 ctDocument;
- private XWPFSettings settings;
- /**
- * Keeps track on all id-values used in this document and included parts, like headers, footers, etc.
- */
- private IdentifierManager drawingIdManager = new IdentifierManager(0L,4294967295L);
protected List<XWPFFooter> footers = new ArrayList<XWPFFooter>();
protected List<XWPFHeader> headers = new ArrayList<XWPFHeader>();
protected List<XWPFComment> comments = new ArrayList<XWPFComment>();
protected XWPFNumbering numbering;
protected XWPFStyles styles;
protected XWPFFootnotes footnotes;
-
- /** Handles the joy of different headers/footers for different pages */
+ private CTDocument1 ctDocument;
+ private XWPFSettings settings;
+ /**
+ * Keeps track on all id-values used in this document and included parts, like headers, footers, etc.
+ */
+ private IdentifierManager drawingIdManager = new IdentifierManager(0L, 4294967295L);
+ /**
+ * Handles the joy of different headers/footers for different pages
+ */
private XWPFHeaderFooterPolicy headerFooterPolicy;
public XWPFDocument(OPCPackage pkg) throws IOException {
load(XWPFFactory.getInstance());
}
- public XWPFDocument(){
+ public XWPFDocument() {
super(newPackage());
onDocumentCreate();
}
+ /**
+ * Create a new WordProcessingML package and setup the default minimal content
+ */
+ protected static OPCPackage newPackage() {
+ try {
+ OPCPackage pkg = OPCPackage.create(new ByteArrayOutputStream());
+ // Main part
+ PackagePartName corePartName = PackagingURIHelper.createPartName(XWPFRelation.DOCUMENT.getDefaultFileName());
+ // Create main part relationship
+ pkg.addRelationship(corePartName, TargetMode.INTERNAL, PackageRelationshipTypes.CORE_DOCUMENT);
+ // Create main document part
+ pkg.createPart(corePartName, XWPFRelation.DOCUMENT.getContentType());
+
+ pkg.getPackageProperties().setCreatorProperty(DOCUMENT_CREATOR);
+
+ return pkg;
+ } catch (Exception e) {
+ throw new POIXMLException(e);
+ }
+ }
+
@Override
protected void onDocumentRead() throws IOException {
try {
XWPFTable t = new XWPFTable((CTTbl) o, this);
bodyElements.add(t);
tables.add(t);
- } else if (o instanceof CTSdtBlock){
- XWPFSDT c = new XWPFSDT((CTSdtBlock)o, this);
- bodyElements.add(c);
- contentControls.add(c);
- }
+ } else if (o instanceof CTSdtBlock) {
+ XWPFSDT c = new XWPFSDT((CTSdtBlock) o, this);
+ bodyElements.add(c);
+ contentControls.add(c);
+ }
}
cursor.dispose();
Method onDocumentRead = gp.getClass().getDeclaredMethod("onDocumentRead");
onDocumentRead.setAccessible(true);
onDocumentRead.invoke(gp);
- } catch(Exception e) {
+ } catch (Exception e) {
throw new POIXMLException(e);
}
}
}
}
- private void initHyperlinks(){
+ private void initHyperlinks() {
// Get the hyperlinks
// TODO: make me optional/separated in private function
try {
Iterator<PackageRelationship> relIter =
getPackagePart().getRelationshipsByType(XWPFRelation.HYPERLINK.getRelation()).iterator();
- while(relIter.hasNext()) {
+ while (relIter.hasNext()) {
PackageRelationship rel = relIter.next();
hyperlinks.add(new XWPFHyperlink(rel.getId(), rel.getTargetURI().toString()));
}
- } catch (InvalidFormatException e){
+ } catch (InvalidFormatException e) {
throw new POIXMLException(e);
}
}
@SuppressWarnings("deprecation")
private void initFootnotes() throws XmlException, IOException {
- for(POIXMLDocumentPart p : getRelations()){
+ for (POIXMLDocumentPart p : getRelations()) {
String relation = p.getPackageRelationship().getRelationshipType();
if (relation.equals(XWPFRelation.FOOTNOTE.getRelation())) {
- this.footnotes = (XWPFFootnotes)p;
+ this.footnotes = (XWPFFootnotes) p;
this.footnotes.onDocumentRead();
- } else if (relation.equals(XWPFRelation.ENDNOTE.getRelation())){
+ } else if (relation.equals(XWPFRelation.ENDNOTE.getRelation())) {
EndnotesDocument endnotesDocument = EndnotesDocument.Factory.parse(p.getPackagePart().getInputStream());
- for(CTFtnEdn ctFtnEdn : endnotesDocument.getEndnotes().getEndnoteArray()) {
+ for (CTFtnEdn ctFtnEdn : endnotesDocument.getEndnotes().getEndnoteArray()) {
endnotes.put(ctFtnEdn.getId().intValue(), new XWPFFootnote(this, ctFtnEdn));
}
}
}
}
- /**
- * Create a new WordProcessingML package and setup the default minimal content
- */
- protected static OPCPackage newPackage() {
- try {
- OPCPackage pkg = OPCPackage.create(new ByteArrayOutputStream());
- // Main part
- PackagePartName corePartName = PackagingURIHelper.createPartName(XWPFRelation.DOCUMENT.getDefaultFileName());
- // Create main part relationship
- pkg.addRelationship(corePartName, TargetMode.INTERNAL, PackageRelationshipTypes.CORE_DOCUMENT);
- // Create main document part
- pkg.createPart(corePartName, XWPFRelation.DOCUMENT.getContentType());
-
- pkg.getPackageProperties().setCreatorProperty(DOCUMENT_CREATOR);
-
- return pkg;
- } catch (Exception e){
- throw new POIXMLException(e);
- }
- }
-
/**
* Create a new CTWorkbook with all values set to default
*/
ctDocument = CTDocument1.Factory.newInstance();
ctDocument.addNewBody();
- settings = (XWPFSettings) createRelationship(XWPFRelation.SETTINGS,XWPFFactory.getInstance());
+ settings = (XWPFSettings) createRelationship(XWPFRelation.SETTINGS, XWPFFactory.getInstance());
POIXMLProperties.ExtendedProperties expProps = getProperties().getExtendedProperties();
expProps.getUnderlyingProperties().setApplication(DOCUMENT_CREATOR);
/**
* returns an Iterator with paragraphs and tables
+ *
* @see org.apache.poi.xwpf.usermodel.IBody#getBodyElements()
*/
@Override
* @see org.apache.poi.xwpf.usermodel.IBody#getParagraphs()
*/
@Override
- public List<XWPFParagraph> getParagraphs(){
+ public List<XWPFParagraph> getParagraphs() {
return Collections.unmodifiableList(paragraphs);
}
* @see org.apache.poi.xwpf.usermodel.IBody#getTables()
*/
@Override
- public List<XWPFTable> getTables(){
+ public List<XWPFTable> getTables() {
return Collections.unmodifiableList(tables);
}
*/
@Override
public XWPFTable getTableArray(int pos) {
- if (pos > 0 && pos < tables.size()){
+ if (pos > 0 && pos < tables.size()) {
return tables.get(pos);
}
return null;
}
/**
- *
- * @return the list of footers
+ * @return the list of footers
*/
- public List<XWPFFooter> getFooterList(){
+ public List<XWPFFooter> getFooterList() {
return Collections.unmodifiableList(footers);
}
- public XWPFFooter getFooterArray(int pos){
+ public XWPFFooter getFooterArray(int pos) {
return footers.get(pos);
}
/**
- *
- * @return the list of headers
+ * @return the list of headers
*/
- public List<XWPFHeader> getHeaderList(){
+ public List<XWPFHeader> getHeaderList() {
return Collections.unmodifiableList(headers);
}
- public XWPFHeader getHeaderArray(int pos){
+ public XWPFHeader getHeaderArray(int pos) {
return headers.get(pos);
}
- public String getTblStyle(XWPFTable table){
+ public String getTblStyle(XWPFTable table) {
return table.getStyleID();
}
}
public XWPFFootnote getFootnoteByID(int id) {
- if(footnotes == null) return null;
+ if (footnotes == null) return null;
return footnotes.getFootnoteById(id);
}
public XWPFFootnote getEndnoteByID(int id) {
- if(endnotes == null) return null;
+ if (endnotes == null) return null;
return endnotes.get(id);
}
public List<XWPFFootnote> getFootnotes() {
- if(footnotes == null) {
+ if (footnotes == null) {
return Collections.emptyList();
}
return footnotes.getFootnotesList();
/**
* Get the document part that's defined as the
- * given relationship of the core document.
+ * given relationship of the core document.
*/
public PackagePart getPartById(String id) {
try {
/**
* Returns the policy on headers and footers, which
- * also provides a way to get at them.
+ * also provides a way to get at them.
*/
public XWPFHeaderFooterPolicy getHeaderFooterPolicy() {
return headerFooterPolicy;
PackagePart[] parts;
try {
parts = getRelatedByType(XWPFRelation.STYLES.getRelation());
- } catch(InvalidFormatException e) {
+ } catch (InvalidFormatException e) {
throw new IllegalStateException(e);
}
- if(parts.length != 1) {
+ if (parts.length != 1) {
throw new IllegalStateException("Expecting one Styles document part, but found " + parts.length);
}
* Finds that for example the 2nd entry in the body list is the 1st paragraph
*/
private int getBodyElementSpecificPos(int pos, List<? extends IBodyElement> list) {
- // If there's nothing to find, skip it
- if(list.size() == 0) {
- return -1;
- }
-
- if(pos >= 0 && pos < bodyElements.size()) {
- // Ensure the type is correct
- IBodyElement needle = bodyElements.get(pos);
- if(needle.getElementType() != list.get(0).getElementType()) {
- // Wrong type
- return -1;
- }
-
- // Work back until we find it
- int startPos = Math.min(pos, list.size()-1);
- for(int i=startPos; i>=0; i--) {
- if(list.get(i) == needle) {
- return i;
- }
- }
- }
-
- // Couldn't be found
- return -1;
- }
-
+ // If there's nothing to find, skip it
+ if (list.size() == 0) {
+ return -1;
+ }
+
+ if (pos >= 0 && pos < bodyElements.size()) {
+ // Ensure the type is correct
+ IBodyElement needle = bodyElements.get(pos);
+ if (needle.getElementType() != list.get(0).getElementType()) {
+ // Wrong type
+ return -1;
+ }
+
+ // Work back until we find it
+ int startPos = Math.min(pos, list.size() - 1);
+ for (int i = startPos; i >= 0; i--) {
+ if (list.get(i) == needle) {
+ return i;
+ }
+ }
+ }
+
+ // Couldn't be found
+ return -1;
+ }
+
/**
* Look up the paragraph at the specified position in the body elements list
* and return this paragraphs position in the paragraphs list
- *
- * @param pos
- * The position of the relevant paragraph in the body elements
+ *
+ * @param pos The position of the relevant paragraph in the body elements
* list
* @return the position of the paragraph in the paragraphs list, if there is
- * a paragraph at the position in the bodyelements list. Else it
- * will return -1
- *
+ * a paragraph at the position in the bodyelements list. Else it
+ * will return -1
*/
public int getParagraphPos(int pos) {
- return getBodyElementSpecificPos(pos, paragraphs);
+ return getBodyElementSpecificPos(pos, paragraphs);
}
/**
- * get with the position of a table in the bodyelement array list
+ * get with the position of a table in the bodyelement array list
* the position of this table in the table array list
+ *
* @param pos position of the table in the bodyelement array list
* @return if there is a table at the position in the bodyelement array list,
- * else it will return null.
+ * else it will return null.
*/
public int getTablePos(int pos) {
- return getBodyElementSpecificPos(pos, tables);
+ return getBodyElementSpecificPos(pos, tables);
}
/**
* of the documents body. When this method is done, the cursor passed as
* parameter points to the {@link org.apache.xmlbeans.XmlCursor.TokenType#END}
* of the newly inserted paragraph.
- *
+ *
* @param cursor
* @return the {@link XWPFParagraph} object representing the newly inserted
- * CTP object
+ * CTP object
*/
@Override
public XWPFParagraph insertNewParagraph(XmlCursor cursor) {
cursor.toCursor(tableCursor);
cursor.toEndToken();
return newT;
- }
- finally {
+ } finally {
tableCursor.dispose();
}
}
/**
* verifies that cursor is on the right position
+ *
* @param cursor
*/
private boolean isCursorInBody(XmlCursor cursor) {
private int getPosOfBodyElement(IBodyElement needle) {
BodyElementType type = needle.getElementType();
- IBodyElement current;
- for(int i=0; i<bodyElements.size(); i++) {
+ IBodyElement current;
+ for (int i = 0; i < bodyElements.size(); i++) {
current = bodyElements.get(i);
- if(current.getElementType() == type) {
- if(current.equals(needle)) {
+ if (current.getElementType() == type) {
+ if (current.equals(needle)) {
return i;
}
}
/**
* Get the position of the paragraph, within the list
- * of all the body elements.
+ * of all the body elements.
+ *
* @param p The paragraph to find
- * @return The location, or -1 if the paragraph couldn't be found
+ * @return The location, or -1 if the paragraph couldn't be found
*/
- public int getPosOfParagraph(XWPFParagraph p){
+ public int getPosOfParagraph(XWPFParagraph p) {
return getPosOfBodyElement(p);
}
/**
* Get the position of the table, within the list of
- * all the body elements.
+ * all the body elements.
+ *
* @param t The table to find
* @return The location, or -1 if the table couldn't be found
*/
- public int getPosOfTable(XWPFTable t){
+ public int getPosOfTable(XWPFTable t) {
return getPosOfBodyElement(t);
}
/**
* Gets the index of the relation we're trying to create
+ *
* @param relation
* @return i
*/
private int getRelationIndex(XWPFRelation relation) {
List<POIXMLDocumentPart> relations = getRelations();
int i = 1;
- for (Iterator<POIXMLDocumentPart> it = relations.iterator(); it.hasNext() ; ) {
- POIXMLDocumentPart item = it.next();
- if (item.getPackageRelationship().getRelationshipType().equals(relation.getRelation())) {
- i++;
- }
+ for (Iterator<POIXMLDocumentPart> it = relations.iterator(); it.hasNext(); ) {
+ POIXMLDocumentPart item = it.next();
+ if (item.getPackageRelationship().getRelationshipType().equals(relation.getRelation())) {
+ i++;
+ }
}
return i;
}
/**
* Appends a new paragraph to this document
+ *
* @return a new paragraph
*/
public XWPFParagraph createParagraph() {
/**
* Creates an empty numbering if one does not already exist and sets the numbering member
+ *
* @return numbering
*/
public XWPFNumbering createNumbering() {
- if(numbering == null) {
+ if (numbering == null) {
NumberingDocument numberingDoc = NumberingDocument.Factory.newInstance();
XWPFRelation relation = XWPFRelation.NUMBERING;
int i = getRelationIndex(relation);
- XWPFNumbering wrapper = (XWPFNumbering)createRelationship(relation, XWPFFactory.getInstance(), i);
+ XWPFNumbering wrapper = (XWPFNumbering) createRelationship(relation, XWPFFactory.getInstance(), i);
wrapper.setNumbering(numberingDoc.addNewNumbering());
numbering = wrapper;
}
/**
* Creates an empty styles for the document if one does not already exist
+ *
* @return styles
*/
public XWPFStyles createStyles() {
- if(styles == null) {
- StylesDocument stylesDoc = StylesDocument.Factory.newInstance();
+ if (styles == null) {
+ StylesDocument stylesDoc = StylesDocument.Factory.newInstance();
- XWPFRelation relation = XWPFRelation.STYLES;
- int i = getRelationIndex(relation);
+ XWPFRelation relation = XWPFRelation.STYLES;
+ int i = getRelationIndex(relation);
- XWPFStyles wrapper = (XWPFStyles)createRelationship(relation, XWPFFactory.getInstance(), i);
- wrapper.setStyles(stylesDoc.addNewStyles());
- styles = wrapper;
- }
+ XWPFStyles wrapper = (XWPFStyles) createRelationship(relation, XWPFFactory.getInstance(), i);
+ wrapper.setStyles(stylesDoc.addNewStyles());
+ styles = wrapper;
+ }
- return styles;
+ return styles;
}
/**
* Creates an empty footnotes element for the document if one does not already exist
+ *
* @return footnotes
*/
public XWPFFootnotes createFootnotes() {
- if(footnotes == null) {
- FootnotesDocument footnotesDoc = FootnotesDocument.Factory.newInstance();
+ if (footnotes == null) {
+ FootnotesDocument footnotesDoc = FootnotesDocument.Factory.newInstance();
- XWPFRelation relation = XWPFRelation.FOOTNOTE;
- int i = getRelationIndex(relation);
+ XWPFRelation relation = XWPFRelation.FOOTNOTE;
+ int i = getRelationIndex(relation);
- XWPFFootnotes wrapper = (XWPFFootnotes)createRelationship(relation, XWPFFactory.getInstance(), i);
- wrapper.setFootnotes(footnotesDoc.addNewFootnotes());
- footnotes = wrapper;
- }
+ XWPFFootnotes wrapper = (XWPFFootnotes) createRelationship(relation, XWPFFactory.getInstance(), i);
+ wrapper.setFootnotes(footnotesDoc.addNewFootnotes());
+ footnotes = wrapper;
+ }
- return footnotes;
+ return footnotes;
}
public XWPFFootnote addFootnote(CTFtnEdn note) {
- return footnotes.addFootnote(note);
+ return footnotes.addFootnote(note);
}
public XWPFFootnote addEndnote(CTFtnEdn note) {
- XWPFFootnote endnote = new XWPFFootnote(this, note);
- endnotes.put(note.getId().intValue(), endnote);
- return endnote;
+ XWPFFootnote endnote = new XWPFFootnote(this, note);
+ endnotes.put(note.getId().intValue(), endnote);
+ return endnote;
}
/**
- * remove a BodyElement from bodyElements array list
+ * remove a BodyElement from bodyElements array list
+ *
* @param pos
* @return true if removing was successfully, else return false
*/
public boolean removeBodyElement(int pos) {
if (pos >= 0 && pos < bodyElements.size()) {
- BodyElementType type = bodyElements.get(pos).getElementType();
- if (type == BodyElementType.TABLE){
+ BodyElementType type = bodyElements.get(pos).getElementType();
+ if (type == BodyElementType.TABLE) {
int tablePos = getTablePos(pos);
tables.remove(tablePos);
ctDocument.getBody().removeTbl(tablePos);
ctDocument.getBody().removeP(paraPos);
}
bodyElements.remove(pos);
- return true;
+ return true;
}
return false;
}
/**
* copies content of a paragraph to a existing paragraph in the list paragraphs at position pos
+ *
* @param paragraph
* @param pos
*/
/**
* Create an empty table with one row and one column as default.
+ *
* @return a new table
*/
public XWPFTable createTable() {
/**
* Create an empty table with a number of rows and cols specified
+ *
* @param rows
* @param cols
* @return table
*/
public XWPFTable createTable(int rows, int cols) {
- XWPFTable table = new XWPFTable(ctDocument.getBody().addNewTbl(), this, rows, cols);
- bodyElements.add(table);
- tables.add(table);
- return table;
+ XWPFTable table = new XWPFTable(ctDocument.getBody().addNewTbl(), this, rows, cols);
+ bodyElements.add(table);
+ tables.add(table);
+ return table;
}
/**
- *
+ *
*/
public void createTOC() {
CTSdtBlock block = this.getDocument().getBody().addNewSdt();
}
}
- /**Replace content of table in array tables at position pos with a
+ /**
+ * Replace content of table in array tables at position pos with a
+ *
* @param pos
* @param table
*/
* <w:settings ... >
* <w:documentProtection w:edit="readOnly" w:enforcement="1"/>
* </pre>
- *
+ *
* @return true if documentProtection is enforced with option readOnly
*/
public boolean isEnforcedReadonlyProtection() {
* <w:settings ... >
* <w:documentProtection w:edit="forms" w:enforcement="1"/>
* </pre>
- *
+ *
* @return true if documentProtection is enforced with option forms
*/
public boolean isEnforcedFillingFormsProtection() {
* <w:settings ... >
* <w:documentProtection w:edit="comments" w:enforcement="1"/>
* </pre>
- *
+ *
* @return true if documentProtection is enforced with option comments
*/
public boolean isEnforcedCommentsProtection() {
* <w:settings ... >
* <w:documentProtection w:edit="trackedChanges" w:enforcement="1"/>
* </pre>
- *
+ *
* @return true if documentProtection is enforced with option trackedChanges
*/
public boolean isEnforcedTrackedChangesProtection() {
* <br/>
* sample snippet from settings.xml
* <pre>
- * <w:documentProtection w:edit="readOnly" w:enforcement="1"
+ * <w:documentProtection w:edit="readOnly" w:enforcement="1"
* w:cryptProviderType="rsaAES" w:cryptAlgorithmClass="hash"
* w:cryptAlgorithmType="typeAny" w:cryptAlgorithmSid="14"
* w:cryptSpinCount="100000" w:hash="..." w:salt="...."
* />
* </pre>
- *
+ *
* @param password the plaintext password, if null no password will be applied
* @param hashAlgo the hash algorithm - only md2, m5, sha1, sha256, sha384 and sha512 are supported.
- * if null, it will default default to sha1
+ * if null, it will default default to sha1
*/
public void enforceReadonlyProtection(String password, HashAlgorithm hashAlgo) {
settings.setEnforcementEditValue(STDocProtect.READ_ONLY, password, hashAlgo);
}
-
+
/**
* Enforce the Filling Forms protection.<br/>
* In the documentProtection tag inside settings.xml file, <br/>
* <br/>
* sample snippet from settings.xml
* <pre>
- * <w:documentProtection w:edit="forms" w:enforcement="1"
+ * <w:documentProtection w:edit="forms" w:enforcement="1"
* w:cryptProviderType="rsaAES" w:cryptAlgorithmClass="hash"
* w:cryptAlgorithmType="typeAny" w:cryptAlgorithmSid="14"
* w:cryptSpinCount="100000" w:hash="..." w:salt="...."
* />
* </pre>
- *
+ *
* @param password the plaintext password, if null no password will be applied
* @param hashAlgo the hash algorithm - only md2, m5, sha1, sha256, sha384 and sha512 are supported.
- * if null, it will default default to sha1
+ * if null, it will default default to sha1
*/
public void enforceFillingFormsProtection(String password, HashAlgorithm hashAlgo) {
settings.setEnforcementEditValue(STDocProtect.FORMS, password, hashAlgo);
}
-
+
/**
* Enforce the Comments protection.<br/>
* In the documentProtection tag inside settings.xml file,<br/>
* <br/>
* sample snippet from settings.xml
* <pre>
- * <w:documentProtection w:edit="comments" w:enforcement="1"
+ * <w:documentProtection w:edit="comments" w:enforcement="1"
* w:cryptProviderType="rsaAES" w:cryptAlgorithmClass="hash"
* w:cryptAlgorithmType="typeAny" w:cryptAlgorithmSid="14"
* w:cryptSpinCount="100000" w:hash="..." w:salt="...."
* />
* </pre>
- *
+ *
* @param password the plaintext password, if null no password will be applied
* @param hashAlgo the hash algorithm - only md2, m5, sha1, sha256, sha384 and sha512 are supported.
- * if null, it will default default to sha1
+ * if null, it will default default to sha1
*/
public void enforceCommentsProtection(String password, HashAlgorithm hashAlgo) {
settings.setEnforcementEditValue(STDocProtect.COMMENTS, password, hashAlgo);
}
-
+
/**
* Enforce the Tracked Changes protection.<br/>
* In the documentProtection tag inside settings.xml file, <br/>
* <br/>
* sample snippet from settings.xml
* <pre>
- * <w:documentProtection w:edit="trackedChanges" w:enforcement="1"
+ * <w:documentProtection w:edit="trackedChanges" w:enforcement="1"
* w:cryptProviderType="rsaAES" w:cryptAlgorithmClass="hash"
* w:cryptAlgorithmType="typeAny" w:cryptAlgorithmSid="14"
* w:cryptSpinCount="100000" w:hash="..." w:salt="...."
* />
* </pre>
- *
+ *
* @param password the plaintext password, if null no password will be applied
* @param hashAlgo the hash algorithm - only md2, m5, sha1, sha256, sha384 and sha512 are supported.
- * if null, it will default default to sha1
+ * if null, it will default default to sha1
*/
public void enforceTrackedChangesProtection(String password, HashAlgorithm hashAlgo) {
settings.setEnforcementEditValue(STDocProtect.TRACKED_CHANGES, password, hashAlgo);
public boolean validateProtectionPassword(String password) {
return settings.validateProtectionPassword(password);
}
-
+
/**
* Remove protection enforcement.<br/>
* In the documentProtection tag inside settings.xml file <br/>
* Enforces fields update on document open (in Word).
* In the settings.xml file <br/>
* sets the updateSettings value to true (w:updateSettings w:val="true")
- *
- * NOTICES:
- * <ul>
- * <li>Causing Word to ask on open: "This document contains fields that may refer to other files. Do you want to update the fields in this document?"
- * (if "Update automatic links at open" is enabled)</li>
- * <li>Flag is removed after saving with changes in Word </li>
- * </ul>
+ * <p/>
+ * NOTICES:
+ * <ul>
+ * <li>Causing Word to ask on open: "This document contains fields that may refer to other files. Do you want to update the fields in this document?"
+ * (if "Update automatic links at open" is enabled)</li>
+ * <li>Flag is removed after saving with changes in Word </li>
+ * </ul>
*/
public void enforceUpdateFields() {
settings.setUpdateFields();
}
-
- /**
- * Check if revision tracking is turned on.
- *
- * @return <code>true</code> if revision tracking is turned on
- */
- public boolean isTrackRevisions() {
- return settings.isTrackRevisions();
- }
-
- /**
- * Enable or disable revision tracking.
- *
- * @param enable <code>true</code> to turn on revision tracking, <code>false</code> to turn off revision tracking
- */
- public void setTrackRevisions(boolean enable) {
- settings.setTrackRevisions(enable);
- }
+
+ /**
+ * Check if revision tracking is turned on.
+ *
+ * @return <code>true</code> if revision tracking is turned on
+ */
+ public boolean isTrackRevisions() {
+ return settings.isTrackRevisions();
+ }
+
+ /**
+ * Enable or disable revision tracking.
+ *
+ * @param enable <code>true</code> to turn on revision tracking, <code>false</code> to turn off revision tracking
+ */
+ public void setTrackRevisions(boolean enable) {
+ settings.setTrackRevisions(enable);
+ }
/**
* inserts an existing XWPFTable to the arrays bodyElements and tables
+ *
* @param pos
* @param table
*/
/**
* Returns all Pictures, which are referenced from the document itself.
+ *
* @return a {@link List} of {@link XWPFPictureData}. The returned {@link List} is unmodifiable. Use #a
*/
public List<XWPFPictureData> getAllPictures() {
list = new ArrayList<XWPFPictureData>(1);
packagePictures.put(picData.getChecksum(), list);
}
- if (!list.contains(picData))
- {
+ if (!list.contains(picData)) {
list.add(picData);
}
}
-
- XWPFPictureData findPackagePictureData(byte[] pictureData, int format)
- {
+
+ XWPFPictureData findPackagePictureData(byte[] pictureData, int format) {
long checksum = IOUtils.calculateChecksum(pictureData);
XWPFPictureData xwpfPicData = null;
/*
xwpfPicData = curElem;
}
}
- }
+ }
return xwpfPicData;
}
- public String addPictureData(byte[] pictureData,int format) throws InvalidFormatException
- {
+ public String addPictureData(byte[] pictureData, int format) throws InvalidFormatException {
XWPFPictureData xwpfPicData = findPackagePictureData(pictureData, format);
POIXMLRelation relDesc = XWPFPictureData.RELATIONS[format];
-
- if (xwpfPicData == null)
- {
+
+ if (xwpfPicData == null) {
/* Part doesn't exist, create a new one */
int idx = getNextPicNameNumber(format);
- xwpfPicData = (XWPFPictureData) createRelationship(relDesc, XWPFFactory.getInstance(),idx);
+ xwpfPicData = (XWPFPictureData) createRelationship(relDesc, XWPFFactory.getInstance(), idx);
/* write bytes to new part */
PackagePart picDataPart = xwpfPicData.getPackagePart();
OutputStream out = null;
registerPackagePictureData(xwpfPicData);
pictures.add(xwpfPicData);
-
+
return getRelationId(xwpfPicData);
- }
- else if (!getRelations().contains(xwpfPicData))
- {
+ } else if (!getRelations().contains(xwpfPicData)) {
/*
* Part already existed, but was not related so far. Create
* relationship to the already existing part and update
TargetMode targetMode = TargetMode.INTERNAL;
PackagePartName partName = picDataPart.getPartName();
String relation = relDesc.getRelation();
- PackageRelationship relShip = getPackagePart().addRelationship(partName,targetMode,relation);
+ PackageRelationship relShip = getPackagePart().addRelationship(partName, targetMode, relation);
String id = relShip.getId();
- addRelation(id,xwpfPicData);
+ addRelation(id, xwpfPicData);
pictures.add(xwpfPicData);
return id;
- }
- else
- {
+ } else {
/* Part already existed, get relation id and return it */
return getRelationId(xwpfPicData);
}
}
-
- public String addPictureData(InputStream is,int format) throws InvalidFormatException
- {
+
+ public String addPictureData(InputStream is, int format) throws InvalidFormatException {
try {
byte[] data = IOUtils.toByteArray(is);
return addPictureData(data, format);
/**
* get the next free ImageNumber
+ *
* @param format
* @return the next free ImageNumber
- * @throws InvalidFormatException
+ * @throws InvalidFormatException
*/
public int getNextPicNameNumber(int format) throws InvalidFormatException {
int img = getAllPackagePictures().size() + 1;
/**
* returns the PictureData by blipID
+ *
* @param blipID
* @return XWPFPictureData of a specificID
*/
/**
* getNumbering
+ *
* @return numbering
*/
public XWPFNumbering getNumbering() {
/**
* get Styles
+ *
* @return styles for this document
*/
public XWPFStyles getStyles() {
/**
* get the paragraph with the CTP class p
- *
+ *
* @param p
* @return the paragraph with the CTP class p
*/
/**
* get a table by its CTTbl-Object
+ *
* @param ctTbl
- * @see org.apache.poi.xwpf.usermodel.IBody#getTable(org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTbl)
* @return a table by its CTTbl-Object or null
+ * @see org.apache.poi.xwpf.usermodel.IBody#getTable(org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTbl)
*/
@Override
public XWPFTable getTable(CTTbl ctTbl) {
/**
* Returns the paragraph that of position pos
+ *
* @see org.apache.poi.xwpf.usermodel.IBody#getParagraphArray(int)
*/
@Override
* returns the Part, to which the body belongs, which you need for adding relationship to other parts
* Actually it is needed of the class XWPFTableCell. Because you have to know to which part the tableCell
* belongs.
+ *
* @see org.apache.poi.xwpf.usermodel.IBody#getPart()
*/
@Override
/**
* get the TableCell which belongs to the TableCell
+ *
* @param cell
*/
@Override
XmlCursor cursor = cell.newCursor();
cursor.toParent();
XmlObject o = cursor.getObject();
- if(!(o instanceof CTRow)){
+ if (!(o instanceof CTRow)) {
return null;
}
- CTRow row = (CTRow)o;
+ CTRow row = (CTRow) o;
cursor.toParent();
o = cursor.getObject();
cursor.dispose();
- if(! (o instanceof CTTbl)){
+ if (!(o instanceof CTTbl)) {
return null;
}
CTTbl tbl = (CTTbl) o;
XWPFTable table = getTable(tbl);
- if(table == null){
+ if (table == null) {
return null;
}
XWPFTableRow tableRow = table.getRow(row);
import org.apache.poi.util.POILogFactory;
import org.apache.poi.util.POILogger;
-/**
- * @author Yegor Kozlov
- */
-public final class XWPFFactory extends POIXMLFactory {
-
- private static final POILogger logger = POILogFactory.getLogger(XWPFFactory.class);
-
- private XWPFFactory(){
-
- }
-
- private static final XWPFFactory inst = new XWPFFactory();
-
- public static XWPFFactory getInstance(){
- return inst;
- }
-
- @Override
- public POIXMLDocumentPart createDocumentPart(POIXMLDocumentPart parent, PackageRelationship rel, PackagePart part){
- POIXMLRelation descriptor = XWPFRelation.getInstance(rel.getRelationshipType());
- if(descriptor == null || descriptor.getRelationClass() == null){
- logger.log(POILogger.DEBUG, "using default POIXMLDocumentPart for " + rel.getRelationshipType());
- return new POIXMLDocumentPart(part, rel);
- }
+/**\r
+ * @author Yegor Kozlov\r
+ */\r
+public final class XWPFFactory extends POIXMLFactory {\r
+\r
+ private static final POILogger logger = POILogFactory.getLogger(XWPFFactory.class);\r
+ private static final XWPFFactory inst = new XWPFFactory();\r
+\r
+ private XWPFFactory() {\r
+\r
+ }\r
+\r
+ public static XWPFFactory getInstance() {\r
+ return inst;\r
+ }\r
+\r
+ @Override\r
+ public POIXMLDocumentPart createDocumentPart(POIXMLDocumentPart parent, PackageRelationship rel, PackagePart part) {\r
+ POIXMLRelation descriptor = XWPFRelation.getInstance(rel.getRelationshipType());\r
+ if (descriptor == null || descriptor.getRelationClass() == null) {\r
+ logger.log(POILogger.DEBUG, "using default POIXMLDocumentPart for " + rel.getRelationshipType());\r
+ return new POIXMLDocumentPart(part, rel);\r
+ }\r
try {
Class<? extends POIXMLDocumentPart> cls = descriptor.getRelationClass();
Constructor<? extends POIXMLDocumentPart> constructor = cls.getDeclaredConstructor(POIXMLDocumentPart.class, PackagePart.class, PackageRelationship.class);
return constructor.newInstance(parent, part, rel);
} catch (NoSuchMethodException e) {
- Constructor<? extends POIXMLDocumentPart> constructor = cls.getDeclaredConstructor(PackagePart.class, PackageRelationship.class);
- return constructor.newInstance(part, rel);
- }
- } catch (Exception e){
- throw new POIXMLException(e);
- }
- }
-
- @Override
- public POIXMLDocumentPart newDocumentPart(POIXMLRelation descriptor){
- try {
- Class<? extends POIXMLDocumentPart> cls = descriptor.getRelationClass();
- Constructor<? extends POIXMLDocumentPart> constructor = cls.getDeclaredConstructor();
- return constructor.newInstance();
- } catch (Exception e){
- throw new POIXMLException(e);
- }
- }
+ Constructor<? extends POIXMLDocumentPart> constructor = cls.getDeclaredConstructor(PackagePart.class, PackageRelationship.class);\r
+ return constructor.newInstance(part, rel);\r
+ }\r
+ } catch (Exception e) {\r
+ throw new POIXMLException(e);\r
+ }\r
+ }\r
+\r
+ @Override\r
+ public POIXMLDocumentPart newDocumentPart(POIXMLRelation descriptor) {\r
+ try {\r
+ Class<? extends POIXMLDocumentPart> cls = descriptor.getRelationClass();\r
+ Constructor<? extends POIXMLDocumentPart> constructor = cls.getDeclaredConstructor();\r
+ return constructor.newInstance();\r
+ } catch (Exception e) {\r
+ throw new POIXMLException(e);\r
+ }\r
+ }\r
}
while (cursor.toNextSelection()) {
XmlObject o = cursor.getObject();
if (o instanceof CTP) {
- XWPFParagraph p = new XWPFParagraph((CTP)o, this);
+ XWPFParagraph p = new XWPFParagraph((CTP) o, this);
paragraphs.add(p);
bodyElements.add(p);
}
if (o instanceof CTTbl) {
- XWPFTable t = new XWPFTable((CTTbl)o, this);
+ XWPFTable t = new XWPFTable((CTTbl) o, this);
tables.add(t);
bodyElements.add(t);
}
-
+
}
cursor.dispose();
}
protected void commit() throws IOException {
XmlOptions xmlOptions = new XmlOptions(DEFAULT_XML_OPTIONS);
xmlOptions.setSaveSyntheticDocumentElement(new QName(CTNumbering.type.getName().getNamespaceURI(), "ftr"));
- Map<String,String> map = new HashMap<String, String>();
+ Map<String, String> map = new HashMap<String, String>();
map.put("http://schemas.openxmlformats.org/markup-compatibility/2006", "ve");
map.put("urn:schemas-microsoft-com:office:office", "o");
map.put("http://schemas.openxmlformats.org/officeDocument/2006/relationships", "r");
out.close();
}
- @Override
- protected void onDocumentRead() throws IOException{
+ @Override
+ protected void onDocumentRead() throws IOException {
super.onDocumentRead();
FtrDocument ftrDocument = null;
InputStream is;
while (cursor.toNextSelection()) {
XmlObject o = cursor.getObject();
if (o instanceof CTP) {
- XWPFParagraph p = new XWPFParagraph((CTP)o, this);
+ XWPFParagraph p = new XWPFParagraph((CTP) o, this);
paragraphs.add(p);
bodyElements.add(p);
}
if (o instanceof CTTbl) {
- XWPFTable t = new XWPFTable((CTTbl)o, this);
+ XWPFTable t = new XWPFTable((CTTbl) o, this);
tables.add(t);
bodyElements.add(t);
}
- if (o instanceof CTSdtBlock){
- XWPFSDT c = new XWPFSDT((CTSdtBlock)o, this);
- bodyElements.add(c);
- }
+ if (o instanceof CTSdtBlock) {
+ XWPFSDT c = new XWPFSDT((CTSdtBlock) o, this);
+ bodyElements.add(c);
+ }
}
cursor.dispose();
} catch (Exception e) {
/**
* get the PartType of the body
+ *
* @see org.apache.poi.xwpf.usermodel.IBody#getPartType()
*/
public BodyType getPartType() {
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTP;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTRow;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTSdtBlock;
-import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTbl;
-import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTc;
-
-public class XWPFFootnote implements Iterable<XWPFParagraph>,IBody {
- private List<XWPFParagraph> paragraphs = new ArrayList<XWPFParagraph>();
- private List<XWPFTable> tables= new ArrayList<XWPFTable>();
- private List<XWPFPictureData> pictures = new ArrayList<XWPFPictureData>();
- private List<IBodyElement> bodyElements = new ArrayList<IBodyElement>();
-
+import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTbl;\r
+import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTc;\r
+\r
+public class XWPFFootnote implements Iterable<XWPFParagraph>, IBody {\r
+ private List<XWPFParagraph> paragraphs = new ArrayList<XWPFParagraph>();\r
+ private List<XWPFTable> tables = new ArrayList<XWPFTable>();\r
+ private List<XWPFPictureData> pictures = new ArrayList<XWPFPictureData>();\r
+ private List<IBodyElement> bodyElements = new ArrayList<IBodyElement>();\r
+\r
private CTFtnEdn ctFtnEdn;
private XWPFFootnotes footnotes;
- private XWPFDocument document;
-
- public XWPFFootnote(CTFtnEdn note, XWPFFootnotes xFootnotes) {
- footnotes = xFootnotes;
- ctFtnEdn = note;
- document = xFootnotes.getXWPFDocument();
- init();
- }
-
- public XWPFFootnote(XWPFDocument document, CTFtnEdn body) {
- ctFtnEdn = body;
- this.document = document;
- init();
- }
-
- private void init(){
- XmlCursor cursor = ctFtnEdn.newCursor();
- //copied from XWPFDocument...should centralize this code
- //to avoid duplication
- cursor.selectPath("./*");
- while (cursor.toNextSelection()) {
- XmlObject o = cursor.getObject();
- if (o instanceof CTP) {
- XWPFParagraph p = new XWPFParagraph((CTP) o, this);
- bodyElements.add(p);
- paragraphs.add(p);
- } else if (o instanceof CTTbl) {
- XWPFTable t = new XWPFTable((CTTbl) o, this);
- bodyElements.add(t);
- tables.add(t);
- } else if (o instanceof CTSdtBlock){
- XWPFSDT c = new XWPFSDT((CTSdtBlock)o, this);
- bodyElements.add(c);
- }
-
- }
- cursor.dispose();
- }
-
- public List<XWPFParagraph> getParagraphs() {
- return paragraphs;
- }
-
- public Iterator<XWPFParagraph> iterator(){
- return paragraphs.iterator();
- }
-
+ private XWPFDocument document;\r
+\r
+ public XWPFFootnote(CTFtnEdn note, XWPFFootnotes xFootnotes) {\r
+ footnotes = xFootnotes;\r
+ ctFtnEdn = note;\r
+ document = xFootnotes.getXWPFDocument();\r
+ init();\r
+ }\r
+\r
+ public XWPFFootnote(XWPFDocument document, CTFtnEdn body) {\r
+ ctFtnEdn = body;\r
+ this.document = document;\r
+ init();\r
+ }\r
+\r
+ private void init() {\r
+ XmlCursor cursor = ctFtnEdn.newCursor();\r
+ //copied from XWPFDocument...should centralize this code\r
+ //to avoid duplication\r
+ cursor.selectPath("./*");\r
+ while (cursor.toNextSelection()) {\r
+ XmlObject o = cursor.getObject();\r
+ if (o instanceof CTP) {\r
+ XWPFParagraph p = new XWPFParagraph((CTP) o, this);\r
+ bodyElements.add(p);\r
+ paragraphs.add(p);\r
+ } else if (o instanceof CTTbl) {\r
+ XWPFTable t = new XWPFTable((CTTbl) o, this);\r
+ bodyElements.add(t);\r
+ tables.add(t);\r
+ } else if (o instanceof CTSdtBlock) {\r
+ XWPFSDT c = new XWPFSDT((CTSdtBlock) o, this);\r
+ bodyElements.add(c);\r
+ }\r
+\r
+ }\r
+ cursor.dispose();\r
+ }\r
+\r
+ public List<XWPFParagraph> getParagraphs() {\r
+ return paragraphs;\r
+ }\r
+\r
+ public Iterator<XWPFParagraph> iterator() {\r
+ return paragraphs.iterator();\r
+ }\r
+\r
public List<XWPFTable> getTables() {
return tables;
}
public List<IBodyElement> getBodyElements() {
return bodyElements;
- }
-
- public CTFtnEdn getCTFtnEdn() {
- return ctFtnEdn;
- }
-
- public void setCTFtnEdn(CTFtnEdn footnote) {
- ctFtnEdn = footnote;
- }
-
- /**
+ }\r
+\r
+ public CTFtnEdn getCTFtnEdn() {\r
+ return ctFtnEdn;\r
+ }\r
+\r
+ public void setCTFtnEdn(CTFtnEdn footnote) {\r
+ ctFtnEdn = footnote;\r
+ }\r
+\r
+ /**\r
* @param pos in table array
* @return The table at position pos
- * @see org.apache.poi.xwpf.usermodel.IBody#getTableArray(int)
- */
- public XWPFTable getTableArray(int pos) {
- if(pos > 0 && pos < tables.size()){
- return tables.get(pos);
- }
- return null;
+ * @see org.apache.poi.xwpf.usermodel.IBody#getTableArray(int)\r
+ */\r
+ public XWPFTable getTableArray(int pos) {\r
+ if (pos > 0 && pos < tables.size()) {\r
+ return tables.get(pos);\r
+ }\r
+ return null;\r
}
-
- /**
- * inserts an existing XWPFTable to the arrays bodyElements and tables
- * @param pos
- * @param table
- * @see org.apache.poi.xwpf.usermodel.IBody#insertTable(int pos, XWPFTable table)
+\r
+ /**\r
+ * inserts an existing XWPFTable to the arrays bodyElements and tables\r
+ *\r
+ * @param pos\r
+ * @param table\r
+ * @see org.apache.poi.xwpf.usermodel.IBody#insertTable(int pos, XWPFTable table)\r
*/
@SuppressWarnings("deprecation")
public void insertTable(int pos, XWPFTable table) {
- bodyElements.add(pos, table);
- int i = 0;
- for (CTTbl tbl : ctFtnEdn.getTblArray()) {
- if(tbl == table.getCTTbl()){
- break;
- }
- i++;
+ bodyElements.add(pos, table);\r
+ int i = 0;\r
+ for (CTTbl tbl : ctFtnEdn.getTblArray()) {\r
+ if (tbl == table.getCTTbl()) {\r
+ break;\r
+ }\r
+ i++;\r
}
tables.add(i, table);
}
- /**
- * if there is a corresponding {@link XWPFTable} of the parameter ctTable in the tableList of this header
- * the method will return this table
- * if there is no corresponding {@link XWPFTable} the method will return null
- * @param ctTable
- * @see org.apache.poi.xwpf.usermodel.IBody#getTable(CTTbl ctTable)
- */
- public XWPFTable getTable(CTTbl ctTable){
- for (XWPFTable table : tables) {
- if(table==null)
- return null;
- if(table.getCTTbl().equals(ctTable))
- return table;
- }
- return null;
+ /**\r
+ * if there is a corresponding {@link XWPFTable} of the parameter ctTable in the tableList of this header\r
+ * the method will return this table\r
+ * if there is no corresponding {@link XWPFTable} the method will return null\r
+ *\r
+ * @param ctTable\r
+ * @see org.apache.poi.xwpf.usermodel.IBody#getTable(CTTbl ctTable)\r
+ */\r
+ public XWPFTable getTable(CTTbl ctTable) {\r
+ for (XWPFTable table : tables) {\r
+ if (table == null)\r
+ return null;\r
+ if (table.getCTTbl().equals(ctTable))\r
+ return table;\r
+ }\r
+ return null;\r
}
- /**
- * if there is a corresponding {@link XWPFParagraph} of the parameter ctTable in the paragraphList of this header or footer
- * the method will return this paragraph
- * if there is no corresponding {@link XWPFParagraph} the method will return null
- * @param p is instance of CTP and is searching for an XWPFParagraph
- * @return null if there is no XWPFParagraph with an corresponding CTPparagraph in the paragraphList of this header or footer
- * XWPFParagraph with the correspondig CTP p
- * @see org.apache.poi.xwpf.usermodel.IBody#getParagraph(CTP p)
- */
- public XWPFParagraph getParagraph(CTP p){
- for (XWPFParagraph paragraph : paragraphs) {
- if(paragraph.getCTP().equals(p))
- return paragraph;
- }
- return null;
+ /**\r
+ * if there is a corresponding {@link XWPFParagraph} of the parameter ctTable in the paragraphList of this header or footer\r
+ * the method will return this paragraph\r
+ * if there is no corresponding {@link XWPFParagraph} the method will return null\r
+ *\r
+ * @param p is instance of CTP and is searching for an XWPFParagraph\r
+ * @return null if there is no XWPFParagraph with an corresponding CTPparagraph in the paragraphList of this header or footer\r
+ * XWPFParagraph with the correspondig CTP p\r
+ * @see org.apache.poi.xwpf.usermodel.IBody#getParagraph(CTP p)\r
+ */\r
+ public XWPFParagraph getParagraph(CTP p) {\r
+ for (XWPFParagraph paragraph : paragraphs) {\r
+ if (paragraph.getCTP().equals(p))\r
+ return paragraph;\r
+ }\r
+ return null;\r
}
-
- /**
- * Returns the paragraph that holds
- * the text of the header or footer.
- * @see org.apache.poi.xwpf.usermodel.IBody#getParagraphArray(int pos)
- */
- public XWPFParagraph getParagraphArray(int pos) {
+\r
+ /**\r
+ * Returns the paragraph that holds\r
+ * the text of the header or footer.\r
+ *\r
+ * @see org.apache.poi.xwpf.usermodel.IBody#getParagraphArray(int pos)\r
+ */\r
+ public XWPFParagraph getParagraphArray(int pos) {\r
return paragraphs.get(pos);
}
-
- /**
- * get the TableCell which belongs to the TableCell
- * @param cell
- * @see org.apache.poi.xwpf.usermodel.IBody#getTableCell(CTTc cell)
- */
+\r
+ /**\r
+ * get the TableCell which belongs to the TableCell\r
+ *\r
+ * @param cell\r
+ * @see org.apache.poi.xwpf.usermodel.IBody#getTableCell(CTTc cell)\r
+ */\r
public XWPFTableCell getTableCell(CTTc cell) {
- XmlCursor cursor = cell.newCursor();
- cursor.toParent();
- XmlObject o = cursor.getObject();
- if(!(o instanceof CTRow)){
- return null;
- }
- CTRow row = (CTRow)o;
- cursor.toParent();
- o = cursor.getObject();
- cursor.dispose();
- if(! (o instanceof CTTbl)){
- return null;
- }
- CTTbl tbl = (CTTbl) o;
- XWPFTable table = getTable(tbl);
- if(table == null){
- return null;
- }
- XWPFTableRow tableRow = table.getRow(row);
- if(row == null){
- return null;
- }
- return tableRow.getTableCell(cell);
+ XmlCursor cursor = cell.newCursor();\r
+ cursor.toParent();\r
+ XmlObject o = cursor.getObject();\r
+ if (!(o instanceof CTRow)) {\r
+ return null;\r
+ }\r
+ CTRow row = (CTRow) o;\r
+ cursor.toParent();\r
+ o = cursor.getObject();\r
+ cursor.dispose();\r
+ if (!(o instanceof CTTbl)) {\r
+ return null;\r
+ }\r
+ CTTbl tbl = (CTTbl) o;\r
+ XWPFTable table = getTable(tbl);\r
+ if (table == null) {\r
+ return null;\r
+ }\r
+ XWPFTableRow tableRow = table.getRow(row);\r
+ if (row == null) {\r
+ return null;\r
+ }\r
+ return tableRow.getTableCell(cell);\r
}
-
- /**
- * verifies that cursor is on the right position
- * @param cursor
- */
- private boolean isCursorInFtn(XmlCursor cursor) {
- XmlCursor verify = cursor.newCursor();
- verify.toParent();
- if(verify.getObject() == this.ctFtnEdn){
- return true;
- }
- return false;
- }
-
- public POIXMLDocumentPart getOwner(){
- return footnotes;
- }
-
- /**
- *
- * @param cursor
- * @return the inserted table
- * @see org.apache.poi.xwpf.usermodel.IBody#insertNewTbl(XmlCursor cursor)
- */
- public XWPFTable insertNewTbl(XmlCursor cursor) {
- if(isCursorInFtn(cursor)){
- String uri = CTTbl.type.getName().getNamespaceURI();
- String localPart = "tbl";
- cursor.beginElement(localPart,uri);
- cursor.toParent();
- CTTbl t = (CTTbl)cursor.getObject();
- XWPFTable newT = new XWPFTable(t, this);
- cursor.removeXmlContents();
- XmlObject o = null;
- while(!(o instanceof CTTbl)&&(cursor.toPrevSibling())){
- o = cursor.getObject();
- }
- if(!(o instanceof CTTbl)){
- tables.add(0, newT);
- }
- else{
- int pos = tables.indexOf(getTable((CTTbl)o))+1;
- tables.add(pos,newT);
- }
- int i=0;
- cursor = t.newCursor();
- while(cursor.toPrevSibling()){
- o =cursor.getObject();
- if(o instanceof CTP || o instanceof CTTbl)
- i++;
- }
- bodyElements.add(i, newT);
+\r
+ /**\r
+ * verifies that cursor is on the right position\r
+ *\r
+ * @param cursor\r
+ */\r
+ private boolean isCursorInFtn(XmlCursor cursor) {\r
+ XmlCursor verify = cursor.newCursor();\r
+ verify.toParent();\r
+ if (verify.getObject() == this.ctFtnEdn) {\r
+ return true;\r
+ }\r
+ return false;\r
+ }\r
+\r
+ public POIXMLDocumentPart getOwner() {\r
+ return footnotes;\r
+ }\r
+\r
+ /**\r
+ * @param cursor\r
+ * @return the inserted table\r
+ * @see org.apache.poi.xwpf.usermodel.IBody#insertNewTbl(XmlCursor cursor)\r
+ */\r
+ public XWPFTable insertNewTbl(XmlCursor cursor) {\r
+ if (isCursorInFtn(cursor)) {\r
+ String uri = CTTbl.type.getName().getNamespaceURI();\r
+ String localPart = "tbl";\r
+ cursor.beginElement(localPart, uri);\r
+ cursor.toParent();\r
+ CTTbl t = (CTTbl) cursor.getObject();\r
+ XWPFTable newT = new XWPFTable(t, this);\r
+ cursor.removeXmlContents();\r
+ XmlObject o = null;\r
+ while (!(o instanceof CTTbl) && (cursor.toPrevSibling())) {\r
+ o = cursor.getObject();\r
+ }\r
+ if (!(o instanceof CTTbl)) {\r
+ tables.add(0, newT);\r
+ } else {\r
+ int pos = tables.indexOf(getTable((CTTbl) o)) + 1;\r
+ tables.add(pos, newT);\r
+ }\r
+ int i = 0;\r
+ cursor = t.newCursor();\r
+ while (cursor.toPrevSibling()) {\r
+ o = cursor.getObject();\r
+ if (o instanceof CTP || o instanceof CTTbl)\r
+ i++;\r
+ }\r
+ bodyElements.add(i, newT);\r
cursor = t.newCursor();
cursor.toEndToken();
return newT;
}
return null;
}
-
- /**
- * add a new paragraph at position of the cursor
- * @param cursor
- * @return the inserted paragraph
- * @see org.apache.poi.xwpf.usermodel.IBody#insertNewParagraph(XmlCursor cursor)
- */
- public XWPFParagraph insertNewParagraph(XmlCursor cursor){
- if(isCursorInFtn(cursor)){
- String uri = CTP.type.getName().getNamespaceURI();
- String localPart = "p";
- cursor.beginElement(localPart,uri);
- cursor.toParent();
- CTP p = (CTP)cursor.getObject();
- XWPFParagraph newP = new XWPFParagraph(p, this);
- XmlObject o = null;
- while(!(o instanceof CTP)&&(cursor.toPrevSibling())){
- o = cursor.getObject();
- }
- if((!(o instanceof CTP)) || (CTP)o == p){
- paragraphs.add(0, newP);
- }
- else{
- int pos = paragraphs.indexOf(getParagraph((CTP)o))+1;
- paragraphs.add(pos,newP);
- }
- int i=0;
- cursor.toCursor(p.newCursor());
- while(cursor.toPrevSibling()){
- o =cursor.getObject();
- if(o instanceof CTP || o instanceof CTTbl)
- i++;
- }
- bodyElements.add(i, newP);
+\r
+ /**\r
+ * add a new paragraph at position of the cursor\r
+ *\r
+ * @param cursor\r
+ * @return the inserted paragraph\r
+ * @see org.apache.poi.xwpf.usermodel.IBody#insertNewParagraph(XmlCursor cursor)\r
+ */\r
+ public XWPFParagraph insertNewParagraph(XmlCursor cursor) {\r
+ if (isCursorInFtn(cursor)) {\r
+ String uri = CTP.type.getName().getNamespaceURI();\r
+ String localPart = "p";\r
+ cursor.beginElement(localPart, uri);\r
+ cursor.toParent();\r
+ CTP p = (CTP) cursor.getObject();\r
+ XWPFParagraph newP = new XWPFParagraph(p, this);\r
+ XmlObject o = null;\r
+ while (!(o instanceof CTP) && (cursor.toPrevSibling())) {\r
+ o = cursor.getObject();\r
+ }\r
+ if ((!(o instanceof CTP)) || (CTP) o == p) {\r
+ paragraphs.add(0, newP);\r
+ } else {\r
+ int pos = paragraphs.indexOf(getParagraph((CTP) o)) + 1;\r
+ paragraphs.add(pos, newP);\r
+ }\r
+ int i = 0;\r
+ cursor.toCursor(p.newCursor());\r
+ while (cursor.toPrevSibling()) {\r
+ o = cursor.getObject();\r
+ if (o instanceof CTP || o instanceof CTTbl)\r
+ i++;\r
+ }\r
+ bodyElements.add(i, newP);\r
cursor.toCursor(p.newCursor());
cursor.toEndToken();
return newP;
}
return null;
}
-
- /**
- * add a new table to the end of the footnote
- * @param table
- * @return the added XWPFTable
- */
+\r
+ /**\r
+ * add a new table to the end of the footnote\r
+ *\r
+ * @param table\r
+ * @return the added XWPFTable\r
+ */\r
public XWPFTable addNewTbl(CTTbl table) {
CTTbl newTable = ctFtnEdn.addNewTbl();
newTable.set(table);
tables.add(xTable);
return xTable;
}
-
- /**
- * add a new paragraph to the end of the footnote
- * @param paragraph
- * @return the added XWPFParagraph
- */
+\r
+ /**\r
+ * add a new paragraph to the end of the footnote\r
+ *\r
+ * @param paragraph\r
+ * @return the added XWPFParagraph\r
+ */\r
public XWPFParagraph addNewParagraph(CTP paragraph) {
CTP newPara = ctFtnEdn.addNewP();
newPara.set(paragraph);
return xPara;
}
- /**
- * @see org.apache.poi.xwpf.usermodel.IBody#getXWPFDocument()
- */
- public XWPFDocument getXWPFDocument() {
- return document;
- }
-
- /**
- * returns the Part, to which the body belongs, which you need for adding relationship to other parts
- * @see org.apache.poi.xwpf.usermodel.IBody#getPart()
- */
- public POIXMLDocumentPart getPart() {
+ /**\r
+ * @see org.apache.poi.xwpf.usermodel.IBody#getXWPFDocument()\r
+ */\r
+ public XWPFDocument getXWPFDocument() {\r
+ return document;\r
+ }\r
+\r
+ /**\r
+ * returns the Part, to which the body belongs, which you need for adding relationship to other parts\r
+ *\r
+ * @see org.apache.poi.xwpf.usermodel.IBody#getPart()\r
+ */\r
+ public POIXMLDocumentPart getPart() {\r
return footnotes;
}
-
- /**
- * get the PartType of the body
- * @see org.apache.poi.xwpf.usermodel.IBody#getPartType()
- */
- public BodyType getPartType() {
+\r
+ /**\r
+ * get the PartType of the body\r
+ *\r
+ * @see org.apache.poi.xwpf.usermodel.IBody#getPartType()\r
+ */\r
+ public BodyType getPartType() {\r
return BodyType.FOOTNOTE;
}
}
import org.apache.poi.POIXMLException;
import org.apache.poi.openxml4j.exceptions.OpenXML4JException;
import org.apache.poi.openxml4j.opc.PackagePart;
-import org.apache.poi.openxml4j.opc.PackageRelationship;
-import org.apache.xmlbeans.XmlException;
-import org.apache.xmlbeans.XmlOptions;
-import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTFtnEdn;
-import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTFootnotes;
-import org.openxmlformats.schemas.wordprocessingml.x2006.main.FootnotesDocument;
-
-/**
- * Looks after the collection of Footnotes for a document
- */
-public class XWPFFootnotes extends POIXMLDocumentPart {
- private List<XWPFFootnote> listFootnote = new ArrayList<XWPFFootnote>();
- private CTFootnotes ctFootnotes;
-
- protected XWPFDocument document;
-
- /**
- * Construct XWPFFootnotes from a package part
- *
- * @param part the package part holding the data of the footnotes,
- * @param rel the package relationship of type "http://schemas.openxmlformats.org/officeDocument/2006/relationships/footnotes"
- */
- public XWPFFootnotes(PackagePart part, PackageRelationship rel) throws IOException, OpenXML4JException{
- super(part, rel);
- }
-
+import org.apache.poi.openxml4j.opc.PackageRelationship;\r
+import org.apache.xmlbeans.XmlException;\r
+import org.apache.xmlbeans.XmlOptions;\r
+import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTFootnotes;\r
+import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTFtnEdn;\r
+import org.openxmlformats.schemas.wordprocessingml.x2006.main.FootnotesDocument;\r
+\r
+/**\r
+ * Looks after the collection of Footnotes for a document\r
+ */\r
+public class XWPFFootnotes extends POIXMLDocumentPart {\r
+ protected XWPFDocument document;\r
+ private List<XWPFFootnote> listFootnote = new ArrayList<XWPFFootnote>();\r
+ private CTFootnotes ctFootnotes;\r
+\r
+ /**\r
+ * Construct XWPFFootnotes from a package part\r
+ *\r
+ * @param part the package part holding the data of the footnotes,\r
+ * @param rel the package relationship of type "http://schemas.openxmlformats.org/officeDocument/2006/relationships/footnotes"\r
+ */\r
+ public XWPFFootnotes(PackagePart part, PackageRelationship rel) throws IOException, OpenXML4JException {\r
+ super(part, rel);\r
+ }\r
+\r
/**
* Construct XWPFFootnotes from scratch for a new document.
*/
/**
* Read document
- */
- @Override
- @SuppressWarnings("deprecation")
- protected void onDocumentRead () throws IOException {
- FootnotesDocument notesDoc;
- try {
- InputStream is = getPackagePart().getInputStream();
+ */\r
+ @Override\r
+ @SuppressWarnings("deprecation")\r
+ protected void onDocumentRead() throws IOException {\r
+ FootnotesDocument notesDoc;\r
+ try {\r
+ InputStream is = getPackagePart().getInputStream();\r
notesDoc = FootnotesDocument.Factory.parse(is);
ctFootnotes = notesDoc.getFootnotes();
} catch (XmlException e) {
throw new POIXMLException();
- }
-
- // Find our footnotes
- for(CTFtnEdn note : ctFootnotes.getFootnoteArray()) {
- listFootnote.add(new XWPFFootnote(note, this));
- }
- }
+ }\r
+\r
+ // Find our footnotes\r
+ for (CTFtnEdn note : ctFootnotes.getFootnoteArray()) {\r
+ listFootnote.add(new XWPFFootnote(note, this));\r
+ }\r
+ }\r
@Override
- protected void commit() throws IOException {
- XmlOptions xmlOptions = new XmlOptions(DEFAULT_XML_OPTIONS);
- xmlOptions.setSaveSyntheticDocumentElement(new QName(CTFootnotes.type.getName().getNamespaceURI(), "footnotes"));
- Map<String,String> map = new HashMap<String,String>();
- map.put("http://schemas.openxmlformats.org/officeDocument/2006/relationships", "r");
- map.put("http://schemas.openxmlformats.org/wordprocessingml/2006/main", "w");
- xmlOptions.setSaveSuggestedPrefixes(map);
+ protected void commit() throws IOException {\r
+ XmlOptions xmlOptions = new XmlOptions(DEFAULT_XML_OPTIONS);\r
+ xmlOptions.setSaveSyntheticDocumentElement(new QName(CTFootnotes.type.getName().getNamespaceURI(), "footnotes"));\r
+ Map<String, String> map = new HashMap<String, String>();\r
+ map.put("http://schemas.openxmlformats.org/officeDocument/2006/relationships", "r");\r
+ map.put("http://schemas.openxmlformats.org/wordprocessingml/2006/main", "w");\r
+ xmlOptions.setSaveSuggestedPrefixes(map);\r
PackagePart part = getPackagePart();
OutputStream out = part.getOutputStream();
ctFootnotes.save(out, xmlOptions);
public List<XWPFFootnote> getFootnotesList() {
return listFootnote;
+ }\r
+\r
+ public XWPFFootnote getFootnoteById(int id) {\r
+ for (XWPFFootnote note : listFootnote) {\r
+ if (note.getCTFtnEdn().getId().intValue() == id)\r
+ return note;\r
+ }\r
+ return null;\r
}
-
- public XWPFFootnote getFootnoteById(int id) {
- for(XWPFFootnote note : listFootnote) {
- if(note.getCTFtnEdn().getId().intValue() == id)
- return note;
- }
- return null;
- }
-
- /**
- * Sets the ctFootnotes
- * @param footnotes
- */
- public void setFootnotes(CTFootnotes footnotes) {
+\r
+ /**\r
+ * Sets the ctFootnotes\r
+ *\r
+ * @param footnotes\r
+ */\r
+ public void setFootnotes(CTFootnotes footnotes) {\r
ctFootnotes = footnotes;
}
-
- /**
- * add an XWPFFootnote to the document
- * @param footnote
- * @throws IOException
- */
- public void addFootnote(XWPFFootnote footnote){
- listFootnote.add(footnote);
- ctFootnotes.addNewFootnote().set(footnote.getCTFtnEdn());
- }
-
- /**
- * add a footnote to the document
- * @param note
- * @throws IOException
- */
- public XWPFFootnote addFootnote(CTFtnEdn note){
- CTFtnEdn newNote = ctFootnotes.addNewFootnote();
- newNote.set(note);
- XWPFFootnote xNote = new XWPFFootnote(newNote, this);
+\r
+ /**\r
+ * add an XWPFFootnote to the document\r
+ *\r
+ * @param footnote\r
+ * @throws IOException\r
+ */\r
+ public void addFootnote(XWPFFootnote footnote) {\r
+ listFootnote.add(footnote);\r
+ ctFootnotes.addNewFootnote().set(footnote.getCTFtnEdn());\r
+ }\r
+\r
+ /**\r
+ * add a footnote to the document\r
+ *\r
+ * @param note\r
+ * @throws IOException\r
+ */\r
+ public XWPFFootnote addFootnote(CTFtnEdn note) {\r
+ CTFtnEdn newNote = ctFootnotes.addNewFootnote();\r
+ newNote.set(note);\r
+ XWPFFootnote xNote = new XWPFFootnote(newNote, this);\r
listFootnote.add(xNote);
- return xNote;
- }
-
- public void setXWPFDocument(XWPFDocument doc) {
- document = doc;
- }
-
- /**
- * @see org.apache.poi.xwpf.usermodel.IBody#getPart()
- */
- public XWPFDocument getXWPFDocument() {
- if ( document != null) {
- return document;
- } else {
- return (XWPFDocument)getParent();
- }
- }
-}
+ return xNote;\r
+ }\r
+\r
+ /**\r
+ * @see org.apache.poi.xwpf.usermodel.IBody#getPart()\r
+ */\r
+ public XWPFDocument getXWPFDocument() {\r
+ if (document != null) {\r
+ return document;\r
+ } else {\r
+ return (XWPFDocument) getParent();\r
+ }\r
+ }\r
+\r
+ public void setXWPFDocument(XWPFDocument doc) {\r
+ document = doc;\r
+ }\r
+}\r
cursor.dispose();
}
- /**
+ /**
* save and commit footer
*/
@Override
protected void commit() throws IOException {
XmlOptions xmlOptions = new XmlOptions(DEFAULT_XML_OPTIONS);
xmlOptions.setSaveSyntheticDocumentElement(new QName(CTNumbering.type.getName().getNamespaceURI(), "hdr"));
- Map<String,String> map = new HashMap<String, String>();
+ Map<String, String> map = new HashMap<String, String>();
map.put("http://schemas.openxmlformats.org/markup-compatibility/2006", "ve");
map.put("urn:schemas-microsoft-com:office:office", "o");
map.put("http://schemas.openxmlformats.org/officeDocument/2006/relationships", "r");
/**
* reads the document
- * @throws IOException
+ *
+ * @throws IOException
*/
- @Override
+ @Override
protected void onDocumentRead() throws IOException {
- super.onDocumentRead();
+ super.onDocumentRead();
HdrDocument hdrDocument = null;
InputStream is;
try {
while (cursor.toNextSelection()) {
XmlObject o = cursor.getObject();
if (o instanceof CTP) {
- XWPFParagraph p = new XWPFParagraph((CTP)o, this);
+ XWPFParagraph p = new XWPFParagraph((CTP) o, this);
paragraphs.add(p);
bodyElements.add(p);
}
if (o instanceof CTTbl) {
- XWPFTable t = new XWPFTable((CTTbl)o, this);
+ XWPFTable t = new XWPFTable((CTTbl) o, this);
tables.add(t);
bodyElements.add(t);
}
- if (o instanceof CTSdtBlock){
- XWPFSDT c = new XWPFSDT((CTSdtBlock)o, this);
+ if (o instanceof CTSdtBlock) {
+ XWPFSDT c = new XWPFSDT((CTSdtBlock) o, this);
bodyElements.add(c);
}
}
/**
* get the PartType of the body
+ *
* @see org.apache.poi.xwpf.usermodel.IBody#getPartType()
*/
public BodyType getPartType() {
*/
public abstract class XWPFHeaderFooter extends POIXMLDocumentPart implements IBody {
List<XWPFParagraph> paragraphs = new ArrayList<XWPFParagraph>(1);
- List<XWPFTable> tables= new ArrayList<XWPFTable>(1);
+ List<XWPFTable> tables = new ArrayList<XWPFTable>(1);
List<XWPFPictureData> pictures = new ArrayList<XWPFPictureData>();
List<IBodyElement> bodyElements = new ArrayList<IBodyElement>(1);
XWPFDocument document;
XWPFHeaderFooter(XWPFDocument doc, CTHdrFtr hdrFtr) {
- if (doc==null) {
+ if (doc == null) {
throw new NullPointerException();
}
public XWPFHeaderFooter(POIXMLDocumentPart parent, PackagePart part, PackageRelationship rel) throws IOException {
super(parent, part, rel);
- this.document = (XWPFDocument)getParent();
+ this.document = (XWPFDocument) getParent();
- if (this.document==null) {
+ if (this.document == null) {
throw new NullPointerException();
}
}
@Override
protected void onDocumentRead() throws IOException {
- for (POIXMLDocumentPart poixmlDocumentPart : getRelations()){
- if(poixmlDocumentPart instanceof XWPFPictureData){
+ for (POIXMLDocumentPart poixmlDocumentPart : getRelations()) {
+ if (poixmlDocumentPart instanceof XWPFPictureData) {
XWPFPictureData xwpfPicData = (XWPFPictureData) poixmlDocumentPart;
pictures.add(xwpfPicData);
document.registerPackagePictureData(xwpfPicData);
return headerFooter;
}
- public List<IBodyElement> getBodyElements(){
+ public List<IBodyElement> getBodyElements() {
return Collections.unmodifiableList(bodyElements);
}
/**
* Returns the paragraph(s) that holds
- * the text of the header or footer.
+ * the text of the header or footer.
* Normally there is only the one paragraph, but
- * there could be more in certain cases, or
- * a table.
+ * there could be more in certain cases, or
+ * a table.
*/
public List<XWPFParagraph> getParagraphs() {
return Collections.unmodifiableList(paragraphs);
/**
* Return the table(s) that holds the text
- * of the header or footer, for complex cases
- * where a paragraph isn't used.
+ * of the header or footer, for complex cases
+ * where a paragraph isn't used.
* Normally there's just one paragraph, but some
- * complex headers/footers have a table or two
- * in addition.
+ * complex headers/footers have a table or two
+ * in addition.
*/
- public List<XWPFTable> getTables()throws ArrayIndexOutOfBoundsException {
+ public List<XWPFTable> getTables() throws ArrayIndexOutOfBoundsException {
return Collections.unmodifiableList(tables);
}
-
/**
* Returns the textual content of the header/footer,
- * by flattening out the text of its paragraph(s)
+ * by flattening out the text of its paragraph(s)
*/
public String getText() {
StringBuffer t = new StringBuffer();
- //TODO: simplify this to get ibody elements in order
- for(int i=0; i<paragraphs.size(); i++) {
- if(! paragraphs.get(i).isEmpty()) {
+ //TODO: simplify this to get ibody elements in order
+ for (int i = 0; i < paragraphs.size(); i++) {
+ if (!paragraphs.get(i).isEmpty()) {
String text = paragraphs.get(i).getText();
- if(text != null && text.length() > 0) {
+ if (text != null && text.length() > 0) {
t.append(text);
t.append('\n');
}
}
List<XWPFTable> tables = getTables();
- for(int i=0; i<tables.size(); i++) {
+ for (int i = 0; i < tables.size(); i++) {
String text = tables.get(i).getText();
- if(text != null && text.length() > 0) {
+ if (text != null && text.length() > 0) {
t.append(text);
t.append('\n');
}
}
-
- for (IBodyElement bodyElement : getBodyElements()){
- if (bodyElement instanceof XWPFSDT){
- t.append(((XWPFSDT) bodyElement).getContent().getText()+'\n');
- }
- }
- return t.toString();
+
+ for (IBodyElement bodyElement : getBodyElements()) {
+ if (bodyElement instanceof XWPFSDT) {
+ t.append(((XWPFSDT) bodyElement).getContent().getText() + '\n');
+ }
+ }
+ return t.toString();
}
/**
* set a new headerFooter
*/
- public void setHeaderFooter(CTHdrFtr headerFooter){
+ public void setHeaderFooter(CTHdrFtr headerFooter) {
this.headerFooter = headerFooter;
readHdrFtr();
}
/**
* if there is a corresponding {@link XWPFTable} of the parameter ctTable in the tableList of this header
* the method will return this table
- * if there is no corresponding {@link XWPFTable} the method will return null
+ * if there is no corresponding {@link XWPFTable} the method will return null
+ *
* @param ctTable
*/
- public XWPFTable getTable(CTTbl ctTable){
+ public XWPFTable getTable(CTTbl ctTable) {
for (XWPFTable table : tables) {
- if(table==null)
+ if (table == null)
return null;
- if(table.getCTTbl().equals(ctTable))
+ if (table.getCTTbl().equals(ctTable))
return table;
}
return null;
/**
* if there is a corresponding {@link XWPFParagraph} of the parameter ctTable in the paragraphList of this header or footer
* the method will return this paragraph
- * if there is no corresponding {@link XWPFParagraph} the method will return null
+ * if there is no corresponding {@link XWPFParagraph} the method will return null
+ *
* @param p is instance of CTP and is searching for an XWPFParagraph
* @return null if there is no XWPFParagraph with an corresponding CTPparagraph in the paragraphList of this header or footer
- * XWPFParagraph with the correspondig CTP p
+ * XWPFParagraph with the correspondig CTP p
*/
- public XWPFParagraph getParagraph(CTP p){
+ public XWPFParagraph getParagraph(CTP p) {
for (XWPFParagraph paragraph : paragraphs) {
- if(paragraph.getCTP().equals(p))
+ if (paragraph.getCTP().equals(p))
return paragraph;
}
return null;
/**
* Returns the paragraph that holds
- * the text of the header or footer.
+ * the text of the header or footer.
*/
public XWPFParagraph getParagraphArray(int pos) {
/**
* get a List of all Paragraphs
- * @return a list of {@link XWPFParagraph}
+ *
+ * @return a list of {@link XWPFParagraph}
*/
- public List<XWPFParagraph> getListParagraph(){
+ public List<XWPFParagraph> getListParagraph() {
return paragraphs;
}
/**
* get all Pictures in this package
+ *
* @return all Pictures in this package
*/
- public List<XWPFPictureData> getAllPackagePictures(){
+ public List<XWPFPictureData> getAllPackagePictures() {
return document.getAllPackagePictures();
}
/**
* Adds a picture to the document.
*
- * @param pictureData The picture data
- * @param format The format of the picture.
- *
+ * @param pictureData The picture data
+ * @param format The format of the picture.
* @return the index to this picture (0 based), the added picture can be obtained from {@link #getAllPictures()} .
- * @throws InvalidFormatException
+ * @throws InvalidFormatException
*/
- public String addPictureData(byte[] pictureData,int format) throws InvalidFormatException
- {
+ public String addPictureData(byte[] pictureData, int format) throws InvalidFormatException {
XWPFPictureData xwpfPicData = document.findPackagePictureData(pictureData, format);
POIXMLRelation relDesc = XWPFPictureData.RELATIONS[format];
- if (xwpfPicData == null)
- {
+ if (xwpfPicData == null) {
/* Part doesn't exist, create a new one */
int idx = document.getNextPicNameNumber(format);
- xwpfPicData = (XWPFPictureData) createRelationship(relDesc, XWPFFactory.getInstance(),idx);
+ xwpfPicData = (XWPFPictureData) createRelationship(relDesc, XWPFFactory.getInstance(), idx);
/* write bytes to new part */
PackagePart picDataPart = xwpfPicData.getPackagePart();
OutputStream out = null;
document.registerPackagePictureData(xwpfPicData);
pictures.add(xwpfPicData);
return getRelationId(xwpfPicData);
- }
- else if (!getRelations().contains(xwpfPicData))
- {
+ } else if (!getRelations().contains(xwpfPicData)) {
/*
* Part already existed, but was not related so far. Create
* relationship to the already existing part and update
TargetMode targetMode = TargetMode.INTERNAL;
PackagePartName partName = picDataPart.getPartName();
String relation = relDesc.getRelation();
- PackageRelationship relShip = getPackagePart().addRelationship(partName,targetMode,relation);
+ PackageRelationship relShip = getPackagePart().addRelationship(partName, targetMode, relation);
String id = relShip.getId();
- addRelation(id,xwpfPicData);
+ addRelation(id, xwpfPicData);
pictures.add(xwpfPicData);
return id;
- }
- else
- {
+ } else {
/* Part already existed, get relation id and return it */
return getRelationId(xwpfPicData);
}
/**
* Adds a picture to the document.
*
- * @param is The stream to read image from
- * @param format The format of the picture.
- *
+ * @param is The stream to read image from
+ * @param format The format of the picture.
* @return the index to this picture (0 based), the added picture can be obtained from {@link #getAllPictures()} .
- * @throws InvalidFormatException
- * @throws IOException
+ * @throws InvalidFormatException
+ * @throws IOException
*/
- public String addPictureData(InputStream is, int format) throws InvalidFormatException,IOException {
+ public String addPictureData(InputStream is, int format) throws InvalidFormatException, IOException {
byte[] data = IOUtils.toByteArray(is);
- return addPictureData(data,format);
+ return addPictureData(data, format);
}
/**
* returns the PictureData by blipID
+ *
* @param blipID
* @return XWPFPictureData of a specificID
- * @throws Exception
+ * @throws Exception
*/
public XWPFPictureData getPictureDataByID(String blipID) {
POIXMLDocumentPart relatedPart = getRelationById(blipID);
if (relatedPart != null && relatedPart instanceof XWPFPictureData) {
return (XWPFPictureData) relatedPart;
}
- return null;
+ return null;
}
/**
* add a new paragraph at position of the cursor
+ *
* @param cursor
* @return the inserted paragraph
*/
- public XWPFParagraph insertNewParagraph(XmlCursor cursor){
- if(isCursorInHdrF(cursor)){
+ public XWPFParagraph insertNewParagraph(XmlCursor cursor) {
+ if (isCursorInHdrF(cursor)) {
String uri = CTP.type.getName().getNamespaceURI();
String localPart = "p";
- cursor.beginElement(localPart,uri);
+ cursor.beginElement(localPart, uri);
cursor.toParent();
- CTP p = (CTP)cursor.getObject();
+ CTP p = (CTP) cursor.getObject();
XWPFParagraph newP = new XWPFParagraph(p, this);
XmlObject o = null;
- while(!(o instanceof CTP)&&(cursor.toPrevSibling())){
+ while (!(o instanceof CTP) && (cursor.toPrevSibling())) {
o = cursor.getObject();
}
- if((!(o instanceof CTP)) || (CTP)o == p){
+ if ((!(o instanceof CTP)) || (CTP) o == p) {
paragraphs.add(0, newP);
+ } else {
+ int pos = paragraphs.indexOf(getParagraph((CTP) o)) + 1;
+ paragraphs.add(pos, newP);
}
- else{
- int pos = paragraphs.indexOf(getParagraph((CTP)o))+1;
- paragraphs.add(pos,newP);
- }
- int i=0;
+ int i = 0;
cursor.toCursor(p.newCursor());
- while(cursor.toPrevSibling()){
- o =cursor.getObject();
- if(o instanceof CTP || o instanceof CTTbl)
+ while (cursor.toPrevSibling()) {
+ o = cursor.getObject();
+ if (o instanceof CTP || o instanceof CTTbl)
i++;
}
bodyElements.add(i, newP);
/**
- *
* @param cursor
* @return the inserted table
*/
public XWPFTable insertNewTbl(XmlCursor cursor) {
- if(isCursorInHdrF(cursor)){
+ if (isCursorInHdrF(cursor)) {
String uri = CTTbl.type.getName().getNamespaceURI();
String localPart = "tbl";
- cursor.beginElement(localPart,uri);
+ cursor.beginElement(localPart, uri);
cursor.toParent();
- CTTbl t = (CTTbl)cursor.getObject();
+ CTTbl t = (CTTbl) cursor.getObject();
XWPFTable newT = new XWPFTable(t, this);
cursor.removeXmlContents();
XmlObject o = null;
- while(!(o instanceof CTTbl)&&(cursor.toPrevSibling())){
+ while (!(o instanceof CTTbl) && (cursor.toPrevSibling())) {
o = cursor.getObject();
}
- if(!(o instanceof CTTbl)){
+ if (!(o instanceof CTTbl)) {
tables.add(0, newT);
+ } else {
+ int pos = tables.indexOf(getTable((CTTbl) o)) + 1;
+ tables.add(pos, newT);
}
- else{
- int pos = tables.indexOf(getTable((CTTbl)o))+1;
- tables.add(pos,newT);
- }
- int i=0;
+ int i = 0;
cursor = t.newCursor();
- while(cursor.toPrevSibling()){
- o =cursor.getObject();
- if(o instanceof CTP || o instanceof CTTbl)
+ while (cursor.toPrevSibling()) {
+ o = cursor.getObject();
+ if (o instanceof CTP || o instanceof CTTbl)
i++;
}
bodyElements.add(i, newT);
/**
* verifies that cursor is on the right position
+ *
* @param cursor
*/
private boolean isCursorInHdrF(XmlCursor cursor) {
XmlCursor verify = cursor.newCursor();
verify.toParent();
- if(verify.getObject() == this.headerFooter){
+ if (verify.getObject() == this.headerFooter) {
return true;
}
return false;
}
- public POIXMLDocumentPart getOwner(){
+ public POIXMLDocumentPart getOwner() {
return this;
}
/**
* Returns the table at position pos
+ *
* @see org.apache.poi.xwpf.usermodel.IBody#getTableArray(int)
*/
public XWPFTable getTableArray(int pos) {
- if(pos > 0 && pos < tables.size()){
+ if (pos > 0 && pos < tables.size()) {
return tables.get(pos);
}
return null;
/**
* inserts an existing XWPFTable to the arrays bodyElements and tables
+ *
* @param pos
* @param table
*/
bodyElements.add(pos, table);
int i = 0;
for (CTTbl tbl : headerFooter.getTblArray()) {
- if(tbl == table.getCTTbl()){
+ if (tbl == table.getCTTbl()) {
break;
}
i++;
}
- public void readHdrFtr(){
+ public void readHdrFtr() {
bodyElements = new ArrayList<IBodyElement>();
paragraphs = new ArrayList<XWPFParagraph>();
- tables= new ArrayList<XWPFTable>();
+ tables = new ArrayList<XWPFTable>();
// parse the document with cursor and add
// the XmlObject to its lists
XmlCursor cursor = headerFooter.newCursor();
while (cursor.toNextSelection()) {
XmlObject o = cursor.getObject();
if (o instanceof CTP) {
- XWPFParagraph p = new XWPFParagraph((CTP)o, this);
+ XWPFParagraph p = new XWPFParagraph((CTP) o, this);
paragraphs.add(p);
bodyElements.add(p);
}
if (o instanceof CTTbl) {
- XWPFTable t = new XWPFTable((CTTbl)o, this);
+ XWPFTable t = new XWPFTable((CTTbl) o, this);
tables.add(t);
bodyElements.add(t);
}
/**
* get the TableCell which belongs to the TableCell
+ *
* @param cell
*/
public XWPFTableCell getTableCell(CTTc cell) {
XmlCursor cursor = cell.newCursor();
cursor.toParent();
XmlObject o = cursor.getObject();
- if(!(o instanceof CTRow)){
+ if (!(o instanceof CTRow)) {
return null;
}
- CTRow row = (CTRow)o;
+ CTRow row = (CTRow) o;
cursor.toParent();
o = cursor.getObject();
cursor.dispose();
- if(! (o instanceof CTTbl)){
+ if (!(o instanceof CTTbl)) {
return null;
}
CTTbl tbl = (CTTbl) o;
XWPFTable table = getTable(tbl);
- if(table == null){
+ if (table == null) {
return null;
}
XWPFTableRow tableRow = table.getRow(row);
- if(row == null){
+ if (row == null) {
return null;
}
return tableRow.getTableCell(cell);
}
- public void setXWPFDocument(XWPFDocument doc) {
- document = doc;
- }
-
public XWPFDocument getXWPFDocument() {
- if (document!=null) {
+ if (document != null) {
return document;
} else {
- return (XWPFDocument)getParent();
+ return (XWPFDocument) getParent();
}
}
+ public void setXWPFDocument(XWPFDocument doc) {
+ document = doc;
+ }
+
/**
* returns the Part, to which the body belongs, which you need for adding relationship to other parts
+ *
* @see org.apache.poi.xwpf.usermodel.IBody#getPart()
*/
public POIXMLDocumentPart getPart() {
/**
* Sketch of XWPF hyperlink class
- *
-* @author Yury Batrakov (batrakov at gmail.com)
- *
+ *
+ * @author Yury Batrakov (batrakov at gmail.com)
*/
-public class XWPFHyperlink
-{
+public class XWPFHyperlink {
String id, url;
- public XWPFHyperlink(String id, String url)
- {
+
+ public XWPFHyperlink(String id, String url) {
this.id = id;
this.url = url;
}
-
- public String getId()
- {
+
+ public String getId() {
return id;
}
-
- public String getURL()
- {
+
+ public String getURL() {
return url;
}
}
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTR;
/**
- * A run of text with a Hyperlink applied to it.
- * Any given Hyperlink may be made up of multiple of these.
- */
-public class XWPFHyperlinkRun extends XWPFRun
-{
- private CTHyperlink hyperlink;
-
- public XWPFHyperlinkRun(CTHyperlink hyperlink, CTR run, IRunBody p) {
- super(run, p);
- this.hyperlink = hyperlink;
- }
-
- public CTHyperlink getCTHyperlink() {
- return hyperlink;
- }
-
- public String getAnchor() {
- return hyperlink.getAnchor();
- }
-
- /**
- * Returns the ID of the hyperlink, if one is set.
- */
- public String getHyperlinkId() {
- return hyperlink.getId();
- }
- public void setHyperlinkId(String id) {
- hyperlink.setId(id);
- }
-
- /**
- * If this Hyperlink is an external reference hyperlink,
- * return the object for it.
- */
- public XWPFHyperlink getHyperlink(XWPFDocument document) {
- String id = getHyperlinkId();
- if(id == null)
- return null;
-
- return document.getHyperlinkByID(id);
- }
-}
+ * A run of text with a Hyperlink applied to it.\r
+ * Any given Hyperlink may be made up of multiple of these.\r
+ */\r
+public class XWPFHyperlinkRun extends XWPFRun {\r
+ private CTHyperlink hyperlink;\r
+\r
+ public XWPFHyperlinkRun(CTHyperlink hyperlink, CTR run, IRunBody p) {\r
+ super(run, p);\r
+ this.hyperlink = hyperlink;\r
+ }\r
+\r
+ public CTHyperlink getCTHyperlink() {\r
+ return hyperlink;\r
+ }\r
+\r
+ public String getAnchor() {\r
+ return hyperlink.getAnchor();\r
+ }\r
+\r
+ /**\r
+ * Returns the ID of the hyperlink, if one is set.\r
+ */\r
+ public String getHyperlinkId() {\r
+ return hyperlink.getId();\r
+ }\r
+\r
+ public void setHyperlinkId(String id) {\r
+ hyperlink.setId(id);\r
+ }\r
+\r
+ /**\r
+ * If this Hyperlink is an external reference hyperlink,\r
+ * return the object for it.\r
+ */\r
+ public XWPFHyperlink getHyperlink(XWPFDocument document) {\r
+ String id = getHyperlinkId();\r
+ if (id == null)\r
+ return null;\r
+\r
+ return document.getHyperlinkByID(id);\r
+ }\r
+}\r
package org.apache.poi.xwpf.usermodel;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTLatentStyles;
-import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTLsdException;
-
-public class XWPFLatentStyles {
- private CTLatentStyles latentStyles;
- protected XWPFStyles styles; //LatentStyle shall know styles
-
- protected XWPFLatentStyles(){
- }
-
- protected XWPFLatentStyles(CTLatentStyles latentStyles){
- this(latentStyles,null);
- }
-
- protected XWPFLatentStyles(CTLatentStyles latentStyles, XWPFStyles styles) {
- this.latentStyles=latentStyles;
- this.styles=styles;
- }
-
- public int getNumberOfStyles() {
+import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTLsdException;\r
+\r
+public class XWPFLatentStyles {\r
+ protected XWPFStyles styles; //LatentStyle shall know styles\r
+ private CTLatentStyles latentStyles;\r
+\r
+ protected XWPFLatentStyles() {\r
+ }\r
+\r
+ protected XWPFLatentStyles(CTLatentStyles latentStyles) {\r
+ this(latentStyles, null);\r
+ }\r
+\r
+ protected XWPFLatentStyles(CTLatentStyles latentStyles, XWPFStyles styles) {\r
+ this.latentStyles = latentStyles;\r
+ this.styles = styles;\r
+ }\r
+\r
+ public int getNumberOfStyles() {\r
return latentStyles.sizeOfLsdExceptionArray();
}
/**
- * checks whether specific LatentStyleID is a latentStyle
- */
- @SuppressWarnings("deprecation")
- protected boolean isLatentStyle(String latentStyleID){
- for ( CTLsdException lsd: latentStyles.getLsdExceptionArray()) {
- if(lsd.getName().equals(latentStyleID)) {
- return true;
- }
- }
- return false;
- }
-}
+ * checks whether specific LatentStyleID is a latentStyle\r
+ */\r
+ @SuppressWarnings("deprecation")\r
+ protected boolean isLatentStyle(String latentStyleID) {\r
+ for (CTLsdException lsd : latentStyles.getLsdExceptionArray()) {\r
+ if (lsd.getName().equals(latentStyleID)) {\r
+ return true;\r
+ }\r
+ }\r
+ return false;\r
+ }\r
+}\r
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTNum;
-
-/**
- * @author Philipp Epp
- *
- */
-public class XWPFNum {
- private CTNum ctNum;
- protected XWPFNumbering numbering;
-
- public XWPFNum(){
- this.ctNum = null;
- this.numbering = null;
- }
-
- public XWPFNum(CTNum ctNum){
- this.ctNum = ctNum;
- this.numbering = null;
- }
-
- public XWPFNum(XWPFNumbering numbering){
- this.ctNum = null;
- this.numbering = numbering;
- }
-
- public XWPFNum(CTNum ctNum, XWPFNumbering numbering){
- this.ctNum = ctNum;
- this.numbering = numbering;
- }
-
- public XWPFNumbering getNumbering(){
- return numbering;
- }
-
- public CTNum getCTNum(){
- return ctNum;
- }
-
- public void setNumbering(XWPFNumbering numbering){
- this.numbering = numbering;
- }
-
- public void setCTNum(CTNum ctNum){
- this.ctNum = ctNum;
- }
+\r
+/**\r
+ * @author Philipp Epp\r
+ */\r
+public class XWPFNum {\r
+ protected XWPFNumbering numbering;\r
+ private CTNum ctNum;\r
+\r
+ public XWPFNum() {\r
+ this.ctNum = null;\r
+ this.numbering = null;\r
+ }\r
+\r
+ public XWPFNum(CTNum ctNum) {\r
+ this.ctNum = ctNum;\r
+ this.numbering = null;\r
+ }\r
+\r
+ public XWPFNum(XWPFNumbering numbering) {\r
+ this.ctNum = null;\r
+ this.numbering = numbering;\r
+ }\r
+\r
+ public XWPFNum(CTNum ctNum, XWPFNumbering numbering) {\r
+ this.ctNum = ctNum;\r
+ this.numbering = numbering;\r
+ }\r
+\r
+ public XWPFNumbering getNumbering() {\r
+ return numbering;\r
+ }\r
+\r
+ public void setNumbering(XWPFNumbering numbering) {\r
+ this.numbering = numbering;\r
+ }\r
+\r
+ public CTNum getCTNum() {\r
+ return ctNum;\r
+ }\r
+\r
+ public void setCTNum(CTNum ctNum) {\r
+ this.ctNum = ctNum;\r
+ }\r
}
\ No newline at end of file
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTNum;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTNumbering;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.NumberingDocument;
-
-/**
- * @author Philipp Epp
- *
- */
-public class XWPFNumbering extends POIXMLDocumentPart {
- protected List<XWPFAbstractNum> abstractNums = new ArrayList<XWPFAbstractNum>();
- protected List<XWPFNum> nums = new ArrayList<XWPFNum>();
-
- private CTNumbering ctNumbering;
- boolean isNew;
-
- /**
- *create a new styles object with an existing document
- */
- public XWPFNumbering(PackagePart part, PackageRelationship rel) throws IOException, OpenXML4JException{
- super(part, rel);
- isNew = true;
- }
-
- /**
- * create a new XWPFNumbering object for use in a new document
- */
- public XWPFNumbering(){
- abstractNums = new ArrayList<XWPFAbstractNum>();
- nums = new ArrayList<XWPFNum>();
- isNew = true;
- }
-
- /**
- * read numbering form an existing package
- */
- @Override
- @SuppressWarnings("deprecation")
- protected void onDocumentRead() throws IOException{
- NumberingDocument numberingDoc = null;
- InputStream is;
- is = getPackagePart().getInputStream();
- try {
- numberingDoc = NumberingDocument.Factory.parse(is);
- ctNumbering = numberingDoc.getNumbering();
- //get any Nums
- for(CTNum ctNum : ctNumbering.getNumArray()) {
- nums.add(new XWPFNum(ctNum, this));
- }
- for(CTAbstractNum ctAbstractNum : ctNumbering.getAbstractNumArray()){
- abstractNums.add(new XWPFAbstractNum(ctAbstractNum, this));
- }
- isNew = false;
- } catch (XmlException e) {
- throw new POIXMLException();
- }
- }
-
- /**
- * save and commit numbering
- */
- @Override
- protected void commit() throws IOException {
- XmlOptions xmlOptions = new XmlOptions(DEFAULT_XML_OPTIONS);
- xmlOptions.setSaveSyntheticDocumentElement(new QName(CTNumbering.type.getName().getNamespaceURI(), "numbering"));
- Map<String,String> map = new HashMap<String,String>();
- map.put("http://schemas.openxmlformats.org/markup-compatibility/2006", "ve");
- map.put("urn:schemas-microsoft-com:office:office", "o");
- map.put("http://schemas.openxmlformats.org/officeDocument/2006/relationships", "r");
+\r
+/**\r
+ * @author Philipp Epp\r
+ */\r
+public class XWPFNumbering extends POIXMLDocumentPart {\r
+ protected List<XWPFAbstractNum> abstractNums = new ArrayList<XWPFAbstractNum>();\r
+ protected List<XWPFNum> nums = new ArrayList<XWPFNum>();\r
+ boolean isNew;\r
+ private CTNumbering ctNumbering;\r
+\r
+ /**\r
+ * create a new styles object with an existing document\r
+ */\r
+ public XWPFNumbering(PackagePart part, PackageRelationship rel) throws IOException, OpenXML4JException {\r
+ super(part, rel);\r
+ isNew = true;\r
+ }\r
+\r
+ /**\r
+ * create a new XWPFNumbering object for use in a new document\r
+ */\r
+ public XWPFNumbering() {\r
+ abstractNums = new ArrayList<XWPFAbstractNum>();\r
+ nums = new ArrayList<XWPFNum>();\r
+ isNew = true;\r
+ }\r
+\r
+ /**\r
+ * read numbering form an existing package\r
+ */\r
+ @Override\r
+ @SuppressWarnings("deprecation")\r
+ protected void onDocumentRead() throws IOException {\r
+ NumberingDocument numberingDoc = null;\r
+ InputStream is;\r
+ is = getPackagePart().getInputStream();\r
+ try {\r
+ numberingDoc = NumberingDocument.Factory.parse(is);\r
+ ctNumbering = numberingDoc.getNumbering();\r
+ //get any Nums\r
+ for (CTNum ctNum : ctNumbering.getNumArray()) {\r
+ nums.add(new XWPFNum(ctNum, this));\r
+ }\r
+ for (CTAbstractNum ctAbstractNum : ctNumbering.getAbstractNumArray()) {\r
+ abstractNums.add(new XWPFAbstractNum(ctAbstractNum, this));\r
+ }\r
+ isNew = false;\r
+ } catch (XmlException e) {\r
+ throw new POIXMLException();\r
+ }\r
+ }\r
+\r
+ /**\r
+ * save and commit numbering\r
+ */\r
+ @Override\r
+ protected void commit() throws IOException {\r
+ XmlOptions xmlOptions = new XmlOptions(DEFAULT_XML_OPTIONS);\r
+ xmlOptions.setSaveSyntheticDocumentElement(new QName(CTNumbering.type.getName().getNamespaceURI(), "numbering"));\r
+ Map<String, String> map = new HashMap<String, String>();\r
+ map.put("http://schemas.openxmlformats.org/markup-compatibility/2006", "ve");\r
+ map.put("urn:schemas-microsoft-com:office:office", "o");\r
+ map.put("http://schemas.openxmlformats.org/officeDocument/2006/relationships", "r");\r
map.put("http://schemas.openxmlformats.org/officeDocument/2006/math", "m");
map.put("urn:schemas-microsoft-com:vml", "v");
map.put("http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing", "wp");
OutputStream out = part.getOutputStream();
ctNumbering.save(out, xmlOptions);
out.close();
- }
-
-
- /**
- * Sets the ctNumbering
- * @param numbering
- */
- public void setNumbering(CTNumbering numbering){
- ctNumbering = numbering;
- }
-
-
- /**
- * Checks whether number with numID exists
- * @param numID
- * @return boolean true if num exist, false if num not exist
- */
- public boolean numExist(BigInteger numID){
- for (XWPFNum num : nums) {
- if (num.getCTNum().getNumId().equals(numID))
- return true;
- }
- return false;
- }
-
- /**
- * add a new number to the numbering document
- * @param num
- */
- public BigInteger addNum(XWPFNum num){
- ctNumbering.addNewNum();
- int pos = ctNumbering.sizeOfNumArray() - 1;
- ctNumbering.setNumArray(pos, num.getCTNum());
- nums.add(num);
- return num.getCTNum().getNumId();
- }
-
- /**
- * Add a new num with an abstractNumID
- * @return return NumId of the added num
- */
- public BigInteger addNum(BigInteger abstractNumID){
- CTNum ctNum = this.ctNumbering.addNewNum();
- ctNum.addNewAbstractNumId();
- ctNum.getAbstractNumId().setVal(abstractNumID);
- ctNum.setNumId(BigInteger.valueOf(nums.size()+1));
- XWPFNum num = new XWPFNum(ctNum, this);
- nums.add(num);
- return ctNum.getNumId();
- }
-
- /**
- * Add a new num with an abstractNumID and a numID
- * @param abstractNumID
- * @param numID
- */
- public void addNum(BigInteger abstractNumID, BigInteger numID){
- CTNum ctNum = this.ctNumbering.addNewNum();
- ctNum.addNewAbstractNumId();
- ctNum.getAbstractNumId().setVal(abstractNumID);
- ctNum.setNumId(numID);
- XWPFNum num = new XWPFNum(ctNum, this);
- nums.add(num);
- }
-
- /**
- * get Num by NumID
- * @param numID
- * @return abstractNum with NumId if no Num exists with that NumID
- * null will be returned
- */
- public XWPFNum getNum(BigInteger numID){
- for(XWPFNum num: nums){
- if(num.getCTNum().getNumId().equals(numID))
- return num;
- }
- return null;
- }
- /**
- * get AbstractNum by abstractNumID
- * @param abstractNumID
- * @return abstractNum with abstractNumId if no abstractNum exists with that abstractNumID
- * null will be returned
- */
- public XWPFAbstractNum getAbstractNum(BigInteger abstractNumID){
- for(XWPFAbstractNum abstractNum: abstractNums){
- if(abstractNum.getAbstractNum().getAbstractNumId().equals(abstractNumID)){
- return abstractNum;
- }
- }
- return null;
- }
- /**
- * Compare AbstractNum with abstractNums of this numbering document.
- * If the content of abstractNum equals with an abstractNum of the List in numbering
- * the BigInteger Value of it will be returned.
- * If no equal abstractNum is existing null will be returned
- *
- * @param abstractNum
- * @return BigInteger
- */
- public BigInteger getIdOfAbstractNum(XWPFAbstractNum abstractNum){
- CTAbstractNum copy = (CTAbstractNum) abstractNum.getCTAbstractNum().copy();
- XWPFAbstractNum newAbstractNum = new XWPFAbstractNum(copy, this);
- int i;
- for (i = 0; i < abstractNums.size(); i++) {
- newAbstractNum.getCTAbstractNum().setAbstractNumId(BigInteger.valueOf(i));
- newAbstractNum.setNumbering(this);
- if(newAbstractNum.getCTAbstractNum().valueEquals(abstractNums.get(i).getCTAbstractNum())){
- return newAbstractNum.getCTAbstractNum().getAbstractNumId();
- }
- }
- return null;
- }
-
-
- /**
- * add a new AbstractNum and return its AbstractNumID
- * @param abstractNum
- */
- public BigInteger addAbstractNum(XWPFAbstractNum abstractNum){
- int pos = abstractNums.size();
- if(abstractNum.getAbstractNum() != null){ // Use the current CTAbstractNum if it exists
- ctNumbering.addNewAbstractNum().set(abstractNum.getAbstractNum());
- } else {
- ctNumbering.addNewAbstractNum();
- abstractNum.getAbstractNum().setAbstractNumId(BigInteger.valueOf(pos));
- ctNumbering.setAbstractNumArray(pos, abstractNum.getAbstractNum());
- }
- abstractNums.add(abstractNum);
- return abstractNum.getCTAbstractNum().getAbstractNumId();
- }
-
- /**
- * remove an existing abstractNum
- * @param abstractNumID
- * @return true if abstractNum with abstractNumID exists in NumberingArray,
- * false if abstractNum with abstractNumID not exists
- */
- public boolean removeAbstractNum(BigInteger abstractNumID){
- if(abstractNumID.byteValue()<abstractNums.size()){
- ctNumbering.removeAbstractNum(abstractNumID.byteValue());
- abstractNums.remove(abstractNumID.byteValue());
- return true;
- }
- return false;
- }
- /**
- *return the abstractNumID
- *If the AbstractNumID not exists
- *return null
- * @param numID
- * @return abstractNumID
- */
- public BigInteger getAbstractNumID(BigInteger numID){
- XWPFNum num = getNum(numID);
- if(num == null)
- return null;
- if (num.getCTNum() == null)
- return null;
- if (num.getCTNum().getAbstractNumId() == null)
- return null;
- return num.getCTNum().getAbstractNumId().getVal();
- }
-}
-
+ }\r
+\r
+\r
+ /**\r
+ * Sets the ctNumbering\r
+ *\r
+ * @param numbering\r
+ */\r
+ public void setNumbering(CTNumbering numbering) {\r
+ ctNumbering = numbering;\r
+ }\r
+\r
+\r
+ /**\r
+ * Checks whether number with numID exists\r
+ *\r
+ * @param numID\r
+ * @return boolean true if num exist, false if num not exist\r
+ */\r
+ public boolean numExist(BigInteger numID) {\r
+ for (XWPFNum num : nums) {\r
+ if (num.getCTNum().getNumId().equals(numID))\r
+ return true;\r
+ }\r
+ return false;\r
+ }\r
+\r
+ /**\r
+ * add a new number to the numbering document\r
+ *\r
+ * @param num\r
+ */\r
+ public BigInteger addNum(XWPFNum num) {\r
+ ctNumbering.addNewNum();\r
+ int pos = ctNumbering.sizeOfNumArray() - 1;\r
+ ctNumbering.setNumArray(pos, num.getCTNum());\r
+ nums.add(num);\r
+ return num.getCTNum().getNumId();\r
+ }\r
+\r
+ /**\r
+ * Add a new num with an abstractNumID\r
+ *\r
+ * @return return NumId of the added num\r
+ */\r
+ public BigInteger addNum(BigInteger abstractNumID) {\r
+ CTNum ctNum = this.ctNumbering.addNewNum();\r
+ ctNum.addNewAbstractNumId();\r
+ ctNum.getAbstractNumId().setVal(abstractNumID);\r
+ ctNum.setNumId(BigInteger.valueOf(nums.size() + 1));\r
+ XWPFNum num = new XWPFNum(ctNum, this);\r
+ nums.add(num);\r
+ return ctNum.getNumId();\r
+ }\r
+\r
+ /**\r
+ * Add a new num with an abstractNumID and a numID\r
+ *\r
+ * @param abstractNumID\r
+ * @param numID\r
+ */\r
+ public void addNum(BigInteger abstractNumID, BigInteger numID) {\r
+ CTNum ctNum = this.ctNumbering.addNewNum();\r
+ ctNum.addNewAbstractNumId();\r
+ ctNum.getAbstractNumId().setVal(abstractNumID);\r
+ ctNum.setNumId(numID);\r
+ XWPFNum num = new XWPFNum(ctNum, this);\r
+ nums.add(num);\r
+ }\r
+\r
+ /**\r
+ * get Num by NumID\r
+ *\r
+ * @param numID\r
+ * @return abstractNum with NumId if no Num exists with that NumID\r
+ * null will be returned\r
+ */\r
+ public XWPFNum getNum(BigInteger numID) {\r
+ for (XWPFNum num : nums) {\r
+ if (num.getCTNum().getNumId().equals(numID))\r
+ return num;\r
+ }\r
+ return null;\r
+ }\r
+\r
+ /**\r
+ * get AbstractNum by abstractNumID\r
+ *\r
+ * @param abstractNumID\r
+ * @return abstractNum with abstractNumId if no abstractNum exists with that abstractNumID\r
+ * null will be returned\r
+ */\r
+ public XWPFAbstractNum getAbstractNum(BigInteger abstractNumID) {\r
+ for (XWPFAbstractNum abstractNum : abstractNums) {\r
+ if (abstractNum.getAbstractNum().getAbstractNumId().equals(abstractNumID)) {\r
+ return abstractNum;\r
+ }\r
+ }\r
+ return null;\r
+ }\r
+\r
+ /**\r
+ * Compare AbstractNum with abstractNums of this numbering document.\r
+ * If the content of abstractNum equals with an abstractNum of the List in numbering\r
+ * the BigInteger Value of it will be returned.\r
+ * If no equal abstractNum is existing null will be returned\r
+ *\r
+ * @param abstractNum\r
+ * @return BigInteger\r
+ */\r
+ public BigInteger getIdOfAbstractNum(XWPFAbstractNum abstractNum) {\r
+ CTAbstractNum copy = (CTAbstractNum) abstractNum.getCTAbstractNum().copy();\r
+ XWPFAbstractNum newAbstractNum = new XWPFAbstractNum(copy, this);\r
+ int i;\r
+ for (i = 0; i < abstractNums.size(); i++) {\r
+ newAbstractNum.getCTAbstractNum().setAbstractNumId(BigInteger.valueOf(i));\r
+ newAbstractNum.setNumbering(this);\r
+ if (newAbstractNum.getCTAbstractNum().valueEquals(abstractNums.get(i).getCTAbstractNum())) {\r
+ return newAbstractNum.getCTAbstractNum().getAbstractNumId();\r
+ }\r
+ }\r
+ return null;\r
+ }\r
+\r
+\r
+ /**\r
+ * add a new AbstractNum and return its AbstractNumID\r
+ *\r
+ * @param abstractNum\r
+ */\r
+ public BigInteger addAbstractNum(XWPFAbstractNum abstractNum) {\r
+ int pos = abstractNums.size();\r
+ if (abstractNum.getAbstractNum() != null) { // Use the current CTAbstractNum if it exists\r
+ ctNumbering.addNewAbstractNum().set(abstractNum.getAbstractNum());\r
+ } else {\r
+ ctNumbering.addNewAbstractNum();\r
+ abstractNum.getAbstractNum().setAbstractNumId(BigInteger.valueOf(pos));\r
+ ctNumbering.setAbstractNumArray(pos, abstractNum.getAbstractNum());\r
+ }\r
+ abstractNums.add(abstractNum);\r
+ return abstractNum.getCTAbstractNum().getAbstractNumId();\r
+ }\r
+\r
+ /**\r
+ * remove an existing abstractNum\r
+ *\r
+ * @param abstractNumID\r
+ * @return true if abstractNum with abstractNumID exists in NumberingArray,\r
+ * false if abstractNum with abstractNumID not exists\r
+ */\r
+ public boolean removeAbstractNum(BigInteger abstractNumID) {\r
+ if (abstractNumID.byteValue() < abstractNums.size()) {\r
+ ctNumbering.removeAbstractNum(abstractNumID.byteValue());\r
+ abstractNums.remove(abstractNumID.byteValue());\r
+ return true;\r
+ }\r
+ return false;\r
+ }\r
+\r
+ /**\r
+ * return the abstractNumID\r
+ * If the AbstractNumID not exists\r
+ * return null\r
+ *\r
+ * @param numID\r
+ * @return abstractNumID\r
+ */\r
+ public BigInteger getAbstractNumID(BigInteger numID) {\r
+ XWPFNum num = getNum(numID);\r
+ if (num == null)\r
+ return null;\r
+ if (num.getCTNum() == null)\r
+ return null;\r
+ if (num.getCTNum().getAbstractNumId() == null)\r
+ return null;\r
+ return num.getCTNum().getAbstractNumId().getVal();\r
+ }\r
+}\r
+\r
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
+
import org.apache.poi.POIXMLDocumentPart;
import org.apache.poi.util.Internal;
import org.apache.poi.wp.usermodel.Paragraph;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.STTextAlignment;
/**
- * <p>A Paragraph within a Document, Table, Header etc.</p>
- *
+ * <p>A Paragraph within a Document, Table, Header etc.</p>
+ * <p/>
* <p>A paragraph has a lot of styling information, but the
- * actual text (possibly along with more styling) is held on
- * the child {@link XWPFRun}s.</p>
+ * actual text (possibly along with more styling) is held on
+ * the child {@link XWPFRun}s.</p>
*/
public class XWPFParagraph implements IBodyElement, IRunBody, ISDTContents, Paragraph {
private final CTP paragraph;
protected IBody part;
- /** For access to the document's hyperlink, comments, tables etc */
+ /**
+ * For access to the document's hyperlink, comments, tables etc
+ */
protected XWPFDocument document;
protected List<XWPFRun> runs;
protected List<IRunElement> iruns;
public XWPFParagraph(CTP prgrph, IBody part) {
this.paragraph = prgrph;
this.part = part;
-
+
this.document = part.getXWPFDocument();
- if (document==null) {
+ if (document == null) {
throw new NullPointerException();
}
buildRunsInOrderFromXml(paragraph);
// Look for bits associated with the runs
- for(XWPFRun run : runs) {
+ for (XWPFRun run : runs) {
CTR r = run.getCTR();
// Check for bits that only apply when attached to a core document
c.selectPath("child::*");
while (c.toNextSelection()) {
XmlObject o = c.getObject();
- if(o instanceof CTFtnEdnRef) {
- CTFtnEdnRef ftn = (CTFtnEdnRef)o;
+ if (o instanceof CTFtnEdnRef) {
+ CTFtnEdnRef ftn = (CTFtnEdnRef) o;
footnoteText.append(" [").append(ftn.getId()).append(": ");
XWPFFootnote footnote =
- ftn.getDomNode().getLocalName().equals("footnoteReference") ?
- document.getFootnoteByID(ftn.getId().intValue()) :
- document.getEndnoteByID(ftn.getId().intValue());
+ ftn.getDomNode().getLocalName().equals("footnoteReference") ?
+ document.getFootnoteByID(ftn.getId().intValue()) :
+ document.getEndnoteByID(ftn.getId().intValue());
boolean first = true;
for (XWPFParagraph p : footnote.getParagraphs()) {
/**
* Identifies (in order) the parts of the paragraph /
- * sub-paragraph that correspond to character text
- * runs, and builds the appropriate runs for these.
+ * sub-paragraph that correspond to character text
+ * runs, and builds the appropriate runs for these.
*/
private void buildRunsInOrderFromXml(XmlObject object) {
XmlCursor c = object.newCursor();
while (c.toNextSelection()) {
XmlObject o = c.getObject();
if (o instanceof CTR) {
- XWPFRun r = new XWPFRun((CTR) o, this);
- runs.add(r);
- iruns.add(r);
- }
- if (o instanceof CTHyperlink) {
- CTHyperlink link = (CTHyperlink) o;
- for (CTR r : link.getRArray()) {
- XWPFHyperlinkRun hr = new XWPFHyperlinkRun(link, r, this);
- runs.add(hr);
- iruns.add(hr);
- }
- }
- if (o instanceof CTSdtBlock) {
- XWPFSDT cc = new XWPFSDT((CTSdtBlock) o, part);
- iruns.add(cc);
- }
- if (o instanceof CTSdtRun) {
- XWPFSDT cc = new XWPFSDT((CTSdtRun) o, part);
- iruns.add(cc);
- }
- if (o instanceof CTRunTrackChange) {
- for (CTR r : ((CTRunTrackChange) o).getRArray()) {
- XWPFRun cr = new XWPFRun(r, this);
- runs.add(cr);
- iruns.add(cr);
- }
- }
- if (o instanceof CTSimpleField) {
- for (CTR r : ((CTSimpleField) o).getRArray()) {
- XWPFRun cr = new XWPFRun(r, this);
- runs.add(cr);
- iruns.add(cr);
- }
- }
+ XWPFRun r = new XWPFRun((CTR) o, this);
+ runs.add(r);
+ iruns.add(r);
+ }
+ if (o instanceof CTHyperlink) {
+ CTHyperlink link = (CTHyperlink) o;
+ for (CTR r : link.getRArray()) {
+ XWPFHyperlinkRun hr = new XWPFHyperlinkRun(link, r, this);
+ runs.add(hr);
+ iruns.add(hr);
+ }
+ }
+ if (o instanceof CTSdtBlock) {
+ XWPFSDT cc = new XWPFSDT((CTSdtBlock) o, part);
+ iruns.add(cc);
+ }
+ if (o instanceof CTSdtRun) {
+ XWPFSDT cc = new XWPFSDT((CTSdtRun) o, part);
+ iruns.add(cc);
+ }
+ if (o instanceof CTRunTrackChange) {
+ for (CTR r : ((CTRunTrackChange) o).getRArray()) {
+ XWPFRun cr = new XWPFRun(r, this);
+ runs.add(cr);
+ iruns.add(cr);
+ }
+ }
+ if (o instanceof CTSimpleField) {
+ for (CTR r : ((CTSimpleField) o).getRArray()) {
+ XWPFRun cr = new XWPFRun(r, this);
+ runs.add(cr);
+ iruns.add(cr);
+ }
+ }
if (o instanceof CTSmartTagRun) {
- // Smart Tags can be nested many times.
+ // Smart Tags can be nested many times.
// This implementation does not preserve the tagging information
buildRunsInOrderFromXml(o);
}
}
c.dispose();
}
-
+
@Internal
public CTP getCTP() {
return paragraph;
}
- public List<XWPFRun> getRuns(){
+ public List<XWPFRun> getRuns() {
return Collections.unmodifiableList(runs);
}
-
+
/**
* Return literal runs and sdt/content control objects.
+ *
* @return List<IRunElement>
*/
public List<IRunElement> getIRuns() {
return Collections.unmodifiableList(iruns);
}
-
- public boolean isEmpty(){
+
+ public boolean isEmpty() {
return !paragraph.getDomNode().hasChildNodes();
}
- public XWPFDocument getDocument(){
+ public XWPFDocument getDocument() {
return document;
}
public String getText() {
StringBuffer out = new StringBuffer();
for (IRunElement run : iruns) {
- if (run instanceof XWPFSDT){
- out.append(((XWPFSDT)run).getContent().getText());
+ if (run instanceof XWPFSDT) {
+ out.append(((XWPFSDT) run).getContent().getText());
} else {
out.append(run.toString());
}
/**
* Return styleID of the paragraph if style exist for this paragraph
- * if not, null will be returned
- * @return styleID as String
+ * if not, null will be returned
+ *
+ * @return styleID as String
*/
public String getStyleID() {
if (paragraph.getPPr() != null) {
- if(paragraph.getPPr().getPStyle()!= null) {
- if (paragraph.getPPr().getPStyle().getVal()!= null)
+ if (paragraph.getPPr().getPStyle() != null) {
+ if (paragraph.getPPr().getPStyle().getVal() != null)
return paragraph.getPPr().getPStyle().getVal();
}
}
return null;
- }
+ }
+
/**
* If style exist for this paragraph
* NumId of the paragraph will be returned.
- * If style not exist null will be returned
- * @return NumID as BigInteger
+ * If style not exist null will be returned
+ *
+ * @return NumID as BigInteger
*/
- public BigInteger getNumID(){
- if(paragraph.getPPr()!=null){
- if(paragraph.getPPr().getNumPr()!=null){
- if(paragraph.getPPr().getNumPr().getNumId()!=null)
+ public BigInteger getNumID() {
+ if (paragraph.getPPr() != null) {
+ if (paragraph.getPPr().getNumPr() != null) {
+ if (paragraph.getPPr().getNumPr().getNumId() != null)
return paragraph.getPPr().getNumPr().getNumId().getVal();
}
}
return null;
}
+ /**
+ * setNumID of Paragraph
+ *
+ * @param numPos
+ */
+ public void setNumID(BigInteger numPos) {
+ if (paragraph.getPPr() == null)
+ paragraph.addNewPPr();
+ if (paragraph.getPPr().getNumPr() == null)
+ paragraph.getPPr().addNewNumPr();
+ if (paragraph.getPPr().getNumPr().getNumId() == null) {
+ paragraph.getPPr().getNumPr().addNewNumId();
+ }
+ paragraph.getPPr().getNumPr().getNumId().setVal(numPos);
+ }
+
/**
* Returns Ilvl of the numeric style for this paragraph.
* Returns null if this paragraph does not have numeric style.
+ *
* @return Ilvl as BigInteger
*/
public BigInteger getNumIlvl() {
- if(paragraph.getPPr()!=null){
- if(paragraph.getPPr().getNumPr()!=null){
- if(paragraph.getPPr().getNumPr().getIlvl()!=null)
+ if (paragraph.getPPr() != null) {
+ if (paragraph.getPPr().getNumPr() != null) {
+ if (paragraph.getPPr().getNumPr().getIlvl() != null)
return paragraph.getPPr().getNumPr().getIlvl().getVal();
}
}
/**
* Returns numbering format for this paragraph, eg bullet or
- * lowerLetter.
+ * lowerLetter.
* Returns null if this paragraph does not have numeric style.
*/
public String getNumFmt() {
BigInteger numID = getNumID();
XWPFNumbering numbering = document.getNumbering();
- if(numID != null && numbering != null) {
+ if (numID != null && numbering != null) {
XWPFNum num = numbering.getNum(numID);
- if(num != null) {
+ if (num != null) {
BigInteger ilvl = getNumIlvl();
BigInteger abstractNumId = num.getCTNum().getAbstractNumId().getVal();
CTAbstractNum anum = numbering.getAbstractNum(abstractNumId).getAbstractNum();
CTLvl level = null;
- for(int i = 0; i < anum.sizeOfLvlArray(); i++) {
+ for (int i = 0; i < anum.sizeOfLvlArray(); i++) {
CTLvl lvl = anum.getLvlArray(i);
- if(lvl.getIlvl().equals(ilvl)) {
+ if (lvl.getIlvl().equals(ilvl)) {
level = lvl;
break;
}
}
- if(level != null && level.getNumFmt() != null
- && level.getNumFmt().getVal() != null)
+ if (level != null && level.getNumFmt() != null
+ && level.getNumFmt().getVal() != null)
return level.getNumFmt().getVal().toString();
}
}
public String getNumLevelText() {
BigInteger numID = getNumID();
XWPFNumbering numbering = document.getNumbering();
- if(numID != null && numbering != null) {
+ if (numID != null && numbering != null) {
XWPFNum num = numbering.getNum(numID);
- if(num != null) {
+ if (num != null) {
BigInteger ilvl = getNumIlvl();
CTNum ctNum = num.getCTNum();
if (ctNum == null)
return null;
CTLvl level = null;
- for(int i = 0; i < anum.sizeOfLvlArray(); i++) {
+ for (int i = 0; i < anum.sizeOfLvlArray(); i++) {
CTLvl lvl = anum.getLvlArray(i);
- if(lvl != null && lvl.getIlvl() != null && lvl.getIlvl().equals(ilvl)) {
+ if (lvl != null && lvl.getIlvl() != null && lvl.getIlvl().equals(ilvl)) {
level = lvl;
break;
}
}
- if(level != null && level.getLvlText() != null
- && level.getLvlText().getVal() != null)
+ if (level != null && level.getLvlText() != null
+ && level.getLvlText().getVal() != null)
return level.getLvlText().getVal().toString();
}
}
return null;
}
-
/**
* Gets the numstartOverride for the paragraph numbering for this paragraph.
+ *
* @return returns the overridden start number or null if there is no override for this paragraph.
*/
public BigInteger getNumStartOverride() {
BigInteger numID = getNumID();
XWPFNumbering numbering = document.getNumbering();
- if(numID != null && numbering != null) {
+ if (numID != null && numbering != null) {
XWPFNum num = numbering.getNum(numID);
- if(num != null) {
+ if (num != null) {
CTNum ctNum = num.getCTNum();
if (ctNum == null) {
return null;
}
BigInteger ilvl = getNumIlvl();
CTNumLvl level = null;
- for(int i = 0; i < ctNum.sizeOfLvlOverrideArray(); i++) {
+ for (int i = 0; i < ctNum.sizeOfLvlOverrideArray(); i++) {
CTNumLvl ctNumLvl = ctNum.getLvlOverrideArray(i);
- if(ctNumLvl != null && ctNumLvl.getIlvl() != null &&
- ctNumLvl.getIlvl().equals(ilvl)) {
+ if (ctNumLvl != null && ctNumLvl.getIlvl() != null &&
+ ctNumLvl.getIlvl().equals(ilvl)) {
level = ctNumLvl;
break;
}
}
- if(level != null && level.getStartOverride() != null) {
+ if (level != null && level.getStartOverride() != null) {
return level.getStartOverride().getVal();
}
}
}
return null;
}
- /**
- * setNumID of Paragraph
- * @param numPos
- */
- public void setNumID(BigInteger numPos) {
- if(paragraph.getPPr()==null)
- paragraph.addNewPPr();
- if(paragraph.getPPr().getNumPr()==null)
- paragraph.getPPr().addNewNumPr();
- if(paragraph.getPPr().getNumPr().getNumId()==null){
- paragraph.getPPr().getNumPr().addNewNumId();
- }
- paragraph.getPPr().getNumPr().getNumId().setVal(numPos);
- }
/**
* Returns the text of the paragraph, but not of any objects in the
*/
public String getParagraphText() {
StringBuffer out = new StringBuffer();
- for(XWPFRun run : runs) {
+ for (XWPFRun run : runs) {
out.append(run.toString());
}
return out.toString();
*/
public String getPictureText() {
StringBuffer out = new StringBuffer();
- for(XWPFRun run : runs) {
+ for (XWPFRun run : runs) {
out.append(run.getPictureText());
}
return out.toString();
/**
* Returns the footnote text of the paragraph
*
- * @return the footnote text or empty string if the paragraph does not have footnotes
+ * @return the footnote text or empty string if the paragraph does not have footnotes
*/
public String getFootnoteText() {
return footnoteText.toString();
public int getFontAlignment() {
return getAlignment().getValue();
}
+
public void setFontAlignment(int align) {
ParagraphAlignment pAlign = ParagraphAlignment.valueOf(align);
setAlignment(pAlign);
CTPPr pr = getCTPPr();
return (pr == null || !pr.isSetTextAlignment()) ? TextAlignment.AUTO
: TextAlignment.valueOf(pr.getTextAlignment().getVal()
- .intValue());
+ .intValue());
}
/**
CTPPr pr = getCTPPr();
CTTextAlignment textAlignment = pr.isSetTextAlignment() ? pr
.getTextAlignment() : pr.addNewTextAlignment();
- STTextAlignment.Enum en = STTextAlignment.Enum
- .forInt(valign.getValue());
- textAlignment.setVal(en);
+ STTextAlignment.Enum en = STTextAlignment.Enum
+ .forInt(valign.getValue());
+ textAlignment.setVal(en);
+ }
+
+ /**
+ * Specifies the border which shall be displayed above a set of paragraphs
+ * which have the same set of paragraph border settings.
+ *
+ * @return paragraphBorder - the top border for the paragraph
+ * @see #setBorderTop(Borders)
+ * @see Borders a list of all types of borders
+ */
+ public Borders getBorderTop() {
+ CTPBdr border = getCTPBrd(false);
+ CTBorder ct = null;
+ if (border != null) {
+ ct = border.getTop();
+ }
+ STBorder.Enum ptrn = (ct != null) ? ct.getVal() : STBorder.NONE;
+ return Borders.valueOf(ptrn.intValue());
}
/**
}
/**
- * Specifies the border which shall be displayed above a set of paragraphs
- * which have the same set of paragraph border settings.
+ * Specifies the border which shall be displayed below a set of
+ * paragraphs which have the same set of paragraph border settings.
*
- * @return paragraphBorder - the top border for the paragraph
- * @see #setBorderTop(Borders)
+ * @return paragraphBorder - the bottom border for the paragraph
+ * @see #setBorderBottom(Borders)
* @see Borders a list of all types of borders
*/
- public Borders getBorderTop() {
+ public Borders getBorderBottom() {
CTPBdr border = getCTPBrd(false);
CTBorder ct = null;
if (border != null) {
- ct = border.getTop();
+ ct = border.getBottom();
}
- STBorder.Enum ptrn = (ct != null) ? ct.getVal() : STBorder.NONE;
+ STBorder.Enum ptrn = ct != null ? ct.getVal() : STBorder.NONE;
return Borders.valueOf(ptrn.intValue());
}
}
/**
- * Specifies the border which shall be displayed below a set of
- * paragraphs which have the same set of paragraph border settings.
+ * Specifies the border which shall be displayed on the left side of the
+ * page around the specified paragraph.
*
- * @return paragraphBorder - the bottom border for the paragraph
- * @see #setBorderBottom(Borders)
- * @see Borders a list of all types of borders
+ * @return ParagraphBorder - the left border for the paragraph
+ * @see #setBorderLeft(Borders)
+ * @see Borders for a list of all possible borders
*/
- public Borders getBorderBottom() {
+ public Borders getBorderLeft() {
CTPBdr border = getCTPBrd(false);
CTBorder ct = null;
if (border != null) {
- ct = border.getBottom();
+ ct = border.getLeft();
}
STBorder.Enum ptrn = ct != null ? ct.getVal() : STBorder.NONE;
return Borders.valueOf(ptrn.intValue());
}
/**
- * Specifies the border which shall be displayed on the left side of the
+ * Specifies the border which shall be displayed on the right side of the
* page around the specified paragraph.
*
- * @return ParagraphBorder - the left border for the paragraph
- * @see #setBorderLeft(Borders)
+ * @return ParagraphBorder - the right border for the paragraph
+ * @see #setBorderRight(Borders)
* @see Borders for a list of all possible borders
*/
- public Borders getBorderLeft() {
+ public Borders getBorderRight() {
CTPBdr border = getCTPBrd(false);
CTBorder ct = null;
if (border != null) {
- ct = border.getLeft();
+ ct = border.getRight();
}
STBorder.Enum ptrn = ct != null ? ct.getVal() : STBorder.NONE;
return Borders.valueOf(ptrn.intValue());
}
/**
- * Specifies the border which shall be displayed on the right side of the
- * page around the specified paragraph.
+ * Specifies the border which shall be displayed between each paragraph in a
+ * set of paragraphs which have the same set of paragraph border settings.
*
- * @return ParagraphBorder - the right border for the paragraph
- * @see #setBorderRight(Borders)
+ * @return ParagraphBorder - the between border for the paragraph
+ * @see #setBorderBetween(Borders)
* @see Borders for a list of all possible borders
*/
- public Borders getBorderRight() {
+ public Borders getBorderBetween() {
CTPBdr border = getCTPBrd(false);
CTBorder ct = null;
if (border != null) {
- ct = border.getRight();
+ ct = border.getBetween();
}
STBorder.Enum ptrn = ct != null ? ct.getVal() : STBorder.NONE;
return Borders.valueOf(ptrn.intValue());
}
/**
- * Specifies the border which shall be displayed between each paragraph in a
- * set of paragraphs which have the same set of paragraph border settings.
+ * Specifies that when rendering this document in a paginated
+ * view, the contents of this paragraph are rendered on the start of a new
+ * page in the document.
+ * <p/>
+ * If this element is omitted on a given paragraph,
+ * its value is determined by the setting previously set at any level of the
+ * style hierarchy (i.e. that previous setting remains unchanged). If this
+ * setting is never specified in the style hierarchy, then this property
+ * shall not be applied. Since the paragraph is specified to start on a new
+ * page, it begins page two even though it could have fit on page one.
+ * </p>
*
- * @return ParagraphBorder - the between border for the paragraph
- * @see #setBorderBetween(Borders)
- * @see Borders for a list of all possible borders
+ * @return boolean - if page break is set
*/
- public Borders getBorderBetween() {
- CTPBdr border = getCTPBrd(false);
- CTBorder ct = null;
- if (border != null) {
- ct = border.getBetween();
+ public boolean isPageBreak() {
+ CTPPr ppr = getCTPPr();
+ CTOnOff ct_pageBreak = ppr.isSetPageBreakBefore() ? ppr
+ .getPageBreakBefore() : null;
+ if (ct_pageBreak != null
+ && ct_pageBreak.getVal().intValue() == STOnOff.INT_TRUE) {
+ return true;
}
- STBorder.Enum ptrn = ct != null ? ct.getVal() : STBorder.NONE;
- return Borders.valueOf(ptrn.intValue());
+ return false;
}
/**
}
/**
- * Specifies that when rendering this document in a paginated
- * view, the contents of this paragraph are rendered on the start of a new
- * page in the document.
- * <p/>
- * If this element is omitted on a given paragraph,
- * its value is determined by the setting previously set at any level of the
- * style hierarchy (i.e. that previous setting remains unchanged). If this
- * setting is never specified in the style hierarchy, then this property
- * shall not be applied. Since the paragraph is specified to start on a new
- * page, it begins page two even though it could have fit on page one.
- * </p>
+ * Specifies the spacing that should be added after the last line in this
+ * paragraph in the document in absolute units.
*
- * @return boolean - if page break is set
+ * @return int - value representing the spacing after the paragraph
*/
- public boolean isPageBreak() {
- CTPPr ppr = getCTPPr();
- CTOnOff ct_pageBreak = ppr.isSetPageBreakBefore() ? ppr
- .getPageBreakBefore() : null;
- if (ct_pageBreak != null
- && ct_pageBreak.getVal().intValue() == STOnOff.INT_TRUE) {
- return true;
- }
- return false;
+ public int getSpacingAfter() {
+ CTSpacing spacing = getCTSpacing(false);
+ return (spacing != null && spacing.isSetAfter()) ? spacing.getAfter().intValue() : -1;
}
/**
* Specifies the spacing that should be added after the last line in this
* paragraph in the document in absolute units.
*
- * @return int - value representing the spacing after the paragraph
+ * @return bigInteger - value representing the spacing after the paragraph
+ * @see #setSpacingAfterLines(int)
*/
- public int getSpacingAfter() {
+ public int getSpacingAfterLines() {
CTSpacing spacing = getCTSpacing(false);
- return (spacing != null && spacing.isSetAfter()) ? spacing.getAfter().intValue() : -1;
+ return (spacing != null && spacing.isSetAfterLines()) ? spacing.getAfterLines().intValue() : -1;
}
/**
spacing.setAfterLines(bi);
}
-
/**
- * Specifies the spacing that should be added after the last line in this
+ * Specifies the spacing that should be added above the first line in this
* paragraph in the document in absolute units.
*
- * @return bigInteger - value representing the spacing after the paragraph
- * @see #setSpacingAfterLines(int)
+ * @return the spacing that should be added above the first line
+ * @see #setSpacingBefore(int)
*/
- public int getSpacingAfterLines() {
+ public int getSpacingBefore() {
CTSpacing spacing = getCTSpacing(false);
- return (spacing != null && spacing.isSetAfterLines()) ? spacing.getAfterLines().intValue() : -1;
+ return (spacing != null && spacing.isSetBefore()) ? spacing.getBefore().intValue() : -1;
}
-
/**
* Specifies the spacing that should be added above the first line in this
* paragraph in the document in absolute units.
}
/**
- * Specifies the spacing that should be added above the first line in this
- * paragraph in the document in absolute units.
+ * Specifies the spacing that should be added before the first line in this paragraph in the
+ * document in line units.
+ * The value of this attribute is specified in one hundredths of a line.
*
- * @return the spacing that should be added above the first line
- * @see #setSpacingBefore(int)
+ * @return the spacing that should be added before the first line in this paragraph
+ * @see #setSpacingBeforeLines(int)
*/
- public int getSpacingBefore() {
+ public int getSpacingBeforeLines() {
CTSpacing spacing = getCTSpacing(false);
- return (spacing != null && spacing.isSetBefore()) ? spacing.getBefore().intValue() : -1;
+ return (spacing != null && spacing.isSetBeforeLines()) ? spacing.getBeforeLines().intValue() : -1;
}
/**
}
/**
- * Specifies the spacing that should be added before the first line in this paragraph in the
- * document in line units.
- * The value of this attribute is specified in one hundredths of a line.
+ * Specifies how the spacing between lines is calculated as stored in the
+ * line attribute. If this attribute is omitted, then it shall be assumed to
+ * be of a value auto if a line attribute value is present.
*
- * @return the spacing that should be added before the first line in this paragraph
- * @see #setSpacingBeforeLines(int)
+ * @return rule
+ * @see LineSpacingRule
+ * @see #setSpacingLineRule(LineSpacingRule)
*/
- public int getSpacingBeforeLines() {
+ public LineSpacingRule getSpacingLineRule() {
CTSpacing spacing = getCTSpacing(false);
- return (spacing != null && spacing.isSetBeforeLines()) ? spacing.getBeforeLines().intValue() : -1;
+ return (spacing != null && spacing.isSetLineRule()) ? LineSpacingRule.valueOf(spacing
+ .getLineRule().intValue()) : LineSpacingRule.AUTO;
}
-
/**
* Specifies how the spacing between lines is calculated as stored in the
* line attribute. If this attribute is omitted, then it shall be assumed to
}
/**
- * Specifies how the spacing between lines is calculated as stored in the
- * line attribute. If this attribute is omitted, then it shall be assumed to
- * be of a value auto if a line attribute value is present.
+ * Specifies the indentation which shall be placed between the left text
+ * margin for this paragraph and the left edge of that paragraph's content
+ * in a left to right paragraph, and the right text margin and the right
+ * edge of that paragraph's text in a right to left paragraph
+ * <p/>
+ * If this attribute is omitted, its value shall be assumed to be zero.
+ * Negative values are defined such that the text is moved past the text margin,
+ * positive values move the text inside the text margin.
+ * </p>
*
- * @return rule
- * @see LineSpacingRule
- * @see #setSpacingLineRule(LineSpacingRule)
+ * @return indentation or null if indentation is not set
*/
- public LineSpacingRule getSpacingLineRule() {
- CTSpacing spacing = getCTSpacing(false);
- return (spacing != null && spacing.isSetLineRule()) ? LineSpacingRule.valueOf(spacing
- .getLineRule().intValue()) : LineSpacingRule.AUTO;
+ public int getIndentationLeft() {
+ CTInd indentation = getCTInd(false);
+ return (indentation != null && indentation.isSetLeft()) ? indentation.getLeft().intValue()
+ : -1;
}
-
/**
* Specifies the indentation which shall be placed between the left text
* margin for this paragraph and the left edge of that paragraph's content
}
/**
- * Specifies the indentation which shall be placed between the left text
- * margin for this paragraph and the left edge of that paragraph's content
+ * Specifies the indentation which shall be placed between the right text
+ * margin for this paragraph and the right edge of that paragraph's content
* in a left to right paragraph, and the right text margin and the right
* edge of that paragraph's text in a right to left paragraph
* <p/>
*
* @return indentation or null if indentation is not set
*/
- public int getIndentationLeft() {
+
+ public int getIndentationRight() {
CTInd indentation = getCTInd(false);
- return (indentation != null && indentation.isSetLeft()) ? indentation.getLeft().intValue()
+ return (indentation != null && indentation.isSetRight()) ? indentation.getRight().intValue()
: -1;
}
-
+
/**
* Specifies the indentation which shall be placed between the right text
* margin for this paragraph and the right edge of that paragraph's content
}
/**
- * Specifies the indentation which shall be placed between the right text
- * margin for this paragraph and the right edge of that paragraph's content
- * in a left to right paragraph, and the right text margin and the right
- * edge of that paragraph's text in a right to left paragraph
- * <p/>
- * If this attribute is omitted, its value shall be assumed to be zero.
- * Negative values are defined such that the text is moved past the text margin,
- * positive values move the text inside the text margin.
- * </p>
+ * Specifies the indentation which shall be removed from the first line of
+ * the parent paragraph, by moving the indentation on the first line back
+ * towards the beginning of the direction of text flow.
+ * This indentation is
+ * specified relative to the paragraph indentation which is specified for
+ * all other lines in the parent paragraph.
+ * The firstLine and hanging
+ * attributes are mutually exclusive, if both are specified, then the
+ * firstLine value is ignored.
*
* @return indentation or null if indentation is not set
*/
-
- public int getIndentationRight() {
+ public int getIndentationHanging() {
CTInd indentation = getCTInd(false);
- return (indentation != null && indentation.isSetRight()) ? indentation.getRight().intValue()
- : -1;
+ return (indentation != null && indentation.isSetHanging()) ? indentation.getHanging().intValue() : -1;
}
/**
indent.setHanging(bi);
}
- /**
- * Specifies the indentation which shall be removed from the first line of
- * the parent paragraph, by moving the indentation on the first line back
- * towards the beginning of the direction of text flow.
- * This indentation is
- * specified relative to the paragraph indentation which is specified for
- * all other lines in the parent paragraph.
- * The firstLine and hanging
- * attributes are mutually exclusive, if both are specified, then the
- * firstLine value is ignored.
- *
- * @return indentation or null if indentation is not set
- */
- public int getIndentationHanging() {
- CTInd indentation = getCTInd(false);
- return (indentation != null && indentation.isSetHanging()) ? indentation.getHanging().intValue() : -1;
- }
-
/**
* Specifies the additional indentation which shall be applied to the first
* line of the parent paragraph. This additional indentation is specified
* mutually exclusive, if both are specified, then the firstLine value is
* ignored.
* If the firstLineChars attribute is also specified, then this
- * value is ignored. If this attribute is omitted, then its value shall be
+ * value is ignored.
+ * If this attribute is omitted, then its value shall be
* assumed to be zero (if needed).
*
- * @param indentation
+ * @return indentation or null if indentation is not set
*/
- public void setIndentationFirstLine(int indentation) {
- CTInd indent = getCTInd(true);
- BigInteger bi = new BigInteger("" + indentation);
- indent.setFirstLine(bi);
+ public int getIndentationFirstLine() {
+ CTInd indentation = getCTInd(false);
+ return (indentation != null && indentation.isSetFirstLine()) ? indentation.getFirstLine().intValue()
+ : -1;
}
/**
* mutually exclusive, if both are specified, then the firstLine value is
* ignored.
* If the firstLineChars attribute is also specified, then this
- * value is ignored.
- * If this attribute is omitted, then its value shall be
+ * value is ignored. If this attribute is omitted, then its value shall be
* assumed to be zero (if needed).
*
- * @return indentation or null if indentation is not set
+ * @param indentation
*/
- public int getIndentationFirstLine() {
- CTInd indentation = getCTInd(false);
- return (indentation != null && indentation.isSetFirstLine()) ? indentation.getFirstLine().intValue()
- : -1;
+ public void setIndentationFirstLine(int indentation) {
+ CTInd indent = getCTInd(true);
+ BigInteger bi = new BigInteger("" + indentation);
+ indent.setFirstLine(bi);
}
public int getIndentFromLeft() {
return getIndentFromLeft();
}
+
public void setIndentFromLeft(int dxaLeft) {
setIndentationLeft(dxaLeft);
}
public int getIndentFromRight() {
return getIndentFromRight();
}
+
public void setIndentFromRight(int dxaRight) {
setIndentationRight(dxaRight);
}
public int getFirstLineIndent() {
return getIndentationFirstLine();
}
+
public void setFirstLineIndent(int first) {
setIndentationFirstLine(first);
}
+ /**
+ * This element specifies whether a consumer shall break Latin text which
+ * exceeds the text extents of a line by breaking the word across two lines
+ * (breaking on the character level) or by moving the word to the following
+ * line (breaking on the word level).
+ *
+ * @return boolean
+ */
+ public boolean isWordWrapped() {
+ CTOnOff wordWrap = getCTPPr().isSetWordWrap() ? getCTPPr()
+ .getWordWrap() : null;
+ if (wordWrap != null) {
+ return (wordWrap.getVal() == STOnOff.ON
+ || wordWrap.getVal() == STOnOff.TRUE || wordWrap.getVal() == STOnOff.X_1) ? true
+ : false;
+ }
+ return false;
+ }
+
/**
* This element specifies whether a consumer shall break Latin text which
* exceeds the text extents of a line by breaking the word across two lines
else
wordWrap.unsetVal();
}
+
+ public boolean isWordWrap() {
+ return isWordWrapped();
+ }
+
@Deprecated
public void setWordWrap(boolean wrap) {
setWordWrapped(wrap);
}
/**
- * This element specifies whether a consumer shall break Latin text which
- * exceeds the text extents of a line by breaking the word across two lines
- * (breaking on the character level) or by moving the word to the following
- * line (breaking on the word level).
- *
- * @return boolean
+ * @return the style of the paragraph
*/
- public boolean isWordWrapped() {
- CTOnOff wordWrap = getCTPPr().isSetWordWrap() ? getCTPPr()
- .getWordWrap() : null;
- if (wordWrap != null) {
- return (wordWrap.getVal() == STOnOff.ON
- || wordWrap.getVal() == STOnOff.TRUE || wordWrap.getVal() == STOnOff.X_1) ? true
- : false;
- }
- return false;
- }
- public boolean isWordWrap() {
- return isWordWrapped();
+ public String getStyle() {
+ CTPPr pr = getCTPPr();
+ CTString style = pr.isSetPStyle() ? pr.getPStyle() : null;
+ return style != null ? style.getVal() : null;
}
/**
* This method provides a style to the paragraph
* This is useful when, e.g. an Heading style has to be assigned
+ *
* @param newStyle
*/
public void setStyle(String newStyle) {
CTString style = pr.getPStyle() != null ? pr.getPStyle() : pr.addNewPStyle();
style.setVal(newStyle);
}
-
- /**
- * @return the style of the paragraph
- */
- public String getStyle() {
- CTPPr pr = getCTPPr();
- CTString style = pr.isSetPStyle() ? pr.getPStyle() : null;
- return style != null ? style.getVal() : null;
- }
/**
* Get a <b>copy</b> of the currently used CTPBrd, if none is used, return
: paragraph.getPPr();
return pr;
}
-
-
+
+
/**
- * add a new run at the end of the position of
+ * add a new run at the end of the position of
* the content of parameter run
+ *
* @param run
*/
- protected void addRun(CTR run){
+ protected void addRun(CTR run) {
int pos;
pos = paragraph.sizeOfRArray();
paragraph.addNewR();
paragraph.setRArray(pos, run);
}
-
+
/**
* Appends a new run to this paragraph
*
/**
* insert a new Run in RunArray
+ *
* @param pos
- * @return the inserted run
+ * @return the inserted run
*/
- public XWPFRun insertNewRun(int pos){
+ public XWPFRun insertNewRun(int pos) {
if (pos >= 0 && pos <= paragraph.sizeOfRArray()) {
CTR ctRun = paragraph.insertNewR(pos);
XWPFRun newRun = new XWPFRun(ctRun, this);
-
+
// To update the iruns, find where we're going
// in the normal runs, and go in there
int iPos = iruns.size();
}
}
iruns.add(iPos, newRun);
-
+
// Runs itself is easy to update
runs.add(pos, newRun);
-
+
return newRun;
}
return null;
* this methods parse the paragraph and search for the string searched.
* If it finds the string, it will return true and the position of the String
* will be saved in the parameter startPos.
+ *
* @param searched
* @param startPos
*/
- public TextSegement searchText(String searched,PositionInParagraph startPos) {
- int startRun = startPos.getRun(),
- startText = startPos.getText(),
- startChar = startPos.getChar();
+ public TextSegement searchText(String searched, PositionInParagraph startPos) {
+ int startRun = startPos.getRun(),
+ startText = startPos.getText(),
+ startChar = startPos.getChar();
int beginRunPos = 0, candCharPos = 0;
boolean newList = false;
CTR[] rArray = paragraph.getRArray();
- for (int runPos=startRun; runPos<rArray.length; runPos++) {
- int beginTextPos = 0,beginCharPos = 0, textPos = 0, charPos = 0;
+ for (int runPos = startRun; runPos < rArray.length; runPos++) {
+ int beginTextPos = 0, beginCharPos = 0, textPos = 0, charPos = 0;
CTR ctRun = rArray[runPos];
XmlCursor c = ctRun.newCursor();
c.selectPath("./*");
- while(c.toNextSelection()){
+ while (c.toNextSelection()) {
XmlObject o = c.getObject();
- if(o instanceof CTText){
- if(textPos>=startText){
- String candidate = ((CTText)o).getStringValue();
- if(runPos==startRun)
- charPos= startChar;
+ if (o instanceof CTText) {
+ if (textPos >= startText) {
+ String candidate = ((CTText) o).getStringValue();
+ if (runPos == startRun)
+ charPos = startChar;
else
charPos = 0;
-
- for(; charPos<candidate.length(); charPos++){
- if((candidate.charAt(charPos)==searched.charAt(0))&&(candCharPos==0)){
+
+ for (; charPos < candidate.length(); charPos++) {
+ if ((candidate.charAt(charPos) == searched.charAt(0)) && (candCharPos == 0)) {
beginTextPos = textPos;
beginCharPos = charPos;
beginRunPos = runPos;
newList = true;
}
- if(candidate.charAt(charPos)==searched.charAt(candCharPos)){
- if(candCharPos+1<searched.length())
+ if (candidate.charAt(charPos) == searched.charAt(candCharPos)) {
+ if (candCharPos + 1 < searched.length())
candCharPos++;
- else if(newList){
+ else if (newList) {
TextSegement segement = new TextSegement();
segement.setBeginRun(beginRunPos);
segement.setBeginText(beginTextPos);
segement.setEndChar(charPos);
return segement;
}
- }
- else {
- candCharPos=0;
+ } else {
+ candCharPos = 0;
}
}
}
textPos++;
- }
- else if(o instanceof CTProofErr){
+ } else if (o instanceof CTProofErr) {
c.removeXml();
- }
- else if(o instanceof CTRPr);
+ } else if (o instanceof CTRPr) ;
//do nothing
else
- candCharPos=0;
+ candCharPos = 0;
}
c.dispose();
}
return null;
}
-
+
/**
* get a Text
+ *
* @param segment
*/
- public String getText(TextSegement segment){
+ public String getText(TextSegement segment) {
int runBegin = segment.getBeginRun();
int textBegin = segment.getBeginText();
- int charBegin = segment.getBeginChar();
+ int charBegin = segment.getBeginChar();
int runEnd = segment.getEndRun();
int textEnd = segment.getEndText();
- int charEnd = segment.getEndChar();
+ int charEnd = segment.getEndChar();
StringBuilder out = new StringBuilder();
CTR[] rArray = paragraph.getRArray();
- for(int i=runBegin; i<=runEnd;i++){
+ for (int i = runBegin; i <= runEnd; i++) {
CTText[] tArray = rArray[i].getTArray();
- int startText=0, endText = tArray.length-1;
- if(i==runBegin)
- startText=textBegin;
- if(i==runEnd)
+ int startText = 0, endText = tArray.length - 1;
+ if (i == runBegin)
+ startText = textBegin;
+ if (i == runEnd)
endText = textEnd;
- for(int j=startText;j<=endText;j++){
+ for (int j = startText; j <= endText; j++) {
String tmpText = tArray[j].getStringValue();
- int startChar=0, endChar = tmpText.length()-1;
- if((j==textBegin)&&(i==runBegin))
- startChar=charBegin;
- if((j==textEnd)&&(i==runEnd)){
+ int startChar = 0, endChar = tmpText.length() - 1;
+ if ((j == textBegin) && (i == runBegin))
+ startChar = charBegin;
+ if ((j == textEnd) && (i == runEnd)) {
endChar = charEnd;
}
- out.append(tmpText.substring(startChar, endChar+1));
+ out.append(tmpText.substring(startChar, endChar + 1));
}
}
return out.toString();
/**
* removes a Run at the position pos in the paragraph
+ *
* @param pos
* @return true if the run was removed
*/
- public boolean removeRun(int pos){
+ public boolean removeRun(int pos) {
if (pos >= 0 && pos < paragraph.sizeOfRArray()) {
// Remove the run from our high level lists
XWPFRun run = runs.get(pos);
/**
* returns the type of the BodyElement Paragraph
+ *
* @see org.apache.poi.xwpf.usermodel.IBodyElement#getElementType()
*/
public BodyElementType getElementType() {
return BodyElementType.PARAGRAPH;
}
- public IBody getBody()
- {
+ public IBody getBody() {
return part;
}
/**
* returns the part of the bodyElement
+ *
* @see org.apache.poi.xwpf.usermodel.IBody#getPart()
*/
public POIXMLDocumentPart getPart() {
- if(part != null){
+ if (part != null) {
return part.getPart();
}
return null;
/**
* returns the partType of the bodyPart which owns the bodyElement
- *
+ *
* @see org.apache.poi.xwpf.usermodel.IBody#getPartType()
*/
public BodyType getPartType() {
/**
* adds a new Run to the Paragraph
- *
+ *
* @param r
*/
public void addRun(XWPFRun r) {
/**
* return the XWPFRun-Element which owns the CTR run-Element
- *
+ *
* @param r
*/
public XWPFRun getRun(CTR r) {
public class XWPFPicture {
private CTPicture ctPic;
- private String description;
- private XWPFRun run;
-
- public XWPFPicture(CTPicture ctPic, XWPFRun run){
- this.run = run;
- this.ctPic = ctPic;
- description = ctPic.getNvPicPr().getCNvPr().getDescr();
+ private String description;\r
+ private XWPFRun run;\r
+\r
+ public XWPFPicture(CTPicture ctPic, XWPFRun run) {\r
+ this.run = run;\r
+ this.ctPic = ctPic;\r
+ description = ctPic.getNvPicPr().getCNvPr().getDescr();\r
}
-
- /**
- * Link Picture with PictureData
- * @param rel
- */
- public void setPictureReference(PackageRelationship rel){
- ctPic.getBlipFill().getBlip().setEmbed(rel.getId());
- }
-
+\r
+ /**\r
+ * Link Picture with PictureData\r
+ *\r
+ * @param rel\r
+ */\r
+ public void setPictureReference(PackageRelationship rel) {\r
+ ctPic.getBlipFill().getBlip().setEmbed(rel.getId());\r
+ }\r
+\r
/**
* Return the underlying CTPicture bean that holds all properties for this picture
- *
- * @return the underlying CTPicture bean
- */
- public CTPicture getCTPicture(){
- return ctPic;
- }
-
+ *\r
+ * @return the underlying CTPicture bean\r
+ */\r
+ public CTPicture getCTPicture() {\r
+ return ctPic;\r
+ }\r
+\r
/**
- * Get the PictureData of the Picture, if present.
- * Note - not all kinds of picture have data
- */
- public XWPFPictureData getPictureData(){
- CTBlipFillProperties blipProps = ctPic.getBlipFill();
-
- if(blipProps == null || !blipProps.isSetBlip()) {
- // return null if Blip data is missing
- return null;
- }
-
- String blipId = blipProps.getBlip().getEmbed();
- POIXMLDocumentPart part = run.getParent().getPart();
- if (part != null)
- {
- POIXMLDocumentPart relatedPart = part.getRelationById(blipId);
- if (relatedPart instanceof XWPFPictureData) {
- return (XWPFPictureData) relatedPart;
+ * Get the PictureData of the Picture, if present.\r
+ * Note - not all kinds of picture have data\r
+ */\r
+ public XWPFPictureData getPictureData() {\r
+ CTBlipFillProperties blipProps = ctPic.getBlipFill();\r
+\r
+ if (blipProps == null || !blipProps.isSetBlip()) {\r
+ // return null if Blip data is missing\r
+ return null;\r
+ }\r
+\r
+ String blipId = blipProps.getBlip().getEmbed();\r
+ POIXMLDocumentPart part = run.getParent().getPart();\r
+ if (part != null) {\r
+ POIXMLDocumentPart relatedPart = part.getRelationById(blipId);\r
+ if (relatedPart instanceof XWPFPictureData) {\r
+ return (XWPFPictureData) relatedPart;\r
}
}
return null;
public class XWPFPictureData extends POIXMLDocumentPart {
/**
- * Relationships for each known picture type
- */
- protected static final POIXMLRelation[] RELATIONS;
- static {
- RELATIONS = new POIXMLRelation[13];
- RELATIONS[Document.PICTURE_TYPE_EMF] = XWPFRelation.IMAGE_EMF;
+ * Relationships for each known picture type\r
+ */\r
+ protected static final POIXMLRelation[] RELATIONS;\r
+\r
+ static {\r
+ RELATIONS = new POIXMLRelation[13];\r
+ RELATIONS[Document.PICTURE_TYPE_EMF] = XWPFRelation.IMAGE_EMF;\r
RELATIONS[Document.PICTURE_TYPE_WMF] = XWPFRelation.IMAGE_WMF;
RELATIONS[Document.PICTURE_TYPE_PICT] = XWPFRelation.IMAGE_PICT;
RELATIONS[Document.PICTURE_TYPE_JPEG] = XWPFRelation.IMAGE_JPEG;
}
private Long checksum = null;
-
- /**
- * Create a new XWPFGraphicData node
- *
- */
- protected XWPFPictureData() {
- super();
+\r
+ /**\r
+ * Create a new XWPFGraphicData node\r
+ */\r
+ protected XWPFPictureData() {\r
+ super();\r
}
/**
* Construct XWPFPictureData from a package part
- *
- * @param part the package part holding the drawing data,
- * @param rel the package relationship holding this drawing,
- * the relationship type must be http://schemas.openxmlformats.org/officeDocument/2006/relationships/image
- */
- public XWPFPictureData(PackagePart part, PackageRelationship rel) {
- super(part, rel);
+ *\r
+ * @param part the package part holding the drawing data,\r
+ * @param rel the package relationship holding this drawing,\r
+ * the relationship type must be http://schemas.openxmlformats.org/officeDocument/2006/relationships/image\r
+ */\r
+ public XWPFPictureData(PackagePart part, PackageRelationship rel) {\r
+ super(part, rel);\r
}
@Override
* You can grab the picture data directly from the underlying package part as follows:
* <br/>
* <code>
- * InputStream is = getPackagePart().getInputStream();
- * </code>
- * </p>
- * @return the Picture data.
- */
- public byte[] getData() {
+ * InputStream is = getPackagePart().getInputStream();\r
+ * </code>\r
+ * </p>\r
+ *\r
+ * @return the Picture data.\r
+ */\r
+ public byte[] getData() {\r
try {
return IOUtils.toByteArray(getPackagePart().getInputStream());
} catch (IOException e) {
return null;
return name.substring(name.lastIndexOf('/') + 1);
}
-
- /**
- * Suggests a file extension for this image.
- * @return the file extension.
- */
- public String suggestFileExtension() {
+\r
+ /**\r
+ * Suggests a file extension for this image.\r
+ *\r
+ * @return the file extension.\r
+ */\r
+ public String suggestFileExtension() {\r
return getPackagePart().getPartName().getExtension();
}
-
- /**
- * Return an integer constant that specifies type of this picture
- *
- * @return an integer constant that specifies type of this picture
- * @see org.apache.poi.xwpf.usermodel.Document#PICTURE_TYPE_EMF
- * @see org.apache.poi.xwpf.usermodel.Document#PICTURE_TYPE_WMF
+\r
+ /**\r
+ * Return an integer constant that specifies type of this picture\r
+ *\r
+ * @return an integer constant that specifies type of this picture\r
+ * @see org.apache.poi.xwpf.usermodel.Document#PICTURE_TYPE_EMF\r
+ * @see org.apache.poi.xwpf.usermodel.Document#PICTURE_TYPE_WMF\r
* @see org.apache.poi.xwpf.usermodel.Document#PICTURE_TYPE_PICT
* @see org.apache.poi.xwpf.usermodel.Document#PICTURE_TYPE_JPEG
* @see org.apache.poi.xwpf.usermodel.Document#PICTURE_TYPE_PNG
if (!ownPackage.equals(foreignPackage)) {
return false;
- }
- }
- }
-
- Long foreignChecksum = picData.getChecksum();
- Long localChecksum = getChecksum();
-
+ }\r
+ }\r
+ }\r
+\r
+ Long foreignChecksum = picData.getChecksum();\r
+ Long localChecksum = getChecksum();\r
+\r
if (!(localChecksum.equals(foreignChecksum))) {
return false;
}
@Override
public int hashCode() {
return getChecksum().hashCode();
- }
-
- /**
- * *PictureData objects store the actual content in the part directly without keeping a
- * copy like all others therefore we need to handle them differently.
- */
- @Override
+ }\r
+\r
+ /**\r
+ * *PictureData objects store the actual content in the part directly without keeping a\r
+ * copy like all others therefore we need to handle them differently.\r
+ */\r
+ @Override\r
protected void prepareForCommit() {
// do not clear the part here
}
*/
protected static final Map<String, XWPFRelation> _table = new HashMap<String, XWPFRelation>();
-
public static final XWPFRelation DOCUMENT = new XWPFRelation(
"application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml",
"http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument",
null
);
public static final XWPFRelation TEMPLATE = new XWPFRelation(
- "application/vnd.openxmlformats-officedocument.wordprocessingml.template.main+xml",
- "http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument",
- "/word/document.xml",
- null
+ "application/vnd.openxmlformats-officedocument.wordprocessingml.template.main+xml",
+ "http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument",
+ "/word/document.xml",
+ null
);
public static final XWPFRelation MACRO_DOCUMENT = new XWPFRelation(
"application/vnd.ms-word.document.macroEnabled.main+xml",
"/word/glossary/document.xml",
null
);
-
public static final XWPFRelation NUMBERING = new XWPFRelation(
- "application/vnd.openxmlformats-officedocument.wordprocessingml.numbering+xml",
- "http://schemas.openxmlformats.org/officeDocument/2006/relationships/numbering",
- "/word/numbering.xml",
- XWPFNumbering.class
+ "application/vnd.openxmlformats-officedocument.wordprocessingml.numbering+xml",
+ "http://schemas.openxmlformats.org/officeDocument/2006/relationships/numbering",
+ "/word/numbering.xml",
+ XWPFNumbering.class
);
public static final XWPFRelation FONT_TABLE = new XWPFRelation(
"application/vnd.openxmlformats-officedocument.wordprocessingml.fontTable+xml",
null
);
public static final XWPFRelation FOOTNOTE = new XWPFRelation(
- "application/vnd.openxmlformats-officedocument.wordprocessingml.footnotes+xml",
- "http://schemas.openxmlformats.org/officeDocument/2006/relationships/footnotes",
- "/word/footnotes.xml",
- XWPFFootnotes.class
+ "application/vnd.openxmlformats-officedocument.wordprocessingml.footnotes+xml",
+ "http://schemas.openxmlformats.org/officeDocument/2006/relationships/footnotes",
+ "/word/footnotes.xml",
+ XWPFFootnotes.class
);
public static final XWPFRelation ENDNOTE = new XWPFRelation(
null,
null,
null
);
-
/**
* Supported image formats
*/
public static final XWPFRelation IMAGE_EMF = new XWPFRelation(
- "image/x-emf",
- "http://schemas.openxmlformats.org/officeDocument/2006/relationships/image",
- "/word/media/image#.emf",
- XWPFPictureData.class
- );
- public static final XWPFRelation IMAGE_WMF = new XWPFRelation(
- "image/x-wmf",
- "http://schemas.openxmlformats.org/officeDocument/2006/relationships/image",
- "/word/media/image#.wmf",
- XWPFPictureData.class
- );
- public static final XWPFRelation IMAGE_PICT = new XWPFRelation(
- "image/pict",
- "http://schemas.openxmlformats.org/officeDocument/2006/relationships/image",
- "/word/media/image#.pict",
- XWPFPictureData.class
- );
- public static final XWPFRelation IMAGE_JPEG = new XWPFRelation(
- "image/jpeg",
- "http://schemas.openxmlformats.org/officeDocument/2006/relationships/image",
- "/word/media/image#.jpeg",
- XWPFPictureData.class
- );
- public static final XWPFRelation IMAGE_PNG = new XWPFRelation(
- "image/png",
- "http://schemas.openxmlformats.org/officeDocument/2006/relationships/image",
- "/word/media/image#.png",
- XWPFPictureData.class
- );
- public static final XWPFRelation IMAGE_DIB = new XWPFRelation(
- "image/dib",
- "http://schemas.openxmlformats.org/officeDocument/2006/relationships/image",
- "/word/media/image#.dib",
- XWPFPictureData.class
- );
- public static final XWPFRelation IMAGE_GIF = new XWPFRelation(
- "image/gif",
- "http://schemas.openxmlformats.org/officeDocument/2006/relationships/image",
- "/word/media/image#.gif",
- XWPFPictureData.class
- );
+ "image/x-emf",
+ "http://schemas.openxmlformats.org/officeDocument/2006/relationships/image",
+ "/word/media/image#.emf",
+ XWPFPictureData.class
+ );
+ public static final XWPFRelation IMAGE_WMF = new XWPFRelation(
+ "image/x-wmf",
+ "http://schemas.openxmlformats.org/officeDocument/2006/relationships/image",
+ "/word/media/image#.wmf",
+ XWPFPictureData.class
+ );
+ public static final XWPFRelation IMAGE_PICT = new XWPFRelation(
+ "image/pict",
+ "http://schemas.openxmlformats.org/officeDocument/2006/relationships/image",
+ "/word/media/image#.pict",
+ XWPFPictureData.class
+ );
+ public static final XWPFRelation IMAGE_JPEG = new XWPFRelation(
+ "image/jpeg",
+ "http://schemas.openxmlformats.org/officeDocument/2006/relationships/image",
+ "/word/media/image#.jpeg",
+ XWPFPictureData.class
+ );
+ public static final XWPFRelation IMAGE_PNG = new XWPFRelation(
+ "image/png",
+ "http://schemas.openxmlformats.org/officeDocument/2006/relationships/image",
+ "/word/media/image#.png",
+ XWPFPictureData.class
+ );
+ public static final XWPFRelation IMAGE_DIB = new XWPFRelation(
+ "image/dib",
+ "http://schemas.openxmlformats.org/officeDocument/2006/relationships/image",
+ "/word/media/image#.dib",
+ XWPFPictureData.class
+ );
+ public static final XWPFRelation IMAGE_GIF = new XWPFRelation(
+ "image/gif",
+ "http://schemas.openxmlformats.org/officeDocument/2006/relationships/image",
+ "/word/media/image#.gif",
+ XWPFPictureData.class
+ );
public static final XWPFRelation IMAGE_TIFF = new XWPFRelation(
"image/tiff",
"http://schemas.openxmlformats.org/officeDocument/2006/relationships/image",
"/word/media/image#.wpg",
XWPFPictureData.class
);
-
- public static final XWPFRelation IMAGES = new XWPFRelation(
- null,
- "http://schemas.openxmlformats.org/officeDocument/2006/relationships/image",
- null,
- null
- );
-
+ public static final XWPFRelation IMAGES = new XWPFRelation(
+ null,
+ "http://schemas.openxmlformats.org/officeDocument/2006/relationships/image",
+ null,
+ null
+ );
private XWPFRelation(String type, String rel, String defaultName, Class<? extends POIXMLDocumentPart> cls) {
super(type, rel, defaultName, cls);
import org.apache.xmlbeans.XmlCursor;
import org.apache.xmlbeans.XmlException;
import org.apache.xmlbeans.XmlObject;
-import org.apache.xmlbeans.XmlString;
-import org.apache.xmlbeans.XmlToken;
-import org.apache.xmlbeans.impl.values.XmlAnyTypeImpl;
-import org.openxmlformats.schemas.drawingml.x2006.main.*;
-import org.openxmlformats.schemas.drawingml.x2006.picture.CTPicture;
-import org.openxmlformats.schemas.drawingml.x2006.picture.CTPictureNonVisual;
-import org.openxmlformats.schemas.drawingml.x2006.wordprocessingDrawing.CTAnchor;
-import org.openxmlformats.schemas.drawingml.x2006.wordprocessingDrawing.CTInline;
-import org.openxmlformats.schemas.wordprocessingml.x2006.main.*;
-import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTColor;
-import org.w3c.dom.NodeList;
-import org.w3c.dom.Text;
-
+import org.apache.xmlbeans.XmlString;\r
+import org.apache.xmlbeans.XmlToken;\r
+import org.apache.xmlbeans.impl.values.XmlAnyTypeImpl;\r
+import org.openxmlformats.schemas.drawingml.x2006.main.CTBlip;\r
+import org.openxmlformats.schemas.drawingml.x2006.main.CTBlipFillProperties;\r
+import org.openxmlformats.schemas.drawingml.x2006.main.CTGraphicalObject;\r
+import org.openxmlformats.schemas.drawingml.x2006.main.CTGraphicalObjectData;\r
+import org.openxmlformats.schemas.drawingml.x2006.main.CTNonVisualDrawingProps;\r
+import org.openxmlformats.schemas.drawingml.x2006.main.CTNonVisualPictureProperties;\r
+import org.openxmlformats.schemas.drawingml.x2006.main.CTPoint2D;\r
+import org.openxmlformats.schemas.drawingml.x2006.main.CTPositiveSize2D;\r
+import org.openxmlformats.schemas.drawingml.x2006.main.CTPresetGeometry2D;\r
+import org.openxmlformats.schemas.drawingml.x2006.main.CTShapeProperties;\r
+import org.openxmlformats.schemas.drawingml.x2006.main.CTTransform2D;\r
+import org.openxmlformats.schemas.drawingml.x2006.main.STShapeType;\r
+import org.openxmlformats.schemas.drawingml.x2006.picture.CTPicture;\r
+import org.openxmlformats.schemas.drawingml.x2006.picture.CTPictureNonVisual;\r
+import org.openxmlformats.schemas.drawingml.x2006.wordprocessingDrawing.CTAnchor;\r
+import org.openxmlformats.schemas.drawingml.x2006.wordprocessingDrawing.CTInline;\r
+import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTBr;\r
+import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTColor;\r
+import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTDrawing;\r
+import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTEmpty;\r
+import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTFFCheckBox;\r
+import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTFldChar;\r
+import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTFonts;\r
+import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTFtnEdnRef;\r
+import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTHpsMeasure;\r
+import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTOnOff;\r
+import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTPTab;\r
+import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTR;\r
+import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTRPr;\r
+import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTSignedHpsMeasure;\r
+import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTSignedTwipsMeasure;\r
+import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTText;\r
+import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTUnderline;\r
+import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTVerticalAlignRun;\r
+import org.openxmlformats.schemas.wordprocessingml.x2006.main.STBrClear;\r
+import org.openxmlformats.schemas.wordprocessingml.x2006.main.STBrType;\r
+import org.openxmlformats.schemas.wordprocessingml.x2006.main.STFldCharType;\r
+import org.openxmlformats.schemas.wordprocessingml.x2006.main.STOnOff;\r
+import org.openxmlformats.schemas.wordprocessingml.x2006.main.STUnderline;\r
+import org.openxmlformats.schemas.wordprocessingml.x2006.main.STVerticalAlignRun;\r
+import org.w3c.dom.NodeList;\r
+import org.w3c.dom.Text;\r
+\r
/**
* XWPFRun object defines a region of text with a common set of properties
*/
private CTR run;
private String pictureText;
private IRunBody parent;
- private List<XWPFPicture> pictures;
-
- /**
- * @see <a href="http://msdn.microsoft.com/en-us/library/ff533743(v=office.12).aspx">[MS-OI29500] Run Fonts</a>
- */
- public static enum FontCharRange {
- ascii /* char 0-127 */,
- cs /* complex symbol */,
- eastAsia /* east asia */,
- hAnsi /* high ansi */
- };
-
- /**
- * @param r the CTR bean which holds the run attributes
- * @param p the parent paragraph
- */
+ private List<XWPFPicture> pictures;\r
+\r
+ /**\r
+ * @param r the CTR bean which holds the run attributes\r
+ * @param p the parent paragraph\r
+ */\r
@SuppressWarnings("deprecation")
public XWPFRun(CTR r, IRunBody p) {
this.run = r;
// Look for any text in any of our pictures or drawings
StringBuilder text = new StringBuilder();
- List<XmlObject> pictTextObjs = new ArrayList<XmlObject>();
- pictTextObjs.addAll(Arrays.asList(r.getPictArray()));
- pictTextObjs.addAll(Arrays.asList(r.getDrawingArray()));
- for(XmlObject o : pictTextObjs) {
- XmlObject[] ts = o.selectPath("declare namespace w='http://schemas.openxmlformats.org/wordprocessingml/2006/main' .//w:t");
- for (XmlObject t : ts) {
- NodeList kids = t.getDomNode().getChildNodes();
+ List<XmlObject> pictTextObjs = new ArrayList<XmlObject>();\r
+ pictTextObjs.addAll(Arrays.asList(r.getPictArray()));\r
+ pictTextObjs.addAll(Arrays.asList(r.getDrawingArray()));\r
+ for (XmlObject o : pictTextObjs) {\r
+ XmlObject[] ts = o.selectPath("declare namespace w='http://schemas.openxmlformats.org/wordprocessingml/2006/main' .//w:t");\r
+ for (XmlObject t : ts) {\r
+ NodeList kids = t.getDomNode().getChildNodes();\r
for (int n = 0; n < kids.getLength(); n++) {
if (kids.item(n) instanceof Text) {
if (text.length() > 0)
}
pictureText = text.toString();
- // Do we have any embedded pictures?
- // (They're a different CTPicture, under the drawingml namespace)
- pictures = new ArrayList<XWPFPicture>();
- for(XmlObject o : pictTextObjs) {
- for(CTPicture pict : getCTPictures(o)) {
- XWPFPicture picture = new XWPFPicture(pict, this);
- pictures.add(picture);
- }
- }
- }
- /**
- * @deprecated Use {@link XWPFRun#XWPFRun(CTR, IRunBody)}
- */
- public XWPFRun(CTR r, XWPFParagraph p) {
- this(r, (IRunBody)p);
- }
-
- private List<CTPicture> getCTPictures(XmlObject o) {
- List<CTPicture> pictures = new ArrayList<CTPicture>();
- XmlObject[] picts = o.selectPath("declare namespace pic='"+CTPicture.type.getName().getNamespaceURI()+"' .//pic:pic");
- for(XmlObject pict : picts) {
- if(pict instanceof XmlAnyTypeImpl) {
- // Pesky XmlBeans bug - see Bugzilla #49934
- try {
- pict = CTPicture.Factory.parse( pict.toString() );
- } catch(XmlException e) {
- throw new POIXMLException(e);
- }
- }
- if(pict instanceof CTPicture) {
- pictures.add((CTPicture)pict);
- }
- }
- return pictures;
+ // Do we have any embedded pictures?\r
+ // (They're a different CTPicture, under the drawingml namespace)\r
+ pictures = new ArrayList<XWPFPicture>();\r
+ for (XmlObject o : pictTextObjs) {\r
+ for (CTPicture pict : getCTPictures(o)) {\r
+ XWPFPicture picture = new XWPFPicture(pict, this);\r
+ pictures.add(picture);\r
+ }\r
+ }\r
+ }\r
+\r
+ ;\r
+\r
+ /**\r
+ * @deprecated Use {@link XWPFRun#XWPFRun(CTR, IRunBody)}\r
+ */\r
+ public XWPFRun(CTR r, XWPFParagraph p) {\r
+ this(r, (IRunBody) p);\r
+ }\r
+\r
+ /**\r
+ * Add the xml:spaces="preserve" attribute if the string has leading or trailing white spaces\r
+ *\r
+ * @param xs the string to check\r
+ */\r
+ static void preserveSpaces(XmlString xs) {\r
+ String text = xs.getStringValue();\r
+ if (text != null && (text.startsWith(" ") || text.endsWith(" "))) {\r
+ XmlCursor c = xs.newCursor();\r
+ c.toNextToken();\r
+ c.insertAttributeWithValue(new QName("http://www.w3.org/XML/1998/namespace", "space"), "preserve");\r
+ c.dispose();\r
+ }\r
+ }\r
+\r
+ private List<CTPicture> getCTPictures(XmlObject o) {\r
+ List<CTPicture> pictures = new ArrayList<CTPicture>();\r
+ XmlObject[] picts = o.selectPath("declare namespace pic='" + CTPicture.type.getName().getNamespaceURI() + "' .//pic:pic");\r
+ for (XmlObject pict : picts) {\r
+ if (pict instanceof XmlAnyTypeImpl) {\r
+ // Pesky XmlBeans bug - see Bugzilla #49934\r
+ try {\r
+ pict = CTPicture.Factory.parse(pict.toString());\r
+ } catch (XmlException e) {\r
+ throw new POIXMLException(e);\r
+ }\r
+ }\r
+ if (pict instanceof CTPicture) {\r
+ pictures.add((CTPicture) pict);\r
+ }\r
+ }\r
+ return pictures;\r
}
-
- /**
- * Get the currently used CTR object
- * @return ctr object
- */
- @Internal
+\r
+ /**\r
+ * Get the currently used CTR object\r
+ *\r
+ * @return ctr object\r
+ */\r
+ @Internal\r
public CTR getCTR() {
return run;
}
-
- /**
- * Get the currently referenced paragraph/SDT object
- * @return current parent
- */
- public IRunBody getParent() {
- return parent;
- }
- /**
- * Get the currently referenced paragraph, or null if a SDT object
- * @deprecated use {@link XWPFRun#getParent()} instead
- */
- public XWPFParagraph getParagraph() {
- if (parent instanceof XWPFParagraph)
- return (XWPFParagraph)parent;
- return null;
- }
-
- /**
- * @return The {@link XWPFDocument} instance, this run belongs to, or
- * <code>null</code> if parent structure (paragraph > document) is not properly set.
- */
- public XWPFDocument getDocument() {
- if (parent != null) {
+\r
+ /**\r
+ * Get the currently referenced paragraph/SDT object\r
+ *\r
+ * @return current parent\r
+ */\r
+ public IRunBody getParent() {\r
+ return parent;\r
+ }\r
+\r
+ /**\r
+ * Get the currently referenced paragraph, or null if a SDT object\r
+ *\r
+ * @deprecated use {@link XWPFRun#getParent()} instead\r
+ */\r
+ public XWPFParagraph getParagraph() {\r
+ if (parent instanceof XWPFParagraph)\r
+ return (XWPFParagraph) parent;\r
+ return null;\r
+ }\r
+\r
+ /**\r
+ * @return The {@link XWPFDocument} instance, this run belongs to, or\r
+ * <code>null</code> if parent structure (paragraph > document) is not properly set.\r
+ */\r
+ public XWPFDocument getDocument() {\r
+ if (parent != null) {\r
return parent.getDocument();
}
return null;
}
/**
- * For isBold, isItalic etc
- */
- private boolean isCTOnOff(CTOnOff onoff) {
- if(! onoff.isSetVal())
- return true;
- if(onoff.getVal() == STOnOff.ON)
- return true;
- if(onoff.getVal() == STOnOff.TRUE)
- return true;
- return false;
- }
+ * For isBold, isItalic etc\r
+ */\r
+ private boolean isCTOnOff(CTOnOff onoff) {\r
+ if (!onoff.isSetVal())\r
+ return true;\r
+ if (onoff.getVal() == STOnOff.ON)\r
+ return true;\r
+ if (onoff.getVal() == STOnOff.TRUE)\r
+ return true;\r
+ return false;\r
+ }\r
/**
* Whether the bold property shall be applied to all non-complex script
* characters in the contents of this run when displayed in a document
*
* @return <code>true</code> if the bold property is applied
- */
- public boolean isBold() {
- CTRPr pr = run.getRPr();
- if(pr == null || !pr.isSetB()) {
- return false;
- }
- return isCTOnOff(pr.getB());
+ */\r
+ public boolean isBold() {\r
+ CTRPr pr = run.getRPr();\r
+ if (pr == null || !pr.isSetB()) {\r
+ return false;\r
+ }\r
+ return isCTOnOff(pr.getB());\r
}
-
- /**
- * Whether the bold property shall be applied to all non-complex script
- * characters in the contents of this run when displayed in a document.
- * <p>
- * This formatting property is a toggle property, which specifies that its
- * behavior differs between its use within a style definition and its use as
+\r
+ /**\r
+ * Whether the bold property shall be applied to all non-complex script\r
+ * characters in the contents of this run when displayed in a document.\r
+ * <p>\r
+ * This formatting property is a toggle property, which specifies that its\r
+ * behavior differs between its use within a style definition and its use as\r
* direct formatting. When used as part of a style definition, setting this
* property shall toggle the current state of that property as specified up
* to this point in the hierarchy (i.e. applied to not applied, and vice
}
/**
- * Get text color. The returned value is a string in the hex form "RRGGBB".
- */
- public String getColor() {
- String color = null;
- if (run.isSetRPr()) {
- CTRPr pr = run.getRPr();
- if (pr.isSetColor()) {
- CTColor clr = pr.getColor();
- color = clr.xgetVal().getStringValue();
- }
- }
- return color;
- }
-
- /**
- * Set text color.
- * @param rgbStr - the desired color, in the hex form "RRGGBB".
- */
- public void setColor(String rgbStr) {
+ * Get text color. The returned value is a string in the hex form "RRGGBB".\r
+ */\r
+ public String getColor() {\r
+ String color = null;\r
+ if (run.isSetRPr()) {\r
+ CTRPr pr = run.getRPr();\r
+ if (pr.isSetColor()) {\r
+ CTColor clr = pr.getColor();\r
+ color = clr.xgetVal().getStringValue();\r
+ }\r
+ }\r
+ return color;\r
+ }\r
+\r
+ /**\r
+ * Set text color.\r
+ *\r
+ * @param rgbStr - the desired color, in the hex form "RRGGBB".\r
+ */\r
+ public void setColor(String rgbStr) {\r
CTRPr pr = run.isSetRPr() ? run.getRPr() : run.addNewRPr();
CTColor color = pr.isSetColor() ? pr.getColor() : pr.addNewColor();
color.setVal(rgbStr);
/**
* Sets the text of this text run
*
- * @param value the literal text which shall be displayed in the document
- */
- public void setText(String value) {
- setText(value,run.sizeOfTArray());
- }
-
- /**
- * Sets the text of this text run in the
- *
- * @param value the literal text which shall be displayed in the document
- * @param pos - position in the text array (NB: 0 based)
- */
- public void setText(String value, int pos) {
- if(pos > run.sizeOfTArray()) throw new ArrayIndexOutOfBoundsException("Value too large for the parameter position in XWPFRun.setText(String value,int pos)");
- CTText t = (pos < run.sizeOfTArray() && pos >= 0) ? run.getTArray(pos) : run.addNewT();
- t.setStringValue(value);
- preserveSpaces(t);
+ * @param value the literal text which shall be displayed in the document\r
+ */\r
+ public void setText(String value) {\r
+ setText(value, run.sizeOfTArray());\r
+ }\r
+\r
+ /**\r
+ * Sets the text of this text run in the\r
+ *\r
+ * @param value the literal text which shall be displayed in the document\r
+ * @param pos - position in the text array (NB: 0 based)\r
+ */\r
+ public void setText(String value, int pos) {\r
+ if (pos > run.sizeOfTArray())\r
+ throw new ArrayIndexOutOfBoundsException("Value too large for the parameter position in XWPFRun.setText(String value,int pos)");\r
+ CTText t = (pos < run.sizeOfTArray() && pos >= 0) ? run.getTArray(pos) : run.addNewT();\r
+ t.setStringValue(value);\r
+ preserveSpaces(t);\r
}
/**
* characters in the contents of this run when displayed in a document.
*
* @return <code>true</code> if the italic property is applied
- */
- public boolean isItalic() {
- CTRPr pr = run.getRPr();
- if(pr == null || !pr.isSetI())
- return false;
- return isCTOnOff(pr.getI());
- }
+ */\r
+ public boolean isItalic() {\r
+ CTRPr pr = run.getRPr();\r
+ if (pr == null || !pr.isSetI())\r
+ return false;\r
+ return isCTOnOff(pr.getI());\r
+ }\r
/**
* Whether the bold property shall be applied to all non-complex script
*
* @return the Underline pattern applyed to this run
* @see UnderlinePatterns
- */
- public UnderlinePatterns getUnderline() {
- CTRPr pr = run.getRPr();
- return (pr != null && pr.isSetU() && pr.getU().getVal() != null)
- ? UnderlinePatterns.valueOf(pr.getU().getVal().intValue())
- : UnderlinePatterns.NONE;
- }
-
+ */\r
+ public UnderlinePatterns getUnderline() {\r
+ CTRPr pr = run.getRPr();\r
+ return (pr != null && pr.isSetU() && pr.getU().getVal() != null)\r
+ ? UnderlinePatterns.valueOf(pr.getU().getVal().intValue())\r
+ : UnderlinePatterns.NONE;\r
+ }\r
+\r
/**
* Specifies that the contents of this run should be displayed along with an
* underline appearing directly below the character heigh
* horizontal line through the center of the line.
*
* @return <code>true</code> if the strike property is applied
- */
- public boolean isStrikeThrough() {
- CTRPr pr = run.getRPr();
- if(pr == null || !pr.isSetStrike())
- return false;
- return isCTOnOff(pr.getStrike());
- }
- @Deprecated
- public boolean isStrike() {
- return isStrikeThrough();
- }
- /**
- * Specifies that the contents of this run shall be displayed with a double
- * horizontal line through the center of the line.
- *
- * @return <code>true</code> if the double strike property is applied
- */
- public boolean isDoubleStrikeThrough() {
- CTRPr pr = run.getRPr();
- if(pr == null || !pr.isSetDstrike())
- return false;
- return isCTOnOff(pr.getDstrike());
- }
-
- /**
- * Specifies that the contents of this run shall be displayed with a single
+ */\r
+ public boolean isStrikeThrough() {\r
+ CTRPr pr = run.getRPr();\r
+ if (pr == null || !pr.isSetStrike())\r
+ return false;\r
+ return isCTOnOff(pr.getStrike());\r
+ }\r
+\r
+ /**\r
+ * Specifies that the contents of this run shall be displayed with a single\r
* horizontal line through the center of the line.
* <p/>
* This formatting property is a toggle property, which specifies that its
*/
public void setStrikeThrough(boolean value) {
CTRPr pr = run.isSetRPr() ? run.getRPr() : run.addNewRPr();
- CTOnOff strike = pr.isSetStrike() ? pr.getStrike() : pr.addNewStrike();
- strike.setVal(value ? STOnOff.TRUE : STOnOff.FALSE);
- }
- @Deprecated
- public void setStrike(boolean value) {
- setStrikeThrough(value);
- }
- /**
- * Specifies that the contents of this run shall be displayed with a
- * double horizontal line through the center of the line.
- * @see #setStrikeThrough(boolean) for the rules about this
- */
- public void setDoubleStrikethrough(boolean value) {
+ CTOnOff strike = pr.isSetStrike() ? pr.getStrike() : pr.addNewStrike();\r
+ strike.setVal(value ? STOnOff.TRUE : STOnOff.FALSE);\r
+ }\r
+\r
+ @Deprecated\r
+ public boolean isStrike() {\r
+ return isStrikeThrough();\r
+ }\r
+\r
+ @Deprecated\r
+ public void setStrike(boolean value) {\r
+ setStrikeThrough(value);\r
+ }\r
+\r
+ /**\r
+ * Specifies that the contents of this run shall be displayed with a double\r
+ * horizontal line through the center of the line.\r
+ *\r
+ * @return <code>true</code> if the double strike property is applied\r
+ */\r
+ public boolean isDoubleStrikeThrough() {\r
+ CTRPr pr = run.getRPr();\r
+ if (pr == null || !pr.isSetDstrike())\r
+ return false;\r
+ return isCTOnOff(pr.getDstrike());\r
+ }\r
+\r
+ /**\r
+ * Specifies that the contents of this run shall be displayed with a\r
+ * double horizontal line through the center of the line.\r
+ *\r
+ * @see #setStrikeThrough(boolean) for the rules about this\r
+ */\r
+ public void setDoubleStrikethrough(boolean value) {\r
CTRPr pr = run.isSetRPr() ? run.getRPr() : run.addNewRPr();
CTOnOff dstrike = pr.isSetDstrike() ? pr.getDstrike() : pr.addNewDstrike();
dstrike.setVal(value ? STOnOff.TRUE : STOnOff.FALSE);
}
-
- public boolean isSmallCaps() {
- CTRPr pr = run.getRPr();
- if(pr == null || !pr.isSetSmallCaps())
- return false;
- return isCTOnOff(pr.getSmallCaps());
- }
- public void setSmallCaps(boolean value) {
- CTRPr pr = run.isSetRPr() ? run.getRPr() : run.addNewRPr();
- CTOnOff caps = pr.isSetSmallCaps() ? pr.getSmallCaps() : pr.addNewSmallCaps();
- caps.setVal(value ? STOnOff.TRUE : STOnOff.FALSE);
- }
- public boolean isCapitalized() {
- CTRPr pr = run.getRPr();
- if(pr == null || !pr.isSetCaps())
- return false;
- return isCTOnOff(pr.getCaps());
- }
- public void setCapitalized(boolean value) {
- CTRPr pr = run.isSetRPr() ? run.getRPr() : run.addNewRPr();
- CTOnOff caps = pr.isSetCaps() ? pr.getCaps() : pr.addNewCaps();
- caps.setVal(value ? STOnOff.TRUE : STOnOff.FALSE);
- }
-
- public boolean isShadowed() {
- CTRPr pr = run.getRPr();
- if(pr == null || !pr.isSetShadow())
- return false;
- return isCTOnOff(pr.getShadow());
- }
- public void setShadow(boolean value) {
- CTRPr pr = run.isSetRPr() ? run.getRPr() : run.addNewRPr();
- CTOnOff shadow = pr.isSetShadow() ? pr.getShadow() : pr.addNewShadow();
- shadow.setVal(value ? STOnOff.TRUE : STOnOff.FALSE);
- }
-
- public boolean isImprinted() {
- CTRPr pr = run.getRPr();
- if(pr == null || !pr.isSetImprint())
- return false;
- return isCTOnOff(pr.getImprint());
- }
- public void setImprinted(boolean value) {
- CTRPr pr = run.isSetRPr() ? run.getRPr() : run.addNewRPr();
- CTOnOff imprinted = pr.isSetImprint() ? pr.getImprint() : pr.addNewImprint();
- imprinted.setVal(value ? STOnOff.TRUE : STOnOff.FALSE);
- }
-
- public boolean isEmbossed() {
- CTRPr pr = run.getRPr();
- if(pr == null || !pr.isSetEmboss())
- return false;
- return isCTOnOff(pr.getEmboss());
- }
- public void setEmbossed(boolean value) {
- CTRPr pr = run.isSetRPr() ? run.getRPr() : run.addNewRPr();
- CTOnOff emboss = pr.isSetEmboss() ? pr.getEmboss() : pr.addNewEmboss();
- emboss.setVal(value ? STOnOff.TRUE : STOnOff.FALSE);
- }
-
- /**
- * Specifies the alignment which shall be applied to the contents of this
- * run in relation to the default appearance of the run's text.
+\r
+ public boolean isSmallCaps() {\r
+ CTRPr pr = run.getRPr();\r
+ if (pr == null || !pr.isSetSmallCaps())\r
+ return false;\r
+ return isCTOnOff(pr.getSmallCaps());\r
+ }\r
+\r
+ public void setSmallCaps(boolean value) {\r
+ CTRPr pr = run.isSetRPr() ? run.getRPr() : run.addNewRPr();\r
+ CTOnOff caps = pr.isSetSmallCaps() ? pr.getSmallCaps() : pr.addNewSmallCaps();\r
+ caps.setVal(value ? STOnOff.TRUE : STOnOff.FALSE);\r
+ }\r
+\r
+ public boolean isCapitalized() {\r
+ CTRPr pr = run.getRPr();\r
+ if (pr == null || !pr.isSetCaps())\r
+ return false;\r
+ return isCTOnOff(pr.getCaps());\r
+ }\r
+\r
+ public void setCapitalized(boolean value) {\r
+ CTRPr pr = run.isSetRPr() ? run.getRPr() : run.addNewRPr();\r
+ CTOnOff caps = pr.isSetCaps() ? pr.getCaps() : pr.addNewCaps();\r
+ caps.setVal(value ? STOnOff.TRUE : STOnOff.FALSE);\r
+ }\r
+\r
+ public boolean isShadowed() {\r
+ CTRPr pr = run.getRPr();\r
+ if (pr == null || !pr.isSetShadow())\r
+ return false;\r
+ return isCTOnOff(pr.getShadow());\r
+ }\r
+\r
+ public void setShadow(boolean value) {\r
+ CTRPr pr = run.isSetRPr() ? run.getRPr() : run.addNewRPr();\r
+ CTOnOff shadow = pr.isSetShadow() ? pr.getShadow() : pr.addNewShadow();\r
+ shadow.setVal(value ? STOnOff.TRUE : STOnOff.FALSE);\r
+ }\r
+\r
+ public boolean isImprinted() {\r
+ CTRPr pr = run.getRPr();\r
+ if (pr == null || !pr.isSetImprint())\r
+ return false;\r
+ return isCTOnOff(pr.getImprint());\r
+ }\r
+\r
+ public void setImprinted(boolean value) {\r
+ CTRPr pr = run.isSetRPr() ? run.getRPr() : run.addNewRPr();\r
+ CTOnOff imprinted = pr.isSetImprint() ? pr.getImprint() : pr.addNewImprint();\r
+ imprinted.setVal(value ? STOnOff.TRUE : STOnOff.FALSE);\r
+ }\r
+\r
+ public boolean isEmbossed() {\r
+ CTRPr pr = run.getRPr();\r
+ if (pr == null || !pr.isSetEmboss())\r
+ return false;\r
+ return isCTOnOff(pr.getEmboss());\r
+ }\r
+\r
+ public void setEmbossed(boolean value) {\r
+ CTRPr pr = run.isSetRPr() ? run.getRPr() : run.addNewRPr();\r
+ CTOnOff emboss = pr.isSetEmboss() ? pr.getEmboss() : pr.addNewEmboss();\r
+ emboss.setVal(value ? STOnOff.TRUE : STOnOff.FALSE);\r
+ }\r
+\r
+ /**\r
+ * Specifies the alignment which shall be applied to the contents of this\r
+ * run in relation to the default appearance of the run's text.\r
* This allows the text to be repositioned as subscript or superscript without
* altering the font size of the run properties.
*
CTVerticalAlignRun ctValign = pr.isSetVertAlign() ? pr.getVertAlign() : pr.addNewVertAlign();
ctValign.setVal(STVerticalAlignRun.Enum.forInt(valign.getValue()));
}
-
- public int getKerning() {
- CTRPr pr = run.getRPr();
- if(pr == null || !pr.isSetKern())
- return 0;
- return pr.getKern().getVal().intValue();
- }
- public void setKerning(int kern) {
- CTRPr pr = run.isSetRPr() ? run.getRPr() : run.addNewRPr();
- CTHpsMeasure kernmes = pr.isSetKern() ? pr.getKern() : pr.addNewKern();
- kernmes.setVal(BigInteger.valueOf(kern));
- }
-
- public int getCharacterSpacing() {
- CTRPr pr = run.getRPr();
- if(pr == null || !pr.isSetSpacing())
- return 0;
- return pr.getSpacing().getVal().intValue();
- }
- public void setCharacterSpacing(int twips) {
- CTRPr pr = run.isSetRPr() ? run.getRPr() : run.addNewRPr();
- CTSignedTwipsMeasure spc = pr.isSetSpacing() ? pr.getSpacing() : pr.addNewSpacing();
- spc.setVal(BigInteger.valueOf(twips));
- }
-
- /**
- * Gets the fonts which shall be used to display the text contents of
- * this run. Specifies a font which shall be used to format all characters
+\r
+ public int getKerning() {\r
+ CTRPr pr = run.getRPr();\r
+ if (pr == null || !pr.isSetKern())\r
+ return 0;\r
+ return pr.getKern().getVal().intValue();\r
+ }\r
+\r
+ public void setKerning(int kern) {\r
+ CTRPr pr = run.isSetRPr() ? run.getRPr() : run.addNewRPr();\r
+ CTHpsMeasure kernmes = pr.isSetKern() ? pr.getKern() : pr.addNewKern();\r
+ kernmes.setVal(BigInteger.valueOf(kern));\r
+ }\r
+\r
+ public int getCharacterSpacing() {\r
+ CTRPr pr = run.getRPr();\r
+ if (pr == null || !pr.isSetSpacing())\r
+ return 0;\r
+ return pr.getSpacing().getVal().intValue();\r
+ }\r
+\r
+ public void setCharacterSpacing(int twips) {\r
+ CTRPr pr = run.isSetRPr() ? run.getRPr() : run.addNewRPr();\r
+ CTSignedTwipsMeasure spc = pr.isSetSpacing() ? pr.getSpacing() : pr.addNewSpacing();\r
+ spc.setVal(BigInteger.valueOf(twips));\r
+ }\r
+\r
+ /**\r
+ * Gets the fonts which shall be used to display the text contents of\r
+ * this run. Specifies a font which shall be used to format all characters\r
* in the ASCII range (0 - 127) within the parent run
*
* @return a string representing the font family
*/
- public String getFontFamily() {
- return getFontFamily(null);
- }
- /**
- * Alias for {@link #getFontFamily()}
- */
- public String getFontName() {
+ public String getFontFamily() {\r
+ return getFontFamily(null);\r
+ }\r
+\r
+ /**\r
+ * Specifies the fonts which shall be used to display the text contents of\r
+ * this run. Specifies a font which shall be used to format all characters\r
+ * in the ASCII range (0 - 127) within the parent run.\r
+ * <p/>\r
+ * Also sets the other font ranges, if they haven't been set before\r
+ *\r
+ * @param fontFamily\r
+ * @see FontCharRange\r
+ */\r
+ public void setFontFamily(String fontFamily) {\r
+ setFontFamily(fontFamily, null);\r
+ }\r
+\r
+ /**\r
+ * Alias for {@link #getFontFamily()}\r
+ */\r
+ public String getFontName() {\r
return getFontFamily();
}
/**
* Gets the font family for the specified font char range.
- * If fcr is null, the font char range "ascii" is used
- *
- * @param fcr the font char range, defaults to "ansi"
- * @return a string representing the font famil
- */
- public String getFontFamily(FontCharRange fcr) {
- CTRPr pr = run.getRPr();
- if (pr == null || !pr.isSetRFonts()) return null;
-
- CTFonts fonts = pr.getRFonts();
- switch (fcr == null ? FontCharRange.ascii : fcr) {
- default:
- case ascii:
- return fonts.getAscii();
- case cs:
- return fonts.getCs();
- case eastAsia:
- return fonts.getEastAsia();
- case hAnsi:
- return fonts.getHAnsi();
- }
- }
-
-
- /**
- * Specifies the fonts which shall be used to display the text contents of
- * this run. Specifies a font which shall be used to format all characters
- * in the ASCII range (0 - 127) within the parent run.
- *
- * Also sets the other font ranges, if they haven't been set before
- *
- * @param fontFamily
- *
- * @see FontCharRange
- */
- public void setFontFamily(String fontFamily) {
- setFontFamily(fontFamily, null);
- }
-
- /**
- * Specifies the fonts which shall be used to display the text contents of
- * this run. The default handling for fcr == null is to overwrite the
- * ascii font char range with the given font family and also set all not
- * specified font ranges
- *
- * @param fontFamily
- * @param fcr FontCharRange or null for default handling
- */
- public void setFontFamily(String fontFamily, FontCharRange fcr) {
- CTRPr pr = run.isSetRPr() ? run.getRPr() : run.addNewRPr();
- CTFonts fonts = pr.isSetRFonts() ? pr.getRFonts() : pr.addNewRFonts();
-
- if (fcr == null) {
- fonts.setAscii(fontFamily);
- if (!fonts.isSetHAnsi()) {
+ * If fcr is null, the font char range "ascii" is used\r
+ *\r
+ * @param fcr the font char range, defaults to "ansi"\r
+ * @return a string representing the font famil\r
+ */\r
+ public String getFontFamily(FontCharRange fcr) {\r
+ CTRPr pr = run.getRPr();\r
+ if (pr == null || !pr.isSetRFonts()) return null;\r
+\r
+ CTFonts fonts = pr.getRFonts();\r
+ switch (fcr == null ? FontCharRange.ascii : fcr) {\r
+ default:\r
+ case ascii:\r
+ return fonts.getAscii();\r
+ case cs:\r
+ return fonts.getCs();\r
+ case eastAsia:\r
+ return fonts.getEastAsia();\r
+ case hAnsi:\r
+ return fonts.getHAnsi();\r
+ }\r
+ }\r
+\r
+ /**\r
+ * Specifies the fonts which shall be used to display the text contents of\r
+ * this run. The default handling for fcr == null is to overwrite the\r
+ * ascii font char range with the given font family and also set all not\r
+ * specified font ranges\r
+ *\r
+ * @param fontFamily\r
+ * @param fcr FontCharRange or null for default handling\r
+ */\r
+ public void setFontFamily(String fontFamily, FontCharRange fcr) {\r
+ CTRPr pr = run.isSetRPr() ? run.getRPr() : run.addNewRPr();\r
+ CTFonts fonts = pr.isSetRFonts() ? pr.getRFonts() : pr.addNewRFonts();\r
+\r
+ if (fcr == null) {\r
+ fonts.setAscii(fontFamily);\r
+ if (!fonts.isSetHAnsi()) {\r
fonts.setHAnsi(fontFamily);
}
if (!fonts.isSetCs()) {
}
if (!fonts.isSetEastAsia()) {
fonts.setEastAsia(fontFamily);
- }
- } else {
- switch (fcr) {
- case ascii:
- fonts.setAscii(fontFamily);
- break;
- case cs:
- fonts.setCs(fontFamily);
- break;
- case eastAsia:
- fonts.setEastAsia(fontFamily);
- break;
- case hAnsi:
- fonts.setHAnsi(fontFamily);
- break;
- }
- }
- }
+ }\r
+ } else {\r
+ switch (fcr) {\r
+ case ascii:\r
+ fonts.setAscii(fontFamily);\r
+ break;\r
+ case cs:\r
+ fonts.setCs(fontFamily);\r
+ break;\r
+ case eastAsia:\r
+ fonts.setEastAsia(fontFamily);\r
+ break;\r
+ case hAnsi:\r
+ fonts.setHAnsi(fontFamily);\r
+ break;\r
+ }\r
+ }\r
+ }\r
/**
* Specifies the font size which shall be applied to all non complex script
* be used for non complex script characters.
* </p>
*
- * @param size
- */
- public void setFontSize(int size) {
- BigInteger bint=new BigInteger(""+size);
- CTRPr pr = run.isSetRPr() ? run.getRPr() : run.addNewRPr();
- CTHpsMeasure ctSize = pr.isSetSz() ? pr.getSz() : pr.addNewSz();
- ctSize.setVal(bint.multiply(new BigInteger("2")));
+ * @param size\r
+ */\r
+ public void setFontSize(int size) {\r
+ BigInteger bint = new BigInteger("" + size);\r
+ CTRPr pr = run.isSetRPr() ? run.getRPr() : run.addNewRPr();\r
+ CTHpsMeasure ctSize = pr.isSetSz() ? pr.getSz() : pr.addNewSz();\r
+ ctSize.setVal(bint.multiply(new BigInteger("2")));\r
}
/**
* contents of this run.
* </p>
*
- * @param val
- */
- public void setTextPosition(int val) {
- BigInteger bint=new BigInteger(""+val);
- CTRPr pr = run.isSetRPr() ? run.getRPr() : run.addNewRPr();
- CTSignedHpsMeasure position = pr.isSetPosition() ? pr.getPosition() : pr.addNewPosition();
- position.setVal(bint);
+ * @param val\r
+ */\r
+ public void setTextPosition(int val) {\r
+ BigInteger bint = new BigInteger("" + val);\r
+ CTRPr pr = run.isSetRPr() ? run.getRPr() : run.addNewRPr();\r
+ CTSignedHpsMeasure position = pr.isSetPosition() ? pr.getPosition() : pr.addNewPosition();\r
+ position.setVal(bint);\r
+ }\r
+\r
+ /**\r
+ *\r
+ */\r
+ public void removeBreak() {\r
+ // TODO\r
}
-
- /**
- *
- */
- public void removeBreak() {
- // TODO
- }
-
- /**
- * Specifies that a break shall be placed at the current location in the run
- * content.
- * A break is a special character which is used to override the
- * normal line breaking that would be performed based on the normal layout
- * of the document's contents.
- * @see #addCarriageReturn()
- */
- public void addBreak() {
- run.addNewBr();
- }
-
- /**
- * Specifies that a break shall be placed at the current location in the run
+\r
+ /**\r
+ * Specifies that a break shall be placed at the current location in the run\r
+ * content.\r
+ * A break is a special character which is used to override the\r
+ * normal line breaking that would be performed based on the normal layout\r
+ * of the document's contents.\r
+ *\r
+ * @see #addCarriageReturn()\r
+ */\r
+ public void addBreak() {\r
+ run.addNewBr();\r
+ }\r
+\r
+ /**\r
+ * Specifies that a break shall be placed at the current location in the run\r
* content.
* A break is a special character which is used to override the
* normal line breaking that would be performed based on the normal layout
* of the document's contents.
* <p>
* The behavior of this break character (the
- * location where text shall be restarted after this break) shall be
- * determined by its type values.
- * </p>
- * @see BreakType
- */
- public void addBreak(BreakType type){
- CTBr br=run.addNewBr();
- br.setType(STBrType.Enum.forInt(type.getValue()));
- }
-
+ * location where text shall be restarted after this break) shall be\r
+ * determined by its type values.\r
+ * </p>\r
+ *\r
+ * @see BreakType\r
+ */\r
+ public void addBreak(BreakType type) {\r
+ CTBr br = run.addNewBr();\r
+ br.setType(STBrType.Enum.forInt(type.getValue()));\r
+ }\r
+\r
/**
* Specifies that a break shall be placed at the current location in the run
* content. A break is a special character which is used to override the
* of the document's contents.
* <p>
* The behavior of this break character (the
- * location where text shall be restarted after this break) shall be
- * determined by its type (in this case is BreakType.TEXT_WRAPPING as default) and clear attribute values.
- * </p>
- * @see BreakClear
- */
- public void addBreak(BreakClear clear){
- CTBr br=run.addNewBr();
- br.setType(STBrType.Enum.forInt(BreakType.TEXT_WRAPPING.getValue()));
- br.setClear(STBrClear.Enum.forInt(clear.getValue()));
+ * location where text shall be restarted after this break) shall be\r
+ * determined by its type (in this case is BreakType.TEXT_WRAPPING as default) and clear attribute values.\r
+ * </p>\r
+ *\r
+ * @see BreakClear\r
+ */\r
+ public void addBreak(BreakClear clear) {\r
+ CTBr br = run.addNewBr();\r
+ br.setType(STBrType.Enum.forInt(BreakType.TEXT_WRAPPING.getValue()));\r
+ br.setClear(STBrClear.Enum.forInt(clear.getValue()));\r
+ }\r
+\r
+ /**\r
+ * Specifies that a tab shall be placed at the current location in\r
+ * the run content.\r
+ */\r
+ public void addTab() {\r
+ run.addNewTab();\r
}
-
- /**
- * Specifies that a tab shall be placed at the current location in
- * the run content.
- */
- public void addTab() {
- run.addNewTab();
- }
-
- public void removeTab() {
- //TODO
- }
-
- /**
- * Specifies that a carriage return shall be placed at the
+\r
+ public void removeTab() {\r
+ //TODO\r
+ }\r
+\r
+ /**\r
+ * Specifies that a carriage return shall be placed at the\r
* current location in the run content.
* A carriage return is used to end the current line of text in
* Wordprocess.
public void addCarriageReturn() {
run.addNewCr();
}
-
- public void removeCarriageReturn() {
- //TODO
- }
-
- /**
- * Adds a picture to the run. This method handles
- * attaching the picture data to the overall file.
- *
- * @see org.apache.poi.xwpf.usermodel.Document#PICTURE_TYPE_EMF
- * @see org.apache.poi.xwpf.usermodel.Document#PICTURE_TYPE_WMF
- * @see org.apache.poi.xwpf.usermodel.Document#PICTURE_TYPE_PICT
- * @see org.apache.poi.xwpf.usermodel.Document#PICTURE_TYPE_JPEG
- * @see org.apache.poi.xwpf.usermodel.Document#PICTURE_TYPE_PNG
- * @see org.apache.poi.xwpf.usermodel.Document#PICTURE_TYPE_DIB
- *
- * @param pictureData The raw picture data
- * @param pictureType The type of the picture, eg {@link Document#PICTURE_TYPE_JPEG}
- * @param width width in EMUs. To convert to / from points use {@link org.apache.poi.util.Units}
- * @param height height in EMUs. To convert to / from points use {@link org.apache.poi.util.Units}
- * @throws org.apache.poi.openxml4j.exceptions.InvalidFormatException
- * @throws IOException
- */
- public XWPFPicture addPicture(InputStream pictureData, int pictureType, String filename, int width, int height)
- throws InvalidFormatException, IOException {
- XWPFDocument doc = parent.getDocument();
-
- // Add the picture + relationship
+\r
+ public void removeCarriageReturn() {\r
+ //TODO\r
+ }\r
+\r
+ /**\r
+ * Adds a picture to the run. This method handles\r
+ * attaching the picture data to the overall file.\r
+ *\r
+ * @param pictureData The raw picture data\r
+ * @param pictureType The type of the picture, eg {@link Document#PICTURE_TYPE_JPEG}\r
+ * @param width width in EMUs. To convert to / from points use {@link org.apache.poi.util.Units}\r
+ * @param height height in EMUs. To convert to / from points use {@link org.apache.poi.util.Units}\r
+ * @throws org.apache.poi.openxml4j.exceptions.InvalidFormatException\r
+ * @throws IOException\r
+ * @see org.apache.poi.xwpf.usermodel.Document#PICTURE_TYPE_EMF\r
+ * @see org.apache.poi.xwpf.usermodel.Document#PICTURE_TYPE_WMF\r
+ * @see org.apache.poi.xwpf.usermodel.Document#PICTURE_TYPE_PICT\r
+ * @see org.apache.poi.xwpf.usermodel.Document#PICTURE_TYPE_JPEG\r
+ * @see org.apache.poi.xwpf.usermodel.Document#PICTURE_TYPE_PNG\r
+ * @see org.apache.poi.xwpf.usermodel.Document#PICTURE_TYPE_DIB\r
+ */\r
+ public XWPFPicture addPicture(InputStream pictureData, int pictureType, String filename, int width, int height)\r
+ throws InvalidFormatException, IOException {\r
+ XWPFDocument doc = parent.getDocument();\r
+\r
+ // Add the picture + relationship\r
String relationId = doc.addPictureData(pictureData, pictureType);
XWPFPictureData picData = (XWPFPictureData) doc.getRelationById(relationId);
try {
CTDrawing drawing = run.addNewDrawing();
CTInline inline = drawing.addNewInline();
-
- // Do the fiddly namespace bits on the inline
- // (We need full control of what goes where and as what)
- String xml =
- "<a:graphic xmlns:a=\"" + CTGraphicalObject.type.getName().getNamespaceURI() + "\">" +
- "<a:graphicData uri=\"" + CTPicture.type.getName().getNamespaceURI() + "\">" +
- "<pic:pic xmlns:pic=\"" + CTPicture.type.getName().getNamespaceURI() + "\" />" +
- "</a:graphicData>" +
- "</a:graphic>";
- inline.set(XmlToken.Factory.parse(xml));
-
- // Setup the inline
+\r
+ // Do the fiddly namespace bits on the inline\r
+ // (We need full control of what goes where and as what)\r
+ String xml =\r
+ "<a:graphic xmlns:a=\"" + CTGraphicalObject.type.getName().getNamespaceURI() + "\">" +\r
+ "<a:graphicData uri=\"" + CTPicture.type.getName().getNamespaceURI() + "\">" +\r
+ "<pic:pic xmlns:pic=\"" + CTPicture.type.getName().getNamespaceURI() + "\" />" +\r
+ "</a:graphicData>" +\r
+ "</a:graphic>";\r
+ inline.set(XmlToken.Factory.parse(xml));\r
+\r
+ // Setup the inline\r
inline.setDistT(0);
inline.setDistR(0);
inline.setDistB(0);
CTNonVisualPictureProperties cNvPicPr = nvPicPr.addNewCNvPicPr();
cNvPicPr.addNewPicLocks().setNoChangeAspect(true);
-
- CTBlipFillProperties blipFill = pic.addNewBlipFill();
- CTBlip blip = blipFill.addNewBlip();
- blip.setEmbed( picData.getPackageRelationship().getId() );
- blipFill.addNewStretch().addNewFillRect();
-
- CTShapeProperties spPr = pic.addNewSpPr();
+\r
+ CTBlipFillProperties blipFill = pic.addNewBlipFill();\r
+ CTBlip blip = blipFill.addNewBlip();\r
+ blip.setEmbed(picData.getPackageRelationship().getId());\r
+ blipFill.addNewStretch().addNewFillRect();\r
+\r
+ CTShapeProperties spPr = pic.addNewSpPr();\r
CTTransform2D xfrm = spPr.addNewXfrm();
CTPoint2D off = xfrm.addNewOff();
prstGeom.addNewAvLst();
// Finish up
- XWPFPicture xwpfPicture = new XWPFPicture(pic, this);
- pictures.add(xwpfPicture);
- return xwpfPicture;
- } catch(XmlException e) {
- throw new IllegalStateException(e);
- }
- }
-
- /**
- * Returns the embedded pictures of the run. These
- * are pictures which reference an external,
- * embedded picture image such as a .png or .jpg
- */
- public List<XWPFPicture> getEmbeddedPictures() {
- return pictures;
- }
-
- /**
- * Add the xml:spaces="preserve" attribute if the string has leading or trailing white spaces
- *
- * @param xs the string to check
- */
- static void preserveSpaces(XmlString xs) {
- String text = xs.getStringValue();
- if (text != null && (text.startsWith(" ") || text.endsWith(" "))) {
- XmlCursor c = xs.newCursor();
- c.toNextToken();
- c.insertAttributeWithValue(new QName("http://www.w3.org/XML/1998/namespace", "space"), "preserve");
- c.dispose();
- }
- }
-
- /**
- * Returns the string version of the text
- */
- public String toString() {
- return text();
- }
- /**
- * Returns the string version of the text, with tabs and
- * carriage returns in place of their xml equivalents.
- */
- public String text() {
- StringBuffer text = new StringBuffer();
+ XWPFPicture xwpfPicture = new XWPFPicture(pic, this);\r
+ pictures.add(xwpfPicture);\r
+ return xwpfPicture;\r
+ } catch (XmlException e) {\r
+ throw new IllegalStateException(e);\r
+ }\r
+ }\r
+\r
+ /**\r
+ * Returns the embedded pictures of the run. These\r
+ * are pictures which reference an external,\r
+ * embedded picture image such as a .png or .jpg\r
+ */\r
+ public List<XWPFPicture> getEmbeddedPictures() {\r
+ return pictures;\r
+ }\r
+\r
+ /**\r
+ * Returns the string version of the text\r
+ */\r
+ public String toString() {\r
+ return text();\r
+ }\r
+\r
+ /**\r
+ * Returns the string version of the text, with tabs and\r
+ * carriage returns in place of their xml equivalents.\r
+ */\r
+ public String text() {\r
+ StringBuffer text = new StringBuffer();\r
// Grab the text and tabs of the text run
// Do so in a way that preserves the ordering
// come up as instances of CTText, but we don't want them
// in the normal text output
if (!"w:instrText".equals(tagName)) {
- text.append(((CTText) o).getStringValue());
- }
- }
-
- // Complex type evaluation (currently only for extraction of check boxes)
- if(o instanceof CTFldChar) {
- CTFldChar ctfldChar = ((CTFldChar)o);
- if(ctfldChar.getFldCharType() == STFldCharType.BEGIN) {
- if(ctfldChar.getFfData() != null) {
- for(CTFFCheckBox checkBox : ctfldChar.getFfData().getCheckBoxList()) {
- if(checkBox.getDefault().getVal() == STOnOff.X_1) {
- text.append("|X|");
- } else {
- text.append("|_|");
- }
- }
- }
- }
- }
-
+ text.append(((CTText) o).getStringValue());\r
+ }\r
+ }\r
+\r
+ // Complex type evaluation (currently only for extraction of check boxes)\r
+ if (o instanceof CTFldChar) {\r
+ CTFldChar ctfldChar = ((CTFldChar) o);\r
+ if (ctfldChar.getFldCharType() == STFldCharType.BEGIN) {\r
+ if (ctfldChar.getFfData() != null) {\r
+ for (CTFFCheckBox checkBox : ctfldChar.getFfData().getCheckBoxList()) {\r
+ if (checkBox.getDefault().getVal() == STOnOff.X_1) {\r
+ text.append("|X|");\r
+ } else {\r
+ text.append("|_|");\r
+ }\r
+ }\r
+ }\r
+ }\r
+ }\r
+\r
if (o instanceof CTPTab) {
text.append("\t");
}
}
if ("w:cr".equals(tagName) || "cr".equals(tagName)) {
text.append("\n");
- }
- }
- if (o instanceof CTFtnEdnRef) {
- CTFtnEdnRef ftn = (CTFtnEdnRef)o;
- String footnoteRef = ftn.getDomNode().getLocalName().equals("footnoteReference") ?
- "[footnoteRef:" + ftn.getId().intValue() + "]" : "[endnoteRef:" + ftn.getId().intValue() + "]";
- text.append(footnoteRef);
- }
- }
-
- c.dispose();
-
- // Any picture text?
- if(pictureText != null && pictureText.length() > 0) {
- text.append("\n").append(pictureText);
- }
-
- return text.toString();
- }
-}
+ }\r
+ }\r
+ if (o instanceof CTFtnEdnRef) {\r
+ CTFtnEdnRef ftn = (CTFtnEdnRef) o;\r
+ String footnoteRef = ftn.getDomNode().getLocalName().equals("footnoteReference") ?\r
+ "[footnoteRef:" + ftn.getId().intValue() + "]" : "[endnoteRef:" + ftn.getId().intValue() + "]";\r
+ text.append(footnoteRef);\r
+ }\r
+ }\r
+\r
+ c.dispose();\r
+\r
+ // Any picture text?\r
+ if (pictureText != null && pictureText.length() > 0) {\r
+ text.append("\n").append(pictureText);\r
+ }\r
+\r
+ return text.toString();\r
+ }\r
+\r
+ /**\r
+ * @see <a href="http://msdn.microsoft.com/en-us/library/ff533743(v=office.12).aspx">[MS-OI29500] Run Fonts</a>\r
+ */\r
+ public static enum FontCharRange {\r
+ ascii /* char 0-127 */,\r
+ cs /* complex symbol */,\r
+ eastAsia /* east asia */,\r
+ hAnsi /* high ansi */\r
+ }\r
+}\r
package org.apache.poi.xwpf.usermodel;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTSdtBlock;
-import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTSdtRun;
-
-/**
- * Experimental class to offer rudimentary read-only processing of
- * of StructuredDocumentTags/ContentControl
- *
- * WARNING - APIs expected to change rapidly
- *
- */
-public class XWPFSDT extends AbstractXWPFSDT
- implements IBodyElement, IRunBody, ISDTContents, IRunElement {
- private final ISDTContent content;
-
- public XWPFSDT(CTSdtRun sdtRun, IBody part){
- super(sdtRun.getSdtPr(), part);
- this.content = new XWPFSDTContent(sdtRun.getSdtContent(), part, this);
- }
-
- public XWPFSDT(CTSdtBlock block, IBody part){
- super(block.getSdtPr(), part);
- this.content = new XWPFSDTContent( block.getSdtContent(), part, this);
- }
-
- public ISDTContent getContent(){
- return content;
- }
-
-}
+import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTSdtRun;\r
+\r
+/**\r
+ * Experimental class to offer rudimentary read-only processing of\r
+ * of StructuredDocumentTags/ContentControl\r
+ * <p/>\r
+ * WARNING - APIs expected to change rapidly\r
+ */\r
+public class XWPFSDT extends AbstractXWPFSDT\r
+ implements IBodyElement, IRunBody, ISDTContents, IRunElement {\r
+ private final ISDTContent content;\r
+\r
+ public XWPFSDT(CTSdtRun sdtRun, IBody part) {\r
+ super(sdtRun.getSdtPr(), part);\r
+ this.content = new XWPFSDTContent(sdtRun.getSdtContent(), part, this);\r
+ }\r
+\r
+ public XWPFSDT(CTSdtBlock block, IBody part) {\r
+ super(block.getSdtPr(), part);\r
+ this.content = new XWPFSDTContent(block.getSdtContent(), part, this);\r
+ }\r
+\r
+ public ISDTContent getContent() {\r
+ return content;\r
+ }\r
+\r
+}\r
==================================================================== */
package org.apache.poi.xwpf.usermodel;
-import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTSdtCell;
-
-/**
- * Experimental class to offer rudimentary read-only processing of
- * of StructuredDocumentTags/ContentControl that can appear
- * in a table row as if a table cell.
- * <p>
- * These can contain one or more cells or other SDTs within them.
- *
- * WARNING - APIs expected to change rapidly
- *
- */
-public class XWPFSDTCell extends AbstractXWPFSDT implements ICell {
- private final XWPFSDTContentCell cellContent;
-
- public XWPFSDTCell(CTSdtCell sdtCell, XWPFTableRow xwpfTableRow, IBody part){
- super(sdtCell.getSdtPr(), part);
- cellContent = new XWPFSDTContentCell(sdtCell.getSdtContent(), xwpfTableRow, part);
- }
-
- @Override
- public ISDTContent getContent(){
- return cellContent;
- }
-
-}
+import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTSdtCell;\r
+\r
+/**\r
+ * Experimental class to offer rudimentary read-only processing of\r
+ * of StructuredDocumentTags/ContentControl that can appear\r
+ * in a table row as if a table cell.\r
+ * <p/>\r
+ * These can contain one or more cells or other SDTs within them.\r
+ * <p/>\r
+ * WARNING - APIs expected to change rapidly\r
+ */\r
+public class XWPFSDTCell extends AbstractXWPFSDT implements ICell {\r
+ private final XWPFSDTContentCell cellContent;\r
+\r
+ public XWPFSDTCell(CTSdtCell sdtCell, XWPFTableRow xwpfTableRow, IBody part) {\r
+ super(sdtCell.getSdtPr(), part);\r
+ cellContent = new XWPFSDTContentCell(sdtCell.getSdtContent(), xwpfTableRow, part);\r
+ }\r
+\r
+ @Override\r
+ public ISDTContent getContent() {\r
+ return cellContent;\r
+ }\r
+\r
+}\r
==================================================================== */
package org.apache.poi.xwpf.usermodel;
-import java.util.ArrayList;
-import java.util.List;
-
-
-import org.apache.xmlbeans.XmlCursor;
-import org.apache.xmlbeans.XmlObject;
-import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTP;
-import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTR;
-
-import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTSdtBlock;
-import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTSdtContentBlock;
-import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTSdtContentRun;
-import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTbl;
-
-/**
- * Experimental class to offer rudimentary read-only processing of
- * of the contentblock of an SDT/ContentControl.
- *
- *
- *
- * WARNING - APIs expected to change rapidly
- *
- */
-public class XWPFSDTContent implements ISDTContent {
-
+import java.util.ArrayList;\r
+import java.util.List;\r
+\r
+import org.apache.xmlbeans.XmlCursor;\r
+import org.apache.xmlbeans.XmlObject;\r
+import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTP;\r
+import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTR;\r
+import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTSdtBlock;\r
+import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTSdtContentBlock;\r
+import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTSdtContentRun;\r
+import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTbl;\r
+\r
+/**\r
+ * Experimental class to offer rudimentary read-only processing of\r
+ * of the contentblock of an SDT/ContentControl.\r
+ * <p/>\r
+ * <p/>\r
+ * <p/>\r
+ * WARNING - APIs expected to change rapidly\r
+ */\r
+public class XWPFSDTContent implements ISDTContent {\r
+\r
// private final IBody part;
// private final XWPFDocument document;
private List<XWPFParagraph> paragraphs = new ArrayList<XWPFParagraph>();
private List<XWPFTable> tables = new ArrayList<XWPFTable>();
private List<XWPFRun> runs = new ArrayList<XWPFRun>();
- private List<XWPFSDT> contentControls = new ArrayList<XWPFSDT>();
- private List<ISDTContents> bodyElements = new ArrayList<ISDTContents>();
-
- public XWPFSDTContent(CTSdtContentRun sdtRun, IBody part, IRunBody parent){
- for (CTR ctr : sdtRun.getRArray()){
- XWPFRun run = new XWPFRun(ctr, parent);
- runs.add(run);
- bodyElements.add(run);
- }
- }
- public XWPFSDTContent(CTSdtContentBlock block, IBody part, IRunBody parent){
- XmlCursor cursor = block.newCursor();
- cursor.selectPath("./*");
- while (cursor.toNextSelection()) {
+ private List<XWPFSDT> contentControls = new ArrayList<XWPFSDT>();\r
+ private List<ISDTContents> bodyElements = new ArrayList<ISDTContents>();\r
+\r
+ public XWPFSDTContent(CTSdtContentRun sdtRun, IBody part, IRunBody parent) {\r
+ for (CTR ctr : sdtRun.getRArray()) {\r
+ XWPFRun run = new XWPFRun(ctr, parent);\r
+ runs.add(run);\r
+ bodyElements.add(run);\r
+ }\r
+ }\r
+\r
+ public XWPFSDTContent(CTSdtContentBlock block, IBody part, IRunBody parent) {\r
+ XmlCursor cursor = block.newCursor();\r
+ cursor.selectPath("./*");\r
+ while (cursor.toNextSelection()) {\r
XmlObject o = cursor.getObject();
if (o instanceof CTP) {
XWPFParagraph p = new XWPFParagraph((CTP) o, part);
bodyElements.add(p);
paragraphs.add(p);
} else if (o instanceof CTTbl) {
- XWPFTable t = new XWPFTable((CTTbl) o, part);
- bodyElements.add(t);
- tables.add(t);
- } else if (o instanceof CTSdtBlock){
- XWPFSDT c = new XWPFSDT(((CTSdtBlock)o), part);
- bodyElements.add(c);
- contentControls.add(c);
- } else if (o instanceof CTR) {
+ XWPFTable t = new XWPFTable((CTTbl) o, part);\r
+ bodyElements.add(t);\r
+ tables.add(t);\r
+ } else if (o instanceof CTSdtBlock) {\r
+ XWPFSDT c = new XWPFSDT(((CTSdtBlock) o), part);\r
+ bodyElements.add(c);\r
+ contentControls.add(c);\r
+ } else if (o instanceof CTR) {\r
XWPFRun run = new XWPFRun((CTR) o, parent);
runs.add(run);
bodyElements.add(run);
}
- }
- }
-
- public String getText(){
- StringBuilder text = new StringBuilder();
- boolean addNewLine = false;
- for (int i = 0; i < bodyElements.size(); i++){
- Object o = bodyElements.get(i);
- if (o instanceof XWPFParagraph){
- appendParagraph((XWPFParagraph)o, text);
- addNewLine = true;
- } else if (o instanceof XWPFTable){
- appendTable((XWPFTable)o, text);
- addNewLine = true;
- } else if (o instanceof XWPFSDT){
- text.append(((XWPFSDT)o).getContent().getText());
- addNewLine = true;
- } else if (o instanceof XWPFRun){
- text.append(((XWPFRun)o).toString());
- addNewLine = false;
- }
- if (addNewLine == true && i < bodyElements.size()-1){
- text.append("\n");
- }
- }
+ }\r
+ }\r
+\r
+ public String getText() {\r
+ StringBuilder text = new StringBuilder();\r
+ boolean addNewLine = false;\r
+ for (int i = 0; i < bodyElements.size(); i++) {\r
+ Object o = bodyElements.get(i);\r
+ if (o instanceof XWPFParagraph) {\r
+ appendParagraph((XWPFParagraph) o, text);\r
+ addNewLine = true;\r
+ } else if (o instanceof XWPFTable) {\r
+ appendTable((XWPFTable) o, text);\r
+ addNewLine = true;\r
+ } else if (o instanceof XWPFSDT) {\r
+ text.append(((XWPFSDT) o).getContent().getText());\r
+ addNewLine = true;\r
+ } else if (o instanceof XWPFRun) {\r
+ text.append(((XWPFRun) o).toString());\r
+ addNewLine = false;\r
+ }\r
+ if (addNewLine == true && i < bodyElements.size() - 1) {\r
+ text.append("\n");\r
+ }\r
+ }\r
return text.toString();
}
//this works recursively to pull embedded tables from within cells
for (XWPFTableRow row : table.getRows()) {
List<ICell> cells = row.getTableICells();
- for (int i = 0; i < cells.size(); i++) {
- ICell cell = cells.get(i);
- if (cell instanceof XWPFTableCell) {
- text.append(((XWPFTableCell)cell).getTextRecursively());
- } else if (cell instanceof XWPFSDTCell) {
- text.append(((XWPFSDTCell)cell).getContent().getText());
- }
- if (i < cells.size()-1) {
- text.append("\t");
- }
- }
- text.append('\n');
- }
- }
-
- private void appendParagraph(XWPFParagraph paragraph, StringBuilder text) {
- for(IRunElement run : paragraph.getRuns()) {
- text.append(run.toString());
- }
- }
-
- public String toString(){
- return getText();
- }
+ for (int i = 0; i < cells.size(); i++) {\r
+ ICell cell = cells.get(i);\r
+ if (cell instanceof XWPFTableCell) {\r
+ text.append(((XWPFTableCell) cell).getTextRecursively());\r
+ } else if (cell instanceof XWPFSDTCell) {\r
+ text.append(((XWPFSDTCell) cell).getContent().getText());\r
+ }\r
+ if (i < cells.size() - 1) {\r
+ text.append("\t");\r
+ }\r
+ }\r
+ text.append('\n');\r
+ }\r
+ }\r
+\r
+ private void appendParagraph(XWPFParagraph paragraph, StringBuilder text) {\r
+ for (IRunElement run : paragraph.getRuns()) {\r
+ text.append(run.toString());\r
+ }\r
+ }\r
+\r
+ public String toString() {\r
+ return getText();\r
+ }\r
}\r
import javax.xml.namespace.QName;
-
-import org.apache.xmlbeans.XmlCursor;
-import org.apache.xmlbeans.XmlCursor.TokenType;
-
-import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTSdtContentCell;
-
-
-
-/**
- * Experimental class to offer rudimentary read-only processing of
- * of the XWPFSDTCellContent.
-
- * WARNING - APIs expected to change rapidly
- *
- */
-public class XWPFSDTContentCell implements ISDTContent {
-
+\r
+import org.apache.xmlbeans.XmlCursor;\r
+import org.apache.xmlbeans.XmlCursor.TokenType;\r
+import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTSdtContentCell;\r
+\r
+\r
+/**\r
+ * Experimental class to offer rudimentary read-only processing of\r
+ * of the XWPFSDTCellContent.\r
+ * <p/>\r
+ * WARNING - APIs expected to change rapidly\r
+ */\r
+public class XWPFSDTContentCell implements ISDTContent {\r
+\r
//A full implementation would grab the icells
//that a content cell can contain. This would require
//significant changes, including changing the notion that the
//parent of a cell can be not just a row, but an sdt.
//For now we are just grabbing the text out of the text tokentypes.
- //private List<ICell> cells = new ArrayList<ICell>().
-
- private String text = "";
- public XWPFSDTContentCell(CTSdtContentCell sdtContentCell,
- XWPFTableRow xwpfTableRow, IBody part){
- super();
- StringBuilder sb = new StringBuilder();
- XmlCursor cursor = sdtContentCell.newCursor();
-
- //keep track of the following,
- //and add "\n" only before the start of a body
- //element if it is not the first body element.
-
- //index of cell in row
- int tcCnt = 0;
- //count of body objects
+ //private List<ICell> cells = new ArrayList<ICell>().\r
+\r
+ private String text = "";\r
+\r
+ public XWPFSDTContentCell(CTSdtContentCell sdtContentCell,\r
+ XWPFTableRow xwpfTableRow, IBody part) {\r
+ super();\r
+ StringBuilder sb = new StringBuilder();\r
+ XmlCursor cursor = sdtContentCell.newCursor();\r
+
+ //keep track of the following,\r
+ //and add "\n" only before the start of a body\r
+ //element if it is not the first body element.\r
+\r
+ //index of cell in row\r
+ int tcCnt = 0;\r
+ //count of body objects\r
int iBodyCnt = 0;
int depth = 1;
-
- while (cursor.hasNextToken() && depth > 0) {
- TokenType t = cursor.toNextToken();
- if (t.isText()){
- sb.append(cursor.getTextValue());
- } else if (isStartToken(cursor, "tr")) {
- tcCnt = 0;
+\r
+ while (cursor.hasNextToken() && depth > 0) {\r
+ TokenType t = cursor.toNextToken();\r
+ if (t.isText()) {\r
+ sb.append(cursor.getTextValue());\r
+ } else if (isStartToken(cursor, "tr")) {\r
+ tcCnt = 0;\r
iBodyCnt = 0;
} else if (isStartToken(cursor, "tc")) {
if (tcCnt++ > 0) {
isStartToken(cursor, "sdt")) {
if (iBodyCnt > 0) {
sb.append("\n");
- }
- iBodyCnt++;
- }
- if (cursor.isStart()){
- depth++;
- } else if (cursor.isEnd()){
- depth--;
- }
- }
- text = sb.toString();
- }
-
-
-
- private boolean isStartToken(XmlCursor cursor, String string) {
- if (! cursor.isStart()) {
- return false;
- }
- QName qName = cursor.getName();
+ }\r
+ iBodyCnt++;\r
+ }\r
+ if (cursor.isStart()) {\r
+ depth++;\r
+ } else if (cursor.isEnd()) {\r
+ depth--;\r
+ }\r
+ }\r
+ text = sb.toString();\r
+ }\r
+\r
+\r
+ private boolean isStartToken(XmlCursor cursor, String string) {\r
+ if (!cursor.isStart()) {\r
+ return false;\r
+ }\r
+ QName qName = cursor.getName();\r
if (qName != null && qName.getLocalPart() != null &&
qName.getLocalPart().equals(string)) {
return true;
}
return false;
- }
-
-
- public String getText(){
- return text;
- }
-
- public String toString(){
- return getText();
- }
+ }\r
+\r
+\r
+ public String getText() {\r
+ return text;\r
+ }\r
+\r
+ public String toString() {\r
+ return getText();\r
+ }\r
}\r
}
@Override
- protected void onDocumentRead() throws IOException
- {
+ protected void onDocumentRead() throws IOException {
super.onDocumentRead();
readFrom(getPackagePart().getInputStream());
}
* <pre>
* <w:zoom w:percent="50" />
* <pre>
+ *
* @return percentage as an integer of zoom level
*/
public long getZoomPercent() {
- CTZoom zoom;
- if (!ctSettings.isSetZoom()) {
- zoom = ctSettings.addNewZoom();
- } else {
- zoom = ctSettings.getZoom();
- }
-
- return zoom.getPercent().longValue();
+ CTZoom zoom;
+ if (!ctSettings.isSetZoom()) {
+ zoom = ctSettings.addNewZoom();
+ } else {
+ zoom = ctSettings.getZoom();
+ }
+
+ return zoom.getPercent().longValue();
}
/**
* In the zoom tag inside settings.xml file <br/>
* it sets the value of zoom
* <br/>
- * sample snippet from settings.xml
+ * sample snippet from settings.xml
* <pre>
- * <w:zoom w:percent="50" />
+ * <w:zoom w:percent="50" />
* <pre>
*/
public void setZoomPercent(long zoomPercent) {
- if (! ctSettings.isSetZoom()) {
- ctSettings.addNewZoom();
- }
- CTZoom zoom = ctSettings.getZoom();
- zoom.setPercent(BigInteger.valueOf(zoomPercent));
+ if (!ctSettings.isSetZoom()) {
+ ctSettings.addNewZoom();
+ }
+ CTZoom zoom = ctSettings.getZoom();
+ zoom.setPercent(BigInteger.valueOf(zoomPercent));
}
/**
* Verifies the documentProtection tag inside settings.xml file <br/>
* if the protection is enforced (w:enforcement="1") <br/>
* and if the kind of protection equals to passed (STDocProtect.Enum editValue) <br/>
- *
+ * <p/>
* <br/>
* sample snippet from settings.xml
* <pre>
* <w:settings ... >
* <w:documentProtection w:edit="readOnly" w:enforcement="1"/>
* </pre>
- *
+ *
* @return true if documentProtection is enforced with option readOnly
*/
public boolean isEnforcedWith(STDocProtect.Enum editValue) {
* <br/>
* sample snippet from settings.xml
* <pre>
- * <w:documentProtection w:edit="[passed editValue]" w:enforcement="1"
+ * <w:documentProtection w:edit="[passed editValue]" w:enforcement="1"
* w:cryptProviderType="rsaAES" w:cryptAlgorithmClass="hash"
* w:cryptAlgorithmType="typeAny" w:cryptAlgorithmSid="14"
* w:cryptSpinCount="100000" w:hash="..." w:salt="...."
* />
* </pre>
- *
+ *
* @param editValue the protection type
- * @param password the plaintext password, if null no password will be applied
- * @param hashAlgo the hash algorithm - only md2, m5, sha1, sha256, sha384 and sha512 are supported.
- * if null, it will default default to sha1
+ * @param password the plaintext password, if null no password will be applied
+ * @param hashAlgo the hash algorithm - only md2, m5, sha1, sha256, sha384 and sha512 are supported.
+ * if null, it will default default to sha1
*/
public void setEnforcementEditValue(org.openxmlformats.schemas.wordprocessingml.x2006.main.STDocProtect.Enum editValue,
- String password, HashAlgorithm hashAlgo) {
+ String password, HashAlgorithm hashAlgo) {
safeGetDocumentProtection().setEnforcement(STOnOff.X_1);
safeGetDocumentProtection().setEdit(editValue);
-
+
if (password == null) {
if (safeGetDocumentProtection().isSetCryptProviderType()) {
safeGetDocumentProtection().unsetCryptProviderType();
if (safeGetDocumentProtection().isSetCryptAlgorithmClass()) {
safeGetDocumentProtection().unsetCryptAlgorithmClass();
}
-
+
if (safeGetDocumentProtection().isSetCryptAlgorithmType()) {
safeGetDocumentProtection().unsetCryptAlgorithmType();
}
-
+
if (safeGetDocumentProtection().isSetCryptAlgorithmSid()) {
safeGetDocumentProtection().unsetCryptAlgorithmSid();
}
-
+
if (safeGetDocumentProtection().isSetSalt()) {
safeGetDocumentProtection().unsetSalt();
}
-
+
if (safeGetDocumentProtection().isSetCryptSpinCount()) {
safeGetDocumentProtection().unsetCryptSpinCount();
}
-
+
if (safeGetDocumentProtection().isSetHash()) {
safeGetDocumentProtection().unsetHash();
}
final STCryptProv.Enum providerType;
final int sid;
switch (hashAlgo) {
- case md2:
- providerType = STCryptProv.RSA_FULL;
- sid = 1;
- break;
- case md4:
- providerType = STCryptProv.RSA_FULL;
- sid = 2;
- break;
- case md5:
- providerType = STCryptProv.RSA_FULL;
- sid = 3;
- break;
- case sha1:
- providerType = STCryptProv.RSA_FULL;
- sid = 4;
- break;
- case sha256:
- providerType = STCryptProv.RSA_AES;
- sid = 12;
- break;
- case sha384:
- providerType = STCryptProv.RSA_AES;
- sid = 13;
- break;
- case sha512:
- providerType = STCryptProv.RSA_AES;
- sid = 14;
- break;
- default:
- throw new EncryptedDocumentException
- ("Hash algorithm '"+hashAlgo+"' is not supported for document write protection.");
+ case md2:
+ providerType = STCryptProv.RSA_FULL;
+ sid = 1;
+ break;
+ case md4:
+ providerType = STCryptProv.RSA_FULL;
+ sid = 2;
+ break;
+ case md5:
+ providerType = STCryptProv.RSA_FULL;
+ sid = 3;
+ break;
+ case sha1:
+ providerType = STCryptProv.RSA_FULL;
+ sid = 4;
+ break;
+ case sha256:
+ providerType = STCryptProv.RSA_AES;
+ sid = 12;
+ break;
+ case sha384:
+ providerType = STCryptProv.RSA_AES;
+ sid = 13;
+ break;
+ case sha512:
+ providerType = STCryptProv.RSA_AES;
+ sid = 14;
+ break;
+ default:
+ throw new EncryptedDocumentException
+ ("Hash algorithm '" + hashAlgo + "' is not supported for document write protection.");
}
-
- SecureRandom random = new SecureRandom();
+
+ SecureRandom random = new SecureRandom();
byte salt[] = random.generateSeed(16);
-
+
// Iterations specifies the number of times the hashing function shall be iteratively run (using each
// iteration's result as the input for the next iteration).
int spinCount = 100000;
-
+
if (hashAlgo == null) hashAlgo = HashAlgorithm.sha1;
String legacyHash = CryptoFunctions.xorHashPasswordReversed(password);
safeGetDocumentProtection().setCryptAlgorithmClass(STAlgClass.HASH);
safeGetDocumentProtection().setCryptProviderType(providerType);
safeGetDocumentProtection().setCryptAlgorithmSid(BigInteger.valueOf(sid));
- }
+ }
}
/**
byte hash[] = safeGetDocumentProtection().getHash();
byte salt[] = safeGetDocumentProtection().getSalt();
BigInteger spinCount = safeGetDocumentProtection().getCryptSpinCount();
-
+
if (sid == null || hash == null || salt == null || spinCount == null) return false;
-
+
HashAlgorithm hashAlgo;
switch (sid.intValue()) {
- case 1: hashAlgo = HashAlgorithm.md2; break;
- case 2: hashAlgo = HashAlgorithm.md4; break;
- case 3: hashAlgo = HashAlgorithm.md5; break;
- case 4: hashAlgo = HashAlgorithm.sha1; break;
- case 12: hashAlgo = HashAlgorithm.sha256; break;
- case 13: hashAlgo = HashAlgorithm.sha384; break;
- case 14: hashAlgo = HashAlgorithm.sha512; break;
- default: return false;
+ case 1:
+ hashAlgo = HashAlgorithm.md2;
+ break;
+ case 2:
+ hashAlgo = HashAlgorithm.md4;
+ break;
+ case 3:
+ hashAlgo = HashAlgorithm.md5;
+ break;
+ case 4:
+ hashAlgo = HashAlgorithm.sha1;
+ break;
+ case 12:
+ hashAlgo = HashAlgorithm.sha256;
+ break;
+ case 13:
+ hashAlgo = HashAlgorithm.sha384;
+ break;
+ case 14:
+ hashAlgo = HashAlgorithm.sha512;
+ break;
+ default:
+ return false;
}
-
+
String legacyHash = CryptoFunctions.xorHashPasswordReversed(password);
// Implementation Notes List:
// --> In this third stage, the reversed byte order legacy hash from the second stage shall
// be converted to Unicode hex string representation
byte hash2[] = CryptoFunctions.hashPassword(legacyHash, hashAlgo, salt, spinCount.intValue(), false);
-
+
return Arrays.equals(hash, hash2);
}
-
+
/**
* Removes protection enforcement.<br/>
* In the documentProtection tag inside settings.xml file <br/>
* Enforces fields update on document open (in Word).
* In the settings.xml file <br/>
* sets the updateSettings value to true (w:updateSettings w:val="true")
- *
- * NOTICES:
- * <ul>
- * <li>Causing Word to ask on open: "This document contains fields that may refer to other files. Do you want to update the fields in this document?"
- * (if "Update automatic links at open" is enabled)</li>
- * <li>Flag is removed after saving with changes in Word </li>
- * </ul>
+ * <p/>
+ * NOTICES:
+ * <ul>
+ * <li>Causing Word to ask on open: "This document contains fields that may refer to other files. Do you want to update the fields in this document?"
+ * (if "Update automatic links at open" is enabled)</li>
+ * <li>Flag is removed after saving with changes in Word </li>
+ * </ul>
*/
public void setUpdateFields() {
- CTOnOff onOff = CTOnOff.Factory.newInstance();
- onOff.setVal(STOnOff.TRUE);
- ctSettings.setUpdateFields(onOff);
+ CTOnOff onOff = CTOnOff.Factory.newInstance();
+ onOff.setVal(STOnOff.TRUE);
+ ctSettings.setUpdateFields(onOff);
}
boolean isUpdateFields() {
/**
* Check if revision tracking is turned on.
- *
+ *
* @return <code>true</code> if revision tracking is turned on
*/
public boolean isTrackRevisions() {
/**
* Enable or disable revision tracking.
- *
+ *
* @param enable <code>true</code> to turn on revision tracking, <code>false</code> to turn off revision tracking
*/
public void setTrackRevisions(boolean enable) {
- if(enable) {
- if(!ctSettings.isSetTrackRevisions()) {
+ if (enable) {
+ if (!ctSettings.isSetTrackRevisions()) {
ctSettings.addNewTrackRevisions();
}
} else {
- if(ctSettings.isSetTrackRevisions()) {
+ if (ctSettings.isSetTrackRevisions()) {
ctSettings.unsetTrackRevisions();
}
}
@Override
protected void commit() throws IOException {
if (ctSettings == null) {
- throw new IllegalStateException("Unable to write out settings that were never read in!");
+ throw new IllegalStateException("Unable to write out settings that were never read in!");
}
XmlOptions xmlOptions = new XmlOptions(DEFAULT_XML_OPTIONS);
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTStyle;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.STStyleType;
-
-/**
- * @author Philipp Epp
- *
- */
-public class XWPFStyle {
-
- private CTStyle ctStyle;
- protected XWPFStyles styles;
-
- /**
- * constructor
- * @param style
- */
- public XWPFStyle(CTStyle style){
- this(style,null);
- }
- /**
- * constructor
- * @param style
- * @param styles
- */
- public XWPFStyle(CTStyle style, XWPFStyles styles){
- this.ctStyle = style;
- this.styles = styles;
- }
-
- /**
- * get StyleID of the style
- * @return styleID StyleID of the style
- */
- public String getStyleId(){
- return ctStyle.getStyleId();
- }
-
- /**
- * get Type of the Style
- * @return ctType
- */
- public STStyleType.Enum getType(){
- return ctStyle.getType();
- }
-
- /**
- * set style
- * @param style
- */
- public void setStyle(CTStyle style){
- this.ctStyle = style;
- }
- /**
- * get ctStyle
- * @return ctStyle
- */
- public CTStyle getCTStyle(){
- return this.ctStyle;
- }
- /**
- * set styleID
- * @param styleId
- */
- public void setStyleId(String styleId){
- ctStyle.setStyleId(styleId);
- }
-
- /**
- * set styleType
- * @param type
- */
- public void setType(STStyleType.Enum type){
- ctStyle.setType(type);
- }
- /**
- * get styles
- * @return styles the styles to which this style belongs
- */
- public XWPFStyles getStyles(){
- return styles;
- }
-
- public String getBasisStyleID(){
- if(ctStyle.getBasedOn()!=null)
- return ctStyle.getBasedOn().getVal();
- else
- return null;
- }
-
-
- /**
- * get StyleID of the linked Style
- */
- public String getLinkStyleID(){
- if (ctStyle.getLink()!=null)
- return ctStyle.getLink().getVal();
- else
- return null;
- }
-
- /**
- * get StyleID of the next style
- */
- public String getNextStyleID(){
- if(ctStyle.getNext()!=null)
- return ctStyle.getNext().getVal();
- else
- return null;
- }
-
- public String getName() {
- if(ctStyle.isSetName())
- return ctStyle.getName().getVal();
- return null;
- }
-
- /**
- * compares the names of the Styles
- * @param compStyle
- */
- public boolean hasSameName(XWPFStyle compStyle){
- CTStyle ctCompStyle = compStyle.getCTStyle();
- String name = ctCompStyle.getName().getVal();
- return name.equals(ctStyle.getName().getVal());
- }
-
-}//end class
+\r
+/**\r
+ * @author Philipp Epp\r
+ */\r
+public class XWPFStyle {\r
+\r
+ protected XWPFStyles styles;\r
+ private CTStyle ctStyle;\r
+\r
+ /**\r
+ * constructor\r
+ *\r
+ * @param style\r
+ */\r
+ public XWPFStyle(CTStyle style) {\r
+ this(style, null);\r
+ }\r
+\r
+ /**\r
+ * constructor\r
+ *\r
+ * @param style\r
+ * @param styles\r
+ */\r
+ public XWPFStyle(CTStyle style, XWPFStyles styles) {\r
+ this.ctStyle = style;\r
+ this.styles = styles;\r
+ }\r
+\r
+ /**\r
+ * get StyleID of the style\r
+ *\r
+ * @return styleID StyleID of the style\r
+ */\r
+ public String getStyleId() {\r
+ return ctStyle.getStyleId();\r
+ }\r
+\r
+ /**\r
+ * set styleID\r
+ *\r
+ * @param styleId\r
+ */\r
+ public void setStyleId(String styleId) {\r
+ ctStyle.setStyleId(styleId);\r
+ }\r
+\r
+ /**\r
+ * get Type of the Style\r
+ *\r
+ * @return ctType\r
+ */\r
+ public STStyleType.Enum getType() {\r
+ return ctStyle.getType();\r
+ }\r
+\r
+ /**\r
+ * set styleType\r
+ *\r
+ * @param type\r
+ */\r
+ public void setType(STStyleType.Enum type) {\r
+ ctStyle.setType(type);\r
+ }\r
+\r
+ /**\r
+ * set style\r
+ *\r
+ * @param style\r
+ */\r
+ public void setStyle(CTStyle style) {\r
+ this.ctStyle = style;\r
+ }\r
+\r
+ /**\r
+ * get ctStyle\r
+ *\r
+ * @return ctStyle\r
+ */\r
+ public CTStyle getCTStyle() {\r
+ return this.ctStyle;\r
+ }\r
+\r
+ /**\r
+ * get styles\r
+ *\r
+ * @return styles the styles to which this style belongs\r
+ */\r
+ public XWPFStyles getStyles() {\r
+ return styles;\r
+ }\r
+\r
+ public String getBasisStyleID() {\r
+ if (ctStyle.getBasedOn() != null)\r
+ return ctStyle.getBasedOn().getVal();\r
+ else\r
+ return null;\r
+ }\r
+\r
+\r
+ /**\r
+ * get StyleID of the linked Style\r
+ */\r
+ public String getLinkStyleID() {\r
+ if (ctStyle.getLink() != null)\r
+ return ctStyle.getLink().getVal();\r
+ else\r
+ return null;\r
+ }\r
+\r
+ /**\r
+ * get StyleID of the next style\r
+ */\r
+ public String getNextStyleID() {\r
+ if (ctStyle.getNext() != null)\r
+ return ctStyle.getNext().getVal();\r
+ else\r
+ return null;\r
+ }\r
+\r
+ public String getName() {\r
+ if (ctStyle.isSetName())\r
+ return ctStyle.getName().getVal();\r
+ return null;\r
+ }\r
+\r
+ /**\r
+ * compares the names of the Styles\r
+ *\r
+ * @param compStyle\r
+ */\r
+ public boolean hasSameName(XWPFStyle compStyle) {\r
+ CTStyle ctCompStyle = compStyle.getCTStyle();\r
+ String name = ctCompStyle.getName().getVal();\r
+ return name.equals(ctStyle.getName().getVal());\r
+ }\r
+\r
+}//end class\r
import org.apache.poi.POIXMLException;
import org.apache.poi.openxml4j.exceptions.OpenXML4JException;
import org.apache.poi.openxml4j.opc.PackagePart;
-import org.apache.poi.openxml4j.opc.PackageRelationship;
-import org.apache.xmlbeans.XmlException;
-import org.apache.xmlbeans.XmlOptions;
-import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTPPrDefault;
-import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTStyle;
-import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTStyles;
-import org.openxmlformats.schemas.wordprocessingml.x2006.main.StylesDocument;
-import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTRPr;
-import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTRPrDefault;
-import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTLanguage;
-import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTFonts;
-import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTDocDefaults;
-/**
- * Holds details of built-in, default and user styles, which
- * apply to tables / paragraphs / lists etc.
- * Text within one of those with custom stylings has the style
- * information stored in the {@link XWPFRun}
- */
-public class XWPFStyles extends POIXMLDocumentPart{
- private CTStyles ctStyles;
- private List<XWPFStyle> listStyle = new ArrayList<XWPFStyle>();
-
- private XWPFLatentStyles latentStyles;
- private XWPFDefaultRunStyle defaultRunStyle;
- private XWPFDefaultParagraphStyle defaultParaStyle;
+import org.apache.poi.openxml4j.opc.PackageRelationship;\r
+import org.apache.xmlbeans.XmlException;\r
+import org.apache.xmlbeans.XmlOptions;\r
+import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTDocDefaults;\r
+import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTFonts;\r
+import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTLanguage;\r
+import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTPPrDefault;\r
+import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTRPr;\r
+import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTRPrDefault;\r
+import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTStyle;\r
+import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTStyles;\r
+import org.openxmlformats.schemas.wordprocessingml.x2006.main.StylesDocument;\r
+\r
+/**\r
+ * Holds details of built-in, default and user styles, which\r
+ * apply to tables / paragraphs / lists etc.\r
+ * Text within one of those with custom stylings has the style\r
+ * information stored in the {@link XWPFRun}\r
+ */\r
+public class XWPFStyles extends POIXMLDocumentPart {\r
+ private CTStyles ctStyles;\r
+ private List<XWPFStyle> listStyle = new ArrayList<XWPFStyle>();\r
+\r
+ private XWPFLatentStyles latentStyles;\r
+ private XWPFDefaultRunStyle defaultRunStyle;\r
+ private XWPFDefaultParagraphStyle defaultParaStyle;\r
/**
* Construct XWPFStyles from a package part
*
- * @param part the package part holding the data of the styles,
- * @param rel the package relationship of type "http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles"
- */
- public XWPFStyles(PackagePart part, PackageRelationship rel) throws IOException, OpenXML4JException{
- super(part, rel);
- }
-
+ * @param part the package part holding the data of the styles,\r
+ * @param rel the package relationship of type "http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles"\r
+ */\r
+ public XWPFStyles(PackagePart part, PackageRelationship rel) throws IOException, OpenXML4JException {\r
+ super(part, rel);\r
+ }\r
+\r
/**
* Construct XWPFStyles from scratch for a new document.
*/
}
/**
- * Read document
- */
- @Override
- protected void onDocumentRead() throws IOException{
- StylesDocument stylesDoc;
- try {
- InputStream is = getPackagePart().getInputStream();
+ * Read document\r
+ */\r
+ @Override\r
+ protected void onDocumentRead() throws IOException {\r
+ StylesDocument stylesDoc;\r
+ try {\r
+ InputStream is = getPackagePart().getInputStream();\r
stylesDoc = StylesDocument.Factory.parse(is);
setStyles(stylesDoc.getStyles());
latentStyles = new XWPFLatentStyles(ctStyles.getLatentStyles(), this);
if (ctStyles == null) {
throw new IllegalStateException("Unable to write out styles that were never read in!");
}
-
- XmlOptions xmlOptions = new XmlOptions(DEFAULT_XML_OPTIONS);
- xmlOptions.setSaveSyntheticDocumentElement(new QName(CTStyles.type.getName().getNamespaceURI(), "styles"));
- Map<String,String> map = new HashMap<String,String>();
- map.put("http://schemas.openxmlformats.org/officeDocument/2006/relationships", "r");
- map.put("http://schemas.openxmlformats.org/wordprocessingml/2006/main", "w");
- xmlOptions.setSaveSuggestedPrefixes(map);
+\r
+ XmlOptions xmlOptions = new XmlOptions(DEFAULT_XML_OPTIONS);\r
+ xmlOptions.setSaveSyntheticDocumentElement(new QName(CTStyles.type.getName().getNamespaceURI(), "styles"));\r
+ Map<String, String> map = new HashMap<String, String>();\r
+ map.put("http://schemas.openxmlformats.org/officeDocument/2006/relationships", "r");\r
+ map.put("http://schemas.openxmlformats.org/wordprocessingml/2006/main", "w");\r
+ xmlOptions.setSaveSuggestedPrefixes(map);\r
PackagePart part = getPackagePart();
OutputStream out = part.getOutputStream();
ctStyles.save(out, xmlOptions);
out.close();
- }
-
- protected void ensureDocDefaults() {
- if (! ctStyles.isSetDocDefaults()) {
- ctStyles.addNewDocDefaults();
- }
-
- CTDocDefaults docDefaults = ctStyles.getDocDefaults();
- if (! docDefaults.isSetPPrDefault())
- docDefaults.addNewPPrDefault();
- if (! docDefaults.isSetRPrDefault())
- docDefaults.addNewRPrDefault();
-
- CTPPrDefault pprd = docDefaults.getPPrDefault();
- CTRPrDefault rprd = docDefaults.getRPrDefault();
- if (!pprd.isSetPPr()) pprd.addNewPPr();
- if (!rprd.isSetRPr()) rprd.addNewRPr();
-
- defaultRunStyle = new XWPFDefaultRunStyle(rprd.getRPr());
- defaultParaStyle = new XWPFDefaultParagraphStyle(pprd.getPPr());
- }
-
- /**
- * Sets the ctStyles
- * @param styles
- */
- @SuppressWarnings("deprecation")
+ }\r
+\r
+ protected void ensureDocDefaults() {\r
+ if (!ctStyles.isSetDocDefaults()) {\r
+ ctStyles.addNewDocDefaults();\r
+ }\r
+\r
+ CTDocDefaults docDefaults = ctStyles.getDocDefaults();\r
+ if (!docDefaults.isSetPPrDefault())\r
+ docDefaults.addNewPPrDefault();\r
+ if (!docDefaults.isSetRPrDefault())\r
+ docDefaults.addNewRPrDefault();\r
+\r
+ CTPPrDefault pprd = docDefaults.getPPrDefault();\r
+ CTRPrDefault rprd = docDefaults.getRPrDefault();\r
+ if (!pprd.isSetPPr()) pprd.addNewPPr();\r
+ if (!rprd.isSetRPr()) rprd.addNewRPr();\r
+\r
+ defaultRunStyle = new XWPFDefaultRunStyle(rprd.getRPr());\r
+ defaultParaStyle = new XWPFDefaultParagraphStyle(pprd.getPPr());\r
+ }\r
+\r
+ /**\r
+ * Sets the ctStyles\r
+ *\r
+ * @param styles\r
+ */\r
+ @SuppressWarnings("deprecation")\r
public void setStyles(CTStyles styles) {
- ctStyles = styles;
-
- // Build up all the style objects
- for(CTStyle style : ctStyles.getStyleArray()) {
- listStyle.add(new XWPFStyle(style, this));
- }
- if (ctStyles.isSetDocDefaults()) {
+ ctStyles = styles;\r
+\r
+ // Build up all the style objects\r
+ for (CTStyle style : ctStyles.getStyleArray()) {\r
+ listStyle.add(new XWPFStyle(style, this));\r
+ }\r
+ if (ctStyles.isSetDocDefaults()) {\r
CTDocDefaults docDefaults = ctStyles.getDocDefaults();
if (docDefaults.isSetRPrDefault() && docDefaults.getRPrDefault().isSetRPr()) {
defaultRunStyle = new XWPFDefaultRunStyle(
}
}
}
-
- /**
- * checks whether style with styleID exist
- * @param styleID styleID of the Style in the style-Document
- * @return true if style exist, false if style not exist
- */
- public boolean styleExist(String styleID){
- for (XWPFStyle style : listStyle) {
- if (style.getStyleId().equals(styleID))
- return true;
- }
- return false;
- }
- /**
- * add a style to the document
- * @param style
- * @throws IOException
- */
- public void addStyle(XWPFStyle style){
- listStyle.add(style);
- ctStyles.addNewStyle();
- int pos = ctStyles.sizeOfStyleArray() - 1;
- ctStyles.setStyleArray(pos, style.getCTStyle());
- }
- /**
- * Get style by a styleID
- * @param styleID styleID of the searched style
- * @return style
- */
- public XWPFStyle getStyle(String styleID){
- for (XWPFStyle style : listStyle) {
- if(style.getStyleId().equals(styleID))
- return style;
- }
- return null;
- }
- public int getNumberOfStyles() {
- return listStyle.size();
- }
-
- /**
- * get the styles which are related to the parameter style and their relatives
- * this method can be used to copy all styles from one document to another document
- * @param style
- * @return a list of all styles which were used by this method
- */
- public List<XWPFStyle> getUsedStyleList(XWPFStyle style){
- List<XWPFStyle> usedStyleList = new ArrayList<XWPFStyle>();
- usedStyleList.add(style);
- return getUsedStyleList(style, usedStyleList);
- }
-
- /**
- * get the styles which are related to parameter style
- * @param style
- * @return all Styles of the parameterList
- */
- private List<XWPFStyle> getUsedStyleList(XWPFStyle style, List<XWPFStyle> usedStyleList){
- String basisStyleID = style.getBasisStyleID();
- XWPFStyle basisStyle = getStyle(basisStyleID);
- if((basisStyle!=null)&&(!usedStyleList.contains(basisStyle))){
- usedStyleList.add(basisStyle);
- getUsedStyleList(basisStyle, usedStyleList);
- }
- String linkStyleID = style.getLinkStyleID();
- XWPFStyle linkStyle = getStyle(linkStyleID);
- if((linkStyle!=null)&&(!usedStyleList.contains(linkStyle))){
- usedStyleList.add(linkStyle);
- getUsedStyleList(linkStyle, usedStyleList);
- }
-
- String nextStyleID = style.getNextStyleID();
- XWPFStyle nextStyle = getStyle(nextStyleID);
- if((nextStyle!=null)&&(!usedStyleList.contains(nextStyle))){
- usedStyleList.add(linkStyle);
- getUsedStyleList(linkStyle, usedStyleList);
- }
- return usedStyleList;
- }
-
- protected CTLanguage getCTLanguage() {
- ensureDocDefaults();
-
- CTLanguage lang = null;
- if (defaultRunStyle.getRPr().isSetLang()) {
- lang = defaultRunStyle.getRPr().getLang();
- } else {
- lang = defaultRunStyle.getRPr().addNewLang();
- }
-
- return lang;
- }
-
- /**
- * Sets the default spelling language on ctStyles DocDefaults parameter
- * @param strSpellingLanguage
- */
- public void setSpellingLanguage(String strSpellingLanguage) {
+\r
+ /**\r
+ * checks whether style with styleID exist\r
+ *\r
+ * @param styleID styleID of the Style in the style-Document\r
+ * @return true if style exist, false if style not exist\r
+ */\r
+ public boolean styleExist(String styleID) {\r
+ for (XWPFStyle style : listStyle) {\r
+ if (style.getStyleId().equals(styleID))\r
+ return true;\r
+ }\r
+ return false;\r
+ }\r
+\r
+ /**\r
+ * add a style to the document\r
+ *\r
+ * @param style\r
+ * @throws IOException\r
+ */\r
+ public void addStyle(XWPFStyle style) {\r
+ listStyle.add(style);\r
+ ctStyles.addNewStyle();\r
+ int pos = ctStyles.sizeOfStyleArray() - 1;\r
+ ctStyles.setStyleArray(pos, style.getCTStyle());\r
+ }\r
+\r
+ /**\r
+ * Get style by a styleID\r
+ *\r
+ * @param styleID styleID of the searched style\r
+ * @return style\r
+ */\r
+ public XWPFStyle getStyle(String styleID) {\r
+ for (XWPFStyle style : listStyle) {\r
+ if (style.getStyleId().equals(styleID))\r
+ return style;\r
+ }\r
+ return null;\r
+ }\r
+\r
+ public int getNumberOfStyles() {\r
+ return listStyle.size();\r
+ }\r
+\r
+ /**\r
+ * get the styles which are related to the parameter style and their relatives\r
+ * this method can be used to copy all styles from one document to another document\r
+ *\r
+ * @param style\r
+ * @return a list of all styles which were used by this method\r
+ */\r
+ public List<XWPFStyle> getUsedStyleList(XWPFStyle style) {\r
+ List<XWPFStyle> usedStyleList = new ArrayList<XWPFStyle>();\r
+ usedStyleList.add(style);\r
+ return getUsedStyleList(style, usedStyleList);\r
+ }\r
+\r
+ /**\r
+ * get the styles which are related to parameter style\r
+ *\r
+ * @param style\r
+ * @return all Styles of the parameterList\r
+ */\r
+ private List<XWPFStyle> getUsedStyleList(XWPFStyle style, List<XWPFStyle> usedStyleList) {\r
+ String basisStyleID = style.getBasisStyleID();\r
+ XWPFStyle basisStyle = getStyle(basisStyleID);\r
+ if ((basisStyle != null) && (!usedStyleList.contains(basisStyle))) {\r
+ usedStyleList.add(basisStyle);\r
+ getUsedStyleList(basisStyle, usedStyleList);\r
+ }\r
+ String linkStyleID = style.getLinkStyleID();\r
+ XWPFStyle linkStyle = getStyle(linkStyleID);\r
+ if ((linkStyle != null) && (!usedStyleList.contains(linkStyle))) {\r
+ usedStyleList.add(linkStyle);\r
+ getUsedStyleList(linkStyle, usedStyleList);\r
+ }\r
+\r
+ String nextStyleID = style.getNextStyleID();\r
+ XWPFStyle nextStyle = getStyle(nextStyleID);\r
+ if ((nextStyle != null) && (!usedStyleList.contains(nextStyle))) {\r
+ usedStyleList.add(linkStyle);\r
+ getUsedStyleList(linkStyle, usedStyleList);\r
+ }\r
+ return usedStyleList;\r
+ }\r
+\r
+ protected CTLanguage getCTLanguage() {\r
+ ensureDocDefaults();\r
+\r
+ CTLanguage lang = null;\r
+ if (defaultRunStyle.getRPr().isSetLang()) {\r
+ lang = defaultRunStyle.getRPr().getLang();\r
+ } else {\r
+ lang = defaultRunStyle.getRPr().addNewLang();\r
+ }\r
+\r
+ return lang;\r
+ }\r
+\r
+ /**\r
+ * Sets the default spelling language on ctStyles DocDefaults parameter\r
+ *\r
+ * @param strSpellingLanguage\r
+ */\r
+ public void setSpellingLanguage(String strSpellingLanguage) {\r
CTLanguage lang = getCTLanguage();
- lang.setVal(strSpellingLanguage);
- lang.setBidi(strSpellingLanguage);
- }
-
- /**
- * Sets the default East Asia spelling language on ctStyles DocDefaults parameter
- * @param strEastAsia
- */
- public void setEastAsia(String strEastAsia) {
+ lang.setVal(strSpellingLanguage);\r
+ lang.setBidi(strSpellingLanguage);\r
+ }\r
+\r
+ /**\r
+ * Sets the default East Asia spelling language on ctStyles DocDefaults parameter\r
+ *\r
+ * @param strEastAsia\r
+ */\r
+ public void setEastAsia(String strEastAsia) {\r
CTLanguage lang = getCTLanguage();
lang.setEastAsia(strEastAsia);
}
- /**
- * Sets the default font on ctStyles DocDefaults parameter
- * TODO Replace this with specific setters for each type, possibly
- * on XWPFDefaultRunStyle
- */
- public void setDefaultFonts(CTFonts fonts) {
- ensureDocDefaults();
-
- CTRPr runProps = defaultRunStyle.getRPr();
- runProps.setRFonts(fonts);
- }
+ /**\r
+ * Sets the default font on ctStyles DocDefaults parameter\r
+ * TODO Replace this with specific setters for each type, possibly\r
+ * on XWPFDefaultRunStyle\r
+ */\r
+ public void setDefaultFonts(CTFonts fonts) {\r
+ ensureDocDefaults();\r
+\r
+ CTRPr runProps = defaultRunStyle.getRPr();\r
+ runProps.setRFonts(fonts);\r
+ }\r
/**
- * get the style with the same name
- * if this style is not existing, return null
- */
- public XWPFStyle getStyleWithSameName(XWPFStyle style){
- for (XWPFStyle ownStyle : listStyle) {
- if(ownStyle.hasSameName(style)){
- return ownStyle;
- }
- }
- return null;
- }
+ * get the style with the same name\r
+ * if this style is not existing, return null\r
+ */\r
+ public XWPFStyle getStyleWithSameName(XWPFStyle style) {\r
+ for (XWPFStyle ownStyle : listStyle) {\r
+ if (ownStyle.hasSameName(style)) {\r
+ return ownStyle;\r
+ }\r
+ }\r
+ return null;\r
+ }\r
/**
* Get the default style which applies text runs in the document
* of paragraphs (and other block-level content) arranged in rows and columns.</p>
*/
public class XWPFTable implements IBodyElement, ISDTContents {
- protected StringBuffer text = new StringBuffer();
- private CTTbl ctTbl;
- protected List<XWPFTableRow> tableRows;
- protected List<String> styleIDs;
-
- // Create a map from this XWPF-level enum to the STBorder.Enum values
- public static enum XWPFBorderType { NIL, NONE, SINGLE, THICK, DOUBLE, DOTTED, DASHED, DOT_DASH };
private static EnumMap<XWPFBorderType, STBorder.Enum> xwpfBorderTypeMap;
// Create a map from the STBorder.Enum values to the XWPF-level enums
private static HashMap<Integer, XWPFBorderType> stBorderTypeMap;
- protected IBody part;
-
static {
// populate enum maps
xwpfBorderTypeMap = new EnumMap<XWPFBorderType, STBorder.Enum>(XWPFBorderType.class);
stBorderTypeMap.put(STBorder.INT_DOUBLE, XWPFBorderType.DOUBLE);
stBorderTypeMap.put(STBorder.INT_DOTTED, XWPFBorderType.DOTTED);
stBorderTypeMap.put(STBorder.INT_DASHED, XWPFBorderType.DASHED);
- stBorderTypeMap.put(STBorder.INT_DOT_DASH, XWPFBorderType.DOT_DASH);
+ stBorderTypeMap.put(STBorder.INT_DOT_DASH, XWPFBorderType.DOT_DASH);
}
-
+
+ protected StringBuffer text = new StringBuffer();
+ protected List<XWPFTableRow> tableRows;
+
+ ;
+ protected List<String> styleIDs;
+ protected IBody part;
+ private CTTbl ctTbl;
+
public XWPFTable(CTTbl table, IBody part, int row, int col) {
this(table, part);
}
@SuppressWarnings("deprecation")
- public XWPFTable(CTTbl table, IBody part){
+ public XWPFTable(CTTbl table, IBody part) {
this.part = part;
this.ctTbl = table;
* Convenience method to extract text in cells. This
* does not extract text recursively in cells, and it does not
* currently include text in SDT (form) components.
- * <p>
+ * <p/>
* To get all text within a table, see XWPFWordExtractor's appendTableText
- * as an example.
+ * as an example.
*
* @return text
*/
return null;
}
-
/**
- * @param width
+ * @return width value
*/
- public void setWidth(int width) {
+ public int getWidth() {
CTTblPr tblPr = getTrPr();
- CTTblWidth tblWidth = tblPr.isSetTblW() ? tblPr.getTblW() : tblPr.addNewTblW();
- tblWidth.setW(new BigInteger("" + width));
+ return tblPr.isSetTblW() ? tblPr.getTblW().getW().intValue() : -1;
}
/**
- * @return width value
+ * @param width
*/
- public int getWidth() {
+ public void setWidth(int width) {
CTTblPr tblPr = getTrPr();
- return tblPr.isSetTblW() ? tblPr.getTblW().getW().intValue() : -1;
+ CTTblWidth tblWidth = tblPr.isSetTblW() ? tblPr.getTblW() : tblPr.addNewTblW();
+ tblWidth.setW(new BigInteger("" + width));
}
/**
}
}
}
-
+
/**
* get the StyleID of the table
- * @return style-ID of the table
+ *
+ * @return style-ID of the table
*/
- public String getStyleID(){
+ public String getStyleID() {
String styleId = null;
CTTblPr tblPr = ctTbl.getTblPr();
if (tblPr != null) {
/**
* Set the table style. If the style is not defined in the document, MS Word
* will set the table style to "Normal".
+ *
* @param styleName - the style name to apply to this table
*/
public void setStyleID(String styleName) {
/**
* add a new Row to the table
- *
- * @param row the row which should be added
+ *
+ * @param row the row which should be added
*/
- public void addRow(XWPFTableRow row){
+ public void addRow(XWPFTableRow row) {
ctTbl.addNewTr();
- ctTbl.setTrArray(getNumberOfRows()-1, row.getCtRow());
+ ctTbl.setTrArray(getNumberOfRows() - 1, row.getCtRow());
tableRows.add(row);
}
/**
* add a new Row to the table
* at position pos
- * @param row the row which should be added
+ *
+ * @param row the row which should be added
*/
- public boolean addRow(XWPFTableRow row, int pos){
- if(pos >= 0 && pos <= tableRows.size()){
+ public boolean addRow(XWPFTableRow row, int pos) {
+ if (pos >= 0 && pos <= tableRows.size()) {
ctTbl.insertNewTr(pos);
- ctTbl.setTrArray(pos,row.getCtRow());
+ ctTbl.setTrArray(pos, row.getCtRow());
tableRows.add(pos, row);
return true;
}
}
/**
- * inserts a new tablerow
+ * inserts a new tablerow
+ *
* @param pos
- * @return the inserted row
+ * @return the inserted row
*/
- public XWPFTableRow insertNewTableRow(int pos){
- if(pos >= 0 && pos <= tableRows.size()){
+ public XWPFTableRow insertNewTableRow(int pos) {
+ if (pos >= 0 && pos <= tableRows.size()) {
CTRow row = ctTbl.insertNewTr(pos);
XWPFTableRow tableRow = new XWPFTableRow(row, this);
tableRows.add(pos, tableRow);
return null;
}
-
/**
* Remove a row at position pos from the table
- * @param pos position the Row in the Table
+ *
+ * @param pos position the Row in the Table
*/
public boolean removeRow(int pos) throws IndexOutOfBoundsException {
if (pos >= 0 && pos < tableRows.size()) {
return tableRows;
}
-
/**
* returns the type of the BodyElement Table
+ *
* @see org.apache.poi.xwpf.usermodel.IBodyElement#getElementType()
*/
public BodyElementType getElementType() {
/**
* returns the part of the bodyElement
+ *
* @see org.apache.poi.xwpf.usermodel.IBody#getPart()
*/
public POIXMLDocumentPart getPart() {
- if(part != null){
+ if (part != null) {
return part.getPart();
}
return null;
/**
* returns the partType of the bodyPart which owns the bodyElement
+ *
* @see org.apache.poi.xwpf.usermodel.IBody#getPartType()
*/
public BodyType getPartType() {
* if this row is not existing in the table null will be returned
*/
public XWPFTableRow getRow(CTRow row) {
- for(int i=0; i<getRows().size(); i++){
- if(getRows().get(i).getCtRow()== row) return getRow(i);
+ for (int i = 0; i < getRows().size(); i++) {
+ if (getRows().get(i).getCtRow() == row) return getRow(i);
}
return null;
}
+
+ // Create a map from this XWPF-level enum to the STBorder.Enum values
+ public static enum XWPFBorderType {
+ NIL, NONE, SINGLE, THICK, DOUBLE, DOTTED, DASHED, DOT_DASH
+ }
}
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTVerticalJc;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.STShd;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.STVerticalJc;
-
-/**
- * Represents a Cell within a {@link XWPFTable}. The
- * Cell is the thing that holds the actual content (paragraphs etc)
- */
-public class XWPFTableCell implements IBody, ICell {
- private final CTTc ctTc;
- protected List<XWPFParagraph> paragraphs = null;
- protected List<XWPFTable> tables = null;
- protected List<IBodyElement> bodyElements = null;
- protected IBody part;
- private XWPFTableRow tableRow = null;
- // Create a map from this XWPF-level enum to the STVerticalJc.Enum values
- public static enum XWPFVertAlign { TOP, CENTER, BOTH, BOTTOM };
- private static EnumMap<XWPFVertAlign, STVerticalJc.Enum> alignMap;
- // Create a map from the STVerticalJc.Enum values to the XWPF-level enums
- private static HashMap<Integer, XWPFVertAlign> stVertAlignTypeMap;
+\r
+/**\r
+ * Represents a Cell within a {@link XWPFTable}. The\r
+ * Cell is the thing that holds the actual content (paragraphs etc)\r
+ */\r
+public class XWPFTableCell implements IBody, ICell {\r
+ private static EnumMap<XWPFVertAlign, STVerticalJc.Enum> alignMap;\r
+ // Create a map from the STVerticalJc.Enum values to the XWPF-level enums\r
+ private static HashMap<Integer, XWPFVertAlign> stVertAlignTypeMap;\r
static {
// populate enum maps
stVertAlignTypeMap.put(STVerticalJc.INT_CENTER, XWPFVertAlign.CENTER);
stVertAlignTypeMap.put(STVerticalJc.INT_BOTH, XWPFVertAlign.BOTH);
stVertAlignTypeMap.put(STVerticalJc.INT_BOTTOM, XWPFVertAlign.BOTTOM);
-
- }
-
- /**
- * If a table cell does not include at least one block-level element, then this document shall be considered corrupt
- */
+\r
+ }\r
+\r
+ private final CTTc ctTc;\r
+ protected List<XWPFParagraph> paragraphs = null;\r
+ protected List<XWPFTable> tables = null;\r
+ protected List<IBodyElement> bodyElements = null;\r
+\r
+ ;\r
+ protected IBody part;\r
+ private XWPFTableRow tableRow = null;\r
+\r
+ /**\r
+ * If a table cell does not include at least one block-level element, then this document shall be considered corrupt\r
+ */\r
public XWPFTableCell(CTTc cell, XWPFTableRow tableRow, IBody part) {
this.ctTc = cell;
- this.part = part;
- this.tableRow = tableRow;
- // NB: If a table cell does not include at least one block-level element, then this document shall be considered corrupt.
- if(cell.sizeOfPArray()<1)
- cell.addNewP();
- bodyElements = new ArrayList<IBodyElement>();
- paragraphs = new ArrayList<XWPFParagraph>();
+ this.part = part;\r
+ this.tableRow = tableRow;\r
+ // NB: If a table cell does not include at least one block-level element, then this document shall be considered corrupt.\r
+ if (cell.sizeOfPArray() < 1)\r
+ cell.addNewP();\r
+ bodyElements = new ArrayList<IBodyElement>();\r
+ paragraphs = new ArrayList<XWPFParagraph>();\r
tables = new ArrayList<XWPFTable>();
XmlCursor cursor = ctTc.newCursor();
cursor.selectPath("./*");
- while (cursor.toNextSelection()) {
- XmlObject o = cursor.getObject();
- if (o instanceof CTP) {
- XWPFParagraph p = new XWPFParagraph((CTP)o, this);
- paragraphs.add(p);
- bodyElements.add(p);
- }
- if (o instanceof CTTbl) {
- XWPFTable t = new XWPFTable((CTTbl)o, this);
- tables.add(t);
- bodyElements.add(t);
- }
- if (o instanceof CTSdtBlock){
- XWPFSDT c = new XWPFSDT((CTSdtBlock)o, this);
- bodyElements.add(c);
- }
- if (o instanceof CTSdtRun){
- XWPFSDT c = new XWPFSDT((CTSdtRun)o, this);
- System.out.println(c.getContent().getText());
- bodyElements.add(c);
- }
- }
- cursor.dispose();
- }
-
-
- @Internal
- public CTTc getCTTc() {
- return ctTc;
- }
-
- /**
- * returns an Iterator with paragraphs and tables
- * @see org.apache.poi.xwpf.usermodel.IBody#getBodyElements()
- */
- public List<IBodyElement> getBodyElements(){
- return Collections.unmodifiableList(bodyElements);
+ while (cursor.toNextSelection()) {\r
+ XmlObject o = cursor.getObject();\r
+ if (o instanceof CTP) {\r
+ XWPFParagraph p = new XWPFParagraph((CTP) o, this);\r
+ paragraphs.add(p);\r
+ bodyElements.add(p);\r
+ }\r
+ if (o instanceof CTTbl) {\r
+ XWPFTable t = new XWPFTable((CTTbl) o, this);\r
+ tables.add(t);\r
+ bodyElements.add(t);\r
+ }\r
+ if (o instanceof CTSdtBlock) {\r
+ XWPFSDT c = new XWPFSDT((CTSdtBlock) o, this);\r
+ bodyElements.add(c);\r
+ }\r
+ if (o instanceof CTSdtRun) {\r
+ XWPFSDT c = new XWPFSDT((CTSdtRun) o, this);\r
+ System.out.println(c.getContent().getText());\r
+ bodyElements.add(c);\r
+ }\r
+ }\r
+ cursor.dispose();\r
+ }\r
+\r
+ @Internal\r
+ public CTTc getCTTc() {\r
+ return ctTc;\r
}
-
- public void setParagraph(XWPFParagraph p) {
- if (ctTc.sizeOfPArray() == 0) {
- ctTc.addNewP();
+\r
+ /**\r
+ * returns an Iterator with paragraphs and tables\r
+ *\r
+ * @see org.apache.poi.xwpf.usermodel.IBody#getBodyElements()\r
+ */\r
+ public List<IBodyElement> getBodyElements() {\r
+ return Collections.unmodifiableList(bodyElements);\r
+ }\r
+\r
+ public void setParagraph(XWPFParagraph p) {\r
+ if (ctTc.sizeOfPArray() == 0) {\r
+ ctTc.addNewP();\r
}
ctTc.setPArray(0, p.getCTP());
}
- /**
- * returns a list of paragraphs
- */
- public List<XWPFParagraph> getParagraphs(){
- return paragraphs;
- }
-
- /**
- * Add a Paragraph to this Table Cell
- * @return The paragraph which was added
- */
- public XWPFParagraph addParagraph() {
- XWPFParagraph p = new XWPFParagraph(ctTc.addNewP(), this);
- addParagraph(p);
- return p;
- }
-
- /**
- * add a Paragraph to this TableCell
- * @param p the paragaph which has to be added
- */
- public void addParagraph(XWPFParagraph p){
- paragraphs.add(p);
- }
-
- /**
- * removes a paragraph of this tablecell
- * @param pos
- */
- public void removeParagraph(int pos){
- paragraphs.remove(pos);
- ctTc.removeP(pos);
- }
-
- /**
- * if there is a corresponding {@link XWPFParagraph} of the parameter ctTable in the paragraphList of this table
- * the method will return this paragraph
- * if there is no corresponding {@link XWPFParagraph} the method will return null
- * @param p is instance of CTP and is searching for an XWPFParagraph
- * @return null if there is no XWPFParagraph with an corresponding CTPparagraph in the paragraphList of this table
- * XWPFParagraph with the correspondig CTP p
- */
- public XWPFParagraph getParagraph(CTP p){
- for (XWPFParagraph paragraph : paragraphs) {
- if(p.equals(paragraph.getCTP())){
- return paragraph;
- }
- }
- return null;
- }
-
- public void setText(String text) {
- CTP ctP = (ctTc.sizeOfPArray() == 0) ? ctTc.addNewP() : ctTc.getPArray(0);
- XWPFParagraph par = new XWPFParagraph(ctP, this);
- par.createRun().setText(text);
- }
-
- public XWPFTableRow getTableRow(){
- return tableRow;
- }
-
- /**
- * Set cell color. This sets some associated values; for finer control
- * you may want to access these elements individually.
- * @param rgbStr - the desired cell color, in the hex form "RRGGBB".
- */
- public void setColor(String rgbStr) {
- CTTcPr tcpr = ctTc.isSetTcPr() ? ctTc.getTcPr() : ctTc.addNewTcPr();
- CTShd ctshd = tcpr.isSetShd() ? tcpr.getShd() : tcpr.addNewShd();
- ctshd.setColor("auto");
- ctshd.setVal(STShd.CLEAR);
- ctshd.setFill(rgbStr);
- }
-
- /**
- * Get cell color. Note that this method only returns the "fill" value.
- * @return RGB string of cell color
- */
- public String getColor() {
- String color = null;
- CTTcPr tcpr = ctTc.getTcPr();
- if (tcpr != null) {
- CTShd ctshd = tcpr.getShd();
- if (ctshd != null) {
- color = ctshd.xgetFill().getStringValue();
- }
- }
- return color;
- }
-
- /**
- * Set the vertical alignment of the cell.
- * @param vAlign - the desired alignment enum value
- */
- public void setVerticalAlignment(XWPFVertAlign vAlign) {
- CTTcPr tcpr = ctTc.isSetTcPr() ? ctTc.getTcPr() : ctTc.addNewTcPr();
- CTVerticalJc va = tcpr.addNewVAlign();
- va.setVal(alignMap.get(vAlign));
- }
-
- /**
- * Get the vertical alignment of the cell.
- * @return the cell alignment enum value
- */
- public XWPFVertAlign getVerticalAlignment() {
- XWPFVertAlign vAlign = null;
- CTTcPr tcpr = ctTc.getTcPr();
- if (ctTc != null) {
- CTVerticalJc va = tcpr.getVAlign();
- vAlign = stVertAlignTypeMap.get(va.getVal().intValue());
- }
- return vAlign;
- }
-
- /**
- * add a new paragraph at position of the cursor
- * @param cursor
- * @return the inserted paragraph
- */
- public XWPFParagraph insertNewParagraph(XmlCursor cursor){
- if(!isCursorInTableCell(cursor)) {
- return null;
- }
-
- String uri = CTP.type.getName().getNamespaceURI();
- String localPart = "p";
- cursor.beginElement(localPart,uri);
- cursor.toParent();
- CTP p = (CTP)cursor.getObject();
- XWPFParagraph newP = new XWPFParagraph(p, this);
- XmlObject o = null;
- while(!(o instanceof CTP)&&(cursor.toPrevSibling())){
- o = cursor.getObject();
- }
- if((!(o instanceof CTP)) || (CTP)o == p){
- paragraphs.add(0, newP);
- }
- else{
- int pos = paragraphs.indexOf(getParagraph((CTP)o))+1;
- paragraphs.add(pos,newP);
- }
- int i=0;
- cursor.toCursor(p.newCursor());
- while(cursor.toPrevSibling()){
- o =cursor.getObject();
- if(o instanceof CTP || o instanceof CTTbl)
- i++;
- }
- bodyElements.add(i, newP);
- cursor.toCursor(p.newCursor());
- cursor.toEndToken();
- return newP;
- }
-
- public XWPFTable insertNewTbl(XmlCursor cursor) {
- if(isCursorInTableCell(cursor)){
- String uri = CTTbl.type.getName().getNamespaceURI();
- String localPart = "tbl";
- cursor.beginElement(localPart,uri);
- cursor.toParent();
- CTTbl t = (CTTbl)cursor.getObject();
- XWPFTable newT = new XWPFTable(t, this);
- cursor.removeXmlContents();
- XmlObject o = null;
- while(!(o instanceof CTTbl)&&(cursor.toPrevSibling())){
- o = cursor.getObject();
- }
- if(!(o instanceof CTTbl)){
- tables.add(0, newT);
- }
- else{
- int pos = tables.indexOf(getTable((CTTbl)o))+1;
- tables.add(pos,newT);
- }
- int i=0;
- cursor = t.newCursor();
- while(cursor.toPrevSibling()){
- o =cursor.getObject();
- if(o instanceof CTP || o instanceof CTTbl)
- i++;
- }
- bodyElements.add(i, newT);
- cursor = t.newCursor();
- cursor.toEndToken();
- return newT;
- }
- return null;
- }
-
- /**
- * verifies that cursor is on the right position
- */
- private boolean isCursorInTableCell(XmlCursor cursor) {
- XmlCursor verify = cursor.newCursor();
- verify.toParent();
- if(verify.getObject() == this.ctTc){
- return true;
- }
- return false;
- }
-
-
-
- /**
- * @see org.apache.poi.xwpf.usermodel.IBody#getParagraphArray(int)
- */
- public XWPFParagraph getParagraphArray(int pos) {
- if(pos > 0 && pos < paragraphs.size()){
- return paragraphs.get(pos);
- }
- return null;
- }
-
- /**
- * get the to which the TableCell belongs
- *
- * @see org.apache.poi.xwpf.usermodel.IBody#getPart()
- */
- public POIXMLDocumentPart getPart() {
- return tableRow.getTable().getPart();
- }
-
- /**
- * @see org.apache.poi.xwpf.usermodel.IBody#getPartType()
- */
- public BodyType getPartType() {
- return BodyType.TABLECELL;
- }
-
-
- /**
- * get a table by its CTTbl-Object
- * @see org.apache.poi.xwpf.usermodel.IBody#getTable(org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTbl)
- */
- public XWPFTable getTable(CTTbl ctTable) {
- for(int i=0; i<tables.size(); i++){
- if(getTables().get(i).getCTTbl() == ctTable) return getTables().get(i);
- }
- return null;
- }
-
-
- /**
- * @see org.apache.poi.xwpf.usermodel.IBody#getTableArray(int)
- */
- public XWPFTable getTableArray(int pos) {
- if(pos > 0 && pos < tables.size()){
- return tables.get(pos);
- }
- return null;
- }
-
-
- /**
- * @see org.apache.poi.xwpf.usermodel.IBody#getTables()
- */
- public List<XWPFTable> getTables() {
- return Collections.unmodifiableList(tables);
- }
-
-
- /**
- * inserts an existing XWPFTable to the arrays bodyElements and tables
- * @see org.apache.poi.xwpf.usermodel.IBody#insertTable(int, org.apache.poi.xwpf.usermodel.XWPFTable)
- */
- @SuppressWarnings("deprecation")
+ /**\r
+ * returns a list of paragraphs\r
+ */\r
+ public List<XWPFParagraph> getParagraphs() {\r
+ return paragraphs;\r
+ }\r
+\r
+ /**\r
+ * Add a Paragraph to this Table Cell\r
+ *\r
+ * @return The paragraph which was added\r
+ */\r
+ public XWPFParagraph addParagraph() {\r
+ XWPFParagraph p = new XWPFParagraph(ctTc.addNewP(), this);\r
+ addParagraph(p);\r
+ return p;\r
+ }\r
+\r
+ /**\r
+ * add a Paragraph to this TableCell\r
+ *\r
+ * @param p the paragaph which has to be added\r
+ */\r
+ public void addParagraph(XWPFParagraph p) {\r
+ paragraphs.add(p);\r
+ }\r
+\r
+ /**\r
+ * removes a paragraph of this tablecell\r
+ *\r
+ * @param pos\r
+ */\r
+ public void removeParagraph(int pos) {\r
+ paragraphs.remove(pos);\r
+ ctTc.removeP(pos);\r
+ }\r
+\r
+ /**\r
+ * if there is a corresponding {@link XWPFParagraph} of the parameter ctTable in the paragraphList of this table\r
+ * the method will return this paragraph\r
+ * if there is no corresponding {@link XWPFParagraph} the method will return null\r
+ *\r
+ * @param p is instance of CTP and is searching for an XWPFParagraph\r
+ * @return null if there is no XWPFParagraph with an corresponding CTPparagraph in the paragraphList of this table\r
+ * XWPFParagraph with the correspondig CTP p\r
+ */\r
+ public XWPFParagraph getParagraph(CTP p) {\r
+ for (XWPFParagraph paragraph : paragraphs) {\r
+ if (p.equals(paragraph.getCTP())) {\r
+ return paragraph;\r
+ }\r
+ }\r
+ return null;\r
+ }\r
+\r
+ public XWPFTableRow getTableRow() {\r
+ return tableRow;\r
+ }\r
+\r
+ /**\r
+ * Get cell color. Note that this method only returns the "fill" value.\r
+ *\r
+ * @return RGB string of cell color\r
+ */\r
+ public String getColor() {\r
+ String color = null;\r
+ CTTcPr tcpr = ctTc.getTcPr();\r
+ if (tcpr != null) {\r
+ CTShd ctshd = tcpr.getShd();\r
+ if (ctshd != null) {\r
+ color = ctshd.xgetFill().getStringValue();\r
+ }\r
+ }\r
+ return color;\r
+ }\r
+\r
+ /**\r
+ * Set cell color. This sets some associated values; for finer control\r
+ * you may want to access these elements individually.\r
+ *\r
+ * @param rgbStr - the desired cell color, in the hex form "RRGGBB".\r
+ */\r
+ public void setColor(String rgbStr) {\r
+ CTTcPr tcpr = ctTc.isSetTcPr() ? ctTc.getTcPr() : ctTc.addNewTcPr();\r
+ CTShd ctshd = tcpr.isSetShd() ? tcpr.getShd() : tcpr.addNewShd();\r
+ ctshd.setColor("auto");\r
+ ctshd.setVal(STShd.CLEAR);\r
+ ctshd.setFill(rgbStr);\r
+ }\r
+\r
+ /**\r
+ * Get the vertical alignment of the cell.\r
+ *\r
+ * @return the cell alignment enum value\r
+ */\r
+ public XWPFVertAlign getVerticalAlignment() {\r
+ XWPFVertAlign vAlign = null;\r
+ CTTcPr tcpr = ctTc.getTcPr();\r
+ if (ctTc != null) {\r
+ CTVerticalJc va = tcpr.getVAlign();\r
+ vAlign = stVertAlignTypeMap.get(va.getVal().intValue());\r
+ }\r
+ return vAlign;\r
+ }\r
+\r
+ /**\r
+ * Set the vertical alignment of the cell.\r
+ *\r
+ * @param vAlign - the desired alignment enum value\r
+ */\r
+ public void setVerticalAlignment(XWPFVertAlign vAlign) {\r
+ CTTcPr tcpr = ctTc.isSetTcPr() ? ctTc.getTcPr() : ctTc.addNewTcPr();\r
+ CTVerticalJc va = tcpr.addNewVAlign();\r
+ va.setVal(alignMap.get(vAlign));\r
+ }\r
+\r
+ /**\r
+ * add a new paragraph at position of the cursor\r
+ *\r
+ * @param cursor\r
+ * @return the inserted paragraph\r
+ */\r
+ public XWPFParagraph insertNewParagraph(XmlCursor cursor) {\r
+ if (!isCursorInTableCell(cursor)) {\r
+ return null;\r
+ }\r
+\r
+ String uri = CTP.type.getName().getNamespaceURI();\r
+ String localPart = "p";\r
+ cursor.beginElement(localPart, uri);\r
+ cursor.toParent();\r
+ CTP p = (CTP) cursor.getObject();\r
+ XWPFParagraph newP = new XWPFParagraph(p, this);\r
+ XmlObject o = null;\r
+ while (!(o instanceof CTP) && (cursor.toPrevSibling())) {\r
+ o = cursor.getObject();\r
+ }\r
+ if ((!(o instanceof CTP)) || (CTP) o == p) {\r
+ paragraphs.add(0, newP);\r
+ } else {\r
+ int pos = paragraphs.indexOf(getParagraph((CTP) o)) + 1;\r
+ paragraphs.add(pos, newP);\r
+ }\r
+ int i = 0;\r
+ cursor.toCursor(p.newCursor());\r
+ while (cursor.toPrevSibling()) {\r
+ o = cursor.getObject();\r
+ if (o instanceof CTP || o instanceof CTTbl)\r
+ i++;\r
+ }\r
+ bodyElements.add(i, newP);\r
+ cursor.toCursor(p.newCursor());\r
+ cursor.toEndToken();\r
+ return newP;\r
+ }\r
+\r
+ public XWPFTable insertNewTbl(XmlCursor cursor) {\r
+ if (isCursorInTableCell(cursor)) {\r
+ String uri = CTTbl.type.getName().getNamespaceURI();\r
+ String localPart = "tbl";\r
+ cursor.beginElement(localPart, uri);\r
+ cursor.toParent();\r
+ CTTbl t = (CTTbl) cursor.getObject();\r
+ XWPFTable newT = new XWPFTable(t, this);\r
+ cursor.removeXmlContents();\r
+ XmlObject o = null;\r
+ while (!(o instanceof CTTbl) && (cursor.toPrevSibling())) {\r
+ o = cursor.getObject();\r
+ }\r
+ if (!(o instanceof CTTbl)) {\r
+ tables.add(0, newT);\r
+ } else {\r
+ int pos = tables.indexOf(getTable((CTTbl) o)) + 1;\r
+ tables.add(pos, newT);\r
+ }\r
+ int i = 0;\r
+ cursor = t.newCursor();\r
+ while (cursor.toPrevSibling()) {\r
+ o = cursor.getObject();\r
+ if (o instanceof CTP || o instanceof CTTbl)\r
+ i++;\r
+ }\r
+ bodyElements.add(i, newT);\r
+ cursor = t.newCursor();\r
+ cursor.toEndToken();\r
+ return newT;\r
+ }\r
+ return null;\r
+ }\r
+\r
+ /**\r
+ * verifies that cursor is on the right position\r
+ */\r
+ private boolean isCursorInTableCell(XmlCursor cursor) {\r
+ XmlCursor verify = cursor.newCursor();\r
+ verify.toParent();\r
+ if (verify.getObject() == this.ctTc) {\r
+ return true;\r
+ }\r
+ return false;\r
+ }\r
+\r
+ /**\r
+ * @see org.apache.poi.xwpf.usermodel.IBody#getParagraphArray(int)\r
+ */\r
+ public XWPFParagraph getParagraphArray(int pos) {\r
+ if (pos > 0 && pos < paragraphs.size()) {\r
+ return paragraphs.get(pos);\r
+ }\r
+ return null;\r
+ }\r
+\r
+ /**\r
+ * get the to which the TableCell belongs\r
+ *\r
+ * @see org.apache.poi.xwpf.usermodel.IBody#getPart()\r
+ */\r
+ public POIXMLDocumentPart getPart() {\r
+ return tableRow.getTable().getPart();\r
+ }\r
+\r
+ /**\r
+ * @see org.apache.poi.xwpf.usermodel.IBody#getPartType()\r
+ */\r
+ public BodyType getPartType() {\r
+ return BodyType.TABLECELL;\r
+ }\r
+\r
+ /**\r
+ * get a table by its CTTbl-Object\r
+ *\r
+ * @see org.apache.poi.xwpf.usermodel.IBody#getTable(org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTbl)\r
+ */\r
+ public XWPFTable getTable(CTTbl ctTable) {\r
+ for (int i = 0; i < tables.size(); i++) {\r
+ if (getTables().get(i).getCTTbl() == ctTable) return getTables().get(i);\r
+ }\r
+ return null;\r
+ }\r
+\r
+ /**\r
+ * @see org.apache.poi.xwpf.usermodel.IBody#getTableArray(int)\r
+ */\r
+ public XWPFTable getTableArray(int pos) {\r
+ if (pos > 0 && pos < tables.size()) {\r
+ return tables.get(pos);\r
+ }\r
+ return null;\r
+ }\r
+\r
+ /**\r
+ * @see org.apache.poi.xwpf.usermodel.IBody#getTables()\r
+ */\r
+ public List<XWPFTable> getTables() {\r
+ return Collections.unmodifiableList(tables);\r
+ }\r
+\r
+ /**\r
+ * inserts an existing XWPFTable to the arrays bodyElements and tables\r
+ *\r
+ * @see org.apache.poi.xwpf.usermodel.IBody#insertTable(int, org.apache.poi.xwpf.usermodel.XWPFTable)\r
+ */\r
+ @SuppressWarnings("deprecation")\r
public void insertTable(int pos, XWPFTable table) {
bodyElements.add(pos, table);
int i = 0;
}
i++;
}
- tables.add(i, table);
- }
-
- public String getText(){
- StringBuffer text = new StringBuffer();
- for (XWPFParagraph p : paragraphs) {
- text.append(p.getText());
- }
- return text.toString();
- }
-
- /**
- * extracts all text recursively through embedded tables and embedded SDTs
- */
- public String getTextRecursively(){
-
- StringBuffer text = new StringBuffer();
- for (int i = 0; i < bodyElements.size(); i++){
- boolean isLast = (i== bodyElements.size()-1)? true : false;
- appendBodyElementText(text, bodyElements.get(i), isLast);
- }
-
- return text.toString();
- }
-
- private void appendBodyElementText(StringBuffer text, IBodyElement e, boolean isLast){
- if (e instanceof XWPFParagraph){
- text.append(((XWPFParagraph)e).getText());
- if (isLast == false){
- text.append('\t');
- }
- } else if (e instanceof XWPFTable){
- XWPFTable eTable = (XWPFTable)e;
- for (XWPFTableRow row : eTable.getRows()){
- for (XWPFTableCell cell : row.getTableCells()){
- List<IBodyElement> localBodyElements = cell.getBodyElements();
- for (int i = 0; i < localBodyElements.size(); i++){
- boolean localIsLast = (i== localBodyElements.size()-1)? true : false;
- appendBodyElementText(text, localBodyElements.get(i), localIsLast);
- }
- }
- }
-
- if (isLast == false){
- text.append('\n');
- }
- } else if (e instanceof XWPFSDT){
- text.append(((XWPFSDT)e).getContent().getText());
- if (isLast == false){
- text.append('\t');
- }
- }
+ tables.add(i, table);\r
+ }\r
+\r
+ public String getText() {\r
+ StringBuffer text = new StringBuffer();\r
+ for (XWPFParagraph p : paragraphs) {\r
+ text.append(p.getText());\r
+ }\r
+ return text.toString();\r
+ }\r
+\r
+ public void setText(String text) {\r
+ CTP ctP = (ctTc.sizeOfPArray() == 0) ? ctTc.addNewP() : ctTc.getPArray(0);\r
+ XWPFParagraph par = new XWPFParagraph(ctP, this);\r
+ par.createRun().setText(text);\r
+ }\r
+\r
+ /**\r
+ * extracts all text recursively through embedded tables and embedded SDTs\r
+ */\r
+ public String getTextRecursively() {\r
+\r
+ StringBuffer text = new StringBuffer();\r
+ for (int i = 0; i < bodyElements.size(); i++) {\r
+ boolean isLast = (i == bodyElements.size() - 1) ? true : false;\r
+ appendBodyElementText(text, bodyElements.get(i), isLast);\r
+ }\r
+\r
+ return text.toString();\r
+ }\r
+\r
+ private void appendBodyElementText(StringBuffer text, IBodyElement e, boolean isLast) {\r
+ if (e instanceof XWPFParagraph) {\r
+ text.append(((XWPFParagraph) e).getText());\r
+ if (isLast == false) {\r
+ text.append('\t');\r
+ }\r
+ } else if (e instanceof XWPFTable) {\r
+ XWPFTable eTable = (XWPFTable) e;\r
+ for (XWPFTableRow row : eTable.getRows()) {\r
+ for (XWPFTableCell cell : row.getTableCells()) {\r
+ List<IBodyElement> localBodyElements = cell.getBodyElements();\r
+ for (int i = 0; i < localBodyElements.size(); i++) {\r
+ boolean localIsLast = (i == localBodyElements.size() - 1) ? true : false;\r
+ appendBodyElementText(text, localBodyElements.get(i), localIsLast);\r
+ }\r
+ }\r
+ }\r
+\r
+ if (isLast == false) {\r
+ text.append('\n');\r
+ }\r
+ } else if (e instanceof XWPFSDT) {\r
+ text.append(((XWPFSDT) e).getContent().getText());\r
+ if (isLast == false) {\r
+ text.append('\t');\r
+ }\r
+ }\r
}
/**
- * get the TableCell which belongs to the TableCell
- */
- public XWPFTableCell getTableCell(CTTc cell) {
- XmlCursor cursor = cell.newCursor();
- cursor.toParent();
- XmlObject o = cursor.getObject();
- if(!(o instanceof CTRow)){
- return null;
- }
- CTRow row = (CTRow)o;
- cursor.toParent();
- o = cursor.getObject();
- cursor.dispose();
- if(! (o instanceof CTTbl)){
- return null;
- }
- CTTbl tbl = (CTTbl) o;
- XWPFTable table = getTable(tbl);
- if(table == null){
- return null;
- }
- XWPFTableRow tableRow = table.getRow(row);
- if (tableRow == null) {
- return null;
- }
- return tableRow.getTableCell(cell);
- }
-
- public XWPFDocument getXWPFDocument() {
- return part.getXWPFDocument();
- }
-}
+ * get the TableCell which belongs to the TableCell\r
+ */\r
+ public XWPFTableCell getTableCell(CTTc cell) {\r
+ XmlCursor cursor = cell.newCursor();\r
+ cursor.toParent();\r
+ XmlObject o = cursor.getObject();\r
+ if (!(o instanceof CTRow)) {\r
+ return null;\r
+ }\r
+ CTRow row = (CTRow) o;\r
+ cursor.toParent();\r
+ o = cursor.getObject();\r
+ cursor.dispose();\r
+ if (!(o instanceof CTTbl)) {\r
+ return null;\r
+ }\r
+ CTTbl tbl = (CTTbl) o;\r
+ XWPFTable table = getTable(tbl);\r
+ if (table == null) {\r
+ return null;\r
+ }\r
+ XWPFTableRow tableRow = table.getRow(row);\r
+ if (tableRow == null) {\r
+ return null;\r
+ }\r
+ return tableRow.getTableCell(cell);\r
+ }\r
+\r
+ public XWPFDocument getXWPFDocument() {\r
+ return part.getXWPFDocument();\r
+ }\r
+\r
+ // Create a map from this XWPF-level enum to the STVerticalJc.Enum values\r
+ public static enum XWPFVertAlign {\r
+ TOP, CENTER, BOTH, BOTTOM\r
+ }\r
+}\r
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTrPr;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.STOnOff;
-
-/**
- * A row within an {@link XWPFTable}. Rows mostly just have
- * sizings and stylings, the interesting content lives inside
- * the child {@link XWPFTableCell}s
- */
-public class XWPFTableRow {
- private CTRow ctRow;
+\r
+/**\r
+ * A row within an {@link XWPFTable}. Rows mostly just have\r
+ * sizings and stylings, the interesting content lives inside\r
+ * the child {@link XWPFTableCell}s\r
+ */\r
+public class XWPFTableRow {\r
+ private CTRow ctRow;\r
private XWPFTable table;
private List<XWPFTableCell> tableCells;
public CTRow getCtRow() {
return ctRow;
}
-
- /**
- * create a new XWPFTableCell and add it to the tableCell-list of this tableRow
- * @return the newly created XWPFTableCell
- */
- public XWPFTableCell createCell() {
- XWPFTableCell tableCell = new XWPFTableCell(ctRow.addNewTc(), this, table.getBody());
- tableCells.add(tableCell);
- return tableCell;
- }
-
- public XWPFTableCell getCell(int pos) {
- if (pos >= 0 && pos < ctRow.sizeOfTcArray()) {
- return getTableCells().get(pos);
- }
- return null;
- }
-
- public void removeCell(int pos) {
- if (pos >= 0 && pos < ctRow.sizeOfTcArray()) {
- tableCells.remove(pos);
- }
- }
- /**
- * adds a new TableCell at the end of this tableRow
- */
- public XWPFTableCell addNewTableCell(){
- CTTc cell = ctRow.addNewTc();
- XWPFTableCell tableCell = new XWPFTableCell(cell, this, table.getBody());
- tableCells.add(tableCell);
- return tableCell;
- }
-
- /**
+\r
+ /**\r
+ * create a new XWPFTableCell and add it to the tableCell-list of this tableRow\r
+ *\r
+ * @return the newly created XWPFTableCell\r
+ */\r
+ public XWPFTableCell createCell() {\r
+ XWPFTableCell tableCell = new XWPFTableCell(ctRow.addNewTc(), this, table.getBody());\r
+ tableCells.add(tableCell);\r
+ return tableCell;\r
+ }\r
+\r
+ public XWPFTableCell getCell(int pos) {\r
+ if (pos >= 0 && pos < ctRow.sizeOfTcArray()) {\r
+ return getTableCells().get(pos);\r
+ }\r
+ return null;\r
+ }\r
+\r
+ public void removeCell(int pos) {\r
+ if (pos >= 0 && pos < ctRow.sizeOfTcArray()) {\r
+ tableCells.remove(pos);\r
+ }\r
+ }\r
+\r
+ /**\r
+ * adds a new TableCell at the end of this tableRow\r
+ */\r
+ public XWPFTableCell addNewTableCell() {\r
+ CTTc cell = ctRow.addNewTc();\r
+ XWPFTableCell tableCell = new XWPFTableCell(cell, this, table.getBody());\r
+ tableCells.add(tableCell);\r
+ return tableCell;\r
+ }\r
+\r
+ /**\r
* This element specifies the height of the current table row within the
* current table. This height shall be used to determine the resulting
* height of the table row, which may be absolute or relative (depending on
* its attribute values). If omitted, then the table row shall automatically
- * resize its height to the height required by its contents (the equivalent
- * of an hRule value of auto).
- *
- * @param height
- */
- public void setHeight(int height) {
- CTTrPr properties = getTrPr();
- CTHeight h = properties.sizeOfTrHeightArray() == 0 ? properties.addNewTrHeight() : properties.getTrHeightArray(0);
- h.setVal(new BigInteger("" + height));
- }
-
- /**
+ * resize its height to the height required by its contents (the equivalent\r
+ * of an hRule value of auto).\r
+ *\r
+ * @return height\r
+ */\r
+ public int getHeight() {\r
+ CTTrPr properties = getTrPr();\r
+ return properties.sizeOfTrHeightArray() == 0 ? 0 : properties.getTrHeightArray(0).getVal().intValue();\r
+ }\r
+\r
+ /**\r
* This element specifies the height of the current table row within the
* current table. This height shall be used to determine the resulting
* height of the table row, which may be absolute or relative (depending on
* its attribute values). If omitted, then the table row shall automatically
- * resize its height to the height required by its contents (the equivalent
- * of an hRule value of auto).
- *
- * @return height
- */
- public int getHeight() {
- CTTrPr properties = getTrPr();
- return properties.sizeOfTrHeightArray() == 0 ? 0 : properties.getTrHeightArray(0).getVal().intValue();
- }
-
- private CTTrPr getTrPr() {
- return (ctRow.isSetTrPr()) ? ctRow.getTrPr() : ctRow.addNewTrPr();
- }
-
- public XWPFTable getTable(){
- return table;
- }
-
- /**
- * create and return a list of all XWPFTableCell
- * who belongs to this row
- * @return a list of {@link XWPFTableCell}
- */
- public List<ICell> getTableICells(){
-
- List<ICell> cells = new ArrayList<ICell>();
- //Can't use ctRow.getTcList because that only gets table cells
- //Can't use ctRow.getSdtList because that only gets sdts that are at cell level
+ * resize its height to the height required by its contents (the equivalent\r
+ * of an hRule value of auto).\r
+ *\r
+ * @param height\r
+ */\r
+ public void setHeight(int height) {\r
+ CTTrPr properties = getTrPr();\r
+ CTHeight h = properties.sizeOfTrHeightArray() == 0 ? properties.addNewTrHeight() : properties.getTrHeightArray(0);\r
+ h.setVal(new BigInteger("" + height));\r
+ }\r
+\r
+ private CTTrPr getTrPr() {\r
+ return (ctRow.isSetTrPr()) ? ctRow.getTrPr() : ctRow.addNewTrPr();\r
+ }\r
+\r
+ public XWPFTable getTable() {\r
+ return table;\r
+ }\r
+\r
+ /**\r
+ * create and return a list of all XWPFTableCell\r
+ * who belongs to this row\r
+ *\r
+ * @return a list of {@link XWPFTableCell}\r
+ */\r
+ public List<ICell> getTableICells() {\r
+\r
+ List<ICell> cells = new ArrayList<ICell>();\r
+ //Can't use ctRow.getTcList because that only gets table cells\r
+ //Can't use ctRow.getSdtList because that only gets sdts that are at cell level\r
XmlCursor cursor = ctRow.newCursor();
- cursor.selectPath("./*");
- while (cursor.toNextSelection()) {
- XmlObject o = cursor.getObject();
- if (o instanceof CTTc){
- cells.add(new XWPFTableCell((CTTc)o, this, table.getBody()));
- } else if (o instanceof CTSdtCell) {
- cells.add(new XWPFSDTCell((CTSdtCell)o, this, table.getBody()));
- }
- }
- return cells;
- }
-
- /**
- * create and return a list of all XWPFTableCell
- * who belongs to this row
- * @return a list of {@link XWPFTableCell}
- */
- @SuppressWarnings("deprecation")
- public List<XWPFTableCell> getTableCells(){
- if(tableCells == null){
- List<XWPFTableCell> cells = new ArrayList<XWPFTableCell>();
- for (CTTc tableCell : ctRow.getTcArray()) {
- cells.add(new XWPFTableCell(tableCell, this, table.getBody()));
- }
- //TODO: it is possible to have an SDT that contains a cell in within a row
- //need to modify this code so that it pulls out SDT wrappers around cells, too.
-
- this.tableCells = cells;
- }
- return tableCells;
- }
-
- /**
+ cursor.selectPath("./*");\r
+ while (cursor.toNextSelection()) {\r
+ XmlObject o = cursor.getObject();\r
+ if (o instanceof CTTc) {\r
+ cells.add(new XWPFTableCell((CTTc) o, this, table.getBody()));\r
+ } else if (o instanceof CTSdtCell) {\r
+ cells.add(new XWPFSDTCell((CTSdtCell) o, this, table.getBody()));\r
+ }\r
+ }\r
+ return cells;\r
+ }
+
+ /**\r
+ * create and return a list of all XWPFTableCell\r
+ * who belongs to this row\r
+ *\r
+ * @return a list of {@link XWPFTableCell}\r
+ */\r
+ @SuppressWarnings("deprecation")\r
+ public List<XWPFTableCell> getTableCells() {\r
+ if (tableCells == null) {\r
+ List<XWPFTableCell> cells = new ArrayList<XWPFTableCell>();\r
+ for (CTTc tableCell : ctRow.getTcArray()) {\r
+ cells.add(new XWPFTableCell(tableCell, this, table.getBody()));\r
+ }\r
+ //TODO: it is possible to have an SDT that contains a cell in within a row\r
+ //need to modify this code so that it pulls out SDT wrappers around cells, too.\r
+\r
+ this.tableCells = cells;\r
+ }\r
+ return tableCells;\r
+ }\r
+\r
+ /**\r
* returns the XWPFTableCell which belongs to the CTTC cell
- * if there is no XWPFTableCell which belongs to the parameter CTTc cell null will be returned
- */
- public XWPFTableCell getTableCell(CTTc cell) {
- for(int i=0; i<tableCells.size(); i++){
- if (tableCells.get(i).getCTTc() == cell)
- return tableCells.get(i);
- }
- return null;
- }
-
- /**
- * This attribute controls whether to allow table rows to split across pages.
- * The logic for this attribute is a little unusual: a true value means
- * DON'T allow rows to split, false means allow rows to split.
- * @param split - if true, don't allow rows to be split. If false, allow
- * rows to be split.
- */
- public void setCantSplitRow(boolean split) {
- CTTrPr trpr = getTrPr();
- CTOnOff onoff = trpr.addNewCantSplit();
- onoff.setVal(split ? STOnOff.ON : STOnOff.OFF);
- }
-
- /**
- * Return true if the "can't split row" value is true. The logic for this
- * attribute is a little unusual: a TRUE value means DON'T allow rows to
- * split, FALSE means allow rows to split.
- * @return true if rows can't be split, false otherwise.
- */
- public boolean isCantSplitRow() {
- boolean isCant = false;
- CTTrPr trpr = getTrPr();
- if (trpr.sizeOfCantSplitArray() > 0) {
- CTOnOff onoff = trpr.getCantSplitArray(0);
- isCant = onoff.getVal().equals(STOnOff.ON);
- }
- return isCant;
- }
-
- /**
- * This attribute controls whether to repeat a table's header row at the top
- * of a table split across pages.
- * @param repeat - if TRUE, repeat header row at the top of each page of table;
- * if FALSE, don't repeat header row.
- */
- public void setRepeatHeader(boolean repeat) {
- CTTrPr trpr = getTrPr();
- CTOnOff onoff = trpr.addNewTblHeader();
- onoff.setVal(repeat ? STOnOff.ON : STOnOff.OFF);
- }
-
- /**
- * Return true if a table's header row should be repeated at the top of a
- * table split across pages.
- * @return true if table's header row should be repeated at the top of each
- * page of table, false otherwise.
- */
- public boolean isRepeatHeader() {
- boolean repeat = false;
- CTTrPr trpr = getTrPr();
- if (trpr.sizeOfTblHeaderArray() > 0) {
- CTOnOff rpt = trpr.getTblHeaderArray(0);
- repeat = rpt.getVal().equals(STOnOff.ON);
- }
- return repeat;
- }
-}
+ * if there is no XWPFTableCell which belongs to the parameter CTTc cell null will be returned\r
+ */\r
+ public XWPFTableCell getTableCell(CTTc cell) {\r
+ for (int i = 0; i < tableCells.size(); i++) {\r
+ if (tableCells.get(i).getCTTc() == cell)\r
+ return tableCells.get(i);\r
+ }\r
+ return null;\r
+ }\r
+\r
+ /**\r
+ * Return true if the "can't split row" value is true. The logic for this\r
+ * attribute is a little unusual: a TRUE value means DON'T allow rows to\r
+ * split, FALSE means allow rows to split.\r
+ *\r
+ * @return true if rows can't be split, false otherwise.\r
+ */\r
+ public boolean isCantSplitRow() {\r
+ boolean isCant = false;\r
+ CTTrPr trpr = getTrPr();\r
+ if (trpr.sizeOfCantSplitArray() > 0) {\r
+ CTOnOff onoff = trpr.getCantSplitArray(0);\r
+ isCant = onoff.getVal().equals(STOnOff.ON);\r
+ }\r
+ return isCant;\r
+ }\r
+\r
+ /**\r
+ * This attribute controls whether to allow table rows to split across pages.\r
+ * The logic for this attribute is a little unusual: a true value means\r
+ * DON'T allow rows to split, false means allow rows to split.\r
+ *\r
+ * @param split - if true, don't allow rows to be split. If false, allow\r
+ * rows to be split.\r
+ */\r
+ public void setCantSplitRow(boolean split) {\r
+ CTTrPr trpr = getTrPr();\r
+ CTOnOff onoff = trpr.addNewCantSplit();\r
+ onoff.setVal(split ? STOnOff.ON : STOnOff.OFF);\r
+ }\r
+\r
+ /**\r
+ * Return true if a table's header row should be repeated at the top of a\r
+ * table split across pages.\r
+ *\r
+ * @return true if table's header row should be repeated at the top of each\r
+ * page of table, false otherwise.\r
+ */\r
+ public boolean isRepeatHeader() {\r
+ boolean repeat = false;\r
+ CTTrPr trpr = getTrPr();\r
+ if (trpr.sizeOfTblHeaderArray() > 0) {\r
+ CTOnOff rpt = trpr.getTblHeaderArray(0);\r
+ repeat = rpt.getVal().equals(STOnOff.ON);\r
+ }\r
+ return repeat;\r
+ }\r
+\r
+ /**\r
+ * This attribute controls whether to repeat a table's header row at the top\r
+ * of a table split across pages.\r
+ *\r
+ * @param repeat - if TRUE, repeat header row at the top of each page of table;\r
+ * if FALSE, don't repeat header row.\r
+ */\r
+ public void setRepeatHeader(boolean repeat) {\r
+ CTTrPr trpr = getTrPr();\r
+ CTOnOff onoff = trpr.addNewTblHeader();\r
+ onoff.setVal(repeat ? STOnOff.ON : STOnOff.OFF);\r
+ }\r
+}\r
/**
* Collects all tests for <tt>org.apache.poi.xwpf</tt> and sub-packages.
- */
-@RunWith(Suite.class)
-@Suite.SuiteClasses({
- TestXWPFBugs.class,
- org.apache.poi.xwpf.usermodel.TestXWPFBugs.class,
- TestXWPFDocument.class,
- TestXWPFWordExtractor.class,
- TestXWPFHeaderFooterPolicy.class,
- TestXWPFHeader.class,
- TestXWPFHeadings.class,
- TestXWPFParagraph.class,
- TestXWPFRun.class,
- TestXWPFTable.class,
- TestXWPFStyles.class,
- TestXWPFPictureData.class,
- TestXWPFNumbering.class,
- TestAllExtendedProperties.class,
- TestPackageCorePropertiesGetKeywords.class
-})
-public final class AllXWPFTests {
+ */\r
+@RunWith(Suite.class)\r
+@Suite.SuiteClasses({\r
+ TestXWPFBugs.class,\r
+ org.apache.poi.xwpf.usermodel.TestXWPFBugs.class,\r
+ TestXWPFDocument.class,\r
+ TestXWPFWordExtractor.class,\r
+ TestXWPFHeaderFooterPolicy.class,\r
+ TestXWPFHeader.class,\r
+ TestXWPFHeadings.class,\r
+ TestXWPFParagraph.class,\r
+ TestXWPFRun.class,\r
+ TestXWPFTable.class,\r
+ TestXWPFStyles.class,\r
+ TestXWPFPictureData.class,\r
+ TestXWPFNumbering.class,\r
+ TestAllExtendedProperties.class,\r
+ TestPackageCorePropertiesGetKeywords.class\r
+})\r
+public final class AllXWPFTests {\r
}
\ No newline at end of file
package org.apache.poi.xwpf;
-import java.io.IOException;
-
-import junit.framework.TestCase;
-
-import org.apache.poi.POIXMLProperties.CoreProperties;
-import org.apache.poi.openxml4j.opc.PackageProperties;
-import org.apache.poi.xwpf.usermodel.XWPFDocument;
+import java.io.IOException;\r
+\r
+import junit.framework.TestCase;\r
+import org.apache.poi.POIXMLProperties.CoreProperties;\r
+import org.apache.poi.openxml4j.opc.PackageProperties;\r
+import org.apache.poi.xwpf.usermodel.XWPFDocument;\r
import org.openxmlformats.schemas.officeDocument.x2006.extendedProperties.CTDigSigBlob;
import org.openxmlformats.schemas.officeDocument.x2006.extendedProperties.CTProperties;
import org.openxmlformats.schemas.officeDocument.x2006.extendedProperties.CTVectorLpstr;
/**
* Tests if the {@link CoreProperties#getKeywords()} method. This test has been
- * submitted because even though the
- * {@link PackageProperties#getKeywordsProperty()} had been present before, the
- * {@link CoreProperties#getKeywords()} had been missing.
- *
- * The author of this has added {@link CoreProperties#getKeywords()} and
- * {@link CoreProperties#setKeywords(String)} and this test is supposed to test
- * them.
- *
- * @author Antoni Mylka
- *
- */
-public final class TestAllExtendedProperties extends TestCase {
- public void testGetAllExtendedProperties() throws IOException {
- XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("TestPoiXMLDocumentCorePropertiesGetKeywords.docx");
- CTProperties ctProps = doc.getProperties().getExtendedProperties().getUnderlyingProperties();
- assertEquals("Microsoft Office Word",ctProps.getApplication());
- assertEquals("14.0000",ctProps.getAppVersion());
- assertEquals(57,ctProps.getCharacters());
- assertEquals(66,ctProps.getCharactersWithSpaces());
- assertEquals("",ctProps.getCompany());
- assertNull(ctProps.getDigSig());
- assertEquals(0,ctProps.getDocSecurity());
- assertNotNull(ctProps.getDomNode());
-
- CTVectorVariant vec = ctProps.getHeadingPairs();
- assertEquals(2,vec.getVector().sizeOfVariantArray());
- assertEquals("Title",vec.getVector().getVariantArray(0).getLpstr());
- assertEquals(1,vec.getVector().getVariantArray(1).getI4());
-
- assertFalse(ctProps.isSetHiddenSlides());
- assertEquals(0,ctProps.getHiddenSlides());
- assertFalse(ctProps.isSetHLinks());
- assertNull(ctProps.getHLinks());
- assertNull(ctProps.getHyperlinkBase());
- assertTrue(ctProps.isSetHyperlinksChanged());
- assertFalse(ctProps.getHyperlinksChanged());
- assertEquals(1,ctProps.getLines());
- assertTrue(ctProps.isSetLinksUpToDate());
- assertFalse(ctProps.getLinksUpToDate());
- assertNull(ctProps.getManager());
- assertFalse(ctProps.isSetMMClips());
- assertEquals(0,ctProps.getMMClips());
- assertFalse(ctProps.isSetNotes());
- assertEquals(0,ctProps.getNotes());
- assertEquals(1,ctProps.getPages());
- assertEquals(1,ctProps.getParagraphs());
- assertNull(ctProps.getPresentationFormat());
- assertTrue(ctProps.isSetScaleCrop());
- assertFalse(ctProps.getScaleCrop());
- assertTrue(ctProps.isSetSharedDoc());
- assertFalse(ctProps.getSharedDoc());
- assertFalse(ctProps.isSetSlides());
- assertEquals(0,ctProps.getSlides());
- assertEquals("Normal.dotm",ctProps.getTemplate());
-
- CTVectorLpstr vec2 = ctProps.getTitlesOfParts();
- assertEquals(1,vec2.getVector().sizeOfLpstrArray());
- assertEquals("Example Word 2010 Document",vec2.getVector().getLpstrArray(0));
-
- assertEquals(3,ctProps.getTotalTime());
- assertEquals(10,ctProps.getWords());
-
- // Check the digital signature part
- // Won't be there in this file, but we
- // need to do this check so that the
- // appropriate parts end up in the
- // smaller ooxml schemas file
- CTDigSigBlob blob = ctProps.getDigSig();
- assertNull(blob);
-
- blob = CTDigSigBlob.Factory.newInstance();
- blob.setBlob(new byte [] {2,6,7,2,3,4,5,1,2,3});
- }
-}
+ * submitted because even though the\r
+ * {@link PackageProperties#getKeywordsProperty()} had been present before, the\r
+ * {@link CoreProperties#getKeywords()} had been missing.\r
+ * <p/>\r
+ * The author of this has added {@link CoreProperties#getKeywords()} and\r
+ * {@link CoreProperties#setKeywords(String)} and this test is supposed to test\r
+ * them.\r
+ *\r
+ * @author Antoni Mylka\r
+ */\r
+public final class TestAllExtendedProperties extends TestCase {\r
+ public void testGetAllExtendedProperties() throws IOException {\r
+ XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("TestPoiXMLDocumentCorePropertiesGetKeywords.docx");\r
+ CTProperties ctProps = doc.getProperties().getExtendedProperties().getUnderlyingProperties();\r
+ assertEquals("Microsoft Office Word", ctProps.getApplication());\r
+ assertEquals("14.0000", ctProps.getAppVersion());\r
+ assertEquals(57, ctProps.getCharacters());\r
+ assertEquals(66, ctProps.getCharactersWithSpaces());\r
+ assertEquals("", ctProps.getCompany());\r
+ assertNull(ctProps.getDigSig());\r
+ assertEquals(0, ctProps.getDocSecurity());\r
+ assertNotNull(ctProps.getDomNode());\r
+\r
+ CTVectorVariant vec = ctProps.getHeadingPairs();\r
+ assertEquals(2, vec.getVector().sizeOfVariantArray());\r
+ assertEquals("Title", vec.getVector().getVariantArray(0).getLpstr());\r
+ assertEquals(1, vec.getVector().getVariantArray(1).getI4());\r
+\r
+ assertFalse(ctProps.isSetHiddenSlides());\r
+ assertEquals(0, ctProps.getHiddenSlides());\r
+ assertFalse(ctProps.isSetHLinks());\r
+ assertNull(ctProps.getHLinks());\r
+ assertNull(ctProps.getHyperlinkBase());\r
+ assertTrue(ctProps.isSetHyperlinksChanged());\r
+ assertFalse(ctProps.getHyperlinksChanged());\r
+ assertEquals(1, ctProps.getLines());\r
+ assertTrue(ctProps.isSetLinksUpToDate());\r
+ assertFalse(ctProps.getLinksUpToDate());\r
+ assertNull(ctProps.getManager());\r
+ assertFalse(ctProps.isSetMMClips());\r
+ assertEquals(0, ctProps.getMMClips());\r
+ assertFalse(ctProps.isSetNotes());\r
+ assertEquals(0, ctProps.getNotes());\r
+ assertEquals(1, ctProps.getPages());\r
+ assertEquals(1, ctProps.getParagraphs());\r
+ assertNull(ctProps.getPresentationFormat());\r
+ assertTrue(ctProps.isSetScaleCrop());\r
+ assertFalse(ctProps.getScaleCrop());\r
+ assertTrue(ctProps.isSetSharedDoc());\r
+ assertFalse(ctProps.getSharedDoc());\r
+ assertFalse(ctProps.isSetSlides());\r
+ assertEquals(0, ctProps.getSlides());\r
+ assertEquals("Normal.dotm", ctProps.getTemplate());\r
+\r
+ CTVectorLpstr vec2 = ctProps.getTitlesOfParts();\r
+ assertEquals(1, vec2.getVector().sizeOfLpstrArray());\r
+ assertEquals("Example Word 2010 Document", vec2.getVector().getLpstrArray(0));\r
+\r
+ assertEquals(3, ctProps.getTotalTime());\r
+ assertEquals(10, ctProps.getWords());\r
+\r
+ // Check the digital signature part\r
+ // Won't be there in this file, but we\r
+ // need to do this check so that the\r
+ // appropriate parts end up in the\r
+ // smaller ooxml schemas file\r
+ CTDigSigBlob blob = ctProps.getDigSig();\r
+ assertNull(blob);\r
+\r
+ blob = CTDigSigBlob.Factory.newInstance();\r
+ blob.setBlob(new byte[]{2, 6, 7, 2, 3, 4, 5, 1, 2, 3});\r
+ }\r
+}\r
package org.apache.poi.xwpf;
-import java.io.IOException;
-
-import junit.framework.TestCase;
-
-import org.apache.poi.POIXMLProperties.CoreProperties;
-import org.apache.poi.openxml4j.opc.PackageProperties;
-import org.apache.poi.xwpf.usermodel.XWPFDocument;
+import java.io.IOException;\r
+\r
+import junit.framework.TestCase;\r
+import org.apache.poi.POIXMLProperties.CoreProperties;\r
+import org.apache.poi.openxml4j.opc.PackageProperties;\r
+import org.apache.poi.xwpf.usermodel.XWPFDocument;\r
/**
* Tests if the {@link CoreProperties#getKeywords()} method. This test has been
- * submitted because even though the
- * {@link PackageProperties#getKeywordsProperty()} had been present before, the
- * {@link CoreProperties#getKeywords()} had been missing.
- *
- * The author of this has added {@link CoreProperties#getKeywords()} and
- * {@link CoreProperties#setKeywords(String)} and this test is supposed to test
- * them.
- *
- * @author Antoni Mylka
- *
- */
-public final class TestPackageCorePropertiesGetKeywords extends TestCase {
- public void testGetSetKeywords() throws IOException {
- XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("TestPoiXMLDocumentCorePropertiesGetKeywords.docx");
- String keywords = doc.getProperties().getCoreProperties().getKeywords();
- assertEquals("extractor, test, rdf", keywords);
-
- doc.getProperties().getCoreProperties().setKeywords("test, keywords");
- doc = XWPFTestDataSamples.writeOutAndReadBack(doc);
- keywords = doc.getProperties().getCoreProperties().getKeywords();
- assertEquals("test, keywords",keywords);
- }
-}
+ * submitted because even though the\r
+ * {@link PackageProperties#getKeywordsProperty()} had been present before, the\r
+ * {@link CoreProperties#getKeywords()} had been missing.\r
+ * <p/>\r
+ * The author of this has added {@link CoreProperties#getKeywords()} and\r
+ * {@link CoreProperties#setKeywords(String)} and this test is supposed to test\r
+ * them.\r
+ *\r
+ * @author Antoni Mylka\r
+ */\r
+public final class TestPackageCorePropertiesGetKeywords extends TestCase {\r
+ public void testGetSetKeywords() throws IOException {\r
+ XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("TestPoiXMLDocumentCorePropertiesGetKeywords.docx");\r
+ String keywords = doc.getProperties().getCoreProperties().getKeywords();\r
+ assertEquals("extractor, test, rdf", keywords);\r
+\r
+ doc.getProperties().getCoreProperties().setKeywords("test, keywords");\r
+ doc = XWPFTestDataSamples.writeOutAndReadBack(doc);\r
+ keywords = doc.getProperties().getCoreProperties().getKeywords();\r
+ assertEquals("test, keywords", keywords);\r
+ }\r
+}\r
public class TestXWPFBugs {\r
/**\r
* A word document that's encrypted with non-standard\r
- * Encryption options, and no cspname section. See bug 53475\r
+ * Encryption options, and no cspname section. See bug 53475\r
*/\r
@Test\r
public void bug53475NoCSPName() throws Exception {\r
assertEquals(HashAlgorithm.sha1, info.getHeader().getHashAlgorithmEx());\r
\r
// Check it can be decoded\r
- Decryptor d = Decryptor.getInstance(info); \r
+ Decryptor d = Decryptor.getInstance(info);\r
assertTrue("Unable to process: document is encrypted", d.verifyPassword("solrcell"));\r
\r
// Check we can read the word document in that\r
assertNotNull(text);\r
assertEquals("This is password protected Word document.", text.trim());\r
ex.close();\r
- \r
+\r
filesystem.close();\r
}\r
\r
assertEquals(HashAlgorithm.sha1, info.getHeader().getHashAlgorithmEx());\r
\r
// Check it can be decoded\r
- Decryptor d = Decryptor.getInstance(info); \r
+ Decryptor d = Decryptor.getInstance(info);\r
assertTrue("Unable to process: document is encrypted", d.verifyPassword("pass"));\r
\r
// Check we can read the word document in that\r
// I know ... a stupid typo, maybe next time ...\r
assertEquals("The is a password protected document.", text.trim());\r
ex.close();\r
- \r
+\r
filesystem.close();\r
}\r
}\r
import java.io.IOException;
import junit.framework.TestCase;
-
import org.apache.poi.xwpf.XWPFTestDataSamples;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
/**
* Get text out of the simple file
- * @throws IOException
+ *
+ * @throws IOException
*/
public void testFile() throws IOException {
XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("ExternalEntityInText.docx");
XWPFWordExtractor extractor = new XWPFWordExtractor(doc);
String text = extractor.getText();
-
+
assertTrue(text.length() > 0);
// Check contents, they should not contain the text from POI web site after colon!
assertEquals("Here should not be the POI web site: \"\"", text.trim());
-
+
extractor.close();
}
import java.util.regex.Pattern;
import junit.framework.TestCase;
-
import org.apache.poi.xwpf.XWPFTestDataSamples;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
/**
* Get text out of the simple file
- * @throws IOException
+ *
+ * @throws IOException
*/
public void testGetSimpleText() throws IOException {
XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("sample.docx");
}
}
assertEquals(3, ps);
-
+
extractor.close();
}
/**
* Tests getting the text out of a complex file
- * @throws IOException
+ *
+ * @throws IOException
*/
public void testGetComplexText() throws IOException {
XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("IllustrativeCases.docx");
}
}
assertEquals(134, ps);
-
+
extractor.close();
}
// Now check contents
extractor.setFetchHyperlinks(false);
assertEquals(
- "This is a test document.\nThis bit is in bold and italic\n" +
- "Back to normal\n" +
- "This contains BOLD, ITALIC and BOTH, as well as RED and YELLOW text.\n" +
- "We have a hyperlink here, and another.\n",
+ "This is a test document.\nThis bit is in bold and italic\n" +
+ "Back to normal\n" +
+ "This contains BOLD, ITALIC and BOTH, as well as RED and YELLOW text.\n" +
+ "We have a hyperlink here, and another.\n",
extractor.getText()
);
// One hyperlink is a real one, one is just to the top of page
extractor.setFetchHyperlinks(true);
assertEquals(
- "This is a test document.\nThis bit is in bold and italic\n" +
- "Back to normal\n" +
- "This contains BOLD, ITALIC and BOTH, as well as RED and YELLOW text.\n" +
- "We have a hyperlink <http://poi.apache.org/> here, and another.\n",
+ "This is a test document.\nThis bit is in bold and italic\n" +
+ "Back to normal\n" +
+ "This contains BOLD, ITALIC and BOTH, as well as RED and YELLOW text.\n" +
+ "We have a hyperlink <http://poi.apache.org/> here, and another.\n",
extractor.getText()
);
-
+
extractor.close();
}
"Footer Left\tFooter Middle\tFooter Right\n",
extractor.getText()
);
-
+
extractor.close();
}
String text = extractor.getText();
assertTrue(text.contains("snoska"));
assertTrue(text.contains("Eto ochen prostoy[footnoteRef:1] text so snoskoy"));
-
+
extractor.close();
}
XWPFWordExtractor extractor = new XWPFWordExtractor(doc);
assertTrue(extractor.getText().contains("snoska"));
-
+
extractor.close();
}
String text = extractor.getText();
assertTrue("Unable to find expected word in text\n" + text, text.contains("testdoc"));
assertTrue("Unable to find expected word in text\n" + text, text.contains("test phrase"));
-
+
extractor.close();
}
String text = extractor.getText();
assertTrue(text.contains("XXX"));
assertTrue(text.contains("tilaka [endnoteRef:2]or 'tika'"));
-
+
extractor.close();
}
assertTrue(extractor.getText().contains("pendant worn"));
assertTrue(extractor.getText().contains("extremely well"));
-
+
extractor.close();
}
assertTrue(extractor.getText().contains("Section 1"));
assertTrue(extractor.getText().contains("Section 2"));
assertTrue(extractor.getText().contains("Section 3"));
-
+
extractor.close();
}
/**
* Test that we can open and process .docm
- * (macro enabled) docx files (bug #45690)
- * @throws IOException
+ * (macro enabled) docx files (bug #45690)
+ *
+ * @throws IOException
*/
public void testDOCMFiles() throws IOException {
XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("45690.docm");
assertTrue(extractor.getText().contains("2004"));
assertTrue(extractor.getText().contains("2008"));
assertTrue(extractor.getText().contains("(120 "));
-
+
extractor.close();
}
-
+
/**
* Test that we handle things like tabs and
- * carriage returns properly in the text that
- * we're extracting (bug #49189)
- * @throws IOException
+ * carriage returns properly in the text that
+ * we're extracting (bug #49189)
+ *
+ * @throws IOException
*/
public void testDocTabs() throws IOException {
- XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("WithTabs.docx");
- XWPFWordExtractor extractor = new XWPFWordExtractor(doc);
-
- // Check bits
- assertTrue(extractor.getText().contains("a"));
- assertTrue(extractor.getText().contains("\t"));
- assertTrue(extractor.getText().contains("b"));
-
- // Now check the first paragraph in total
- assertTrue(extractor.getText().contains("a\tb\n"));
-
- extractor.close();
+ XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("WithTabs.docx");
+ XWPFWordExtractor extractor = new XWPFWordExtractor(doc);
+
+ // Check bits
+ assertTrue(extractor.getText().contains("a"));
+ assertTrue(extractor.getText().contains("\t"));
+ assertTrue(extractor.getText().contains("b"));
+
+ // Now check the first paragraph in total
+ assertTrue(extractor.getText().contains("a\tb\n"));
+
+ extractor.close();
}
-
+
/**
* The output should not contain field codes, e.g. those specified in the
* w:instrText tag (spec sec. 17.16.23)
- * @throws IOException
+ *
+ * @throws IOException
*/
public void testNoFieldCodes() throws IOException {
XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("FieldCodes.docx");
assertTrue(text.length() > 0);
assertFalse(text.contains("AUTHOR"));
assertFalse(text.contains("CREATEDATE"));
-
+
extractor.close();
}
-
+
/**
* The output should contain the values of simple fields, those specified
* with the fldSimple element (spec sec. 17.16.19)
- * @throws IOException
+ *
+ * @throws IOException
*/
public void testFldSimpleContent() throws IOException {
XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("FldSimple.docx");
String text = extractor.getText();
assertTrue(text.length() > 0);
assertTrue(text.contains("FldSimple.docx"));
-
+
extractor.close();
}
XWPFWordExtractor extractor = new XWPFWordExtractor(doc);
String text = extractor.getText();
assertTrue(text.length() > 0);
-
+
extractor.close();
}
-
+
/**
* Test for basic extraction of SDT content
+ *
* @throws IOException
*/
public void testSimpleControlContent() throws IOException {
XWPFWordExtractor ex = new XWPFWordExtractor(doc);
String s = ex.getText().toLowerCase();
int hits = 0;
-
- for (String targ : targs){
+
+ for (String targ : targs) {
boolean hit = false;
- if (s.indexOf(targ) > -1){
+ if (s.indexOf(targ) > -1) {
hit = true;
hits++;
}
- assertEquals("controlled content loading-"+targ, true, hit);
+ assertEquals("controlled content loading-" + targ, true, hit);
}
assertEquals("controlled content loading hit count", targs.length, hits);
ex.close();
-
-
+
+
doc = XWPFTestDataSamples.openSampleDocument("Bug54771a.docx");
targs = new String[]{
"bb",
};
ex = new XWPFWordExtractor(doc);
s = ex.getText().toLowerCase();
-
+
//At one point in development there were three copies of the text.
//This ensures that there is only one copy.
- for (String targ : targs){
+ for (String targ : targs) {
Matcher m = Pattern.compile(targ).matcher(s);
int hit = 0;
while (m.find()) {
hit++;
}
- assertEquals("controlled content loading-"+targ, 1, hit);
+ assertEquals("controlled content loading-" + targ, 1, hit);
}
//"test\n" appears twice: once as the "title" and once in the text.
//This also happens when you save this document as text from MSWord.
Matcher m = Pattern.compile("test\n").matcher(s);
int hit = 0;
- while (m.find()){
+ while (m.find()) {
hit++;
}
assertEquals("test<N>", 2, hit);
ex.close();
}
- /** No Header or Footer in document */
+ /**
+ * No Header or Footer in document
+ */
public void testBug55733() throws Exception {
XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("55733.docx");
- XWPFWordExtractor extractor = new XWPFWordExtractor(doc);
+ XWPFWordExtractor extractor = new XWPFWordExtractor(doc);
// Check it gives text without error
extractor.getText();
extractor.close();
}
-
- public void testCheckboxes() throws IOException {
+
+ public void testCheckboxes() throws IOException {
XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("checkboxes.docx");
System.out.println(doc);
XWPFWordExtractor extractor = new XWPFWordExtractor(doc);
-
+
assertEquals("This is a small test for checkboxes \nunchecked: |_| \n" +
- "Or checked: |X|\n\n\n\n\n" +
- "Test a checkbox within a textbox: |_| -> |X|\n\n\n" +
- "In Table:\n|_|\t|X|\n\n\n" +
- "In Sequence:\n|X||_||X|\n", extractor.getText());
+ "Or checked: |X|\n\n\n\n\n" +
+ "Test a checkbox within a textbox: |_| -> |X|\n\n\n" +
+ "In Table:\n|_|\t|X|\n\n\n" +
+ "In Sequence:\n|X||_||X|\n", extractor.getText());
extractor.close();
}
}
package org.apache.poi.xwpf.model;
-import java.io.IOException;
-
-import junit.framework.TestCase;
-
-import org.apache.poi.xwpf.XWPFTestDataSamples;
-import org.apache.poi.xwpf.usermodel.XWPFDocument;
-import org.apache.poi.xwpf.usermodel.XWPFHyperlinkRun;
+import java.io.IOException;\r
+\r
+import junit.framework.TestCase;\r
+import org.apache.poi.xwpf.XWPFTestDataSamples;\r
+import org.apache.poi.xwpf.usermodel.XWPFDocument;\r
+import org.apache.poi.xwpf.usermodel.XWPFHyperlinkRun;\r
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
/**
- * Tests for the various XWPF decorators
- */
-public class TestXWPFDecorators extends TestCase {
- private XWPFDocument simple;
- private XWPFDocument hyperlink;
- private XWPFDocument comments;
-
- protected void setUp() throws IOException {
- simple = XWPFTestDataSamples.openSampleDocument("SampleDoc.docx");
- hyperlink = XWPFTestDataSamples.openSampleDocument("TestDocument.docx");
- comments = XWPFTestDataSamples.openSampleDocument("WordWithAttachments.docx");
- }
-
- @SuppressWarnings("deprecation")
- public void testHyperlink() {
- XWPFParagraph ps;
- XWPFParagraph ph;
- assertEquals(7, simple.getParagraphs().size());
- assertEquals(5, hyperlink.getParagraphs().size());
-
- // Simple text
- ps = simple.getParagraphs().get(0);
- assertEquals("I am a test document", ps.getParagraphText());
- assertEquals(1, ps.getRuns().size());
-
- ph = hyperlink.getParagraphs().get(4);
- assertEquals("We have a hyperlink here, and another.", ph.getParagraphText());
- assertEquals(3, ph.getRuns().size());
-
-
- // The proper way to do hyperlinks(!)
- assertFalse(ps.getRuns().get(0) instanceof XWPFHyperlinkRun);
- assertFalse(ph.getRuns().get(0) instanceof XWPFHyperlinkRun);
- assertTrue(ph.getRuns().get(1) instanceof XWPFHyperlinkRun);
- assertFalse(ph.getRuns().get(2) instanceof XWPFHyperlinkRun);
-
- XWPFHyperlinkRun link = (XWPFHyperlinkRun)ph.getRuns().get(1);
- assertEquals("http://poi.apache.org/", link.getHyperlink(hyperlink).getURL());
-
-
- // Test the old style decorator
- // You probably don't want to still be using it...
- assertEquals(
- "I am a test document",
- (new XWPFHyperlinkDecorator(ps, null, false)).getText()
- );
- assertEquals(
- "I am a test document",
- (new XWPFHyperlinkDecorator(ps, null, true)).getText()
- );
-
- assertEquals(
- "We have a hyperlink here, and another.hyperlink",
- (new XWPFHyperlinkDecorator(ph, null, false)).getText()
- );
- assertEquals(
- "We have a hyperlink here, and another.hyperlink <http://poi.apache.org/>",
- (new XWPFHyperlinkDecorator(ph, null, true)).getText()
- );
- }
-
- public void testComments() {
- int numComments = 0;
- for(XWPFParagraph p : comments.getParagraphs()) {
- XWPFCommentsDecorator d = new XWPFCommentsDecorator(p, null);
- if(d.getCommentText().length() > 0) {
- numComments++;
- assertEquals("\tComment by", d.getCommentText().substring(0, 11));
- }
- }
- assertEquals(3, numComments);
- }
-}
+ * Tests for the various XWPF decorators\r
+ */\r
+public class TestXWPFDecorators extends TestCase {\r
+ private XWPFDocument simple;\r
+ private XWPFDocument hyperlink;\r
+ private XWPFDocument comments;\r
+\r
+ protected void setUp() throws IOException {\r
+ simple = XWPFTestDataSamples.openSampleDocument("SampleDoc.docx");\r
+ hyperlink = XWPFTestDataSamples.openSampleDocument("TestDocument.docx");\r
+ comments = XWPFTestDataSamples.openSampleDocument("WordWithAttachments.docx");\r
+ }\r
+\r
+ @SuppressWarnings("deprecation")\r
+ public void testHyperlink() {\r
+ XWPFParagraph ps;\r
+ XWPFParagraph ph;\r
+ assertEquals(7, simple.getParagraphs().size());\r
+ assertEquals(5, hyperlink.getParagraphs().size());\r
+\r
+ // Simple text\r
+ ps = simple.getParagraphs().get(0);\r
+ assertEquals("I am a test document", ps.getParagraphText());\r
+ assertEquals(1, ps.getRuns().size());\r
+\r
+ ph = hyperlink.getParagraphs().get(4);\r
+ assertEquals("We have a hyperlink here, and another.", ph.getParagraphText());\r
+ assertEquals(3, ph.getRuns().size());\r
+\r
+\r
+ // The proper way to do hyperlinks(!)\r
+ assertFalse(ps.getRuns().get(0) instanceof XWPFHyperlinkRun);\r
+ assertFalse(ph.getRuns().get(0) instanceof XWPFHyperlinkRun);\r
+ assertTrue(ph.getRuns().get(1) instanceof XWPFHyperlinkRun);\r
+ assertFalse(ph.getRuns().get(2) instanceof XWPFHyperlinkRun);\r
+\r
+ XWPFHyperlinkRun link = (XWPFHyperlinkRun) ph.getRuns().get(1);\r
+ assertEquals("http://poi.apache.org/", link.getHyperlink(hyperlink).getURL());\r
+\r
+\r
+ // Test the old style decorator\r
+ // You probably don't want to still be using it...\r
+ assertEquals(\r
+ "I am a test document",\r
+ (new XWPFHyperlinkDecorator(ps, null, false)).getText()\r
+ );\r
+ assertEquals(\r
+ "I am a test document",\r
+ (new XWPFHyperlinkDecorator(ps, null, true)).getText()\r
+ );\r
+\r
+ assertEquals(\r
+ "We have a hyperlink here, and another.hyperlink",\r
+ (new XWPFHyperlinkDecorator(ph, null, false)).getText()\r
+ );\r
+ assertEquals(\r
+ "We have a hyperlink here, and another.hyperlink <http://poi.apache.org/>",\r
+ (new XWPFHyperlinkDecorator(ph, null, true)).getText()\r
+ );\r
+ }\r
+\r
+ public void testComments() {\r
+ int numComments = 0;\r
+ for (XWPFParagraph p : comments.getParagraphs()) {\r
+ XWPFCommentsDecorator d = new XWPFCommentsDecorator(p, null);\r
+ if (d.getCommentText().length() > 0) {\r
+ numComments++;\r
+ assertEquals("\tComment by", d.getCommentText().substring(0, 11));\r
+ }\r
+ }\r
+ assertEquals(3, numComments);\r
+ }\r
+}\r
import java.io.IOException;
import junit.framework.TestCase;
-
import org.apache.poi.xwpf.XWPFTestDataSamples;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
* Tests for XWPF Header Footer Stuff
*/
public class TestXWPFHeaderFooterPolicy extends TestCase {
- private XWPFDocument noHeader;
- private XWPFDocument header;
- private XWPFDocument headerFooter;
- private XWPFDocument footer;
- private XWPFDocument oddEven;
- private XWPFDocument diffFirst;
-
- protected void setUp() throws IOException {
-
- noHeader = XWPFTestDataSamples.openSampleDocument("NoHeadFoot.docx");
- header = XWPFTestDataSamples.openSampleDocument("ThreeColHead.docx");
- headerFooter = XWPFTestDataSamples.openSampleDocument("SimpleHeadThreeColFoot.docx");
- footer = XWPFTestDataSamples.openSampleDocument("FancyFoot.docx");
- oddEven = XWPFTestDataSamples.openSampleDocument("PageSpecificHeadFoot.docx");
- diffFirst = XWPFTestDataSamples.openSampleDocument("DiffFirstPageHeadFoot.docx");
- }
-
- public void testPolicy() {
- XWPFHeaderFooterPolicy policy;
-
- policy = noHeader.getHeaderFooterPolicy();
- assertNull(policy.getDefaultHeader());
- assertNull(policy.getDefaultFooter());
-
- assertNull(policy.getHeader(1));
- assertNull(policy.getHeader(2));
- assertNull(policy.getHeader(3));
- assertNull(policy.getFooter(1));
- assertNull(policy.getFooter(2));
- assertNull(policy.getFooter(3));
-
-
- policy = header.getHeaderFooterPolicy();
- assertNotNull(policy.getDefaultHeader());
- assertNull(policy.getDefaultFooter());
-
- assertEquals(policy.getDefaultHeader(), policy.getHeader(1));
- assertEquals(policy.getDefaultHeader(), policy.getHeader(2));
- assertEquals(policy.getDefaultHeader(), policy.getHeader(3));
- assertNull(policy.getFooter(1));
- assertNull(policy.getFooter(2));
- assertNull(policy.getFooter(3));
-
-
- policy = footer.getHeaderFooterPolicy();
- assertNull(policy.getDefaultHeader());
- assertNotNull(policy.getDefaultFooter());
-
- assertNull(policy.getHeader(1));
- assertNull(policy.getHeader(2));
- assertNull(policy.getHeader(3));
- assertEquals(policy.getDefaultFooter(), policy.getFooter(1));
- assertEquals(policy.getDefaultFooter(), policy.getFooter(2));
- assertEquals(policy.getDefaultFooter(), policy.getFooter(3));
-
-
- policy = headerFooter.getHeaderFooterPolicy();
- assertNotNull(policy.getDefaultHeader());
- assertNotNull(policy.getDefaultFooter());
-
- assertEquals(policy.getDefaultHeader(), policy.getHeader(1));
- assertEquals(policy.getDefaultHeader(), policy.getHeader(2));
- assertEquals(policy.getDefaultHeader(), policy.getHeader(3));
- assertEquals(policy.getDefaultFooter(), policy.getFooter(1));
- assertEquals(policy.getDefaultFooter(), policy.getFooter(2));
- assertEquals(policy.getDefaultFooter(), policy.getFooter(3));
-
-
- policy = oddEven.getHeaderFooterPolicy();
- assertNotNull(policy.getDefaultHeader());
- assertNotNull(policy.getDefaultFooter());
- assertNotNull(policy.getEvenPageHeader());
- assertNotNull(policy.getEvenPageFooter());
-
- assertEquals(policy.getDefaultHeader(), policy.getHeader(1));
- assertEquals(policy.getEvenPageHeader(), policy.getHeader(2));
- assertEquals(policy.getDefaultHeader(), policy.getHeader(3));
- assertEquals(policy.getDefaultFooter(), policy.getFooter(1));
- assertEquals(policy.getEvenPageFooter(), policy.getFooter(2));
- assertEquals(policy.getDefaultFooter(), policy.getFooter(3));
-
-
- policy = diffFirst.getHeaderFooterPolicy();
- assertNotNull(policy.getDefaultHeader());
- assertNotNull(policy.getDefaultFooter());
- assertNotNull(policy.getFirstPageHeader());
- assertNotNull(policy.getFirstPageFooter());
- assertNull(policy.getEvenPageHeader());
- assertNull(policy.getEvenPageFooter());
-
- assertEquals(policy.getFirstPageHeader(), policy.getHeader(1));
- assertEquals(policy.getDefaultHeader(), policy.getHeader(2));
- assertEquals(policy.getDefaultHeader(), policy.getHeader(3));
- assertEquals(policy.getFirstPageFooter(), policy.getFooter(1));
- assertEquals(policy.getDefaultFooter(), policy.getFooter(2));
- assertEquals(policy.getDefaultFooter(), policy.getFooter(3));
- }
-
- public void testContents() {
- XWPFHeaderFooterPolicy policy;
-
- // Test a few simple bits off a simple header
- policy = diffFirst.getHeaderFooterPolicy();
-
- assertEquals(
- "I am the header on the first page, and I" + '\u2019' + "m nice and simple\n",
- policy.getFirstPageHeader().getText()
- );
- assertEquals(
- "First header column!\tMid header\tRight header!\n",
- policy.getDefaultHeader().getText()
- );
-
-
- // And a few bits off a more complex header
- policy = oddEven.getHeaderFooterPolicy();
-
- assertEquals(
- "[ODD Page Header text]\n\n",
- policy.getDefaultHeader().getText()
- );
- assertEquals(
- "[This is an Even Page, with a Header]\n\n",
- policy.getEvenPageHeader().getText()
- );
- }
+ private XWPFDocument noHeader;
+ private XWPFDocument header;
+ private XWPFDocument headerFooter;
+ private XWPFDocument footer;
+ private XWPFDocument oddEven;
+ private XWPFDocument diffFirst;
+
+ protected void setUp() throws IOException {
+
+ noHeader = XWPFTestDataSamples.openSampleDocument("NoHeadFoot.docx");
+ header = XWPFTestDataSamples.openSampleDocument("ThreeColHead.docx");
+ headerFooter = XWPFTestDataSamples.openSampleDocument("SimpleHeadThreeColFoot.docx");
+ footer = XWPFTestDataSamples.openSampleDocument("FancyFoot.docx");
+ oddEven = XWPFTestDataSamples.openSampleDocument("PageSpecificHeadFoot.docx");
+ diffFirst = XWPFTestDataSamples.openSampleDocument("DiffFirstPageHeadFoot.docx");
+ }
+
+ public void testPolicy() {
+ XWPFHeaderFooterPolicy policy;
+
+ policy = noHeader.getHeaderFooterPolicy();
+ assertNull(policy.getDefaultHeader());
+ assertNull(policy.getDefaultFooter());
+
+ assertNull(policy.getHeader(1));
+ assertNull(policy.getHeader(2));
+ assertNull(policy.getHeader(3));
+ assertNull(policy.getFooter(1));
+ assertNull(policy.getFooter(2));
+ assertNull(policy.getFooter(3));
+
+
+ policy = header.getHeaderFooterPolicy();
+ assertNotNull(policy.getDefaultHeader());
+ assertNull(policy.getDefaultFooter());
+
+ assertEquals(policy.getDefaultHeader(), policy.getHeader(1));
+ assertEquals(policy.getDefaultHeader(), policy.getHeader(2));
+ assertEquals(policy.getDefaultHeader(), policy.getHeader(3));
+ assertNull(policy.getFooter(1));
+ assertNull(policy.getFooter(2));
+ assertNull(policy.getFooter(3));
+
+
+ policy = footer.getHeaderFooterPolicy();
+ assertNull(policy.getDefaultHeader());
+ assertNotNull(policy.getDefaultFooter());
+
+ assertNull(policy.getHeader(1));
+ assertNull(policy.getHeader(2));
+ assertNull(policy.getHeader(3));
+ assertEquals(policy.getDefaultFooter(), policy.getFooter(1));
+ assertEquals(policy.getDefaultFooter(), policy.getFooter(2));
+ assertEquals(policy.getDefaultFooter(), policy.getFooter(3));
+
+
+ policy = headerFooter.getHeaderFooterPolicy();
+ assertNotNull(policy.getDefaultHeader());
+ assertNotNull(policy.getDefaultFooter());
+
+ assertEquals(policy.getDefaultHeader(), policy.getHeader(1));
+ assertEquals(policy.getDefaultHeader(), policy.getHeader(2));
+ assertEquals(policy.getDefaultHeader(), policy.getHeader(3));
+ assertEquals(policy.getDefaultFooter(), policy.getFooter(1));
+ assertEquals(policy.getDefaultFooter(), policy.getFooter(2));
+ assertEquals(policy.getDefaultFooter(), policy.getFooter(3));
+
+
+ policy = oddEven.getHeaderFooterPolicy();
+ assertNotNull(policy.getDefaultHeader());
+ assertNotNull(policy.getDefaultFooter());
+ assertNotNull(policy.getEvenPageHeader());
+ assertNotNull(policy.getEvenPageFooter());
+
+ assertEquals(policy.getDefaultHeader(), policy.getHeader(1));
+ assertEquals(policy.getEvenPageHeader(), policy.getHeader(2));
+ assertEquals(policy.getDefaultHeader(), policy.getHeader(3));
+ assertEquals(policy.getDefaultFooter(), policy.getFooter(1));
+ assertEquals(policy.getEvenPageFooter(), policy.getFooter(2));
+ assertEquals(policy.getDefaultFooter(), policy.getFooter(3));
+
+
+ policy = diffFirst.getHeaderFooterPolicy();
+ assertNotNull(policy.getDefaultHeader());
+ assertNotNull(policy.getDefaultFooter());
+ assertNotNull(policy.getFirstPageHeader());
+ assertNotNull(policy.getFirstPageFooter());
+ assertNull(policy.getEvenPageHeader());
+ assertNull(policy.getEvenPageFooter());
+
+ assertEquals(policy.getFirstPageHeader(), policy.getHeader(1));
+ assertEquals(policy.getDefaultHeader(), policy.getHeader(2));
+ assertEquals(policy.getDefaultHeader(), policy.getHeader(3));
+ assertEquals(policy.getFirstPageFooter(), policy.getFooter(1));
+ assertEquals(policy.getDefaultFooter(), policy.getFooter(2));
+ assertEquals(policy.getDefaultFooter(), policy.getFooter(3));
+ }
+
+ public void testContents() {
+ XWPFHeaderFooterPolicy policy;
+
+ // Test a few simple bits off a simple header
+ policy = diffFirst.getHeaderFooterPolicy();
+
+ assertEquals(
+ "I am the header on the first page, and I" + '\u2019' + "m nice and simple\n",
+ policy.getFirstPageHeader().getText()
+ );
+ assertEquals(
+ "First header column!\tMid header\tRight header!\n",
+ policy.getDefaultHeader().getText()
+ );
+
+
+ // And a few bits off a more complex header
+ policy = oddEven.getHeaderFooterPolicy();
+
+ assertEquals(
+ "[ODD Page Header text]\n\n",
+ policy.getDefaultHeader().getText()
+ );
+ assertEquals(
+ "[This is an Even Page, with a Header]\n\n",
+ policy.getEvenPageHeader().getText()
+ );
+ }
}
assertFalse(document.isTrackRevisions());\r
\r
document.setTrackRevisions(true);\r
- \r
+\r
assertTrue(document.isTrackRevisions());\r
}\r
\r
import static org.junit.Assert.assertEquals;\r
import static org.junit.Assert.assertNotNull;\r
\r
-import java.io.FileInputStream;\r
import java.io.IOException;\r
\r
import org.apache.poi.openxml4j.exceptions.OpenXML4JException;\r
-import org.apache.poi.openxml4j.opc.OPCPackage;\r
import org.apache.poi.xwpf.XWPFTestDataSamples;\r
import org.apache.poi.xwpf.usermodel.XWPFRun.FontCharRange;\r
import org.junit.Test;\r
@Test\r
public void bug55802() throws Exception {\r
String blabla =\r
- "Bir, iki, \u00fc\u00e7, d\u00f6rt, be\u015f,\n"+\r
- "\nalt\u0131, yedi, sekiz, dokuz, on.\n"+\r
- "\nK\u0131rm\u0131z\u0131 don,\n"+\r
- "\ngel bizim bah\u00e7eye kon,\n"+\r
- "\nsar\u0131 limon";\r
+ "Bir, iki, \u00fc\u00e7, d\u00f6rt, be\u015f,\n" +\r
+ "\nalt\u0131, yedi, sekiz, dokuz, on.\n" +\r
+ "\nK\u0131rm\u0131z\u0131 don,\n" +\r
+ "\ngel bizim bah\u00e7eye kon,\n" +\r
+ "\nsar\u0131 limon";\r
XWPFDocument doc = new XWPFDocument();\r
XWPFRun run = doc.createParagraph().createRun();\r
- \r
+\r
for (String str : blabla.split("\n")) {\r
run.setText(str);\r
run.addBreak();\r
assertEquals(run.getFontFamily(FontCharRange.hAnsi), "Arial");\r
}\r
\r
- \r
+\r
@Test\r
public void bug57312_NullPointException() throws IOException {\r
XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("57312.docx");\r
assertNotNull(doc);\r
- \r
- for( IBodyElement bodyElement : doc.getBodyElements()){\r
+\r
+ for (IBodyElement bodyElement : doc.getBodyElements()) {\r
BodyElementType elementType = bodyElement.getElementType();\r
- \r
- if(elementType == BodyElementType.PARAGRAPH) {\r
+\r
+ if (elementType == BodyElementType.PARAGRAPH) {\r
XWPFParagraph paragraph = (XWPFParagraph) bodyElement;\r
- \r
- for (IRunElement iRunElem : paragraph.getIRuns()){\r
- \r
- if (iRunElem instanceof XWPFRun){ \r
+\r
+ for (IRunElement iRunElem : paragraph.getIRuns()) {\r
+\r
+ if (iRunElem instanceof XWPFRun) {\r
XWPFRun runElement = (XWPFRun) iRunElem;\r
- \r
+\r
UnderlinePatterns underline = runElement.getUnderline();\r
assertNotNull(underline);\r
- \r
+\r
//System.out.println("Found: " + underline + ": " + runElement.getText(0));\r
}\r
}\r
- } \r
+ }\r
}\r
}\r
\r
- \r
+\r
@Test\r
public void test56392() throws IOException, OpenXML4JException {\r
XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("56392.docx");\r
- assertNotNull(doc);\r
+ assertNotNull(doc);\r
}\r
- \r
+\r
/**\r
* Removing a run needs to remove it from both Runs and IRuns\r
*/\r
XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("sample.docx");\r
assertNotNull(doc);\r
assertEquals(3, doc.getParagraphs().size());\r
- \r
+\r
for (XWPFParagraph paragraph : doc.getParagraphs()) {\r
paragraph.removeRun(0);\r
assertNotNull(paragraph.getText());\r
import java.util.List;
import junit.framework.TestCase;
-
import org.apache.poi.POIXMLDocumentPart;
import org.apache.poi.POIXMLProperties;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
OPCPackage pack = doc.getPackage();
boolean found = false;
- for(PackagePart part : pack.getParts()) {
- if(part.getContentType().equals(XWPFRelation.DOCUMENT.getContentType())) {
+ for (PackagePart part : pack.getParts()) {
+ if (part.getContentType().equals(XWPFRelation.DOCUMENT.getContentType())) {
found = true;
}
if (false) {
assertEquals("Apache POI", props.getExtendedProperties().getUnderlyingProperties().getApplication());
}
- public void testAddParagraph() throws IOException{
+ public void testAddParagraph() throws IOException {
XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("sample.docx");
assertEquals(3, doc.getParagraphs().size());
public void testAddPicture() throws IOException, InvalidFormatException {
XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("sample.docx");
byte[] jpeg = XWPFTestDataSamples.getImage("nature1.jpg");
- String relationId = doc.addPictureData(jpeg,XWPFDocument.PICTURE_TYPE_JPEG);
+ String relationId = doc.addPictureData(jpeg, XWPFDocument.PICTURE_TYPE_JPEG);
byte[] newJpeg = ((XWPFPictureData) doc.getRelationById(relationId)).getData();
- assertEquals(newJpeg.length,jpeg.length);
- for (int i = 0 ; i < jpeg.length ; i++)
- {
- assertEquals(newJpeg[i],jpeg[i]);
+ assertEquals(newJpeg.length, jpeg.length);
+ for (int i = 0; i < jpeg.length; i++) {
+ assertEquals(newJpeg[i], jpeg[i]);
}
}
+
public void testAllPictureFormats() throws IOException, InvalidFormatException {
XWPFDocument doc = new XWPFDocument();
os.close();
XWPFHeader xwpfHeader = doc.getHeaderArray(0);
PackageRelationship relationship = xwpfHeader.getPackagePart().addRelationship(partName, TargetMode.INTERNAL, jpgRelation.getRelation());
- XWPFPictureData newPicData = new XWPFPictureData(newImagePart,relationship);
+ XWPFPictureData newPicData = new XWPFPictureData(newImagePart, relationship);
/* new part is now ready to rumble */
assertFalse(xwpfHeader.getAllPictures().contains(newPicData));
List<XWPFPictureData> allPackagePictures = doc.getAllPackagePictures();
assertNotNull(allPictures);
- assertEquals(3,allPictures.size());
+ assertEquals(3, allPictures.size());
for (XWPFPictureData xwpfPictureData : allPictures) {
assertTrue(allPackagePictures.contains(xwpfPictureData));
}
List<XWPFPictureData> allPackagePictures = doc.getAllPackagePictures();
assertNotNull(allPackagePictures);
- assertEquals(5,allPackagePictures.size());
+ assertEquals(5, allPackagePictures.size());
try {
allPackagePictures.add(allPackagePictures.get(0));
public void testPictureHandlingSimpleFile() throws IOException, InvalidFormatException {
XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("issue_51265_1.docx");
- assertEquals(1,doc.getAllPackagePictures().size());
+ assertEquals(1, doc.getAllPackagePictures().size());
byte[] newPic = XWPFTestDataSamples.getImage("abstract4.jpg");
String id1 = doc.addPictureData(newPic, Document.PICTURE_TYPE_JPEG);
- assertEquals(2,doc.getAllPackagePictures().size());
+ assertEquals(2, doc.getAllPackagePictures().size());
/* copy data, to avoid instance-equality */
byte[] newPicCopy = Arrays.copyOf(newPic, newPic.length);
String id2 = doc.addPictureData(newPicCopy, Document.PICTURE_TYPE_JPEG);
- assertEquals(id1,id2);
+ assertEquals(id1, id2);
doc.getPackage().revert();
}
public void testPictureHandlingHeaderDocumentImages() throws IOException {
XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("issue_51265_2.docx");
- assertEquals(1,doc.getAllPictures().size());
- assertEquals(1,doc.getAllPackagePictures().size());
- assertEquals(1,doc.getHeaderArray(0).getAllPictures().size());
+ assertEquals(1, doc.getAllPictures().size());
+ assertEquals(1, doc.getAllPackagePictures().size());
+ assertEquals(1, doc.getHeaderArray(0).getAllPictures().size());
doc.getPackage().revert();
}
XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("issue_51265_3.docx");
XWPFHeader xwpfHeader = doc.getHeaderArray(0);
- assertEquals(3,doc.getAllPictures().size());
- assertEquals(3,xwpfHeader.getAllPictures().size());
- assertEquals(5,doc.getAllPackagePictures().size());
+ assertEquals(3, doc.getAllPictures().size());
+ assertEquals(3, xwpfHeader.getAllPictures().size());
+ assertEquals(5, doc.getAllPackagePictures().size());
byte[] nature1 = XWPFTestDataSamples.getImage("nature1.jpg");
String id = doc.addPictureData(nature1, Document.PICTURE_TYPE_JPEG);
POIXMLDocumentPart part1 = xwpfHeader.getRelationById("rId1");
XWPFPictureData part2 = (XWPFPictureData) doc.getRelationById(id);
- assertSame(part1,part2);
+ assertSame(part1, part2);
doc.getPackage().revert();
}
+
public void testZeroLengthLibreOfficeDocumentWithWaterMarkHeader() throws IOException {
XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("zero-length.docx");
POIXMLProperties properties = doc.getProperties();
assertEquals(0, extendedProperties.getUnderlyingProperties().getCharacters());
}
- public void testSettings(){
+ public void testSettings() {
XWPFSettings settings = new XWPFSettings();
settings.setZoomPercent(50);
assertEquals(50, settings.getZoomPercent());
import java.io.IOException;
import java.math.BigInteger;
-import java.util.List;
-
-import junit.framework.TestCase;
-
-import org.apache.poi.xwpf.XWPFTestDataSamples;
-
-import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTFtnEdn;
-import org.openxmlformats.schemas.wordprocessingml.x2006.main.STFtnEdn;
-
-public class TestXWPFFootnotes extends TestCase {
-
- public void testAddFootnotesToDocument() throws IOException{
- XWPFDocument docOut = new XWPFDocument();
-
- BigInteger noteId = BigInteger.valueOf(1);
-
- XWPFFootnotes footnotes = docOut.createFootnotes();
- CTFtnEdn ctNote = CTFtnEdn.Factory.newInstance();
- ctNote.setId(noteId);
- ctNote.setType(STFtnEdn.NORMAL);
- footnotes.addFootnote(ctNote);
-
- XWPFDocument docIn = XWPFTestDataSamples.writeOutAndReadBack(docOut);
-
- XWPFFootnote note = docIn.getFootnoteByID(noteId.intValue());
- assertEquals(note.getCTFtnEdn().getType(), STFtnEdn.NORMAL);
- }
-
- /**
- * Bug 55066 - avoid double loading the footnotes
- */
- public void testLoadFootnotesOnce() throws IOException{
- XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("Bug54849.docx");
- List<XWPFFootnote> footnotes = doc.getFootnotes();
- int hits = 0;
- for (XWPFFootnote fn : footnotes){
- for (IBodyElement e : fn.getBodyElements()){
- if (e instanceof XWPFParagraph){
- String txt = ((XWPFParagraph)e).getText();
- if (txt.indexOf("Footnote_sdt") > -1){
- hits++;
- }
- }
- }
- }
- assertEquals("Load footnotes once", 1, hits);
- }
-}
-
+import java.util.List;\r
+\r
+import junit.framework.TestCase;\r
+import org.apache.poi.xwpf.XWPFTestDataSamples;\r
+import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTFtnEdn;\r
+import org.openxmlformats.schemas.wordprocessingml.x2006.main.STFtnEdn;\r
+\r
+public class TestXWPFFootnotes extends TestCase {\r
+\r
+ public void testAddFootnotesToDocument() throws IOException {\r
+ XWPFDocument docOut = new XWPFDocument();\r
+\r
+ BigInteger noteId = BigInteger.valueOf(1);\r
+\r
+ XWPFFootnotes footnotes = docOut.createFootnotes();\r
+ CTFtnEdn ctNote = CTFtnEdn.Factory.newInstance();\r
+ ctNote.setId(noteId);\r
+ ctNote.setType(STFtnEdn.NORMAL);\r
+ footnotes.addFootnote(ctNote);\r
+\r
+ XWPFDocument docIn = XWPFTestDataSamples.writeOutAndReadBack(docOut);\r
+\r
+ XWPFFootnote note = docIn.getFootnoteByID(noteId.intValue());\r
+ assertEquals(note.getCTFtnEdn().getType(), STFtnEdn.NORMAL);\r
+ }\r
+\r
+ /**\r
+ * Bug 55066 - avoid double loading the footnotes\r
+ */\r
+ public void testLoadFootnotesOnce() throws IOException {\r
+ XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("Bug54849.docx");\r
+ List<XWPFFootnote> footnotes = doc.getFootnotes();\r
+ int hits = 0;\r
+ for (XWPFFootnote fn : footnotes) {\r
+ for (IBodyElement e : fn.getBodyElements()) {\r
+ if (e instanceof XWPFParagraph) {\r
+ String txt = ((XWPFParagraph) e).getText();\r
+ if (txt.indexOf("Footnote_sdt") > -1) {\r
+ hits++;\r
+ }\r
+ }\r
+ }\r
+ }\r
+ assertEquals("Load footnotes once", 1, hits);\r
+ }\r
+}\r
+\r
package org.apache.poi.xwpf.usermodel;
-import java.io.IOException;
-
-import junit.framework.TestCase;
-
-import org.apache.poi.xwpf.XWPFTestDataSamples;
-import org.apache.poi.xwpf.model.XWPFHeaderFooterPolicy;
-import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTP;
+import java.io.IOException;\r
+\r
+import junit.framework.TestCase;\r
+import org.apache.poi.xwpf.XWPFTestDataSamples;\r
+import org.apache.poi.xwpf.model.XWPFHeaderFooterPolicy;\r
+import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTP;\r
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTR;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTText;
assertEquals("First paragraph for the footer", paras[0].getText());
assertEquals("Second paragraph for the footer", paras[1].getText());
}
-
- public void testSetWatermark() throws IOException {
- XWPFDocument sampleDoc = XWPFTestDataSamples.openSampleDocument("SampleDoc.docx");
-
- // No header is set (yet)
- XWPFHeaderFooterPolicy policy = sampleDoc.getHeaderFooterPolicy();
- assertNull(policy.getDefaultHeader());
+\r
+ public void testSetWatermark() throws IOException {\r
+ XWPFDocument sampleDoc = XWPFTestDataSamples.openSampleDocument("SampleDoc.docx");\r
+\r
+ // No header is set (yet)\r
+ XWPFHeaderFooterPolicy policy = sampleDoc.getHeaderFooterPolicy();\r
+ assertNull(policy.getDefaultHeader());\r
assertNull(policy.getFirstPageHeader());
assertNull(policy.getDefaultFooter());
policy.createWatermark("DRAFT");
- assertNotNull(policy.getDefaultHeader());
- assertNotNull(policy.getFirstPageHeader());
- assertNotNull(policy.getEvenPageHeader());
-
- // Re-open, and check
- XWPFDocument reopened = XWPFTestDataSamples.writeOutAndReadBack(sampleDoc);
- policy = reopened.getHeaderFooterPolicy();
+ assertNotNull(policy.getDefaultHeader());\r
+ assertNotNull(policy.getFirstPageHeader());\r
+ assertNotNull(policy.getEvenPageHeader());\r
+\r
+ // Re-open, and check\r
+ XWPFDocument reopened = XWPFTestDataSamples.writeOutAndReadBack(sampleDoc);\r
+ policy = reopened.getHeaderFooterPolicy();\r
assertNotNull(policy.getDefaultHeader());
assertNotNull(policy.getFirstPageHeader());
==================================================================== */
package org.apache.poi.xwpf.usermodel;
-import java.io.IOException;
-
-import junit.framework.TestCase;
-
-import org.apache.poi.xwpf.XWPFTestDataSamples;
-import org.apache.xmlbeans.XmlException;
-import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTSdtBlock;
-
-/**
- * @author Paolo Mottadelli
- */
-public final class TestXWPFHeadings extends TestCase{
- private static final String HEADING1 = "Heading1";
-
- public void testSetParagraphStyle() throws IOException, XmlException {
- //new clean instance of paragraph
- XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("heading123.docx");
- XWPFParagraph p = doc.createParagraph();
- XWPFRun run = p.createRun();
- run.setText("Heading 1");
-
- CTSdtBlock block = doc.getDocument().getBody().addNewSdt();
-
- assertNull(p.getStyle());
- p.setStyle(HEADING1);
- assertEquals(HEADING1, p.getCTP().getPPr().getPStyle().getVal());
-
- doc.createTOC();
- /*
- // TODO - finish this test
- if (false) {
- CTStyles styles = doc.getStyle();
- CTStyle style = styles.addNewStyle();
+import java.io.IOException;\r
+\r
+import junit.framework.TestCase;\r
+import org.apache.poi.xwpf.XWPFTestDataSamples;\r
+import org.apache.xmlbeans.XmlException;\r
+import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTSdtBlock;\r
+
+/**\r
+ * @author Paolo Mottadelli\r
+ */\r
+public final class TestXWPFHeadings extends TestCase {\r
+ private static final String HEADING1 = "Heading1";\r
+\r
+ public void testSetParagraphStyle() throws IOException, XmlException {\r
+ //new clean instance of paragraph\r
+ XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("heading123.docx");\r
+ XWPFParagraph p = doc.createParagraph();\r
+ XWPFRun run = p.createRun();\r
+ run.setText("Heading 1");\r
+\r
+ CTSdtBlock block = doc.getDocument().getBody().addNewSdt();\r
+\r
+ assertNull(p.getStyle());\r
+ p.setStyle(HEADING1);\r
+ assertEquals(HEADING1, p.getCTP().getPPr().getPStyle().getVal());\r
+\r
+ doc.createTOC();\r
+ /*\r
+ // TODO - finish this test\r
+ if (false) {\r
+ CTStyles styles = doc.getStyle();\r
+ CTStyle style = styles.addNewStyle();\r
style.setType(STStyleType.PARAGRAPH);
style.setStyleId("Heading1");
}
package org.apache.poi.xwpf.usermodel;
import java.io.IOException;
-import java.math.BigInteger;
-
-import junit.framework.TestCase;
-
-import org.apache.poi.xwpf.XWPFTestDataSamples;
-import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTNum;
-import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTNumLvl;
-
-public class TestXWPFNumbering extends TestCase {
-
- public void testCompareAbstractNum() throws IOException {
- XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("Numbering.docx");
- XWPFNumbering numbering = doc.getNumbering();
- BigInteger numId = BigInteger.valueOf(1);
- assertTrue(numbering.numExist(numId));
- XWPFNum num = numbering.getNum(numId);
- BigInteger abstrNumId = num.getCTNum().getAbstractNumId().getVal();
- XWPFAbstractNum abstractNum = numbering.getAbstractNum(abstrNumId);
- BigInteger compareAbstractNum = numbering.getIdOfAbstractNum(abstractNum);
- assertEquals(abstrNumId, compareAbstractNum);
- }
-
- public void testAddNumberingToDoc() throws IOException{
- BigInteger abstractNumId = BigInteger.valueOf(1);
- BigInteger numId = BigInteger.valueOf(1);
-
- XWPFDocument docOut = new XWPFDocument();
- XWPFNumbering numbering = docOut.createNumbering();
- numId = numbering.addNum(abstractNumId);
-
- XWPFDocument docIn = XWPFTestDataSamples.writeOutAndReadBack(docOut);
-
- numbering = docIn.getNumbering();
- assertTrue(numbering.numExist(numId));
- XWPFNum num = numbering.getNum(numId);
-
- BigInteger compareAbstractNum = num.getCTNum().getAbstractNumId().getVal();
- assertEquals(abstractNumId, compareAbstractNum);
- }
-
- public void testGetNumIlvl() throws IOException{
- XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("Numbering.docx");
- BigInteger numIlvl = BigInteger.valueOf(0);
- assertEquals(numIlvl, doc.getParagraphs().get(0).getNumIlvl());
- numIlvl = BigInteger.valueOf(1);
- assertEquals(numIlvl, doc.getParagraphs().get(5).getNumIlvl());
- }
-
- public void testGetNumFmt() throws IOException{
- XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("Numbering.docx");
- assertEquals("bullet", doc.getParagraphs().get(0).getNumFmt());
- assertEquals("bullet", doc.getParagraphs().get(1).getNumFmt());
- assertEquals("bullet", doc.getParagraphs().get(2).getNumFmt());
- assertEquals("bullet", doc.getParagraphs().get(3).getNumFmt());
- assertEquals("decimal", doc.getParagraphs().get(4).getNumFmt());
- assertEquals("lowerLetter", doc.getParagraphs().get(5).getNumFmt());
- assertEquals("lowerRoman", doc.getParagraphs().get(6).getNumFmt());
- }
-
- public void testLvlText() throws IOException {
- XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("Numbering.docx");
-
- assertEquals("%1.%2.%3.", doc.getParagraphs().get(12).getNumLevelText());
-
- assertEquals("NEW-%1-FORMAT", doc.getParagraphs().get(14).getNumLevelText());
-
- XWPFParagraph p = doc.getParagraphs().get(18);
- assertEquals("%1.", p.getNumLevelText());
- //test that null doesn't throw NPE
- assertNull(p.getNumFmt());
- }
-
- public void testOverrideList() throws IOException {
- XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("NumberingWOverrides.docx");
- XWPFParagraph p = doc.getParagraphs().get(4);
- XWPFNumbering numbering = doc.getNumbering();
- CTNum ctNum = numbering.getNum(p.getNumID()).getCTNum();
- assertEquals(9, ctNum.sizeOfLvlOverrideArray());
- CTNumLvl ctNumLvl = ctNum.getLvlOverrideArray(0);
- assertEquals("upperLetter", ctNumLvl.getLvl().getNumFmt().getVal().toString());
- }
-
-}
+import java.math.BigInteger;\r
+\r
+import junit.framework.TestCase;\r
+import org.apache.poi.xwpf.XWPFTestDataSamples;\r
+import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTNum;\r
+import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTNumLvl;\r
+\r
+public class TestXWPFNumbering extends TestCase {\r
+\r
+ public void testCompareAbstractNum() throws IOException {\r
+ XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("Numbering.docx");\r
+ XWPFNumbering numbering = doc.getNumbering();\r
+ BigInteger numId = BigInteger.valueOf(1);\r
+ assertTrue(numbering.numExist(numId));\r
+ XWPFNum num = numbering.getNum(numId);\r
+ BigInteger abstrNumId = num.getCTNum().getAbstractNumId().getVal();\r
+ XWPFAbstractNum abstractNum = numbering.getAbstractNum(abstrNumId);\r
+ BigInteger compareAbstractNum = numbering.getIdOfAbstractNum(abstractNum);\r
+ assertEquals(abstrNumId, compareAbstractNum);\r
+ }\r
+\r
+ public void testAddNumberingToDoc() throws IOException {\r
+ BigInteger abstractNumId = BigInteger.valueOf(1);\r
+ BigInteger numId = BigInteger.valueOf(1);\r
+\r
+ XWPFDocument docOut = new XWPFDocument();\r
+ XWPFNumbering numbering = docOut.createNumbering();\r
+ numId = numbering.addNum(abstractNumId);\r
+\r
+ XWPFDocument docIn = XWPFTestDataSamples.writeOutAndReadBack(docOut);\r
+\r
+ numbering = docIn.getNumbering();\r
+ assertTrue(numbering.numExist(numId));\r
+ XWPFNum num = numbering.getNum(numId);\r
+\r
+ BigInteger compareAbstractNum = num.getCTNum().getAbstractNumId().getVal();\r
+ assertEquals(abstractNumId, compareAbstractNum);\r
+ }\r
+\r
+ public void testGetNumIlvl() throws IOException {\r
+ XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("Numbering.docx");\r
+ BigInteger numIlvl = BigInteger.valueOf(0);\r
+ assertEquals(numIlvl, doc.getParagraphs().get(0).getNumIlvl());\r
+ numIlvl = BigInteger.valueOf(1);\r
+ assertEquals(numIlvl, doc.getParagraphs().get(5).getNumIlvl());\r
+ }\r
+\r
+ public void testGetNumFmt() throws IOException {\r
+ XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("Numbering.docx");\r
+ assertEquals("bullet", doc.getParagraphs().get(0).getNumFmt());\r
+ assertEquals("bullet", doc.getParagraphs().get(1).getNumFmt());\r
+ assertEquals("bullet", doc.getParagraphs().get(2).getNumFmt());\r
+ assertEquals("bullet", doc.getParagraphs().get(3).getNumFmt());\r
+ assertEquals("decimal", doc.getParagraphs().get(4).getNumFmt());\r
+ assertEquals("lowerLetter", doc.getParagraphs().get(5).getNumFmt());\r
+ assertEquals("lowerRoman", doc.getParagraphs().get(6).getNumFmt());\r
+ }\r
+\r
+ public void testLvlText() throws IOException {\r
+ XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("Numbering.docx");\r
+\r
+ assertEquals("%1.%2.%3.", doc.getParagraphs().get(12).getNumLevelText());\r
+\r
+ assertEquals("NEW-%1-FORMAT", doc.getParagraphs().get(14).getNumLevelText());\r
+\r
+ XWPFParagraph p = doc.getParagraphs().get(18);\r
+ assertEquals("%1.", p.getNumLevelText());\r
+ //test that null doesn't throw NPE\r
+ assertNull(p.getNumFmt());\r
+ }\r
+\r
+ public void testOverrideList() throws IOException {\r
+ XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("NumberingWOverrides.docx");\r
+ XWPFParagraph p = doc.getParagraphs().get(4);\r
+ XWPFNumbering numbering = doc.getNumbering();\r
+ CTNum ctNum = numbering.getNum(p.getNumID()).getCTNum();\r
+ assertEquals(9, ctNum.sizeOfLvlOverrideArray());\r
+ CTNumLvl ctNumLvl = ctNum.getLvlOverrideArray(0);\r
+ assertEquals("upperLetter", ctNumLvl.getLvl().getNumFmt().getVal().toString());\r
+ }\r
+\r
+}\r
import java.util.List;
import junit.framework.TestCase;
-
import org.apache.poi.xwpf.XWPFTestDataSamples;
import org.openxmlformats.schemas.drawingml.x2006.picture.CTPicture;
import org.openxmlformats.schemas.drawingml.x2006.picture.PicDocument;
import org.openxmlformats.schemas.drawingml.x2006.picture.impl.PicDocumentImpl;
-import org.openxmlformats.schemas.wordprocessingml.x2006.main.*;
+import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTBookmark;
+import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTBorder;
+import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTInd;
+import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTJc;
+import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTOnOff;
+import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTP;
+import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTPBdr;
+import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTPPr;
+import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTR;
+import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTSpacing;
+import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTextAlignment;
+import org.openxmlformats.schemas.wordprocessingml.x2006.main.STBorder;
+import org.openxmlformats.schemas.wordprocessingml.x2006.main.STJc;
+import org.openxmlformats.schemas.wordprocessingml.x2006.main.STLineSpacingRule;
+import org.openxmlformats.schemas.wordprocessingml.x2006.main.STOnOff;
+import org.openxmlformats.schemas.wordprocessingml.x2006.main.STTextAlignment;
/**
* Tests for XWPF Paragraphs
/**
* Check that we get the right paragraph from the header
- * @throws IOException
+ *
+ * @throws IOException
*/
public void disabled_testHeaderParagraph() throws IOException {
XWPFDocument xml = XWPFTestDataSamples.openSampleDocument("ThreeColHead.docx");
XWPFHeader hdr = xml.getHeaderFooterPolicy().getDefaultHeader();
assertNotNull(hdr);
- List<XWPFParagraph> ps = hdr.getParagraphs();
+ List<XWPFParagraph> ps = hdr.getParagraphs();
assertEquals(1, ps.size());
XWPFParagraph p = ps.get(0);
/**
* Check that we get the right paragraphs from the document
- * @throws IOException
+ *
+ * @throws IOException
*/
public void disabled_testDocumentParagraph() throws IOException {
XWPFDocument xml = XWPFTestDataSamples.openSampleDocument("ThreeColHead.docx");
assertEquals(STBorder.NONE.intValue(), p.getBorderTop().getValue());
CTP ctp = p.getCTP();
- CTPPr ppr = ctp.getPPr()== null? ctp.addNewPPr() : ctp.getPPr();
+ CTPPr ppr = ctp.getPPr() == null ? ctp.addNewPPr() : ctp.getPPr();
//bordi
CTPBdr bdr = ppr.addNewPBdr();
assertEquals(STJc.LEFT.intValue(), p.getAlignment().getValue());
CTP ctp = p.getCTP();
- CTPPr ppr = ctp.getPPr()== null? ctp.addNewPPr() : ctp.getPPr();
+ CTPPr ppr = ctp.getPPr() == null ? ctp.addNewPPr() : ctp.getPPr();
CTJc align = ppr.addNewJc();
align.setVal(STJc.CENTER);
XWPFParagraph p = doc.createParagraph();
CTP ctp = p.getCTP();
- CTPPr ppr = ctp.getPPr()== null? ctp.addNewPPr() : ctp.getPPr();
+ CTPPr ppr = ctp.getPPr() == null ? ctp.addNewPPr() : ctp.getPPr();
assertEquals(-1, p.getSpacingAfter());
XWPFParagraph p = doc.createParagraph();
CTP ctp = p.getCTP();
- CTPPr ppr = ctp.getPPr()== null? ctp.addNewPPr() : ctp.getPPr();
+ CTPPr ppr = ctp.getPPr() == null ? ctp.addNewPPr() : ctp.getPPr();
assertEquals(STLineSpacingRule.INT_AUTO, p.getSpacingLineRule().getValue());
assertEquals(-1, p.getIndentationLeft());
CTP ctp = p.getCTP();
- CTPPr ppr = ctp.getPPr()== null? ctp.addNewPPr() : ctp.getPPr();
+ CTPPr ppr = ctp.getPPr() == null ? ctp.addNewPPr() : ctp.getPPr();
assertEquals(-1, p.getIndentationLeft());
XWPFParagraph p = doc.createParagraph();
CTP ctp = p.getCTP();
- CTPPr ppr = ctp.getPPr()== null? ctp.addNewPPr() : ctp.getPPr();
+ CTPPr ppr = ctp.getPPr() == null ? ctp.addNewPPr() : ctp.getPPr();
CTTextAlignment txtAlign = ppr.addNewTextAlignment();
txtAlign.setVal(STTextAlignment.CENTER);
XWPFParagraph p = doc.createParagraph();
CTP ctp = p.getCTP();
- CTPPr ppr = ctp.getPPr()== null? ctp.addNewPPr() : ctp.getPPr();
+ CTPPr ppr = ctp.getPPr() == null ? ctp.addNewPPr() : ctp.getPPr();
CTOnOff wordWrap = ppr.addNewWordWrap();
wordWrap.setVal(STOnOff.FALSE);
XWPFParagraph p = doc.createParagraph();
CTP ctp = p.getCTP();
- CTPPr ppr = ctp.getPPr()== null? ctp.addNewPPr() : ctp.getPPr();
+ CTPPr ppr = ctp.getPPr() == null ? ctp.addNewPPr() : ctp.getPPr();
CTOnOff pageBreak = ppr.addNewPageBreakBefore();
pageBreak.setVal(STOnOff.FALSE);
assertEquals(0, paragraph.getCTP().sizeOfBookmarkEndArray());
CTBookmark ctBookmark = paragraph.getCTP().getBookmarkStartArray(0);
assertEquals("poi", ctBookmark.getName());
- for(CTBookmark bookmark : paragraph.getCTP().getBookmarkStartArray()) {
- assertEquals("poi", bookmark.getName());
+ for (CTBookmark bookmark : paragraph.getCTP().getBookmarkStartArray()) {
+ assertEquals("poi", bookmark.getName());
}
}
p.setNumID(new BigInteger("10"));
assertEquals("10", p.getNumID().toString());
}
-
+
public void testAddingRuns() throws Exception {
- XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("sample.docx");
-
- XWPFParagraph p = doc.getParagraphs().get(0);
- assertEquals(2, p.getRuns().size());
-
- XWPFRun r = p.createRun();
- assertEquals(3, p.getRuns().size());
- assertEquals(2, p.getRuns().indexOf(r));
-
- XWPFRun r2 = p.insertNewRun(1);
- assertEquals(4, p.getRuns().size());
- assertEquals(1, p.getRuns().indexOf(r2));
- assertEquals(3, p.getRuns().indexOf(r));
+ XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("sample.docx");
+
+ XWPFParagraph p = doc.getParagraphs().get(0);
+ assertEquals(2, p.getRuns().size());
+
+ XWPFRun r = p.createRun();
+ assertEquals(3, p.getRuns().size());
+ assertEquals(2, p.getRuns().indexOf(r));
+
+ XWPFRun r2 = p.insertNewRun(1);
+ assertEquals(4, p.getRuns().size());
+ assertEquals(1, p.getRuns().indexOf(r2));
+ assertEquals(3, p.getRuns().indexOf(r));
}
-
+
public void testPictures() throws Exception {
- XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("VariousPictures.docx");
- assertEquals(7, doc.getParagraphs().size());
-
- XWPFParagraph p;
- XWPFRun r;
-
- // Text paragraphs
- assertEquals("Sheet with various pictures", doc.getParagraphs().get(0).getText());
- assertEquals("(jpeg, png, wmf, emf and pict) ", doc.getParagraphs().get(1).getText());
-
- // Spacer ones
- assertEquals("", doc.getParagraphs().get(2).getText());
- assertEquals("", doc.getParagraphs().get(3).getText());
- assertEquals("", doc.getParagraphs().get(4).getText());
-
- // Image one
- p = doc.getParagraphs().get(5);
- assertEquals(6, p.getRuns().size());
-
- r = p.getRuns().get(0);
- assertEquals("", r.toString());
- assertEquals(1, r.getEmbeddedPictures().size());
- assertNotNull(r.getEmbeddedPictures().get(0).getPictureData());
- assertEquals("image1.wmf", r.getEmbeddedPictures().get(0).getPictureData().getFileName());
-
- r = p.getRuns().get(1);
- assertEquals("", r.toString());
- assertEquals(1, r.getEmbeddedPictures().size());
- assertNotNull(r.getEmbeddedPictures().get(0).getPictureData());
- assertEquals("image2.png", r.getEmbeddedPictures().get(0).getPictureData().getFileName());
-
- r = p.getRuns().get(2);
- assertEquals("", r.toString());
- assertEquals(1, r.getEmbeddedPictures().size());
- assertNotNull(r.getEmbeddedPictures().get(0).getPictureData());
- assertEquals("image3.emf", r.getEmbeddedPictures().get(0).getPictureData().getFileName());
-
- r = p.getRuns().get(3);
- assertEquals("", r.toString());
- assertEquals(1, r.getEmbeddedPictures().size());
- assertNotNull(r.getEmbeddedPictures().get(0).getPictureData());
- assertEquals("image4.emf", r.getEmbeddedPictures().get(0).getPictureData().getFileName());
-
- r = p.getRuns().get(4);
- assertEquals("", r.toString());
- assertEquals(1, r.getEmbeddedPictures().size());
- assertNotNull(r.getEmbeddedPictures().get(0).getPictureData());
- assertEquals("image5.jpeg", r.getEmbeddedPictures().get(0).getPictureData().getFileName());
-
- r = p.getRuns().get(5);
- assertEquals(" ", r.toString());
- assertEquals(0, r.getEmbeddedPictures().size());
-
- // Final spacer
- assertEquals("", doc.getParagraphs().get(6).getText());
-
-
- // Look in detail at one
- r = p.getRuns().get(4);
- XWPFPicture pict = r.getEmbeddedPictures().get(0);
- CTPicture picture = pict.getCTPicture();
- assertEquals("rId8", picture.getBlipFill().getBlip().getEmbed());
-
- // Ensure that the ooxml compiler finds everything we need
- r.getCTR().getDrawingArray(0);
- r.getCTR().getDrawingArray(0).getInlineArray(0);
- r.getCTR().getDrawingArray(0).getInlineArray(0).getGraphic();
- r.getCTR().getDrawingArray(0).getInlineArray(0).getGraphic().getGraphicData();
- PicDocument pd = new PicDocumentImpl(null);
- assertTrue(pd.isNil());
+ XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("VariousPictures.docx");
+ assertEquals(7, doc.getParagraphs().size());
+
+ XWPFParagraph p;
+ XWPFRun r;
+
+ // Text paragraphs
+ assertEquals("Sheet with various pictures", doc.getParagraphs().get(0).getText());
+ assertEquals("(jpeg, png, wmf, emf and pict) ", doc.getParagraphs().get(1).getText());
+
+ // Spacer ones
+ assertEquals("", doc.getParagraphs().get(2).getText());
+ assertEquals("", doc.getParagraphs().get(3).getText());
+ assertEquals("", doc.getParagraphs().get(4).getText());
+
+ // Image one
+ p = doc.getParagraphs().get(5);
+ assertEquals(6, p.getRuns().size());
+
+ r = p.getRuns().get(0);
+ assertEquals("", r.toString());
+ assertEquals(1, r.getEmbeddedPictures().size());
+ assertNotNull(r.getEmbeddedPictures().get(0).getPictureData());
+ assertEquals("image1.wmf", r.getEmbeddedPictures().get(0).getPictureData().getFileName());
+
+ r = p.getRuns().get(1);
+ assertEquals("", r.toString());
+ assertEquals(1, r.getEmbeddedPictures().size());
+ assertNotNull(r.getEmbeddedPictures().get(0).getPictureData());
+ assertEquals("image2.png", r.getEmbeddedPictures().get(0).getPictureData().getFileName());
+
+ r = p.getRuns().get(2);
+ assertEquals("", r.toString());
+ assertEquals(1, r.getEmbeddedPictures().size());
+ assertNotNull(r.getEmbeddedPictures().get(0).getPictureData());
+ assertEquals("image3.emf", r.getEmbeddedPictures().get(0).getPictureData().getFileName());
+
+ r = p.getRuns().get(3);
+ assertEquals("", r.toString());
+ assertEquals(1, r.getEmbeddedPictures().size());
+ assertNotNull(r.getEmbeddedPictures().get(0).getPictureData());
+ assertEquals("image4.emf", r.getEmbeddedPictures().get(0).getPictureData().getFileName());
+
+ r = p.getRuns().get(4);
+ assertEquals("", r.toString());
+ assertEquals(1, r.getEmbeddedPictures().size());
+ assertNotNull(r.getEmbeddedPictures().get(0).getPictureData());
+ assertEquals("image5.jpeg", r.getEmbeddedPictures().get(0).getPictureData().getFileName());
+
+ r = p.getRuns().get(5);
+ assertEquals(" ", r.toString());
+ assertEquals(0, r.getEmbeddedPictures().size());
+
+ // Final spacer
+ assertEquals("", doc.getParagraphs().get(6).getText());
+
+
+ // Look in detail at one
+ r = p.getRuns().get(4);
+ XWPFPicture pict = r.getEmbeddedPictures().get(0);
+ CTPicture picture = pict.getCTPicture();
+ assertEquals("rId8", picture.getBlipFill().getBlip().getEmbed());
+
+ // Ensure that the ooxml compiler finds everything we need
+ r.getCTR().getDrawingArray(0);
+ r.getCTR().getDrawingArray(0).getInlineArray(0);
+ r.getCTR().getDrawingArray(0).getInlineArray(0).getGraphic();
+ r.getCTR().getDrawingArray(0).getInlineArray(0).getGraphic().getGraphicData();
+ PicDocument pd = new PicDocumentImpl(null);
+ assertTrue(pd.isNil());
}
-
- public void testTika792() throws Exception{
- //This test forces the loading of CTMoveBookmark and
- //CTMoveBookmarkImpl into ooxml-lite.
- XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("Tika-792.docx");
- XWPFParagraph paragraph = doc.getParagraphs().get(0);
- assertEquals("s", paragraph.getText());
+
+ public void testTika792() throws Exception {
+ //This test forces the loading of CTMoveBookmark and
+ //CTMoveBookmarkImpl into ooxml-lite.
+ XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("Tika-792.docx");
+ XWPFParagraph paragraph = doc.getParagraphs().get(0);
+ assertEquals("s", paragraph.getText());
}
public void testSettersGetters() {
XWPFDocument doc = new XWPFDocument();
XWPFParagraph p = doc.createParagraph();
-
+
assertTrue(p.isEmpty());
assertFalse(p.removeRun(0));
assertFalse(p.isEmpty());
assertNull(p.getStyleID());
assertNull(p.getStyle());
-
+
assertNull(p.getNumID());
p.setNumID(BigInteger.valueOf(12));
assertEquals(BigInteger.valueOf(12), p.getNumID());
assertEquals(BigInteger.valueOf(13), p.getNumID());
assertNull(p.getNumFmt());
-
+
assertNull(p.getNumIlvl());
-
+
assertEquals("", p.getParagraphText());
assertEquals("", p.getPictureText());
assertEquals("", p.getFootnoteText());
-
+
p.setBorderBetween(Borders.NONE);
assertEquals(Borders.NONE, p.getBorderBetween());
p.setBorderBetween(Borders.BASIC_BLACK_DASHES);
assertEquals(Borders.BASIC_BLACK_DASHES, p.getBorderBetween());
-
+
p.setBorderBottom(Borders.NONE);
assertEquals(Borders.NONE, p.getBorderBottom());
p.setBorderBottom(Borders.BABY_RATTLE);
assertEquals(Borders.NONE, p.getBorderBottom());
p.setBorderBottom(Borders.BASIC_WHITE_DOTS);
assertEquals(Borders.BASIC_WHITE_DOTS, p.getBorderBottom());
-
+
assertFalse(p.isPageBreak());
p.setPageBreak(true);
assertTrue(p.isPageBreak());
p.setPageBreak(false);
assertFalse(p.isPageBreak());
-
+
assertEquals(-1, p.getSpacingAfter());
p.setSpacingAfter(12);
assertEquals(12, p.getSpacingAfter());
-
+
assertEquals(-1, p.getSpacingAfterLines());
p.setSpacingAfterLines(14);
assertEquals(14, p.getSpacingAfterLines());
-
+
assertEquals(-1, p.getSpacingBefore());
p.setSpacingBefore(16);
assertEquals(16, p.getSpacingBefore());
-
+
assertEquals(-1, p.getSpacingBeforeLines());
p.setSpacingBeforeLines(18);
assertEquals(18, p.getSpacingBeforeLines());
-
+
assertEquals(LineSpacingRule.AUTO, p.getSpacingLineRule());
p.setSpacingLineRule(LineSpacingRule.EXACT);
assertEquals(LineSpacingRule.EXACT, p.getSpacingLineRule());
-
+
assertEquals(-1, p.getIndentationLeft());
p.setIndentationLeft(21);
assertEquals(21, p.getIndentationLeft());
-
+
assertEquals(-1, p.getIndentationRight());
p.setIndentationRight(25);
assertEquals(25, p.getIndentationRight());
assertTrue(p.isWordWrap());
p.setWordWrap(false);
assertFalse(p.isWordWrap());
-
+
assertNull(p.getStyle());
p.setStyle("teststyle");
assertEquals("teststyle", p.getStyle());
-
+
p.addRun(CTR.Factory.newInstance());
-
+
//assertTrue(p.removeRun(0));
-
+
assertNotNull(p.getBody());
assertEquals(BodyElementType.PARAGRAPH, p.getElementType());
assertEquals(BodyType.DOCUMENT, p.getPartType());
}
-
+
public void testSearchTextNotFound() {
XWPFDocument doc = new XWPFDocument();
XWPFParagraph p = doc.createParagraph();
List<XWPFParagraph> ps = xml.getParagraphs();
assertEquals(10, ps.size());
-
+
XWPFParagraph p = ps.get(0);
TextSegement segment = p.searchText("sample word document", new PositionInParagraph());
assertNotNull(segment);
-
+
assertEquals("sample word document", p.getText(segment));
-
+
assertTrue(p.removeRun(0));
}
-
+
@SuppressWarnings("deprecation")
public void testRuns() {
XWPFDocument doc = new XWPFDocument();
XWPFRun r = new XWPFRun(run, doc.createParagraph());
p.addRun(r);
p.addRun(r);
-
+
assertNotNull(p.getRun(run));
assertNull(p.getRun(null));
}
import static org.junit.Assert.assertArrayEquals;
import java.io.IOException;
-import java.util.List;
-
-import junit.framework.TestCase;
-
-import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
-import org.apache.poi.openxml4j.opc.PackageRelationship;
-import org.apache.poi.xssf.usermodel.XSSFRelation;
+import java.util.List;\r
+\r
+import junit.framework.TestCase;\r
+import org.apache.poi.openxml4j.exceptions.InvalidFormatException;\r
+import org.apache.poi.openxml4j.opc.PackageRelationship;\r
+import org.apache.poi.xssf.usermodel.XSSFRelation;\r
import org.apache.poi.xwpf.XWPFTestDataSamples;
-import org.apache.poi.xwpf.model.XWPFHeaderFooterPolicy;
-
-public class TestXWPFPictureData extends TestCase {
-
- public void testRead() throws InvalidFormatException, IOException
- {
- XWPFDocument sampleDoc = XWPFTestDataSamples.openSampleDocument("VariousPictures.docx");
- List<XWPFPictureData> pictures = sampleDoc.getAllPictures();
-
- assertEquals(5,pictures.size());
- String[] ext = {"wmf","png","emf","emf","jpeg"};
- for (int i = 0 ; i < pictures.size() ; i++)
- {
- assertEquals(ext[i],pictures.get(i).suggestFileExtension());
- }
-
- int num = pictures.size();
-
- byte[] pictureData = XWPFTestDataSamples.getImage("nature1.jpg");
-
- String relationId = sampleDoc.addPictureData(pictureData,XWPFDocument.PICTURE_TYPE_JPEG);
- // picture list was updated
- assertEquals(num + 1,pictures.size());
- XWPFPictureData pict = (XWPFPictureData) sampleDoc.getRelationById(relationId);
- assertEquals("jpeg",pict.suggestFileExtension());
- assertArrayEquals(pictureData,pict.getData());
- }
-
- public void testPictureInHeader() throws IOException
- {
- XWPFDocument sampleDoc = XWPFTestDataSamples.openSampleDocument("headerPic.docx");
- verifyOneHeaderPicture(sampleDoc);
-
- XWPFDocument readBack = XWPFTestDataSamples.writeOutAndReadBack(sampleDoc);
- verifyOneHeaderPicture(readBack);
- }
+import org.apache.poi.xwpf.model.XWPFHeaderFooterPolicy;\r
+\r
+public class TestXWPFPictureData extends TestCase {\r
+\r
+ public void testRead() throws InvalidFormatException, IOException {\r
+ XWPFDocument sampleDoc = XWPFTestDataSamples.openSampleDocument("VariousPictures.docx");\r
+ List<XWPFPictureData> pictures = sampleDoc.getAllPictures();\r
+\r
+ assertEquals(5, pictures.size());\r
+ String[] ext = {"wmf", "png", "emf", "emf", "jpeg"};\r
+ for (int i = 0; i < pictures.size(); i++) {\r
+ assertEquals(ext[i], pictures.get(i).suggestFileExtension());\r
+ }\r
+\r
+ int num = pictures.size();\r
+\r
+ byte[] pictureData = XWPFTestDataSamples.getImage("nature1.jpg");\r
+\r
+ String relationId = sampleDoc.addPictureData(pictureData, XWPFDocument.PICTURE_TYPE_JPEG);\r
+ // picture list was updated\r
+ assertEquals(num + 1, pictures.size());\r
+ XWPFPictureData pict = (XWPFPictureData) sampleDoc.getRelationById(relationId);\r
+ assertEquals("jpeg", pict.suggestFileExtension());\r
+ assertArrayEquals(pictureData, pict.getData());\r
+ }\r
+\r
+ public void testPictureInHeader() throws IOException {\r
+ XWPFDocument sampleDoc = XWPFTestDataSamples.openSampleDocument("headerPic.docx");\r
+ verifyOneHeaderPicture(sampleDoc);\r
+\r
+ XWPFDocument readBack = XWPFTestDataSamples.writeOutAndReadBack(sampleDoc);\r
+ verifyOneHeaderPicture(readBack);\r
+ }\r
private void verifyOneHeaderPicture(XWPFDocument sampleDoc) {
XWPFHeaderFooterPolicy policy = sampleDoc.getHeaderFooterPolicy();
- XWPFHeader header = policy.getDefaultHeader();
-
- List<XWPFPictureData> pictures = header.getAllPictures();
- assertEquals(1,pictures.size());
- }
-
- public void testNew() throws InvalidFormatException, IOException
- {
- XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("EmptyDocumentWithHeaderFooter.docx");
- byte[] jpegData = XWPFTestDataSamples.getImage("nature1.jpg");
- assertNotNull(jpegData);
+ XWPFHeader header = policy.getDefaultHeader();\r
+\r
+ List<XWPFPictureData> pictures = header.getAllPictures();\r
+ assertEquals(1, pictures.size());\r
+ }\r
+\r
+ public void testNew() throws InvalidFormatException, IOException {\r
+ XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("EmptyDocumentWithHeaderFooter.docx");\r
+ byte[] jpegData = XWPFTestDataSamples.getImage("nature1.jpg");\r
+ assertNotNull(jpegData);\r
byte[] gifData = XWPFTestDataSamples.getImage("nature1.gif");
assertNotNull(gifData);
byte[] pngData = XWPFTestDataSamples.getImage("nature1.png");
- assertNotNull(pngData);
-
- List<XWPFPictureData> pictures = doc.getAllPictures();
- assertEquals(0,pictures.size());
-
- // Document shouldn't have any image relationships
- assertEquals(13,doc.getPackagePart().getRelationships().size());
- for (PackageRelationship rel : doc.getPackagePart().getRelationships())
- {
- if (rel.getRelationshipType().equals(XSSFRelation.IMAGE_JPEG.getRelation()))
- {
- fail("Shouldn't have JPEG yet");
- }
- }
-
- // Add the image
- String relationId = doc.addPictureData(jpegData,XWPFDocument.PICTURE_TYPE_JPEG);
- assertEquals(1,pictures.size());
- XWPFPictureData jpgPicData = (XWPFPictureData) doc.getRelationById(relationId);
- assertEquals("jpeg",jpgPicData.suggestFileExtension());
- assertArrayEquals(jpegData,jpgPicData.getData());
-
- // Ensure it now has one
- assertEquals(14,doc.getPackagePart().getRelationships().size());
- PackageRelationship jpegRel = null;
- for (PackageRelationship rel : doc.getPackagePart().getRelationships())
- {
- if (rel.getRelationshipType().equals(XWPFRelation.IMAGE_JPEG.getRelation()))
- {
- if (jpegRel != null)
- fail("Found 2 jpegs!");
- jpegRel = rel;
- }
- }
- assertNotNull("JPEG Relationship not found",jpegRel);
-
- // Check the details
- assertNotNull(jpegRel);
- assertEquals(XWPFRelation.IMAGE_JPEG.getRelation(),jpegRel.getRelationshipType());
- assertEquals("/word/document.xml",jpegRel.getSource().getPartName().toString());
- assertEquals("/word/media/image1.jpeg",jpegRel.getTargetURI().getPath());
-
- XWPFPictureData pictureDataByID = doc.getPictureDataByID(jpegRel.getId());
- assertArrayEquals(jpegData, pictureDataByID.getData());
-
- // Save an re-load, check it appears
- doc = XWPFTestDataSamples.writeOutAndReadBack(doc);
- assertEquals(1,doc.getAllPictures().size());
- assertEquals(1,doc.getAllPackagePictures().size());
-
- // verify the picture that we read back in
- pictureDataByID = doc.getPictureDataByID(jpegRel.getId());
- assertArrayEquals(jpegData, pictureDataByID.getData());
-
- }
-
- public void testBug51770() throws InvalidFormatException, IOException {
+ assertNotNull(pngData);\r
+\r
+ List<XWPFPictureData> pictures = doc.getAllPictures();\r
+ assertEquals(0, pictures.size());\r
+\r
+ // Document shouldn't have any image relationships\r
+ assertEquals(13, doc.getPackagePart().getRelationships().size());\r
+ for (PackageRelationship rel : doc.getPackagePart().getRelationships()) {\r
+ if (rel.getRelationshipType().equals(XSSFRelation.IMAGE_JPEG.getRelation())) {\r
+ fail("Shouldn't have JPEG yet");\r
+ }\r
+ }\r
+\r
+ // Add the image\r
+ String relationId = doc.addPictureData(jpegData, XWPFDocument.PICTURE_TYPE_JPEG);\r
+ assertEquals(1, pictures.size());\r
+ XWPFPictureData jpgPicData = (XWPFPictureData) doc.getRelationById(relationId);\r
+ assertEquals("jpeg", jpgPicData.suggestFileExtension());\r
+ assertArrayEquals(jpegData, jpgPicData.getData());\r
+\r
+ // Ensure it now has one\r
+ assertEquals(14, doc.getPackagePart().getRelationships().size());\r
+ PackageRelationship jpegRel = null;\r
+ for (PackageRelationship rel : doc.getPackagePart().getRelationships()) {\r
+ if (rel.getRelationshipType().equals(XWPFRelation.IMAGE_JPEG.getRelation())) {\r
+ if (jpegRel != null)\r
+ fail("Found 2 jpegs!");\r
+ jpegRel = rel;\r
+ }\r
+ }\r
+ assertNotNull("JPEG Relationship not found", jpegRel);\r
+\r
+ // Check the details\r
+ assertNotNull(jpegRel);\r
+ assertEquals(XWPFRelation.IMAGE_JPEG.getRelation(), jpegRel.getRelationshipType());\r
+ assertEquals("/word/document.xml", jpegRel.getSource().getPartName().toString());\r
+ assertEquals("/word/media/image1.jpeg", jpegRel.getTargetURI().getPath());\r
+\r
+ XWPFPictureData pictureDataByID = doc.getPictureDataByID(jpegRel.getId());\r
+ assertArrayEquals(jpegData, pictureDataByID.getData());\r
+\r
+ // Save an re-load, check it appears\r
+ doc = XWPFTestDataSamples.writeOutAndReadBack(doc);\r
+ assertEquals(1, doc.getAllPictures().size());\r
+ assertEquals(1, doc.getAllPackagePictures().size());\r
+\r
+ // verify the picture that we read back in\r
+ pictureDataByID = doc.getPictureDataByID(jpegRel.getId());\r
+ assertArrayEquals(jpegData, pictureDataByID.getData());\r
+\r
+ }\r
+\r
+ public void testBug51770() throws InvalidFormatException, IOException {\r
XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("Bug51170.docx");
XWPFHeaderFooterPolicy policy = doc.getHeaderFooterPolicy();
XWPFHeader header = policy.getDefaultHeader();
for (XWPFParagraph paragraph : header.getParagraphs()) {
for (XWPFRun run : paragraph.getRuns()) {
for (XWPFPicture picture : run.getEmbeddedPictures()) {
- if (paragraph.getDocument() != null) {
- //System.out.println(picture.getCTPicture());
- XWPFPictureData data = picture.getPictureData();
- if(data != null) System.out.println(data.getFileName());
- }
- }
- }
+ if (paragraph.getDocument() != null) {\r
+ //System.out.println(picture.getCTPicture());\r
+ XWPFPictureData data = picture.getPictureData();\r
+ if (data != null) System.out.println(data.getFileName());\r
+ }\r
+ }\r
+ }\r
}
}
import java.io.IOException;
import java.math.BigInteger;
import java.util.Iterator;
-import java.util.List;
-
-import junit.framework.TestCase;
-
-import org.apache.poi.xwpf.XWPFTestDataSamples;
-import org.apache.poi.xwpf.model.XWPFHeaderFooterPolicy;
-import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTBr;
+import java.util.List;\r
+\r
+import junit.framework.TestCase;\r
+import org.apache.poi.xwpf.XWPFTestDataSamples;\r
+import org.apache.poi.xwpf.model.XWPFHeaderFooterPolicy;\r
+import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTBr;\r
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTR;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTRPr;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.STBrClear;
p = doc.createParagraph();
this.ctRun = CTR.Factory.newInstance();
- }
-
- public void testSetGetText() {
- ctRun.addNewT().setStringValue("TEST STRING");
- ctRun.addNewT().setStringValue("TEST2 STRING");
- ctRun.addNewT().setStringValue("TEST3 STRING");
-
- assertEquals(3,ctRun.sizeOfTArray());
- XWPFRun run = new XWPFRun(ctRun, p);
-
- assertEquals("TEST2 STRING",run.getText(1));
-
- run.setText("NEW STRING",0);
- assertEquals("NEW STRING",run.getText(0));
-
- //run.setText("xxx",14);
- //fail("Position wrong");
- }
-
- public void testSetGetBold() {
- CTRPr rpr = ctRun.addNewRPr();
- rpr.addNewB().setVal(STOnOff.TRUE);
+ }\r
+\r
+ public void testSetGetText() {\r
+ ctRun.addNewT().setStringValue("TEST STRING");\r
+ ctRun.addNewT().setStringValue("TEST2 STRING");\r
+ ctRun.addNewT().setStringValue("TEST3 STRING");\r
+\r
+ assertEquals(3, ctRun.sizeOfTArray());\r
+ XWPFRun run = new XWPFRun(ctRun, p);\r
+\r
+ assertEquals("TEST2 STRING", run.getText(1));\r
+\r
+ run.setText("NEW STRING", 0);\r
+ assertEquals("NEW STRING", run.getText(0));\r
+\r
+ //run.setText("xxx",14);\r
+ //fail("Position wrong");\r
+ }\r
+\r
+ public void testSetGetBold() {\r
+ CTRPr rpr = ctRun.addNewRPr();\r
+ rpr.addNewB().setVal(STOnOff.TRUE);\r
XWPFRun run = new XWPFRun(ctRun, p);
assertEquals(true, run.isBold());
run.setText("T1");
run.addCarriageReturn();
run.addCarriageReturn();
- run.setText("T2");
- run.addCarriageReturn();
- assertEquals(3, run.getCTR().sizeOfCrArray());
-
- assertEquals("T1\n\nT2\n", run.toString());
- }
-
- public void testAddTabsAndLineBreaks() {
- ctRun.addNewT().setStringValue("TEST STRING");
- ctRun.addNewCr();
+ run.setText("T2");\r
+ run.addCarriageReturn();\r
+ assertEquals(3, run.getCTR().sizeOfCrArray());\r
+\r
+ assertEquals("T1\n\nT2\n", run.toString());\r
+ }\r
+\r
+ public void testAddTabsAndLineBreaks() {\r
+ ctRun.addNewT().setStringValue("TEST STRING");\r
+ ctRun.addNewCr();\r
ctRun.addNewT().setStringValue("TEST2 STRING");
ctRun.addNewTab();
ctRun.addNewT().setStringValue("TEST3 STRING");
run.addCarriageReturn();
run.setText("T2");
run.addTab();
- run.setText("T3");
- assertEquals(1, run.getCTR().sizeOfCrArray());
- assertEquals(1, run.getCTR().sizeOfTabArray());
-
- assertEquals("T1\nT2\tT3", run.toString());
- }
-
+ run.setText("T3");\r
+ assertEquals(1, run.getCTR().sizeOfCrArray());\r
+ assertEquals(1, run.getCTR().sizeOfTabArray());\r
+\r
+ assertEquals("T1\nT2\tT3", run.toString());\r
+ }\r
+\r
public void testAddPageBreak() {
- ctRun.addNewT().setStringValue("TEST STRING");
- ctRun.addNewBr();
- ctRun.addNewT().setStringValue("TEST2 STRING");
- CTBr breac=ctRun.addNewBr();
- breac.setClear(STBrClear.LEFT);
- ctRun.addNewT().setStringValue("TEST3 STRING");
- assertEquals(2, ctRun.sizeOfBrArray());
+ ctRun.addNewT().setStringValue("TEST STRING");\r
+ ctRun.addNewBr();\r
+ ctRun.addNewT().setStringValue("TEST2 STRING");\r
+ CTBr breac = ctRun.addNewBr();\r
+ breac.setClear(STBrClear.LEFT);\r
+ ctRun.addNewT().setStringValue("TEST3 STRING");\r
+ assertEquals(2, ctRun.sizeOfBrArray());\r
XWPFRun run = new XWPFRun(CTR.Factory.newInstance(), p);
run.setText("TEXT1");
run.addBreak(BreakType.TEXT_WRAPPING);
assertEquals(2, run.getCTR().sizeOfBrArray());
}
-
- /**
- * Test that on an existing document, we do the
- * right thing with it
- * @throws IOException
- */
- public void testExisting() throws IOException {
- XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("TestDocument.docx");
- XWPFParagraph p;
- XWPFRun run;
-
-
- // First paragraph is simple
- p = doc.getParagraphArray(0);
- assertEquals("This is a test document.", p.getText());
- assertEquals(2, p.getRuns().size());
-
- run = p.getRuns().get(0);
- assertEquals("This is a test document", run.toString());
- assertEquals(false, run.isBold());
- assertEquals(false, run.isItalic());
- assertEquals(false, run.isStrike());
- assertEquals(null, run.getCTR().getRPr());
-
- run = p.getRuns().get(1);
- assertEquals(".", run.toString());
- assertEquals(false, run.isBold());
- assertEquals(false, run.isItalic());
- assertEquals(false, run.isStrike());
- assertEquals(null, run.getCTR().getRPr());
-
-
- // Next paragraph is all in one style, but a different one
- p = doc.getParagraphArray(1);
- assertEquals("This bit is in bold and italic", p.getText());
- assertEquals(1, p.getRuns().size());
-
- run = p.getRuns().get(0);
- assertEquals("This bit is in bold and italic", run.toString());
- assertEquals(true, run.isBold());
- assertEquals(true, run.isItalic());
- assertEquals(false, run.isStrike());
- assertEquals(true, run.getCTR().getRPr().isSetB());
- assertEquals(false, run.getCTR().getRPr().getB().isSetVal());
-
-
- // Back to normal
- p = doc.getParagraphArray(2);
- assertEquals("Back to normal", p.getText());
- assertEquals(1, p.getRuns().size());
-
- run = p.getRuns().get(0);
- assertEquals("Back to normal", run.toString());
- assertEquals(false, run.isBold());
- assertEquals(false, run.isItalic());
- assertEquals(false, run.isStrike());
- assertEquals(null, run.getCTR().getRPr());
-
-
- // Different styles in one paragraph
- p = doc.getParagraphArray(3);
- assertEquals("This contains BOLD, ITALIC and BOTH, as well as RED and YELLOW text.", p.getText());
- assertEquals(11, p.getRuns().size());
-
- run = p.getRuns().get(0);
- assertEquals("This contains ", run.toString());
- assertEquals(false, run.isBold());
- assertEquals(false, run.isItalic());
- assertEquals(false, run.isStrike());
- assertEquals(null, run.getCTR().getRPr());
-
- run = p.getRuns().get(1);
- assertEquals("BOLD", run.toString());
- assertEquals(true, run.isBold());
- assertEquals(false, run.isItalic());
- assertEquals(false, run.isStrike());
-
- run = p.getRuns().get(2);
- assertEquals(", ", run.toString());
- assertEquals(false, run.isBold());
- assertEquals(false, run.isItalic());
- assertEquals(false, run.isStrike());
- assertEquals(null, run.getCTR().getRPr());
-
- run = p.getRuns().get(3);
- assertEquals("ITALIC", run.toString());
- assertEquals(false, run.isBold());
- assertEquals(true, run.isItalic());
- assertEquals(false, run.isStrike());
-
- run = p.getRuns().get(4);
- assertEquals(" and ", run.toString());
- assertEquals(false, run.isBold());
- assertEquals(false, run.isItalic());
- assertEquals(false, run.isStrike());
- assertEquals(null, run.getCTR().getRPr());
-
- run = p.getRuns().get(5);
- assertEquals("BOTH", run.toString());
- assertEquals(true, run.isBold());
- assertEquals(true, run.isItalic());
- assertEquals(false, run.isStrike());
-
- run = p.getRuns().get(6);
- assertEquals(", as well as ", run.toString());
- assertEquals(false, run.isBold());
- assertEquals(false, run.isItalic());
- assertEquals(false, run.isStrike());
- assertEquals(null, run.getCTR().getRPr());
-
- run = p.getRuns().get(7);
- assertEquals("RED", run.toString());
- assertEquals(false, run.isBold());
- assertEquals(false, run.isItalic());
- assertEquals(false, run.isStrike());
-
- run = p.getRuns().get(8);
- assertEquals(" and ", run.toString());
- assertEquals(false, run.isBold());
- assertEquals(false, run.isItalic());
- assertEquals(false, run.isStrike());
- assertEquals(null, run.getCTR().getRPr());
-
- run = p.getRuns().get(9);
- assertEquals("YELLOW", run.toString());
- assertEquals(false, run.isBold());
- assertEquals(false, run.isItalic());
- assertEquals(false, run.isStrike());
-
- run = p.getRuns().get(10);
- assertEquals(" text.", run.toString());
- assertEquals(false, run.isBold());
- assertEquals(false, run.isItalic());
- assertEquals(false, run.isStrike());
- assertEquals(null, run.getCTR().getRPr());
- }
-
- public void testPictureInHeader() throws IOException {
+\r
+ /**\r
+ * Test that on an existing document, we do the\r
+ * right thing with it\r
+ *\r
+ * @throws IOException\r
+ */\r
+ public void testExisting() throws IOException {\r
+ XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("TestDocument.docx");\r
+ XWPFParagraph p;\r
+ XWPFRun run;\r
+\r
+\r
+ // First paragraph is simple\r
+ p = doc.getParagraphArray(0);\r
+ assertEquals("This is a test document.", p.getText());\r
+ assertEquals(2, p.getRuns().size());\r
+\r
+ run = p.getRuns().get(0);\r
+ assertEquals("This is a test document", run.toString());\r
+ assertEquals(false, run.isBold());\r
+ assertEquals(false, run.isItalic());\r
+ assertEquals(false, run.isStrike());\r
+ assertEquals(null, run.getCTR().getRPr());\r
+\r
+ run = p.getRuns().get(1);\r
+ assertEquals(".", run.toString());\r
+ assertEquals(false, run.isBold());\r
+ assertEquals(false, run.isItalic());\r
+ assertEquals(false, run.isStrike());\r
+ assertEquals(null, run.getCTR().getRPr());\r
+\r
+\r
+ // Next paragraph is all in one style, but a different one\r
+ p = doc.getParagraphArray(1);\r
+ assertEquals("This bit is in bold and italic", p.getText());\r
+ assertEquals(1, p.getRuns().size());\r
+\r
+ run = p.getRuns().get(0);\r
+ assertEquals("This bit is in bold and italic", run.toString());\r
+ assertEquals(true, run.isBold());\r
+ assertEquals(true, run.isItalic());\r
+ assertEquals(false, run.isStrike());\r
+ assertEquals(true, run.getCTR().getRPr().isSetB());\r
+ assertEquals(false, run.getCTR().getRPr().getB().isSetVal());\r
+\r
+\r
+ // Back to normal\r
+ p = doc.getParagraphArray(2);\r
+ assertEquals("Back to normal", p.getText());\r
+ assertEquals(1, p.getRuns().size());\r
+\r
+ run = p.getRuns().get(0);\r
+ assertEquals("Back to normal", run.toString());\r
+ assertEquals(false, run.isBold());\r
+ assertEquals(false, run.isItalic());\r
+ assertEquals(false, run.isStrike());\r
+ assertEquals(null, run.getCTR().getRPr());\r
+\r
+\r
+ // Different styles in one paragraph\r
+ p = doc.getParagraphArray(3);\r
+ assertEquals("This contains BOLD, ITALIC and BOTH, as well as RED and YELLOW text.", p.getText());\r
+ assertEquals(11, p.getRuns().size());\r
+\r
+ run = p.getRuns().get(0);\r
+ assertEquals("This contains ", run.toString());\r
+ assertEquals(false, run.isBold());\r
+ assertEquals(false, run.isItalic());\r
+ assertEquals(false, run.isStrike());\r
+ assertEquals(null, run.getCTR().getRPr());\r
+\r
+ run = p.getRuns().get(1);\r
+ assertEquals("BOLD", run.toString());\r
+ assertEquals(true, run.isBold());\r
+ assertEquals(false, run.isItalic());\r
+ assertEquals(false, run.isStrike());\r
+\r
+ run = p.getRuns().get(2);\r
+ assertEquals(", ", run.toString());\r
+ assertEquals(false, run.isBold());\r
+ assertEquals(false, run.isItalic());\r
+ assertEquals(false, run.isStrike());\r
+ assertEquals(null, run.getCTR().getRPr());\r
+\r
+ run = p.getRuns().get(3);\r
+ assertEquals("ITALIC", run.toString());\r
+ assertEquals(false, run.isBold());\r
+ assertEquals(true, run.isItalic());\r
+ assertEquals(false, run.isStrike());\r
+\r
+ run = p.getRuns().get(4);\r
+ assertEquals(" and ", run.toString());\r
+ assertEquals(false, run.isBold());\r
+ assertEquals(false, run.isItalic());\r
+ assertEquals(false, run.isStrike());\r
+ assertEquals(null, run.getCTR().getRPr());\r
+\r
+ run = p.getRuns().get(5);\r
+ assertEquals("BOTH", run.toString());\r
+ assertEquals(true, run.isBold());\r
+ assertEquals(true, run.isItalic());\r
+ assertEquals(false, run.isStrike());\r
+\r
+ run = p.getRuns().get(6);\r
+ assertEquals(", as well as ", run.toString());\r
+ assertEquals(false, run.isBold());\r
+ assertEquals(false, run.isItalic());\r
+ assertEquals(false, run.isStrike());\r
+ assertEquals(null, run.getCTR().getRPr());\r
+\r
+ run = p.getRuns().get(7);\r
+ assertEquals("RED", run.toString());\r
+ assertEquals(false, run.isBold());\r
+ assertEquals(false, run.isItalic());\r
+ assertEquals(false, run.isStrike());\r
+\r
+ run = p.getRuns().get(8);\r
+ assertEquals(" and ", run.toString());\r
+ assertEquals(false, run.isBold());\r
+ assertEquals(false, run.isItalic());\r
+ assertEquals(false, run.isStrike());\r
+ assertEquals(null, run.getCTR().getRPr());\r
+\r
+ run = p.getRuns().get(9);\r
+ assertEquals("YELLOW", run.toString());\r
+ assertEquals(false, run.isBold());\r
+ assertEquals(false, run.isItalic());\r
+ assertEquals(false, run.isStrike());\r
+\r
+ run = p.getRuns().get(10);\r
+ assertEquals(" text.", run.toString());\r
+ assertEquals(false, run.isBold());\r
+ assertEquals(false, run.isItalic());\r
+ assertEquals(false, run.isStrike());\r
+ assertEquals(null, run.getCTR().getRPr());\r
+ }\r
+\r
+ public void testPictureInHeader() throws IOException {\r
XWPFDocument sampleDoc = XWPFTestDataSamples.openSampleDocument("headerPic.docx");
XWPFHeaderFooterPolicy policy = sampleDoc.getHeaderFooterPolicy();
for (XWPFPicture pic : pictures) {
assertNotNull(pic.getPictureData());
- assertEquals("DOZOR", pic.getDescription());
- }
-
- count+= pictures.size();
- }
- }
-
- assertEquals(1, count);
- }
-
- public void testAddPicture() throws Exception {
- XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("TestDocument.docx");
- XWPFParagraph p = doc.getParagraphArray(2);
- XWPFRun r = p.getRuns().get(0);
-
- assertEquals(0, doc.getAllPictures().size());
- assertEquals(0, r.getEmbeddedPictures().size());
-
- r.addPicture(new ByteArrayInputStream(new byte[0]), Document.PICTURE_TYPE_JPEG, "test.jpg", 21, 32);
-
- assertEquals(1, doc.getAllPictures().size());
- assertEquals(1, r.getEmbeddedPictures().size());
- }
-
- /**
- * Bugzilla #52288 - setting the font family on the
- * run mustn't NPE
- */
- public void testSetFontFamily_52288() throws Exception {
- XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("52288.docx");
- final Iterator<XWPFParagraph> paragraphs = doc.getParagraphsIterator();
- while (paragraphs.hasNext()) {
- final XWPFParagraph paragraph = paragraphs.next();
- for (final XWPFRun run : paragraph.getRuns()) {
- if (run != null) {
- final String text = run.getText(0);
- if (text != null) {
- run.setFontFamily("Times New Roman");
- }
- }
- }
- }
- }
-}
+ assertEquals("DOZOR", pic.getDescription());\r
+ }\r
+\r
+ count += pictures.size();\r
+ }\r
+ }\r
+\r
+ assertEquals(1, count);\r
+ }\r
+\r
+ public void testAddPicture() throws Exception {\r
+ XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("TestDocument.docx");\r
+ XWPFParagraph p = doc.getParagraphArray(2);\r
+ XWPFRun r = p.getRuns().get(0);\r
+\r
+ assertEquals(0, doc.getAllPictures().size());\r
+ assertEquals(0, r.getEmbeddedPictures().size());\r
+\r
+ r.addPicture(new ByteArrayInputStream(new byte[0]), Document.PICTURE_TYPE_JPEG, "test.jpg", 21, 32);\r
+\r
+ assertEquals(1, doc.getAllPictures().size());\r
+ assertEquals(1, r.getEmbeddedPictures().size());\r
+ }\r
+\r
+ /**\r
+ * Bugzilla #52288 - setting the font family on the\r
+ * run mustn't NPE\r
+ */\r
+ public void testSetFontFamily_52288() throws Exception {\r
+ XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("52288.docx");\r
+ final Iterator<XWPFParagraph> paragraphs = doc.getParagraphsIterator();\r
+ while (paragraphs.hasNext()) {\r
+ final XWPFParagraph paragraph = paragraphs.next();\r
+ for (final XWPFRun run : paragraph.getRuns()) {\r
+ if (run != null) {\r
+ final String text = run.getText(0);\r
+ if (text != null) {\r
+ run.setFontFamily("Times New Roman");\r
+ }\r
+ }\r
+ }\r
+ }\r
+ }\r
+}\r
limitations under the License.
==================================================================== */
-package org.apache.poi.xwpf.usermodel;
-
-import java.util.ArrayList;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-
-import junit.framework.TestCase;
-
-import org.apache.poi.xwpf.XWPFTestDataSamples;
-
-public final class TestXWPFSDT extends TestCase {
-
- /**
- * Test simple tag and title extraction from SDT
- * @throws Exception
- */
- public void testTagTitle() throws Exception {
- XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("Bug54849.docx");
- String tag = null;
- String title= null;
- List<AbstractXWPFSDT> sdts = extractAllSDTs(doc);
- for (AbstractXWPFSDT sdt :sdts){
- if (sdt.getContent().toString().equals("Rich_text")){
- tag = "MyTag";
- title = "MyTitle";
- break;
- }
-
- }
- assertEquals("controls size", 13, sdts.size());
-
+package org.apache.poi.xwpf.usermodel;\r
+\r
+import java.util.ArrayList;\r
+import java.util.List;\r
+import java.util.Map;\r
+\r
+import junit.framework.TestCase;\r
+import org.apache.poi.xwpf.XWPFTestDataSamples;\r
+\r
+public final class TestXWPFSDT extends TestCase {\r
+\r
+ /**\r
+ * Test simple tag and title extraction from SDT\r
+ *\r
+ * @throws Exception\r
+ */\r
+ public void testTagTitle() throws Exception {\r
+ XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("Bug54849.docx");\r
+ String tag = null;\r
+ String title = null;\r
+ List<AbstractXWPFSDT> sdts = extractAllSDTs(doc);\r
+ for (AbstractXWPFSDT sdt : sdts) {\r
+ if (sdt.getContent().toString().equals("Rich_text")) {\r
+ tag = "MyTag";\r
+ title = "MyTitle";\r
+ break;\r
+ }\r
+\r
+ }\r
+ assertEquals("controls size", 13, sdts.size());\r
+\r
assertEquals("tag", "MyTag", tag);
assertEquals("title", "MyTitle", title);
- }
-
-
- public void testGetSDTs() throws Exception{
- String[] contents = new String[]{
- "header_rich_text",
- "Rich_text",
+ }\r
+\r
+\r
+ public void testGetSDTs() throws Exception {\r
+ String[] contents = new String[]{\r
+ "header_rich_text",\r
+ "Rich_text",\r
"Rich_text_pre_table\nRich_text_cell1\t\t\t\n\t\t\t\n\t\t\t\n\nRich_text_post_table",
"Plain_text_no_newlines",
"Plain_text_with_newlines1\nplain_text_with_newlines2",
};
XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("Bug54849.docx");
List<AbstractXWPFSDT> sdts = extractAllSDTs(doc);
-
- assertEquals("number of sdts", contents.length, sdts.size());
-
- for (int i = 0; i < contents.length; i++){
- AbstractXWPFSDT sdt = sdts.get(i);
- assertEquals(i+ ": " + contents[i], contents[i], sdt.getContent().toString());
- }
- }
- /**
- * POI-54771 and TIKA-1317
- */
+\r
+ assertEquals("number of sdts", contents.length, sdts.size());\r
+\r
+ for (int i = 0; i < contents.length; i++) {\r
+ AbstractXWPFSDT sdt = sdts.get(i);\r
+ assertEquals(i + ": " + contents[i], contents[i], sdt.getContent().toString());\r
+ }\r
+ }\r
+\r
+ /**\r
+ * POI-54771 and TIKA-1317\r
+ */\r
public void testSDTAsCell() throws Exception {
//Bug54771a.docx and Bug54771b.docx test slightly
//different recursion patterns. Keep both!
- XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("Bug54771a.docx");
- List<AbstractXWPFSDT> sdts = extractAllSDTs(doc);
- String text = sdts.get(0).getContent().getText();
- assertEquals(2, sdts.size());
- assertTrue(text.indexOf("Test") > -1);
-
- text = sdts.get(1).getContent().getText();
+ XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("Bug54771a.docx");\r
+ List<AbstractXWPFSDT> sdts = extractAllSDTs(doc);\r
+ String text = sdts.get(0).getContent().getText();\r
+ assertEquals(2, sdts.size());\r
+ assertTrue(text.indexOf("Test") > -1);\r
+\r
+ text = sdts.get(1).getContent().getText();\r
assertTrue(text.indexOf("Test Subtitle") > -1);
assertTrue(text.indexOf("Test User") > -1);
assertTrue(text.indexOf("Test") < text.indexOf("Test Subtitle"));
-
- doc = XWPFTestDataSamples.openSampleDocument("Bug54771b.docx");
- sdts = extractAllSDTs(doc);
- assertEquals(3, sdts.size());
- assertTrue(sdts.get(0).getContent().getText().indexOf("Test") > -1);
-
- assertTrue(sdts.get(1).getContent().getText().indexOf("Test Subtitle") > -1);
- assertTrue(sdts.get(2).getContent().getText().indexOf("Test User") > -1);
-
- }
-
- /**
- * POI-55142 and Tika 1130
- */
- public void testNewLinesBetweenRuns() throws Exception{
- XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("Bug55142.docx");
- List<AbstractXWPFSDT> sdts = extractAllSDTs(doc);
- List<String> targs = new ArrayList<String>();
- //these test newlines and tabs in paragraphs/body elements
- targs.add("Rich-text1 abcdefghi");
- targs.add("Rich-text2 abcd\t\tefgh");
- targs.add("Rich-text3 abcd\nefg");
- targs.add("Rich-text4 abcdefg");
- targs.add("Rich-text5 abcdefg\nhijk");
- targs.add("Plain-text1 abcdefg");
- targs.add("Plain-text2 abcdefg\nhijk\nlmnop");
- //this tests consecutive runs within a cell (not a paragraph)
- //this test case was triggered by Tika-1130
- targs.add("sdt_incell2 abcdefg");
-
- for (int i = 0; i < sdts.size(); i++){
- AbstractXWPFSDT sdt = sdts.get(i);
- assertEquals(targs.get(i), targs.get(i), sdt.getContent().getText());
- }
- }
-
- private List<AbstractXWPFSDT> extractAllSDTs(XWPFDocument doc){
-
- List<AbstractXWPFSDT> sdts = new ArrayList<AbstractXWPFSDT>();
-
- List<XWPFHeader> headers = doc.getHeaderList();
- for (XWPFHeader header : headers){
- sdts.addAll(extractSDTsFromBodyElements(header.getBodyElements()));
- }
- sdts.addAll(extractSDTsFromBodyElements(doc.getBodyElements()));
-
- List<XWPFFooter> footers = doc.getFooterList();
- for (XWPFFooter footer : footers){
- sdts.addAll(extractSDTsFromBodyElements(footer.getBodyElements()));
- }
-
- for (XWPFFootnote footnote : doc.getFootnotes()){
- sdts.addAll(extractSDTsFromBodyElements(footnote.getBodyElements()));
- }
- for (Map.Entry<Integer, XWPFFootnote> e : doc.endnotes.entrySet()){
- sdts.addAll(extractSDTsFromBodyElements(e.getValue().getBodyElements()));
- }
- return sdts;
- }
-
- private List<AbstractXWPFSDT> extractSDTsFromBodyElements(List<IBodyElement> elements){
- List<AbstractXWPFSDT> sdts = new ArrayList<AbstractXWPFSDT>();
- for (IBodyElement e : elements){
- if (e instanceof XWPFSDT){
- XWPFSDT sdt = (XWPFSDT)e;
- sdts.add(sdt);
- } else if (e instanceof XWPFParagraph){
-
- XWPFParagraph p = (XWPFParagraph)e;
- for (IRunElement e2 : p.getIRuns()){
- if (e2 instanceof XWPFSDT){
- XWPFSDT sdt = (XWPFSDT)e2;
- sdts.add(sdt);
- }
- }
- } else if (e instanceof XWPFTable){
- XWPFTable table = (XWPFTable)e;
- sdts.addAll(extractSDTsFromTable(table));
- }
- }
+\r
+ doc = XWPFTestDataSamples.openSampleDocument("Bug54771b.docx");\r
+ sdts = extractAllSDTs(doc);\r
+ assertEquals(3, sdts.size());\r
+ assertTrue(sdts.get(0).getContent().getText().indexOf("Test") > -1);\r
+\r
+ assertTrue(sdts.get(1).getContent().getText().indexOf("Test Subtitle") > -1);\r
+ assertTrue(sdts.get(2).getContent().getText().indexOf("Test User") > -1);\r
+\r
+ }\r
+\r
+ /**\r
+ * POI-55142 and Tika 1130\r
+ */\r
+ public void testNewLinesBetweenRuns() throws Exception {\r
+ XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("Bug55142.docx");\r
+ List<AbstractXWPFSDT> sdts = extractAllSDTs(doc);\r
+ List<String> targs = new ArrayList<String>();\r
+ //these test newlines and tabs in paragraphs/body elements\r
+ targs.add("Rich-text1 abcdefghi");\r
+ targs.add("Rich-text2 abcd\t\tefgh");\r
+ targs.add("Rich-text3 abcd\nefg");\r
+ targs.add("Rich-text4 abcdefg");\r
+ targs.add("Rich-text5 abcdefg\nhijk");\r
+ targs.add("Plain-text1 abcdefg");\r
+ targs.add("Plain-text2 abcdefg\nhijk\nlmnop");\r
+ //this tests consecutive runs within a cell (not a paragraph)\r
+ //this test case was triggered by Tika-1130\r
+ targs.add("sdt_incell2 abcdefg");\r
+\r
+ for (int i = 0; i < sdts.size(); i++) {\r
+ AbstractXWPFSDT sdt = sdts.get(i);\r
+ assertEquals(targs.get(i), targs.get(i), sdt.getContent().getText());\r
+ }\r
+ }\r
+\r
+ private List<AbstractXWPFSDT> extractAllSDTs(XWPFDocument doc) {\r
+\r
+ List<AbstractXWPFSDT> sdts = new ArrayList<AbstractXWPFSDT>();\r
+\r
+ List<XWPFHeader> headers = doc.getHeaderList();\r
+ for (XWPFHeader header : headers) {\r
+ sdts.addAll(extractSDTsFromBodyElements(header.getBodyElements()));\r
+ }\r
+ sdts.addAll(extractSDTsFromBodyElements(doc.getBodyElements()));\r
+\r
+ List<XWPFFooter> footers = doc.getFooterList();\r
+ for (XWPFFooter footer : footers) {\r
+ sdts.addAll(extractSDTsFromBodyElements(footer.getBodyElements()));\r
+ }\r
+\r
+ for (XWPFFootnote footnote : doc.getFootnotes()) {\r
+ sdts.addAll(extractSDTsFromBodyElements(footnote.getBodyElements()));\r
+ }\r
+ for (Map.Entry<Integer, XWPFFootnote> e : doc.endnotes.entrySet()) {\r
+ sdts.addAll(extractSDTsFromBodyElements(e.getValue().getBodyElements()));\r
+ }\r
+ return sdts;\r
+ }\r
+\r
+ private List<AbstractXWPFSDT> extractSDTsFromBodyElements(List<IBodyElement> elements) {\r
+ List<AbstractXWPFSDT> sdts = new ArrayList<AbstractXWPFSDT>();\r
+ for (IBodyElement e : elements) {\r
+ if (e instanceof XWPFSDT) {\r
+ XWPFSDT sdt = (XWPFSDT) e;\r
+ sdts.add(sdt);\r
+ } else if (e instanceof XWPFParagraph) {\r
+\r
+ XWPFParagraph p = (XWPFParagraph) e;\r
+ for (IRunElement e2 : p.getIRuns()) {\r
+ if (e2 instanceof XWPFSDT) {\r
+ XWPFSDT sdt = (XWPFSDT) e2;\r
+ sdts.add(sdt);\r
+ }\r
+ }\r
+ } else if (e instanceof XWPFTable) {\r
+ XWPFTable table = (XWPFTable) e;\r
+ sdts.addAll(extractSDTsFromTable(table));\r
+ }\r
+ }\r
return sdts;
}
private List<AbstractXWPFSDT> extractSDTsFromTable(XWPFTable table) {
List<AbstractXWPFSDT> sdts = new ArrayList<AbstractXWPFSDT>();
- for (XWPFTableRow r : table.getRows()) {
- for (ICell c : r.getTableICells()) {
- if (c instanceof XWPFSDTCell) {
- sdts.add((XWPFSDTCell)c);
- } else if (c instanceof XWPFTableCell) {
- sdts.addAll(extractSDTsFromBodyElements(((XWPFTableCell)c).getBodyElements()));
- }
- }
- }
+ for (XWPFTableRow r : table.getRows()) {\r
+ for (ICell c : r.getTableICells()) {\r
+ if (c instanceof XWPFSDTCell) {\r
+ sdts.add((XWPFSDTCell) c);\r
+ } else if (c instanceof XWPFTableCell) {\r
+ sdts.addAll(extractSDTsFromBodyElements(((XWPFTableCell) c).getBodyElements()));\r
+ }\r
+ }\r
+ }\r
return sdts;
}
}
import java.io.IOException;\r
\r
import junit.framework.TestCase;\r
-\r
import org.apache.poi.xwpf.XWPFTestDataSamples;\r
\r
/**\r
* Tests for reading SmartTags from Word docx.\r
*\r
- * @author Fabian Lange\r
+ * @author Fabian Lange\r
*/\r
public final class TestXWPFSmartTag extends TestCase {\r
\r
import java.io.IOException;
import java.util.ArrayList;
-import java.util.List;
-
-import junit.framework.TestCase;
-
-import org.apache.poi.xwpf.XWPFTestDataSamples;
-import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTFonts;
-import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTLatentStyles;
+import java.util.List;\r
+\r
+import junit.framework.TestCase;\r
+import org.apache.poi.xwpf.XWPFTestDataSamples;\r
+import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTFonts;\r
+import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTLatentStyles;\r
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTLsdException;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTStyle;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTStyles;
public class TestXWPFStyles extends TestCase {
-// protected void setUp() throws Exception {
-// super.setUp();
-// }
-
- public void testGetUsedStyles() throws IOException{
- XWPFDocument sampleDoc = XWPFTestDataSamples.openSampleDocument("Styles.docx");
- List<XWPFStyle> testUsedStyleList = new ArrayList<XWPFStyle>();
- XWPFStyles styles = sampleDoc.getStyles();
- XWPFStyle style = styles.getStyle("berschrift1");
- testUsedStyleList.add(style);
- testUsedStyleList.add(styles.getStyle("Standard"));
- testUsedStyleList.add(styles.getStyle("berschrift1Zchn"));
- testUsedStyleList.add(styles.getStyle("Absatz-Standardschriftart"));
- style.hasSameName(style);
-
- List<XWPFStyle> usedStyleList = styles.getUsedStyleList(style);
- assertEquals(usedStyleList, testUsedStyleList);
-
-
- }
-
- public void testAddStylesToDocument() throws IOException{
- XWPFDocument docOut = new XWPFDocument();
- XWPFStyles styles = docOut.createStyles();
-
- String strStyleId = "headline1";
- CTStyle ctStyle = CTStyle.Factory.newInstance();
-
- ctStyle.setStyleId(strStyleId);
- XWPFStyle s = new XWPFStyle(ctStyle);
- styles.addStyle(s);
-
- assertTrue(styles.styleExist(strStyleId));
-
- XWPFDocument docIn = XWPFTestDataSamples.writeOutAndReadBack(docOut);
-
- styles = docIn.getStyles();
- assertTrue(styles.styleExist(strStyleId));
- }
-
- /**
- * Bug #52449 - We should be able to write a file containing
- * both regular and glossary styles without error
- */
- public void test52449() throws Exception {
- XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("52449.docx");
- XWPFStyles styles = doc.getStyles();
- assertNotNull(styles);
-
- XWPFDocument docIn = XWPFTestDataSamples.writeOutAndReadBack(doc);
- styles = docIn.getStyles();
- assertNotNull(styles);
- }
-
-
- /**
- * YK: tests below don't make much sense,
- * they exist only to copy xml beans to pi-ooxml-schemas.jar
- */
- public void testLanguages(){
- XWPFDocument docOut = new XWPFDocument();
- XWPFStyles styles = docOut.createStyles();
- styles.setEastAsia("Chinese");
+// protected void setUp() throws Exception {\r
+// super.setUp();\r
+// }\r
+\r
+ public void testGetUsedStyles() throws IOException {\r
+ XWPFDocument sampleDoc = XWPFTestDataSamples.openSampleDocument("Styles.docx");\r
+ List<XWPFStyle> testUsedStyleList = new ArrayList<XWPFStyle>();\r
+ XWPFStyles styles = sampleDoc.getStyles();\r
+ XWPFStyle style = styles.getStyle("berschrift1");\r
+ testUsedStyleList.add(style);\r
+ testUsedStyleList.add(styles.getStyle("Standard"));\r
+ testUsedStyleList.add(styles.getStyle("berschrift1Zchn"));\r
+ testUsedStyleList.add(styles.getStyle("Absatz-Standardschriftart"));\r
+ style.hasSameName(style);\r
+\r
+ List<XWPFStyle> usedStyleList = styles.getUsedStyleList(style);\r
+ assertEquals(usedStyleList, testUsedStyleList);\r
+\r
+\r
+ }\r
+\r
+ public void testAddStylesToDocument() throws IOException {\r
+ XWPFDocument docOut = new XWPFDocument();\r
+ XWPFStyles styles = docOut.createStyles();\r
+\r
+ String strStyleId = "headline1";\r
+ CTStyle ctStyle = CTStyle.Factory.newInstance();\r
+\r
+ ctStyle.setStyleId(strStyleId);\r
+ XWPFStyle s = new XWPFStyle(ctStyle);\r
+ styles.addStyle(s);\r
+\r
+ assertTrue(styles.styleExist(strStyleId));\r
+\r
+ XWPFDocument docIn = XWPFTestDataSamples.writeOutAndReadBack(docOut);\r
+\r
+ styles = docIn.getStyles();\r
+ assertTrue(styles.styleExist(strStyleId));\r
+ }\r
+\r
+ /**\r
+ * Bug #52449 - We should be able to write a file containing\r
+ * both regular and glossary styles without error\r
+ */\r
+ public void test52449() throws Exception {\r
+ XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("52449.docx");\r
+ XWPFStyles styles = doc.getStyles();\r
+ assertNotNull(styles);\r
+\r
+ XWPFDocument docIn = XWPFTestDataSamples.writeOutAndReadBack(doc);\r
+ styles = docIn.getStyles();\r
+ assertNotNull(styles);\r
+ }\r
+\r
+\r
+ /**\r
+ * YK: tests below don't make much sense,\r
+ * they exist only to copy xml beans to pi-ooxml-schemas.jar\r
+ */\r
+ public void testLanguages() {\r
+ XWPFDocument docOut = new XWPFDocument();\r
+ XWPFStyles styles = docOut.createStyles();\r
+ styles.setEastAsia("Chinese");\r
styles.setSpellingLanguage("English");
CTLsdException ex = latentStyles.addNewLsdException();
ex.setName("ex1");
XWPFLatentStyles ls = new XWPFLatentStyles(latentStyles);
- assertEquals(true, ls.isLatentStyle("ex1"));
- assertEquals(false, ls.isLatentStyle("notex1"));
- }
-
- public void testSetStyles_Bug57254() throws IOException {
- XWPFDocument docOut = new XWPFDocument();
- XWPFStyles styles = docOut.createStyles();
+ assertEquals(true, ls.isLatentStyle("ex1"));\r
+ assertEquals(false, ls.isLatentStyle("notex1"));\r
+ }\r
+\r
+ public void testSetStyles_Bug57254() throws IOException {\r
+ XWPFDocument docOut = new XWPFDocument();\r
+ XWPFStyles styles = docOut.createStyles();\r
CTStyles ctStyles = CTStyles.Factory.newInstance();
String strStyleId = "headline1";
CTStyle ctStyle = ctStyles.addNewStyle();
-
- ctStyle.setStyleId(strStyleId);
- styles.setStyles(ctStyles);
-
- assertTrue(styles.styleExist(strStyleId));
-
- XWPFDocument docIn = XWPFTestDataSamples.writeOutAndReadBack(docOut);
-
- styles = docIn.getStyles();
- assertTrue(styles.styleExist(strStyleId));
- }
-
- public void testEasyAccessToStyles() throws IOException {
- XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("SampleDoc.docx");
- XWPFStyles styles = doc.getStyles();
- assertNotNull(styles);
-
- // Has 3 paragraphs on page one, a break, and 3 on page 2
- assertEquals(7, doc.getParagraphs().size());
-
- // Check the first three have no run styles, just default paragraph style
- for (int i=0; i<3; i++) {
- XWPFParagraph p = doc.getParagraphs().get(i);
- assertEquals(null, p.getStyle());
- assertEquals(null, p.getStyleID());
- assertEquals(1, p.getRuns().size());
-
- XWPFRun r = p.getRuns().get(0);
- assertEquals(null, r.getColor());
- assertEquals(null, r.getFontFamily());
- assertEquals(null, r.getFontName());
- assertEquals(-1, r.getFontSize());
- }
-
- // On page two, has explicit styles, but on runs not on
- // the paragraph itself
- for (int i=4; i<7; i++) {
- XWPFParagraph p = doc.getParagraphs().get(i);
- assertEquals(null, p.getStyle());
- assertEquals(null, p.getStyleID());
- assertEquals(1, p.getRuns().size());
-
- XWPFRun r = p.getRuns().get(0);
- assertEquals("Arial Black", r.getFontFamily());
- assertEquals("Arial Black", r.getFontName());
- assertEquals(16, r.getFontSize());
- assertEquals("548DD4", r.getColor());
- }
-
- // Check the document styles
- // Should have a style defined for each type
- assertEquals(4, styles.getNumberOfStyles());
+\r
+ ctStyle.setStyleId(strStyleId);\r
+ styles.setStyles(ctStyles);\r
+\r
+ assertTrue(styles.styleExist(strStyleId));\r
+\r
+ XWPFDocument docIn = XWPFTestDataSamples.writeOutAndReadBack(docOut);\r
+
+ styles = docIn.getStyles();\r
+ assertTrue(styles.styleExist(strStyleId));\r
+ }\r
+\r
+ public void testEasyAccessToStyles() throws IOException {\r
+ XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("SampleDoc.docx");\r
+ XWPFStyles styles = doc.getStyles();\r
+ assertNotNull(styles);\r
+\r
+ // Has 3 paragraphs on page one, a break, and 3 on page 2\r
+ assertEquals(7, doc.getParagraphs().size());\r
+\r
+ // Check the first three have no run styles, just default paragraph style\r
+ for (int i = 0; i < 3; i++) {\r
+ XWPFParagraph p = doc.getParagraphs().get(i);\r
+ assertEquals(null, p.getStyle());\r
+ assertEquals(null, p.getStyleID());\r
+ assertEquals(1, p.getRuns().size());\r
+\r
+ XWPFRun r = p.getRuns().get(0);\r
+ assertEquals(null, r.getColor());\r
+ assertEquals(null, r.getFontFamily());\r
+ assertEquals(null, r.getFontName());\r
+ assertEquals(-1, r.getFontSize());\r
+ }\r
+\r
+ // On page two, has explicit styles, but on runs not on\r
+ // the paragraph itself\r
+ for (int i = 4; i < 7; i++) {\r
+ XWPFParagraph p = doc.getParagraphs().get(i);\r
+ assertEquals(null, p.getStyle());\r
+ assertEquals(null, p.getStyleID());\r
+ assertEquals(1, p.getRuns().size());\r
+\r
+ XWPFRun r = p.getRuns().get(0);\r
+ assertEquals("Arial Black", r.getFontFamily());\r
+ assertEquals("Arial Black", r.getFontName());\r
+ assertEquals(16, r.getFontSize());\r
+ assertEquals("548DD4", r.getColor());\r
+ }\r
+\r
+ // Check the document styles\r
+ // Should have a style defined for each type\r
+ assertEquals(4, styles.getNumberOfStyles());\r
assertNotNull(styles.getStyle("Normal"));
- assertNotNull(styles.getStyle("DefaultParagraphFont"));
- assertNotNull(styles.getStyle("TableNormal"));
- assertNotNull(styles.getStyle("NoList"));
-
- // We can't do much yet with latent styles
- assertEquals(137, styles.getLatentStyles().getNumberOfStyles());
-
- // Check the default styles
- assertNotNull(styles.getDefaultRunStyle());
- assertNotNull(styles.getDefaultParagraphStyle());
-
- assertEquals(11, styles.getDefaultRunStyle().getFontSize());
- assertEquals(200, styles.getDefaultParagraphStyle().getSpacingAfter());
- }
+ assertNotNull(styles.getStyle("DefaultParagraphFont"));\r
+ assertNotNull(styles.getStyle("TableNormal"));\r
+ assertNotNull(styles.getStyle("NoList"));\r
+\r
+ // We can't do much yet with latent styles\r
+ assertEquals(137, styles.getLatentStyles().getNumberOfStyles());\r
+\r
+ // Check the default styles\r
+ assertNotNull(styles.getDefaultRunStyle());\r
+ assertNotNull(styles.getDefaultParagraphStyle());\r
+\r
+ assertEquals(11, styles.getDefaultRunStyle().getFontSize());\r
+ assertEquals(200, styles.getDefaultParagraphStyle().getSpacingAfter());\r
+ }\r
}
package org.apache.poi.xwpf.usermodel;
import java.math.BigInteger;
-import java.util.List;
-
-import junit.framework.TestCase;
-
-import org.apache.poi.xwpf.XWPFTestDataSamples;
-import org.apache.poi.xwpf.usermodel.XWPFTable.XWPFBorderType;
-import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTP;
+import java.util.List;\r
+\r
+import junit.framework.TestCase;\r
+import org.apache.poi.xwpf.XWPFTestDataSamples;\r
+import org.apache.poi.xwpf.usermodel.XWPFTable.XWPFBorderType;\r
+import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTP;\r
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTR;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTRow;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTbl;
assertEquals(1, xtab.getCTTbl().getTrArray(0).sizeOfTcArray());
}
-
- public void testSetGetWidth() {
- XWPFDocument doc = new XWPFDocument();
-
- CTTbl table = CTTbl.Factory.newInstance();
- table.addNewTblPr().addNewTblW().setW(new BigInteger("1000"));
-
+\r
+ public void testSetGetWidth() {\r
+ XWPFDocument doc = new XWPFDocument();\r
+\r
+ CTTbl table = CTTbl.Factory.newInstance();\r
+ table.addNewTblPr().addNewTblW().setW(new BigInteger("1000"));\r
+\r
XWPFTable xtab = new XWPFTable(table, doc);
assertEquals(1000, xtab.getWidth());
XWPFTableRow row = xtab.createRow();
row.setHeight(20);
assertEquals(20, row.getHeight());
- }
-
- public void testSetGetMargins() {
- // instantiate the following class so it'll get picked up by
- // the XmlBean process and added to the jar file. it's required
- // for the following XWPFTable methods.
- CTTblCellMar ctm = CTTblCellMar.Factory.newInstance();
- assertNotNull(ctm);
- // create a table
- XWPFDocument doc = new XWPFDocument();
- CTTbl ctTable = CTTbl.Factory.newInstance();
- XWPFTable table = new XWPFTable(ctTable, doc);
- // set margins
- table.setCellMargins(50, 50, 250, 450);
+ }\r
+\r
+ public void testSetGetMargins() {\r
+ // instantiate the following class so it'll get picked up by\r
+ // the XmlBean process and added to the jar file. it's required\r
+ // for the following XWPFTable methods.\r
+ CTTblCellMar ctm = CTTblCellMar.Factory.newInstance();\r
+ assertNotNull(ctm);\r
+ // create a table\r
+ XWPFDocument doc = new XWPFDocument();\r
+ CTTbl ctTable = CTTbl.Factory.newInstance();\r
+ XWPFTable table = new XWPFTable(ctTable, doc);\r
+ // set margins\r
+ table.setCellMargins(50, 50, 250, 450);\r
// get margin components
int t = table.getCellMarginTop();
assertEquals(50, t);
assertEquals(250, b);
int r = table.getCellMarginRight();
assertEquals(450, r);
- }
-
- public void testSetGetHBorders() {
- // instantiate the following classes so they'll get picked up by
- // the XmlBean process and added to the jar file. they are required
- // for the following XWPFTable methods.
- CTTblBorders cttb = CTTblBorders.Factory.newInstance();
- assertNotNull(cttb);
- STBorder stb = STBorder.Factory.newInstance();
- assertNotNull(stb);
- // create a table
- XWPFDocument doc = new XWPFDocument();
- CTTbl ctTable = CTTbl.Factory.newInstance();
- XWPFTable table = new XWPFTable(ctTable, doc);
- // set inside horizontal border
- table.setInsideHBorder(XWPFBorderType.SINGLE, 4, 0, "FF0000");
+ }\r
+\r
+ public void testSetGetHBorders() {\r
+ // instantiate the following classes so they'll get picked up by\r
+ // the XmlBean process and added to the jar file. they are required\r
+ // for the following XWPFTable methods.\r
+ CTTblBorders cttb = CTTblBorders.Factory.newInstance();\r
+ assertNotNull(cttb);\r
+ STBorder stb = STBorder.Factory.newInstance();\r
+ assertNotNull(stb);\r
+ // create a table\r
+ XWPFDocument doc = new XWPFDocument();\r
+ CTTbl ctTable = CTTbl.Factory.newInstance();\r
+ XWPFTable table = new XWPFTable(ctTable, doc);\r
+ // set inside horizontal border\r
+ table.setInsideHBorder(XWPFBorderType.SINGLE, 4, 0, "FF0000");\r
// get inside horizontal border components
int s = table.getInsideHBorderSize();
assertEquals(4, s);
assertEquals("FF0000", clr);
XWPFBorderType bt = table.getInsideHBorderType();
assertEquals(XWPFBorderType.SINGLE, bt);
- }
-
- public void testSetGetVBorders() {
- // create a table
- XWPFDocument doc = new XWPFDocument();
- CTTbl ctTable = CTTbl.Factory.newInstance();
- XWPFTable table = new XWPFTable(ctTable, doc);
+ }\r
+\r
+ public void testSetGetVBorders() {\r
+ // create a table\r
+ XWPFDocument doc = new XWPFDocument();\r
+ CTTbl ctTable = CTTbl.Factory.newInstance();\r
+ XWPFTable table = new XWPFTable(ctTable, doc);\r
// set inside vertical border
table.setInsideVBorder(XWPFBorderType.DOUBLE, 4, 0, "00FF00");
// get inside vertical border components
XWPFBorderType bt = table.getInsideVBorderType();
assertEquals(XWPFBorderType.DOUBLE, bt);
int sz = table.getInsideVBorderSize();
- assertEquals(4, sz);
- int sp = table.getInsideVBorderSpace();
- assertEquals(0, sp);
- String clr = table.getInsideVBorderColor();
- assertEquals("00FF00", clr);
- }
-
+ assertEquals(4, sz);\r
+ int sp = table.getInsideVBorderSpace();\r
+ assertEquals(0, sp);\r
+ String clr = table.getInsideVBorderColor();\r
+ assertEquals("00FF00", clr);\r
+ }\r
+\r
public void testSetGetRowBandSize() {
XWPFDocument doc = new XWPFDocument();
CTTbl ctTable = CTTbl.Factory.newInstance();
table.setColBandSize(16);
int sz = table.getColBandSize();
assertEquals(16, sz);
- }
-
- public void testCreateTable() throws Exception {
- // open an empty document
- XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("sample.docx");
-
- // create a table with 5 rows and 7 columns
- int noRows = 5;
- int noCols = 7;
- XWPFTable table = doc.createTable(noRows,noCols);
-
- // assert the table is empty
- List<XWPFTableRow> rows = table.getRows();
- assertEquals("Table has less rows than requested.", noRows, rows.size());
- for (XWPFTableRow xwpfRow : rows)
- {
- assertNotNull(xwpfRow);
- for (int i = 0 ; i < 7 ; i++)
- {
- XWPFTableCell xwpfCell = xwpfRow.getCell(i);
- assertNotNull(xwpfCell);
- assertEquals("Empty cells should not have one paragraph.",1,xwpfCell.getParagraphs().size());
- xwpfCell = xwpfRow.getCell(i);
- assertEquals("Calling 'getCell' must not modify cells content.",1,xwpfCell.getParagraphs().size());
- }
- }
- doc.getPackage().revert();
- }
+ }\r
+\r
+ public void testCreateTable() throws Exception {\r
+ // open an empty document\r
+ XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("sample.docx");\r
+\r
+ // create a table with 5 rows and 7 columns\r
+ int noRows = 5;\r
+ int noCols = 7;\r
+ XWPFTable table = doc.createTable(noRows, noCols);\r
+\r
+ // assert the table is empty\r
+ List<XWPFTableRow> rows = table.getRows();\r
+ assertEquals("Table has less rows than requested.", noRows, rows.size());\r
+ for (XWPFTableRow xwpfRow : rows) {\r
+ assertNotNull(xwpfRow);\r
+ for (int i = 0; i < 7; i++) {\r
+ XWPFTableCell xwpfCell = xwpfRow.getCell(i);\r
+ assertNotNull(xwpfCell);\r
+ assertEquals("Empty cells should not have one paragraph.", 1, xwpfCell.getParagraphs().size());\r
+ xwpfCell = xwpfRow.getCell(i);\r
+ assertEquals("Calling 'getCell' must not modify cells content.", 1, xwpfCell.getParagraphs().size());\r
+ }\r
+ }\r
+ doc.getPackage().revert();\r
+ }\r
}
\ No newline at end of file
* ====================================================================
*/
-package org.apache.poi.xwpf.usermodel;
-
-import junit.framework.TestCase;
-
-import org.apache.poi.xwpf.usermodel.XWPFTableCell.XWPFVertAlign;
-import org.openxmlformats.schemas.wordprocessingml.x2006.main.*;
-
-public class TestXWPFTableCell extends TestCase {
-
- @Override
- protected void setUp() throws Exception {
- super.setUp();
- }
-
- public void testSetGetVertAlignment() throws Exception {
- // instantiate the following classes so they'll get picked up by
- // the XmlBean process and added to the jar file. they are required
- // for the following XWPFTableCell methods.
- CTShd ctShd = CTShd.Factory.newInstance();
- assertNotNull(ctShd);
- CTVerticalJc ctVjc = CTVerticalJc.Factory.newInstance();
- assertNotNull(ctVjc);
- STShd stShd = STShd.Factory.newInstance();
- assertNotNull(stShd);
- STVerticalJc stVjc = STVerticalJc.Factory.newInstance();
- assertNotNull(stVjc);
-
- // create a table
- XWPFDocument doc = new XWPFDocument();
- CTTbl ctTable = CTTbl.Factory.newInstance();
- XWPFTable table = new XWPFTable(ctTable, doc);
- // table has a single row by default; grab it
- XWPFTableRow tr = table.getRow(0);
+package org.apache.poi.xwpf.usermodel;\r
+\r
+import junit.framework.TestCase;\r
+import org.apache.poi.xwpf.usermodel.XWPFTableCell.XWPFVertAlign;\r
+import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTHMerge;\r
+import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTShd;\r
+import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTbl;\r
+import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTc;\r
+import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTcBorders;\r
+import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTcPr;\r
+import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTVMerge;\r
+import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTVerticalJc;\r
+import org.openxmlformats.schemas.wordprocessingml.x2006.main.STMerge;\r
+import org.openxmlformats.schemas.wordprocessingml.x2006.main.STShd;\r
+import org.openxmlformats.schemas.wordprocessingml.x2006.main.STVerticalJc;\r
+\r
+public class TestXWPFTableCell extends TestCase {\r
+\r
+ @Override\r
+ protected void setUp() throws Exception {\r
+ super.setUp();\r
+ }\r
+\r
+ public void testSetGetVertAlignment() throws Exception {\r
+ // instantiate the following classes so they'll get picked up by\r
+ // the XmlBean process and added to the jar file. they are required\r
+ // for the following XWPFTableCell methods.\r
+ CTShd ctShd = CTShd.Factory.newInstance();\r
+ assertNotNull(ctShd);\r
+ CTVerticalJc ctVjc = CTVerticalJc.Factory.newInstance();\r
+ assertNotNull(ctVjc);\r
+ STShd stShd = STShd.Factory.newInstance();\r
+ assertNotNull(stShd);\r
+ STVerticalJc stVjc = STVerticalJc.Factory.newInstance();\r
+ assertNotNull(stVjc);\r
+\r
+ // create a table\r
+ XWPFDocument doc = new XWPFDocument();\r
+ CTTbl ctTable = CTTbl.Factory.newInstance();\r
+ XWPFTable table = new XWPFTable(ctTable, doc);\r
+ // table has a single row by default; grab it\r
+ XWPFTableRow tr = table.getRow(0);\r
assertNotNull(tr);
// row has a single cell by default; grab it
XWPFTableCell cell = tr.getCell(0);
- cell.setVerticalAlignment(XWPFVertAlign.BOTH);
- XWPFVertAlign al = cell.getVerticalAlignment();
- assertEquals(XWPFVertAlign.BOTH, al);
- }
-
- public void testSetGetColor() throws Exception {
- // create a table
- XWPFDocument doc = new XWPFDocument();
- CTTbl ctTable = CTTbl.Factory.newInstance();
- XWPFTable table = new XWPFTable(ctTable, doc);
- // table has a single row by default; grab it
- XWPFTableRow tr = table.getRow(0);
+ cell.setVerticalAlignment(XWPFVertAlign.BOTH);\r
+ XWPFVertAlign al = cell.getVerticalAlignment();\r
+ assertEquals(XWPFVertAlign.BOTH, al);\r
+ }\r
+\r
+ public void testSetGetColor() throws Exception {\r
+ // create a table\r
+ XWPFDocument doc = new XWPFDocument();\r
+ CTTbl ctTable = CTTbl.Factory.newInstance();\r
+ XWPFTable table = new XWPFTable(ctTable, doc);\r
+ // table has a single row by default; grab it\r
+ XWPFTableRow tr = table.getRow(0);\r
assertNotNull(tr);
// row has a single cell by default; grab it
XWPFTableCell cell = tr.getCell(0);
- cell.setColor("F0000F");
- String clr = cell.getColor();
- assertEquals("F0000F", clr);
- }
-
- /**
- * ensure that CTHMerge & CTTcBorders go in poi-ooxml.jar
- */
- public void test54099(){
- XWPFDocument doc = new XWPFDocument();
- CTTbl ctTable = CTTbl.Factory.newInstance();
- XWPFTable table = new XWPFTable(ctTable, doc);
+ cell.setColor("F0000F");\r
+ String clr = cell.getColor();\r
+ assertEquals("F0000F", clr);\r
+ }\r
+\r
+ /**\r
+ * ensure that CTHMerge & CTTcBorders go in poi-ooxml.jar\r
+ */\r
+ public void test54099() {\r
+ XWPFDocument doc = new XWPFDocument();\r
+ CTTbl ctTable = CTTbl.Factory.newInstance();\r
+ XWPFTable table = new XWPFTable(ctTable, doc);\r
XWPFTableRow tr = table.getRow(0);
XWPFTableCell cell = tr.getCell(0);
limitations under the License.
==================================================================== */
-package org.apache.poi.xwpf.usermodel;
-
-import junit.framework.TestCase;
-
-import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTRow;
-import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTbl;
-
-public class TestXWPFTableRow extends TestCase {
-
- @Override
- protected void setUp() throws Exception {
- super.setUp();
- }
-
- public void testCreateRow() throws Exception {
- CTRow ctRow = CTRow.Factory.newInstance();
- assertNotNull(ctRow);
- }
-
- @Override
- protected void tearDown() throws Exception {
- super.tearDown();
- }
-
- public void testSetGetCantSplitRow() {
- // create a table
- XWPFDocument doc = new XWPFDocument();
- CTTbl ctTable = CTTbl.Factory.newInstance();
- XWPFTable table = new XWPFTable(ctTable, doc);
- // table has a single row by default; grab it
- XWPFTableRow tr = table.getRow(0);
- assertNotNull(tr);
-
- tr.setCantSplitRow(true);
- boolean isCant = tr.isCantSplitRow();
- assert(isCant);
- }
-
- public void testSetGetRepeatHeader() {
- // create a table
- XWPFDocument doc = new XWPFDocument();
- CTTbl ctTable = CTTbl.Factory.newInstance();
- XWPFTable table = new XWPFTable(ctTable, doc);
- // table has a single row by default; grab it
- XWPFTableRow tr = table.getRow(0);
- assertNotNull(tr);
-
- tr.setRepeatHeader(true);
- boolean isRpt = tr.isRepeatHeader();
- assert(isRpt);
- }
-}
+package org.apache.poi.xwpf.usermodel;\r
+\r
+import junit.framework.TestCase;\r
+import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTRow;\r
+import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTbl;\r
+\r
+public class TestXWPFTableRow extends TestCase {\r
+\r
+ @Override\r
+ protected void setUp() throws Exception {\r
+ super.setUp();\r
+ }\r
+\r
+ public void testCreateRow() throws Exception {\r
+ CTRow ctRow = CTRow.Factory.newInstance();\r
+ assertNotNull(ctRow);\r
+ }\r
+\r
+ @Override\r
+ protected void tearDown() throws Exception {\r
+ super.tearDown();\r
+ }\r
+\r
+ public void testSetGetCantSplitRow() {\r
+ // create a table\r
+ XWPFDocument doc = new XWPFDocument();\r
+ CTTbl ctTable = CTTbl.Factory.newInstance();\r
+ XWPFTable table = new XWPFTable(ctTable, doc);\r
+ // table has a single row by default; grab it\r
+ XWPFTableRow tr = table.getRow(0);\r
+ assertNotNull(tr);\r
+\r
+ tr.setCantSplitRow(true);\r
+ boolean isCant = tr.isCantSplitRow();\r
+ assert (isCant);\r
+ }\r
+\r
+ public void testSetGetRepeatHeader() {\r
+ // create a table\r
+ XWPFDocument doc = new XWPFDocument();\r
+ CTTbl ctTable = CTTbl.Factory.newInstance();\r
+ XWPFTable table = new XWPFTable(ctTable, doc);\r
+ // table has a single row by default; grab it\r
+ XWPFTableRow tr = table.getRow(0);\r
+ assertNotNull(tr);\r
+\r
+ tr.setRepeatHeader(true);\r
+ boolean isRpt = tr.isRepeatHeader();\r
+ assert (isRpt);\r
+ }\r
+}\r