使用wkhtmltopdfpdfkit的Python包装器出现问题对象没有属性'配置和其他

问题描述

我遇到的问题与此帖子非常相似:pdfkit - python : 'str' object has no attribute decode

我正在通过Web应用程序运行python脚本。

使用python 3.6版pip3安装后导入pdfkit。

import pdfkit

def pdfkit(source,method):

if method == "string":

    try:
        options = {
            'page-size': 'A4','margin-top': '0.75in','margin-right': '0.75in','margin-bottom': '0.75in','margin-left': '0.75in',}
        config = pdfkit.configuration(wkhtmltopdf=bytes("/usr/local/bin/wkhtmltopdf",'utf8'))
        pdf = pdfkit.from_string(source,False,options=options,configuration=config)
        return pdf

    except Exception as e:
        return str(e)
else:
    return "Error:  Not yet Supported"

我按照UBUNTU 20.04的这些说明安装了wkhtmltopdf。它说这些是“无头的”,可以从命令行执行。实际上,在使用pdfkit包装器时确实可以,但是当我尝试通过python脚本本身运行时,它是行不通的。

我遇到的错误之一是:

{
   "pdf": "'function' object has no attribute 'configuration'"
}

除其他外,如果删除配置,则类似from_string。

只是想知道我是否需要导入其他模块,或者是否需要在系统上使用其他版本的wkhtmltopdf。

我需要获取其他二进制文件,还是按照此处的说明进行操作?这很令人困惑,因为有多种安装方法包括CLI,.deb软件包和使用GitHub上的信息。谢谢。

wkhtmltopdf/packaging

wkhtmltopdf for UBUNTU

解决方法

谢谢。发布答案,因为我想跟进并详细说明。

那是一个问题,函数名称(Duh!):

仍然可以使用它,但是大多数情况下都可以。我刚刚开始使用Python。真的很好。希望我早点发现。

def getpdf(源,方法):

if method == "string":

    try:
        options = {
            'page-size': 'A4','margin-top': '0.75in','margin-right': '0.75in','margin-bottom': '0.75in','margin-left': '0.75in',}
        config = pdfkit.configuration(wkhtmltopdf=bytes("/usr/local/bin/wkhtmltopdf",'utf8'))
        pdf = pdfkit.from_string(source,False,options=options)
        return pdf

    except Exception as e:
        return str(e)
#       pdf = pdfkit.from_string(html,False)
#       return pdf;
else:
    return "Error:  Not yet Supported"

def HTMLTOPDF(输出,uri,**请求):

if request['method'] != 'POST':
    output.SendMethodNotAllowed('POST')
else:
    query = json.loads(request['body'])
    pdf = getpdf(query['html'],query['method'])
    print (pdf)
    encoded = base64.b64encode(pdf)
    response = dict();
    response['pdf'] = pdf
    output.AnswerBuffer(encoded,'text/html')

现在大多数情况下都可以使用,按原样,我只是将编码结果返回为base64,或者似乎是因为我通过请求获得的响应看起来像(JVBERi0xLjQKMSAwIG9iago8PAovVGl0bGUgKP7 / KQovQ3JlYXRvciAo)。我对将结果返回为JSON感兴趣,因为我想将其他内容传递回去:

{“ base64”:encoded“,” status“:”“,” error“:”“},类似的东西。

我尝试过这样的事情:

    encoded = base64.b64encode(pdf)
    response = dict();
    response['pdf'] = encoded
    response['status'] = "status"
    output.AnswerBuffer(json.dumps(response,indent = 3),'application/json')

我得到一个错误:

“字节”类型的对象不可JSON序列化

尽管如此。至少我可以找回原始的base64,这实际上可能会更容易。