Java實現(xiàn)將Word轉換成Html的示例代碼
前言
在業(yè)務中,如果需要在瀏覽器中預覽Word文檔,或者需要將Word文檔轉成HTML文件保存,那么本章內容,可以幫助到你。
實現(xiàn)這一功能,有多種實現(xiàn)方式,如:docx4j、poi、Free Spire.Doc for Java、openoffice、jacob都可以實現(xiàn)轉換功能,但都有局限性。在這稍微介紹一下哈,大家可做個對比
docx4j
docx4j主要是針對docx文件進行操作,操作的對象的Microsoft Open XML文件。
java當中用于操作office(docx/xlsx/ppt)等文件的類庫
poi
POI是Apache軟件基金會的開放源碼函式庫,POI提供API給Java程序對Microsoft Office格式檔案讀和寫的功能。
結構:
HSSF - 提供讀寫Microsoft Excel格式檔案的功能。
XSSF - 提供讀寫Microsoft Excel OOXML格式檔案的功能。
HWPF - 提供讀寫Microsoft Word格式檔案的功能。
HSLF - 提供讀寫Microsoft PowerPoint格式檔案的功能。
HDGF - 提供讀寫Microsoft Visio格式檔案的功能。
Free Spire.Doc for Java(功能強大,但可以收費)
Free Spire.Doc for Java 是一款免費、專業(yè)的 Java Word 組件,開發(fā)人員使用它可以輕松地將 Word 文檔創(chuàng)建、讀取、編輯、轉換和打印等功能集成到自己的 Java 應用程序中。作為一款完全獨立的組件,F(xiàn)ree Spire.Doc for Java的運行環(huán)境無需安裝 Microsoft Office。
友情提示:免費版有篇幅限制。在加載或保存 Word 文檔時,要求 Word 文檔不超過 500 個段落,25 個表格。同時將 Word 文檔轉換為 PDF 和 XPS 等格式時,僅支持轉換前三頁
openoffice
一、利用jodconverter(基于OpenOffice服務)將文件(.doc、.docx、.xls、.ppt)轉化為html格式。
二、利用jodconverter(基于OpenOffice服務)將文件(.doc、.docx、.xls、.ppt)轉化為pdf格式。需要用戶安裝了Adobe Reader XI
jacob(不能用于Linux)
需要引入jacob.jar jar包,并且jar包還要調用jacob.dll文件,需要事先把jacob.dll文件放到以下3處地方:C:\Windows\System32 目錄下,安裝的jdk文件夾下的bin目錄中,以及jre文件夾下的bin目錄(注意一定是你這個項目運行所用到的jdk和jre)
它允許在java中調用com接口自動組件,它使用JNI(本地調用進程)來進行本地調用COM庫。它可運行在x86和支持32位和64位Java虛擬機
本文采用poi來進行轉換
1、Poi轉換
1.1、引入依賴
<!-- WordToHtml .doc .odcx poi --> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-scratchpad</artifactId> <version>4.1.2</version> </dependency> <!-- 操作excel的庫 注意版本保持一致 poi poi-ooxml poi-scratchpad --> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>4.1.2</version> </dependency> <!-- https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml --> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>4.1.2</version> </dependency> <dependency> <groupId>fr.opensagres.xdocreport</groupId> <artifactId>fr.opensagres.poi.xwpf.converter.xhtml</artifactId> <version>2.0.2</version> </dependency> <!-- https://mvnrepository.com/artifact/fr.opensagres.xdocreport/fr.opensagres.xdocreport.converter.docx.xwpf --> <dependency> <groupId>fr.opensagres.xdocreport</groupId> <artifactId>fr.opensagres.xdocreport.converter.docx.xwpf</artifactId> <version>2.0.1</version> </dependency>
1.2、工具類
poi轉換工具類
/** * poi WordToHtml工具類 */ @Slf4j public class WordToHtml { // 文件上傳保存路徑 @Value(value = "${upload.path}") private final String uploadPath = ""; //轉換的方法 public File convert(MultipartFile file) { //獲得文件的名字 String filename = file.getOriginalFilename(); //獲得文件的擴展名 String suffix = filename.substring(filename.lastIndexOf(".")); String newName = UUID.randomUUID().toString(); // TODO 需要保存在一個新的位置 // File =new File 表示目錄的一個抽象,可以進一步用exists()和isDirectory()方法判斷。 File convFile = new File(uploadPath + newName + suffix); FileOutputStream fos = null; try { //創(chuàng)建文件 convFile.createNewFile(); //FileOutputStream 是輸出流 將文件輸出到磁盤或者數(shù)據(jù)庫中 fos = new FileOutputStream(convFile); fos.write(file.getBytes()); } catch (IOException ex) { log.error("上傳文件出錯!", ex); return null; } finally { IOUtils.closeQuietly(fos); } // 輸入文件名的所在文件夾 // 加上反斜杠 String parentDirectory = convFile.getParent(); if (!parentDirectory.endsWith("\\")) { parentDirectory = parentDirectory + "\\"; } if (filename.endsWith(".docx")) { return docxConvert(parentDirectory, convFile.getAbsolutePath(), newName); } else if (filename.endsWith(".doc")) { return docConvert(parentDirectory, convFile.getAbsolutePath(), newName); } else { log.error("不支持的文件格式!"); return null; } } /** * html 流文件 修改內容 width:595.3pt; 因為轉換的HTML頁面默認內容區(qū)域不是html自適應大小,內容位置不對 * @param parentDirectory html文件所在文件夾 * @param filename html舊文件地址 * @param newName html新文件地址 * @return */ private File htmlreplace(String parentDirectory, String filename, String newName) { try { // 讀取生成的Html FileInputStream inputStream = new FileInputStream(new File(parentDirectory + filename + ".html")); InputStream inputStrem = readInputStrem(inputStream); // 清空文件內容 clearInfoForFile(parentDirectory + filename + ".html"); // TODO: 2022/4/22 進行流輸出Html文件 inputStrem // 1、讀取內容 byte[] buffer = new byte[inputStrem.available()]; inputStrem.read(buffer); // 寫入內容 OutputStream outStream = new FileOutputStream(new File(parentDirectory + newName + ".html")); outStream.write(buffer); return new File(parentDirectory + newName + ".html"); } catch (FileNotFoundException e) { log.error("Html轉換失敗!",e); return null; } catch (IOException e) { log.error("Html轉換失?。?,e); return null; } } /** * 讀取HTML 流文件,并查詢當中的width:595.3pt; / white-space:pre-wrap; 或類似符號直接替換為空格 * * @param inputStream * @return */ private static InputStream readInputStrem(InputStream inputStream) { // 匹配內容 String regEx_special = "width:595.3pt;"; String regEx_special2 = "white-space:pre-wrap;"; // 替換新內容 String replace = "white-space:pre-wrap;word-break:break-all;"; try { //<1>創(chuàng)建字節(jié)數(shù)組輸出流,用來輸出讀取到的內容 ByteArrayOutputStream baos = new ByteArrayOutputStream(); //<2>創(chuàng)建緩存大小 byte[] buffer = new byte[1024]; // 1KB //每次讀取到內容的長度 int len = -1; //<3>開始讀取輸入流中的內容 while ((len = inputStream.read(buffer)) != -1) { //當?shù)扔?1說明沒有數(shù)據(jù)可以讀取了 baos.write(buffer, 0, len); //把讀取到的內容寫到輸出流中 } //<4> 把字節(jié)數(shù)組轉換為字符串 String content = baos.toString(); //<5>關閉輸入流和輸出流 // inputStream.close(); baos.close(); // log.info("讀取的內容:{}", content); // 判斷HTML內容是否具有HTML的 width:595.3pt; Pattern compile = Pattern.compile(regEx_special, Pattern.CASE_INSENSITIVE); Matcher matcher = compile.matcher(content); String replaceAll = matcher.replaceAll(""); // 判斷是否具有white-space:pre-wrap; Pattern compile2 = Pattern.compile(regEx_special2, Pattern.CASE_INSENSITIVE); Matcher matcher2 = compile2.matcher(replaceAll); String replaceAll2 = matcher2.replaceAll(replace); // log.info("替換后的內容:{}", replaceAll2); // 將字符串轉化為輸入流返回 InputStream stringStream = getStringStream(replaceAll2); //<6>返回結果 return stringStream; } catch (Exception e) { e.printStackTrace(); log.error("錯誤信息:{}", e.getMessage()); return null; } } /** * 將一個字符串轉化為輸入流 * @param sInputString 字符串 * @return */ public static InputStream getStringStream(String sInputString) { if (sInputString != null && !sInputString.trim().equals("")) { try { ByteArrayInputStream tInputStringStream = new ByteArrayInputStream(sInputString.getBytes()); return tInputStringStream; } catch (Exception e) { e.printStackTrace(); } } return null; } /** * 清空文件內容 * @param fileName */ public static void clearInfoForFile(String fileName) { File file =new File(fileName); try { if(!file.exists()) { file.createNewFile(); } FileWriter fileWriter =new FileWriter(file); fileWriter.write(""); fileWriter.flush(); fileWriter.close(); } catch (IOException e) { e.printStackTrace(); } } /** * 轉換.docx 當word文檔字體大于5號字體時,會出現(xiàn)不規(guī)律排列文字換行(因為轉換的HTML頁面默認內容區(qū)域不是html原始區(qū)域) * @param parentDirectory html文件所在文件夾 (主要用于圖像的管理) * @param filename word文件地址 * @param newName html文件地址 * @return */ private File docxConvert(String parentDirectory, String filename, String newName) { try { // 1) 加載word文檔生成 XWPFDocument對象 XWPFDocument document = new XWPFDocument(new FileInputStream(filename)); // 設置存放圖片地址 XHTMLOptions options = XHTMLOptions.create().setImageManager(new ImageManager(new File(parentDirectory), UUID.randomUUID().toString())).indent(4); OutputStream out = new FileOutputStream(new File(parentDirectory + newName + ".html")); // 自定義編碼格式 OutputStreamWriter writer = new OutputStreamWriter(out,"GBK"); // 生成HTML XHTMLConverter xhtmlConverter = (XHTMLConverter)XHTMLConverter.getInstance(); xhtmlConverter.convert(document, writer, options); // 將生成的HTML進行內容匹配替換 File htmlreplace = htmlreplace(parentDirectory, newName, newName); return htmlreplace; // return new File(parentDirectory + newName + ".html"); } catch (IOException ex) { log.error("word轉化出錯!", ex); return null; } } /** * 轉換.doc * @param parentDirectory html文件所在文件夾 (主要用于圖像的管理) * @param filename word文件地址 * @param newName html文件地址 * @return */ private File docConvert(String parentDirectory, String filename, String newName) { try { HWPFDocument document = new HWPFDocument(new FileInputStream(filename)); WordToHtmlConverter wordToHtmlConverter = new WordToHtmlConverter( DocumentBuilderFactory.newInstance().newDocumentBuilder() .newDocument()); // converter默認對圖片不作處理,需要手動下載圖片并嵌入到html中 wordToHtmlConverter.setPicturesManager(new PicturesManager() { @Override public String savePicture(byte[] bytes, PictureType pictureType, String s, float v, float v1) { String imageFilename = parentDirectory + ""; String identity = UUID.randomUUID().toString(); File imageFile = new File(imageFilename, identity + s); imageFile.getParentFile().mkdirs(); InputStream in = null; FileOutputStream out = null; try { in = new ByteArrayInputStream(bytes); out = new FileOutputStream(imageFile); IOUtils.copy(in, out); } catch (IOException ex) { log.error("word轉化出錯!", ex); } finally { if (in != null) { IOUtils.closeQuietly(in); } if (out != null) { IOUtils.closeQuietly(out); } } return imageFile.getName(); } }); wordToHtmlConverter.processDocument(document); Document htmlDocument = wordToHtmlConverter.getDocument(); ByteArrayOutputStream out = new ByteArrayOutputStream(); DOMSource domSource = new DOMSource(htmlDocument); StreamResult streamResult = new StreamResult(out); // 設置轉換屬性 TransformerFactory tf = TransformerFactory.newInstance(); Transformer serializer = tf.newTransformer(); serializer.setOutputProperty(OutputKeys.ENCODING, "GBK"); serializer.setOutputProperty(OutputKeys.INDENT, "yes"); serializer.setOutputProperty(OutputKeys.METHOD, "html"); serializer.transform(domSource, streamResult); out.close(); String result = new String(out.toByteArray()); FileWriter writer = new FileWriter(parentDirectory + newName + ".html"); writer.write(result); writer.close(); } catch (IOException | TransformerException | ParserConfigurationException ex) { log.error("word轉化出錯!", ex); } return new File(parentDirectory + newName + ".html"); } /** * 將上傳的Word文檔轉化成HTML字符串 * * @param file * @return */ public String convertToHtml(MultipartFile file) { String wordContent = ""; // 將Word文件轉換為html File file2 = convert(file); // 讀取html文件 if (file2 != null) { return "文件轉換成功"; } return "文件轉換失敗"; } /** * wordToHtml * @param wordFilePath word文件路徑 * @param htmlFilePath html文件路徑 * @throws IOException * @throws ParserConfigurationException * @throws TransformerException */ public static File wordToHtml(String wordFilePath,String htmlFilePath) { // 提取出word文檔名稱和后綴 String filename = wordFilePath.substring(wordFilePath.lastIndexOf("/")+1); // 提取出html文件存放路徑和文件名稱 String newName = htmlFilePath.substring(htmlFilePath.lastIndexOf("/")+1,htmlFilePath.lastIndexOf(".")); File convFile = new File(htmlFilePath); // 輸入文件名的所在文件夾 // 加上反斜杠 String parentDirectory = convFile.getParent(); if (!parentDirectory.endsWith("\\")) { parentDirectory = parentDirectory + "\\"; } if (filename.endsWith(".docx")) { return new WordToHtml().docxConvert(parentDirectory, wordFilePath, newName); } else if (filename.endsWith(".doc")) { return new WordToHtml().docConvert(parentDirectory, wordFilePath, newName); } else { log.error("不支持的文件格式!"); return null; } } }
1.3、測試類
/** * @Author:wk * @Create:2022/4/21/15:10 * @Description:WordToHtml測試類 poi * @Version:1.0 */ @Slf4j public class WordToHtmlTest { public static void main(String[] args) { long timeMillis = System.currentTimeMillis(); log.info("開始轉換!"); String wordFilePath = "src/main/resources/word/nc.docx"; String htmlFilePath = "src/main/resources/html/nc5.html"; File file = WordToHtml.wordToHtml(wordFilePath, htmlFilePath); // 讀取html文件 if (file != null) { log.info("文件存放路徑:{}",file.getPath()); log.info("轉換結束!用時:{}ms",System.currentTimeMillis()-timeMillis); return; } log.error("文件轉換失??!"); } }
測試效果(真實效果存在較小差異)由于截圖一頁顯示不全,所以文檔和頁面都做了響應調整哈
.doc
.docx(文檔是一樣的, 此處就不截屏了哈)
到此這篇關于Java實現(xiàn)將Word轉換成Html的示例代碼的文章就介紹到這了,更多相關Java Word轉Html內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Spring?Boot教程之提高開發(fā)效率必備工具lombok
這篇文章主要介紹了Spring?Boot教程之提高開發(fā)效率必備工具lombok的相關資料,需要的朋友可以參考下2022-08-08解決OkHttp接收gzip壓縮數(shù)據(jù)返回亂碼問題
這篇文章主要介紹了解決OkHttp接收gzip壓縮數(shù)據(jù)返回亂碼問題,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-06-06MybatisPlus 主鍵策略之type=IdType.ASSIGN_ID等詳解
雪花算法(雪花)是微博開源的分布式ID生成算法其核心思想就是:使用一個64位的長型的數(shù)字作為全局唯一ID,這篇文章主要介紹了MybatisPlus 主鍵策略(type=IdType.ASSIGN_ID等詳解),需要的朋友可以參考下2024-04-04java中string.trim()函數(shù)的作用實例及源碼
這篇文章主要介紹了java中string.trim()函數(shù)的作用實例及源碼,具有一定借鑒價值,需要的朋友可以參考下2018-01-01基于springboot和redis實現(xiàn)單點登錄
這篇文章主要為大家詳細介紹了基于springboot和redis實現(xiàn)單點登錄,具有一定的參考價值,感興趣的小伙伴們可以參考一下2019-06-06SpringBoot監(jiān)聽事件和處理事件程序示例詳解
這篇文章主要介紹了SpringBoot監(jiān)聽事件和處理事件程序示例,監(jiān)聽和處理事件是一種常用的模式,用于在應用程序的不同部分之間傳遞信息,Spring 的事件發(fā)布/訂閱模型允許我們創(chuàng)建自定義事件,并在這些事件發(fā)生時由注冊的監(jiān)聽器進行處理,需要的朋友可以參考下2022-06-06