您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

使用Python将HTML转换为PDF

使用Python将HTML转换为PDF

为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")
python 2022/1/1 18:49:58 有364人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶