如何使用pdfkit将网页图片一并转换为PDF?
解决pdfkit转换网页PDF不包含图片的问题
一、修复当前pdfkit+wkhtmltopdf配置
你的代码中'no-images': None是错误配置——wkhtmltopdf的--no-images是禁用图片的命令行开关,pdfkit会将值为None的参数转为不带值的开关,相当于强制关闭图片加载。按以下方式调整配置:
修改后的代码
import pdfkit config = pdfkit.configuration(wkhtmltopdf='C:/Program Files/wkhtmltopdf/bin/wkhtmltopdf.exe') options = { 'enable-local-file-access': None, # 移除no-images参数,确保图片加载开关默认开启 'load-media-error-handling': 'ignore', # 忽略个别图片加载失败的情况 'javascript-delay': 3000, # 给懒加载图片留足加载时间(可根据网页调整时长) 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36', # 模拟浏览器UA,避免网站拦截 'allow': '*' # 允许加载所有远程资源 } pdfkit.from_url( 'https://stadt-bremerhaven.de/eve-flare-portables-stimmungslicht-mit-thread-ausprobiert/', 'out.pdf', configuration=config, options=options, verbose=True )
额外排查点
- 检查wkhtmltopdf版本:旧版本可能存在兼容性问题,建议下载最新稳定版
- 查看
verbose输出:如果有图片加载失败的错误日志,可针对性解决(比如跨域限制、资源链接失效)
二、替代库推荐
如果上述方法仍无效,可尝试以下更稳定的方案:
1. WeasyPrint
基于Python的HTML/CSS渲染引擎,对现代网页标准支持较好,处理图片加载更可靠:
from weasyprint import HTML HTML('https://stadt-bremerhaven.de/eve-flare-portables-stimmungslicht-mit-thread-ausprobiert/').write_pdf('out_weasy.pdf')
安装方式:pip install weasyprint(Windows下会自动安装预编译依赖,Linux/macOS需额外安装GTK+相关组件)
2. Selenium + ChromeDriver
模拟真实Chrome浏览器渲染,完美支持懒加载、JS动态生成的内容:
from selenium import webdriver from selenium.webdriver.chrome.options import Options chrome_options = Options() chrome_options.add_argument('--headless=new') chrome_options.add_argument('--disable-gpu') chrome_options.add_argument('--no-sandbox') driver = webdriver.Chrome(options=chrome_options) driver.get('https://stadt-bremerhaven.de/eve-flare-portables-stimmungslicht-mit-thread-ausprobiert/') driver.implicitly_wait(5) # 等待懒加载图片全部加载 # 导出PDF with open('out_selenium.pdf', 'wb') as f: f.write(driver.execute_cdp_cmd('Page.printToPDF', {}).get('data').encode('utf-8')) driver.quit()
优势:完全还原浏览器渲染效果,能处理所有动态内容;缺点:需要安装Chrome浏览器和对应版本的ChromeDriver,资源占用较高
内容的提问来源于stack exchange,提问作者BertBaker
相关产品推荐
相关产品推荐

