Java源码示例:org.docx4j.TraversalUtil
示例1
public static void replaceRichText(WordprocessingMLPackage wordMLPackage, Map<String, String> richTextMap) throws Docx4JException, JAXBException {
MainDocumentPart document = wordMLPackage.getMainDocumentPart();
Map<String, List<Object>> textNodeMap = new HashMap<String, List<Object>>();
findRichTextNode(textNodeMap, document.getContents().getBody(), null);
Iterator<String> iterator = richTextMap.keySet().iterator();
while (iterator.hasNext()) {
String textTag = iterator.next();
List<Object> textNodeList = textNodeMap.get(textTag);
if (textNodeList != null && richTextMap.containsKey(textTag)) {
List<Object> textObjList = convertToWmlObject(wordMLPackage, richTextMap.get(textTag));
for (int i = 0, iSize = textNodeList.size(); i < iSize; i++) {
Object nodeObject = textNodeList.get(i);
if (nodeObject != null) {
//setWmlPprSetting(textNodeList.get(i), textObjList);
TraversalUtil.replaceChildren(nodeObject , textObjList);
}
}
}
}
}
示例2
protected void findNameForCurrentTable(final TableManager currentTable) {
new TraversalUtil(currentTable.firstRow,
new RegexpFinder<P>(docxFormatter, AbstractFormatter.BAND_NAME_DECLARATION_PATTERN, P.class) {
@Override
protected void onFind(P paragraph, Matcher matcher) {
if (currentTable.bandName == null) {
super.onFind(paragraph, matcher);
currentTable.bandName = matcher.group(1);
String bandNameDeclaration = matcher.group();
Set<Text> mergedTexts = new TextMerger(paragraph, bandNameDeclaration).mergeMatchedTexts();
for (Text text : mergedTexts) {
text.setValue(text.getValue().replace(bandNameDeclaration, ""));
}
}
}
});
}
示例3
protected Part resolveTextPartForDOCX(Text text, WordprocessingMLPackage wordPackage) {
java.util.List<SectionWrapper> sectionWrappers = wordPackage.getDocumentModel().getSections();
for (SectionWrapper sw : sectionWrappers) {
HeaderFooterPolicy hfp = sw.getHeaderFooterPolicy();
List<Part> parts = Arrays.asList(hfp.getFirstHeader(), hfp.getDefaultHeader(), hfp.getEvenHeader(),
hfp.getFirstFooter(), hfp.getDefaultFooter(), hfp.getEvenFooter());
for (Part part : parts) {
TextMatchCallback callback = new TextMatchCallback(text);
new TraversalUtil(part, callback);
if (callback.matched) {
return part;
}
}
}
return wordPackage.getMainDocumentPart();
}
示例4
public void removeAllComment(String filePath, String savePath)
throws Exception {
WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage
.load(new java.io.File(filePath));
//清空comments.xml内容
Parts parts = wordMLPackage.getParts();
HashMap<PartName, Part> partMap = parts.getParts();
CommentsPart commentPart = (CommentsPart) partMap.get(new PartName(
"/word/comments.xml"));
Comments comments = commentPart.getContents();
List<Comment> commentList = comments.getComment();
for (int i = 0, len = commentList.size(); i < len; i++) {
commentList.remove(0);
}
//清空document.xml文件中批注
MainDocumentPart documentPart = wordMLPackage.getMainDocumentPart();
org.docx4j.wml.Document wmlDocumentEl = (org.docx4j.wml.Document) documentPart
.getContents();
Body body = wmlDocumentEl.getBody();
CommentFinder cf = new CommentFinder();
new TraversalUtil(body, cf);
for (Child commentElement : cf.commentElements) {
System.out.println(commentElement.getClass().getName());
Object parent = commentElement.getParent();
List<Object> theList = ((ContentAccessor) parent).getContent();
boolean removeResult = remove(theList, commentElement);
System.out.println(removeResult);
}
wordMLPackage.save(new FileOutputStream(savePath));
}
示例5
/**
* Replace text
*
* See also http://www.docx4java.org/forums/docx-java-f6/best-approach-to-search-replace-in-a-template-merge-t1040.html
*/
public static void replaceText(InputStream input, HashMap<String, String> model, OutputStream output) throws Docx4JException,
JAXBException, IOException {
log.info("replaceText({}, {}, {})", new Object[]{input, model, output});
WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage.load(input);
MainDocumentPart documentPart = wordMLPackage.getMainDocumentPart();
for (final Map.Entry<String, String> entry : model.entrySet()) {
new TraversalUtil(documentPart, new TraversalUtil.CallbackImpl() {
@Override
public List<Object> apply(Object child) {
if (child instanceof org.docx4j.wml.Text) {
org.docx4j.wml.Text t = (org.docx4j.wml.Text) child;
if (t.getValue().contains(entry.getKey())) {
t.setValue(t.getValue().replaceAll(entry.getKey(), entry.getValue()));
}
}
return null;
}
});
}
// Save it
wordMLPackage.save(output);
log.info("replaceText: void");
}
示例6
protected void collectDataFromObjects(Object... objects) {
for (Object object : objects) {
if (object != null) {
TextVisitor collectAliasesCallback = new TextVisitor(docxFormatter);
new TraversalUtil(object, collectAliasesCallback);
texts.addAll(collectAliasesCallback.textWrappers);
}
}
}
示例7
public Tr copyRow(Tr row) {
Tr copiedRow = XmlUtils.deepCopy(row);
new TraversalUtil(copiedRow, INVARIANTS_SETTER);//set parent for each sub-element of copied row (otherwise parent would be JaxbElement)
int index = table.getContent().indexOf(row);
table.getContent().add(index, copiedRow);
return copiedRow;
}
示例8
/**
* 替换书签为图片
*
* @param wordMLPackage
* @param documentPart
* @param imageParameters
* @throws Exception
*/
private static void replaceBookMarkWithImage(WordprocessingMLPackage wordMLPackage,
MainDocumentPart documentPart,
Map<String, String> imageParameters)
throws Exception {
Document wmlDoc = documentPart.getContents();
Body body = wmlDoc.getBody();
// 提取正文中所有段落
List<Object> paragraphs = body.getContent();
// 提取书签并创建书签的游标
RangeFinder rt = new RangeFinder("CTBookmark", "CTMarkupRange");
new TraversalUtil(paragraphs, rt);
// 遍历书签
for (CTBookmark bm : rt.getStarts()) {
String bookmarkName = bm.getName();
String imagePath = imageParameters.get(bookmarkName);
if (imagePath != null) {
File imageFile = new File(imagePath);
InputStream imageStream = new FileInputStream(imageFile);
// 读入图片并转化为字节数组,因为docx4j只能字节数组的方式插入图片
byte[] bytes = IOUtils.toByteArray(imageStream);
// 创建一个行内图片
BinaryPartAbstractImage imagePart = BinaryPartAbstractImage.createImagePart(wordMLPackage, bytes);
// createImageInline函数的前四个参数我都没有找到具体啥意思
// 最后一个是限制图片的宽度,缩放的依据
Inline inline = imagePart.createImageInline(null, null, 0, 1, false, 800);
// 获取该书签的父级段落
P p = (P) (bm.getParent());
ObjectFactory factory = new ObjectFactory();
// 新建一个Run
R run = factory.createR();
// drawing 画布
Drawing drawing = factory.createDrawing();
drawing.getAnchorOrInline()
.add(inline);
run.getContent()
.add(drawing);
p.getContent()
.add(run);
}
}
}
示例9
/**
* Since we start with headers/footers which each take up approx half the page,
* there is little room for the body content (which would result in many pages,
* and unnecessary processing).
*
* At the same time, we need enough body content to produce first page, odd page,
* and even page for each section.
*
* So this method replaces the existing body content with content which is sufficient
* for our needs. This method isn't essential, but it should make things faster.
*
* It leaves the headers/footers untouched, since it is those which we're
* most interested in at this point.
*
* @param hfPkg
*/
static void trimContent(WordprocessingMLPackage hfPkg) {
// Find the sectPrs
SectPrFinder sf = new SectPrFinder(hfPkg.getMainDocumentPart());
try {
new TraversalUtil(hfPkg.getMainDocumentPart().getContents(), sf);
} catch (Docx4JException e) {
// TODO Auto-generated catch block
log.error(e.getMessage(), e);
}
List<SectPr> sectPrList = sf.getSectPrList();
// Was there a body level one?
if (hfPkg.getMainDocumentPart().getJaxbElement().getBody().getSectPr()!=null) {
//then delete the first entry (which is where SectPrFinder put it)
sectPrList.remove(0);
}
// Now generate content; let's use
P filler = createFillerP();
List<Object> contents = hfPkg.getMainDocumentPart().getContent();
contents.clear();
for (SectPr sectPr : sectPrList) {
contents.add(filler);
contents.add(filler);
contents.add(filler);
contents.add(filler);
// We expect to cause, in due course, something like:
// WARN org.apache.fop.apps.FOUserAgent .processEvent line 97 -
// The contents of fo:region-body on page 6 exceed its viewport
// by 29068 millipoints. (See position 1:1038)
// now add the sectPr
P p = Context.getWmlObjectFactory().createP();
PPr ppr = Context.getWmlObjectFactory().createPPr();
p.setPPr(ppr);
ppr.setSectPr(sectPr);
contents.add(p);
}
// Add content before the body level sectPr
if (hfPkg.getMainDocumentPart().getJaxbElement().getBody().getSectPr()!=null) {
contents.add(filler);
contents.add(filler);
contents.add(filler);
contents.add(filler);
}
}
示例10
protected void collectTexts() {
TextVisitor collectAliasesCallback = new TextVisitor(docxFormatter);
new TraversalUtil(mainDocumentPart, collectAliasesCallback);
texts = collectAliasesCallback.textWrappers;
}
示例11
protected void collectTables() {
TableCollector collectTablesCallback = new TableCollector(docxFormatter);
new TraversalUtil(mainDocumentPart, collectTablesCallback);
tables = collectTablesCallback.tableManagers;
}
示例12
public List<Object> apply(Object object) {
final TableManager currentTable = !currentTables.isEmpty() ? currentTables.peek() : null;
if (currentTable == null || currentTable.isSkipIt()) {
return null;
}
if (object instanceof Tr) {
Tr currentRow = (Tr) object;
if (currentTable.firstRow == null) {
currentTable.firstRow = currentRow;
findNameForCurrentTable(currentTable);
if (currentTable.bandName == null) {
currentTable.setSkipIt(true);
} else {
tableManagers.add(currentTable);
}
}
if (currentTable.rowWithAliases == null) {
RegexpCollectionFinder<P> aliasFinder = new RegexpCollectionFinder<P>(docxFormatter, AbstractFormatter.UNIVERSAL_ALIAS_PATTERN, P.class);
new TraversalUtil(currentRow, aliasFinder);
List<String> foundAliases = aliasFinder.getValues();
if (!foundAliases.isEmpty()) {
boolean fromCurrentBand = false;
for (String foundAlias : foundAliases) {
String parameterName = docxFormatter.unwrapParameterName(foundAlias);
if (parameterName != null) {
String[] parts = parameterName.split("\\.");
if (parts.length == 1) {
fromCurrentBand = true;
break;
} else if (docxFormatter.findBandByPath(parts[0]) == null) {
fromCurrentBand = true;
break;
}
}
}
if (fromCurrentBand) {
currentTable.rowWithAliases = currentRow;
}
}
}
}
return null;
}
示例13
protected void handleUrls() {
UrlVisitor urlVisitor = new UrlVisitor(new DocxFormatterDelegate(this), wordprocessingMLPackage.getMainDocumentPart());
new TraversalUtil(wordprocessingMLPackage.getMainDocumentPart(), urlVisitor);
}