使用Python将HTML转换为PDF

4
我正在尝试在Django中将HTML转换为PDF文档,但一直没有成功。我尝试使用wkhtmltopdf 0.9.9,然而Apache会抛出一个错误,指出wkhtmltopdf无法连接到服务器。当我直接使用wkhtmltopdf运行时,它能够完美地将HTML转换为PDF文档。
我还尝试使用unoconv,但渲染后的PDF文件没有应用CSS样式。我也尝试使用xhtml2pdf,但同样遇到了相同的问题,生成的PDF文件没有任何CSS样式。我已经花费大量时间来解决这个问题,但仍然没有更近一步的进展。
如果您需要更多信息,请告诉我。
4个回答

4

为 Django 配置 Pisa 不应该 太难

网上有很多示例可以向您展示如何做,并解释如何在模板中链接到外部资源:

在您的情况下,您应该尝试第一个博客文章中提到的链接回调函数:

def fetch_resources(uri, rel):
    """
    Callback to allow pisa/reportlab to retrieve Images,Stylesheets, etc.
    `uri` is the href attribute from the html link element.
    `rel` gives a relative path, but it's not used here.

    """
    path = os.path.join(settings.MEDIA_ROOT, uri.replace(settings.MEDIA_URL, ""))
    return path

对于更新的Django版本,您可能应该使用STATIC_ROOT而不是MEDIA_ROOT

然后在您的渲染方法中相应地使用fetch resources

pdf = pisa.pisaDocument(StringIO.StringIO(
        html.encode("UTF-8")), 
        result, 
        link_callback=fetch_resources,
        encoding="utf-8")

0

我建议您使用pisa、pypdf和html5lib的组合,这对我很有效。


0
一种可能的但不太优雅的解决方案是运行一个小脚本,通过无头浏览器组件(Linux 上的 Webkit/Xvfb)呈现 HTML,然后将其保存为 PDF。

0
您可以使用pyhtml2pdf模块将HTML页面转换为PDF。
#if your using website URL
from pyhtml2pdf import converter
url = 'https://.....'
converter.convert(url, 'sample.pdf')

# if have the html file saved 
import os
from pyhtml2pdf import converter
path = os.path.abspath('abcd.html')
converter.convert(f'file:///{path}', 'sample.pdf') 

源代码请点击此处


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接