Java Code Examples for org.docx4j.openpackaging.packages.WordprocessingMLPackage#save()

The following examples show how to use org.docx4j.openpackaging.packages.WordprocessingMLPackage#save() . 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: PStyle12PtInTableNormalOverrideTrueTest.java    From docx4j-export-FO with Apache License 2.0 6 votes vote down vote up
@Test 
	public void testTblStyle_AllSilent() throws Exception {
		
		// Result is to use the implicit 10pt		
	
		WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage.createPackage();
		wordMLPackage.getMainDocumentPart().setContents(
				(Document)XmlUtils.unmarshalString(mdpXml_tblStyle) );
		wordMLPackage.getMainDocumentPart().getStyleDefinitionsPart().setContents(
				(Styles)XmlUtils.unmarshalString(styles_no_font_sz) );

		setSetting(wordMLPackage, OVERRIDE);  // table style should get overridden
		
		wordMLPackage.save(new File(System.getProperty("user.dir") + "/OUT_PStyleInTableTest.docx"));
		
		// NB PropertyResolver puts 10pt in DocDefaults, if nothing is specified!
		
		ParagraphStylesInTableFix.process(wordMLPackage);
		
		Style s = getStyle(wordMLPackage, getStyleName());
		this.assertSz(s, 20);
//		Assert.assertTrue(s.getRPr().getSz().getVal().intValue()==20); 
	}
 
Example 2
Source File: DocxProducer.java    From OfficeProducer with Apache License 2.0 6 votes vote down vote up
/**
 * 创建Docx并加密,返回InputStream
 *
 * @param templatePath    模板docx路径
 * @param parameters      参数和值
 * @param imageParameters 书签和图片
 * @return
 */
public static InputStream CreateEncryptDocxStreamFromTemplate(String templatePath,
                                                              HashMap<String, String> parameters,
                                                              HashMap<String, String> paragraphParameters,
                                                              HashMap<String, String> imageParameters,
                                                              String passWord)
        throws Exception {
    WordprocessingMLPackage wordMLPackage = CreateWordprocessingMLPackageFromTemplate(templatePath, parameters, paragraphParameters, imageParameters);

    //加密
    ProtectDocument protection = new ProtectDocument(wordMLPackage);
    protection.restrictEditing(STDocProtect.READ_ONLY, passWord);

    ByteArrayOutputStream baos = new ByteArrayOutputStream();

    wordMLPackage.save(baos);

    ByteArrayDataSource bads =
            new ByteArrayDataSource(baos.toByteArray(), "application/vnd.openxmlformats-officedocument.wordprocessingml.document");
    return bads.getInputStream();

}
 
Example 3
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 4
Source File: Docx4j_创建表格_S5_Test.java    From docx4j-template with Apache License 2.0 5 votes vote down vote up
public void testDocx4jCreateTable() throws Exception {  
    boolean landscape = false;  
    WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage  
            .createPackage(PageSizePaper.A4, landscape);  
    ObjectFactory factory = Context.getWmlObjectFactory();  
    setPageMargins(wordMLPackage, factory);  
    String imgFilePath = "f:/saveFile/tmp/2sql日志.jpg";  
    Tbl table = createTableWithContent(wordMLPackage, factory, imgFilePath);  
    wordMLPackage.getMainDocumentPart().addObject(table);  
    wordMLPackage.save(new File("f:/saveFile/temp/sys_"  
            + System.currentTimeMillis() + ".docx"));  
}
 
Example 5
Source File: HtmlToDOCDemo.java    From docx4j-template with 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 6
Source File: PStyle11PtInTableOverrideTrueTest.java    From docx4j-export-FO with Apache License 2.0 5 votes vote down vote up
@Test 
	public void testTblStyle_AllSilent() throws Exception {
	
		WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage.createPackage();
		wordMLPackage.getMainDocumentPart().setContents(
				(Document)XmlUtils.unmarshalString(mdpXml_tblStyle) );
		wordMLPackage.getMainDocumentPart().getStyleDefinitionsPart().setContents(
				(Styles)XmlUtils.unmarshalString(styles_no_font_sz) );
		
//		// NB createVirtualStylesForDocDefaults() puts 10pt there, if nothing is specified!
//		// So we need to delete that!
//		wordMLPackage.getMainDocumentPart().getStyleDefinitionsPart().createVirtualStylesForDocDefaults();
//		Style dd = wordMLPackage.getMainDocumentPart().getStyleDefinitionsPart().getStyleById("DocDefaults");
//		dd.getRPr().setSz(null);
//		dd.getRPr().setSzCs(null);
		
		setSetting(wordMLPackage, OVERRIDE);  // table style should get overridden
	
		wordMLPackage.save(new File(System.getProperty("user.dir") + "/OUT_PStyleInTableTest.docx"));
		
		ParagraphStylesInTableFix.process(wordMLPackage);
		
		Style s = getStyle(wordMLPackage, getStyleName());
		//Assert.assertTrue(s.getRPr().getSz().getVal().intValue()==40); 		
		
		if (s==null) {
			log.warn("missing style " + getStyleName());
			Assert.fail("missing style " + getStyleName());
		} else {		
			this.assertSz(s, 40);
		}		
		
		
	}
 
Example 7
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 8
Source File: PStyle11PtInTableOverrideTrueTest.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()==EXPECTED_RESULT); 
	}
 
Example 9
Source File: TextBoxTest.java    From docx4j-export-FO with Apache License 2.0 5 votes vote down vote up
private static void execute(WordprocessingMLPackage wordMLPackage) throws Docx4JException, IOException {
	
   	// Pretty print the main document part
	System.out.println(
			XmlUtils.marshaltoString(wordMLPackage.getMainDocumentPart().getJaxbElement(), true, true) );
	
	// Optionally save it
	if (save) {
		String filename = System.getProperty("user.dir") + "/OUT_CreateWordprocessingMLDocument.docx";
		wordMLPackage.save(new File(filename) );
		System.out.println("Saved " + filename);
	}
	
	// FO
	if (fo) {
		
		OutputStream baos = new ByteArrayOutputStream();
		Exporter<FOSettings> exporter = FOExporterVisitor.getInstance();
		FOSettings settings = new FOSettings();
		settings.setWmlPackage(wordMLPackage);
		settings.setApacheFopMime(FOSettings.INTERNAL_FO_MIME);
		exporter.export(settings, baos);
		
		System.out.println( ((ByteArrayOutputStream) baos).toString("UTF-8"));
		
	} else {
		
		Docx4J.toPDF(wordMLPackage, 
				FileUtils.openOutputStream(new File(System.getProperty("user.dir") + "/OUT_textbox.pdf")));
		
	}		
}
 
Example 10
Source File: PStyle12PtInTableGridOverrideTrueTest.java    From docx4j-export-FO with Apache License 2.0 5 votes vote down vote up
@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 11
Source File: WmlElementUtils.java    From docx4j-template with Apache License 2.0 4 votes vote down vote up
/**
 * @Description:保存WordprocessingMLPackage
 */
public void saveWordPackage(WordprocessingMLPackage wordPackage, File file) throws Exception {
    wordPackage.save(file);
}
 
Example 12
Source File: Docx4j_创建批注_S3_Test.java    From docx4j-template with Apache License 2.0 4 votes vote down vote up
public void saveWordPackage(WordprocessingMLPackage wordPackage, File file)  
        throws Exception {  
    wordPackage.save(file);  
}
 
Example 13
Source File: Docx4J_简单例子.java    From docx4j-template with Apache License 2.0 4 votes vote down vote up
public void saveWordPackage(WordprocessingMLPackage wordPackage, File file)
		throws Exception {
	wordPackage.save(file);
}
 
Example 14
Source File: WordprocessingMLDocxStAXTemplate_Test.java    From docx4j-template with Apache License 2.0 4 votes vote down vote up
@Test
public void test() throws Exception {
	Map<String, Object> variables = new HashMap<String, Object>();
	
	variables.put("title", "变量替换测试");
	variables.put("content", "测试效果不错");
	
	Map<String, String> map = new HashMap<>();
	map.put("title", "Ognl Expression 测试! ");
	variables.put("map", map);
	
	File sourceDocx = new java.io.File("src/test/resources/tpl/template.docx");
	File outputDocx = new java.io.File("src/test/resources/output/docxTemplate_output3.docx");

	WordprocessingMLPackage wmlPackage = docxTemplate.process(sourceDocx, variables);
	wmlPackage.save(outputDocx);
	
	
}
 
Example 15
Source File: PStyle12PtInTableNormalOverrideFalseTest.java    From docx4j-export-FO with Apache License 2.0 4 votes vote down vote up
@Test 
	public void testTblStyle_BasedOn_Normal12() throws Exception {
		
		// A style basedOn Normal is ignored where the font size comes from Normal
	
		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-TableNormal-BR".equals(s.getStyleId())) {
				ours = s;
				break;
			}
		}
		
//		Style s = getStyle(wordMLPackage, STYLE_NAME);
		assertSz(ours, EXPECTED_RESULT);

	}
 
Example 16
Source File: WordprocessingMLThymeleafTemplate_Test.java    From docx4j-template with Apache License 2.0 3 votes vote down vote up
@Test
public void test() throws Exception {
	
	variables.put("title", "变量替换测试");
	variables.put("content", "测试效果不错");
	
	WordprocessingMLPackage wordMLPackage = thymeleafTemplate.process("/tpl/thymeleaf.tpl", variables);
	
	File outputDocx = new java.io.File("src/test/resources/output/thymeleafTemplate_output.docx");
	wordMLPackage.save(outputDocx);
	
}
 
Example 17
Source File: WordprocessingMLFreemarkerTemplate_Test.java    From docx4j-template with Apache License 2.0 3 votes vote down vote up
@Test
public void test() throws Exception {
	
	
	variables.put("title", "变量替换测试");
	variables.put("content", "测试效果不错");
	
	WordprocessingMLPackage wordMLPackage = freemarkerTemplate.process("freemarker.tpl", variables);
	
	File outputDocx = new java.io.File("src/test/resources/output/freemarkerTemplate_output.docx");
	wordMLPackage.save(outputDocx);
	
}
 
Example 18
Source File: WordprocessingMLRythmTemplate_Test.java    From docx4j-template with Apache License 2.0 3 votes vote down vote up
@Test
public void test() throws Exception {
	
	variables.put("title", "变量替换测试");
	variables.put("content", "测试效果不错");
	
	WordprocessingMLPackage wordMLPackage = rythmTemplate.process("/tpl/rythm.tpl", variables);
	
	File outputDocx = new java.io.File("src/test/resources/output/rythmTemplate_output.docx");
	wordMLPackage.save(outputDocx);
	
}
 
Example 19
Source File: WordprocessingMLHttlTemplate_Test.java    From docx4j-template with Apache License 2.0 3 votes vote down vote up
@Test
public void test() throws Exception {
	
	
	variables.put("title", "变量替换测试");
	variables.put("content", "测试效果不错");
	
	WordprocessingMLPackage wordMLPackage = httlTemplate.process("httl.tpl", variables);
	
	File outputDocx = new java.io.File("src/test/resources/output/httlTemplate_output.docx");
	wordMLPackage.save(outputDocx);
	
}
 
Example 20
Source File: WordprocessingMLVelocityTemplate_Test.java    From docx4j-template with Apache License 2.0 3 votes vote down vote up
@Test
public void test() throws Exception {
	
	variables.put("title", "变量替换测试");
	variables.put("content", "测试效果不错");
	
	WordprocessingMLPackage wordMLPackage = velocityTemplate.process("/tpl/rythm.tpl", variables);
	
	File outputDocx = new java.io.File("src/test/resources/output/velocityTemplate_output.docx");
	wordMLPackage.save(outputDocx);
	
}