pdfkit导出网页为PDF时图片无法嵌入显示的问题如何解决
问题产生原因
- 底层依赖兼容性问题:pdfkit底层调用wkhtmltopdf工具实现PDF导出,旧版本的wkhtmltopdf使用的libpng库对携带错误iCCP色彩配置文件的PNG图片容错性极低,会直接拒绝加载这类图片,最终PDF中就会显示为问号图标,你看到的
libpng warning: iCCP: known incorrect sRGB profile就是对应的报错提示。 - 反爬机制拦截:Quora对爬虫请求有严格的校验,pdfkit默认的请求头特征会被识别为非浏览器请求,图片资源的访问会被拦截,无法正常加载。
- 资源加载不充分:网页中的图片大多采用懒加载逻辑,pdfkit默认的资源等待时间过短,图片还没完成加载就已开始生成PDF。
针对pdfkit的修复方案
首先升级底层依赖的wkhtmltopdf到0.12.6及以上的稳定版本,新版本已经修复了iCCP配置文件异常的PNG图片加载问题,大部分场景下可以直接解决图片显示问号的问题,相关警告也不会再影响渲染。
之后调整pdfkit的启动参数,增加自定义请求头绕过反爬、延长资源等待时间确保懒加载图片加载完成,修改后的示例代码如下:
import pdfkit options = { 'custom-header': [ ('User-Agent', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/118.0.0.0 Safari/537.36'), ('Accept', 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8') ], 'custom-header-propagation': '', 'javascript-delay': '5000', 'enable-javascript': '', 'no-stop-slow-scripts': '', 'disable-smart-shrinking': '', 'image-quality': '100' } pdfkit.from_url('https://www.quora.com/Spoilers-What-is-something-you-noticed-in-Avengers-Endgame-that-you-believe-others-have-missed/answer/Prabhhav-Sharma?ch=3&share=5feaef03&srid=aHe5', 'output.pdf', options=options)
替代工具方案(适合个人使用场景)
如果调整pdfkit参数后仍有问题,可改用以下兼容性更好的工具实现需求:
- Playwright导出:底层基于Chromium内核,对各类网页资源的兼容性远高于wkhtmltopdf,可自动处理懒加载和反爬校验,示例代码如下:
from playwright.sync_api import sync_playwright with sync_playwright() as p: browser = p.chromium.launch(headless=True) page = browser.new_page(user_agent='Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/118.0.0.0 Safari/537.36') page.goto('https://www.quora.com/Spoilers-What-is-something-you-noticed-in-Avengers-Endgame-that-you-believe-others-have-missed/answer/Prabhhav-Sharma?ch=3&share=5feaef03&srid=aHe5', wait_until='networkidle') page.pdf(path='output.pdf', format='A4', print_background=True) browser.close()
- 浏览器命令行导出:直接调用Chrome/Edge的无头模式导出PDF,不需要额外配置复杂参数,执行对应命令即可,以Edge为例:
msedge --headless=new --disable-gpu --run-all-compositor-stages-before-draw --print-to-pdf="output.pdf" https://www.quora.com/Spoilers-What-is-something-you-noticed-in-Avengers-Endgame-that-you-believe-others-have-missed/answer/Prabhhav-Sharma?ch=3&share=5feaef03&srid=aHe5
内容的提问来源于stack exchange,提问作者Nagabhushan S N
相关产品推荐
相关产品推荐

