使用Apache POI获取java中的单词缩略图

时间:2012-12-02 20:09:32

标签: java apache-poi

我在jsf中研究一个网络共享项目。在这个项目中,用户可以上传文件,如.doc,.pdf,.ppt,..等。我想把这个文档首页显示为缩略图。经过一些谷歌搜索后,我发现了Apache POI。任何人对我的问题都有任何建议吗?如何返回word doc第一页的缩略图?我试试这段代码。这段代码只是得到了word doc包含的第一张图片:

        POIFSFileSystem fs = new POIFSFileSystem(new FileInputStream("d:\\test.doc"));
        HWPFDocument doc = new HWPFDocument(fs);
        PicturesTable pt=doc.getPicturesTable();
        List<Picture> p=pt.getAllPictures();
        BufferedImage image=ImageIO.read(new ByteArrayInputStream(p.get(0).getContent()));
        ImageIO.write(image, "JPG", new File("d:\\test.jpg"));

1 个答案:

答案 0 :(得分:0)

你在做什么什么都没做。 HWPFDocument可以提取文档中嵌入的缩略图(保存文件时,选中“添加预览”选项)。因此,HWPFDocument只能提取具有缩略图的文档的缩略图。

即便如此,你必须做到: {代码}

static byte[] process(File docFile) throws Exception {
    final HWPFDocumentCore wordDocument = AbstractWordUtils.loadDoc(docFile);
    SummaryInformation summaryInformation = wordDocument.getSummaryInformation();
    System.out.println(summaryInformation.getAuthor());
    System.out.println(summaryInformation.getApplicationName() + ":" + summaryInformation.getTitle());
    Thumbnail thumbnail = new Thumbnail(summaryInformation.getThumbnail());
    System.out.println(thumbnail.getClipboardFormat());
    System.out.println(thumbnail.getClipboardFormatTag());
    return thumbnail.getThumbnailAsWMF();
}

{代码} 之后,您可能需要将WMF文件格式转换为更常见的格式(jpeg,png ...)。 ImageMagick可以提供帮助。