【问题标题】:HTML to PDF with correct formatting from Python从 Python 以正确格式将 HTML 转换为 PDF
【发布时间】:2019-03-18 23:27:15
【问题描述】:

我一直在尝试使用 Wea​​syprint 和 PDFKIT 将网页转换为 pdf。我已成功保存了包含部分页面的 PDF。 在 weasyprint 中,我无法弄清楚如何从页面中获取正确的 CSS 样式。使用 PDFKIT 我似乎在检索网站的移动版本而不是整页。我正在使用 python 3.6。

from urllib.request import Request, urlopen
import webbrowser
import pdfkit
import weasyprint

#pdfkit.from_url('http://google.com', 'out.pdf')

print("started script")
website = 'https://www.bbcgoodfood.com/recipes/3228/chilli-con-carne'
filename = 'savedPDF.pdf'

req = Request(website, headers={'User-Agent': 'Mozilla/5.0'})
print(urlopen(req).getcode())

temp = urlopen(req).getcode()
if temp == 200:
    pdfkit.from_url(website, 'out.pdf')

    weasyprint.HTML(website).write_pdf('/Users/me/Documents/weasyprint.pdf')
    weasyprint.HTML(website).write_pdf(filename,stylesheets=[weasyprint.CSS('https://www.bbcgoodfood.com/sites/default/files/advagg_css/css__pDgD1vQBFL4LZ6AO_Uw8wEc3MBEaHOzbhMtPie685P8__Kxa0k0VBbKvV5-TOMN_kW3S7CrkFMM4Zf0LjDvzMFnk__mXPuNFBZ0nocZLk5Qifty02tMfg-gomArSBCcGw1mLo.css')])

我在 pdfkit 中看不到指定要连接的内容的选项。 此外,从 weasyprint 创建的两个 PDF 是相同的。

【问题讨论】:

    标签: python python-3.x macos pdfkit weasyprint


    【解决方案1】:

    在搞砸了上面提到的包一段时间后,我仍然在努力获得正确的输出。

    我已经解决了使用 webkit2png,这几乎可以完美地工作,唯一的缺点是我在一些保存的文件中出现了一个 cookie 弹出消息。

    【讨论】:

      猜你喜欢
      • 2014-04-15
      • 1970-01-01
      • 1970-01-01
      • 2012-01-20
      • 2016-06-26
      • 2013-08-21
      • 2012-10-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多