wkhtmltopdf介绍:
-
灵活性:wkhtmltopdf支持多种输入格式,包括本地HTML文件、远程URL和HTML片段。它还提供了丰富的选项和参数,使用户能够自定 义生成的PDF文件的布局、样式和其他属性。
-
跨平台支持:wkhtmltopdf可在多个操作系统上运行,包括Windows、Linux和Mac OS X。这使得它成为开发人员和用户在不同平台上生成PDF文件的理想选择。
-
高质量输出:由于基于WebKit引擎,wkhtmltopdf能够准确地呈现HTML和CSS样式,生成高质量的PDF输出。它支持各种排版功能,如分页、页眉页脚、表格、图像等,并能处理复杂的CSS样式和布局。
-
扩展性:wkhtmltopdf可以通过插件和自定义脚本进行扩展。用户可以编写自定义的JavaScript脚本来处理页面上的元素,或者使用插件来添加额外的功能,如水印、页码等。
-
命令行界面:wkhtmltopdf提供了命令行界面,使用户能够轻松地将HTML文件或网页转换为PDF。这使得它可以与其他工具或脚本集成 ,并可以在自动化流程中使用。
总之,wkhtmltopdf是一个功能强大、灵活且易于使用的工具,可用于将HTML内容转换为高质量的PDF文档。无论是开发人员还是普通用户,都能够从中受益并满足各种需要。
1、下载wkhtmltopdf
通过wkhtmltoimage和wkhtmltopdf实现HTML转图片和PDF
2、Linux安装wkhtmltopdf
# 下载
wget https://github.com/wkhtmltopdf/packaging/releases/download/0.12.6-1/wkhtmltox-0.12.6-1.centos7.x86_64.rpm
# 安装
yum install libXrender libXext fontconfig
yum install xorg-x11-fonts-75dpi.noarch
rpm -Uvh wkhtmltox-0.12.6-1.centos7.x86_64.rpm
# 查看安装位置
whereis wkhtmltopdf
# 安装字体命令
yum -y install fontconfig
#查看linux已安装字体
fc-list
#查看linux已安装中文字体(如果未安装需要安装中文字体,以免出现生成中文PDF乱码)
fc-list :lang=zh
#安装中文字体
mkdir -p /usr/share/fonts/my_fonts
#需要上传simhei.ttf
cd /usr/share/fonts/my_fonts
#安装字体索引
yum install mkfontscale
#进入目录 cd /usr/share/fonts/my_fonts,执行索引字体生成
mkfontscale
#html转PDF命令
wkhtmltopdf 【cmd】 【url】 【文件地址】
3、操作工具类
import cn.hutool.core.io.FileUtil;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import net.coobird.thumbnailator.Thumbnails;
import java.io.IOException;
import java.io.InputStream;
import java.util.concurrent.CountDownLatch;
/**
* <p>
* html 转 图片或pdf 工具类
* </p>
*
* @author zhouyx
* @description https://wkhtmltopdf.org
* html转pdf: wkhtmltopdf http://localhost:8088/mogo-valuation/v4.4/pdf/test zhouyx.pdf
* html转图片: wkhtmltoimage http://localhost:8088/mogo-valuation/v4.4/pdf/test zhouyx.png
* 帮助 wkhtmltopdf -h 或 wkhtmltoimage -h
* @date 2023/03/07 19:08
*/
@Slf4j
public class WkHtmlUtil {
/**
* 工具根目录
*/
private static final String TOOL_WIN_ROOT_DIRECTORY = "";
public static void main(String[] args) throws Exception {
String sourceFilePath = "http://localhost:8088/mogo-valuation/v4.4/pdf/test";
// String targetPngFilePath = Constants.DEFAULT_FOLDER_TMP_GENERATE + "/zhouyx.png";
String targetPdfFilePath = "D:\\testPdf\\zhouyx.pdf";
// 设置宽高
String cmdByImage = "--crop-w 150 --crop-h 150 --quality 100";
// byte[] imageBytes = html2ImageBytes(cmdByImage, sourceFilePath, targetPngFilePath);
// byte[] imageBytesByCompress = html2ImageBytesByCompress(cmdByImage, sourceFilePath, targetPngFilePath);
byte[] pdfBytes = html2PdfBytes("", sourceFilePath, targetPdfFilePath);
}
/**
* html转图片
*
* @param cmd 工具操作指令
* @param sourceFilePath html源资源
* @param targetFilePath 生成目标资源
* @return 图片字节码
* @author zhouyx
* @date 2023/03/07 19:08
*/
public static byte[] html2ImageBytes(String cmd, String sourceFilePath, String targetFilePath) {
return baseTool("wkhtmltoimage", cmd, sourceFilePath, targetFilePath);
}
/**
* html转图片 - 图片压缩版
*
* @param cmd 工具操作指令
* @param sourceFilePath html源资源
* @param targetFilePath 生成目标资源
* @return 图片字节码
* @author zhouyx
* @date 2023/03/07 19:08
*/
@SneakyThrows(Exception.class)
public static byte[] html2ImageBytesByCompress(String cmd, String sourceFilePath, String targetFilePath) {
String filePath = baseToolForPath("wkhtmltoimage", cmd, sourceFilePath, targetFilePath);
Thumbnails.of(filePath)
.scale(1f)
.toFile(targetFilePath);
return FileUtil.readBytes(targetFilePath);
}
/**
* html转pdf
*
* @param cmd 工具操作指令
* @param sourceFilePath html源资源
* @param targetFilePath 生成目标资源
* @return pdf字节码
* @author zhouyx
* @date 2023/03/07 19:08
*/
public static byte[] html2PdfBytes(String cmd, String sourceFilePath, String targetFilePath) {
return baseTool("wkhtmltopdf", cmd, sourceFilePath, targetFilePath);
}
/**
* html转pdf
*
* @param cmd 工具操作指令
* @param sourceFilePath html源资源
* @param targetFilePath 生成目标资源
* @return pdf字节码
* @author zhouyx
* @date 2023/03/07 19:08
*/
public static String html2PdfFilePath(String cmd, String sourceFilePath, String targetFilePath) {
return baseToolForPath("wkhtmltopdf", cmd, sourceFilePath, targetFilePath);
}
/**
* 工具基础操作
*
* @param tool 工具
* @param cmd 工具操作指令
* @param sourceFilePath html源资源
* @param targetFilePath 生成目标资源
* @return 字节码
* @author zhouyx
* @date 2023/03/07 19:08
*/
@SneakyThrows({Exception.class})
private static byte[] baseTool(String tool, String cmd, String sourceFilePath, String targetFilePath) {
String filePath = baseToolForPath(tool, cmd, sourceFilePath, targetFilePath);
return FileUtil.readBytes(filePath);
}
/**
* 基本工具路径
* 工具基础操作
*
* @param tool 工具
* @param cmd 工具操作指令
* @param sourceFilePath html源资源
* @param targetFilePath 生成目标资源
* @return 生成资源路径
* @author zhouyx
* @date 2023/03/07 19:08
*/
@SneakyThrows({Exception.class})
public static String baseToolForPath(String command) {
// 先创建父目录
Process process = null;
ProcessBuilder pb = new ProcessBuilder(
command
);
try {
process = pb.start();
// 等待当前命令执行完,再往下执行
process.waitFor();
} catch (IOException e) {
e.printStackTrace();
throw new Exception("工具丢失,请联系系统管理员!");
}finally {
if (null != process) {
process.destroy();
}
}
log.info("=============== FINISH: [{}] ===============", command);
return command;
}
/**
* 基本工具路径
* 工具基础操作
*
* @param tool 工具
* @param cmd 工具操作指令
* @param sourceFilePath html源资源
* @param targetFilePath 生成目标资源
* @return 生成资源路径
* @author zhouyx
* @date 2023/03/07 19:08
*/
@SneakyThrows({Exception.class})
private static String baseToolForPath(String tool, String cmd, String sourceFilePath, String targetFilePath) {
// 先创建父目录
FileUtil.mkParentDirs(targetFilePath);
String command = String.format("%s %s %s %s", getToolRootPath() + tool, cmd, sourceFilePath, targetFilePath);
// ProcessBuilder pb = new ProcessBuilder(
// getToolRootPath() + tool, cmd, sourceFilePath, targetFilePath
//
// );
Process process = null;
InputStream is = null;
InputStream errIs = null;
final CountDownLatch latch = new CountDownLatch(2);
try {
// process=pb.start();
process = Runtime.getRuntime().exec(command);
/**
* process的InputStream和ErrorStream都要接收处理
* 否则会出现问题
*/
is = process.getInputStream();
errIs = process.getErrorStream();
new Thread(new ProcessInputSteramThread(is,latch)).start();
new Thread(new ProcessInputSteramThread(errIs,latch)).start();
//等待当前命令执行完,再往下执行
process.waitFor();
} catch (Exception e) {
e.printStackTrace();
throw new Exception("工具丢失,请联系系统管理员!");
}finally {
if (null != process) {
latch.await();
process.destroy();
}
}
log.info("=============== FINISH: [{}] ===============", command);
return targetFilePath;
}
/**
* 根据不同系统获取工具
*
* @return 工具位置
* @author zhouyx
* @date 2023/03/07 19:08
*/
private static String getToolRootPath() {
String system = System.getProperty("os.name");
if (system.contains("Windows")) {
return TOOL_WIN_ROOT_DIRECTORY;
} else if (system.contains("Linux") || system.contains("Mac OS X")) {
return "";
}
return "";
}
}
import lombok.extern.slf4j.Slf4j;
import java.io.IOException;
import java.io.InputStream;
import java.util.concurrent.CountDownLatch;
/**
* @author zhouyx
* @date 2023/05/15
**/
@Slf4j
public class ProcessInputSteramThread implements Runnable{
private InputStream is ;
private CountDownLatch latch;
public ProcessInputSteramThread(InputStream is,CountDownLatch latch){
this.is = is ;
this.latch = latch;
}
@Override
public void run() {
byte[] bytes = new byte[1024];
int len = 0 ;
while (true) {
try {
//处理流判断读写流
if ((len = is.read(bytes)) != -1){
// System.out.println(new String(bytes, 0, len, "gb2312"));
}else {
break ;
}
} catch (IOException e) {
e.printStackTrace();
log.error("WK生成PDF处理流判断读写流失败");
break;
}
}
latch.countDown();
}
}