【问题标题】:How convert dynamic html page to pdf in django?如何在django中将动态html页面转换为pdf?
【发布时间】:2016-07-10 04:10:39
【问题描述】:

1) 我解析一些页面来获取信息。 2)由于信息难以分离,我将其安装到 html 页面并使用自定义 css 使其美观。 3)然后我尝试将其转换为pdf以提供给客户。

但是所有的 pdf-convectors 都要求特定的 url,或者文件等等。例如:

def parse(request):
        done = csrf(request)
        if request.POST:
            USERNAME = request.POST.get('logins', '')
            PASSWORD = request.POST.get('password', '')
            dialogue_url = request.POST.get('links', '')
            total_pages = int(request.POST.get('numbers', ''))
            news = []
            news.extend(parse_one(USERNAME, PASSWORD, dialogue_url, total_pages))
            contex = {
                        "news" : news,
                    }
            done.update(contex)

        pageclan = render(request, 'marketing/parser.html', done)

        # create an API client instance
        client = pdfcrowd.Client(*** ***)

        # convert a web page and store the generated PDF to a variable. That is doesn't work. Convertor doesn't support such url.
        pdf = client.convertURI('pageclan')

         # set HTTP response headers
        response = HttpResponse(content_type="application/pdf")
        response["Cache-Control"] = "max-age=0"
        response["Accept-Ranges"] = "none"
        response["Content-Disposition"] = "attachment; filename=jivo_log.pdf"

        # send the generated PDF
        response.write(pdf)
        return response

有什么工具可以正常工作吗?

【问题讨论】:

    标签: python html css django pdf


    【解决方案1】:

    来自PDFCrowd Python API documentation

    您也可以转换原始 HTML 代码,只需使用 convertHtml() 方法而不是 convertURI()

    pdf = client.convertHtml("<head></head><body>My HTML Layout</body>")

    这意味着您可以修改您的代码以将convertHtml 方法与您呈现的页面(这是一个HTML 字符串)一起使用:

    pdf = client.convertHtml(pageclan.content)
    

    【讨论】:

    • 'HttpResponse' 对象没有属性 'encode' html = html.encode('utf-8') 似乎它要求 utf-8 或其他东西
    • @SergeyBakotin 是的,您只需要使用content。查看更新的答案。
    猜你喜欢
    • 1970-01-01
    • 2014-07-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-13
    • 2011-07-01
    • 1970-01-01
    相关资源
    最近更新 更多