org.docx4j.XmlUtils Java Examples

The following examples show how to use org.docx4j.XmlUtils. 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: LayoutMasterSetBuilder.java    From docx4j-export-FO with 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 #2
Source File: RepeatProcessor.java    From docx-stamper with 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 #3
Source File: WmlElementUtils.java    From docx4j-template with 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 File: WatermarkPicture.java    From kbase-doc with 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 #5
Source File: CoordinatesWalker.java    From docx-stamper with 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 #6
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 #7
Source File: TextMerger.java    From yarg with 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 #8
Source File: WmlElementUtils.java    From docx4j-template with 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 #9
Source File: WordprocessingMLTemplateWriter.java    From docx4j-template with Apache License 2.0 6 votes vote down vote up
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 #10
Source File: WordprocessingMLTemplateWriter.java    From docx4j-template with Apache License 2.0 6 votes vote down vote up
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 #11
Source File: Docx4j_工具类_S3_Test.java    From docx4j-template with 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 #12
Source File: PStyle12PtInTableNormalOverrideTrueTest.java    From docx4j-export-FO with Apache License 2.0 6 votes vote down vote up
@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 #13
Source File: DocumentWalker.java    From docx-stamper with 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 #14
Source File: LayoutMasterSetBuilder.java    From docx4j-export-FO with 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 File: XsltFOFunctions.java    From docx4j-export-FO with 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 #16
Source File: PStyle12PtInTableGridOverrideFalseTest.java    From docx4j-export-FO with Apache License 2.0 6 votes vote down vote up
/**
	 * 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
Source File: Docx4j_读取内容控件_S3_Test.java    From docx4j-template with Apache License 2.0 6 votes vote down vote up
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 #18
Source File: Docx4j_删除所有批注_S3_Test.java    From docx4j-template with Apache License 2.0 6 votes vote down vote up
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 #19
Source File: AliasVisitor.java    From yarg with 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 #20
Source File: CommentUtil.java    From docx-stamper with 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 #21
Source File: PStyle11PtInTableOverrideFalseTest.java    From docx4j-export-FO with Apache License 2.0 6 votes vote down vote up
@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 #22
Source File: Docx4j_工具类_S3_Test.java    From docx4j-template with 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 #23
Source File: DocumentWalker.java    From docx-stamper with MIT License 5 votes vote down vote up
private void walkParagraph(P p) {
    onParagraph(p);
    for (Object element : p.getContent()) {
        if (XmlUtils.unwrap(element) instanceof CommentRangeStart) {
            CommentRangeStart commentRangeStart = (CommentRangeStart) element;
            onCommentRangeStart(commentRangeStart);
        } else if (XmlUtils.unwrap(element) instanceof CommentRangeEnd) {
            CommentRangeEnd commentRangeEnd = (CommentRangeEnd) element;
            onCommentRangeEnd(commentRangeEnd);
        }
    }
}
 
Example #24
Source File: PStyle12PtInTableGridOverrideFalseTest.java    From docx4j-export-FO with Apache License 2.0 5 votes vote down vote up
@Test 
	public void testTblStyle_BasedOn_Normal12() throws Exception {
		
		// A style basedOn Normal is ignored where the font size comes from Normal
	
		WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage.createPackage();
		wordMLPackage.getMainDocumentPart().setContents(
				(Document)XmlUtils.unmarshalString(mdpXml_tblStyle) );
		wordMLPackage.getMainDocumentPart().getStyleDefinitionsPart().setContents(
				(Styles)XmlUtils.unmarshalString(styles_basedOn_Normal) );
		
		// Use our style!
		List<Object> xpathResults = wordMLPackage.getMainDocumentPart().getJAXBNodesViaXPath("//w:p", true);
		PPr ppr = Context.getWmlObjectFactory().createPPr();
		((P)xpathResults.get(0)).setPPr(ppr);
		PStyle ps = Context.getWmlObjectFactory().createPPrBasePStyle();
		ps.setVal("testStyle");
		ppr.setPStyle(ps);
		
		setSetting(wordMLPackage, OVERRIDE); 

		wordMLPackage.save(new File(System.getProperty("user.dir") + "/OUT_PStyleInTableTest.docx"));
		
		ParagraphStylesInTableFix.process(wordMLPackage);
		
//		// Revert style and save: 
//		ppr.setPStyle(ps); // doesn't work - wrong ref!
//		wordMLPackage.save(new File(System.getProperty("user.dir") + "/OUT_PStyleInTableTest.docx"));
		
		Style ours = null;
		for (Style s : wordMLPackage.getMainDocumentPart().getStyleDefinitionsPart().getContents().getStyle()) {
			if ("testStyle-TableGrid-BR".equals(s.getStyleId())) {
				ours = s;
				break;
			}
		}
		
//		Style s = getStyle(wordMLPackage, STYLE_NAME);
		Assert.assertTrue(ours.getRPr().getSz().getVal().intValue()==EXPECTED_RESULT); 
	}
 
Example #25
Source File: PStyle12PtInTableGridOverrideFalseTest.java    From docx4j-export-FO with Apache License 2.0 5 votes vote down vote up
@Test 
	public void testTblStyle_BasedOnNormal() throws Exception {
		
		// A style basedOn Normal is honoured, provided it (not Normal) contributes the font size
	
		WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage.createPackage();
		wordMLPackage.getMainDocumentPart().setContents(
				(Document)XmlUtils.unmarshalString(mdpXml_tblStyle) );
		wordMLPackage.getMainDocumentPart().getStyleDefinitionsPart().setContents(
				(Styles)XmlUtils.unmarshalString(styles_in_basedOn_Normal) );
		
		// Use our style!
		List<Object> xpathResults = wordMLPackage.getMainDocumentPart().getJAXBNodesViaXPath("//w:p", true);
		PPr ppr = Context.getWmlObjectFactory().createPPr();
		((P)xpathResults.get(0)).setPPr(ppr);
		PStyle ps = Context.getWmlObjectFactory().createPPrBasePStyle();
		ps.setVal("testStyle");
		ppr.setPStyle(ps);
		
		setSetting(wordMLPackage, OVERRIDE); 

		wordMLPackage.save(new File(System.getProperty("user.dir") + "/OUT_PStyleInTableTest.docx"));
		
		ParagraphStylesInTableFix.process(wordMLPackage);
		
//		// Revert style and save: 
//		ppr.setPStyle(ps); // doesn't work - wrong ref!
//		wordMLPackage.save(new File(System.getProperty("user.dir") + "/OUT_PStyleInTableTest.docx"));
		
		Style ours = null;
		for (Style s : wordMLPackage.getMainDocumentPart().getStyleDefinitionsPart().getContents().getStyle()) {
			if ("testStyle-TableGrid-BR".equals(s.getStyleId())) {
				ours = s;
				break;
			}
		}
		
//		Style s = getStyle(wordMLPackage, STYLE_NAME);
		Assert.assertTrue(ours.getRPr().getSz().getVal().intValue()==24); 
	}
 
Example #26
Source File: CreateBlockTest.java    From docx4j-export-FO with Apache License 2.0 5 votes vote down vote up
@Test
public void test() throws SAXException, IOException, TransformerException, InvalidFormatException {
	
	/* Here we want to test white space handling in 
	 * 	protected static DocumentFragment createBlock(WordprocessingMLPackage wmlPackage, RunFontSelector runFontSelector, NodeIterator childResults,
		boolean sdt, PPr pPrDirect, PPr pPr, RPr rPr, RPr rPrParagraphMark) 
		
		
	 */
	
	// We need NodeIterator, simulating the results from XSLT
	File f = new File("src/test/java/org/docx4j/convert/out/fo/nodes.fo");
	DocumentBuilder db = XmlUtils.getNewDocumentBuilder();
	Document doc = db.parse(f);
	NodeIterator childResults = XPathAPI.selectNodeIterator(doc, "/*");

	//System.out.println(childResults.nextNode().getNodeName());
	
	// Other params don't matter
	FOConversionContext context = null; 
	String pStyleVal = "styleX";
	boolean sdt = false;
	PPr pPrDirect = new PPr();
	PPr pPr = new PPr(); 
	RPr rPr = new RPr();
	RPr rPrParagraphMark  = new RPr();
	
	WordprocessingMLPackage wmlPackage = WordprocessingMLPackage.createPackage();
	RunFontSelector runFontSelector = FOConversionContext.createRunFontSelector(wmlPackage);
	
	DocumentFragment df = XsltFOFunctions.createBlock( wmlPackage, runFontSelector,  pStyleVal,  childResults,
			 sdt,  pPrDirect,  pPr,  rPr,  rPrParagraphMark);
	
	System.out.println(XmlUtils.w3CDomNodeToString(df));
	
}
 
Example #27
Source File: CoordinatesWalker.java    From docx-stamper with MIT License 5 votes vote down vote up
private void walkTableRow(TableRowCoordinates rowCoordinates) {
    onTableRow(rowCoordinates);
    int cellIndex = 0;
    for (Object rowContentElement : rowCoordinates.getRow().getContent()) {
        if (XmlUtils.unwrap(rowContentElement) instanceof Tc) {
            Tc cell = rowContentElement instanceof Tc ? (Tc) rowContentElement : (Tc) ((JAXBElement) rowContentElement).getValue();
            TableCellCoordinates cellCoordinates = new TableCellCoordinates(cell, cellIndex, rowCoordinates);
            walkTableCell(cellCoordinates);
        }
        cellIndex++;
    }
}
 
Example #28
Source File: PStyle12PtInTableGridOverrideTrueTest.java    From docx4j-export-FO with Apache License 2.0 5 votes vote down vote up
@Test 
	public void testTblStyle_BasedOn_Normal12() throws Exception {
		
		// Compat setting says Paragraph style overrides table style		
	
		WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage.createPackage();
		wordMLPackage.getMainDocumentPart().setContents(
				(Document)XmlUtils.unmarshalString(mdpXml_tblStyle) );
		wordMLPackage.getMainDocumentPart().getStyleDefinitionsPart().setContents(
				(Styles)XmlUtils.unmarshalString(styles_basedOn_Normal) );
		
		// Use our style!
		List<Object> xpathResults = wordMLPackage.getMainDocumentPart().getJAXBNodesViaXPath("//w:p", true);
		PPr ppr = Context.getWmlObjectFactory().createPPr();
		((P)xpathResults.get(0)).setPPr(ppr);
		PStyle ps = Context.getWmlObjectFactory().createPPrBasePStyle();
		ps.setVal("testStyle");
		ppr.setPStyle(ps);
		
		setSetting(wordMLPackage, OVERRIDE); 

		wordMLPackage.save(new File(System.getProperty("user.dir") + "/OUT_PStyleInTableTest.docx"));
		
		ParagraphStylesInTableFix.process(wordMLPackage);
		
//		// Revert style and save: 
//		ppr.setPStyle(ps); // doesn't work - wrong ref!
//		wordMLPackage.save(new File(System.getProperty("user.dir") + "/OUT_PStyleInTableTest.docx"));
		
		Style ours = null;
		for (Style s : wordMLPackage.getMainDocumentPart().getStyleDefinitionsPart().getContents().getStyle()) {
			if ("testStyle-TableGrid-BR".equals(s.getStyleId())) {
				ours = s;
				break;
			}
		}
		
//		Style s = getStyle(wordMLPackage, STYLE_NAME);
		Assert.assertTrue(ours.getRPr().getSz().getVal().intValue()==EXPECTED_RESULT); 
	}
 
Example #29
Source File: SampleDocumentGenerator.java    From docx4j-export-FO with 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 #30
Source File: PStyle12PtInTableGridOverrideTrueTest.java    From docx4j-export-FO with Apache License 2.0 5 votes vote down vote up
@Test 
	public void testTblStyle_BasedOnNormal() throws Exception {
		
		// Compat setting says Paragraph style overrides table style		
	
		WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage.createPackage();
		wordMLPackage.getMainDocumentPart().setContents(
				(Document)XmlUtils.unmarshalString(mdpXml_tblStyle) );
		wordMLPackage.getMainDocumentPart().getStyleDefinitionsPart().setContents(
				(Styles)XmlUtils.unmarshalString(styles_in_basedOn_Normal) );
		
		// Use our style!
		List<Object> xpathResults = wordMLPackage.getMainDocumentPart().getJAXBNodesViaXPath("//w:p", true);
		PPr ppr = Context.getWmlObjectFactory().createPPr();
		((P)xpathResults.get(0)).setPPr(ppr);
		PStyle ps = Context.getWmlObjectFactory().createPPrBasePStyle();
		ps.setVal("testStyle");
		ppr.setPStyle(ps);
		
		setSetting(wordMLPackage, OVERRIDE);  // table style should get overridden
	
		wordMLPackage.save(new File(System.getProperty("user.dir") + "/OUT_PStyleInTableTest.docx"));
		
		ParagraphStylesInTableFix.process(wordMLPackage);
		
//		// Revert style and save: 
//		ppr.setPStyle(ps); // doesn't work - wrong ref!
//		wordMLPackage.save(new File(System.getProperty("user.dir") + "/OUT_PStyleInTableTest.docx"));
		
		Style ours = null;
		for (Style s : wordMLPackage.getMainDocumentPart().getStyleDefinitionsPart().getContents().getStyle()) {
			if ("testStyle-TableGrid-BR".equals(s.getStyleId())) {
				ours = s;
				break;
			}
		}
		
//		Style s = getStyle(wordMLPackage, STYLE_NAME);
		Assert.assertTrue(ours.getRPr().getSz().getVal().intValue()==24); 
	}