Java Code Examples for org.docx4j.XmlUtils

The following examples show how to use org.docx4j.XmlUtils. These examples are extracted from open source projects. 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 Project: kbase-doc   Source File: WatermarkPicture.java    License: Apache License 2.0 6 votes vote down vote up
private SectPr createSectPr() throws Exception {
		
		String openXML = "<w:sectPr xmlns:w=\"http://schemas.openxmlformats.org/wordprocessingml/2006/main\" xmlns:r=\"http://schemas.openxmlformats.org/officeDocument/2006/relationships\">"
				
				// Word adds the background image in each of 3 header parts
	            + "<w:headerReference r:id=\"" + createHeaderPart("even").getId() + "\" w:type=\"even\"/>"
	            + "<w:headerReference r:id=\"" + createHeaderPart("default").getId() + "\" w:type=\"default\"/>"
	            + "<w:headerReference r:id=\"" + createHeaderPart("first").getId() + "\" w:type=\"first\"/>"
	            
	            // Word adds empty footer parts when you create a watermark, but its not necessary
	            
//	            + "<w:footerReference r:id=\"rId9\" w:type=\"even\"/>"
//	            + "<w:footerReference r:id=\"rId10\" w:type=\"default\"/>"
//	            + "<w:footerReference r:id=\"rId12\" w:type=\"first\"/>"
	            
	            + "<w:pgSz w:h=\"15840\" w:w=\"12240\"/>"
	            + "<w:pgMar w:bottom=\"1440\" w:footer=\"708\" w:gutter=\"0\" w:header=\"708\" w:left=\"1440\" w:right=\"1440\" w:top=\"1440\"/>"
	            + "<w:cols w:space=\"708\"/>"
	            + "<w:docGrid w:linePitch=\"360\"/>"
	        +"</w:sectPr>";
	 
		return (SectPr)XmlUtils.unmarshalString(openXML);
	
	}
 
Example 2
Source Project: docx4j-template   Source File: WmlElementUtils.java    License: 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 3
Source Project: docx4j-template   Source File: WmlElementUtils.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * @Description:删除指定位置的表格,删除后表格数量减一
 */
public static boolean removeTableByIndex(WordprocessingMLPackage wordMLPackage, int index) throws Exception {
    boolean flag = false;
    if (index < 0) {
        return flag;
    }
    List<Object> objList = wordMLPackage.getMainDocumentPart().getContent();
    if (objList == null) {
        return flag;
    }
    int k = -1;
    for (int i = 0, len = objList.size(); i < len; i++) {
        Object obj = XmlUtils.unwrap(objList.get(i));
        if (obj instanceof Tbl) {
            k++;
            if (k == index) {
                wordMLPackage.getMainDocumentPart().getContent().remove(i);
                flag = true;
                break;
            }
        }
    }
    return flag;
}
 
Example 4
Source Project: docx4j-template   Source File: WmlElementUtils.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * @Description: 删除指定行 删除后行数减一
 */
public static boolean removeTrByIndex(Tbl tbl, int index) {
    boolean flag = false;
    if (index < 0) {
        return flag;
    }
    List<Object> objList = tbl.getContent();
    if (objList == null) {
        return flag;
    }
    int k = -1;
    for (int i = 0, len = objList.size(); i < len; i++) {
        Object obj = XmlUtils.unwrap(objList.get(i));
        if (obj instanceof Tr) {
            k++;
            if (k == index) {
                tbl.getContent().remove(i);
                flag = true;
                break;
            }
        }
    }
    return flag;
}
 
Example 5
public static void writeToStream(WordprocessingMLPackage wmlPackage,OutputStream output) throws IOException, Docx4JException {
	Assert.notNull(wmlPackage, " wmlPackage is not specified!");
	Assert.notNull(output, " output is not specified!");
	InputStream input = null;
	try {
		//Document对象
		MainDocumentPart document = wmlPackage.getMainDocumentPart();	
		//Document XML
		String documentXML = XmlUtils.marshaltoString(wmlPackage);
		//转成字节输入流
		input = IOUtils.toBufferedInputStream(new ByteArrayInputStream(documentXML.getBytes()));
		//输出模板
		IOUtils.copy(input, output);
	} finally {
		IOUtils.closeQuietly(input);
	}
}
 
Example 6
public void writeToWriter(WordprocessingMLPackage wmlPackage,Writer output) throws IOException, Docx4JException {
	Assert.notNull(wmlPackage, " wmlPackage is not specified!");
	Assert.notNull(output, " output is not specified!");
	InputStream input = null;
	try {
		//Document对象
		MainDocumentPart document = wmlPackage.getMainDocumentPart();	
		//Document XML
		String documentXML = XmlUtils.marshaltoString(wmlPackage.getPackage());
		//转成字节输入流
		input = IOUtils.toBufferedInputStream(new ByteArrayInputStream(documentXML.getBytes()));
		//获取模板输出编码格式
		String charsetName = Docx4jProperties.getProperty(Docx4jConstants.DOCX4J_CONVERT_OUT_WMLTEMPLATE_CHARSETNAME, Docx4jConstants.DEFAULT_CHARSETNAME );
		//输出模板
		IOUtils.copy(input, output, Charset.forName(charsetName));
	} finally {
		IOUtils.closeQuietly(input);
	}
}
 
Example 7
Source Project: docx4j-template   Source File: Docx4j_工具类_S3_Test.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * @Description:删除指定位置的表格,删除后表格数量减一
 */
public boolean removeTableByIndex(WordprocessingMLPackage wordMLPackage,
        int index) throws Exception {
    boolean flag = false;
    if (index < 0) {
        return flag;
    }
    List<Object> objList = wordMLPackage.getMainDocumentPart().getContent();
    if (objList == null) {
        return flag;
    }
    int k = -1;
    for (int i = 0, len = objList.size(); i < len; i++) {
        Object obj = XmlUtils.unwrap(objList.get(i));
        if (obj instanceof Tbl) {
            k++;
            if (k == index) {
                wordMLPackage.getMainDocumentPart().getContent().remove(i);
                flag = true;
                break;
            }
        }
    }
    return flag;
}
 
Example 8
Source Project: docx4j-template   Source File: Docx4j_工具类_S3_Test.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * @Description: 删除指定行 删除后行数减一
 */
public boolean removeTrByIndex(Tbl tbl, int index) {
    boolean flag = false;
    if (index < 0) {
        return flag;
    }
    List<Object> objList = tbl.getContent();
    if (objList == null) {
        return flag;
    }
    int k = -1;
    for (int i = 0, len = objList.size(); i < len; i++) {
        Object obj = XmlUtils.unwrap(objList.get(i));
        if (obj instanceof Tr) {
            k++;
            if (k == index) {
                tbl.getContent().remove(i);
                flag = true;
                break;
            }
        }
    }
    return flag;
}
 
Example 9
Source Project: docx-stamper   Source File: CommentUtil.java    License: MIT License 6 votes vote down vote up
private static boolean deleteCommentReference(ContentAccessor parent,
		BigInteger commentId) {
	for (int i = 0; i < parent.getContent().size(); i++) {
		Object contentObject = XmlUtils.unwrap(parent.getContent().get(i));
		if (contentObject instanceof ContentAccessor) {
			if (deleteCommentReference((ContentAccessor) contentObject, commentId)) {
				return true;
			}
		}
		if (contentObject instanceof R) {
			for (Object runContentObject : ((R) contentObject).getContent()) {
				Object unwrapped = XmlUtils.unwrap(runContentObject);
				if (unwrapped instanceof R.CommentReference) {
					BigInteger foundCommentId = ((R.CommentReference) unwrapped)
							.getId();
					if (foundCommentId.equals(commentId)) {
						parent.getContent().remove(i);
						return true;
					}
				}
			}
		}
	}
	return false;
}
 
Example 10
Source Project: yarg   Source File: AliasVisitor.java    License: Apache License 2.0 6 votes vote down vote up
public void walkJAXBElements(Object parent) {
    List children = getChildren(parent);
    if (children != null) {

        for (Object object : children) {
            object = XmlUtils.unwrap(object);

            if (object instanceof Child && !(parent instanceof SdtBlock)) {
                ((Child) object).setParent(parent);
            }

            this.apply(object);

            if (this.shouldTraverse(object)) {
                walkJAXBElements(object);
            }
        }
    }
}
 
Example 11
public List<Object> apply(Object o) {  
    if (o instanceof javax.xml.bind.JAXBElement  
            && (((JAXBElement) o).getName().getLocalPart()  
                    .equals("commentReference")  
                    || ((JAXBElement) o).getName().getLocalPart()  
                            .equals("commentRangeStart") || ((JAXBElement) o)  
                    .getName().getLocalPart().equals("commentRangeEnd"))) {  
        System.out.println(((JAXBElement) o).getName().getLocalPart());  
        commentElements.add((Child) XmlUtils.unwrap(o));  
    } else if (o instanceof CommentReference  
            || o instanceof CommentRangeStart  
            || o instanceof CommentRangeEnd) {  
        System.out.println(o.getClass().getName());  
        commentElements.add((Child) o);  
    }  
    return null;  
}
 
Example 12
public void walkJAXBElements(Object parent) {  
    List children = getChildren(parent);  
    if (children != null) {  
        for (Object o : children) {  
            if (o instanceof javax.xml.bind.JAXBElement  
                    && (((JAXBElement) o).getName().getLocalPart()  
                            .equals("sdt"))) {  
                ((Child) ((JAXBElement) o).getValue()).setParent(XmlUtils  
                        .unwrap(parent));  
            } else {  
                o = XmlUtils.unwrap(o);  
                if (o instanceof Child) {  
                    ((Child) o).setParent(XmlUtils.unwrap(parent));  
                }  
            }  
            this.apply(o);  
            if (this.shouldTraverse(o)) {  
                walkJAXBElements(o);  
            }  
        }  
    }  
}
 
Example 13
Source Project: docx4j-export-FO   Source File: XsltFOFunctions.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Use RunFontSelector to determine the correct font for the list item label.
 * 
 * @param context
 * @param foListItemLabelBody
 * @param pPr
 * @param rPr
 * @param text
 */
protected static void setFont(RunFontSelector runFontSelector, Element foListItemLabelBody, PPr pPr, RPr rPr, String text) {
	
	DocumentFragment result = (DocumentFragment)runFontSelector.fontSelector(pPr, rPr, text);
	log.debug(XmlUtils.w3CDomNodeToString(result));
	// eg <fo:inline xmlns:fo="http://www.w3.org/1999/XSL/Format" font-family="Times New Roman">1)</fo:inline>
	
	// Now get the attribute value
	if (result!=null && result.getFirstChild()!=null) {
		Attr attr = ((Element)result.getFirstChild()).getAttributeNode("font-family");
		if (attr!=null) {
			foListItemLabelBody.setAttribute("font-family", attr.getValue());
		}
	}
			
}
 
Example 14
Source Project: docx4j-export-FO   Source File: LayoutMasterSetBuilder.java    License: Apache License 2.0 6 votes vote down vote up
public static DocumentFragment getLayoutMasterSetFragment(AbstractWmlConversionContext context) {

		LayoutMasterSet lms = getFoLayoutMasterSet(context);	
		
		// Set suitable extents, for which we need area tree 
		FOSettings foSettings = (FOSettings)context.getConversionSettings();
		if ( !foSettings.lsLayoutMasterSetCalculationInProgress()) // Avoid infinite loop
			// Can't just do it where foSettings.getApacheFopMime() is not MimeConstants.MIME_FOP_AREA_TREE,
			// since TOC functionality uses that.
		{
			fixExtents( lms, context, true);
		}
		
		org.w3c.dom.Document document = XmlUtils.marshaltoW3CDomDocument(lms, Context.getXslFoContext() );
		DocumentFragment docfrag = document.createDocumentFragment();
		docfrag.appendChild(document.getDocumentElement());
		
		
		return docfrag;		
	}
 
Example 15
Source Project: docx4j-export-FO   Source File: LayoutMasterSetBuilder.java    License: Apache License 2.0 6 votes vote down vote up
/**
    * For XSLFOExporterNonXSLT
    * @since 3.0
    * 
    */	
public static void appendLayoutMasterSetFragment(AbstractWmlConversionContext context, Node foRoot) {

	LayoutMasterSet lms = getFoLayoutMasterSet(context);	
	
	// Set suitable extents, for which we need area tree 
	FOSettings foSettings = (FOSettings)context.getConversionSettings();
	if ( !foSettings.lsLayoutMasterSetCalculationInProgress()) // Avoid infinite loop
		// Can't just do it where foSettings.getApacheFopMime() is not MimeConstants.MIME_FOP_AREA_TREE,
		// since TOC functionality uses that.
	{
		fixExtents( lms, context, false);
	}
	
	org.w3c.dom.Document document = XmlUtils.marshaltoW3CDomDocument(lms, Context.getXslFoContext() );
	XmlUtils.treeCopy(document.getDocumentElement(), foRoot);
}
 
Example 16
/**
	 * table says 40, Normal says nothing.
	 * don't override table style
	 * @throws Exception
	 */
	@Test 
	public void testTblStyle_AllSilent() throws Exception {
				
		WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage.createPackage();
		wordMLPackage.getMainDocumentPart().setContents(
				(Document)XmlUtils.unmarshalString(mdpXml_tblStyle) );
		wordMLPackage.getMainDocumentPart().getStyleDefinitionsPart().setContents(
				(Styles)XmlUtils.unmarshalString(styles_no_font_sz) );
		
//		// NB PropertyResolver puts 10pt in DocDefaults, if nothing is specified!
		
		setSetting(wordMLPackage, OVERRIDE); // resulting text in table is 40pt

		wordMLPackage.save(new File(System.getProperty("user.dir") + "/OUT_PStyleInTableTest.docx"));
		
		ParagraphStylesInTableFix.process(wordMLPackage);
		
		Style s = getStyle(wordMLPackage, getStyleName());
		this.assertSz(s, 40);
	}
 
Example 17
@Test 
	@Ignore
	public void testTblStyle_AllSilent() throws Exception {
		
		WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage.createPackage();
		wordMLPackage.getMainDocumentPart().setContents(
				(Document)XmlUtils.unmarshalString(mdpXml_tblStyle) );
		wordMLPackage.getMainDocumentPart().getStyleDefinitionsPart().setContents(
				(Styles)XmlUtils.unmarshalString(styles_no_font_sz) );

		setSetting(wordMLPackage, OVERRIDE); 

		wordMLPackage.save(new File(System.getProperty("user.dir") + "/OUT_PStyleInTableTest.docx"));
		
//		// NB createVirtualStylesForDocDefaults() puts 10pt there, if nothing is specified!
//		// So we need to delete that!
//		wordMLPackage.getMainDocumentPart().getStyleDefinitionsPart().createVirtualStylesForDocDefaults();
//		Style dd = wordMLPackage.getMainDocumentPart().getStyleDefinitionsPart().getStyleById("DocDefaults");
//		dd.getRPr().setSz(null);
//		dd.getRPr().setSzCs(null);
		
		ParagraphStylesInTableFix.process(wordMLPackage);
		
		Style s = getStyle(wordMLPackage, getStyleName());
		Assert.assertTrue(s.getRPr().getSz().getVal().intValue()==EXPECTED_RESULT); 
	}
 
Example 18
@Test 
	public void testTblStyle_AllSilent() throws Exception {
		
		// Result is to use the implicit 10pt		
	
		WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage.createPackage();
		wordMLPackage.getMainDocumentPart().setContents(
				(Document)XmlUtils.unmarshalString(mdpXml_tblStyle) );
		wordMLPackage.getMainDocumentPart().getStyleDefinitionsPart().setContents(
				(Styles)XmlUtils.unmarshalString(styles_no_font_sz) );

		setSetting(wordMLPackage, OVERRIDE);  // table style should get overridden
		
		wordMLPackage.save(new File(System.getProperty("user.dir") + "/OUT_PStyleInTableTest.docx"));
		
		// NB PropertyResolver puts 10pt in DocDefaults, if nothing is specified!
		
		ParagraphStylesInTableFix.process(wordMLPackage);
		
		Style s = getStyle(wordMLPackage, getStyleName());
		this.assertSz(s, 20);
//		Assert.assertTrue(s.getRPr().getSz().getVal().intValue()==20); 
	}
 
Example 19
Source Project: docx-stamper   Source File: RepeatProcessor.java    License: MIT License 6 votes vote down vote up
private void repeatRows(final WordprocessingMLPackage document) {
    for (TableRowCoordinates rCoords : tableRowsToRepeat.keySet()) {
        List<Object> expressionContexts = tableRowsToRepeat.get(rCoords);
        int index = rCoords.getIndex();
        for (final Object expressionContext : expressionContexts) {
            Tr rowClone = XmlUtils.deepCopy(rCoords.getRow());
            DocumentWalker walker = new BaseDocumentWalker(rowClone) {
                @Override
                protected void onParagraph(P paragraph) {
                    placeholderReplacer.resolveExpressionsForParagraph(paragraph, expressionContext, document);
                }
            };
            walker.walk();
            rCoords.getParentTableCoordinates().getTable().getContent().add(++index, rowClone);
        }
        rCoords.getParentTableCoordinates().getTable().getContent().remove(rCoords.getRow());
    }
}
 
Example 20
Source Project: yarg   Source File: TextMerger.java    License: Apache License 2.0 6 votes vote down vote up
public Set<Text> mergeMatchedTexts() {
    for (Object paragraphContentObject : paragraph.getContent()) {
        if (paragraphContentObject instanceof R) {
            R currentRun = (R) paragraphContentObject;
            for (Object runContentObject : currentRun.getContent()) {
                Object unwrappedRunContentObject = XmlUtils.unwrap(runContentObject);
                if (unwrappedRunContentObject instanceof Text) {
                    handleText((Text) unwrappedRunContentObject);
                }
            }
        }
    }

    removeUnnecessaryTexts();

    return resultingTexts;
}
 
Example 21
Source Project: docx-stamper   Source File: CoordinatesWalker.java    License: MIT License 6 votes vote down vote up
private void walkTableCell(TableCellCoordinates cellCoordinates) {
    onTableCell(cellCoordinates);
    int elementIndex = 0;
    for (Object cellContentElement : cellCoordinates.getCell().getContent()) {
        if (XmlUtils.unwrap(cellContentElement) instanceof P) {
            P p = (P) cellContentElement;
            ParagraphCoordinates paragraphCoordinates = new ParagraphCoordinates(p, elementIndex, cellCoordinates);
            onParagraph(paragraphCoordinates);
        } else if (XmlUtils.unwrap(cellContentElement) instanceof Tbl) {
            Tbl nestedTable = (Tbl) ((JAXBElement) cellContentElement).getValue();
            TableCoordinates innerTableCoordinates = new TableCoordinates(nestedTable, elementIndex, cellCoordinates);
            walkTable(innerTableCoordinates);
        }
        elementIndex++;
    }
}
 
Example 22
Source Project: docx-stamper   Source File: DocumentWalker.java    License: MIT License 6 votes vote down vote up
public void walk() {
    for (Object contentElement : contentAccessor.getContent()) {
        Object unwrappedObject = XmlUtils.unwrap(contentElement);
        if (unwrappedObject instanceof P) {
            P p = (P) unwrappedObject;
            walkParagraph(p);
        } else if (unwrappedObject instanceof Tbl) {
            Tbl table = (Tbl) unwrappedObject;
            walkTable(table);
        } else if (unwrappedObject instanceof Tr) {
            Tr row = (Tr) unwrappedObject;
            walkTableRow(row);
        } else if (unwrappedObject instanceof Tc) {
            Tc cell = (Tc) unwrappedObject;
            walkTableCell(cell);
        } else if (unwrappedObject instanceof CommentRangeStart) {
            CommentRangeStart commentRangeStart = (CommentRangeStart) unwrappedObject;
            onCommentRangeStart(commentRangeStart);
        } else if (unwrappedObject instanceof CommentRangeEnd) {
            CommentRangeEnd commentRangeEnd = (CommentRangeEnd) unwrappedObject;
            onCommentRangeEnd(commentRangeEnd);
        }
    }
}
 
Example 23
Source Project: docx-stamper   Source File: DocumentWalker.java    License: MIT License 5 votes vote down vote up
private void walkTable(Tbl table) {
    onTable(table);
    for (Object contentElement : table.getContent()) {
        if (XmlUtils.unwrap(contentElement) instanceof Tr) {
            Tr row = (Tr) contentElement;
            walkTableRow(row);
        }
    }
}
 
Example 24
Source Project: docx4j-template   Source File: HtmlToDOCDemo.java    License: Apache License 2.0 5 votes vote down vote up
private static List<Object> convertToWmlObject(
		WordprocessingMLPackage wordMLPackage, String content)
		throws Docx4JException, JAXBException {
	MainDocumentPart document = wordMLPackage.getMainDocumentPart();
	//获取Jsoup参数
	String charsetName = Docx4jProperties.getProperty(Docx4jConstants.DOCX4J_CONVERT_OUT_WMLTEMPLATE_CHARSETNAME, Docx4jConstants.DEFAULT_CHARSETNAME );
	
	List<Object> wmlObjList = null;
	String templateString = XmlUtils.marshaltoString(document.getContents().getBody());
	System.out.println(templateString);
	Body templateBody = document.getContents().getBody();
	try {
		document.getContents().setBody(XmlUtils.deepCopy(templateBody));
		document.getContent().clear();
		Document doc = Jsoup.parse(content);
		doc.outputSettings().syntax(Document.OutputSettings.Syntax.xml).escapeMode(Entities.EscapeMode.xhtml);
		//XHTMLImporterImpl xhtmlImporter = new XHTMLImporterImpl(wordMLPackage);
		
		AlternativeFormatInputPart  part = document.addAltChunk(AltChunkType.Xhtml,doc.html().getBytes(Charset.forName(charsetName)));
		
		WordprocessingMLPackage tempPackage = document.convertAltChunks();
		File file = new File("d://temp.docx");
		tempPackage.save(file);
		wmlObjList = document.getContent();
		//part.getOwningRelationshipPart().getSourceP().get
		//wmlObjList = xhtmlImporter.convert(doc.html(), doc.baseUri());
	} finally {
		document.getContents().setBody(templateBody);
	}
	return wmlObjList;
}
 
Example 25
Source Project: docx4j-template   Source File: SampleDocument.java    License: Apache License 2.0 5 votes vote down vote up
static void addObject(MainDocumentPart wordDocumentPart, String template, String fontName ) throws JAXBException {
	
    HashMap substitution = new HashMap();
    substitution.put("fontname", fontName);
    Object o = XmlUtils.unmarshallFromTemplate(template, substitution);
    wordDocumentPart.addObject(o);    		    
	
}
 
Example 26
Source Project: docx-stamper   Source File: DocumentWalker.java    License: MIT License 5 votes vote down vote up
private void walkTableRow(Tr row) {
    onTableRow(row);
    for (Object rowContentElement : row.getContent()) {
        if (XmlUtils.unwrap(rowContentElement) instanceof Tc) {
            Tc cell = rowContentElement instanceof Tc ? (Tc) rowContentElement : (Tc) ((JAXBElement) rowContentElement).getValue();
            walkTableCell(cell);
        }
    }
}
 
Example 27
Source Project: docx4j-template   Source File: WmlElementUtils.java    License: 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 28
Source Project: yarg   Source File: TableCollector.java    License: Apache License 2.0 5 votes vote down vote up
public void walkJAXBElements(Object parent) {
    List children = getChildren(parent);
    if (children != null) {

        for (Object o : children) {
            o = XmlUtils.unwrap(o);

            if (o instanceof Child && !(parent instanceof SdtBlock)) {
                ((Child) o).setParent(parent);
            }

            if (o instanceof Tbl) {
                currentTables.push(new TableManager(docxFormatter, (Tbl) o));
            }

            this.apply(o);

            if (this.shouldTraverse(o)) {
                walkJAXBElements(o);
            }

            if (o instanceof Tbl) {
                TableManager currentTable = currentTables.pop();
                currentTable.setSkipIt(false);
            }
        }
    }
}
 
Example 29
Source Project: docx-stamper   Source File: DocumentWalker.java    License: MIT License 5 votes vote down vote up
private void walkTableCell(Tc cell) {
    onTableCell(cell);
    for (Object cellContentElement : cell.getContent()) {
        if (XmlUtils.unwrap(cellContentElement) instanceof P) {
            P p = (P) cellContentElement;
            walkParagraph(p);
        } else if (XmlUtils.unwrap(cellContentElement) instanceof Tbl) {
            Tbl nestedTable = (Tbl) ((JAXBElement) cellContentElement).getValue();
            walkTable(nestedTable);
        }
    }
}
 
Example 30
Source Project: docx4j-template   Source File: Docx4j_替换模板.java    License: Apache License 2.0 5 votes vote down vote up
/** 
 * 获取单元格字符串 
 */  
private String[] getTcMarshalStr(Tr tr) {  
    List<Object> tcObjList = tr.getContent();  
    String[] marshaArr = new String[7];  
    // 跳过层次  
    for (int i = 1, len = tcObjList.size(); i < len; i++) {  
        marshaArr[i - 1] = XmlUtils.marshaltoString(tcObjList.get(i), true, false);  
    }  
    return marshaArr;  
}