|
@@ -0,0 +1,68 @@
|
|
|
|
+package com.qmth.boot.tools.html2pdf;
|
|
|
|
+
|
|
|
|
+import com.qmth.boot.tools.models.PageSize;
|
|
|
|
+import org.apache.commons.lang3.StringUtils;
|
|
|
|
+
|
|
|
|
+import java.io.File;
|
|
|
|
+import java.util.Arrays;
|
|
|
|
+
|
|
|
|
+/**
|
|
|
|
+ * 调用wkhtmltopdf工具完成html转pdf文件的工具类
|
|
|
|
+ */
|
|
|
|
+public class HtmlToPdf {
|
|
|
|
+
|
|
|
|
+ private static String exePath = null;
|
|
|
|
+
|
|
|
|
+ private static final String COMMAND_PATTERN = "%s --encoding utf8 --disable-smart-shrinking --margin-top 0 --margin-bottom 0 --margin-left 0 --margin-right 0 --page-size %s %s %s %s";
|
|
|
|
+
|
|
|
|
+ static {
|
|
|
|
+ //尝试获取系统环境变量QMTH_HOME,在安装包环境下自动定位wkhtmltopdf工具目录
|
|
|
|
+ String qmthHome = System.getenv("QMTH_HOME");
|
|
|
|
+ if (StringUtils.isNotBlank(qmthHome)) {
|
|
|
|
+ File file = new File(StringUtils
|
|
|
|
+ .join(Arrays.asList(qmthHome, "common", "wkhtmltopdf", "bin", "wkhtmltopdf"), File.separator));
|
|
|
|
+ if (file.exists() && file.isFile()) {
|
|
|
|
+ exePath = file.getAbsolutePath();
|
|
|
|
+ }
|
|
|
|
+ }
|
|
|
|
+ }
|
|
|
|
+
|
|
|
|
+ /**
|
|
|
|
+ * 非安装包环境下,应用自定义wkhtmltopdf工具目录,需要保证文件存在
|
|
|
|
+ *
|
|
|
|
+ * @param filePath
|
|
|
|
+ */
|
|
|
|
+ public static void setExePath(String filePath) {
|
|
|
|
+ File file = new File(filePath);
|
|
|
|
+ if (file.exists() && file.isFile()) {
|
|
|
|
+ exePath = filePath;
|
|
|
|
+ } else {
|
|
|
|
+ throw new RuntimeException("Invalid exePath: " + filePath);
|
|
|
|
+ }
|
|
|
|
+ }
|
|
|
|
+
|
|
|
|
+ /**
|
|
|
|
+ * 执行html转pdf操作
|
|
|
|
+ *
|
|
|
|
+ * @param url - html的完整链接地址
|
|
|
|
+ * @param file - 本地生成文件,自动创建所在目录,不存在时自动创建空白文件
|
|
|
|
+ * @param pageSize - 转换纸张尺寸
|
|
|
|
+ * @throws Exception
|
|
|
|
+ */
|
|
|
|
+ public static void execute(String url, File file, PageSize pageSize) throws Exception {
|
|
|
|
+ if (exePath == null) {
|
|
|
|
+ throw new RuntimeException("HtmlToPdf exePath unexists");
|
|
|
|
+ }
|
|
|
|
+ file.getParentFile().mkdirs();
|
|
|
|
+ if (!file.exists()) {
|
|
|
|
+ file.createNewFile();
|
|
|
|
+ }
|
|
|
|
+ String extendParam = "";
|
|
|
|
+ if (pageSize == PageSize.A3) {
|
|
|
|
+ extendParam = "--orientation Landscape";
|
|
|
|
+ }
|
|
|
|
+ String command = String
|
|
|
|
+ .format(COMMAND_PATTERN, exePath, pageSize.getCode(), extendParam, url, file.getAbsolutePath());
|
|
|
|
+ Runtime.getRuntime().exec(command).waitFor();
|
|
|
|
+ }
|
|
|
|
+}
|