@
<dependency>
<groupId>com.luhuiguo</groupId>
<artifactId>aspose-words</artifactId>
<version>23.1</version></dependency>
<dependency>
<groupId>org.apache.pdfbox</groupId>
<artifactId>pdfbox</artifactId>
<version>2.0.4</version>
</dependency>
public static String wordToHtmlStr(String wordPath) {
try {
Document doc = new Document(wordPath); // Address是將要被轉化的word檔案
String htmlStr = doc.toString();
return htmlStr;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
驗證結果:
public static String pdfToHtmlStr(String pdfPath) throws IOException, ParserConfigurationException {
PDDocument document = PDDocument.load(new File(pdfPath));
Writer writer = new StringWriter();
new PDFDomTree().writeText(document, writer);
writer.close();
document.close();
return writer.toString();
}
驗證結果:
有時我們是需要的不僅僅返回html字串,而是需要生成一個html檔案這時應該怎麼做呢?一個改動量小的做法就是使用org.apache.commons.io包下的FileUtils工具類寫入目標地址:
首先需要引入pom:
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.8.0</version>
</dependency>
相關程式碼:
String htmlStr = FileConvertUtil.pdfToHtmlStr("D:\\書籍\\電子書\\小說\\歷史小說\\最後的可汗.doc");
FileUtils.write(new File("D:\\test\\doc.html"), htmlStr, "utf-8");
除此之外,還可以對上面的程式碼進行一些調整,已實現生成html檔案,程式碼調整如下:
public static void wordToHtml(String wordPath, String htmlPath) {
try {
File sourceFile = new File(wordPath);
String path = htmlPath + File.separator + sourceFile.getName().substring(0, sourceFile.getName().lastIndexOf(".")) + ".html";
File file = new File(path); // 新建一個空白pdf檔案
FileOutputStream os = new FileOutputStream(file);
Document doc = new Document(wordPath); // Address是將要被轉化的word檔案
HtmlSaveOptions options = new HtmlSaveOptions();
options.setExportImagesAsBase64(true);
options.setExportRelativeFontSize(true);
doc.save(os, options);
} catch (Exception e) {
e.printStackTrace();
}
}
驗證結果:
public static void pdfToHtml(String pdfPath, String htmlPath) throws IOException, ParserConfigurationException {
File file = new File(pdfPath);
String path = htmlPath + File.separator + file.getName().substring(0, file.getName().lastIndexOf(".")) + ".html";
PDDocument document = PDDocument.load(new File(pdfPath));
Writer writer = new PrintWriter(path, "UTF-8");
new PDFDomTree().writeText(document, writer);
writer.close();
document.close();
}
圖片版PDF檔案驗證結果:
文字版PDF檔案驗證結果: