org.docx4j.openpackaging.packages.WordprocessingMLPackage Java Examples

The following examples show how to use org.docx4j.openpackaging.packages.WordprocessingMLPackage. 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: Docx4J_例子2.java    From docx4j-template with Apache License 2.0 10 votes vote down vote up
public Ftr getFtr(WordprocessingMLPackage wordprocessingMLPackage,
		ObjectFactory factory, Part sourcePart, boolean isUnderLine,
		String underLineSz) throws Exception {
	Ftr ftr = factory.createFtr();
	File file = new File("f:/saveFile/tmp/xxt.jpg");
	java.io.InputStream is = new java.io.FileInputStream(file);
	ftr.getContent().add(
			newImage(wordprocessingMLPackage, factory, sourcePart,
					BufferUtil.getBytesFromInputStream(is), "filename",
					"这是页脚", 1, 2, isUnderLine, underLineSz,
					JcEnumeration.CENTER));
	if (isUnderLine) {
		ftr.getContent().add(
				createHeaderBlankP(wordprocessingMLPackage, factory,
						underLineSz, JcEnumeration.CENTER));
	}
	return ftr;
}
 
Example #2
Source File: TernaryOperatorTest.java    From docx-stamper with MIT License 8 votes vote down vote up
@Test
public void test2() throws IOException, Docx4JException {
    NameContext context = new NameContext();
    context.setName("Homer");
    InputStream template = getClass().getResourceAsStream("TernaryOperatorTest2.docx");
    WordprocessingMLPackage document = stampAndLoad(template, context);

    P firstParagraph = (P) document.getMainDocumentPart().getContent().get(1);
    Assert.assertEquals("Text before replacement ", new ParagraphWrapper(firstParagraph).getText());

    P secondParagraph = (P) document.getMainDocumentPart().getContent().get(2);
    Assert.assertEquals("replacement Text after", new ParagraphWrapper(secondParagraph).getText());

    P thirdParagraph = (P) document.getMainDocumentPart().getContent().get(3);
    Assert.assertEquals("Text before replacement Text after", new ParagraphWrapper(thirdParagraph).getText());
}
 
Example #3
Source File: AddingAnInlineImageToTable.java    From docx4j-template with Apache License 2.0 7 votes vote down vote up
/**
 *  首先我们创建包和对象工厂, 因此在类的随处我们都可以使用它们. 然后我们创建一个表格并添加
 *  边框. 接下来我们创建一个表格行并在第一个域添加一些文本.
 *  对于第二个域, 我们用与前面一样的图片创建一个段落并添加进去. 最后把行添加到表格中, 并将
 *  表格添加到包中, 然后保存这个包.
 */
public static void main (String[] args) throws Exception {
    wordMLPackage = WordprocessingMLPackage.createPackage();
    factory = Context.getWmlObjectFactory();
 
    Tbl table = factory.createTbl();
    addBorders(table);
 
    Tr tr = factory.createTr();
 
    P paragraphOfText = wordMLPackage.getMainDocumentPart().createParagraphOfText("Field 1");
    addTableCell(tr, paragraphOfText);
 
    File file = new File("src/main/resources/iProfsLogo.png");
    P paragraphWithImage = addInlineImageToParagraph(createInlineImage(file));
    addTableCell(tr, paragraphWithImage);
 
    table.getContent().add(tr);
 
    wordMLPackage.getMainDocumentPart().addObject(table);
    wordMLPackage.save(new java.io.File("src/main/files/HelloWord8.docx"));
}
 
Example #4
Source File: Docx4jTest.java    From docx4j-template with Apache License 2.0 7 votes vote down vote up
/**
 * 创建包含图片的内容
 *
 * @param word
 * @param sourcePart
 * @param imageFilePath
 * @return
 * @throws Exception
 */
public static P newImage(WordprocessingMLPackage word,
                         Part sourcePart,
                         String imageFilePath) throws Exception {
    BinaryPartAbstractImage imagePart = BinaryPartAbstractImage
            .createImagePart(word, sourcePart, new File(imageFilePath));
    //随机数ID
    int id = (int) (Math.random() * 10000);
    //这里的id不重复即可
    Inline inline = imagePart.createImageInline("image", "image", id, id * 2, false);

    Drawing drawing = factory.createDrawing();
    drawing.getAnchorOrInline().add(inline);

    R r = factory.createR();
    r.getContent().add(drawing);

    P p = factory.createP();
    p.getContent().add(r);

    return p;
}
 
Example #5
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 #6
Source File: Docx4j_工具类_S3_Test.java    From docx4j-template with Apache License 2.0 6 votes vote down vote up
/**
 * @Description: 设置行号
 * @param distance
 *            :距正文距离 1厘米=567
 * @param start
 *            :起始编号(0开始)
 * @param countBy
 *            :行号间隔
 * @param restartType
 *            :STLineNumberRestart.CONTINUOUS(continuous连续编号)<br/>
 *            STLineNumberRestart.NEW_PAGE(每页重新编号)<br/>
 *            STLineNumberRestart.NEW_SECTION(每节重新编号)
 */
public void setDocInNumType(WordprocessingMLPackage wordPackage,
        String countBy, String distance, String start,
        STLineNumberRestart restartType) {
    SectPr sectPr = getDocSectPr(wordPackage);
    CTLineNumber lnNumType = sectPr.getLnNumType();
    if (lnNumType == null) {
        lnNumType = new CTLineNumber();
        sectPr.setLnNumType(lnNumType);
    }
    if (StringUtils.isNotBlank(countBy)) {
        lnNumType.setCountBy(new BigInteger(countBy));
    }
    if (StringUtils.isNotBlank(distance)) {
        lnNumType.setDistance(new BigInteger(distance));
    }
    if (StringUtils.isNotBlank(start)) {
        lnNumType.setStart(new BigInteger(start));
    }
    if (restartType != null) {
        lnNumType.setRestart(restartType);
    }
}
 
Example #7
Source File: Docx4J_例子2.java    From docx4j-template with Apache License 2.0 6 votes vote down vote up
public void createHeaderReference(
		WordprocessingMLPackage wordprocessingMLPackage,
		MainDocumentPart t, ObjectFactory factory, Relationship relationship)
		throws InvalidFormatException {
	List<SectionWrapper> sections = wordprocessingMLPackage
			.getDocumentModel().getSections();
	SectPr sectPr = sections.get(sections.size() - 1).getSectPr();
	// There is always a section wrapper, but it might not contain a sectPr
	if (sectPr == null) {
		sectPr = factory.createSectPr();
		t.addObject(sectPr);
		sections.get(sections.size() - 1).setSectPr(sectPr);
	}
	HeaderReference headerReference = factory.createHeaderReference();
	headerReference.setId(relationship.getId());
	headerReference.setType(HdrFtrRef.DEFAULT);
	sectPr.getEGHdrFtrReferences().add(headerReference);
}
 
Example #8
Source File: Docx4j_创建表格_S5_Test.java    From docx4j-template with Apache License 2.0 6 votes vote down vote up
public P newImage(WordprocessingMLPackage wordMLPackage,  
        ObjectFactory factory, byte[] bytes, String filenameHint,  
        String altText, int id1, int id2, long cx) throws Exception {  
    BinaryPartAbstractImage imagePart = BinaryPartAbstractImage  
            .createImagePart(wordMLPackage, bytes);  
    Inline inline = imagePart.createImageInline(filenameHint, altText, id1,  
            id2, cx, false);  
    // Now add the inline in w:p/w:r/w:drawing  
    P p = factory.createP();  
    R run = factory.createR();  
    p.getContent().add(run);  
    Drawing drawing = factory.createDrawing();  
    run.getContent().add(drawing);  
    drawing.getAnchorOrInline().add(inline);  
    return p;  
}
 
Example #9
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 #10
Source File: Docx4j_工具类_S3_Test.java    From docx4j-template with Apache License 2.0 6 votes vote down vote up
/**
 * @Description: 只删除单独的段落,不包括表格内或其他内的段落
 */
public boolean removeParaByIndex(WordprocessingMLPackage wordMLPackage,
        int index) {
    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++) {
        if (objList.get(i) instanceof P) {
            k++;
            if (k == index) {
                wordMLPackage.getMainDocumentPart().getContent().remove(i);
                flag = true;
                break;
            }
        }
    }
    return flag;
}
 
Example #11
Source File: PStyleTableAbstract.java    From docx4j-export-FO with Apache License 2.0 6 votes vote down vote up
protected void setSetting(WordprocessingMLPackage wmlPackage, boolean val) throws Docx4JException {
	
		DocumentSettingsPart dsp = wmlPackage.getMainDocumentPart().getDocumentSettingsPart();
		if (dsp==null) {
			dsp = new DocumentSettingsPart();
			wmlPackage.getMainDocumentPart().addTargetPart(dsp);
			
			dsp.setContents( Context.getWmlObjectFactory().createCTSettings() );
		} 

		if (val) {
			dsp.setWordCompatSetting("overrideTableStyleFontSizeAndJustification", "1");
		} else {
			dsp.setWordCompatSetting("overrideTableStyleFontSizeAndJustification", "0");				
		}
}
 
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: SettingColumnWidthForTable.java    From docx4j-template with Apache License 2.0 6 votes vote down vote up
/**
 *  创建一个带边框的表格并添加一行. 然后添加两个带内容的单元格并给定宽度.
 */
public static void main (String[] args) throws Docx4JException {
    wordMLPackage = WordprocessingMLPackage.createPackage();
    factory = Context.getWmlObjectFactory();
 
    Tbl table = factory.createTbl();
    addBorders(table);
 
    Tr tr = factory.createTr();
 
    addTableCellWithWidth(tr, "Field 1", 2500);
    addTableCellWithWidth(tr, "Field 2", 0);
 
    table.getContent().add(tr);
 
    wordMLPackage.getMainDocumentPart().addObject(table);
    wordMLPackage.save(new java.io.File("src/main/HelloWord133.docx") );
}
 
Example #14
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 #15
Source File: CommentUtilTest.java    From docx-stamper with MIT License 6 votes vote down vote up
@Test
public void onlyParagraphsWithCommentRangeStartAreCommented() throws Docx4JException {
    WordprocessingMLPackage document = loadDocument("CommentUtilTest.docx");

    P p1 = (P) document.getMainDocumentPart().getContent().get(0);
    P p2 = (P) document.getMainDocumentPart().getContent().get(1);
    P p3 = (P) document.getMainDocumentPart().getContent().get(3);
    P p4 = (P) document.getMainDocumentPart().getContent().get(4);
    P p5 = (P) document.getMainDocumentPart().getContent().get(5);

    Assert.assertNull(CommentUtil.getCommentFor(p1, document));
    Assert.assertEquals("Comment for paragraph 2.", CommentUtil.getCommentStringFor(p2, document));
    Assert.assertEquals("Comment for paragraph 3.", CommentUtil.getCommentStringFor(p3, document));
    Assert.assertNull(CommentUtil.getCommentFor(p4, document));
    Assert.assertNull(CommentUtil.getCommentFor(p5, document));
}
 
Example #16
Source File: Docx4J_例子2.java    From docx4j-template with Apache License 2.0 6 votes vote down vote up
public Hdr getHdr(WordprocessingMLPackage wordprocessingMLPackage,
		ObjectFactory factory, Part sourcePart, boolean isUnderLine,
		String underLineSize) throws Exception {
	Hdr hdr = factory.createHdr();
	File file = new File("f:/saveFile/tmp/xxt.jpg");
	java.io.InputStream is = new java.io.FileInputStream(file);
	hdr.getContent().add(
			newImage(wordprocessingMLPackage, factory, sourcePart,
					BufferUtil.getBytesFromInputStream(is), "filename",
					"这是页眉部分", 1, 2, isUnderLine, underLineSize,
					JcEnumeration.CENTER));
	if (isUnderLine) {
		hdr.getContent().add(
				createHeaderBlankP(wordprocessingMLPackage, factory,
						underLineSize, JcEnumeration.CENTER));
	}
	return hdr;
}
 
Example #17
Source File: ConditionalDisplayOfParagraphsTest.java    From docx-stamper with MIT License 6 votes vote down vote up
private void paragraphsInNestedTablesAreRemoved(WordprocessingMLPackage document) {
    final List<Tbl> tables = new ArrayList<>();
    CoordinatesWalker walker = new BaseCoordinatesWalker(document) {
        @Override
        protected void onTable(TableCoordinates tableCoordinates) {
            tables.add(tableCoordinates.getTable());
        }
    };
    walker.walk();

    Tbl nestedTable = tables.get(1);
    Tc cell = (Tc) ((JAXBElement) ((Tr) nestedTable.getContent().get(1)).getContent().get(0)).getValue();
    P p1 = (P) cell.getContent().get(0);

    Assert.assertEquals(1, cell.getContent().size());
    Assert.assertEquals("This paragraph stays untouched.", new ParagraphWrapper(p1).getText());
}
 
Example #18
Source File: WordToHtmlRenditionProvider.java    From spring-content with Apache License 2.0 5 votes vote down vote up
@Override
public InputStream convert(InputStream fromInputSource, String toMimeType) {
	try {
		WordprocessingMLPackage pkg = WordprocessingMLPackage.load(fromInputSource);

		// Refresh the values of DOCPROPERTY fields
		FieldUpdater updater = new FieldUpdater(pkg);
		updater.update(true);

		AbstractHtmlExporter exporter = new HtmlExporterNG2();
		HTMLSettings htmlSettings = Docx4J.createHTMLSettings();
		htmlSettings.setImageDirPath("/tmp/sample-docx.html_files");
		htmlSettings.setImageTargetUri("/tmp/_files");
		htmlSettings.setWmlPackage(pkg);

		Docx4jProperties.setProperty("docx4j.Convert.Out.HTML.OutputMethodXML", true);

		OutputStream os = new FileOutputStream("/tmp/temp.html");
		Docx4J.toHTML(htmlSettings, os, Docx4J.FLAG_EXPORT_PREFER_XSL);
		IOUtils.closeQuietly(os);

		if (pkg.getMainDocumentPart().getFontTablePart() != null) {
			pkg.getMainDocumentPart().getFontTablePart()
					.deleteEmbeddedFontTempFiles();
		}
		// This would also do it, via finalize() methods
		htmlSettings = null;
		pkg = null;

		return new FileInputStream("/tmp/temp.html");
	}
	catch (Exception e) {

	}

	return null;
}
 
Example #19
Source File: Docx4J_例子2.java    From docx4j-template with Apache License 2.0 5 votes vote down vote up
public Relationship createTextFooterPart(
		WordprocessingMLPackage wordprocessingMLPackage,
		MainDocumentPart t, ObjectFactory factory, String content,
		boolean isUnderLine, String underLineSz, JcEnumeration jcEnumeration)
		throws Exception {
	FooterPart footerPart = new FooterPart();
	Relationship rel = t.addTargetPart(footerPart);
	footerPart.setJaxbElement(getTextFtr(wordprocessingMLPackage, factory,
			footerPart, content, isUnderLine, underLineSz, jcEnumeration));
	return rel;
}
 
Example #20
Source File: Docx4j_工具类_S3_Test.java    From docx4j-template with Apache License 2.0 5 votes vote down vote up
/**
 * @Description:设置word 垂直对齐方式(Word默认方式都是"顶端对齐")
 */
public void setDocVAlign(WordprocessingMLPackage wordPackage,
        STVerticalJc valignType) {
    if (valignType != null) {
        SectPr sectPr = getDocSectPr(wordPackage);
        CTVerticalJc valign = sectPr.getVAlign();
        if (valign == null) {
            valign = new CTVerticalJc();
            sectPr.setVAlign(valign);
        }
        valign.setVal(valignType);
    }
}
 
Example #21
Source File: Docx4J_简单例子2.java    From docx4j-template with Apache License 2.0 5 votes vote down vote up
public Hdr getHdr(WordprocessingMLPackage wordprocessingMLPackage,  
        ObjectFactory factory, Part sourcePart) throws Exception {  
    Hdr hdr = factory.createHdr();  
    File file = new File("f:/saveFile/tmp/xxt.jpg");  
    java.io.InputStream is = new java.io.FileInputStream(file);  
    hdr.getContent().add(  
            newImage(wordprocessingMLPackage, factory, sourcePart,  
                    BufferUtil.getBytesFromInputStream(is), "filename",  
                    "这是页眉部分", 1, 2, JcEnumeration.CENTER));  
    hdr.getContent().add(createHeaderBlankP(wordprocessingMLPackage, factory,JcEnumeration.CENTER));  
    return hdr;  
}
 
Example #22
Source File: Docx4J_简单例子2.java    From docx4j-template with Apache License 2.0 5 votes vote down vote up
public Relationship createFooterPart(  
        WordprocessingMLPackage wordprocessingMLPackage,  
        MainDocumentPart t, ObjectFactory factory) throws Exception {  
    FooterPart footerPart = new FooterPart();  
    Relationship rel = t.addTargetPart(footerPart);  
    footerPart.setJaxbElement(getFtr(wordprocessingMLPackage, factory,  
            footerPart));  
    return rel;  
}
 
Example #23
Source File: WmlElementUtils.java    From docx4j-template with Apache License 2.0 5 votes vote down vote up
/**
 * @Description:创建表格(默认水平居中,垂直居中)
 */
public static Tbl createTable(WordprocessingMLPackage wordPackage, int rowNum, int colsNum) throws Exception {
    colsNum = Math.max(1, colsNum);
    rowNum = Math.max(1, rowNum);
    int widthTwips = getWritableWidth(wordPackage);
    int colWidth = widthTwips / colsNum;
    int[] widthArr = new int[colsNum];
    for (int i = 0; i < colsNum; i++) {
        widthArr[i] = colWidth;
    }
    return createTable(rowNum, colsNum, widthArr);
}
 
Example #24
Source File: PhysicalFontUtils.java    From docx4j-template with Apache License 2.0 5 votes vote down vote up
public static void setDefaultFont(WordprocessingMLPackage wmlPackage,String fontName) throws Docx4JException {
    //设置文件默认字体
    RFonts rfonts = Context.getWmlObjectFactory().createRFonts(); 
    rfonts.setAsciiTheme(null);
    rfonts.setAscii(fontName);
    rfonts.setHAnsi(fontName);
    rfonts.setEastAsia(fontName);
    RPr rpr = wmlPackage.getMainDocumentPart().getPropertyResolver().getDocumentDefaultRPr();
    rpr.setRFonts(rfonts);
}
 
Example #25
Source File: ConditionalDisplayOfParagraphsTest.java    From docx-stamper with MIT License 5 votes vote down vote up
@Test
public void unresolvedInlineProcessorExpressionsAreRemoved() throws Docx4JException, IOException {
    NameContext context = new NameContext();
    context.setName("Bart");
    InputStream template = getClass().getResourceAsStream("ConditionalDisplayOfParagraphsWithoutCommentTest.docx");
    WordprocessingMLPackage document = stampAndLoad(template, context);
    globalInlineProcessorExpressionIsRemoved(document);
}
 
Example #26
Source File: PStyle12PtInTableNormalOverrideFalseTest.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-TableNormal-BR".equals(s.getStyleId())) {
				ours = s;
				break;
			}
		}
		
//		Style s = getStyle(wordMLPackage, STYLE_NAME);
		Assert.assertTrue(ours.getRPr().getSz().getVal().intValue()==EXPECTED_RESULT); 
	}
 
Example #27
Source File: WordprocessingMLPackageBuilder.java    From docx4j-template with Apache License 2.0 5 votes vote down vote up
public WordprocessingMLPackage buildWhithXhtmlFragment(String xhtml,boolean altChunk) throws Exception {
/*	
 * 	根据docx4j.properties配置文件中:
 * 	docx4j.PageSize = A4
 * 	docx4j.PageOrientationLandscape = true
 * 	创建默认的WordProcessingML package
 */
		WordprocessingMLPackage wmlPackage = WordprocessingMLPackage.createPackage();
//返回WordprocessingMLPackage对象
return buildWhithXhtmlFragment(wmlPackage, xhtml, altChunk);
  }
 
Example #28
Source File: PStyle11PtInTableOverrideTrueTest.java    From docx4j-export-FO with Apache License 2.0 5 votes vote down vote up
@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 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);
		
		setSetting(wordMLPackage, OVERRIDE);  // table style should get overridden
	
		wordMLPackage.save(new File(System.getProperty("user.dir") + "/OUT_PStyleInTableTest.docx"));
		
		ParagraphStylesInTableFix.process(wordMLPackage);
		
		Style s = getStyle(wordMLPackage, getStyleName());
		//Assert.assertTrue(s.getRPr().getSz().getVal().intValue()==40); 		
		
		if (s==null) {
			log.warn("missing style " + getStyleName());
			Assert.fail("missing style " + getStyleName());
		} else {		
			this.assertSz(s, 40);
		}		
		
		
	}
 
Example #29
Source File: PStyle12PtInTableGridOverrideTrueTest.java    From docx4j-export-FO with Apache License 2.0 5 votes vote down vote up
@Test
//@Ignore
public void testTblStyle_P12() throws Exception {
	
	WordprocessingMLPackage wordMLPackage = test(mdpXml_direct_12pt, styles_no_font_sz, 40);
	
	//wordMLPackage.save(new File(System.getProperty("user.dir") + "/OUT_PStyleInTableTest.docx"));
	
	/* In this case, our result correctly preserves the direct rPr formatting
	 * (so the contents of Normal-TableGrid-BR is irrelevant)
	 * 
        <w:tc>
          <w:p>
            <w:pPr>
              <w:pStyle w:val="Normal-TableGrid-BR"/>
            </w:pPr>
            <w:r>
              <w:rPr>
                <w:sz w:val="24"/>
                <w:szCs w:val="24"/>
              </w:rPr>
              <w:t xml:space="preserve">some latin text here </w:t>
            </w:r>
          </w:p>
        </w:tc>
        */
	
	List<Object> xpathResults = wordMLPackage.getMainDocumentPart().getJAXBNodesViaXPath("//w:rPr", true);
	RPr rPr = ((RPr)xpathResults.get(0));
	Assert.assertTrue(rPr.getSz().getVal().intValue()==24); 

	
}
 
Example #30
Source File: WmlElementUtils.java    From docx4j-template with Apache License 2.0 5 votes vote down vote up
/**
 * @Description:设置文字方向 tbRl 垂直
 */
public static void setDocTextDirection(WordprocessingMLPackage wordPackage, String textDirection) {
    if (StringUtils.isNotBlank(textDirection)) {
        SectPr sectPr = getDocSectPr(wordPackage);
        TextDirection textDir = sectPr.getTextDirection();
        if (textDir == null) {
            textDir = new TextDirection();
            sectPr.setTextDirection(textDir);
        }
        textDir.setVal(textDirection);
    }
}