Python使用pdfkit、wkhtmltopdf将html转换为pdf错误记录文档

1、首先,必须安装一下pdfkit这个模块库,使用命令:pip install pdfkit,安装完成后即可,只需在代码写入一行代码,导入即可:

import pdffkit

2、接着,我这边是尝试将一个html文件转换为pdf的,我的代码是这样的,点击一个按钮时就转换,代码很简单,主要附上python代码:

def export_pdf(request):
    pdfkit.from_file('test.html', r'D:\test\' + id + '.pdf')

注意,这里面的html文件必须为绝对路径,要不然可能在项目中会找不到文件,报文件找不到错误,之后点击按钮触发这个函数,结果报如下错误:

No wkhtmltopdf executable found: "b''"
If this file exists please check that this process can read it. Otherwise please install wkhtmltopdf - https://github.com/JazzCore/python-pdfkit/wiki/Installing-wkhtmltopdf

3、接着,处理这个问题,说是我没安装wkhtmltopdf,不过确实没安装,于是去https://github.com/JazzCore/python-pdfkit/wiki/Installing-wkhtmltopdf 安装windows底下的版本,安装完了之后再运行,还是报这个错误,好吧。

接下来就开始找解决办法了,改下代码如下:

def export_pdf(request):    
    path_wk = r'D:\SoftWare\wkhtmltopdf\bin\wkhtmltopdf.exe'  # 安装位置
    config = pdfkit.configuration(wkhtmltopdf=path_wk)
    pdfkit.from_file('test.html', r'D:\test' + id + '.pdf', configuration=config)

4、继续点击按钮,触发这个方法,发现报了一个这样的错误:

wkhtmltopdf reported an error:
Loading pages (1/6)
[>                                                           ] 0%
[======>                                                     ] 10%
[==============================>                             ] 50%
[============================================================] 100%
QPainter::begin(): Returned false
Error: Unable to write to destination                              
Exit with code 1, due to unknown error.

这是什么东西,看不懂,去查了好久都查不到要怎么解决。。。当然,未完待续:

5、于是看报错信息,报错信息如下所示:

主要看最后一行,点进去那个pdfkit.py,接着在to_pdf加个断点去调试一下,重新点击那个按钮,进来了,按F8键一步步走,如下图所示:

input为None去了,于是就可以知道传过的source有问题,此时的source是一个对象,还不是一个文件对象,就抛出异常了,因此代码有问题,改下代码如下:

def export_pdf(request):
    id = request.POST.get('id', '')
    path_wk = r'D:\SoftWare\wkhtmltopdf\bin\wkhtmltopdf.exe'  # 安装位置
    config = pdfkit.configuration(wkhtmltopdf=path_wk)
    with open('test.html') as f:
        pdfkit.from_file(f, r'D:\test' + id + '.pdf', configuration=config)

6、此时又报个错误了,错误如下:

'gbk' codec can't decode byte 0xa2 in position 153: illegal multibyte sequence

编码格式问题,于是修改一下代码如下:

def export_pdf(request):
    id = request.POST.get('id', '')
    path_wk = r'D:\SoftWare\wkhtmltopdf\bin\wkhtmltopdf.exe'  # 安装位置
    config = pdfkit.configuration(wkhtmltopdf=path_wk)
    with open('test.html', 'r', encoding='utf-8') as f:
        pdfkit.from_file(f, r'D:\test' + id + '.pdf', configuration=config)

7、继续点击按钮导出这个pdf,发现又报错了,又是之前那个错误:

wkhtmltopdf reported an error:
Loading pages (1/6)
[>                                                           ] 0%
[======>                                                     ] 10%
[==============================>                             ] 50%
[============================================================] 100%

8、最后,找了一天终于知道问题在哪里了,就出现在这一行代码里面:

pdfkit.from_file(f, r'D:\test' + id + '.pdf', configuration=config)

第二个参数的问题,不能指向本地的某个路径,还是什么情况,我修改一下代码如下:

def export_pdf(request):
    id = request.POST.get('id', '')
    path_wk = r'D:\SoftWare\wkhtmltopdf\bin\wkhtmltopdf.exe'  # 安装位置
    config = pdfkit.configuration(wkhtmltopdf=path_wk)
    with open('test.html', 'r', encoding='utf-8') as f:
        pdfkit.from_file(f, 'test.pdf', configuration=config)
    file = open('test.pdf', 'rb')
    response = FileResponse(file)
    response['Content-Type'] = 'application/pdf'
    response['Content-Disposition'] = 'attachment;filename="test.pdf"'
    return response

如果上面没返回一个HttpResponse的话,会报下面的错误:

The view test.export_pdf didn't return an HttpResponse object. It returned None instead.

9、这样便可以导出一个pdf文件了,并且直接下载到本地默认的地方,但是如果你得html有问题的话,导出来的就有问题,这里只是简单的一个测试代码而已。

10、以上就是我最近遇到的一些问题,记录一下,仅供大家学习参考,谢谢!

可以使用Python中的多个库来实现将爬取到的网页内容转换PDF格式并保存。以下是一种可能的实现方法,使用了`pdfkit`和`BeautifulSoup`库: 首先,确保你已经安装了`pdfkit`和`BeautifulSoup`库。可以使用以下命令进行安装: ``` pip install pdfkit beautifulsoup4 ``` 接下来,你需要安装一个HTMLPDF的工具,例如`wkhtmltopdf`。你可以在`wkhtmltopdf`的官方网站上下载并安装适合你操作系统的版本。 安装完成后,你可以使用以下代码将爬取到的网页内容转换PDF并保存: ```python import pdfkit from bs4 import BeautifulSoup import requests # 爬取网页内容 url = 'https://www.example.com' # 替换成你要爬取的网页URL response = requests.get(url) html_content = response.content # 解析HTML内容 soup = BeautifulSoup(html_content, 'html.parser') # 将HTML内容保存为临时文件 with open('temp.html', 'w', encoding='utf-8') as f: f.write(str(soup)) # 将临时文件转换PDF并保存 pdfkit.from_file('temp.html', 'output.pdf') # 删除临时文件 os.remove('temp.html') ``` 在上面的代码中,我们首先使用`requests`库获取网页的内容,然后使用`BeautifulSoup`库解析HTML内容。接下来,我们将HTML内容保存为临时文件`temp.html`,然后使用`pdfkit`库将临时文件转换PDF格式并保存为`output.pdf`。最后,我们删除临时文件。 请注意,使用`pdfkit`进行HTMLPDF时,你需要提前安装并配置好`wkhtmltopdf`工具。具体安装和配置方式可以参考`wkhtmltopdf`的官方文档。 希望这个例子能帮到你!如果还有其他问题,请随时提问。
评论 9
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值