org.docx4j.wml.P Java Examples

The following examples show how to use org.docx4j.wml.P. 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: 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 #2
Source File: WordprocessingMLPackageRender.java    From docx4j-template with Apache License 2.0 6 votes vote down vote up
public void addStyling(Tc tableCell, String content, boolean bold, String fontSize) {  
    P paragraph = factory.createP();  
   
    Text text = factory.createText();  
    text.setValue(content);  
   
    R run = factory.createR();  
    run.getContent().add(text);  
   
    paragraph.getContent().add(run);  
   
    RPr runProperties = factory.createRPr();  
    if (bold) {  
        addBoldStyle(runProperties);  
    }  
   
    if (fontSize != null && !fontSize.isEmpty()) {  
        setFontSize(runProperties, fontSize);  
    }  
   
    run.setRPr(runProperties);  
   
    tableCell.getContent().add(paragraph);  
}
 
Example #3
Source File: WmlElementUtils.java    From docx4j-template with Apache License 2.0 6 votes vote down vote up
/**
 * @Description: 设置段落边框样式
 */
public static void setParagraghBorders(P p, CTBorder topBorder, CTBorder bottomBorder, CTBorder leftBorder,
        CTBorder rightBorder) {
    PPr ppr = getPPr(p);
    PBdr pBdr = new PBdr();
    if (topBorder != null) {
        pBdr.setTop(topBorder);
    }
    if (bottomBorder != null) {
        pBdr.setBottom(bottomBorder);
    }
    if (leftBorder != null) {
        pBdr.setLeft(leftBorder);
    }
    if (rightBorder != null) {
        pBdr.setRight(rightBorder);
    }
    ppr.setPBdr(pBdr);
}
 
Example #4
Source File: ObjectDeleterTest.java    From docx-stamper with MIT License 6 votes vote down vote up
@Test
public void deletesCorrectParagraphsInTableCells() throws Docx4JException, IOException {
    InputStream template = getClass().getResourceAsStream("ObjectDeleterTest-paragraphsInTableCells.docx");
    WordprocessingMLPackage document = WordprocessingMLPackage.load(template);
    final List<ParagraphCoordinates> coordinates = getParagraphCoordinates(document);

    ObjectDeleter deleter = new ObjectDeleter(document);
    deleter.deleteParagraph(coordinates.get(1));
    deleter.deleteParagraph(coordinates.get(2));
    deleter.deleteParagraph(coordinates.get(4));
    deleter.deleteParagraph(coordinates.get(5));
    deleter.deleteParagraph(coordinates.get(8));
    deleter.deleteParagraph(coordinates.get(11));

    WordprocessingMLPackage savedDocument = saveAndLoadDocument(document);
    List<TableCellCoordinates> cellCoordinates = getTableCellCoordinats(savedDocument);

    Assert.assertEquals("0 This paragraph stays.", new ParagraphWrapper((P) cellCoordinates.get(0).getCell().getContent().get(0)).getText());
    Assert.assertEquals("", new ParagraphWrapper((P) cellCoordinates.get(1).getCell().getContent().get(0)).getText());
    Assert.assertEquals("3 This is the second paragraph.", new ParagraphWrapper((P) cellCoordinates.get(2).getCell().getContent().get(0)).getText());
    Assert.assertEquals("6 This is the fifth paragraph.", new ParagraphWrapper((P) cellCoordinates.get(2).getCell().getContent().get(1)).getText());
    Assert.assertEquals("7 This is the first paragraph.", new ParagraphWrapper((P) cellCoordinates.get(3).getCell().getContent().get(0)).getText());
    Assert.assertEquals("9 This is the third paragraph.", new ParagraphWrapper((P) cellCoordinates.get(3).getCell().getContent().get(1)).getText());
    Assert.assertEquals("10 This is the fourth paragraph.", new ParagraphWrapper((P) cellCoordinates.get(3).getCell().getContent().get(2)).getText());
}
 
Example #5
Source File: Docx4j_工具类_S3_Test.java    From docx4j-template with Apache License 2.0 6 votes vote down vote up
/**
 * @Description: 隐藏单元格内容
 */
public void setTcHidden(Tc tc, boolean hidden) {
    List<P> pList = getTcAllP(tc);
    for (P p : pList) {
        PPr ppr = getPPr(p);
        List<Object> objRList = getAllElementFromObject(p, R.class);
        if (objRList == null) {
            continue;
        }
        for (Object objR : objRList) {
            if (objR instanceof R) {
                R r = (R) objR;
                RPr rpr = getRPr(r);
                setRPrVanishStyle(rpr, hidden);
            }
        }
        setParaVanish(ppr, hidden);
    }
}
 
Example #6
Source File: Docx4J_简单例子.java    From docx4j-template with Apache License 2.0 6 votes vote down vote up
public Hdr getTextHdr(WordprocessingMLPackage wordprocessingMLPackage,
		ObjectFactory factory, Part sourcePart, String content,
		JcEnumeration jcEnumeration) throws Exception {
	Hdr hdr = factory.createHdr();
	P headP = factory.createP();
	Text text = factory.createText();
	text.setValue(content);
	R run = factory.createR();
	run.getContent().add(text);
	headP.getContent().add(run);

	PPr pPr = headP.getPPr();
	if (pPr == null) {
		pPr = factory.createPPr();
	}
	Jc jc = pPr.getJc();
	if (jc == null) {
		jc = new Jc();
	}
	jc.setVal(jcEnumeration);
	pPr.setJc(jc);
	headP.setPPr(pPr);
	hdr.getContent().add(headP);
	return hdr;
}
 
Example #7
Source File: DocxBuilder.java    From TranskribusCore with GNU General Public License v3.0 6 votes vote down vote up
private void addParagraph(String mdName, String mdValue, MainDocumentPart mdp, String style) {
		
		if (mdValue != null && !mdValue.equals("")){
			org.docx4j.wml.P  p = mdp.createStyledParagraphOfText(style, mdName + mdValue);
			
			mdp.addObject(p);
			
//			org.docx4j.wml.Text  t = factory.createText();
//			t.setValue(mdName + mdValue);
//			t.setSpace("preserve");
//					
//			org.docx4j.wml.R  run = factory.createR();
//			p.getContent().add(run);
//			run.getContent().add(t);
//			
//		    org.docx4j.wml.PPr  pPr = factory.createPPr();
//	        p.setPPr(pPr);
//	        		
//		    org.docx4j.wml.PPrBase.PStyle pStyle = factory.createPPrBasePStyle();
//		    pPr.setPStyle(pStyle);
//		    pStyle.setVal(style);
		}
		
	}
 
Example #8
Source File: WmlElementUtils.java    From docx4j-template with Apache License 2.0 6 votes vote down vote up
/**
 * @Description: 添加图片到段落
 */
public static void addImageToPara(WordprocessingMLPackage wordMLPackage, ObjectFactory factory, P paragraph,
        String filePath, String content, RPr rpr, String altText, int id1, int id2) throws Exception {
    R run = factory.createR();
    if (content != null) {
        Text text = factory.createText();
        text.setValue(content);
        text.setSpace("preserve");
        run.setRPr(rpr);
        run.getContent().add(text);
    }

    InputStream is = new FileInputStream(filePath);
    byte[] bytes = IOUtils.toByteArray(is);
    BinaryPartAbstractImage imagePart = BinaryPartAbstractImage.createImagePart(wordMLPackage, bytes);
    Inline inline = imagePart.createImageInline(filePath, altText, id1, id2, false);
    Drawing drawing = factory.createDrawing();
    drawing.getAnchorOrInline().add(inline);
    run.getContent().add(drawing);
    paragraph.getContent().add(run);
}
 
Example #9
Source File: WmlElementUtils.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 #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: ObjectDeleterTest.java    From docx-stamper with MIT License 6 votes vote down vote up
@Test
public void deletesCorrectGlobalParagraphs() throws Docx4JException, IOException {
    InputStream template = getClass().getResourceAsStream("ObjectDeleterTest-globalParagraphs.docx");
    WordprocessingMLPackage document = WordprocessingMLPackage.load(template);

    int index = 0;
    List<ParagraphCoordinates> coordinates = new ArrayList<>();
    for (Object contentElement : document.getMainDocumentPart().getContent()) {
        P paragraph = (P) contentElement;
        coordinates.add(new ParagraphCoordinates(paragraph, index));
        index++;
    }

    ObjectDeleter deleter = new ObjectDeleter(document);
    deleter.deleteParagraph(coordinates.get(0));
    deleter.deleteParagraph(coordinates.get(2));
    deleter.deleteParagraph(coordinates.get(3));

    WordprocessingMLPackage savedDocument = saveAndLoadDocument(document);
    Assert.assertEquals(2, savedDocument.getMainDocumentPart().getContent().size());
    Assert.assertEquals("This is the second paragraph.", new ParagraphWrapper((P) savedDocument.getMainDocumentPart().getContent().get(0)).getText());
    Assert.assertEquals("This is the fifth paragraph.", new ParagraphWrapper((P) savedDocument.getMainDocumentPart().getContent().get(1)).getText());
}
 
Example #12
Source File: Docx4J_简单例子2.java    From docx4j-template with Apache License 2.0 6 votes vote down vote up
public Ftr getTextFtr(WordprocessingMLPackage wordprocessingMLPackage,  
        ObjectFactory factory, Part sourcePart, String content,  
        JcEnumeration jcEnumeration) throws Exception {  
    Ftr ftr = factory.createFtr();  
    P footerP = factory.createP();  
    Text text = factory.createText();  
    text.setValue(content);  
    R run = factory.createR();  
    run.getContent().add(text);  
    footerP.getContent().add(run);  
  
    PPr pPr = footerP.getPPr();  
    if (pPr == null) {  
        pPr = factory.createPPr();  
    }  
    Jc jc = pPr.getJc();  
    if (jc == null) {  
        jc = new Jc();  
    }  
    jc.setVal(jcEnumeration);  
    pPr.setJc(jc);  
    footerP.setPPr(pPr);  
    ftr.getContent().add(footerP);  
    return ftr;  
}
 
Example #13
Source File: WmlElementUtils.java    From docx4j-template with Apache License 2.0 6 votes vote down vote up
/**
    * 插入图片
    * @param wPackage
    * @param bm
    * @param file
    * @throws Exception 
    */
public static void addImage(WordprocessingMLPackage wPackage, CTBookmark bm, String file) throws Exception {
	// 这儿可以对单个书签进行操作,也可以用一个map对所有的书签进行处理
	// 获取该书签的父级段落
	P p = (P) (bm.getParent());
	// R对象是匿名的复杂类型,然而我并不知道具体啥意思,估计这个要好好去看看ooxml才知道
	R run = factory.createR();
	// 读入图片并转化为字节数组,因为docx4j只能字节数组的方式插入图片
        byte[] bytes = null;//FileUtil.getByteFormBase64DataByImage(file);

        //	InputStream is = new FileInputStream;
       //	byte[] bytes = IOUtils.toByteArray(inputStream);
	//  byte[] bytes = FileUtil.getByteFormBase64DataByImage("");
	// 开始创建一个行内图片
	BinaryPartAbstractImage imagePart = BinaryPartAbstractImage.createImagePart(wPackage, bytes);
	// createImageInline函数的前四个参数我都没有找到具体啥意思,,,,
	// 最有一个是限制图片的宽度,缩放的依据
	Inline inline = imagePart.createImageInline(null, null, 0, 1, false, 0);
	// 获取该书签的父级段落
	// drawing理解为画布?
	Drawing drawing = factory.createDrawing();
	drawing.getAnchorOrInline().add(inline);
	run.getContent().add(drawing);
	p.getContent().add(run);
}
 
Example #14
Source File: UrlVisitor.java    From yarg with Apache License 2.0 6 votes vote down vote up
@Override
public List<Object> apply(Object o) {
    if (o instanceof P.Hyperlink) {
        P.Hyperlink hyperlink = (P.Hyperlink) o;
        try {
            Relationships contents = mainDocumentPart.getRelationshipsPart().getContents();
            List<Relationship> relationships = contents.getRelationship();
            for (Relationship relationship : relationships) {
                if (relationship.getId().equals(hyperlink.getId())) {
                    relationship.setTarget(docxFormatter.handleStringWithAliases(URLDecoder.decode(relationship.getTarget(), "UTF-8")));
                }
            }
        } catch (Exception e) {
            throw new RuntimeException("An error occurred while processing URL with aliases",e);
        }
    }
    return null;
}
 
Example #15
Source File: Docx4j_替换模板.java    From docx4j-template with Apache License 2.0 6 votes vote down vote up
/** 
 * 设置单元格内容 
 *  
 * @param tc 
 * @param content 
 */  
public static void setNewTcContent(Tc tc, String content) {  
    P p = factory.createP();  
    tc.getContent().add(p);  
    R run = factory.createR();  
    p.getContent().add(run);  
    if (content != null) {  
        String[] contentArr = content.split("\n");  
        Text text = factory.createText();  
        text.setSpace("preserve");  
        text.setValue(contentArr[0]);  
        run.getContent().add(text);  
  
        for (int i = 1, len = contentArr.length; i < len; i++) {  
            Br br = factory.createBr();  
            run.getContent().add(br);// 换行  
            text = factory.createText();  
            text.setSpace("preserve");  
            text.setValue(contentArr[i]);  
            run.getContent().add(text);  
        }  
    }  
}
 
Example #16
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 #17
Source File: Docx4J_简单例子2.java    From docx4j-template with Apache License 2.0 5 votes vote down vote up
public void addFieldBegin(ObjectFactory factory, P paragraph) {  
    R run = factory.createR();  
    FldChar fldchar = factory.createFldChar();  
    fldchar.setFldCharType(STFldCharType.BEGIN);  
    run.getContent().add(fldchar);  
    paragraph.getContent().add(run);  
}
 
Example #18
Source File: Docx4J_例子2.java    From docx4j-template with Apache License 2.0 5 votes vote down vote up
public void addTableCell(ObjectFactory factory,
		WordprocessingMLPackage wordMLPackage, Tr tableRow, String content,
		RPr rpr, JcEnumeration jcEnumeration, boolean hasBgColor,
		String backgroudColor) {
	Tc tableCell = factory.createTc();
	P p = factory.createP();
	setParagraphSpacing(factory, p, jcEnumeration, true, "0", "0", null,
			null, true, "240", STLineSpacingRule.AUTO);
	Text t = factory.createText();
	t.setValue(content);
	R run = factory.createR();
	// 设置表格内容字体样式
	run.setRPr(rpr);

	TcPr tcPr = tableCell.getTcPr();
	if (tcPr == null) {
		tcPr = factory.createTcPr();
	}

	CTVerticalJc valign = factory.createCTVerticalJc();
	valign.setVal(STVerticalJc.CENTER);
	tcPr.setVAlign(valign);

	run.getContent().add(t);
	p.getContent().add(run);
	tableCell.getContent().add(p);
	if (hasBgColor) {
		CTShd shd = tcPr.getShd();
		if (shd == null) {
			shd = factory.createCTShd();
		}
		shd.setColor("auto");
		shd.setFill(backgroudColor);
		tcPr.setShd(shd);
	}
	tableCell.setTcPr(tcPr);
	tableRow.getContent().add(tableCell);
}
 
Example #19
Source File: Docx4J_简单例子2.java    From docx4j-template with Apache License 2.0 5 votes vote down vote up
public void addPageNumberField(ObjectFactory factory, P paragraph) {  
    R run = factory.createR();  
    Text txt = new Text();  
    txt.setSpace("preserve");  
    txt.setValue("PAGE  \\* MERGEFORMAT ");  
    run.getContent().add(factory.createRInstrText(txt));  
    paragraph.getContent().add(run);  
}
 
Example #20
Source File: Docx4J_简单例子.java    From docx4j-template with Apache License 2.0 5 votes vote down vote up
public void addFieldBegin(ObjectFactory factory, P paragraph) {
	R run = factory.createR();
	FldChar fldchar = factory.createFldChar();
	fldchar.setFldCharType(STFldCharType.BEGIN);
	run.getContent().add(fldchar);
	paragraph.getContent().add(run);
}
 
Example #21
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); 
	}
 
Example #22
Source File: AddingPageNrToFooter.java    From docx4j-template with Apache License 2.0 5 votes vote down vote up
/**
 * Every fields needs to be delimited by complex field characters. This method
 * adds the delimiter that follows the actual field to the given paragraph.
 * @param paragraph
 */
private static void addFieldEnd(P paragraph) {
    FldChar fldcharend = factory.createFldChar();
    fldcharend.setFldCharType(STFldCharType.END);
    R run3 = factory.createR();
    run3.getContent().add(fldcharend);
    paragraph.getContent().add(run3);
}
 
Example #23
Source File: LineBreakReplacementTest.java    From docx-stamper with MIT License 5 votes vote down vote up
private void lineBreaksAreReplaced(WordprocessingMLPackage document) {
    P paragraph = (P) document.getMainDocumentPart().getContent().get(2);
    Assert.assertTrue(new ParagraphWrapper(paragraph).getText().contains("This paragraph should be"));
    Assert.assertTrue(new ParagraphWrapper(paragraph).getText().contains("split in"));
    Assert.assertTrue(new ParagraphWrapper(paragraph).getText().contains("three lines"));

    Assert.assertEquals(R.class, paragraph.getContent().get(1).getClass());
    Assert.assertEquals(Br.class, ((R)paragraph.getContent().get(1)).getContent().get(0).getClass());

    Assert.assertEquals(R.class, paragraph.getContent().get(3).getClass());
    Assert.assertEquals(Br.class, ((R)paragraph.getContent().get(3)).getContent().get(0).getClass());
}
 
Example #24
Source File: Docx4J_例子2.java    From docx4j-template with Apache License 2.0 5 votes vote down vote up
public P createImageParagraph(WordprocessingMLPackage wordMLPackage,
		ObjectFactory factory, P p, String fileName, String content,
		byte[] bytes, JcEnumeration jcEnumeration) throws Exception {
	BinaryPartAbstractImage imagePart = BinaryPartAbstractImage
			.createImagePart(wordMLPackage, bytes);
	Inline inline = imagePart.createImageInline(fileName, "这是图片", 1, 2,
			false);
	Text text = factory.createText();
	text.setValue(content);
	text.setSpace("preserve");
	R run = factory.createR();
	p.getContent().add(run);
	run.getContent().add(text);
	Drawing drawing = factory.createDrawing();
	run.getContent().add(drawing);
	drawing.getAnchorOrInline().add(inline);
	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);
	p.setPPr(pPr);
	setParagraphSpacing(factory, p, jcEnumeration, true, "0", "0", null,
			null, true, "240", STLineSpacingRule.AUTO);
	return p;
}
 
Example #25
Source File: AddingPageNrToFooter.java    From docx4j-template with Apache License 2.0 5 votes vote down vote up
/**
 * Adds a page break to the document.
 *
 * @param documentPart
 */
private static void addPageBreak(MainDocumentPart documentPart) {
    Br breakObj = new Br();
    breakObj.setType(STBrType.PAGE);
    P paragraph = factory.createP();
    paragraph.getContent().add(breakObj);
    documentPart.getJaxbElement().getBody().getContent().add(paragraph);
}
 
Example #26
Source File: PStyle11PtInTableOverrideFalseTest.java    From docx4j-export-FO with Apache License 2.0 5 votes vote down vote up
@Test 
	@Ignore
	public void testTblStyle_BasedOn_Normal11() throws Exception {
		
		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()==22); 
	}
 
Example #27
Source File: Docx4J_例子2.java    From docx4j-template with Apache License 2.0 5 votes vote down vote up
public void addPageNumberField(ObjectFactory factory, P paragraph) {
	R run = factory.createR();
	Text txt = new Text();
	txt.setSpace("preserve");
	txt.setValue("PAGE  \\* MERGEFORMAT ");
	run.getContent().add(factory.createRInstrText(txt));
	paragraph.getContent().add(run);
}
 
Example #28
Source File: Docx4J_例子2.java    From docx4j-template with Apache License 2.0 5 votes vote down vote up
public void addFieldEnd(ObjectFactory factory, P paragraph) {
	FldChar fldcharend = factory.createFldChar();
	fldcharend.setFldCharType(STFldCharType.END);
	R run3 = factory.createR();
	run3.getContent().add(fldcharend);
	paragraph.getContent().add(run3);
}
 
Example #29
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 #30
Source File: ParagraphUtils.java    From docx4j-template with Apache License 2.0 5 votes vote down vote up
public static P addInlineImageToParagraph(Inline inline) {
    // Now add the in-line image to a paragraph
    P paragraph = factory.createP();
    R run = factory.createR();
    paragraph.getContent().add(run);
    Drawing drawing = factory.createDrawing();
    run.getContent().add(drawing);
    drawing.getAnchorOrInline().add(inline);
    return paragraph;
}