xwpfrun 文字被拆开怎么这只黑体字

org.apache.poi.xwpf.usermodel.XWPFRun.java ( Source and Javadoc)
Example: ArrayList or java.util.ArrayList &
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831
public class XWPFRun {
public XWPFRun( r,
this.run =
this.paragraph =
drawingList = r.getDrawingList();
for ( ctDrawing : drawingList) {
anchorList = ctDrawing.getAnchorList();
for ( anchor : anchorList) {
if (anchor.getDocPr() != null) {
getDocument().getDrawingIdManager().reserve(anchor.getDocPr().getId());
inlineList = ctDrawing.getInlineList();
for ( inline : inlineList) {
if (inline.getDocPr() != null) {
getDocument().getDrawingIdManager().reserve(inline.getDocPr().getId());
text = new ();
pictTextObjs = new ();
pictTextObjs.addAll(r.getPictList());
pictTextObjs.addAll(drawingList);
for( o : pictTextObjs) {
[] t = o.selectPath("declare namespace w='http://schemas.openxmlformats.org/wordprocessingml/2006/main' .//w:t");
for (int m = 0; m & t. m++) {
kids = t[m].getDomNode().getChildNodes();
for (int n = 0; n & kids.getLength(); n++) {
if (kids.item(n) instanceof ) {
if(text.length() & 0)
text.append("\n");
text.append(kids.item(n).getNodeValue());
pictureText = text.toString();
pictures = new ();
for( o : pictTextObjs) {
for( pict : getCTPictures(o)) {
picture = new (pict, this);
pictures.add(picture);
getCTPictures( o) {
pictures = new ();
[] picts = o.selectPath("declare namespace pic='"+CTPicture.type.getName().getNamespaceURI()+"' .//pic:pic");
for( pict : picts) {
if(pict instanceof ) {
pict = CTPicture.Factory.parse( pict.toString() );
} catch( e) {
throw new (e);
if(pict instanceof ) {
pictures.add(()pict);
getCTR() {
getParagraph() {
getDocument() {
if (paragraph != null) {
return paragraph.getDocument();
return null;
private boolean isCTOnOff( onoff) {
if(! onoff.isSetVal())
return true;
if(onoff.getVal() == STOnOff.ON)
return true;
if(onoff.getVal() == STOnOff.TRUE)
return true;
return false;
public boolean isBold() {
pr = run.getRPr();
if(pr == null || !pr.isSetB()) {
return false;
return isCTOnOff(pr.getB());
public void setBold(boolean value) {
pr = run.isSetRPr() ? run.getRPr() : run.addNewRPr();
bold = pr.isSetB() ? pr.getB() : pr.addNewB();
bold.setVal(value ? STOnOff.TRUE : STOnOff.FALSE);
getColor() {
color = null;
if (run.isSetRPr()) {
pr = run.getRPr();
if (pr.isSetColor()) {
clr = pr.getColor();
color = clr.xgetVal().getStringValue();
public void setColor( rgbStr) {
pr = run.isSetRPr() ? run.getRPr() : run.addNewRPr();
color = pr.isSetColor() ? pr.getColor() : pr.addNewColor();
color.setVal(rgbStr);
getText(int pos) {
return run.sizeOfTArray() == 0 ? null : run.getTArray(pos)
.getStringValue();
getPictureText() {
return pictureT
public void setText( value) {
setText(value,run.getTList().size());
public void setText( value, int pos) {
if(pos & run.sizeOfTArray()) throw new ("Value too large for the parameter position in XWPFRun.setText(String value,int pos)");
t = (pos & run.sizeOfTArray() && pos &= 0) ? run.getTArray(pos) : run.addNewT();
t.setStringValue(value);
preserveSpaces(t);
public boolean isItalic() {
pr = run.getRPr();
if(pr == null || !pr.isSetI())
return false;
return isCTOnOff(pr.getI());
public void setItalic(boolean value) {
pr = run.isSetRPr() ? run.getRPr() : run.addNewRPr();
italic = pr.isSetI() ? pr.getI() : pr.addNewI();
italic.setVal(value ? STOnOff.TRUE : STOnOff.FALSE);
getUnderline() {
pr = run.getRPr();
return (pr != null && pr.isSetU()) ? UnderlinePatterns.valueOf(pr
.getU().getVal().intValue()) : UnderlinePatterns.NONE;
public void setUnderline( value) {
pr = run.isSetRPr() ? run.getRPr() : run.addNewRPr();
underline = (pr.getU() == null) ? pr.addNewU() : pr.getU();
underline.setVal(STUnderline.Enum.forInt(value.getValue()));
public boolean isStrike() {
pr = run.getRPr();
if(pr == null || !pr.isSetStrike())
return false;
return isCTOnOff(pr.getStrike());
public void setStrike(boolean value) {
pr = run.isSetRPr() ? run.getRPr() : run.addNewRPr();
strike = pr.isSetStrike() ? pr.getStrike() : pr.addNewStrike();
strike.setVal(value ? STOnOff.TRUE : STOnOff.FALSE);
getSubscript() {
pr = run.getRPr();
return (pr != null && pr.isSetVertAlign()) ? VerticalAlign.valueOf(pr.getVertAlign().getVal().intValue()) : VerticalAlign.BASELINE;
public void setSubscript( valign) {
pr = run.isSetRPr() ? run.getRPr() : run.addNewRPr();
ctValign = pr.isSetVertAlign() ? pr.getVertAlign() : pr.addNewVertAlign();
ctValign.setVal(STVerticalAlignRun.Enum.forInt(valign.getValue()));
getFontFamily() {
pr = run.getRPr();
return (pr != null && pr.isSetRFonts()) ? pr.getRFonts().getAscii()
public void setFontFamily( fontFamily) {
pr = run.isSetRPr() ? run.getRPr() : run.addNewRPr();
fonts = pr.isSetRFonts() ? pr.getRFonts() : pr.addNewRFonts();
fonts.setAscii(fontFamily);
public int getFontSize() {
pr = run.getRPr();
return (pr != null && pr.isSetSz()) ? pr.getSz().getVal().divide(new ("2")).intValue() : -1;
public void setFontSize(int size) {
bint=new (""+size);
pr = run.isSetRPr() ? run.getRPr() : run.addNewRPr();
ctSize = pr.isSetSz() ? pr.getSz() : pr.addNewSz();
ctSize.setVal(bint.multiply(new ("2")));
public int getTextPosition() {
pr = run.getRPr();
return (pr != null && pr.isSetPosition()) ? pr.getPosition().getVal().intValue()
public void setTextPosition(int val) {
bint=new (""+val);
pr = run.isSetRPr() ? run.getRPr() : run.addNewRPr();
position = pr.isSetPosition() ? pr.getPosition() : pr.addNewPosition();
position.setVal(bint);
public void removeBreak() {
public void addBreak() {
run.addNewBr();
public void addBreak( type){
br=run.addNewBr();
br.setType(STBrType.Enum.forInt(type.getValue()));
public void addBreak( clear){
br=run.addNewBr();
br.setType(STBrType.Enum.forInt(BreakType.TEXT_WRAPPING.getValue()));
br.setClear(STBrClear.Enum.forInt(clear.getValue()));
public void addCarriageReturn() {
run.addNewCr();
public void removeCarriageReturn() {
addPicture( pictureData, int pictureType,
filename, int width, int height)
doc = paragraph.
relationId = doc.addPictureData(pictureData, pictureType);
picData = () doc.getRelationById(relationId);
drawing = run.addNewDrawing();
inline = drawing.addNewInline();
"&a:graphic xmlns:a=\"" + CTGraphicalObject.type.getName().getNamespaceURI() + "\"&" +
"&a:graphicData uri=\"" + CTPicture.type.getName().getNamespaceURI() + "\"&" +
"&pic:pic xmlns:pic=\"" + CTPicture.type.getName().getNamespaceURI() + "\" /&" +
"&/a:graphicData&" +
"&/a:graphic&";
inline.set(XmlToken.Factory.parse(xml));
inline.setDistT(0);
inline.setDistR(0);
inline.setDistB(0);
inline.setDistL(0);
docPr = inline.addNewDocPr();
long id = getParagraph().document.getDrawingIdManager().reserveNew();
docPr.setId(id);
docPr.setName("Drawing " + id);
docPr.setDescr(filename);
extent = inline.addNewExtent();
extent.setCx(width);
extent.setCy(height);
graphic = inline.getGraphic();
graphicData = graphic.getGraphicData();
pic = getCTPictures(graphicData).get(0);
nvPicPr = pic.addNewNvPicPr();
cNvPr = nvPicPr.addNewCNvPr();
cNvPr.setId(0L);
cNvPr.setName("Picture " + id);
cNvPr.setDescr(filename);
cNvPicPr = nvPicPr.addNewCNvPicPr();
cNvPicPr.addNewPicLocks().setNoChangeAspect(true);
blipFill = pic.addNewBlipFill();
blip = blipFill.addNewBlip();
blip.setEmbed( picData.getPackageRelationship().getId() );
blipFill.addNewStretch().addNewFillRect();
spPr = pic.addNewSpPr();
xfrm = spPr.addNewXfrm();
off = xfrm.addNewOff();
off.setX(0);
off.setY(0);
ext = xfrm.addNewExt();
ext.setCx(width);
ext.setCy(height);
prstGeom = spPr.addNewPrstGeom();
prstGeom.setPrst(STShapeType.RECT);
prstGeom.addNewAvLst();
xwpfPicture = new (pic, this);
pictures.add(xwpfPicture);
return xwpfP
} catch( e) {
throw new (e);
getEmbeddedPictures() {
static void preserveSpaces( xs) {
text = xs.getStringValue();
if (text != null && (text.startsWith(" ") || text.endsWith(" "))) {
c = xs.newCursor();
c.toNextToken();
c.insertAttributeWithValue(new ("http://www.w3.org/XML/1998/namespace", "space"), "preserve");
c.dispose();
toString() {
text = new ();
c = run.newCursor();
c.selectPath("./*");
while (c.toNextSelection()) {
o = c.getObject();
if (o instanceof ) {
tagName = o.getDomNode().getNodeName();
if (!"w:instrText".equals(tagName)) {
text.append((() o).getStringValue());
if (o instanceof ) {
text.append("\t");
if (o instanceof ) {
text.append("\n");
if (o instanceof ) {
tagName = o.getDomNode().getNodeName();
if ("w:tab".equals(tagName)) {
text.append("\t");
if ("w:br".equals(tagName)) {
text.append("\n");
if ("w:cr".equals(tagName)) {
text.append("\n");
c.dispose();
if(pictureText != null && pictureText.length() & 0) {
text.append("\n").append(pictureText);
return text.toString();
Example: ArrayList or java.util.ArrayList &org.apache.poi.xwpf.usermodel.XWPFRun - 源码查看 - 拨云剑
/* ====================================================================
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements.
See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==================================================================== */
package org.apache.poi.xwpf.
import java.io.IOE
import java.io.InputS
import java.math.BigI
import java.util.ArrayL
import java.util.L
import javax.xml.namespace.QN
import org.apache.poi.POIXMLE
import org.apache.poi.openxml4j.exceptions.InvalidFormatE
import org.apache.poi.util.I
import org.apache.xmlbeans.XmlC
import org.apache.xmlbeans.XmlE
import org.apache.xmlbeans.XmlO
import org.apache.xmlbeans.XmlS
import org.apache.xmlbeans.XmlT
import org.apache.xmlbeans.impl.values.XmlAnyTypeI
import org.openxmlformats.schemas.drawingml.x2006.main.CTB
import org.openxmlformats.schemas.drawingml.x2006.main.CTBlipFillP
import org.openxmlformats.schemas.drawingml.x2006.main.CTGraphicalO
import org.openxmlformats.schemas.drawingml.x2006.main.CTGraphicalObjectD
import org.openxmlformats.schemas.drawingml.x2006.main.CTNonVisualDrawingP
import org.openxmlformats.schemas.drawingml.x2006.main.CTNonVisualPictureP
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.CTShapeP
import org.openxmlformats.schemas.drawingml.x2006.main.CTTransform2D;
import org.openxmlformats.schemas.drawingml.x2006.main.STShapeT
import org.openxmlformats.schemas.drawingml.x2006.wordprocessingDrawing.CTA
import org.openxmlformats.schemas.drawingml.x2006.wordprocessingDrawing.CTI
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTBr;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTC
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTD
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTE
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTF
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTHpsM
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTOnO
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTPT
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTR;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTRPr;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTSignedHpsM
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTT
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTU
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTVerticalAlignR
import org.openxmlformats.schemas.wordprocessingml.x2006.main.STBrC
import org.openxmlformats.schemas.wordprocessingml.x2006.main.STBrT
import org.openxmlformats.schemas.wordprocessingml.x2006.main.STOnO
import org.openxmlformats.schemas.wordprocessingml.x2006.main.STU
import org.openxmlformats.schemas.wordprocessingml.x2006.main.STVerticalAlignR
import org.w3c.dom.NodeL
import org.w3c.dom.T
import org.openxmlformats.schemas.drawingml.x2006.picture.CTP
import org.openxmlformats.schemas.drawingml.x2006.picture.CTPictureNonV
* XWPFRun object defines a region of text with a common set of properties
* @author Yegor Kozlov
* @author Gregg Morris (gregg dot morris at gmail dot com) - added getColor(), setColor()
public class XWPFRun {
private CTR
private String pictureT
private XWPFP
private List
* @param r the CTR bean which holds the run attributes
* @param p the parent paragraph
public XWPFRun(CTR r, XWPFParagraph p) {
this.run =
this.paragraph =
* reserve already occupied drawing ids, so reserving new ids later will
* not corrupt the document
List drawingList = r.getDrawingList();
for (CTDrawing ctDrawing : drawingList) {
List anchorList = ctDrawing.getAnchorList();
for (CTAnchor anchor : anchorList) {
if (anchor.getDocPr() != null) {
getDocument().getDrawingIdManager().reserve(anchor.getDocPr().getId());
List inlineList = ctDrawing.getInlineList();
for (CTInline inline : inlineList) {
if (inline.getDocPr() != null) {
getDocument().getDrawingIdManager().reserve(inline.getDocPr().getId());
// Look for any text in any of our pictures or drawings
StringBuffer text = new StringBuffer();
List pictTextObjs = new ArrayList();
pictTextObjs.addAll(r.getPictList());
pictTextObjs.addAll(drawingList);
for(XmlObject o : pictTextObjs) {
XmlObject[] t = o.selectPath("declare namespace w='http://schemas.openxmlformats.org/wordprocessingml/2006/main' .//w:t");
for (int m = 0; m < t. m++) {
NodeList kids = t[m].getDomNode().getChildNodes();
for (int n = 0; n
text.append("\n");
text.append(kids.item(n).getNodeValue());
pictureText = text.toString();
// Do we have any embedded pictures?
// (They're a different CTPicture, under the drawingml namespace)
pictures = new ArrayList();
for(XmlObject o : pictTextObjs) {
for(CTPicture pict : getCTPictures(o)) {
XWPFPicture picture = new XWPFPicture(pict, this);
pictures.add(picture);
private List getCTPictures(XmlObject o) {
List pictures = new ArrayList();
XmlObject[] picts = o.selectPath("declare namespace pic='"+CTPicture.type.getName().getNamespaceURI()+"' .//pic:pic");
for(XmlObject pict : picts) {
if(pict instanceof XmlAnyTypeImpl) {
// Pesky XmlBeans bug - see Bugzilla #49934
pict = CTPicture.Factory.parse( pict.toString() );
} catch(XmlException e) {
throw new POIXMLException(e);
if(pict instanceof CTPicture) {
pictures.add((CTPicture)pict);
* Get the currently used CTR object
* @return ctr object
public CTR getCTR() {
* Get the currenty referenced paragraph object
* @return current paragraph
public XWPFParagraph getParagraph() {
* @return The {@link XWPFDocument} instance, this run belongs to, or
null if parent structure (paragraph > document) is not properly set.
public XWPFDocument getDocument() {
if (paragraph != null) {
return paragraph.getDocument();
* For isBold, isItalic etc
private boolean isCTOnOff(CTOnOff onoff) {
if(! onoff.isSetVal())
if(onoff.getVal() == STOnOff.ON)
if(onoff.getVal() == STOnOff.TRUE)
* Whether the bold property shall be applied to all non-complex script
* characters in the contents of this run when displayed in a document
* @return true if the bold property is applied
public boolean isBold() {
CTRPr pr = run.getRPr();
if(pr == null || !pr.isSetB()) {
return isCTOnOff(pr.getB());
* Whether the bold property shall be applied to all non-complex script
* characters in the contents of this run when displayed in a document.
* This formatting property is a toggle property, which specifies that its
* behavior differs between its use within a style definition and its use as
* direct formatting. When used as part of a style definition, setting this
* property shall toggle the current state of that property as specified up
* to this point in the hierarchy (i.e. applied to not applied, and vice
* versa). Setting it to false (or an equivalent) shall
* result in the current setting remaining unchanged. However, when used as
* direct formatting, setting this property to true or false shall set the
* absolute state of the resulting property.
* If this element is not present, the default value is to leave the
* formatting applied at previous level in the style hierarchy. If this
* element is never applied in the style hierarchy, then bold shall not be
* applied to non-complex script characters.
* @param value true if the bold property is applied to
public void setBold(boolean value) {
CTRPr pr = run.isSetRPr() ? run.getRPr() : run.addNewRPr();
CTOnOff bold = pr.isSetB() ? pr.getB() : pr.addNewB();
bold.setVal(value ? STOnOff.TRUE : STOnOff.FALSE);
* Get text color. The returned value is a string in the hex form "RRGGBB".
public String getColor() {
String color =
if (run.isSetRPr()) {
CTRPr pr = run.getRPr();
if (pr.isSetColor()) {
CTColor clr = pr.getColor();
color = clr.xgetVal().getStringValue();
* Set text color.
* @param rgbStr - the desired color, in the hex form "RRGGBB".
public void setColor(String rgbStr) {
CTRPr pr = run.isSetRPr() ? run.getRPr() : run.addNewRPr();
CTColor color = pr.isSetColor() ? pr.getColor() : pr.addNewColor();
color.setVal(rgbStr);
* Return the string content of this text run
* @return the text of this text run or null if not set
public String getText(int pos) {
return run.sizeOfTArray() == 0 ? null : run.getTArray(pos)
.getStringValue();
* Returns text embedded in pictures
public String getPictureText() {
return pictureT
* Sets the text of this text run
* @param value the literal text which shall be displayed in the document
public void setText(String value) {
setText(value,run.getTList().size());
* Sets the text of this text run in the
* @param value the literal text which shall be displayed in the document
* @param pos - position in the text array (NB: 0 based)
public void setText(String value, int pos) {
if(pos > run.sizeOfTArray()) throw new ArrayIndexOutOfBoundsException("Value too large for the parameter position in XWPFRun.setText(String value,int pos)");
CTText t = (pos = 0) ? run.getTArray(pos) : run.addNewT();
t.setStringValue(value);
preserveSpaces(t);
* Whether the italic property should be applied to all non-complex script
* characters in the contents of this run when displayed in a document.
* @return true if the italic property is applied
public boolean isItalic() {
CTRPr pr = run.getRPr();
if(pr == null || !pr.isSetI())
return isCTOnOff(pr.getI());
* Whether the bold property shall be applied to all non-complex script
* characters in the contents of this run when displayed in a document
* This formatting property is a toggle property, which specifies that its
* behavior differs between its use within a style definition and its use as
* direct formatting. When used as part of a style definition, setting this
* property shall toggle the current state of that property as specified up
* to this point in the hierarchy (i.e. applied to not applied, and vice
* versa). Setting it to false (or an equivalent) shall
* result in the current setting remaining unchanged. However, when used as
* direct formatting, setting this property to true or false shall set the
* absolute state of the resulting property.
* If this element is not present, the default value is to leave the
* formatting applied at previous level in the style hierarchy. If this
* element is never applied in the style hierarchy, then bold shall not be
* applied to non-complex script characters.
* @param value true if the italic property is applied to
public void setItalic(boolean value) {
CTRPr pr = run.isSetRPr() ? run.getRPr() : run.addNewRPr();
CTOnOff italic = pr.isSetI() ? pr.getI() : pr.addNewI();
italic.setVal(value ? STOnOff.TRUE : STOnOff.FALSE);
* Specifies that the contents of this run should be displayed along with an
* underline appearing directly below the character heigh
* @return the Underline pattern applyed to this run
* @see UnderlinePatterns
public UnderlinePatterns getUnderline() {
CTRPr pr = run.getRPr();
return (pr != null && pr.isSetU()) ? UnderlinePatterns.valueOf(pr
.getU().getVal().intValue()) : UnderlinePatterns.NONE;
* Specifies that the contents of this run should be displayed along with an
* underline appearing directly below the character heigh
* If this element is not present, the default value is to leave the
* formatting applied at previous level in the style hierarchy. If this
* element is never applied in the style hierarchy, then an underline shall
* not be applied to the contents of this run.
* @param value -
underline type
* @see UnderlinePatterns : all possible patterns that could be applied
public void setUnderline(UnderlinePatterns value) {
CTRPr pr = run.isSetRPr() ? run.getRPr() : run.addNewRPr();
CTUnderline underline = (pr.getU() == null) ? pr.addNewU() : pr.getU();
underline.setVal(STUnderline.Enum.forInt(value.getValue()));
* Specifies that the contents of this run shall be displayed with a single
* horizontal line through the center of the line.
* @return true if the strike property is applied
public boolean isStrike() {
CTRPr pr = run.getRPr();
if(pr == null || !pr.isSetStrike())
return isCTOnOff(pr.getStrike());
* Specifies that the contents of this run shall be displayed with a single
* horizontal line through the center of the line.
* This formatting property is a toggle property, which specifies that its
* behavior differs between its use within a style definition and its use as
* direct formatting. When used as part of a style definition, setting this
* property shall toggle the current state of that property as specified up
* to this point in the hierarchy (i.e. applied to not applied, and vice
* versa). Setting it to false (or an equivalent) shall result in the
* current setting remaining unchanged. However, when used as direct
* formatting, setting this property to true or false shall set the absolute
* state of the resulting property.
* If this element is not present, the default value is to leave the
* formatting applied at previous level in the style hierarchy. If this
* element is never applied in the style hierarchy, then strikethrough shall
* not be applied to the contents of this run.
* @param value true if the strike property is applied to
public void setStrike(boolean value) {
CTRPr pr = run.isSetRPr() ? run.getRPr() : run.addNewRPr();
CTOnOff strike = pr.isSetStrike() ? pr.getStrike() : pr.addNewStrike();
strike.setVal(value ? STOnOff.TRUE : STOnOff.FALSE);
* Specifies the alignment which shall be applied to the contents of this
* run in relation to the default appearance of the run's text.
* This allows the text to be repositioned as subscript or superscript without
* altering the font size of the run properties.
* @return VerticalAlign
* @see VerticalAlign all possible value that could be applyed to this run
public VerticalAlign getSubscript() {
CTRPr pr = run.getRPr();
return (pr != null && pr.isSetVertAlign()) ? VerticalAlign.valueOf(pr.getVertAlign().getVal().intValue()) : VerticalAlign.BASELINE;
* Specifies the alignment which shall be applied to the contents of this
* run in relation to the default appearance of the run's text. This allows
* the text to be repositioned as subscript or superscript without altering
* the font size of the run properties.
* If this element is not present, the default value is to leave the
* formatting applied at previous level in the style hierarchy. If this
* element is never applied in the style hierarchy, then the text shall not
* be subscript or superscript relative to the default baseline location for
* the contents of this run.
* @param valign
* @see VerticalAlign
public void setSubscript(VerticalAlign valign) {
CTRPr pr = run.isSetRPr() ? run.getRPr() : run.addNewRPr();
CTVerticalAlignRun ctValign = pr.isSetVertAlign() ? pr.getVertAlign() : pr.addNewVertAlign();
ctValign.setVal(STVerticalAlignRun.Enum.forInt(valign.getValue()));
* 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
* @return a string representing the font family
public String getFontFamily() {
CTRPr pr = run.getRPr();
return (pr != null && pr.isSetRFonts()) ? pr.getRFonts().getAscii()
* 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
* @param fontFamily
public void setFontFamily(String fontFamily) {
CTRPr pr = run.isSetRPr() ? run.getRPr() : run.addNewRPr();
CTFonts fonts = pr.isSetRFonts() ? pr.getRFonts() : pr.addNewRFonts();
fonts.setAscii(fontFamily);
* Specifies the font size which shall be applied to all non complex script
* characters in the contents of this run when displayed.
* @return value representing the font size
public int getFontSize() {
CTRPr pr = run.getRPr();
return (pr != null && pr.isSetSz()) ? pr.getSz().getVal().divide(new BigInteger("2")).intValue() : -1;
* Specifies the font size which shall be applied to all non complex script
* characters in the contents of this run when displayed.
* If this element is not present, the default value is to leave the value
* applied at previous level in the style hierarchy. If this element is
* never applied in the style hierarchy, then any appropriate font size may
* be used for non complex script characters.
* @param size
public void setFontSize(int size) {
BigInteger bint=new BigInteger(""+size);
CTRPr pr = run.isSetRPr() ? run.getRPr() : run.addNewRPr();
CTHpsMeasure ctSize = pr.isSetSz() ? pr.getSz() : pr.addNewSz();
ctSize.setVal(bint.multiply(new BigInteger("2")));
* This element specifies the amount by which text shall be raised or
* lowered for this run in relation to the default baseline of the
* surrounding non-positioned text. This allows the text to be repositioned
* without altering the font size of the contents.
* @return a big integer representing the amount of text shall be "moved"
public int getTextPosition() {
CTRPr pr = run.getRPr();
return (pr != null && pr.isSetPosition()) ? pr.getPosition().getVal().intValue()
* This element specifies the amount by which text shall be raised or
* lowered for this run in relation to the default baseline of the
* surrounding non-positioned text. This allows the text to be repositioned
* without altering the font size of the contents.
* If the val attribute is positive, then the parent run shall be raised
* above the baseline of the surrounding text by the specified number of
* half-points. If the val attribute is negative, then the parent run shall
* be lowered below the baseline of the surrounding text by the specified
* number of half-points.
* If this element is not present, the default value is to leave the
* formatting applied at previous level in the style hierarchy. If this
* element is never applied in the style hierarchy, then the text shall not
* be raised or lowered relative to the default baseline location for the
* contents of this run.
* @param val
public void setTextPosition(int val) {
BigInteger bint=new BigInteger(""+val);
CTRPr pr = run.isSetRPr() ? run.getRPr() : run.addNewRPr();
CTSignedHpsMeasure position = pr.isSetPosition() ? pr.getPosition() : pr.addNewPosition();
position.setVal(bint);
public void removeBreak() {
* Specifies that a break shall be placed at the current location in the run
* content.
* A break is a special character which is used to override the
* normal line breaking that would be performed based on the normal layout
* of the document's contents.
* @see #addCarriageReturn()
public void addBreak() {
run.addNewBr();
* Specifies that a break shall be placed at the current location in the run
* content.
* A break is a special character which is used to override the
* normal line breaking that would be performed based on the normal layout
* of the document's contents.
* The behavior of this break character (the
* location where text shall be restarted after this break) shall be
* determined by its type values.
* @see BreakType
public void addBreak(BreakType type){
CTBr br=run.addNewBr();
br.setType(STBrType.Enum.forInt(type.getValue()));
* Specifies that a break shall be placed at the current location in the run
* content. A break is a special character which is used to override the
* normal line breaking that would be performed based on the normal layout
* of the document's contents.
* The behavior of this break character (the
* location where text shall be restarted after this break) shall be
* determined by its type (in this case is BreakType.TEXT_WRAPPING as default) and clear attribute values.
* @see BreakClear
public void addBreak(BreakClear clear){
CTBr br=run.addNewBr();
br.setType(STBrType.Enum.forInt(BreakType.TEXT_WRAPPING.getValue()));
br.setClear(STBrClear.Enum.forInt(clear.getValue()));
* Specifies that a carriage return shall be placed at the
* current location in the run content.
* A carriage return is used to end the current line of text in
* Wordprocess.
* The behavior of a carriage return in run content shall be
* identical to a break character with null type and clear attributes, which
* shall end the current line and find the next available line on which to
* continue.
* The carriage return character forced the following text to be
* restarted on the next available line in the document.
public void addCarriageReturn() {
run.addNewCr();
public void removeCarriageReturn() {
* Adds a picture to the run. This method handles
attaching the picture data to the overall file.
* @see org.apache.poi.xwpf.usermodel.Document#PICTURE_TYPE_EMF
* @see org.apache.poi.xwpf.usermodel.Document#PICTURE_TYPE_WMF
* @see org.apache.poi.xwpf.usermodel.Document#PICTURE_TYPE_PICT
* @see org.apache.poi.xwpf.usermodel.Document#PICTURE_TYPE_JPEG
* @see org.apache.poi.xwpf.usermodel.Document#PICTURE_TYPE_PNG
* @see org.apache.poi.xwpf.usermodel.Document#PICTURE_TYPE_DIB
* @param pictureData The raw picture data
* @param pictureType The type of the picture, eg {@link Document#PICTURE_TYPE_JPEG}
* @param width width in EMUs. To convert to / from points use {@link org.apache.poi.util.Units}
* @param height height in EMUs. To convert to / from points use {@link org.apache.poi.util.Units}
* @throws org.apache.poi.openxml4j.exceptions.InvalidFormatException
* @throws IOException
public XWPFPicture addPicture(InputStream pictureData, int pictureType, String filename, int width, int height)
throws InvalidFormatException, IOException {
XWPFDocument doc = paragraph.
// Add the picture + relationship
String relationId = doc.addPictureData(pictureData, pictureType);
XWPFPictureData picData = (XWPFPictureData) doc.getRelationById(relationId);
// Create the drawing entry for it
CTDrawing drawing = run.addNewDrawing();
CTInline inline = drawing.addNewInline();
// Do the fiddly namespace bits on the inline
// (We need full control of what goes where and as what)
String xml =
inline.set(XmlToken.Factory.parse(xml));
// Setup the inline
inline.setDistT(0);
inline.setDistR(0);
inline.setDistB(0);
inline.setDistL(0);
CTNonVisualDrawingProps docPr = inline.addNewDocPr();
long id = getParagraph().document.getDrawingIdManager().reserveNew();
docPr.setId(id);
/* This name is not visible in Word 2010 anywhere. */
docPr.setName("Drawing " + id);
docPr.setDescr(filename);
CTPositiveSize2D extent = inline.addNewExtent();
extent.setCx(width);
extent.setCy(height);
// Grab the picture object
CTGraphicalObject graphic = inline.getGraphic();
CTGraphicalObjectData graphicData = graphic.getGraphicData();
CTPicture pic = getCTPictures(graphicData).get(0);
// Set it up
CTPictureNonVisual nvPicPr = pic.addNewNvPicPr();
CTNonVisualDrawingProps cNvPr = nvPicPr.addNewCNvPr();
/* use "0" for the id. See ECM-576, 20.2.2.3 */
cNvPr.setId(0L);
/* This name is not visible in Word 2010 anywhere */
cNvPr.setName("Picture " + id);
cNvPr.setDescr(filename);
CTNonVisualPictureProperties cNvPicPr = nvPicPr.addNewCNvPicPr();
cNvPicPr.addNewPicLocks().setNoChangeAspect(true);
CTBlipFillProperties blipFill = pic.addNewBlipFill();
CTBlip blip = blipFill.addNewBlip();
blip.setEmbed( picData.getPackageRelationship().getId() );
blipFill.addNewStretch().addNewFillRect();
CTShapeProperties spPr = pic.addNewSpPr();
CTTransform2D xfrm = spPr.addNewXfrm();
CTPoint2D off = xfrm.addNewOff();
off.setX(0);
off.setY(0);
CTPositiveSize2D ext = xfrm.addNewExt();
ext.setCx(width);
ext.setCy(height);
CTPresetGeometry2D prstGeom = spPr.addNewPrstGeom();
prstGeom.setPrst(STShapeType.RECT);
prstGeom.addNewAvLst();
// Finish up
XWPFPicture xwpfPicture = new XWPFPicture(pic, this);
pictures.add(xwpfPicture);
return xwpfP
} catch(XmlException e) {
throw new IllegalStateException(e);
* Returns the embedded pictures of the run. These
are pictures which reference an external,
embedded picture image such as a .png or .jpg
public List getEmbeddedPictures() {
* 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, with tabs and
carriage returns in place of their xml equivalents.
public String toString() {
StringBuffer text = new StringBuffer();
// Grab the text and tabs of the text run
// Do so in a way that preserves the ordering
XmlCursor c = run.newCursor();
c.selectPath("./*");
while (c.toNextSelection()) {
XmlObject o = c.getObject();
if (o instanceof CTText) {
String tagName = o.getDomNode().getNodeName();
// Field Codes (w:instrText, defined in spec sec. 17.16.23)
come up as instances of CTText, but we don't want them
in the normal text output
if (!"w:instrText".equals(tagName)) {
text.append(((CTText) o).getStringValue());
if (o instanceof CTPTab) {
text.append("\t");
if (o instanceof CTBr) {
text.append("\n");
if (o instanceof CTEmpty) {
// Some inline text elements get returned not as
themselves, but as CTEmpty, owing to some odd
definitions around line 5642 of the XSDs
// This bit works around it, and replicates the above
rules for that case
String tagName = o.getDomNode().getNodeName();
if ("w:tab".equals(tagName)) {
text.append("\t");
if ("w:br".equals(tagName)) {
text.append("\n");
if ("w:cr".equals(tagName)) {
text.append("\n");
c.dispose();
// Any picture text?
if(pictureText != null && pictureText.length() > 0) {
text.append("\n").append(pictureText);
return text.toString();

我要回帖

更多关于 xwpfrun addpicture 的文章

 

随机推荐