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()
相关推荐
羊小蜜.2 小时前
Mysql 03: 连接查询全解——内连接、外连接与复合条件查询
数据库·mysql·算法·连接查询
架构师沉默2 小时前
为什么 Dubbo 从 ZooKeeper 转向 Nacos?
java·后端·架构
IvorySQL2 小时前
PostgreSQL 技术日报 (4月2日)|社区工具更新与内核补丁讨论速递
数据库·postgresql·开源
用户8307196840822 小时前
Spring Prototype Bean的四种正确使用方式
java·spring boot·后端
永恒_顺其自然2 小时前
Java Web 传统项目异步分块上传系统实现方案
java·开发语言·前端
百撕可乐2 小时前
NextJS官网实战01:Vue与React的区别
前端·react.js·前端框架
polaris06302 小时前
完美解决phpstudy安装后mysql无法启动
数据库·mysql
Можно2 小时前
Vue 组件样式隔离完全指南:从原理到实战
前端·javascript·vue.js
赫瑞3 小时前
Java中的大数处理 —— BigInteger
java·开发语言