需求简述
使用html文本或者文件生成保留原有样式及格式的pdf或者word文档,经调研,itext适用于少量代码的转换,对html的格式比较严格,html代码一多就会导致样式丢失,主要是用法简单易上手,
wkhtmltopdf毕竟是一款软件,功能相对来说强大很多,主要是对部署项目这块比较麻烦
wkhtmltopdf需安装使用环境,poi只需引入依赖
wkhtmltopdf安装
-
官网下载https://wkhtmltopdf.org/downloads.html
-
命令手册: https://wkhtmltopdf.org/usage/wkhtmltopdf.txt
linux安装
一.将下载下来的tar.xz安装包解压
1. 例: tar xvfJ wkhtmltox-0.12.3_linux-generic-amd64.tar.xz
1. 然后进入到wkhtmltopdf bin目录下,设置权限和环境变量
1. 将bin目录下的wkhtmltopdf和wkhtmltoimage移动到/usr/bin下
- sudo cp wkhtmltoimage /usr/bin/wkhtmltoimage
- sudo cp wkhtmltopdf /usr/bin/wkhtmltopdf
- 添加权限 更改全部者
- sudo chown root:root /usr/bin/wkhtmltoimage
- sudo chown root:root /usr/bin/wkhtmltopdf
- sudo chmod +x /usr/bin/wkhtmltoimage
- sudo chmod +x /usr/bin/wkhtmltopdf
4.设置环境变量
- vim /etc/profile 的最后一行添加
- export PATH= $PATH:/
二. 进行测试
-wkhtmltopdf www.baidu.com baidu.pdf
-"Done"表示完成
三.导出后pdf文件中文空白
-在系统中添加中文字体
-C:\Windows\Fonts\simsun.ttc中文字体,上传至linux中/usr/share/fonts/目录下
java集成wkhtmltopdf
思路
<!-- 解析html中元素 -->
<dependency>
<groupId>org.jsoup</groupId>
<artifactId>jsoup</artifactId>
<version>1.11.3</version>
</dependency>
<!-- 我当时使用JDK11 -->
<!-- 猜测因jdk版本高问题导致找不到文件,导入三个依赖即可,此问题可能会出现在linux导出时命令运行完成,但不生效-->
<dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
<version>2.3.0</version>
</dependency>
<dependency>
<groupId>com.sun.xml.bind</groupId>
<artifactId>jaxb-impl</artifactId>
<version>2.3.0</version>
</dependency>
<dependency>
<groupId>com.sun.xml.bind</groupId>
<artifactId>jaxb-core</artifactId>
<version>2.3.0</version>
</dependency>
<!-- pdf导出word使用的poi-->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>4.0.0</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>4.0.0</version>
</dependency>
<!-- wkhtmltopdf所需-->
<dependency>
<groupId>e-iceblue</groupId>
<artifactId>spire.pdf</artifactId>
<version>4.1.2</version>
</dependency>
<!--wkhtmltopdf所需的连接地址 -->
<repositories>
<repository>
<id>com.e-iceblue</id>
<url>http://repo.e-iceblue.com/nexus/content/groups/public/</url>
</repository>
ory>
</repositories>
html转pdf实现思路
html转word实现思路
pdf转word问题解决方案
1.重新读取word文档,删除第一个元素可以删除生成doc的警告.
2通过poi,提取所有的文档元素,设置行距,以及非中文字体
- 此方法不是在当前文件下进行修改,需要重新创建文件将字节流输入此文件