Html转PDF导出wkhtmltopdf工具 教程 及工具类

1wkhtmltopdf的安装与使用

官网下载:   wkhtmltopdficon-default.png?t=O83Ahttps://wkhtmltopdf.org/downloads.html

2工具类介绍 

  

package com.auxgroup.tms.server.util;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.io.*;

/**
 * @Description 描述
 * @Author huazhongqiang
 * @Date 2025-01-13 9:39
 */
@Component
@Slf4j
public class HtmlToPdfUtil {
    // wkhtmltopdf在系统中的路径,使用该组件的时候需要安装一个软件
    private static final String toPdfTool = "D:\\HzqApp\\wkhtmltopdf\\bin\\wkhtmltopdf.exe";

    /**
     * html字符串转pdf并写入输出流
     *
     * @param htmlString   html字符串
     * @param outputStream 输出流
     * @return 转换成功返回true
     */
    public static boolean convertFromHtmlString(String htmlString, OutputStream outputStream) {
        File tempHtmlFile = null;
        File tempPdfFile = null;
        try {
            // 创建临时HTML文件
            tempHtmlFile = File.createTempFile("temp", ".html");
            tempHtmlFile.deleteOnExit(); // 确保程序退出时删除临时文件

            // 将HTML字符串写入临时文件
            try (FileWriter writer = new FileWriter(tempHtmlFile)) {
                writer.write(htmlString);
            }

            // 创建临时PDF文件
            tempPdfFile = File.createTempFile("temp", ".pdf");
            tempPdfFile.deleteOnExit(); // 确保程序退出时删除临时文件

            // 使用临时文件路径调用convert方法
            if (!convert(tempHtmlFile.getAbsolutePath(), tempPdfFile.getAbsolutePath())) {
                return false;
            }

            // 将生成的PDF文件内容写入输出流
            try (InputStream inputStream = new FileInputStream(tempPdfFile)) {
                byte[] buffer = new byte[1024];
                int bytesRead;
                while ((bytesRead = inputStream.read(buffer)) != -1) {
                    outputStream.write(buffer, 0, bytesRead);
                }
            }

            return true;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        } finally {
            // 删除临时文件
            if (tempHtmlFile != null && tempHtmlFile.exists()) {
                tempHtmlFile.delete();
            }
            if (tempPdfFile != null && tempPdfFile.exists()) {
                tempPdfFile.delete();
            }
        }
    }

    /**
     * html转pdf
     *
     * @param srcPath  html路径,可以是硬盘上的路径,也可以是网络路径
     * @param destPath pdf保存路径
     * @return 转换成功返回true
     */
    private static boolean convert(String srcPath, String destPath) {
        File file = new File(destPath);
        File parent = file.getParentFile();
        // 如果pdf保存路径不存在,则创建路径
        if (!parent.exists()) {
            parent.mkdirs();
        }
        StringBuilder cmd = new StringBuilder();
        if (System.getProperty("os.name").indexOf("Windows") == -1) {
            // 非windows 系统
            //toPdfTool = FileUtil.convertSystemFilePath("/home/ubuntu/wkhtmltox/bin/wkhtmltopdf");
        }
        cmd.append(toPdfTool);
        cmd.append(" ");
        cmd.append("-n --enable-local-file-access");
        log.info("=================================================" + cmd.toString());
        cmd.append(" ");
        cmd.append(" --encoding utf-8"); // 设置字符编码为UTF-8
        cmd.append(" --page-size A4");//纸张设置为A4
        cmd.append("  --margin-top 3cm ");// 设置页面上边距 (default 10mm)
        cmd.append(" --header-spacing 5 ");// (设置页眉和内容的距离,默认0)
        cmd.append(" --footer-spacing 5 ");// (设置页脚和内容的距离)
        cmd.append(srcPath);
        cmd.append(" ");
        cmd.append(destPath);

        boolean result = true;
        try {
            Process proc = Runtime.getRuntime().exec(cmd.toString());
            HtmlToPdfInterceptor error = new HtmlToPdfInterceptor(proc.getErrorStream());
            HtmlToPdfInterceptor output = new HtmlToPdfInterceptor(proc.getInputStream());
            error.start();
            output.start();
            proc.waitFor();
        } catch (Exception e) {
            result = false;
            e.printStackTrace();
        }
        return result;
    }

    public static void main(String[] args) {
        String htmlString = "<html><head><meta charset=\"UTF-8\"></head><body><h1>测试PDF生成</h1><p>这是一个测试HTML字符串。</p></body></html>";
        try (FileOutputStream outputStream = new FileOutputStream("D:\\html\\abc_from_string.pdf")) {
            HtmlToPdfUtil.convertFromHtmlString(htmlString, outputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


}

3导出 效果

xx.pdf

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值