如何将网页或HTML链接转换为PDF?

2024-06-16 13:59:12 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试将HTML页面或HTML URL转换为pdf,它不仅可以转换HTML,还可以转换css并保存它。我不知道应该使用什么(weasyprint、wkhtmltoppdf或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()

还有这个密码

^{pr2}$

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


Tags: nonehttpurlpdfhtml页面csspdfkit
2条回答

这应该行得通

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

另外,另一个解决方案可能是通过selenium制作屏幕截图,然后从这些图像中合成.pdf。但是,它很脏。在

您可以尝试使用: 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)

相关问题 更多 >