java实现word转html(支持docx及doc文件)

server/2025/1/20 16:36:49/
htmledit_views">
html" title=java>java">private final static String tempPath = "C:\\Users\\xxx\\Desktop\\Word2Html\\src\\test\\";//图片及相关文件保存的路径public static void main(String argv[]) {try {JFileChooser fileChooser = new JFileChooser();fileChooser.setDialogTitle("Select a Word Document");fileChooser.setAcceptAllFileFilterUsed(false);fileChooser.addChoosableFileFilter(new html" title=java>javax.swing.filechooser.FileNameExtensionFilter("Word Documents", "doc", "docx"));int returnValue = fileChooser.showOpenDialog(null);if (returnValue == JFileChooser.APPROVE_OPTION) {File inputFile = fileChooser.getSelectedFile();String fileName = inputFile.getAbsolutePath();String defaultOutputDir = System.getProperty("user.home") + "\\Desktop\\";String outputFileName = defaultOutputDir + inputFile.getName().replaceFirst("[.][^.]+$", "") + ".html";if (fileName.endsWith(".doc")) {doc2Html(fileName, outputFileName);} else if (fileName.endsWith(".docx")) {docx2Html(fileName, outputFileName);}}} catch (Exception e) {e.printStackTrace();}}/*** doc转换为html** @param fileName* @param outPutFile* @throws TransformerException* @throws IOException* @throws ParserConfigurationException*/public static void doc2Html(String fileName, String outPutFile) throws TransformerException, IOException, ParserConfigurationException {long startTime = System.currentTimeMillis();HWPFDocument html" title=word>wordDocument = new HWPFDocument(new FileInputStream(fileName));WordToHtmlConverter html" title=word>wordToHtmlConverter = new WordToHtmlConverter(DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument());// 图片保存路径设置html" title=word>wordToHtmlConverter.setPicturesManager(new PicturesManager() {public String savePicture(byte[] content, PictureType pictureType, String suggestedName, float widthInches, float heightInches) {String picturePath = "images" + File.separator + suggestedName;// 检查并创建图片文件夹File imageFolder = new File(tempPath + "images");if (!imageFolder.exists()) {boolean created = imageFolder.mkdirs(); // 创建文件夹if (created) {System.out.println("Images folder created at: " + imageFolder.getAbsolutePath());} else {System.out.println("Failed to create images folder.");}}// 写入图片数据,确保每次写入try {File pictureFile = new File(tempPath + picturePath);try (FileOutputStream fos = new FileOutputStream(pictureFile)) {fos.write(content);  // 写入图片数据System.out.println("Image saved to: " + pictureFile.getAbsolutePath());}} catch (IOException e) {e.printStackTrace();}return picturePath; // 返回相对路径}});html" title=word>wordToHtmlConverter.processDocument(html" title=word>wordDocument);Document htmlDocument = html" title=word>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, "utf-8");serializer.setOutputProperty(OutputKeys.INDENT, "yes");serializer.setOutputProperty(OutputKeys.METHOD, "html");serializer.transform(domSource, streamResult);out.close();String htmlContent = new String(out.toByteArray());htmlContent = htmlContent.replaceAll("TOC \\\\o \"1-3\" \\\\h \\\\z \\\\u", "");writeFile(htmlContent, outPutFile);System.out.println("Generate " + outPutFile + " with " + (System.currentTimeMillis() - startTime) + " ms.");}/*** 写文件** @param content* @param path*/public static void writeFile(String content, String path) {FileOutputStream fos = null;BufferedWriter bw = null;try {File file = new File(path);fos = new FileOutputStream(file);bw = new BufferedWriter(new OutputStreamWriter(fos, "utf-8"));bw.write(content);} catch (FileNotFoundException fnfe) {fnfe.printStackTrace();} catch (IOException ioe) {ioe.printStackTrace();} finally {try {if (bw != null) bw.close();if (fos != null) fos.close();} catch (IOException e) {}}}/*** docx格式html" title=word>word转换为html** @param fileName* @param outPutFile* @throws TransformerException* @throws IOException* @throws ParserConfigurationException*/public static void docx2Html(String fileName, String outPutFile) throws TransformerException, IOException, ParserConfigurationException {long startTime = System.currentTimeMillis();XWPFDocument document = new XWPFDocument(new FileInputStream(fileName));// 提取目录StringBuilder toc = new StringBuilder();toc.append("<div id='toc'>\n<h2>Table of Contents</h2>\n<ul>\n");// 遍历文档中的段落,查找标题并构建目录List<XWPFParagraph> paragraphs = document.getParagraphs();for (XWPFParagraph paragraph : paragraphs) {String style = paragraph.getStyle();  // 获取段落样式if (style != null && (style.equals("Heading 1") || style.equals("Heading 2") || style.equals("Heading 3"))) {String text = paragraph.getText();// 根据标题级别构建目录项toc.append("<li><a href='#" + text.hashCode() + "'>" + text + "</a></li>\n");}}toc.append("</ul>\n</div>\n");// 设置XHTMLOptionsXHTMLOptions options = XHTMLOptions.create().indent(4);File imageFolder = new File(tempPath);options.setExtractor(new FileImageExtractor(imageFolder));options.URIResolver(new FileURIResolver(imageFolder));File outFile = new File(outPutFile);outFile.getParentFile().mkdirs();OutputStream out = new FileOutputStream(outFile);// Convert docx to XHTMLXHTMLConverter.getInstance().convert(document, out, options);System.out.println("Generate " + outPutFile + " with " + (System.currentTimeMillis() - startTime) + " ms.");// 获取转换后的HTML内容String htmlContent = new String(((ByteArrayOutputStream) out).toByteArray(), "UTF-8");// 将TOC插入到HTML的开头htmlContent = toc + htmlContent;// 手动添加表格样式(边框)htmlContent = htmlContent.replaceAll("<table>", "<table style='border: 1px solid black; border-collapse: collapse;'>");htmlContent = htmlContent.replaceAll("<td>", "<td style='border: 1px solid black; padding: 5px;'>");htmlContent = htmlContent.replaceAll("<th>", "<th style='border: 1px solid black; padding: 5px;'>");// 写入到输出文件writeFile(htmlContent, outPutFile);}

pom文件

html" title=java>java"><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><groupId>fxma</groupId><artifactId>Word2Html</artifactId><version>0.0.1-SNAPSHOT</version><packaging>jar</packaging><name>Word2Html</name><url>http://maven.apache.org</url><properties><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding></properties><dependencies><dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>3.8.1</version><scope>test</scope></dependency><dependency><groupId>commons-io</groupId><artifactId>commons-io</artifactId><version>2.4</version></dependency><dependency><groupId>org.apache.poi</groupId><artifactId>poi</artifactId><version>3.8</version></dependency><dependency><groupId>org.apache.poi</groupId><artifactId>poi-ooxml</artifactId><version>3.8</version></dependency><dependency><groupId>org.apache.poi</groupId><artifactId>poi-scratchpad</artifactId><version>3.8</version></dependency><dependency><groupId>fr.opensagres.xdocreport</groupId><artifactId>xdocreport</artifactId><version>1.0.4</version></dependency><dependency><groupId>org.apache.poi</groupId><artifactId>ooxml-schemas</artifactId><version>1.1</version></dependency></dependencies>
</project>

 

 


http://www.ppmy.cn/server/159935.html

相关文章

Restormer: Efficient Transformer for High-Resolution Image Restoration解读

论文地址&#xff1a;Restormer: Efficient Transformer for High-Resolution Image Restoration。 摘要 由于卷积神经网络&#xff08;CNN&#xff09;在从大规模数据中学习可推广的图像先验方面表现出色&#xff0c;这些模型已被广泛应用于图像复原及相关任务。近年来&…

Java 17 新特性详解与代码示例

&#x1f496; 欢迎来到我的博客&#xff01; 非常高兴能在这里与您相遇。在这里&#xff0c;您不仅能获得有趣的技术分享&#xff0c;还能感受到轻松愉快的氛围。无论您是编程新手&#xff0c;还是资深开发者&#xff0c;都能在这里找到属于您的知识宝藏&#xff0c;学习和成长…

Docker私有仓库管理工具Registry

Docker私有仓库管理工具Registry 1 介绍 Registry是私有Docker仓库管理工具&#xff0c;Registry没有可视化管理页面和完备的管理策略。可借助Harbor、docker-registry-browser完成可视化和管理。Harbor是由VMware开发的企业级Docker registry服务。docker-registry-browser是…

OpenWrt 中使用 LuCI 界面部署 Docker 镜像

本篇博客将介绍如何在 OpenWrt 上使用 LuCI 部署 Docker 镜像&#xff0c;以 "hello-world" 镜像为例。 前提条件 已安装支持 Docker 的 OpenWrt 系统。 Docker 服务已在 OpenWrt 上成功安装并运行。 LuCI Docker 插件&#xff08;luci-app-docker 或类似的管理界…

Azure Synapse Dedicated SQL Pool通过配置选项和参数优化性能

配置选项与参数 分布键&#xff08;Distribution Key&#xff09;&#xff1a; • 选择&#xff1a;在大数据量表中&#xff0c;选择经常用于JOIN、WHERE条件中的列作为分布键&#xff0c;如Date、ID等。 • 策略&#xff1a;对于范围查询&#xff0c;使用HASH分布避免数据倾斜…

c++模版详解(不涉及编译原理)

模版的作用 先看看下面的代码感受一下模版的作用吧 #include<iostream> using namespace std;void Swap(int& a, int& b) {int temp a;a b;b temp; }void Swap(double& a, double& b) {double temp a;a b;b temp; }int main() {int a 1, b 2;Sw…

PHP基础(上)

一.PHP简介 1.什么是PHP 介绍&#xff1a;PHP 全称为 “PHP: Hypertext Preprocessor”&#xff0c;是开源且广泛应用的通用脚本语言。它专为 Web 开发打造&#xff0c;能无缝嵌入 HTML 代码。PHP 支持面向过程与面向对象等多种编程范式&#xff0c;拥有庞大丰富的函数库&…

登录、注册、忘记密码、首页HTML模板

<!DOCTYPE html> <html lang"zh"> <head><meta charset"UTF-8"><meta name"viewport" content"widthdevice-width, initial-scale1.0"><title>登录</title><style>body {display: fl…