簡體   English   中英

使用帶有 XWPF 的 Apache POI 獲取 Java 中的單詞縮略圖

[英]Get thumbnail of word in java using Apache POI with XWPF

這個問題涉及使用 HWPF 獲取 word 文檔的縮略圖:

使用 Apache POI 在 Java 中獲取單詞的縮略圖

我想用 XWPF 來做到這一點 - 用於 word xml 文檔 (.docx) 的 Apache POI API。 沒有 getThumbnail() 方法或類似方法。 我怎樣才能做到這一點? 我想使用“另存為...”對話框中的“生成縮略圖”選項提取由 Word 生成的嵌入縮略圖 - 這適用於帶有 HWPF 的 .doc 文檔。

經過一些深入的研究,尤其是關於開放包裝公約,我自己找到了答案。 XWPF Document API中沒有“ getThumbnai()”便捷方法。 縮略圖必須通過特定的包關系提取:

XWPFDocument wordDocument = new XWPFDocument(new FileInputStream(docxFile));

ArrayList<PackagePart> packageParts= wordDocument.getPackage().getPartsByRelationshipType
("http://schemas.openxmlformats.org/package/2006/relationships/metadata/thumbnail");

PackagePart packagePart = packageParts.get(0);
FileOutputStream fos = new FileOutputStream("c:\\temp\\thumb.emf");
IOUtils.copy(packagePart.getInputStream(), fos);

您需要升級您的Apache POI版本! 您需要使用Apache POI 3.15 beta 2或更高版本

在這些較新的版本上,您會在POIXMLProperties上找到一些與Thumbnail相關的方法,例如getThumbnailFilename()getThumbnailImage()

要將縮略圖保存到文件中,請使用XWPF,例如:

XWPFDocument wordDocument = new XWPFDocument(new FileInputStream(docxFile));
POIXMLProperties props = workDocument.getProperties();

String thumbnail = props.getThumbnailFilename();
if (thumbnail == null) {
   // No thumbnail
} else {
   FileOutputStream fos = new FileOutputStream("c:\\temp\\"+thumbnail);
   IOUtils.copy(props.getThumbnailImage(), fos);
}

有一個 JVM 庫用於制作縮略圖, thumbnails4j ,它在后台使用 POI 來處理 docx 文件。

File input = new File("/path/to/my_file.docx");
Thumbnailer thumbnailer = new DOCXThumbnailer();
List<Dimensions> outputDimensions = Collections.singletonList(new Dimensions(100, 100));
BufferedImage output = thumbnailer.getThumbnails(input, outputDimensions).get(0);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM