org.docx4j.openpackaging.parts.WordprocessingML.MainDocumentPart Java Examples

The following examples show how to use org.docx4j.openpackaging.parts.WordprocessingML.MainDocumentPart. 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 7 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 #2
Source File: Docx4J_简单例子2.java    From docx4j-template with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {  
    Docx4J_简单例子 t = new Docx4J_简单例子();  
    WordprocessingMLPackage wordMLPackage = t  
            .createWordprocessingMLPackage();  
    MainDocumentPart mp = wordMLPackage.getMainDocumentPart();  
    ObjectFactory factory = Context.getWmlObjectFactory();  
    //图片页眉  
    //Relationship relationship =t.createHeaderPart(wordMLPackage, mp, factory);  
    //文字页眉  
    Relationship relationship =t.createTextHeaderPart(wordMLPackage, mp, factory, "我是页眉,多创造,少抄袭", JcEnumeration.CENTER);  
    t.createHeaderReference(wordMLPackage, mp, factory, relationship);  
      
    t.addParagraphTest(wordMLPackage, mp, factory);  
    t.addPageBreak(wordMLPackage, factory);  
      
    t.createNormalTableTest(wordMLPackage, mp, factory);  
    //页脚  
    relationship =t.createFooterPageNumPart(wordMLPackage, mp, factory);  
    t.createFooterReference(wordMLPackage, mp, factory, relationship);  
      
    t.saveWordPackage(wordMLPackage, new File(  
            "f:/saveFile/temp/s5_simple.docx"));  
}
 
Example #3
Source File: WordprocessingMLDocxSaxTemplate.java    From docx4j-template with Apache License 2.0 6 votes vote down vote up
/**
 * 变量替换方式实现(只能解决固定模板的word生成)
 * @param template :模板内容
 * @param variables :变量
 * @return {@link WordprocessingMLPackage} 对象
 * @throws Exception :异常对象
 */
@Override
public WordprocessingMLPackage process(InputStream template, Map<String, Object> variables) throws Exception {
	// Document loading (required)
	WordprocessingMLPackage wordMLPackage;
	if (template == null) {
		// Create a docx
		System.out.println("No imput path passed, creating dummy document");
		wordMLPackage = WordprocessingMLPackage.createPackage();
		SampleDocument.createContent(wordMLPackage.getMainDocumentPart());	
	} else {
		System.out.println("Loading file from InputStream");
		wordMLPackage = Docx4J.load(template);
	}
       if (null != variables && !variables.isEmpty()) {
       	// 替换变量并输出Word文档 
       	MainDocumentPart documentPart = wordMLPackage.getMainDocumentPart();
       	// 将${}里的内容结构层次替换为一层
       	VariablePrepare.prepare(wordMLPackage);
       	WMLPackageUtils.cleanDocumentPart(documentPart);
       	// 替换变量
       	documentPart.pipe( new VariableReplaceSAXHandler( this.getPlaceholderStart() , this.getPlaceholderEnd(), variables) );
        }
       // 返回WordprocessingMLPackage对象
	return FontMapperHolder.useFontMapper(wordMLPackage);
}
 
Example #4
Source File: DocxBuilder.java    From TranskribusCore with GNU General Public License v3.0 6 votes vote down vote up
private void getFormattedTextForLineElement(List<WordType> words, P p, MainDocumentPart mdp) throws Exception{
	
	int wordCount = 0;
	int nrWords = words.size();
	
	for (WordType word : words){
		getFormattedTextForShapeElement((ITrpShapeType) word, p, mdp);
		//add empty space after each word
		if (wordCount < nrWords-1){
			org.docx4j.wml.Text  t = factory.createText();
			t.setValue(" ");
			t.setSpace("preserve");
			
			org.docx4j.wml.R  run = factory.createR();
			p.getContent().add(run);
			run.getContent().add(t);
		}
		wordCount++;
	}

}
 
Example #5
Source File: HtmlToDOCDemo.java    From docx4j-template with Apache License 2.0 6 votes vote down vote up
public static void replaceRichText(WordprocessingMLPackage wordMLPackage, Map<String, String> richTextMap) throws Docx4JException, JAXBException {
	MainDocumentPart document = wordMLPackage.getMainDocumentPart();
	Map<String, List<Object>> textNodeMap = new HashMap<String, List<Object>>();
	findRichTextNode(textNodeMap, document.getContents().getBody(), null);
	Iterator<String> iterator = richTextMap.keySet().iterator();
	while (iterator.hasNext()) {
		String textTag = iterator.next();
		List<Object> textNodeList = textNodeMap.get(textTag);
		if (textNodeList != null && richTextMap.containsKey(textTag)) {
			List<Object> textObjList = convertToWmlObject(wordMLPackage, richTextMap.get(textTag));
			for (int i = 0, iSize = textNodeList.size(); i < iSize; i++) {
				Object nodeObject = textNodeList.get(i);
				if (nodeObject != null) {
					//setWmlPprSetting(textNodeList.get(i), textObjList);
					TraversalUtil.replaceChildren(nodeObject , textObjList);
				}
			}
		}
	}
}
 
Example #6
Source File: Docx4jUtils.java    From docx4j-template with Apache License 2.0 6 votes vote down vote up
private void insertDocx(MainDocumentPart main, byte[] bytes, int chunkId) {  
    try {  
        AlternativeFormatInputPart afiPart = new AlternativeFormatInputPart(new PartName("/part" + chunkId + ".docx"));  
        // afiPart.setContentType(new ContentType(CONTENT_TYPE));
        afiPart.setContentType(new ContentType(ContentTypes.APPLICATION_XML));
        afiPart.setBinaryData(bytes);  
        Relationship altChunkRel = main.addTargetPart(afiPart);  
  
        CTAltChunk chunk = Context.getWmlObjectFactory().createCTAltChunk();  
        chunk.setId(altChunkRel.getId());  
  
        main.addObject(chunk);  
    } catch (Exception e) {  
        e.printStackTrace();  
    }  
}
 
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: WordprocessingMLDocxStAXTemplate.java    From docx4j-template with Apache License 2.0 6 votes vote down vote up
/**
 * @param template :模板文件
 * @param variables :变量
 * @return {@link WordprocessingMLPackage} 对象
 * @throws Exception :异常对象
 */
@Override
public WordprocessingMLPackage process(File template, Map<String, Object> variables) throws Exception{
	// Document loading (required)
	WordprocessingMLPackage wordMLPackage;
	if (template == null || !template.exists() || !template.isFile() ) {
		// Create a docx
		System.out.println("No imput path passed, creating dummy document");
		wordMLPackage = WordprocessingMLPackage.createPackage();
		SampleDocument.createContent(wordMLPackage.getMainDocumentPart());	
	} else {
		System.out.println("Loading file from " + template.getAbsolutePath());
		wordMLPackage = Docx4J.load(template);
	}
	if (null != variables && !variables.isEmpty()) {
       	// 替换变量并输出Word文档 
       	MainDocumentPart documentPart = wordMLPackage.getMainDocumentPart();  
       	// 将${}里的内容结构层次替换为一层
       	VariablePrepare.prepare(wordMLPackage);
       	WMLPackageUtils.cleanDocumentPart(documentPart);
       	// 替换变量
       	documentPart.pipe( new VariableReplaceSaTXHandler( this.getPlaceholderStart() , this.getPlaceholderEnd(), variables) );
        }
       // 返回WordprocessingMLPackage对象
	return FontMapperHolder.useFontMapper(wordMLPackage);
}
 
Example #9
Source File: WordprocessingMLDocxStAXTemplate.java    From docx4j-template with Apache License 2.0 6 votes vote down vote up
/**
 * 变量替换方式实现(只能解决固定模板的word生成)
 * @param template :模板内容
 * @param variables :变量
 * @return {@link WordprocessingMLPackage} 对象
 * @throws Exception :异常对象
 */
@Override
public WordprocessingMLPackage process(InputStream template, Map<String, Object> variables) throws Exception {
	// Document loading (required)
	WordprocessingMLPackage wordMLPackage;
	if (template == null) {
		// Create a docx
		System.out.println("No imput path passed, creating dummy document");
		wordMLPackage = WordprocessingMLPackage.createPackage();
		SampleDocument.createContent(wordMLPackage.getMainDocumentPart());	
	} else {
		System.out.println("Loading file from InputStream");
		wordMLPackage = Docx4J.load(template);
	}
       if (null != variables && !variables.isEmpty()) {
       	// 替换变量并输出Word文档 
       	MainDocumentPart documentPart = wordMLPackage.getMainDocumentPart();
       	// 将${}里的内容结构层次替换为一层
       	VariablePrepare.prepare(wordMLPackage);
       	WMLPackageUtils.cleanDocumentPart(documentPart);
       	// 替换变量
       	documentPart.pipe( new VariableReplaceSaTXHandler( this.getPlaceholderStart() , this.getPlaceholderEnd(), variables) );
        }
       // 返回WordprocessingMLPackage对象
	return FontMapperHolder.useFontMapper(wordMLPackage);
}
 
Example #10
Source File: Docx4J_简单例子.java    From docx4j-template with Apache License 2.0 6 votes vote down vote up
public void createFooterReference(
		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);
	}
	FooterReference footerReference = factory.createFooterReference();
	footerReference.setId(relationship.getId());
	footerReference.setType(HdrFtrRef.DEFAULT);
	sectPr.getEGHdrFtrReferences().add(footerReference);
}
 
Example #11
Source File: WmlElementUtils.java    From docx4j-template with Apache License 2.0 6 votes vote down vote up
/**
 * @Description:得到所有表格
 */
public static List<Tbl> getAllTbl(WordprocessingMLPackage wordMLPackage) {
    MainDocumentPart mainDocPart = wordMLPackage.getMainDocumentPart();
    List<Object> objList = getAllElementFromObject(mainDocPart, Tbl.class);
    if (objList == null) {
        return null;
    }
    List<Tbl> tblList = new ArrayList<Tbl>();
    for (Object obj : objList) {
        if (obj instanceof Tbl) {
            Tbl tbl = (Tbl) obj;
            tblList.add(tbl);
        }
    }
    return tblList;
}
 
Example #12
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 #13
Source File: Docx4J_例子2.java    From docx4j-template with Apache License 2.0 6 votes vote down vote up
public void createFooterReference(
		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);
	}
	FooterReference footerReference = factory.createFooterReference();
	footerReference.setId(relationship.getId());
	footerReference.setType(HdrFtrRef.DEFAULT);
	sectPr.getEGHdrFtrReferences().add(footerReference);
}
 
Example #14
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 #15
Source File: Docx4J_简单例子2.java    From docx4j-template with Apache License 2.0 6 votes vote down vote up
public void createFooterReference(  
        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);  
    }  
    FooterReference footerReference = factory.createFooterReference();  
    footerReference.setId(relationship.getId());  
    footerReference.setType(HdrFtrRef.DEFAULT);  
    sectPr.getEGHdrFtrReferences().add(footerReference);  
}
 
Example #16
Source File: DocxProducer.java    From OfficeProducer with Apache License 2.0 6 votes vote down vote up
/**
 * 根据字符串参数替换段落
 *
 * @param documentPart
 * @param paragraphParameters
 */
private static void replaceParagraph(MainDocumentPart documentPart, HashMap<String, String> paragraphParameters) throws JAXBException, Docx4JException {
    //List<Object> tables = getAllElementFromObject(documentPart, Tbl.class);
    /*for (Map.Entry<String, String> entries : paragraphParameters.entrySet()) {
        final Tbl table = getTemplateTable(tables, entries.getKey());
        final List<Object> allElementFromObject = getAllElementFromObject(table, P.class);
        final P p = (P) allElementFromObject.get(1);
        appendParaRContent(p, entries.getValue());
    }*/
    final List<Object> allElementFromObject = getAllElementFromObject(documentPart, P.class);
    //final P p = (P) allElementFromObject.get(22);

    for (Object paragraph : allElementFromObject) {
        final P para = (P) paragraph;
        if (!isNullOrEmpty(para.getContent())) {
            final List<Object> content = para.getContent();
            final String stringFromContent = getStringFromContent(content);
            final String s = paragraphParameters.get(stringFromContent);
            if (s != null) {
                appendParaRContent(para, s);
            }
        }
    }
}
 
Example #17
Source File: DocxProducer.java    From OfficeProducer with Apache License 2.0 6 votes vote down vote up
/**
 * 创建Docx的主方法
 *
 * @param templatePath        模板docx路径
 * @param parameters          参数和值
 * @param paragraphParameters 段落参数
 * @param imageParameters     书签和图片
 * @return
 */
private static WordprocessingMLPackage CreateWordprocessingMLPackageFromTemplate(String templatePath,
                                                                                 HashMap<String, String> parameters,
                                                                                 HashMap<String, String> paragraphParameters,
                                                                                 HashMap<String, String> imageParameters)
        throws Exception {
    @Cleanup InputStream docxStream = DocxProducer.class.getResourceAsStream(templatePath);
    WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage.load(docxStream);
    MainDocumentPart documentPart = wordMLPackage.getMainDocumentPart();

    //第一步 替换字符参数
    if (parameters != null) {
        replaceParameters(documentPart, parameters);
    }

    //第二步 替换段落
    if (paragraphParameters != null) {
        replaceParagraph(documentPart, paragraphParameters);
    }

    //第三步 插入图片
    if (imageParameters != null) {
        replaceBookMarkWithImage(wordMLPackage, documentPart, imageParameters);
    }
    return wordMLPackage;
}
 
Example #18
Source File: Docx4j_工具类_S3_Test.java    From docx4j-template with Apache License 2.0 6 votes vote down vote up
/**
 * @Description:得到所有表格
 */
public List<Tbl> getAllTbl(WordprocessingMLPackage wordMLPackage) {
    MainDocumentPart mainDocPart = wordMLPackage.getMainDocumentPart();
    List<Object> objList = getAllElementFromObject(mainDocPart, Tbl.class);
    if (objList == null) {
        return null;
    }
    List<Tbl> tblList = new ArrayList<Tbl>();
    for (Object obj : objList) {
        if (obj instanceof Tbl) {
            Tbl tbl = (Tbl) obj;
            tblList.add(tbl);
        }
    }
    return tblList;
}
 
Example #19
Source File: Docx4J_简单例子.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 #20
Source File: Docx4J_简单例子2.java    From docx4j-template with Apache License 2.0 5 votes vote down vote up
public void addPageBreak(WordprocessingMLPackage wordMLPackage,  
        ObjectFactory factory) {  
    MainDocumentPart documentPart = wordMLPackage.getMainDocumentPart();  
    Br breakObj = new Br();  
    breakObj.setType(STBrType.PAGE);  
    P paragraph = factory.createP();  
    paragraph.getContent().add(breakObj);  
    documentPart.addObject(paragraph);  
}
 
Example #21
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,  
        JcEnumeration jcEnumeration) throws Exception {  
    FooterPart footerPart = new FooterPart();  
    Relationship rel = t.addTargetPart(footerPart);  
    footerPart.setJaxbElement(getTextFtr(wordprocessingMLPackage, factory,  
            footerPart, content, jcEnumeration));  
    return rel;  
}
 
Example #22
Source File: MSOUtils.java    From document-management-system with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Generate sample docx
 */
public static void generateSample(int paragraphs, OutputStream os) throws Exception {
	WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage.createPackage();
	MainDocumentPart mdp = wordMLPackage.getMainDocumentPart();
	LoremIpsum li = new LoremIpsum();

	for (int i = 0; i < paragraphs; i++) {
		mdp.addParagraphOfText(li.getParagraphs());
	}

	wordMLPackage.save(os);
}
 
Example #23
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 #24
Source File: WordToTextRenditionProvider.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);

		MainDocumentPart documentPart = pkg.getMainDocumentPart();

		org.docx4j.wml.Document wmlDocumentEl = (org.docx4j.wml.Document) documentPart
				.getJaxbElement();

		OutputStream os = new FileOutputStream("/tmp/temp.txt");
		Writer out = new OutputStreamWriter(os);

		TextUtils.extractText(wmlDocumentEl, out);
		out.close();

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

		return new FileInputStream("/tmp/temp.txt");

	}
	catch (Exception e) {
		e.printStackTrace();
	}

	return null;
}
 
Example #25
Source File: Docx4J_简单例子2.java    From docx4j-template with Apache License 2.0 5 votes vote down vote up
public Relationship createFooterPageNumPart(  
        WordprocessingMLPackage wordprocessingMLPackage,  
        MainDocumentPart t, ObjectFactory factory) throws Exception {  
    FooterPart footerPart = new FooterPart();  
    footerPart.setPackage(wordprocessingMLPackage);  
    footerPart.setJaxbElement(createFooterWithPageNr(factory));  
    return t.addTargetPart(footerPart);  
}
 
Example #26
Source File: MSOUtils.java    From document-management-system with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Replace text
 *
 * See also http://www.docx4java.org/forums/docx-java-f6/best-approach-to-search-replace-in-a-template-merge-t1040.html
 */
public static void replaceText(InputStream input, HashMap<String, String> model, OutputStream output) throws Docx4JException,
		JAXBException, IOException {
	log.info("replaceText({}, {}, {})", new Object[]{input, model, output});
	WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage.load(input);
	MainDocumentPart documentPart = wordMLPackage.getMainDocumentPart();

	for (final Map.Entry<String, String> entry : model.entrySet()) {
		new TraversalUtil(documentPart, new TraversalUtil.CallbackImpl() {
			@Override
			public List<Object> apply(Object child) {
				if (child instanceof org.docx4j.wml.Text) {
					org.docx4j.wml.Text t = (org.docx4j.wml.Text) child;

					if (t.getValue().contains(entry.getKey())) {
						t.setValue(t.getValue().replaceAll(entry.getKey(), entry.getValue()));
					}
				}

				return null;
			}
		});
	}

	// Save it
	wordMLPackage.save(output);
	log.info("replaceText: void");
}
 
Example #27
Source File: AddingAPageBreak.java    From docx4j-template with Apache License 2.0 5 votes vote down vote up
/**
 * 向文档添加一个换行符
 */
private static void addPageBreak() {
    MainDocumentPart documentPart = wordMLPackage.getMainDocumentPart();
 
    Br breakObj = new Br();
    breakObj.setType(STBrType.PAGE);
 
    P paragraph = factory.createP();
    paragraph.getContent().add(breakObj);
    documentPart.getJaxbElement().getBody().getContent().add(paragraph);
}
 
Example #28
Source File: AddingTableOfContent.java    From docx4j-template with Apache License 2.0 5 votes vote down vote up
/**
 *  首先我们创建对象工厂和包并从包中抽出文档部件. 然后我们添加目录表, 后面跟着一些带有分类
 *  标题样式的段落. 最后我们保存包.
 */
public static void main(String[] args) throws Docx4JException {
    factory = Context.getWmlObjectFactory();
    WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage.createPackage();
    MainDocumentPart documentPart = wordMLPackage.getMainDocumentPart();
 
    addTableOfContent(documentPart);
 
    documentPart.addStyledParagraphOfText("Heading1", "Hello 1");
    documentPart.addStyledParagraphOfText("Heading2", "Hello 2");
    documentPart.addStyledParagraphOfText("Heading3", "Hello 3");
    documentPart.addStyledParagraphOfText("Heading1", "Hello 1");
 
    wordMLPackage.save(new File("src/main/files/HelloWord10.docx"));
}
 
Example #29
Source File: Docx4J_简单例子.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,
		JcEnumeration jcEnumeration) throws Exception {
	FooterPart footerPart = new FooterPart();
	Relationship rel = t.addTargetPart(footerPart);
	footerPart.setJaxbElement(getTextFtr(wordprocessingMLPackage, factory,
			footerPart, content, jcEnumeration));
	return rel;
}
 
Example #30
Source File: Docx4J_简单例子.java    From docx4j-template with Apache License 2.0 5 votes vote down vote up
public Relationship createTextHeaderPart(
		WordprocessingMLPackage wordprocessingMLPackage,
		MainDocumentPart t, ObjectFactory factory, String content,
		JcEnumeration jcEnumeration) throws Exception {
	HeaderPart headerPart = new HeaderPart();
	Relationship rel = t.addTargetPart(headerPart);
	headerPart.setJaxbElement(getTextHdr(wordprocessingMLPackage, factory,
			headerPart, content, jcEnumeration));
	return rel;
}