【问题标题】:How to convert Webpage page or HTML url to pdf?如何将网页页面或 HTML url 转换为 pdf?
【发布时间】:2018-04-07 09:24:48
【问题描述】:

我正在尝试将 HTML 页面或 HTML URL 转换为 pdf,它不仅可以转换 html,还可以转换 css 并保存它。我很困惑我应该使用什么(weasyprint、wkhtmltopdf 或 python pdfkit)。同时我正在使用这段代码:

def ConvertToPdf(urltoConvert=None):
    import pdfkit
    pdfFormatOptions= {'page-size':'Letter', 'disable-forms':'','zoom': 1}
    pdfObject = None
    try:
        pdfkit.from_url('http://tdi.dartmouth.edu/', 'dart.pdf')
    except:
       Exception while converting"

        pass
    return pdfObject
if __name__ == "__main__":
  #  url ='http://tdi.dartmouth.edu/'
    ConvertToPdf()

还有这段代码

import weasyprint
pdf = weasyprint.HTML('http://tdi.dartmouth.edu/').write_pdf()
len(pdf)
file('dart.pdf', 'w').write(pdf)

但一切都是徒劳的,请帮忙。

【问题讨论】:

    标签: python web-scraping wkhtmltopdf pdfkit weasyprint


    【解决方案1】:

    您可能想尝试使用: https://pypi.python.org/pypi/pdfkit

    它还有保存CSS的功能

    You can specify external CSS files when converting files or strings using css option.
    
    Warning This is a workaround for this bug in wkhtmltopdf. You should try –user-style-sheet option first.
    
    # Single CSS file
    css = 'example.css'
    pdfkit.from_file('file.html', options=options, css=css)
    
    # Multiple CSS files
    css = ['example.css', 'example2.css']
    pdfkit.from_file('file.html', options=options, css=css)
    

    【讨论】:

    • 对于每个网站,我们必须在之前指定 CSS 文件吗?我的意思是,如果我们自动使用脚本将每个 html 页面简单地转换为带有 css 的 pdf。我们如何知道 css 文件。??
    【解决方案2】:

    这应该可以正常工作

    import pdfkit
    pdfkit.from_url('http://google.com', 'res.pdf')
    

    另外,另一种解决方案可能是通过 selenium 制作屏幕截图并从这些图像中编写 .pdf。但是,它很脏。

    【讨论】:

    • 是否也转换 CSS ?以及如何保存它?
    • 请帮帮我。
    猜你喜欢
    • 1970-01-01
    • 2018-03-02
    • 2011-01-13
    • 2011-07-01
    • 2012-11-21
    • 1970-01-01
    • 2021-11-09
    • 1970-01-01
    相关资源
    最近更新 更多