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()
相关推荐
kyriewen4 小时前
Anthropic 估值逼近万亿美元,Claude Sonnet 5 + Claude Science 一天两连发
前端·ai编程·claude
小徐_23335 小时前
Wot UI 2.2.0 发布:Button 新增 subtle,VideoPreview 预览体验继续增强
前端·微信小程序·uni-app
倔强的石头_6 小时前
《Kingbase护城河》——猎捕慢查询:执行计划的微观解析与索引调优实战
数据库
天蓝色的鱼鱼8 小时前
关于 CSS 你可能不知道的属性,但关键时刻很有用
前端·css
SelectDB8 小时前
Apache Doris Python UDF:让 SQL 直接调用 Python 生态,支撑 Agent 时代复杂业务逻辑
大数据·数据库·python
泯泷9 小时前
第 2 篇:设计第一套字节码:Opcode、Instruction 与 Constant Pool
前端·javascript·安全
妙码生花9 小时前
从 PHP 到 AI + Golang,程序员自救转型手记(十五):优化细节、网络请求封装
前端·后端·ai编程
泯泷9 小时前
第 1 篇:从 1 + 2 开始:亲手写出第一台 JSVM
前端·javascript·安全
团团崽_七分甜9 小时前
Spring Boot 核心知识点总结
前端