org.docx4j.wml.ContentAccessor Java Examples

The following examples show how to use org.docx4j.wml.ContentAccessor. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: WmlElementUtils.java    From docx4j-template with Apache License 2.0 6 votes vote down vote up
public static <T> List<T> getChildrenElements(Object source, Class<T> targetClass) {  
    List<T> result = new ArrayList<T>();  
    //获取真实的对象
	Object target = XmlUtils.unwrap(source);
	//if (target.getClass().equals(targetClass)) {
    if (targetClass.isAssignableFrom(target.getClass())) { 
        result.add((T)target);
    } else if (target instanceof ContentAccessor) {  
        List<?> children = ((ContentAccessor) target).getContent();  
        //if (children.getClass().equals(targetClass)) {
        if (targetClass.isAssignableFrom(children.getClass())) { 
            result.add((T)children);
        }
    }
    return result;  
}
 
Example #2
Source File: Docx4j_替换模板.java    From docx4j-template with Apache License 2.0 6 votes vote down vote up
/** 
 * 按class获取内容 
 */  
public static List<Object> getAllElementFromObject(Object obj, Class<?> toSearch) {  
    List<Object> result = new ArrayList<Object>();  
    if (obj instanceof JAXBElement) {  
        obj = ((JAXBElement<?>) obj).getValue();  
    }  
    if (obj.getClass().equals(toSearch)) {  
        result.add(obj);  
    } else if (obj instanceof ContentAccessor) {  
        List<?> children = ((ContentAccessor) obj).getContent();  
        for (Object child : children) {  
            result.addAll(getAllElementFromObject(child, toSearch));  
        }  
    }  
    return result;  
}
 
Example #3
Source File: Docx4j_合并单元格_S4_Test.java    From docx4j-template with Apache License 2.0 6 votes vote down vote up
/** 
 * @Description:得到指定类型的元素 
 */  
public static List<Object> getAllElementFromObject(Object obj,  
        Class<?> toSearch) {  
    List<Object> result = new ArrayList<Object>();  
    if (obj instanceof JAXBElement)  
        obj = ((JAXBElement<?>) obj).getValue();  
    if (obj.getClass().equals(toSearch))  
        result.add(obj);  
    else if (obj instanceof ContentAccessor) {  
        List<?> children = ((ContentAccessor) obj).getContent();  
        for (Object child : children) {  
            result.addAll(getAllElementFromObject(child, toSearch));  
        }  
    }  
    return result;  
}
 
Example #4
Source File: WmlElementUtils.java    From docx4j-template with Apache License 2.0 5 votes vote down vote up
public static <T> List<T> getTargetElements(Object source, Class<T> targetClass) {  
    List<T> result = new ArrayList<T>();  
    //获取真实的对象
	Object target = XmlUtils.unwrap(source);
    //if (target.getClass().equals(targetClass)) {
	if (targetClass.isAssignableFrom(target.getClass())) { 
        result.add((T) target);  
    } else if (target instanceof ContentAccessor) {  
        List<?> children = ((ContentAccessor) target).getContent();  
        for (Object child : children) {  
            result.addAll(getTargetElements(child, targetClass));  
        }
    }
    return result;  
}
 
Example #5
Source File: WmlElementUtils.java    From docx4j-template with Apache License 2.0 5 votes vote down vote up
/**
 * @Description:得到指定类型的元素
 */
public static List<Object> getAllElementFromObject(Object obj, Class<?> toSearch) {
    List<Object> result = new ArrayList<Object>();
    if (obj instanceof JAXBElement)
        obj = ((JAXBElement<?>) obj).getValue();
    if (obj.getClass().equals(toSearch))
        result.add(obj);
    else if (obj instanceof ContentAccessor) {
        List<?> children = ((ContentAccessor) obj).getContent();
        for (Object child : children) {
            result.addAll(getAllElementFromObject(child, toSearch));
        }
    }
    return result;
}
 
Example #6
Source File: Docx4j_删除所有批注_S3_Test.java    From docx4j-template with Apache License 2.0 5 votes vote down vote up
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));  
}
 
Example #7
Source File: ParagraphRepeatProcessor.java    From docx-stamper with MIT License 5 votes vote down vote up
@Override
public void commitChanges(WordprocessingMLPackage document) {
    for (ParagraphCoordinates rCoords : pToRepeat.keySet()) {
        ParagraphsToRepeat paragraphsToRepeat = pToRepeat.get(rCoords);
        List<Object> expressionContexts = paragraphsToRepeat.data;


        List<P> paragraphsToAdd = new ArrayList<>();
        for (final Object expressionContext : expressionContexts) {
            for (P paragraphToClone : paragraphsToRepeat.paragraphs) {
                P pClone = XmlUtils.deepCopy(paragraphToClone);
                placeholderReplacer.resolveExpressionsForParagraph(pClone, expressionContext, document);

                paragraphsToAdd.add(pClone);
            }
        }

        Object parent = rCoords.getParagraph().getParent();
        if (parent instanceof ContentAccessor) {
            ContentAccessor contentAccessor = (ContentAccessor) parent;
            int index = contentAccessor.getContent().indexOf(rCoords.getParagraph());
            if (index >= 0) {
                contentAccessor.getContent().addAll(index, paragraphsToAdd);
            }

            contentAccessor.getContent().removeAll(paragraphsToRepeat.paragraphs);
        }
    }
}
 
Example #8
Source File: AliasVisitor.java    From yarg with Apache License 2.0 5 votes vote down vote up
@Override
public List<Object> apply(Object o) {
    if (o instanceof P || o instanceof P.Hyperlink) {
        String paragraphText = docxFormatter.getElementText(o);

        if (AbstractFormatter.UNIVERSAL_ALIAS_PATTERN.matcher(paragraphText).find()) {
            Set<Text> mergedTexts = new TextMerger((ContentAccessor) o, AbstractFormatter.UNIVERSAL_ALIAS_REGEXP).mergeMatchedTexts();
            for (Text text : mergedTexts) {
                handle(text);
            }
        }
    }

    return null;
}
 
Example #9
Source File: WMLPackageUtils.java    From docx4j-template with Apache License 2.0 4 votes vote down vote up
/**
 * 在标签处插入内容
 * 
 * @param bm
 * @param wPackage
 * @param object
 * @throws Exception
 */
public static void replaceText(CTBookmark bm,  Object object) throws Exception {
	if (object == null) {
		return;
	}
	// do we have data for this one?
	if (bm.getName() == null)
		return;
	String value = object.toString();
	//Log.info("标签名称:"+bm.getName());
	try {
		// Can't just remove the object from the parent,
		// since in the parent, it may be wrapped in a JAXBElement
		List<Object> theList = null;
		ParaRPr rpr = null;
		if (bm.getParent() instanceof P) {
			PPr pprTemp = ((P) (bm.getParent())).getPPr();
			if (pprTemp == null) {
				rpr = null;
			} else {
				rpr = ((P) (bm.getParent())).getPPr().getRPr();
			}
			theList = ((ContentAccessor) (bm.getParent())).getContent();
		} else {
			return;
		}
		int rangeStart = -1;
		int rangeEnd = -1;
		int i = 0;
		for (Object ox : theList) {
			Object listEntry = XmlUtils.unwrap(ox);
			if (listEntry.equals(bm)) {

				if (((CTBookmark) listEntry).getName() != null) {

					rangeStart = i + 1;

				}
			} else if (listEntry instanceof CTMarkupRange) {
				if (((CTMarkupRange) listEntry).getId().equals(bm.getId())) {
					rangeEnd = i - 1;

					break;
				}
			}
			i++;
		}
		int x = i - 1;
		//if (rangeStart > 0 && x >= rangeStart) {
			// Delete the bookmark range
			for (int j = x; j >= rangeStart; j--) {
				theList.remove(j);
			}
			// now add a run
			org.docx4j.wml.R run = factory.createR();
			org.docx4j.wml.Text t = factory.createText();
			// if (rpr != null)
			// run.setRPr(paraRPr2RPr(rpr));
			t.setValue(value);
			run.getContent().add(t);
			//t.setValue(value);

			theList.add(rangeStart, run);
		//}
	} catch (ClassCastException cce) {
		//Log.error(cce);
	}
}
 
Example #10
Source File: ParagraphRepeatProcessor.java    From docx-stamper with MIT License 4 votes vote down vote up
public static List<P> getParagraphsInsideComment(P paragraph) {
    BigInteger commentId = null;
    boolean foundEnd = false;

    List<P> paragraphs = new ArrayList<>();
    paragraphs.add(paragraph);

    for (Object object : paragraph.getContent()) {
        if (object instanceof CommentRangeStart) {
            commentId = ((CommentRangeStart) object).getId();
        }
        if (object instanceof CommentRangeEnd && commentId != null && commentId.equals(((CommentRangeEnd) object).getId())) {
            foundEnd = true;
        }
    }
    if (!foundEnd && commentId != null) {
        Object parent = paragraph.getParent();
        if (parent instanceof ContentAccessor) {
            ContentAccessor contentAccessor = (ContentAccessor) parent;
            int index = contentAccessor.getContent().indexOf(paragraph);
            for (int i = index + 1; i < contentAccessor.getContent().size() && !foundEnd; i ++) {
                Object next = contentAccessor.getContent().get(i);

                if (next instanceof CommentRangeEnd && ((CommentRangeEnd) next).getId().equals(commentId)) {
                    foundEnd = true;
                } else {
                    if (next instanceof P) {
                        paragraphs.add((P) next);
                    }
                    if (next instanceof ContentAccessor) {
                        ContentAccessor childContent = (ContentAccessor) next;
                        for (Object child : childContent.getContent()) {
                            if (child instanceof CommentRangeEnd && ((CommentRangeEnd) child).getId().equals(commentId)) {
                                foundEnd = true;
                                break;
                            }
                        }
                    }
                }
            }
        }
    }
    return paragraphs;
}
 
Example #11
Source File: TextMerger.java    From yarg with Apache License 2.0 4 votes vote down vote up
public TextMerger(ContentAccessor paragraph, String regexp) {
    this.paragraph = paragraph;
    this.regexp = regexp;
    this.regexpPattern = Pattern.compile(regexp);
    this.first2SymbolsOfRegexp = regexp.replaceAll("\\\\", "").substring(0, 2);
}