org.docx4j.openpackaging.exceptions.Docx4JException Java Examples

The following examples show how to use org.docx4j.openpackaging.exceptions.Docx4JException. 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: TernaryOperatorTest.java    From docx-stamper with MIT License 8 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 #2
Source File: WmlElementUtils.java    From docx4j-template with Apache License 2.0 7 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 File: FORendererApacheFOP.java    From docx4j-export-FO with 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 #4
Source File: MultiStampTest.java    From docx-stamper with 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 #5
Source File: CoreUtils.java    From TranskribusCore with 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 #6
Source File: PStyleTableAbstract.java    From docx4j-export-FO with 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 #7
Source File: TableWithStyledContent.java    From docx4j-template with 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 #8
Source File: WordprocessingMLTemplateWriter.java    From docx4j-template with Apache License 2.0 6 votes vote down vote up
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 #9
Source File: SettingColumnWidthForTable.java    From docx4j-template with 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);
 
    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 #10
Source File: FORendererApacheFOP.java    From docx4j-export-FO with 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 #11
Source File: ObjectDeleterTest.java    From docx-stamper with 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 #12
Source File: CommentUtil.java    From docx-stamper with 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 #13
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 #14
Source File: TableWithMergedCells.java    From docx4j-template with 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 #15
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 #16
Source File: ChangingTheStyleSheet.java    From docx4j-template with 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 #17
Source File: CustomEvaluationContextConfigurerTest.java    From docx-stamper with MIT License 6 votes vote down vote up
@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 File: FORendererApacheFOP.java    From docx4j-export-FO with Apache License 2.0 5 votes vote down vote up
/**
 * Allow user access to FOUserAgent, so they can setAccessibility(true).  Access to other settings
 * is possible but unsupported.
 * 
 * @param wmlPackage
 * @return
 * @throws FOPException
 */
public static FOUserAgent getFOUserAgent(FOSettings settings) throws Docx4JException, FOPException {
	
	FopFactory fopFactory = getFopFactory(
			setupApacheFopConfiguration(settings)); // relies on the WordML package being there, for font info
	settings.getSettings().put(FOP_FACTORY, fopFactory);
	
    FOUserAgent foUserAgent = fopFactory.newFOUserAgent();
	settings.getSettings().put(FO_USER_AGENT, foUserAgent);
	
	return foUserAgent;
}
 
Example #19
Source File: TabsIndendationTest.java    From docx-stamper with MIT License 5 votes vote down vote up
@Test
public void tabsArePreserved() throws Docx4JException, IOException {
  NameContext context = new NameContext();
  context.setName("Homer Simpson");
  InputStream template = getClass().getResourceAsStream("TabsIntendationTest.docx");
  WordprocessingMLPackage document = stampAndLoad(template, context);

  P nameParagraph = (P) document.getMainDocumentPart().getContent().get(0);
  Assert.assertEquals("Tab\tHomer Simpson", new ParagraphWrapper(nameParagraph).getText());
}
 
Example #20
Source File: LeaveEmptyOnExpressionErrorTest.java    From docx-stamper with MIT License 5 votes vote down vote up
@Test
public void test() throws Docx4JException, IOException {
  NameContext context = new NameContext();
  context.setName("Homer Simpson");
  InputStream template = getClass().getResourceAsStream("LeaveEmptyOnExpressionErrorTest.docx");
  OutputStream out = getOutputStream();
  DocxStamper stamper = new DocxStamperConfiguration()
          .leaveEmptyOnExpressionError(true)
          .build();
  stamper.stamp(template, context, out);
  InputStream in = getInputStream(out);
  WordprocessingMLPackage document = WordprocessingMLPackage.load(in);
  resolvedExpressionsAreReplaced(document);
}
 
Example #21
Source File: DocxProducer.java    From OfficeProducer with Apache License 2.0 5 votes vote down vote up
/**
 * 获取模板中的表格
 *
 * @param tables
 * @param templateKey
 * @return
 * @throws Docx4JException
 * @throws JAXBException
 */
private static Tbl getTemplateTable(List<Object> tables, String templateKey) throws Docx4JException, JAXBException {
    for (Object tbl : tables) {
        List<?> textElements = getAllElementFromObject(tbl, Text.class);
        for (Object text : textElements) {
            Text textElement = (Text) text;
            if (textElement.getValue() != null && textElement.getValue().equals(templateKey))
                return (Tbl) tbl;
        }
    }
    return null;
}
 
Example #22
Source File: ConditionalDisplayOfTablesTest.java    From docx-stamper with 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("ConditionalDisplayOfTablesTest.docx");
    WordprocessingMLPackage document = stampAndLoad(template, context);
    globalTablesAreRemoved(document);
    nestedTablesAreRemoved(document);
}
 
Example #23
Source File: FOPAreaTreeHelper.java    From docx4j-export-FO with Apache License 2.0 5 votes vote down vote up
static org.w3c.dom.Document getAreaTreeViaFOP(WordprocessingMLPackage hfPkg, boolean useXSLT) throws Docx4JException, ParserConfigurationException, SAXException, IOException  {

    	  // Currently FOP dependent!  But an Antenna House version ought to be feasible.
    	
        FOSettings foSettings = Docx4J.createFOSettings();
        foSettings.setWmlPackage(hfPkg);
        foSettings.setApacheFopMime(MimeConstants.MIME_FOP_AREA_TREE);
        
        foSettings.setLayoutMasterSetCalculationInProgress(true); // avoid recursion
        
//        foSettings.getFeatures().add(ConversionFeatures.PP_PDF_APACHEFOP_DISABLE_PAGEBREAK_LIST_ITEM); // in 3.0.1, this is off by default
        
        // Since hfPkg is already a clone, we don't need PP_COMMON_DEEP_COPY
        // Plus it invokes setFontMapper, which does processEmbeddings again, and those fonts aren't much use to us here
        foSettings.getFeatures().remove(ConversionFeatures.PP_COMMON_DEEP_COPY);
        
        if (log.isDebugEnabled()) {
        	foSettings.setFoDumpFile(new java.io.File(System.getProperty("user.dir") + "/hf.fo"));
        }

        ByteArrayOutputStream os = new ByteArrayOutputStream();
        
        if (useXSLT) {
        	Docx4J.toFO(foSettings, os, Docx4J.FLAG_EXPORT_PREFER_XSL);
        } else {
        	Docx4J.toFO(foSettings, os, Docx4J.FLAG_EXPORT_PREFER_NONXSL);        	
        }
        
        InputStream is = new ByteArrayInputStream(os.toByteArray());
		DocumentBuilder builder = XmlUtils.getNewDocumentBuilder();
		return builder.parse(is);

    }
 
Example #24
Source File: AbstractDocx4jTest.java    From docx-stamper with MIT License 5 votes vote down vote up
protected <T> WordprocessingMLPackage stampAndLoad(InputStream template, T contextRoot, DocxStamperConfiguration config) throws IOException, Docx4JException {
    OutputStream out = getOutputStream();
    DocxStamper stamper = new DocxStamper(config);
    stamper.stamp(template, contextRoot, out);
    InputStream in = getInputStream(out);
    return WordprocessingMLPackage.load(in);
}
 
Example #25
Source File: Docx4j_替换模板.java    From docx4j-template with Apache License 2.0 5 votes vote down vote up
/** 
 * 替换图表数据 
 */  
private void replacePieChartData(WordprocessingMLPackage wordMLPackage, String[] chartArr) throws Docx4JException {  
    RelationshipsPart rp = wordMLPackage.getMainDocumentPart().getRelationshipsPart();  
    Relationship rel = rp.getRelationshipByType(Namespaces.SPREADSHEETML_CHART);  
    Chart chart = (Chart) rp.getPart(rel);  
    CTChartSpace chartSpace = chart.getContents();  
    List<Object> charObjList = chartSpace.getChart().getPlotArea().getAreaChartOrArea3DChartOrLineChart();  
    CTPieChart pieChart = (CTPieChart) charObjList.get(0);  
    List<CTPieSer> serList = pieChart.getSer();  
    CTNumDataSource serVal = serList.get(0).getVal();  
    List<CTNumVal> ptList = serVal.getNumRef().getNumCache().getPt();  
    ptList.get(0).setV(chartArr[0]);  
    ptList.get(1).setV(chartArr[1]);  
}
 
Example #26
Source File: TableWithBorders.java    From docx4j-template with Apache License 2.0 5 votes vote down vote up
public static void main (String[] args) throws Docx4JException {
    wordMLPackage = WordprocessingMLPackage.createPackage();
    factory = Context.getWmlObjectFactory();
 
    Tbl table = createTableWithContent();
 
    addBorders(table);
 
    wordMLPackage.getMainDocumentPart().addObject(table);
    wordMLPackage.save(new java.io.File(
        "src/main/files/HelloWord5.docx") );
}
 
Example #27
Source File: FOExporterVisitorDelegate.java    From docx4j-export-FO with Apache License 2.0 5 votes vote down vote up
protected void appendPartContent(FOConversionContext conversionContext, 
								  Document document, 
								  Element currentParent,
								  String name, Part part, List<Object> content) throws Docx4JException {
   Element	flow = document.createElementNS(XSL_FO, "static-content");    	
   	currentParent.appendChild(flow); 
   	flow.setAttribute("flow-name", name);
   	appendPartContent(conversionContext, document, part, content, flow);
}
 
Example #28
Source File: ExpressionReplacementInHeaderAndFooterTest.java    From docx-stamper with MIT License 5 votes vote down vote up
@Test
public void test() throws Docx4JException, IOException {
    NameContext context = new NameContext();
    context.setName("Homer Simpson");
    InputStream template = getClass().getResourceAsStream("ExpressionReplacementInHeaderAndFooterTest.docx");
    WordprocessingMLPackage document = stampAndLoad(template, context);
    resolvedExpressionsAreReplacedInHeader(document);
    resolvedExpressionsAreReplacedInFooter(document);
    unresolvedExpressionsAreNotReplacedInHeader(document);
    unresolvedExpressionsAreNotReplacedInFooter(document);
}
 
Example #29
Source File: AddingAPageBreak.java    From docx4j-template with Apache License 2.0 5 votes vote down vote up
public static void main (String[] args) throws Docx4JException {
    wordMLPackage = WordprocessingMLPackage.createPackage();
    factory = Context.getWmlObjectFactory();
 
    wordMLPackage.getMainDocumentPart().addParagraphOfText("Hello Word!");
 
    addPageBreak();
 
    wordMLPackage.getMainDocumentPart().addParagraphOfText("This is page 2!");
    wordMLPackage.save(new java.io.File("src/main/files/HelloWord11.docx") );
}
 
Example #30
Source File: ConditionalDisplayOfParagraphsTest.java    From docx-stamper with MIT License 5 votes vote down vote up
@Test
public void inlineProcessorExpressionsAreResolved() throws Docx4JException, IOException {
    NameContext context = new NameContext();
    context.setName("Homer");
    InputStream template = getClass().getResourceAsStream("ConditionalDisplayOfParagraphsWithoutCommentTest.docx");
    WordprocessingMLPackage document = stampAndLoad(template, context);
    globalParagraphsAreRemoved(document);
    paragraphsInTableAreRemoved(document);
    paragraphsInNestedTablesAreRemoved(document);
}