Skip to content

使用chrome将html转换为PDF

python
import asyncio
from pyppeteer import launch
from pathlib import Path

class ChromeHelper:

    def __init__(self):
        self.edge_path = r'C:\\Program Files (x86)\\Microsoft\\Edge\\Application\\msedge.exe'  # Replace with your Edge executable path
        self.browser = None
    
    async def start_chrome(self):
        self.browser = await launch(
            executablePath=self.edge_path,
            headless=True,
            args=['--js-flags="--experimental-wasm-simd"']
        )

    async def html_to_pdf(self, html_content, output_path):
        if Path(output_path).exists():
            return
        
        if not self.browser:
            await self.start_chrome()

        page = await self.browser.newPage()
        await page.setContent(html_content)
        await page.pdf({'path': output_path, 'format': 'A5'})
    
    async def close(self):
        if self.browser:
            await self.browser.close()

async def content_to_pdf(html_content, output_path):
    chrome_helper = ChromeHelper()
    await chrome_helper.html_to_pdf(html_content, output_path)
    await chrome_helper.close()

if __name__ == '__main__':
    with open('input.html', 'r', encoding='utf-8') as fp:
        html_content = fp.read()

    asyncio.run(content_to_pdf(html_content, output_path='output.pdf'))
toml
dependencies = [
    "pyppeteer>=2.0.0",
]
requires-python = "==3.9.*"

Released under the MIT License.