Java實(shí)現(xiàn)word,pdf轉(zhuǎn)html并保留格式
一、word轉(zhuǎn)html
依賴(lài):
<properties>
<poi.version>5.2.3</poi.version>
<xhtml.version>2.0.4</xhtml.version>
</properties>
<!--word轉(zhuǎn)html-->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-scratchpad</artifactId>
<version>${poi.version}</version>
</dependency>
<!--word轉(zhuǎn)html-->
<dependency>
<groupId>fr.opensagres.xdocreport</groupId>
<artifactId>fr.opensagres.poi.xwpf.converter.xhtml</artifactId>
<version>${xhtml.version}</version>
</dependency>
<!--處理office文檔表格相關(guān) 2007+版-->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>${poi.version}</version>
</dependency>
<!--處理office文檔表格相關(guān) 2003版-->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>${poi.version}</version>
</dependency>代碼:
import fr.opensagres.poi.xwpf.converter.xhtml.Base64EmbedImgManager;
import fr.opensagres.poi.xwpf.converter.xhtml.XHTMLConverter;
import fr.opensagres.poi.xwpf.converter.xhtml.XHTMLOptions;
import org.apache.commons.codec.binary.Base64;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.converter.WordToHtmlConverter;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.*;
import java.net.URL;
public class WordUtil {
public static String wordToHtml(String fileUrl,String fileSuffix) throws Exception {
URL url = new URL(fileUrl);
try (InputStream inputStream = url.openStream()) {
if(fileSuffix.equals(".docx") || fileSuffix.equals(".DOCX")){
return word2007ToHtml(inputStream);
} else if (fileSuffix.equals(".doc") || fileSuffix.equals(".DOC")) {
return word2003ToHtml(inputStream);
}else{
throw new RuntimeException("錯(cuò)誤的文件后綴");
}
} catch (RuntimeException e) {
throw new RuntimeException(e.getMessage());
}
}
/**
* word2007轉(zhuǎn)換成html
* 對(duì)于docx,可以用下面這種方式:
* @throws Exception
*/
public static String word2007ToHtml(InputStream inputStream) {
try (ByteArrayOutputStream htmlStream = new ByteArrayOutputStream();
XWPFDocument docxDocument = new XWPFDocument(inputStream)) {
XHTMLOptions options = XHTMLOptions.create();
// 是否忽略未使用的樣式
options.setIgnoreStylesIfUnused(false);
// 設(shè)置片段模式,<div>標(biāo)簽包裹
options.setFragment(true);
// 圖片轉(zhuǎn)base64
options.setImageManager(new Base64EmbedImgManager());
// 轉(zhuǎn)換htm1
XHTMLConverter.getInstance().convert(docxDocument, htmlStream, options);
return htmlStream.toString();
} catch (Exception e) {
System.out.println("Word轉(zhuǎn)Html過(guò)程出現(xiàn)異常!");
throw new RuntimeException(e.getMessage());
}
}
/**
* word2003轉(zhuǎn)換成html
* 對(duì)于doc,可以用下面這種方式:
* @throws Exception
*/
public static String word2003ToHtml(InputStream inputStream ) throws Exception {
try (StringWriter writer = new StringWriter();
HWPFDocument document = new HWPFDocument(inputStream)) {
WordToHtmlConverter wordToHtmlConverter = new WordToHtmlConverter(DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument());
//將圖片轉(zhuǎn)成base64的格式
wordToHtmlConverter.setPicturesManager((bytes, pictureType, s, v, v1) -> "data:image/png;base64," + Base64.encodeBase64String(bytes));
wordToHtmlConverter.processDocument(document);
org.w3c.dom.Document htmlDocument = wordToHtmlConverter.getDocument();
DOMSource domSource = new DOMSource(htmlDocument);
TransformerFactory factory = TransformerFactory.newInstance();
Transformer serializer = factory.newTransformer();
serializer.setOutputProperty(OutputKeys.ENCODING, "utf-8");
serializer.setOutputProperty(OutputKeys.INDENT, "yes");
serializer.setOutputProperty(OutputKeys.METHOD, "html");
serializer.transform(domSource, new StreamResult(writer));
return writer.toString();
} catch (Exception e) {
System.out.println("Word轉(zhuǎn)Html過(guò)程出現(xiàn)異常!");
throw new RuntimeException(e.getMessage());
}
}
}二、pdf轉(zhuǎn)html
依賴(lài):
<dependency>
<groupId>net.sf.cssbox</groupId>
<artifactId>pdf2dom</artifactId>
</dependency>
<dependency>
<groupId>net.mabboud.fontverter</groupId>
<artifactId>FontVerter</artifactId>
</dependency>
<dependency>
<groupId>org.reflections</groupId>
<artifactId>reflections</artifactId>
</dependency>
<!--pdf轉(zhuǎn)文本-->
<dependency>
<groupId>org.apache.pdfbox</groupId>
<artifactId>pdfbox</artifactId>
</dependency>代碼:
import org.apache.pdfbox.pdmodel.PDDocument;
import org.fit.pdfdom.PDFDomTree;
import java.io.*;
import java.net.URL;
public class PDFUtil {
public static String pdfToHtml(String fileUrl) throws IOException {
URL url = new URL(fileUrl);
try (InputStream inputStream = url.openStream()){
return pdfToHtml(inputStream);
}catch (Exception e){
throw new IOException(e.getMessage());
}
}
public static String pdfToHtml(InputStream inputStream) throws IOException {
String outFilePath = "mypdf.html";
String pdfContent = "";
PDDocument document = PDDocument.load(inputStream);
Writer writer = new PrintWriter(outFilePath, "UTF-8");
new PDFDomTree().writeText(document, writer);
writer.close();
document.close();
// 獲取html內(nèi)容
try (BufferedReader reader = new BufferedReader(new FileReader(outFilePath))) {
StringBuilder htmlContent = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
htmlContent.append(line).append("\n"); // 追加每一行內(nèi)容,并添加換行符
}
pdfContent = String.valueOf(htmlContent);
return pdfContent;
} catch (IOException e) {
e.printStackTrace();
System.err.println("讀取 HTML 文件時(shí)出錯(cuò)。");
}
return null;
}
}三、方法補(bǔ)充
Java實(shí)現(xiàn)word轉(zhuǎn)html
1.引入maven依賴(lài)
<properties>
<poi.version>5.2.3</poi.version>
<xhtml.version>2.0.4</xhtml.version>
</properties>
<!--word轉(zhuǎn)html-->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-scratchpad</artifactId>
<version>${poi.version}</version>
</dependency>
<!--word轉(zhuǎn)html-->
<dependency>
<groupId>fr.opensagres.xdocreport</groupId>
<artifactId>fr.opensagres.poi.xwpf.converter.xhtml</artifactId>
<version>${xhtml.version}</version>
</dependency>
<!--處理office文檔表格相關(guān) 2007+版-->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>${poi.version}</version>
</dependency>
<!--處理office文檔表格相關(guān) 2003版-->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>${poi.version}</version>
</dependency>
2.Java代碼
/**
* Word2007(docx)格式轉(zhuǎn)html
* @param filePath 文件路徑
* @return 返回轉(zhuǎn)成String類(lèi)型的html字符串
* @throws IOException
*/
public static String docxToHtml(String filePath) {
try (ByteArrayOutputStream htmlStream = new ByteArrayOutputStream();
XWPFDocument docxDocument = new XWPFDocument(Files.newInputStream(Paths.get(filePath)))) {
XHTMLOptions options = XHTMLOptions.create();
// 是否忽略未使用的樣式
options.setIgnoreStylesIfUnused(false);
// 設(shè)置片段模式,<div>標(biāo)簽包裹
options.setFragment(true);
// 圖片轉(zhuǎn)base64
options.setImageManager(new Base64EmbedImgManager());
// 轉(zhuǎn)換htm1
XHTMLConverter.getInstance().convert(docxDocument, htmlStream, options);
return htmlStream.toString();
} catch (Exception e) {
log.error("Word轉(zhuǎn)Html過(guò)程出現(xiàn)異常!", e);
}
return null;
}
/**
* Word2003(doc)格式轉(zhuǎn)html
* @param filePath 文件路徑
* @return 返回轉(zhuǎn)成String類(lèi)型的html字符串
* @throws Exception
*/
public static String docToHtml(String filePath) {
try (StringWriter writer = new StringWriter();
HWPFDocument document = new HWPFDocument(Files.newInputStream(new File(filePath).toPath()))) {
WordToHtmlConverter wordToHtmlConverter = new WordToHtmlConverter(DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument());
//將圖片轉(zhuǎn)成base64的格式
wordToHtmlConverter.setPicturesManager((bytes, pictureType, s, v, v1) -> "data:image/png;base64," + Base64.encodeBase64String(bytes));
wordToHtmlConverter.processDocument(document);
org.w3c.dom.Document htmlDocument = wordToHtmlConverter.getDocument();
DOMSource domSource = new DOMSource(htmlDocument);
TransformerFactory factory = TransformerFactory.newInstance();
Transformer serializer = factory.newTransformer();
serializer.setOutputProperty(OutputKeys.ENCODING, "utf-8");
serializer.setOutputProperty(OutputKeys.INDENT, "yes");
serializer.setOutputProperty(OutputKeys.METHOD, "html");
serializer.transform(domSource, new StreamResult(writer));
return writer.toString();
} catch (Exception e) {
log.error("Word轉(zhuǎn)Html過(guò)程出現(xiàn)異常!", e);
}
return null;
}
/**
* word 轉(zhuǎn) html
* 自動(dòng)檢測(cè)文件格式轉(zhuǎn)換
* @param filePath 文件本地路徑
* @return 成功返回轉(zhuǎn)換后的html字符串;失敗返回null
*/
public static String autoWord2Html(String filePath) {
int lastIndexOf = filePath.lastIndexOf(".");
String suffix = filePath.substring(lastIndexOf + 1);
if ("doc".equalsIgnoreCase(suffix)) {
return docToHtml(filePath);
} else if ("docx".equalsIgnoreCase(suffix)) {
return docxToHtml(filePath);
} else {
log.info("文件格式錯(cuò)誤,只支持Docx和Doc格式的文檔!");
return null;
}
}
使用Java實(shí)現(xiàn)PDF到HTML的轉(zhuǎn)換
引入以下依賴(lài)
<dependency>
<groupId>net.sf.cssbox</groupId>
<artifactId>pdf2dom</artifactId>
<version>2.0.3</version>
</dependency>
<dependency>
<groupId>net.mabboud.fontverter</groupId>
<artifactId>FontVerter</artifactId>
<version>1.2.22</version> <!-- 請(qǐng)根據(jù)需要使用最新版本 -->
</dependency>
<dependency>
<groupId>org.reflections</groupId>
<artifactId>reflections</artifactId>
<version>0.10.2</version> <!-- 請(qǐng)根據(jù)需要使用最新版本 -->
</dependency>
<!--pdf轉(zhuǎn)文本-->
<dependency>
<groupId>org.apache.pdfbox</groupId>
<artifactId>pdfbox</artifactId>
<version>2.0.24</version>
</dependency>實(shí)現(xiàn)關(guān)鍵代碼
File file = new File(pdfUrl);
String localPdfFilePath = 要解析的PDF文件路徑(本地)+ file.getName();
String newPdfFilePath = 截取PDF后生成的PDF文件路徑+ file.getName();
String outFilePath = 生成的HTML文件.html";
String pdfContent = "";
PDDocument pdfDocument = PDDocument.load(new File(localPdfFilePath));
// 檢查文檔中是否有頁(yè)面
if (pdfDocument.getNumberOfPages() > 0) {
// 移除第一頁(yè)
pdfDocument.removePage(0);
}
// 保存更改后的PDF到新文件
pdfDocument.save(new File(newPdfFilePath));
System.out.println("第一頁(yè)已被移除,新PDF保存在: " + newPdfFilePath);
pdfDocument.close();
// 轉(zhuǎn)換成html格式文件
PDDocument document = PDDocument.load(new File(newPdfFilePath));
Writer writer = new PrintWriter(outFilePath, "UTF-8");
new PDFDomTree().writeText(document, writer);
writer.close();
document.close();
// 獲取html內(nèi)容
try (BufferedReader reader = new BufferedReader(new FileReader(outFilePath))) {
StringBuilder htmlContent = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
htmlContent.append(line).append("\n"); // 追加每一行內(nèi)容,并添加換行符
}
pdfContent = String.valueOf(htmlContent);
} catch (IOException e) {
e.printStackTrace();
System.err.println("讀取 HTML 文件時(shí)出錯(cuò)。");
}到此這篇關(guān)于Java實(shí)現(xiàn)word,pdf轉(zhuǎn)html并保留格式的文章就介紹到這了,更多相關(guān)Java word,pdf轉(zhuǎn)html內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Netty分布式Future與Promise執(zhí)行回調(diào)相關(guān)邏輯剖析
這篇文章主要為大家介紹了Netty分布式Future與Promise執(zhí)行回調(diào)相關(guān)邏輯剖析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步2022-03-03
Java使用POI-TL和JFreeChart動(dòng)態(tài)生成Word報(bào)告
本文介紹了使用POI-TL和JFreeChart生成包含動(dòng)態(tài)數(shù)據(jù)和圖表的Word報(bào)告的方法,并分享了實(shí)際開(kāi)發(fā)中的踩坑經(jīng)驗(yàn),通過(guò)代碼示例講解的非常詳細(xì),具有一定的參考價(jià)值,需要的朋友可以參考下2025-02-02
SpringBoot實(shí)現(xiàn)異步調(diào)用的方法示例
本文介紹了在Java的SpringBoot中實(shí)現(xiàn)異步請(qǐng)求和異步調(diào)用的幾種方法,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2025-01-01
Java 關(guān)于時(shí)間復(fù)雜度和空間復(fù)雜度的深度刨析
算法復(fù)雜度分為時(shí)間復(fù)雜度和空間復(fù)雜度。其作用: 時(shí)間復(fù)雜度是度量算法執(zhí)行的時(shí)間長(zhǎng)短;而空間復(fù)雜度是度量算法所需存儲(chǔ)空間的大小2021-11-11
Java圖形界面之JFrame,JLabel,JButton詳解
這篇文章主要介紹了Java圖形界面之JFrame、JLabel、JButton詳解,文中有非常詳細(xì)的代碼示例,對(duì)正在學(xué)習(xí)java的小伙伴們有非常好的幫助,需要的朋友可以參考下2021-04-04
Java SSL證書(shū)錯(cuò)誤:No subject alternative name
本文深入解析Java SSL證書(shū)錯(cuò)誤'No subject alternative names present'的解決方案,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2026-03-03

