说明

在Java生态中处理Office文档时,开发人员常面临格式兼容性和功能完整性的挑战。商业组件Aspose以其卓越的文档处理能力成为企业级解决方案之一,支持Word、Excel、PDF等多种格式的精准转换与操作。

请勿用于商业用途,若侵权请联系我。

参考了一些网上大神的破解文章,因为网上现存的基本上不是最新版的,本文采用了比较新一点的 24.12版本进行破解,可以支持使用几年了。

HTML转Word和PDF功能

除了基本的文档处理外,Aspose Words还提供了强大的HTML转Word和PDF功能,支持复杂的样式保留和格式转换。

核心功能特点:

  1. 完整保留HTML中的样式和布局
  2. 支持自定义页眉页脚(可添加公司Logo)
  3. 自动优化中英文字体(中文默认微软雅黑,英文Times New Roman)
  4. 表格自动调整和优化
  5. 列表样式自动修正
  6. 图片自适应处理
  7. 生成高质量的PDF文档

使用步骤:

1. pom 文件引入依赖

<dependencies><dependency><groupId>com.aspose</groupId><artifactId>aspose-words</artifactId><version>24.12</version><classifier>jdk17</classifier></dependency>
</dependencies><repositories><repository><id>AsposeJavaAPI</id><name>Aspose Java API</name><url>https://releases.aspose.com/java/repo/</url></repository>
</repositories>

2. HTML转Word和PDF工具类

package com.gene.project.genereport.utils;import com.aspose.words.*;
import com.aspose.words.Font;
import com.aspose.words.Shape;
import com.gene.common.utils.StringUtils;import java.awt.*;
import java.io.File;
import java.io.InputStream;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;public class HtmlToWordGenerator {/*** 将 HTML 文件转换为 Word 和 PDF 文件,并返回文件路径** @param htmlFilePath     HTML 文件路径* @param logoImagePath    页眉图片路径(本地路径)* @param outputFileName   输出文件名(不带扩展名)* @param folderPath       输出文件夹路径* @return 包含 docx 和 pdf 文件路径的 Map* @throws Exception 异常处理*/public static Map<String, Object> exportHtmlToWordAndPdf(String htmlFilePath,String logoImagePath,String outputFileName,String folderPath) throws Exception {registerWord2412();// 设置 HTML 加载选项HtmlLoadOptions optionsHtml = new HtmlLoadOptions();optionsHtml.setEncoding(StandardCharsets.UTF_8);optionsHtml.setMswVersion(MsWordVersion.WORD_2019);// 加载 HTML 文件Document doc = new Document(htmlFilePath, optionsHtml);doc.getCompatibilityOptions().optimizeFor(MsWordVersion.WORD_2019);// 设置纸张、页眉页脚等页面格式for (Section section : doc.getSections()) {PageSetup pageSetup = section.getPageSetup();pageSetup.setPaperSize(PaperSize.A4);pageSetup.setOrientation(Orientation.PORTRAIT);pageSetup.setTopMargin(36);pageSetup.setBottomMargin(36);pageSetup.setLeftMargin(36);pageSetup.setRightMargin(36);pageSetup.setHeaderDistance(0);pageSetup.setFooterDistance(36.0);if (StringUtils.isNotEmpty(logoImagePath)) {// 设置页眉HeaderFooter header = new HeaderFooter(doc, HeaderFooterType.HEADER_PRIMARY);Paragraph headerPara = new Paragraph(doc);headerPara.getParagraphFormat().setAlignment(ParagraphAlignment.CENTER);InputStream imageStream = Files.newInputStream(new File(logoImagePath).toPath());double usableWidth = pageSetup.getPageWidth() - pageSetup.getLeftMargin() - pageSetup.getRightMargin();double fixedHeight = 30;Shape imageShape = new Shape(doc, ShapeType.IMAGE);imageShape.setAspectRatioLocked(false);imageShape.getImageData().setImage(imageStream);imageShape.setWrapType(WrapType.INLINE);imageShape.setWidth(usableWidth);imageShape.setHeight(fixedHeight);headerPara.appendChild(imageShape);header.appendChild(headerPara);section.getHeadersFooters().add(header);}// 设置页脚HeaderFooter footer = new HeaderFooter(doc, HeaderFooterType.FOOTER_PRIMARY);Paragraph footerPara = new Paragraph(doc);footerPara.getParagraphFormat().setAlignment(ParagraphAlignment.CENTER);footerPara.appendField("PAGE", String.valueOf(FieldType.FIELD_PAGE));footerPara.appendChild(new Run(doc, " / "));footerPara.appendField("NUMPAGES", String.valueOf(FieldType.FIELD_NUM_PAGES));footer.appendChild(footerPara);section.getHeadersFooters().add(footer);}// 白色背景doc.setPageColor(Color.WHITE);// 文字运行NodeCollection runs = doc.getChildNodes(NodeType.RUN, true);for (int i = 0; i < runs.getCount(); i++) {Run run = (Run) runs.get(i);String text = run.getText();Font font = run.getFont();double originalSize = font.getSize();if (originalSize > 0) {font.setSize(Math.max(originalSize * 0.8, 6));}if (text.matches("^[\\u4e00-\\u9fa5\\p{Punct}\\s]+$")) {font.setName("Microsoft YaHei");} else if (text.matches("^[A-Za-z0-9\\p{Punct}\\s]+$")) {font.setName("Times New Roman");} else {font.setName("Microsoft YaHei");font.setNameAscii("Times New Roman");font.setNameFarEast("Microsoft YaHei");font.setNameOther("Microsoft YaHei");}}// 表格样式设置NodeCollection tables = doc.getChildNodes(NodeType.TABLE, true);for (int t = 0; t < tables.getCount(); t++) {Table table = (Table) tables.get(t);table.setAlignment(TableAlignment.CENTER);table.setPreferredWidth(PreferredWidth.fromPercent(95));table.setAllowAutoFit(false);for (Row row : table.getRows()) {row.getRowFormat().setHeightRule(HeightRule.AUTO);row.getRowFormat().setHeight(20);for (Cell cell : row.getCells()) {cell.getCellFormat().setVerticalAlignment(CellVerticalAlignment.CENTER);cell.getCellFormat().setTopPadding(5);cell.getCellFormat().setBottomPadding(5);cell.getCellFormat().setLeftPadding(5);cell.getCellFormat().setRightPadding(5);for (Paragraph para : cell.getParagraphs()) {para.getParagraphFormat().setSpaceBefore(0);para.getParagraphFormat().setSpaceAfter(0);para.getParagraphFormat().setLineSpacing(12);}}}}// 段落处理NodeCollection paragraphs = doc.getChildNodes(NodeType.PARAGRAPH, true);boolean firstHeading1Found = false;for (int i = 0; i < paragraphs.getCount(); i++) {Paragraph para = (Paragraph) paragraphs.get(i);String styleName = para.getParagraphFormat().getStyleName();ParagraphFormat paragraphFormat = para.getParagraphFormat();if ("Heading 1".equals(styleName)) {if (firstHeading1Found) {paragraphFormat.setPageBreakBefore(true);} else {firstHeading1Found = true;}}if ("Heading 2".equals(styleName)) {paragraphFormat.setLeftIndent(0);paragraphFormat.setRightIndent(0);}ListFormat listFormat = para.getListFormat();if (listFormat.isListItem()) {ListLevel listLevel = listFormat.getListLevel();String bullet = listLevel.getNumberFormat();if ("\uF0B7".equals(bullet)) {listLevel.getFont().setName("Microsoft YaHei");listLevel.getFont().setNameAscii("Microsoft YaHei");listLevel.getFont().setNameFarEast("Microsoft YaHei");listLevel.getFont().setNameOther("Microsoft YaHei");if (para.getRuns().getCount() > 0) {double fontSize = para.getRuns().get(0).getFont().getSize();listLevel.getFont().setSize(fontSize);}listLevel.setNumberFormat("•");} else if (".".equals(bullet) || "·".equals(bullet)) {listLevel.getFont().setName("Times New Roman");listLevel.getFont().setNameAscii("Times New Roman");listLevel.getFont().setNameFarEast("Times New Roman");listLevel.getFont().setNameOther("Times New Roman");if (para.getRuns().getCount() > 0) {double fontSize = para.getRuns().get(0).getFont().getSize();listLevel.getFont().setSize(fontSize);}}}}Map<String, Object> result = new HashMap<>();// 输出文件路径String uuid = UUID.randomUUID().toString();String docxPath = folderPath + File.separator + outputFileName + "_" + uuid + ".docx";String pdfPath = folderPath + File.separator + outputFileName + "_" + uuid + ".pdf";// 保存 Word 文件OoxmlSaveOptions wordOptions = new OoxmlSaveOptions(SaveFormat.DOCX);wordOptions.setCompliance(OoxmlCompliance.ISO_29500_2008_TRANSITIONAL);wordOptions.setCompressionLevel(CompressionLevel.MAXIMUM);doc.save(docxPath, wordOptions);result.put("docxFilePath", docxPath);// 保存 PDF 文件PdfSaveOptions pdfOptions = new PdfSaveOptions();pdfOptions.setUseCoreFonts(false);pdfOptions.setUseHighQualityRendering(true);pdfOptions.setJpegQuality(100);pdfOptions.setImageCompression(0);pdfOptions.setCompliance(PdfCompliance.PDF_20);pdfOptions.setFontEmbeddingMode(PdfFontEmbeddingMode.EMBED_ALL);pdfOptions.setExportDocumentStructure(true);pdfOptions.setDmlRenderingMode(DmlRenderingMode.DRAWING_ML);pdfOptions.setDmlEffectsRenderingMode(DmlEffectsRenderingMode.FINE);pdfOptions.setEmbedFullFonts(true);doc.save(pdfPath, pdfOptions);result.put("pdfFilePath", pdfPath);return result;}/*** 核心破解方法*/public static void registerWord2412() {try {Class<?> zzodClass = Class.forName("com.aspose.words.zzod");Constructor<?> constructors = zzodClass.getDeclaredConstructors()[0];constructors.setAccessible(true);Object instance = constructors.newInstance(null, null);Field zzWws = zzodClass.getDeclaredField("zzWws");zzWws.setAccessible(true);zzWws.set(instance, 1);Field zzVZC = zzodClass.getDeclaredField("zzVZC");zzVZC.setAccessible(true);zzVZC.set(instance, 1);Class<?> zz83Class = Class.forName("com.aspose.words.zz83");constructors.setAccessible(true);constructors.newInstance(null, null);Field zzZY4 = zz83Class.getDeclaredField("zzZY4");zzZY4.setAccessible(true);ArrayList<Object> zzwPValue = new ArrayList<>();zzwPValue.add(instance);zzZY4.set(null, zzwPValue);Class<?> zzXuRClass = Class.forName("com.aspose.words.zzXuR");Field zzWE8 = zzXuRClass.getDeclaredField("zzWE8");zzWE8.setAccessible(true);zzWE8.set(null, 128);Field zzZKj = zzXuRClass.getDeclaredField("zzZKj");zzZKj.setAccessible(true);zzZKj.set(null, false);} catch (Exception e) {e.printStackTrace();}}
}

3. 使用示例

public class HtmlToWordTest {public static void main(String[] args) {try {String htmlPath = "input.html";String logoPath = "company_logo.png";String outputName = "Report";String outputFolder = "output";Map<String, Object> result = HtmlToWordGenerator.exportHtmlToWordAndPdf(htmlPath, logoPath, outputName, outputFolder);System.out.println("Word文件生成成功: " + result.get("docxFilePath"));System.out.println("PDF文件生成成功: " + result.get("pdfFilePath"));} catch (Exception e) {e.printStackTrace();}}
}

重要声明

请勿用于商业用途,商业用途请购买官方正版,用于商业用途本人不承担任何责任。

功能特点总结

  1. 格式保留:完整保留HTML中的样式、布局和结构
  2. 字体优化:自动区分中英文应用不同字体
  3. 表格处理:自动调整表格宽度和样式
  4. 列表修正:规范化列表符号和编号
  5. 页眉页脚:支持自定义页眉页脚和页码
  6. 高质量PDF:生成符合PDF 2.0标准的高质量文档
  7. 批量处理:支持批量转换多个HTML文件

该工具类特别适合需要将网页内容或HTML报告转换为正式Word/PDF文档的场景,如报告生成、文档归档等需求。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如若转载,请注明出处:http://www.pswp.cn/diannao/97512.shtml
繁体地址,请注明出处:http://hk.pswp.cn/diannao/97512.shtml
英文地址,请注明出处:http://en.pswp.cn/diannao/97512.shtml

如若内容造成侵权/违法违规/事实不符,请联系英文站点网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

php连接rabbitmq例子

首先确保安装好了Rabbitmq服务器。1.新建一个空白php项目&#xff0c;安装php客户端库&#xff1a;composer require php-amqplib/php-amqplib2.生产者然后添加生产者代码 (producer.php)<?php require_once __DIR__ . /vendor/autoload.php;use PhpAmqpLib\Connection\AMQ…

Docker Swarm vs Kubernetes vs Nomad:容器编排方案对比与选型建议

Docker Swarm vs Kubernetes vs Nomad&#xff1a;容器编排方案对比与选型建议 在微服务和云原生时代&#xff0c;容器编排成为支持大规模容器化应用的关键技术。本文将从问题背景、方案对比、优缺点分析、选型建议以及实际应用效果验证五个方面&#xff0c;对Docker Swarm、Ku…

似然函数对数似然函数负对数似然函数

目录1. 似然函数的定义2. 对数似然函数的定义3. 负对数似然函数的定义4. 负对数似然函数的优化5. 具体应用示例5.1 逻辑回归中的负对数似然函数5.2 优化逻辑回归的负对数似然函数1. 似然函数的定义 似然函数L(θ∣X)L(\theta | X)L(θ∣X)是在给定参数θ\thetaθ 下&#xff0…

鸿蒙地址选择库(ArkTs UI)

功能点&#xff1a;支持三级联动、点击确认返回省市区code及name&#xff08;安心&#xff09;、布局可以高度自定义 实现&#xff1a;TextPicker读取本地json&#xff08;也可用第三方的json 不过需要自行调整了&#xff09; 先上图吧、废话下面再说&#xff1a; 凑和看吧、…

YOLO 目标检测:数据集构建(LabelImg 实操)、评估指标(mAP/IOU)、 NMS 后处理

文章目录基本知识介绍1.视觉处理三大任务2.训练、验证、测试、推理3.数据集3.1 数据集格式3.2 数据集标注4.上游任务和下游任务YOLO指标1.真实框&#xff08;Ground Truth Box&#xff09;与边界框&#xff08;Bounding Box&#xff09;2.交并比&#xff08;IOU&#xff09;3.置…

进程状态 —— Linux内核(Kernel)

&#x1f381;个人主页&#xff1a;工藤新一 &#x1f50d;系列专栏&#xff1a;C面向对象&#xff08;类和对象篇&#xff09; &#x1f31f;心中的天空之城&#xff0c;终会照亮我前方的路 &#x1f389;欢迎大家点赞&#x1f44d;评论&#x1f4dd;收藏⭐文章 文章目录进…

计算机视觉与深度学习 | 低照度图像处理算法综述:发展、技术与趋势

文章目录 一、发展历程:从传统模型到智能融合 (一)传统模型构建阶段(1970s-2016) (二)深度学习应用阶段(2017-2020) (三)硬件-算法协同阶段(2021至今) 二、技术分类与性能对比 (一)传统方法体系 (二)深度学习方法 1. 监督学习模型 2. 无监督/自监督方法 3. 混…

责任链模式实践-开放银行数据保护及合规

责任链模式介绍什么是责任链模责任链模式是一种行为设计模式&#xff0c; 允许你将请求沿着处理者链进行发送。 收到请求后&#xff0c; 每个处理者均可对请求进行处理&#xff0c; 或将其传递给链上的下个处理者。责任链模式结构伪代码基于责任链的开放银行数据保护及合规实践…

npm install --global @dcloudio/uni-cli 时安装失败

这个日志显示在执行 npm install --global dcloudio/uni-cli 时安装失败&#xff0c;核心错误是 UNABLE_TO_GET_GET_ISSUER_CERT_LOCALLY&#xff08;无法获取本地颁发者证书&#xff09;&#xff0c;属于 HTTPS 证书验证失败 问题。错误原因npm 访问官方 registry&#xff08;…

吱吱企业通讯软件可私有化部署,构建安全可控的通讯办公平台

在当今激烈的市场竞争环境中&#xff0c;企业通讯已成为制胜的关键因素。吱吱作为一款专为企业管理设计的IM即时办公通讯软件&#xff0c;提供了高度安全的通讯办公环境&#xff0c;确保信息在内部流通的安全性与高效性&#xff0c;为企业数字化转型奠定了坚实的基础。 一、私有…

暄桐:唯有认真思考过死亡,才足以应对日常

暄桐是一间传统美学教育教室&#xff0c;创办于2011年&#xff0c;林曦是创办人和授课老师&#xff0c;教授以书法为主的传统文化和技艺&#xff0c;皆在以书法为起点&#xff0c;亲近中国传统之美&#xff0c;以实践和所得&#xff0c;滋养当下生活。初听庄子在妻子离世后“鼓…

目标检测领域基本概念

基于提议的方法&#xff0c;也常被称为两阶段 (Two-stage) 方法&#xff0c;是目标检测领域的经典范式。它们将目标检测任务分解为两个主要步骤&#xff1a;阶段一&#xff1a;区域提议 (Region Proposal Generation) 目标&#xff1a; 在图像中生成一系列可能包含物体的候选区…

【开题答辩全过程】以 基于SpringBoot的流浪猫狗领养系统为例,包含答辩的问题和答案

个人简介一名14年经验的资深毕设内行人&#xff0c;语言擅长Java、php、微信小程序、Python、Golang、安卓Android等开发项目包括大数据、深度学习、网站、小程序、安卓、算法。平常会做一些项目定制化开发、代码讲解、答辩教学、文档编写、也懂一些降重方面的技巧。感谢大家的…

扣子(coze)实践指南进阶篇——创建工作流,并将工作流接入智能体

大家好&#xff0c;欢迎阅读这份《智能体&#xff08;AIAgent&#xff09;开发指南》&#xff01; 在大模型和智能体快速发展的今天&#xff0c;很多朋友希望学习如何从零开始搭建一个属于自己的智能体。本教程的特点是 完全基于国产大模型与火山推理引擎实现&#xff0c;不用翻…

【STM32】外部中断(上)

【STM32】外部中断前言一、中断系统1.1 什么是中断1.2 中断优先级1.3 中断嵌套1.4 中断执行流程二、NVIC2.1NVIC基本结构2.2 NVIC优先级分组三、EXTI3.1 EXTI 外部中断&#xff08;Extern Interrupt&#xff09;3.2 EXTI基本结构3.3 AFIO复用IO口3.4 EXTI内部框图前言 【STM32…

TimeDP Learning to Generate Multi-Domain Time Series with Domain Prompts论文阅读笔记

TimeDP Learning to Generate Multi-Domain Time Series with Domain Prompts 摘要 在跨域时序数据生成任务中&#xff0c;提出使用”时间序列语义原型“模块定义时间序列原型来表示时间序列基&#xff0c;每个原型向量作为“词”表示一些基本的时间序列特征。应用原型分配模块…

Ubuntu安装NVIDIA显卡驱动

清理旧驱动 sudo apt purge nvidia* libnvidia* sudo apt autoremovesudo find /etc -name *nvidia* -exec sudo rm -rf {} sudo rm -rf /usr/local/cuda*禁用 nouveau echo blacklist nouveau options nouveau modeset0 | sudo tee /etc/modprobe.d/blacklist-nouveau.conf…

硬件工程师成长之路:从入门到精通的技术旅程

文章目录前言第一阶段&#xff1a;基础知识的积累理论知识储备动手实践第二阶段&#xff1a;专业技能的提升PCB设计嵌入式系统开发第三阶段&#xff1a;专业方向的选择射频&#xff08;RF&#xff09;工程电源设计高速数字电路FPGA/ASIC设计第四阶段&#xff1a;工程管理与视野…

PyTorch 张量(Tensor)详解:从基础到实战

1. 引言在深度学习和科学计算领域&#xff0c;张量&#xff08;Tensor&#xff09; 是最基础的数据结构。PyTorch 作为当前最流行的深度学习框架之一&#xff0c;其核心计算单元就是张量。与 NumPy 的 ndarray 类似&#xff0c;PyTorch 张量支持高效的数值计算&#xff0c;但额…

CPTS---Hospital

端口扫描 nmap -A -p- -n -Pn -T4 10.10.11.241 22/tcp open ssh OpenSSH 9.0p1 Ubuntu 1ubuntu8.5 (Ubuntu Linux; protocol 2.0) | ssh-hostkey: | 256 e1:4b:4b:3a:6d:18:66:69:39:f7:aa:74:b3:16:0a:aa (ECDSA) |_ 256 96:c1:dc:d8:97:20:95:e7:01:5…