Search in sources :

Example 1 with Picture

use of org.apache.poi.hwpf.usermodel.Picture in project poi by apache.

the class TestHWPFPictures method testEscherDrawing.

/**
	 * Pending the missing files being uploaded to
	 *  bug #44937
	 */
public void testEscherDrawing() {
    HWPFDocument docD = HWPFTestDataSamples.openSampleFile(docDFile);
    List<Picture> allPictures = docD.getPicturesTable().getAllPictures();
    assertEquals(1, allPictures.size());
    Picture pic = allPictures.get(0);
    assertNotNull(pic);
    byte[] picD = readFile(imgDFile);
    assertEquals(picD.length, pic.getContent().length);
    assertBytesSame(picD, pic.getContent());
}
Also used : Picture(org.apache.poi.hwpf.usermodel.Picture)

Example 2 with Picture

use of org.apache.poi.hwpf.usermodel.Picture in project poi by apache.

the class TestHWPFPictures method testImageData.

/**
	 * Test that we have the right images in at least one file
	 */
public void testImageData() {
    HWPFDocument docB = HWPFTestDataSamples.openSampleFile(docBFile);
    PicturesTable picB = docB.getPicturesTable();
    List<Picture> picturesB = picB.getAllPictures();
    assertEquals(2, picturesB.size());
    Picture pic1 = picturesB.get(0);
    Picture pic2 = picturesB.get(1);
    assertNotNull(pic1);
    assertNotNull(pic2);
    // Check the same
    byte[] pic1B = readFile(imgAFile);
    byte[] pic2B = readFile(imgBFile);
    assertEquals(pic1B.length, pic1.getContent().length);
    assertEquals(pic2B.length, pic2.getContent().length);
    assertBytesSame(pic1B, pic1.getContent());
    assertBytesSame(pic2B, pic2.getContent());
}
Also used : Picture(org.apache.poi.hwpf.usermodel.Picture) PicturesTable(org.apache.poi.hwpf.model.PicturesTable)

Example 3 with Picture

use of org.apache.poi.hwpf.usermodel.Picture in project poi by apache.

the class TestHWPFPictures method testCompressedImageData.

/**
	 * Test that compressed image data is correctly returned.
	 */
public void testCompressedImageData() {
    HWPFDocument docC = HWPFTestDataSamples.openSampleFile(docCFile);
    PicturesTable picC = docC.getPicturesTable();
    List<Picture> picturesC = picC.getAllPictures();
    assertEquals(1, picturesC.size());
    Picture pic = picturesC.get(0);
    assertNotNull(pic);
    // Check the same
    byte[] picBytes = readFile(imgCFile);
    assertEquals(picBytes.length, pic.getContent().length);
    assertBytesSame(picBytes, pic.getContent());
}
Also used : Picture(org.apache.poi.hwpf.usermodel.Picture) PicturesTable(org.apache.poi.hwpf.model.PicturesTable)

Example 4 with Picture

use of org.apache.poi.hwpf.usermodel.Picture in project poi by apache.

the class AbstractWordConverter method processCharacters.

protected boolean processCharacters(final HWPFDocumentCore wordDocument, final int currentTableLevel, final Range range, final Element block) {
    if (range == null)
        return false;
    boolean haveAnyText = false;
    /*
         * In text there can be fields, bookmarks, may be other structures (code
         * below allows extension). Those structures can overlaps, so either we
         * should process char-by-char (slow) or find a correct way to
         * reconstruct the structure of range -- sergey
         */
    List<Structure> structures = new LinkedList<Structure>();
    if (wordDocument instanceof HWPFDocument) {
        final HWPFDocument doc = (HWPFDocument) wordDocument;
        Map<Integer, List<Bookmark>> rangeBookmarks = doc.getBookmarks().getBookmarksStartedBetween(range.getStartOffset(), range.getEndOffset());
        if (rangeBookmarks != null) {
            for (List<Bookmark> lists : rangeBookmarks.values()) {
                for (Bookmark bookmark : lists) {
                    if (!bookmarkStack.contains(bookmark))
                        addToStructures(structures, new Structure(bookmark));
                }
            }
        }
        // TODO: dead fields?
        int skipUntil = -1;
        for (int c = 0; c < range.numCharacterRuns(); c++) {
            CharacterRun characterRun = range.getCharacterRun(c);
            if (characterRun == null)
                throw new AssertionError();
            if (characterRun.getStartOffset() < skipUntil)
                continue;
            String text = characterRun.text();
            if (text == null || text.length() == 0 || text.charAt(0) != FIELD_BEGIN_MARK)
                continue;
            Field aliveField = ((HWPFDocument) wordDocument).getFields().getFieldByStartOffset(FieldsDocumentPart.MAIN, characterRun.getStartOffset());
            if (aliveField != null) {
                addToStructures(structures, new Structure(aliveField));
            } else {
                int[] separatorEnd = tryDeadField_lookupFieldSeparatorEnd(wordDocument, range, c);
                if (separatorEnd != null) {
                    addToStructures(structures, new Structure(new DeadFieldBoundaries(c, separatorEnd[0], separatorEnd[1]), characterRun.getStartOffset(), range.getCharacterRun(separatorEnd[1]).getEndOffset()));
                    c = separatorEnd[1];
                }
            }
        }
    }
    structures = new ArrayList<Structure>(structures);
    Collections.sort(structures);
    int previous = range.getStartOffset();
    for (Structure structure : structures) {
        if (structure.start != previous) {
            Range subrange = new Range(previous, structure.start, range) {

                @Override
                public String toString() {
                    return "BetweenStructuresSubrange " + super.toString();
                }
            };
            processCharacters(wordDocument, currentTableLevel, subrange, block);
        }
        if (structure.structure instanceof Bookmark) {
            // other bookmarks with same boundaries
            List<Bookmark> bookmarks = new LinkedList<Bookmark>();
            for (Bookmark bookmark : ((HWPFDocument) wordDocument).getBookmarks().getBookmarksStartedBetween(structure.start, structure.start + 1).values().iterator().next()) {
                if (bookmark.getStart() == structure.start && bookmark.getEnd() == structure.end) {
                    bookmarks.add(bookmark);
                }
            }
            bookmarkStack.addAll(bookmarks);
            try {
                int end = Math.min(range.getEndOffset(), structure.end);
                Range subrange = new Range(structure.start, end, range) {

                    @Override
                    public String toString() {
                        return "BookmarksSubrange " + super.toString();
                    }
                };
                processBookmarks(wordDocument, block, subrange, currentTableLevel, bookmarks);
            } finally {
                bookmarkStack.removeAll(bookmarks);
            }
        } else if (structure.structure instanceof Field) {
            Field field = (Field) structure.structure;
            processField((HWPFDocument) wordDocument, range, currentTableLevel, field, block);
        } else if (structure.structure instanceof DeadFieldBoundaries) {
            DeadFieldBoundaries boundaries = (DeadFieldBoundaries) structure.structure;
            processDeadField(wordDocument, block, range, currentTableLevel, boundaries.beginMark, boundaries.separatorMark, boundaries.endMark);
        } else {
            throw new UnsupportedOperationException("NYI: " + structure.structure.getClass());
        }
        previous = Math.min(range.getEndOffset(), structure.end);
    }
    if (previous != range.getStartOffset()) {
        if (previous > range.getEndOffset()) {
            logger.log(POILogger.WARN, "Latest structure in ", range, " ended at #" + previous, " after range boundaries [", range.getStartOffset() + "; " + range.getEndOffset(), ")");
            return true;
        }
        if (previous < range.getEndOffset()) {
            Range subrange = new Range(previous, range.getEndOffset(), range) {

                @Override
                public String toString() {
                    return "AfterStructureSubrange " + super.toString();
                }
            };
            processCharacters(wordDocument, currentTableLevel, subrange, block);
        }
        return true;
    }
    for (int c = 0; c < range.numCharacterRuns(); c++) {
        CharacterRun characterRun = range.getCharacterRun(c);
        if (characterRun == null)
            throw new AssertionError();
        if (wordDocument instanceof HWPFDocument && ((HWPFDocument) wordDocument).getPicturesTable().hasPicture(characterRun)) {
            HWPFDocument newFormat = (HWPFDocument) wordDocument;
            Picture picture = newFormat.getPicturesTable().extractPicture(characterRun, true);
            processImage(block, characterRun.text().charAt(0) == 0x01, picture);
            continue;
        }
        String text = characterRun.text();
        if (text.isEmpty())
            continue;
        if (characterRun.isSpecialCharacter()) {
            if (text.charAt(0) == SPECCHAR_AUTONUMBERED_FOOTNOTE_REFERENCE && (wordDocument instanceof HWPFDocument)) {
                HWPFDocument doc = (HWPFDocument) wordDocument;
                processNoteAnchor(doc, characterRun, block);
                continue;
            }
            if (text.charAt(0) == SPECCHAR_DRAWN_OBJECT && (wordDocument instanceof HWPFDocument)) {
                HWPFDocument doc = (HWPFDocument) wordDocument;
                processDrawnObject(doc, characterRun, block);
                continue;
            }
            if (characterRun.isOle2() && (wordDocument instanceof HWPFDocument)) {
                HWPFDocument doc = (HWPFDocument) wordDocument;
                processOle2(doc, characterRun, block);
                continue;
            }
            if (characterRun.isSymbol() && (wordDocument instanceof HWPFDocument)) {
                HWPFDocument doc = (HWPFDocument) wordDocument;
                processSymbol(doc, characterRun, block);
                continue;
            }
        }
        if (text.charAt(0) == FIELD_BEGIN_MARK) {
            if (wordDocument instanceof HWPFDocument) {
                Field aliveField = ((HWPFDocument) wordDocument).getFields().getFieldByStartOffset(FieldsDocumentPart.MAIN, characterRun.getStartOffset());
                if (aliveField != null) {
                    processField(((HWPFDocument) wordDocument), range, currentTableLevel, aliveField, block);
                    int continueAfter = aliveField.getFieldEndOffset();
                    while (c < range.numCharacterRuns() && range.getCharacterRun(c).getEndOffset() <= continueAfter) c++;
                    if (c < range.numCharacterRuns())
                        c--;
                    continue;
                }
            }
            int skipTo = tryDeadField(wordDocument, range, currentTableLevel, c, block);
            if (skipTo != c) {
                c = skipTo;
                continue;
            }
            continue;
        }
        if (text.charAt(0) == FIELD_SEPARATOR_MARK) {
            // shall not appear without FIELD_BEGIN_MARK
            continue;
        }
        if (text.charAt(0) == FIELD_END_MARK) {
            // shall not appear without FIELD_BEGIN_MARK
            continue;
        }
        if (characterRun.isSpecialCharacter() || characterRun.isObj() || characterRun.isOle2()) {
            continue;
        }
        if (text.endsWith("\r") || (text.charAt(text.length() - 1) == BEL_MARK && currentTableLevel != Integer.MIN_VALUE))
            text = text.substring(0, text.length() - 1);
        {
            // line breaks
            StringBuilder stringBuilder = new StringBuilder();
            for (char charChar : text.toCharArray()) {
                if (charChar == 11) {
                    if (stringBuilder.length() > 0) {
                        outputCharacters(block, characterRun, stringBuilder.toString());
                        stringBuilder.setLength(0);
                    }
                    processLineBreak(block, characterRun);
                } else if (charChar == 30) {
                    // Non-breaking hyphens are stored as ASCII 30
                    stringBuilder.append(UNICODECHAR_NONBREAKING_HYPHEN);
                } else if (charChar == 31) {
                    // Non-required hyphens to zero-width space
                    stringBuilder.append(UNICODECHAR_ZERO_WIDTH_SPACE);
                } else if (charChar >= 0x20 || charChar == 0x09 || charChar == 0x0A || charChar == 0x0D) {
                    stringBuilder.append(charChar);
                }
            }
            if (stringBuilder.length() > 0) {
                outputCharacters(block, characterRun, stringBuilder.toString());
                stringBuilder.setLength(0);
            }
        }
        haveAnyText |= text.trim().length() != 0;
    }
    return haveAnyText;
}
Also used : CharacterRun(org.apache.poi.hwpf.usermodel.CharacterRun) Range(org.apache.poi.hwpf.usermodel.Range) LinkedList(java.util.LinkedList) HWPFDocument(org.apache.poi.hwpf.HWPFDocument) Field(org.apache.poi.hwpf.usermodel.Field) Bookmark(org.apache.poi.hwpf.usermodel.Bookmark) Picture(org.apache.poi.hwpf.usermodel.Picture) ArrayList(java.util.ArrayList) LinkedList(java.util.LinkedList) List(java.util.List) HWPFList(org.apache.poi.hwpf.usermodel.HWPFList)

Example 5 with Picture

use of org.apache.poi.hwpf.usermodel.Picture in project wechat by dllwh.

the class WordUtil method convertHtmlByWord2003.

/**
 * @方法描述: 将word2003转换为html文件
 * @param sourceFile
 *            源word文件路径
 * @param parentPath
 *            目标文件路径
 * @param saveFileName
 *            目标文件名称
 * @param charsetName
 *            编码
 * @return
 * @throws Exception
 */
public static boolean convertHtmlByWord2003(String sourceFile, String parentPath, String saveFileName, String encode) throws Exception {
    if (StringUtils.isBlank(encode)) {
        encode = "UTF-8";
    }
    File imgPath = new File(parentPath);
    if (!imgPath.exists()) {
        // 图片目录不存在则创建
        imgPath.mkdirs();
    }
    // 创建一个文档
    HWPFDocument wordDocument = new HWPFDocument(new FileInputStream(sourceFile));
    // 对普通文本的操作
    WordToHtmlConverter wordToHtmlConverter = new WordToHtmlConverter(DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument());
    // 对图片的操作: 图片在html文件上的相对路径
    wordToHtmlConverter.setPicturesManager(new PicturesManager() {

        public String savePicture(byte[] content, PictureType pictureType, String suggestedName, float widthInches, float heightInches) {
            return suggestedName;
        }
    });
    // 保存图片
    List<Picture> pics = wordDocument.getPicturesTable().getAllPictures();
    if (pics != null) {
        for (int i = 0; i < pics.size(); i++) {
            Picture pic = (Picture) pics.get(i);
            try {
                pic.writeImageContent(new FileOutputStream(parentPath + pic.suggestFullFileName()));
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
        }
    }
    // 解析word文档
    wordToHtmlConverter.processDocument(wordDocument);
    Document htmlDocument = wordToHtmlConverter.getDocument();
    ByteArrayOutputStream output = new ByteArrayOutputStream();
    DOMSource domSource = new DOMSource(htmlDocument);
    StreamResult streamResult = new StreamResult(output);
    // 下面都是转换
    TransformerFactory tf = TransformerFactory.newInstance();
    Transformer serializer = tf.newTransformer();
    serializer.setOutputProperty(OutputKeys.ENCODING, encode);
    serializer.setOutputProperty(OutputKeys.INDENT, "yes");
    serializer.setOutputProperty(OutputKeys.METHOD, "html");
    serializer.transform(domSource, streamResult);
    // 调用writeFile类
    writeFile(new String(output.toByteArray()), parentPath + File.separator + saveFileName, encode);
    IOUtils.closeQuietly(output);
    return false;
}
Also used : DOMSource(javax.xml.transform.dom.DOMSource) TransformerFactory(javax.xml.transform.TransformerFactory) Transformer(javax.xml.transform.Transformer) StreamResult(javax.xml.transform.stream.StreamResult) FileNotFoundException(java.io.FileNotFoundException) ByteArrayOutputStream(java.io.ByteArrayOutputStream) HWPFDocument(org.apache.poi.hwpf.HWPFDocument) XWPFDocument(org.apache.poi.xwpf.usermodel.XWPFDocument) Document(org.w3c.dom.Document) FileInputStream(java.io.FileInputStream) PicturesManager(org.apache.poi.hwpf.converter.PicturesManager) WordToHtmlConverter(org.apache.poi.hwpf.converter.WordToHtmlConverter) HWPFDocument(org.apache.poi.hwpf.HWPFDocument) Picture(org.apache.poi.hwpf.usermodel.Picture) PictureType(org.apache.poi.hwpf.usermodel.PictureType) FileOutputStream(java.io.FileOutputStream) File(java.io.File)

Aggregations

Picture (org.apache.poi.hwpf.usermodel.Picture)13 PicturesTable (org.apache.poi.hwpf.model.PicturesTable)6 HWPFDocument (org.apache.poi.hwpf.HWPFDocument)4 CharacterRun (org.apache.poi.hwpf.usermodel.CharacterRun)4 ArrayList (java.util.ArrayList)3 Range (org.apache.poi.hwpf.usermodel.Range)3 FileNotFoundException (java.io.FileNotFoundException)2 List (java.util.List)2 Transformer (javax.xml.transform.Transformer)2 TransformerFactory (javax.xml.transform.TransformerFactory)2 DOMSource (javax.xml.transform.dom.DOMSource)2 StreamResult (javax.xml.transform.stream.StreamResult)2 PicturesManager (org.apache.poi.hwpf.converter.PicturesManager)2 WordToHtmlConverter (org.apache.poi.hwpf.converter.WordToHtmlConverter)2 Field (org.apache.poi.hwpf.usermodel.Field)2 Paragraph (org.apache.poi.hwpf.usermodel.Paragraph)2 PictureType (org.apache.poi.hwpf.usermodel.PictureType)2 Document (org.w3c.dom.Document)2 BufferedImage (java.awt.image.BufferedImage)1 ByteArrayInputStream (java.io.ByteArrayInputStream)1