Java Code Examples for org.docx4j.openpackaging.packages.WordprocessingMLPackage

The following examples show how to use org.docx4j.openpackaging.packages.WordprocessingMLPackage. 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: docx-stamper   Source File: TernaryOperatorTest.java    License: MIT License 6 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 2
/**
 *  首先我们创建包和对象工厂, 因此在类的随处我们都可以使用它们. 然后我们创建一个表格并添加
 *  边框. 接下来我们创建一个表格行并在第一个域添加一些文本.
 *  对于第二个域, 我们用与前面一样的图片创建一个段落并添加进去. 最后把行添加到表格中, 并将
 *  表格添加到包中, 然后保存这个包.
 */
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 3
Source Project: docx4j-template   Source File: Docx4jTest.java    License: Apache License 2.0 6 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 4
Source Project: docx4j-template   Source File: Docx4j_工具类_S3_Test.java    License: 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 5
Source Project: docx4j-template   Source File: Docx4J_例子2.java    License: 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 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 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 8
Source Project: docx4j-export-FO   Source File: PStyleTableAbstract.java    License: 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 9
@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 10
/**
 *  创建一个带边框的表格并添加一行. 然后添加两个带内容的单元格并给定宽度.
 */
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 11
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 12
Source Project: docx-stamper   Source File: ConditionalDisplayOfParagraphsTest.java    License: 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 13
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 14
Source Project: docx4j-template   Source File: Docx4J_例子2.java    License: Apache License 2.0 6 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 15
Source Project: docx4j-template   Source File: Docx4J_例子2.java    License: 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 16
Source Project: docx-stamper   Source File: CommentUtilTest.java    License: 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 17
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 18
Source Project: docx4j-template   Source File: Docx4J_简单例子2.java    License: 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 19
Source Project: docx4j-template   Source File: Docx4J_例子2.java    License: 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
@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 21
Source Project: docx4j-template   Source File: Docx4J_简单例子2.java    License: Apache License 2.0 5 votes vote down vote up
public P createHeaderBlankP(WordprocessingMLPackage wordMLPackage,  
        ObjectFactory factory,  
        JcEnumeration jcEnumeration) throws Exception{  
    P p = factory.createP();  
    R run = factory.createR();  
    p.getContent().add(run);  
    PPr pPr = p.getPPr();  
    if (pPr == null) {  
        pPr = factory.createPPr();  
    }  
    Jc jc = pPr.getJc();  
    if (jc == null) {  
        jc = new Jc();  
    }  
    jc.setVal(jcEnumeration);  
    pPr.setJc(jc);  
      
    PBdr pBdr=pPr.getPBdr();  
    if(pBdr==null){  
        pBdr=factory.createPPrBasePBdr();  
    }  
    CTBorder value=new CTBorder();  
    value.setVal(STBorder.SINGLE);  
    value.setColor("000000");  
    value.setSpace(new BigInteger("0"));  
    value.setSz(new BigInteger("3"));  
    pBdr.setBetween(value);  
    pPr.setPBdr(pBdr);  
    p.setPPr(pPr);  
    setParagraphSpacing(factory, p, jcEnumeration, "0", "0");  
    return p;  
}
 
Example 22
Source Project: docx-stamper   Source File: ConditionalDisplayOfParagraphsTest.java    License: MIT License 5 votes vote down vote up
@Test
public void processorExpressionsInCommentsAreResolved() throws Docx4JException, IOException {
    NameContext context = new NameContext();
    context.setName("Homer");
    InputStream template = getClass().getResourceAsStream("ConditionalDisplayOfParagraphsTest.docx");
    WordprocessingMLPackage document = stampAndLoad(template, context);
    globalParagraphsAreRemoved(document);
    paragraphsInTableAreRemoved(document);
    paragraphsInNestedTablesAreRemoved(document);
}
 
Example 23
@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-TableNormal-BR".equals(s.getStyleId())) {
				ours = s;
				break;
			}
		}
		
//		Style s = getStyle(wordMLPackage, STYLE_NAME);
		Assert.assertTrue(ours.getRPr().getSz().getVal().intValue()==EXPECTED_RESULT); 
	}
 
Example 24
Source Project: docx4j-export-FO   Source File: PStyleTableAbstract.java    License: Apache License 2.0 5 votes vote down vote up
protected Style getStyle(WordprocessingMLPackage wordMLPackage, String stylename) throws Docx4JException {
	
	for (Style s : wordMLPackage.getMainDocumentPart().getStyleDefinitionsPart().getContents().getStyle()) {
		if (stylename.equals(s.getStyleId())) {
			return s;
		}
	}
	return null;
}
 
Example 25
public Comments addDocumentCommentsPart(  
        WordprocessingMLPackage wordMLPackage, ObjectFactory factory)  
        throws Exception {  
    CommentsPart cp = new CommentsPart();  
    wordMLPackage.getMainDocumentPart().addTargetPart(cp);  
    Comments comments = factory.createComments();  
    cp.setJaxbElement(comments);  
    return comments;  
}
 
Example 26
public WordprocessingMLPackageBuilder configDefaultFont(WordprocessingMLPackage wmlPackage,String fontName) throws Exception {
//设置文件默认字体
try {
	PhysicalFontUtils.setDefaultFont(wmlPackage, fontName);
} catch (Exception e) {
	// TODO Auto-generated catch block
	e.printStackTrace();
}
      //返回WordprocessingMLPackage对象
    	return this;
  }
 
Example 27
Source Project: docx4j-template   Source File: Docx4J_例子2.java    License: Apache License 2.0 5 votes vote down vote up
public void createTableTest(WordprocessingMLPackage wordMLPackage,
		MainDocumentPart t, ObjectFactory factory) throws Exception {
	RPr titleRpr = getRPr(factory, "宋体", "000000", "22", STHint.EAST_ASIA,
			true, false, false, false);
	RPr contentRpr = getRPr(factory, "宋体", "000000", "22",
			STHint.EAST_ASIA, false, false, false, false);
	Tbl table = factory.createTbl();
	addBorders(table, "2");

	double[] colWidthPercent = new double[] { 15, 20, 20, 20, 25 };// 百分比
	setTableGridCol(wordMLPackage, factory, table, 100, colWidthPercent);
	List<String> columnList = new ArrayList<String>();
	columnList.add("序号");
	columnList.add("姓名信息|姓甚|名谁");
	columnList.add("名刺信息|籍贯|营生");
	addTableTitleCell(factory, wordMLPackage, table, columnList, titleRpr,
			JcEnumeration.CENTER, true, "C6D9F1");

	for (int i = 0; i < 10; i++) {
		Tr contentRow = factory.createTr();
		addTableCell(factory, wordMLPackage, contentRow, i + "",
				contentRpr, JcEnumeration.CENTER, false, null);
		addTableCell(factory, wordMLPackage, contentRow, "无名氏", contentRpr,
				JcEnumeration.CENTER, false, null);
		addTableCell(factory, wordMLPackage, contentRow, "佚名", contentRpr,
				JcEnumeration.CENTER, false, null);
		addTableCell(factory, wordMLPackage, contentRow, "武林", contentRpr,
				JcEnumeration.CENTER, false, null);
		addTableCell(factory, wordMLPackage, contentRow, "吟诗赋曲",
				contentRpr, JcEnumeration.CENTER, false, null);
		table.getContent().add(contentRow);
	}
	setTableAlign(factory, table, JcEnumeration.CENTER);
	t.addObject(table);
}
 
Example 28
Source Project: docx4j-template   Source File: Docx4J_例子2.java    License: Apache License 2.0 5 votes vote down vote up
public Relationship createTextHeaderPart(
		WordprocessingMLPackage wordprocessingMLPackage,
		MainDocumentPart t, ObjectFactory factory, String content,
		boolean isUnderLine, String underLineSz, JcEnumeration jcEnumeration)
		throws Exception {
	HeaderPart headerPart = new HeaderPart();
	Relationship rel = t.addTargetPart(headerPart);
	headerPart.setJaxbElement(getTextHdr(wordprocessingMLPackage, factory,
			headerPart, content, isUnderLine, underLineSz, jcEnumeration));
	return rel;
}
 
Example 29
@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 30
Source Project: docx4j-template   Source File: AddingAnInlineImage.java    License: Apache License 2.0 5 votes vote down vote up
/**
 *  像往常一样, 我们创建了一个包(package)来容纳文档.
 *  然后我们创建了一个指向将要添加到文档的图片的文件对象.为了能够对图片做一些操作, 我们将它转换
 *  为字节数组. 最后我们将图片添加到包中并保存这个包(package).
 */
public static void main (String[] args) throws Exception {
    WordprocessingMLPackage  wordMLPackage = WordprocessingMLPackage.createPackage();
 
    File file = new File("src/main/resources/iProfsLogo.png");
    byte[] bytes = convertImageToByteArray(file);
    addImageToPackage(wordMLPackage, bytes);
 
    wordMLPackage.save(new java.io.File("src/main/files/HelloWord7.docx"));
}