python实现HTML转PDF

复制代码
import os
import sys
import asyncio
from urllib.parse import urlparse

from pyppeteer import launch


# 直接写你的真实文件路径
INPUT_HTML = r"C:\Users\70292727\Desktop\test\报价单.html"
OUTPUT_PDF = r"C:\Users\70292727\Desktop\test\报价单.pdf"
BROWSER_EXE = r"C:\Program Files (x86)\Microsoft\Edge\Application\msedge.exe"


def is_url(path: str) -> bool:
    """判断是否为 URL"""
    if not path:
        return False
    parsed = urlparse(path)
    return parsed.scheme in ("http", "https")


def path_to_file_url(path: str) -> str:
    """本地路径转 file:/// URL"""
    abs_path = os.path.abspath(path)
    return "file:///" + abs_path.replace("\\", "/")


async def html_to_pdf(input_path: str, output_pdf: str, browser_exe: str) -> None:
    if not input_path:
        raise ValueError("input_path 不能为空")
    if not output_pdf:
        raise ValueError("output_pdf 不能为空")
    if not browser_exe:
        raise ValueError("browser_exe 不能为空")

    if not os.path.isfile(browser_exe):
        raise FileNotFoundError(f"浏览器程序不存在:{browser_exe}")

    input_path = os.path.abspath(input_path)
    if not is_url(input_path) and not os.path.isfile(input_path):
        raise FileNotFoundError(f"HTML 文件不存在:{input_path}")

    output_pdf = os.path.abspath(output_pdf)
    output_dir = os.path.dirname(output_pdf)
    if output_dir and not os.path.exists(output_dir):
        os.makedirs(output_dir, exist_ok=True)

    browser = await launch(
        executablePath=browser_exe,
        headless=True,
        autoClose=True,
        args=[
            "--no-sandbox",
            "--disable-setuid-sandbox",
            "--disable-dev-shm-usage",
            "--disable-gpu",
            "--allow-file-access-from-files",
            "--enable-local-file-accesses",
            "--disable-web-security",
        ],
    )

    try:
        page = await browser.newPage()

        if is_url(input_path):
            print(f"检测到输入为网页地址:{input_path}")
            await page.goto(input_path, {"waitUntil": "networkidle2"})
        else:
            print(f"检测到输入为本地 HTML 文件:{input_path}")
            file_url = path_to_file_url(input_path)
            await page.goto(file_url, {"waitUntil": "networkidle2"})

        await page.pdf({
            "path": output_pdf,
            "format": "A4",
            "printBackground": True,
            "margin": {
                "top": "15mm",
                "right": "15mm",
                "bottom": "15mm",
                "left": "15mm",
            }
        })

        print(f"PDF 生成成功:{output_pdf}")

    finally:
        await browser.close()


def main():
    try:
        asyncio.run(html_to_pdf(INPUT_HTML, OUTPUT_PDF, BROWSER_EXE))
    except Exception as e:
        print(f"转换失败:{e}")
        sys.exit(1)


if __name__ == "__main__":
    main()
相关推荐
满栀5852 分钟前
vue动态路由效果
前端·javascript·vue.js·前端框架·vue
952368 分钟前
Spring-cloud配置中心
java·spring·spring cloud·微服务
土豆~11 分钟前
文件名没后缀就打不开:前端文件预览的内容嗅探改造
前端·状态模式
ydd10010019 分钟前
寻找两个正序数组的中位数 Java 题解,二分分割详解
java·开发语言
Euato_Key1 小时前
全栈视野学习Cookie——理解 Cookie 的本质
前端
前端开发呀1 小时前
我的 AI 终端配置清单
前端
老纪的技术唠嗑局1 小时前
超级干货分享:中小企业使用 OceanBase 实践经验汇总
数据库
敲代码的玉米C1 小时前
测试一直在写你的真实数据根
前端·人工智能·架构
CLOUD ACE1 小时前
谷歌云代理|零售商Target 如何利用 Spanner Graph 提升零售发现体验并将数据库维护成本降低 50%
数据库·零售
真上帝的左手1 小时前
10. 软件设计&架构-Spring Security 7 整合CAS SSO 单点登录
java·spring·架构·sso