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()
相关推荐
Asize1 小时前
AI 协作开发新范式:我用 SDD 做了个排版 npm 包
前端·人工智能
kyriewen2 小时前
我把今年流传的前端 AI 面试题整理了一遍——4 类场景题+回答框架(附速查表)
前端·面试·程序员
计算机魔术师3 小时前
国产多模态模型正面硬刚Opus旗舰:差距从30%缩到3%
前端
风骏时光牛马3 小时前
程序员进阶:深度思考,解锁职场成长的底层逻辑
前端
IT_陈寒3 小时前
用了Proxy才发现以前的JavaScript白写了
前端·人工智能·后端
爱丶不疚4 小时前
Eval: Agent 说的 Eval 是什么?从单测、TDD 到 Sentry 聊起
前端·ai编程·vibecoding
求道於盲4 小时前
python中的类型标注
前端
计算机魔术师4 小时前
从硅谷测试到全球铺开,ChatGPT广告的10亿美元秘密
前端
这个DBA有点耶4 小时前
2026年分布式数据库有哪些主流选择?先评估这5个维度再决定
数据库·分布式·dba
古法安卓5 小时前
Android-日志系统源码解析
android·java·android studio