POI-57975: clean up white spaces and other style issues in XWPF

git-svn-id: https://svn.apache.org/repos/asf/poi/trunk@1682473 13f79535-47bb-0310-9956-ffa450edef68
This commit is contained in:
Tim Allison 2015-05-29 14:01:31 +00:00
parent 179e46232b
commit 0a914712bc
84 changed files with 6434 additions and 6255 deletions

View File

@ -32,14 +32,12 @@ import java.util.Map;
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;
import junit.framework.TestCase;
import org.junit.Test;
import org.junit.internal.TextListener;
import org.junit.runner.JUnitCore;import org.junit.runner.Result;
/**
* Build a 'lite' version of the ooxml-schemas.jar

View File

@ -46,46 +46,47 @@ import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTSectPr;
* 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;
}
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;
}
/**
* 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 String getText() {
StringBuffer text = new StringBuffer();
XWPFHeaderFooterPolicy hfPolicy = document.getHeaderFooterPolicy();
@ -94,9 +95,9 @@ public class XWPFWordExtractor extends POIXMLTextExtractor {
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
@ -105,108 +106,108 @@ public class XWPFWordExtractor extends POIXMLTextExtractor {
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();
}
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());
}
}
XWPFHeaderFooterPolicy headerFooterPolicy = null;
public void appendParagraphText(StringBuffer text, XWPFParagraph paragraph) {
try {
CTSectPr ctSectPr = null;
if (paragraph.getCTP().getPPr() != null) {
ctSectPr = paragraph.getCTP().getPPr().getSectPr();
}
if (ctSectPr!=null) {
headerFooterPolicy = new XWPFHeaderFooterPolicy(document, ctSectPr);
extractHeaders(text, headerFooterPolicy);
}
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() + ">");
}
}
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');
}
// 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');
}
// 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);
}
}
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() );
}
}
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());
}
}
}

View File

@ -22,16 +22,15 @@ import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTP;
* 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;
}
}

View File

@ -21,38 +21,36 @@ import org.apache.poi.xwpf.usermodel.XWPFParagraph;
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);
}
private StringBuffer commentText;
@SuppressWarnings("deprecation")
public XWPFCommentsDecorator(XWPFParagraph paragraph, XWPFParagraphDecorator nextDecorator) {
super(paragraph, nextDecorator);
public XWPFCommentsDecorator(XWPFParagraphDecorator nextDecorator) {
this(nextDecorator.paragraph, nextDecorator);
}
XWPFComment comment;
commentText = new StringBuffer();
@SuppressWarnings("deprecation")
public XWPFCommentsDecorator(XWPFParagraph paragraph, XWPFParagraphDecorator nextDecorator) {
super(paragraph, nextDecorator);
for(CTMarkupRange anchor : paragraph.getCTP().getCommentRangeStartArray())
{
if((comment = paragraph.getDocument().getCommentByID(anchor.getId().toString())) != null)
commentText.append("\tComment by " + comment.getAuthor()+": "+comment.getText());
}
}
XWPFComment comment;
commentText = new StringBuffer();
public String getCommentText() {
return commentText.toString();
}
public String getText() {
return super.getText() + commentText;
}
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;
}
}

View File

@ -45,7 +45,6 @@ import org.openxmlformats.schemas.wordprocessingml.x2006.main.FtrDocument;
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;
@ -61,10 +60,10 @@ import schemasMicrosoftComVml.STTrueFalse;
/**
* 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;
@ -84,8 +83,8 @@ public class XWPFHeaderFooterPolicy {
/**
* 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());
@ -93,8 +92,8 @@ public class XWPFHeaderFooterPolicy {
/**
* 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
@ -102,7 +101,7 @@ public class XWPFHeaderFooterPolicy {
// 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());
@ -114,13 +113,12 @@ public class XWPFHeaderFooterPolicy {
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
@ -130,9 +128,9 @@ public class XWPFHeaderFooterPolicy {
}
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;
@ -140,9 +138,9 @@ public class XWPFHeaderFooterPolicy {
}
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;
@ -159,15 +157,15 @@ public class XWPFHeaderFooterPolicy {
/**
* 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);
@ -193,15 +191,15 @@ public class XWPFHeaderFooterPolicy {
/**
* 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);
@ -220,10 +218,10 @@ public class XWPFHeaderFooterPolicy {
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;
@ -231,14 +229,14 @@ public class XWPFHeaderFooterPolicy {
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;
}
@ -246,13 +244,12 @@ public class XWPFHeaderFooterPolicy {
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();
@ -270,21 +267,20 @@ public class XWPFHeaderFooterPolicy {
* 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();
@ -330,60 +326,70 @@ public class XWPFHeaderFooterPolicy {
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;
@ -459,7 +465,7 @@ public class XWPFHeaderFooterPolicy {
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");

View File

@ -23,50 +23,49 @@ import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTR;
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;
}
}

View File

@ -22,22 +22,22 @@ import org.apache.poi.xwpf.usermodel.XWPFParagraph;
* 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();
}
}

View File

@ -19,9 +19,9 @@
-->
<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>

View File

@ -13,102 +13,92 @@
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();
}
}
==================================================================== */
package org.apache.poi.xwpf.usermodel;
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
* <p/>
* WARNING - APIs expected to change rapidly.
* <p/>
* 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();
}
}

View File

@ -21,15 +21,14 @@ package org.apache.poi.xwpf.usermodel;
* <p>
* 9 Jan 2010
* </p>
* <p>
* // TODO insert Javadoc here!
* </p>
* @author epp
*
*/
public enum BodyElementType {
CONTENTCONTROL,
PARAGRAPH,
TABLE,
}
* <p>
* // TODO insert Javadoc here!
* </p>
*
* @author epp
*/
public enum BodyElementType {
CONTENTCONTROL,
PARAGRAPH,
TABLE,
}

View File

@ -29,14 +29,15 @@ import java.util.Map;
* </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
* be used as a border at the page level - the borders under the pgBorders
* element
* </li>
* </ul>
*
* @author Gisella Bronzetti
*/
public enum Borders {
NIL(1),
@ -596,31 +597,32 @@ public enum Borders {
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;
}
}
ZIG_ZAG_STITCH(191);
private static Map<Integer, Borders> imap = new HashMap<Integer, Borders>();
static {
for (Borders p : values()) {
imap.put(Integer.valueOf(p.getValue()), p);
}
}
private final int value;
private Borders(int val) {
value = val;
}
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;
}
public int getValue() {
return value;
}
}

View File

@ -20,23 +20,23 @@ import java.util.HashMap;
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
* determine the next available line when a break's type attribute has a value
* of textWrapping.
*
* @author Gisella Bronzetti
*/
public enum BreakClear {
/**
* 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
* right or the presence of any floating objects which intersect with the
* line,
* <p/>
* This is the setting for a typical line break in a document.
*/
NONE(1),
/**
@ -80,31 +80,32 @@ public enum BreakClear {
* 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;
}
}
*/
ALL(4);
private static Map<Integer, BreakClear> imap = new HashMap<Integer, BreakClear>();
static {
for (BreakClear p : values()) {
imap.put(new Integer(p.getValue()), p);
}
}
private final int value;
private BreakClear(int val) {
value = val;
}
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;
}
public int getValue() {
return value;
}
}

View File

@ -21,18 +21,18 @@ import java.util.Map;
/**
* 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.
* 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.
*/
PAGE(1),
@ -53,31 +53,32 @@ public enum BreakType {
* 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;
}
}
*/
TEXT_WRAPPING(3);
private static Map<Integer, BreakType> imap = new HashMap<Integer, BreakType>();
static {
for (BreakType p : values()) {
imap.put(new Integer(p.getValue()), p);
}
}
private final int value;
private BreakType(int val) {
value = val;
}
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;
}
public int getValue() {
return value;
}
}

View File

@ -14,31 +14,45 @@
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;
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;
/**
* Tag Image File (.tiff)
*/
public static final int PICTURE_TYPE_TIFF = 9;

View File

@ -27,64 +27,68 @@ import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTc;
/**
* <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
* 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 {
/**
* 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
* 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 paragraph that of position pos
@ -94,32 +98,36 @@ public interface IBody {
/**
* 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);
/**
* 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
*/
void insertTable(int pos, XWPFTable table);
/**
* returns the TableCell to which the Table belongs
* @param cell
*/
public XWPFTableCell getTableCell(CTTc cell);
/**
* returns the TableCell to which the Table belongs
*
* @param cell
*/
public XWPFTableCell getTableCell(CTTc cell);
/**
* Return XWPFDocument

View File

@ -18,15 +18,18 @@
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();
}
/**
* 9 Jan 2010
*
* @author Philipp Epp
*/
public interface IBodyElement {
IBody getBody();
POIXMLDocumentPart getPart();
BodyType getPartType();
BodyElementType getElementType();
}

View File

@ -15,13 +15,13 @@
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:
* &lt;tr&gt;&lt;tc/&gt;&lt;tc/&gt;&lt;sdt&gt&lt;tc/&gt;&lt;/sdt&gt;&lt;/tr&gt;
*/
public interface ICell {
}
/**
* Interface for anything that can be at a table cell level:
* {@link XWPFTableCell}, {@link XWPFSDTCell}
* <p/>
* Schematically something like this:
* &lt;tr&gt;&lt;tc/&gt;&lt;tc/&gt;&lt;sdt&gt&lt;tc/&gt;&lt;/sdt&gt;&lt;/tr&gt;
*/
public interface ICell {
}

View File

@ -22,10 +22,11 @@ import org.apache.poi.wp.usermodel.Paragraph;
/**
* 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();
}

View File

@ -20,11 +20,10 @@ import org.apache.poi.wp.usermodel.CharacterRun;
/**
* 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 {
}
public interface IRunElement {}

View File

@ -15,21 +15,20 @@
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();
/**
* Experimental interface to offer rudimentary read-only processing of
* of the contentblock of an SDT/ContentControl.
* <p/>
* <p/>
* <p/>
* WARNING - APIs expected to change rapidly
*/
public interface ISDTContent {
public String getText();
public String toString();
}

View File

@ -18,8 +18,8 @@ package org.apache.poi.xwpf.usermodel;
/**
* 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 {
}

View File

@ -19,13 +19,13 @@ package org.apache.poi.xwpf.usermodel;
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 {
/**
* 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 {
/**
* Specifies that the line spacing of the parent object shall be
@ -45,31 +45,32 @@ public enum LineSpacingRule {
/**
* 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;
}
}
*/
AT_LEAST(3);
private static Map<Integer, LineSpacingRule> imap = new HashMap<Integer, LineSpacingRule>();
static {
for (LineSpacingRule p : values()) {
imap.put(new Integer(p.getValue()), p);
}
}
private final int value;
private LineSpacingRule(int val) {
value = val;
}
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;
}
public int getValue() {
return value;
}
}

View File

@ -37,30 +37,31 @@ public enum ParagraphAlignment {
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),
THAI_DISTRIBUTE(10);
private static Map<Integer, ParagraphAlignment> imap = new HashMap<Integer, ParagraphAlignment>();
static {
for (ParagraphAlignment p : values()) {
imap.put(new Integer(p.getValue()), p);
}
}
private final int value;
private ParagraphAlignment(int val) {
value = val;
}
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;
}
public int getValue() {
return value;
}
}

View File

@ -17,49 +17,47 @@
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;
}
}
/**
* 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;
}
}

View File

@ -38,85 +38,85 @@ import org.openxmlformats.schemas.wordprocessingml.x2006.main.STOnOff;
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);
}
}
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);
}
}

View File

@ -17,25 +17,25 @@
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;
/**
* 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),
/**
* Specifies that all text in the parent object shall be
* aligned to the baseline of each character when displayed.
@ -44,34 +44,35 @@ public enum TextAlignment {
/**
* 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;
}
}
*/
BOTTOM(4),
/**
* Specifies that all text in the parent object shall be
* aligned automatically when displayed.
*/
AUTO(5);
private static Map<Integer, TextAlignment> imap = new HashMap<Integer, TextAlignment>();
static {
for (TextAlignment p : values()) {
imap.put(new Integer(p.getValue()), p);
}
}
private final int value;
private TextAlignment(int val) {
value = val;
}
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;
}
public int getValue() {
return value;
}
}

View File

@ -16,83 +16,84 @@
==================================================================== */
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);
}
}
/**
* 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);
}
}

View File

@ -19,13 +19,13 @@ package org.apache.poi.xwpf.usermodel;
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 {
/**
* 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 {
/**
* Specifies an underline consisting of a single line beneath all characters
@ -132,31 +132,32 @@ public enum UnderlinePatterns {
/**
* 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;
}
}
*/
NONE(18);
private static Map<Integer, UnderlinePatterns> imap = new HashMap<Integer, UnderlinePatterns>();
static {
for (UnderlinePatterns p : values()) {
imap.put(new Integer(p.getValue()), p);
}
}
private final int value;
private UnderlinePatterns(int val) {
value = val;
}
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;
}
public int getValue() {
return value;
}
}

View File

@ -21,13 +21,13 @@ import java.util.Map;
/**
* 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
* be repositioned as subscript or superscript without altering the font size of
* the run properties.
*
* @author Gisella Bronzetti
*/
public enum VerticalAlign {
/**
* Specifies that the text in the parent run shall be located at the
@ -44,31 +44,32 @@ public enum VerticalAlign {
* 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;
}
}
*/
SUBSCRIPT(3);
private static Map<Integer, VerticalAlign> imap = new HashMap<Integer, VerticalAlign>();
static {
for (VerticalAlign p : values()) {
imap.put(new Integer(p.getValue()), p);
}
}
private final int value;
private VerticalAlign(int val) {
value = val;
}
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;
}
public int getValue() {
return value;
}
}

View File

@ -18,42 +18,43 @@
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;
}
}
/**
* @author Philipp Epp
*/
public class XWPFAbstractNum {
protected XWPFNumbering numbering;
private CTAbstractNum ctAbstractNum;
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 void setNumbering(XWPFNumbering numbering) {
this.numbering = numbering;
}
public CTAbstractNum getCTAbstractNum() {
return ctAbstractNum;
}
}

View File

@ -21,42 +21,35 @@ import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTP;
/**
* 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();
}
}

View File

@ -22,21 +22,21 @@ import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTPPr;
/**
* 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();
*/
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();
return -1;
}
}

View File

@ -22,21 +22,21 @@ import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTRPr;
/**
* 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;
*/
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;
return -1;
}
}

View File

@ -28,30 +28,29 @@ import org.apache.poi.openxml4j.opc.PackageRelationship;
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);
}
/**
* @author Yegor Kozlov
*/
public final class XWPFFactory extends POIXMLFactory {
private static final POILogger logger = POILogFactory.getLogger(XWPFFactory.class);
private static final XWPFFactory inst = new XWPFFactory();
private 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);
}
try {
Class<? extends POIXMLDocumentPart> cls = descriptor.getRelationClass();
@ -59,23 +58,23 @@ public final class XWPFFactory extends POIXMLFactory {
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);
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);
}
}
}

View File

@ -53,16 +53,16 @@ public class XWPFFooter extends XWPFHeaderFooter {
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();
}
@ -78,7 +78,7 @@ public class XWPFFooter extends XWPFHeaderFooter {
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");
@ -95,8 +95,8 @@ public class XWPFFooter extends XWPFHeaderFooter {
out.close();
}
@Override
protected void onDocumentRead() throws IOException{
@Override
protected void onDocumentRead() throws IOException {
super.onDocumentRead();
FtrDocument ftrDocument = null;
InputStream is;
@ -111,19 +111,19 @@ public class XWPFFooter extends XWPFHeaderFooter {
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) {
@ -133,6 +133,7 @@ public class XWPFFooter extends XWPFHeaderFooter {
/**
* get the PartType of the body
*
* @see org.apache.poi.xwpf.usermodel.IBody#getPartType()
*/
public BodyType getPartType() {

View File

@ -27,64 +27,64 @@ import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTFtnEdn;
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;
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>();
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;
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();
}
public List<XWPFTable> getTables() {
return tables;
}
@ -95,226 +95,231 @@ public class XWPFFootnote implements Iterable<XWPFParagraph>,IBody {
public List<IBodyElement> getBodyElements() {
return bodyElements;
}
public CTFtnEdn getCTFtnEdn() {
return ctFtnEdn;
}
public void setCTFtnEdn(CTFtnEdn footnote) {
ctFtnEdn = footnote;
}
/**
}
public CTFtnEdn getCTFtnEdn() {
return ctFtnEdn;
}
public void setCTFtnEdn(CTFtnEdn footnote) {
ctFtnEdn = footnote;
}
/**
* @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)
*/
public XWPFTable getTableArray(int pos) {
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
* @see org.apache.poi.xwpf.usermodel.IBody#insertTable(int pos, XWPFTable table)
/**
* 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)
*/
@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);
int i = 0;
for (CTTbl tbl : ctFtnEdn.getTblArray()) {
if (tbl == table.getCTTbl()) {
break;
}
i++;
}
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;
/**
* 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;
}
/**
* 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;
/**
* 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;
}
/**
* 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) {
/**
* 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) {
return paragraphs.get(pos);
}
/**
* get the TableCell which belongs to the TableCell
* @param cell
* @see org.apache.poi.xwpf.usermodel.IBody#getTableCell(CTTc cell)
*/
/**
* get the TableCell which belongs to the TableCell
*
* @param cell
* @see org.apache.poi.xwpf.usermodel.IBody#getTableCell(CTTc cell)
*/
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();
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);
}
/**
* 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);
/**
* 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);
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);
/**
* 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);
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
*/
/**
* add a new table to the end of the footnote
*
* @param table
* @return the added XWPFTable
*/
public XWPFTable addNewTbl(CTTbl table) {
CTTbl newTable = ctFtnEdn.addNewTbl();
newTable.set(table);
@ -322,12 +327,13 @@ public class XWPFFootnote implements Iterable<XWPFParagraph>,IBody {
tables.add(xTable);
return xTable;
}
/**
* add a new paragraph to the end of the footnote
* @param paragraph
* @return the added XWPFParagraph
*/
/**
* add a new paragraph to the end of the footnote
*
* @param paragraph
* @return the added XWPFParagraph
*/
public XWPFParagraph addNewParagraph(CTP paragraph) {
CTP newPara = ctFtnEdn.addNewP();
newPara.set(paragraph);
@ -336,26 +342,28 @@ public class XWPFFootnote implements Iterable<XWPFParagraph>,IBody {
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() {
/**
* @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() {
return footnotes;
}
/**
* get the PartType of the body
* @see org.apache.poi.xwpf.usermodel.IBody#getPartType()
*/
public BodyType getPartType() {
/**
* get the PartType of the body
*
* @see org.apache.poi.xwpf.usermodel.IBody#getPartType()
*/
public BodyType getPartType() {
return BodyType.FOOTNOTE;
}
}

View File

@ -31,32 +31,31 @@ import org.apache.poi.POIXMLDocumentPart;
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;
import org.apache.xmlbeans.XmlException;
import org.apache.xmlbeans.XmlOptions;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTFootnotes;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTFtnEdn;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.FootnotesDocument;
/**
* Looks after the collection of Footnotes for a document
*/
public class XWPFFootnotes extends POIXMLDocumentPart {
protected XWPFDocument document;
private List<XWPFFootnote> listFootnote = new ArrayList<XWPFFootnote>();
private CTFootnotes ctFootnotes;
/**
* 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);
}
/**
* Construct XWPFFootnotes from scratch for a new document.
*/
@ -65,33 +64,33 @@ public class XWPFFootnotes extends POIXMLDocumentPart {
/**
* Read document
*/
@Override
@SuppressWarnings("deprecation")
protected void onDocumentRead () throws IOException {
FootnotesDocument notesDoc;
try {
InputStream is = getPackagePart().getInputStream();
*/
@Override
@SuppressWarnings("deprecation")
protected void onDocumentRead() throws IOException {
FootnotesDocument notesDoc;
try {
InputStream is = getPackagePart().getInputStream();
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));
}
}
}
// Find our footnotes
for (CTFtnEdn note : ctFootnotes.getFootnoteArray()) {
listFootnote.add(new XWPFFootnote(note, this));
}
}
@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 {
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);
PackagePart part = getPackagePart();
OutputStream out = part.getOutputStream();
ctFootnotes.save(out, xmlOptions);
@ -100,59 +99,62 @@ public class XWPFFootnotes extends POIXMLDocumentPart {
public List<XWPFFootnote> getFootnotesList() {
return listFootnote;
}
public XWPFFootnote getFootnoteById(int id) {
for (XWPFFootnote note : listFootnote) {
if (note.getCTFtnEdn().getId().intValue() == id)
return note;
}
return null;
}
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) {
/**
* Sets the ctFootnotes
*
* @param footnotes
*/
public void setFootnotes(CTFootnotes footnotes) {
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);
/**
* 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);
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;
}
/**
* @see org.apache.poi.xwpf.usermodel.IBody#getPart()
*/
public XWPFDocument getXWPFDocument() {
if (document != null) {
return document;
} else {
return (XWPFDocument) getParent();
}
}
public void setXWPFDocument(XWPFDocument doc) {
document = doc;
}
}

View File

@ -69,14 +69,14 @@ public class XWPFHeader extends XWPFHeaderFooter {
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");
@ -95,11 +95,12 @@ public class XWPFHeader extends XWPFHeaderFooter {
/**
* reads the document
* @throws IOException
*
* @throws IOException
*/
@Override
@Override
protected void onDocumentRead() throws IOException {
super.onDocumentRead();
super.onDocumentRead();
HdrDocument hdrDocument = null;
InputStream is;
try {
@ -113,17 +114,17 @@ public class XWPFHeader extends XWPFHeaderFooter {
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);
}
}
@ -135,6 +136,7 @@ public class XWPFHeader extends XWPFHeaderFooter {
/**
* get the PartType of the body
*
* @see org.apache.poi.xwpf.usermodel.IBody#getPartType()
*/
public BodyType getPartType() {

View File

@ -46,7 +46,7 @@ import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTc;
*/
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);
@ -54,7 +54,7 @@ public abstract class XWPFHeaderFooter extends POIXMLDocumentPart implements IBo
XWPFDocument document;
XWPFHeaderFooter(XWPFDocument doc, CTHdrFtr hdrFtr) {
if (doc==null) {
if (doc == null) {
throw new NullPointerException();
}
@ -70,17 +70,17 @@ public abstract class XWPFHeaderFooter extends POIXMLDocumentPart implements IBo
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);
@ -93,16 +93,16 @@ public abstract class XWPFHeaderFooter extends POIXMLDocumentPart implements IBo
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);
@ -111,29 +111,28 @@ public abstract class XWPFHeaderFooter extends POIXMLDocumentPart implements IBo
/**
* 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');
}
@ -141,26 +140,26 @@ public abstract class XWPFHeaderFooter extends POIXMLDocumentPart implements IBo
}
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();
}
@ -168,14 +167,15 @@ public abstract class XWPFHeaderFooter extends POIXMLDocumentPart implements IBo
/**
* 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;
@ -184,14 +184,15 @@ public abstract class XWPFHeaderFooter extends POIXMLDocumentPart implements IBo
/**
* 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;
@ -200,7 +201,7 @@ public abstract class XWPFHeaderFooter extends POIXMLDocumentPart implements IBo
/**
* Returns the paragraph that holds
* the text of the header or footer.
* the text of the header or footer.
*/
public XWPFParagraph getParagraphArray(int pos) {
@ -209,9 +210,10 @@ public abstract class XWPFHeaderFooter extends POIXMLDocumentPart implements IBo
/**
* 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;
}
@ -221,9 +223,10 @@ public abstract class XWPFHeaderFooter extends POIXMLDocumentPart implements IBo
/**
* get all Pictures in this package
*
* @return all Pictures in this package
*/
public List<XWPFPictureData> getAllPackagePictures(){
public List<XWPFPictureData> getAllPackagePictures() {
return document.getAllPackagePictures();
}
@ -231,22 +234,19 @@ public abstract class XWPFHeaderFooter extends POIXMLDocumentPart implements IBo
/**
* 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;
@ -266,9 +266,7 @@ public abstract class XWPFHeaderFooter extends POIXMLDocumentPart implements IBo
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
@ -279,14 +277,12 @@ public abstract class XWPFHeaderFooter extends POIXMLDocumentPart implements IBo
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);
}
@ -295,61 +291,61 @@ public abstract class XWPFHeaderFooter extends POIXMLDocumentPart implements IBo
/**
* 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);
@ -362,35 +358,33 @@ public abstract class XWPFHeaderFooter extends POIXMLDocumentPart implements IBo
/**
*
* @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);
@ -403,29 +397,31 @@ public abstract class XWPFHeaderFooter extends POIXMLDocumentPart implements IBo
/**
* 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;
@ -433,6 +429,7 @@ public abstract class XWPFHeaderFooter extends POIXMLDocumentPart implements IBo
/**
* inserts an existing XWPFTable to the arrays bodyElements and tables
*
* @param pos
* @param table
*/
@ -441,7 +438,7 @@ public abstract class XWPFHeaderFooter extends POIXMLDocumentPart implements IBo
bodyElements.add(pos, table);
int i = 0;
for (CTTbl tbl : headerFooter.getTblArray()) {
if(tbl == table.getCTTbl()){
if (tbl == table.getCTTbl()) {
break;
}
i++;
@ -450,10 +447,10 @@ public abstract class XWPFHeaderFooter extends POIXMLDocumentPart implements IBo
}
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();
@ -461,12 +458,12 @@ public abstract class XWPFHeaderFooter extends POIXMLDocumentPart implements IBo
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);
}
@ -476,48 +473,50 @@ public abstract class XWPFHeaderFooter extends POIXMLDocumentPart implements IBo
/**
* 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 XWPFDocument getXWPFDocument() {
if (document != null) {
return document;
} else {
return (XWPFDocument) getParent();
}
}
public void setXWPFDocument(XWPFDocument doc) {
document = doc;
}
public XWPFDocument getXWPFDocument() {
if (document!=null) {
return document;
} else {
return (XWPFDocument)getParent();
}
}
/**
* 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() {

View File

@ -18,26 +18,22 @@ package org.apache.poi.xwpf.usermodel;
/**
* 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;
}
}

View File

@ -20,45 +20,45 @@ import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTHyperlink;
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.
* 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);
}
}

View File

@ -17,38 +17,38 @@
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;
public class XWPFLatentStyles {
protected XWPFStyles styles; //LatentStyle shall know styles
private CTLatentStyles latentStyles;
protected XWPFLatentStyles() {
}
protected XWPFLatentStyles(CTLatentStyles latentStyles) {
this(latentStyles, null);
}
protected XWPFLatentStyles(CTLatentStyles latentStyles, XWPFStyles styles) {
this.latentStyles = latentStyles;
this.styles = styles;
}
public int getNumberOfStyles() {
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
*/
@SuppressWarnings("deprecation")
protected boolean isLatentStyle(String latentStyleID) {
for (CTLsdException lsd : latentStyles.getLsdExceptionArray()) {
if (lsd.getName().equals(latentStyleID)) {
return true;
}
}
return false;
}
}

View File

@ -18,48 +18,47 @@ package org.apache.poi.xwpf.usermodel;
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;
}
/**
* @author Philipp Epp
*/
public class XWPFNum {
protected XWPFNumbering numbering;
private CTNum ctNum;
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 void setNumbering(XWPFNumbering numbering) {
this.numbering = numbering;
}
public CTNum getCTNum() {
return ctNum;
}
public void setCTNum(CTNum ctNum) {
this.ctNum = ctNum;
}
}

View File

@ -38,71 +38,69 @@ import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTAbstractNum;
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");
/**
* @author Philipp Epp
*/
public class XWPFNumbering extends POIXMLDocumentPart {
protected List<XWPFAbstractNum> abstractNums = new ArrayList<XWPFAbstractNum>();
protected List<XWPFNum> nums = new ArrayList<XWPFNum>();
boolean isNew;
private CTNumbering ctNumbering;
/**
* 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");
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");
@ -114,169 +112,182 @@ public class XWPFNumbering extends POIXMLDocumentPart {
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();
}
}
}
/**
* 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();
}
}

View File

@ -28,51 +28,51 @@ import org.openxmlformats.schemas.drawingml.x2006.picture.CTPicture;
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;
private XWPFRun run;
public XWPFPicture(CTPicture ctPic, XWPFRun run) {
this.run = run;
this.ctPic = ctPic;
description = ctPic.getNvPicPr().getCNvPr().getDescr();
}
/**
* Link Picture with PictureData
* @param rel
*/
public void setPictureReference(PackageRelationship rel){
ctPic.getBlipFill().getBlip().setEmbed(rel.getId());
}
/**
* Link Picture with PictureData
*
* @param rel
*/
public void setPictureReference(PackageRelationship rel) {
ctPic.getBlipFill().getBlip().setEmbed(rel.getId());
}
/**
* Return the underlying CTPicture bean that holds all properties for this picture
*
* @return the underlying CTPicture bean
*/
public CTPicture getCTPicture(){
return ctPic;
}
*
* @return the underlying CTPicture bean
*/
public CTPicture getCTPicture() {
return ctPic;
}
/**
* 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.
* 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;
}
}
return null;

View File

@ -40,12 +40,13 @@ import org.apache.poi.util.IOUtils;
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
*/
protected static final POIXMLRelation[] RELATIONS;
static {
RELATIONS = new POIXMLRelation[13];
RELATIONS[Document.PICTURE_TYPE_EMF] = XWPFRelation.IMAGE_EMF;
RELATIONS[Document.PICTURE_TYPE_WMF] = XWPFRelation.IMAGE_WMF;
RELATIONS[Document.PICTURE_TYPE_PICT] = XWPFRelation.IMAGE_PICT;
RELATIONS[Document.PICTURE_TYPE_JPEG] = XWPFRelation.IMAGE_JPEG;
@ -59,24 +60,23 @@ public class XWPFPictureData extends POIXMLDocumentPart {
}
private Long checksum = null;
/**
* Create a new XWPFGraphicData node
*
*/
protected XWPFPictureData() {
super();
/**
* Create a new XWPFGraphicData node
*/
protected XWPFPictureData() {
super();
}
/**
* 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);
*
* @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);
}
@Override
@ -91,12 +91,13 @@ public class XWPFPictureData extends POIXMLDocumentPart {
* 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();
* </code>
* </p>
*
* @return the Picture data.
*/
public byte[] getData() {
try {
return IOUtils.toByteArray(getPackagePart().getInputStream());
} catch (IOException e) {
@ -115,21 +116,22 @@ public class XWPFPictureData extends POIXMLDocumentPart {
return null;
return name.substring(name.lastIndexOf('/') + 1);
}
/**
* Suggests a file extension for this image.
* @return the file extension.
*/
public String suggestFileExtension() {
/**
* Suggests a file extension for this image.
*
* @return the file extension.
*/
public String suggestFileExtension() {
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
/**
* 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
* @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
@ -217,13 +219,13 @@ public class XWPFPictureData extends POIXMLDocumentPart {
if (!ownPackage.equals(foreignPackage)) {
return false;
}
}
}
Long foreignChecksum = picData.getChecksum();
Long localChecksum = getChecksum();
}
}
}
Long foreignChecksum = picData.getChecksum();
Long localChecksum = getChecksum();
if (!(localChecksum.equals(foreignChecksum))) {
return false;
}
@ -233,13 +235,13 @@ public class XWPFPictureData extends POIXMLDocumentPart {
@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
}
/**
* *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
protected void prepareForCommit() {
// do not clear the part here
}

View File

@ -33,7 +33,6 @@ public final class XWPFRelation extends POIXMLRelation {
*/
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",
@ -41,10 +40,10 @@ public final class XWPFRelation extends POIXMLRelation {
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",
@ -64,12 +63,11 @@ public final class XWPFRelation extends POIXMLRelation {
"/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",
@ -126,10 +124,10 @@ public final class XWPFRelation extends POIXMLRelation {
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,
@ -137,52 +135,51 @@ public final class XWPFRelation extends POIXMLRelation {
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",
@ -207,14 +204,12 @@ public final class XWPFRelation extends POIXMLRelation {
"/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);

File diff suppressed because it is too large Load Diff

View File

@ -17,31 +17,30 @@
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;
/**
* Experimental class to offer rudimentary read-only processing of
* of StructuredDocumentTags/ContentControl
* <p/>
* 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;
}
}

View File

@ -16,29 +16,28 @@
==================================================================== */
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;
/**
* 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.
* <p/>
* 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;
}
}

View File

@ -16,93 +16,91 @@
==================================================================== */
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;
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.
* <p/>
* <p/>
* <p/>
* WARNING - APIs expected to change rapidly
*/
public class XWPFSDTContent implements ISDTContent {
// 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>();
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()) {
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);
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) {
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");
}
}
}
}
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");
}
}
return text.toString();
}
@ -110,28 +108,28 @@ public class XWPFSDTContent implements ISDTContent {
//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++) {
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();
}
}

View File

@ -18,54 +18,52 @@ package org.apache.poi.xwpf.usermodel;
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 {
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.
* <p/>
* WARNING - APIs expected to change rapidly
*/
public class XWPFSDTContentCell implements ISDTContent {
//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 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();
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
//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
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;
while (cursor.hasNextToken() && depth > 0) {
TokenType t = cursor.toNextToken();
if (t.isText()) {
sb.append(cursor.getTextValue());
} else if (isStartToken(cursor, "tr")) {
tcCnt = 0;
iBodyCnt = 0;
} else if (isStartToken(cursor, "tc")) {
if (tcCnt++ > 0) {
@ -77,38 +75,37 @@ public class XWPFSDTContentCell implements ISDTContent {
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();
}
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();
if (qName != null && qName.getLocalPart() != null &&
qName.getLocalPart().equals(string)) {
return true;
}
return false;
}
public String getText(){
return text;
}
public String toString(){
return getText();
}
}
public String getText() {
return text;
}
public String toString() {
return getText();
}
}

View File

@ -59,8 +59,7 @@ public class XWPFSettings extends POIXMLDocumentPart {
}
@Override
protected void onDocumentRead() throws IOException
{
protected void onDocumentRead() throws IOException {
super.onDocumentRead();
readFrom(getPackagePart().getInputStream());
}
@ -74,17 +73,18 @@ public class XWPFSettings extends POIXMLDocumentPart {
* <pre>
* &lt;w:zoom w:percent="50" /&gt;
* <pre>
*
* @return percentage as an integer of zoom level
*/
public long getZoomPercent() {
CTZoom zoom;
if (!ctSettings.isSetZoom()) {
zoom = ctSettings.addNewZoom();
} else {
zoom = ctSettings.getZoom();
}
CTZoom zoom;
if (!ctSettings.isSetZoom()) {
zoom = ctSettings.addNewZoom();
} else {
zoom = ctSettings.getZoom();
}
return zoom.getPercent().longValue();
return zoom.getPercent().longValue();
}
/**
@ -92,31 +92,31 @@ public class XWPFSettings extends POIXMLDocumentPart {
* 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>
* &lt;w:zoom w:percent="50" /&gt;
* &lt;w:zoom w:percent="50" /&gt;
* <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>
* &lt;w:settings ... &gt;
* &lt;w:documentProtection w:edit=&quot;readOnly&quot; w:enforcement=&quot;1&quot;/&gt;
* </pre>
*
*
* @return true if documentProtection is enforced with option readOnly
*/
public boolean isEnforcedWith(STDocProtect.Enum editValue) {
@ -152,23 +152,23 @@ public class XWPFSettings extends POIXMLDocumentPart {
* <br/>
* sample snippet from settings.xml
* <pre>
* &lt;w:documentProtection w:edit=&quot;[passed editValue]&quot; w:enforcement=&quot;1&quot;
* &lt;w:documentProtection w:edit=&quot;[passed editValue]&quot; w:enforcement=&quot;1&quot;
* w:cryptProviderType=&quot;rsaAES&quot; w:cryptAlgorithmClass=&quot;hash&quot;
* w:cryptAlgorithmType=&quot;typeAny&quot; w:cryptAlgorithmSid=&quot;14&quot;
* w:cryptSpinCount=&quot;100000&quot; w:hash=&quot;...&quot; w:salt=&quot;....&quot;
* /&gt;
* </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();
@ -177,23 +177,23 @@ public class XWPFSettings extends POIXMLDocumentPart {
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();
}
@ -201,47 +201,47 @@ public class XWPFSettings extends POIXMLDocumentPart {
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);
@ -257,7 +257,7 @@ public class XWPFSettings extends POIXMLDocumentPart {
safeGetDocumentProtection().setCryptAlgorithmClass(STAlgClass.HASH);
safeGetDocumentProtection().setCryptProviderType(providerType);
safeGetDocumentProtection().setCryptAlgorithmSid(BigInteger.valueOf(sid));
}
}
}
/**
@ -271,30 +271,45 @@ public class XWPFSettings extends POIXMLDocumentPart {
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/>
@ -308,18 +323,18 @@ public class XWPFSettings extends POIXMLDocumentPart {
* 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() {
@ -328,7 +343,7 @@ public class XWPFSettings extends POIXMLDocumentPart {
/**
* Check if revision tracking is turned on.
*
*
* @return <code>true</code> if revision tracking is turned on
*/
public boolean isTrackRevisions() {
@ -337,16 +352,16 @@ public class XWPFSettings extends POIXMLDocumentPart {
/**
* 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();
}
}
@ -355,7 +370,7 @@ public class XWPFSettings extends POIXMLDocumentPart {
@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);

View File

@ -19,128 +19,141 @@ package org.apache.poi.xwpf.usermodel;
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
/**
* @author Philipp Epp
*/
public class XWPFStyle {
protected XWPFStyles styles;
private CTStyle ctStyle;
/**
* 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();
}
/**
* set styleID
*
* @param styleId
*/
public void setStyleId(String styleId) {
ctStyle.setStyleId(styleId);
}
/**
* get Type of the Style
*
* @return ctType
*/
public STStyleType.Enum getType() {
return ctStyle.getType();
}
/**
* set styleType
*
* @param type
*/
public void setType(STStyleType.Enum type) {
ctStyle.setType(type);
}
/**
* set style
*
* @param style
*/
public void setStyle(CTStyle style) {
this.ctStyle = style;
}
/**
* get ctStyle
*
* @return ctStyle
*/
public CTStyle getCTStyle() {
return this.ctStyle;
}
/**
* 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

View File

@ -31,42 +31,43 @@ import org.apache.poi.POIXMLDocumentPart;
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;
import org.apache.xmlbeans.XmlException;
import org.apache.xmlbeans.XmlOptions;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTDocDefaults;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTFonts;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTLanguage;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTPPrDefault;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTRPr;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTRPrDefault;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTStyle;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTStyles;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.StylesDocument;
/**
* 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;
/**
* 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,
* @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);
}
/**
* Construct XWPFStyles from scratch for a new document.
*/
@ -74,13 +75,13 @@ public class XWPFStyles extends POIXMLDocumentPart{
}
/**
* Read document
*/
@Override
protected void onDocumentRead() throws IOException{
StylesDocument stylesDoc;
try {
InputStream is = getPackagePart().getInputStream();
* Read document
*/
@Override
protected void onDocumentRead() throws IOException {
StylesDocument stylesDoc;
try {
InputStream is = getPackagePart().getInputStream();
stylesDoc = StylesDocument.Factory.parse(is);
setStyles(stylesDoc.getStyles());
latentStyles = new XWPFLatentStyles(ctStyles.getLatentStyles(), this);
@ -94,52 +95,53 @@ public class XWPFStyles extends POIXMLDocumentPart{
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);
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);
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")
}
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")
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;
// Build up all the style objects
for (CTStyle style : ctStyles.getStyleArray()) {
listStyle.add(new XWPFStyle(style, this));
}
if (ctStyles.isSetDocDefaults()) {
CTDocDefaults docDefaults = ctStyles.getDocDefaults();
if (docDefaults.isSetRPrDefault() && docDefaults.getRPrDefault().isSetRPr()) {
defaultRunStyle = new XWPFDefaultRunStyle(
@ -151,142 +153,152 @@ public class XWPFStyles extends POIXMLDocumentPart{
}
}
}
/**
* 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) {
/**
* 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) {
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);
lang.setBidi(strSpellingLanguage);
}
/**
* Sets the default East Asia spelling language on ctStyles DocDefaults parameter
*
* @param strEastAsia
*/
public void setEastAsia(String strEastAsia) {
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);
}
/**
* 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);
}
/**
* 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
* 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 default style which applies text runs in the document

View File

@ -44,19 +44,10 @@ import org.openxmlformats.schemas.wordprocessingml.x2006.main.STTblWidth;
* 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);
@ -77,9 +68,17 @@ public class XWPFTable implements IBodyElement, ISDTContents {
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);
@ -94,7 +93,7 @@ public class XWPFTable implements IBodyElement, ISDTContents {
}
@SuppressWarnings("deprecation")
public XWPFTable(CTTbl table, IBody part){
public XWPFTable(CTTbl table, IBody part) {
this.part = part;
this.ctTbl = table;
@ -163,9 +162,9 @@ public class XWPFTable implements IBodyElement, ISDTContents {
* 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
*/
@ -216,6 +215,13 @@ public class XWPFTable implements IBodyElement, ISDTContents {
return null;
}
/**
* @return width value
*/
public int getWidth() {
CTTblPr tblPr = getTrPr();
return tblPr.isSetTblW() ? tblPr.getTblW().getW().intValue() : -1;
}
/**
* @param width
@ -226,14 +232,6 @@ public class XWPFTable implements IBodyElement, ISDTContents {
tblWidth.setW(new BigInteger("" + width));
}
/**
* @return width value
*/
public int getWidth() {
CTTblPr tblPr = getTrPr();
return tblPr.isSetTblW() ? tblPr.getTblW().getW().intValue() : -1;
}
/**
* @return number of rows in table
*/
@ -253,12 +251,13 @@ public class XWPFTable implements IBodyElement, ISDTContents {
}
}
}
/**
* 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) {
@ -273,6 +272,7 @@ public class XWPFTable implements IBodyElement, ISDTContents {
/**
* 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) {
@ -523,24 +523,25 @@ public class XWPFTable implements IBodyElement, ISDTContents {
/**
* 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;
}
@ -548,12 +549,13 @@ public class XWPFTable implements IBodyElement, ISDTContents {
}
/**
* 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);
@ -562,10 +564,10 @@ public class XWPFTable implements IBodyElement, ISDTContents {
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()) {
@ -582,9 +584,9 @@ public class XWPFTable implements IBodyElement, ISDTContents {
return tableRows;
}
/**
* returns the type of the BodyElement Table
*
* @see org.apache.poi.xwpf.usermodel.IBodyElement#getElementType()
*/
public BodyElementType getElementType() {
@ -597,10 +599,11 @@ public class XWPFTable implements IBodyElement, ISDTContents {
/**
* 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;
@ -608,6 +611,7 @@ public class XWPFTable implements IBodyElement, ISDTContents {
/**
* returns the partType of the bodyPart which owns the bodyElement
*
* @see org.apache.poi.xwpf.usermodel.IBody#getPartType()
*/
public BodyType getPartType() {
@ -619,9 +623,14 @@ public class XWPFTable implements IBodyElement, ISDTContents {
* 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
}
}

View File

@ -37,23 +37,15 @@ import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTcPr;
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;
/**
* 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 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;
static {
// populate enum maps
@ -68,337 +60,343 @@ public class XWPFTableCell implements IBody, ICell {
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
*/
}
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;
/**
* If a table cell does not include at least one block-level element, then this document shall be considered corrupt
*/
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;
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>();
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();
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;
}
@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);
}
public void setParagraph(XWPFParagraph p) {
if (ctTc.sizeOfPArray() == 0) {
ctTc.addNewP();
/**
* returns an Iterator with paragraphs and tables
*
* @see org.apache.poi.xwpf.usermodel.IBody#getBodyElements()
*/
public List<IBodyElement> getBodyElements() {
return Collections.unmodifiableList(bodyElements);
}
public void setParagraph(XWPFParagraph p) {
if (ctTc.sizeOfPArray() == 0) {
ctTc.addNewP();
}
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")
/**
* 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 XWPFTableRow getTableRow() {
return tableRow;
}
/**
* 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 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 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;
}
/**
* 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));
}
/**
* 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")
public void insertTable(int pos, XWPFTable table) {
bodyElements.add(pos, table);
int i = 0;
@ -408,90 +406,101 @@ public class XWPFTableCell implements IBody, ICell {
}
i++;
}
tables.add(i, table);
}
public String getText(){
StringBuffer text = new StringBuffer();
for (XWPFParagraph p : paragraphs) {
text.append(p.getText());
}
return text.toString();
tables.add(i, table);
}
public String getText() {
StringBuffer text = new StringBuffer();
for (XWPFParagraph p : paragraphs) {
text.append(p.getText());
}
return text.toString();
}
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);
}
/**
* 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');
}
}
}
/**
* 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');
}
}
}
/**
* 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
*/
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();
}
// Create a map from this XWPF-level enum to the STVerticalJc.Enum values
public static enum XWPFVertAlign {
TOP, CENTER, BOTH, BOTTOM
}
}

View File

@ -31,14 +31,14 @@ import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTc;
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;
/**
* 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;
private XWPFTable table;
private List<XWPFTableCell> tableCells;
@ -52,187 +52,195 @@ public class XWPFTableRow {
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;
}
/**
/**
* 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;
}
/**
* 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
* of an hRule value of auto).
*
* @return height
*/
public int getHeight() {
CTTrPr properties = getTrPr();
return properties.sizeOfTrHeightArray() == 0 ? 0 : properties.getTrHeightArray(0).getVal().intValue();
}
/**
* 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
* 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));
}
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
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;
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;
}
/**
/**
* 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;
}
/**
* 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
*/
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;
}
/**
* 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 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 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;
}
/**
* 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);
}
}

View File

@ -33,24 +33,24 @@ import org.junit.runners.Suite;
/**
* 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 {
*/
@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 {
}

View File

@ -17,13 +17,12 @@
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;
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 org.openxmlformats.schemas.officeDocument.x2006.extendedProperties.CTDigSigBlob;
import org.openxmlformats.schemas.officeDocument.x2006.extendedProperties.CTProperties;
import org.openxmlformats.schemas.officeDocument.x2006.extendedProperties.CTVectorLpstr;
@ -31,77 +30,76 @@ import org.openxmlformats.schemas.officeDocument.x2006.extendedProperties.CTVect
/**
* 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
* {@link PackageProperties#getKeywordsProperty()} had been present before, the
* {@link CoreProperties#getKeywords()} had been missing.
* <p/>
* 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});
}
}

View File

@ -17,36 +17,34 @@
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;
import junit.framework.TestCase;
import org.apache.poi.POIXMLProperties.CoreProperties;
import org.apache.poi.openxml4j.opc.PackageProperties;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
/**
* 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
* {@link PackageProperties#getKeywordsProperty()} had been present before, the
* {@link CoreProperties#getKeywords()} had been missing.
* <p/>
* 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);
}
}

View File

@ -40,7 +40,7 @@ import org.junit.Test;
public class TestXWPFBugs {
/**
* A word document that's encrypted with non-standard
* Encryption options, and no cspname section. See bug 53475
* Encryption options, and no cspname section. See bug 53475
*/
@Test
public void bug53475NoCSPName() throws Exception {
@ -54,7 +54,7 @@ public class TestXWPFBugs {
assertEquals(HashAlgorithm.sha1, info.getHeader().getHashAlgorithmEx());
// Check it can be decoded
Decryptor d = Decryptor.getInstance(info);
Decryptor d = Decryptor.getInstance(info);
assertTrue("Unable to process: document is encrypted", d.verifyPassword("solrcell"));
// Check we can read the word document in that
@ -66,7 +66,7 @@ public class TestXWPFBugs {
assertNotNull(text);
assertEquals("This is password protected Word document.", text.trim());
ex.close();
filesystem.close();
}
@ -90,7 +90,7 @@ public class TestXWPFBugs {
assertEquals(HashAlgorithm.sha1, info.getHeader().getHashAlgorithmEx());
// Check it can be decoded
Decryptor d = Decryptor.getInstance(info);
Decryptor d = Decryptor.getInstance(info);
assertTrue("Unable to process: document is encrypted", d.verifyPassword("pass"));
// Check we can read the word document in that
@ -103,7 +103,7 @@ public class TestXWPFBugs {
// I know ... a stupid typo, maybe next time ...
assertEquals("The is a password protected document.", text.trim());
ex.close();
filesystem.close();
}
}

View File

@ -20,7 +20,6 @@ package org.apache.poi.xwpf.extractor;
import java.io.IOException;
import junit.framework.TestCase;
import org.apache.poi.xwpf.XWPFTestDataSamples;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
@ -28,19 +27,20 @@ public class TestExternalEntities extends TestCase {
/**
* 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();
}

View File

@ -22,7 +22,6 @@ import java.util.regex.Matcher;
import java.util.regex.Pattern;
import junit.framework.TestCase;
import org.apache.poi.xwpf.XWPFTestDataSamples;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
@ -33,7 +32,8 @@ public class TestXWPFWordExtractor extends TestCase {
/**
* Get text out of the simple file
* @throws IOException
*
* @throws IOException
*/
public void testGetSimpleText() throws IOException {
XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("sample.docx");
@ -59,13 +59,14 @@ public class TestXWPFWordExtractor extends TestCase {
}
}
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");
@ -97,7 +98,7 @@ public class TestXWPFWordExtractor extends TestCase {
}
}
assertEquals(134, ps);
extractor.close();
}
@ -108,23 +109,23 @@ public class TestXWPFWordExtractor extends TestCase {
// 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();
}
@ -173,7 +174,7 @@ public class TestXWPFWordExtractor extends TestCase {
"Footer Left\tFooter Middle\tFooter Right\n",
extractor.getText()
);
extractor.close();
}
@ -183,7 +184,7 @@ public class TestXWPFWordExtractor extends TestCase {
String text = extractor.getText();
assertTrue(text.contains("snoska"));
assertTrue(text.contains("Eto ochen prostoy[footnoteRef:1] text so snoskoy"));
extractor.close();
}
@ -193,7 +194,7 @@ public class TestXWPFWordExtractor extends TestCase {
XWPFWordExtractor extractor = new XWPFWordExtractor(doc);
assertTrue(extractor.getText().contains("snoska"));
extractor.close();
}
@ -204,7 +205,7 @@ public class TestXWPFWordExtractor extends TestCase {
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();
}
@ -214,7 +215,7 @@ public class TestXWPFWordExtractor extends TestCase {
String text = extractor.getText();
assertTrue(text.contains("XXX"));
assertTrue(text.contains("tilaka [endnoteRef:2]or 'tika'"));
extractor.close();
}
@ -224,7 +225,7 @@ public class TestXWPFWordExtractor extends TestCase {
assertTrue(extractor.getText().contains("pendant worn"));
assertTrue(extractor.getText().contains("extremely well"));
extractor.close();
}
@ -235,14 +236,15 @@ public class TestXWPFWordExtractor extends TestCase {
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");
@ -251,35 +253,37 @@ public class TestXWPFWordExtractor extends TestCase {
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");
@ -288,14 +292,15 @@ public class TestXWPFWordExtractor extends TestCase {
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");
@ -303,7 +308,7 @@ public class TestXWPFWordExtractor extends TestCase {
String text = extractor.getText();
assertTrue(text.length() > 0);
assertTrue(text.contains("FldSimple.docx"));
extractor.close();
}
@ -316,12 +321,13 @@ public class TestXWPFWordExtractor extends TestCase {
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 {
@ -345,19 +351,19 @@ public class TestXWPFWordExtractor extends TestCase {
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",
@ -366,48 +372,50 @@ public class TestXWPFWordExtractor extends TestCase {
};
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();
}
}

View File

@ -17,86 +17,85 @@
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;
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 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
*/
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);
}
}

View File

@ -20,7 +20,6 @@ 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;
@ -28,130 +27,130 @@ 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;
private XWPFDocument noHeader;
private XWPFDocument header;
private XWPFDocument headerFooter;
private XWPFDocument footer;
private XWPFDocument oddEven;
private XWPFDocument diffFirst;
protected void setUp() throws IOException {
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");
}
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;
public void testPolicy() {
XWPFHeaderFooterPolicy policy;
policy = noHeader.getHeaderFooterPolicy();
assertNull(policy.getDefaultHeader());
assertNull(policy.getDefaultFooter());
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));
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());
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));
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());
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));
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());
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));
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());
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));
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());
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));
}
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;
public void testContents() {
XWPFHeaderFooterPolicy policy;
// Test a few simple bits off a simple header
policy = diffFirst.getHeaderFooterPolicy();
// 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()
);
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();
// 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()
);
}
assertEquals(
"[ODD Page Header text]\n\n",
policy.getDefaultHeader().getText()
);
assertEquals(
"[This is an Even Page, with a Header]\n\n",
policy.getEvenPageHeader().getText()
);
}
}

View File

@ -44,7 +44,7 @@ public class TestChangeTracking {
assertFalse(document.isTrackRevisions());
document.setTrackRevisions(true);
assertTrue(document.isTrackRevisions());
}

View File

@ -19,11 +19,9 @@ package org.apache.poi.xwpf.usermodel;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import java.io.FileInputStream;
import java.io.IOException;
import org.apache.poi.openxml4j.exceptions.OpenXML4JException;
import org.apache.poi.openxml4j.opc.OPCPackage;
import org.apache.poi.xwpf.XWPFTestDataSamples;
import org.apache.poi.xwpf.usermodel.XWPFRun.FontCharRange;
import org.junit.Test;
@ -32,14 +30,14 @@ public class TestXWPFBugs {
@Test
public void bug55802() throws Exception {
String blabla =
"Bir, iki, \u00fc\u00e7, d\u00f6rt, be\u015f,\n"+
"\nalt\u0131, yedi, sekiz, dokuz, on.\n"+
"\nK\u0131rm\u0131z\u0131 don,\n"+
"\ngel bizim bah\u00e7eye kon,\n"+
"\nsar\u0131 limon";
"Bir, iki, \u00fc\u00e7, d\u00f6rt, be\u015f,\n" +
"\nalt\u0131, yedi, sekiz, dokuz, on.\n" +
"\nK\u0131rm\u0131z\u0131 don,\n" +
"\ngel bizim bah\u00e7eye kon,\n" +
"\nsar\u0131 limon";
XWPFDocument doc = new XWPFDocument();
XWPFRun run = doc.createParagraph().createRun();
for (String str : blabla.split("\n")) {
run.setText(str);
run.addBreak();
@ -55,40 +53,40 @@ public class TestXWPFBugs {
assertEquals(run.getFontFamily(FontCharRange.hAnsi), "Arial");
}
@Test
public void bug57312_NullPointException() throws IOException {
XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("57312.docx");
assertNotNull(doc);
for( IBodyElement bodyElement : doc.getBodyElements()){
for (IBodyElement bodyElement : doc.getBodyElements()) {
BodyElementType elementType = bodyElement.getElementType();
if(elementType == BodyElementType.PARAGRAPH) {
if (elementType == BodyElementType.PARAGRAPH) {
XWPFParagraph paragraph = (XWPFParagraph) bodyElement;
for (IRunElement iRunElem : paragraph.getIRuns()){
if (iRunElem instanceof XWPFRun){
for (IRunElement iRunElem : paragraph.getIRuns()) {
if (iRunElem instanceof XWPFRun) {
XWPFRun runElement = (XWPFRun) iRunElem;
UnderlinePatterns underline = runElement.getUnderline();
assertNotNull(underline);
//System.out.println("Found: " + underline + ": " + runElement.getText(0));
}
}
}
}
}
}
@Test
public void test56392() throws IOException, OpenXML4JException {
XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("56392.docx");
assertNotNull(doc);
assertNotNull(doc);
}
/**
* Removing a run needs to remove it from both Runs and IRuns
*/
@ -97,7 +95,7 @@ public class TestXWPFBugs {
XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("sample.docx");
assertNotNull(doc);
assertEquals(3, doc.getParagraphs().size());
for (XWPFParagraph paragraph : doc.getParagraphs()) {
paragraph.removeRun(0);
assertNotNull(paragraph.getText());

View File

@ -23,7 +23,6 @@ import java.util.Arrays;
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;
@ -44,8 +43,8 @@ public final class TestXWPFDocument extends TestCase {
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) {
@ -106,7 +105,7 @@ public final class TestXWPFDocument extends TestCase {
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());
@ -129,15 +128,15 @@ public final class TestXWPFDocument extends TestCase {
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();
@ -235,7 +234,7 @@ public final class TestXWPFDocument extends TestCase {
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));
@ -267,7 +266,7 @@ public final class TestXWPFDocument extends TestCase {
List<XWPFPictureData> allPackagePictures = doc.getAllPackagePictures();
assertNotNull(allPictures);
assertEquals(3,allPictures.size());
assertEquals(3, allPictures.size());
for (XWPFPictureData xwpfPictureData : allPictures) {
assertTrue(allPackagePictures.contains(xwpfPictureData));
}
@ -287,7 +286,7 @@ public final class TestXWPFDocument extends TestCase {
List<XWPFPictureData> allPackagePictures = doc.getAllPackagePictures();
assertNotNull(allPackagePictures);
assertEquals(5,allPackagePictures.size());
assertEquals(5, allPackagePictures.size());
try {
allPackagePictures.add(allPackagePictures.get(0));
@ -301,22 +300,22 @@ public final class TestXWPFDocument extends TestCase {
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();
}
@ -324,18 +323,19 @@ public final class TestXWPFDocument extends TestCase {
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();
@ -352,7 +352,7 @@ public final class TestXWPFDocument extends TestCase {
assertEquals(0, extendedProperties.getUnderlyingProperties().getCharacters());
}
public void testSettings(){
public void testSettings() {
XWPFSettings settings = new XWPFSettings();
settings.setZoomPercent(50);
assertEquals(50, settings.getZoomPercent());

View File

@ -19,52 +19,50 @@ package org.apache.poi.xwpf.usermodel;
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;
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);
}
}

View File

@ -17,13 +17,12 @@
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;
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 org.openxmlformats.schemas.wordprocessingml.x2006.main.CTR;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTText;
@ -159,25 +158,25 @@ public final class TestXWPFHeader extends TestCase {
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());
public void testSetWatermark() throws IOException {
XWPFDocument sampleDoc = XWPFTestDataSamples.openSampleDocument("SampleDoc.docx");
// No header is set (yet)
XWPFHeaderFooterPolicy policy = sampleDoc.getHeaderFooterPolicy();
assertNull(policy.getDefaultHeader());
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());
assertNotNull(policy.getFirstPageHeader());
assertNotNull(policy.getEvenPageHeader());
// Re-open, and check
XWPFDocument reopened = XWPFTestDataSamples.writeOutAndReadBack(sampleDoc);
policy = reopened.getHeaderFooterPolicy();
assertNotNull(policy.getDefaultHeader());
assertNotNull(policy.getFirstPageHeader());

View File

@ -16,39 +16,38 @@
==================================================================== */
package org.apache.poi.xwpf.usermodel;
import java.io.IOException;
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;
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();
/**
* @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();
style.setType(STStyleType.PARAGRAPH);
style.setStyleId("Heading1");
}

View File

@ -18,86 +18,85 @@
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;
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());
}
}

View File

@ -22,12 +22,26 @@ import java.math.BigInteger;
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
@ -36,7 +50,8 @@ public final class TestXWPFParagraph extends TestCase {
/**
* 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");
@ -44,7 +59,7 @@ public final class TestXWPFParagraph extends TestCase {
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);
@ -55,7 +70,8 @@ public final class TestXWPFParagraph extends TestCase {
/**
* 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");
@ -88,7 +104,7 @@ public final class TestXWPFParagraph extends TestCase {
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();
@ -109,7 +125,7 @@ public final class TestXWPFParagraph extends TestCase {
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);
@ -125,7 +141,7 @@ public final class TestXWPFParagraph extends TestCase {
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());
@ -142,7 +158,7 @@ public final class TestXWPFParagraph extends TestCase {
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());
@ -161,7 +177,7 @@ public final class TestXWPFParagraph extends TestCase {
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());
@ -179,7 +195,7 @@ public final class TestXWPFParagraph extends TestCase {
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);
@ -194,7 +210,7 @@ public final class TestXWPFParagraph extends TestCase {
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);
@ -210,7 +226,7 @@ public final class TestXWPFParagraph extends TestCase {
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);
@ -229,8 +245,8 @@ public final class TestXWPFParagraph extends TestCase {
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());
}
}
@ -241,108 +257,108 @@ public final class TestXWPFParagraph extends TestCase {
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;
XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("VariousPictures.docx");
assertEquals(7, doc.getParagraphs().size());
// 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());
XWPFParagraph p;
XWPFRun r;
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());
// Text paragraphs
assertEquals("Sheet with various pictures", doc.getParagraphs().get(0).getText());
assertEquals("(jpeg, png, wmf, emf and pict) ", doc.getParagraphs().get(1).getText());
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());
// Spacer ones
assertEquals("", doc.getParagraphs().get(2).getText());
assertEquals("", doc.getParagraphs().get(3).getText());
assertEquals("", doc.getParagraphs().get(4).getText());
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());
// Image one
p = doc.getParagraphs().get(5);
assertEquals(6, p.getRuns().size());
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(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(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());
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));
@ -355,7 +371,7 @@ public final class TestXWPFParagraph extends TestCase {
assertFalse(p.isEmpty());
assertNull(p.getStyleID());
assertNull(p.getStyle());
assertNull(p.getNumID());
p.setNumID(BigInteger.valueOf(12));
assertEquals(BigInteger.valueOf(12), p.getNumID());
@ -363,18 +379,18 @@ public final class TestXWPFParagraph extends TestCase {
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);
@ -394,37 +410,37 @@ public final class TestXWPFParagraph extends TestCase {
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());
@ -442,20 +458,20 @@ public final class TestXWPFParagraph extends TestCase {
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();
@ -469,17 +485,17 @@ public final class TestXWPFParagraph extends TestCase {
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();
@ -489,7 +505,7 @@ public final class TestXWPFParagraph extends TestCase {
XWPFRun r = new XWPFRun(run, doc.createParagraph());
p.addRun(r);
p.addRun(r);
assertNotNull(p.getRun(run));
assertNull(p.getRun(null));
}

View File

@ -20,138 +20,129 @@ package org.apache.poi.xwpf.usermodel;
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;
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 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;
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);
}
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();
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);
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);
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 {
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) {
//System.out.println(picture.getCTPicture());
XWPFPictureData data = picture.getPictureData();
if (data != null) System.out.println(data.getFileName());
}
}
}
}
}

View File

@ -20,13 +20,12 @@ import java.io.ByteArrayInputStream;
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;
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 org.openxmlformats.schemas.wordprocessingml.x2006.main.CTR;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTRPr;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.STBrClear;
@ -46,28 +45,28 @@ public class TestXWPFRun extends TestCase {
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);
}
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);
XWPFRun run = new XWPFRun(ctRun, p);
assertEquals(true, run.isBold());
@ -178,16 +177,16 @@ public class TestXWPFRun extends TestCase {
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");
run.addCarriageReturn();
assertEquals(3, run.getCTR().sizeOfCrArray());
assertEquals("T1\n\nT2\n", run.toString());
}
public void testAddTabsAndLineBreaks() {
ctRun.addNewT().setStringValue("TEST STRING");
ctRun.addNewCr();
ctRun.addNewT().setStringValue("TEST2 STRING");
ctRun.addNewTab();
ctRun.addNewT().setStringValue("TEST3 STRING");
@ -199,21 +198,21 @@ public class TestXWPFRun extends TestCase {
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");
assertEquals(1, run.getCTR().sizeOfCrArray());
assertEquals(1, run.getCTR().sizeOfTabArray());
assertEquals("T1\nT2\tT3", run.toString());
}
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");
ctRun.addNewBr();
ctRun.addNewT().setStringValue("TEST2 STRING");
CTBr breac = ctRun.addNewBr();
breac.setClear(STBrClear.LEFT);
ctRun.addNewT().setStringValue("TEST3 STRING");
assertEquals(2, ctRun.sizeOfBrArray());
XWPFRun run = new XWPFRun(CTR.Factory.newInstance(), p);
run.setText("TEXT1");
@ -222,144 +221,145 @@ public class TestXWPFRun extends TestCase {
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 {
/**
* 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 {
XWPFDocument sampleDoc = XWPFTestDataSamples.openSampleDocument("headerPic.docx");
XWPFHeaderFooterPolicy policy = sampleDoc.getHeaderFooterPolicy();
@ -373,47 +373,47 @@ public class TestXWPFRun extends TestCase {
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());
}
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");
}
}
}
}
}
}

View File

@ -15,48 +15,46 @@
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;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
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());
assertEquals("tag", "MyTag", tag);
assertEquals("title", "MyTitle", title);
}
public void testGetSDTs() throws Exception{
String[] contents = new String[]{
"header_rich_text",
"Rich_text",
}
public void testGetSDTs() throws Exception {
String[] contents = new String[]{
"header_rich_text",
"Rich_text",
"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",
@ -72,125 +70,126 @@ public final class TestXWPFSDT extends TestCase {
};
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
*/
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
*/
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");
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();
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));
}
}
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));
}
}
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()) {
for (ICell c : r.getTableICells()) {
if (c instanceof XWPFSDTCell) {
sdts.add((XWPFSDTCell) c);
} else if (c instanceof XWPFTableCell) {
sdts.addAll(extractSDTsFromBodyElements(((XWPFTableCell) c).getBodyElements()));
}
}
}
return sdts;
}
}

View File

@ -19,13 +19,12 @@ package org.apache.poi.xwpf.usermodel;
import java.io.IOException;
import junit.framework.TestCase;
import org.apache.poi.xwpf.XWPFTestDataSamples;
/**
* Tests for reading SmartTags from Word docx.
*
* @author Fabian Lange
* @author Fabian Lange
*/
public final class TestXWPFSmartTag extends TestCase {

View File

@ -19,13 +19,12 @@ package org.apache.poi.xwpf.usermodel;
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;
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 org.openxmlformats.schemas.wordprocessingml.x2006.main.CTLsdException;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTStyle;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTStyles;
@ -33,69 +32,69 @@ import org.openxmlformats.schemas.wordprocessingml.x2006.main.STStyleType;
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 {
// 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");
styles.setSpellingLanguage("English");
@ -116,82 +115,82 @@ public class TestXWPFStyles extends TestCase {
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"));
assertEquals(false, ls.isLatentStyle("notex1"));
}
public void testSetStyles_Bug57254() throws IOException {
XWPFDocument docOut = new XWPFDocument();
XWPFStyles styles = docOut.createStyles();
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);
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());
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());
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"));
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());
}
}

View File

@ -17,13 +17,12 @@
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;
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 org.openxmlformats.schemas.wordprocessingml.x2006.main.CTR;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTRow;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTbl;
@ -122,13 +121,13 @@ public class TestXWPFTable extends TestCase {
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"));
public void testSetGetWidth() {
XWPFDocument doc = new XWPFDocument();
CTTbl table = CTTbl.Factory.newInstance();
table.addNewTblPr().addNewTblW().setW(new BigInteger("1000"));
XWPFTable xtab = new XWPFTable(table, doc);
assertEquals(1000, xtab.getWidth());
@ -146,20 +145,20 @@ public class TestXWPFTable extends TestCase {
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);
}
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);
// get margin components
int t = table.getCellMarginTop();
assertEquals(50, t);
@ -169,22 +168,22 @@ public class TestXWPFTable extends TestCase {
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");
}
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");
// get inside horizontal border components
int s = table.getInsideHBorderSize();
assertEquals(4, s);
@ -194,26 +193,26 @@ public class TestXWPFTable extends TestCase {
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);
}
public void testSetGetVBorders() {
// create a table
XWPFDocument doc = new XWPFDocument();
CTTbl ctTable = CTTbl.Factory.newInstance();
XWPFTable table = new XWPFTable(ctTable, doc);
// 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);
int sp = table.getInsideVBorderSpace();
assertEquals(0, sp);
String clr = table.getInsideVBorderColor();
assertEquals("00FF00", clr);
}
public void testSetGetRowBandSize() {
XWPFDocument doc = new XWPFDocument();
CTTbl ctTable = CTTbl.Factory.newInstance();
@ -230,32 +229,30 @@ public class TestXWPFTable extends TestCase {
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();
}
}
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();
}
}

View File

@ -17,71 +17,80 @@
* ====================================================================
*/
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;
import junit.framework.TestCase;
import org.apache.poi.xwpf.usermodel.XWPFTableCell.XWPFVertAlign;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTHMerge;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTShd;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTbl;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTc;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTcBorders;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTcPr;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTVMerge;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTVerticalJc;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.STMerge;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.STShd;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.STVerticalJc;
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);
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);
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);
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");
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);
XWPFTableRow tr = table.getRow(0);
XWPFTableCell cell = tr.getCell(0);

View File

@ -15,55 +15,54 @@
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;
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);
}
}