You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Python PDFkit转换NextJS网站为PDF时加载无响应问题排查

问题:pdfkit转换NextJS构建页面(如IMDb)时持续无响应

问题现象

  • 用pdfkit转换普通URL(比如google.com)完全正常,但转换NextJS构建的IMDb页面时,脚本一直卡着没反应,也没任何错误日志
  • 直接用wkhtmltopdf命令调试,进度卡在87%,没有能排查问题的输出:

    Loading pages (1/6)
    [====================================================> ] 87%

解决思路与方案

  1. 延长JS延迟时间
    NextJS页面依赖大量异步渲染逻辑,默认的1-5秒延迟可能不够,试试把javascript-delay调到10秒甚至更久,确保页面完全渲染完成:
'javascript-delay': '10000'
  1. 忽略资源加载错误
    页面里的图片、媒体资源加载失败可能导致进程卡住,添加参数忽略这类错误:
"load-media-error-handling": "ignore",
"no-stop-slow-scripts": ""  # 禁止终止慢脚本,避免NextJS的渲染逻辑被中断
  1. 启用调试日志
    打开JS调试和详细输出,能看到页面加载过程中的具体问题:
"debug-javascript": ""

或者直接用wkhtmltopdf命令加详细参数:

wkhtmltopdf --javascript-delay 10000 --debug-javascript --verbose --load-error-handling ignore --load-media-error-handling ignore --no-stop-slow-scripts http://imdb.com out.pdf
  1. 简化页面加载
    如果还是卡,先禁用图片加载排除干扰,确认是图片问题再调整图片相关参数:
'disable-images': ''

修改后的完整代码

import pdfkit

try:
    options = {
        'encoding': 'utf-8',
        'margin-top': '0cm',
        'margin-bottom': '0cm',
        'margin-left': '0cm',
        'margin-right': '0cm',
        'disable-smart-shrinking': '',
        'page-width': '595px',
        'page-height': '842px',
        'no-outline': None,
        'javascript-delay': '10000',  # 延长JS等待时间
        "load-error-handling": "ignore",
        "load-media-error-handling": "ignore",
        "no-stop-slow-scripts": "",
        "debug-javascript": ""  # 开启JS调试日志
    }
    pdfkit.from_url(
        'https://www.imdb.com/', 'out.pdf', options=options, verbose=True)
except Exception as e:
    print(f"错误信息: {str(e)}")

内容的提问来源于stack exchange,提问作者michael holstein

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 20:50:29