python --html转pdf/pdf分页优化

python 复制代码
import os

class HtmlToPdfConverter:
    """
    HTML转PDF工具类(基于wkhtmltopdf)
    核心功能:自动检测HTML中是否包含表格,仅在有表格时注入分页优化CSS,避免表格跨页重叠
    """
    
    def __init__(self):
        """初始化转换器,无需额外参数"""
        pass

    def _has_table(self, html_content):
        """
        私有方法:判断HTML内容中是否包含表格标签
        :param html_content: 读取的HTML文本内容
        :return: bool - True(有表格)/False(无表格)
        """
        # 转小写避免大小写标签问题(如<TABLE>、<table>)
        return '<table' in html_content.lower()

    def _inject_precise_css(self, html_path):
        """
        私有方法:注入精准的分页CSS(仅防行断裂,不禁止表格分页)
        :param html_path: HTML文件路径
        """
        # 定义分页优化CSS
        precise_css = """
        <style>
        tr {
            page-break-inside: avoid !important;
            page-break-after: auto !important;
        }
        td, th {
            page-break-inside: avoid !important;
            white-space: normal !important;
            word-wrap: break-word !important;
        }
        table {
            border-collapse: collapse !important;
            page-break-inside: auto !important;
            width: 100% !important;
        }
        body {
            page-break-inside: auto !important;
            margin: 0;
            padding: 0;
        }
        </style>
        """
        
        # 读取HTML内容
        with open(html_path, 'r', encoding='utf-8') as f:
            html_content = f.read()
        
        # 仅当包含表格时才注入CSS
        if self._has_table(html_content):
            # 优先插入到<head>标签内,无<head>则加在开头
            if '<head>' in html_content:
                new_content = html_content.replace('<head>', f'<head>{precise_css}')
            else:
                new_content = precise_css + html_content
            
            # 写回HTML文件
            with open(html_path, 'w', encoding='utf-8') as f:
                f.write(new_content)

    def html2pdf_new(self, group_path, msg_path):
        """
        对外公开方法:执行HTML转PDF(核心逻辑)
        :param group_path: 存放report.html的目录路径
        :param msg_path: 输出PDF文件的目录路径
        """
        # 拼接文件完整路径
        report_path = os.path.join(group_path, "report.html")
        target_path = os.path.join(msg_path, "html_pdf.pdf")

        # 仅当有表格时注入CSS,无表格则跳过
        self._inject_precise_css(report_path)

        # 构造wkhtmltopdf命令(保留核心优化参数)
        cmd = (
            "wkhtmltopdf "
            "--encoding 'utf-8' "          # 编码设置,防止中文乱码
            "--disable-smart-shrinking "   # 禁用智能压缩,避免表格挤压重叠
            "--enable-local-file-access "  # 允许加载本地文件(CSS/图片)
            "{} {}".format(report_path, target_path)
        )
        
        # 执行命令行转换
        os.system(cmd)


# ===================== 使用示例 =====================
if __name__ == "__main__":
    # 1. 实例化转换器
    converter = HtmlToPdfConverter()
    
    # 2. 调用转换方法(传入实际路径)
    # converter.html2pdf_new("你的report.html所在目录", "你要输出PDF的目录")
    # 示例:
    # converter.html2pdf_new(r"C:\data\group", r"C:\data\msg")

官网下载地址:https://wkhtmltopdf.org/downloads.html

相关推荐
2301_8009769310 分钟前
正则表达式
开发语言·python·正则表达式
码界奇点23 分钟前
基于Python的新浪微博数据爬虫系统设计与实现
数据库·爬虫·python·毕业设计·新浪微博·源代码管理
AI木马人1 小时前
1.人工智能实战:大模型推理接口响应慢?从模型加载到 FastAPI 部署的完整优化方案
人工智能·python·fastapi
青少儿编程课堂1 小时前
2026青少儿信息素养大赛备赛指南!Python/Scratch/C++备考要点
开发语言·c++·python
用户8356290780511 小时前
使用 Python 设置 Excel 数据验证
后端·python
Nick_zcy2 小时前
小说在线阅读网站和小说管理系统 · 功能全解析
java·后端·python·springboot·ruoyi
*Lisen2 小时前
从零手写 FlashAttention(PyTorch实现 + 原理推导)
人工智能·pytorch·python
web打印社区2 小时前
2026最新Web静默打印解决方案,无插件无预览,完美替代Lodop
前端·javascript·vue.js·electron·pdf
用户8356290780512 小时前
用 Python 轻松在 Excel 工作表中应用条件格式
后端·python
red1giant_star2 小时前
Python根据文件后缀统计文件大小、找出文件位置(仿Everything)
后端·python