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

The following examples show how to use org.docx4j.openpackaging.parts.WordprocessingML.MainDocumentPart. 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: docx4j-template   Source File: HtmlToDOCDemo.java    License: 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 2
/**
 * @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 VariableReplaceSAXHandler( this.getPlaceholderStart() , this.getPlaceholderEnd(), variables) );
        }
       // 返回WordprocessingMLPackage对象
	return FontMapperHolder.useFontMapper(wordMLPackage);
}
 
Example 3
/**
 * 变量替换方式实现(只能解决固定模板的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
/**
 * @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 5
/**
 * 变量替换方式实现(只能解决固定模板的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 6
Source Project: docx4j-template   Source File: Docx4jUtils.java    License: 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 Project: docx4j-template   Source File: WmlElementUtils.java    License: 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 8
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 9
Source Project: docx4j-template   Source File: Docx4j_工具类_S3_Test.java    License: 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 10
Source Project: OfficeProducer   Source File: DocxProducer.java    License: 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 11
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 12
Source Project: docx4j-template   Source File: Docx4J_例子2.java    License: 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 13
Source Project: docx4j-template   Source File: Docx4J_简单例子2.java    License: 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 14
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 15
Source Project: docx4j-template   Source File: Docx4J_简单例子2.java    License: 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 Project: OfficeProducer   Source File: DocxProducer.java    License: 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 Project: docx4j-template   Source File: Docx4J_简单例子.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 18
Source Project: docx4j-template   Source File: Docx4J_简单例子.java    License: 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 19
Source Project: TranskribusCore   Source File: DocxBuilder.java    License: 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 20
Source Project: TranskribusCore   Source File: DocxBuilder.java    License: 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 21
Source Project: yarg   Source File: HtmlContentInliner.java    License: Apache License 2.0 5 votes vote down vote up
public void inlineToDocx(WordprocessingMLPackage wordPackage, Text text, Object paramValue, Matcher matcher) {
    try {
        R run = (R) text.getParent();
        wordPackage.getContentTypeManager().addDefaultContentType("xhtml", "text/xhtml");
        MainDocumentPart mainDocumentPart = wordPackage.getMainDocumentPart();
        mainDocumentPart.addAltChunk(AltChunkType.Xhtml, paramValue.toString().getBytes(), run);
        text.setValue("");
    } catch (Exception e) {
        throw new ReportFormattingException("An error occurred while inserting html to docx file", e);
    }
}
 
Example 22
Source Project: docx4j-template   Source File: HtmlToDOCDemo.java    License: Apache License 2.0 5 votes vote down vote up
private static List<Object> convertToWmlObject(
		WordprocessingMLPackage wordMLPackage, String content)
		throws Docx4JException, JAXBException {
	MainDocumentPart document = wordMLPackage.getMainDocumentPart();
	//获取Jsoup参数
	String charsetName = Docx4jProperties.getProperty(Docx4jConstants.DOCX4J_CONVERT_OUT_WMLTEMPLATE_CHARSETNAME, Docx4jConstants.DEFAULT_CHARSETNAME );
	
	List<Object> wmlObjList = null;
	String templateString = XmlUtils.marshaltoString(document.getContents().getBody());
	System.out.println(templateString);
	Body templateBody = document.getContents().getBody();
	try {
		document.getContents().setBody(XmlUtils.deepCopy(templateBody));
		document.getContent().clear();
		Document doc = Jsoup.parse(content);
		doc.outputSettings().syntax(Document.OutputSettings.Syntax.xml).escapeMode(Entities.EscapeMode.xhtml);
		//XHTMLImporterImpl xhtmlImporter = new XHTMLImporterImpl(wordMLPackage);
		
		AlternativeFormatInputPart  part = document.addAltChunk(AltChunkType.Xhtml,doc.html().getBytes(Charset.forName(charsetName)));
		
		WordprocessingMLPackage tempPackage = document.convertAltChunks();
		File file = new File("d://temp.docx");
		tempPackage.save(file);
		wmlObjList = document.getContent();
		//part.getOwningRelationshipPart().getSourceP().get
		//wmlObjList = xhtmlImporter.convert(doc.html(), doc.baseUri());
	} finally {
		document.getContents().setBody(templateBody);
	}
	return wmlObjList;
}
 
Example 23
/**
 * @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);
           // 获取静态变量集合
           HashMap<String, String> staticMap = getStaticData(variables);
           // 替换普通变量  
           documentPart.variableReplace(staticMap);  
        }
       // 返回WordprocessingMLPackage对象
	return FontMapperHolder.useFontMapper(wordMLPackage);
}
 
Example 24
/**
 * 变量替换方式实现(只能解决固定模板的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);
           // 获取静态变量集合
           HashMap<String, String> staticMap = getStaticData(variables);
           // 替换普通变量  
           documentPart.variableReplace(staticMap);  
        }
       // 返回WordprocessingMLPackage对象
	return FontMapperHolder.useFontMapper(wordMLPackage);
}
 
Example 25
Source Project: docx4j-template   Source File: SampleDocument.java    License: Apache License 2.0 5 votes vote down vote up
static void addObject(MainDocumentPart wordDocumentPart, String template, String fontName ) throws JAXBException {
	
    HashMap substitution = new HashMap();
    substitution.put("fontname", fontName);
    Object o = XmlUtils.unmarshallFromTemplate(template, substitution);
    wordDocumentPart.addObject(o);    		    
	
}
 
Example 26
Source Project: docx4j-template   Source File: WMLPackageUtils.java    License: Apache License 2.0 5 votes vote down vote up
public static void replacePlaceholder(MainDocumentPart documentPart, String placeholder, String content ) { 
	// 获取文档对象中所有的Text类型对象
    List<Text> texts = WmlElementUtils.getTargetElements(documentPart, Text.class);  
   // 循环Text类型对象集合
    for (Text text : texts) {  
        Text textElement = (Text) text;  
        if (textElement.getValue().equals(placeholder)) {  
            textElement.setValue(content);  
        }  
    }  
}
 
Example 27
Source Project: docx4j-template   Source File: WmlElementUtils.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * @Description: 设置页面背景色
 */
public static void setDocumentBackGround(WordprocessingMLPackage wordPackage, ObjectFactory factory, String color)
        throws Exception {
    MainDocumentPart mdp = wordPackage.getMainDocumentPart();
    CTBackground bkground = mdp.getContents().getBackground();
    if (StringUtils.isNotBlank(color)) {
        if (bkground == null) {
            bkground = factory.createCTBackground();
            bkground.setColor(color);
        }
        mdp.getContents().setBackground(bkground);
    }
}
 
Example 28
public void extract(WordprocessingMLPackage wmlPackage,Writer out) throws Exception {
	MainDocumentPart documentPart = wmlPackage.getMainDocumentPart();		
	org.docx4j.wml.Document wmlDocumentEl = documentPart.getContents();
	TextUtils.extractText(wmlDocumentEl, out);
	//out.flush();
	//out.close();
}
 
Example 29
Source Project: docx4j-template   Source File: Docx4j_工具类_S3_Test.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * @Description: 设置页面背景色
 */
public void setDocumentBackGround(WordprocessingMLPackage wordPackage,
        ObjectFactory factory, String color) throws Exception {
    MainDocumentPart mdp = wordPackage.getMainDocumentPart();
    CTBackground bkground = mdp.getContents().getBackground();
    if (StringUtils.isNotBlank(color)) {
        if (bkground == null) {
            bkground = factory.createCTBackground();
            bkground.setColor(color);
        }
        mdp.getContents().setBackground(bkground);
    }
}
 
Example 30
Source Project: docx4j-export-FO   Source File: SampleDocumentGenerator.java    License: Apache License 2.0 5 votes vote down vote up
static void addObject(MainDocumentPart wordDocumentPart, String template, String fontName ) throws JAXBException {
	
    HashMap substitution = new HashMap();
    substitution.put("fontname", fontName);
    Object o = XmlUtils.unmarshallFromTemplate(template, substitution);
    wordDocumentPart.addObject(o);    		    
	
}