org.apache.poi.xwpf.usermodel.XWPFDocument Java Examples

The following examples show how to use org.apache.poi.xwpf.usermodel.XWPFDocument. 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: ConvertDocxLettreRelanceToXHTML.java    From xdocreport.samples with GNU Lesser General Public License v3.0 7 votes vote down vote up
public static void main( String[] args )
{
    long startTime = System.currentTimeMillis();

    try
    {
        // 1) Load docx with POI XWPFDocument
        XWPFDocument document = new XWPFDocument( Data.class.getResourceAsStream( "DocxLettreRelance.docx" ) );

        // 2) Convert POI XWPFDocument 2 PDF with iText
        File outFile = new File( "target/DocxLettreRelance.htm" );
        outFile.getParentFile().mkdirs();

        OutputStream out = new FileOutputStream( outFile );
        XHTMLConverter.getInstance().convert( document, out, null );
    }
    catch ( Throwable e )
    {
        e.printStackTrace();
    }

    System.out.println( "Generate DocxLettreRelance.htm with " + ( System.currentTimeMillis() - startTime )
        + " ms." );
}
 
Example #2
Source File: M2DocTestUtils.java    From M2Doc with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Gets the textual element of the .docx at the given {@link URI}.
 * 
 * @param uriConverter
 *            the {@link URIConverter}
 * @param uri
 *            the .docx {@link URI}
 * @return the textual element of the .docx at the given {@link URI}
 */
public static String getTextContent(URIConverter uriConverter, URI uri) {
    String result = "";

    try (InputStream is = uriConverter.createInputStream(uri);
            OPCPackage oPackage = OPCPackage.open(is);
            XWPFDocument document = new XWPFDocument(oPackage);
            XWPFWordExtractor ex = new XWPFWordExtractor(document);) {

        result += "===== Document Text ====\n";
        result += ex.getText();
        // CHECKSTYLE:OFF
    } catch (Throwable e) {
        // CHECKSTYLE:ON
        /*
         * if for some reason we can't use POI to get the text content then move along, we'll still get the XML and hashs
         */
    }
    return result;
}
 
Example #3
Source File: ELModeTest.java    From poi-tl with Apache License 2.0 6 votes vote down vote up
@Test
public void testSpringELMode() throws Exception {
    // Spring EL 无法容忍变量不存在,直接抛出异常,表达式计算引擎为Spring Expression Language
    Configure config = Configure.newBuilder().setElMode(ELMode.SPEL_MODE).build();
    XWPFTemplate template = XWPFTemplate.compile(resource, config).render(model);

    XWPFDocument document = XWPFTestSupport.readNewDocument(template);
    XWPFParagraph paragraph = document.getParagraphArray(0);
    assertEquals(paragraph.getText(), "Sayi");
    paragraph = document.getParagraphArray(1);
    assertEquals(paragraph.getText(), "卅一");
    paragraph = document.getParagraphArray(3);
    assertEquals(paragraph.getText(), "2018-10-01");
    paragraph = document.getParagraphArray(4);
    assertEquals(paragraph.getText(), "http://www.deepoove.com");

    assertEquals(document.getAllPictures().size(), 1);
    assertEquals(document.getTables().size(), 1);
    document.close();

}
 
Example #4
Source File: ConvertDocxBigToPDF.java    From xdocreport.samples with GNU Lesser General Public License v3.0 6 votes vote down vote up
public static void main( String[] args )
{
    long startTime = System.currentTimeMillis();

    try
    {
        // 1) Load docx with POI XWPFDocument
        XWPFDocument document = new XWPFDocument( Data.class.getResourceAsStream( "DocxBig.docx" ) );

        // 2) Convert POI XWPFDocument 2 PDF with iText
        File outFile = new File( "target/DocxBig.pdf" );
        outFile.getParentFile().mkdirs();

        OutputStream out = new FileOutputStream( outFile );
        PdfOptions options = PdfOptions.create().fontEncoding( "windows-1250" );
        PdfConverter.getInstance().convert( document, out, options );
    }
    catch ( Throwable e )
    {
        e.printStackTrace();
    }

    System.out.println( "Generate DocxBig.pdf with " + ( System.currentTimeMillis() - startTime ) + " ms." );
}
 
Example #5
Source File: BookMarks.java    From frpMgr with MIT License 6 votes vote down vote up
/** 
 * 构造函数,用以分析文档,解析出所有的标签
 * @param document  Word OOXML document instance. 
 */
public BookMarks(XWPFDocument document) {

	//初始化标签缓存
	this._bookmarks = new HashMap<String, BookMark>();

	// 首先解析文档普通段落中的标签 
	this.procParaList(document.getParagraphs());

	//利用繁琐的方法,从所有的表格中得到得到标签,处理比较原始和简单
	List<XWPFTable> tableList = document.getTables();

	for (XWPFTable table : tableList) {
		//得到表格的列信息
		List<XWPFTableRow> rowList = table.getRows();
		for (XWPFTableRow row : rowList) {
			//得到行中的列信息
			List<XWPFTableCell> cellList = row.getTableCells();
			for (XWPFTableCell cell : cellList) {
				//逐个解析标签信息
				//this.procParaList(cell.getParagraphs(), row);
				this.procParaList(cell);
			}
		}
	}
}
 
Example #6
Source File: RawCopier.java    From M2Doc with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Gets the output {@link PackagePart} name for the given source {@link PackagePart} in the given output {@link XWPFDocument}.
 * 
 * @param source
 *            the source {@link PackagePart}
 * @param outputDoc
 *            the output {@link XWPFDocument}
 * @return the output {@link PackagePart} name for the given source {@link PackagePart} in the given output {@link XWPFDocument}
 * @throws InvalidFormatException
 *             if a {@link PackagePart} can't be accessed
 */
private PackagePartName getOutputPartName(PackagePart source, XWPFDocument outputDoc)
        throws InvalidFormatException {
    PackagePartName possiblePartName = source.getPartName();
    PackagePart existingPart = outputDoc.getPackage().getPart(possiblePartName);
    int index = 1;
    final Matcher matcher = INTEGER_PATTERN.matcher(possiblePartName.getName());
    final boolean indexFound = matcher.find();
    while (existingPart != null) {
        existingPart = outputDoc.getPackage().getPart(possiblePartName);
        if (existingPart != null) {
            if (indexFound) {
                possiblePartName = PackagingURIHelper.createPartName(matcher.replaceFirst(String.valueOf(index++)));
            } else {
                possiblePartName = PackagingURIHelper
                        .createPartName(source.getPartName().getName().replace(".", index++ + "."));
            }
        }
    }

    return possiblePartName;
}
 
Example #7
Source File: FileBeanParser.java    From everywhere with Apache License 2.0 6 votes vote down vote up
private static String readDoc (String filePath, InputStream is) throws Exception {
    String text= "";
    is = FileMagic.prepareToCheckMagic(is);
    try {
        if (FileMagic.valueOf(is) == FileMagic.OLE2) {
            WordExtractor ex = new WordExtractor(is);
            text = ex.getText();
            ex.close();
        } else if(FileMagic.valueOf(is) == FileMagic.OOXML) {
            XWPFDocument doc = new XWPFDocument(is);
            XWPFWordExtractor extractor = new XWPFWordExtractor(doc);
            text = extractor.getText();
            extractor.close();
        }
    } catch (OfficeXmlFileException e) {
        logger.error(filePath, e);
    } finally {
        if (is != null) {
            is.close();
        }
    }
    return text;
}
 
Example #8
Source File: JeecgTemplateWordView.java    From autopoi with Apache License 2.0 6 votes vote down vote up
@Override
protected void renderMergedOutputModel(Map<String, Object> model, HttpServletRequest request, HttpServletResponse response) throws Exception {
	String codedFileName = "临时文件.docx";
	if (model.containsKey(TemplateWordConstants.FILE_NAME)) {
		codedFileName = (String) model.get(TemplateWordConstants.FILE_NAME) + ".docx";
	}
	if (isIE(request)) {
		codedFileName = java.net.URLEncoder.encode(codedFileName, "UTF8");
	} else {
		codedFileName = new String(codedFileName.getBytes("UTF-8"), "ISO-8859-1");
	}
	response.setHeader("content-disposition", "attachment;filename=" + codedFileName);
	XWPFDocument document = WordExportUtil.exportWord07((String) model.get(TemplateWordConstants.URL), (Map<String, Object>) model.get(TemplateWordConstants.MAP_DATA));
	ServletOutputStream out = response.getOutputStream();
	document.write(out);
	out.flush();
}
 
Example #9
Source File: WatermarkWordTests.java    From kbase-doc with Apache License 2.0 6 votes vote down vote up
@Test
public void testDocx2() throws IOException {
	String filepath = "E:\\ConvertTester\\docx\\NVR5X-I人脸比对配置-ekozhan.docx";
	XWPFDocument doc = new XWPFDocument(new FileInputStream(filepath));
	XWPFHeaderFooterPolicy policy = new XWPFHeaderFooterPolicy(doc);
	
	policy.createWatermark("ekozhan123");
	doc.write(new FileOutputStream("E:\\ConvertTester\\docx\\NVR5X-I人脸比对配置-ekozhan-11.docx"));
	doc.close();
}
 
Example #10
Source File: M2DocUtils.java    From M2Doc with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Gets or create the first {@link XWPFRun} of the given {@link XWPFDocument}.
 * 
 * @param document
 *            the {@link XWPFDocument}
 * @return the first {@link XWPFRun} of the given {@link XWPFDocument} or the created one if none existed
 */
public static XWPFRun getOrCreateFirstRun(XWPFDocument document) {
    final XWPFRun res;

    final XWPFParagraph paragraph;
    if (!document.getParagraphs().isEmpty()) {
        paragraph = document.getParagraphs().get(0);
    } else {
        paragraph = document.createParagraph();
    }
    if (!paragraph.getRuns().isEmpty()) {
        res = paragraph.getRuns().get(0);
    } else {
        res = paragraph.createRun();
    }

    return res;
}
 
Example #11
Source File: WordXTableParser.java    From sun-wordtable-read with Apache License 2.0 6 votes vote down vote up
public List<WordTable> parse(InputStream inputStream) {
	List<WordTable> wordTables = Lists.newArrayList();

	try {
		XWPFDocument doc = new XWPFDocument(inputStream); // 载入文档  

		//获取文档中所有的表格  
		List<XWPFTable> tables = doc.getTables();
		for (XWPFTable table : tables) {
			ISingleWordTableParser parser = new SingleWordXTableParser(table, this.context);
			WordTable wordTable = parser.parse();
			wordTables.add(wordTable);
		}
	} catch (Exception e) {
		logger.error(e.getMessage(), e);
	} finally {
		IOUtils.closeQuietly(inputStream);
	}

	return wordTables;
}
 
Example #12
Source File: M2DocNewProjectWizard.java    From M2Doc with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Creates the sample template.
 * 
 * @param templateName
 *            the template name
 * @param variableName
 *            the variable name
 * @param variableValue
 *            the variable value
 * @param monitor
 *            the {@link IProgressMonitor}
 * @param project
 *            the {@link IllegalPropertySetDataException}
 * @return
 * @throws IOException
 *             if the template file can't be saved
 * @throws CoreException
 *             if the template file can't be saved
 * @throws InvalidFormatException
 *             if the sample template can't be read
 * @return the template {@link URI}
 */
private URI createSampleTemplate(final String templateName, final String variableName, final EObject variableValue,
        IProgressMonitor monitor, final IProject project)
        throws IOException, CoreException, InvalidFormatException {
    final URI res;

    final URIConverter uriConverter = new ExtensibleURIConverterImpl();
    final MemoryURIHandler handler = new MemoryURIHandler();
    uriConverter.getURIHandlers().add(0, handler);
    try (XWPFDocument sampleTemplate = M2DocUtils.createSampleTemplate(variableName, variableValue.eClass());) {
        final URI memoryURI = URI
                .createURI(MemoryURIHandler.PROTOCOL + "://resources/temp." + M2DocUtils.DOCX_EXTENSION_FILE);
        POIServices.getInstance().saveFile(uriConverter, sampleTemplate, memoryURI);

        try (InputStream source = uriConverter.createInputStream(memoryURI)) {
            final IFile templateFile = project.getFile(templateName);
            templateFile.create(source, true, monitor);
            res = URI.createPlatformResourceURI(templateFile.getFullPath().toString(), true);
        }
    }

    return res;
}
 
Example #13
Source File: RawCopier.java    From M2Doc with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Copies the given {@link CTSdtBlock} in the given output {@link IBody}.
 * 
 * @param outputBody
 *            the output {@link IBody}
 * @param block
 *            the {@link CTSdtBlock} to insert
 */
private void copyCTSdtBlock(IBody outputBody, CTSdtBlock block) {
    final CTSdtBlock stdBlock;
    if (outputBody instanceof XWPFDocument) {
        stdBlock = ((XWPFDocument) outputBody).getDocument().getBody().addNewSdt();
    } else if (outputBody instanceof XWPFHeaderFooter) {
        stdBlock = ((XWPFHeaderFooter) outputBody)._getHdrFtr().addNewSdt();
    } else if (outputBody instanceof XWPFFootnote) {
        stdBlock = ((XWPFFootnote) outputBody).getCTFtnEdn().addNewSdt();
    } else if (outputBody instanceof XWPFTableCell) {
        stdBlock = ((XWPFTableCell) outputBody).getCTTc().addNewSdt();
    } else {
        throw new IllegalStateException("can't insert control in " + outputBody.getClass().getCanonicalName());
    }
    stdBlock.set(block.copy());
    new XWPFSDT(stdBlock, outputBody); // this do the insertion
}
 
Example #14
Source File: IndexerTextExtractor.java    From eplmp with Eclipse Public License 1.0 6 votes vote down vote up
private String microsoftWordDocumentToString(InputStream inputStream) throws IOException {
    String strRet;

    try (InputStream wordStream = new BufferedInputStream(inputStream)) {
        if (POIFSFileSystem.hasPOIFSHeader(wordStream)) {
            WordExtractor wordExtractor = new WordExtractor(wordStream);
            strRet = wordExtractor.getText();
            wordExtractor.close();
        } else {
            XWPFWordExtractor wordXExtractor = new XWPFWordExtractor(new XWPFDocument(wordStream));
            strRet = wordXExtractor.getText();
            wordXExtractor.close();
        }
    }

    return strRet;
}
 
Example #15
Source File: GenconfUtilsTests.java    From M2Doc with Eclipse Public License 1.0 6 votes vote down vote up
@Test
public void getOldDefinitionsExistingNotDeclared() throws IOException {
    final Generation generation = GenconfPackage.eINSTANCE.getGenconfFactory().createGeneration();
    final StringDefinition stringDefinition = GenconfPackage.eINSTANCE.getGenconfFactory().createStringDefinition();
    stringDefinition.setKey("variable");
    generation.getDefinitions().add(stringDefinition);

    try (XWPFDocument document = new XWPFDocument()) {
        final TemplateCustomProperties properties = new TemplateCustomProperties(document);

        final List<Definition> definitions = GenconfUtils.getOldDefinitions(generation, properties);

        assertEquals(1, definitions.size());
        assertEquals(stringDefinition, definitions.get(0));
    }
}
 
Example #16
Source File: GenconfUtilsTests.java    From M2Doc with Eclipse Public License 1.0 6 votes vote down vote up
@Test
public void getOldDefinitionsExistingInvalidType() throws IOException {
    final Generation generation = GenconfPackage.eINSTANCE.getGenconfFactory().createGeneration();
    final StringDefinition stringDefinition = GenconfPackage.eINSTANCE.getGenconfFactory().createStringDefinition();
    stringDefinition.setKey("variable");
    generation.getDefinitions().add(stringDefinition);

    try (XWPFDocument document = new XWPFDocument()) {
        final TemplateCustomProperties properties = new TemplateCustomProperties(document);

        properties.getVariables().put("variable", "ecore::EClass");

        final List<Definition> definitions = GenconfUtils.getOldDefinitions(generation, properties);

        assertEquals(1, definitions.size());
        assertEquals(stringDefinition, definitions.get(0));
    }
}
 
Example #17
Source File: GenconfUtilsTests.java    From M2Doc with Eclipse Public License 1.0 6 votes vote down vote up
@Test
public void getOldDefinitionsExisting() throws IOException {
    final Generation generation = GenconfPackage.eINSTANCE.getGenconfFactory().createGeneration();
    final StringDefinition stringDefinition = GenconfPackage.eINSTANCE.getGenconfFactory().createStringDefinition();
    stringDefinition.setKey("variable");
    generation.getDefinitions().add(stringDefinition);

    try (XWPFDocument document = new XWPFDocument()) {
        final TemplateCustomProperties properties = new TemplateCustomProperties(document);

        properties.getVariables().put("variable", TemplateCustomProperties.STRING_TYPE);

        final List<Definition> definitions = GenconfUtils.getOldDefinitions(generation, properties);

        assertEquals(0, definitions.size());
    }
}
 
Example #18
Source File: RunProviderTests.java    From M2Doc with Eclipse Public License 1.0 6 votes vote down vote up
@Test
public void testNonEmptyDoc() throws InvalidFormatException, IOException {
    try (FileInputStream is = new FileInputStream("resources/document/notEmpty/notEmpty-template.docx");
            OPCPackage oPackage = OPCPackage.open(is);
            XWPFDocument document = new XWPFDocument(oPackage);) {
        TokenProvider iterator = new TokenProvider(document);
        XWPFRun run = iterator.next().getRun();
        assertEquals("P1Run1 ", run.getText(run.getTextPosition()));
        run = iterator.next().getRun();
        assertEquals("P1Run2", run.getText(run.getTextPosition()));
        run = iterator.next().getRun();
        assertEquals(" P1Run3", run.getText(run.getTextPosition()));
        run = iterator.next().getRun();
        assertEquals("P2Run1 ", run.getText(run.getTextPosition()));
        run = iterator.next().getRun();
        assertEquals("P2Run2", run.getText(run.getTextPosition()));
        run = iterator.next().getRun();
        assertEquals(" ", run.getText(run.getTextPosition()));
        run = iterator.next().getRun();
        assertEquals("P2Run3", run.getText(run.getTextPosition()));
        run = iterator.next().getRun();
        assertEquals("", run.getText(run.getTextPosition()));
        assertTrue(!iterator.hasNext());
    }
}
 
Example #19
Source File: RunProviderTests.java    From M2Doc with Eclipse Public License 1.0 6 votes vote down vote up
@Test(expected = NoSuchElementException.class)
public void testAccessEmptyIterator() throws InvalidFormatException, IOException {
    try (FileInputStream is = new FileInputStream("resources/document/notEmpty/notEmpty-template.docx");
            OPCPackage oPackage = OPCPackage.open(is);
            XWPFDocument document = new XWPFDocument(oPackage);) {
        TokenProvider iterator = new TokenProvider(document);
        iterator.next().getRun();
        iterator.next().getRun();
        iterator.next().getRun();
        iterator.next().getRun();
        iterator.next().getRun();
        iterator.next().getRun();
        iterator.next().getRun();
        iterator.next().getRun();
        iterator.next().getRun();
    }
}
 
Example #20
Source File: RunProviderTests.java    From M2Doc with Eclipse Public License 1.0 6 votes vote down vote up
@Test
public void testLookaheadEmptyIterator() throws InvalidFormatException, IOException {
    try (FileInputStream is = new FileInputStream("resources/document/notEmpty/notEmpty-template.docx");
            OPCPackage oPackage = OPCPackage.open(is);
            XWPFDocument document = new XWPFDocument(oPackage);) {
        TokenProvider iterator = new TokenProvider(document);
        iterator.next().getRun();
        iterator.next().getRun();
        iterator.next().getRun();
        iterator.next().getRun();
        iterator.next().getRun();
        iterator.next().getRun();
        iterator.next().getRun();
        iterator.next().getRun();
        assertNull(iterator.lookAhead(1));
    }
}
 
Example #21
Source File: AbstractBodyParser.java    From M2Doc with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Gets the {@link CTSdtBlock} at the given sdtIndex in the given {@link IBody}.
 * 
 * @param body
 *            the {@link IBody}
 * @param sdtIndex
 *            the index in internal sdt list
 * @return the {@link CTSdtBlock} at the given sdtIndex in the given {@link IBody}
 */
private static CTSdtBlock getCTSdtBlock(IBody body, int sdtIndex) {
    final CTSdtBlock res;

    if (body instanceof XWPFDocument) {
        res = ((XWPFDocument) body).getDocument().getBody().getSdtArray(sdtIndex);
    } else if (body instanceof XWPFHeaderFooter) {
        res = ((XWPFHeaderFooter) body)._getHdrFtr().getSdtArray(sdtIndex);
    } else if (body instanceof XWPFFootnote) {
        res = ((XWPFFootnote) body).getCTFtnEdn().getSdtArray(sdtIndex);
    } else if (body instanceof XWPFTableCell) {
        res = ((XWPFTableCell) body).getCTTc().getSdtArray(sdtIndex);
    } else {
        throw new IllegalStateException("can't insert control in " + body.getClass().getCanonicalName());
    }

    return res;
}
 
Example #22
Source File: GenconfUtilsTests.java    From M2Doc with Eclipse Public License 1.0 6 votes vote down vote up
@Test
public void getNewDefinitionsExisting() throws IOException {
    final Generation generation = GenconfPackage.eINSTANCE.getGenconfFactory().createGeneration();
    final StringDefinition stringDefinition = GenconfPackage.eINSTANCE.getGenconfFactory().createStringDefinition();
    stringDefinition.setKey("variable");
    generation.getDefinitions().add(stringDefinition);

    try (XWPFDocument document = new XWPFDocument()) {
        final TemplateCustomProperties properties = new TemplateCustomProperties(document);

        properties.getVariables().put("variable", TemplateCustomProperties.STRING_TYPE);

        final List<Definition> definitions = GenconfUtils.getNewDefinitions(generation, properties);

        assertEquals(0, definitions.size());
    }
}
 
Example #23
Source File: RunIteratorTests.java    From M2Doc with Eclipse Public License 1.0 6 votes vote down vote up
@Test
public void testNonEmptyDoc() throws InvalidFormatException, IOException {
    try (FileInputStream is = new FileInputStream("resources/document/notEmpty/notEmpty-template.docx");
            OPCPackage oPackage = OPCPackage.open(is);
            XWPFDocument document = new XWPFDocument(oPackage);) {
        TokenIterator iterator = new TokenIterator(document);
        XWPFRun run = iterator.next().getRun();
        assertEquals("P1Run1 ", run.getText(run.getTextPosition()));
        run = iterator.next().getRun();
        assertEquals("P1Run2", run.getText(run.getTextPosition()));
        run = iterator.next().getRun();
        assertEquals(" P1Run3", run.getText(run.getTextPosition()));
        run = iterator.next().getRun();
        assertEquals("P2Run1 ", run.getText(run.getTextPosition()));
        run = iterator.next().getRun();
        assertEquals("P2Run2", run.getText(run.getTextPosition()));
        run = iterator.next().getRun();
        assertEquals(" ", run.getText(run.getTextPosition()));
        run = iterator.next().getRun();
        assertEquals("P2Run3", run.getText(run.getTextPosition()));
        run = iterator.next().getRun();
        assertEquals("", run.getText(run.getTextPosition()));
        assertTrue(!iterator.hasNext());
    }
}
 
Example #24
Source File: ELModeTest.java    From poi-tl with Apache License 2.0 6 votes vote down vote up
@Test
public void testPoitlELMode() throws Exception {
    model.getDetail().setDesc(null);
    // poi_tl_mode 当变量不存在时,会友好的认为变量是null,不会抛出异常
    XWPFTemplate template = XWPFTemplate.compile(resource).render(model);
    XWPFDocument document = XWPFTestSupport.readNewDocument(template);
    XWPFParagraph paragraph = document.getParagraphArray(0);
    assertEquals(paragraph.getText(), "Sayi");
    paragraph = document.getParagraphArray(1);
    assertEquals(paragraph.getText(), "卅一");
    paragraph = document.getParagraphArray(3);
    assertEquals(paragraph.getText(), "");
    paragraph = document.getParagraphArray(4);
    assertEquals(paragraph.getText(), "");

    assertEquals(document.getAllPictures().size(), 1);
    assertEquals(document.getTables().size(), 1);
    document.close();
}
 
Example #25
Source File: IfTemplateRenderTest.java    From poi-tl with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("serial")
@Test
public void testIfTrue() throws Exception {
    Map<String, Object> datas = new HashMap<String, Object>() {
        {
            put("title", "poi-tl");
            put("isShowTitle", true);
            put("showUser", new HashMap<String, Object>() {
                {
                    put("user", "Sayi");
                    put("showDate", new HashMap<String, Object>() {
                        {
                            put("date", "2020-02-10");
                        }
                    });
                }
            });
        }
    };

    XWPFTemplate template = XWPFTemplate.compile("src/test/resources/template/iterable_if1.docx");
    template.render(datas);

    XWPFDocument document = XWPFTestSupport.readNewDocument(template);
    XWPFTable table = document.getTableArray(0);
    XWPFTableCell cell = table.getRow(1).getCell(0);
    XWPFHeader header = document.getHeaderArray(0);

    testParagraph(document);
    testParagraph(cell);
    testParagraph(header);
}
 
Example #26
Source File: M2DocWikiTextServices.java    From M2Doc with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Sets the destination {@link XWPFDocument}.
 * 
 * @param destinationDocument
 *            the destination {@link XWPFDocument}
 */
public void setDestinationDocument(XWPFDocument destinationDocument) {
    this.builder = new M2DocMElementBuilder(uriConverter, destinationDocument);
    asciiDocParser.setBuilder(builder);
    confluenceParser.setBuilder(builder);
    markdownParser.setBuilder(builder);
    mediaWikiParser.setBuilder(builder);
    textileParser.setBuilder(builder);
    tracWikiParser.setBuilder(builder);
    tWikiParser.setBuilder(builder);
}
 
Example #27
Source File: TemplateCustomPropertiesTests.java    From M2Doc with Eclipse Public License 1.0 5 votes vote down vote up
@Test
public void getUnusedVariablesInFooter() throws IOException, InvalidFormatException {
    try (XWPFDocument document = POIServices.getInstance().getXWPFDocument(URIConverter.INSTANCE,
            URI.createFileURI("resources/document/properties/unusedVariablesInFooter.docx"));) {
        final TemplateCustomProperties properties = new TemplateCustomProperties(document);
        final List<String> unusedVariables = properties.getUnusedDeclarations();

        assertEquals(1, unusedVariables.size());
        assertEquals("unusedVariable", unusedVariables.get(0));
    }
}
 
Example #28
Source File: TemplateCustomPropertiesTests.java    From M2Doc with Eclipse Public License 1.0 5 votes vote down vote up
@Test
public void setM2DocVersion() throws IOException {
    try (XWPFDocument document = POIServices.getInstance().getXWPFDocument(URIConverter.INSTANCE,
            URI.createFileURI("resources/document/properties/properties-template-m2docVersion.docx"));) {
        final TemplateCustomProperties properties = new TemplateCustomProperties(document);

        assertEquals("2.0.0", properties.getM2DocVersion());

        properties.setM2DocVersion("3.0.0");

        assertEquals("3.0.0", properties.getM2DocVersion());
    }
}
 
Example #29
Source File: RunProviderTests.java    From M2Doc with Eclipse Public License 1.0 5 votes vote down vote up
@Test
public void testHasElements() throws InvalidFormatException, IOException {
    try (FileInputStream is = new FileInputStream("resources/document/notEmpty/notEmpty-template.docx");
            OPCPackage oPackage = OPCPackage.open(is);
            XWPFDocument document = new XWPFDocument(oPackage);) {
        TokenProvider iterator = new TokenProvider(document);
        // CHECKSTYLE:OFF
        assertTrue(iterator.hasElements(7));
        // CHECKSTYLE:ON
        XWPFRun run = iterator.next().getRun();
        assertTrue(iterator.hasElements(6));
        assertEquals("P1Run1 ", run.getText(run.getTextPosition()));
        run = iterator.next().getRun();
        assertTrue(iterator.hasElements(5));
        assertEquals("P1Run2", run.getText(run.getTextPosition()));
        run = iterator.next().getRun();
        assertTrue(iterator.hasElements(4));
        assertEquals(" P1Run3", run.getText(run.getTextPosition()));
        run = iterator.next().getRun();
        assertTrue(iterator.hasElements(3));
        assertEquals("P2Run1 ", run.getText(run.getTextPosition()));
        run = iterator.next().getRun();
        assertTrue(iterator.hasElements(2));
        assertEquals("P2Run2", run.getText(run.getTextPosition()));
        run = iterator.next().getRun();
        assertTrue(iterator.hasElements(1));
        assertEquals(" ", run.getText(run.getTextPosition()));
        run = iterator.next().getRun();
        assertTrue(iterator.hasElements(0));
        assertEquals("P2Run3", run.getText(run.getTextPosition()));
        run = iterator.next().getRun();
        assertEquals("", run.getText(run.getTextPosition()));
        assertTrue(!iterator.hasNext());
    }
}
 
Example #30
Source File: TemplateValidationGeneratorTests.java    From M2Doc with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Ensure that the validation generation produces a document with an error.
 * 
 * @throws InvalidFormatException
 * @throws IOException
 * @throws DocumentParserException
 * @throws DocumentGenerationException
 */
@Test
public void testErrorGeneration()
        throws InvalidFormatException, IOException, DocumentParserException, DocumentGenerationException {
    IQueryEnvironment queryEnvironment = org.eclipse.acceleo.query.runtime.Query
            .newEnvironmentWithDefaultServices(null);
    final File tempFile = File.createTempFile("testParsingErrorSimpleTag", ".docx");

    try (DocumentTemplate documentTemplate = M2DocUtils.parse(URIConverter.INSTANCE,
            URI.createFileURI("resources/document/notEmpty/notEmpty-template.docx"), queryEnvironment,
            new ClassProvider(this.getClass().getClassLoader()), new BasicMonitor())) {
        final XWPFRun location = ((XWPFParagraph) documentTemplate.getDocument().getBodyElements().get(0)).getRuns()
                .get(0);
        documentTemplate.getBody().getValidationMessages().add(
                new TemplateValidationMessage(ValidationMessageLevel.ERROR, "XXXXXXXXXXXXXXXXXXXXXXXX", location));
        M2DocUtils.serializeValidatedDocumentTemplate(URIConverter.INSTANCE, documentTemplate,
                URI.createFileURI(tempFile.getAbsolutePath()));
    }
    assertTrue(new File(tempFile.getAbsolutePath()).exists());

    try (FileInputStream resIs = new FileInputStream(tempFile.getAbsolutePath());
            OPCPackage resOPackage = OPCPackage.open(resIs);
            XWPFDocument resDocument = new XWPFDocument(resOPackage);) {

        final XWPFRun messageRun = M2DocTestUtils.getRunContaining(resDocument, "XXXXXXXXXXXXXXXXXXXXXXXX");

        assertNotNull(messageRun);
        assertEquals("XXXXXXXXXXXXXXXXXXXXXXXX", messageRun.text());
        assertEquals("FF0000", messageRun.getColor());
    }

    tempFile.delete();
}