Example usage for org.apache.poi.xwpf.usermodel XWPFDocument XWPFDocument

List of usage examples for org.apache.poi.xwpf.usermodel XWPFDocument XWPFDocument

Introduction

In this page you can find the example usage for org.apache.poi.xwpf.usermodel XWPFDocument XWPFDocument.

Prototype

public XWPFDocument(InputStream is) throws IOException 

Source Link

Usage

From source file:com.crimelab.service.PolygraphServiceImpl.java

@Override
public XWPFDocument create(Polygraph polygraph, HttpSession session) {
    XWPFDocument document = null;/* w  w  w  .j  a va  2  s .c om*/

    //Insert into dbase
    //        polygraphDAO.polygraphInfo(polygraph);
    try {
        //Blank Document
        InputStream inpDocx = session.getServletContext()
                .getResourceAsStream("/WEB-INF/templates/Polygraph.docx");
        document = new XWPFDocument(inpDocx);

        //create Paragraph
        XWPFParagraph subjectNo = document.createParagraph();
        XWPFRun r1 = subjectNo.createRun();
        r1.setText("POLYGRAPH SUBJECT NO: " + polygraph.getSubjectNo());
        subjectNo.setAlignment(ParagraphAlignment.CENTER);
        r1.setBold(true);
        ;

        //create table
        XWPFTable table = document.createTable();
        //width 
        CTTbl tableFix = table.getCTTbl();
        CTTblPr pr = tableFix.getTblPr();
        CTTblWidth tblW = pr.getTblW();
        tblW.setW(BigInteger.valueOf(4800));
        tblW.setType(STTblWidth.PCT);
        pr.setTblW(tblW);
        tableFix.setTblPr(pr);

        //create first row
        XWPFTableRow tableRowOne = table.getRow(0);
        XWPFTableCell headerCell = tableRowOne.getCell(0);
        XWPFParagraph headerParagraph = headerCell.getParagraphs().get(0);
        XWPFRun hRun = headerParagraph.createRun();
        headerCell.setColor("CDCDB4");
        hRun.setText("PERSONAL INFORMATION");
        tableRowOne.addNewTableCell().setText(null);

        headerParagraph.setAlignment(ParagraphAlignment.CENTER);
        XWPFTableCell photoHeaderCell = tableRowOne.getCell(1);
        XWPFParagraph photoHeaderParagraph = photoHeaderCell.getParagraphs().get(0);
        XWPFRun pRun = photoHeaderParagraph.createRun();
        photoHeaderCell.setColor("CDCDB4");
        pRun.setText("PHOTO");
        photoHeaderParagraph.setAlignment(ParagraphAlignment.CENTER);

        XWPFTableRow tableRowTwo = table.createRow();
        XWPFTableCell cell = tableRowTwo.getCell(0);
        XWPFParagraph personalInfo = cell.getParagraphs().get(0);
        XWPFRun r2 = personalInfo.createRun();
        r2.setText("Name");
        r2.addTab();
        r2.addTab();
        r2.setText(": " + polygraph.getName());
        r2.addBreak();
        r2.setText("Gender");
        r2.addTab();
        r2.addTab();
        r2.setText(": " + polygraph.getGender());
        r2.addBreak();
        r2.setText("Age");
        r2.addTab();
        r2.addTab();
        r2.setText(": " + polygraph.getAge());
        r2.addBreak();
        r2.setText("Date of Birth");
        r2.addTab();
        r2.setText(": " + polygraph.getBirthdate());
        r2.addBreak();
        r2.setText("Civil Status");
        r2.addTab();
        r2.setText(": " + polygraph.getCivilStatus());
        r2.addBreak();
        r2.setText("ID Presented");
        r2.addTab();
        r2.setText(": " + polygraph.getIdPresented());
        r2.addBreak();
        r2.setText("Address");
        r2.addTab();
        r2.setText(": " + polygraph.getAddress());

        //Adding the picture
        XWPFTableCell pictureCell = tableRowTwo.getCell(1);
        XWPFParagraph pictureHolder = pictureCell.getParagraphs().get(0);
        XWPFRun pictureRun = pictureHolder.createRun();
        FileInputStream getPhoto = new FileInputStream(polygraph.getPhotoLocation());
        FileInputStream getImage = new FileInputStream(polygraph.getPhotoLocation());
        ImageInputStream imageInput = ImageIO.createImageInputStream(getPhoto);
        BufferedImage bi = ImageIO.read(imageInput);
        pictureHolder.setAlignment(ParagraphAlignment.RIGHT);
        pictureRun.addPicture(getImage, XWPFDocument.PICTURE_TYPE_JPEG, null, Units.toEMU(120),
                Units.toEMU(120));

        XWPFParagraph spacing = document.createParagraph();
        XWPFRun spacingRun = spacing.createRun();

        //create table
        XWPFTable otherTable = document.createTable();
        //width 
        CTTbl tableFixTwo = otherTable.getCTTbl();
        CTTblPr prTwo = tableFixTwo.getTblPr();
        CTTblWidth tblWTwo = prTwo.getTblW();
        tblWTwo.setW(BigInteger.valueOf(4800));
        tblWTwo.setType(STTblWidth.PCT);
        prTwo.setTblW(tblWTwo);
        tableFixTwo.setTblPr(prTwo);

        XWPFTableRow examInfoHeader = otherTable.createRow();
        XWPFTableCell cellInfo = examInfoHeader.getCell(0);
        XWPFParagraph examInfo = cellInfo.getParagraphs().get(0);
        XWPFRun r3 = examInfo.createRun();
        cellInfo.setColor("CDCDB4");
        r3.setText("EXAM INFORMATION");
        examInfo.setAlignment(ParagraphAlignment.CENTER);

        XWPFTableRow examInfoRow = otherTable.createRow();
        XWPFTableCell cellRowInfo = examInfoRow.getCell(0);
        XWPFParagraph examInfoRowP = cellRowInfo.getParagraphs().get(0);
        XWPFRun examRun = examInfoRowP.createRun();
        examRun.setText("Case Number");
        examRun.addTab();
        examRun.addTab();
        examRun.setText(": " + polygraph.getCaseNo());
        examRun.addBreak();
        examRun.setText("Requesting Party");
        examRun.addTab();
        examRun.setText(": " + polygraph.getRequestingParty());
        examRun.addBreak();
        examRun.setText("Time/Date Received");
        examRun.addTab();
        examRun.setText(": " + polygraph.getTimeDateReceived());
        examRun.addBreak();
        examRun.setText("Nature of Case");
        examRun.addTab();
        examRun.addTab();
        examRun.setText(": " + polygraph.getNatureOfCase());
        examRun.addBreak();
        examRun.setText("Exam Location");
        examRun.addTab();
        examRun.addTab();
        examRun.setText(": " + polygraph.getExamLocation());
        examRun.addBreak();
        examRun.setText("Exam Date");
        examRun.addTab();
        examRun.addTab();
        examRun.setText(": " + polygraph.getExamDate());

        otherTable.removeRow(0);

        XWPFParagraph purposeOfExamination = document.createParagraph();
        XWPFRun r4 = purposeOfExamination.createRun();
        r4.setUnderline(UnderlinePatterns.SINGLE);
        r4.addBreak();
        r4.setText("SECTION 1: PURPOSE OF EXAMINATION");
        r4.addTab();
        r4.addTab();
        r4.addTab();
        r4.addTab();
        r4.addTab();
        r4.addTab();
        r4.addTab();
        r4.addTab();
        r4.addTab();

        XWPFParagraph purposeOfExaminationContents = document.createParagraph();
        XWPFRun r4Contents = purposeOfExaminationContents.createRun();
        r4Contents.setText(polygraph.getPurpose());

        XWPFParagraph preTestInterview = document.createParagraph();
        XWPFRun r5 = preTestInterview.createRun();
        r5.setUnderline(UnderlinePatterns.SINGLE);
        r5.setText("SECTION 2: PRE-TEST INTERVIEW");
        r5.addTab();
        r5.addTab();
        r5.addTab();
        r5.addTab();
        r5.addTab();
        r5.addTab();
        r5.addTab();
        r5.addTab();
        r5.addTab();

        XWPFParagraph preTestInterviewContents = document.createParagraph();
        XWPFRun r5Contents = preTestInterviewContents.createRun();
        r5Contents.setText(polygraph.getPreTest());

        XWPFParagraph inTestPhase = document.createParagraph();
        XWPFRun r6 = inTestPhase.createRun();
        r6.setUnderline(UnderlinePatterns.SINGLE);
        r6.setText("SECTION 3: IN-TEST PHASE");
        r6.addTab();
        r6.addTab();
        r6.addTab();
        r6.addTab();
        r6.addTab();
        r6.addTab();
        r6.addTab();
        r6.addTab();
        r6.addTab();
        r6.addTab();

        XWPFParagraph inTestPhaseContents = document.createParagraph();
        XWPFRun r6Contents = inTestPhaseContents.createRun();
        r6Contents.setText(polygraph.getInTest());

        XWPFParagraph result = document.createParagraph();
        XWPFRun r7 = result.createRun();
        r7.setUnderline(UnderlinePatterns.SINGLE);
        r7.setText("SECTION 4: RESULT");
        r7.addTab();
        r7.addTab();
        r7.addTab();
        r7.addTab();
        r7.addTab();
        r7.addTab();
        r7.addTab();
        r7.addTab();
        r7.addTab();
        r7.addTab();
        r7.addTab();

        XWPFParagraph resultContents = document.createParagraph();
        XWPFRun r7Contents = resultContents.createRun();
        r7Contents.setText(polygraph.getResult());

        XWPFParagraph postTestInterview = document.createParagraph();
        XWPFRun r8 = postTestInterview.createRun();
        r8.setUnderline(UnderlinePatterns.SINGLE);
        r8.setText("SECTION 5: POST-TEST INTERVIEW");
        r8.addTab();
        r8.addTab();
        r8.addTab();
        r8.addTab();
        r8.addTab();
        r8.addTab();
        r8.addTab();
        r8.addTab();
        r8.addTab();

        XWPFParagraph postTestInterviewContents = document.createParagraph();
        XWPFRun r8Contents = postTestInterviewContents.createRun();
        r8Contents.setText(polygraph.getPostTest());

        XWPFParagraph remarks = document.createParagraph();
        XWPFRun r9 = remarks.createRun();
        r9.setUnderline(UnderlinePatterns.SINGLE);
        r9.setText("REMARKS:");
        r9.addTab();
        r9.addTab();
        r9.addTab();
        r9.addTab();
        r9.addTab();
        r9.addTab();
        r9.addTab();
        r9.addTab();
        r9.addTab();
        r9.addTab();
        r9.addTab();
        r9.addTab();

        XWPFParagraph remarksContents = document.createParagraph();
        XWPFRun r9Contents = remarksContents.createRun();
        r9Contents.setText(polygraph.getRemarks());

        XWPFParagraph timeDateCompleted = document.createParagraph();
        XWPFRun r10 = timeDateCompleted.createRun();
        r10.setUnderline(UnderlinePatterns.SINGLE);
        r10.setText("TIME AND DATE COMPLETED:");
        r10.addTab();
        r10.addTab();
        r10.addTab();
        r10.addTab();
        r10.addTab();
        r10.addTab();
        r10.addTab();
        r10.addTab();
        r10.addTab();
        r10.addTab();

        XWPFParagraph timeDateCompletedContents = document.createParagraph();
        XWPFRun r10Contents = timeDateCompletedContents.createRun();
        r10Contents.setText(polygraph.getTimeDateCompleted());

        XWPFParagraph examinedBy = document.createParagraph();
        XWPFRun r11 = examinedBy.createRun();
        r11.setUnderline(UnderlinePatterns.SINGLE);
        r11.setText("EXAMINED BY:");
        r11.addTab();
        r11.addTab();
        r11.addTab();
        r11.addTab();
        r11.addTab();
        r11.addTab();
        r11.addTab();
        r11.addTab();
        r11.addTab();
        r11.addTab();
        r11.addTab();
        r11.addTab();

        XWPFParagraph examinedByContents = document.createParagraph();
        XWPFRun r11Contents = examinedByContents.createRun();
        r11Contents.setText(polygraph.getExaminerName());
        r11Contents.addBreak();
        r11Contents.setText(polygraph.getExaminerRank());
        r11Contents.addBreak();
        r11Contents.setText(polygraph.getExaminerPosition());

        XWPFParagraph approvedBy = document.createParagraph();
        XWPFRun r12 = approvedBy.createRun();
        r12.setUnderline(UnderlinePatterns.SINGLE);
        r12.setText("APPROVED BY:");
        r12.addTab();
        r12.addTab();
        r12.addTab();
        r12.addTab();
        r12.addTab();
        r12.addTab();
        r12.addTab();
        r12.addTab();
        r12.addTab();
        r12.addTab();
        r12.addTab();
        r12.addTab();

        XWPFParagraph approvedByContents = document.createParagraph();
        XWPFRun r12Contents = approvedByContents.createRun();
        //            r12Contents.setText(polygraph.getApprovedName());
        //            r12Contents.addBreak();
        //            r12Contents.setText(polygraph.getApprovedRank());
        //            r12Contents.addBreak();
        //            r12Contents.setText(polygraph.getApprovedPosition());
        //            r12Contents.addBreak();

        XWPFParagraph notedBy = document.createParagraph();
        XWPFRun r13 = notedBy.createRun();
        r13.setUnderline(UnderlinePatterns.SINGLE);
        r13.setText("NOTED BY:");
        r13.addTab();
        r13.addTab();
        r13.addTab();
        r13.addTab();
        r13.addTab();
        r13.addTab();
        r13.addTab();
        r13.addTab();
        r13.addTab();
        r13.addTab();
        r13.addTab();
        r13.addTab();

        XWPFParagraph notedByContents = document.createParagraph();
        XWPFRun r13Contents = notedByContents.createRun();
        r13Contents.setText(polygraph.getNotedName());
        r13Contents.addBreak();
        r13Contents.setText(polygraph.getNotedRank());
        r13Contents.addBreak();
        r13Contents.setText(polygraph.getNotedPosition());
        r13Contents.addBreak();
        table.setInsideVBorder(XWPFTable.XWPFBorderType.NIL, 0, 0, "white");

        document.getXWPFDocument();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return document;
}

From source file:com.docdoku.server.esindexer.ESTools.java

License:Open Source License

private static String microsoftWordDocumentToString(InputStream inputStream) throws IOException {
    String strRet;//from ww  w .  j ava  2 s  .  c  o  m
    try (InputStream wordStream = new BufferedInputStream(inputStream)) {
        if (POIFSFileSystem.hasPOIFSHeader(wordStream)) {
            WordExtractor wordExtractor = new WordExtractor(wordStream);
            strRet = wordExtractor.getText();
        } else {
            XWPFWordExtractor wordXExtractor = new XWPFWordExtractor(new XWPFDocument(wordStream));
            strRet = wordXExtractor.getText();
        }
    }
    return strRet;
}

From source file:com.example.office.DOCDocumentParse.java

@SuppressWarnings("unused")
private File doc2docxOld(File docFile) {
    String docxFilePath = docFile.getPath() + "x";
    File docxFile = new File(docxFilePath);
    if (!docxFile.exists()) {
        XWPFDocument document = null;/*from  ww w  . jav  a2 s  .  co  m*/
        try (InputStream ins = new FileInputStream(docxFile);
                OutputStream out = new FileOutputStream(docxFile);) {
            Document doc = new Document(docFile.getPath());
            doc.save(docxFile.getPath());
            document = new XWPFDocument(ins);

            // document.removeBodyElement(0)
            List<IBodyElement> elements = document.getBodyElements();
            IBodyElement element = elements.get(elements.size() - 1);
            if (StringUtils.equals(BodyElementType.PARAGRAPH.name(), element.getElementType().name())) {
                XWPFParagraph xp = ((XWPFParagraph) element);
                String text = xp.getText();
                if (StringUtils.isNotBlank(text)) {
                    if (text.contains("Evaluation") && text.contains("Aspose")) {
                        document.removeBodyElement(elements.size() - 1);
                    }
                }
            }
            IBodyElement element0 = elements.get(0);
            if (StringUtils.equals(BodyElementType.PARAGRAPH.name(), element0.getElementType().name())) {
                XWPFParagraph xp = ((XWPFParagraph) element0);
                String text = xp.getText();
                if (StringUtils.isNotBlank(text)) {
                    if (text.contains("Evaluation") && text.contains("Aspose")) {
                        document.removeBodyElement(0);
                    }
                }
            }

            document.write(out);
        } catch (Exception e) {
            LogUtils.writeWarnExceptionLog(log, e);
        } finally {
            try {
                if (document != null)
                    document.close();
            } catch (IOException e) {
                LogUtils.writeDebugExceptionLog(log, e);
            }
        }
    }
    return docxFile;
}

From source file:com.example.office.DOCDocumentParse.java

private void deleteAsposeInfo(File docxFile) {
    XWPFDocument document = null;/*  w  w w  . j a v a 2s.c  o m*/
    try (InputStream ins = new FileInputStream(docxFile); OutputStream out = new FileOutputStream(docxFile);) {
        document = new XWPFDocument(ins);
        List<IBodyElement> elements = document.getBodyElements();
        IBodyElement element = elements.get(elements.size() - 1);
        if (StringUtils.equals(BodyElementType.PARAGRAPH.name(), element.getElementType().name())) {
            XWPFParagraph xp = ((XWPFParagraph) element);
            String text = xp.getText();
            if (StringUtils.isNotBlank(text)) {
                if (text.contains("Evaluation") && text.contains("Aspose")) {
                    document.removeBodyElement(elements.size() - 1);
                }
            }
        }
        IBodyElement element0 = elements.get(0);
        if (StringUtils.equals(BodyElementType.PARAGRAPH.name(), element0.getElementType().name())) {
            XWPFParagraph xp = ((XWPFParagraph) element0);
            String text = xp.getText();
            if (StringUtils.isNotBlank(text)) {
                if (text.contains("Evaluation") && text.contains("Aspose")) {
                    document.removeBodyElement(0);
                }
            }
        }

        document.write(out);
    } catch (Exception e) {
        LogUtils.writeWarnExceptionLog(log, e);
    } finally {
        if (document != null) {
            try {
                document.close();
            } catch (IOException e) {
                LogUtils.writeDebugExceptionLog(log, e);
            }
        }

    }
}

From source file:com.foc.vaadin.gui.mswordGenerator.FocXmlMSWordParser.java

License:Apache License

private XWPFDocument createDocument() {
    if (document == null) {
        try {//from  w  w w. j a  va  2 s.  c o  m
            FocXMLLayout xmlLayout = getFocXMLLayout();
            if (xmlLayout != null && xmlLayout.isArabic()) {
                document = new XWPFDocument(
                        this.getClass().getClassLoader().getResourceAsStream("templates/rtl.dotx"));
            } else {
                document = new XWPFDocument();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    return document;
}

From source file:com.frameworkset.platform.cms.searchmanager.extractors.CmsExtractorMsWord.java

License:Open Source License

/** 
 * @see org.opencms.search.extractors.I_CmsTextExtractor#extractText(java.io.InputStream, java.lang.String)
 *//*w  w w.j  a  v a 2s.  com*/
public I_CmsExtractionResult extractText(InputStream in, String encoding) throws Exception {

    // first extract the text using the text actraction libary
    //       WordTextExtractorFactory factory = new WordTextExtractorFactory();

    //        TextExtractor wordExtractor = factory.textExtractor(getStreamCopy(in));

    //        String result = wordExtractor.getText();
    //        String result = wordExtractor.extractText(getStreamCopy(in));
    StringBuffer content = new StringBuffer();
    //       org.apache.poi.hwpf

    //        HWPFDocument doc = new HWPFDocument(in);
    //         Range range = doc.getRange();
    //         int paragraphCount = range.numParagraphs();// ?
    //         for (int i = 0; i < paragraphCount; i++) {// ?????
    //             Paragraph pp = range.getParagraph(i);
    //             content.append(pp.text());
    //         }
    String result = null;
    Map metaInfo = null;
    if (version.equals(ContentHandler.VERSION_2003)) {
        WordExtractor ex = new WordExtractor(in);
        result = ex.getText();
        SummaryInformation info = ex.getSummaryInformation();
        this.m_summary = info;
        this.m_documentSummary = ex.getDocSummaryInformation();
        metaInfo = extractMetaInformation();
    } else {
        XWPFDocument doc = new XWPFDocument(in);
        XWPFWordExtractor ex = new XWPFWordExtractor(doc);
        result = ex.getText();
        cp = ex.getCoreProperties();
        metaInfo = extractMetaInformation();
        //           SummaryInformation info = doc.getSummaryInformation();
        //             this.m_summary = info;
        //             this.m_documentSummary = doc.getDocSummaryInformation();
    }

    //        result = removeControlChars(result);

    //     String result = content.toString();
    // now extract the meta information using POI 
    //        POIFSReader reader = new POIFSReader();
    //        reader.registerListener(this);
    //        reader.read(getStreamCopy(getStreamCopy(in)));

    // free some memory
    cleanup();

    // return the final result
    return new CmsExtractionResult(result, metaInfo);
}

From source file:com.fy.utils.xwpf.XWPFTestDataSamples.java

License:Apache License

public static XWPFDocument openSampleDocument(String sampleName) throws IOException {
    InputStream is = POIDataSamples.getDocumentInstance().openResourceAsStream(sampleName);
    return new XWPFDocument(is);
}

From source file:com.fy.utils.xwpf.XWPFTestDataSamples.java

License:Apache License

public static XWPFDocument writeOutAndReadBack(XWPFDocument doc) throws IOException {
    ByteArrayOutputStream baos = new ByteArrayOutputStream(4096);
    doc.write(baos);/*w w w .j av a2 s.c  o  m*/
    ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
    return new XWPFDocument(bais);
}

From source file:com.gezipu360.cashier.bean.word.UpdateEmbeddedDoc.java

License:Apache License

/**
 * Create a new instance of the UpdateEmbeddedDoc class using the following
 * parameters;//from w ww . ja  v a 2s  .co m
 *
 * @param filename An instance of the String class that encapsulates the name
 *                 of and path to a WordprocessingML Word document that contains an
 *                 embedded binary Excel workbook.
 * @throws java.io.FileNotFoundException Thrown if the file cannot be found
 *                                       on the underlying file system.
 * @throws java.io.IOException           Thrown if a problem occurs in the underlying
 *                                       file system.
 */
public UpdateEmbeddedDoc(String filename) throws FileNotFoundException, IOException {
    this.docFile = new File(filename);
    FileInputStream fis = null;
    if (!this.docFile.exists()) {
        throw new FileNotFoundException("The Word dcoument " + filename + " does not exist.");
    }
    try {

        // Open the Word document file and instantiate the XWPFDocument
        // class.
        fis = new FileInputStream(this.docFile);
        this.doc = new XWPFDocument(fis);
    } finally {
        if (fis != null) {
            try {
                fis.close();
                fis = null;
            } catch (IOException ioEx) {
                System.out.println("IOException caught trying to close "
                        + "FileInputStream in the constructor of " + "UpdateEmbeddedDoc.");
            }
        }
    }
}

From source file:com.jaeksoft.searchlib.parser.DocxParser.java

License:Open Source License

@Override
protected void parseContent(StreamLimiter streamLimiter, LanguageEnum lang) throws IOException {

    ParserResultItem result = getNewParserResultItem();

    XWPFDocument document = new XWPFDocument(streamLimiter.getNewInputStream());
    XWPFWordExtractor word = null;/*from w w w  .  j  a v  a 2  s .c o  m*/
    try {
        word = new XWPFWordExtractor(document);

        CoreProperties info = word.getCoreProperties();
        if (info != null) {
            result.addField(ParserFieldEnum.title, info.getTitle());
            result.addField(ParserFieldEnum.creator, info.getCreator());
            result.addField(ParserFieldEnum.subject, info.getSubject());
            result.addField(ParserFieldEnum.description, info.getDescription());
            result.addField(ParserFieldEnum.keywords, info.getKeywords());
        }

        String content = word.getText();
        result.addField(ParserFieldEnum.content, StringUtils.replaceConsecutiveSpaces(content, " "));

        result.langDetection(10000, ParserFieldEnum.content);
    } finally {
        IOUtils.close(word);
    }
}