Java Code Examples for org.docx4j.openpackaging.exceptions.Docx4JException

The following examples show how to use org.docx4j.openpackaging.exceptions.Docx4JException. 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
Source Project: docx4j-template   Source File: WmlElementUtils.java    License: Apache License 2.0 6 votes vote down vote up
public static void replaceTable(String[] placeholders, List<Map<String, String>> textToAdd,  
           WordprocessingMLPackage template) throws Docx4JException, JAXBException {  
    List<Tbl> tables = getTargetElements(template.getMainDocumentPart(), Tbl.class);  
  
    // 1. find the table  
    Tbl tempTable = getTable(tables, placeholders[0]);  
    List<Tr> rows = getTargetElements(tempTable, Tr.class);  
  
    // first row is header, second row is content  
    if (rows.size() == 2) {  
    	
        // this is our template row  
        Tr templateRow = (Tr) rows.get(1);  
  
        for (Map<String, String> replacements : textToAdd) {  
            // 2 and 3 are done in this method  
            addRowToTable(tempTable, templateRow, replacements);  
        }  
  
        // 4. remove the template row  
        tempTable.getContent().remove(templateRow);  
    }  
}
 
Example 3
Source Project: docx-stamper   Source File: TernaryOperatorTest.java    License: MIT License 6 votes vote down vote up
@Test
public void test2() throws IOException, Docx4JException {
    NameContext context = new NameContext();
    context.setName("Homer");
    InputStream template = getClass().getResourceAsStream("TernaryOperatorTest2.docx");
    WordprocessingMLPackage document = stampAndLoad(template, context);

    P firstParagraph = (P) document.getMainDocumentPart().getContent().get(1);
    Assert.assertEquals("Text before replacement ", new ParagraphWrapper(firstParagraph).getText());

    P secondParagraph = (P) document.getMainDocumentPart().getContent().get(2);
    Assert.assertEquals("replacement Text after", new ParagraphWrapper(secondParagraph).getText());

    P thirdParagraph = (P) document.getMainDocumentPart().getContent().get(3);
    Assert.assertEquals("Text before replacement Text after", new ParagraphWrapper(thirdParagraph).getText());
}
 
Example 4
public static void writeToStream(WordprocessingMLPackage wmlPackage,OutputStream output) throws IOException, Docx4JException {
	Assert.notNull(wmlPackage, " wmlPackage is not specified!");
	Assert.notNull(output, " output is not specified!");
	InputStream input = null;
	try {
		//Document对象
		MainDocumentPart document = wmlPackage.getMainDocumentPart();	
		//Document XML
		String documentXML = XmlUtils.marshaltoString(wmlPackage);
		//转成字节输入流
		input = IOUtils.toBufferedInputStream(new ByteArrayInputStream(documentXML.getBytes()));
		//输出模板
		IOUtils.copy(input, output);
	} finally {
		IOUtils.closeQuietly(input);
	}
}
 
Example 5
Source Project: docx4j-template   Source File: ChangingTheStyleSheet.java    License: Apache License 2.0 6 votes vote down vote up
/**
 *  First we create the package, then we alter the style sheet and add some
 *  styled paragraphs. Finally we save the package.
 */
public static void main (String[] args) throws Docx4JException {
    wordMLPackage = WordprocessingMLPackage.createPackage();
    alterStyleSheet();
 
    wordMLPackage.getMainDocumentPart().addStyledParagraphOfText("Title",
        "Hello World! This title is now in Arial.");
    wordMLPackage.getMainDocumentPart().addStyledParagraphOfText("Subtitle",
        "Subtitle, this subtitle is now Arial too");
    wordMLPackage.getMainDocumentPart().addStyledParagraphOfText("Heading1",
        "As is Heading1");
    wordMLPackage.getMainDocumentPart().addStyledParagraphOfText("Heading2",
        "Heading2 is now Arial, no longer bold and has an underline " +
        "and fontsize 12");
    wordMLPackage.getMainDocumentPart().addStyledParagraphOfText("Heading3",
        "Heading3 is now Arial");
    wordMLPackage.getMainDocumentPart().addStyledParagraphOfText("Normal",
        "And normal text has changed to Arial and fontsize 10");
 
    wordMLPackage.save(new java.io.File("src/main/files/HelloWord12.docx") );
}
 
Example 6
Source Project: docx4j-template   Source File: TableWithMergedCells.java    License: Apache License 2.0 6 votes vote down vote up
/**
 *  创建一个带边框的表格并添加四个带内容的行, 然后将表格添加到文档并保存
 */
public static void main (String[] args) throws Docx4JException {
    wordMLPackage = WordprocessingMLPackage.createPackage();
    factory = Context.getWmlObjectFactory();
 
    Tbl table = factory.createTbl();
    addBorders(table);
 
    addTableRowWithMergedCells("Heading 1", "Heading 1.1",
        "Field 1", table);
    addTableRowWithMergedCells(null, "Heading 1.2", "Field 2", table);
 
    addTableRowWithMergedCells("Heading 2", "Heading 2.1",
        "Field 3", table);
    addTableRowWithMergedCells(null, "Heading 2.2", "Field 4", table);
 
    wordMLPackage.getMainDocumentPart().addObject(table);
    wordMLPackage.save(new java.io.File(
        "src/main/files/HelloWord9.docx") );
}
 
Example 7
/**
 *  创建一个带边框的表格并添加一行. 然后添加两个带内容的单元格并给定宽度.
 */
public static void main (String[] args) throws Docx4JException {
    wordMLPackage = WordprocessingMLPackage.createPackage();
    factory = Context.getWmlObjectFactory();
 
    Tbl table = factory.createTbl();
    addBorders(table);
 
    Tr tr = factory.createTr();
 
    addTableCellWithWidth(tr, "Field 1", 2500);
    addTableCellWithWidth(tr, "Field 2", 0);
 
    table.getContent().add(tr);
 
    wordMLPackage.getMainDocumentPart().addObject(table);
    wordMLPackage.save(new java.io.File("src/main/HelloWord133.docx") );
}
 
Example 8
Source Project: docx4j-template   Source File: TableWithStyledContent.java    License: Apache License 2.0 6 votes vote down vote up
/**
  *  跟前面的做的一样, 我们再一次创建了一个表格, 并添加了三个单元格, 其中有两个
  *  单元带有样式. 在新方法中我们传进表格行, 单元格内容, 是否为粗体及字体大小作
  *  为参数. 你需要注意, 因为the Office Open specification规范定义这个属性是半个
  *  点(half-point)大小, 因此字体大小需要是你想在Word中显示大小的两倍, 
 */
public static void main (String[] args) throws Docx4JException {
    wordMLPackage = WordprocessingMLPackage.createPackage();
    factory = Context.getWmlObjectFactory();
 
    Tbl table = factory.createTbl();
    Tr tableRow = factory.createTr();
 
    addRegularTableCell(tableRow, "Normal text");
    addStyledTableCell(tableRow, "Bold text", true, null);
    addStyledTableCell(tableRow, "Bold large text", true, "40");
 
    table.getContent().add(tableRow);
    addBorders(table);
 
    wordMLPackage.getMainDocumentPart().addObject(table);
    wordMLPackage.save(new java.io.File("src/main/files/HelloWord6.docx") );
}
 
Example 9
Source Project: docx-stamper   Source File: MultiStampTest.java    License: MIT License 6 votes vote down vote up
@Test
public void expressionsAreResolvedOnMultiStamp() throws Docx4JException, IOException {
	DocxStamper stamper = new DocxStamper(new DocxStamperConfiguration());
	NamesContext context = new NamesContext();

	InputStream template = getClass().getResourceAsStream("MultiStampTest.docx");
	OutputStream out = getOutputStream();
	stamper.stamp(template, context, out);
	InputStream in = getInputStream(out);
	WordprocessingMLPackage document = WordprocessingMLPackage.load(in);
	assertTableRows(document);

	template = getClass().getResourceAsStream("MultiStampTest.docx");
	out = getOutputStream();
	stamper.stamp(template, context, out);
	in = getInputStream(out);
	document = WordprocessingMLPackage.load(in);
	assertTableRows(document);
}
 
Example 10
Source Project: TranskribusCore   Source File: CoreUtils.java    License: GNU General Public License v3.0 6 votes vote down vote up
public static void convertDocxFilesToTxtFiles(String inputFolder, String outputFolder, boolean overwrite)
		throws IOException, Docx4JException, JAXBException {
	File inDir = new File(inputFolder);
	if (!inDir.exists()) {
		throw new IOException("Input folder does not exist: " + inputFolder);
	}

	File outDir = createDirectory(outputFolder, overwrite);

	File[] docxFiles = inDir.listFiles(new FilenameFilter() {
		@Override
		public boolean accept(File dir, String name) {
			return name.toLowerCase().endsWith(".docx");
		}
	});

	for (File docx : docxFiles) {
		String txt = extractTextFromDocx(docx.getAbsolutePath());
		String basename = FilenameUtils.getBaseName(docx.getName());
		Files.write(Paths.get(outDir.getAbsolutePath() + File.separator + basename + ".txt"), txt.getBytes());
	}
}
 
Example 11
Source Project: docx-stamper   Source File: CommentUtil.java    License: MIT License 6 votes vote down vote up
private static void collectComments(final Map<BigInteger, CommentWrapper> comments,
		WordprocessingMLPackage document) {
	try {
		CommentsPart commentsPart = (CommentsPart) document.getParts()
				.get(new PartName("/word/comments.xml"));
		if (commentsPart != null) {
			for (Comments.Comment comment : commentsPart.getContents().getComment()) {
				CommentWrapper commentWrapper = comments.get(comment.getId());
				if (commentWrapper != null) {
					commentWrapper.setComment(comment);
				}
			}
		}
	}
	catch (Docx4JException e) {
		throw new IllegalStateException(e);
	}
}
 
Example 12
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 13
Source Project: docx4j-export-FO   Source File: FORendererApacheFOP.java    License: Apache License 2.0 6 votes vote down vote up
public void setResults(FormattingResults formattingResults) throws Docx4JException {
	
	List<PageSequenceResults> resultList = null;
	PageSequenceResults pageSequenceResults = null;
	
	if (formattingResults == null) {
		throw new Docx4JException("Apache fop returned no FormattingResults (null)");
	}
	else {
		resultList = formattingResults.getPageSequences();
		if (resultList == null) {
			throw new Docx4JException("Apache fop returned null pageSequences");
		}
		else if (resultList.size() != pageNumberInformation.size()) {
			throw new Docx4JException("Apache fop returned different count of sections than expected, returned: " + resultList.size() + ", expected: " + pageNumberInformation.size());
		}
	}
	
	putDocumentPageCount(formattingResults.getPageCount());
	for (int i=0; i<formattingResults.getPageSequences().size(); i++) {
		pageSequenceResults = resultList.get(i);
		putSectionPageCount(i, pageSequenceResults.getPageCount());
	}
}
 
Example 14
Source Project: docx4j-export-FO   Source File: FORendererApacheFOP.java    License: Apache License 2.0 6 votes vote down vote up
protected void render(FopFactory fopFactory, FOUserAgent foUserAgent, String outputFormat, Source foDocumentSrc, PlaceholderReplacementHandler.PlaceholderLookup placeholderLookup, OutputStream outputStream) throws Docx4JException {
	Fop fop = null;
	Result result = null;
	try {
		if (foUserAgent==null) {
			fop = fopFactory.newFop(outputFormat, outputStream);
		} else {
			fop = fopFactory.newFop(outputFormat, foUserAgent, outputStream);				
		}
		result = (placeholderLookup == null ?
				//1 Pass
				new SAXResult(fop.getDefaultHandler()) :
				//2 Pass
				new SAXResult(new PlaceholderReplacementHandler(fop.getDefaultHandler(), placeholderLookup)));
	} catch (FOPException e) {
		throw new Docx4JException("Exception setting up result for fo transformation: " + e.getMessage(), e);
	}
	
	XmlSerializerUtil.serialize(foDocumentSrc, result, false, false);
}
 
Example 15
Source Project: docx4j-export-FO   Source File: PStyleTableAbstract.java    License: Apache License 2.0 6 votes vote down vote up
protected void setSetting(WordprocessingMLPackage wmlPackage, boolean val) throws Docx4JException {
	
		DocumentSettingsPart dsp = wmlPackage.getMainDocumentPart().getDocumentSettingsPart();
		if (dsp==null) {
			dsp = new DocumentSettingsPart();
			wmlPackage.getMainDocumentPart().addTargetPart(dsp);
			
			dsp.setContents( Context.getWmlObjectFactory().createCTSettings() );
		} 

		if (val) {
			dsp.setWordCompatSetting("overrideTableStyleFontSizeAndJustification", "1");
		} else {
			dsp.setWordCompatSetting("overrideTableStyleFontSizeAndJustification", "0");				
		}
}
 
Example 16
Source Project: docx-stamper   Source File: ObjectDeleterTest.java    License: MIT License 6 votes vote down vote up
@Test
public void deletesCorrectGlobalTables() throws Docx4JException, IOException {
    InputStream template = getClass().getResourceAsStream("ObjectDeleterTest-tables.docx");
    WordprocessingMLPackage document = WordprocessingMLPackage.load(template);
    final List<TableCoordinates> coordinates = getTableCoordinats(document);

    ObjectDeleter deleter = new ObjectDeleter(document);
    deleter.deleteTable(coordinates.get(1));
    deleter.deleteTable(coordinates.get(3));

    WordprocessingMLPackage savedDocument = saveAndLoadDocument(document);

    List<TableCoordinates> newTableCoordinates = getTableCoordinats(savedDocument);
    Assert.assertEquals(2, newTableCoordinates.size());

    List<TableCellCoordinates> cellCoordinates = getTableCellCoordinats(savedDocument);
    Assert.assertEquals("This", new ParagraphWrapper((P) cellCoordinates.get(0).getCell().getContent().get(0)).getText());
    Assert.assertEquals("Table", new ParagraphWrapper((P) cellCoordinates.get(1).getCell().getContent().get(0)).getText());
    Assert.assertEquals("Stays", new ParagraphWrapper((P) cellCoordinates.get(2).getCell().getContent().get(0)).getText());
    Assert.assertEquals("!", new ParagraphWrapper((P) cellCoordinates.get(3).getCell().getContent().get(0)).getText());
    Assert.assertEquals("This table stays", new ParagraphWrapper((P) cellCoordinates.get(4).getCell().getContent().get(0)).getText());
}
 
Example 17
@Test
public void customEvaluationContextConfigurerIsHonored() throws Docx4JException, IOException {
  DocxStamperConfiguration config = new DocxStamperConfiguration();
  config.setEvaluationContextConfigurer(new EvaluationContextConfigurer() {
    @Override
    public void configureEvaluationContext(StandardEvaluationContext context) {
      context.addPropertyAccessor(new SimpleGetter("foo", "bar"));
    }
  });

  InputStream template = getClass().getResourceAsStream("CustomEvaluationContextConfigurerTest.docx");
  WordprocessingMLPackage document = stampAndLoad(template, new EmptyContext(), config);

  P p2 = (P) document.getMainDocumentPart().getContent().get(2);
  Assert.assertEquals("The variable foo has the value bar.", new ParagraphWrapper(p2).getText());
}
 
Example 18
Source Project: kbase-doc   Source File: WordProcessor.java    License: Apache License 2.0 5 votes vote down vote up
private SectPr createSectPr() throws JAXBException, Docx4JException, IOException {
	String openXML = "<w:sectPr xmlns:w=\"http://schemas.openxmlformats.org/wordprocessingml/2006/main\" xmlns:r=\"http://schemas.openxmlformats.org/officeDocument/2006/relationships\">"
			// Word adds the background image in each of 3 header parts
			+ "<w:headerReference r:id=\"" + createHeaderPart("even").getId() + "\" w:type=\"even\"/>"
			+ "<w:headerReference r:id=\"" + createHeaderPart("default").getId() + "\" w:type=\"default\"/>"
			+ "<w:headerReference r:id=\"" + createHeaderPart("first").getId() + "\" w:type=\"first\"/>"

            + "<w:pgSz w:h=\"15840\" w:w=\"12240\"/>"
            + "<w:pgMar w:bottom=\"1440\" w:footer=\"708\" w:gutter=\"0\" w:header=\"708\" w:left=\"1440\" w:right=\"1440\" w:top=\"1440\"/>"
            + "<w:cols w:space=\"708\"/>"
            + "<w:docGrid w:linePitch=\"360\"/>"
            +"</w:sectPr>";
	return (SectPr)XmlUtils.unmarshalString(openXML);
}
 
Example 19
Source Project: docx4j-template   Source File: XHTMLImporterUtils.java    License: Apache License 2.0 5 votes vote down vote up
public static WordprocessingMLPackage handle(WordprocessingMLPackage wmlPackage, Document doc,boolean fragment,boolean altChunk) throws IOException, Docx4JException {
	//设置转换模式
	doc.outputSettings().syntax(Document.OutputSettings.Syntax.xml).escapeMode(Entities.EscapeMode.xhtml);  //转为 xhtml 格式
	
	if(altChunk){
		//Document对象
		MainDocumentPart document = wmlPackage.getMainDocumentPart();
		//获取Jsoup参数
		String charsetName = Docx4jProperties.getProperty(Docx4jConstants.DOCX4J_JSOUP_PARSE_CHARSETNAME, Docx4jConstants.DEFAULT_CHARSETNAME );
		//设置转换模式
		doc.outputSettings().syntax(Document.OutputSettings.Syntax.xml).escapeMode(Entities.EscapeMode.xhtml);  //转为 xhtml 格式
		//创建html导入对象
		//XHTMLImporterImpl xhtmlImporter = new XHTMLImporterImpl(wordMLPackage);
		document.addAltChunk(AltChunkType.Xhtml, (fragment ? doc.body().html() : doc.html()) .getBytes(Charset.forName(charsetName)));
		//document.addAltChunk(type, bytes, attachmentPoint)
		//document.addAltChunk(type, is)
		//document.addAltChunk(type, is, attachmentPoint)
		WordprocessingMLPackage tempPackage = document.convertAltChunks();
		
		//返回处理后的WordprocessingMLPackage对象
		return tempPackage;
	}
	
	//创建html导入对象
	XHTMLImporterImpl xhtmlImporter = new XHTMLImporterImpl(wmlPackage);
	//将xhtml转换为wmlPackage可用的对象
	List<Object> list = xhtmlImporter.convert((fragment ? doc.body().html() : doc.html()), doc.baseUri());
	//导入转换后的内容对象
	wmlPackage.getMainDocumentPart().getContent().addAll(list);
	//返回原WordprocessingMLPackage对象
	return wmlPackage;
}
 
Example 20
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 21
Source Project: docx4j-template   Source File: PhysicalFontUtils.java    License: Apache License 2.0 5 votes vote down vote up
public static void setWmlPackageFonts(WordprocessingMLPackage wmlPackage) throws Docx4JException {
try {
	//字体映射;  
	Mapper fontMapper = newFontMapper();
	//设置文档字体库
	wmlPackage.setFontMapper(fontMapper, true);
} catch (Exception e) {
	throw new Docx4JException(e.getMessage(),e.getCause());
}
  }
 
Example 22
Source Project: docx-stamper   Source File: TernaryOperatorTest.java    License: MIT License 5 votes vote down vote up
@Test
public void test() throws Docx4JException, IOException {
    NameContext context = new NameContext();
    context.setName("Homer");
    InputStream template = getClass().getResourceAsStream("TernaryOperatorTest.docx");
    WordprocessingMLPackage document = stampAndLoad(template, context);
    P nameParagraph = (P) document.getMainDocumentPart().getContent().get(3);
    Assert.assertEquals("Homer <-- this should read \"Homer\".", new ParagraphWrapper(nameParagraph).getText());
    P fooParagraph = (P) document.getMainDocumentPart().getContent().get(4);
    Assert.assertEquals("<-- this should be empty.", new ParagraphWrapper(fooParagraph).getText().trim());
}
 
Example 23
Source Project: docx4j-template   Source File: Docx4jUtils.java    License: Apache License 2.0 5 votes vote down vote up
public InputStream mergeDocx(final List<InputStream> streams)  throws Docx4JException, IOException {  
  
    WordprocessingMLPackage target = null;  
    final File generated = File.createTempFile("generated", ".docx");  
  
    int chunkId = 0;  
    Iterator<InputStream> it = streams.iterator();  
    while (it.hasNext()) {  
        InputStream is = it.next();  
        if (is != null) {  
            if (target == null) {  
                // Copy first (master) document   
                OutputStream os = new FileOutputStream(generated);  
                os.write(IOUtils.toByteArray(is));  
                os.close();  
  
                target = WordprocessingMLPackage.load(generated);  
            } else {  
                // Attach the others (Alternative input parts)   
                insertDocx(target.getMainDocumentPart(),  
                        IOUtils.toByteArray(is), chunkId++);  
            }  
        }  
    }  
  
    if (target != null) {  
        target.save(generated);  
        return new FileInputStream(generated);  
    } else {  
        return null;  
    }  
}
 
Example 24
Source Project: docx4j-template   Source File: WmlElementUtils.java    License: Apache License 2.0 5 votes vote down vote up
public static Tbl getTable(List<Tbl> tables, String placeholder) throws Docx4JException {  
    for (Iterator<Tbl> iterator = tables.iterator(); iterator.hasNext();) {  
    	Tbl tbl = iterator.next();
    	//查找当前table下面的text对象
        List<Text> textElements = getTargetElements(tbl, Text.class);  
        for (Text text : textElements) {
            Text textElement = (Text) text;
            //
            if (textElement.getValue() != null && textElement.getValue().equals(placeholder))  {
                return (Tbl) tbl;  
            }
        }  
    }  
    return null;  
}
 
Example 25
Source Project: docx-stamper   Source File: LineBreakReplacementTest.java    License: MIT License 5 votes vote down vote up
@Test
public void test() throws Docx4JException, IOException {
    NameContext context = new NameContext();
    DocxStamperConfiguration config = new DocxStamperConfiguration();
    config.setLineBreakPlaceholder("#");
    InputStream template = getClass().getResourceAsStream("LineBreakReplacementTest.docx");
    WordprocessingMLPackage document = stampAndLoad(template, context, config);
    lineBreaksAreReplaced(document);
}
 
Example 26
Source Project: docx-stamper   Source File: ExpressionWithSurroundingSpacesTest.java    License: MIT License 5 votes vote down vote up
@Test
public void test() throws Docx4JException, IOException {
    Context context = new Context();
    InputStream template = getClass().getResourceAsStream("ExpressionWithSurroundingSpacesTest.docx");
    WordprocessingMLPackage document = stampAndLoad(template, context);

    Assert.assertEquals("Before Expression After.", new ParagraphWrapper((P) document.getMainDocumentPart().getContent().get(2)).getText());
    Assert.assertEquals("Before Expression After.", new ParagraphWrapper((P) document.getMainDocumentPart().getContent().get(3)).getText());
    Assert.assertEquals("Before Expression After.", new ParagraphWrapper((P) document.getMainDocumentPart().getContent().get(4)).getText());
    Assert.assertEquals("Before Expression After.", new ParagraphWrapper((P) document.getMainDocumentPart().getContent().get(5)).getText());
    Assert.assertEquals("Before Expression After.", new ParagraphWrapper((P) document.getMainDocumentPart().getContent().get(6)).getText());
    Assert.assertEquals("Before Expression After.", new ParagraphWrapper((P) document.getMainDocumentPart().getContent().get(7)).getText());
    Assert.assertEquals("Before Expression After.", new ParagraphWrapper((P) document.getMainDocumentPart().getContent().get(8)).getText());
}
 
Example 27
Source Project: docx-stamper   Source File: FailOnUnresolvedExpressionTest.java    License: MIT License 5 votes vote down vote up
@Test
public void doesNotFail() throws Docx4JException, IOException {
    NameContext context = new NameContext();
    context.setName("Homer");
    InputStream template = getClass().getResourceAsStream("FailOnUnresolvedExpressionTest.docx");
    DocxStamper stamper = new DocxStamperConfiguration()
            .setFailOnUnresolvedExpression(false)
            .build();
    stamper.stamp(template, context, new ByteArrayOutputStream());
    // no exception
}
 
Example 28
/**
 * 将 {@link org.docx4j.openpackaging.packages.WordprocessingMLPackage} 存为 docx
 * @param wmlPackage {@link WordprocessingMLPackage} 对象
 * @param output 文件输出流
 * @throws IOException :IO异常
 * @throws Docx4JException : Docx4j异常
 */
public void writeToDocx(WordprocessingMLPackage wmlPackage,OutputStream output) throws IOException, Docx4JException {
	Assert.notNull(wmlPackage, " wmlPackage is not specified!");
	Assert.notNull(output, " output is not specified!");
       try {
       	wmlPackage.save(output , Docx4J.FLAG_SAVE_ZIP_FILE );//保存到 docx 文件
	} finally{
		IOUtils.closeQuietly(output);
       }
}
 
Example 29
Source Project: docx-stamper   Source File: ConditionalDisplayOfParagraphsTest.java    License: MIT License 5 votes vote down vote up
@Test
public void processorExpressionsInCommentsAreResolved() throws Docx4JException, IOException {
    NameContext context = new NameContext();
    context.setName("Homer");
    InputStream template = getClass().getResourceAsStream("ConditionalDisplayOfParagraphsTest.docx");
    WordprocessingMLPackage document = stampAndLoad(template, context);
    globalParagraphsAreRemoved(document);
    paragraphsInTableAreRemoved(document);
    paragraphsInNestedTablesAreRemoved(document);
}
 
Example 30
/**
 * 将 {@link org.docx4j.openpackaging.packages.WordprocessingMLPackage} 存为 pdf
 * @param wmlPackage {@link WordprocessingMLPackage} 对象
 * @param output 文件输出流
 * @throws IOException :IO异常
 * @throws Docx4JException : Docx4j异常
 */
public void writeToPDF(WordprocessingMLPackage wmlPackage,OutputStream output) throws IOException, Docx4JException {
	Assert.notNull(wmlPackage, " wmlPackage is not specified!");
	Assert.notNull(output, " output is not specified!");
       try {
		Docx4J.toPDF(wmlPackage, output); //保存到 pdf 文件
		output.flush();
	} finally{
		IOUtils.closeQuietly(output);
       }
}