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
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 Project: frpMgr   Author: Zo3i   File: BookMarks.java    License: 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 #3
Source Project: autopoi   Author: zhangdaiscott   File: JeecgTemplateWordView.java    License: 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 #4
Source Project: M2Doc   Author: ObeoNetwork   File: RawCopier.java    License: 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 #5
Source Project: everywhere   Author: madneal   File: FileBeanParser.java    License: 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 #6
Source Project: kbase-doc   Author: ekoz   File: WatermarkWordTests.java    License: 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 #7
Source Project: sun-wordtable-read   Author: suncht   File: WordXTableParser.java    License: 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 #8
Source Project: eplmp   Author: polarsys   File: IndexerTextExtractor.java    License: 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 #9
Source Project: M2Doc   Author: ObeoNetwork   File: GenconfUtilsTests.java    License: 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 #10
Source Project: M2Doc   Author: ObeoNetwork   File: AbstractBodyParser.java    License: 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 #11
Source Project: M2Doc   Author: ObeoNetwork   File: GenconfUtilsTests.java    License: 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 #12
Source Project: M2Doc   Author: ObeoNetwork   File: GenconfUtilsTests.java    License: 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 #13
Source Project: M2Doc   Author: ObeoNetwork   File: GenconfUtilsTests.java    License: 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 #14
Source Project: M2Doc   Author: ObeoNetwork   File: RunProviderTests.java    License: 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 #15
Source Project: M2Doc   Author: ObeoNetwork   File: RunProviderTests.java    License: 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 #16
Source Project: M2Doc   Author: ObeoNetwork   File: RunProviderTests.java    License: 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 #17
Source Project: M2Doc   Author: ObeoNetwork   File: RunIteratorTests.java    License: 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 #18
Source Project: poi-tl   Author: Sayi   File: ELModeTest.java    License: 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 #19
Source Project: M2Doc   Author: ObeoNetwork   File: RawCopier.java    License: 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 #20
Source Project: M2Doc   Author: ObeoNetwork   File: M2DocNewProjectWizard.java    License: 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 #21
Source Project: M2Doc   Author: ObeoNetwork   File: M2DocTestUtils.java    License: 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 #22
Source Project: M2Doc   Author: ObeoNetwork   File: M2DocUtils.java    License: 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 #23
Source Project: poi-tl   Author: Sayi   File: ELModeTest.java    License: 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 #24
Source Project: xdocreport.samples   Author: opensagres   File: ConvertDocxBigToPDF.java    License: 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 #25
Source Project: autopoi   Author: zhangdaiscott   File: PoiPublicUtil.java    License: Apache License 2.0 5 votes vote down vote up
private static Integer getImageType(String type) {
	if (type.equalsIgnoreCase("JPG") || type.equalsIgnoreCase("JPEG")) {
		return XWPFDocument.PICTURE_TYPE_JPEG;
	}
	if (type.equalsIgnoreCase("GIF")) {
		return XWPFDocument.PICTURE_TYPE_GIF;
	}
	if (type.equalsIgnoreCase("BMP")) {
		return XWPFDocument.PICTURE_TYPE_GIF;
	}
	if (type.equalsIgnoreCase("PNG")) {
		return XWPFDocument.PICTURE_TYPE_PNG;
	}
	return XWPFDocument.PICTURE_TYPE_JPEG;
}
 
Example #26
Source Project: poi-tl   Author: Sayi   File: NumberingContinue.java    License: Apache License 2.0 5 votes vote down vote up
public void updateNumbering(XWPFParagraph source, XWPFParagraph target) {
    XWPFDocument document = source.getDocument();
    XWPFNumbering numbering = document.getNumbering();
    if (null == numbering) return;
    BigInteger numID = source.getNumID();
    if (numID == null) return;

    if (null != continueNumID && numID.equals(continueNumID)) { return; }

    if (consistCache.get(numID) != null) {
        target.setNumID(consistCache.get(numID));
        return;
    }

    NumberingWrapper wrapper = new NumberingWrapper(numbering);
    XWPFNum num = numbering.getNum(numID);
    if (null == num) return;
    XWPFAbstractNum abstractNum = numbering.getAbstractNum(num.getCTNum().getAbstractNumId().getVal());
    CTAbstractNum ctAbstractNum = (CTAbstractNum) abstractNum.getAbstractNum().copy();
    ctAbstractNum.setAbstractNumId(wrapper.getNextAbstractNumID());

    // clear continues list
    // (related to tracking numbering definitions when documents are
    // repurposed and
    // changed
    if (ctAbstractNum.isSetNsid()) ctAbstractNum.unsetNsid();
    // related to where the definition can be displayed in the user
    // interface
    if (ctAbstractNum.isSetTmpl()) ctAbstractNum.unsetTmpl();

    BigInteger abstractNumID = numbering.addAbstractNum(new XWPFAbstractNum(ctAbstractNum));
    BigInteger newNumId = numbering.addNum(abstractNumID);
    target.setNumID(newNumId);
    consistCache.put(numID, newNumId);
}
 
Example #27
Source Project: sun-wordtable-read   Author: suncht   File: WordTableCellContentOleObject.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 读取Ole对象
 * 
 * @param embedId
 * @param xdoc
 * @return
 */
private WcOleObject readOleObject(String embedId, final XWPFDocument xdoc) {
	if (StringUtils.isBlank(embedId)) {
		return null;
	}
	WcOleObject oleObject = null;
	List<POIXMLDocumentPart> parts = xdoc.getRelations();
	for (POIXMLDocumentPart poixmlDocumentPart : parts) {
		String id = poixmlDocumentPart.getPackageRelationship().getId();
		if (embedId.equals(id)) {
			PackagePart packagePart = poixmlDocumentPart.getPackagePart();

			oleObject = new WcOleObject();
			// oleObjectContent.setFileName(packagePart.getPartName().getName());

			// 解析Ole对象中的文件,参考:http://poi.apache.org/poifs/how-to.html
			try (InputStream is = packagePart.getInputStream();) {
				POIFSFileSystem poifs = new POIFSFileSystem(is);

				if (isOle10NativeObject(poifs.getRoot())) {
					oleObject = readOle10Native(poifs);
				} else {
					oleObject = readDocumentOle(poifs, is);
				}
			} catch (Exception e) {
				logger.error(e.getMessage(), e);
			}
		}
	}

	return oleObject;
}
 
Example #28
Source Project: M2Doc   Author: ObeoNetwork   File: M2DocUtils.java    License: Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Parses a document for {@link UserContent} and returns the {@link DocumentTemplate} resulting from
 * this parsing.
 * 
 * @param uriConverter
 *            the {@link URIConverter uri converter} to use.
 * @param documentURI
 *            URI for the document
 * @param queryEnvironment
 *            the {@link IQueryEnvironment}
 * @return the {@link DocumentTemplate} resulting from parsing the specified
 *         document
 * @throws DocumentParserException
 *             if a problem occurs while parsing the document.
 */
@SuppressWarnings("resource")
public static DocumentTemplate parseUserContent(URIConverter uriConverter, URI documentURI,
        IQueryEnvironment queryEnvironment) throws DocumentParserException {
    final DocumentTemplate result = (DocumentTemplate) EcoreUtil.create(TemplatePackage.Literals.DOCUMENT_TEMPLATE);
    final ResourceImpl r = new ResourceImpl(documentURI);

    try {
        // resources are closed in DocumentTemplate.close()
        final InputStream is = uriConverter.createInputStream(documentURI);
        final OPCPackage oPackage = OPCPackage.open(is);
        final XWPFDocument document = new XWPFDocument(oPackage);
        r.getContents().add(result);
        final BodyGeneratedParser parser = new BodyGeneratedParser(document, queryEnvironment);
        result.setBody(parser.parseBlock(null));
        result.setInputStream(is);
        result.setOpcPackage(oPackage);
        result.setDocument(document);
        for (XWPFFooter footer : document.getFooterList()) {
            final BodyGeneratedParser footerParser = new BodyGeneratedParser(footer, queryEnvironment);
            result.getFooters().add(footerParser.parseBlock(null));
        }
        for (XWPFHeader header : document.getHeaderList()) {
            final BodyGeneratedParser headerParser = new BodyGeneratedParser(header, queryEnvironment);
            result.getHeaders().add(headerParser.parseBlock(null));
        }

    } catch (IOException e) {
        throw new DocumentParserException("Unable to open " + documentURI, e);
    } catch (InvalidFormatException e1) {
        throw new DocumentParserException("Invalid .docx format " + documentURI, e1);
    }

    return result;
}
 
Example #29
Source Project: sun-wordtable-read   Author: suncht   File: WordEmbedsTest.java    License: Apache License 2.0 5 votes vote down vote up
private static void listEmbeds(XWPFDocument doc) throws OpenXML4JException {
	List<PackagePart> embeddedDocs = doc.getAllEmbedds();
	if (embeddedDocs != null && !embeddedDocs.isEmpty()) {
		Iterator<PackagePart> pIter = embeddedDocs.iterator();
		while (pIter.hasNext()) {
			PackagePart pPart = pIter.next();
			System.out.print(pPart.getPartName() + ", ");

			System.out.print(pPart.getContentType() + ", ");
			System.out.println();
		}
	}
}
 
Example #30
Source Project: sun-wordtable-read   Author: suncht   File: WordEmbedsTest.java    License: Apache License 2.0 5 votes vote down vote up
private static void listEmbeds2(XWPFDocument doc) throws Exception {
	for (final PackagePart pPart : doc.getAllEmbedds()) {
		final String contentType = pPart.getContentType();
		System.out.println(contentType + "\n");
		if (contentType.equals("application/vnd.ms-excel")) {
			final HSSFWorkbook embeddedWorkbook = new HSSFWorkbook(pPart.getInputStream());

			for (int sheet = 0; sheet < embeddedWorkbook.getNumberOfSheets(); sheet++) {
				final HSSFSheet activeSheet = embeddedWorkbook.getSheetAt(sheet);
				if (activeSheet.getSheetName().equalsIgnoreCase("Sheet1")) {
					for (int rowIndex = activeSheet.getFirstRowNum(); rowIndex <= activeSheet
							.getLastRowNum(); rowIndex++) {
						final HSSFRow row = activeSheet.getRow(rowIndex);
						for (int cellIndex = row.getFirstCellNum(); cellIndex <= row
								.getLastCellNum(); cellIndex++) {
							final HSSFCell cell = row.getCell(cellIndex);
							if (cell != null) {
								if (cell.getCellType() == Cell.CELL_TYPE_STRING)
									System.out.println("Row:" + rowIndex + " Cell:" + cellIndex + " = "
											+ cell.getStringCellValue());
								if (cell.getCellType() == Cell.CELL_TYPE_NUMERIC) {
									System.out.println("Row:" + rowIndex + " Cell:" + cellIndex + " = "
											+ cell.getNumericCellValue());

									cell.setCellValue(cell.getNumericCellValue() * 2); // update
																						// the
																						// value
								}
							}
						}
					}
				}
			}
		}
	}
}