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

@ -35,11 +35,9 @@ import java.util.jar.JarFile;
import java.util.regex.Pattern; import java.util.regex.Pattern;
import junit.framework.TestCase; import junit.framework.TestCase;
import org.junit.Test; import org.junit.Test;
import org.junit.internal.TextListener; import org.junit.internal.TextListener;
import org.junit.runner.JUnitCore; import org.junit.runner.JUnitCore;import org.junit.runner.Result;
import org.junit.runner.Result;
/** /**
* Build a 'lite' version of the ooxml-schemas.jar * Build a 'lite' version of the ooxml-schemas.jar

View File

@ -46,45 +46,46 @@ import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTSectPr;
* Helper class to extract text from an OOXML Word file * Helper class to extract text from an OOXML Word file
*/ */
public class XWPFWordExtractor extends POIXMLTextExtractor { public class XWPFWordExtractor extends POIXMLTextExtractor {
public static final XWPFRelation[] SUPPORTED_TYPES = new XWPFRelation[] { public static final XWPFRelation[] SUPPORTED_TYPES = new XWPFRelation[]{
XWPFRelation.DOCUMENT, XWPFRelation.TEMPLATE, XWPFRelation.DOCUMENT, XWPFRelation.TEMPLATE,
XWPFRelation.MACRO_DOCUMENT, XWPFRelation.MACRO_DOCUMENT,
XWPFRelation.MACRO_TEMPLATE_DOCUMENT XWPFRelation.MACRO_TEMPLATE_DOCUMENT
}; };
private XWPFDocument document; private XWPFDocument document;
private boolean fetchHyperlinks = false; private boolean fetchHyperlinks = false;
public XWPFWordExtractor(OPCPackage container) throws XmlException, OpenXML4JException, IOException { public XWPFWordExtractor(OPCPackage container) throws XmlException, OpenXML4JException, IOException {
this(new XWPFDocument(container)); this(new XWPFDocument(container));
} }
public XWPFWordExtractor(XWPFDocument document) {
super(document);
this.document = document;
}
/** public XWPFWordExtractor(XWPFDocument document) {
* Should we also fetch the hyperlinks, when fetching super(document);
* the text content? Default is to only output the this.document = document;
* hyperlink label, and not the contents }
*/
public void setFetchHyperlinks(boolean fetch) {
fetchHyperlinks = fetch;
}
public static void main(String[] args) throws Exception { public static void main(String[] args) throws Exception {
if(args.length < 1) { if (args.length < 1) {
System.err.println("Use:"); System.err.println("Use:");
System.err.println(" XWPFWordExtractor <filename.docx>"); System.err.println(" XWPFWordExtractor <filename.docx>");
System.exit(1); System.exit(1);
} }
POIXMLTextExtractor extractor = POIXMLTextExtractor extractor =
new XWPFWordExtractor(POIXMLDocument.openPackage( new XWPFWordExtractor(POIXMLDocument.openPackage(
args[0] args[0]
)); ));
System.out.println(extractor.getText()); System.out.println(extractor.getText());
extractor.close(); extractor.close();
} }
/**
* Should we also fetch the hyperlinks, when fetching
* the text content? Default is to only output the
* hyperlink label, and not the contents
*/
public void setFetchHyperlinks(boolean fetch) {
fetchHyperlinks = fetch;
}
public String getText() { public String getText() {
StringBuffer text = new StringBuffer(); StringBuffer text = new StringBuffer();
@ -94,9 +95,9 @@ public class XWPFWordExtractor extends POIXMLTextExtractor {
extractHeaders(text, hfPolicy); extractHeaders(text, hfPolicy);
// Process all body elements // Process all body elements
for (IBodyElement e : document.getBodyElements()){ for (IBodyElement e : document.getBodyElements()) {
appendBodyElementText(text, e); appendBodyElementText(text, e);
text.append('\n'); text.append('\n');
} }
// Finish up with all the footers // Finish up with all the footers
@ -105,108 +106,108 @@ public class XWPFWordExtractor extends POIXMLTextExtractor {
return text.toString(); return text.toString();
} }
public void appendBodyElementText(StringBuffer text, IBodyElement e){ public void appendBodyElementText(StringBuffer text, IBodyElement e) {
if (e instanceof XWPFParagraph){ if (e instanceof XWPFParagraph) {
appendParagraphText(text, (XWPFParagraph)e); appendParagraphText(text, (XWPFParagraph) e);
} else if (e instanceof XWPFTable){ } else if (e instanceof XWPFTable) {
appendTableText(text, (XWPFTable)e); appendTableText(text, (XWPFTable) e);
} else if (e instanceof XWPFSDT){ } else if (e instanceof XWPFSDT) {
text.append(((XWPFSDT)e).getContent().getText()); text.append(((XWPFSDT) e).getContent().getText());
} }
} }
public void appendParagraphText(StringBuffer text, XWPFParagraph paragraph){ public void appendParagraphText(StringBuffer text, XWPFParagraph paragraph) {
try { try {
CTSectPr ctSectPr = null; CTSectPr ctSectPr = null;
if (paragraph.getCTP().getPPr()!=null) { if (paragraph.getCTP().getPPr() != null) {
ctSectPr = paragraph.getCTP().getPPr().getSectPr(); ctSectPr = paragraph.getCTP().getPPr().getSectPr();
} }
XWPFHeaderFooterPolicy headerFooterPolicy = null; XWPFHeaderFooterPolicy headerFooterPolicy = null;
if (ctSectPr!=null) { if (ctSectPr != null) {
headerFooterPolicy = new XWPFHeaderFooterPolicy(document, ctSectPr); headerFooterPolicy = new XWPFHeaderFooterPolicy(document, ctSectPr);
extractHeaders(text, headerFooterPolicy); extractHeaders(text, headerFooterPolicy);
} }
for(IRunElement run : paragraph.getRuns()) { for (IRunElement run : paragraph.getRuns()) {
text.append(run.toString()); text.append(run.toString());
if(run instanceof XWPFHyperlinkRun && fetchHyperlinks) { if (run instanceof XWPFHyperlinkRun && fetchHyperlinks) {
XWPFHyperlink link = ((XWPFHyperlinkRun)run).getHyperlink(document); XWPFHyperlink link = ((XWPFHyperlinkRun) run).getHyperlink(document);
if(link != null) if (link != null)
text.append(" <" + link.getURL() + ">"); text.append(" <" + link.getURL() + ">");
} }
} }
// Add comments // Add comments
XWPFCommentsDecorator decorator = new XWPFCommentsDecorator(paragraph, null); XWPFCommentsDecorator decorator = new XWPFCommentsDecorator(paragraph, null);
String commentText = decorator.getCommentText(); String commentText = decorator.getCommentText();
if (commentText.length() > 0){ if (commentText.length() > 0) {
text.append(commentText).append('\n'); text.append(commentText).append('\n');
} }
// Do endnotes and footnotes // Do endnotes and footnotes
String footnameText = paragraph.getFootnoteText(); String footnameText = paragraph.getFootnoteText();
if(footnameText != null && footnameText.length() > 0) { if (footnameText != null && footnameText.length() > 0) {
text.append(footnameText + '\n'); text.append(footnameText + '\n');
} }
if (ctSectPr!=null) { if (ctSectPr != null) {
extractFooters(text, headerFooterPolicy); extractFooters(text, headerFooterPolicy);
} }
} catch (IOException e) { } catch (IOException e) {
throw new POIXMLException(e); throw new POIXMLException(e);
} catch (XmlException e) { } catch (XmlException e) {
throw new POIXMLException(e); throw new POIXMLException(e);
} }
} }
private void appendTableText(StringBuffer text, XWPFTable table) { private void appendTableText(StringBuffer text, XWPFTable table) {
//this works recursively to pull embedded tables from tables //this works recursively to pull embedded tables from tables
for (XWPFTableRow row : table.getRows()) { for (XWPFTableRow row : table.getRows()) {
List<ICell> cells = row.getTableICells(); List<ICell> cells = row.getTableICells();
for (int i = 0; i < cells.size(); i++) { for (int i = 0; i < cells.size(); i++) {
ICell cell = cells.get(i); ICell cell = cells.get(i);
if (cell instanceof XWPFTableCell) { if (cell instanceof XWPFTableCell) {
text.append(((XWPFTableCell)cell).getTextRecursively()); text.append(((XWPFTableCell) cell).getTextRecursively());
} else if (cell instanceof XWPFSDTCell) { } else if (cell instanceof XWPFSDTCell) {
text.append(((XWPFSDTCell)cell).getContent().getText()); text.append(((XWPFSDTCell) cell).getContent().getText());
} }
if (i < cells.size()-1) { if (i < cells.size() - 1) {
text.append("\t"); text.append("\t");
} }
} }
text.append('\n'); text.append('\n');
} }
} }
private void extractFooters(StringBuffer text, XWPFHeaderFooterPolicy hfPolicy) { private void extractFooters(StringBuffer text, XWPFHeaderFooterPolicy hfPolicy) {
if (hfPolicy == null) return; if (hfPolicy == null) return;
if(hfPolicy.getFirstPageFooter() != null) { if (hfPolicy.getFirstPageFooter() != null) {
text.append( hfPolicy.getFirstPageFooter().getText() ); text.append(hfPolicy.getFirstPageFooter().getText());
} }
if(hfPolicy.getEvenPageFooter() != null) { if (hfPolicy.getEvenPageFooter() != null) {
text.append( hfPolicy.getEvenPageFooter().getText() ); text.append(hfPolicy.getEvenPageFooter().getText());
} }
if(hfPolicy.getDefaultFooter() != null) { if (hfPolicy.getDefaultFooter() != null) {
text.append( hfPolicy.getDefaultFooter().getText() ); text.append(hfPolicy.getDefaultFooter().getText());
} }
} }
private void extractHeaders(StringBuffer text, XWPFHeaderFooterPolicy hfPolicy) { private void extractHeaders(StringBuffer text, XWPFHeaderFooterPolicy hfPolicy) {
if (hfPolicy == null) return; if (hfPolicy == null) return;
if(hfPolicy.getFirstPageHeader() != null) { if (hfPolicy.getFirstPageHeader() != null) {
text.append( hfPolicy.getFirstPageHeader().getText() ); text.append(hfPolicy.getFirstPageHeader().getText());
} }
if(hfPolicy.getEvenPageHeader() != null) { if (hfPolicy.getEvenPageHeader() != null) {
text.append( hfPolicy.getEvenPageHeader().getText() ); text.append(hfPolicy.getEvenPageHeader().getText());
} }
if(hfPolicy.getDefaultHeader() != null) { if (hfPolicy.getDefaultHeader() != null) {
text.append( hfPolicy.getDefaultHeader().getText() ); text.append(hfPolicy.getDefaultHeader().getText());
} }
} }
} }

View File

@ -22,16 +22,15 @@ import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTP;
* Base class for XWPF paragraphs * Base class for XWPF paragraphs
* *
* @author Yury Batrakov (batrakov at gmail.com) * @author Yury Batrakov (batrakov at gmail.com)
*
*/ */
public class XMLParagraph { public class XMLParagraph {
protected CTP paragraph; protected CTP paragraph;
public XMLParagraph(CTP paragraph) { public XMLParagraph(CTP paragraph) {
this.paragraph = paragraph; this.paragraph = paragraph;
} }
public CTP getCTP() { public CTP getCTP() {
return paragraph; return paragraph;
} }
} }

View File

@ -25,34 +25,32 @@ import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTMarkupRange;
* found in paragraph to its text * found in paragraph to its text
* *
* @author Yury Batrakov (batrakov at gmail.com) * @author Yury Batrakov (batrakov at gmail.com)
*
*/ */
public class XWPFCommentsDecorator extends XWPFParagraphDecorator { public class XWPFCommentsDecorator extends XWPFParagraphDecorator {
private StringBuffer commentText; private StringBuffer commentText;
public XWPFCommentsDecorator(XWPFParagraphDecorator nextDecorator) { public XWPFCommentsDecorator(XWPFParagraphDecorator nextDecorator) {
this(nextDecorator.paragraph, nextDecorator); this(nextDecorator.paragraph, nextDecorator);
} }
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
public XWPFCommentsDecorator(XWPFParagraph paragraph, XWPFParagraphDecorator nextDecorator) { public XWPFCommentsDecorator(XWPFParagraph paragraph, XWPFParagraphDecorator nextDecorator) {
super(paragraph, nextDecorator); super(paragraph, nextDecorator);
XWPFComment comment; XWPFComment comment;
commentText = new StringBuffer(); commentText = new StringBuffer();
for(CTMarkupRange anchor : paragraph.getCTP().getCommentRangeStartArray()) for (CTMarkupRange anchor : paragraph.getCTP().getCommentRangeStartArray()) {
{ if ((comment = paragraph.getDocument().getCommentByID(anchor.getId().toString())) != null)
if((comment = paragraph.getDocument().getCommentByID(anchor.getId().toString())) != null) commentText.append("\tComment by " + comment.getAuthor() + ": " + comment.getText());
commentText.append("\tComment by " + comment.getAuthor()+": "+comment.getText()); }
} }
}
public String getCommentText() { public String getCommentText() {
return commentText.toString(); return commentText.toString();
} }
public String getText() { public String getText() {
return super.getText() + commentText; 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.HdrDocument;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.STHdrFtr; import org.openxmlformats.schemas.wordprocessingml.x2006.main.STHdrFtr;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.STHdrFtr.Enum; import org.openxmlformats.schemas.wordprocessingml.x2006.main.STHdrFtr.Enum;
import schemasMicrosoftComOfficeOffice.CTLock; import schemasMicrosoftComOfficeOffice.CTLock;
import schemasMicrosoftComOfficeOffice.STConnectType; import schemasMicrosoftComOfficeOffice.STConnectType;
import schemasMicrosoftComVml.CTFormulas; import schemasMicrosoftComVml.CTFormulas;
@ -61,10 +60,10 @@ import schemasMicrosoftComVml.STTrueFalse;
/** /**
* A .docx file can have no headers/footers, the same header/footer * A .docx file can have no headers/footers, the same header/footer
* on each page, odd/even page footers, and optionally also * on each page, odd/even page footers, and optionally also
* a different header/footer on the first page. * a different header/footer on the first page.
* This class handles sorting out what there is, and giving you * 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 class XWPFHeaderFooterPolicy {
public static final Enum DEFAULT = STHdrFtr.DEFAULT; public static final Enum DEFAULT = STHdrFtr.DEFAULT;
@ -84,8 +83,8 @@ public class XWPFHeaderFooterPolicy {
/** /**
* Figures out the policy for the given document, * Figures out the policy for the given document,
* and creates any header and footer objects * and creates any header and footer objects
* as required. * as required.
*/ */
public XWPFHeaderFooterPolicy(XWPFDocument doc) throws IOException, XmlException { public XWPFHeaderFooterPolicy(XWPFDocument doc) throws IOException, XmlException {
this(doc, doc.getDocument().getBody().getSectPr()); this(doc, doc.getDocument().getBody().getSectPr());
@ -93,8 +92,8 @@ public class XWPFHeaderFooterPolicy {
/** /**
* Figures out the policy for the given document, * Figures out the policy for the given document,
* and creates any header and footer objects * and creates any header and footer objects
* as required. * as required.
*/ */
public XWPFHeaderFooterPolicy(XWPFDocument doc, CTSectPr sectPr) throws IOException, XmlException { public XWPFHeaderFooterPolicy(XWPFDocument doc, CTSectPr sectPr) throws IOException, XmlException {
// Grab what headers and footers have been defined // Grab what headers and footers have been defined
@ -102,7 +101,7 @@ public class XWPFHeaderFooterPolicy {
// doesn't seem that .docx properly supports that // doesn't seem that .docx properly supports that
// feature of the file format yet // feature of the file format yet
this.doc = doc; this.doc = doc;
for(int i=0; i<sectPr.sizeOfHeaderReferenceArray(); i++) { for (int i = 0; i < sectPr.sizeOfHeaderReferenceArray(); i++) {
// Get the header // Get the header
CTHdrFtrRef ref = sectPr.getHeaderReferenceArray(i); CTHdrFtrRef ref = sectPr.getHeaderReferenceArray(i);
POIXMLDocumentPart relatedPart = doc.getRelationById(ref.getId()); POIXMLDocumentPart relatedPart = doc.getRelationById(ref.getId());
@ -114,13 +113,12 @@ public class XWPFHeaderFooterPolicy {
Enum type = ref.getType(); Enum type = ref.getType();
assignHeader(hdr, type); assignHeader(hdr, type);
} }
for(int i=0; i<sectPr.sizeOfFooterReferenceArray(); i++) { for (int i = 0; i < sectPr.sizeOfFooterReferenceArray(); i++) {
// Get the footer // Get the footer
CTHdrFtrRef ref = sectPr.getFooterReferenceArray(i); CTHdrFtrRef ref = sectPr.getFooterReferenceArray(i);
POIXMLDocumentPart relatedPart = doc.getRelationById(ref.getId()); POIXMLDocumentPart relatedPart = doc.getRelationById(ref.getId());
XWPFFooter ftr = null; XWPFFooter ftr = null;
if (relatedPart != null && relatedPart instanceof XWPFFooter) if (relatedPart != null && relatedPart instanceof XWPFFooter) {
{
ftr = (XWPFFooter) relatedPart; ftr = (XWPFFooter) relatedPart;
} }
// Assign it // Assign it
@ -130,9 +128,9 @@ public class XWPFHeaderFooterPolicy {
} }
private void assignFooter(XWPFFooter ftr, Enum type) { private void assignFooter(XWPFFooter ftr, Enum type) {
if(type == STHdrFtr.FIRST) { if (type == STHdrFtr.FIRST) {
firstPageFooter = ftr; firstPageFooter = ftr;
} else if(type == STHdrFtr.EVEN) { } else if (type == STHdrFtr.EVEN) {
evenPageFooter = ftr; evenPageFooter = ftr;
} else { } else {
defaultFooter = ftr; defaultFooter = ftr;
@ -140,9 +138,9 @@ public class XWPFHeaderFooterPolicy {
} }
private void assignHeader(XWPFHeader hdr, Enum type) { private void assignHeader(XWPFHeader hdr, Enum type) {
if(type == STHdrFtr.FIRST) { if (type == STHdrFtr.FIRST) {
firstPageHeader = hdr; firstPageHeader = hdr;
} else if(type == STHdrFtr.EVEN) { } else if (type == STHdrFtr.EVEN) {
evenPageHeader = hdr; evenPageHeader = hdr;
} else { } else {
defaultHeader = hdr; defaultHeader = hdr;
@ -159,15 +157,15 @@ public class XWPFHeaderFooterPolicy {
/** /**
* Creates a new header of the specified type, to which the * Creates a new header of the specified type, to which the
* supplied (and previously unattached!) paragraphs are * supplied (and previously unattached!) paragraphs are
* added to. * added to.
*/ */
public XWPFHeader createHeader(Enum type, XWPFParagraph[] pars) throws IOException { public XWPFHeader createHeader(Enum type, XWPFParagraph[] pars) throws IOException {
XWPFRelation relation = XWPFRelation.HEADER; XWPFRelation relation = XWPFRelation.HEADER;
String pStyle = "Header"; String pStyle = "Header";
int i = getRelationIndex(relation); int i = getRelationIndex(relation);
HdrDocument hdrDoc = HdrDocument.Factory.newInstance(); 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); CTHdrFtr hdr = buildHdr(type, pStyle, wrapper, pars);
wrapper.setHeaderFooter(hdr); wrapper.setHeaderFooter(hdr);
@ -193,15 +191,15 @@ public class XWPFHeaderFooterPolicy {
/** /**
* Creates a new footer of the specified type, to which the * Creates a new footer of the specified type, to which the
* supplied (and previously unattached!) paragraphs are * supplied (and previously unattached!) paragraphs are
* added to. * added to.
*/ */
public XWPFFooter createFooter(Enum type, XWPFParagraph[] pars) throws IOException { public XWPFFooter createFooter(Enum type, XWPFParagraph[] pars) throws IOException {
XWPFRelation relation = XWPFRelation.FOOTER; XWPFRelation relation = XWPFRelation.FOOTER;
String pStyle = "Footer"; String pStyle = "Footer";
int i = getRelationIndex(relation); int i = getRelationIndex(relation);
FtrDocument ftrDoc = FtrDocument.Factory.newInstance(); 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); CTHdrFtr ftr = buildFtr(type, pStyle, wrapper, pars);
wrapper.setHeaderFooter(ftr); wrapper.setHeaderFooter(ftr);
@ -220,7 +218,7 @@ public class XWPFHeaderFooterPolicy {
private int getRelationIndex(XWPFRelation relation) { private int getRelationIndex(XWPFRelation relation) {
List<POIXMLDocumentPart> relations = doc.getRelations(); List<POIXMLDocumentPart> relations = doc.getRelations();
int i = 1; int i = 1;
for (Iterator<POIXMLDocumentPart> it = relations.iterator(); it.hasNext() ; ) { for (Iterator<POIXMLDocumentPart> it = relations.iterator(); it.hasNext(); ) {
POIXMLDocumentPart item = it.next(); POIXMLDocumentPart item = it.next();
if (item.getPackageRelationship().getRelationshipType().equals(relation.getRelation())) { if (item.getPackageRelationship().getRelationshipType().equals(relation.getRelation())) {
i++; i++;
@ -231,14 +229,14 @@ public class XWPFHeaderFooterPolicy {
private CTHdrFtr buildFtr(Enum type, String pStyle, XWPFHeaderFooter wrapper, XWPFParagraph[] pars) { 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); // 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); setFooterReference(type, wrapper);
return ftr; return ftr;
} }
private CTHdrFtr buildHdr(Enum type, String pStyle, XWPFHeaderFooter wrapper, XWPFParagraph[] pars) { 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); // 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); setHeaderReference(type, wrapper);
return hdr; return hdr;
} }
@ -246,13 +244,12 @@ public class XWPFHeaderFooterPolicy {
private CTHdrFtr buildHdrFtr(String pStyle, XWPFParagraph[] paragraphs) { private CTHdrFtr buildHdrFtr(String pStyle, XWPFParagraph[] paragraphs) {
CTHdrFtr ftr = CTHdrFtr.Factory.newInstance(); CTHdrFtr ftr = CTHdrFtr.Factory.newInstance();
if (paragraphs != null) { if (paragraphs != null) {
for (int i = 0 ; i < paragraphs.length ; i++) { for (int i = 0; i < paragraphs.length; i++) {
CTP p = ftr.addNewP(); CTP p = ftr.addNewP();
//ftr.setPArray(0, paragraphs[i].getCTP()); // MB 23 May 2010 //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(); CTP p = ftr.addNewP();
byte[] rsidr = doc.getDocument().getBody().getPArray(0).getRsidR(); byte[] rsidr = doc.getDocument().getBody().getPArray(0).getRsidR();
byte[] rsidrdefault = doc.getDocument().getBody().getPArray(0).getRsidRDefault(); byte[] rsidrdefault = doc.getDocument().getBody().getPArray(0).getRsidRDefault();
@ -279,12 +276,11 @@ public class XWPFHeaderFooterPolicy {
private CTHdrFtr buildHdrFtr(String pStyle, XWPFParagraph[] paragraphs, XWPFHeaderFooter wrapper) { private CTHdrFtr buildHdrFtr(String pStyle, XWPFParagraph[] paragraphs, XWPFHeaderFooter wrapper) {
CTHdrFtr ftr = wrapper._getHdrFtr(); CTHdrFtr ftr = wrapper._getHdrFtr();
if (paragraphs != null) { if (paragraphs != null) {
for (int i = 0 ; i < paragraphs.length ; i++) { for (int i = 0; i < paragraphs.length; i++) {
CTP p = ftr.addNewP(); CTP p = ftr.addNewP();
ftr.setPArray(i, paragraphs[i].getCTP()); ftr.setPArray(i, paragraphs[i].getCTP());
} }
} } else {
else {
CTP p = ftr.addNewP(); CTP p = ftr.addNewP();
byte[] rsidr = doc.getDocument().getBody().getPArray(0).getRsidR(); byte[] rsidr = doc.getDocument().getBody().getPArray(0).getRsidR();
byte[] rsidrdefault = doc.getDocument().getBody().getPArray(0).getRsidRDefault(); byte[] rsidrdefault = doc.getDocument().getBody().getPArray(0).getRsidRDefault();
@ -330,60 +326,70 @@ public class XWPFHeaderFooterPolicy {
public XWPFHeader getFirstPageHeader() { public XWPFHeader getFirstPageHeader() {
return firstPageHeader; return firstPageHeader;
} }
public XWPFFooter getFirstPageFooter() { public XWPFFooter getFirstPageFooter() {
return firstPageFooter; return firstPageFooter;
} }
/** /**
* Returns the odd page header. This is * Returns the odd page header. This is
* also the same as the default one... * also the same as the default one...
*/ */
public XWPFHeader getOddPageHeader() { public XWPFHeader getOddPageHeader() {
return defaultHeader; return defaultHeader;
} }
/** /**
* Returns the odd page footer. This is * Returns the odd page footer. This is
* also the same as the default one... * also the same as the default one...
*/ */
public XWPFFooter getOddPageFooter() { public XWPFFooter getOddPageFooter() {
return defaultFooter; return defaultFooter;
} }
public XWPFHeader getEvenPageHeader() { public XWPFHeader getEvenPageHeader() {
return evenPageHeader; return evenPageHeader;
} }
public XWPFFooter getEvenPageFooter() { public XWPFFooter getEvenPageFooter() {
return evenPageFooter; return evenPageFooter;
} }
public XWPFHeader getDefaultHeader() { public XWPFHeader getDefaultHeader() {
return defaultHeader; return defaultHeader;
} }
public XWPFFooter getDefaultFooter() { public XWPFFooter getDefaultFooter() {
return defaultFooter; return defaultFooter;
} }
/** /**
* Get the header that applies to the given * Get the header that applies to the given
* (1 based) page. * (1 based) page.
*
* @param pageNumber The one based page number * @param pageNumber The one based page number
*/ */
public XWPFHeader getHeader(int pageNumber) { public XWPFHeader getHeader(int pageNumber) {
if(pageNumber == 1 && firstPageHeader != null) { if (pageNumber == 1 && firstPageHeader != null) {
return firstPageHeader; return firstPageHeader;
} }
if(pageNumber % 2 == 0 && evenPageHeader != null) { if (pageNumber % 2 == 0 && evenPageHeader != null) {
return evenPageHeader; return evenPageHeader;
} }
return defaultHeader; return defaultHeader;
} }
/** /**
* Get the footer that applies to the given * Get the footer that applies to the given
* (1 based) page. * (1 based) page.
*
* @param pageNumber The one based page number * @param pageNumber The one based page number
*/ */
public XWPFFooter getFooter(int pageNumber) { public XWPFFooter getFooter(int pageNumber) {
if(pageNumber == 1 && firstPageFooter != null) { if (pageNumber == 1 && firstPageFooter != null) {
return firstPageFooter; return firstPageFooter;
} }
if(pageNumber % 2 == 0 && evenPageFooter != null) { if (pageNumber % 2 == 0 && evenPageFooter != null) {
return evenPageFooter; return evenPageFooter;
} }
return defaultFooter; return defaultFooter;
@ -459,7 +465,7 @@ public class XWPFHeaderFooterPolicy {
lock.setExt(STExt.EDIT); lock.setExt(STExt.EDIT);
CTShape shape = group.addNewShape(); CTShape shape = group.addNewShape();
shape.setId("PowerPlusWaterMarkObject" + idx); shape.setId("PowerPlusWaterMarkObject" + idx);
shape.setSpid("_x0000_s102" + (4+idx)); shape.setSpid("_x0000_s102" + (4 + idx));
shape.setType("#_x0000_t136"); 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.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"); 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

@ -24,49 +24,48 @@ import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTText;
/** /**
* Decorator class for XWPFParagraph allowing to add hyperlinks * Decorator class for XWPFParagraph allowing to add hyperlinks
* found in paragraph to its text. * found in paragraph to its text.
* * <p/>
* Note - adds the hyperlink at the end, not in the right place... * Note - adds the hyperlink at the end, not in the right place...
* *
* @deprecated Use {@link XWPFHyperlinkRun} instead * @deprecated Use {@link XWPFHyperlinkRun} instead
*/ */
@Deprecated @Deprecated
public class XWPFHyperlinkDecorator extends XWPFParagraphDecorator { public class XWPFHyperlinkDecorator extends XWPFParagraphDecorator {
private StringBuffer hyperlinkText; private StringBuffer hyperlinkText;
/** /**
* @param nextDecorator The next decorator to use * @param nextDecorator The next decorator to use
* @param outputHyperlinkUrls Should we output the links too, or just the link text? * @param outputHyperlinkUrls Should we output the links too, or just the link text?
*/ */
public XWPFHyperlinkDecorator(XWPFParagraphDecorator nextDecorator, boolean outputHyperlinkUrls) { public XWPFHyperlinkDecorator(XWPFParagraphDecorator nextDecorator, boolean outputHyperlinkUrls) {
this(nextDecorator.paragraph, nextDecorator, outputHyperlinkUrls); this(nextDecorator.paragraph, nextDecorator, outputHyperlinkUrls);
} }
/** /**
* @param prgrph The paragraph of text to work on * @param prgrph The paragraph of text to work on
* @param outputHyperlinkUrls Should we output the links too, or just the link text? * @param outputHyperlinkUrls Should we output the links too, or just the link text?
*/ */
public XWPFHyperlinkDecorator(XWPFParagraph prgrph, XWPFParagraphDecorator nextDecorator, boolean outputHyperlinkUrls) { public XWPFHyperlinkDecorator(XWPFParagraph prgrph, XWPFParagraphDecorator nextDecorator, boolean outputHyperlinkUrls) {
super(prgrph, nextDecorator); super(prgrph, nextDecorator);
hyperlinkText = new StringBuffer(); hyperlinkText = new StringBuffer();
// loop over hyperlink anchors // loop over hyperlink anchors
for(CTHyperlink link : paragraph.getCTP().getHyperlinkArray()){ for (CTHyperlink link : paragraph.getCTP().getHyperlinkArray()) {
for (CTR r : link.getRArray()) { for (CTR r : link.getRArray()) {
// Loop over text runs // Loop over text runs
for (CTText text : r.getTArray()){ for (CTText text : r.getTArray()) {
hyperlinkText.append(text.getStringValue()); hyperlinkText.append(text.getStringValue());
} }
} }
if(outputHyperlinkUrls && paragraph.getDocument().getHyperlinkByID(link.getId()) != null) { if (outputHyperlinkUrls && paragraph.getDocument().getHyperlinkByID(link.getId()) != null) {
hyperlinkText.append(" <"+paragraph.getDocument().getHyperlinkByID(link.getId()).getURL()+">"); hyperlinkText.append(" <" + paragraph.getDocument().getHyperlinkByID(link.getId()).getURL() + ">");
} }
} }
} }
public String getText() public String getText() {
{ return super.getText() + hyperlinkText;
return super.getText() + hyperlinkText; }
}
} }

View File

@ -22,22 +22,22 @@ import org.apache.poi.xwpf.usermodel.XWPFParagraph;
* Base decorator class for XWPFParagraph * Base decorator class for XWPFParagraph
*/ */
public abstract class XWPFParagraphDecorator { public abstract class XWPFParagraphDecorator {
protected XWPFParagraph paragraph; protected XWPFParagraph paragraph;
protected XWPFParagraphDecorator nextDecorator; protected XWPFParagraphDecorator nextDecorator;
public XWPFParagraphDecorator(XWPFParagraph paragraph) { public XWPFParagraphDecorator(XWPFParagraph paragraph) {
this(paragraph, null); this(paragraph, null);
} }
public XWPFParagraphDecorator(XWPFParagraph paragraph, XWPFParagraphDecorator nextDecorator) { public XWPFParagraphDecorator(XWPFParagraph paragraph, XWPFParagraphDecorator nextDecorator) {
this.paragraph = paragraph; this.paragraph = paragraph;
this.nextDecorator = nextDecorator; this.nextDecorator = nextDecorator;
} }
public String getText() { public String getText() {
if(nextDecorator != null) { if (nextDecorator != null) {
return nextDecorator.getText(); return nextDecorator.getText();
} }
return paragraph.getText(); return paragraph.getText();
} }
} }

View File

@ -19,9 +19,9 @@
--> -->
<html> <html>
<body> <body>
<p>This package contains classes for handling Microsoft .docx <p>This package contains classes for handling Microsoft .docx
Word Processing files, known in POI as XWPF (XML Word Processing Word Processing files, known in POI as XWPF (XML Word Processing
Format). Format).
</p> </p>
</body> </body>
</html> </html>

View File

@ -16,99 +16,89 @@
==================================================================== */ ==================================================================== */
package org.apache.poi.xwpf.usermodel; package org.apache.poi.xwpf.usermodel;
import java.util.List;
import org.apache.poi.POIXMLDocumentPart; import org.apache.poi.POIXMLDocumentPart;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTSdtPr; import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTSdtPr;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTString; import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTString;
/** /**
* Experimental abstract class that is a base for XWPFSDT and XWPFSDTCell * Experimental abstract class that is a base for XWPFSDT and XWPFSDTCell
* * <p/>
* WARNING - APIs expected to change rapidly. * WARNING - APIs expected to change rapidly.
* * <p/>
* These classes have so far been built only for read-only processing. * These classes have so far been built only for read-only processing.
*
*/ */
public abstract class AbstractXWPFSDT implements ISDTContents { public abstract class AbstractXWPFSDT implements ISDTContents {
private final String title; private final String title;
private final String tag; private final String tag;
private final IBody part; private final IBody part;
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
public AbstractXWPFSDT(CTSdtPr pr, IBody part){ public AbstractXWPFSDT(CTSdtPr pr, IBody part) {
CTString[] aliases = pr.getAliasArray(); CTString[] aliases = pr.getAliasArray();
if (aliases != null && aliases.length > 0){ if (aliases != null && aliases.length > 0) {
title = aliases[0].getVal(); title = aliases[0].getVal();
} else { } else {
title = ""; title = "";
} }
CTString[] tags = pr.getTagArray(); CTString[] tags = pr.getTagArray();
if (tags != null && tags.length > 0){ if (tags != null && tags.length > 0) {
tag = tags[0].getVal(); tag = tags[0].getVal();
} else { } else {
tag = ""; tag = "";
} }
this.part = part; this.part = part;
} }
/** /**
* * @return first SDT Title
* @return first SDT Title */
*/ public String getTitle() {
public String getTitle(){ return title;
return title; }
}
/** /**
* * @return first SDT Tag
* @return first SDT Tag */
*/ public String getTag() {
public String getTag(){ return tag;
return tag; }
}
/** /**
* * @return the content object
* @return the content object */
*/ public abstract ISDTContent getContent();
public abstract ISDTContent getContent();
/** /**
* * @return null
* @return null */
*/ public IBody getBody() {
public IBody getBody() { return null;
return null; }
}
/** /**
* * @return document part
* @return document part */
*/ public POIXMLDocumentPart getPart() {
public POIXMLDocumentPart getPart() { return part.getPart();
return part.getPart(); }
}
/** /**
* * @return partType
* @return partType */
*/ public BodyType getPartType() {
public BodyType getPartType() { return BodyType.CONTENTCONTROL;
return BodyType.CONTENTCONTROL; }
}
/** /**
* * @return element type
* @return element type */
*/ public BodyElementType getElementType() {
public BodyElementType getElementType() { return BodyElementType.CONTENTCONTROL;
return BodyElementType.CONTENTCONTROL; }
}
public XWPFDocument getDocument() { public XWPFDocument getDocument() {
return part.getXWPFDocument(); return part.getXWPFDocument();
} }
} }

View File

@ -24,12 +24,11 @@ package org.apache.poi.xwpf.usermodel;
* <p> * <p>
* // TODO insert Javadoc here! * // TODO insert Javadoc here!
* </p> * </p>
* @author epp
* *
* @author epp
*/ */
public enum BodyElementType { public enum BodyElementType {
CONTENTCONTROL, CONTENTCONTROL,
PARAGRAPH, PARAGRAPH,
TABLE, TABLE,
} }

View File

@ -32,8 +32,9 @@ import java.util.Map;
* specified on any object which allows a border, however, art borders may only * 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 * be used as a border at the page level - the borders under the pgBorders
* element * element
*</li> * </li>
* </ul> * </ul>
*
* @author Gisella Bronzetti * @author Gisella Bronzetti
*/ */
public enum Borders { public enum Borders {
@ -599,23 +600,20 @@ public enum Borders {
ZIG_ZAG_STITCH(191); 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>(); private static Map<Integer, Borders> imap = new HashMap<Integer, Borders>();
static { static {
for (Borders p : values()) { for (Borders p : values()) {
imap.put(Integer.valueOf(p.getValue()), p); imap.put(Integer.valueOf(p.getValue()), p);
} }
} }
private final int value;
private Borders(int val) {
value = val;
}
public static Borders valueOf(int type) { public static Borders valueOf(int type) {
Borders pBorder = imap.get(Integer.valueOf(type)); Borders pBorder = imap.get(Integer.valueOf(type));
if (pBorder == null) { if (pBorder == null) {
@ -623,4 +621,8 @@ public enum Borders {
} }
return pBorder; return pBorder;
} }
public int getValue() {
return value;
}
} }

View File

@ -33,7 +33,7 @@ public enum BreakClear {
* line in the WordprocessingML document, regardless of its position left to * line in the WordprocessingML document, regardless of its position left to
* right or the presence of any floating objects which intersect with the * right or the presence of any floating objects which intersect with the
* line, * line,
* * <p/>
* This is the setting for a typical line break in a document. * This is the setting for a typical line break in a document.
*/ */
@ -83,28 +83,29 @@ public enum BreakClear {
*/ */
ALL(4); 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 final int value;
private BreakClear(int val) { private BreakClear(int val) {
value = 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) { public static BreakClear valueOf(int type) {
BreakClear bType = imap.get(new Integer(type)); BreakClear bType = imap.get(new Integer(type));
if (bType == null) if (bType == null)
throw new IllegalArgumentException("Unknown break clear type: " throw new IllegalArgumentException("Unknown break clear type: "
+ type); + type);
return bType; return bType;
}
public int getValue() {
return value;
} }
} }

View File

@ -56,28 +56,29 @@ public enum BreakType {
*/ */
TEXT_WRAPPING(3); 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 final int value;
private BreakType(int val) { private BreakType(int val) {
value = 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) { public static BreakType valueOf(int type) {
BreakType bType = imap.get(new Integer(type)); BreakType bType = imap.get(new Integer(type));
if (bType == null) if (bType == null)
throw new IllegalArgumentException("Unknown break type: " throw new IllegalArgumentException("Unknown break type: "
+ type); + type);
return bType; return bType;
}
public int getValue() {
return value;
} }
} }

View File

@ -17,25 +17,39 @@
package org.apache.poi.xwpf.usermodel; package org.apache.poi.xwpf.usermodel;
public interface Document { public interface Document {
/** Extended windows meta file */ /**
* Extended windows meta file
*/
public static final int PICTURE_TYPE_EMF = 2; public static final int PICTURE_TYPE_EMF = 2;
/** Windows Meta File */ /**
* Windows Meta File
*/
public static final int PICTURE_TYPE_WMF = 3; public static final int PICTURE_TYPE_WMF = 3;
/** Mac PICT format */ /**
* Mac PICT format
*/
public static final int PICTURE_TYPE_PICT = 4; public static final int PICTURE_TYPE_PICT = 4;
/** JPEG format */ /**
* JPEG format
*/
public static final int PICTURE_TYPE_JPEG = 5; public static final int PICTURE_TYPE_JPEG = 5;
/** PNG format */ /**
* PNG format
*/
public static final int PICTURE_TYPE_PNG = 6; public static final int PICTURE_TYPE_PNG = 6;
/** Device independent bitmap */ /**
* Device independent bitmap
*/
public static final int PICTURE_TYPE_DIB = 7; public static final int PICTURE_TYPE_DIB = 7;
/** GIF image format */ /**
* GIF image format
*/
public static final int PICTURE_TYPE_GIF = 8; public static final int PICTURE_TYPE_GIF = 8;
/** /**

View File

@ -30,7 +30,7 @@ import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTc;
* can contain collections of Paragraphs and Tables. It provides a * can contain collections of Paragraphs and Tables. It provides a
* common way to work with these and their contents.</p> * common way to work with these and their contents.</p>
* <p>Typically, this is something like a XWPFDocument, or one of * <p>Typically, this is something like a XWPFDocument, or one of
* the parts in it like XWPFHeader, XWPFFooter, XWPFTableCell * the parts in it like XWPFHeader, XWPFFooter, XWPFTableCell
* </p> * </p>
*/ */
public interface IBody { public interface IBody {
@ -38,6 +38,7 @@ public interface IBody {
* returns the Part, to which the body belongs, which you need for adding relationship to other parts * 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 * Actually it is needed of the class XWPFTableCell. Because you have to know to which part the tableCell
* belongs. * belongs.
*
* @return the Part, to which the body belongs * @return the Part, to which the body belongs
*/ */
public POIXMLDocumentPart getPart(); public POIXMLDocumentPart getPart();
@ -45,26 +46,27 @@ public interface IBody {
/** /**
* get the PartType of the body, for example * get the PartType of the body, for example
* DOCUMENT, HEADER, FOOTER, FOOTNOTE, * DOCUMENT, HEADER, FOOTER, FOOTNOTE,
*
* @return the PartType of the body * @return the PartType of the body
*/ */
public BodyType getPartType(); public BodyType getPartType();
/** /**
* Returns an Iterator with paragraphs and tables, * Returns an Iterator with paragraphs and tables,
* in the order that they occur in the text. * in the order that they occur in the text.
*/ */
public List<IBodyElement> getBodyElements(); public List<IBodyElement> getBodyElements();
/** /**
* Returns the paragraph(s) that holds * Returns the paragraph(s) that holds
* the text of the header or footer. * the text of the header or footer.
*/ */
public List<XWPFParagraph> getParagraphs(); public List<XWPFParagraph> getParagraphs();
/** /**
* Return the table(s) that holds the text * Return the table(s) that holds the text
* of the IBodyPart, for complex cases * of the IBodyPart, for complex cases
* where a paragraph isn't used. * where a paragraph isn't used.
*/ */
public List<XWPFTable> getTables(); public List<XWPFTable> getTables();
@ -72,9 +74,10 @@ public interface IBody {
* if there is a corresponding {@link XWPFParagraph} of the parameter ctTable in the paragraphList of this header or footer * 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 * 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 * @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 * @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);
@ -82,6 +85,7 @@ public interface IBody {
* if there is a corresponding {@link XWPFTable} of the parameter ctTable in the tableList of this header * if there is a corresponding {@link XWPFTable} of the parameter ctTable in the tableList of this header
* the method will return this table * 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 * @param ctTable
*/ */
public XWPFTable getTable(CTTbl ctTable); public XWPFTable getTable(CTTbl ctTable);
@ -97,19 +101,22 @@ public interface IBody {
public XWPFTable getTableArray(int pos); public XWPFTable getTableArray(int pos);
/** /**
*inserts a new paragraph at position of the cursor * inserts a new paragraph at position of the cursor
*
* @param cursor * @param cursor
*/ */
public XWPFParagraph insertNewParagraph(XmlCursor cursor); public XWPFParagraph insertNewParagraph(XmlCursor cursor);
/** /**
* inserts a new Table at the cursor position. * inserts a new Table at the cursor position.
*
* @param cursor * @param cursor
*/ */
public XWPFTable insertNewTbl(XmlCursor cursor); public XWPFTable insertNewTbl(XmlCursor cursor);
/** /**
* inserts a new Table at position pos * inserts a new Table at position pos
*
* @param pos * @param pos
* @param table * @param table
*/ */
@ -117,6 +124,7 @@ public interface IBody {
/** /**
* returns the TableCell to which the Table belongs * returns the TableCell to which the Table belongs
*
* @param cell * @param cell
*/ */
public XWPFTableCell getTableCell(CTTc cell); public XWPFTableCell getTableCell(CTTc cell);

View File

@ -21,12 +21,15 @@ import org.apache.poi.POIXMLDocumentPart;
/** /**
* 9 Jan 2010 * 9 Jan 2010
* @author Philipp Epp
* *
* @author Philipp Epp
*/ */
public interface IBodyElement{ public interface IBodyElement {
IBody getBody(); IBody getBody();
POIXMLDocumentPart getPart(); POIXMLDocumentPart getPart();
BodyType getPartType();
BodyElementType getElementType(); BodyType getPartType();
BodyElementType getElementType();
} }

View File

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

View File

@ -22,10 +22,11 @@ import org.apache.poi.wp.usermodel.Paragraph;
/** /**
* Simple interface describing both {@link XWPFParagraph} * Simple interface describing both {@link XWPFParagraph}
* and {@link XWPFSDT} * and {@link XWPFSDT}
* * <p/>
* TODO Should this be based on / extend {@link Paragraph}? * TODO Should this be based on / extend {@link Paragraph}?
*/ */
public interface IRunBody { public interface IRunBody {
public XWPFDocument getDocument(); public XWPFDocument getDocument();
public POIXMLDocumentPart getPart();
public POIXMLDocumentPart getPart();
} }

View File

@ -20,11 +20,10 @@ import org.apache.poi.wp.usermodel.CharacterRun;
/** /**
* Common interface for things that can occur * Common interface for things that can occur
* where a run (text with common stylings) can, * where a run (text with common stylings) can,
* eg {@link XWPFRun} or {@link XWPFSDT}. * eg {@link XWPFRun} or {@link XWPFSDT}.
* TODO More methods to follow shortly! * TODO More methods to follow shortly!
* * <p/>
* TODO Make this based on {@link CharacterRun} * TODO Make this based on {@link CharacterRun}
*/ */
public interface IRunElement { public interface IRunElement {}
}

View File

@ -19,14 +19,13 @@ package org.apache.poi.xwpf.usermodel;
/** /**
* Experimental interface to offer rudimentary read-only processing of * Experimental interface to offer rudimentary read-only processing of
* of the contentblock of an SDT/ContentControl. * of the contentblock of an SDT/ContentControl.
* * <p/>
* * <p/>
* * <p/>
* WARNING - APIs expected to change rapidly * WARNING - APIs expected to change rapidly
*
*/ */
public interface ISDTContent { public interface ISDTContent {
public String getText(); public String getText();

View File

@ -18,8 +18,8 @@ package org.apache.poi.xwpf.usermodel;
/** /**
* Interface for anything that can be within an SDT: * Interface for anything that can be within an SDT:
* {@link XWPFRun}, {@link XWPFTable}, {@link XWPFParagraph}, * {@link XWPFRun}, {@link XWPFTable}, {@link XWPFParagraph},
* {@link XWPFSDT} etc * {@link XWPFSDT} etc
*/ */
public interface ISDTContents { public interface ISDTContents {
} }

View File

@ -49,27 +49,28 @@ public enum LineSpacingRule {
AT_LEAST(3); 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 final int value;
private LineSpacingRule(int val) { private LineSpacingRule(int val) {
value = 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) { public static LineSpacingRule valueOf(int type) {
LineSpacingRule lineType = imap.get(new Integer(type)); LineSpacingRule lineType = imap.get(new Integer(type));
if (lineType == null) if (lineType == null)
throw new IllegalArgumentException("Unknown line type: " + type); throw new IllegalArgumentException("Unknown line type: " + type);
return lineType; return lineType;
}
public int getValue() {
return value;
} }
} }

View File

@ -40,27 +40,28 @@ public enum ParagraphAlignment {
LOW_KASHIDA(9), LOW_KASHIDA(9),
THAI_DISTRIBUTE(10); 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>(); private static Map<Integer, ParagraphAlignment> imap = new HashMap<Integer, ParagraphAlignment>();
static{
static {
for (ParagraphAlignment p : values()) { for (ParagraphAlignment p : values()) {
imap.put(new Integer(p.getValue()), p); imap.put(new Integer(p.getValue()), p);
} }
} }
public static ParagraphAlignment valueOf(int type){ private final int value;
private ParagraphAlignment(int val) {
value = val;
}
public static ParagraphAlignment valueOf(int type) {
ParagraphAlignment err = imap.get(new Integer(type)); ParagraphAlignment err = imap.get(new Integer(type));
if(err == null) throw new IllegalArgumentException("Unknown paragraph alignment: " + type); if (err == null) throw new IllegalArgumentException("Unknown paragraph alignment: " + type);
return err; return err;
} }
public int getValue() {
return value;
}
} }

View File

@ -20,46 +20,44 @@ package org.apache.poi.xwpf.usermodel;
/** /**
* postion of a character in a paragrapho * postion of a character in a paragrapho
* 1st RunPositon * 1st RunPositon
* 2nd TextPosition * 2nd TextPosition
* 3rd CharacterPosition * 3rd CharacterPosition
* */
*
*/
public class PositionInParagraph { public class PositionInParagraph {
private int posRun = 0, posText = 0, posChar = 0; private int posRun = 0, posText = 0, posChar = 0;
public PositionInParagraph(){ public PositionInParagraph() {
} }
public PositionInParagraph(int posRun, int posText, int posChar){ public PositionInParagraph(int posRun, int posText, int posChar) {
this.posRun=posRun; this.posRun = posRun;
this.posChar=posChar; this.posChar = posChar;
this.posText= posText; this.posText = posText;
} }
public int getRun() { public int getRun() {
return posRun; return posRun;
} }
public void setRun(int beginRun) { public void setRun(int beginRun) {
this.posRun = beginRun; this.posRun = beginRun;
} }
public int getText() { public int getText() {
return posText; return posText;
} }
public void setText(int beginText) { public void setText(int beginText) {
this.posText = beginText; this.posText = beginText;
} }
public int getChar() { public int getChar() {
return posChar; return posChar;
} }
public void setChar(int beginChar) { public void setChar(int beginChar) {
this.posChar = beginChar; this.posChar = beginChar;
} }
} }

View File

@ -41,82 +41,82 @@ import org.openxmlformats.schemas.wordprocessingml.x2006.main.STTheme;
public class TOC { public class TOC {
CTSdtBlock block; CTSdtBlock block;
public TOC() { public TOC() {
this(CTSdtBlock.Factory.newInstance()); this(CTSdtBlock.Factory.newInstance());
} }
public TOC(CTSdtBlock block) { public TOC(CTSdtBlock block) {
this.block = block; this.block = block;
CTSdtPr sdtPr = block.addNewSdtPr(); CTSdtPr sdtPr = block.addNewSdtPr();
CTDecimalNumber id = sdtPr.addNewId(); CTDecimalNumber id = sdtPr.addNewId();
id.setVal(new BigInteger("4844945")); id.setVal(new BigInteger("4844945"));
sdtPr.addNewDocPartObj().addNewDocPartGallery().setVal("Table of contents"); sdtPr.addNewDocPartObj().addNewDocPartGallery().setVal("Table of contents");
CTSdtEndPr sdtEndPr = block.addNewSdtEndPr(); CTSdtEndPr sdtEndPr = block.addNewSdtEndPr();
CTRPr rPr = sdtEndPr.addNewRPr(); CTRPr rPr = sdtEndPr.addNewRPr();
CTFonts fonts = rPr.addNewRFonts(); CTFonts fonts = rPr.addNewRFonts();
fonts.setAsciiTheme(STTheme.MINOR_H_ANSI); fonts.setAsciiTheme(STTheme.MINOR_H_ANSI);
fonts.setEastAsiaTheme(STTheme.MINOR_H_ANSI); fonts.setEastAsiaTheme(STTheme.MINOR_H_ANSI);
fonts.setHAnsiTheme(STTheme.MINOR_H_ANSI); fonts.setHAnsiTheme(STTheme.MINOR_H_ANSI);
fonts.setCstheme(STTheme.MINOR_BIDI); fonts.setCstheme(STTheme.MINOR_BIDI);
rPr.addNewB().setVal(STOnOff.OFF); rPr.addNewB().setVal(STOnOff.OFF);
rPr.addNewBCs().setVal(STOnOff.OFF); rPr.addNewBCs().setVal(STOnOff.OFF);
rPr.addNewColor().setVal("auto"); rPr.addNewColor().setVal("auto");
rPr.addNewSz().setVal(new BigInteger("24")); rPr.addNewSz().setVal(new BigInteger("24"));
rPr.addNewSzCs().setVal(new BigInteger("24")); rPr.addNewSzCs().setVal(new BigInteger("24"));
CTSdtContentBlock content = block.addNewSdtContent(); CTSdtContentBlock content = block.addNewSdtContent();
CTP p = content.addNewP(); CTP p = content.addNewP();
p.setRsidR("00EF7E24".getBytes()); p.setRsidR("00EF7E24".getBytes());
p.setRsidRDefault("00EF7E24".getBytes()); p.setRsidRDefault("00EF7E24".getBytes());
p.addNewPPr().addNewPStyle().setVal("TOCHeading"); p.addNewPPr().addNewPStyle().setVal("TOCHeading");
p.addNewR().addNewT().setStringValue("Table of Contents"); p.addNewR().addNewT().setStringValue("Table of Contents");
} }
@Internal @Internal
public CTSdtBlock getBlock() { public CTSdtBlock getBlock() {
return this.block; return this.block;
} }
public void addRow(int level, String title, int page, String bookmarkRef) { public void addRow(int level, String title, int page, String bookmarkRef) {
CTSdtContentBlock contentBlock = this.block.getSdtContent(); CTSdtContentBlock contentBlock = this.block.getSdtContent();
CTP p = contentBlock.addNewP(); CTP p = contentBlock.addNewP();
p.setRsidR("00EF7E24".getBytes()); p.setRsidR("00EF7E24".getBytes());
p.setRsidRDefault("00EF7E24".getBytes()); p.setRsidRDefault("00EF7E24".getBytes());
CTPPr pPr = p.addNewPPr(); CTPPr pPr = p.addNewPPr();
pPr.addNewPStyle().setVal("TOC" + level); pPr.addNewPStyle().setVal("TOC" + level);
CTTabs tabs = pPr.addNewTabs(); CTTabs tabs = pPr.addNewTabs();
CTTabStop tab = tabs.addNewTab(); CTTabStop tab = tabs.addNewTab();
tab.setVal(STTabJc.RIGHT); tab.setVal(STTabJc.RIGHT);
tab.setLeader(STTabTlc.DOT); tab.setLeader(STTabTlc.DOT);
tab.setPos(new BigInteger("8290")); tab.setPos(new BigInteger("8290"));
pPr.addNewRPr().addNewNoProof(); pPr.addNewRPr().addNewNoProof();
CTR run = p.addNewR(); CTR run = p.addNewR();
run.addNewRPr().addNewNoProof(); run.addNewRPr().addNewNoProof();
run.addNewT().setStringValue(title); run.addNewT().setStringValue(title);
run = p.addNewR(); run = p.addNewR();
run.addNewRPr().addNewNoProof(); run.addNewRPr().addNewNoProof();
run.addNewTab(); run.addNewTab();
run = p.addNewR(); run = p.addNewR();
run.addNewRPr().addNewNoProof(); run.addNewRPr().addNewNoProof();
run.addNewFldChar().setFldCharType(STFldCharType.BEGIN); run.addNewFldChar().setFldCharType(STFldCharType.BEGIN);
// pageref run // pageref run
run = p.addNewR(); run = p.addNewR();
run.addNewRPr().addNewNoProof(); run.addNewRPr().addNewNoProof();
CTText text = run.addNewInstrText(); CTText text = run.addNewInstrText();
text.setSpace(Space.PRESERVE); text.setSpace(Space.PRESERVE);
// bookmark reference // bookmark reference
text.setStringValue(" PAGEREF _Toc" + bookmarkRef + " \\h "); text.setStringValue(" PAGEREF _Toc" + bookmarkRef + " \\h ");
p.addNewR().addNewRPr().addNewNoProof(); p.addNewR().addNewRPr().addNewNoProof();
run = p.addNewR(); run = p.addNewR();
run.addNewRPr().addNewNoProof(); run.addNewRPr().addNewNoProof();
run.addNewFldChar().setFldCharType(STFldCharType.SEPARATE); run.addNewFldChar().setFldCharType(STFldCharType.SEPARATE);
// page number run // page number run
run = p.addNewR(); run = p.addNewR();
run.addNewRPr().addNewNoProof(); run.addNewRPr().addNewNoProof();
run.addNewT().setStringValue(Integer.valueOf(page).toString()); run.addNewT().setStringValue(Integer.valueOf(page).toString());
run = p.addNewR(); run = p.addNewR();
run.addNewRPr().addNewNoProof(); run.addNewRPr().addNewNoProof();
run.addNewFldChar().setFldCharType(STFldCharType.END); run.addNewFldChar().setFldCharType(STFldCharType.END);
} }
} }

View File

@ -52,26 +52,27 @@ public enum TextAlignment {
*/ */
AUTO(5); 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 final int value;
private TextAlignment(int val){ private TextAlignment(int val) {
value = val; value = val;
} }
public int getValue(){ public static TextAlignment valueOf(int type) {
return value; TextAlignment align = imap.get(new Integer(type));
if (align == null) throw new IllegalArgumentException("Unknown text alignment: " + type);
return align;
} }
private static Map<Integer, TextAlignment> imap = new HashMap<Integer, TextAlignment>(); public int getValue() {
static{ return value;
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;
} }
} }

View File

@ -19,80 +19,81 @@ package org.apache.poi.xwpf.usermodel;
/** /**
* saves the begin and end position of a text in a Paragraph * saves the begin and end position of a text in a Paragraph
*/ */
public class TextSegement { public class TextSegement {
private PositionInParagraph beginPos; private PositionInParagraph beginPos;
private PositionInParagraph endPos; private PositionInParagraph endPos;
public TextSegement(){ public TextSegement() {
this.beginPos = new PositionInParagraph(); this.beginPos = new PositionInParagraph();
this. endPos = new PositionInParagraph(); this.endPos = new PositionInParagraph();
} }
public TextSegement(int beginRun, int endRun, int beginText, int endText, int beginChar, int endChar){ public TextSegement(int beginRun, int endRun, int beginText, int endText, int beginChar, int endChar) {
PositionInParagraph beginPos = new PositionInParagraph(beginRun, beginText, beginChar); PositionInParagraph beginPos = new PositionInParagraph(beginRun, beginText, beginChar);
PositionInParagraph endPos = new PositionInParagraph(endRun, endText, endChar); PositionInParagraph endPos = new PositionInParagraph(endRun, endText, endChar);
this.beginPos = beginPos; this.beginPos = beginPos;
this.endPos = endPos; this.endPos = endPos;
} }
public TextSegement(PositionInParagraph beginPos, PositionInParagraph endPos){ public TextSegement(PositionInParagraph beginPos, PositionInParagraph endPos) {
this.beginPos = beginPos; this.beginPos = beginPos;
this.endPos = endPos; this.endPos = endPos;
} }
public PositionInParagraph getBeginPos(){ public PositionInParagraph getBeginPos() {
return beginPos; return beginPos;
} }
public PositionInParagraph getEndPos(){ public PositionInParagraph getEndPos() {
return endPos; return endPos;
} }
public int getBeginRun(){ public int getBeginRun() {
return beginPos.getRun(); return beginPos.getRun();
} }
public void setBeginRun(int beginRun){ public void setBeginRun(int beginRun) {
beginPos.setRun(beginRun); beginPos.setRun(beginRun);
} }
public int getBeginText(){ public int getBeginText() {
return beginPos.getText(); return beginPos.getText();
} }
public void setBeginText(int beginText){ public void setBeginText(int beginText) {
beginPos.setText(beginText); beginPos.setText(beginText);
} }
public int getBeginChar(){ public int getBeginChar() {
return beginPos.getChar(); return beginPos.getChar();
} }
public void setBeginChar(int beginChar){ public void setBeginChar(int beginChar) {
beginPos.setChar(beginChar); beginPos.setChar(beginChar);
} }
public int getEndRun(){
return endPos.getRun();
}
public void setEndRun(int endRun){ public int getEndRun() {
endPos.setRun(endRun); return endPos.getRun();
} }
public int getEndText(){ public void setEndRun(int endRun) {
return endPos.getText(); endPos.setRun(endRun);
} }
public void setEndText(int endText){ public int getEndText() {
endPos.setText(endText); return endPos.getText();
} }
public int getEndChar(){ public void setEndText(int endText) {
return endPos.getChar(); endPos.setText(endText);
} }
public void setEndChar(int endChar){ public int getEndChar() {
endPos.setChar(endChar); return endPos.getChar();
} }
public void setEndChar(int endChar) {
endPos.setChar(endChar);
}
} }

View File

@ -135,28 +135,29 @@ public enum UnderlinePatterns {
*/ */
NONE(18); 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 final int value;
private UnderlinePatterns(int val) { private UnderlinePatterns(int val) {
value = 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) { public static UnderlinePatterns valueOf(int type) {
UnderlinePatterns align = imap.get(new Integer(type)); UnderlinePatterns align = imap.get(new Integer(type));
if (align == null) if (align == null)
throw new IllegalArgumentException("Unknown underline pattern: " throw new IllegalArgumentException("Unknown underline pattern: "
+ type); + type);
return align; return align;
}
public int getValue() {
return value;
} }
} }

View File

@ -47,28 +47,29 @@ public enum VerticalAlign {
*/ */
SUBSCRIPT(3); 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 final int value;
private VerticalAlign(int val) { private VerticalAlign(int val) {
value = 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) { public static VerticalAlign valueOf(int type) {
VerticalAlign align = imap.get(new Integer(type)); VerticalAlign align = imap.get(new Integer(type));
if (align == null) if (align == null)
throw new IllegalArgumentException("Unknown vertical alignment: " throw new IllegalArgumentException("Unknown vertical alignment: "
+ type); + type);
return align; return align;
}
public int getValue() {
return value;
} }
} }

View File

@ -21,39 +21,40 @@ import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTAbstractNum;
/** /**
* @author Philipp Epp * @author Philipp Epp
*
*/ */
public class XWPFAbstractNum { public class XWPFAbstractNum {
private CTAbstractNum ctAbstractNum; protected XWPFNumbering numbering;
protected XWPFNumbering numbering; private CTAbstractNum ctAbstractNum;
protected XWPFAbstractNum() { protected XWPFAbstractNum() {
this.ctAbstractNum = null; this.ctAbstractNum = null;
this.numbering = null; this.numbering = null;
} }
public XWPFAbstractNum(CTAbstractNum abstractNum){
this.ctAbstractNum = abstractNum;
}
public XWPFAbstractNum(CTAbstractNum ctAbstractNum, XWPFNumbering numbering){ public XWPFAbstractNum(CTAbstractNum abstractNum) {
this.ctAbstractNum = ctAbstractNum; this.ctAbstractNum = abstractNum;
this.numbering = numbering; }
}
public CTAbstractNum getAbstractNum(){
return ctAbstractNum;
}
public XWPFNumbering getNumbering(){ public XWPFAbstractNum(CTAbstractNum ctAbstractNum, XWPFNumbering numbering) {
return numbering; this.ctAbstractNum = ctAbstractNum;
} this.numbering = numbering;
}
public CTAbstractNum getCTAbstractNum(){ public CTAbstractNum getAbstractNum() {
return ctAbstractNum; return ctAbstractNum;
} }
public void setNumbering(XWPFNumbering numbering){ public XWPFNumbering getNumbering() {
this.numbering = numbering; return numbering;
} }
public void setNumbering(XWPFNumbering numbering) {
this.numbering = numbering;
}
public CTAbstractNum getCTAbstractNum() {
return ctAbstractNum;
}
} }

View File

@ -22,41 +22,34 @@ import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTP;
/** /**
* Sketch of XWPF comment class * 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 id;
protected String author; protected String author;
protected StringBuffer text; protected StringBuffer text;
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
public XWPFComment(CTComment comment, XWPFDocument document) public XWPFComment(CTComment comment, XWPFDocument document) {
{
text = new StringBuffer(); text = new StringBuffer();
id = comment.getId().toString(); id = comment.getId().toString();
author = comment.getAuthor(); author = comment.getAuthor();
for(CTP ctp : comment.getPArray()) for (CTP ctp : comment.getPArray()) {
{
XWPFParagraph p = new XWPFParagraph(ctp, document); XWPFParagraph p = new XWPFParagraph(ctp, document);
text.append(p.getText()); text.append(p.getText());
} }
} }
public String getId() public String getId() {
{
return id; return id;
} }
public String getAuthor() public String getAuthor() {
{
return author; return author;
} }
public String getText() public String getText() {
{
return text.toString(); return text.toString();
} }
} }

View File

@ -76,23 +76,17 @@ import org.openxmlformats.schemas.wordprocessingml.x2006.main.StylesDocument;
/** /**
* <p>High(ish) level class for working with .docx files.</p> * <p>High(ish) level class for working with .docx files.</p>
* * <p/>
* <p>This class tries to hide some of the complexity * <p>This class tries to hide some of the complexity
* of the underlying file format, but as it's not a * of the underlying file format, but as it's not a
* mature and stable API yet, certain parts of the * mature and stable API yet, certain parts of the
* XML structure come through. You'll therefore almost * XML structure come through. You'll therefore almost
* certainly need to refer to the OOXML specifications * certainly need to refer to the OOXML specifications
* from * from
* http://www.ecma-international.org/publications/standards/Ecma-376.htm * http://www.ecma-international.org/publications/standards/Ecma-376.htm
* at some point in your use.</p> * at some point in your use.</p>
*/ */
public class XWPFDocument extends POIXMLDocument implements Document, IBody { public class XWPFDocument extends POIXMLDocument implements Document, IBody {
private CTDocument1 ctDocument;
private XWPFSettings settings;
/**
* Keeps track on all id-values used in this document and included parts, like headers, footers, etc.
*/
private IdentifierManager drawingIdManager = new IdentifierManager(0L,4294967295L);
protected List<XWPFFooter> footers = new ArrayList<XWPFFooter>(); protected List<XWPFFooter> footers = new ArrayList<XWPFFooter>();
protected List<XWPFHeader> headers = new ArrayList<XWPFHeader>(); protected List<XWPFHeader> headers = new ArrayList<XWPFHeader>();
protected List<XWPFComment> comments = new ArrayList<XWPFComment>(); protected List<XWPFComment> comments = new ArrayList<XWPFComment>();
@ -107,8 +101,15 @@ public class XWPFDocument extends POIXMLDocument implements Document, IBody {
protected XWPFNumbering numbering; protected XWPFNumbering numbering;
protected XWPFStyles styles; protected XWPFStyles styles;
protected XWPFFootnotes footnotes; protected XWPFFootnotes footnotes;
private CTDocument1 ctDocument;
/** Handles the joy of different headers/footers for different pages */ private XWPFSettings settings;
/**
* Keeps track on all id-values used in this document and included parts, like headers, footers, etc.
*/
private IdentifierManager drawingIdManager = new IdentifierManager(0L, 4294967295L);
/**
* Handles the joy of different headers/footers for different pages
*/
private XWPFHeaderFooterPolicy headerFooterPolicy; private XWPFHeaderFooterPolicy headerFooterPolicy;
public XWPFDocument(OPCPackage pkg) throws IOException { public XWPFDocument(OPCPackage pkg) throws IOException {
@ -125,11 +126,32 @@ public class XWPFDocument extends POIXMLDocument implements Document, IBody {
load(XWPFFactory.getInstance()); load(XWPFFactory.getInstance());
} }
public XWPFDocument(){ public XWPFDocument() {
super(newPackage()); super(newPackage());
onDocumentCreate(); onDocumentCreate();
} }
/**
* Create a new WordProcessingML package and setup the default minimal content
*/
protected static OPCPackage newPackage() {
try {
OPCPackage pkg = OPCPackage.create(new ByteArrayOutputStream());
// Main part
PackagePartName corePartName = PackagingURIHelper.createPartName(XWPFRelation.DOCUMENT.getDefaultFileName());
// Create main part relationship
pkg.addRelationship(corePartName, TargetMode.INTERNAL, PackageRelationshipTypes.CORE_DOCUMENT);
// Create main document part
pkg.createPart(corePartName, XWPFRelation.DOCUMENT.getContentType());
pkg.getPackageProperties().setCreatorProperty(DOCUMENT_CREATOR);
return pkg;
} catch (Exception e) {
throw new POIXMLException(e);
}
}
@Override @Override
protected void onDocumentRead() throws IOException { protected void onDocumentRead() throws IOException {
try { try {
@ -152,11 +174,11 @@ public class XWPFDocument extends POIXMLDocument implements Document, IBody {
XWPFTable t = new XWPFTable((CTTbl) o, this); XWPFTable t = new XWPFTable((CTTbl) o, this);
bodyElements.add(t); bodyElements.add(t);
tables.add(t); tables.add(t);
} else if (o instanceof CTSdtBlock){ } else if (o instanceof CTSdtBlock) {
XWPFSDT c = new XWPFSDT((CTSdtBlock)o, this); XWPFSDT c = new XWPFSDT((CTSdtBlock) o, this);
bodyElements.add(c); bodyElements.add(c);
contentControls.add(c); contentControls.add(c);
} }
} }
cursor.dispose(); cursor.dispose();
@ -205,7 +227,7 @@ public class XWPFDocument extends POIXMLDocument implements Document, IBody {
Method onDocumentRead = gp.getClass().getDeclaredMethod("onDocumentRead"); Method onDocumentRead = gp.getClass().getDeclaredMethod("onDocumentRead");
onDocumentRead.setAccessible(true); onDocumentRead.setAccessible(true);
onDocumentRead.invoke(gp); onDocumentRead.invoke(gp);
} catch(Exception e) { } catch (Exception e) {
throw new POIXMLException(e); throw new POIXMLException(e);
} }
} }
@ -217,59 +239,38 @@ public class XWPFDocument extends POIXMLDocument implements Document, IBody {
} }
} }
private void initHyperlinks(){ private void initHyperlinks() {
// Get the hyperlinks // Get the hyperlinks
// TODO: make me optional/separated in private function // TODO: make me optional/separated in private function
try { try {
Iterator<PackageRelationship> relIter = Iterator<PackageRelationship> relIter =
getPackagePart().getRelationshipsByType(XWPFRelation.HYPERLINK.getRelation()).iterator(); getPackagePart().getRelationshipsByType(XWPFRelation.HYPERLINK.getRelation()).iterator();
while(relIter.hasNext()) { while (relIter.hasNext()) {
PackageRelationship rel = relIter.next(); PackageRelationship rel = relIter.next();
hyperlinks.add(new XWPFHyperlink(rel.getId(), rel.getTargetURI().toString())); hyperlinks.add(new XWPFHyperlink(rel.getId(), rel.getTargetURI().toString()));
} }
} catch (InvalidFormatException e){ } catch (InvalidFormatException e) {
throw new POIXMLException(e); throw new POIXMLException(e);
} }
} }
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
private void initFootnotes() throws XmlException, IOException { private void initFootnotes() throws XmlException, IOException {
for(POIXMLDocumentPart p : getRelations()){ for (POIXMLDocumentPart p : getRelations()) {
String relation = p.getPackageRelationship().getRelationshipType(); String relation = p.getPackageRelationship().getRelationshipType();
if (relation.equals(XWPFRelation.FOOTNOTE.getRelation())) { if (relation.equals(XWPFRelation.FOOTNOTE.getRelation())) {
this.footnotes = (XWPFFootnotes)p; this.footnotes = (XWPFFootnotes) p;
this.footnotes.onDocumentRead(); this.footnotes.onDocumentRead();
} else if (relation.equals(XWPFRelation.ENDNOTE.getRelation())){ } else if (relation.equals(XWPFRelation.ENDNOTE.getRelation())) {
EndnotesDocument endnotesDocument = EndnotesDocument.Factory.parse(p.getPackagePart().getInputStream()); EndnotesDocument endnotesDocument = EndnotesDocument.Factory.parse(p.getPackagePart().getInputStream());
for(CTFtnEdn ctFtnEdn : endnotesDocument.getEndnotes().getEndnoteArray()) { for (CTFtnEdn ctFtnEdn : endnotesDocument.getEndnotes().getEndnoteArray()) {
endnotes.put(ctFtnEdn.getId().intValue(), new XWPFFootnote(this, ctFtnEdn)); endnotes.put(ctFtnEdn.getId().intValue(), new XWPFFootnote(this, ctFtnEdn));
} }
} }
} }
} }
/**
* Create a new WordProcessingML package and setup the default minimal content
*/
protected static OPCPackage newPackage() {
try {
OPCPackage pkg = OPCPackage.create(new ByteArrayOutputStream());
// Main part
PackagePartName corePartName = PackagingURIHelper.createPartName(XWPFRelation.DOCUMENT.getDefaultFileName());
// Create main part relationship
pkg.addRelationship(corePartName, TargetMode.INTERNAL, PackageRelationshipTypes.CORE_DOCUMENT);
// Create main document part
pkg.createPart(corePartName, XWPFRelation.DOCUMENT.getContentType());
pkg.getPackageProperties().setCreatorProperty(DOCUMENT_CREATOR);
return pkg;
} catch (Exception e){
throw new POIXMLException(e);
}
}
/** /**
* Create a new CTWorkbook with all values set to default * Create a new CTWorkbook with all values set to default
*/ */
@ -278,7 +279,7 @@ public class XWPFDocument extends POIXMLDocument implements Document, IBody {
ctDocument = CTDocument1.Factory.newInstance(); ctDocument = CTDocument1.Factory.newInstance();
ctDocument.addNewBody(); ctDocument.addNewBody();
settings = (XWPFSettings) createRelationship(XWPFRelation.SETTINGS,XWPFFactory.getInstance()); settings = (XWPFSettings) createRelationship(XWPFRelation.SETTINGS, XWPFFactory.getInstance());
POIXMLProperties.ExtendedProperties expProps = getProperties().getExtendedProperties(); POIXMLProperties.ExtendedProperties expProps = getProperties().getExtendedProperties();
expProps.getUnderlyingProperties().setApplication(DOCUMENT_CREATOR); expProps.getUnderlyingProperties().setApplication(DOCUMENT_CREATOR);
@ -298,6 +299,7 @@ public class XWPFDocument extends POIXMLDocument implements Document, IBody {
/** /**
* returns an Iterator with paragraphs and tables * returns an Iterator with paragraphs and tables
*
* @see org.apache.poi.xwpf.usermodel.IBody#getBodyElements() * @see org.apache.poi.xwpf.usermodel.IBody#getBodyElements()
*/ */
@Override @Override
@ -313,7 +315,7 @@ public class XWPFDocument extends POIXMLDocument implements Document, IBody {
* @see org.apache.poi.xwpf.usermodel.IBody#getParagraphs() * @see org.apache.poi.xwpf.usermodel.IBody#getParagraphs()
*/ */
@Override @Override
public List<XWPFParagraph> getParagraphs(){ public List<XWPFParagraph> getParagraphs() {
return Collections.unmodifiableList(paragraphs); return Collections.unmodifiableList(paragraphs);
} }
@ -321,7 +323,7 @@ public class XWPFDocument extends POIXMLDocument implements Document, IBody {
* @see org.apache.poi.xwpf.usermodel.IBody#getTables() * @see org.apache.poi.xwpf.usermodel.IBody#getTables()
*/ */
@Override @Override
public List<XWPFTable> getTables(){ public List<XWPFTable> getTables() {
return Collections.unmodifiableList(tables); return Collections.unmodifiableList(tables);
} }
@ -330,37 +332,35 @@ public class XWPFDocument extends POIXMLDocument implements Document, IBody {
*/ */
@Override @Override
public XWPFTable getTableArray(int pos) { public XWPFTable getTableArray(int pos) {
if (pos > 0 && pos < tables.size()){ if (pos > 0 && pos < tables.size()) {
return tables.get(pos); return tables.get(pos);
} }
return null; return null;
} }
/** /**
* * @return the list of footers
* @return the list of footers
*/ */
public List<XWPFFooter> getFooterList(){ public List<XWPFFooter> getFooterList() {
return Collections.unmodifiableList(footers); return Collections.unmodifiableList(footers);
} }
public XWPFFooter getFooterArray(int pos){ public XWPFFooter getFooterArray(int pos) {
return footers.get(pos); return footers.get(pos);
} }
/** /**
* * @return the list of headers
* @return the list of headers
*/ */
public List<XWPFHeader> getHeaderList(){ public List<XWPFHeader> getHeaderList() {
return Collections.unmodifiableList(headers); return Collections.unmodifiableList(headers);
} }
public XWPFHeader getHeaderArray(int pos){ public XWPFHeader getHeaderArray(int pos) {
return headers.get(pos); return headers.get(pos);
} }
public String getTblStyle(XWPFTable table){ public String getTblStyle(XWPFTable table) {
return table.getStyleID(); return table.getStyleID();
} }
@ -374,17 +374,17 @@ public class XWPFDocument extends POIXMLDocument implements Document, IBody {
} }
public XWPFFootnote getFootnoteByID(int id) { public XWPFFootnote getFootnoteByID(int id) {
if(footnotes == null) return null; if (footnotes == null) return null;
return footnotes.getFootnoteById(id); return footnotes.getFootnoteById(id);
} }
public XWPFFootnote getEndnoteByID(int id) { public XWPFFootnote getEndnoteByID(int id) {
if(endnotes == null) return null; if (endnotes == null) return null;
return endnotes.get(id); return endnotes.get(id);
} }
public List<XWPFFootnote> getFootnotes() { public List<XWPFFootnote> getFootnotes() {
if(footnotes == null) { if (footnotes == null) {
return Collections.emptyList(); return Collections.emptyList();
} }
return footnotes.getFootnotesList(); return footnotes.getFootnotesList();
@ -409,7 +409,7 @@ public class XWPFDocument extends POIXMLDocument implements Document, IBody {
/** /**
* Get the document part that's defined as the * Get the document part that's defined as the
* given relationship of the core document. * given relationship of the core document.
*/ */
public PackagePart getPartById(String id) { public PackagePart getPartById(String id) {
try { try {
@ -422,7 +422,7 @@ public class XWPFDocument extends POIXMLDocument implements Document, IBody {
/** /**
* Returns the policy on headers and footers, which * Returns the policy on headers and footers, which
* also provides a way to get at them. * also provides a way to get at them.
*/ */
public XWPFHeaderFooterPolicy getHeaderFooterPolicy() { public XWPFHeaderFooterPolicy getHeaderFooterPolicy() {
return headerFooterPolicy; return headerFooterPolicy;
@ -436,10 +436,10 @@ public class XWPFDocument extends POIXMLDocument implements Document, IBody {
PackagePart[] parts; PackagePart[] parts;
try { try {
parts = getRelatedByType(XWPFRelation.STYLES.getRelation()); parts = getRelatedByType(XWPFRelation.STYLES.getRelation());
} catch(InvalidFormatException e) { } catch (InvalidFormatException e) {
throw new IllegalStateException(e); throw new IllegalStateException(e);
} }
if(parts.length != 1) { if (parts.length != 1) {
throw new IllegalStateException("Expecting one Styles document part, but found " + parts.length); throw new IllegalStateException("Expecting one Styles document part, but found " + parts.length);
} }
@ -471,57 +471,56 @@ public class XWPFDocument extends POIXMLDocument implements Document, IBody {
* Finds that for example the 2nd entry in the body list is the 1st paragraph * Finds that for example the 2nd entry in the body list is the 1st paragraph
*/ */
private int getBodyElementSpecificPos(int pos, List<? extends IBodyElement> list) { private int getBodyElementSpecificPos(int pos, List<? extends IBodyElement> list) {
// If there's nothing to find, skip it // If there's nothing to find, skip it
if(list.size() == 0) { if (list.size() == 0) {
return -1; return -1;
} }
if(pos >= 0 && pos < bodyElements.size()) { if (pos >= 0 && pos < bodyElements.size()) {
// Ensure the type is correct // Ensure the type is correct
IBodyElement needle = bodyElements.get(pos); IBodyElement needle = bodyElements.get(pos);
if(needle.getElementType() != list.get(0).getElementType()) { if (needle.getElementType() != list.get(0).getElementType()) {
// Wrong type // Wrong type
return -1; return -1;
} }
// Work back until we find it // Work back until we find it
int startPos = Math.min(pos, list.size()-1); int startPos = Math.min(pos, list.size() - 1);
for(int i=startPos; i>=0; i--) { for (int i = startPos; i >= 0; i--) {
if(list.get(i) == needle) { if (list.get(i) == needle) {
return i; return i;
} }
} }
} }
// Couldn't be found // Couldn't be found
return -1; return -1;
} }
/** /**
* Look up the paragraph at the specified position in the body elements list * Look up the paragraph at the specified position in the body elements list
* and return this paragraphs position in the paragraphs list * and return this paragraphs position in the paragraphs list
* *
* @param pos * @param pos The position of the relevant paragraph in the body elements
* The position of the relevant paragraph in the body elements
* list * list
* @return the position of the paragraph in the paragraphs list, if there is * @return the position of the paragraph in the paragraphs list, if there is
* a paragraph at the position in the bodyelements list. Else it * a paragraph at the position in the bodyelements list. Else it
* will return -1 * will return -1
*
*/ */
public int getParagraphPos(int pos) { public int getParagraphPos(int pos) {
return getBodyElementSpecificPos(pos, paragraphs); return getBodyElementSpecificPos(pos, paragraphs);
} }
/** /**
* get with the position of a table in the bodyelement array list * get with the position of a table in the bodyelement array list
* the position of this table in the table array list * the position of this table in the table array list
*
* @param pos position of the table in the bodyelement array list * @param pos position of the table in the bodyelement array list
* @return if there is a table at the position in the bodyelement array list, * @return if there is a table at the position in the bodyelement array list,
* else it will return null. * else it will return null.
*/ */
public int getTablePos(int pos) { public int getTablePos(int pos) {
return getBodyElementSpecificPos(pos, tables); return getBodyElementSpecificPos(pos, tables);
} }
/** /**
@ -533,7 +532,7 @@ public class XWPFDocument extends POIXMLDocument implements Document, IBody {
* *
* @param cursor * @param cursor
* @return the {@link XWPFParagraph} object representing the newly inserted * @return the {@link XWPFParagraph} object representing the newly inserted
* CTP object * CTP object
*/ */
@Override @Override
public XWPFParagraph insertNewParagraph(XmlCursor cursor) { public XWPFParagraph insertNewParagraph(XmlCursor cursor) {
@ -635,8 +634,7 @@ public class XWPFDocument extends POIXMLDocument implements Document, IBody {
cursor.toCursor(tableCursor); cursor.toCursor(tableCursor);
cursor.toEndToken(); cursor.toEndToken();
return newT; return newT;
} } finally {
finally {
tableCursor.dispose(); tableCursor.dispose();
} }
} }
@ -645,6 +643,7 @@ public class XWPFDocument extends POIXMLDocument implements Document, IBody {
/** /**
* verifies that cursor is on the right position * verifies that cursor is on the right position
*
* @param cursor * @param cursor
*/ */
private boolean isCursorInBody(XmlCursor cursor) { private boolean isCursorInBody(XmlCursor cursor) {
@ -660,10 +659,10 @@ public class XWPFDocument extends POIXMLDocument implements Document, IBody {
private int getPosOfBodyElement(IBodyElement needle) { private int getPosOfBodyElement(IBodyElement needle) {
BodyElementType type = needle.getElementType(); BodyElementType type = needle.getElementType();
IBodyElement current; IBodyElement current;
for(int i=0; i<bodyElements.size(); i++) { for (int i = 0; i < bodyElements.size(); i++) {
current = bodyElements.get(i); current = bodyElements.get(i);
if(current.getElementType() == type) { if (current.getElementType() == type) {
if(current.equals(needle)) { if (current.equals(needle)) {
return i; return i;
} }
} }
@ -673,21 +672,23 @@ public class XWPFDocument extends POIXMLDocument implements Document, IBody {
/** /**
* Get the position of the paragraph, within the list * Get the position of the paragraph, within the list
* of all the body elements. * of all the body elements.
*
* @param p The paragraph to find * @param p The paragraph to find
* @return The location, or -1 if the paragraph couldn't be found * @return The location, or -1 if the paragraph couldn't be found
*/ */
public int getPosOfParagraph(XWPFParagraph p){ public int getPosOfParagraph(XWPFParagraph p) {
return getPosOfBodyElement(p); return getPosOfBodyElement(p);
} }
/** /**
* Get the position of the table, within the list of * Get the position of the table, within the list of
* all the body elements. * all the body elements.
*
* @param t The table to find * @param t The table to find
* @return The location, or -1 if the table couldn't be found * @return The location, or -1 if the table couldn't be found
*/ */
public int getPosOfTable(XWPFTable t){ public int getPosOfTable(XWPFTable t) {
return getPosOfBodyElement(t); return getPosOfBodyElement(t);
} }
@ -718,23 +719,25 @@ public class XWPFDocument extends POIXMLDocument implements Document, IBody {
/** /**
* Gets the index of the relation we're trying to create * Gets the index of the relation we're trying to create
*
* @param relation * @param relation
* @return i * @return i
*/ */
private int getRelationIndex(XWPFRelation relation) { private int getRelationIndex(XWPFRelation relation) {
List<POIXMLDocumentPart> relations = getRelations(); List<POIXMLDocumentPart> relations = getRelations();
int i = 1; int i = 1;
for (Iterator<POIXMLDocumentPart> it = relations.iterator(); it.hasNext() ; ) { for (Iterator<POIXMLDocumentPart> it = relations.iterator(); it.hasNext(); ) {
POIXMLDocumentPart item = it.next(); POIXMLDocumentPart item = it.next();
if (item.getPackageRelationship().getRelationshipType().equals(relation.getRelation())) { if (item.getPackageRelationship().getRelationshipType().equals(relation.getRelation())) {
i++; i++;
} }
} }
return i; return i;
} }
/** /**
* Appends a new paragraph to this document * Appends a new paragraph to this document
*
* @return a new paragraph * @return a new paragraph
*/ */
public XWPFParagraph createParagraph() { public XWPFParagraph createParagraph() {
@ -746,16 +749,17 @@ public class XWPFDocument extends POIXMLDocument implements Document, IBody {
/** /**
* Creates an empty numbering if one does not already exist and sets the numbering member * Creates an empty numbering if one does not already exist and sets the numbering member
*
* @return numbering * @return numbering
*/ */
public XWPFNumbering createNumbering() { public XWPFNumbering createNumbering() {
if(numbering == null) { if (numbering == null) {
NumberingDocument numberingDoc = NumberingDocument.Factory.newInstance(); NumberingDocument numberingDoc = NumberingDocument.Factory.newInstance();
XWPFRelation relation = XWPFRelation.NUMBERING; XWPFRelation relation = XWPFRelation.NUMBERING;
int i = getRelationIndex(relation); int i = getRelationIndex(relation);
XWPFNumbering wrapper = (XWPFNumbering)createRelationship(relation, XWPFFactory.getInstance(), i); XWPFNumbering wrapper = (XWPFNumbering) createRelationship(relation, XWPFFactory.getInstance(), i);
wrapper.setNumbering(numberingDoc.addNewNumbering()); wrapper.setNumbering(numberingDoc.addNewNumbering());
numbering = wrapper; numbering = wrapper;
} }
@ -765,61 +769,64 @@ public class XWPFDocument extends POIXMLDocument implements Document, IBody {
/** /**
* Creates an empty styles for the document if one does not already exist * Creates an empty styles for the document if one does not already exist
*
* @return styles * @return styles
*/ */
public XWPFStyles createStyles() { public XWPFStyles createStyles() {
if(styles == null) { if (styles == null) {
StylesDocument stylesDoc = StylesDocument.Factory.newInstance(); StylesDocument stylesDoc = StylesDocument.Factory.newInstance();
XWPFRelation relation = XWPFRelation.STYLES; XWPFRelation relation = XWPFRelation.STYLES;
int i = getRelationIndex(relation); int i = getRelationIndex(relation);
XWPFStyles wrapper = (XWPFStyles)createRelationship(relation, XWPFFactory.getInstance(), i); XWPFStyles wrapper = (XWPFStyles) createRelationship(relation, XWPFFactory.getInstance(), i);
wrapper.setStyles(stylesDoc.addNewStyles()); wrapper.setStyles(stylesDoc.addNewStyles());
styles = wrapper; styles = wrapper;
} }
return styles; return styles;
} }
/** /**
* Creates an empty footnotes element for the document if one does not already exist * Creates an empty footnotes element for the document if one does not already exist
*
* @return footnotes * @return footnotes
*/ */
public XWPFFootnotes createFootnotes() { public XWPFFootnotes createFootnotes() {
if(footnotes == null) { if (footnotes == null) {
FootnotesDocument footnotesDoc = FootnotesDocument.Factory.newInstance(); FootnotesDocument footnotesDoc = FootnotesDocument.Factory.newInstance();
XWPFRelation relation = XWPFRelation.FOOTNOTE; XWPFRelation relation = XWPFRelation.FOOTNOTE;
int i = getRelationIndex(relation); int i = getRelationIndex(relation);
XWPFFootnotes wrapper = (XWPFFootnotes)createRelationship(relation, XWPFFactory.getInstance(), i); XWPFFootnotes wrapper = (XWPFFootnotes) createRelationship(relation, XWPFFactory.getInstance(), i);
wrapper.setFootnotes(footnotesDoc.addNewFootnotes()); wrapper.setFootnotes(footnotesDoc.addNewFootnotes());
footnotes = wrapper; footnotes = wrapper;
} }
return footnotes; return footnotes;
} }
public XWPFFootnote addFootnote(CTFtnEdn note) { public XWPFFootnote addFootnote(CTFtnEdn note) {
return footnotes.addFootnote(note); return footnotes.addFootnote(note);
} }
public XWPFFootnote addEndnote(CTFtnEdn note) { public XWPFFootnote addEndnote(CTFtnEdn note) {
XWPFFootnote endnote = new XWPFFootnote(this, note); XWPFFootnote endnote = new XWPFFootnote(this, note);
endnotes.put(note.getId().intValue(), endnote); endnotes.put(note.getId().intValue(), endnote);
return endnote; return endnote;
} }
/** /**
* remove a BodyElement from bodyElements array list * remove a BodyElement from bodyElements array list
*
* @param pos * @param pos
* @return true if removing was successfully, else return false * @return true if removing was successfully, else return false
*/ */
public boolean removeBodyElement(int pos) { public boolean removeBodyElement(int pos) {
if (pos >= 0 && pos < bodyElements.size()) { if (pos >= 0 && pos < bodyElements.size()) {
BodyElementType type = bodyElements.get(pos).getElementType(); BodyElementType type = bodyElements.get(pos).getElementType();
if (type == BodyElementType.TABLE){ if (type == BodyElementType.TABLE) {
int tablePos = getTablePos(pos); int tablePos = getTablePos(pos);
tables.remove(tablePos); tables.remove(tablePos);
ctDocument.getBody().removeTbl(tablePos); ctDocument.getBody().removeTbl(tablePos);
@ -837,6 +844,7 @@ public class XWPFDocument extends POIXMLDocument implements Document, IBody {
/** /**
* copies content of a paragraph to a existing paragraph in the list paragraphs at position pos * copies content of a paragraph to a existing paragraph in the list paragraphs at position pos
*
* @param paragraph * @param paragraph
* @param pos * @param pos
*/ */
@ -859,6 +867,7 @@ public class XWPFDocument extends POIXMLDocument implements Document, IBody {
/** /**
* Create an empty table with one row and one column as default. * Create an empty table with one row and one column as default.
*
* @return a new table * @return a new table
*/ */
public XWPFTable createTable() { public XWPFTable createTable() {
@ -870,15 +879,16 @@ public class XWPFDocument extends POIXMLDocument implements Document, IBody {
/** /**
* Create an empty table with a number of rows and cols specified * Create an empty table with a number of rows and cols specified
*
* @param rows * @param rows
* @param cols * @param cols
* @return table * @return table
*/ */
public XWPFTable createTable(int rows, int cols) { public XWPFTable createTable(int rows, int cols) {
XWPFTable table = new XWPFTable(ctDocument.getBody().addNewTbl(), this, rows, cols); XWPFTable table = new XWPFTable(ctDocument.getBody().addNewTbl(), this, rows, cols);
bodyElements.add(table); bodyElements.add(table);
tables.add(table); tables.add(table);
return table; return table;
} }
/** /**
@ -900,7 +910,9 @@ public class XWPFDocument extends POIXMLDocument implements Document, IBody {
} }
} }
/**Replace content of table in array tables at position pos with a /**
* Replace content of table in array tables at position pos with a
*
* @param pos * @param pos
* @param table * @param table
*/ */
@ -1011,7 +1023,7 @@ public class XWPFDocument extends POIXMLDocument implements Document, IBody {
* *
* @param password the plaintext password, if null no password will be applied * @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. * @param hashAlgo the hash algorithm - only md2, m5, sha1, sha256, sha384 and sha512 are supported.
* if null, it will default default to sha1 * if null, it will default default to sha1
*/ */
public void enforceReadonlyProtection(String password, HashAlgorithm hashAlgo) { public void enforceReadonlyProtection(String password, HashAlgorithm hashAlgo) {
settings.setEnforcementEditValue(STDocProtect.READ_ONLY, password, hashAlgo); settings.setEnforcementEditValue(STDocProtect.READ_ONLY, password, hashAlgo);
@ -1047,7 +1059,7 @@ public class XWPFDocument extends POIXMLDocument implements Document, IBody {
* *
* @param password the plaintext password, if null no password will be applied * @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. * @param hashAlgo the hash algorithm - only md2, m5, sha1, sha256, sha384 and sha512 are supported.
* if null, it will default default to sha1 * if null, it will default default to sha1
*/ */
public void enforceFillingFormsProtection(String password, HashAlgorithm hashAlgo) { public void enforceFillingFormsProtection(String password, HashAlgorithm hashAlgo) {
settings.setEnforcementEditValue(STDocProtect.FORMS, password, hashAlgo); settings.setEnforcementEditValue(STDocProtect.FORMS, password, hashAlgo);
@ -1083,7 +1095,7 @@ public class XWPFDocument extends POIXMLDocument implements Document, IBody {
* *
* @param password the plaintext password, if null no password will be applied * @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. * @param hashAlgo the hash algorithm - only md2, m5, sha1, sha256, sha384 and sha512 are supported.
* if null, it will default default to sha1 * if null, it will default default to sha1
*/ */
public void enforceCommentsProtection(String password, HashAlgorithm hashAlgo) { public void enforceCommentsProtection(String password, HashAlgorithm hashAlgo) {
settings.setEnforcementEditValue(STDocProtect.COMMENTS, password, hashAlgo); settings.setEnforcementEditValue(STDocProtect.COMMENTS, password, hashAlgo);
@ -1119,7 +1131,7 @@ public class XWPFDocument extends POIXMLDocument implements Document, IBody {
* *
* @param password the plaintext password, if null no password will be applied * @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. * @param hashAlgo the hash algorithm - only md2, m5, sha1, sha256, sha384 and sha512 are supported.
* if null, it will default default to sha1 * if null, it will default default to sha1
*/ */
public void enforceTrackedChangesProtection(String password, HashAlgorithm hashAlgo) { public void enforceTrackedChangesProtection(String password, HashAlgorithm hashAlgo) {
settings.setEnforcementEditValue(STDocProtect.TRACKED_CHANGES, password, hashAlgo); settings.setEnforcementEditValue(STDocProtect.TRACKED_CHANGES, password, hashAlgo);
@ -1148,38 +1160,39 @@ public class XWPFDocument extends POIXMLDocument implements Document, IBody {
* Enforces fields update on document open (in Word). * Enforces fields update on document open (in Word).
* In the settings.xml file <br/> * In the settings.xml file <br/>
* sets the updateSettings value to true (w:updateSettings w:val="true") * sets the updateSettings value to true (w:updateSettings w:val="true")
* * <p/>
* NOTICES: * NOTICES:
* <ul> * <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?" * <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> * (if "Update automatic links at open" is enabled)</li>
* <li>Flag is removed after saving with changes in Word </li> * <li>Flag is removed after saving with changes in Word </li>
* </ul> * </ul>
*/ */
public void enforceUpdateFields() { public void enforceUpdateFields() {
settings.setUpdateFields(); settings.setUpdateFields();
} }
/** /**
* Check if revision tracking is turned on. * Check if revision tracking is turned on.
* *
* @return <code>true</code> if revision tracking is turned on * @return <code>true</code> if revision tracking is turned on
*/ */
public boolean isTrackRevisions() { public boolean isTrackRevisions() {
return settings.isTrackRevisions(); return settings.isTrackRevisions();
} }
/** /**
* Enable or disable revision tracking. * Enable or disable revision tracking.
* *
* @param enable <code>true</code> to turn on revision tracking, <code>false</code> to turn off 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) { public void setTrackRevisions(boolean enable) {
settings.setTrackRevisions(enable); settings.setTrackRevisions(enable);
} }
/** /**
* inserts an existing XWPFTable to the arrays bodyElements and tables * inserts an existing XWPFTable to the arrays bodyElements and tables
*
* @param pos * @param pos
* @param table * @param table
*/ */
@ -1199,6 +1212,7 @@ public class XWPFDocument extends POIXMLDocument implements Document, IBody {
/** /**
* Returns all Pictures, which are referenced from the document itself. * Returns all Pictures, which are referenced from the document itself.
*
* @return a {@link List} of {@link XWPFPictureData}. The returned {@link List} is unmodifiable. Use #a * @return a {@link List} of {@link XWPFPictureData}. The returned {@link List} is unmodifiable. Use #a
*/ */
public List<XWPFPictureData> getAllPictures() { public List<XWPFPictureData> getAllPictures() {
@ -1223,14 +1237,12 @@ public class XWPFDocument extends POIXMLDocument implements Document, IBody {
list = new ArrayList<XWPFPictureData>(1); list = new ArrayList<XWPFPictureData>(1);
packagePictures.put(picData.getChecksum(), list); packagePictures.put(picData.getChecksum(), list);
} }
if (!list.contains(picData)) if (!list.contains(picData)) {
{
list.add(picData); list.add(picData);
} }
} }
XWPFPictureData findPackagePictureData(byte[] pictureData, int format) XWPFPictureData findPackagePictureData(byte[] pictureData, int format) {
{
long checksum = IOUtils.calculateChecksum(pictureData); long checksum = IOUtils.calculateChecksum(pictureData);
XWPFPictureData xwpfPicData = null; XWPFPictureData xwpfPicData = null;
/* /*
@ -1250,16 +1262,14 @@ public class XWPFDocument extends POIXMLDocument implements Document, IBody {
return xwpfPicData; return xwpfPicData;
} }
public String addPictureData(byte[] pictureData,int format) throws InvalidFormatException public String addPictureData(byte[] pictureData, int format) throws InvalidFormatException {
{
XWPFPictureData xwpfPicData = findPackagePictureData(pictureData, format); XWPFPictureData xwpfPicData = findPackagePictureData(pictureData, format);
POIXMLRelation relDesc = XWPFPictureData.RELATIONS[format]; POIXMLRelation relDesc = XWPFPictureData.RELATIONS[format];
if (xwpfPicData == null) if (xwpfPicData == null) {
{
/* Part doesn't exist, create a new one */ /* Part doesn't exist, create a new one */
int idx = getNextPicNameNumber(format); int idx = getNextPicNameNumber(format);
xwpfPicData = (XWPFPictureData) createRelationship(relDesc, XWPFFactory.getInstance(),idx); xwpfPicData = (XWPFPictureData) createRelationship(relDesc, XWPFFactory.getInstance(), idx);
/* write bytes to new part */ /* write bytes to new part */
PackagePart picDataPart = xwpfPicData.getPackagePart(); PackagePart picDataPart = xwpfPicData.getPackagePart();
OutputStream out = null; OutputStream out = null;
@ -1280,9 +1290,7 @@ public class XWPFDocument extends POIXMLDocument implements Document, IBody {
pictures.add(xwpfPicData); pictures.add(xwpfPicData);
return getRelationId(xwpfPicData); return getRelationId(xwpfPicData);
} } else if (!getRelations().contains(xwpfPicData)) {
else if (!getRelations().contains(xwpfPicData))
{
/* /*
* Part already existed, but was not related so far. Create * Part already existed, but was not related so far. Create
* relationship to the already existing part and update * relationship to the already existing part and update
@ -1293,21 +1301,18 @@ public class XWPFDocument extends POIXMLDocument implements Document, IBody {
TargetMode targetMode = TargetMode.INTERNAL; TargetMode targetMode = TargetMode.INTERNAL;
PackagePartName partName = picDataPart.getPartName(); PackagePartName partName = picDataPart.getPartName();
String relation = relDesc.getRelation(); String relation = relDesc.getRelation();
PackageRelationship relShip = getPackagePart().addRelationship(partName,targetMode,relation); PackageRelationship relShip = getPackagePart().addRelationship(partName, targetMode, relation);
String id = relShip.getId(); String id = relShip.getId();
addRelation(id,xwpfPicData); addRelation(id, xwpfPicData);
pictures.add(xwpfPicData); pictures.add(xwpfPicData);
return id; return id;
} } else {
else
{
/* Part already existed, get relation id and return it */ /* Part already existed, get relation id and return it */
return getRelationId(xwpfPicData); return getRelationId(xwpfPicData);
} }
} }
public String addPictureData(InputStream is,int format) throws InvalidFormatException public String addPictureData(InputStream is, int format) throws InvalidFormatException {
{
try { try {
byte[] data = IOUtils.toByteArray(is); byte[] data = IOUtils.toByteArray(is);
return addPictureData(data, format); return addPictureData(data, format);
@ -1318,6 +1323,7 @@ public class XWPFDocument extends POIXMLDocument implements Document, IBody {
/** /**
* get the next free ImageNumber * get the next free ImageNumber
*
* @param format * @param format
* @return the next free ImageNumber * @return the next free ImageNumber
* @throws InvalidFormatException * @throws InvalidFormatException
@ -1336,6 +1342,7 @@ public class XWPFDocument extends POIXMLDocument implements Document, IBody {
/** /**
* returns the PictureData by blipID * returns the PictureData by blipID
*
* @param blipID * @param blipID
* @return XWPFPictureData of a specificID * @return XWPFPictureData of a specificID
*/ */
@ -1350,6 +1357,7 @@ public class XWPFDocument extends POIXMLDocument implements Document, IBody {
/** /**
* getNumbering * getNumbering
*
* @return numbering * @return numbering
*/ */
public XWPFNumbering getNumbering() { public XWPFNumbering getNumbering() {
@ -1358,6 +1366,7 @@ public class XWPFDocument extends POIXMLDocument implements Document, IBody {
/** /**
* get Styles * get Styles
*
* @return styles for this document * @return styles for this document
*/ */
public XWPFStyles getStyles() { public XWPFStyles getStyles() {
@ -1382,9 +1391,10 @@ public class XWPFDocument extends POIXMLDocument implements Document, IBody {
/** /**
* get a table by its CTTbl-Object * get a table by its CTTbl-Object
*
* @param ctTbl * @param ctTbl
* @see org.apache.poi.xwpf.usermodel.IBody#getTable(org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTbl)
* @return a table by its CTTbl-Object or null * @return a table by its CTTbl-Object or null
* @see org.apache.poi.xwpf.usermodel.IBody#getTable(org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTbl)
*/ */
@Override @Override
public XWPFTable getTable(CTTbl ctTbl) { public XWPFTable getTable(CTTbl ctTbl) {
@ -1406,6 +1416,7 @@ public class XWPFDocument extends POIXMLDocument implements Document, IBody {
/** /**
* Returns the paragraph that of position pos * Returns the paragraph that of position pos
*
* @see org.apache.poi.xwpf.usermodel.IBody#getParagraphArray(int) * @see org.apache.poi.xwpf.usermodel.IBody#getParagraphArray(int)
*/ */
@Override @Override
@ -1420,6 +1431,7 @@ public class XWPFDocument extends POIXMLDocument implements Document, IBody {
* returns the Part, to which the body belongs, which you need for adding relationship to other parts * 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 * Actually it is needed of the class XWPFTableCell. Because you have to know to which part the tableCell
* belongs. * belongs.
*
* @see org.apache.poi.xwpf.usermodel.IBody#getPart() * @see org.apache.poi.xwpf.usermodel.IBody#getPart()
*/ */
@Override @Override
@ -1441,6 +1453,7 @@ public class XWPFDocument extends POIXMLDocument implements Document, IBody {
/** /**
* get the TableCell which belongs to the TableCell * get the TableCell which belongs to the TableCell
*
* @param cell * @param cell
*/ */
@Override @Override
@ -1448,19 +1461,19 @@ public class XWPFDocument extends POIXMLDocument implements Document, IBody {
XmlCursor cursor = cell.newCursor(); XmlCursor cursor = cell.newCursor();
cursor.toParent(); cursor.toParent();
XmlObject o = cursor.getObject(); XmlObject o = cursor.getObject();
if(!(o instanceof CTRow)){ if (!(o instanceof CTRow)) {
return null; return null;
} }
CTRow row = (CTRow)o; CTRow row = (CTRow) o;
cursor.toParent(); cursor.toParent();
o = cursor.getObject(); o = cursor.getObject();
cursor.dispose(); cursor.dispose();
if(! (o instanceof CTTbl)){ if (!(o instanceof CTTbl)) {
return null; return null;
} }
CTTbl tbl = (CTTbl) o; CTTbl tbl = (CTTbl) o;
XWPFTable table = getTable(tbl); XWPFTable table = getTable(tbl);
if(table == null){ if (table == null) {
return null; return null;
} }
XWPFTableRow tableRow = table.getRow(row); XWPFTableRow tableRow = table.getRow(row);

View File

@ -31,24 +31,23 @@ import org.apache.poi.util.POILogger;
/** /**
* @author Yegor Kozlov * @author Yegor Kozlov
*/ */
public final class XWPFFactory extends POIXMLFactory { public final class XWPFFactory extends POIXMLFactory {
private static final POILogger logger = POILogFactory.getLogger(XWPFFactory.class); private static final POILogger logger = POILogFactory.getLogger(XWPFFactory.class);
private static final XWPFFactory inst = new XWPFFactory();
private XWPFFactory(){ private XWPFFactory() {
} }
private static final XWPFFactory inst = new XWPFFactory(); public static XWPFFactory getInstance() {
public static XWPFFactory getInstance(){
return inst; return inst;
} }
@Override @Override
public POIXMLDocumentPart createDocumentPart(POIXMLDocumentPart parent, PackageRelationship rel, PackagePart part){ public POIXMLDocumentPart createDocumentPart(POIXMLDocumentPart parent, PackageRelationship rel, PackagePart part) {
POIXMLRelation descriptor = XWPFRelation.getInstance(rel.getRelationshipType()); POIXMLRelation descriptor = XWPFRelation.getInstance(rel.getRelationshipType());
if(descriptor == null || descriptor.getRelationClass() == null){ if (descriptor == null || descriptor.getRelationClass() == null) {
logger.log(POILogger.DEBUG, "using default POIXMLDocumentPart for " + rel.getRelationshipType()); logger.log(POILogger.DEBUG, "using default POIXMLDocumentPart for " + rel.getRelationshipType());
return new POIXMLDocumentPart(part, rel); return new POIXMLDocumentPart(part, rel);
} }
@ -62,18 +61,18 @@ public final class XWPFFactory extends POIXMLFactory {
Constructor<? extends POIXMLDocumentPart> constructor = cls.getDeclaredConstructor(PackagePart.class, PackageRelationship.class); Constructor<? extends POIXMLDocumentPart> constructor = cls.getDeclaredConstructor(PackagePart.class, PackageRelationship.class);
return constructor.newInstance(part, rel); return constructor.newInstance(part, rel);
} }
} catch (Exception e){ } catch (Exception e) {
throw new POIXMLException(e); throw new POIXMLException(e);
} }
} }
@Override @Override
public POIXMLDocumentPart newDocumentPart(POIXMLRelation descriptor){ public POIXMLDocumentPart newDocumentPart(POIXMLRelation descriptor) {
try { try {
Class<? extends POIXMLDocumentPart> cls = descriptor.getRelationClass(); Class<? extends POIXMLDocumentPart> cls = descriptor.getRelationClass();
Constructor<? extends POIXMLDocumentPart> constructor = cls.getDeclaredConstructor(); Constructor<? extends POIXMLDocumentPart> constructor = cls.getDeclaredConstructor();
return constructor.newInstance(); return constructor.newInstance();
} catch (Exception e){ } catch (Exception e) {
throw new POIXMLException(e); throw new POIXMLException(e);
} }
} }

View File

@ -53,12 +53,12 @@ public class XWPFFooter extends XWPFHeaderFooter {
while (cursor.toNextSelection()) { while (cursor.toNextSelection()) {
XmlObject o = cursor.getObject(); XmlObject o = cursor.getObject();
if (o instanceof CTP) { if (o instanceof CTP) {
XWPFParagraph p = new XWPFParagraph((CTP)o, this); XWPFParagraph p = new XWPFParagraph((CTP) o, this);
paragraphs.add(p); paragraphs.add(p);
bodyElements.add(p); bodyElements.add(p);
} }
if (o instanceof CTTbl) { if (o instanceof CTTbl) {
XWPFTable t = new XWPFTable((CTTbl)o, this); XWPFTable t = new XWPFTable((CTTbl) o, this);
tables.add(t); tables.add(t);
bodyElements.add(t); bodyElements.add(t);
} }
@ -78,7 +78,7 @@ public class XWPFFooter extends XWPFHeaderFooter {
protected void commit() throws IOException { protected void commit() throws IOException {
XmlOptions xmlOptions = new XmlOptions(DEFAULT_XML_OPTIONS); XmlOptions xmlOptions = new XmlOptions(DEFAULT_XML_OPTIONS);
xmlOptions.setSaveSyntheticDocumentElement(new QName(CTNumbering.type.getName().getNamespaceURI(), "ftr")); 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("http://schemas.openxmlformats.org/markup-compatibility/2006", "ve");
map.put("urn:schemas-microsoft-com:office:office", "o"); 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/relationships", "r");
@ -96,7 +96,7 @@ public class XWPFFooter extends XWPFHeaderFooter {
} }
@Override @Override
protected void onDocumentRead() throws IOException{ protected void onDocumentRead() throws IOException {
super.onDocumentRead(); super.onDocumentRead();
FtrDocument ftrDocument = null; FtrDocument ftrDocument = null;
InputStream is; InputStream is;
@ -111,19 +111,19 @@ public class XWPFFooter extends XWPFHeaderFooter {
while (cursor.toNextSelection()) { while (cursor.toNextSelection()) {
XmlObject o = cursor.getObject(); XmlObject o = cursor.getObject();
if (o instanceof CTP) { if (o instanceof CTP) {
XWPFParagraph p = new XWPFParagraph((CTP)o, this); XWPFParagraph p = new XWPFParagraph((CTP) o, this);
paragraphs.add(p); paragraphs.add(p);
bodyElements.add(p); bodyElements.add(p);
} }
if (o instanceof CTTbl) { if (o instanceof CTTbl) {
XWPFTable t = new XWPFTable((CTTbl)o, this); XWPFTable t = new XWPFTable((CTTbl) o, this);
tables.add(t); tables.add(t);
bodyElements.add(t); bodyElements.add(t);
} }
if (o instanceof CTSdtBlock){ if (o instanceof CTSdtBlock) {
XWPFSDT c = new XWPFSDT((CTSdtBlock)o, this); XWPFSDT c = new XWPFSDT((CTSdtBlock) o, this);
bodyElements.add(c); bodyElements.add(c);
} }
} }
cursor.dispose(); cursor.dispose();
} catch (Exception e) { } catch (Exception e) {
@ -133,6 +133,7 @@ public class XWPFFooter extends XWPFHeaderFooter {
/** /**
* get the PartType of the body * get the PartType of the body
*
* @see org.apache.poi.xwpf.usermodel.IBody#getPartType() * @see org.apache.poi.xwpf.usermodel.IBody#getPartType()
*/ */
public BodyType getPartType() { public BodyType getPartType() {

View File

@ -30,9 +30,9 @@ import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTSdtBlock;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTbl; import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTbl;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTc; import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTc;
public class XWPFFootnote implements Iterable<XWPFParagraph>,IBody { public class XWPFFootnote implements Iterable<XWPFParagraph>, IBody {
private List<XWPFParagraph> paragraphs = new ArrayList<XWPFParagraph>(); private List<XWPFParagraph> paragraphs = new ArrayList<XWPFParagraph>();
private List<XWPFTable> tables= new ArrayList<XWPFTable>(); private List<XWPFTable> tables = new ArrayList<XWPFTable>();
private List<XWPFPictureData> pictures = new ArrayList<XWPFPictureData>(); private List<XWPFPictureData> pictures = new ArrayList<XWPFPictureData>();
private List<IBodyElement> bodyElements = new ArrayList<IBodyElement>(); private List<IBodyElement> bodyElements = new ArrayList<IBodyElement>();
@ -41,47 +41,47 @@ public class XWPFFootnote implements Iterable<XWPFParagraph>,IBody {
private XWPFDocument document; private XWPFDocument document;
public XWPFFootnote(CTFtnEdn note, XWPFFootnotes xFootnotes) { public XWPFFootnote(CTFtnEdn note, XWPFFootnotes xFootnotes) {
footnotes = xFootnotes; footnotes = xFootnotes;
ctFtnEdn = note; ctFtnEdn = note;
document = xFootnotes.getXWPFDocument(); document = xFootnotes.getXWPFDocument();
init(); init();
} }
public XWPFFootnote(XWPFDocument document, CTFtnEdn body) { public XWPFFootnote(XWPFDocument document, CTFtnEdn body) {
ctFtnEdn = body; ctFtnEdn = body;
this.document = document; this.document = document;
init(); init();
} }
private void init(){ private void init() {
XmlCursor cursor = ctFtnEdn.newCursor(); XmlCursor cursor = ctFtnEdn.newCursor();
//copied from XWPFDocument...should centralize this code //copied from XWPFDocument...should centralize this code
//to avoid duplication //to avoid duplication
cursor.selectPath("./*"); cursor.selectPath("./*");
while (cursor.toNextSelection()) { while (cursor.toNextSelection()) {
XmlObject o = cursor.getObject(); XmlObject o = cursor.getObject();
if (o instanceof CTP) { if (o instanceof CTP) {
XWPFParagraph p = new XWPFParagraph((CTP) o, this); XWPFParagraph p = new XWPFParagraph((CTP) o, this);
bodyElements.add(p); bodyElements.add(p);
paragraphs.add(p); paragraphs.add(p);
} else if (o instanceof CTTbl) { } else if (o instanceof CTTbl) {
XWPFTable t = new XWPFTable((CTTbl) o, this); XWPFTable t = new XWPFTable((CTTbl) o, this);
bodyElements.add(t); bodyElements.add(t);
tables.add(t); tables.add(t);
} else if (o instanceof CTSdtBlock){ } else if (o instanceof CTSdtBlock) {
XWPFSDT c = new XWPFSDT((CTSdtBlock)o, this); XWPFSDT c = new XWPFSDT((CTSdtBlock) o, this);
bodyElements.add(c); bodyElements.add(c);
} }
} }
cursor.dispose(); cursor.dispose();
} }
public List<XWPFParagraph> getParagraphs() { public List<XWPFParagraph> getParagraphs() {
return paragraphs; return paragraphs;
} }
public Iterator<XWPFParagraph> iterator(){ public Iterator<XWPFParagraph> iterator() {
return paragraphs.iterator(); return paragraphs.iterator();
} }
@ -98,11 +98,11 @@ public class XWPFFootnote implements Iterable<XWPFParagraph>,IBody {
} }
public CTFtnEdn getCTFtnEdn() { public CTFtnEdn getCTFtnEdn() {
return ctFtnEdn; return ctFtnEdn;
} }
public void setCTFtnEdn(CTFtnEdn footnote) { public void setCTFtnEdn(CTFtnEdn footnote) {
ctFtnEdn = footnote; ctFtnEdn = footnote;
} }
/** /**
@ -111,7 +111,7 @@ public class XWPFFootnote implements Iterable<XWPFParagraph>,IBody {
* @see org.apache.poi.xwpf.usermodel.IBody#getTableArray(int) * @see org.apache.poi.xwpf.usermodel.IBody#getTableArray(int)
*/ */
public XWPFTable getTableArray(int pos) { public XWPFTable getTableArray(int pos) {
if(pos > 0 && pos < tables.size()){ if (pos > 0 && pos < tables.size()) {
return tables.get(pos); return tables.get(pos);
} }
return null; return null;
@ -119,6 +119,7 @@ public class XWPFFootnote implements Iterable<XWPFParagraph>,IBody {
/** /**
* inserts an existing XWPFTable to the arrays bodyElements and tables * inserts an existing XWPFTable to the arrays bodyElements and tables
*
* @param pos * @param pos
* @param table * @param table
* @see org.apache.poi.xwpf.usermodel.IBody#insertTable(int pos, XWPFTable table) * @see org.apache.poi.xwpf.usermodel.IBody#insertTable(int pos, XWPFTable table)
@ -128,7 +129,7 @@ public class XWPFFootnote implements Iterable<XWPFParagraph>,IBody {
bodyElements.add(pos, table); bodyElements.add(pos, table);
int i = 0; int i = 0;
for (CTTbl tbl : ctFtnEdn.getTblArray()) { for (CTTbl tbl : ctFtnEdn.getTblArray()) {
if(tbl == table.getCTTbl()){ if (tbl == table.getCTTbl()) {
break; break;
} }
i++; i++;
@ -141,14 +142,15 @@ public class XWPFFootnote implements Iterable<XWPFParagraph>,IBody {
* if there is a corresponding {@link XWPFTable} of the parameter ctTable in the tableList of this header * if there is a corresponding {@link XWPFTable} of the parameter ctTable in the tableList of this header
* the method will return this table * 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 * @param ctTable
* @see org.apache.poi.xwpf.usermodel.IBody#getTable(CTTbl ctTable) * @see org.apache.poi.xwpf.usermodel.IBody#getTable(CTTbl ctTable)
*/ */
public XWPFTable getTable(CTTbl ctTable){ public XWPFTable getTable(CTTbl ctTable) {
for (XWPFTable table : tables) { for (XWPFTable table : tables) {
if(table==null) if (table == null)
return null; return null;
if(table.getCTTbl().equals(ctTable)) if (table.getCTTbl().equals(ctTable))
return table; return table;
} }
return null; return null;
@ -158,14 +160,15 @@ public class XWPFFootnote implements Iterable<XWPFParagraph>,IBody {
* if there is a corresponding {@link XWPFParagraph} of the parameter ctTable in the paragraphList of this header or footer * 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 * 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 * @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 * @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
* @see org.apache.poi.xwpf.usermodel.IBody#getParagraph(CTP p) * @see org.apache.poi.xwpf.usermodel.IBody#getParagraph(CTP p)
*/ */
public XWPFParagraph getParagraph(CTP p){ public XWPFParagraph getParagraph(CTP p) {
for (XWPFParagraph paragraph : paragraphs) { for (XWPFParagraph paragraph : paragraphs) {
if(paragraph.getCTP().equals(p)) if (paragraph.getCTP().equals(p))
return paragraph; return paragraph;
} }
return null; return null;
@ -173,7 +176,8 @@ public class XWPFFootnote implements Iterable<XWPFParagraph>,IBody {
/** /**
* Returns the paragraph that holds * Returns the paragraph that holds
* the text of the header or footer. * the text of the header or footer.
*
* @see org.apache.poi.xwpf.usermodel.IBody#getParagraphArray(int pos) * @see org.apache.poi.xwpf.usermodel.IBody#getParagraphArray(int pos)
*/ */
public XWPFParagraph getParagraphArray(int pos) { public XWPFParagraph getParagraphArray(int pos) {
@ -183,6 +187,7 @@ public class XWPFFootnote implements Iterable<XWPFParagraph>,IBody {
/** /**
* get the TableCell which belongs to the TableCell * get the TableCell which belongs to the TableCell
*
* @param cell * @param cell
* @see org.apache.poi.xwpf.usermodel.IBody#getTableCell(CTTc cell) * @see org.apache.poi.xwpf.usermodel.IBody#getTableCell(CTTc cell)
*/ */
@ -190,23 +195,23 @@ public class XWPFFootnote implements Iterable<XWPFParagraph>,IBody {
XmlCursor cursor = cell.newCursor(); XmlCursor cursor = cell.newCursor();
cursor.toParent(); cursor.toParent();
XmlObject o = cursor.getObject(); XmlObject o = cursor.getObject();
if(!(o instanceof CTRow)){ if (!(o instanceof CTRow)) {
return null; return null;
} }
CTRow row = (CTRow)o; CTRow row = (CTRow) o;
cursor.toParent(); cursor.toParent();
o = cursor.getObject(); o = cursor.getObject();
cursor.dispose(); cursor.dispose();
if(! (o instanceof CTTbl)){ if (!(o instanceof CTTbl)) {
return null; return null;
} }
CTTbl tbl = (CTTbl) o; CTTbl tbl = (CTTbl) o;
XWPFTable table = getTable(tbl); XWPFTable table = getTable(tbl);
if(table == null){ if (table == null) {
return null; return null;
} }
XWPFTableRow tableRow = table.getRow(row); XWPFTableRow tableRow = table.getRow(row);
if(row == null){ if (row == null) {
return null; return null;
} }
return tableRow.getTableCell(cell); return tableRow.getTableCell(cell);
@ -214,52 +219,51 @@ public class XWPFFootnote implements Iterable<XWPFParagraph>,IBody {
/** /**
* verifies that cursor is on the right position * verifies that cursor is on the right position
*
* @param cursor * @param cursor
*/ */
private boolean isCursorInFtn(XmlCursor cursor) { private boolean isCursorInFtn(XmlCursor cursor) {
XmlCursor verify = cursor.newCursor(); XmlCursor verify = cursor.newCursor();
verify.toParent(); verify.toParent();
if(verify.getObject() == this.ctFtnEdn){ if (verify.getObject() == this.ctFtnEdn) {
return true; return true;
} }
return false; return false;
} }
public POIXMLDocumentPart getOwner(){ public POIXMLDocumentPart getOwner() {
return footnotes; return footnotes;
} }
/** /**
*
* @param cursor * @param cursor
* @return the inserted table * @return the inserted table
* @see org.apache.poi.xwpf.usermodel.IBody#insertNewTbl(XmlCursor cursor) * @see org.apache.poi.xwpf.usermodel.IBody#insertNewTbl(XmlCursor cursor)
*/ */
public XWPFTable insertNewTbl(XmlCursor cursor) { public XWPFTable insertNewTbl(XmlCursor cursor) {
if(isCursorInFtn(cursor)){ if (isCursorInFtn(cursor)) {
String uri = CTTbl.type.getName().getNamespaceURI(); String uri = CTTbl.type.getName().getNamespaceURI();
String localPart = "tbl"; String localPart = "tbl";
cursor.beginElement(localPart,uri); cursor.beginElement(localPart, uri);
cursor.toParent(); cursor.toParent();
CTTbl t = (CTTbl)cursor.getObject(); CTTbl t = (CTTbl) cursor.getObject();
XWPFTable newT = new XWPFTable(t, this); XWPFTable newT = new XWPFTable(t, this);
cursor.removeXmlContents(); cursor.removeXmlContents();
XmlObject o = null; XmlObject o = null;
while(!(o instanceof CTTbl)&&(cursor.toPrevSibling())){ while (!(o instanceof CTTbl) && (cursor.toPrevSibling())) {
o = cursor.getObject(); o = cursor.getObject();
} }
if(!(o instanceof CTTbl)){ if (!(o instanceof CTTbl)) {
tables.add(0, newT); tables.add(0, newT);
} else {
int pos = tables.indexOf(getTable((CTTbl) o)) + 1;
tables.add(pos, newT);
} }
else{ int i = 0;
int pos = tables.indexOf(getTable((CTTbl)o))+1;
tables.add(pos,newT);
}
int i=0;
cursor = t.newCursor(); cursor = t.newCursor();
while(cursor.toPrevSibling()){ while (cursor.toPrevSibling()) {
o =cursor.getObject(); o = cursor.getObject();
if(o instanceof CTP || o instanceof CTTbl) if (o instanceof CTP || o instanceof CTTbl)
i++; i++;
} }
bodyElements.add(i, newT); bodyElements.add(i, newT);
@ -272,34 +276,34 @@ public class XWPFFootnote implements Iterable<XWPFParagraph>,IBody {
/** /**
* add a new paragraph at position of the cursor * add a new paragraph at position of the cursor
*
* @param cursor * @param cursor
* @return the inserted paragraph * @return the inserted paragraph
* @see org.apache.poi.xwpf.usermodel.IBody#insertNewParagraph(XmlCursor cursor) * @see org.apache.poi.xwpf.usermodel.IBody#insertNewParagraph(XmlCursor cursor)
*/ */
public XWPFParagraph insertNewParagraph(XmlCursor cursor){ public XWPFParagraph insertNewParagraph(XmlCursor cursor) {
if(isCursorInFtn(cursor)){ if (isCursorInFtn(cursor)) {
String uri = CTP.type.getName().getNamespaceURI(); String uri = CTP.type.getName().getNamespaceURI();
String localPart = "p"; String localPart = "p";
cursor.beginElement(localPart,uri); cursor.beginElement(localPart, uri);
cursor.toParent(); cursor.toParent();
CTP p = (CTP)cursor.getObject(); CTP p = (CTP) cursor.getObject();
XWPFParagraph newP = new XWPFParagraph(p, this); XWPFParagraph newP = new XWPFParagraph(p, this);
XmlObject o = null; XmlObject o = null;
while(!(o instanceof CTP)&&(cursor.toPrevSibling())){ while (!(o instanceof CTP) && (cursor.toPrevSibling())) {
o = cursor.getObject(); o = cursor.getObject();
} }
if((!(o instanceof CTP)) || (CTP)o == p){ if ((!(o instanceof CTP)) || (CTP) o == p) {
paragraphs.add(0, newP); paragraphs.add(0, newP);
} else {
int pos = paragraphs.indexOf(getParagraph((CTP) o)) + 1;
paragraphs.add(pos, newP);
} }
else{ int i = 0;
int pos = paragraphs.indexOf(getParagraph((CTP)o))+1;
paragraphs.add(pos,newP);
}
int i=0;
cursor.toCursor(p.newCursor()); cursor.toCursor(p.newCursor());
while(cursor.toPrevSibling()){ while (cursor.toPrevSibling()) {
o =cursor.getObject(); o = cursor.getObject();
if(o instanceof CTP || o instanceof CTTbl) if (o instanceof CTP || o instanceof CTTbl)
i++; i++;
} }
bodyElements.add(i, newP); bodyElements.add(i, newP);
@ -312,6 +316,7 @@ public class XWPFFootnote implements Iterable<XWPFParagraph>,IBody {
/** /**
* add a new table to the end of the footnote * add a new table to the end of the footnote
*
* @param table * @param table
* @return the added XWPFTable * @return the added XWPFTable
*/ */
@ -325,6 +330,7 @@ public class XWPFFootnote implements Iterable<XWPFParagraph>,IBody {
/** /**
* add a new paragraph to the end of the footnote * add a new paragraph to the end of the footnote
*
* @param paragraph * @param paragraph
* @return the added XWPFParagraph * @return the added XWPFParagraph
*/ */
@ -339,12 +345,13 @@ public class XWPFFootnote implements Iterable<XWPFParagraph>,IBody {
/** /**
* @see org.apache.poi.xwpf.usermodel.IBody#getXWPFDocument() * @see org.apache.poi.xwpf.usermodel.IBody#getXWPFDocument()
*/ */
public XWPFDocument getXWPFDocument() { public XWPFDocument getXWPFDocument() {
return document; return document;
} }
/** /**
* returns the Part, to which the body belongs, which you need for adding relationship to other parts * 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() * @see org.apache.poi.xwpf.usermodel.IBody#getPart()
*/ */
public POIXMLDocumentPart getPart() { public POIXMLDocumentPart getPart() {
@ -353,6 +360,7 @@ public class XWPFFootnote implements Iterable<XWPFParagraph>,IBody {
/** /**
* get the PartType of the body * get the PartType of the body
*
* @see org.apache.poi.xwpf.usermodel.IBody#getPartType() * @see org.apache.poi.xwpf.usermodel.IBody#getPartType()
*/ */
public BodyType getPartType() { public BodyType getPartType() {

View File

@ -34,26 +34,25 @@ import org.apache.poi.openxml4j.opc.PackagePart;
import org.apache.poi.openxml4j.opc.PackageRelationship; import org.apache.poi.openxml4j.opc.PackageRelationship;
import org.apache.xmlbeans.XmlException; import org.apache.xmlbeans.XmlException;
import org.apache.xmlbeans.XmlOptions; 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.CTFootnotes;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTFtnEdn;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.FootnotesDocument; import org.openxmlformats.schemas.wordprocessingml.x2006.main.FootnotesDocument;
/** /**
* Looks after the collection of Footnotes for a document * Looks after the collection of Footnotes for a document
*/ */
public class XWPFFootnotes extends POIXMLDocumentPart { public class XWPFFootnotes extends POIXMLDocumentPart {
protected XWPFDocument document;
private List<XWPFFootnote> listFootnote = new ArrayList<XWPFFootnote>(); private List<XWPFFootnote> listFootnote = new ArrayList<XWPFFootnote>();
private CTFootnotes ctFootnotes; private CTFootnotes ctFootnotes;
protected XWPFDocument document;
/** /**
* Construct XWPFFootnotes from a package part * Construct XWPFFootnotes from a package part
* *
* @param part the package part holding the data of the footnotes, * @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" * @param rel the package relationship of type "http://schemas.openxmlformats.org/officeDocument/2006/relationships/footnotes"
*/ */
public XWPFFootnotes(PackagePart part, PackageRelationship rel) throws IOException, OpenXML4JException{ public XWPFFootnotes(PackagePart part, PackageRelationship rel) throws IOException, OpenXML4JException {
super(part, rel); super(part, rel);
} }
@ -68,7 +67,7 @@ public class XWPFFootnotes extends POIXMLDocumentPart {
*/ */
@Override @Override
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
protected void onDocumentRead () throws IOException { protected void onDocumentRead() throws IOException {
FootnotesDocument notesDoc; FootnotesDocument notesDoc;
try { try {
InputStream is = getPackagePart().getInputStream(); InputStream is = getPackagePart().getInputStream();
@ -79,7 +78,7 @@ public class XWPFFootnotes extends POIXMLDocumentPart {
} }
// Find our footnotes // Find our footnotes
for(CTFtnEdn note : ctFootnotes.getFootnoteArray()) { for (CTFtnEdn note : ctFootnotes.getFootnoteArray()) {
listFootnote.add(new XWPFFootnote(note, this)); listFootnote.add(new XWPFFootnote(note, this));
} }
} }
@ -88,7 +87,7 @@ public class XWPFFootnotes extends POIXMLDocumentPart {
protected void commit() throws IOException { protected void commit() throws IOException {
XmlOptions xmlOptions = new XmlOptions(DEFAULT_XML_OPTIONS); XmlOptions xmlOptions = new XmlOptions(DEFAULT_XML_OPTIONS);
xmlOptions.setSaveSyntheticDocumentElement(new QName(CTFootnotes.type.getName().getNamespaceURI(), "footnotes")); xmlOptions.setSaveSyntheticDocumentElement(new QName(CTFootnotes.type.getName().getNamespaceURI(), "footnotes"));
Map<String,String> map = new HashMap<String,String>(); Map<String, String> map = new HashMap<String, String>();
map.put("http://schemas.openxmlformats.org/officeDocument/2006/relationships", "r"); map.put("http://schemas.openxmlformats.org/officeDocument/2006/relationships", "r");
map.put("http://schemas.openxmlformats.org/wordprocessingml/2006/main", "w"); map.put("http://schemas.openxmlformats.org/wordprocessingml/2006/main", "w");
xmlOptions.setSaveSuggestedPrefixes(map); xmlOptions.setSaveSuggestedPrefixes(map);
@ -103,8 +102,8 @@ public class XWPFFootnotes extends POIXMLDocumentPart {
} }
public XWPFFootnote getFootnoteById(int id) { public XWPFFootnote getFootnoteById(int id) {
for(XWPFFootnote note : listFootnote) { for (XWPFFootnote note : listFootnote) {
if(note.getCTFtnEdn().getId().intValue() == id) if (note.getCTFtnEdn().getId().intValue() == id)
return note; return note;
} }
return null; return null;
@ -112,6 +111,7 @@ public class XWPFFootnotes extends POIXMLDocumentPart {
/** /**
* Sets the ctFootnotes * Sets the ctFootnotes
*
* @param footnotes * @param footnotes
*/ */
public void setFootnotes(CTFootnotes footnotes) { public void setFootnotes(CTFootnotes footnotes) {
@ -120,20 +120,22 @@ public class XWPFFootnotes extends POIXMLDocumentPart {
/** /**
* add an XWPFFootnote to the document * add an XWPFFootnote to the document
*
* @param footnote * @param footnote
* @throws IOException * @throws IOException
*/ */
public void addFootnote(XWPFFootnote footnote){ public void addFootnote(XWPFFootnote footnote) {
listFootnote.add(footnote); listFootnote.add(footnote);
ctFootnotes.addNewFootnote().set(footnote.getCTFtnEdn()); ctFootnotes.addNewFootnote().set(footnote.getCTFtnEdn());
} }
/** /**
* add a footnote to the document * add a footnote to the document
*
* @param note * @param note
* @throws IOException * @throws IOException
*/ */
public XWPFFootnote addFootnote(CTFtnEdn note){ public XWPFFootnote addFootnote(CTFtnEdn note) {
CTFtnEdn newNote = ctFootnotes.addNewFootnote(); CTFtnEdn newNote = ctFootnotes.addNewFootnote();
newNote.set(note); newNote.set(note);
XWPFFootnote xNote = new XWPFFootnote(newNote, this); XWPFFootnote xNote = new XWPFFootnote(newNote, this);
@ -141,18 +143,18 @@ public class XWPFFootnotes extends POIXMLDocumentPart {
return xNote; return xNote;
} }
public void setXWPFDocument(XWPFDocument doc) {
document = doc;
}
/** /**
* @see org.apache.poi.xwpf.usermodel.IBody#getPart() * @see org.apache.poi.xwpf.usermodel.IBody#getPart()
*/ */
public XWPFDocument getXWPFDocument() { public XWPFDocument getXWPFDocument() {
if ( document != null) { if (document != null) {
return document; return document;
} else { } else {
return (XWPFDocument)getParent(); return (XWPFDocument) getParent();
} }
} }
public void setXWPFDocument(XWPFDocument doc) {
document = doc;
}
} }

View File

@ -69,14 +69,14 @@ public class XWPFHeader extends XWPFHeaderFooter {
cursor.dispose(); cursor.dispose();
} }
/** /**
* save and commit footer * save and commit footer
*/ */
@Override @Override
protected void commit() throws IOException { protected void commit() throws IOException {
XmlOptions xmlOptions = new XmlOptions(DEFAULT_XML_OPTIONS); XmlOptions xmlOptions = new XmlOptions(DEFAULT_XML_OPTIONS);
xmlOptions.setSaveSyntheticDocumentElement(new QName(CTNumbering.type.getName().getNamespaceURI(), "hdr")); 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("http://schemas.openxmlformats.org/markup-compatibility/2006", "ve");
map.put("urn:schemas-microsoft-com:office:office", "o"); 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/relationships", "r");
@ -95,6 +95,7 @@ public class XWPFHeader extends XWPFHeaderFooter {
/** /**
* reads the document * reads the document
*
* @throws IOException * @throws IOException
*/ */
@Override @Override
@ -113,17 +114,17 @@ public class XWPFHeader extends XWPFHeaderFooter {
while (cursor.toNextSelection()) { while (cursor.toNextSelection()) {
XmlObject o = cursor.getObject(); XmlObject o = cursor.getObject();
if (o instanceof CTP) { if (o instanceof CTP) {
XWPFParagraph p = new XWPFParagraph((CTP)o, this); XWPFParagraph p = new XWPFParagraph((CTP) o, this);
paragraphs.add(p); paragraphs.add(p);
bodyElements.add(p); bodyElements.add(p);
} }
if (o instanceof CTTbl) { if (o instanceof CTTbl) {
XWPFTable t = new XWPFTable((CTTbl)o, this); XWPFTable t = new XWPFTable((CTTbl) o, this);
tables.add(t); tables.add(t);
bodyElements.add(t); bodyElements.add(t);
} }
if (o instanceof CTSdtBlock){ if (o instanceof CTSdtBlock) {
XWPFSDT c = new XWPFSDT((CTSdtBlock)o, this); XWPFSDT c = new XWPFSDT((CTSdtBlock) o, this);
bodyElements.add(c); bodyElements.add(c);
} }
} }
@ -135,6 +136,7 @@ public class XWPFHeader extends XWPFHeaderFooter {
/** /**
* get the PartType of the body * get the PartType of the body
*
* @see org.apache.poi.xwpf.usermodel.IBody#getPartType() * @see org.apache.poi.xwpf.usermodel.IBody#getPartType()
*/ */
public BodyType 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 { public abstract class XWPFHeaderFooter extends POIXMLDocumentPart implements IBody {
List<XWPFParagraph> paragraphs = new ArrayList<XWPFParagraph>(1); 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<XWPFPictureData> pictures = new ArrayList<XWPFPictureData>();
List<IBodyElement> bodyElements = new ArrayList<IBodyElement>(1); List<IBodyElement> bodyElements = new ArrayList<IBodyElement>(1);
@ -54,7 +54,7 @@ public abstract class XWPFHeaderFooter extends POIXMLDocumentPart implements IBo
XWPFDocument document; XWPFDocument document;
XWPFHeaderFooter(XWPFDocument doc, CTHdrFtr hdrFtr) { XWPFHeaderFooter(XWPFDocument doc, CTHdrFtr hdrFtr) {
if (doc==null) { if (doc == null) {
throw new NullPointerException(); 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 { public XWPFHeaderFooter(POIXMLDocumentPart parent, PackagePart part, PackageRelationship rel) throws IOException {
super(parent, part, rel); super(parent, part, rel);
this.document = (XWPFDocument)getParent(); this.document = (XWPFDocument) getParent();
if (this.document==null) { if (this.document == null) {
throw new NullPointerException(); throw new NullPointerException();
} }
} }
@Override @Override
protected void onDocumentRead() throws IOException { protected void onDocumentRead() throws IOException {
for (POIXMLDocumentPart poixmlDocumentPart : getRelations()){ for (POIXMLDocumentPart poixmlDocumentPart : getRelations()) {
if(poixmlDocumentPart instanceof XWPFPictureData){ if (poixmlDocumentPart instanceof XWPFPictureData) {
XWPFPictureData xwpfPicData = (XWPFPictureData) poixmlDocumentPart; XWPFPictureData xwpfPicData = (XWPFPictureData) poixmlDocumentPart;
pictures.add(xwpfPicData); pictures.add(xwpfPicData);
document.registerPackagePictureData(xwpfPicData); document.registerPackagePictureData(xwpfPicData);
@ -93,16 +93,16 @@ public abstract class XWPFHeaderFooter extends POIXMLDocumentPart implements IBo
return headerFooter; return headerFooter;
} }
public List<IBodyElement> getBodyElements(){ public List<IBodyElement> getBodyElements() {
return Collections.unmodifiableList(bodyElements); return Collections.unmodifiableList(bodyElements);
} }
/** /**
* Returns the paragraph(s) that holds * 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 * Normally there is only the one paragraph, but
* there could be more in certain cases, or * there could be more in certain cases, or
* a table. * a table.
*/ */
public List<XWPFParagraph> getParagraphs() { public List<XWPFParagraph> getParagraphs() {
return Collections.unmodifiableList(paragraphs); return Collections.unmodifiableList(paragraphs);
@ -111,29 +111,28 @@ public abstract class XWPFHeaderFooter extends POIXMLDocumentPart implements IBo
/** /**
* Return the table(s) that holds the text * Return the table(s) that holds the text
* of the header or footer, for complex cases * of the header or footer, for complex cases
* where a paragraph isn't used. * where a paragraph isn't used.
* Normally there's just one paragraph, but some * Normally there's just one paragraph, but some
* complex headers/footers have a table or two * complex headers/footers have a table or two
* in addition. * in addition.
*/ */
public List<XWPFTable> getTables()throws ArrayIndexOutOfBoundsException { public List<XWPFTable> getTables() throws ArrayIndexOutOfBoundsException {
return Collections.unmodifiableList(tables); return Collections.unmodifiableList(tables);
} }
/** /**
* Returns the textual content of the header/footer, * 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() { public String getText() {
StringBuffer t = new StringBuffer(); StringBuffer t = new StringBuffer();
//TODO: simplify this to get ibody elements in order //TODO: simplify this to get ibody elements in order
for(int i=0; i<paragraphs.size(); i++) { for (int i = 0; i < paragraphs.size(); i++) {
if(! paragraphs.get(i).isEmpty()) { if (!paragraphs.get(i).isEmpty()) {
String text = paragraphs.get(i).getText(); String text = paragraphs.get(i).getText();
if(text != null && text.length() > 0) { if (text != null && text.length() > 0) {
t.append(text); t.append(text);
t.append('\n'); t.append('\n');
} }
@ -141,26 +140,26 @@ public abstract class XWPFHeaderFooter extends POIXMLDocumentPart implements IBo
} }
List<XWPFTable> tables = getTables(); 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(); String text = tables.get(i).getText();
if(text != null && text.length() > 0) { if (text != null && text.length() > 0) {
t.append(text); t.append(text);
t.append('\n'); t.append('\n');
} }
} }
for (IBodyElement bodyElement : getBodyElements()){ for (IBodyElement bodyElement : getBodyElements()) {
if (bodyElement instanceof XWPFSDT){ if (bodyElement instanceof XWPFSDT) {
t.append(((XWPFSDT) bodyElement).getContent().getText()+'\n'); t.append(((XWPFSDT) bodyElement).getContent().getText() + '\n');
} }
} }
return t.toString(); return t.toString();
} }
/** /**
* set a new headerFooter * set a new headerFooter
*/ */
public void setHeaderFooter(CTHdrFtr headerFooter){ public void setHeaderFooter(CTHdrFtr headerFooter) {
this.headerFooter = headerFooter; this.headerFooter = headerFooter;
readHdrFtr(); readHdrFtr();
} }
@ -169,13 +168,14 @@ 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 * if there is a corresponding {@link XWPFTable} of the parameter ctTable in the tableList of this header
* the method will return this table * 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 * @param ctTable
*/ */
public XWPFTable getTable(CTTbl ctTable){ public XWPFTable getTable(CTTbl ctTable) {
for (XWPFTable table : tables) { for (XWPFTable table : tables) {
if(table==null) if (table == null)
return null; return null;
if(table.getCTTbl().equals(ctTable)) if (table.getCTTbl().equals(ctTable))
return table; return table;
} }
return null; return null;
@ -185,13 +185,14 @@ 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 * 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 * 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 * @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 * @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) { for (XWPFParagraph paragraph : paragraphs) {
if(paragraph.getCTP().equals(p)) if (paragraph.getCTP().equals(p))
return paragraph; return paragraph;
} }
return null; return null;
@ -200,7 +201,7 @@ public abstract class XWPFHeaderFooter extends POIXMLDocumentPart implements IBo
/** /**
* Returns the paragraph that holds * Returns the paragraph that holds
* the text of the header or footer. * the text of the header or footer.
*/ */
public XWPFParagraph getParagraphArray(int pos) { public XWPFParagraph getParagraphArray(int pos) {
@ -209,9 +210,10 @@ public abstract class XWPFHeaderFooter extends POIXMLDocumentPart implements IBo
/** /**
* get a List of all Paragraphs * 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; return paragraphs;
} }
@ -221,9 +223,10 @@ public abstract class XWPFHeaderFooter extends POIXMLDocumentPart implements IBo
/** /**
* get all Pictures in this package * get all Pictures in this package
*
* @return all Pictures in this package * @return all Pictures in this package
*/ */
public List<XWPFPictureData> getAllPackagePictures(){ public List<XWPFPictureData> getAllPackagePictures() {
return document.getAllPackagePictures(); return document.getAllPackagePictures();
} }
@ -231,22 +234,19 @@ public abstract class XWPFHeaderFooter extends POIXMLDocumentPart implements IBo
/** /**
* Adds a picture to the document. * Adds a picture to the document.
* *
* @param pictureData The picture data * @param pictureData The picture data
* @param format The format of the picture. * @param format The format of the picture.
*
* @return the index to this picture (0 based), the added picture can be obtained from {@link #getAllPictures()} . * @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); XWPFPictureData xwpfPicData = document.findPackagePictureData(pictureData, format);
POIXMLRelation relDesc = XWPFPictureData.RELATIONS[format]; POIXMLRelation relDesc = XWPFPictureData.RELATIONS[format];
if (xwpfPicData == null) if (xwpfPicData == null) {
{
/* Part doesn't exist, create a new one */ /* Part doesn't exist, create a new one */
int idx = document.getNextPicNameNumber(format); int idx = document.getNextPicNameNumber(format);
xwpfPicData = (XWPFPictureData) createRelationship(relDesc, XWPFFactory.getInstance(),idx); xwpfPicData = (XWPFPictureData) createRelationship(relDesc, XWPFFactory.getInstance(), idx);
/* write bytes to new part */ /* write bytes to new part */
PackagePart picDataPart = xwpfPicData.getPackagePart(); PackagePart picDataPart = xwpfPicData.getPackagePart();
OutputStream out = null; OutputStream out = null;
@ -266,9 +266,7 @@ public abstract class XWPFHeaderFooter extends POIXMLDocumentPart implements IBo
document.registerPackagePictureData(xwpfPicData); document.registerPackagePictureData(xwpfPicData);
pictures.add(xwpfPicData); pictures.add(xwpfPicData);
return getRelationId(xwpfPicData); return getRelationId(xwpfPicData);
} } else if (!getRelations().contains(xwpfPicData)) {
else if (!getRelations().contains(xwpfPicData))
{
/* /*
* Part already existed, but was not related so far. Create * Part already existed, but was not related so far. Create
* relationship to the already existing part and update * relationship to the already existing part and update
@ -279,14 +277,12 @@ public abstract class XWPFHeaderFooter extends POIXMLDocumentPart implements IBo
TargetMode targetMode = TargetMode.INTERNAL; TargetMode targetMode = TargetMode.INTERNAL;
PackagePartName partName = picDataPart.getPartName(); PackagePartName partName = picDataPart.getPartName();
String relation = relDesc.getRelation(); String relation = relDesc.getRelation();
PackageRelationship relShip = getPackagePart().addRelationship(partName,targetMode,relation); PackageRelationship relShip = getPackagePart().addRelationship(partName, targetMode, relation);
String id = relShip.getId(); String id = relShip.getId();
addRelation(id,xwpfPicData); addRelation(id, xwpfPicData);
pictures.add(xwpfPicData); pictures.add(xwpfPicData);
return id; return id;
} } else {
else
{
/* Part already existed, get relation id and return it */ /* Part already existed, get relation id and return it */
return getRelationId(xwpfPicData); return getRelationId(xwpfPicData);
} }
@ -295,20 +291,20 @@ public abstract class XWPFHeaderFooter extends POIXMLDocumentPart implements IBo
/** /**
* Adds a picture to the document. * Adds a picture to the document.
* *
* @param is The stream to read image from * @param is The stream to read image from
* @param format The format of the picture. * @param format The format of the picture.
*
* @return the index to this picture (0 based), the added picture can be obtained from {@link #getAllPictures()} . * @return the index to this picture (0 based), the added picture can be obtained from {@link #getAllPictures()} .
* @throws InvalidFormatException * @throws InvalidFormatException
* @throws IOException * @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); byte[] data = IOUtils.toByteArray(is);
return addPictureData(data,format); return addPictureData(data, format);
} }
/** /**
* returns the PictureData by blipID * returns the PictureData by blipID
*
* @param blipID * @param blipID
* @return XWPFPictureData of a specificID * @return XWPFPictureData of a specificID
* @throws Exception * @throws Exception
@ -323,33 +319,33 @@ public abstract class XWPFHeaderFooter extends POIXMLDocumentPart implements IBo
/** /**
* add a new paragraph at position of the cursor * add a new paragraph at position of the cursor
*
* @param cursor * @param cursor
* @return the inserted paragraph * @return the inserted paragraph
*/ */
public XWPFParagraph insertNewParagraph(XmlCursor cursor){ public XWPFParagraph insertNewParagraph(XmlCursor cursor) {
if(isCursorInHdrF(cursor)){ if (isCursorInHdrF(cursor)) {
String uri = CTP.type.getName().getNamespaceURI(); String uri = CTP.type.getName().getNamespaceURI();
String localPart = "p"; String localPart = "p";
cursor.beginElement(localPart,uri); cursor.beginElement(localPart, uri);
cursor.toParent(); cursor.toParent();
CTP p = (CTP)cursor.getObject(); CTP p = (CTP) cursor.getObject();
XWPFParagraph newP = new XWPFParagraph(p, this); XWPFParagraph newP = new XWPFParagraph(p, this);
XmlObject o = null; XmlObject o = null;
while(!(o instanceof CTP)&&(cursor.toPrevSibling())){ while (!(o instanceof CTP) && (cursor.toPrevSibling())) {
o = cursor.getObject(); o = cursor.getObject();
} }
if((!(o instanceof CTP)) || (CTP)o == p){ if ((!(o instanceof CTP)) || (CTP) o == p) {
paragraphs.add(0, newP); paragraphs.add(0, newP);
} else {
int pos = paragraphs.indexOf(getParagraph((CTP) o)) + 1;
paragraphs.add(pos, newP);
} }
else{ int i = 0;
int pos = paragraphs.indexOf(getParagraph((CTP)o))+1;
paragraphs.add(pos,newP);
}
int i=0;
cursor.toCursor(p.newCursor()); cursor.toCursor(p.newCursor());
while(cursor.toPrevSibling()){ while (cursor.toPrevSibling()) {
o =cursor.getObject(); o = cursor.getObject();
if(o instanceof CTP || o instanceof CTTbl) if (o instanceof CTP || o instanceof CTTbl)
i++; i++;
} }
bodyElements.add(i, newP); bodyElements.add(i, newP);
@ -362,35 +358,33 @@ public abstract class XWPFHeaderFooter extends POIXMLDocumentPart implements IBo
/** /**
*
* @param cursor * @param cursor
* @return the inserted table * @return the inserted table
*/ */
public XWPFTable insertNewTbl(XmlCursor cursor) { public XWPFTable insertNewTbl(XmlCursor cursor) {
if(isCursorInHdrF(cursor)){ if (isCursorInHdrF(cursor)) {
String uri = CTTbl.type.getName().getNamespaceURI(); String uri = CTTbl.type.getName().getNamespaceURI();
String localPart = "tbl"; String localPart = "tbl";
cursor.beginElement(localPart,uri); cursor.beginElement(localPart, uri);
cursor.toParent(); cursor.toParent();
CTTbl t = (CTTbl)cursor.getObject(); CTTbl t = (CTTbl) cursor.getObject();
XWPFTable newT = new XWPFTable(t, this); XWPFTable newT = new XWPFTable(t, this);
cursor.removeXmlContents(); cursor.removeXmlContents();
XmlObject o = null; XmlObject o = null;
while(!(o instanceof CTTbl)&&(cursor.toPrevSibling())){ while (!(o instanceof CTTbl) && (cursor.toPrevSibling())) {
o = cursor.getObject(); o = cursor.getObject();
} }
if(!(o instanceof CTTbl)){ if (!(o instanceof CTTbl)) {
tables.add(0, newT); tables.add(0, newT);
} else {
int pos = tables.indexOf(getTable((CTTbl) o)) + 1;
tables.add(pos, newT);
} }
else{ int i = 0;
int pos = tables.indexOf(getTable((CTTbl)o))+1;
tables.add(pos,newT);
}
int i=0;
cursor = t.newCursor(); cursor = t.newCursor();
while(cursor.toPrevSibling()){ while (cursor.toPrevSibling()) {
o =cursor.getObject(); o = cursor.getObject();
if(o instanceof CTP || o instanceof CTTbl) if (o instanceof CTP || o instanceof CTTbl)
i++; i++;
} }
bodyElements.add(i, newT); bodyElements.add(i, newT);
@ -403,29 +397,31 @@ public abstract class XWPFHeaderFooter extends POIXMLDocumentPart implements IBo
/** /**
* verifies that cursor is on the right position * verifies that cursor is on the right position
*
* @param cursor * @param cursor
*/ */
private boolean isCursorInHdrF(XmlCursor cursor) { private boolean isCursorInHdrF(XmlCursor cursor) {
XmlCursor verify = cursor.newCursor(); XmlCursor verify = cursor.newCursor();
verify.toParent(); verify.toParent();
if(verify.getObject() == this.headerFooter){ if (verify.getObject() == this.headerFooter) {
return true; return true;
} }
return false; return false;
} }
public POIXMLDocumentPart getOwner(){ public POIXMLDocumentPart getOwner() {
return this; return this;
} }
/** /**
* Returns the table at position pos * Returns the table at position pos
*
* @see org.apache.poi.xwpf.usermodel.IBody#getTableArray(int) * @see org.apache.poi.xwpf.usermodel.IBody#getTableArray(int)
*/ */
public XWPFTable getTableArray(int pos) { public XWPFTable getTableArray(int pos) {
if(pos > 0 && pos < tables.size()){ if (pos > 0 && pos < tables.size()) {
return tables.get(pos); return tables.get(pos);
} }
return null; return null;
@ -433,6 +429,7 @@ public abstract class XWPFHeaderFooter extends POIXMLDocumentPart implements IBo
/** /**
* inserts an existing XWPFTable to the arrays bodyElements and tables * inserts an existing XWPFTable to the arrays bodyElements and tables
*
* @param pos * @param pos
* @param table * @param table
*/ */
@ -441,7 +438,7 @@ public abstract class XWPFHeaderFooter extends POIXMLDocumentPart implements IBo
bodyElements.add(pos, table); bodyElements.add(pos, table);
int i = 0; int i = 0;
for (CTTbl tbl : headerFooter.getTblArray()) { for (CTTbl tbl : headerFooter.getTblArray()) {
if(tbl == table.getCTTbl()){ if (tbl == table.getCTTbl()) {
break; break;
} }
i++; i++;
@ -450,10 +447,10 @@ public abstract class XWPFHeaderFooter extends POIXMLDocumentPart implements IBo
} }
public void readHdrFtr(){ public void readHdrFtr() {
bodyElements = new ArrayList<IBodyElement>(); bodyElements = new ArrayList<IBodyElement>();
paragraphs = new ArrayList<XWPFParagraph>(); paragraphs = new ArrayList<XWPFParagraph>();
tables= new ArrayList<XWPFTable>(); tables = new ArrayList<XWPFTable>();
// parse the document with cursor and add // parse the document with cursor and add
// the XmlObject to its lists // the XmlObject to its lists
XmlCursor cursor = headerFooter.newCursor(); XmlCursor cursor = headerFooter.newCursor();
@ -461,12 +458,12 @@ public abstract class XWPFHeaderFooter extends POIXMLDocumentPart implements IBo
while (cursor.toNextSelection()) { while (cursor.toNextSelection()) {
XmlObject o = cursor.getObject(); XmlObject o = cursor.getObject();
if (o instanceof CTP) { if (o instanceof CTP) {
XWPFParagraph p = new XWPFParagraph((CTP)o, this); XWPFParagraph p = new XWPFParagraph((CTP) o, this);
paragraphs.add(p); paragraphs.add(p);
bodyElements.add(p); bodyElements.add(p);
} }
if (o instanceof CTTbl) { if (o instanceof CTTbl) {
XWPFTable t = new XWPFTable((CTTbl)o, this); XWPFTable t = new XWPFTable((CTTbl) o, this);
tables.add(t); tables.add(t);
bodyElements.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 * get the TableCell which belongs to the TableCell
*
* @param cell * @param cell
*/ */
public XWPFTableCell getTableCell(CTTc cell) { public XWPFTableCell getTableCell(CTTc cell) {
XmlCursor cursor = cell.newCursor(); XmlCursor cursor = cell.newCursor();
cursor.toParent(); cursor.toParent();
XmlObject o = cursor.getObject(); XmlObject o = cursor.getObject();
if(!(o instanceof CTRow)){ if (!(o instanceof CTRow)) {
return null; return null;
} }
CTRow row = (CTRow)o; CTRow row = (CTRow) o;
cursor.toParent(); cursor.toParent();
o = cursor.getObject(); o = cursor.getObject();
cursor.dispose(); cursor.dispose();
if(! (o instanceof CTTbl)){ if (!(o instanceof CTTbl)) {
return null; return null;
} }
CTTbl tbl = (CTTbl) o; CTTbl tbl = (CTTbl) o;
XWPFTable table = getTable(tbl); XWPFTable table = getTable(tbl);
if(table == null){ if (table == null) {
return null; return null;
} }
XWPFTableRow tableRow = table.getRow(row); XWPFTableRow tableRow = table.getRow(row);
if(row == null){ if (row == null) {
return null; return null;
} }
return tableRow.getTableCell(cell); return tableRow.getTableCell(cell);
} }
public XWPFDocument getXWPFDocument() {
if (document != null) {
return document;
} else {
return (XWPFDocument) getParent();
}
}
public void setXWPFDocument(XWPFDocument doc) { public void setXWPFDocument(XWPFDocument doc) {
document = 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 * 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() * @see org.apache.poi.xwpf.usermodel.IBody#getPart()
*/ */
public POIXMLDocumentPart getPart() { public POIXMLDocumentPart getPart() {

View File

@ -19,25 +19,21 @@ package org.apache.poi.xwpf.usermodel;
/** /**
* Sketch of XWPF hyperlink class * 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; String id, url;
public XWPFHyperlink(String id, String url)
{ public XWPFHyperlink(String id, String url) {
this.id = id; this.id = id;
this.url = url; this.url = url;
} }
public String getId() public String getId() {
{
return id; return id;
} }
public String getURL() public String getURL() {
{
return url; return url;
} }
} }

View File

@ -23,42 +23,42 @@ import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTR;
* A run of text with a Hyperlink applied to it. * A run of text with a Hyperlink applied to it.
* Any given Hyperlink may be made up of multiple of these. * Any given Hyperlink may be made up of multiple of these.
*/ */
public class XWPFHyperlinkRun extends XWPFRun public class XWPFHyperlinkRun extends XWPFRun {
{ private CTHyperlink hyperlink;
private CTHyperlink hyperlink;
public XWPFHyperlinkRun(CTHyperlink hyperlink, CTR run, IRunBody p) { public XWPFHyperlinkRun(CTHyperlink hyperlink, CTR run, IRunBody p) {
super(run, p); super(run, p);
this.hyperlink = hyperlink; this.hyperlink = hyperlink;
} }
public CTHyperlink getCTHyperlink() { public CTHyperlink getCTHyperlink() {
return hyperlink; return hyperlink;
} }
public String getAnchor() { public String getAnchor() {
return hyperlink.getAnchor(); return hyperlink.getAnchor();
} }
/** /**
* Returns the ID of the hyperlink, if one is set. * Returns the ID of the hyperlink, if one is set.
*/ */
public String getHyperlinkId() { public String getHyperlinkId() {
return hyperlink.getId(); return hyperlink.getId();
} }
public void setHyperlinkId(String id) {
hyperlink.setId(id);
}
/** public void setHyperlinkId(String id) {
* If this Hyperlink is an external reference hyperlink, hyperlink.setId(id);
* return the object for it. }
*/
public XWPFHyperlink getHyperlink(XWPFDocument document) {
String id = getHyperlinkId();
if(id == null)
return null;
return document.getHyperlinkByID(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

@ -20,19 +20,19 @@ import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTLatentStyles;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTLsdException; import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTLsdException;
public class XWPFLatentStyles { public class XWPFLatentStyles {
private CTLatentStyles latentStyles;
protected XWPFStyles styles; //LatentStyle shall know styles protected XWPFStyles styles; //LatentStyle shall know styles
private CTLatentStyles latentStyles;
protected XWPFLatentStyles(){ protected XWPFLatentStyles() {
} }
protected XWPFLatentStyles(CTLatentStyles latentStyles){ protected XWPFLatentStyles(CTLatentStyles latentStyles) {
this(latentStyles,null); this(latentStyles, null);
} }
protected XWPFLatentStyles(CTLatentStyles latentStyles, XWPFStyles styles) { protected XWPFLatentStyles(CTLatentStyles latentStyles, XWPFStyles styles) {
this.latentStyles=latentStyles; this.latentStyles = latentStyles;
this.styles=styles; this.styles = styles;
} }
public int getNumberOfStyles() { public int getNumberOfStyles() {
@ -43,9 +43,9 @@ public class XWPFLatentStyles {
* checks whether specific LatentStyleID is a latentStyle * checks whether specific LatentStyleID is a latentStyle
*/ */
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
protected boolean isLatentStyle(String latentStyleID){ protected boolean isLatentStyle(String latentStyleID) {
for ( CTLsdException lsd: latentStyles.getLsdExceptionArray()) { for (CTLsdException lsd : latentStyles.getLsdExceptionArray()) {
if(lsd.getName().equals(latentStyleID)) { if (lsd.getName().equals(latentStyleID)) {
return true; return true;
} }
} }

View File

@ -21,45 +21,44 @@ import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTNum;
/** /**
* @author Philipp Epp * @author Philipp Epp
*
*/ */
public class XWPFNum { public class XWPFNum {
private CTNum ctNum; protected XWPFNumbering numbering;
protected XWPFNumbering numbering; private CTNum ctNum;
public XWPFNum(){ public XWPFNum() {
this.ctNum = null; this.ctNum = null;
this.numbering = null; this.numbering = null;
} }
public XWPFNum(CTNum ctNum){ public XWPFNum(CTNum ctNum) {
this.ctNum = ctNum; this.ctNum = ctNum;
this.numbering = null; this.numbering = null;
} }
public XWPFNum(XWPFNumbering numbering){ public XWPFNum(XWPFNumbering numbering) {
this.ctNum = null; this.ctNum = null;
this.numbering = numbering; this.numbering = numbering;
} }
public XWPFNum(CTNum ctNum, XWPFNumbering numbering){ public XWPFNum(CTNum ctNum, XWPFNumbering numbering) {
this.ctNum = ctNum; this.ctNum = ctNum;
this.numbering = numbering; this.numbering = numbering;
} }
public XWPFNumbering getNumbering(){ public XWPFNumbering getNumbering() {
return numbering; return numbering;
} }
public CTNum getCTNum(){ public void setNumbering(XWPFNumbering numbering) {
return ctNum; this.numbering = numbering;
} }
public void setNumbering(XWPFNumbering numbering){ public CTNum getCTNum() {
this.numbering = numbering; return ctNum;
} }
public void setCTNum(CTNum ctNum){ public void setCTNum(CTNum ctNum) {
this.ctNum = ctNum; this.ctNum = ctNum;
} }
} }

View File

@ -41,65 +41,63 @@ import org.openxmlformats.schemas.wordprocessingml.x2006.main.NumberingDocument;
/** /**
* @author Philipp Epp * @author Philipp Epp
*
*/ */
public class XWPFNumbering extends POIXMLDocumentPart { public class XWPFNumbering extends POIXMLDocumentPart {
protected List<XWPFAbstractNum> abstractNums = new ArrayList<XWPFAbstractNum>(); protected List<XWPFAbstractNum> abstractNums = new ArrayList<XWPFAbstractNum>();
protected List<XWPFNum> nums = new ArrayList<XWPFNum>(); protected List<XWPFNum> nums = new ArrayList<XWPFNum>();
boolean isNew;
private CTNumbering ctNumbering; private CTNumbering ctNumbering;
boolean isNew;
/** /**
*create a new styles object with an existing document * create a new styles object with an existing document
*/ */
public XWPFNumbering(PackagePart part, PackageRelationship rel) throws IOException, OpenXML4JException{ public XWPFNumbering(PackagePart part, PackageRelationship rel) throws IOException, OpenXML4JException {
super(part, rel); super(part, rel);
isNew = true; isNew = true;
} }
/** /**
* create a new XWPFNumbering object for use in a new document * create a new XWPFNumbering object for use in a new document
*/ */
public XWPFNumbering(){ public XWPFNumbering() {
abstractNums = new ArrayList<XWPFAbstractNum>(); abstractNums = new ArrayList<XWPFAbstractNum>();
nums = new ArrayList<XWPFNum>(); nums = new ArrayList<XWPFNum>();
isNew = true; isNew = true;
} }
/** /**
* read numbering form an existing package * read numbering form an existing package
*/ */
@Override @Override
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
protected void onDocumentRead() throws IOException{ protected void onDocumentRead() throws IOException {
NumberingDocument numberingDoc = null; NumberingDocument numberingDoc = null;
InputStream is; InputStream is;
is = getPackagePart().getInputStream(); is = getPackagePart().getInputStream();
try { try {
numberingDoc = NumberingDocument.Factory.parse(is); numberingDoc = NumberingDocument.Factory.parse(is);
ctNumbering = numberingDoc.getNumbering(); ctNumbering = numberingDoc.getNumbering();
//get any Nums //get any Nums
for(CTNum ctNum : ctNumbering.getNumArray()) { for (CTNum ctNum : ctNumbering.getNumArray()) {
nums.add(new XWPFNum(ctNum, this)); nums.add(new XWPFNum(ctNum, this));
} }
for(CTAbstractNum ctAbstractNum : ctNumbering.getAbstractNumArray()){ for (CTAbstractNum ctAbstractNum : ctNumbering.getAbstractNumArray()) {
abstractNums.add(new XWPFAbstractNum(ctAbstractNum, this)); abstractNums.add(new XWPFAbstractNum(ctAbstractNum, this));
} }
isNew = false; isNew = false;
} catch (XmlException e) { } catch (XmlException e) {
throw new POIXMLException(); throw new POIXMLException();
} }
} }
/** /**
* save and commit numbering * save and commit numbering
*/ */
@Override @Override
protected void commit() throws IOException { protected void commit() throws IOException {
XmlOptions xmlOptions = new XmlOptions(DEFAULT_XML_OPTIONS); XmlOptions xmlOptions = new XmlOptions(DEFAULT_XML_OPTIONS);
xmlOptions.setSaveSyntheticDocumentElement(new QName(CTNumbering.type.getName().getNamespaceURI(), "numbering")); xmlOptions.setSaveSyntheticDocumentElement(new QName(CTNumbering.type.getName().getNamespaceURI(), "numbering"));
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("http://schemas.openxmlformats.org/markup-compatibility/2006", "ve");
map.put("urn:schemas-microsoft-com:office:office", "o"); 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/relationships", "r");
@ -117,166 +115,179 @@ public class XWPFNumbering extends POIXMLDocumentPart {
} }
/** /**
* Sets the ctNumbering * Sets the ctNumbering
* @param numbering *
*/ * @param numbering
public void setNumbering(CTNumbering numbering){ */
ctNumbering = numbering; public void setNumbering(CTNumbering numbering) {
} ctNumbering = numbering;
}
/** /**
* Checks whether number with numID exists * Checks whether number with numID exists
* @param numID *
* @return boolean true if num exist, false if num not exist * @param numID
*/ * @return boolean true if num exist, false if num not exist
public boolean numExist(BigInteger numID){ */
for (XWPFNum num : nums) { public boolean numExist(BigInteger numID) {
if (num.getCTNum().getNumId().equals(numID)) for (XWPFNum num : nums) {
return true; if (num.getCTNum().getNumId().equals(numID))
} return true;
return false; }
} return false;
}
/** /**
* add a new number to the numbering document * add a new number to the numbering document
* @param num *
*/ * @param num
public BigInteger addNum(XWPFNum num){ */
ctNumbering.addNewNum(); public BigInteger addNum(XWPFNum num) {
int pos = ctNumbering.sizeOfNumArray() - 1; ctNumbering.addNewNum();
ctNumbering.setNumArray(pos, num.getCTNum()); int pos = ctNumbering.sizeOfNumArray() - 1;
nums.add(num); ctNumbering.setNumArray(pos, num.getCTNum());
return num.getCTNum().getNumId(); nums.add(num);
} return num.getCTNum().getNumId();
}
/** /**
* Add a new num with an abstractNumID * Add a new num with an abstractNumID
* @return return NumId of the added num *
*/ * @return return NumId of the added num
public BigInteger addNum(BigInteger abstractNumID){ */
CTNum ctNum = this.ctNumbering.addNewNum(); public BigInteger addNum(BigInteger abstractNumID) {
ctNum.addNewAbstractNumId(); CTNum ctNum = this.ctNumbering.addNewNum();
ctNum.getAbstractNumId().setVal(abstractNumID); ctNum.addNewAbstractNumId();
ctNum.setNumId(BigInteger.valueOf(nums.size()+1)); ctNum.getAbstractNumId().setVal(abstractNumID);
XWPFNum num = new XWPFNum(ctNum, this); ctNum.setNumId(BigInteger.valueOf(nums.size() + 1));
nums.add(num); XWPFNum num = new XWPFNum(ctNum, this);
return ctNum.getNumId(); nums.add(num);
} return ctNum.getNumId();
}
/** /**
* Add a new num with an abstractNumID and a numID * Add a new num with an abstractNumID and a numID
* @param abstractNumID *
* @param numID * @param abstractNumID
*/ * @param numID
public void addNum(BigInteger abstractNumID, BigInteger numID){ */
CTNum ctNum = this.ctNumbering.addNewNum(); public void addNum(BigInteger abstractNumID, BigInteger numID) {
ctNum.addNewAbstractNumId(); CTNum ctNum = this.ctNumbering.addNewNum();
ctNum.getAbstractNumId().setVal(abstractNumID); ctNum.addNewAbstractNumId();
ctNum.setNumId(numID); ctNum.getAbstractNumId().setVal(abstractNumID);
XWPFNum num = new XWPFNum(ctNum, this); ctNum.setNumId(numID);
nums.add(num); XWPFNum num = new XWPFNum(ctNum, this);
} nums.add(num);
}
/** /**
* get Num by NumID * get Num by NumID
* @param numID *
* @return abstractNum with NumId if no Num exists with that NumID * @param numID
* null will be returned * @return abstractNum with NumId if no Num exists with that NumID
*/ * null will be returned
public XWPFNum getNum(BigInteger numID){ */
for(XWPFNum num: nums){ public XWPFNum getNum(BigInteger numID) {
if(num.getCTNum().getNumId().equals(numID)) for (XWPFNum num : nums) {
return num; if (num.getCTNum().getNumId().equals(numID))
} return num;
return null; }
} return null;
/** }
* get AbstractNum by abstractNumID
* @param abstractNumID /**
* @return abstractNum with abstractNumId if no abstractNum exists with that abstractNumID * get AbstractNum by abstractNumID
* null will be returned *
*/ * @param abstractNumID
public XWPFAbstractNum getAbstractNum(BigInteger abstractNumID){ * @return abstractNum with abstractNumId if no abstractNum exists with that abstractNumID
for(XWPFAbstractNum abstractNum: abstractNums){ * null will be returned
if(abstractNum.getAbstractNum().getAbstractNumId().equals(abstractNumID)){ */
return abstractNum; public XWPFAbstractNum getAbstractNum(BigInteger abstractNumID) {
} for (XWPFAbstractNum abstractNum : abstractNums) {
} if (abstractNum.getAbstractNum().getAbstractNumId().equals(abstractNumID)) {
return null; return abstractNum;
} }
/** }
* Compare AbstractNum with abstractNums of this numbering document. return null;
* 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 /**
* * Compare AbstractNum with abstractNums of this numbering document.
* @param abstractNum * If the content of abstractNum equals with an abstractNum of the List in numbering
* @return BigInteger * the BigInteger Value of it will be returned.
*/ * If no equal abstractNum is existing null will be returned
public BigInteger getIdOfAbstractNum(XWPFAbstractNum abstractNum){ *
CTAbstractNum copy = (CTAbstractNum) abstractNum.getCTAbstractNum().copy(); * @param abstractNum
XWPFAbstractNum newAbstractNum = new XWPFAbstractNum(copy, this); * @return BigInteger
int i; */
for (i = 0; i < abstractNums.size(); i++) { public BigInteger getIdOfAbstractNum(XWPFAbstractNum abstractNum) {
newAbstractNum.getCTAbstractNum().setAbstractNumId(BigInteger.valueOf(i)); CTAbstractNum copy = (CTAbstractNum) abstractNum.getCTAbstractNum().copy();
newAbstractNum.setNumbering(this); XWPFAbstractNum newAbstractNum = new XWPFAbstractNum(copy, this);
if(newAbstractNum.getCTAbstractNum().valueEquals(abstractNums.get(i).getCTAbstractNum())){ int i;
return newAbstractNum.getCTAbstractNum().getAbstractNumId(); for (i = 0; i < abstractNums.size(); i++) {
} newAbstractNum.getCTAbstractNum().setAbstractNumId(BigInteger.valueOf(i));
} newAbstractNum.setNumbering(this);
return null; if (newAbstractNum.getCTAbstractNum().valueEquals(abstractNums.get(i).getCTAbstractNum())) {
} return newAbstractNum.getCTAbstractNum().getAbstractNumId();
}
}
return null;
}
/** /**
* add a new AbstractNum and return its AbstractNumID * add a new AbstractNum and return its AbstractNumID
* @param abstractNum *
*/ * @param abstractNum
public BigInteger addAbstractNum(XWPFAbstractNum abstractNum){ */
int pos = abstractNums.size(); public BigInteger addAbstractNum(XWPFAbstractNum abstractNum) {
if(abstractNum.getAbstractNum() != null){ // Use the current CTAbstractNum if it exists int pos = abstractNums.size();
ctNumbering.addNewAbstractNum().set(abstractNum.getAbstractNum()); if (abstractNum.getAbstractNum() != null) { // Use the current CTAbstractNum if it exists
} else { ctNumbering.addNewAbstractNum().set(abstractNum.getAbstractNum());
ctNumbering.addNewAbstractNum(); } else {
abstractNum.getAbstractNum().setAbstractNumId(BigInteger.valueOf(pos)); ctNumbering.addNewAbstractNum();
ctNumbering.setAbstractNumArray(pos, abstractNum.getAbstractNum()); abstractNum.getAbstractNum().setAbstractNumId(BigInteger.valueOf(pos));
} ctNumbering.setAbstractNumArray(pos, abstractNum.getAbstractNum());
abstractNums.add(abstractNum); }
return abstractNum.getCTAbstractNum().getAbstractNumId(); abstractNums.add(abstractNum);
} return abstractNum.getCTAbstractNum().getAbstractNumId();
}
/** /**
* remove an existing abstractNum * remove an existing abstractNum
* @param abstractNumID *
* @return true if abstractNum with abstractNumID exists in NumberingArray, * @param abstractNumID
* false if abstractNum with abstractNumID not exists * @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()){ public boolean removeAbstractNum(BigInteger abstractNumID) {
ctNumbering.removeAbstractNum(abstractNumID.byteValue()); if (abstractNumID.byteValue() < abstractNums.size()) {
abstractNums.remove(abstractNumID.byteValue()); ctNumbering.removeAbstractNum(abstractNumID.byteValue());
return true; abstractNums.remove(abstractNumID.byteValue());
} return true;
return false; }
} return false;
/** }
*return the abstractNumID
*If the AbstractNumID not exists /**
*return null * return the abstractNumID
* @param numID * If the AbstractNumID not exists
* @return abstractNumID * return null
*/ *
public BigInteger getAbstractNumID(BigInteger numID){ * @param numID
XWPFNum num = getNum(numID); * @return abstractNumID
if(num == null) */
return null; public BigInteger getAbstractNumID(BigInteger numID) {
if (num.getCTNum() == null) XWPFNum num = getNum(numID);
return null; if (num == null)
if (num.getCTNum().getAbstractNumId() == null) return null;
return null; if (num.getCTNum() == null)
return num.getCTNum().getAbstractNumId().getVal(); return null;
} if (num.getCTNum().getAbstractNumId() == null)
return null;
return num.getCTNum().getAbstractNumId().getVal();
}
} }

View File

@ -31,7 +31,7 @@ public class XWPFPicture {
private String description; private String description;
private XWPFRun run; private XWPFRun run;
public XWPFPicture(CTPicture ctPic, XWPFRun run){ public XWPFPicture(CTPicture ctPic, XWPFRun run) {
this.run = run; this.run = run;
this.ctPic = ctPic; this.ctPic = ctPic;
description = ctPic.getNvPicPr().getCNvPr().getDescr(); description = ctPic.getNvPicPr().getCNvPr().getDescr();
@ -39,9 +39,10 @@ public class XWPFPicture {
/** /**
* Link Picture with PictureData * Link Picture with PictureData
*
* @param rel * @param rel
*/ */
public void setPictureReference(PackageRelationship rel){ public void setPictureReference(PackageRelationship rel) {
ctPic.getBlipFill().getBlip().setEmbed(rel.getId()); ctPic.getBlipFill().getBlip().setEmbed(rel.getId());
} }
@ -50,7 +51,7 @@ public class XWPFPicture {
* *
* @return the underlying CTPicture bean * @return the underlying CTPicture bean
*/ */
public CTPicture getCTPicture(){ public CTPicture getCTPicture() {
return ctPic; return ctPic;
} }
@ -58,18 +59,17 @@ public class XWPFPicture {
* Get the PictureData of the Picture, if present. * Get the PictureData of the Picture, if present.
* Note - not all kinds of picture have data * Note - not all kinds of picture have data
*/ */
public XWPFPictureData getPictureData(){ public XWPFPictureData getPictureData() {
CTBlipFillProperties blipProps = ctPic.getBlipFill(); CTBlipFillProperties blipProps = ctPic.getBlipFill();
if(blipProps == null || !blipProps.isSetBlip()) { if (blipProps == null || !blipProps.isSetBlip()) {
// return null if Blip data is missing // return null if Blip data is missing
return null; return null;
} }
String blipId = blipProps.getBlip().getEmbed(); String blipId = blipProps.getBlip().getEmbed();
POIXMLDocumentPart part = run.getParent().getPart(); POIXMLDocumentPart part = run.getParent().getPart();
if (part != null) if (part != null) {
{
POIXMLDocumentPart relatedPart = part.getRelationById(blipId); POIXMLDocumentPart relatedPart = part.getRelationById(blipId);
if (relatedPart instanceof XWPFPictureData) { if (relatedPart instanceof XWPFPictureData) {
return (XWPFPictureData) relatedPart; return (XWPFPictureData) relatedPart;

View File

@ -43,6 +43,7 @@ public class XWPFPictureData extends POIXMLDocumentPart {
* Relationships for each known picture type * Relationships for each known picture type
*/ */
protected static final POIXMLRelation[] RELATIONS; protected static final POIXMLRelation[] RELATIONS;
static { static {
RELATIONS = new POIXMLRelation[13]; RELATIONS = new POIXMLRelation[13];
RELATIONS[Document.PICTURE_TYPE_EMF] = XWPFRelation.IMAGE_EMF; RELATIONS[Document.PICTURE_TYPE_EMF] = XWPFRelation.IMAGE_EMF;
@ -62,7 +63,6 @@ public class XWPFPictureData extends POIXMLDocumentPart {
/** /**
* Create a new XWPFGraphicData node * Create a new XWPFGraphicData node
*
*/ */
protected XWPFPictureData() { protected XWPFPictureData() {
super(); super();
@ -73,7 +73,7 @@ public class XWPFPictureData extends POIXMLDocumentPart {
* *
* @param part the package part holding the drawing data, * @param part the package part holding the drawing data,
* @param rel the package relationship holding this drawing, * @param rel the package relationship holding this drawing,
* the relationship type must be http://schemas.openxmlformats.org/officeDocument/2006/relationships/image * the relationship type must be http://schemas.openxmlformats.org/officeDocument/2006/relationships/image
*/ */
public XWPFPictureData(PackagePart part, PackageRelationship rel) { public XWPFPictureData(PackagePart part, PackageRelationship rel) {
super(part, rel); super(part, rel);
@ -94,6 +94,7 @@ public class XWPFPictureData extends POIXMLDocumentPart {
* InputStream is = getPackagePart().getInputStream(); * InputStream is = getPackagePart().getInputStream();
* </code> * </code>
* </p> * </p>
*
* @return the Picture data. * @return the Picture data.
*/ */
public byte[] getData() { public byte[] getData() {
@ -118,6 +119,7 @@ public class XWPFPictureData extends POIXMLDocumentPart {
/** /**
* Suggests a file extension for this image. * Suggests a file extension for this image.
*
* @return the file extension. * @return the file extension.
*/ */
public String suggestFileExtension() { public String suggestFileExtension() {

View File

@ -33,7 +33,6 @@ public final class XWPFRelation extends POIXMLRelation {
*/ */
protected static final Map<String, XWPFRelation> _table = new HashMap<String, XWPFRelation>(); protected static final Map<String, XWPFRelation> _table = new HashMap<String, XWPFRelation>();
public static final XWPFRelation DOCUMENT = new XWPFRelation( public static final XWPFRelation DOCUMENT = new XWPFRelation(
"application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml", "application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml",
"http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument", "http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument",
@ -41,10 +40,10 @@ public final class XWPFRelation extends POIXMLRelation {
null null
); );
public static final XWPFRelation TEMPLATE = new XWPFRelation( public static final XWPFRelation TEMPLATE = new XWPFRelation(
"application/vnd.openxmlformats-officedocument.wordprocessingml.template.main+xml", "application/vnd.openxmlformats-officedocument.wordprocessingml.template.main+xml",
"http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument", "http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument",
"/word/document.xml", "/word/document.xml",
null null
); );
public static final XWPFRelation MACRO_DOCUMENT = new XWPFRelation( public static final XWPFRelation MACRO_DOCUMENT = new XWPFRelation(
"application/vnd.ms-word.document.macroEnabled.main+xml", "application/vnd.ms-word.document.macroEnabled.main+xml",
@ -64,12 +63,11 @@ public final class XWPFRelation extends POIXMLRelation {
"/word/glossary/document.xml", "/word/glossary/document.xml",
null null
); );
public static final XWPFRelation NUMBERING = new XWPFRelation( public static final XWPFRelation NUMBERING = new XWPFRelation(
"application/vnd.openxmlformats-officedocument.wordprocessingml.numbering+xml", "application/vnd.openxmlformats-officedocument.wordprocessingml.numbering+xml",
"http://schemas.openxmlformats.org/officeDocument/2006/relationships/numbering", "http://schemas.openxmlformats.org/officeDocument/2006/relationships/numbering",
"/word/numbering.xml", "/word/numbering.xml",
XWPFNumbering.class XWPFNumbering.class
); );
public static final XWPFRelation FONT_TABLE = new XWPFRelation( public static final XWPFRelation FONT_TABLE = new XWPFRelation(
"application/vnd.openxmlformats-officedocument.wordprocessingml.fontTable+xml", "application/vnd.openxmlformats-officedocument.wordprocessingml.fontTable+xml",
@ -126,10 +124,10 @@ public final class XWPFRelation extends POIXMLRelation {
null null
); );
public static final XWPFRelation FOOTNOTE = new XWPFRelation( public static final XWPFRelation FOOTNOTE = new XWPFRelation(
"application/vnd.openxmlformats-officedocument.wordprocessingml.footnotes+xml", "application/vnd.openxmlformats-officedocument.wordprocessingml.footnotes+xml",
"http://schemas.openxmlformats.org/officeDocument/2006/relationships/footnotes", "http://schemas.openxmlformats.org/officeDocument/2006/relationships/footnotes",
"/word/footnotes.xml", "/word/footnotes.xml",
XWPFFootnotes.class XWPFFootnotes.class
); );
public static final XWPFRelation ENDNOTE = new XWPFRelation( public static final XWPFRelation ENDNOTE = new XWPFRelation(
null, null,
@ -137,52 +135,51 @@ public final class XWPFRelation extends POIXMLRelation {
null, null,
null null
); );
/** /**
* Supported image formats * Supported image formats
*/ */
public static final XWPFRelation IMAGE_EMF = new XWPFRelation( public static final XWPFRelation IMAGE_EMF = new XWPFRelation(
"image/x-emf", "image/x-emf",
"http://schemas.openxmlformats.org/officeDocument/2006/relationships/image", "http://schemas.openxmlformats.org/officeDocument/2006/relationships/image",
"/word/media/image#.emf", "/word/media/image#.emf",
XWPFPictureData.class XWPFPictureData.class
); );
public static final XWPFRelation IMAGE_WMF = new XWPFRelation( public static final XWPFRelation IMAGE_WMF = new XWPFRelation(
"image/x-wmf", "image/x-wmf",
"http://schemas.openxmlformats.org/officeDocument/2006/relationships/image", "http://schemas.openxmlformats.org/officeDocument/2006/relationships/image",
"/word/media/image#.wmf", "/word/media/image#.wmf",
XWPFPictureData.class XWPFPictureData.class
); );
public static final XWPFRelation IMAGE_PICT = new XWPFRelation( public static final XWPFRelation IMAGE_PICT = new XWPFRelation(
"image/pict", "image/pict",
"http://schemas.openxmlformats.org/officeDocument/2006/relationships/image", "http://schemas.openxmlformats.org/officeDocument/2006/relationships/image",
"/word/media/image#.pict", "/word/media/image#.pict",
XWPFPictureData.class XWPFPictureData.class
); );
public static final XWPFRelation IMAGE_JPEG = new XWPFRelation( public static final XWPFRelation IMAGE_JPEG = new XWPFRelation(
"image/jpeg", "image/jpeg",
"http://schemas.openxmlformats.org/officeDocument/2006/relationships/image", "http://schemas.openxmlformats.org/officeDocument/2006/relationships/image",
"/word/media/image#.jpeg", "/word/media/image#.jpeg",
XWPFPictureData.class XWPFPictureData.class
); );
public static final XWPFRelation IMAGE_PNG = new XWPFRelation( public static final XWPFRelation IMAGE_PNG = new XWPFRelation(
"image/png", "image/png",
"http://schemas.openxmlformats.org/officeDocument/2006/relationships/image", "http://schemas.openxmlformats.org/officeDocument/2006/relationships/image",
"/word/media/image#.png", "/word/media/image#.png",
XWPFPictureData.class XWPFPictureData.class
); );
public static final XWPFRelation IMAGE_DIB = new XWPFRelation( public static final XWPFRelation IMAGE_DIB = new XWPFRelation(
"image/dib", "image/dib",
"http://schemas.openxmlformats.org/officeDocument/2006/relationships/image", "http://schemas.openxmlformats.org/officeDocument/2006/relationships/image",
"/word/media/image#.dib", "/word/media/image#.dib",
XWPFPictureData.class XWPFPictureData.class
); );
public static final XWPFRelation IMAGE_GIF = new XWPFRelation( public static final XWPFRelation IMAGE_GIF = new XWPFRelation(
"image/gif", "image/gif",
"http://schemas.openxmlformats.org/officeDocument/2006/relationships/image", "http://schemas.openxmlformats.org/officeDocument/2006/relationships/image",
"/word/media/image#.gif", "/word/media/image#.gif",
XWPFPictureData.class XWPFPictureData.class
); );
public static final XWPFRelation IMAGE_TIFF = new XWPFRelation( public static final XWPFRelation IMAGE_TIFF = new XWPFRelation(
"image/tiff", "image/tiff",
"http://schemas.openxmlformats.org/officeDocument/2006/relationships/image", "http://schemas.openxmlformats.org/officeDocument/2006/relationships/image",
@ -207,14 +204,12 @@ public final class XWPFRelation extends POIXMLRelation {
"/word/media/image#.wpg", "/word/media/image#.wpg",
XWPFPictureData.class XWPFPictureData.class
); );
public static final XWPFRelation IMAGES = new XWPFRelation(
public static final XWPFRelation IMAGES = new XWPFRelation( null,
null, "http://schemas.openxmlformats.org/officeDocument/2006/relationships/image",
"http://schemas.openxmlformats.org/officeDocument/2006/relationships/image", null,
null, null
null );
);
private XWPFRelation(String type, String rel, String defaultName, Class<? extends POIXMLDocumentPart> cls) { private XWPFRelation(String type, String rel, String defaultName, Class<? extends POIXMLDocumentPart> cls) {
super(type, rel, defaultName, cls); super(type, rel, defaultName, cls);

View File

@ -35,13 +35,46 @@ import org.apache.xmlbeans.XmlObject;
import org.apache.xmlbeans.XmlString; import org.apache.xmlbeans.XmlString;
import org.apache.xmlbeans.XmlToken; import org.apache.xmlbeans.XmlToken;
import org.apache.xmlbeans.impl.values.XmlAnyTypeImpl; import org.apache.xmlbeans.impl.values.XmlAnyTypeImpl;
import org.openxmlformats.schemas.drawingml.x2006.main.*; import org.openxmlformats.schemas.drawingml.x2006.main.CTBlip;
import org.openxmlformats.schemas.drawingml.x2006.main.CTBlipFillProperties;
import org.openxmlformats.schemas.drawingml.x2006.main.CTGraphicalObject;
import org.openxmlformats.schemas.drawingml.x2006.main.CTGraphicalObjectData;
import org.openxmlformats.schemas.drawingml.x2006.main.CTNonVisualDrawingProps;
import org.openxmlformats.schemas.drawingml.x2006.main.CTNonVisualPictureProperties;
import org.openxmlformats.schemas.drawingml.x2006.main.CTPoint2D;
import org.openxmlformats.schemas.drawingml.x2006.main.CTPositiveSize2D;
import org.openxmlformats.schemas.drawingml.x2006.main.CTPresetGeometry2D;
import org.openxmlformats.schemas.drawingml.x2006.main.CTShapeProperties;
import org.openxmlformats.schemas.drawingml.x2006.main.CTTransform2D;
import org.openxmlformats.schemas.drawingml.x2006.main.STShapeType;
import org.openxmlformats.schemas.drawingml.x2006.picture.CTPicture; import org.openxmlformats.schemas.drawingml.x2006.picture.CTPicture;
import org.openxmlformats.schemas.drawingml.x2006.picture.CTPictureNonVisual; import org.openxmlformats.schemas.drawingml.x2006.picture.CTPictureNonVisual;
import org.openxmlformats.schemas.drawingml.x2006.wordprocessingDrawing.CTAnchor; import org.openxmlformats.schemas.drawingml.x2006.wordprocessingDrawing.CTAnchor;
import org.openxmlformats.schemas.drawingml.x2006.wordprocessingDrawing.CTInline; import org.openxmlformats.schemas.drawingml.x2006.wordprocessingDrawing.CTInline;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.*; import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTBr;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTColor; import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTColor;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTDrawing;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTEmpty;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTFFCheckBox;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTFldChar;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTFonts;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTFtnEdnRef;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTHpsMeasure;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTOnOff;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTPTab;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTR;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTRPr;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTSignedHpsMeasure;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTSignedTwipsMeasure;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTText;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTUnderline;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTVerticalAlignRun;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.STBrClear;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.STBrType;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.STFldCharType;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.STOnOff;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.STUnderline;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.STVerticalAlignRun;
import org.w3c.dom.NodeList; import org.w3c.dom.NodeList;
import org.w3c.dom.Text; import org.w3c.dom.Text;
@ -54,16 +87,6 @@ public class XWPFRun implements ISDTContents, IRunElement, CharacterRun {
private IRunBody parent; private IRunBody parent;
private List<XWPFPicture> pictures; private List<XWPFPicture> pictures;
/**
* @see <a href="http://msdn.microsoft.com/en-us/library/ff533743(v=office.12).aspx">[MS-OI29500] Run Fonts</a>
*/
public static enum FontCharRange {
ascii /* char 0-127 */,
cs /* complex symbol */,
eastAsia /* east asia */,
hAnsi /* high ansi */
};
/** /**
* @param r the CTR bean which holds the run attributes * @param r the CTR bean which holds the run attributes
* @param p the parent paragraph * @param p the parent paragraph
@ -95,7 +118,7 @@ public class XWPFRun implements ISDTContents, IRunElement, CharacterRun {
List<XmlObject> pictTextObjs = new ArrayList<XmlObject>(); List<XmlObject> pictTextObjs = new ArrayList<XmlObject>();
pictTextObjs.addAll(Arrays.asList(r.getPictArray())); pictTextObjs.addAll(Arrays.asList(r.getPictArray()));
pictTextObjs.addAll(Arrays.asList(r.getDrawingArray())); pictTextObjs.addAll(Arrays.asList(r.getDrawingArray()));
for(XmlObject o : pictTextObjs) { for (XmlObject o : pictTextObjs) {
XmlObject[] ts = o.selectPath("declare namespace w='http://schemas.openxmlformats.org/wordprocessingml/2006/main' .//w:t"); XmlObject[] ts = o.selectPath("declare namespace w='http://schemas.openxmlformats.org/wordprocessingml/2006/main' .//w:t");
for (XmlObject t : ts) { for (XmlObject t : ts) {
NodeList kids = t.getDomNode().getChildNodes(); NodeList kids = t.getDomNode().getChildNodes();
@ -113,34 +136,52 @@ public class XWPFRun implements ISDTContents, IRunElement, CharacterRun {
// Do we have any embedded pictures? // Do we have any embedded pictures?
// (They're a different CTPicture, under the drawingml namespace) // (They're a different CTPicture, under the drawingml namespace)
pictures = new ArrayList<XWPFPicture>(); pictures = new ArrayList<XWPFPicture>();
for(XmlObject o : pictTextObjs) { for (XmlObject o : pictTextObjs) {
for(CTPicture pict : getCTPictures(o)) { for (CTPicture pict : getCTPictures(o)) {
XWPFPicture picture = new XWPFPicture(pict, this); XWPFPicture picture = new XWPFPicture(pict, this);
pictures.add(picture); pictures.add(picture);
} }
} }
} }
;
/** /**
* @deprecated Use {@link XWPFRun#XWPFRun(CTR, IRunBody)} * @deprecated Use {@link XWPFRun#XWPFRun(CTR, IRunBody)}
*/ */
public XWPFRun(CTR r, XWPFParagraph p) { public XWPFRun(CTR r, XWPFParagraph p) {
this(r, (IRunBody)p); this(r, (IRunBody) p);
}
/**
* Add the xml:spaces="preserve" attribute if the string has leading or trailing white spaces
*
* @param xs the string to check
*/
static void preserveSpaces(XmlString xs) {
String text = xs.getStringValue();
if (text != null && (text.startsWith(" ") || text.endsWith(" "))) {
XmlCursor c = xs.newCursor();
c.toNextToken();
c.insertAttributeWithValue(new QName("http://www.w3.org/XML/1998/namespace", "space"), "preserve");
c.dispose();
}
} }
private List<CTPicture> getCTPictures(XmlObject o) { private List<CTPicture> getCTPictures(XmlObject o) {
List<CTPicture> pictures = new ArrayList<CTPicture>(); List<CTPicture> pictures = new ArrayList<CTPicture>();
XmlObject[] picts = o.selectPath("declare namespace pic='"+CTPicture.type.getName().getNamespaceURI()+"' .//pic:pic"); XmlObject[] picts = o.selectPath("declare namespace pic='" + CTPicture.type.getName().getNamespaceURI() + "' .//pic:pic");
for(XmlObject pict : picts) { for (XmlObject pict : picts) {
if(pict instanceof XmlAnyTypeImpl) { if (pict instanceof XmlAnyTypeImpl) {
// Pesky XmlBeans bug - see Bugzilla #49934 // Pesky XmlBeans bug - see Bugzilla #49934
try { try {
pict = CTPicture.Factory.parse( pict.toString() ); pict = CTPicture.Factory.parse(pict.toString());
} catch(XmlException e) { } catch (XmlException e) {
throw new POIXMLException(e); throw new POIXMLException(e);
} }
} }
if(pict instanceof CTPicture) { if (pict instanceof CTPicture) {
pictures.add((CTPicture)pict); pictures.add((CTPicture) pict);
} }
} }
return pictures; return pictures;
@ -148,6 +189,7 @@ public class XWPFRun implements ISDTContents, IRunElement, CharacterRun {
/** /**
* Get the currently used CTR object * Get the currently used CTR object
*
* @return ctr object * @return ctr object
*/ */
@Internal @Internal
@ -157,24 +199,27 @@ public class XWPFRun implements ISDTContents, IRunElement, CharacterRun {
/** /**
* Get the currently referenced paragraph/SDT object * Get the currently referenced paragraph/SDT object
*
* @return current parent * @return current parent
*/ */
public IRunBody getParent() { public IRunBody getParent() {
return parent; return parent;
} }
/** /**
* Get the currently referenced paragraph, or null if a SDT object * Get the currently referenced paragraph, or null if a SDT object
*
* @deprecated use {@link XWPFRun#getParent()} instead * @deprecated use {@link XWPFRun#getParent()} instead
*/ */
public XWPFParagraph getParagraph() { public XWPFParagraph getParagraph() {
if (parent instanceof XWPFParagraph) if (parent instanceof XWPFParagraph)
return (XWPFParagraph)parent; return (XWPFParagraph) parent;
return null; return null;
} }
/** /**
* @return The {@link XWPFDocument} instance, this run belongs to, or * @return The {@link XWPFDocument} instance, this run belongs to, or
* <code>null</code> if parent structure (paragraph > document) is not properly set. * <code>null</code> if parent structure (paragraph > document) is not properly set.
*/ */
public XWPFDocument getDocument() { public XWPFDocument getDocument() {
if (parent != null) { if (parent != null) {
@ -187,11 +232,11 @@ public class XWPFRun implements ISDTContents, IRunElement, CharacterRun {
* For isBold, isItalic etc * For isBold, isItalic etc
*/ */
private boolean isCTOnOff(CTOnOff onoff) { private boolean isCTOnOff(CTOnOff onoff) {
if(! onoff.isSetVal()) if (!onoff.isSetVal())
return true; return true;
if(onoff.getVal() == STOnOff.ON) if (onoff.getVal() == STOnOff.ON)
return true; return true;
if(onoff.getVal() == STOnOff.TRUE) if (onoff.getVal() == STOnOff.TRUE)
return true; return true;
return false; return false;
} }
@ -204,7 +249,7 @@ public class XWPFRun implements ISDTContents, IRunElement, CharacterRun {
*/ */
public boolean isBold() { public boolean isBold() {
CTRPr pr = run.getRPr(); CTRPr pr = run.getRPr();
if(pr == null || !pr.isSetB()) { if (pr == null || !pr.isSetB()) {
return false; return false;
} }
return isCTOnOff(pr.getB()); return isCTOnOff(pr.getB());
@ -244,19 +289,20 @@ public class XWPFRun implements ISDTContents, IRunElement, CharacterRun {
* Get text color. The returned value is a string in the hex form "RRGGBB". * Get text color. The returned value is a string in the hex form "RRGGBB".
*/ */
public String getColor() { public String getColor() {
String color = null; String color = null;
if (run.isSetRPr()) { if (run.isSetRPr()) {
CTRPr pr = run.getRPr(); CTRPr pr = run.getRPr();
if (pr.isSetColor()) { if (pr.isSetColor()) {
CTColor clr = pr.getColor(); CTColor clr = pr.getColor();
color = clr.xgetVal().getStringValue(); color = clr.xgetVal().getStringValue();
} }
} }
return color; return color;
} }
/** /**
* Set text color. * Set text color.
*
* @param rgbStr - the desired color, in the hex form "RRGGBB". * @param rgbStr - the desired color, in the hex form "RRGGBB".
*/ */
public void setColor(String rgbStr) { public void setColor(String rgbStr) {
@ -288,17 +334,18 @@ public class XWPFRun implements ISDTContents, IRunElement, CharacterRun {
* @param value the literal text which shall be displayed in the document * @param value the literal text which shall be displayed in the document
*/ */
public void setText(String value) { public void setText(String value) {
setText(value,run.sizeOfTArray()); setText(value, run.sizeOfTArray());
} }
/** /**
* Sets the text of this text run in the * Sets the text of this text run in the
* *
* @param value the literal text which shall be displayed in the document * @param value the literal text which shall be displayed in the document
* @param pos - position in the text array (NB: 0 based) * @param pos - position in the text array (NB: 0 based)
*/ */
public void setText(String value, int pos) { public void setText(String value, int pos) {
if(pos > run.sizeOfTArray()) throw new ArrayIndexOutOfBoundsException("Value too large for the parameter position in XWPFRun.setText(String value,int pos)"); if (pos > run.sizeOfTArray())
throw new ArrayIndexOutOfBoundsException("Value too large for the parameter position in XWPFRun.setText(String value,int pos)");
CTText t = (pos < run.sizeOfTArray() && pos >= 0) ? run.getTArray(pos) : run.addNewT(); CTText t = (pos < run.sizeOfTArray() && pos >= 0) ? run.getTArray(pos) : run.addNewT();
t.setStringValue(value); t.setStringValue(value);
preserveSpaces(t); preserveSpaces(t);
@ -312,7 +359,7 @@ public class XWPFRun implements ISDTContents, IRunElement, CharacterRun {
*/ */
public boolean isItalic() { public boolean isItalic() {
CTRPr pr = run.getRPr(); CTRPr pr = run.getRPr();
if(pr == null || !pr.isSetI()) if (pr == null || !pr.isSetI())
return false; return false;
return isCTOnOff(pr.getI()); return isCTOnOff(pr.getI());
} }
@ -391,26 +438,10 @@ public class XWPFRun implements ISDTContents, IRunElement, CharacterRun {
*/ */
public boolean isStrikeThrough() { public boolean isStrikeThrough() {
CTRPr pr = run.getRPr(); CTRPr pr = run.getRPr();
if(pr == null || !pr.isSetStrike()) if (pr == null || !pr.isSetStrike())
return false; return false;
return isCTOnOff(pr.getStrike()); return isCTOnOff(pr.getStrike());
} }
@Deprecated
public boolean isStrike() {
return isStrikeThrough();
}
/**
* Specifies that the contents of this run shall be displayed with a double
* horizontal line through the center of the line.
*
* @return <code>true</code> if the double strike property is applied
*/
public boolean isDoubleStrikeThrough() {
CTRPr pr = run.getRPr();
if(pr == null || !pr.isSetDstrike())
return false;
return isCTOnOff(pr.getDstrike());
}
/** /**
* Specifies that the contents of this run shall be displayed with a single * Specifies that the contents of this run shall be displayed with a single
@ -441,13 +472,34 @@ public class XWPFRun implements ISDTContents, IRunElement, CharacterRun {
CTOnOff strike = pr.isSetStrike() ? pr.getStrike() : pr.addNewStrike(); CTOnOff strike = pr.isSetStrike() ? pr.getStrike() : pr.addNewStrike();
strike.setVal(value ? STOnOff.TRUE : STOnOff.FALSE); strike.setVal(value ? STOnOff.TRUE : STOnOff.FALSE);
} }
@Deprecated
public boolean isStrike() {
return isStrikeThrough();
}
@Deprecated @Deprecated
public void setStrike(boolean value) { public void setStrike(boolean value) {
setStrikeThrough(value); setStrikeThrough(value);
} }
/**
* Specifies that the contents of this run shall be displayed with a double
* horizontal line through the center of the line.
*
* @return <code>true</code> if the double strike property is applied
*/
public boolean isDoubleStrikeThrough() {
CTRPr pr = run.getRPr();
if (pr == null || !pr.isSetDstrike())
return false;
return isCTOnOff(pr.getDstrike());
}
/** /**
* Specifies that the contents of this run shall be displayed with a * Specifies that the contents of this run shall be displayed with a
* double horizontal line through the center of the line. * double horizontal line through the center of the line.
*
* @see #setStrikeThrough(boolean) for the rules about this * @see #setStrikeThrough(boolean) for the rules about this
*/ */
public void setDoubleStrikethrough(boolean value) { public void setDoubleStrikethrough(boolean value) {
@ -458,21 +510,24 @@ public class XWPFRun implements ISDTContents, IRunElement, CharacterRun {
public boolean isSmallCaps() { public boolean isSmallCaps() {
CTRPr pr = run.getRPr(); CTRPr pr = run.getRPr();
if(pr == null || !pr.isSetSmallCaps()) if (pr == null || !pr.isSetSmallCaps())
return false; return false;
return isCTOnOff(pr.getSmallCaps()); return isCTOnOff(pr.getSmallCaps());
} }
public void setSmallCaps(boolean value) { public void setSmallCaps(boolean value) {
CTRPr pr = run.isSetRPr() ? run.getRPr() : run.addNewRPr(); CTRPr pr = run.isSetRPr() ? run.getRPr() : run.addNewRPr();
CTOnOff caps = pr.isSetSmallCaps() ? pr.getSmallCaps() : pr.addNewSmallCaps(); CTOnOff caps = pr.isSetSmallCaps() ? pr.getSmallCaps() : pr.addNewSmallCaps();
caps.setVal(value ? STOnOff.TRUE : STOnOff.FALSE); caps.setVal(value ? STOnOff.TRUE : STOnOff.FALSE);
} }
public boolean isCapitalized() { public boolean isCapitalized() {
CTRPr pr = run.getRPr(); CTRPr pr = run.getRPr();
if(pr == null || !pr.isSetCaps()) if (pr == null || !pr.isSetCaps())
return false; return false;
return isCTOnOff(pr.getCaps()); return isCTOnOff(pr.getCaps());
} }
public void setCapitalized(boolean value) { public void setCapitalized(boolean value) {
CTRPr pr = run.isSetRPr() ? run.getRPr() : run.addNewRPr(); CTRPr pr = run.isSetRPr() ? run.getRPr() : run.addNewRPr();
CTOnOff caps = pr.isSetCaps() ? pr.getCaps() : pr.addNewCaps(); CTOnOff caps = pr.isSetCaps() ? pr.getCaps() : pr.addNewCaps();
@ -481,10 +536,11 @@ public class XWPFRun implements ISDTContents, IRunElement, CharacterRun {
public boolean isShadowed() { public boolean isShadowed() {
CTRPr pr = run.getRPr(); CTRPr pr = run.getRPr();
if(pr == null || !pr.isSetShadow()) if (pr == null || !pr.isSetShadow())
return false; return false;
return isCTOnOff(pr.getShadow()); return isCTOnOff(pr.getShadow());
} }
public void setShadow(boolean value) { public void setShadow(boolean value) {
CTRPr pr = run.isSetRPr() ? run.getRPr() : run.addNewRPr(); CTRPr pr = run.isSetRPr() ? run.getRPr() : run.addNewRPr();
CTOnOff shadow = pr.isSetShadow() ? pr.getShadow() : pr.addNewShadow(); CTOnOff shadow = pr.isSetShadow() ? pr.getShadow() : pr.addNewShadow();
@ -493,10 +549,11 @@ public class XWPFRun implements ISDTContents, IRunElement, CharacterRun {
public boolean isImprinted() { public boolean isImprinted() {
CTRPr pr = run.getRPr(); CTRPr pr = run.getRPr();
if(pr == null || !pr.isSetImprint()) if (pr == null || !pr.isSetImprint())
return false; return false;
return isCTOnOff(pr.getImprint()); return isCTOnOff(pr.getImprint());
} }
public void setImprinted(boolean value) { public void setImprinted(boolean value) {
CTRPr pr = run.isSetRPr() ? run.getRPr() : run.addNewRPr(); CTRPr pr = run.isSetRPr() ? run.getRPr() : run.addNewRPr();
CTOnOff imprinted = pr.isSetImprint() ? pr.getImprint() : pr.addNewImprint(); CTOnOff imprinted = pr.isSetImprint() ? pr.getImprint() : pr.addNewImprint();
@ -505,10 +562,11 @@ public class XWPFRun implements ISDTContents, IRunElement, CharacterRun {
public boolean isEmbossed() { public boolean isEmbossed() {
CTRPr pr = run.getRPr(); CTRPr pr = run.getRPr();
if(pr == null || !pr.isSetEmboss()) if (pr == null || !pr.isSetEmboss())
return false; return false;
return isCTOnOff(pr.getEmboss()); return isCTOnOff(pr.getEmboss());
} }
public void setEmbossed(boolean value) { public void setEmbossed(boolean value) {
CTRPr pr = run.isSetRPr() ? run.getRPr() : run.addNewRPr(); CTRPr pr = run.isSetRPr() ? run.getRPr() : run.addNewRPr();
CTOnOff emboss = pr.isSetEmboss() ? pr.getEmboss() : pr.addNewEmboss(); CTOnOff emboss = pr.isSetEmboss() ? pr.getEmboss() : pr.addNewEmboss();
@ -553,10 +611,11 @@ public class XWPFRun implements ISDTContents, IRunElement, CharacterRun {
public int getKerning() { public int getKerning() {
CTRPr pr = run.getRPr(); CTRPr pr = run.getRPr();
if(pr == null || !pr.isSetKern()) if (pr == null || !pr.isSetKern())
return 0; return 0;
return pr.getKern().getVal().intValue(); return pr.getKern().getVal().intValue();
} }
public void setKerning(int kern) { public void setKerning(int kern) {
CTRPr pr = run.isSetRPr() ? run.getRPr() : run.addNewRPr(); CTRPr pr = run.isSetRPr() ? run.getRPr() : run.addNewRPr();
CTHpsMeasure kernmes = pr.isSetKern() ? pr.getKern() : pr.addNewKern(); CTHpsMeasure kernmes = pr.isSetKern() ? pr.getKern() : pr.addNewKern();
@ -565,10 +624,11 @@ public class XWPFRun implements ISDTContents, IRunElement, CharacterRun {
public int getCharacterSpacing() { public int getCharacterSpacing() {
CTRPr pr = run.getRPr(); CTRPr pr = run.getRPr();
if(pr == null || !pr.isSetSpacing()) if (pr == null || !pr.isSetSpacing())
return 0; return 0;
return pr.getSpacing().getVal().intValue(); return pr.getSpacing().getVal().intValue();
} }
public void setCharacterSpacing(int twips) { public void setCharacterSpacing(int twips) {
CTRPr pr = run.isSetRPr() ? run.getRPr() : run.addNewRPr(); CTRPr pr = run.isSetRPr() ? run.getRPr() : run.addNewRPr();
CTSignedTwipsMeasure spc = pr.isSetSpacing() ? pr.getSpacing() : pr.addNewSpacing(); CTSignedTwipsMeasure spc = pr.isSetSpacing() ? pr.getSpacing() : pr.addNewSpacing();
@ -585,6 +645,21 @@ public class XWPFRun implements ISDTContents, IRunElement, CharacterRun {
public String getFontFamily() { public String getFontFamily() {
return getFontFamily(null); return getFontFamily(null);
} }
/**
* Specifies the fonts which shall be used to display the text contents of
* this run. Specifies a font which shall be used to format all characters
* in the ASCII range (0 - 127) within the parent run.
* <p/>
* Also sets the other font ranges, if they haven't been set before
*
* @param fontFamily
* @see FontCharRange
*/
public void setFontFamily(String fontFamily) {
setFontFamily(fontFamily, null);
}
/** /**
* Alias for {@link #getFontFamily()} * Alias for {@link #getFontFamily()}
*/ */
@ -597,7 +672,7 @@ public class XWPFRun implements ISDTContents, IRunElement, CharacterRun {
* If fcr is null, the font char range "ascii" is used * If fcr is null, the font char range "ascii" is used
* *
* @param fcr the font char range, defaults to "ansi" * @param fcr the font char range, defaults to "ansi"
* @return a string representing the font famil * @return a string representing the font famil
*/ */
public String getFontFamily(FontCharRange fcr) { public String getFontFamily(FontCharRange fcr) {
CTRPr pr = run.getRPr(); CTRPr pr = run.getRPr();
@ -605,34 +680,18 @@ public class XWPFRun implements ISDTContents, IRunElement, CharacterRun {
CTFonts fonts = pr.getRFonts(); CTFonts fonts = pr.getRFonts();
switch (fcr == null ? FontCharRange.ascii : fcr) { switch (fcr == null ? FontCharRange.ascii : fcr) {
default: default:
case ascii: case ascii:
return fonts.getAscii(); return fonts.getAscii();
case cs: case cs:
return fonts.getCs(); return fonts.getCs();
case eastAsia: case eastAsia:
return fonts.getEastAsia(); return fonts.getEastAsia();
case hAnsi: case hAnsi:
return fonts.getHAnsi(); return fonts.getHAnsi();
} }
} }
/**
* Specifies the fonts which shall be used to display the text contents of
* this run. Specifies a font which shall be used to format all characters
* in the ASCII range (0 - 127) within the parent run.
*
* Also sets the other font ranges, if they haven't been set before
*
* @param fontFamily
*
* @see FontCharRange
*/
public void setFontFamily(String fontFamily) {
setFontFamily(fontFamily, null);
}
/** /**
* Specifies the fonts which shall be used to display the text contents of * Specifies the fonts which shall be used to display the text contents of
* this run. The default handling for fcr == null is to overwrite the * this run. The default handling for fcr == null is to overwrite the
@ -640,7 +699,7 @@ public class XWPFRun implements ISDTContents, IRunElement, CharacterRun {
* specified font ranges * specified font ranges
* *
* @param fontFamily * @param fontFamily
* @param fcr FontCharRange or null for default handling * @param fcr FontCharRange or null for default handling
*/ */
public void setFontFamily(String fontFamily, FontCharRange fcr) { public void setFontFamily(String fontFamily, FontCharRange fcr) {
CTRPr pr = run.isSetRPr() ? run.getRPr() : run.addNewRPr(); CTRPr pr = run.isSetRPr() ? run.getRPr() : run.addNewRPr();
@ -659,18 +718,18 @@ public class XWPFRun implements ISDTContents, IRunElement, CharacterRun {
} }
} else { } else {
switch (fcr) { switch (fcr) {
case ascii: case ascii:
fonts.setAscii(fontFamily); fonts.setAscii(fontFamily);
break; break;
case cs: case cs:
fonts.setCs(fontFamily); fonts.setCs(fontFamily);
break; break;
case eastAsia: case eastAsia:
fonts.setEastAsia(fontFamily); fonts.setEastAsia(fontFamily);
break; break;
case hAnsi: case hAnsi:
fonts.setHAnsi(fontFamily); fonts.setHAnsi(fontFamily);
break; break;
} }
} }
} }
@ -699,7 +758,7 @@ public class XWPFRun implements ISDTContents, IRunElement, CharacterRun {
* @param size * @param size
*/ */
public void setFontSize(int size) { public void setFontSize(int size) {
BigInteger bint=new BigInteger(""+size); BigInteger bint = new BigInteger("" + size);
CTRPr pr = run.isSetRPr() ? run.getRPr() : run.addNewRPr(); CTRPr pr = run.isSetRPr() ? run.getRPr() : run.addNewRPr();
CTHpsMeasure ctSize = pr.isSetSz() ? pr.getSz() : pr.addNewSz(); CTHpsMeasure ctSize = pr.isSetSz() ? pr.getSz() : pr.addNewSz();
ctSize.setVal(bint.multiply(new BigInteger("2"))); ctSize.setVal(bint.multiply(new BigInteger("2")));
@ -742,7 +801,7 @@ public class XWPFRun implements ISDTContents, IRunElement, CharacterRun {
* @param val * @param val
*/ */
public void setTextPosition(int val) { public void setTextPosition(int val) {
BigInteger bint=new BigInteger(""+val); BigInteger bint = new BigInteger("" + val);
CTRPr pr = run.isSetRPr() ? run.getRPr() : run.addNewRPr(); CTRPr pr = run.isSetRPr() ? run.getRPr() : run.addNewRPr();
CTSignedHpsMeasure position = pr.isSetPosition() ? pr.getPosition() : pr.addNewPosition(); CTSignedHpsMeasure position = pr.isSetPosition() ? pr.getPosition() : pr.addNewPosition();
position.setVal(bint); position.setVal(bint);
@ -761,6 +820,7 @@ public class XWPFRun implements ISDTContents, IRunElement, CharacterRun {
* A break is a special character which is used to override the * A break is a special character which is used to override the
* normal line breaking that would be performed based on the normal layout * normal line breaking that would be performed based on the normal layout
* of the document's contents. * of the document's contents.
*
* @see #addCarriageReturn() * @see #addCarriageReturn()
*/ */
public void addBreak() { public void addBreak() {
@ -778,10 +838,11 @@ public class XWPFRun implements ISDTContents, IRunElement, CharacterRun {
* location where text shall be restarted after this break) shall be * location where text shall be restarted after this break) shall be
* determined by its type values. * determined by its type values.
* </p> * </p>
*
* @see BreakType * @see BreakType
*/ */
public void addBreak(BreakType type){ public void addBreak(BreakType type) {
CTBr br=run.addNewBr(); CTBr br = run.addNewBr();
br.setType(STBrType.Enum.forInt(type.getValue())); br.setType(STBrType.Enum.forInt(type.getValue()));
} }
@ -795,17 +856,18 @@ public class XWPFRun implements ISDTContents, IRunElement, CharacterRun {
* location where text shall be restarted after this break) shall be * location where text shall be restarted after this break) shall be
* determined by its type (in this case is BreakType.TEXT_WRAPPING as default) and clear attribute values. * determined by its type (in this case is BreakType.TEXT_WRAPPING as default) and clear attribute values.
* </p> * </p>
*
* @see BreakClear * @see BreakClear
*/ */
public void addBreak(BreakClear clear){ public void addBreak(BreakClear clear) {
CTBr br=run.addNewBr(); CTBr br = run.addNewBr();
br.setType(STBrType.Enum.forInt(BreakType.TEXT_WRAPPING.getValue())); br.setType(STBrType.Enum.forInt(BreakType.TEXT_WRAPPING.getValue()));
br.setClear(STBrClear.Enum.forInt(clear.getValue())); br.setClear(STBrClear.Enum.forInt(clear.getValue()));
} }
/** /**
* Specifies that a tab shall be placed at the current location in * Specifies that a tab shall be placed at the current location in
* the run content. * the run content.
*/ */
public void addTab() { public void addTab() {
run.addNewTab(); run.addNewTab();
@ -837,24 +899,23 @@ public class XWPFRun implements ISDTContents, IRunElement, CharacterRun {
/** /**
* Adds a picture to the run. This method handles * Adds a picture to the run. This method handles
* attaching the picture data to the overall file. * attaching the picture data to the overall file.
* *
* @param pictureData The raw picture data
* @param pictureType The type of the picture, eg {@link Document#PICTURE_TYPE_JPEG}
* @param width width in EMUs. To convert to / from points use {@link org.apache.poi.util.Units}
* @param height height in EMUs. To convert to / from points use {@link org.apache.poi.util.Units}
* @throws org.apache.poi.openxml4j.exceptions.InvalidFormatException
* @throws IOException
* @see org.apache.poi.xwpf.usermodel.Document#PICTURE_TYPE_EMF * @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_WMF
* @see org.apache.poi.xwpf.usermodel.Document#PICTURE_TYPE_PICT * @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_JPEG
* @see org.apache.poi.xwpf.usermodel.Document#PICTURE_TYPE_PNG * @see org.apache.poi.xwpf.usermodel.Document#PICTURE_TYPE_PNG
* @see org.apache.poi.xwpf.usermodel.Document#PICTURE_TYPE_DIB * @see org.apache.poi.xwpf.usermodel.Document#PICTURE_TYPE_DIB
*
* @param pictureData The raw picture data
* @param pictureType The type of the picture, eg {@link Document#PICTURE_TYPE_JPEG}
* @param width width in EMUs. To convert to / from points use {@link org.apache.poi.util.Units}
* @param height height in EMUs. To convert to / from points use {@link org.apache.poi.util.Units}
* @throws org.apache.poi.openxml4j.exceptions.InvalidFormatException
* @throws IOException
*/ */
public XWPFPicture addPicture(InputStream pictureData, int pictureType, String filename, int width, int height) public XWPFPicture addPicture(InputStream pictureData, int pictureType, String filename, int width, int height)
throws InvalidFormatException, IOException { throws InvalidFormatException, IOException {
XWPFDocument doc = parent.getDocument(); XWPFDocument doc = parent.getDocument();
// Add the picture + relationship // Add the picture + relationship
@ -869,11 +930,11 @@ public class XWPFRun implements ISDTContents, IRunElement, CharacterRun {
// Do the fiddly namespace bits on the inline // Do the fiddly namespace bits on the inline
// (We need full control of what goes where and as what) // (We need full control of what goes where and as what)
String xml = String xml =
"<a:graphic xmlns:a=\"" + CTGraphicalObject.type.getName().getNamespaceURI() + "\">" + "<a:graphic xmlns:a=\"" + CTGraphicalObject.type.getName().getNamespaceURI() + "\">" +
"<a:graphicData uri=\"" + CTPicture.type.getName().getNamespaceURI() + "\">" + "<a:graphicData uri=\"" + CTPicture.type.getName().getNamespaceURI() + "\">" +
"<pic:pic xmlns:pic=\"" + CTPicture.type.getName().getNamespaceURI() + "\" />" + "<pic:pic xmlns:pic=\"" + CTPicture.type.getName().getNamespaceURI() + "\" />" +
"</a:graphicData>" + "</a:graphicData>" +
"</a:graphic>"; "</a:graphic>";
inline.set(XmlToken.Factory.parse(xml)); inline.set(XmlToken.Factory.parse(xml));
// Setup the inline // Setup the inline
@ -913,7 +974,7 @@ public class XWPFRun implements ISDTContents, IRunElement, CharacterRun {
CTBlipFillProperties blipFill = pic.addNewBlipFill(); CTBlipFillProperties blipFill = pic.addNewBlipFill();
CTBlip blip = blipFill.addNewBlip(); CTBlip blip = blipFill.addNewBlip();
blip.setEmbed( picData.getPackageRelationship().getId() ); blip.setEmbed(picData.getPackageRelationship().getId());
blipFill.addNewStretch().addNewFillRect(); blipFill.addNewStretch().addNewFillRect();
CTShapeProperties spPr = pic.addNewSpPr(); CTShapeProperties spPr = pic.addNewSpPr();
@ -935,44 +996,30 @@ public class XWPFRun implements ISDTContents, IRunElement, CharacterRun {
XWPFPicture xwpfPicture = new XWPFPicture(pic, this); XWPFPicture xwpfPicture = new XWPFPicture(pic, this);
pictures.add(xwpfPicture); pictures.add(xwpfPicture);
return xwpfPicture; return xwpfPicture;
} catch(XmlException e) { } catch (XmlException e) {
throw new IllegalStateException(e); throw new IllegalStateException(e);
} }
} }
/** /**
* Returns the embedded pictures of the run. These * Returns the embedded pictures of the run. These
* are pictures which reference an external, * are pictures which reference an external,
* embedded picture image such as a .png or .jpg * embedded picture image such as a .png or .jpg
*/ */
public List<XWPFPicture> getEmbeddedPictures() { public List<XWPFPicture> getEmbeddedPictures() {
return pictures; return pictures;
} }
/**
* Add the xml:spaces="preserve" attribute if the string has leading or trailing white spaces
*
* @param xs the string to check
*/
static void preserveSpaces(XmlString xs) {
String text = xs.getStringValue();
if (text != null && (text.startsWith(" ") || text.endsWith(" "))) {
XmlCursor c = xs.newCursor();
c.toNextToken();
c.insertAttributeWithValue(new QName("http://www.w3.org/XML/1998/namespace", "space"), "preserve");
c.dispose();
}
}
/** /**
* Returns the string version of the text * Returns the string version of the text
*/ */
public String toString() { public String toString() {
return text(); return text();
} }
/** /**
* Returns the string version of the text, with tabs and * Returns the string version of the text, with tabs and
* carriage returns in place of their xml equivalents. * carriage returns in place of their xml equivalents.
*/ */
public String text() { public String text() {
StringBuffer text = new StringBuffer(); StringBuffer text = new StringBuffer();
@ -994,18 +1041,18 @@ public class XWPFRun implements ISDTContents, IRunElement, CharacterRun {
} }
// Complex type evaluation (currently only for extraction of check boxes) // Complex type evaluation (currently only for extraction of check boxes)
if(o instanceof CTFldChar) { if (o instanceof CTFldChar) {
CTFldChar ctfldChar = ((CTFldChar)o); CTFldChar ctfldChar = ((CTFldChar) o);
if(ctfldChar.getFldCharType() == STFldCharType.BEGIN) { if (ctfldChar.getFldCharType() == STFldCharType.BEGIN) {
if(ctfldChar.getFfData() != null) { if (ctfldChar.getFfData() != null) {
for(CTFFCheckBox checkBox : ctfldChar.getFfData().getCheckBoxList()) { for (CTFFCheckBox checkBox : ctfldChar.getFfData().getCheckBoxList()) {
if(checkBox.getDefault().getVal() == STOnOff.X_1) { if (checkBox.getDefault().getVal() == STOnOff.X_1) {
text.append("|X|"); text.append("|X|");
} else { } else {
text.append("|_|"); text.append("|_|");
}
} }
} }
}
} }
} }
@ -1033,9 +1080,9 @@ public class XWPFRun implements ISDTContents, IRunElement, CharacterRun {
} }
} }
if (o instanceof CTFtnEdnRef) { if (o instanceof CTFtnEdnRef) {
CTFtnEdnRef ftn = (CTFtnEdnRef)o; CTFtnEdnRef ftn = (CTFtnEdnRef) o;
String footnoteRef = ftn.getDomNode().getLocalName().equals("footnoteReference") ? String footnoteRef = ftn.getDomNode().getLocalName().equals("footnoteReference") ?
"[footnoteRef:" + ftn.getId().intValue() + "]" : "[endnoteRef:" + ftn.getId().intValue() + "]"; "[footnoteRef:" + ftn.getId().intValue() + "]" : "[endnoteRef:" + ftn.getId().intValue() + "]";
text.append(footnoteRef); text.append(footnoteRef);
} }
} }
@ -1043,10 +1090,20 @@ public class XWPFRun implements ISDTContents, IRunElement, CharacterRun {
c.dispose(); c.dispose();
// Any picture text? // Any picture text?
if(pictureText != null && pictureText.length() > 0) { if (pictureText != null && pictureText.length() > 0) {
text.append("\n").append(pictureText); text.append("\n").append(pictureText);
} }
return text.toString(); return text.toString();
} }
/**
* @see <a href="http://msdn.microsoft.com/en-us/library/ff533743(v=office.12).aspx">[MS-OI29500] Run Fonts</a>
*/
public static enum FontCharRange {
ascii /* char 0-127 */,
cs /* complex symbol */,
eastAsia /* east asia */,
hAnsi /* high ansi */
}
} }

View File

@ -21,27 +21,26 @@ import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTSdtRun;
/** /**
* Experimental class to offer rudimentary read-only processing of * Experimental class to offer rudimentary read-only processing of
* of StructuredDocumentTags/ContentControl * of StructuredDocumentTags/ContentControl
* * <p/>
* WARNING - APIs expected to change rapidly * WARNING - APIs expected to change rapidly
*
*/ */
public class XWPFSDT extends AbstractXWPFSDT public class XWPFSDT extends AbstractXWPFSDT
implements IBodyElement, IRunBody, ISDTContents, IRunElement { implements IBodyElement, IRunBody, ISDTContents, IRunElement {
private final ISDTContent content; private final ISDTContent content;
public XWPFSDT(CTSdtRun sdtRun, IBody part){ public XWPFSDT(CTSdtRun sdtRun, IBody part) {
super(sdtRun.getSdtPr(), part); super(sdtRun.getSdtPr(), part);
this.content = new XWPFSDTContent(sdtRun.getSdtContent(), part, this); this.content = new XWPFSDTContent(sdtRun.getSdtContent(), part, this);
} }
public XWPFSDT(CTSdtBlock block, IBody part){ public XWPFSDT(CTSdtBlock block, IBody part) {
super(block.getSdtPr(), part); super(block.getSdtPr(), part);
this.content = new XWPFSDTContent( block.getSdtContent(), part, this); this.content = new XWPFSDTContent(block.getSdtContent(), part, this);
} }
public ISDTContent getContent(){ public ISDTContent getContent() {
return content; return content;
} }
} }

View File

@ -20,25 +20,24 @@ import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTSdtCell;
/** /**
* Experimental class to offer rudimentary read-only processing of * Experimental class to offer rudimentary read-only processing of
* of StructuredDocumentTags/ContentControl that can appear * of StructuredDocumentTags/ContentControl that can appear
* in a table row as if a table cell. * in a table row as if a table cell.
* <p> * <p/>
* These can contain one or more cells or other SDTs within them. * These can contain one or more cells or other SDTs within them.
* * <p/>
* WARNING - APIs expected to change rapidly * WARNING - APIs expected to change rapidly
*
*/ */
public class XWPFSDTCell extends AbstractXWPFSDT implements ICell { public class XWPFSDTCell extends AbstractXWPFSDT implements ICell {
private final XWPFSDTContentCell cellContent; private final XWPFSDTContentCell cellContent;
public XWPFSDTCell(CTSdtCell sdtCell, XWPFTableRow xwpfTableRow, IBody part){ public XWPFSDTCell(CTSdtCell sdtCell, XWPFTableRow xwpfTableRow, IBody part) {
super(sdtCell.getSdtPr(), part); super(sdtCell.getSdtPr(), part);
cellContent = new XWPFSDTContentCell(sdtCell.getSdtContent(), xwpfTableRow, part); cellContent = new XWPFSDTContentCell(sdtCell.getSdtContent(), xwpfTableRow, part);
} }
@Override @Override
public ISDTContent getContent(){ public ISDTContent getContent() {
return cellContent; return cellContent;
} }
} }

View File

@ -19,12 +19,10 @@ package org.apache.poi.xwpf.usermodel;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import org.apache.xmlbeans.XmlCursor; import org.apache.xmlbeans.XmlCursor;
import org.apache.xmlbeans.XmlObject; import org.apache.xmlbeans.XmlObject;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTP; import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTP;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTR; import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTR;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTSdtBlock; import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTSdtBlock;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTSdtContentBlock; import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTSdtContentBlock;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTSdtContentRun; import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTSdtContentRun;
@ -32,12 +30,11 @@ import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTbl;
/** /**
* Experimental class to offer rudimentary read-only processing of * Experimental class to offer rudimentary read-only processing of
* of the contentblock of an SDT/ContentControl. * of the contentblock of an SDT/ContentControl.
* * <p/>
* * <p/>
* * <p/>
* WARNING - APIs expected to change rapidly * WARNING - APIs expected to change rapidly
*
*/ */
public class XWPFSDTContent implements ISDTContent { public class XWPFSDTContent implements ISDTContent {
@ -49,14 +46,15 @@ public class XWPFSDTContent implements ISDTContent {
private List<XWPFSDT> contentControls = new ArrayList<XWPFSDT>(); private List<XWPFSDT> contentControls = new ArrayList<XWPFSDT>();
private List<ISDTContents> bodyElements = new ArrayList<ISDTContents>(); private List<ISDTContents> bodyElements = new ArrayList<ISDTContents>();
public XWPFSDTContent(CTSdtContentRun sdtRun, IBody part, IRunBody parent){ public XWPFSDTContent(CTSdtContentRun sdtRun, IBody part, IRunBody parent) {
for (CTR ctr : sdtRun.getRArray()){ for (CTR ctr : sdtRun.getRArray()) {
XWPFRun run = new XWPFRun(ctr, parent); XWPFRun run = new XWPFRun(ctr, parent);
runs.add(run); runs.add(run);
bodyElements.add(run); bodyElements.add(run);
} }
} }
public XWPFSDTContent(CTSdtContentBlock block, IBody part, IRunBody parent){
public XWPFSDTContent(CTSdtContentBlock block, IBody part, IRunBody parent) {
XmlCursor cursor = block.newCursor(); XmlCursor cursor = block.newCursor();
cursor.selectPath("./*"); cursor.selectPath("./*");
while (cursor.toNextSelection()) { while (cursor.toNextSelection()) {
@ -69,8 +67,8 @@ public class XWPFSDTContent implements ISDTContent {
XWPFTable t = new XWPFTable((CTTbl) o, part); XWPFTable t = new XWPFTable((CTTbl) o, part);
bodyElements.add(t); bodyElements.add(t);
tables.add(t); tables.add(t);
} else if (o instanceof CTSdtBlock){ } else if (o instanceof CTSdtBlock) {
XWPFSDT c = new XWPFSDT(((CTSdtBlock)o), part); XWPFSDT c = new XWPFSDT(((CTSdtBlock) o), part);
bodyElements.add(c); bodyElements.add(c);
contentControls.add(c); contentControls.add(c);
} else if (o instanceof CTR) { } else if (o instanceof CTR) {
@ -81,25 +79,25 @@ public class XWPFSDTContent implements ISDTContent {
} }
} }
public String getText(){ public String getText() {
StringBuilder text = new StringBuilder(); StringBuilder text = new StringBuilder();
boolean addNewLine = false; boolean addNewLine = false;
for (int i = 0; i < bodyElements.size(); i++){ for (int i = 0; i < bodyElements.size(); i++) {
Object o = bodyElements.get(i); Object o = bodyElements.get(i);
if (o instanceof XWPFParagraph){ if (o instanceof XWPFParagraph) {
appendParagraph((XWPFParagraph)o, text); appendParagraph((XWPFParagraph) o, text);
addNewLine = true; addNewLine = true;
} else if (o instanceof XWPFTable){ } else if (o instanceof XWPFTable) {
appendTable((XWPFTable)o, text); appendTable((XWPFTable) o, text);
addNewLine = true; addNewLine = true;
} else if (o instanceof XWPFSDT){ } else if (o instanceof XWPFSDT) {
text.append(((XWPFSDT)o).getContent().getText()); text.append(((XWPFSDT) o).getContent().getText());
addNewLine = true; addNewLine = true;
} else if (o instanceof XWPFRun){ } else if (o instanceof XWPFRun) {
text.append(((XWPFRun)o).toString()); text.append(((XWPFRun) o).toString());
addNewLine = false; addNewLine = false;
} }
if (addNewLine == true && i < bodyElements.size()-1){ if (addNewLine == true && i < bodyElements.size() - 1) {
text.append("\n"); text.append("\n");
} }
} }
@ -113,11 +111,11 @@ public class XWPFSDTContent implements ISDTContent {
for (int i = 0; i < cells.size(); i++) { for (int i = 0; i < cells.size(); i++) {
ICell cell = cells.get(i); ICell cell = cells.get(i);
if (cell instanceof XWPFTableCell) { if (cell instanceof XWPFTableCell) {
text.append(((XWPFTableCell)cell).getTextRecursively()); text.append(((XWPFTableCell) cell).getTextRecursively());
} else if (cell instanceof XWPFSDTCell) { } else if (cell instanceof XWPFSDTCell) {
text.append(((XWPFSDTCell)cell).getContent().getText()); text.append(((XWPFSDTCell) cell).getContent().getText());
} }
if (i < cells.size()-1) { if (i < cells.size() - 1) {
text.append("\t"); text.append("\t");
} }
} }
@ -126,12 +124,12 @@ public class XWPFSDTContent implements ISDTContent {
} }
private void appendParagraph(XWPFParagraph paragraph, StringBuilder text) { private void appendParagraph(XWPFParagraph paragraph, StringBuilder text) {
for(IRunElement run : paragraph.getRuns()) { for (IRunElement run : paragraph.getRuns()) {
text.append(run.toString()); text.append(run.toString());
} }
} }
public String toString(){ public String toString() {
return getText(); return getText();
} }
} }

View File

@ -21,17 +21,14 @@ import javax.xml.namespace.QName;
import org.apache.xmlbeans.XmlCursor; import org.apache.xmlbeans.XmlCursor;
import org.apache.xmlbeans.XmlCursor.TokenType; import org.apache.xmlbeans.XmlCursor.TokenType;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTSdtContentCell; import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTSdtContentCell;
/** /**
* Experimental class to offer rudimentary read-only processing of * Experimental class to offer rudimentary read-only processing of
* of the XWPFSDTCellContent. * of the XWPFSDTCellContent.
* <p/>
* WARNING - APIs expected to change rapidly * WARNING - APIs expected to change rapidly
*
*/ */
public class XWPFSDTContentCell implements ISDTContent { public class XWPFSDTContentCell implements ISDTContent {
@ -44,8 +41,9 @@ public class XWPFSDTContentCell implements ISDTContent {
//private List<ICell> cells = new ArrayList<ICell>(). //private List<ICell> cells = new ArrayList<ICell>().
private String text = ""; private String text = "";
public XWPFSDTContentCell(CTSdtContentCell sdtContentCell, public XWPFSDTContentCell(CTSdtContentCell sdtContentCell,
XWPFTableRow xwpfTableRow, IBody part){ XWPFTableRow xwpfTableRow, IBody part) {
super(); super();
StringBuilder sb = new StringBuilder(); StringBuilder sb = new StringBuilder();
XmlCursor cursor = sdtContentCell.newCursor(); XmlCursor cursor = sdtContentCell.newCursor();
@ -62,7 +60,7 @@ public class XWPFSDTContentCell implements ISDTContent {
while (cursor.hasNextToken() && depth > 0) { while (cursor.hasNextToken() && depth > 0) {
TokenType t = cursor.toNextToken(); TokenType t = cursor.toNextToken();
if (t.isText()){ if (t.isText()) {
sb.append(cursor.getTextValue()); sb.append(cursor.getTextValue());
} else if (isStartToken(cursor, "tr")) { } else if (isStartToken(cursor, "tr")) {
tcCnt = 0; tcCnt = 0;
@ -80,9 +78,9 @@ public class XWPFSDTContentCell implements ISDTContent {
} }
iBodyCnt++; iBodyCnt++;
} }
if (cursor.isStart()){ if (cursor.isStart()) {
depth++; depth++;
} else if (cursor.isEnd()){ } else if (cursor.isEnd()) {
depth--; depth--;
} }
} }
@ -90,9 +88,8 @@ public class XWPFSDTContentCell implements ISDTContent {
} }
private boolean isStartToken(XmlCursor cursor, String string) { private boolean isStartToken(XmlCursor cursor, String string) {
if (! cursor.isStart()) { if (!cursor.isStart()) {
return false; return false;
} }
QName qName = cursor.getName(); QName qName = cursor.getName();
@ -104,11 +101,11 @@ public class XWPFSDTContentCell implements ISDTContent {
} }
public String getText(){ public String getText() {
return text; return text;
} }
public String toString(){ public String toString() {
return getText(); return getText();
} }
} }

View File

@ -59,8 +59,7 @@ public class XWPFSettings extends POIXMLDocumentPart {
} }
@Override @Override
protected void onDocumentRead() throws IOException protected void onDocumentRead() throws IOException {
{
super.onDocumentRead(); super.onDocumentRead();
readFrom(getPackagePart().getInputStream()); readFrom(getPackagePart().getInputStream());
} }
@ -74,17 +73,18 @@ public class XWPFSettings extends POIXMLDocumentPart {
* <pre> * <pre>
* &lt;w:zoom w:percent="50" /&gt; * &lt;w:zoom w:percent="50" /&gt;
* <pre> * <pre>
*
* @return percentage as an integer of zoom level * @return percentage as an integer of zoom level
*/ */
public long getZoomPercent() { public long getZoomPercent() {
CTZoom zoom; CTZoom zoom;
if (!ctSettings.isSetZoom()) { if (!ctSettings.isSetZoom()) {
zoom = ctSettings.addNewZoom(); zoom = ctSettings.addNewZoom();
} else { } else {
zoom = ctSettings.getZoom(); zoom = ctSettings.getZoom();
} }
return zoom.getPercent().longValue(); return zoom.getPercent().longValue();
} }
/** /**
@ -98,18 +98,18 @@ public class XWPFSettings extends POIXMLDocumentPart {
* <pre> * <pre>
*/ */
public void setZoomPercent(long zoomPercent) { public void setZoomPercent(long zoomPercent) {
if (! ctSettings.isSetZoom()) { if (!ctSettings.isSetZoom()) {
ctSettings.addNewZoom(); ctSettings.addNewZoom();
} }
CTZoom zoom = ctSettings.getZoom(); CTZoom zoom = ctSettings.getZoom();
zoom.setPercent(BigInteger.valueOf(zoomPercent)); zoom.setPercent(BigInteger.valueOf(zoomPercent));
} }
/** /**
* Verifies the documentProtection tag inside settings.xml file <br/> * Verifies the documentProtection tag inside settings.xml file <br/>
* if the protection is enforced (w:enforcement="1") <br/> * if the protection is enforced (w:enforcement="1") <br/>
* and if the kind of protection equals to passed (STDocProtect.Enum editValue) <br/> * and if the kind of protection equals to passed (STDocProtect.Enum editValue) <br/>
* * <p/>
* <br/> * <br/>
* sample snippet from settings.xml * sample snippet from settings.xml
* <pre> * <pre>
@ -160,12 +160,12 @@ public class XWPFSettings extends POIXMLDocumentPart {
* </pre> * </pre>
* *
* @param editValue the protection type * @param editValue the protection type
* @param password the plaintext password, if null no password will be applied * @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. * @param hashAlgo the hash algorithm - only md2, m5, sha1, sha256, sha384 and sha512 are supported.
* if null, it will default default to sha1 * if null, it will default default to sha1
*/ */
public void setEnforcementEditValue(org.openxmlformats.schemas.wordprocessingml.x2006.main.STDocProtect.Enum editValue, 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().setEnforcement(STOnOff.X_1);
safeGetDocumentProtection().setEdit(editValue); safeGetDocumentProtection().setEdit(editValue);
@ -201,37 +201,37 @@ public class XWPFSettings extends POIXMLDocumentPart {
final STCryptProv.Enum providerType; final STCryptProv.Enum providerType;
final int sid; final int sid;
switch (hashAlgo) { switch (hashAlgo) {
case md2: case md2:
providerType = STCryptProv.RSA_FULL; providerType = STCryptProv.RSA_FULL;
sid = 1; sid = 1;
break; break;
case md4: case md4:
providerType = STCryptProv.RSA_FULL; providerType = STCryptProv.RSA_FULL;
sid = 2; sid = 2;
break; break;
case md5: case md5:
providerType = STCryptProv.RSA_FULL; providerType = STCryptProv.RSA_FULL;
sid = 3; sid = 3;
break; break;
case sha1: case sha1:
providerType = STCryptProv.RSA_FULL; providerType = STCryptProv.RSA_FULL;
sid = 4; sid = 4;
break; break;
case sha256: case sha256:
providerType = STCryptProv.RSA_AES; providerType = STCryptProv.RSA_AES;
sid = 12; sid = 12;
break; break;
case sha384: case sha384:
providerType = STCryptProv.RSA_AES; providerType = STCryptProv.RSA_AES;
sid = 13; sid = 13;
break; break;
case sha512: case sha512:
providerType = STCryptProv.RSA_AES; providerType = STCryptProv.RSA_AES;
sid = 14; sid = 14;
break; break;
default: default:
throw new EncryptedDocumentException throw new EncryptedDocumentException
("Hash algorithm '"+hashAlgo+"' is not supported for document write protection."); ("Hash algorithm '" + hashAlgo + "' is not supported for document write protection.");
} }
@ -276,14 +276,29 @@ public class XWPFSettings extends POIXMLDocumentPart {
HashAlgorithm hashAlgo; HashAlgorithm hashAlgo;
switch (sid.intValue()) { switch (sid.intValue()) {
case 1: hashAlgo = HashAlgorithm.md2; break; case 1:
case 2: hashAlgo = HashAlgorithm.md4; break; hashAlgo = HashAlgorithm.md2;
case 3: hashAlgo = HashAlgorithm.md5; break; break;
case 4: hashAlgo = HashAlgorithm.sha1; break; case 2:
case 12: hashAlgo = HashAlgorithm.sha256; break; hashAlgo = HashAlgorithm.md4;
case 13: hashAlgo = HashAlgorithm.sha384; break; break;
case 14: hashAlgo = HashAlgorithm.sha512; break; case 3:
default: return false; 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); String legacyHash = CryptoFunctions.xorHashPasswordReversed(password);
@ -308,18 +323,18 @@ public class XWPFSettings extends POIXMLDocumentPart {
* Enforces fields update on document open (in Word). * Enforces fields update on document open (in Word).
* In the settings.xml file <br/> * In the settings.xml file <br/>
* sets the updateSettings value to true (w:updateSettings w:val="true") * sets the updateSettings value to true (w:updateSettings w:val="true")
* * <p/>
* NOTICES: * NOTICES:
* <ul> * <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?" * <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> * (if "Update automatic links at open" is enabled)</li>
* <li>Flag is removed after saving with changes in Word </li> * <li>Flag is removed after saving with changes in Word </li>
* </ul> * </ul>
*/ */
public void setUpdateFields() { public void setUpdateFields() {
CTOnOff onOff = CTOnOff.Factory.newInstance(); CTOnOff onOff = CTOnOff.Factory.newInstance();
onOff.setVal(STOnOff.TRUE); onOff.setVal(STOnOff.TRUE);
ctSettings.setUpdateFields(onOff); ctSettings.setUpdateFields(onOff);
} }
boolean isUpdateFields() { boolean isUpdateFields() {
@ -341,12 +356,12 @@ public class XWPFSettings extends POIXMLDocumentPart {
* @param enable <code>true</code> to turn on revision tracking, <code>false</code> to turn off 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) { public void setTrackRevisions(boolean enable) {
if(enable) { if (enable) {
if(!ctSettings.isSetTrackRevisions()) { if (!ctSettings.isSetTrackRevisions()) {
ctSettings.addNewTrackRevisions(); ctSettings.addNewTrackRevisions();
} }
} else { } else {
if(ctSettings.isSetTrackRevisions()) { if (ctSettings.isSetTrackRevisions()) {
ctSettings.unsetTrackRevisions(); ctSettings.unsetTrackRevisions();
} }
} }
@ -355,7 +370,7 @@ public class XWPFSettings extends POIXMLDocumentPart {
@Override @Override
protected void commit() throws IOException { protected void commit() throws IOException {
if (ctSettings == null) { 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); XmlOptions xmlOptions = new XmlOptions(DEFAULT_XML_OPTIONS);

View File

@ -22,125 +22,138 @@ import org.openxmlformats.schemas.wordprocessingml.x2006.main.STStyleType;
/** /**
* @author Philipp Epp * @author Philipp Epp
*
*/ */
public class XWPFStyle { public class XWPFStyle {
private CTStyle ctStyle; protected XWPFStyles styles;
protected XWPFStyles styles; private CTStyle ctStyle;
/** /**
* constructor * constructor
* @param style *
*/ * @param style
public XWPFStyle(CTStyle style){ */
this(style,null); 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 * constructor
* @return styleID StyleID of the style *
*/ * @param style
public String getStyleId(){ * @param styles
return ctStyle.getStyleId(); */
} public XWPFStyle(CTStyle style, XWPFStyles styles) {
this.ctStyle = style;
this.styles = styles;
}
/** /**
* get Type of the Style * get StyleID of the style
* @return ctType *
*/ * @return styleID StyleID of the style
public STStyleType.Enum getType(){ */
return ctStyle.getType(); public String getStyleId() {
} return ctStyle.getStyleId();
}
/** /**
* set style * set styleID
* @param style *
*/ * @param styleId
public void setStyle(CTStyle style){ */
this.ctStyle = style; public void setStyleId(String styleId) {
} ctStyle.setStyleId(styleId);
/** }
* get ctStyle
* @return ctStyle
*/
public CTStyle getCTStyle(){
return this.ctStyle;
}
/**
* set styleID
* @param styleId
*/
public void setStyleId(String styleId){
ctStyle.setStyleId(styleId);
}
/** /**
* set styleType * get Type of the Style
* @param type *
*/ * @return ctType
public void setType(STStyleType.Enum type){ */
ctStyle.setType(type); public STStyleType.Enum getType() {
} return ctStyle.getType();
/** }
* get styles
* @return styles the styles to which this style belongs
*/
public XWPFStyles getStyles(){
return styles;
}
public String getBasisStyleID(){ /**
if(ctStyle.getBasedOn()!=null) * set styleType
return ctStyle.getBasedOn().getVal(); *
else * @param type
return null; */
} 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 * get StyleID of the linked Style
*/ */
public String getLinkStyleID(){ public String getLinkStyleID() {
if (ctStyle.getLink()!=null) if (ctStyle.getLink() != null)
return ctStyle.getLink().getVal(); return ctStyle.getLink().getVal();
else else
return null; return null;
} }
/** /**
* get StyleID of the next style * get StyleID of the next style
*/ */
public String getNextStyleID(){ public String getNextStyleID() {
if(ctStyle.getNext()!=null) if (ctStyle.getNext() != null)
return ctStyle.getNext().getVal(); return ctStyle.getNext().getVal();
else else
return null; return null;
} }
public String getName() { public String getName() {
if(ctStyle.isSetName()) if (ctStyle.isSetName())
return ctStyle.getName().getVal(); return ctStyle.getName().getVal();
return null; return null;
} }
/** /**
* compares the names of the Styles * compares the names of the Styles
* @param compStyle *
*/ * @param compStyle
public boolean hasSameName(XWPFStyle compStyle){ */
CTStyle ctCompStyle = compStyle.getCTStyle(); public boolean hasSameName(XWPFStyle compStyle) {
String name = ctCompStyle.getName().getVal(); CTStyle ctCompStyle = compStyle.getCTStyle();
return name.equals(ctStyle.getName().getVal()); String name = ctCompStyle.getName().getVal();
} return name.equals(ctStyle.getName().getVal());
}
}//end class }//end class

View File

@ -34,22 +34,23 @@ import org.apache.poi.openxml4j.opc.PackagePart;
import org.apache.poi.openxml4j.opc.PackageRelationship; import org.apache.poi.openxml4j.opc.PackageRelationship;
import org.apache.xmlbeans.XmlException; import org.apache.xmlbeans.XmlException;
import org.apache.xmlbeans.XmlOptions; 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.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.CTStyle;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTStyles; import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTStyles;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.StylesDocument; 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 * Holds details of built-in, default and user styles, which
* apply to tables / paragraphs / lists etc. * apply to tables / paragraphs / lists etc.
* Text within one of those with custom stylings has the style * Text within one of those with custom stylings has the style
* information stored in the {@link XWPFRun} * information stored in the {@link XWPFRun}
*/ */
public class XWPFStyles extends POIXMLDocumentPart{ public class XWPFStyles extends POIXMLDocumentPart {
private CTStyles ctStyles; private CTStyles ctStyles;
private List<XWPFStyle> listStyle = new ArrayList<XWPFStyle>(); private List<XWPFStyle> listStyle = new ArrayList<XWPFStyle>();
@ -63,7 +64,7 @@ public class XWPFStyles extends POIXMLDocumentPart{
* @param part the package part holding the data of the styles, * @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" * @param rel the package relationship of type "http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles"
*/ */
public XWPFStyles(PackagePart part, PackageRelationship rel) throws IOException, OpenXML4JException{ public XWPFStyles(PackagePart part, PackageRelationship rel) throws IOException, OpenXML4JException {
super(part, rel); super(part, rel);
} }
@ -77,7 +78,7 @@ public class XWPFStyles extends POIXMLDocumentPart{
* Read document * Read document
*/ */
@Override @Override
protected void onDocumentRead() throws IOException{ protected void onDocumentRead() throws IOException {
StylesDocument stylesDoc; StylesDocument stylesDoc;
try { try {
InputStream is = getPackagePart().getInputStream(); InputStream is = getPackagePart().getInputStream();
@ -97,7 +98,7 @@ public class XWPFStyles extends POIXMLDocumentPart{
XmlOptions xmlOptions = new XmlOptions(DEFAULT_XML_OPTIONS); XmlOptions xmlOptions = new XmlOptions(DEFAULT_XML_OPTIONS);
xmlOptions.setSaveSyntheticDocumentElement(new QName(CTStyles.type.getName().getNamespaceURI(), "styles")); xmlOptions.setSaveSyntheticDocumentElement(new QName(CTStyles.type.getName().getNamespaceURI(), "styles"));
Map<String,String> map = new HashMap<String,String>(); Map<String, String> map = new HashMap<String, String>();
map.put("http://schemas.openxmlformats.org/officeDocument/2006/relationships", "r"); map.put("http://schemas.openxmlformats.org/officeDocument/2006/relationships", "r");
map.put("http://schemas.openxmlformats.org/wordprocessingml/2006/main", "w"); map.put("http://schemas.openxmlformats.org/wordprocessingml/2006/main", "w");
xmlOptions.setSaveSuggestedPrefixes(map); xmlOptions.setSaveSuggestedPrefixes(map);
@ -108,14 +109,14 @@ public class XWPFStyles extends POIXMLDocumentPart{
} }
protected void ensureDocDefaults() { protected void ensureDocDefaults() {
if (! ctStyles.isSetDocDefaults()) { if (!ctStyles.isSetDocDefaults()) {
ctStyles.addNewDocDefaults(); ctStyles.addNewDocDefaults();
} }
CTDocDefaults docDefaults = ctStyles.getDocDefaults(); CTDocDefaults docDefaults = ctStyles.getDocDefaults();
if (! docDefaults.isSetPPrDefault()) if (!docDefaults.isSetPPrDefault())
docDefaults.addNewPPrDefault(); docDefaults.addNewPPrDefault();
if (! docDefaults.isSetRPrDefault()) if (!docDefaults.isSetRPrDefault())
docDefaults.addNewRPrDefault(); docDefaults.addNewRPrDefault();
CTPPrDefault pprd = docDefaults.getPPrDefault(); CTPPrDefault pprd = docDefaults.getPPrDefault();
@ -129,6 +130,7 @@ public class XWPFStyles extends POIXMLDocumentPart{
/** /**
* Sets the ctStyles * Sets the ctStyles
*
* @param styles * @param styles
*/ */
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
@ -136,7 +138,7 @@ public class XWPFStyles extends POIXMLDocumentPart{
ctStyles = styles; ctStyles = styles;
// Build up all the style objects // Build up all the style objects
for(CTStyle style : ctStyles.getStyleArray()) { for (CTStyle style : ctStyles.getStyleArray()) {
listStyle.add(new XWPFStyle(style, this)); listStyle.add(new XWPFStyle(style, this));
} }
if (ctStyles.isSetDocDefaults()) { if (ctStyles.isSetDocDefaults()) {
@ -154,39 +156,45 @@ public class XWPFStyles extends POIXMLDocumentPart{
/** /**
* checks whether style with styleID exist * 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 * @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){ public boolean styleExist(String styleID) {
for (XWPFStyle style : listStyle) { for (XWPFStyle style : listStyle) {
if (style.getStyleId().equals(styleID)) if (style.getStyleId().equals(styleID))
return true; return true;
} }
return false; return false;
} }
/** /**
* add a style to the document * add a style to the document
*
* @param style * @param style
* @throws IOException * @throws IOException
*/ */
public void addStyle(XWPFStyle style){ public void addStyle(XWPFStyle style) {
listStyle.add(style); listStyle.add(style);
ctStyles.addNewStyle(); ctStyles.addNewStyle();
int pos = ctStyles.sizeOfStyleArray() - 1; int pos = ctStyles.sizeOfStyleArray() - 1;
ctStyles.setStyleArray(pos, style.getCTStyle()); ctStyles.setStyleArray(pos, style.getCTStyle());
} }
/** /**
* Get style by a styleID * Get style by a styleID
* @param styleID styleID of the searched style *
* @param styleID styleID of the searched style
* @return style * @return style
*/ */
public XWPFStyle getStyle(String styleID){ public XWPFStyle getStyle(String styleID) {
for (XWPFStyle style : listStyle) { for (XWPFStyle style : listStyle) {
if(style.getStyleId().equals(styleID)) if (style.getStyleId().equals(styleID))
return style; return style;
} }
return null; return null;
} }
public int getNumberOfStyles() { public int getNumberOfStyles() {
return listStyle.size(); return listStyle.size();
} }
@ -194,10 +202,11 @@ public class XWPFStyles extends POIXMLDocumentPart{
/** /**
* get the styles which are related to the parameter style and their relatives * 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 * this method can be used to copy all styles from one document to another document
*
* @param style * @param style
* @return a list of all styles which were used by this method * @return a list of all styles which were used by this method
*/ */
public List<XWPFStyle> getUsedStyleList(XWPFStyle style){ public List<XWPFStyle> getUsedStyleList(XWPFStyle style) {
List<XWPFStyle> usedStyleList = new ArrayList<XWPFStyle>(); List<XWPFStyle> usedStyleList = new ArrayList<XWPFStyle>();
usedStyleList.add(style); usedStyleList.add(style);
return getUsedStyleList(style, usedStyleList); return getUsedStyleList(style, usedStyleList);
@ -205,26 +214,27 @@ public class XWPFStyles extends POIXMLDocumentPart{
/** /**
* get the styles which are related to parameter style * get the styles which are related to parameter style
*
* @param style * @param style
* @return all Styles of the parameterList * @return all Styles of the parameterList
*/ */
private List<XWPFStyle> getUsedStyleList(XWPFStyle style, List<XWPFStyle> usedStyleList){ private List<XWPFStyle> getUsedStyleList(XWPFStyle style, List<XWPFStyle> usedStyleList) {
String basisStyleID = style.getBasisStyleID(); String basisStyleID = style.getBasisStyleID();
XWPFStyle basisStyle = getStyle(basisStyleID); XWPFStyle basisStyle = getStyle(basisStyleID);
if((basisStyle!=null)&&(!usedStyleList.contains(basisStyle))){ if ((basisStyle != null) && (!usedStyleList.contains(basisStyle))) {
usedStyleList.add(basisStyle); usedStyleList.add(basisStyle);
getUsedStyleList(basisStyle, usedStyleList); getUsedStyleList(basisStyle, usedStyleList);
} }
String linkStyleID = style.getLinkStyleID(); String linkStyleID = style.getLinkStyleID();
XWPFStyle linkStyle = getStyle(linkStyleID); XWPFStyle linkStyle = getStyle(linkStyleID);
if((linkStyle!=null)&&(!usedStyleList.contains(linkStyle))){ if ((linkStyle != null) && (!usedStyleList.contains(linkStyle))) {
usedStyleList.add(linkStyle); usedStyleList.add(linkStyle);
getUsedStyleList(linkStyle, usedStyleList); getUsedStyleList(linkStyle, usedStyleList);
} }
String nextStyleID = style.getNextStyleID(); String nextStyleID = style.getNextStyleID();
XWPFStyle nextStyle = getStyle(nextStyleID); XWPFStyle nextStyle = getStyle(nextStyleID);
if((nextStyle!=null)&&(!usedStyleList.contains(nextStyle))){ if ((nextStyle != null) && (!usedStyleList.contains(nextStyle))) {
usedStyleList.add(linkStyle); usedStyleList.add(linkStyle);
getUsedStyleList(linkStyle, usedStyleList); getUsedStyleList(linkStyle, usedStyleList);
} }
@ -246,6 +256,7 @@ public class XWPFStyles extends POIXMLDocumentPart{
/** /**
* Sets the default spelling language on ctStyles DocDefaults parameter * Sets the default spelling language on ctStyles DocDefaults parameter
*
* @param strSpellingLanguage * @param strSpellingLanguage
*/ */
public void setSpellingLanguage(String strSpellingLanguage) { public void setSpellingLanguage(String strSpellingLanguage) {
@ -256,6 +267,7 @@ public class XWPFStyles extends POIXMLDocumentPart{
/** /**
* Sets the default East Asia spelling language on ctStyles DocDefaults parameter * Sets the default East Asia spelling language on ctStyles DocDefaults parameter
*
* @param strEastAsia * @param strEastAsia
*/ */
public void setEastAsia(String strEastAsia) { public void setEastAsia(String strEastAsia) {
@ -266,7 +278,7 @@ public class XWPFStyles extends POIXMLDocumentPart{
/** /**
* Sets the default font on ctStyles DocDefaults parameter * Sets the default font on ctStyles DocDefaults parameter
* TODO Replace this with specific setters for each type, possibly * TODO Replace this with specific setters for each type, possibly
* on XWPFDefaultRunStyle * on XWPFDefaultRunStyle
*/ */
public void setDefaultFonts(CTFonts fonts) { public void setDefaultFonts(CTFonts fonts) {
ensureDocDefaults(); ensureDocDefaults();
@ -279,9 +291,9 @@ public class XWPFStyles extends POIXMLDocumentPart{
* get the style with the same name * get the style with the same name
* if this style is not existing, return null * if this style is not existing, return null
*/ */
public XWPFStyle getStyleWithSameName(XWPFStyle style){ public XWPFStyle getStyleWithSameName(XWPFStyle style) {
for (XWPFStyle ownStyle : listStyle) { for (XWPFStyle ownStyle : listStyle) {
if(ownStyle.hasSameName(style)){ if (ownStyle.hasSameName(style)) {
return ownStyle; return ownStyle;
} }
} }

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> * of paragraphs (and other block-level content) arranged in rows and columns.</p>
*/ */
public class XWPFTable implements IBodyElement, ISDTContents { 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; private static EnumMap<XWPFBorderType, STBorder.Enum> xwpfBorderTypeMap;
// Create a map from the STBorder.Enum values to the XWPF-level enums // Create a map from the STBorder.Enum values to the XWPF-level enums
private static HashMap<Integer, XWPFBorderType> stBorderTypeMap; private static HashMap<Integer, XWPFBorderType> stBorderTypeMap;
protected IBody part;
static { static {
// populate enum maps // populate enum maps
xwpfBorderTypeMap = new EnumMap<XWPFBorderType, STBorder.Enum>(XWPFBorderType.class); xwpfBorderTypeMap = new EnumMap<XWPFBorderType, STBorder.Enum>(XWPFBorderType.class);
@ -80,6 +71,14 @@ public class XWPFTable implements IBodyElement, ISDTContents {
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) { public XWPFTable(CTTbl table, IBody part, int row, int col) {
this(table, part); this(table, part);
@ -94,7 +93,7 @@ public class XWPFTable implements IBodyElement, ISDTContents {
} }
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
public XWPFTable(CTTbl table, IBody part){ public XWPFTable(CTTbl table, IBody part) {
this.part = part; this.part = part;
this.ctTbl = table; this.ctTbl = table;
@ -163,7 +162,7 @@ public class XWPFTable implements IBodyElement, ISDTContents {
* Convenience method to extract text in cells. This * Convenience method to extract text in cells. This
* does not extract text recursively in cells, and it does not * does not extract text recursively in cells, and it does not
* currently include text in SDT (form) components. * currently include text in SDT (form) components.
* <p> * <p/>
* To get all text within a table, see XWPFWordExtractor's appendTableText * To get all text within a table, see XWPFWordExtractor's appendTableText
* as an example. * as an example.
* *
@ -216,6 +215,13 @@ public class XWPFTable implements IBodyElement, ISDTContents {
return null; return null;
} }
/**
* @return width value
*/
public int getWidth() {
CTTblPr tblPr = getTrPr();
return tblPr.isSetTblW() ? tblPr.getTblW().getW().intValue() : -1;
}
/** /**
* @param width * @param width
@ -226,14 +232,6 @@ public class XWPFTable implements IBodyElement, ISDTContents {
tblWidth.setW(new BigInteger("" + width)); 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 * @return number of rows in table
*/ */
@ -256,9 +254,10 @@ public class XWPFTable implements IBodyElement, ISDTContents {
/** /**
* get the StyleID of the table * 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; String styleId = null;
CTTblPr tblPr = ctTbl.getTblPr(); CTTblPr tblPr = ctTbl.getTblPr();
if (tblPr != null) { 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 * Set the table style. If the style is not defined in the document, MS Word
* will set the table style to "Normal". * will set the table style to "Normal".
*
* @param styleName - the style name to apply to this table * @param styleName - the style name to apply to this table
*/ */
public void setStyleID(String styleName) { public void setStyleID(String styleName) {
@ -524,23 +524,24 @@ public class XWPFTable implements IBodyElement, ISDTContents {
/** /**
* add a new Row to the table * 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.addNewTr();
ctTbl.setTrArray(getNumberOfRows()-1, row.getCtRow()); ctTbl.setTrArray(getNumberOfRows() - 1, row.getCtRow());
tableRows.add(row); tableRows.add(row);
} }
/** /**
* add a new Row to the table * add a new Row to the table
* at position pos * 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){ public boolean addRow(XWPFTableRow row, int pos) {
if(pos >= 0 && pos <= tableRows.size()){ if (pos >= 0 && pos <= tableRows.size()) {
ctTbl.insertNewTr(pos); ctTbl.insertNewTr(pos);
ctTbl.setTrArray(pos,row.getCtRow()); ctTbl.setTrArray(pos, row.getCtRow());
tableRows.add(pos, row); tableRows.add(pos, row);
return true; return true;
} }
@ -549,11 +550,12 @@ public class XWPFTable implements IBodyElement, ISDTContents {
/** /**
* inserts a new tablerow * inserts a new tablerow
*
* @param pos * @param pos
* @return the inserted row * @return the inserted row
*/ */
public XWPFTableRow insertNewTableRow(int pos){ public XWPFTableRow insertNewTableRow(int pos) {
if(pos >= 0 && pos <= tableRows.size()){ if (pos >= 0 && pos <= tableRows.size()) {
CTRow row = ctTbl.insertNewTr(pos); CTRow row = ctTbl.insertNewTr(pos);
XWPFTableRow tableRow = new XWPFTableRow(row, this); XWPFTableRow tableRow = new XWPFTableRow(row, this);
tableRows.add(pos, tableRow); tableRows.add(pos, tableRow);
@ -562,10 +564,10 @@ public class XWPFTable implements IBodyElement, ISDTContents {
return null; return null;
} }
/** /**
* Remove a row at position pos from the table * 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 { public boolean removeRow(int pos) throws IndexOutOfBoundsException {
if (pos >= 0 && pos < tableRows.size()) { if (pos >= 0 && pos < tableRows.size()) {
@ -582,9 +584,9 @@ public class XWPFTable implements IBodyElement, ISDTContents {
return tableRows; return tableRows;
} }
/** /**
* returns the type of the BodyElement Table * returns the type of the BodyElement Table
*
* @see org.apache.poi.xwpf.usermodel.IBodyElement#getElementType() * @see org.apache.poi.xwpf.usermodel.IBodyElement#getElementType()
*/ */
public BodyElementType getElementType() { public BodyElementType getElementType() {
@ -597,10 +599,11 @@ public class XWPFTable implements IBodyElement, ISDTContents {
/** /**
* returns the part of the bodyElement * returns the part of the bodyElement
*
* @see org.apache.poi.xwpf.usermodel.IBody#getPart() * @see org.apache.poi.xwpf.usermodel.IBody#getPart()
*/ */
public POIXMLDocumentPart getPart() { public POIXMLDocumentPart getPart() {
if(part != null){ if (part != null) {
return part.getPart(); return part.getPart();
} }
return null; return null;
@ -608,6 +611,7 @@ public class XWPFTable implements IBodyElement, ISDTContents {
/** /**
* returns the partType of the bodyPart which owns the bodyElement * returns the partType of the bodyPart which owns the bodyElement
*
* @see org.apache.poi.xwpf.usermodel.IBody#getPartType() * @see org.apache.poi.xwpf.usermodel.IBody#getPartType()
*/ */
public BodyType 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 * if this row is not existing in the table null will be returned
*/ */
public XWPFTableRow getRow(CTRow row) { public XWPFTableRow getRow(CTRow row) {
for(int i=0; i<getRows().size(); i++){ for (int i = 0; i < getRows().size(); i++) {
if(getRows().get(i).getCtRow()== row) return getRow(i); if (getRows().get(i).getCtRow() == row) return getRow(i);
} }
return null; 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

@ -40,17 +40,9 @@ import org.openxmlformats.schemas.wordprocessingml.x2006.main.STVerticalJc;
/** /**
* Represents a Cell within a {@link XWPFTable}. The * Represents a Cell within a {@link XWPFTable}. The
* Cell is the thing that holds the actual content (paragraphs etc) * Cell is the thing that holds the actual content (paragraphs etc)
*/ */
public class XWPFTableCell implements IBody, ICell { 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; private static EnumMap<XWPFVertAlign, STVerticalJc.Enum> alignMap;
// Create a map from the STVerticalJc.Enum values to the XWPF-level enums // Create a map from the STVerticalJc.Enum values to the XWPF-level enums
private static HashMap<Integer, XWPFVertAlign> stVertAlignTypeMap; private static HashMap<Integer, XWPFVertAlign> stVertAlignTypeMap;
@ -71,6 +63,15 @@ 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;
/** /**
* If a table cell does not include at least one block-level element, then this document shall be considered corrupt * If a table cell does not include at least one block-level element, then this document shall be considered corrupt
*/ */
@ -79,7 +80,7 @@ public class XWPFTableCell implements IBody, ICell {
this.part = part; this.part = part;
this.tableRow = tableRow; this.tableRow = tableRow;
// NB: If a table cell does not include at least one block-level element, then this document shall be considered corrupt. // 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) if (cell.sizeOfPArray() < 1)
cell.addNewP(); cell.addNewP();
bodyElements = new ArrayList<IBodyElement>(); bodyElements = new ArrayList<IBodyElement>();
paragraphs = new ArrayList<XWPFParagraph>(); paragraphs = new ArrayList<XWPFParagraph>();
@ -90,29 +91,28 @@ public class XWPFTableCell implements IBody, ICell {
while (cursor.toNextSelection()) { while (cursor.toNextSelection()) {
XmlObject o = cursor.getObject(); XmlObject o = cursor.getObject();
if (o instanceof CTP) { if (o instanceof CTP) {
XWPFParagraph p = new XWPFParagraph((CTP)o, this); XWPFParagraph p = new XWPFParagraph((CTP) o, this);
paragraphs.add(p); paragraphs.add(p);
bodyElements.add(p); bodyElements.add(p);
} }
if (o instanceof CTTbl) { if (o instanceof CTTbl) {
XWPFTable t = new XWPFTable((CTTbl)o, this); XWPFTable t = new XWPFTable((CTTbl) o, this);
tables.add(t); tables.add(t);
bodyElements.add(t); bodyElements.add(t);
} }
if (o instanceof CTSdtBlock){ if (o instanceof CTSdtBlock) {
XWPFSDT c = new XWPFSDT((CTSdtBlock)o, this); XWPFSDT c = new XWPFSDT((CTSdtBlock) o, this);
bodyElements.add(c); bodyElements.add(c);
} }
if (o instanceof CTSdtRun){ if (o instanceof CTSdtRun) {
XWPFSDT c = new XWPFSDT((CTSdtRun)o, this); XWPFSDT c = new XWPFSDT((CTSdtRun) o, this);
System.out.println(c.getContent().getText()); System.out.println(c.getContent().getText());
bodyElements.add(c); bodyElements.add(c);
} }
} }
cursor.dispose(); cursor.dispose();
} }
@Internal @Internal
public CTTc getCTTc() { public CTTc getCTTc() {
return ctTc; return ctTc;
@ -120,10 +120,11 @@ public class XWPFTableCell implements IBody, ICell {
/** /**
* returns an Iterator with paragraphs and tables * returns an Iterator with paragraphs and tables
*
* @see org.apache.poi.xwpf.usermodel.IBody#getBodyElements() * @see org.apache.poi.xwpf.usermodel.IBody#getBodyElements()
*/ */
public List<IBodyElement> getBodyElements(){ public List<IBodyElement> getBodyElements() {
return Collections.unmodifiableList(bodyElements); return Collections.unmodifiableList(bodyElements);
} }
public void setParagraph(XWPFParagraph p) { public void setParagraph(XWPFParagraph p) {
@ -136,67 +137,83 @@ public class XWPFTableCell implements IBody, ICell {
/** /**
* returns a list of paragraphs * returns a list of paragraphs
*/ */
public List<XWPFParagraph> getParagraphs(){ public List<XWPFParagraph> getParagraphs() {
return paragraphs; return paragraphs;
} }
/** /**
* Add a Paragraph to this Table Cell * Add a Paragraph to this Table Cell
*
* @return The paragraph which was added * @return The paragraph which was added
*/ */
public XWPFParagraph addParagraph() { public XWPFParagraph addParagraph() {
XWPFParagraph p = new XWPFParagraph(ctTc.addNewP(), this); XWPFParagraph p = new XWPFParagraph(ctTc.addNewP(), this);
addParagraph(p); addParagraph(p);
return p; return p;
} }
/** /**
* add a Paragraph to this TableCell * add a Paragraph to this TableCell
*
* @param p the paragaph which has to be added * @param p the paragaph which has to be added
*/ */
public void addParagraph(XWPFParagraph p){ public void addParagraph(XWPFParagraph p) {
paragraphs.add(p); paragraphs.add(p);
} }
/** /**
* removes a paragraph of this tablecell * removes a paragraph of this tablecell
*
* @param pos * @param pos
*/ */
public void removeParagraph(int pos){ public void removeParagraph(int pos) {
paragraphs.remove(pos); paragraphs.remove(pos);
ctTc.removeP(pos); ctTc.removeP(pos);
} }
/** /**
* if there is a corresponding {@link XWPFParagraph} of the parameter ctTable in the paragraphList of this table * if there is a corresponding {@link XWPFParagraph} of the parameter ctTable in the paragraphList of this table
* the method will return this paragraph * 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 table * @param p is instance of CTP and is searching for an XWPFParagraph
* XWPFParagraph with the correspondig CTP p * @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) { public XWPFParagraph getParagraph(CTP p) {
if(p.equals(paragraph.getCTP())){ for (XWPFParagraph paragraph : paragraphs) {
return paragraph; if (p.equals(paragraph.getCTP())) {
} return paragraph;
} }
return null; }
return null;
} }
public void setText(String text) { public XWPFTableRow getTableRow() {
CTP ctP = (ctTc.sizeOfPArray() == 0) ? ctTc.addNewP() : ctTc.getPArray(0); return tableRow;
XWPFParagraph par = new XWPFParagraph(ctP, this);
par.createRun().setText(text);
} }
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 * Set cell color. This sets some associated values; for finer control
* you may want to access these elements individually. * you may want to access these elements individually.
*
* @param rgbStr - the desired cell color, in the hex form "RRGGBB". * @param rgbStr - the desired cell color, in the hex form "RRGGBB".
*/ */
public void setColor(String rgbStr) { public void setColor(String rgbStr) {
@ -208,142 +225,125 @@ public class XWPFTableCell implements IBody, ICell {
} }
/** /**
* Get cell color. Note that this method only returns the "fill" value. * Get the vertical alignment of the cell.
* @return RGB string of cell color *
* @return the cell alignment enum value
*/ */
public String getColor() { public XWPFVertAlign getVerticalAlignment() {
String color = null; XWPFVertAlign vAlign = null;
CTTcPr tcpr = ctTc.getTcPr(); CTTcPr tcpr = ctTc.getTcPr();
if (tcpr != null) { if (ctTc != null) {
CTShd ctshd = tcpr.getShd(); CTVerticalJc va = tcpr.getVAlign();
if (ctshd != null) { vAlign = stVertAlignTypeMap.get(va.getVal().intValue());
color = ctshd.xgetFill().getStringValue(); }
} return vAlign;
}
return color;
} }
/** /**
* Set the vertical alignment of the cell. * Set the vertical alignment of the cell.
*
* @param vAlign - the desired alignment enum value * @param vAlign - the desired alignment enum value
*/ */
public void setVerticalAlignment(XWPFVertAlign vAlign) { public void setVerticalAlignment(XWPFVertAlign vAlign) {
CTTcPr tcpr = ctTc.isSetTcPr() ? ctTc.getTcPr() : ctTc.addNewTcPr(); CTTcPr tcpr = ctTc.isSetTcPr() ? ctTc.getTcPr() : ctTc.addNewTcPr();
CTVerticalJc va = tcpr.addNewVAlign(); CTVerticalJc va = tcpr.addNewVAlign();
va.setVal(alignMap.get(vAlign)); 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 * add a new paragraph at position of the cursor
*
* @param cursor * @param cursor
* @return the inserted paragraph * @return the inserted paragraph
*/ */
public XWPFParagraph insertNewParagraph(XmlCursor cursor){ public XWPFParagraph insertNewParagraph(XmlCursor cursor) {
if(!isCursorInTableCell(cursor)) { if (!isCursorInTableCell(cursor)) {
return null; return null;
} }
String uri = CTP.type.getName().getNamespaceURI(); String uri = CTP.type.getName().getNamespaceURI();
String localPart = "p"; String localPart = "p";
cursor.beginElement(localPart,uri); cursor.beginElement(localPart, uri);
cursor.toParent(); cursor.toParent();
CTP p = (CTP)cursor.getObject(); CTP p = (CTP) cursor.getObject();
XWPFParagraph newP = new XWPFParagraph(p, this); XWPFParagraph newP = new XWPFParagraph(p, this);
XmlObject o = null; XmlObject o = null;
while(!(o instanceof CTP)&&(cursor.toPrevSibling())){ while (!(o instanceof CTP) && (cursor.toPrevSibling())) {
o = cursor.getObject(); o = cursor.getObject();
} }
if((!(o instanceof CTP)) || (CTP)o == p){ if ((!(o instanceof CTP)) || (CTP) o == p) {
paragraphs.add(0, newP); paragraphs.add(0, newP);
} } else {
else{ int pos = paragraphs.indexOf(getParagraph((CTP) o)) + 1;
int pos = paragraphs.indexOf(getParagraph((CTP)o))+1; paragraphs.add(pos, newP);
paragraphs.add(pos,newP); }
} int i = 0;
int i=0; cursor.toCursor(p.newCursor());
cursor.toCursor(p.newCursor()); while (cursor.toPrevSibling()) {
while(cursor.toPrevSibling()){ o = cursor.getObject();
o =cursor.getObject(); if (o instanceof CTP || o instanceof CTTbl)
if(o instanceof CTP || o instanceof CTTbl) i++;
i++; }
} bodyElements.add(i, newP);
bodyElements.add(i, newP); cursor.toCursor(p.newCursor());
cursor.toCursor(p.newCursor()); cursor.toEndToken();
cursor.toEndToken(); return newP;
return newP;
} }
public XWPFTable insertNewTbl(XmlCursor cursor) { public XWPFTable insertNewTbl(XmlCursor cursor) {
if(isCursorInTableCell(cursor)){ if (isCursorInTableCell(cursor)) {
String uri = CTTbl.type.getName().getNamespaceURI(); String uri = CTTbl.type.getName().getNamespaceURI();
String localPart = "tbl"; String localPart = "tbl";
cursor.beginElement(localPart,uri); cursor.beginElement(localPart, uri);
cursor.toParent(); cursor.toParent();
CTTbl t = (CTTbl)cursor.getObject(); CTTbl t = (CTTbl) cursor.getObject();
XWPFTable newT = new XWPFTable(t, this); XWPFTable newT = new XWPFTable(t, this);
cursor.removeXmlContents(); cursor.removeXmlContents();
XmlObject o = null; XmlObject o = null;
while(!(o instanceof CTTbl)&&(cursor.toPrevSibling())){ while (!(o instanceof CTTbl) && (cursor.toPrevSibling())) {
o = cursor.getObject(); o = cursor.getObject();
} }
if(!(o instanceof CTTbl)){ if (!(o instanceof CTTbl)) {
tables.add(0, newT); tables.add(0, newT);
} } else {
else{ int pos = tables.indexOf(getTable((CTTbl) o)) + 1;
int pos = tables.indexOf(getTable((CTTbl)o))+1; tables.add(pos, newT);
tables.add(pos,newT); }
} int i = 0;
int i=0; cursor = t.newCursor();
cursor = t.newCursor(); while (cursor.toPrevSibling()) {
while(cursor.toPrevSibling()){ o = cursor.getObject();
o =cursor.getObject(); if (o instanceof CTP || o instanceof CTTbl)
if(o instanceof CTP || o instanceof CTTbl) i++;
i++; }
} bodyElements.add(i, newT);
bodyElements.add(i, newT); cursor = t.newCursor();
cursor = t.newCursor(); cursor.toEndToken();
cursor.toEndToken(); return newT;
return newT; }
} return null;
return null;
} }
/** /**
* verifies that cursor is on the right position * verifies that cursor is on the right position
*/ */
private boolean isCursorInTableCell(XmlCursor cursor) { private boolean isCursorInTableCell(XmlCursor cursor) {
XmlCursor verify = cursor.newCursor(); XmlCursor verify = cursor.newCursor();
verify.toParent(); verify.toParent();
if(verify.getObject() == this.ctTc){ if (verify.getObject() == this.ctTc) {
return true; return true;
} }
return false; return false;
} }
/** /**
* @see org.apache.poi.xwpf.usermodel.IBody#getParagraphArray(int) * @see org.apache.poi.xwpf.usermodel.IBody#getParagraphArray(int)
*/ */
public XWPFParagraph getParagraphArray(int pos) { public XWPFParagraph getParagraphArray(int pos) {
if(pos > 0 && pos < paragraphs.size()){ if (pos > 0 && pos < paragraphs.size()) {
return paragraphs.get(pos); return paragraphs.get(pos);
} }
return null; return null;
} }
/** /**
@ -359,43 +359,41 @@ public class XWPFTableCell implements IBody, ICell {
* @see org.apache.poi.xwpf.usermodel.IBody#getPartType() * @see org.apache.poi.xwpf.usermodel.IBody#getPartType()
*/ */
public BodyType getPartType() { public BodyType getPartType() {
return BodyType.TABLECELL; return BodyType.TABLECELL;
} }
/** /**
* get a table by its CTTbl-Object * get a table by its CTTbl-Object
*
* @see org.apache.poi.xwpf.usermodel.IBody#getTable(org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTbl) * @see org.apache.poi.xwpf.usermodel.IBody#getTable(org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTbl)
*/ */
public XWPFTable getTable(CTTbl ctTable) { public XWPFTable getTable(CTTbl ctTable) {
for(int i=0; i<tables.size(); i++){ for (int i = 0; i < tables.size(); i++) {
if(getTables().get(i).getCTTbl() == ctTable) return getTables().get(i); if (getTables().get(i).getCTTbl() == ctTable) return getTables().get(i);
} }
return null; return null;
} }
/** /**
* @see org.apache.poi.xwpf.usermodel.IBody#getTableArray(int) * @see org.apache.poi.xwpf.usermodel.IBody#getTableArray(int)
*/ */
public XWPFTable getTableArray(int pos) { public XWPFTable getTableArray(int pos) {
if(pos > 0 && pos < tables.size()){ if (pos > 0 && pos < tables.size()) {
return tables.get(pos); return tables.get(pos);
} }
return null; return null;
} }
/** /**
* @see org.apache.poi.xwpf.usermodel.IBody#getTables() * @see org.apache.poi.xwpf.usermodel.IBody#getTables()
*/ */
public List<XWPFTable> getTables() { public List<XWPFTable> getTables() {
return Collections.unmodifiableList(tables); return Collections.unmodifiableList(tables);
} }
/** /**
* inserts an existing XWPFTable to the arrays bodyElements and 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) * @see org.apache.poi.xwpf.usermodel.IBody#insertTable(int, org.apache.poi.xwpf.usermodel.XWPFTable)
*/ */
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
@ -411,52 +409,58 @@ public class XWPFTableCell implements IBody, ICell {
tables.add(i, table); tables.add(i, table);
} }
public String getText(){ public String getText() {
StringBuffer text = new StringBuffer(); StringBuffer text = new StringBuffer();
for (XWPFParagraph p : paragraphs) { for (XWPFParagraph p : paragraphs) {
text.append(p.getText()); text.append(p.getText());
} }
return text.toString(); 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 * extracts all text recursively through embedded tables and embedded SDTs
*/ */
public String getTextRecursively(){ public String getTextRecursively() {
StringBuffer text = new StringBuffer(); StringBuffer text = new StringBuffer();
for (int i = 0; i < bodyElements.size(); i++){ for (int i = 0; i < bodyElements.size(); i++) {
boolean isLast = (i== bodyElements.size()-1)? true : false; boolean isLast = (i == bodyElements.size() - 1) ? true : false;
appendBodyElementText(text, bodyElements.get(i), isLast); appendBodyElementText(text, bodyElements.get(i), isLast);
} }
return text.toString(); return text.toString();
} }
private void appendBodyElementText(StringBuffer text, IBodyElement e, boolean isLast){ private void appendBodyElementText(StringBuffer text, IBodyElement e, boolean isLast) {
if (e instanceof XWPFParagraph){ if (e instanceof XWPFParagraph) {
text.append(((XWPFParagraph)e).getText()); text.append(((XWPFParagraph) e).getText());
if (isLast == false){ if (isLast == false) {
text.append('\t'); text.append('\t');
} }
} else if (e instanceof XWPFTable){ } else if (e instanceof XWPFTable) {
XWPFTable eTable = (XWPFTable)e; XWPFTable eTable = (XWPFTable) e;
for (XWPFTableRow row : eTable.getRows()){ for (XWPFTableRow row : eTable.getRows()) {
for (XWPFTableCell cell : row.getTableCells()){ for (XWPFTableCell cell : row.getTableCells()) {
List<IBodyElement> localBodyElements = cell.getBodyElements(); List<IBodyElement> localBodyElements = cell.getBodyElements();
for (int i = 0; i < localBodyElements.size(); i++){ for (int i = 0; i < localBodyElements.size(); i++) {
boolean localIsLast = (i== localBodyElements.size()-1)? true : false; boolean localIsLast = (i == localBodyElements.size() - 1) ? true : false;
appendBodyElementText(text, localBodyElements.get(i), localIsLast); appendBodyElementText(text, localBodyElements.get(i), localIsLast);
} }
} }
} }
if (isLast == false){ if (isLast == false) {
text.append('\n'); text.append('\n');
} }
} else if (e instanceof XWPFSDT){ } else if (e instanceof XWPFSDT) {
text.append(((XWPFSDT)e).getContent().getText()); text.append(((XWPFSDT) e).getContent().getText());
if (isLast == false){ if (isLast == false) {
text.append('\t'); text.append('\t');
} }
} }
@ -466,32 +470,37 @@ public class XWPFTableCell implements IBody, ICell {
* get the TableCell which belongs to the TableCell * get the TableCell which belongs to the TableCell
*/ */
public XWPFTableCell getTableCell(CTTc cell) { public XWPFTableCell getTableCell(CTTc cell) {
XmlCursor cursor = cell.newCursor(); XmlCursor cursor = cell.newCursor();
cursor.toParent(); cursor.toParent();
XmlObject o = cursor.getObject(); XmlObject o = cursor.getObject();
if(!(o instanceof CTRow)){ if (!(o instanceof CTRow)) {
return null; return null;
} }
CTRow row = (CTRow)o; CTRow row = (CTRow) o;
cursor.toParent(); cursor.toParent();
o = cursor.getObject(); o = cursor.getObject();
cursor.dispose(); cursor.dispose();
if(! (o instanceof CTTbl)){ if (!(o instanceof CTTbl)) {
return null; return null;
} }
CTTbl tbl = (CTTbl) o; CTTbl tbl = (CTTbl) o;
XWPFTable table = getTable(tbl); XWPFTable table = getTable(tbl);
if(table == null){ if (table == null) {
return null; return null;
} }
XWPFTableRow tableRow = table.getRow(row); XWPFTableRow tableRow = table.getRow(row);
if (tableRow == null) { if (tableRow == null) {
return null; return null;
} }
return tableRow.getTableCell(cell); return tableRow.getTableCell(cell);
} }
public XWPFDocument getXWPFDocument() { public XWPFDocument getXWPFDocument() {
return part.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

@ -34,8 +34,8 @@ import org.openxmlformats.schemas.wordprocessingml.x2006.main.STOnOff;
/** /**
* A row within an {@link XWPFTable}. Rows mostly just have * A row within an {@link XWPFTable}. Rows mostly just have
* sizings and stylings, the interesting content lives inside * sizings and stylings, the interesting content lives inside
* the child {@link XWPFTableCell}s * the child {@link XWPFTableCell}s
*/ */
public class XWPFTableRow { public class XWPFTableRow {
private CTRow ctRow; private CTRow ctRow;
@ -55,50 +55,36 @@ public class XWPFTableRow {
/** /**
* create a new XWPFTableCell and add it to the tableCell-list of this tableRow * create a new XWPFTableCell and add it to the tableCell-list of this tableRow
*
* @return the newly created XWPFTableCell * @return the newly created XWPFTableCell
*/ */
public XWPFTableCell createCell() { public XWPFTableCell createCell() {
XWPFTableCell tableCell = new XWPFTableCell(ctRow.addNewTc(), this, table.getBody()); XWPFTableCell tableCell = new XWPFTableCell(ctRow.addNewTc(), this, table.getBody());
tableCells.add(tableCell); tableCells.add(tableCell);
return tableCell; return tableCell;
} }
public XWPFTableCell getCell(int pos) { public XWPFTableCell getCell(int pos) {
if (pos >= 0 && pos < ctRow.sizeOfTcArray()) { if (pos >= 0 && pos < ctRow.sizeOfTcArray()) {
return getTableCells().get(pos); return getTableCells().get(pos);
} }
return null; return null;
} }
public void removeCell(int pos) { public void removeCell(int pos) {
if (pos >= 0 && pos < ctRow.sizeOfTcArray()) { if (pos >= 0 && pos < ctRow.sizeOfTcArray()) {
tableCells.remove(pos); 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 * adds a new TableCell at the end of this tableRow
* 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) { public XWPFTableCell addNewTableCell() {
CTTrPr properties = getTrPr(); CTTc cell = ctRow.addNewTc();
CTHeight h = properties.sizeOfTrHeightArray() == 0 ? properties.addNewTrHeight() : properties.getTrHeightArray(0); XWPFTableCell tableCell = new XWPFTableCell(cell, this, table.getBody());
h.setVal(new BigInteger("" + height)); tableCells.add(tableCell);
return tableCell;
} }
/** /**
@ -112,24 +98,41 @@ public class XWPFTableRow {
* @return height * @return height
*/ */
public int getHeight() { public int getHeight() {
CTTrPr properties = getTrPr(); CTTrPr properties = getTrPr();
return properties.sizeOfTrHeightArray() == 0 ? 0 : properties.getTrHeightArray(0).getVal().intValue(); 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).
*
* @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() { private CTTrPr getTrPr() {
return (ctRow.isSetTrPr()) ? ctRow.getTrPr() : ctRow.addNewTrPr(); return (ctRow.isSetTrPr()) ? ctRow.getTrPr() : ctRow.addNewTrPr();
} }
public XWPFTable getTable(){ public XWPFTable getTable() {
return table; return table;
} }
/** /**
* create and return a list of all XWPFTableCell * create and return a list of all XWPFTableCell
* who belongs to this row * who belongs to this row
*
* @return a list of {@link XWPFTableCell} * @return a list of {@link XWPFTableCell}
*/ */
public List<ICell> getTableICells(){ public List<ICell> getTableICells() {
List<ICell> cells = new ArrayList<ICell>(); List<ICell> cells = new ArrayList<ICell>();
//Can't use ctRow.getTcList because that only gets table cells //Can't use ctRow.getTcList because that only gets table cells
@ -138,10 +141,10 @@ public class XWPFTableRow {
cursor.selectPath("./*"); cursor.selectPath("./*");
while (cursor.toNextSelection()) { while (cursor.toNextSelection()) {
XmlObject o = cursor.getObject(); XmlObject o = cursor.getObject();
if (o instanceof CTTc){ if (o instanceof CTTc) {
cells.add(new XWPFTableCell((CTTc)o, this, table.getBody())); cells.add(new XWPFTableCell((CTTc) o, this, table.getBody()));
} else if (o instanceof CTSdtCell) { } else if (o instanceof CTSdtCell) {
cells.add(new XWPFSDTCell((CTSdtCell)o, this, table.getBody())); cells.add(new XWPFSDTCell((CTSdtCell) o, this, table.getBody()));
} }
} }
return cells; return cells;
@ -150,21 +153,22 @@ public class XWPFTableRow {
/** /**
* create and return a list of all XWPFTableCell * create and return a list of all XWPFTableCell
* who belongs to this row * who belongs to this row
*
* @return a list of {@link XWPFTableCell} * @return a list of {@link XWPFTableCell}
*/ */
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
public List<XWPFTableCell> getTableCells(){ public List<XWPFTableCell> getTableCells() {
if(tableCells == null){ if (tableCells == null) {
List<XWPFTableCell> cells = new ArrayList<XWPFTableCell>(); List<XWPFTableCell> cells = new ArrayList<XWPFTableCell>();
for (CTTc tableCell : ctRow.getTcArray()) { for (CTTc tableCell : ctRow.getTcArray()) {
cells.add(new XWPFTableCell(tableCell, this, table.getBody())); cells.add(new XWPFTableCell(tableCell, this, table.getBody()));
} }
//TODO: it is possible to have an SDT that contains a cell in within a row //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. //need to modify this code so that it pulls out SDT wrappers around cells, too.
this.tableCells = cells; this.tableCells = cells;
} }
return tableCells; return tableCells;
} }
/** /**
@ -172,67 +176,71 @@ public class XWPFTableRow {
* if there is no XWPFTableCell which belongs to the parameter CTTc cell null will be returned * if there is no XWPFTableCell which belongs to the parameter CTTc cell null will be returned
*/ */
public XWPFTableCell getTableCell(CTTc cell) { public XWPFTableCell getTableCell(CTTc cell) {
for(int i=0; i<tableCells.size(); i++){ for (int i = 0; i < tableCells.size(); i++) {
if (tableCells.get(i).getCTTc() == cell) if (tableCells.get(i).getCTTc() == cell)
return tableCells.get(i); return tableCells.get(i);
} }
return null; 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 * 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 * attribute is a little unusual: a TRUE value means DON'T allow rows to
* split, FALSE means allow rows to split. * split, FALSE means allow rows to split.
*
* @return true if rows can't be split, false otherwise. * @return true if rows can't be split, false otherwise.
*/ */
public boolean isCantSplitRow() { public boolean isCantSplitRow() {
boolean isCant = false; boolean isCant = false;
CTTrPr trpr = getTrPr(); CTTrPr trpr = getTrPr();
if (trpr.sizeOfCantSplitArray() > 0) { if (trpr.sizeOfCantSplitArray() > 0) {
CTOnOff onoff = trpr.getCantSplitArray(0); CTOnOff onoff = trpr.getCantSplitArray(0);
isCant = onoff.getVal().equals(STOnOff.ON); isCant = onoff.getVal().equals(STOnOff.ON);
} }
return isCant; return isCant;
} }
/** /**
* This attribute controls whether to repeat a table's header row at the top * This attribute controls whether to allow table rows to split across pages.
* of a table split across pages. * The logic for this attribute is a little unusual: a true value means
* @param repeat - if TRUE, repeat header row at the top of each page of table; * DON'T allow rows to split, false means allow rows to split.
* if FALSE, don't repeat header row. *
* @param split - if true, don't allow rows to be split. If false, allow
* rows to be split.
*/ */
public void setRepeatHeader(boolean repeat) { public void setCantSplitRow(boolean split) {
CTTrPr trpr = getTrPr(); CTTrPr trpr = getTrPr();
CTOnOff onoff = trpr.addNewTblHeader(); CTOnOff onoff = trpr.addNewCantSplit();
onoff.setVal(repeat ? STOnOff.ON : STOnOff.OFF); onoff.setVal(split ? STOnOff.ON : STOnOff.OFF);
} }
/** /**
* Return true if a table's header row should be repeated at the top of a * Return true if a table's header row should be repeated at the top of a
* table split across pages. * table split across pages.
*
* @return true if table's header row should be repeated at the top of each * @return true if table's header row should be repeated at the top of each
* page of table, false otherwise. * page of table, false otherwise.
*/ */
public boolean isRepeatHeader() { public boolean isRepeatHeader() {
boolean repeat = false; boolean repeat = false;
CTTrPr trpr = getTrPr(); CTTrPr trpr = getTrPr();
if (trpr.sizeOfTblHeaderArray() > 0) { if (trpr.sizeOfTblHeaderArray() > 0) {
CTOnOff rpt = trpr.getTblHeaderArray(0); CTOnOff rpt = trpr.getTblHeaderArray(0);
repeat = rpt.getVal().equals(STOnOff.ON); repeat = rpt.getVal().equals(STOnOff.ON);
} }
return repeat; 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

@ -36,21 +36,21 @@ import org.junit.runners.Suite;
*/ */
@RunWith(Suite.class) @RunWith(Suite.class)
@Suite.SuiteClasses({ @Suite.SuiteClasses({
TestXWPFBugs.class, TestXWPFBugs.class,
org.apache.poi.xwpf.usermodel.TestXWPFBugs.class, org.apache.poi.xwpf.usermodel.TestXWPFBugs.class,
TestXWPFDocument.class, TestXWPFDocument.class,
TestXWPFWordExtractor.class, TestXWPFWordExtractor.class,
TestXWPFHeaderFooterPolicy.class, TestXWPFHeaderFooterPolicy.class,
TestXWPFHeader.class, TestXWPFHeader.class,
TestXWPFHeadings.class, TestXWPFHeadings.class,
TestXWPFParagraph.class, TestXWPFParagraph.class,
TestXWPFRun.class, TestXWPFRun.class,
TestXWPFTable.class, TestXWPFTable.class,
TestXWPFStyles.class, TestXWPFStyles.class,
TestXWPFPictureData.class, TestXWPFPictureData.class,
TestXWPFNumbering.class, TestXWPFNumbering.class,
TestAllExtendedProperties.class, TestAllExtendedProperties.class,
TestPackageCorePropertiesGetKeywords.class TestPackageCorePropertiesGetKeywords.class
}) })
public final class AllXWPFTests { public final class AllXWPFTests {
} }

View File

@ -20,7 +20,6 @@ package org.apache.poi.xwpf;
import java.io.IOException; import java.io.IOException;
import junit.framework.TestCase; import junit.framework.TestCase;
import org.apache.poi.POIXMLProperties.CoreProperties; import org.apache.poi.POIXMLProperties.CoreProperties;
import org.apache.poi.openxml4j.opc.PackageProperties; import org.apache.poi.openxml4j.opc.PackageProperties;
import org.apache.poi.xwpf.usermodel.XWPFDocument; import org.apache.poi.xwpf.usermodel.XWPFDocument;
@ -34,74 +33,73 @@ import org.openxmlformats.schemas.officeDocument.x2006.extendedProperties.CTVect
* submitted because even though the * submitted because even though the
* {@link PackageProperties#getKeywordsProperty()} had been present before, the * {@link PackageProperties#getKeywordsProperty()} had been present before, the
* {@link CoreProperties#getKeywords()} had been missing. * {@link CoreProperties#getKeywords()} had been missing.
* * <p/>
* The author of this has added {@link CoreProperties#getKeywords()} and * The author of this has added {@link CoreProperties#getKeywords()} and
* {@link CoreProperties#setKeywords(String)} and this test is supposed to test * {@link CoreProperties#setKeywords(String)} and this test is supposed to test
* them. * them.
* *
* @author Antoni Mylka * @author Antoni Mylka
*
*/ */
public final class TestAllExtendedProperties extends TestCase { public final class TestAllExtendedProperties extends TestCase {
public void testGetAllExtendedProperties() throws IOException { public void testGetAllExtendedProperties() throws IOException {
XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("TestPoiXMLDocumentCorePropertiesGetKeywords.docx"); XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("TestPoiXMLDocumentCorePropertiesGetKeywords.docx");
CTProperties ctProps = doc.getProperties().getExtendedProperties().getUnderlyingProperties(); CTProperties ctProps = doc.getProperties().getExtendedProperties().getUnderlyingProperties();
assertEquals("Microsoft Office Word",ctProps.getApplication()); assertEquals("Microsoft Office Word", ctProps.getApplication());
assertEquals("14.0000",ctProps.getAppVersion()); assertEquals("14.0000", ctProps.getAppVersion());
assertEquals(57,ctProps.getCharacters()); assertEquals(57, ctProps.getCharacters());
assertEquals(66,ctProps.getCharactersWithSpaces()); assertEquals(66, ctProps.getCharactersWithSpaces());
assertEquals("",ctProps.getCompany()); assertEquals("", ctProps.getCompany());
assertNull(ctProps.getDigSig()); assertNull(ctProps.getDigSig());
assertEquals(0,ctProps.getDocSecurity()); assertEquals(0, ctProps.getDocSecurity());
assertNotNull(ctProps.getDomNode()); assertNotNull(ctProps.getDomNode());
CTVectorVariant vec = ctProps.getHeadingPairs(); CTVectorVariant vec = ctProps.getHeadingPairs();
assertEquals(2,vec.getVector().sizeOfVariantArray()); assertEquals(2, vec.getVector().sizeOfVariantArray());
assertEquals("Title",vec.getVector().getVariantArray(0).getLpstr()); assertEquals("Title", vec.getVector().getVariantArray(0).getLpstr());
assertEquals(1,vec.getVector().getVariantArray(1).getI4()); assertEquals(1, vec.getVector().getVariantArray(1).getI4());
assertFalse(ctProps.isSetHiddenSlides()); assertFalse(ctProps.isSetHiddenSlides());
assertEquals(0,ctProps.getHiddenSlides()); assertEquals(0, ctProps.getHiddenSlides());
assertFalse(ctProps.isSetHLinks()); assertFalse(ctProps.isSetHLinks());
assertNull(ctProps.getHLinks()); assertNull(ctProps.getHLinks());
assertNull(ctProps.getHyperlinkBase()); assertNull(ctProps.getHyperlinkBase());
assertTrue(ctProps.isSetHyperlinksChanged()); assertTrue(ctProps.isSetHyperlinksChanged());
assertFalse(ctProps.getHyperlinksChanged()); assertFalse(ctProps.getHyperlinksChanged());
assertEquals(1,ctProps.getLines()); assertEquals(1, ctProps.getLines());
assertTrue(ctProps.isSetLinksUpToDate()); assertTrue(ctProps.isSetLinksUpToDate());
assertFalse(ctProps.getLinksUpToDate()); assertFalse(ctProps.getLinksUpToDate());
assertNull(ctProps.getManager()); assertNull(ctProps.getManager());
assertFalse(ctProps.isSetMMClips()); assertFalse(ctProps.isSetMMClips());
assertEquals(0,ctProps.getMMClips()); assertEquals(0, ctProps.getMMClips());
assertFalse(ctProps.isSetNotes()); assertFalse(ctProps.isSetNotes());
assertEquals(0,ctProps.getNotes()); assertEquals(0, ctProps.getNotes());
assertEquals(1,ctProps.getPages()); assertEquals(1, ctProps.getPages());
assertEquals(1,ctProps.getParagraphs()); assertEquals(1, ctProps.getParagraphs());
assertNull(ctProps.getPresentationFormat()); assertNull(ctProps.getPresentationFormat());
assertTrue(ctProps.isSetScaleCrop()); assertTrue(ctProps.isSetScaleCrop());
assertFalse(ctProps.getScaleCrop()); assertFalse(ctProps.getScaleCrop());
assertTrue(ctProps.isSetSharedDoc()); assertTrue(ctProps.isSetSharedDoc());
assertFalse(ctProps.getSharedDoc()); assertFalse(ctProps.getSharedDoc());
assertFalse(ctProps.isSetSlides()); assertFalse(ctProps.isSetSlides());
assertEquals(0,ctProps.getSlides()); assertEquals(0, ctProps.getSlides());
assertEquals("Normal.dotm",ctProps.getTemplate()); assertEquals("Normal.dotm", ctProps.getTemplate());
CTVectorLpstr vec2 = ctProps.getTitlesOfParts(); CTVectorLpstr vec2 = ctProps.getTitlesOfParts();
assertEquals(1,vec2.getVector().sizeOfLpstrArray()); assertEquals(1, vec2.getVector().sizeOfLpstrArray());
assertEquals("Example Word 2010 Document",vec2.getVector().getLpstrArray(0)); assertEquals("Example Word 2010 Document", vec2.getVector().getLpstrArray(0));
assertEquals(3,ctProps.getTotalTime()); assertEquals(3, ctProps.getTotalTime());
assertEquals(10,ctProps.getWords()); assertEquals(10, ctProps.getWords());
// Check the digital signature part // Check the digital signature part
// Won't be there in this file, but we // Won't be there in this file, but we
// need to do this check so that the // need to do this check so that the
// appropriate parts end up in the // appropriate parts end up in the
// smaller ooxml schemas file // smaller ooxml schemas file
CTDigSigBlob blob = ctProps.getDigSig(); CTDigSigBlob blob = ctProps.getDigSig();
assertNull(blob); assertNull(blob);
blob = CTDigSigBlob.Factory.newInstance(); blob = CTDigSigBlob.Factory.newInstance();
blob.setBlob(new byte [] {2,6,7,2,3,4,5,1,2,3}); blob.setBlob(new byte[]{2, 6, 7, 2, 3, 4, 5, 1, 2, 3});
} }
} }

View File

@ -20,7 +20,6 @@ package org.apache.poi.xwpf;
import java.io.IOException; import java.io.IOException;
import junit.framework.TestCase; import junit.framework.TestCase;
import org.apache.poi.POIXMLProperties.CoreProperties; import org.apache.poi.POIXMLProperties.CoreProperties;
import org.apache.poi.openxml4j.opc.PackageProperties; import org.apache.poi.openxml4j.opc.PackageProperties;
import org.apache.poi.xwpf.usermodel.XWPFDocument; import org.apache.poi.xwpf.usermodel.XWPFDocument;
@ -30,23 +29,22 @@ import org.apache.poi.xwpf.usermodel.XWPFDocument;
* submitted because even though the * submitted because even though the
* {@link PackageProperties#getKeywordsProperty()} had been present before, the * {@link PackageProperties#getKeywordsProperty()} had been present before, the
* {@link CoreProperties#getKeywords()} had been missing. * {@link CoreProperties#getKeywords()} had been missing.
* * <p/>
* The author of this has added {@link CoreProperties#getKeywords()} and * The author of this has added {@link CoreProperties#getKeywords()} and
* {@link CoreProperties#setKeywords(String)} and this test is supposed to test * {@link CoreProperties#setKeywords(String)} and this test is supposed to test
* them. * them.
* *
* @author Antoni Mylka * @author Antoni Mylka
*
*/ */
public final class TestPackageCorePropertiesGetKeywords extends TestCase { public final class TestPackageCorePropertiesGetKeywords extends TestCase {
public void testGetSetKeywords() throws IOException { public void testGetSetKeywords() throws IOException {
XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("TestPoiXMLDocumentCorePropertiesGetKeywords.docx"); XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("TestPoiXMLDocumentCorePropertiesGetKeywords.docx");
String keywords = doc.getProperties().getCoreProperties().getKeywords(); String keywords = doc.getProperties().getCoreProperties().getKeywords();
assertEquals("extractor, test, rdf", keywords); assertEquals("extractor, test, rdf", keywords);
doc.getProperties().getCoreProperties().setKeywords("test, keywords"); doc.getProperties().getCoreProperties().setKeywords("test, keywords");
doc = XWPFTestDataSamples.writeOutAndReadBack(doc); doc = XWPFTestDataSamples.writeOutAndReadBack(doc);
keywords = doc.getProperties().getCoreProperties().getKeywords(); keywords = doc.getProperties().getCoreProperties().getKeywords();
assertEquals("test, keywords",keywords); assertEquals("test, keywords", keywords);
} }
} }

View File

@ -40,7 +40,7 @@ import org.junit.Test;
public class TestXWPFBugs { public class TestXWPFBugs {
/** /**
* A word document that's encrypted with non-standard * 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 @Test
public void bug53475NoCSPName() throws Exception { public void bug53475NoCSPName() throws Exception {

View File

@ -20,7 +20,6 @@ package org.apache.poi.xwpf.extractor;
import java.io.IOException; import java.io.IOException;
import junit.framework.TestCase; import junit.framework.TestCase;
import org.apache.poi.xwpf.XWPFTestDataSamples; import org.apache.poi.xwpf.XWPFTestDataSamples;
import org.apache.poi.xwpf.usermodel.XWPFDocument; import org.apache.poi.xwpf.usermodel.XWPFDocument;
@ -28,6 +27,7 @@ public class TestExternalEntities extends TestCase {
/** /**
* Get text out of the simple file * Get text out of the simple file
*
* @throws IOException * @throws IOException
*/ */
public void testFile() throws IOException { public void testFile() throws IOException {

View File

@ -22,7 +22,6 @@ import java.util.regex.Matcher;
import java.util.regex.Pattern; import java.util.regex.Pattern;
import junit.framework.TestCase; import junit.framework.TestCase;
import org.apache.poi.xwpf.XWPFTestDataSamples; import org.apache.poi.xwpf.XWPFTestDataSamples;
import org.apache.poi.xwpf.usermodel.XWPFDocument; import org.apache.poi.xwpf.usermodel.XWPFDocument;
@ -33,6 +32,7 @@ public class TestXWPFWordExtractor extends TestCase {
/** /**
* Get text out of the simple file * Get text out of the simple file
*
* @throws IOException * @throws IOException
*/ */
public void testGetSimpleText() throws IOException { public void testGetSimpleText() throws IOException {
@ -65,6 +65,7 @@ public class TestXWPFWordExtractor extends TestCase {
/** /**
* Tests getting the text out of a complex file * Tests getting the text out of a complex file
*
* @throws IOException * @throws IOException
*/ */
public void testGetComplexText() throws IOException { public void testGetComplexText() throws IOException {
@ -108,20 +109,20 @@ public class TestXWPFWordExtractor extends TestCase {
// Now check contents // Now check contents
extractor.setFetchHyperlinks(false); extractor.setFetchHyperlinks(false);
assertEquals( assertEquals(
"This is a test document.\nThis bit is in bold and italic\n" + "This is a test document.\nThis bit is in bold and italic\n" +
"Back to normal\n" + "Back to normal\n" +
"This contains BOLD, ITALIC and BOTH, as well as RED and YELLOW text.\n" + "This contains BOLD, ITALIC and BOTH, as well as RED and YELLOW text.\n" +
"We have a hyperlink here, and another.\n", "We have a hyperlink here, and another.\n",
extractor.getText() extractor.getText()
); );
// One hyperlink is a real one, one is just to the top of page // One hyperlink is a real one, one is just to the top of page
extractor.setFetchHyperlinks(true); extractor.setFetchHyperlinks(true);
assertEquals( assertEquals(
"This is a test document.\nThis bit is in bold and italic\n" + "This is a test document.\nThis bit is in bold and italic\n" +
"Back to normal\n" + "Back to normal\n" +
"This contains BOLD, ITALIC and BOTH, as well as RED and YELLOW text.\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", "We have a hyperlink <http://poi.apache.org/> here, and another.\n",
extractor.getText() extractor.getText()
); );
@ -241,7 +242,8 @@ public class TestXWPFWordExtractor extends TestCase {
/** /**
* Test that we can open and process .docm * Test that we can open and process .docm
* (macro enabled) docx files (bug #45690) * (macro enabled) docx files (bug #45690)
*
* @throws IOException * @throws IOException
*/ */
public void testDOCMFiles() throws IOException { public void testDOCMFiles() throws IOException {
@ -257,28 +259,30 @@ public class TestXWPFWordExtractor extends TestCase {
/** /**
* Test that we handle things like tabs and * Test that we handle things like tabs and
* carriage returns properly in the text that * carriage returns properly in the text that
* we're extracting (bug #49189) * we're extracting (bug #49189)
*
* @throws IOException * @throws IOException
*/ */
public void testDocTabs() throws IOException { public void testDocTabs() throws IOException {
XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("WithTabs.docx"); XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("WithTabs.docx");
XWPFWordExtractor extractor = new XWPFWordExtractor(doc); XWPFWordExtractor extractor = new XWPFWordExtractor(doc);
// Check bits // Check bits
assertTrue(extractor.getText().contains("a")); assertTrue(extractor.getText().contains("a"));
assertTrue(extractor.getText().contains("\t")); assertTrue(extractor.getText().contains("\t"));
assertTrue(extractor.getText().contains("b")); assertTrue(extractor.getText().contains("b"));
// Now check the first paragraph in total // Now check the first paragraph in total
assertTrue(extractor.getText().contains("a\tb\n")); assertTrue(extractor.getText().contains("a\tb\n"));
extractor.close(); extractor.close();
} }
/** /**
* The output should not contain field codes, e.g. those specified in the * The output should not contain field codes, e.g. those specified in the
* w:instrText tag (spec sec. 17.16.23) * w:instrText tag (spec sec. 17.16.23)
*
* @throws IOException * @throws IOException
*/ */
public void testNoFieldCodes() throws IOException { public void testNoFieldCodes() throws IOException {
@ -295,6 +299,7 @@ public class TestXWPFWordExtractor extends TestCase {
/** /**
* The output should contain the values of simple fields, those specified * The output should contain the values of simple fields, those specified
* with the fldSimple element (spec sec. 17.16.19) * with the fldSimple element (spec sec. 17.16.19)
*
* @throws IOException * @throws IOException
*/ */
public void testFldSimpleContent() throws IOException { public void testFldSimpleContent() throws IOException {
@ -322,6 +327,7 @@ public class TestXWPFWordExtractor extends TestCase {
/** /**
* Test for basic extraction of SDT content * Test for basic extraction of SDT content
*
* @throws IOException * @throws IOException
*/ */
public void testSimpleControlContent() throws IOException { public void testSimpleControlContent() throws IOException {
@ -346,13 +352,13 @@ public class TestXWPFWordExtractor extends TestCase {
String s = ex.getText().toLowerCase(); String s = ex.getText().toLowerCase();
int hits = 0; int hits = 0;
for (String targ : targs){ for (String targ : targs) {
boolean hit = false; boolean hit = false;
if (s.indexOf(targ) > -1){ if (s.indexOf(targ) > -1) {
hit = true; hit = true;
hits++; hits++;
} }
assertEquals("controlled content loading-"+targ, true, hit); assertEquals("controlled content loading-" + targ, true, hit);
} }
assertEquals("controlled content loading hit count", targs.length, hits); assertEquals("controlled content loading hit count", targs.length, hits);
ex.close(); ex.close();
@ -369,45 +375,47 @@ public class TestXWPFWordExtractor extends TestCase {
//At one point in development there were three copies of the text. //At one point in development there were three copies of the text.
//This ensures that there is only one copy. //This ensures that there is only one copy.
for (String targ : targs){ for (String targ : targs) {
Matcher m = Pattern.compile(targ).matcher(s); Matcher m = Pattern.compile(targ).matcher(s);
int hit = 0; int hit = 0;
while (m.find()) { while (m.find()) {
hit++; 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. //"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. //This also happens when you save this document as text from MSWord.
Matcher m = Pattern.compile("test\n").matcher(s); Matcher m = Pattern.compile("test\n").matcher(s);
int hit = 0; int hit = 0;
while (m.find()){ while (m.find()) {
hit++; hit++;
} }
assertEquals("test<N>", 2, hit); assertEquals("test<N>", 2, hit);
ex.close(); ex.close();
} }
/** No Header or Footer in document */ /**
* No Header or Footer in document
*/
public void testBug55733() throws Exception { public void testBug55733() throws Exception {
XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("55733.docx"); XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("55733.docx");
XWPFWordExtractor extractor = new XWPFWordExtractor(doc); XWPFWordExtractor extractor = new XWPFWordExtractor(doc);
// Check it gives text without error // Check it gives text without error
extractor.getText(); extractor.getText();
extractor.close(); extractor.close();
} }
public void testCheckboxes() throws IOException { public void testCheckboxes() throws IOException {
XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("checkboxes.docx"); XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("checkboxes.docx");
System.out.println(doc); System.out.println(doc);
XWPFWordExtractor extractor = new XWPFWordExtractor(doc); XWPFWordExtractor extractor = new XWPFWordExtractor(doc);
assertEquals("This is a small test for checkboxes \nunchecked: |_| \n" + assertEquals("This is a small test for checkboxes \nunchecked: |_| \n" +
"Or checked: |X|\n\n\n\n\n" + "Or checked: |X|\n\n\n\n\n" +
"Test a checkbox within a textbox: |_| -> |X|\n\n\n" + "Test a checkbox within a textbox: |_| -> |X|\n\n\n" +
"In Table:\n|_|\t|X|\n\n\n" + "In Table:\n|_|\t|X|\n\n\n" +
"In Sequence:\n|X||_||X|\n", extractor.getText()); "In Sequence:\n|X||_||X|\n", extractor.getText());
extractor.close(); extractor.close();
} }
} }

View File

@ -20,7 +20,6 @@ package org.apache.poi.xwpf.model;
import java.io.IOException; import java.io.IOException;
import junit.framework.TestCase; import junit.framework.TestCase;
import org.apache.poi.xwpf.XWPFTestDataSamples; import org.apache.poi.xwpf.XWPFTestDataSamples;
import org.apache.poi.xwpf.usermodel.XWPFDocument; import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFHyperlinkRun; import org.apache.poi.xwpf.usermodel.XWPFHyperlinkRun;
@ -30,73 +29,73 @@ import org.apache.poi.xwpf.usermodel.XWPFParagraph;
* Tests for the various XWPF decorators * Tests for the various XWPF decorators
*/ */
public class TestXWPFDecorators extends TestCase { public class TestXWPFDecorators extends TestCase {
private XWPFDocument simple; private XWPFDocument simple;
private XWPFDocument hyperlink; private XWPFDocument hyperlink;
private XWPFDocument comments; private XWPFDocument comments;
protected void setUp() throws IOException { protected void setUp() throws IOException {
simple = XWPFTestDataSamples.openSampleDocument("SampleDoc.docx"); simple = XWPFTestDataSamples.openSampleDocument("SampleDoc.docx");
hyperlink = XWPFTestDataSamples.openSampleDocument("TestDocument.docx"); hyperlink = XWPFTestDataSamples.openSampleDocument("TestDocument.docx");
comments = XWPFTestDataSamples.openSampleDocument("WordWithAttachments.docx"); comments = XWPFTestDataSamples.openSampleDocument("WordWithAttachments.docx");
} }
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
public void testHyperlink() { public void testHyperlink() {
XWPFParagraph ps; XWPFParagraph ps;
XWPFParagraph ph; XWPFParagraph ph;
assertEquals(7, simple.getParagraphs().size()); assertEquals(7, simple.getParagraphs().size());
assertEquals(5, hyperlink.getParagraphs().size()); assertEquals(5, hyperlink.getParagraphs().size());
// Simple text // Simple text
ps = simple.getParagraphs().get(0); ps = simple.getParagraphs().get(0);
assertEquals("I am a test document", ps.getParagraphText()); assertEquals("I am a test document", ps.getParagraphText());
assertEquals(1, ps.getRuns().size()); assertEquals(1, ps.getRuns().size());
ph = hyperlink.getParagraphs().get(4); ph = hyperlink.getParagraphs().get(4);
assertEquals("We have a hyperlink here, and another.", ph.getParagraphText()); assertEquals("We have a hyperlink here, and another.", ph.getParagraphText());
assertEquals(3, ph.getRuns().size()); assertEquals(3, ph.getRuns().size());
// The proper way to do hyperlinks(!) // The proper way to do hyperlinks(!)
assertFalse(ps.getRuns().get(0) instanceof XWPFHyperlinkRun); assertFalse(ps.getRuns().get(0) instanceof XWPFHyperlinkRun);
assertFalse(ph.getRuns().get(0) instanceof XWPFHyperlinkRun); assertFalse(ph.getRuns().get(0) instanceof XWPFHyperlinkRun);
assertTrue(ph.getRuns().get(1) instanceof XWPFHyperlinkRun); assertTrue(ph.getRuns().get(1) instanceof XWPFHyperlinkRun);
assertFalse(ph.getRuns().get(2) instanceof XWPFHyperlinkRun); assertFalse(ph.getRuns().get(2) instanceof XWPFHyperlinkRun);
XWPFHyperlinkRun link = (XWPFHyperlinkRun)ph.getRuns().get(1); XWPFHyperlinkRun link = (XWPFHyperlinkRun) ph.getRuns().get(1);
assertEquals("http://poi.apache.org/", link.getHyperlink(hyperlink).getURL()); assertEquals("http://poi.apache.org/", link.getHyperlink(hyperlink).getURL());
// Test the old style decorator // Test the old style decorator
// You probably don't want to still be using it... // You probably don't want to still be using it...
assertEquals( assertEquals(
"I am a test document", "I am a test document",
(new XWPFHyperlinkDecorator(ps, null, false)).getText() (new XWPFHyperlinkDecorator(ps, null, false)).getText()
); );
assertEquals( assertEquals(
"I am a test document", "I am a test document",
(new XWPFHyperlinkDecorator(ps, null, true)).getText() (new XWPFHyperlinkDecorator(ps, null, true)).getText()
); );
assertEquals( assertEquals(
"We have a hyperlink here, and another.hyperlink", "We have a hyperlink here, and another.hyperlink",
(new XWPFHyperlinkDecorator(ph, null, false)).getText() (new XWPFHyperlinkDecorator(ph, null, false)).getText()
); );
assertEquals( assertEquals(
"We have a hyperlink here, and another.hyperlink <http://poi.apache.org/>", "We have a hyperlink here, and another.hyperlink <http://poi.apache.org/>",
(new XWPFHyperlinkDecorator(ph, null, true)).getText() (new XWPFHyperlinkDecorator(ph, null, true)).getText()
); );
} }
public void testComments() { public void testComments() {
int numComments = 0; int numComments = 0;
for(XWPFParagraph p : comments.getParagraphs()) { for (XWPFParagraph p : comments.getParagraphs()) {
XWPFCommentsDecorator d = new XWPFCommentsDecorator(p, null); XWPFCommentsDecorator d = new XWPFCommentsDecorator(p, null);
if(d.getCommentText().length() > 0) { if (d.getCommentText().length() > 0) {
numComments++; numComments++;
assertEquals("\tComment by", d.getCommentText().substring(0, 11)); assertEquals("\tComment by", d.getCommentText().substring(0, 11));
} }
} }
assertEquals(3, numComments); assertEquals(3, numComments);
} }
} }

View File

@ -20,7 +20,6 @@ package org.apache.poi.xwpf.model;
import java.io.IOException; import java.io.IOException;
import junit.framework.TestCase; import junit.framework.TestCase;
import org.apache.poi.xwpf.XWPFTestDataSamples; import org.apache.poi.xwpf.XWPFTestDataSamples;
import org.apache.poi.xwpf.usermodel.XWPFDocument; import org.apache.poi.xwpf.usermodel.XWPFDocument;
@ -28,130 +27,130 @@ import org.apache.poi.xwpf.usermodel.XWPFDocument;
* Tests for XWPF Header Footer Stuff * Tests for XWPF Header Footer Stuff
*/ */
public class TestXWPFHeaderFooterPolicy extends TestCase { public class TestXWPFHeaderFooterPolicy extends TestCase {
private XWPFDocument noHeader; private XWPFDocument noHeader;
private XWPFDocument header; private XWPFDocument header;
private XWPFDocument headerFooter; private XWPFDocument headerFooter;
private XWPFDocument footer; private XWPFDocument footer;
private XWPFDocument oddEven; private XWPFDocument oddEven;
private XWPFDocument diffFirst; private XWPFDocument diffFirst;
protected void setUp() throws IOException { protected void setUp() throws IOException {
noHeader = XWPFTestDataSamples.openSampleDocument("NoHeadFoot.docx"); noHeader = XWPFTestDataSamples.openSampleDocument("NoHeadFoot.docx");
header = XWPFTestDataSamples.openSampleDocument("ThreeColHead.docx"); header = XWPFTestDataSamples.openSampleDocument("ThreeColHead.docx");
headerFooter = XWPFTestDataSamples.openSampleDocument("SimpleHeadThreeColFoot.docx"); headerFooter = XWPFTestDataSamples.openSampleDocument("SimpleHeadThreeColFoot.docx");
footer = XWPFTestDataSamples.openSampleDocument("FancyFoot.docx"); footer = XWPFTestDataSamples.openSampleDocument("FancyFoot.docx");
oddEven = XWPFTestDataSamples.openSampleDocument("PageSpecificHeadFoot.docx"); oddEven = XWPFTestDataSamples.openSampleDocument("PageSpecificHeadFoot.docx");
diffFirst = XWPFTestDataSamples.openSampleDocument("DiffFirstPageHeadFoot.docx"); diffFirst = XWPFTestDataSamples.openSampleDocument("DiffFirstPageHeadFoot.docx");
} }
public void testPolicy() { public void testPolicy() {
XWPFHeaderFooterPolicy policy; XWPFHeaderFooterPolicy policy;
policy = noHeader.getHeaderFooterPolicy(); policy = noHeader.getHeaderFooterPolicy();
assertNull(policy.getDefaultHeader()); assertNull(policy.getDefaultHeader());
assertNull(policy.getDefaultFooter()); assertNull(policy.getDefaultFooter());
assertNull(policy.getHeader(1)); assertNull(policy.getHeader(1));
assertNull(policy.getHeader(2)); assertNull(policy.getHeader(2));
assertNull(policy.getHeader(3)); assertNull(policy.getHeader(3));
assertNull(policy.getFooter(1)); assertNull(policy.getFooter(1));
assertNull(policy.getFooter(2)); assertNull(policy.getFooter(2));
assertNull(policy.getFooter(3)); assertNull(policy.getFooter(3));
policy = header.getHeaderFooterPolicy(); policy = header.getHeaderFooterPolicy();
assertNotNull(policy.getDefaultHeader()); assertNotNull(policy.getDefaultHeader());
assertNull(policy.getDefaultFooter()); assertNull(policy.getDefaultFooter());
assertEquals(policy.getDefaultHeader(), policy.getHeader(1)); assertEquals(policy.getDefaultHeader(), policy.getHeader(1));
assertEquals(policy.getDefaultHeader(), policy.getHeader(2)); assertEquals(policy.getDefaultHeader(), policy.getHeader(2));
assertEquals(policy.getDefaultHeader(), policy.getHeader(3)); assertEquals(policy.getDefaultHeader(), policy.getHeader(3));
assertNull(policy.getFooter(1)); assertNull(policy.getFooter(1));
assertNull(policy.getFooter(2)); assertNull(policy.getFooter(2));
assertNull(policy.getFooter(3)); assertNull(policy.getFooter(3));
policy = footer.getHeaderFooterPolicy(); policy = footer.getHeaderFooterPolicy();
assertNull(policy.getDefaultHeader()); assertNull(policy.getDefaultHeader());
assertNotNull(policy.getDefaultFooter()); assertNotNull(policy.getDefaultFooter());
assertNull(policy.getHeader(1)); assertNull(policy.getHeader(1));
assertNull(policy.getHeader(2)); assertNull(policy.getHeader(2));
assertNull(policy.getHeader(3)); assertNull(policy.getHeader(3));
assertEquals(policy.getDefaultFooter(), policy.getFooter(1)); assertEquals(policy.getDefaultFooter(), policy.getFooter(1));
assertEquals(policy.getDefaultFooter(), policy.getFooter(2)); assertEquals(policy.getDefaultFooter(), policy.getFooter(2));
assertEquals(policy.getDefaultFooter(), policy.getFooter(3)); assertEquals(policy.getDefaultFooter(), policy.getFooter(3));
policy = headerFooter.getHeaderFooterPolicy(); policy = headerFooter.getHeaderFooterPolicy();
assertNotNull(policy.getDefaultHeader()); assertNotNull(policy.getDefaultHeader());
assertNotNull(policy.getDefaultFooter()); assertNotNull(policy.getDefaultFooter());
assertEquals(policy.getDefaultHeader(), policy.getHeader(1)); assertEquals(policy.getDefaultHeader(), policy.getHeader(1));
assertEquals(policy.getDefaultHeader(), policy.getHeader(2)); assertEquals(policy.getDefaultHeader(), policy.getHeader(2));
assertEquals(policy.getDefaultHeader(), policy.getHeader(3)); assertEquals(policy.getDefaultHeader(), policy.getHeader(3));
assertEquals(policy.getDefaultFooter(), policy.getFooter(1)); assertEquals(policy.getDefaultFooter(), policy.getFooter(1));
assertEquals(policy.getDefaultFooter(), policy.getFooter(2)); assertEquals(policy.getDefaultFooter(), policy.getFooter(2));
assertEquals(policy.getDefaultFooter(), policy.getFooter(3)); assertEquals(policy.getDefaultFooter(), policy.getFooter(3));
policy = oddEven.getHeaderFooterPolicy(); policy = oddEven.getHeaderFooterPolicy();
assertNotNull(policy.getDefaultHeader()); assertNotNull(policy.getDefaultHeader());
assertNotNull(policy.getDefaultFooter()); assertNotNull(policy.getDefaultFooter());
assertNotNull(policy.getEvenPageHeader()); assertNotNull(policy.getEvenPageHeader());
assertNotNull(policy.getEvenPageFooter()); assertNotNull(policy.getEvenPageFooter());
assertEquals(policy.getDefaultHeader(), policy.getHeader(1)); assertEquals(policy.getDefaultHeader(), policy.getHeader(1));
assertEquals(policy.getEvenPageHeader(), policy.getHeader(2)); assertEquals(policy.getEvenPageHeader(), policy.getHeader(2));
assertEquals(policy.getDefaultHeader(), policy.getHeader(3)); assertEquals(policy.getDefaultHeader(), policy.getHeader(3));
assertEquals(policy.getDefaultFooter(), policy.getFooter(1)); assertEquals(policy.getDefaultFooter(), policy.getFooter(1));
assertEquals(policy.getEvenPageFooter(), policy.getFooter(2)); assertEquals(policy.getEvenPageFooter(), policy.getFooter(2));
assertEquals(policy.getDefaultFooter(), policy.getFooter(3)); assertEquals(policy.getDefaultFooter(), policy.getFooter(3));
policy = diffFirst.getHeaderFooterPolicy(); policy = diffFirst.getHeaderFooterPolicy();
assertNotNull(policy.getDefaultHeader()); assertNotNull(policy.getDefaultHeader());
assertNotNull(policy.getDefaultFooter()); assertNotNull(policy.getDefaultFooter());
assertNotNull(policy.getFirstPageHeader()); assertNotNull(policy.getFirstPageHeader());
assertNotNull(policy.getFirstPageFooter()); assertNotNull(policy.getFirstPageFooter());
assertNull(policy.getEvenPageHeader()); assertNull(policy.getEvenPageHeader());
assertNull(policy.getEvenPageFooter()); assertNull(policy.getEvenPageFooter());
assertEquals(policy.getFirstPageHeader(), policy.getHeader(1)); assertEquals(policy.getFirstPageHeader(), policy.getHeader(1));
assertEquals(policy.getDefaultHeader(), policy.getHeader(2)); assertEquals(policy.getDefaultHeader(), policy.getHeader(2));
assertEquals(policy.getDefaultHeader(), policy.getHeader(3)); assertEquals(policy.getDefaultHeader(), policy.getHeader(3));
assertEquals(policy.getFirstPageFooter(), policy.getFooter(1)); assertEquals(policy.getFirstPageFooter(), policy.getFooter(1));
assertEquals(policy.getDefaultFooter(), policy.getFooter(2)); assertEquals(policy.getDefaultFooter(), policy.getFooter(2));
assertEquals(policy.getDefaultFooter(), policy.getFooter(3)); assertEquals(policy.getDefaultFooter(), policy.getFooter(3));
} }
public void testContents() { public void testContents() {
XWPFHeaderFooterPolicy policy; XWPFHeaderFooterPolicy policy;
// Test a few simple bits off a simple header // Test a few simple bits off a simple header
policy = diffFirst.getHeaderFooterPolicy(); policy = diffFirst.getHeaderFooterPolicy();
assertEquals( assertEquals(
"I am the header on the first page, and I" + '\u2019' + "m nice and simple\n", "I am the header on the first page, and I" + '\u2019' + "m nice and simple\n",
policy.getFirstPageHeader().getText() policy.getFirstPageHeader().getText()
); );
assertEquals( assertEquals(
"First header column!\tMid header\tRight header!\n", "First header column!\tMid header\tRight header!\n",
policy.getDefaultHeader().getText() policy.getDefaultHeader().getText()
); );
// And a few bits off a more complex header // And a few bits off a more complex header
policy = oddEven.getHeaderFooterPolicy(); policy = oddEven.getHeaderFooterPolicy();
assertEquals( assertEquals(
"[ODD Page Header text]\n\n", "[ODD Page Header text]\n\n",
policy.getDefaultHeader().getText() policy.getDefaultHeader().getText()
); );
assertEquals( assertEquals(
"[This is an Even Page, with a Header]\n\n", "[This is an Even Page, with a Header]\n\n",
policy.getEvenPageHeader().getText() policy.getEvenPageHeader().getText()
); );
} }
} }

View File

@ -19,11 +19,9 @@ package org.apache.poi.xwpf.usermodel;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNotNull;
import java.io.FileInputStream;
import java.io.IOException; import java.io.IOException;
import org.apache.poi.openxml4j.exceptions.OpenXML4JException; 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.XWPFTestDataSamples;
import org.apache.poi.xwpf.usermodel.XWPFRun.FontCharRange; import org.apache.poi.xwpf.usermodel.XWPFRun.FontCharRange;
import org.junit.Test; import org.junit.Test;
@ -32,11 +30,11 @@ public class TestXWPFBugs {
@Test @Test
public void bug55802() throws Exception { public void bug55802() throws Exception {
String blabla = String blabla =
"Bir, iki, \u00fc\u00e7, d\u00f6rt, be\u015f,\n"+ "Bir, iki, \u00fc\u00e7, d\u00f6rt, be\u015f,\n" +
"\nalt\u0131, yedi, sekiz, dokuz, on.\n"+ "\nalt\u0131, yedi, sekiz, dokuz, on.\n" +
"\nK\u0131rm\u0131z\u0131 don,\n"+ "\nK\u0131rm\u0131z\u0131 don,\n" +
"\ngel bizim bah\u00e7eye kon,\n"+ "\ngel bizim bah\u00e7eye kon,\n" +
"\nsar\u0131 limon"; "\nsar\u0131 limon";
XWPFDocument doc = new XWPFDocument(); XWPFDocument doc = new XWPFDocument();
XWPFRun run = doc.createParagraph().createRun(); XWPFRun run = doc.createParagraph().createRun();
@ -61,15 +59,15 @@ public class TestXWPFBugs {
XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("57312.docx"); XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("57312.docx");
assertNotNull(doc); assertNotNull(doc);
for( IBodyElement bodyElement : doc.getBodyElements()){ for (IBodyElement bodyElement : doc.getBodyElements()) {
BodyElementType elementType = bodyElement.getElementType(); BodyElementType elementType = bodyElement.getElementType();
if(elementType == BodyElementType.PARAGRAPH) { if (elementType == BodyElementType.PARAGRAPH) {
XWPFParagraph paragraph = (XWPFParagraph) bodyElement; XWPFParagraph paragraph = (XWPFParagraph) bodyElement;
for (IRunElement iRunElem : paragraph.getIRuns()){ for (IRunElement iRunElem : paragraph.getIRuns()) {
if (iRunElem instanceof XWPFRun){ if (iRunElem instanceof XWPFRun) {
XWPFRun runElement = (XWPFRun) iRunElem; XWPFRun runElement = (XWPFRun) iRunElem;
UnderlinePatterns underline = runElement.getUnderline(); UnderlinePatterns underline = runElement.getUnderline();
@ -86,7 +84,7 @@ public class TestXWPFBugs {
@Test @Test
public void test56392() throws IOException, OpenXML4JException { public void test56392() throws IOException, OpenXML4JException {
XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("56392.docx"); XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("56392.docx");
assertNotNull(doc); assertNotNull(doc);
} }
/** /**

View File

@ -23,7 +23,6 @@ import java.util.Arrays;
import java.util.List; import java.util.List;
import junit.framework.TestCase; import junit.framework.TestCase;
import org.apache.poi.POIXMLDocumentPart; import org.apache.poi.POIXMLDocumentPart;
import org.apache.poi.POIXMLProperties; import org.apache.poi.POIXMLProperties;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException; import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
@ -44,8 +43,8 @@ public final class TestXWPFDocument extends TestCase {
OPCPackage pack = doc.getPackage(); OPCPackage pack = doc.getPackage();
boolean found = false; boolean found = false;
for(PackagePart part : pack.getParts()) { for (PackagePart part : pack.getParts()) {
if(part.getContentType().equals(XWPFRelation.DOCUMENT.getContentType())) { if (part.getContentType().equals(XWPFRelation.DOCUMENT.getContentType())) {
found = true; found = true;
} }
if (false) { if (false) {
@ -106,7 +105,7 @@ public final class TestXWPFDocument extends TestCase {
assertEquals("Apache POI", props.getExtendedProperties().getUnderlyingProperties().getApplication()); assertEquals("Apache POI", props.getExtendedProperties().getUnderlyingProperties().getApplication());
} }
public void testAddParagraph() throws IOException{ public void testAddParagraph() throws IOException {
XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("sample.docx"); XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("sample.docx");
assertEquals(3, doc.getParagraphs().size()); assertEquals(3, doc.getParagraphs().size());
@ -129,15 +128,15 @@ public final class TestXWPFDocument extends TestCase {
public void testAddPicture() throws IOException, InvalidFormatException { public void testAddPicture() throws IOException, InvalidFormatException {
XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("sample.docx"); XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("sample.docx");
byte[] jpeg = XWPFTestDataSamples.getImage("nature1.jpg"); 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(); byte[] newJpeg = ((XWPFPictureData) doc.getRelationById(relationId)).getData();
assertEquals(newJpeg.length,jpeg.length); assertEquals(newJpeg.length, jpeg.length);
for (int i = 0 ; i < jpeg.length ; i++) for (int i = 0; i < jpeg.length; i++) {
{ assertEquals(newJpeg[i], jpeg[i]);
assertEquals(newJpeg[i],jpeg[i]);
} }
} }
public void testAllPictureFormats() throws IOException, InvalidFormatException { public void testAllPictureFormats() throws IOException, InvalidFormatException {
XWPFDocument doc = new XWPFDocument(); XWPFDocument doc = new XWPFDocument();
@ -235,7 +234,7 @@ public final class TestXWPFDocument extends TestCase {
os.close(); os.close();
XWPFHeader xwpfHeader = doc.getHeaderArray(0); XWPFHeader xwpfHeader = doc.getHeaderArray(0);
PackageRelationship relationship = xwpfHeader.getPackagePart().addRelationship(partName, TargetMode.INTERNAL, jpgRelation.getRelation()); 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 */ /* new part is now ready to rumble */
assertFalse(xwpfHeader.getAllPictures().contains(newPicData)); assertFalse(xwpfHeader.getAllPictures().contains(newPicData));
@ -267,7 +266,7 @@ public final class TestXWPFDocument extends TestCase {
List<XWPFPictureData> allPackagePictures = doc.getAllPackagePictures(); List<XWPFPictureData> allPackagePictures = doc.getAllPackagePictures();
assertNotNull(allPictures); assertNotNull(allPictures);
assertEquals(3,allPictures.size()); assertEquals(3, allPictures.size());
for (XWPFPictureData xwpfPictureData : allPictures) { for (XWPFPictureData xwpfPictureData : allPictures) {
assertTrue(allPackagePictures.contains(xwpfPictureData)); assertTrue(allPackagePictures.contains(xwpfPictureData));
} }
@ -287,7 +286,7 @@ public final class TestXWPFDocument extends TestCase {
List<XWPFPictureData> allPackagePictures = doc.getAllPackagePictures(); List<XWPFPictureData> allPackagePictures = doc.getAllPackagePictures();
assertNotNull(allPackagePictures); assertNotNull(allPackagePictures);
assertEquals(5,allPackagePictures.size()); assertEquals(5, allPackagePictures.size());
try { try {
allPackagePictures.add(allPackagePictures.get(0)); allPackagePictures.add(allPackagePictures.get(0));
@ -301,22 +300,22 @@ public final class TestXWPFDocument extends TestCase {
public void testPictureHandlingSimpleFile() throws IOException, InvalidFormatException { public void testPictureHandlingSimpleFile() throws IOException, InvalidFormatException {
XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("issue_51265_1.docx"); XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("issue_51265_1.docx");
assertEquals(1,doc.getAllPackagePictures().size()); assertEquals(1, doc.getAllPackagePictures().size());
byte[] newPic = XWPFTestDataSamples.getImage("abstract4.jpg"); byte[] newPic = XWPFTestDataSamples.getImage("abstract4.jpg");
String id1 = doc.addPictureData(newPic, Document.PICTURE_TYPE_JPEG); 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 */ /* copy data, to avoid instance-equality */
byte[] newPicCopy = Arrays.copyOf(newPic, newPic.length); byte[] newPicCopy = Arrays.copyOf(newPic, newPic.length);
String id2 = doc.addPictureData(newPicCopy, Document.PICTURE_TYPE_JPEG); String id2 = doc.addPictureData(newPicCopy, Document.PICTURE_TYPE_JPEG);
assertEquals(id1,id2); assertEquals(id1, id2);
doc.getPackage().revert(); doc.getPackage().revert();
} }
public void testPictureHandlingHeaderDocumentImages() throws IOException { public void testPictureHandlingHeaderDocumentImages() throws IOException {
XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("issue_51265_2.docx"); XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("issue_51265_2.docx");
assertEquals(1,doc.getAllPictures().size()); assertEquals(1, doc.getAllPictures().size());
assertEquals(1,doc.getAllPackagePictures().size()); assertEquals(1, doc.getAllPackagePictures().size());
assertEquals(1,doc.getHeaderArray(0).getAllPictures().size()); assertEquals(1, doc.getHeaderArray(0).getAllPictures().size());
doc.getPackage().revert(); doc.getPackage().revert();
} }
@ -324,18 +323,19 @@ public final class TestXWPFDocument extends TestCase {
XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("issue_51265_3.docx"); XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("issue_51265_3.docx");
XWPFHeader xwpfHeader = doc.getHeaderArray(0); XWPFHeader xwpfHeader = doc.getHeaderArray(0);
assertEquals(3,doc.getAllPictures().size()); assertEquals(3, doc.getAllPictures().size());
assertEquals(3,xwpfHeader.getAllPictures().size()); assertEquals(3, xwpfHeader.getAllPictures().size());
assertEquals(5,doc.getAllPackagePictures().size()); assertEquals(5, doc.getAllPackagePictures().size());
byte[] nature1 = XWPFTestDataSamples.getImage("nature1.jpg"); byte[] nature1 = XWPFTestDataSamples.getImage("nature1.jpg");
String id = doc.addPictureData(nature1, Document.PICTURE_TYPE_JPEG); String id = doc.addPictureData(nature1, Document.PICTURE_TYPE_JPEG);
POIXMLDocumentPart part1 = xwpfHeader.getRelationById("rId1"); POIXMLDocumentPart part1 = xwpfHeader.getRelationById("rId1");
XWPFPictureData part2 = (XWPFPictureData) doc.getRelationById(id); XWPFPictureData part2 = (XWPFPictureData) doc.getRelationById(id);
assertSame(part1,part2); assertSame(part1, part2);
doc.getPackage().revert(); doc.getPackage().revert();
} }
public void testZeroLengthLibreOfficeDocumentWithWaterMarkHeader() throws IOException { public void testZeroLengthLibreOfficeDocumentWithWaterMarkHeader() throws IOException {
XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("zero-length.docx"); XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("zero-length.docx");
POIXMLProperties properties = doc.getProperties(); POIXMLProperties properties = doc.getProperties();
@ -352,7 +352,7 @@ public final class TestXWPFDocument extends TestCase {
assertEquals(0, extendedProperties.getUnderlyingProperties().getCharacters()); assertEquals(0, extendedProperties.getUnderlyingProperties().getCharacters());
} }
public void testSettings(){ public void testSettings() {
XWPFSettings settings = new XWPFSettings(); XWPFSettings settings = new XWPFSettings();
settings.setZoomPercent(50); settings.setZoomPercent(50);
assertEquals(50, settings.getZoomPercent()); assertEquals(50, settings.getZoomPercent());

View File

@ -22,49 +22,47 @@ import java.math.BigInteger;
import java.util.List; import java.util.List;
import junit.framework.TestCase; import junit.framework.TestCase;
import org.apache.poi.xwpf.XWPFTestDataSamples; import org.apache.poi.xwpf.XWPFTestDataSamples;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTFtnEdn; import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTFtnEdn;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.STFtnEdn; import org.openxmlformats.schemas.wordprocessingml.x2006.main.STFtnEdn;
public class TestXWPFFootnotes extends TestCase { public class TestXWPFFootnotes extends TestCase {
public void testAddFootnotesToDocument() throws IOException{ public void testAddFootnotesToDocument() throws IOException {
XWPFDocument docOut = new XWPFDocument(); XWPFDocument docOut = new XWPFDocument();
BigInteger noteId = BigInteger.valueOf(1); BigInteger noteId = BigInteger.valueOf(1);
XWPFFootnotes footnotes = docOut.createFootnotes(); XWPFFootnotes footnotes = docOut.createFootnotes();
CTFtnEdn ctNote = CTFtnEdn.Factory.newInstance(); CTFtnEdn ctNote = CTFtnEdn.Factory.newInstance();
ctNote.setId(noteId); ctNote.setId(noteId);
ctNote.setType(STFtnEdn.NORMAL); ctNote.setType(STFtnEdn.NORMAL);
footnotes.addFootnote(ctNote); footnotes.addFootnote(ctNote);
XWPFDocument docIn = XWPFTestDataSamples.writeOutAndReadBack(docOut); XWPFDocument docIn = XWPFTestDataSamples.writeOutAndReadBack(docOut);
XWPFFootnote note = docIn.getFootnoteByID(noteId.intValue()); XWPFFootnote note = docIn.getFootnoteByID(noteId.intValue());
assertEquals(note.getCTFtnEdn().getType(), STFtnEdn.NORMAL); assertEquals(note.getCTFtnEdn().getType(), STFtnEdn.NORMAL);
} }
/** /**
* Bug 55066 - avoid double loading the footnotes * Bug 55066 - avoid double loading the footnotes
*/ */
public void testLoadFootnotesOnce() throws IOException{ public void testLoadFootnotesOnce() throws IOException {
XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("Bug54849.docx"); XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("Bug54849.docx");
List<XWPFFootnote> footnotes = doc.getFootnotes(); List<XWPFFootnote> footnotes = doc.getFootnotes();
int hits = 0; int hits = 0;
for (XWPFFootnote fn : footnotes){ for (XWPFFootnote fn : footnotes) {
for (IBodyElement e : fn.getBodyElements()){ for (IBodyElement e : fn.getBodyElements()) {
if (e instanceof XWPFParagraph){ if (e instanceof XWPFParagraph) {
String txt = ((XWPFParagraph)e).getText(); String txt = ((XWPFParagraph) e).getText();
if (txt.indexOf("Footnote_sdt") > -1){ if (txt.indexOf("Footnote_sdt") > -1) {
hits++; hits++;
} }
} }
} }
} }
assertEquals("Load footnotes once", 1, hits); assertEquals("Load footnotes once", 1, hits);
} }
} }

View File

@ -20,7 +20,6 @@ package org.apache.poi.xwpf.usermodel;
import java.io.IOException; import java.io.IOException;
import junit.framework.TestCase; import junit.framework.TestCase;
import org.apache.poi.xwpf.XWPFTestDataSamples; import org.apache.poi.xwpf.XWPFTestDataSamples;
import org.apache.poi.xwpf.model.XWPFHeaderFooterPolicy; import org.apache.poi.xwpf.model.XWPFHeaderFooterPolicy;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTP; import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTP;

View File

@ -19,7 +19,6 @@ package org.apache.poi.xwpf.usermodel;
import java.io.IOException; import java.io.IOException;
import junit.framework.TestCase; import junit.framework.TestCase;
import org.apache.poi.xwpf.XWPFTestDataSamples; import org.apache.poi.xwpf.XWPFTestDataSamples;
import org.apache.xmlbeans.XmlException; import org.apache.xmlbeans.XmlException;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTSdtBlock; import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTSdtBlock;
@ -27,25 +26,25 @@ import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTSdtBlock;
/** /**
* @author Paolo Mottadelli * @author Paolo Mottadelli
*/ */
public final class TestXWPFHeadings extends TestCase{ public final class TestXWPFHeadings extends TestCase {
private static final String HEADING1 = "Heading1"; private static final String HEADING1 = "Heading1";
public void testSetParagraphStyle() throws IOException, XmlException { public void testSetParagraphStyle() throws IOException, XmlException {
//new clean instance of paragraph //new clean instance of paragraph
XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("heading123.docx"); XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("heading123.docx");
XWPFParagraph p = doc.createParagraph(); XWPFParagraph p = doc.createParagraph();
XWPFRun run = p.createRun(); XWPFRun run = p.createRun();
run.setText("Heading 1"); run.setText("Heading 1");
CTSdtBlock block = doc.getDocument().getBody().addNewSdt(); CTSdtBlock block = doc.getDocument().getBody().addNewSdt();
assertNull(p.getStyle()); assertNull(p.getStyle());
p.setStyle(HEADING1); p.setStyle(HEADING1);
assertEquals(HEADING1, p.getCTP().getPPr().getPStyle().getVal()); assertEquals(HEADING1, p.getCTP().getPPr().getPStyle().getVal());
doc.createTOC(); doc.createTOC();
/* /*
// TODO - finish this test // TODO - finish this test
if (false) { if (false) {
CTStyles styles = doc.getStyle(); CTStyles styles = doc.getStyle();
CTStyle style = styles.addNewStyle(); CTStyle style = styles.addNewStyle();

View File

@ -21,83 +21,82 @@ import java.io.IOException;
import java.math.BigInteger; import java.math.BigInteger;
import junit.framework.TestCase; import junit.framework.TestCase;
import org.apache.poi.xwpf.XWPFTestDataSamples; import org.apache.poi.xwpf.XWPFTestDataSamples;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTNum; import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTNum;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTNumLvl; import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTNumLvl;
public class TestXWPFNumbering extends TestCase { public class TestXWPFNumbering extends TestCase {
public void testCompareAbstractNum() throws IOException { public void testCompareAbstractNum() throws IOException {
XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("Numbering.docx"); XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("Numbering.docx");
XWPFNumbering numbering = doc.getNumbering(); XWPFNumbering numbering = doc.getNumbering();
BigInteger numId = BigInteger.valueOf(1); BigInteger numId = BigInteger.valueOf(1);
assertTrue(numbering.numExist(numId)); assertTrue(numbering.numExist(numId));
XWPFNum num = numbering.getNum(numId); XWPFNum num = numbering.getNum(numId);
BigInteger abstrNumId = num.getCTNum().getAbstractNumId().getVal(); BigInteger abstrNumId = num.getCTNum().getAbstractNumId().getVal();
XWPFAbstractNum abstractNum = numbering.getAbstractNum(abstrNumId); XWPFAbstractNum abstractNum = numbering.getAbstractNum(abstrNumId);
BigInteger compareAbstractNum = numbering.getIdOfAbstractNum(abstractNum); BigInteger compareAbstractNum = numbering.getIdOfAbstractNum(abstractNum);
assertEquals(abstrNumId, compareAbstractNum); assertEquals(abstrNumId, compareAbstractNum);
} }
public void testAddNumberingToDoc() throws IOException{ public void testAddNumberingToDoc() throws IOException {
BigInteger abstractNumId = BigInteger.valueOf(1); BigInteger abstractNumId = BigInteger.valueOf(1);
BigInteger numId = BigInteger.valueOf(1); BigInteger numId = BigInteger.valueOf(1);
XWPFDocument docOut = new XWPFDocument(); XWPFDocument docOut = new XWPFDocument();
XWPFNumbering numbering = docOut.createNumbering(); XWPFNumbering numbering = docOut.createNumbering();
numId = numbering.addNum(abstractNumId); numId = numbering.addNum(abstractNumId);
XWPFDocument docIn = XWPFTestDataSamples.writeOutAndReadBack(docOut); XWPFDocument docIn = XWPFTestDataSamples.writeOutAndReadBack(docOut);
numbering = docIn.getNumbering(); numbering = docIn.getNumbering();
assertTrue(numbering.numExist(numId)); assertTrue(numbering.numExist(numId));
XWPFNum num = numbering.getNum(numId); XWPFNum num = numbering.getNum(numId);
BigInteger compareAbstractNum = num.getCTNum().getAbstractNumId().getVal(); BigInteger compareAbstractNum = num.getCTNum().getAbstractNumId().getVal();
assertEquals(abstractNumId, compareAbstractNum); assertEquals(abstractNumId, compareAbstractNum);
} }
public void testGetNumIlvl() throws IOException{ public void testGetNumIlvl() throws IOException {
XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("Numbering.docx"); XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("Numbering.docx");
BigInteger numIlvl = BigInteger.valueOf(0); BigInteger numIlvl = BigInteger.valueOf(0);
assertEquals(numIlvl, doc.getParagraphs().get(0).getNumIlvl()); assertEquals(numIlvl, doc.getParagraphs().get(0).getNumIlvl());
numIlvl = BigInteger.valueOf(1); numIlvl = BigInteger.valueOf(1);
assertEquals(numIlvl, doc.getParagraphs().get(5).getNumIlvl()); assertEquals(numIlvl, doc.getParagraphs().get(5).getNumIlvl());
} }
public void testGetNumFmt() throws IOException{ public void testGetNumFmt() throws IOException {
XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("Numbering.docx"); XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("Numbering.docx");
assertEquals("bullet", doc.getParagraphs().get(0).getNumFmt()); assertEquals("bullet", doc.getParagraphs().get(0).getNumFmt());
assertEquals("bullet", doc.getParagraphs().get(1).getNumFmt()); assertEquals("bullet", doc.getParagraphs().get(1).getNumFmt());
assertEquals("bullet", doc.getParagraphs().get(2).getNumFmt()); assertEquals("bullet", doc.getParagraphs().get(2).getNumFmt());
assertEquals("bullet", doc.getParagraphs().get(3).getNumFmt()); assertEquals("bullet", doc.getParagraphs().get(3).getNumFmt());
assertEquals("decimal", doc.getParagraphs().get(4).getNumFmt()); assertEquals("decimal", doc.getParagraphs().get(4).getNumFmt());
assertEquals("lowerLetter", doc.getParagraphs().get(5).getNumFmt()); assertEquals("lowerLetter", doc.getParagraphs().get(5).getNumFmt());
assertEquals("lowerRoman", doc.getParagraphs().get(6).getNumFmt()); assertEquals("lowerRoman", doc.getParagraphs().get(6).getNumFmt());
} }
public void testLvlText() throws IOException { public void testLvlText() throws IOException {
XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("Numbering.docx"); XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("Numbering.docx");
assertEquals("%1.%2.%3.", doc.getParagraphs().get(12).getNumLevelText()); assertEquals("%1.%2.%3.", doc.getParagraphs().get(12).getNumLevelText());
assertEquals("NEW-%1-FORMAT", doc.getParagraphs().get(14).getNumLevelText()); assertEquals("NEW-%1-FORMAT", doc.getParagraphs().get(14).getNumLevelText());
XWPFParagraph p = doc.getParagraphs().get(18); XWPFParagraph p = doc.getParagraphs().get(18);
assertEquals("%1.", p.getNumLevelText()); assertEquals("%1.", p.getNumLevelText());
//test that null doesn't throw NPE //test that null doesn't throw NPE
assertNull(p.getNumFmt()); assertNull(p.getNumFmt());
} }
public void testOverrideList() throws IOException { public void testOverrideList() throws IOException {
XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("NumberingWOverrides.docx"); XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("NumberingWOverrides.docx");
XWPFParagraph p = doc.getParagraphs().get(4); XWPFParagraph p = doc.getParagraphs().get(4);
XWPFNumbering numbering = doc.getNumbering(); XWPFNumbering numbering = doc.getNumbering();
CTNum ctNum = numbering.getNum(p.getNumID()).getCTNum(); CTNum ctNum = numbering.getNum(p.getNumID()).getCTNum();
assertEquals(9, ctNum.sizeOfLvlOverrideArray()); assertEquals(9, ctNum.sizeOfLvlOverrideArray());
CTNumLvl ctNumLvl = ctNum.getLvlOverrideArray(0); CTNumLvl ctNumLvl = ctNum.getLvlOverrideArray(0);
assertEquals("upperLetter", ctNumLvl.getLvl().getNumFmt().getVal().toString()); assertEquals("upperLetter", ctNumLvl.getLvl().getNumFmt().getVal().toString());
} }
} }

View File

@ -22,12 +22,26 @@ import java.math.BigInteger;
import java.util.List; import java.util.List;
import junit.framework.TestCase; import junit.framework.TestCase;
import org.apache.poi.xwpf.XWPFTestDataSamples; import org.apache.poi.xwpf.XWPFTestDataSamples;
import org.openxmlformats.schemas.drawingml.x2006.picture.CTPicture; import org.openxmlformats.schemas.drawingml.x2006.picture.CTPicture;
import org.openxmlformats.schemas.drawingml.x2006.picture.PicDocument; import org.openxmlformats.schemas.drawingml.x2006.picture.PicDocument;
import org.openxmlformats.schemas.drawingml.x2006.picture.impl.PicDocumentImpl; 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 * Tests for XWPF Paragraphs
@ -36,6 +50,7 @@ public final class TestXWPFParagraph extends TestCase {
/** /**
* Check that we get the right paragraph from the header * Check that we get the right paragraph from the header
*
* @throws IOException * @throws IOException
*/ */
public void disabled_testHeaderParagraph() throws IOException { public void disabled_testHeaderParagraph() throws IOException {
@ -44,7 +59,7 @@ public final class TestXWPFParagraph extends TestCase {
XWPFHeader hdr = xml.getHeaderFooterPolicy().getDefaultHeader(); XWPFHeader hdr = xml.getHeaderFooterPolicy().getDefaultHeader();
assertNotNull(hdr); assertNotNull(hdr);
List<XWPFParagraph> ps = hdr.getParagraphs(); List<XWPFParagraph> ps = hdr.getParagraphs();
assertEquals(1, ps.size()); assertEquals(1, ps.size());
XWPFParagraph p = ps.get(0); XWPFParagraph p = ps.get(0);
@ -55,6 +70,7 @@ public final class TestXWPFParagraph extends TestCase {
/** /**
* Check that we get the right paragraphs from the document * Check that we get the right paragraphs from the document
*
* @throws IOException * @throws IOException
*/ */
public void disabled_testDocumentParagraph() throws IOException { public void disabled_testDocumentParagraph() throws IOException {
@ -88,7 +104,7 @@ public final class TestXWPFParagraph extends TestCase {
assertEquals(STBorder.NONE.intValue(), p.getBorderTop().getValue()); assertEquals(STBorder.NONE.intValue(), p.getBorderTop().getValue());
CTP ctp = p.getCTP(); CTP ctp = p.getCTP();
CTPPr ppr = ctp.getPPr()== null? ctp.addNewPPr() : ctp.getPPr(); CTPPr ppr = ctp.getPPr() == null ? ctp.addNewPPr() : ctp.getPPr();
//bordi //bordi
CTPBdr bdr = ppr.addNewPBdr(); CTPBdr bdr = ppr.addNewPBdr();
@ -109,7 +125,7 @@ public final class TestXWPFParagraph extends TestCase {
assertEquals(STJc.LEFT.intValue(), p.getAlignment().getValue()); assertEquals(STJc.LEFT.intValue(), p.getAlignment().getValue());
CTP ctp = p.getCTP(); 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(); CTJc align = ppr.addNewJc();
align.setVal(STJc.CENTER); align.setVal(STJc.CENTER);
@ -125,7 +141,7 @@ public final class TestXWPFParagraph extends TestCase {
XWPFParagraph p = doc.createParagraph(); XWPFParagraph p = doc.createParagraph();
CTP ctp = p.getCTP(); 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()); assertEquals(-1, p.getSpacingAfter());
@ -142,7 +158,7 @@ public final class TestXWPFParagraph extends TestCase {
XWPFParagraph p = doc.createParagraph(); XWPFParagraph p = doc.createParagraph();
CTP ctp = p.getCTP(); CTP ctp = p.getCTP();
CTPPr ppr = ctp.getPPr()== null? ctp.addNewPPr() : ctp.getPPr(); CTPPr ppr = ctp.getPPr() == null ? ctp.addNewPPr() : ctp.getPPr();
assertEquals(STLineSpacingRule.INT_AUTO, p.getSpacingLineRule().getValue()); assertEquals(STLineSpacingRule.INT_AUTO, p.getSpacingLineRule().getValue());
@ -161,7 +177,7 @@ public final class TestXWPFParagraph extends TestCase {
assertEquals(-1, p.getIndentationLeft()); assertEquals(-1, p.getIndentationLeft());
CTP ctp = p.getCTP(); 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()); assertEquals(-1, p.getIndentationLeft());
@ -179,7 +195,7 @@ public final class TestXWPFParagraph extends TestCase {
XWPFParagraph p = doc.createParagraph(); XWPFParagraph p = doc.createParagraph();
CTP ctp = p.getCTP(); 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(); CTTextAlignment txtAlign = ppr.addNewTextAlignment();
txtAlign.setVal(STTextAlignment.CENTER); txtAlign.setVal(STTextAlignment.CENTER);
@ -194,7 +210,7 @@ public final class TestXWPFParagraph extends TestCase {
XWPFParagraph p = doc.createParagraph(); XWPFParagraph p = doc.createParagraph();
CTP ctp = p.getCTP(); 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(); CTOnOff wordWrap = ppr.addNewWordWrap();
wordWrap.setVal(STOnOff.FALSE); wordWrap.setVal(STOnOff.FALSE);
@ -210,7 +226,7 @@ public final class TestXWPFParagraph extends TestCase {
XWPFParagraph p = doc.createParagraph(); XWPFParagraph p = doc.createParagraph();
CTP ctp = p.getCTP(); 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(); CTOnOff pageBreak = ppr.addNewPageBreakBefore();
pageBreak.setVal(STOnOff.FALSE); pageBreak.setVal(STOnOff.FALSE);
@ -229,8 +245,8 @@ public final class TestXWPFParagraph extends TestCase {
assertEquals(0, paragraph.getCTP().sizeOfBookmarkEndArray()); assertEquals(0, paragraph.getCTP().sizeOfBookmarkEndArray());
CTBookmark ctBookmark = paragraph.getCTP().getBookmarkStartArray(0); CTBookmark ctBookmark = paragraph.getCTP().getBookmarkStartArray(0);
assertEquals("poi", ctBookmark.getName()); assertEquals("poi", ctBookmark.getName());
for(CTBookmark bookmark : paragraph.getCTP().getBookmarkStartArray()) { for (CTBookmark bookmark : paragraph.getCTP().getBookmarkStartArray()) {
assertEquals("poi", bookmark.getName()); assertEquals("poi", bookmark.getName());
} }
} }
@ -243,100 +259,100 @@ public final class TestXWPFParagraph extends TestCase {
} }
public void testAddingRuns() throws Exception { public void testAddingRuns() throws Exception {
XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("sample.docx"); XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("sample.docx");
XWPFParagraph p = doc.getParagraphs().get(0); XWPFParagraph p = doc.getParagraphs().get(0);
assertEquals(2, p.getRuns().size()); assertEquals(2, p.getRuns().size());
XWPFRun r = p.createRun(); XWPFRun r = p.createRun();
assertEquals(3, p.getRuns().size()); assertEquals(3, p.getRuns().size());
assertEquals(2, p.getRuns().indexOf(r)); assertEquals(2, p.getRuns().indexOf(r));
XWPFRun r2 = p.insertNewRun(1); XWPFRun r2 = p.insertNewRun(1);
assertEquals(4, p.getRuns().size()); assertEquals(4, p.getRuns().size());
assertEquals(1, p.getRuns().indexOf(r2)); assertEquals(1, p.getRuns().indexOf(r2));
assertEquals(3, p.getRuns().indexOf(r)); assertEquals(3, p.getRuns().indexOf(r));
} }
public void testPictures() throws Exception { public void testPictures() throws Exception {
XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("VariousPictures.docx"); XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("VariousPictures.docx");
assertEquals(7, doc.getParagraphs().size()); assertEquals(7, doc.getParagraphs().size());
XWPFParagraph p; XWPFParagraph p;
XWPFRun r; XWPFRun r;
// Text paragraphs // Text paragraphs
assertEquals("Sheet with various pictures", doc.getParagraphs().get(0).getText()); assertEquals("Sheet with various pictures", doc.getParagraphs().get(0).getText());
assertEquals("(jpeg, png, wmf, emf and pict) ", doc.getParagraphs().get(1).getText()); assertEquals("(jpeg, png, wmf, emf and pict) ", doc.getParagraphs().get(1).getText());
// Spacer ones // Spacer ones
assertEquals("", doc.getParagraphs().get(2).getText()); assertEquals("", doc.getParagraphs().get(2).getText());
assertEquals("", doc.getParagraphs().get(3).getText()); assertEquals("", doc.getParagraphs().get(3).getText());
assertEquals("", doc.getParagraphs().get(4).getText()); assertEquals("", doc.getParagraphs().get(4).getText());
// Image one // Image one
p = doc.getParagraphs().get(5); p = doc.getParagraphs().get(5);
assertEquals(6, p.getRuns().size()); assertEquals(6, p.getRuns().size());
r = p.getRuns().get(0); r = p.getRuns().get(0);
assertEquals("", r.toString()); assertEquals("", r.toString());
assertEquals(1, r.getEmbeddedPictures().size()); assertEquals(1, r.getEmbeddedPictures().size());
assertNotNull(r.getEmbeddedPictures().get(0).getPictureData()); assertNotNull(r.getEmbeddedPictures().get(0).getPictureData());
assertEquals("image1.wmf", r.getEmbeddedPictures().get(0).getPictureData().getFileName()); assertEquals("image1.wmf", r.getEmbeddedPictures().get(0).getPictureData().getFileName());
r = p.getRuns().get(1); r = p.getRuns().get(1);
assertEquals("", r.toString()); assertEquals("", r.toString());
assertEquals(1, r.getEmbeddedPictures().size()); assertEquals(1, r.getEmbeddedPictures().size());
assertNotNull(r.getEmbeddedPictures().get(0).getPictureData()); assertNotNull(r.getEmbeddedPictures().get(0).getPictureData());
assertEquals("image2.png", r.getEmbeddedPictures().get(0).getPictureData().getFileName()); assertEquals("image2.png", r.getEmbeddedPictures().get(0).getPictureData().getFileName());
r = p.getRuns().get(2); r = p.getRuns().get(2);
assertEquals("", r.toString()); assertEquals("", r.toString());
assertEquals(1, r.getEmbeddedPictures().size()); assertEquals(1, r.getEmbeddedPictures().size());
assertNotNull(r.getEmbeddedPictures().get(0).getPictureData()); assertNotNull(r.getEmbeddedPictures().get(0).getPictureData());
assertEquals("image3.emf", r.getEmbeddedPictures().get(0).getPictureData().getFileName()); assertEquals("image3.emf", r.getEmbeddedPictures().get(0).getPictureData().getFileName());
r = p.getRuns().get(3); r = p.getRuns().get(3);
assertEquals("", r.toString()); assertEquals("", r.toString());
assertEquals(1, r.getEmbeddedPictures().size()); assertEquals(1, r.getEmbeddedPictures().size());
assertNotNull(r.getEmbeddedPictures().get(0).getPictureData()); assertNotNull(r.getEmbeddedPictures().get(0).getPictureData());
assertEquals("image4.emf", r.getEmbeddedPictures().get(0).getPictureData().getFileName()); assertEquals("image4.emf", r.getEmbeddedPictures().get(0).getPictureData().getFileName());
r = p.getRuns().get(4); r = p.getRuns().get(4);
assertEquals("", r.toString()); assertEquals("", r.toString());
assertEquals(1, r.getEmbeddedPictures().size()); assertEquals(1, r.getEmbeddedPictures().size());
assertNotNull(r.getEmbeddedPictures().get(0).getPictureData()); assertNotNull(r.getEmbeddedPictures().get(0).getPictureData());
assertEquals("image5.jpeg", r.getEmbeddedPictures().get(0).getPictureData().getFileName()); assertEquals("image5.jpeg", r.getEmbeddedPictures().get(0).getPictureData().getFileName());
r = p.getRuns().get(5); r = p.getRuns().get(5);
assertEquals(" ", r.toString()); assertEquals(" ", r.toString());
assertEquals(0, r.getEmbeddedPictures().size()); assertEquals(0, r.getEmbeddedPictures().size());
// Final spacer // Final spacer
assertEquals("", doc.getParagraphs().get(6).getText()); assertEquals("", doc.getParagraphs().get(6).getText());
// Look in detail at one // Look in detail at one
r = p.getRuns().get(4); r = p.getRuns().get(4);
XWPFPicture pict = r.getEmbeddedPictures().get(0); XWPFPicture pict = r.getEmbeddedPictures().get(0);
CTPicture picture = pict.getCTPicture(); CTPicture picture = pict.getCTPicture();
assertEquals("rId8", picture.getBlipFill().getBlip().getEmbed()); assertEquals("rId8", picture.getBlipFill().getBlip().getEmbed());
// Ensure that the ooxml compiler finds everything we need // Ensure that the ooxml compiler finds everything we need
r.getCTR().getDrawingArray(0); r.getCTR().getDrawingArray(0);
r.getCTR().getDrawingArray(0).getInlineArray(0); r.getCTR().getDrawingArray(0).getInlineArray(0);
r.getCTR().getDrawingArray(0).getInlineArray(0).getGraphic(); r.getCTR().getDrawingArray(0).getInlineArray(0).getGraphic();
r.getCTR().getDrawingArray(0).getInlineArray(0).getGraphic().getGraphicData(); r.getCTR().getDrawingArray(0).getInlineArray(0).getGraphic().getGraphicData();
PicDocument pd = new PicDocumentImpl(null); PicDocument pd = new PicDocumentImpl(null);
assertTrue(pd.isNil()); assertTrue(pd.isNil());
} }
public void testTika792() throws Exception{ public void testTika792() throws Exception {
//This test forces the loading of CTMoveBookmark and //This test forces the loading of CTMoveBookmark and
//CTMoveBookmarkImpl into ooxml-lite. //CTMoveBookmarkImpl into ooxml-lite.
XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("Tika-792.docx"); XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("Tika-792.docx");
XWPFParagraph paragraph = doc.getParagraphs().get(0); XWPFParagraph paragraph = doc.getParagraphs().get(0);
assertEquals("s", paragraph.getText()); assertEquals("s", paragraph.getText());
} }
public void testSettersGetters() { public void testSettersGetters() {

View File

@ -23,7 +23,6 @@ import java.io.IOException;
import java.util.List; import java.util.List;
import junit.framework.TestCase; import junit.framework.TestCase;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException; import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.openxml4j.opc.PackageRelationship; import org.apache.poi.openxml4j.opc.PackageRelationship;
import org.apache.poi.xssf.usermodel.XSSFRelation; import org.apache.poi.xssf.usermodel.XSSFRelation;
@ -32,32 +31,29 @@ import org.apache.poi.xwpf.model.XWPFHeaderFooterPolicy;
public class TestXWPFPictureData extends TestCase { public class TestXWPFPictureData extends TestCase {
public void testRead() throws InvalidFormatException, IOException public void testRead() throws InvalidFormatException, IOException {
{
XWPFDocument sampleDoc = XWPFTestDataSamples.openSampleDocument("VariousPictures.docx"); XWPFDocument sampleDoc = XWPFTestDataSamples.openSampleDocument("VariousPictures.docx");
List<XWPFPictureData> pictures = sampleDoc.getAllPictures(); List<XWPFPictureData> pictures = sampleDoc.getAllPictures();
assertEquals(5,pictures.size()); assertEquals(5, pictures.size());
String[] ext = {"wmf","png","emf","emf","jpeg"}; String[] ext = {"wmf", "png", "emf", "emf", "jpeg"};
for (int i = 0 ; i < pictures.size() ; i++) for (int i = 0; i < pictures.size(); i++) {
{ assertEquals(ext[i], pictures.get(i).suggestFileExtension());
assertEquals(ext[i],pictures.get(i).suggestFileExtension());
} }
int num = pictures.size(); int num = pictures.size();
byte[] pictureData = XWPFTestDataSamples.getImage("nature1.jpg"); byte[] pictureData = XWPFTestDataSamples.getImage("nature1.jpg");
String relationId = sampleDoc.addPictureData(pictureData,XWPFDocument.PICTURE_TYPE_JPEG); String relationId = sampleDoc.addPictureData(pictureData, XWPFDocument.PICTURE_TYPE_JPEG);
// picture list was updated // picture list was updated
assertEquals(num + 1,pictures.size()); assertEquals(num + 1, pictures.size());
XWPFPictureData pict = (XWPFPictureData) sampleDoc.getRelationById(relationId); XWPFPictureData pict = (XWPFPictureData) sampleDoc.getRelationById(relationId);
assertEquals("jpeg",pict.suggestFileExtension()); assertEquals("jpeg", pict.suggestFileExtension());
assertArrayEquals(pictureData,pict.getData()); assertArrayEquals(pictureData, pict.getData());
} }
public void testPictureInHeader() throws IOException public void testPictureInHeader() throws IOException {
{
XWPFDocument sampleDoc = XWPFTestDataSamples.openSampleDocument("headerPic.docx"); XWPFDocument sampleDoc = XWPFTestDataSamples.openSampleDocument("headerPic.docx");
verifyOneHeaderPicture(sampleDoc); verifyOneHeaderPicture(sampleDoc);
@ -71,11 +67,10 @@ public class TestXWPFPictureData extends TestCase {
XWPFHeader header = policy.getDefaultHeader(); XWPFHeader header = policy.getDefaultHeader();
List<XWPFPictureData> pictures = header.getAllPictures(); List<XWPFPictureData> pictures = header.getAllPictures();
assertEquals(1,pictures.size()); assertEquals(1, pictures.size());
} }
public void testNew() throws InvalidFormatException, IOException public void testNew() throws InvalidFormatException, IOException {
{
XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("EmptyDocumentWithHeaderFooter.docx"); XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("EmptyDocumentWithHeaderFooter.docx");
byte[] jpegData = XWPFTestDataSamples.getImage("nature1.jpg"); byte[] jpegData = XWPFTestDataSamples.getImage("nature1.jpg");
assertNotNull(jpegData); assertNotNull(jpegData);
@ -85,52 +80,48 @@ public class TestXWPFPictureData extends TestCase {
assertNotNull(pngData); assertNotNull(pngData);
List<XWPFPictureData> pictures = doc.getAllPictures(); List<XWPFPictureData> pictures = doc.getAllPictures();
assertEquals(0,pictures.size()); assertEquals(0, pictures.size());
// Document shouldn't have any image relationships // Document shouldn't have any image relationships
assertEquals(13,doc.getPackagePart().getRelationships().size()); assertEquals(13, doc.getPackagePart().getRelationships().size());
for (PackageRelationship rel : doc.getPackagePart().getRelationships()) for (PackageRelationship rel : doc.getPackagePart().getRelationships()) {
{ if (rel.getRelationshipType().equals(XSSFRelation.IMAGE_JPEG.getRelation())) {
if (rel.getRelationshipType().equals(XSSFRelation.IMAGE_JPEG.getRelation()))
{
fail("Shouldn't have JPEG yet"); fail("Shouldn't have JPEG yet");
} }
} }
// Add the image // Add the image
String relationId = doc.addPictureData(jpegData,XWPFDocument.PICTURE_TYPE_JPEG); String relationId = doc.addPictureData(jpegData, XWPFDocument.PICTURE_TYPE_JPEG);
assertEquals(1,pictures.size()); assertEquals(1, pictures.size());
XWPFPictureData jpgPicData = (XWPFPictureData) doc.getRelationById(relationId); XWPFPictureData jpgPicData = (XWPFPictureData) doc.getRelationById(relationId);
assertEquals("jpeg",jpgPicData.suggestFileExtension()); assertEquals("jpeg", jpgPicData.suggestFileExtension());
assertArrayEquals(jpegData,jpgPicData.getData()); assertArrayEquals(jpegData, jpgPicData.getData());
// Ensure it now has one // Ensure it now has one
assertEquals(14,doc.getPackagePart().getRelationships().size()); assertEquals(14, doc.getPackagePart().getRelationships().size());
PackageRelationship jpegRel = null; PackageRelationship jpegRel = null;
for (PackageRelationship rel : doc.getPackagePart().getRelationships()) for (PackageRelationship rel : doc.getPackagePart().getRelationships()) {
{ if (rel.getRelationshipType().equals(XWPFRelation.IMAGE_JPEG.getRelation())) {
if (rel.getRelationshipType().equals(XWPFRelation.IMAGE_JPEG.getRelation()))
{
if (jpegRel != null) if (jpegRel != null)
fail("Found 2 jpegs!"); fail("Found 2 jpegs!");
jpegRel = rel; jpegRel = rel;
} }
} }
assertNotNull("JPEG Relationship not found",jpegRel); assertNotNull("JPEG Relationship not found", jpegRel);
// Check the details // Check the details
assertNotNull(jpegRel); assertNotNull(jpegRel);
assertEquals(XWPFRelation.IMAGE_JPEG.getRelation(),jpegRel.getRelationshipType()); assertEquals(XWPFRelation.IMAGE_JPEG.getRelation(), jpegRel.getRelationshipType());
assertEquals("/word/document.xml",jpegRel.getSource().getPartName().toString()); assertEquals("/word/document.xml", jpegRel.getSource().getPartName().toString());
assertEquals("/word/media/image1.jpeg",jpegRel.getTargetURI().getPath()); assertEquals("/word/media/image1.jpeg", jpegRel.getTargetURI().getPath());
XWPFPictureData pictureDataByID = doc.getPictureDataByID(jpegRel.getId()); XWPFPictureData pictureDataByID = doc.getPictureDataByID(jpegRel.getId());
assertArrayEquals(jpegData, pictureDataByID.getData()); assertArrayEquals(jpegData, pictureDataByID.getData());
// Save an re-load, check it appears // Save an re-load, check it appears
doc = XWPFTestDataSamples.writeOutAndReadBack(doc); doc = XWPFTestDataSamples.writeOutAndReadBack(doc);
assertEquals(1,doc.getAllPictures().size()); assertEquals(1, doc.getAllPictures().size());
assertEquals(1,doc.getAllPackagePictures().size()); assertEquals(1, doc.getAllPackagePictures().size());
// verify the picture that we read back in // verify the picture that we read back in
pictureDataByID = doc.getPictureDataByID(jpegRel.getId()); pictureDataByID = doc.getPictureDataByID(jpegRel.getId());
@ -148,7 +139,7 @@ public class TestXWPFPictureData extends TestCase {
if (paragraph.getDocument() != null) { if (paragraph.getDocument() != null) {
//System.out.println(picture.getCTPicture()); //System.out.println(picture.getCTPicture());
XWPFPictureData data = picture.getPictureData(); XWPFPictureData data = picture.getPictureData();
if(data != null) System.out.println(data.getFileName()); if (data != null) System.out.println(data.getFileName());
} }
} }
} }

View File

@ -23,7 +23,6 @@ import java.util.Iterator;
import java.util.List; import java.util.List;
import junit.framework.TestCase; import junit.framework.TestCase;
import org.apache.poi.xwpf.XWPFTestDataSamples; import org.apache.poi.xwpf.XWPFTestDataSamples;
import org.apache.poi.xwpf.model.XWPFHeaderFooterPolicy; import org.apache.poi.xwpf.model.XWPFHeaderFooterPolicy;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTBr; import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTBr;
@ -53,13 +52,13 @@ public class TestXWPFRun extends TestCase {
ctRun.addNewT().setStringValue("TEST2 STRING"); ctRun.addNewT().setStringValue("TEST2 STRING");
ctRun.addNewT().setStringValue("TEST3 STRING"); ctRun.addNewT().setStringValue("TEST3 STRING");
assertEquals(3,ctRun.sizeOfTArray()); assertEquals(3, ctRun.sizeOfTArray());
XWPFRun run = new XWPFRun(ctRun, p); XWPFRun run = new XWPFRun(ctRun, p);
assertEquals("TEST2 STRING",run.getText(1)); assertEquals("TEST2 STRING", run.getText(1));
run.setText("NEW STRING",0); run.setText("NEW STRING", 0);
assertEquals("NEW STRING",run.getText(0)); assertEquals("NEW STRING", run.getText(0));
//run.setText("xxx",14); //run.setText("xxx",14);
//fail("Position wrong"); //fail("Position wrong");
@ -210,7 +209,7 @@ public class TestXWPFRun extends TestCase {
ctRun.addNewT().setStringValue("TEST STRING"); ctRun.addNewT().setStringValue("TEST STRING");
ctRun.addNewBr(); ctRun.addNewBr();
ctRun.addNewT().setStringValue("TEST2 STRING"); ctRun.addNewT().setStringValue("TEST2 STRING");
CTBr breac=ctRun.addNewBr(); CTBr breac = ctRun.addNewBr();
breac.setClear(STBrClear.LEFT); breac.setClear(STBrClear.LEFT);
ctRun.addNewT().setStringValue("TEST3 STRING"); ctRun.addNewT().setStringValue("TEST3 STRING");
assertEquals(2, ctRun.sizeOfBrArray()); assertEquals(2, ctRun.sizeOfBrArray());
@ -225,138 +224,139 @@ public class TestXWPFRun extends TestCase {
/** /**
* Test that on an existing document, we do the * Test that on an existing document, we do the
* right thing with it * right thing with it
*
* @throws IOException * @throws IOException
*/ */
public void testExisting() throws IOException { public void testExisting() throws IOException {
XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("TestDocument.docx"); XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("TestDocument.docx");
XWPFParagraph p; XWPFParagraph p;
XWPFRun run; XWPFRun run;
// First paragraph is simple // First paragraph is simple
p = doc.getParagraphArray(0); p = doc.getParagraphArray(0);
assertEquals("This is a test document.", p.getText()); assertEquals("This is a test document.", p.getText());
assertEquals(2, p.getRuns().size()); assertEquals(2, p.getRuns().size());
run = p.getRuns().get(0); run = p.getRuns().get(0);
assertEquals("This is a test document", run.toString()); assertEquals("This is a test document", run.toString());
assertEquals(false, run.isBold()); assertEquals(false, run.isBold());
assertEquals(false, run.isItalic()); assertEquals(false, run.isItalic());
assertEquals(false, run.isStrike()); assertEquals(false, run.isStrike());
assertEquals(null, run.getCTR().getRPr()); assertEquals(null, run.getCTR().getRPr());
run = p.getRuns().get(1); run = p.getRuns().get(1);
assertEquals(".", run.toString()); assertEquals(".", run.toString());
assertEquals(false, run.isBold()); assertEquals(false, run.isBold());
assertEquals(false, run.isItalic()); assertEquals(false, run.isItalic());
assertEquals(false, run.isStrike()); assertEquals(false, run.isStrike());
assertEquals(null, run.getCTR().getRPr()); assertEquals(null, run.getCTR().getRPr());
// Next paragraph is all in one style, but a different one // Next paragraph is all in one style, but a different one
p = doc.getParagraphArray(1); p = doc.getParagraphArray(1);
assertEquals("This bit is in bold and italic", p.getText()); assertEquals("This bit is in bold and italic", p.getText());
assertEquals(1, p.getRuns().size()); assertEquals(1, p.getRuns().size());
run = p.getRuns().get(0); run = p.getRuns().get(0);
assertEquals("This bit is in bold and italic", run.toString()); assertEquals("This bit is in bold and italic", run.toString());
assertEquals(true, run.isBold()); assertEquals(true, run.isBold());
assertEquals(true, run.isItalic()); assertEquals(true, run.isItalic());
assertEquals(false, run.isStrike()); assertEquals(false, run.isStrike());
assertEquals(true, run.getCTR().getRPr().isSetB()); assertEquals(true, run.getCTR().getRPr().isSetB());
assertEquals(false, run.getCTR().getRPr().getB().isSetVal()); assertEquals(false, run.getCTR().getRPr().getB().isSetVal());
// Back to normal // Back to normal
p = doc.getParagraphArray(2); p = doc.getParagraphArray(2);
assertEquals("Back to normal", p.getText()); assertEquals("Back to normal", p.getText());
assertEquals(1, p.getRuns().size()); assertEquals(1, p.getRuns().size());
run = p.getRuns().get(0); run = p.getRuns().get(0);
assertEquals("Back to normal", run.toString()); assertEquals("Back to normal", run.toString());
assertEquals(false, run.isBold()); assertEquals(false, run.isBold());
assertEquals(false, run.isItalic()); assertEquals(false, run.isItalic());
assertEquals(false, run.isStrike()); assertEquals(false, run.isStrike());
assertEquals(null, run.getCTR().getRPr()); assertEquals(null, run.getCTR().getRPr());
// Different styles in one paragraph // Different styles in one paragraph
p = doc.getParagraphArray(3); p = doc.getParagraphArray(3);
assertEquals("This contains BOLD, ITALIC and BOTH, as well as RED and YELLOW text.", p.getText()); assertEquals("This contains BOLD, ITALIC and BOTH, as well as RED and YELLOW text.", p.getText());
assertEquals(11, p.getRuns().size()); assertEquals(11, p.getRuns().size());
run = p.getRuns().get(0); run = p.getRuns().get(0);
assertEquals("This contains ", run.toString()); assertEquals("This contains ", run.toString());
assertEquals(false, run.isBold()); assertEquals(false, run.isBold());
assertEquals(false, run.isItalic()); assertEquals(false, run.isItalic());
assertEquals(false, run.isStrike()); assertEquals(false, run.isStrike());
assertEquals(null, run.getCTR().getRPr()); assertEquals(null, run.getCTR().getRPr());
run = p.getRuns().get(1); run = p.getRuns().get(1);
assertEquals("BOLD", run.toString()); assertEquals("BOLD", run.toString());
assertEquals(true, run.isBold()); assertEquals(true, run.isBold());
assertEquals(false, run.isItalic()); assertEquals(false, run.isItalic());
assertEquals(false, run.isStrike()); assertEquals(false, run.isStrike());
run = p.getRuns().get(2); run = p.getRuns().get(2);
assertEquals(", ", run.toString()); assertEquals(", ", run.toString());
assertEquals(false, run.isBold()); assertEquals(false, run.isBold());
assertEquals(false, run.isItalic()); assertEquals(false, run.isItalic());
assertEquals(false, run.isStrike()); assertEquals(false, run.isStrike());
assertEquals(null, run.getCTR().getRPr()); assertEquals(null, run.getCTR().getRPr());
run = p.getRuns().get(3); run = p.getRuns().get(3);
assertEquals("ITALIC", run.toString()); assertEquals("ITALIC", run.toString());
assertEquals(false, run.isBold()); assertEquals(false, run.isBold());
assertEquals(true, run.isItalic()); assertEquals(true, run.isItalic());
assertEquals(false, run.isStrike()); assertEquals(false, run.isStrike());
run = p.getRuns().get(4); run = p.getRuns().get(4);
assertEquals(" and ", run.toString()); assertEquals(" and ", run.toString());
assertEquals(false, run.isBold()); assertEquals(false, run.isBold());
assertEquals(false, run.isItalic()); assertEquals(false, run.isItalic());
assertEquals(false, run.isStrike()); assertEquals(false, run.isStrike());
assertEquals(null, run.getCTR().getRPr()); assertEquals(null, run.getCTR().getRPr());
run = p.getRuns().get(5); run = p.getRuns().get(5);
assertEquals("BOTH", run.toString()); assertEquals("BOTH", run.toString());
assertEquals(true, run.isBold()); assertEquals(true, run.isBold());
assertEquals(true, run.isItalic()); assertEquals(true, run.isItalic());
assertEquals(false, run.isStrike()); assertEquals(false, run.isStrike());
run = p.getRuns().get(6); run = p.getRuns().get(6);
assertEquals(", as well as ", run.toString()); assertEquals(", as well as ", run.toString());
assertEquals(false, run.isBold()); assertEquals(false, run.isBold());
assertEquals(false, run.isItalic()); assertEquals(false, run.isItalic());
assertEquals(false, run.isStrike()); assertEquals(false, run.isStrike());
assertEquals(null, run.getCTR().getRPr()); assertEquals(null, run.getCTR().getRPr());
run = p.getRuns().get(7); run = p.getRuns().get(7);
assertEquals("RED", run.toString()); assertEquals("RED", run.toString());
assertEquals(false, run.isBold()); assertEquals(false, run.isBold());
assertEquals(false, run.isItalic()); assertEquals(false, run.isItalic());
assertEquals(false, run.isStrike()); assertEquals(false, run.isStrike());
run = p.getRuns().get(8); run = p.getRuns().get(8);
assertEquals(" and ", run.toString()); assertEquals(" and ", run.toString());
assertEquals(false, run.isBold()); assertEquals(false, run.isBold());
assertEquals(false, run.isItalic()); assertEquals(false, run.isItalic());
assertEquals(false, run.isStrike()); assertEquals(false, run.isStrike());
assertEquals(null, run.getCTR().getRPr()); assertEquals(null, run.getCTR().getRPr());
run = p.getRuns().get(9); run = p.getRuns().get(9);
assertEquals("YELLOW", run.toString()); assertEquals("YELLOW", run.toString());
assertEquals(false, run.isBold()); assertEquals(false, run.isBold());
assertEquals(false, run.isItalic()); assertEquals(false, run.isItalic());
assertEquals(false, run.isStrike()); assertEquals(false, run.isStrike());
run = p.getRuns().get(10); run = p.getRuns().get(10);
assertEquals(" text.", run.toString()); assertEquals(" text.", run.toString());
assertEquals(false, run.isBold()); assertEquals(false, run.isBold());
assertEquals(false, run.isItalic()); assertEquals(false, run.isItalic());
assertEquals(false, run.isStrike()); assertEquals(false, run.isStrike());
assertEquals(null, run.getCTR().getRPr()); assertEquals(null, run.getCTR().getRPr());
} }
public void testPictureInHeader() throws IOException { public void testPictureInHeader() throws IOException {
@ -376,7 +376,7 @@ public class TestXWPFRun extends TestCase {
assertEquals("DOZOR", pic.getDescription()); assertEquals("DOZOR", pic.getDescription());
} }
count+= pictures.size(); count += pictures.size();
} }
} }
@ -384,36 +384,36 @@ public class TestXWPFRun extends TestCase {
} }
public void testAddPicture() throws Exception { public void testAddPicture() throws Exception {
XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("TestDocument.docx"); XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("TestDocument.docx");
XWPFParagraph p = doc.getParagraphArray(2); XWPFParagraph p = doc.getParagraphArray(2);
XWPFRun r = p.getRuns().get(0); XWPFRun r = p.getRuns().get(0);
assertEquals(0, doc.getAllPictures().size()); assertEquals(0, doc.getAllPictures().size());
assertEquals(0, r.getEmbeddedPictures().size()); assertEquals(0, r.getEmbeddedPictures().size());
r.addPicture(new ByteArrayInputStream(new byte[0]), Document.PICTURE_TYPE_JPEG, "test.jpg", 21, 32); r.addPicture(new ByteArrayInputStream(new byte[0]), Document.PICTURE_TYPE_JPEG, "test.jpg", 21, 32);
assertEquals(1, doc.getAllPictures().size()); assertEquals(1, doc.getAllPictures().size());
assertEquals(1, r.getEmbeddedPictures().size()); assertEquals(1, r.getEmbeddedPictures().size());
} }
/** /**
* Bugzilla #52288 - setting the font family on the * Bugzilla #52288 - setting the font family on the
* run mustn't NPE * run mustn't NPE
*/ */
public void testSetFontFamily_52288() throws Exception { public void testSetFontFamily_52288() throws Exception {
XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("52288.docx"); XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("52288.docx");
final Iterator<XWPFParagraph> paragraphs = doc.getParagraphsIterator(); final Iterator<XWPFParagraph> paragraphs = doc.getParagraphsIterator();
while (paragraphs.hasNext()) { while (paragraphs.hasNext()) {
final XWPFParagraph paragraph = paragraphs.next(); final XWPFParagraph paragraph = paragraphs.next();
for (final XWPFRun run : paragraph.getRuns()) { for (final XWPFRun run : paragraph.getRuns()) {
if (run != null) { if (run != null) {
final String text = run.getText(0); final String text = run.getText(0);
if (text != null) { if (text != null) {
run.setFontFamily("Times New Roman"); run.setFontFamily("Times New Roman");
}
} }
} }
} }
}
} }
} }

View File

@ -18,28 +18,26 @@
package org.apache.poi.xwpf.usermodel; package org.apache.poi.xwpf.usermodel;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.HashSet;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Set;
import junit.framework.TestCase; import junit.framework.TestCase;
import org.apache.poi.xwpf.XWPFTestDataSamples; import org.apache.poi.xwpf.XWPFTestDataSamples;
public final class TestXWPFSDT extends TestCase { public final class TestXWPFSDT extends TestCase {
/** /**
* Test simple tag and title extraction from SDT * Test simple tag and title extraction from SDT
*
* @throws Exception * @throws Exception
*/ */
public void testTagTitle() throws Exception { public void testTagTitle() throws Exception {
XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("Bug54849.docx"); XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("Bug54849.docx");
String tag = null; String tag = null;
String title= null; String title = null;
List<AbstractXWPFSDT> sdts = extractAllSDTs(doc); List<AbstractXWPFSDT> sdts = extractAllSDTs(doc);
for (AbstractXWPFSDT sdt :sdts){ for (AbstractXWPFSDT sdt : sdts) {
if (sdt.getContent().toString().equals("Rich_text")){ if (sdt.getContent().toString().equals("Rich_text")) {
tag = "MyTag"; tag = "MyTag";
title = "MyTitle"; title = "MyTitle";
break; break;
@ -53,7 +51,7 @@ public final class TestXWPFSDT extends TestCase {
} }
public void testGetSDTs() throws Exception{ public void testGetSDTs() throws Exception {
String[] contents = new String[]{ String[] contents = new String[]{
"header_rich_text", "header_rich_text",
"Rich_text", "Rich_text",
@ -75,11 +73,12 @@ public final class TestXWPFSDT extends TestCase {
assertEquals("number of sdts", contents.length, sdts.size()); assertEquals("number of sdts", contents.length, sdts.size());
for (int i = 0; i < contents.length; i++){ for (int i = 0; i < contents.length; i++) {
AbstractXWPFSDT sdt = sdts.get(i); AbstractXWPFSDT sdt = sdts.get(i);
assertEquals(i+ ": " + contents[i], contents[i], sdt.getContent().toString()); assertEquals(i + ": " + contents[i], contents[i], sdt.getContent().toString());
} }
} }
/** /**
* POI-54771 and TIKA-1317 * POI-54771 and TIKA-1317
*/ */
@ -110,69 +109,69 @@ public final class TestXWPFSDT extends TestCase {
/** /**
* POI-55142 and Tika 1130 * POI-55142 and Tika 1130
*/ */
public void testNewLinesBetweenRuns() throws Exception{ public void testNewLinesBetweenRuns() throws Exception {
XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("Bug55142.docx"); XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("Bug55142.docx");
List<AbstractXWPFSDT> sdts = extractAllSDTs(doc); List<AbstractXWPFSDT> sdts = extractAllSDTs(doc);
List<String> targs = new ArrayList<String>(); List<String> targs = new ArrayList<String>();
//these test newlines and tabs in paragraphs/body elements //these test newlines and tabs in paragraphs/body elements
targs.add("Rich-text1 abcdefghi"); targs.add("Rich-text1 abcdefghi");
targs.add("Rich-text2 abcd\t\tefgh"); targs.add("Rich-text2 abcd\t\tefgh");
targs.add("Rich-text3 abcd\nefg"); targs.add("Rich-text3 abcd\nefg");
targs.add("Rich-text4 abcdefg"); targs.add("Rich-text4 abcdefg");
targs.add("Rich-text5 abcdefg\nhijk"); targs.add("Rich-text5 abcdefg\nhijk");
targs.add("Plain-text1 abcdefg"); targs.add("Plain-text1 abcdefg");
targs.add("Plain-text2 abcdefg\nhijk\nlmnop"); targs.add("Plain-text2 abcdefg\nhijk\nlmnop");
//this tests consecutive runs within a cell (not a paragraph) //this tests consecutive runs within a cell (not a paragraph)
//this test case was triggered by Tika-1130 //this test case was triggered by Tika-1130
targs.add("sdt_incell2 abcdefg"); targs.add("sdt_incell2 abcdefg");
for (int i = 0; i < sdts.size(); i++){ for (int i = 0; i < sdts.size(); i++) {
AbstractXWPFSDT sdt = sdts.get(i); AbstractXWPFSDT sdt = sdts.get(i);
assertEquals(targs.get(i), targs.get(i), sdt.getContent().getText()); assertEquals(targs.get(i), targs.get(i), sdt.getContent().getText());
} }
} }
private List<AbstractXWPFSDT> extractAllSDTs(XWPFDocument doc){ private List<AbstractXWPFSDT> extractAllSDTs(XWPFDocument doc) {
List<AbstractXWPFSDT> sdts = new ArrayList<AbstractXWPFSDT>(); List<AbstractXWPFSDT> sdts = new ArrayList<AbstractXWPFSDT>();
List<XWPFHeader> headers = doc.getHeaderList(); List<XWPFHeader> headers = doc.getHeaderList();
for (XWPFHeader header : headers){ for (XWPFHeader header : headers) {
sdts.addAll(extractSDTsFromBodyElements(header.getBodyElements())); sdts.addAll(extractSDTsFromBodyElements(header.getBodyElements()));
} }
sdts.addAll(extractSDTsFromBodyElements(doc.getBodyElements())); sdts.addAll(extractSDTsFromBodyElements(doc.getBodyElements()));
List<XWPFFooter> footers = doc.getFooterList(); List<XWPFFooter> footers = doc.getFooterList();
for (XWPFFooter footer : footers){ for (XWPFFooter footer : footers) {
sdts.addAll(extractSDTsFromBodyElements(footer.getBodyElements())); sdts.addAll(extractSDTsFromBodyElements(footer.getBodyElements()));
} }
for (XWPFFootnote footnote : doc.getFootnotes()){ for (XWPFFootnote footnote : doc.getFootnotes()) {
sdts.addAll(extractSDTsFromBodyElements(footnote.getBodyElements())); sdts.addAll(extractSDTsFromBodyElements(footnote.getBodyElements()));
} }
for (Map.Entry<Integer, XWPFFootnote> e : doc.endnotes.entrySet()){ for (Map.Entry<Integer, XWPFFootnote> e : doc.endnotes.entrySet()) {
sdts.addAll(extractSDTsFromBodyElements(e.getValue().getBodyElements())); sdts.addAll(extractSDTsFromBodyElements(e.getValue().getBodyElements()));
} }
return sdts; return sdts;
} }
private List<AbstractXWPFSDT> extractSDTsFromBodyElements(List<IBodyElement> elements){ private List<AbstractXWPFSDT> extractSDTsFromBodyElements(List<IBodyElement> elements) {
List<AbstractXWPFSDT> sdts = new ArrayList<AbstractXWPFSDT>(); List<AbstractXWPFSDT> sdts = new ArrayList<AbstractXWPFSDT>();
for (IBodyElement e : elements){ for (IBodyElement e : elements) {
if (e instanceof XWPFSDT){ if (e instanceof XWPFSDT) {
XWPFSDT sdt = (XWPFSDT)e; XWPFSDT sdt = (XWPFSDT) e;
sdts.add(sdt); sdts.add(sdt);
} else if (e instanceof XWPFParagraph){ } else if (e instanceof XWPFParagraph) {
XWPFParagraph p = (XWPFParagraph)e; XWPFParagraph p = (XWPFParagraph) e;
for (IRunElement e2 : p.getIRuns()){ for (IRunElement e2 : p.getIRuns()) {
if (e2 instanceof XWPFSDT){ if (e2 instanceof XWPFSDT) {
XWPFSDT sdt = (XWPFSDT)e2; XWPFSDT sdt = (XWPFSDT) e2;
sdts.add(sdt); sdts.add(sdt);
} }
} }
} else if (e instanceof XWPFTable){ } else if (e instanceof XWPFTable) {
XWPFTable table = (XWPFTable)e; XWPFTable table = (XWPFTable) e;
sdts.addAll(extractSDTsFromTable(table)); sdts.addAll(extractSDTsFromTable(table));
} }
} }
@ -185,9 +184,9 @@ public final class TestXWPFSDT extends TestCase {
for (XWPFTableRow r : table.getRows()) { for (XWPFTableRow r : table.getRows()) {
for (ICell c : r.getTableICells()) { for (ICell c : r.getTableICells()) {
if (c instanceof XWPFSDTCell) { if (c instanceof XWPFSDTCell) {
sdts.add((XWPFSDTCell)c); sdts.add((XWPFSDTCell) c);
} else if (c instanceof XWPFTableCell) { } else if (c instanceof XWPFTableCell) {
sdts.addAll(extractSDTsFromBodyElements(((XWPFTableCell)c).getBodyElements())); sdts.addAll(extractSDTsFromBodyElements(((XWPFTableCell) c).getBodyElements()));
} }
} }
} }

View File

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

View File

@ -22,7 +22,6 @@ import java.util.ArrayList;
import java.util.List; import java.util.List;
import junit.framework.TestCase; import junit.framework.TestCase;
import org.apache.poi.xwpf.XWPFTestDataSamples; import org.apache.poi.xwpf.XWPFTestDataSamples;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTFonts; import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTFonts;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTLatentStyles; import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTLatentStyles;
@ -37,62 +36,62 @@ public class TestXWPFStyles extends TestCase {
// super.setUp(); // super.setUp();
// } // }
public void testGetUsedStyles() throws IOException{ public void testGetUsedStyles() throws IOException {
XWPFDocument sampleDoc = XWPFTestDataSamples.openSampleDocument("Styles.docx"); XWPFDocument sampleDoc = XWPFTestDataSamples.openSampleDocument("Styles.docx");
List<XWPFStyle> testUsedStyleList = new ArrayList<XWPFStyle>(); List<XWPFStyle> testUsedStyleList = new ArrayList<XWPFStyle>();
XWPFStyles styles = sampleDoc.getStyles(); XWPFStyles styles = sampleDoc.getStyles();
XWPFStyle style = styles.getStyle("berschrift1"); XWPFStyle style = styles.getStyle("berschrift1");
testUsedStyleList.add(style); testUsedStyleList.add(style);
testUsedStyleList.add(styles.getStyle("Standard")); testUsedStyleList.add(styles.getStyle("Standard"));
testUsedStyleList.add(styles.getStyle("berschrift1Zchn")); testUsedStyleList.add(styles.getStyle("berschrift1Zchn"));
testUsedStyleList.add(styles.getStyle("Absatz-Standardschriftart")); testUsedStyleList.add(styles.getStyle("Absatz-Standardschriftart"));
style.hasSameName(style); style.hasSameName(style);
List<XWPFStyle> usedStyleList = styles.getUsedStyleList(style); List<XWPFStyle> usedStyleList = styles.getUsedStyleList(style);
assertEquals(usedStyleList, testUsedStyleList); assertEquals(usedStyleList, testUsedStyleList);
} }
public void testAddStylesToDocument() throws IOException{ public void testAddStylesToDocument() throws IOException {
XWPFDocument docOut = new XWPFDocument(); XWPFDocument docOut = new XWPFDocument();
XWPFStyles styles = docOut.createStyles(); XWPFStyles styles = docOut.createStyles();
String strStyleId = "headline1"; String strStyleId = "headline1";
CTStyle ctStyle = CTStyle.Factory.newInstance(); CTStyle ctStyle = CTStyle.Factory.newInstance();
ctStyle.setStyleId(strStyleId); ctStyle.setStyleId(strStyleId);
XWPFStyle s = new XWPFStyle(ctStyle); XWPFStyle s = new XWPFStyle(ctStyle);
styles.addStyle(s); styles.addStyle(s);
assertTrue(styles.styleExist(strStyleId)); assertTrue(styles.styleExist(strStyleId));
XWPFDocument docIn = XWPFTestDataSamples.writeOutAndReadBack(docOut); XWPFDocument docIn = XWPFTestDataSamples.writeOutAndReadBack(docOut);
styles = docIn.getStyles(); styles = docIn.getStyles();
assertTrue(styles.styleExist(strStyleId)); assertTrue(styles.styleExist(strStyleId));
} }
/** /**
* Bug #52449 - We should be able to write a file containing * Bug #52449 - We should be able to write a file containing
* both regular and glossary styles without error * both regular and glossary styles without error
*/ */
public void test52449() throws Exception { public void test52449() throws Exception {
XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("52449.docx"); XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("52449.docx");
XWPFStyles styles = doc.getStyles(); XWPFStyles styles = doc.getStyles();
assertNotNull(styles); assertNotNull(styles);
XWPFDocument docIn = XWPFTestDataSamples.writeOutAndReadBack(doc); XWPFDocument docIn = XWPFTestDataSamples.writeOutAndReadBack(doc);
styles = docIn.getStyles(); styles = docIn.getStyles();
assertNotNull(styles); assertNotNull(styles);
} }
/** /**
* YK: tests below don't make much sense, * YK: tests below don't make much sense,
* they exist only to copy xml beans to pi-ooxml-schemas.jar * they exist only to copy xml beans to pi-ooxml-schemas.jar
*/ */
public void testLanguages(){ public void testLanguages() {
XWPFDocument docOut = new XWPFDocument(); XWPFDocument docOut = new XWPFDocument();
XWPFStyles styles = docOut.createStyles(); XWPFStyles styles = docOut.createStyles();
styles.setEastAsia("Chinese"); styles.setEastAsia("Chinese");
@ -148,7 +147,7 @@ public class TestXWPFStyles extends TestCase {
assertEquals(7, doc.getParagraphs().size()); assertEquals(7, doc.getParagraphs().size());
// Check the first three have no run styles, just default paragraph style // Check the first three have no run styles, just default paragraph style
for (int i=0; i<3; i++) { for (int i = 0; i < 3; i++) {
XWPFParagraph p = doc.getParagraphs().get(i); XWPFParagraph p = doc.getParagraphs().get(i);
assertEquals(null, p.getStyle()); assertEquals(null, p.getStyle());
assertEquals(null, p.getStyleID()); assertEquals(null, p.getStyleID());
@ -163,7 +162,7 @@ public class TestXWPFStyles extends TestCase {
// On page two, has explicit styles, but on runs not on // On page two, has explicit styles, but on runs not on
// the paragraph itself // the paragraph itself
for (int i=4; i<7; i++) { for (int i = 4; i < 7; i++) {
XWPFParagraph p = doc.getParagraphs().get(i); XWPFParagraph p = doc.getParagraphs().get(i);
assertEquals(null, p.getStyle()); assertEquals(null, p.getStyle());
assertEquals(null, p.getStyleID()); assertEquals(null, p.getStyleID());

View File

@ -20,7 +20,6 @@ import java.math.BigInteger;
import java.util.List; import java.util.List;
import junit.framework.TestCase; import junit.framework.TestCase;
import org.apache.poi.xwpf.XWPFTestDataSamples; import org.apache.poi.xwpf.XWPFTestDataSamples;
import org.apache.poi.xwpf.usermodel.XWPFTable.XWPFBorderType; import org.apache.poi.xwpf.usermodel.XWPFTable.XWPFBorderType;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTP; import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTP;
@ -149,14 +148,14 @@ public class TestXWPFTable extends TestCase {
} }
public void testSetGetMargins() { public void testSetGetMargins() {
// instantiate the following class so it'll get picked up by // instantiate the following class so it'll get picked up by
// the XmlBean process and added to the jar file. it's required // the XmlBean process and added to the jar file. it's required
// for the following XWPFTable methods. // for the following XWPFTable methods.
CTTblCellMar ctm = CTTblCellMar.Factory.newInstance(); CTTblCellMar ctm = CTTblCellMar.Factory.newInstance();
assertNotNull(ctm); assertNotNull(ctm);
// create a table // create a table
XWPFDocument doc = new XWPFDocument(); XWPFDocument doc = new XWPFDocument();
CTTbl ctTable = CTTbl.Factory.newInstance(); CTTbl ctTable = CTTbl.Factory.newInstance();
XWPFTable table = new XWPFTable(ctTable, doc); XWPFTable table = new XWPFTable(ctTable, doc);
// set margins // set margins
table.setCellMargins(50, 50, 250, 450); table.setCellMargins(50, 50, 250, 450);
@ -172,16 +171,16 @@ public class TestXWPFTable extends TestCase {
} }
public void testSetGetHBorders() { public void testSetGetHBorders() {
// instantiate the following classes so they'll get picked up by // instantiate the following classes so they'll get picked up by
// the XmlBean process and added to the jar file. they are required // the XmlBean process and added to the jar file. they are required
// for the following XWPFTable methods. // for the following XWPFTable methods.
CTTblBorders cttb = CTTblBorders.Factory.newInstance(); CTTblBorders cttb = CTTblBorders.Factory.newInstance();
assertNotNull(cttb); assertNotNull(cttb);
STBorder stb = STBorder.Factory.newInstance(); STBorder stb = STBorder.Factory.newInstance();
assertNotNull(stb); assertNotNull(stb);
// create a table // create a table
XWPFDocument doc = new XWPFDocument(); XWPFDocument doc = new XWPFDocument();
CTTbl ctTable = CTTbl.Factory.newInstance(); CTTbl ctTable = CTTbl.Factory.newInstance();
XWPFTable table = new XWPFTable(ctTable, doc); XWPFTable table = new XWPFTable(ctTable, doc);
// set inside horizontal border // set inside horizontal border
table.setInsideHBorder(XWPFBorderType.SINGLE, 4, 0, "FF0000"); table.setInsideHBorder(XWPFBorderType.SINGLE, 4, 0, "FF0000");
@ -197,7 +196,7 @@ public class TestXWPFTable extends TestCase {
} }
public void testSetGetVBorders() { public void testSetGetVBorders() {
// create a table // create a table
XWPFDocument doc = new XWPFDocument(); XWPFDocument doc = new XWPFDocument();
CTTbl ctTable = CTTbl.Factory.newInstance(); CTTbl ctTable = CTTbl.Factory.newInstance();
XWPFTable table = new XWPFTable(ctTable, doc); XWPFTable table = new XWPFTable(ctTable, doc);
@ -210,7 +209,7 @@ public class TestXWPFTable extends TestCase {
assertEquals(4, sz); assertEquals(4, sz);
int sp = table.getInsideVBorderSpace(); int sp = table.getInsideVBorderSpace();
assertEquals(0, sp); assertEquals(0, sp);
String clr = table.getInsideVBorderColor(); String clr = table.getInsideVBorderColor();
assertEquals("00FF00", clr); assertEquals("00FF00", clr);
} }
@ -233,29 +232,27 @@ public class TestXWPFTable extends TestCase {
} }
public void testCreateTable() throws Exception { public void testCreateTable() throws Exception {
// open an empty document // open an empty document
XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("sample.docx"); XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("sample.docx");
// create a table with 5 rows and 7 columns // create a table with 5 rows and 7 columns
int noRows = 5; int noRows = 5;
int noCols = 7; int noCols = 7;
XWPFTable table = doc.createTable(noRows,noCols); XWPFTable table = doc.createTable(noRows, noCols);
// assert the table is empty // assert the table is empty
List<XWPFTableRow> rows = table.getRows(); List<XWPFTableRow> rows = table.getRows();
assertEquals("Table has less rows than requested.", noRows, rows.size()); assertEquals("Table has less rows than requested.", noRows, rows.size());
for (XWPFTableRow xwpfRow : rows) for (XWPFTableRow xwpfRow : rows) {
{ assertNotNull(xwpfRow);
assertNotNull(xwpfRow); for (int i = 0; i < 7; i++) {
for (int i = 0 ; i < 7 ; i++) XWPFTableCell xwpfCell = xwpfRow.getCell(i);
{ assertNotNull(xwpfCell);
XWPFTableCell xwpfCell = xwpfRow.getCell(i); assertEquals("Empty cells should not have one paragraph.", 1, xwpfCell.getParagraphs().size());
assertNotNull(xwpfCell); xwpfCell = xwpfRow.getCell(i);
assertEquals("Empty cells should not have one paragraph.",1,xwpfCell.getParagraphs().size()); assertEquals("Calling 'getCell' must not modify cells content.", 1, xwpfCell.getParagraphs().size());
xwpfCell = xwpfRow.getCell(i); }
assertEquals("Calling 'getCell' must not modify cells content.",1,xwpfCell.getParagraphs().size()); }
} doc.getPackage().revert();
}
doc.getPackage().revert();
} }
} }

View File

@ -20,33 +20,42 @@
package org.apache.poi.xwpf.usermodel; package org.apache.poi.xwpf.usermodel;
import junit.framework.TestCase; import junit.framework.TestCase;
import org.apache.poi.xwpf.usermodel.XWPFTableCell.XWPFVertAlign; import org.apache.poi.xwpf.usermodel.XWPFTableCell.XWPFVertAlign;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.*; 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 { public class TestXWPFTableCell extends TestCase {
@Override @Override
protected void setUp() throws Exception { protected void setUp() throws Exception {
super.setUp(); super.setUp();
} }
public void testSetGetVertAlignment() throws Exception { public void testSetGetVertAlignment() throws Exception {
// instantiate the following classes so they'll get picked up by // instantiate the following classes so they'll get picked up by
// the XmlBean process and added to the jar file. they are required // the XmlBean process and added to the jar file. they are required
// for the following XWPFTableCell methods. // for the following XWPFTableCell methods.
CTShd ctShd = CTShd.Factory.newInstance(); CTShd ctShd = CTShd.Factory.newInstance();
assertNotNull(ctShd); assertNotNull(ctShd);
CTVerticalJc ctVjc = CTVerticalJc.Factory.newInstance(); CTVerticalJc ctVjc = CTVerticalJc.Factory.newInstance();
assertNotNull(ctVjc); assertNotNull(ctVjc);
STShd stShd = STShd.Factory.newInstance(); STShd stShd = STShd.Factory.newInstance();
assertNotNull(stShd); assertNotNull(stShd);
STVerticalJc stVjc = STVerticalJc.Factory.newInstance(); STVerticalJc stVjc = STVerticalJc.Factory.newInstance();
assertNotNull(stVjc); assertNotNull(stVjc);
// create a table // create a table
XWPFDocument doc = new XWPFDocument(); XWPFDocument doc = new XWPFDocument();
CTTbl ctTable = CTTbl.Factory.newInstance(); CTTbl ctTable = CTTbl.Factory.newInstance();
XWPFTable table = new XWPFTable(ctTable, doc); XWPFTable table = new XWPFTable(ctTable, doc);
// table has a single row by default; grab it // table has a single row by default; grab it
XWPFTableRow tr = table.getRow(0); XWPFTableRow tr = table.getRow(0);
@ -57,12 +66,12 @@ public class TestXWPFTableCell extends TestCase {
cell.setVerticalAlignment(XWPFVertAlign.BOTH); cell.setVerticalAlignment(XWPFVertAlign.BOTH);
XWPFVertAlign al = cell.getVerticalAlignment(); XWPFVertAlign al = cell.getVerticalAlignment();
assertEquals(XWPFVertAlign.BOTH, al); assertEquals(XWPFVertAlign.BOTH, al);
} }
public void testSetGetColor() throws Exception { public void testSetGetColor() throws Exception {
// create a table // create a table
XWPFDocument doc = new XWPFDocument(); XWPFDocument doc = new XWPFDocument();
CTTbl ctTable = CTTbl.Factory.newInstance(); CTTbl ctTable = CTTbl.Factory.newInstance();
XWPFTable table = new XWPFTable(ctTable, doc); XWPFTable table = new XWPFTable(ctTable, doc);
// table has a single row by default; grab it // table has a single row by default; grab it
XWPFTableRow tr = table.getRow(0); XWPFTableRow tr = table.getRow(0);
@ -73,12 +82,12 @@ public class TestXWPFTableCell extends TestCase {
cell.setColor("F0000F"); cell.setColor("F0000F");
String clr = cell.getColor(); String clr = cell.getColor();
assertEquals("F0000F", clr); assertEquals("F0000F", clr);
} }
/** /**
* ensure that CTHMerge & CTTcBorders go in poi-ooxml.jar * ensure that CTHMerge & CTTcBorders go in poi-ooxml.jar
*/ */
public void test54099(){ public void test54099() {
XWPFDocument doc = new XWPFDocument(); XWPFDocument doc = new XWPFDocument();
CTTbl ctTable = CTTbl.Factory.newInstance(); CTTbl ctTable = CTTbl.Factory.newInstance();
XWPFTable table = new XWPFTable(ctTable, doc); XWPFTable table = new XWPFTable(ctTable, doc);

View File

@ -18,52 +18,51 @@
package org.apache.poi.xwpf.usermodel; package org.apache.poi.xwpf.usermodel;
import junit.framework.TestCase; import junit.framework.TestCase;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTRow; import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTRow;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTbl; import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTbl;
public class TestXWPFTableRow extends TestCase { public class TestXWPFTableRow extends TestCase {
@Override @Override
protected void setUp() throws Exception { protected void setUp() throws Exception {
super.setUp(); super.setUp();
} }
public void testCreateRow() throws Exception { public void testCreateRow() throws Exception {
CTRow ctRow = CTRow.Factory.newInstance(); CTRow ctRow = CTRow.Factory.newInstance();
assertNotNull(ctRow); assertNotNull(ctRow);
} }
@Override @Override
protected void tearDown() throws Exception { protected void tearDown() throws Exception {
super.tearDown(); super.tearDown();
} }
public void testSetGetCantSplitRow() { 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 // create a table
XWPFDocument doc = new XWPFDocument(); XWPFDocument doc = new XWPFDocument();
CTTbl ctTable = CTTbl.Factory.newInstance(); CTTbl ctTable = CTTbl.Factory.newInstance();
XWPFTable table = new XWPFTable(ctTable, doc); XWPFTable table = new XWPFTable(ctTable, doc);
// table has a single row by default; grab it // table has a single row by default; grab it
XWPFTableRow tr = table.getRow(0); XWPFTableRow tr = table.getRow(0);
assertNotNull(tr); assertNotNull(tr);
tr.setRepeatHeader(true); tr.setCantSplitRow(true);
boolean isRpt = tr.isRepeatHeader(); boolean isCant = tr.isCantSplitRow();
assert(isRpt); 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);
}
} }